auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<Feature> getRepositoryFeatures(String repositoryName) { List<Feature> repoFeatures = new ArrayList<Feature>(); for (Repository repository : featuresService.listRepositories()) { if (repository.getName().equalsIgnoreCase(repositoryName)) { try { repoFeatures = Arrays.asList(repository.getFeatures()); } catch (Exception ex) { <START> logger.warn("getRepositoryFeatures Exception: " <END> + ex.getMessage(), ex); } break; } } return repoFeatures; }</code><technical_language>Improve warning text. above</technical_language>

Target:
private List<Feature> getRepositoryFeatures(String repositoryName) { List<Feature> repoFeatures = new ArrayList<Feature>(); for (Repository repository : featuresService.listRepositories()) { if (repository.getName().equalsIgnoreCase(repositoryName)) { try { repoFeatures = Arrays.asList(repository.getFeatures()); } catch (Exception ex) { logger.warn("Could not get Repository Features", ex); } break; } } return repoFeatures; }
Source:
<code>private static String getEffectiveLogDirectory(String file) { String logDir; <START> logDir = System.getenv("GO_AGENT_LOG_DIR") == null ? System.getenv("LOG_DIR") : System.getenv("GO_AGENT_LOG_DIR"); <END> if (logDir == null) { logDir = "logs"; } return logDir + "/" + file; }</code><technical_language>check for system property too</technical_language>

Target:
private static String getEffectiveLogDirectory(String file) { return getLogDir() + "/" + file; }
Source:
<code>public void connectOtherProfile(BluetoothDevice device, int firstProfileStatus){ if ((mHandler.hasMessages(MESSAGE_CONNECT_OTHER_PROFILES) == false) && (isQuietModeEnabled()== false)){ ParcelUuid[] featureUuids = device.getUuids(); if ((!(BluetoothUuid.containsAnyUuid(featureUuids, A2DP_SOURCE_SINK_UUIDS))) || (!(BluetoothUuid.isUuidPresent(featureUuids, BluetoothUuid.Handsfree)))) { Log.v(TAG,"Initiate SDP for Missing UUID's support in remote"); device.fetchUuidsWithSdp(); } Message m = mHandler.obtainMessage(MESSAGE_CONNECT_OTHER_PROFILES); m.obj = device; m.arg1 = (int)firstProfileStatus; if <START> (isConnectTimeoutDelayApplicable(device)) <END> { mHandler.sendMessageDelayed(m,CONNECT_OTHER_PROFILES_TIMEOUT_DELAYED); } else { mHandler.sendMessageDelayed(m,CONNECT_OTHER_PROFILES_TIMEOUT); } } }</code><technical_language>rebase this dependent other patches</technical_language>

Target:
public void connectOtherProfile(BluetoothDevice device, int firstProfileStatus){ if ((mHandler.hasMessages(MESSAGE_CONNECT_OTHER_PROFILES) == false) && (isQuietModeEnabled()== false)){ ParcelUuid[] featureUuids = device.getUuids(); if ((!(BluetoothUuid.containsAnyUuid(featureUuids, A2DP_SOURCE_SINK_UUIDS))) || (!(BluetoothUuid.isUuidPresent(featureUuids, BluetoothUuid.Handsfree)))) { Log.v(TAG,"Initiate SDP for Missing UUID's support in remote"); device.fetchUuidsWithSdp(); } Message m = mHandler.obtainMessage(MESSAGE_CONNECT_OTHER_PROFILES); m.obj = device; m.arg1 = (int)firstProfileStatus; mHandler.sendMessageDelayed(m,CONNECT_OTHER_PROFILES_TIMEOUT); } }
Source:
<code>public static void closeSecondaryShells(SWTWorkbenchBot bot) { SWTBotShell[] shells = bot.shells(); SWTBotShell mainShell = getMainShell(shells); if (mainShell == null) { return; } Arrays.stream(shells) .filter(shell -> shell != mainShell) .filter(SWTBotShell::isVisible) .forEach((shell) -> { log.debug(MessageFormat.format("Closing ligering shell with title {0}", shell.getText())); shell.close(); <START> }); <END> }</code><technical_language>I do : .peek(shell -> log.debug(....)) .forEach(SWTBotShell::close) peek() works for logging</technical_language>

Target:
public static void closeSecondaryShells(SWTWorkbenchBot bot) { SWTBotShell[] shells = bot.shells(); SWTBotShell mainShell = getMainShell(shells); if (mainShell == null) { return; } Arrays.stream(shells) .filter(shell -> shell != mainShell) .filter(SWTBotShell::isVisible) .peek(shell -> log.debug(MessageFormat.format("Closing ligering shell with title {0}", shell.getText()))) .forEach(SWTBotShell::close); }
Source:
<code>private Object execute(ElasticsearchParameterAccessor parameterAccessor) { ResultProcessor processor = queryMethod.getResultProcessor().withDynamicProjection(parameterAccessor); Query query = createQuery( new ConvertingParameterAccessor(elasticsearchOperations.getElasticsearchConverter(), parameterAccessor)); Class<?> typeToRead = processor.getReturnedType().getTypeToRead(); <START> String indexName = queryMethod.getEntityInformation().getIndexName(); <END> String indexTypeName = queryMethod.getEntityInformation().getIndexTypeName(); ReactiveElasticsearchQueryExecution execution = getExecution(parameterAccessor, new ResultProcessingConverter(processor, elasticsearchOperations, instantiators)); return execution.execute(query, processor.getReturnedType().getDomainType(), indexName, indexTypeName, typeToRead); }</code><technical_language>a common type bundle indexname/indextypename together</technical_language>

