auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void changePasswordUsingSecretAnswer(String secretAnswer, String pw) throws APIException { <START> User user = Context.getAuthenticatedUser(); <END> if(!isSecretAnswer(user, secretAnswer)) { throw new APIException("secret.answer.not.correct", (Object[]) null); } dao.changePassword(user, pw); }</code><technical_language>code pretty same, this checks secret answer is correct. factor other code in other changePassword method a utility method call checking secret password is correct</technical_language>

Target:
public void changePasswordUsingSecretAnswer(String secretAnswer, String pw) throws APIException { User user = Context.getAuthenticatedUser(); if(!isSecretAnswer(user, secretAnswer)) { throw new APIException("secret.answer.not.correct", (Object[]) null); } updatePassword(user, pw); }
Source:
<code>public SqliteIndexedStorageUtility(Class<T> prototype, String sandboxId, String tableName, String databasePath) { this.tableName = tableName; this.sandboxId = sandboxId; this.prototype = prototype; if(databasePath == null){ <START> databaseFolder = new File(DATABASE_FOLDER); <END> } else{ databaseFolder = new File(databasePath); } Connection c = null; try { c = getConnection(); SqlHelper.createTable(c, tableName, prototype.newInstance()); c.close(); } catch (SQLException e) { System.out.println("Couldn't create table: " + tableName + " due to exception: " + e); e.printStackTrace(); } catch(InstantiationException | IllegalAccessException | ClassNotFoundException e){ throw new RuntimeException(e); } finally{ try { if (c != null) { c.close(); } } catch (SQLException e) { e.printStackTrace(); } } }</code><technical_language>Is pass this in is a dependency classes "Agreeing" default? sketches out in places check for null set default if so. Feels more consistent reliable if of classes required path location, central place set if provided</technical_language>