Target:
private Object execute(ElasticsearchParameterAccessor parameterAccessor) { ResultProcessor processor = queryMethod.getResultProcessor().withDynamicProjection(parameterAccessor); Query query = createQuery( new ConvertingParameterAccessor(elasticsearchOperations.getElasticsearchConverter(), parameterAccessor)); Class<?> typeToRead = processor.getReturnedType().getTypeToRead(); String indexName = queryMethod.getEntityInformation().getIndexName(); String indexTypeName = queryMethod.getEntityInformation().getIndexTypeName(); ReactiveElasticsearchQueryExecution execution = getExecution(parameterAccessor, new ResultProcessingConverter(processor, elasticsearchOperations)); return execution.execute(query, processor.getReturnedType().getDomainType(), indexName, indexTypeName, typeToRead); }
Source:
<code>public Note call() throws GitAPIException { checkCallable(); NoteMap map = NoteMap.newEmptyMap(); RevCommit notesCommit = null; try (RevWalk walk = new RevWalk(repo)) { Ref ref = <START> repo.findRef(notesRef); <END> if (ref != null) { notesCommit = walk.parseCommit(ref.getObjectId()); map = NoteMap.read(walk.getObjectReader(), notesCommit); } return map.getNote(id); } catch (IOException e) { throw new JGitInternalException(e.getMessage(), e); } }</code><technical_language>exactRef</technical_language>

Target:
public Note call() throws GitAPIException { checkCallable(); NoteMap map = NoteMap.newEmptyMap(); RevCommit notesCommit = null; try (RevWalk walk = new RevWalk(repo)) { Ref ref = repo.exactRef(notesRef); if (ref != null) { notesCommit = walk.parseCommit(ref.getObjectId()); map = NoteMap.read(walk.getObjectReader(), notesCommit); } return map.getNote(id); } catch (IOException e) { throw new JGitInternalException(e.getMessage(), e); } }
Source:
<code>protected GenericDatabaseDialect newSinkDialectFor(Set<String> tableTypes) { if (tableTypes != null) { connProps.put(JdbcSinkConfig.TABLE_TYPES_CONFIG, StringUtils.join(tableTypes, ",")); } else { connProps.remove(JdbcSinkConfig.TABLE_TYPES_CONFIG); } sinkConfig = new JdbcSinkConfig(connProps); <START> dialect = createDialect(sinkConfig); <END> assertTrue(dialect.tableTypes.containsAll(tableTypes)); return dialect; }</code><technical_language>tableTypes null</technical_language>

Target:
protected GenericDatabaseDialect newSinkDialectFor(Set<String> tableTypes) { assertNotNull(tableTypes); assertFalse(tableTypes.isEmpty()); connProps.put(JdbcSinkConfig.TABLE_TYPES_CONFIG, StringUtils.join(tableTypes, ",")); sinkConfig = new JdbcSinkConfig(connProps); dialect = createDialect(sinkConfig); assertTrue(dialect.tableTypes.containsAll(tableTypes)); return dialect; }
Source:
<code>public void handleReplaceKeysResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleReplaceKeysResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { <START> LOGGER.error(GET_FIRMWARE_VERSION_RESPONSE_NOT_OK, exception); <END> result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(new ResponseMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), result, exception, null, deviceMessageMetadata.getMessagePriority()), deviceMessageMetadata .getMessageType()); }</code><technical_language>Ehm... replace keys method wrong log message..</technical_language>

Target:
public void handleReplaceKeysResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleReplaceKeysResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Replace Keys Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(new ResponseMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), result, exception, null, deviceMessageMetadata.getMessagePriority()), deviceMessageMetadata .getMessageType()); }
Source:
<code>public void insertLatestOrNewModifications(Material material, MaterialInstance materialInstance, File folder, Modifications list) { List<Modification> newChanges = list.isEmpty() ? materialChecker.findLatestModification(folder, material, subprocessExecutionContext) : materialService.modificationsSince(material, folder, list.latestRevision(material), subprocessExecutionContext); if (newChanges.isEmpty()) { LOGGER.debug( <START> String.format("[Material Update] Did not find any new modifications for material '%s' with flyweight '%s' using working directory '%s'", material, material.getFingerprint(), <END> folder.getAbsolutePath())); } else { LOGGER.info("[Material Update] Found '{}' modifications for material '{}' with flyweight '{}' using working directory '{}'", newChanges.size(), material, material.getFingerprint(), folder.getAbsolutePath()); materialRepository.saveModifications(materialInstance, newChanges); } }</code><technical_language>change</technical_language>

Target:
public void insertLatestOrNewModifications(Material material, MaterialInstance materialInstance, File folder, Modifications list) { List<Modification> newChanges = list.isEmpty() ? materialChecker.findLatestModification(folder, material, subprocessExecutionContext) : materialService.modificationsSince(material, folder, list.latestRevision(material), subprocessExecutionContext); if (newChanges.isEmpty()) { LOGGER.debug("[Material Update] Did not find any new modifications for material '{}' with flyweight '{}' using working directory '{}'", material, material.getFingerprint(), folder.getAbsolutePath()); } else { LOGGER.info("[Material Update] Found '{}' modifications for material '{}' with flyweight '{}' using working directory '{}'", newChanges.size(), material, material.getFingerprint(), folder.getAbsolutePath()); materialRepository.saveModifications(materialInstance, newChanges); } }
Source:
<code>private T copyBufferAndGet(ByteBuffer valueBuffer, int startOffset, int endOffset) <START> { <END> ByteBuffer copyValueBuffer = valueBuffer.asReadOnlyBuffer(); final int size = endOffset > startOffset ? endOffset - startOffset : copyValueBuffer.get(startOffset - Integer.BYTES); copyValueBuffer.position(startOffset); return strategy.fromByteBuffer(copyValueBuffer, size); }</code><technical_language>logic of this method bufferedIndexedGet(), pass -1 strategy.fromByteBuffer(). Please review this aspect GenericIndexed GenericIndexedWriter</technical_language>

Target:
private T copyBufferAndGet(ByteBuffer valueBuffer, int startOffset, int endOffset) { ByteBuffer copyValueBuffer = valueBuffer.asReadOnlyBuffer(); int size = endOffset - startOffset; if (size == 0 && (NullHandling.replaceWithDefault() || copyValueBuffer.get(startOffset - Integer.BYTES) == NULL_VALUE_SIZE_MARKER)) { return null; } copyValueBuffer.position(startOffset); return strategy.fromByteBuffer(copyValueBuffer, size); }
Source:
<code>public static QueryId createQuery(DistributedQueryRunner queryRunner, Session session, String sql) { try { QueryManager queryManager = queryRunner.getCoordinator().getQueryManager(); QueryId queryId = queryManager.createQueryId(); queryManager.createQuery(queryId, new TestingSessionContext(session), sql) <START> .get(); <END> return queryId; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { Throwables.throwIfUnchecked(e.getCause()); throw new RuntimeException(e.getCause()); } }</code><technical_language>This strange, put previous line</technical_language>

Target:
public static QueryId createQuery(DistributedQueryRunner queryRunner, Session session, String sql) { QueryManager queryManager = queryRunner.getCoordinator().getQueryManager(); QueryId queryId = queryManager.createQueryId(); getFutureValue(queryManager.createQuery(queryId, new TestingSessionContext(session), sql)); return queryId; }
Source:
<code>public CounterAspect(String fieldName, String label, Class<? extends ITmfEventAspect<?>>... groups) { super(fieldName, label); fGroups = <START> groups; <END> }</code><technical_language>do need a copy of array ensure @safevarargs? this class is read is knowing people do groups getter</technical_language>

Target:
public CounterAspect(String fieldName, String label, Class<? extends ITmfEventAspect<?>>... groups) { super(fieldName, label); fGroups = Arrays.copyOf(groups, groups.length); }
Source:
<code>public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); Matcher matcher; matcher = reSessionId.matcher(response); if (matcher.find()) { mSessionId = matcher.group(1); } else { throw new BankException(res.getText(R.string.unable_to_find).toString() + " session id."); } matcher = rePersonnr.matcher(response); if (matcher.find()) { mPersonnr = matcher.group(1); } else { throw new BankException(res.getText(R.string.unable_to_find).toString() + " personnummer."); } try { response = urlopen.open(String.format("<LINK_0>", mSessionId, mPersonnr)); matcher = reAccounts.matcher(response); while (matcher.find()) { String name = Html.fromHtml(matcher.group(2)).toString().trim(); Account account = new Account(name, Helpers.parseBalance(matcher.group(5)), matcher.group(1).trim()); if (name.contains("lån") || name.contains("Lån")) { account.setType(Account.LOANS); } else { balance = balance.add(Helpers.parseBalance(matcher.group(5))); } accounts.add(account); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } <START> } finally { <END> super.updateComplete(); } }</code><technical_language>remove finally {</technical_language>

Target:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); Matcher matcher; matcher = reSessionId.matcher(response); if (matcher.find()) { mSessionId = matcher.group(1); } else { throw new BankException(res.getText(R.string.unable_to_find).toString() + " session id."); } matcher = rePersonnr.matcher(response); if (matcher.find()) { mPersonnr = matcher.group(1); } else { throw new BankException(res.getText(R.string.unable_to_find).toString() + " personnummer."); } response = urlopen.open(String.format("<LINK_0>", mSessionId, mPersonnr)); matcher = reAccounts.matcher(response); while (matcher.find()) { String name = Html.fromHtml(matcher.group(2)).toString().trim(); Account account = new Account(name, Helpers.parseBalance(matcher.group(5)), matcher.group(1).trim()); if (name.contains("lån") || name.contains("Lån")) { account.setType(Account.LOANS); } else { balance = balance.add(Helpers.parseBalance(matcher.group(5))); } accounts.add(account); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } super.updateComplete(); }
Source:
<code>public Object getResponse() { <START> return true; <END> }</code><technical_language>false is a valid response</technical_language>

Target:
public Object getResponse() { return response; }
Source:
<code>public Map<String, Builder> processRunMetrics(HashMap<String, Metric> rawMetrics) { Map<String, Builder> newMetrics = new HashMap<>(); for (String key : rawMetrics.keySet()) { Metric metric = rawMetrics.get(key); Measurements measure = metric.getMeasurements(); MeasurementCase measureCase = measure.getMeasurementCase(); if (MeasurementCase.DOUBLE_VALUES.equals(measureCase)) { DoubleValues doubleValues = measure.getDoubleValues(); if (doubleValues.getDoubleValueList().size() > 0) { <START> double sum = doubleValues .getDoubleValueList() .stream() .mapToDouble(Double::doubleValue) .sum(); <END> double avg = sum / doubleValues.getDoubleValueList().size(); newMetrics.put(key + AVERAGE_KEY_TAG, createAvgMetric(avg, metric)); } } else if (MeasurementCase.NUMERIC_VALUES.equals(measureCase)) { NumericValues numValues = measure.getNumericValues(); if (numValues.getNumericValueList().size() > 0) { long sum = numValues .getNumericValueList() .stream() .mapToLong(Long::longValue) .sum(); double avg = (double) sum / numValues.getNumericValueList().size(); newMetrics.put(key + AVERAGE_KEY_TAG, createAvgMetric(avg, metric)); } } } return newMetrics; }</code><technical_language>FYI, a .collect(Collectors.summarizingDouble(Double::doubleValue)); give a DoubleSummaryStatistics object Java average. a simple calculation matter, if provides benefit, know. long others</technical_language>