Target:
public SqliteIndexedStorageUtility(Class<T> prototype, String sandboxId, String tableName, String databasePath) { this.tableName = tableName; this.sandboxId = sandboxId; this.prototype = prototype; databaseFolder = new File(databasePath); Connection c = null; try { c = getConnection(); SqlHelper.createTable(c, tableName, prototype.newInstance()); c.close(); } catch (SQLException e) { System.out.println("Couldn't create table: " + tableName + " due to exception: " + e); e.printStackTrace(); } catch(InstantiationException | IllegalAccessException | ClassNotFoundException e){ throw new RuntimeException(e); } finally{ try { if (c != null) { c.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
Source:
<code>public CourseInstructorCopyTable getCopyInstructorForm() { List<CourseInstructorCopyTableRow> copyQuestionRows = buildCopyInstructorModalRows(instructors); <START> return new CourseInstructorCopyTable(copyQuestionRows); <END> }</code><technical_language>I find name copyQuestionRows misleading..</technical_language>

Target:
public CourseInstructorCopyTable getCopyInstructorForm() { List<CourseInstructorCopyTableRow> copyInstructorModalRows = buildCopyInstructorModalRows(instructors); return new CourseInstructorCopyTable(copyInstructorModalRows); }
Source:
<code>private static String messagesToJson(List<String> tags) { <START> String[] array = new String[tags.size()]; <END> return messagesToJson(tags.toArray(array)); }</code><technical_language>IDEA toArray(new String[collection.size()]) performance improvement toArray(new String[0]) call is encouraged</technical_language>

Target:
private static String messagesToJson(List<String> tags) { return messagesToJson(tags.toArray(new String[0])); }
Source:
<code>private Mono<TextAnalyticsPagedResponse<RecognizeLinkedEntitiesResult>> getRecognizedLinkedEntitiesResponseInPage( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.entitiesLinkingWithResponseAsync( new MultiLanguageBatchInput().setDocuments(Transforms.toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Recognized linked entities for a batch of documents - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to recognize linked entities - {}", error)) <START> .map(this::toTextAnalyticsPagedResponse) <END> .onErrorMap(throwable -> { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse()); } return throwable; }); }</code><technical_language>If error happen early, map error in early phase mapping page result</technical_language>

Target:
private Mono<TextAnalyticsPagedResponse<RecognizeLinkedEntitiesResult>> getRecognizedLinkedEntitiesResponseInPage( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.entitiesLinkingWithResponseAsync( new MultiLanguageBatchInput().setDocuments(Transforms.toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Recognized linked entities for a batch of documents - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to recognize linked entities - {}", error)) .map(this::toTextAnalyticsPagedResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); }
Source:
<code>public BigDecimal convertRain(BigDecimal value) { if (this == DEFAULT_UNIT_SYSTEM) { return value; } <START> return value.multiply(new BigDecimal(0.0393700787)); <END> }</code><technical_language>private static final BigDecimal constant instead of new conversion</technical_language>

Target:
public BigDecimal convertRain(BigDecimal value) { if (this == DEFAULT_UNIT_SYSTEM) { return value; } return value.multiply(MM_TO_INCHES); }
Source:
<code>public <T> T unmarshal(String data, String marshallingFormat, Class<T> unmarshalType) { if (data == null || data.isEmpty()) { return null; } MarshallingFormat format = getFormat(marshallingFormat); Marshaller marshaller = serverMarshallers.get(format); if (marshaller == null) { if (registry != null) { marshaller = MarshallerFactory.getMarshaller(registry.getExtraClasses(), format, this.getClass().getClassLoader()); } else { marshaller = MarshallerFactory.getMarshaller(format, this.getClass().getClassLoader()); <START> } <END> serverMarshallers.put(format, marshaller); } Object instance = marshaller.unmarshall(data, unmarshalType); if (instance instanceof Wrapped) { return (T) ((Wrapped) instance).unwrap(); } return (T) instance; }</code><technical_language>this if/else replaced with: marshaller = MarshallerFactory.getMarshaller(getExtraClasses(registry), format, this.getClass().getClassLoader()); getExtraClasses(registry) do check if registry return empty set. wdyt</technical_language>

Target:
public <T> T unmarshal(String data, String marshallingFormat, Class<T> unmarshalType) { if (data == null || data.isEmpty()) { return null; } MarshallingFormat format = getFormat(marshallingFormat); Marshaller marshaller = serverMarshallers.get(format); if (marshaller == null) { marshaller = MarshallerFactory.getMarshaller(getExtraClasses(registry), format, this.getClass().getClassLoader()); serverMarshallers.put(format, marshaller); } Object instance = marshaller.unmarshall(data, unmarshalType); if (instance instanceof Wrapped) { return (T) ((Wrapped) instance).unwrap(); } return (T) instance; }
Source:
<code>public void startElement(String uri, String localName, String qName, Attributes attributes) { if (qName.equals(nodeName)) { strings = new String[3]; final String[] splitStrings = attributes.getValue(0).split(SPLIT_ONE); <START> if (splitStrings[0].substring(0, 7).equals(PREFIX_CONFIG)) { <END> final String moduleName = splitStrings[0].substring(7).split(SPLIT_TWO)[0]; strings[0] = moduleName; strings[1] = splitStrings[1]; } } currentTag = qName; }</code><technical_language>substring(0, 7) 7? please avoid magic numbers</technical_language>

Target:
public void startElement(String uri, String localName, String qName, Attributes attributes) { if (qName.equals(NODE_NAME)) { final String[] moduleAndCheckName = attributes.getValue(0).split(SPLIT_CHECK_NAME_IN_ATTRIBUTE); if (moduleAndCheckName[0].startsWith(PREFIX_CONFIG)) { singleCheckNameList = new ArrayList<>(); final String moduleName = moduleAndCheckName[0].replaceAll("(.*config_)|(\\.html.*)", ""); singleCheckNameList.add(moduleName); singleCheckNameList.add(moduleAndCheckName[1]); } } currentTag = qName; }
Source:
<code><START> private Object getAllRowsAndAssert(WideRowTable table, Blackhole blackhole, Consumer<Integer> assertion) { <END> return table.getTransactionManager().runTaskThrowOnConflict(txn -> { Iterator<Map.Entry<Cell, byte[]>> iter = txn.getRowsColumnRange( table.getTableRef(), Collections.singleton(Tables.ROW_BYTES.array()), new ColumnRangeSelection(null, null), 10000); int count = 0; while (iter.hasNext()) { blackhole.consume(iter.next()); ++count; } return count; }); }</code><technical_language>accept count</technical_language>

Target:
private void getAllRowsAndAssert(WideRowTable table, Blackhole blackhole, Consumer<Integer> assertion) { int rowsRead = table.getTransactionManager().runTaskThrowOnConflict(txn -> { Iterator<Map.Entry<Cell, byte[]>> iter = txn.getRowsColumnRange( table.getTableRef(), Collections.singleton(Tables.ROW_BYTES.array()), new ColumnRangeSelection(null, null), 10000); int count = 0; while (iter.hasNext()) { blackhole.consume(iter.next()); ++count; } return count; }); assertion.accept(rowsRead); }
Source:
<code>public boolean isLDAPUSer(final String username) { boolean searchResultFlag = false; String searchFilter = "(&(objectCategory=person)(sAMAccountName=" + username + "))"; SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); try { <START> init(); <END> NamingEnumeration<SearchResult> results = this.ctx.search(this.searchBase, searchFilter, searchControls); if (results == null) { return false; } SearchResult searchResult = null; Attributes attribs = null; @SuppressWarnings("rawtypes") NamingEnumeration allMembers = null; String accoutnName = null; while (results.hasMoreElements()) { searchResult = results.nextElement(); attribs = searchResult.getAttributes(); if (attribs.size() > 0) { Attribute attribute = attribs.get("sAMAccountName"); allMembers = attribute.getAll(); while ((allMembers != null) && allMembers.hasMoreElements()) { accoutnName = (String) allMembers.next(); if (accoutnName.equalsIgnoreCase(username)) { searchResultFlag = true; break; } } } if (searchResultFlag) { break; } } } catch (NamingException e) { logger.debug(e, "Error checking LDAP user [%s]", username); } finally { if (this.ctx != null) { try { this.ctx.close(); } catch (NamingException e) { logger.debug(e, "Error closing context"); } } } return searchResultFlag; }</code><technical_language>ctx checked for null. init() return a null</technical_language>

Target:
public boolean isLDAPUSer(final String username) { boolean result = false; try { String accountName = findAccountNameForUser(username); result = accountName != null; } catch (NamingException ex) { logger.info(ex, "Error authenticating LDAP user [%s]", username); } return result; }
Source:
<code>static Type[] mapKeyAndValueTypes(Type context, Class<?> contextRawType) { if (context == Properties.class) return new Type[] { String.class, String.class }; Type mapType = getSupertype(context, contextRawType, Map.class); if (mapType instanceof ParameterizedType) { ParameterizedType mapParameterizedType = (ParameterizedType) mapType; <START> return getCanonicalizedMapTypeArguments(mapParameterizedType); <END> } return new Type[] { Object.class, Object.class }; }</code><technical_language>Frustratingly, this enough. need do for collections, 270</technical_language>

Target:
static Type[] mapKeyAndValueTypes(Type context, Class<?> contextRawType) { if (context == Properties.class) return new Type[] { String.class, String.class }; Type mapType = getSupertype(context, contextRawType, Map.class); if (mapType instanceof ParameterizedType) { ParameterizedType mapParameterizedType = (ParameterizedType) mapType; return mapParameterizedType.getActualTypeArguments(); } return new Type[] { Object.class, Object.class }; }
Source:
<code>private void flush() { synchronized (lock) { tableToBulkMutation.values().stream().forEach(mutation -> { try { mutation.flush(); } catch (final InterruptedException e) { <START> log.error("Failed to apply mutation {}:{}", mutation, e.getMessage()); <END> throw new RuntimeException(e); } }); } }</code><technical_language>log here. Exception is re-thrown relevant information mutations verbose</technical_language>

Target:
private void flush() { synchronized (lock) { tableToBulkMutation.values().stream().forEach(mutation -> { try { mutation.flush(); } catch (final InterruptedException e) { throw new RuntimeException(e); } }); } }
Source:
<code>public void testUnserializableResponse_exceptionPropagatesToClientCallback() throws Throwable { IExecutorService service = client.getExecutorService("executor"); TaskWithUnserialazableResponse counterCallable = new TaskWithUnserialazableResponse(); final CountDownLatch countDownLatch = new CountDownLatch(1); final AtomicReference<Throwable> throwable = new AtomicReference<Throwable>(); service.submit(counterCallable, new ExecutionCallback() { @Override public void onResponse(Object response) { } @Override public void onFailure(Throwable t) { <START> countDownLatch.countDown(); <END> throwable.set(t.getCause()); } }); assertOpenEventually(countDownLatch); throw throwable.get(); }</code><technical_language>I need put this line next line, right</technical_language>

Target:
public void testUnserializableResponse_exceptionPropagatesToClientCallback() throws Throwable { IExecutorService service = client.getExecutorService("executor"); TaskWithUnserialazableResponse counterCallable = new TaskWithUnserialazableResponse(); final CountDownLatch countDownLatch = new CountDownLatch(1); final AtomicReference<Throwable> throwable = new AtomicReference<Throwable>(); service.submit(counterCallable, new ExecutionCallback() { @Override public void onResponse(Object response) { } @Override public void onFailure(Throwable t) { throwable.set(t.getCause()); countDownLatch.countDown(); } }); assertOpenEventually(countDownLatch); throw throwable.get(); }
Source:
<code>public CifsWinrsConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); <START> ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); <END> ConnectionValidator.assetNotThroughJumpstation(mapper, CIFS_PROTOCOL, cifsConnectionType); ConnectionValidator.assertNoSingleQuoteInPassword(password, CIFS_PROTOCOL, cifsConnectionType); this.options = options; }</code><technical_language>static imports</technical_language>

Target:
public CifsWinrsConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper); }
Source:
<code>private ActivityMetadata createMetadataObject(final ActivityDTO dto) { ActivityMetadata metadata = null; switch (dto.getConcept()) { case CERTIFIED_PRODUCT: metadata = new ListingActivityMetadata(); break; case DEVELOPER: metadata = new DeveloperActivityMetadata(); break; case PRODUCT: metadata = new ProductActivityMetadata(); break; case VERSION: metadata = new VersionActivityMetadata(); break; case CERTIFICATION_BODY: metadata = new CertificationBodyActivityMetadata(); break; <START> case ATL: <END> metadata = new TestingLabActivityMetadata(); break; default: break; } return metadata; }</code><technical_language>do ACB & ATL, CERTIFICATION_BODY & TESTING_LAB</technical_language>

Target:
private ActivityMetadata createMetadataObject(final ActivityDTO dto) { ActivityMetadata metadata = null; switch (dto.getConcept()) { case CERTIFIED_PRODUCT: metadata = new ListingActivityMetadata(); break; case DEVELOPER: metadata = new DeveloperActivityMetadata(); break; case PRODUCT: metadata = new ProductActivityMetadata(); break; case VERSION: metadata = new VersionActivityMetadata(); break; case CERTIFICATION_BODY: metadata = new CertificationBodyActivityMetadata(); break; case TESTING_LAB: metadata = new TestingLabActivityMetadata(); break; default: break; } return metadata; }
Source:
<code>public void TXBegin(TransactionType type) { switch (type){ case WRITE_AFTER_WRITE: WWTXBegin(); return; case OPTIMISTIC: OptimisticTXBegin(); return; default: <START> throw new IllegalArgumentException("Unsupported TXN type"); <END> } }</code><technical_language>Do want include input "type" parameter in exception for debugging</technical_language>

Target:
public void TXBegin(TransactionType type) { switch (type){ case WRITE_AFTER_WRITE: WWTXBegin(); return; case OPTIMISTIC: OptimisticTXBegin(); return; default: throw new IllegalArgumentException("Unsupported TXN type:"+type.toString()); } }
Source:
<code>private List<String> findPDPToEmailAddress() { <START> Collection addresses = parameterService.getParameterValuesAsString(KFSConstants.ParameterNamespaces.PDP, KfsParameterConstants.BATCH_COMPONENT, <END> CUPdpParameterConstants.PDP_ACH_INVALID_EMAIL_ERROR_REPORT_TO_ADDRESSES); return new ArrayList<String>(addresses); }</code><technical_language>KFSContstants.ParameterNamespaces.PDP is marked deprecated in base code suggests switching KFSConstants.CoreModuleNamespaces. Do a tech debt user story for this</technical_language>

Target:
private List<String> findPDPToEmailAddress() { Collection addresses = parameterService.getParameterValuesAsString(KFSConstants.CoreModuleNamespaces.PDP, KfsParameterConstants.BATCH_COMPONENT, CUPdpParameterConstants.PDP_ACH_INVALID_EMAIL_ERROR_REPORT_TO_ADDRESSES); return new ArrayList<String>(addresses); }
Source:
<code>private Versioned<Collection<? extends byte[]>> toVersioned( MapEntryValues value) { return value == null <START> ? new Versioned<>(Lists.newArrayList(), -1) <END> : new Versioned<>(value.values(), value.version()); }</code><technical_language>this need a mutable? wrap empty list instead</technical_language>

Target:
private Versioned<Collection<? extends byte[]>> toVersioned( MapEntryValues value) { return value == null ? new Versioned<>(Collections.emptyList(), -1) : new Versioned<>(value.values(), value.version()); }
Source:
<code>private void extractMappings() { if (config.mapping != null && config.mapping.isEmpty()) { isSimple = true; } else { isSimple = false; String[] pathMaps = config.mapping.split(","); for (String pathMap : pathMaps) { String[] mapParts = pathMap.split(":"); String field = mapParts[0]; String expression = mapParts[1]; if (field.isEmpty() && !expression.isEmpty()) { throw new IllegalArgumentException("Json path expression '" + expression + <START> "' has not output field specified"); <END> } if (expression.isEmpty() && !field.isEmpty()) { throw new IllegalArgumentException("Field '" + field + "' doesn't have Json path expression."); } mapping.put(field, expression); } } }</code><technical_language>-></technical_language>

Target:
private void extractMappings() { if (config.mapping != null && config.mapping.isEmpty()) { isSimple = true; } else { isSimple = false; String[] pathMaps = config.mapping.split(","); for (String pathMap : pathMaps) { String[] mapParts = pathMap.split(":"); String field = mapParts[0]; String expression = mapParts[1]; if (field.isEmpty() && !expression.isEmpty()) { throw new IllegalArgumentException("Json path expression '" + expression + "' has no output field specified"); } if (expression.isEmpty() && !field.isEmpty()) { throw new IllegalArgumentException("Field '" + field + "' doesn't have Json path expression."); } mapping.put(field, expression); } } }
Source:
<code>Set<ObjectId> getShallowCommits() throws IOException { if (shallowFile == null || !shallowFile.isFile()) return Collections.emptySet(); if (shallowFileSnapshot == null || shallowFileSnapshot.isModified(shallowFile)) { shallowCommitsIds = new HashSet<ObjectId>(); final BufferedReader reader = open(shallowFile); try { String line; while ((line = reader.readLine()) != null) { try { shallowCommitsIds.add(ObjectId.fromString(line)); } catch (IllegalArgumentException ex) { throw new <START> IOException("bad shallow line: " + <END> line); } } } finally { reader.close(); } shallowFileSnapshot = FileSnapshot.save(shallowFile); } return shallowCommitsIds; }</code><technical_language>this external string resource</technical_language>

Target:
Set<ObjectId> getShallowCommits() throws IOException { if (shallowFile == null || !shallowFile.isFile()) return Collections.emptySet(); if (shallowFileSnapshot == null || shallowFileSnapshot.isModified(shallowFile)) { shallowCommitsIds = new HashSet<ObjectId>(); final BufferedReader reader = open(shallowFile); try { String line; while ((line = reader.readLine()) != null) { try { shallowCommitsIds.add(ObjectId.fromString(line)); } catch (IllegalArgumentException ex) { throw new IOException(MessageFormat .format(JGitText.get().badShallowLine, line)); } } } finally { reader.close(); } shallowFileSnapshot = FileSnapshot.save(shallowFile); } return shallowCommitsIds; }
Source:
<code>private void handlePartialResults( QueryResponse solrResponse, Map<String, Serializable> responseProps) { if (solrResponse.getResponseHeader() != null) { Boolean partialResults = (Boolean) solrResponse.getResponseHeader().get("partialResults"); if (Boolean.TRUE.equals(partialResults)) { responseProps.put("partial-results", true); if (LOGGER.isDebugEnabled()) { String q = "unknown"; if (solrResponse.getResponseHeader().get("params") != null <START> && solrResponse.getResponseHeader().get("params") instanceof SimpleOrderedMap) { <END> q = String.valueOf( ((SimpleOrderedMap) solrResponse.getResponseHeader().get("params")).get("q")); } LOGGER.debug( "Found partial results for query that took {}ms.", solrResponse.getResults().getNumFound(), q, solrResponse.getQTime()); } } } }</code><technical_language>Is enough simply check for instanceof Map instead</technical_language>

Target:
private void handlePartialResults( QueryResponse solrResponse, Map<String, Serializable> responseProps) { boolean partialResults = Optional.of(solrResponse) .map(QueryResponse::getResponseHeader) .map(header -> header.get("partialResults")) .filter(Boolean.class::isInstance) .map(Boolean.class::cast) .orElse(false); if (!partialResults) { return; } responseProps.put("partial-results", true); if (LOGGER.isDebugEnabled()) { String q = Optional.of(solrResponse) .map(QueryResponse::getResponseHeader) .map(header -> header.get("params")) .filter(SimpleOrderedMap.class::isInstance) .map(SimpleOrderedMap.class::cast) .map(params -> params.get("q")) .map(String::valueOf) .orElse("unknown"); LOGGER.debug( "Found partial results for query that took {}ms.", solrResponse.getResults().getNumFound(), q, solrResponse.getQTime()); } }
Source:
<code>public String lookup(final LogEvent event, final String key) { final Message msg = event.getMessage(); <START> if (msg instanceof MapMessage) { <END> try { final Map<String, String> properties = ((StringMapMessage) msg).getData(); if (properties == null) { return ""; } if (key == null || key.length() == 0 || key.equals("*")) { final StringBuilder sb = new StringBuilder("{"); boolean first = true; for (final Map.Entry<String, String> entry : properties.entrySet()) { if (!first) { sb.append(", "); } sb.append(entry.getKey()).append("=").append(entry.getValue()); first = false; } sb.append("}"); return sb.toString(); } return properties.get(key); } catch (final Exception ex) { LOGGER.warn(LOOKUP, "Error while getting property [{}].", key, ex); return null; } } return null; }</code><technical_language>Appending Object values stringbuilder 69 is potentially dangerous, MapMessage.get(String) works this advantage of ParameterFormatter.deepToString</technical_language>

Target:
public String lookup(final LogEvent event, final String key) { final Message msg = event.getMessage(); if (msg instanceof MapMessage) { try { MapMessage<?, ?> mapMessage = (MapMessage) msg; if (key == null || key.length() == 0 || key.equals("*")) { return mapMessage.asString(MapMessage.MapFormat.JAVA_UNQUOTED.name()); } return mapMessage.get(key); } catch (final Exception ex) { LOGGER.warn(LOOKUP, "Error while getting property [{}].", key, ex); return null; } } return null; }
Source:
<code>public SearchResult(final List<Map<String, Object>> items, final PaginationInfo pagination) { <START> assert items != null; <END> assert pagination != null; this.items = items; this.pagination = pagination; }</code><technical_language>asserts validate arguments is generally considered a good practice. common approach is like: this.items = Preconditions.checkNotNull(items, "items null");</technical_language>

Target:
public SearchResult(final List<Map<String, Object>> items, final PaginationInfo pagination) { checkNotNull(items, "items cannot be null"); checkNotNull(pagination, "pagination cannot be null"); this.items = items; this.pagination = pagination; }
Source:
<code>private Publisher translatePublisherDetails(PublisherDetails simple) { <START> Maybe<Publisher> complex = Publisher.fromKey(simple.getKey()); <END> if (!complex.isNothing()) { return complex.requireValue(); } return null; }</code><technical_language>above. If a valid publisher throw exception</technical_language>

Target:
private Publisher translatePublisherDetails(PublisherDetails simple) { Maybe<Publisher> complex = Publisher.fromKey(simple.getKey()); if (!complex.isNothing()) { return complex.requireValue(); } else { throw new IllegalArgumentException("Publisher is not present while extracting " + "publisher details from the simple model."); } }
Source:
<code>public DefaultClientConfiguration(Properties prop) { this(); Assert.requireNonNull(prop, "prop"); <START> for(String key : prop.stringPropertyNames()) { <END> setStringProperty(key, prop.getProperty(key)); } }</code><technical_language>is this loop necessary</technical_language>

Target:
public DefaultClientConfiguration(Properties prop) { this(); Assert.requireNonNull(prop, "prop"); internalProperties.putAll(prop); }
Source:
<code>public void onAfterWrite(RepositoryStreamWriteContext ctx) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) ctx.getPath(); <START> logger.debug(String.format("Closing [%s]", repositoryPath)); <END> }</code><technical_language>move this debug message RepositoryStreamSupport#doClose RepositoryStreamSupport#close</technical_language>

Target:
public void onAfterWrite(RepositoryStreamWriteContext ctx) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) ctx.getPath(); logger.debug(String.format("Complete writing [%s]", repositoryPath)); }
Source:
<code>public Collection<ReferenceGenome> listAllReferenceGenomeTypes() throws IOException { <START> authorizationManager.throwIfNonAdmin(); <END> return referenceGenomeDao.listAllReferenceGenomeTypes(); }</code><technical_language>authorizationManager.throwIfUnauthenticated() instead users view references. current throwIfNonAdmin() for a non-admin user create edit a Project</technical_language>