Target:
public Map<String, Builder> processRunMetrics(HashMap<String, Metric> rawMetrics) { Map<String, Builder> newMetrics = new HashMap<>(); for (String key : rawMetrics.keySet()) { Metric metric = rawMetrics.get(key); Measurements measure = metric.getMeasurements(); MeasurementCase measureCase = measure.getMeasurementCase(); if (MeasurementCase.DOUBLE_VALUES.equals(measureCase)) { DoubleValues doubleValues = measure.getDoubleValues(); if (doubleValues.getDoubleValueList().size() > 0) { double avg = doubleValues .getDoubleValueList() .stream() .collect(Collectors.summarizingDouble(Double::doubleValue)) .getAverage(); newMetrics.put(key + AVERAGE_KEY_TAG, createAvgMetric(avg, metric)); } } else if (MeasurementCase.NUMERIC_VALUES.equals(measureCase)) { NumericValues numValues = measure.getNumericValues(); if (numValues.getNumericValueList().size() > 0) { double avg = numValues .getNumericValueList() .stream() .collect(Collectors.summarizingLong(Long::longValue)) .getAverage(); newMetrics.put(key + AVERAGE_KEY_TAG, createAvgMetric(avg, metric)); } } } return newMetrics; }
Source:
<code>private void handleSuccess(Map<String, Object> params, Task task) { <START> LOGGER.debug("The actions from the task with name: and ID: were successfully executed", task.getName(), task.getId()); <END> activityService.addSuccess(task); task.resetFailuresInRow(); taskService.save(task); eventRelay.sendEventMessage(new MotechEvent( createHandlerSuccessSubject(task.getName()), params )); }</code><technical_language>actions</technical_language>

Target:
private void handleSuccess(Map<String, Object> params, Task task) { LOGGER.debug("All actions from task: with ID: were successfully executed", task.getName(), task.getId()); activityService.addSuccess(task); task.resetFailuresInRow(); taskService.save(task); eventRelay.sendEventMessage(new MotechEvent( createHandlerSuccessSubject(task.getName()), params )); }
Source:
<code>public IBuildPlan parseJob(HudsonModelJob job) throws HudsonException { IBuildPlan plan = createBuildPlan(); String jobUrl = job.getUrl(); if (this.hudsonUrlUtil.isNestedJob(jobUrl)) { plan.setId(jobUrl); } else { plan.setId(job.getName()); } plan.setName(this.hudsonUrlUtil.getDisplayName(jobUrl)); plan.setDescription(job.getDescription()); plan.setUrl(job.getUrl()); updateStateAndStatus(job, plan); updateHealth(job, plan); if (job.getLastBuild() != null) { IBuild build = parseBuild(job, job.getLastBuild()); plan.setLastBuild(build); } parseJobActions(plan.getParameterDefinitions(), job.getAction()); if (job instanceof HudsonMatrixMatrixProject) { List<HudsonMatrixMatrixConfiguration> childConfigs = ((HudsonMatrixMatrixProject) job) .getActiveConfiguration(); <START> if (childConfigs != null && childConfigs.size() > 0) { <END> for (HudsonMatrixMatrixConfiguration config : childConfigs) { IBuildPlan newPlan = parseJob(config); newPlan.setName(config.getDisplayName()); newPlan.setParent(plan); newPlan.setId(newPlan.getParent().getId() + newPlan.getId()); plan.getChildren().add(newPlan); } } } return plan; }</code><technical_language>size check is unecessary</technical_language>

Target:
public IBuildPlan parseJob(HudsonModelJob job) throws HudsonException { IBuildPlan plan = createBuildPlan(); String jobUrl = job.getUrl(); if (this.hudsonUrlUtil.isNestedJob(jobUrl)) { plan.setId(jobUrl); } else { plan.setId(job.getName()); } plan.setName(this.hudsonUrlUtil.getDisplayName(jobUrl)); plan.setDescription(job.getDescription()); plan.setUrl(job.getUrl()); updateStateAndStatus(job, plan); updateHealth(job, plan); if (job.getLastBuild() != null) { IBuild build = parseBuild(job, job.getLastBuild()); plan.setLastBuild(build); } parseJobActions(plan.getParameterDefinitions(), job.getAction()); if (job instanceof HudsonMatrixMatrixProject) { List<HudsonMatrixMatrixConfiguration> childConfigs = ((HudsonMatrixMatrixProject) job) .getActiveConfiguration(); if (childConfigs != null) { for (HudsonMatrixMatrixConfiguration config : childConfigs) { IBuildPlan newPlan = parseJob(config); newPlan.setName(config.getDisplayName()); newPlan.setParent(plan); newPlan.setId(newPlan.getParent().getId() + newPlan.getId()); plan.getChildren().add(newPlan); } } } return plan; }
Source:
<code>public MarketDataBox<ZonedDateTime> toZonedDateTime(MarketDataBox<LocalDate> dates) { if (dates.isScenarioValue()) { int nScenarios = dates.getScenarioCount(); ArgChecker.isTrue(nScenarios == localTimes.getScenarioCount(), "the number of scenarios must be the same"); List<ZonedDateTime> zonedDateTimes = IntStream.range(0, nScenarios) .mapToObj(i -> dates.getValue(i).atTime(localTimes.get(i)).atZone(zoneId)) .collect(Collectors.toList()); return MarketDataBox.ofScenarioValues(zonedDateTimes); } <START> ZonedDateTime zonedDateTime = dates.getSingleValue().atTime(localTimes.get(0)).atZone(zoneId); <END> return MarketDataBox.ofSingleValue(zonedDateTime); }</code><technical_language>definition a defaultLocalTime avoid get(0)</technical_language>