Target:
public Collection<ReferenceGenome> listAllReferenceGenomeTypes() throws IOException { authorizationManager.throwIfUnauthenticated(); return referenceGenomeDao.listAllReferenceGenomeTypes(); }
Source:
<code>public void selectPhotosVideos() { photosVideos.click(); <START> waitForElementByElement(sortingOptions); <END> }</code><technical_language>log()</technical_language>

Target:
public void selectPhotosVideos() { photosVideos.click(); waitForElementByElement(sortingOptions); PageObjectLogging.log("selectPhotosVideos", "Photos and videos option is selected", true, driver); }
Source:
<code>public void testReader() throws IOException { EasyMock.reset(STORAGE); EasyMock.reset(CONFIG); addExpectedPrefixObjects(PREFIXES.get(0), ImmutableList.of(EXPECTED_URIS.get(0))); addExpectedGetObjectMock(EXPECTED_URIS.get(0)); addExpectedPrefixObjects(PREFIXES.get(1), ImmutableList.of(EXPECTED_URIS.get(1))); addExpectedGetObjectMock(EXPECTED_URIS.get(1)); EasyMock.expect(CONFIG.getMaxListingLength()).andReturn(EXPECTED_MAX_LISTING_LENGTH); EasyMock.replay(STORAGE); <START> EasyMock.replay(CONFIG); <END> GoogleCloudStorageInputSource inputSource = new GoogleCloudStorageInputSource( STORAGE, CONFIG, null, PREFIXES, null ); InputRowSchema someSchema = new InputRowSchema( new TimestampSpec("time", "auto", null), new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("dim1", "dim2"))), ImmutableList.of("count") ); InputSourceReader reader = inputSource.reader( someSchema, new CsvInputFormat(ImmutableList.of("time", "dim1", "dim2"), "|", false, null, 0), null ); CloseableIterator<InputRow> iterator = reader.read(); while (iterator.hasNext()) { InputRow nextRow = iterator.next(); Assert.assertEquals(NOW, nextRow.getTimestamp()); Assert.assertEquals("hello", nextRow.getDimension("dim1").get(0)); Assert.assertEquals("world", nextRow.getDimension("dim2").get(0)); } }</code><technical_language>nit: this is repeated in multiple tests, move a helper function</technical_language>

Target:
public void testReader() throws IOException { EasyMock.reset(STORAGE); EasyMock.reset(INPUT_DATA_CONFIG); addExpectedPrefixObjects(PREFIXES.get(0), ImmutableList.of(EXPECTED_URIS.get(0))); addExpectedGetObjectMock(EXPECTED_URIS.get(0)); addExpectedPrefixObjects(PREFIXES.get(1), ImmutableList.of(EXPECTED_URIS.get(1))); addExpectedGetObjectMock(EXPECTED_URIS.get(1)); EasyMock.expect(INPUT_DATA_CONFIG.getMaxListingLength()).andReturn(MAX_LISTING_LENGTH); EasyMock.replay(STORAGE); EasyMock.replay(INPUT_DATA_CONFIG); GoogleCloudStorageInputSource inputSource = new GoogleCloudStorageInputSource( STORAGE, INPUT_DATA_CONFIG, null, PREFIXES, null ); InputRowSchema someSchema = new InputRowSchema( new TimestampSpec("time", "auto", null), new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("dim1", "dim2"))), ImmutableList.of("count") ); InputSourceReader reader = inputSource.reader( someSchema, new CsvInputFormat(ImmutableList.of("time", "dim1", "dim2"), "|", false, null, 0), null ); CloseableIterator<InputRow> iterator = reader.read(); while (iterator.hasNext()) { InputRow nextRow = iterator.next(); Assert.assertEquals(NOW, nextRow.getTimestamp()); Assert.assertEquals("hello", nextRow.getDimension("dim1").get(0)); Assert.assertEquals("world", nextRow.getDimension("dim2").get(0)); } }
Source:
<code>public void afterShortExpirationEntryShouldBeAway() throws InterruptedException { final String KEY = "key"; final HazelcastInstance node = createHazelcastInstance(); try { IMap<String, String> map = node.getMap("test"); map.set(KEY, "value", 1500, TimeUnit.MILLISECONDS); map.lock(KEY); Object object = map.get(KEY); map.unlock(KEY); assertNotNull(object); <START> Thread.sleep(1700); <END> map.lock(KEY); object = map.get(KEY); map.unlock(KEY); assertNull(object); } finally { node.shutdown(); } }</code><technical_language>sleepAtLeastMillis ensure sleep time</technical_language>