Target:
public MarketDataBox<ZonedDateTime> toZonedDateTime(MarketDataBox<LocalDate> dates) { if (dates.isScenarioValue()) { int nScenarios = dates.getScenarioCount(); int nTimes = localTimes.size(); List<ZonedDateTime> zonedDateTimes = IntStream.range(0, nScenarios) .mapToObj(scenarioIndex -> zonedDateTime(dates.getValue(scenarioIndex), nTimes, scenarioIndex)) .collect(Collectors.toList()); return MarketDataBox.ofScenarioValues(zonedDateTimes); } ZonedDateTime zonedDateTime = dates.getSingleValue().atTime(defaultLocalTime).atZone(zoneId); return MarketDataBox.ofSingleValue(zonedDateTime); }
Source:
<code>public @ResponseBody MeaningfulUseAccurateAsOf getAccurateAsOfDate() { MeaningfulUseAccurateAsOfDTO dto = muManager.getMeaningfulUseAccurateAsOf(); MeaningfulUseAccurateAsOf muuAccurate = new MeaningfulUseAccurateAsOf(dto); <START> if(StringUtils.isEmpty(muuAccurate.getId().toString()) && StringUtils.isEmpty(muuAccurate.getAccurateAsOfDate().toString())){ <END> muuAccurate.getErrorMessages().add("Could not obtain the accurate as of date."); } return muuAccurate; }</code><technical_language>If muuAccurate.getId() is null muuAccurate.getAccurateAsOfDate() is null this throw NPE. - requirements for other reasons errorMessages warningMessages, I is is error message warning messages. want throw exception of a type is handled Controller Advice (or add a handler for a type class) error message. EntityNotFoundException? EntityExistsException</technical_language>

Target:
public @ResponseBody AccurateAsOfDateResult getAccurateAsOfDate() throws EntityRetrievalException { MeaningfulUseAccurateAsOfDTO dto = muManager.getMeaningfulUseAccurateAsOf(); if(dto == null){ throw new EntityRetrievalException("Could not retrieve entity for MeaningfulUseAccurateAsOf"); } AccurateAsOfDateResult ar = new AccurateAsOfDateResult(dto.getAccurateAsOfDate().getTime()); return ar; }
Source:
<code>private Metadata initializeMetadata(Data key, Object value) { try { Object keyMetadata = metadataInitializer.createFromData(key); Object valueMetadata; if (value instanceof Data) { valueMetadata = metadataInitializer.createFromData((Data) value); } else { valueMetadata = metadataInitializer.createFromObject(value); } if (keyMetadata != null || valueMetadata != null) { Metadata metadata = new Metadata(); metadata.setKeyMetadata(keyMetadata); metadata.setValueMetadata(valueMetadata); return metadata; } return null; } catch (IOException e) { return null; <START> } <END> }</code><technical_language>if care IOException, handle this exception source? createSchema is source method throwing it, catching exception there</technical_language>

Target:
private Metadata initializeMetadata(Data key, Object value) { try { Object keyMetadata = metadataInitializer.createFromData(key); Object valueMetadata; if (value instanceof Data) { valueMetadata = metadataInitializer.createFromData((Data) value); } else { valueMetadata = metadataInitializer.createFromObject(value); } if (keyMetadata != null || valueMetadata != null) { Metadata metadata = new Metadata(); metadata.setKeyMetadata(keyMetadata); metadata.setValueMetadata(valueMetadata); return metadata; } return null; } catch (IOException e) { return null; } catch (Exception e) { throw rethrow(e); } }
Source:
<code>private void initSchema(Job job) throws IOException { if (schema != null) { return; } schema = PigSchemaConverter.parsePigSchema(getPropertyFromUDFContext(PARQUET_PIG_SCHEMA)); requiredFieldList = PigSchemaConverter.deserializeRequiredFieldList(getPropertyFromUDFContext(PARQUET_PIG_REQUIRED_FIELDS)); <START> columnIndexAccess = Boolean.parseBoolean(getPropertyFromUDFContext(PARQUET_COLUMN_INDEX_ACCESS)); <END> if (schema == null && requestedSchema != null) { schema = requestedSchema; } if (schema == null) { final GlobalMetaData globalMetaData = getParquetInputFormat().getGlobalMetaData(job); schema = getPigSchemaFromMultipleFiles(globalMetaData.getSchema(), globalMetaData.getKeyValueMetaData()); } if (isElephantBirdCompatible(job)) { convertToElephantBirdCompatibleSchema(schema); } }</code><technical_language>backend/frontend interaction clearer, move read/write conf udfcontext setInput() lines setInput() costly need cached. remove interaction setInput initSchema. initSchema is called in setInput anyway</technical_language>

Target:
private void initSchema(Job job) throws IOException { if (schema != null) { return; } if (schema == null && requestedSchema != null) { schema = requestedSchema; } if (schema == null) { final GlobalMetaData globalMetaData = getParquetInputFormat().getGlobalMetaData(job); schema = getPigSchemaFromMultipleFiles(globalMetaData.getSchema(), globalMetaData.getKeyValueMetaData()); } if (isElephantBirdCompatible(job)) { convertToElephantBirdCompatibleSchema(schema); } }
Source:
<code>public static IParser getInstance() { <START> if (instance == null) { <END> instance = new GsonParser(); } return instance; }</code><technical_language>this need a singleton</technical_language>

Target:
public static IParser getInstance() { return new GsonParser(); }
Source:
<code>public boolean getFaultDomainAwareStandbyEnabled() { <START> return getBoolean(FAULT_DOMAIN_AWARE_STANDBY_ENABLED, false); <END> }</code><technical_language>nit: nice default value="false" in FAULT_DOMAIN_AWARE_STANDBY_ENABLED_DEFUALT=false</technical_language>

Target:
public boolean getFaultDomainAwareStandbyEnabled() { return getBoolean(FAULT_DOMAIN_AWARE_STANDBY_ENABLED, FAULT_DOMAIN_AWARE_STANDBY_ENABLED_DEFAULT); }
Source:
<code><START> private void testCreateInsertionFeature(String insertion, String insertionFeature) throws Exception { <END> String urlInsertion = "/ats/program/" + getSawProgram().getArtId() + "/insertion"; String urlFeature = "/ats/program/" + getSawProgram().getArtId() + "/insertion/1234567800/feature"; JsonArray setup = postAndCheck(urlInsertion, Entity.entity(insertion, MediaType.APPLICATION_JSON_TYPE)); JsonArray array = postAndCheck(urlFeature, Entity.entity(insertionFeature, MediaType.APPLICATION_JSON_TYPE)); Assert.assertEquals(1, array.size()); JsonObject obj = getObjectNamed("JAX Insertion Feature", array); Assert.assertNotNull("Did not find value Jax Insertion Feature", obj); }</code><technical_language>getUuid instead of getArtId,</technical_language>