Target:
public void afterShortExpirationEntryShouldBeAway() throws InterruptedException { final String KEY = "key"; final HazelcastInstance node = createHazelcastInstance(); try { IMap<String, String> map = node.getMap("test"); map.set(KEY, "value", 1500, TimeUnit.MILLISECONDS); map.lock(KEY); Object object = map.get(KEY); map.unlock(KEY); assertNotNull(object); sleepAtLeastMillis(1700); map.lock(KEY); object = map.get(KEY); map.unlock(KEY); assertNull(object); } finally { node.shutdown(); } }
Source:
<code>public DeferredPointLightsNode(Context context) { entityManager = context.get(EntityManager.class); <START> DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); <END> playerCamera = context.get(WorldRenderer.class).getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); lightGeometryMaterial = getMaterial(LIGHT_GEOMETRY_MATERIAL); addDesiredStateChange(new EnableMaterial(LIGHT_GEOMETRY_MATERIAL)); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); addDesiredStateChange(new EnableBlending()); addDesiredStateChange(new SetBlendFunction(GL_ONE, GL_ONE_MINUS_SRC_COLOR)); addDesiredStateChange(new DisableDepthTest()); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new SetFboWriteMask(false, false, true, READONLY_GBUFFER, displayResolutionDependentFBOs)); initLightSphereDisplayList(); }</code><technical_language>move this line lines it</technical_language>