Target:
private void testCreateInsertionFeature(String insertion, String insertionFeature) throws Exception { String urlInsertion = "/ats/program/" + getSawProgram().getUuid() + "/insertion"; String urlFeature = "/ats/program/" + getSawProgram().getUuid() + "/insertion/1234567800/feature"; JsonArray setup = postAndCheck(urlInsertion, Entity.entity(insertion, MediaType.APPLICATION_JSON_TYPE)); JsonArray array = postAndCheck(urlFeature, Entity.entity(insertionFeature, MediaType.APPLICATION_JSON_TYPE)); Assert.assertEquals(1, array.size()); JsonObject obj = getObjectNamed("JAX Insertion Feature", array); Assert.assertNotNull("Did not find value Jax Insertion Feature", obj); }
Source:
<code>public void setPublications() { try { List<Metacard> metacards = Security.getInstance() .runAsAdminWithException(() -> federationAdminService.getRegistryMetacards()); for (Metacard metacard : metacards) { String registryId = RegistryUtility.getRegistryId(metacard); if (registryId == null) { LOGGER.debug( "Warning metacard (id: {}} did not contain a registry id.", metacard.getId()); continue; } List<String> locations = RegistryUtility.getListOfStringAttribute( metacard, RegistryObjectMetacardType.PUBLISHED_LOCATIONS); if (!locations.isEmpty()) { publications.put(registryId, Collections.unmodifiableList(locations)); } else { publications.put(registryId, Collections.emptyList()); } } executorService.shutdown(); } catch (PrivilegedActionException | RuntimeException e) { LOGGER.debug( "Error reading from local catalog. Catalog is probably not up yet. Will try again later"); <START> executorService.schedule(this::setPublications, RETRY_INTERVAL, TimeUnit.SECONDS); <END> } }</code><technical_language>this Logger.debug("Error reading local catalog. Catalog is yet. try in seconds.", RETRY_INTERVAL)</technical_language>