Target:
public DeferredPointLightsNode(Context context) { entityManager = context.get(EntityManager.class); playerCamera = context.get(WorldRenderer.class).getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); lightGeometryMaterial = getMaterial(LIGHT_GEOMETRY_MATERIAL); addDesiredStateChange(new EnableMaterial(LIGHT_GEOMETRY_MATERIAL)); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); addDesiredStateChange(new EnableBlending()); addDesiredStateChange(new SetBlendFunction(GL_ONE, GL_ONE_MINUS_SRC_COLOR)); addDesiredStateChange(new DisableDepthTest()); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new SetFboWriteMask(false, false, true, READONLY_GBUFFER, displayResolutionDependentFBOs)); initLightSphereDisplayList(); }
Source:
<code>public SegmentMetadataQueryBuilder copy(SegmentMetadataQueryBuilder builder) { return new SegmentMetadataQueryBuilder() .dataSource(builder.dataSource) .intervals(builder.querySegmentSpec) .toInclude(toInclude) <START> .analysisTypes(analysisTypes.toArray(new SegmentMetadataQuery.AnalysisType[analysisTypes.size()])) <END> .merge(merge) .context(builder.context); }</code><technical_language>is required set analysisTypes calling this ? If this throw a NPE</technical_language>

Target:
public SegmentMetadataQueryBuilder copy(SegmentMetadataQueryBuilder builder) { final SegmentMetadataQuery.AnalysisType[] analysisTypesArray = analysisTypes != null ? analysisTypes.toArray(new SegmentMetadataQuery.AnalysisType[analysisTypes.size()]) : null; return new SegmentMetadataQueryBuilder() .dataSource(builder.dataSource) .intervals(builder.querySegmentSpec) .toInclude(toInclude) .analysisTypes(analysisTypesArray) .merge(merge) .context(builder.context); }
Source:
<code>public static void saveClient(OwnCloudClient client, Account savedAccount, Context context) { AccountManager ac = AccountManager.get(context.getApplicationContext()); if (client != null) { String cookiesString = client.getCookiesString(); <START> if (!cookiesString.equals("")) { <END> ac.setUserData(savedAccount, Constants.KEY_COOKIES, cookiesString); } } }</code><technical_language>this !"".equals(cookiesString) if cookiesString null, get NullPointerException</technical_language>

Target:
public static void saveClient(OwnCloudClient client, Account savedAccount, Context context) { AccountManager ac = AccountManager.get(context.getApplicationContext()); if (client != null) { String cookiesString = client.getCookiesString(); if (!"".equals(cookiesString)) { ac.setUserData(savedAccount, Constants.KEY_COOKIES, cookiesString); } } }
Source:
<code><START> private Map<TopicPartition, Long> readOffsets() throws CopycatException { <END> Map<TopicPartition, Long> offsets = new HashMap<TopicPartition, Long>(); Path path = new Path(url + "/" + topicsDir); PathFilter filter = new FileFilter(); try { FileStatus[] topics = fs.listStatus(path); for (FileStatus topic: topics) { assert(topic.isDirectory()); String topicName = topic.getPath().getName(); FileStatus[] partitions = fs.listStatus(topic.getPath(), filter); for (FileStatus partition: partitions) { assert(partition.isFile()); String filename = partition.getPath().getName(); String[] parts = filename.split("\\."); int partitionNum = Integer.parseInt(parts[0]); long offset = Long.parseLong(parts[1]); TopicPartition topicPart = new TopicPartition(topicName, partitionNum); if (!offsets.containsKey(topicPart) || offset > offsets.get(topicPart)) { offsets.put(topicPart, offset); } } } return offsets; } catch (FileNotFoundException e) { throw new CopycatRuntimeException(e); } catch (IOException e) { throw new CopycatRuntimeException(e); } }</code><technical_language>simpler mark this throws IOException, FileNotFoundException convert Copycat exceptions in caller. in place exceptions need handled for some other errors in constructor anyway</technical_language>

Target:
private Map<TopicPartition, Long> readOffsets() throws IOException { Map<TopicPartition, Long> offsets = new HashMap<TopicPartition, Long>(); Path path = new Path(url + "/" + topicsDir); PathFilter filter = new CommittedFileFilter(); FileStatus[] topics = fs.listStatus(path); for (FileStatus topic: topics) { if (topic.isDirectory()) { String topicName = topic.getPath().getName(); FileStatus[] partitions = fs.listStatus(topic.getPath(), filter); for (FileStatus partition : partitions) { if (partition.isFile()) { String filename = partition.getPath().getName(); String[] parts = filename.split("\\."); try { int partitionNum = Integer.parseInt(parts[0]); long offset = Long.parseLong(parts[1]); TopicPartition topicPart = new TopicPartition(topicName, partitionNum); if (!offsets.containsKey(topicPart) || offset > offsets.get(topicPart)) { offsets.put(topicPart, offset); } } catch (NumberFormatException e) { log.warn("Invalid Copycat HDFS file: {}", filename); } } } } } return offsets; }
Source:
<code>public Long getDistance(InetAddress host, InetAddress host2) { if (host.equals(host2)) { return new Long(0); } else if (distances.get(host) != null && distances.get(host).get(host2) != null) { return distances.get(host).get(host2); <START> } else if (distances.get(host2) != null && distances.get(host2).get(host) != null) { <END> return distances.get(host2).get(host); } return new Long(Long.MAX_VALUE); }</code><technical_language>I is related changes enhancement, distances.get(host) distances.get(host2) extracted variables avoid calling get twice. Besides, new Long(0) new Long(Long.MAX_VALUE); cached avoid creating multiple objects? if I wrong getDistance expensive is part of algorithm time complexity is quadratic</technical_language>