Target:
public void setPublications() { try { List<Metacard> metacards = Security.getInstance() .runAsAdminWithException(() -> federationAdminService.getRegistryMetacards()); for (Metacard metacard : metacards) { String registryId = RegistryUtility.getRegistryId(metacard); if (registryId == null) { LOGGER.debug( "Warning metacard (id: {}} did not contain a registry id.", metacard.getId()); continue; } List<String> locations = RegistryUtility.getListOfStringAttribute( metacard, RegistryObjectMetacardType.PUBLISHED_LOCATIONS); if (!locations.isEmpty()) { publications.put(registryId, Collections.unmodifiableList(locations)); } else { publications.put(registryId, Collections.emptyList()); } } this.destroy(); } catch (PrivilegedActionException | RuntimeException e) { LOGGER.debug( "Error reading from local catalog. Catalog is probably not up yet. Will try again in seconds.", RETRY_INTERVAL); executorService.schedule(this::setPublications, RETRY_INTERVAL, TimeUnit.SECONDS); } }
Source:
<code>protected SalesforceApi() { SSLContext sc; try { String protocol = SSLContext.getDefault().getProtocol(); if (!protocol.equals("TLSv1.2") || !protocol.equals("TLSv1.1")) { sc = SSLContext.getInstance("TLSv1.2"); sc.init(null, null, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>a good code. notify users exceptions, we</technical_language>

Target:
protected SalesforceApi() { final SSLContext sc; try { final String protocol = SSLContext.getDefault().getProtocol(); if (!"TLSv1.2".equals(protocol)) { sc = SSLContext.getInstance("TLSv1.2"); sc.init(null, null, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } } catch (Exception e) { throw new IllegalStateException("Unexpected JVM without TLS 1.2 support", e); } }
Source:
<code>private Single<File> unzipAllFilesAndGetImportDatabaseFile(@NonNull File localZipFile, final boolean overwrite) { return Single.fromCallable(() -> { final SDCardFileManager external = persistenceManager.getExternalStorageManager(); StorageManager internal = persistenceManager.getInternalStorageManager(); if (overwrite) { <START> Logger.info(ManualRestoreTask.this, "Deleting old files from external storage"); <END> for (File f : external.listDirs()) { external.deleteRecursively(f); } } if (!external.unzip(localZipFile, overwrite)) { throw new IOException("Failed to unzip file: " + localZipFile); } Logger.info(ManualRestoreTask.this, "Importing shared preferences"); final File sdPrefs = external.getFile("shared_prefs"); final File prefs = internal.getFile(internal.getRoot().getParentFile(), "shared_prefs"); if (!internal.copy(sdPrefs, prefs, overwrite)) { throw new IOException("Failed to import settings"); } Logger.info(ManualRestoreTask.this, "Importing internal files"); final File internalDir = external.getFile("Internal"); if (!internal.copy(internalDir, internal.getRoot(), overwrite)) { Logger.error(ManualRestoreTask.this, "Failed to import local files"); } final File importDatabaseFile = external.getFile(DatabaseConstants.DATABASE_EXPORT_NAME); if (!importDatabaseFile.exists()) { throw new IOException("Failed to find our import database file"); } external.delete(localZipFile); return importDatabaseFile; }) .doOnSuccess(importDatabaseFile -> Logger.info(ManualRestoreTask.this, "Successfully unzipped our backup and configured all local files")); }</code><technical_language>This risky too. Is a deleting unlinked files? I worry deleting everything, this accidentally data loss</technical_language>

Target:
private Single<File> unzipAllFilesAndGetImportDatabaseFile(@NonNull File localZipFile, final boolean overwrite) { return Single.fromCallable(() -> { final SDCardFileManager external = persistenceManager.getExternalStorageManager(); StorageManager internal = persistenceManager.getInternalStorageManager(); if (!external.unzip(localZipFile, overwrite)) { throw new IOException("Failed to unzip file: " + localZipFile); } Logger.info(ManualRestoreTask.this, "Importing shared preferences"); final File sdPrefs = external.getFile("shared_prefs"); final File prefs = internal.getFile(internal.getRoot().getParentFile(), "shared_prefs"); if (!internal.copy(sdPrefs, prefs, overwrite)) { throw new IOException("Failed to import settings"); } Logger.info(ManualRestoreTask.this, "Importing internal files"); final File internalDir = external.getFile("Internal"); if (!internal.copy(internalDir, internal.getRoot(), overwrite)) { Logger.error(ManualRestoreTask.this, "Failed to import local files"); } final File importDatabaseFile = external.getFile(DatabaseConstants.DATABASE_EXPORT_NAME); if (!importDatabaseFile.exists()) { throw new IOException("Failed to find our import database file"); } external.delete(localZipFile); return importDatabaseFile; }) .doOnSuccess(importDatabaseFile -> Logger.info(ManualRestoreTask.this, "Successfully unzipped our backup and configured all local files")); }
Source:
<code>public HelixManagerProperty getHelixManagerProperty(String zkAddress, String clusterName) { CloudConfig cloudConfig; <START> HelixZkClient zkClient = null; <END> try { HelixZkClient.ZkConnectionConfig connectionConfig = new HelixZkClient.ZkConnectionConfig(zkAddress); zkClient = DedicatedZkClientFactory.getInstance().buildZkClient(connectionConfig); ConfigAccessor configAccessor = new ConfigAccessor(zkClient); try { cloudConfig = configAccessor.getCloudConfig(clusterName) == null ? buildEmptyCloudConfig(clusterName) : configAccessor.getCloudConfig(clusterName); } catch (HelixException e) { cloudConfig = buildEmptyCloudConfig(clusterName); } } finally { if (zkClient != null && !zkClient.isClosed()) { zkClient.close(); } } Properties properties = new Properties(); try { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(HELIX_PARTICIPANT_PROPERTY_FILE); properties.load(stream); } catch (IOException e) { String errMsg = String.format("failed to open Helix participant properties file: %s", HELIX_PARTICIPANT_PROPERTY_FILE); throw new IllegalArgumentException(errMsg, e); } LOG.info("HelixPropertyFactory successfully loaded helix participant properties: {}", properties); return new HelixManagerProperty(properties, cloudConfig); }</code><technical_language>move this block, closed in finally block anyway</technical_language>

Target:
public HelixManagerProperty getHelixManagerProperty(String zkAddress, String clusterName) { CloudConfig cloudConfig = getCloudConfig(zkAddress, clusterName); Properties properties = new Properties(); try { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(HELIX_PARTICIPANT_PROPERTY_FILE); properties.load(stream); } catch (IOException e) { String errMsg = String.format("failed to open Helix participant properties file: %s", HELIX_PARTICIPANT_PROPERTY_FILE); throw new IllegalArgumentException(errMsg, e); } LOG.info("HelixPropertyFactory successfully loaded helix participant properties: {}", properties); return new HelixManagerProperty(properties, cloudConfig); }
Source:
<code>public boolean getSystemDefaultThemeBool(String theme) { <START> if (context.getResources().getString(R.string.theme_dark_name).equals(theme)) { <END> return true; } else if (context.getResources().getString(R.string.theme_default_name).equals(theme)) { return getSystemDefaultThemeBool(getSystemDefaultTheme()); } return false; }</code><technical_language>context a method getString(), need resources get a String</technical_language>

Target:
public boolean getSystemDefaultThemeBool(String theme) { if (theme.equals(THEME_MODE_DARK)) { return true; } else if (theme.equals(THEME_MODE_DEFAULT)) { return getSystemDefaultThemeBool(getSystemDefaultTheme()); } return false; }
Source:
<code>public void testPutSmallObject() throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException { MockWebServer server = new MockWebServer(); MockResponse response = new MockResponse(); response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT); response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT); response.addHeader("ETag", MD5_HASH_STRING); response.setResponseCode(200); server.enqueue(response); server.start(); MinioClient client = new MinioClient(server.url("")); String inputString = HELLO_WORLD; ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8)); <START> client.putObject(BUCKET, "key", data, Long.valueOf(11), null, null, APPLICATION_OCTET_STREAM); <END> }</code><technical_language>need fix L prefix everywhere</technical_language>

Target:
public void testPutSmallObject() throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException { MockWebServer server = new MockWebServer(); MockResponse response = new MockResponse(); response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT); response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT); response.addHeader("ETag", MD5_HASH_STRING); response.setResponseCode(200); server.enqueue(response); server.start(); MinioClient client = new MinioClient(server.url("")); String inputString = HELLO_WORLD; ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8)); client.putObject(BUCKET, "key", data, 11L, null, null, APPLICATION_OCTET_STREAM); }
Source:
<code>public void removeActiveBannerAd(@NonNull String placementId, @Nullable VungleBannerAd activeBannerAd) { Log.d(TAG, "try to removeActiveBannerAd: " + placementId); boolean didRemove = mVungleBanners.remove(placementId, activeBannerAd); if (didRemove && activeBannerAd != null) { Log.d(TAG, "removeActiveBannerAd: " + activeBannerAd + "; size=" + mVungleBanners.size()); <START> activeBannerAd.detach(); <END> } }</code><technical_language>destroy called</technical_language>