Target:
public Long getDistance(InetAddress host, InetAddress host2) { if (host.equals(host2)) { return long0; } else { HashMap<InetAddress, Long> dhost = distances.get(host); HashMap<InetAddress, Long> dhost2 = distances.get(host2); Long dHostToHost2; Long dHost2ToHost; if (dhost != null && (dHostToHost2 = dhost.get(host2)) != null) { return dHostToHost2; } else if (dhost2 != null && (dHost2ToHost = dhost2.get(host)) != null) { return dHost2ToHost; } } return longMax; }
Source:
<code><START> static boolean hasRequiredParameter(String template) { <END> int index = -1; do { index = template.indexOf(":", index + 1); if (index >= 0) { final int regexIndex = template.indexOf("(", index); final int slashIndex = template.indexOf("/", index); int parameterNameEnding = Math.min(regexIndex, slashIndex); if (parameterNameEnding < 0) { parameterNameEnding = slashIndex; } if (parameterNameEnding < 0) { parameterNameEnding = template.length(); } int optional = template.indexOf("?", index); if (0 < optional && optional < parameterNameEnding) { continue; } int wildcard = template.indexOf("*", index); if (0 < wildcard && wildcard < parameterNameEnding) { return false; } return true; } else { return false; } } while (true); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Refactor this method reduce Cognitive Complexity 18 15 allowed. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
static boolean hasRequiredParameter(String template) { int index = -1; do { index = template.indexOf(':', index + 1); if (index >= 0) { final int regexIndex = template.indexOf('(', index); final int slashIndex = template.indexOf('/', index); int parameterNameEnding = Math.min(regexIndex, slashIndex); if (parameterNameEnding < 0) { parameterNameEnding = slashIndex; } if (parameterNameEnding < 0) { parameterNameEnding = template.length(); } int optional = template.indexOf('?', index); if (0 < optional && optional < parameterNameEnding) { continue; } int wildcard = template.indexOf('*', index); if (0 < wildcard && wildcard < parameterNameEnding) { return false; } return true; } else { return false; } } while (true); }
Source:
<code>public void testGetBaseNicVerifyDelegation() throws Exception { CalculateBaseNic spy = spy(calculateBaseNic); spy.getBaseNic(baseNic); <START> verify(spy).getBaseNic(Matchers.any(), Matchers.any()); <END> }</code><technical_language>replace static imports</technical_language>

Target:
public void testGetBaseNicVerifyDelegation() throws Exception { CalculateBaseNic spy = spy(calculateBaseNic); spy.getBaseNic(baseNic); verify(spy).getBaseNic(any(VdsNetworkInterface.class), anyMapOf(String.class, VdsNetworkInterface.class)); }
Source:
<code>public void removeObserver(String tenantId, String id, Observer observer) { List<Observer> observers = eventListener.observersMap.get(id); if (observers != null) { observers.remove(observer); <START> } <END> }</code><technical_language>want check if observers is empty if remove map - tidy up</technical_language>

Target:
public void removeObserver(String tenantId, String id, Observer observer) { List<Observer> observers = eventListener.observersMap.get(id); if (observers != null) { observers.remove(observer); if (observers.isEmpty()) { eventListener.observersMap.remove(id); } } }
Source:
<code>protected void prePopulateUserProfileResults(Step step, StepResult result) { user = DataProvider.getInstance().getUser(getContext()); if (user == null) { user = new User(); } if (result == null) { result = new StepResult<StepResult>(step); } for (ProfileInfoOption option : getProfileStep().getProfileInfoOptions()) { StepResult profileResult = StepResultHelper.findStepResult(result, option.getIdentifier()); if (profileResult == null) { <START> Step profileStep = StepHelper.getStepWithIdentifier(formStep.getFormSteps(), option.getIdentifier()); <END> StepResult stepResult = null; if (profileStep != null) { switch (option) { case NAME: if (user.getName() != null) { StepResult<String> nameResult = new StepResult<>(profileStep); nameResult.setResult(user.getName()); stepResult = nameResult; } break; case EMAIL: if (user.getEmail() != null) { StepResult<String> nameResult = new StepResult<>(profileStep); nameResult.setResult(user.getEmail()); stepResult = nameResult; } break; case BIRTHDATE: if (user.getBirthDate() != null) { StepResult<Long> nameResult = new StepResult<>(profileStep); nameResult.setResult(user.getBirthDate().getTime()); stepResult = nameResult; } break; } } if (stepResult != null) { result.setResultForIdentifier(stepResult.getIdentifier(), stepResult); } } } }</code><technical_language>a bit confused. A FormStep is a Step contains Steps. FormStep (or, extend) Task, multiple steps</technical_language>

Target:
protected void prePopulateUserProfileResults(Step step, StepResult result) { user = DataProvider.getInstance().getUser(getContext()); if (user == null) { user = new User(); } for (ProfileInfoOption option : getProfileStep().getProfileInfoOptions()) { StepResult profileResult = StepResultHelper.findStepResult(result, option.getIdentifier()); if (profileResult == null) { Step profileStep = StepHelper.getStepWithIdentifier(formStep.getFormSteps(), option.getIdentifier()); StepResult stepResult = null; if (profileStep != null) { switch (option) { case NAME: if (user.getName() != null) { StepResult<String> nameResult = new StepResult<>(profileStep); nameResult.setResult(user.getName()); stepResult = nameResult; } break; case EMAIL: if (user.getEmail() != null) { StepResult<String> nameResult = new StepResult<>(profileStep); nameResult.setResult(user.getEmail()); stepResult = nameResult; } break; case BIRTHDATE: if (user.getBirthDate() != null) { StepResult<Long> nameResult = new StepResult<>(profileStep); nameResult.setResult(user.getBirthDate().getTime()); stepResult = nameResult; } break; } } if (stepResult != null) { result.setResultForIdentifier(stepResult.getIdentifier(), stepResult); } } } }
Source:
<code>public static boolean isInChain(Certificate cert, List<Certificate> chain) { String lookSKI = getCertKeyIdSubject(cert); <START> if (null == lookSKI) { <END> return false; } String foundSKI = null; for (Certificate link : chain) { foundSKI = getCertKeyIdSubject(link); if (lookSKI.equals(foundSKI)) { return true; } } return false; }</code><technical_language>Inverse this, combine lines. get rid of entire branch</technical_language>

Target:
public static boolean isInChain(Certificate cert, List<Certificate> chain) { String lookSKI = getCertKeyIdSubject(cert); if (null != lookSKI) { for (Certificate link : chain) { String foundSKI = getCertKeyIdSubject(link); if (lookSKI.equals(foundSKI)) { return true; } } } return false; }
Source:
<code>private <T extends JavaScriptObject> void sendPost(final AsyncCallback<T> cb, String token) { RequestBuilder req = new RequestBuilder(RequestBuilder.POST, url.toString()); req.setHeader("Accept", JsonConstants.JSON_TYPE); <START> req.setHeader("Content-Type", "application/x-www-form-urlencoded"); <END> req.setRequestData(token); req.setCallback(new MyRequestCallback<T>(cb)); try { req.send(); } catch (RequestException e) { RpcStatus.INSTANCE.onRpcComplete(); cb.onFailure(e); } }</code><technical_language>simpler is send content type "application/x-xsrf-token" server require this content type of POST body. This harder for a browser format a valid POST request a traditional <form> tag. means server attempt parse _token field POST parameter map, means need _token hack in CmdLineParser loop, worry + = incorrectly handled incorrect escape. Alternatively GET return valid JSON of {_token:"text"} echo as-is a JSON content type in POST. simple for script language tools work with, client strip line of response body GET (to remove JSON_MAGIC literal) echo POST body, Content-Type set JSON_TYPE ("application/json")</technical_language>

Target:
private <T extends JavaScriptObject> void sendPost(final AsyncCallback<T> cb, String token) { RequestBuilder req = new RequestBuilder(RequestBuilder.POST, url.toString()); req.setHeader("Accept", JsonConstants.JSON_TYPE); req.setHeader("Content-Type", JsonConstants.JSON_TYPE); req.setRequestData(token); req.setCallback(new MyRequestCallback<T>(cb)); try { req.send(); } catch (RequestException e) { RpcStatus.INSTANCE.onRpcComplete(); cb.onFailure(e); } }