Target:
public void removeActiveBannerAd(@NonNull String placementId, @Nullable VungleBannerAd activeBannerAd) { Log.d(TAG, "try to removeActiveBannerAd: " + placementId); boolean didRemove = mVungleBanners.remove(placementId, activeBannerAd); if (didRemove && activeBannerAd != null) { Log.d(TAG, "removeActiveBannerAd: " + activeBannerAd + "; size=" + mVungleBanners.size()); activeBannerAd.detach(); activeBannerAd.destroyAd(); } }
Source:
<code>private void outputModuleBinaryAndSourceMaps( List<JSModule> modules, B options) throws FlagUsageException, IOException { parsedModuleWrappers = parseModuleWrappers( config.moduleWrapper, modules); maybeCreateDirsForPath(config.moduleOutputPathPrefix); Writer mapFileOut = null; if (!(shouldGenerateMapPerModule(options) || config.useJsonStreams)) { mapFileOut = fileNameToOutputWriter2( expandSourceMapPath(options, null)); } for (JSModule m : modules) { <START> if (config.useJsonStreams) { <END> compiler.getSourceMap().reset(); StringBuilder output = new StringBuilder(); writeModuleOutput(output, m); JsonFileSpec jsonFile = new JsonFileSpec(output.toString(), getModuleOutputFileName(m)); StringBuilder moduleSourceMap = new StringBuilder(); compiler.getSourceMap().appendTo(moduleSourceMap, getModuleOutputFileName(m)); jsonFile.setSourceMap(moduleSourceMap.toString()); this.filesToStreamOut.add(jsonFile); } else { if (shouldGenerateMapPerModule(options)) { mapFileOut = fileNameToOutputWriter2(expandSourceMapPath(options, m)); } try (Writer writer = fileNameToLegacyOutputWriter( getModuleOutputFileName(m))) { if (options.sourceMapOutputPath != null) { compiler.getSourceMap().reset(); } writeModuleOutput(writer, m); if (options.sourceMapOutputPath != null) { compiler.getSourceMap().appendTo(mapFileOut, m.getName()); } } if (shouldGenerateMapPerModule(options) && mapFileOut != null) { mapFileOut.close(); mapFileOut = null; } } } if (mapFileOut != null) { mapFileOut.close(); } }</code><technical_language>here, result of IF is in iterations of loop. IF move loop. json-stream stuff extracted a helper method this easier read. if (config.useJsonStreams) { helper-method; } else { for (JSModule m : modules) { previous-stuff; } }</technical_language>

Target:
private void outputModuleBinaryAndSourceMaps( List<JSModule> modules, B options) throws FlagUsageException, IOException { parsedModuleWrappers = parseModuleWrappers( config.moduleWrapper, modules); maybeCreateDirsForPath(config.moduleOutputPathPrefix); Writer mapFileOut = null; if (!(shouldGenerateMapPerModule(options) || config.useJsonStreams)) { mapFileOut = fileNameToOutputWriter2( expandSourceMapPath(options, null)); } for (JSModule m : modules) { if (config.useJsonStreams) { this.filesToStreamOut.add(createJsonFileFromModule(m)); } else { if (shouldGenerateMapPerModule(options)) { mapFileOut = fileNameToOutputWriter2(expandSourceMapPath(options, m)); } try (Writer writer = fileNameToLegacyOutputWriter( getModuleOutputFileName(m))) { if (options.sourceMapOutputPath != null) { compiler.getSourceMap().reset(); } writeModuleOutput(writer, m); if (options.sourceMapOutputPath != null) { compiler.getSourceMap().appendTo(mapFileOut, m.getName()); } } if (shouldGenerateMapPerModule(options) && mapFileOut != null) { mapFileOut.close(); mapFileOut = null; } } } if (mapFileOut != null) { mapFileOut.close(); } }
Source:
<code>public void addCustomButton(String title, String cssClass, CustomButtonAction action) { customButtons.add( <START> new GeoServerAjaxFormLink(customButtons.newChildId()) { <END> @Override protected void onClick(AjaxRequestTarget target, Form<?> form) { action.onClick(target); } @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); CharSequence dynamicExtraParameters = "var result = {'cmSelection': getSelection()};" + "return result;"; attributes.getDynamicExtraParameters().add(dynamicExtraParameters); } }.add(new AttributeAppender("class", cssClass, " ")) .add(new AttributeAppender("title", title, " "))); }</code><technical_language>reason this changed? necessary (but a problem either)</technical_language>

Target:
public void addCustomButton(String title, String cssClass, CustomButtonAction action) { customButtons.add( new AjaxLink<Object>(customButtons.newChildId()) { @Override public void onClick(AjaxRequestTarget target) { action.onClick(target); } @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); CharSequence dynamicExtraParameters = "var result = {'cmSelection': getSelection()};" + "return result;"; attributes.getDynamicExtraParameters().add(dynamicExtraParameters); } }.add(new AttributeAppender("class", cssClass, " ")) .add(new AttributeAppender("title", title, " "))); }
Source:
<code>private void UpdateActionAvailability() { List tempVar = getSelectedItems(); ArrayList selectedItems = (ArrayList) ((tempVar != null) ? tempVar : new ArrayList()); boolean anyEngine = false; for (Object item : selectedItems) { <START> NetworkView networkView = (NetworkView) item; <END> if (StringHelper.stringsEqual(networkView.getname(), ENGINE_NETWORK)) { anyEngine = true; break; } } getEditCommand().setIsExecutionAllowed(selectedItems.size() == 1); getRemoveCommand().setIsExecutionAllowed(selectedItems.size() > 0 && !anyEngine); }</code><technical_language>cast network instead</technical_language>

Target:
private void UpdateActionAvailability() { List tempVar = getSelectedItems(); ArrayList selectedItems = (ArrayList) ((tempVar != null) ? tempVar : new ArrayList()); boolean anyEngine = false; for (Object item : selectedItems) { Network network = (Network) item; if (StringHelper.stringsEqual(network.getName(), ENGINE_NETWORK)) { anyEngine = true; break; } } getEditCommand().setIsExecutionAllowed(selectedItems.size() == 1); getRemoveCommand().setIsExecutionAllowed(selectedItems.size() > 0 && !anyEngine); }