auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void alter_table_core(final String catName, final String dbname, final String name, final Table newTable, final EnvironmentContext envContext) throws InvalidOperationException, MetaException { startFunction("alter_table", ": " + TableName.getQualified(catName, dbname, name) + " newtbl=" + newTable.getTableName()); if (newTable.getParameters() == null || newTable.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) { newTable.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(System .currentTimeMillis() / 1000)); } if (newTable.getSd() != null) { String newLocation = newTable.getSd().getLocation(); if (org.apache.commons.lang.StringUtils.isNotEmpty(newLocation)) { Path tblPath = wh.getDnsPath(new Path(newLocation)); newTable.getSd().setLocation(tblPath.toString()); } } if (!newTable.isSetCatName()) { newTable.setCatName(catName); } boolean success = false; Exception ex = null; try { Table oldt = get_table_core(catName, dbname, name); firePreEvent(new PreAlterTableEvent(oldt, newTable, this)); <START> if (newTable.getDbName() == null) { <END> throw new InvalidOperationException("Unable to alter table" + dbname + "." + name + " as new db name is null"); } alterHandler.alterTable(getMS(), wh, catName, dbname, name, newTable, envContext, this); success = true; } catch (NoSuchObjectException e) { ex = e; throw new InvalidOperationException(e.getMessage()); } catch (MetaException | InvalidOperationException e) { ex = e; throw e; } catch (Exception e) { ex = e; throw newMetaException(e); } finally { endFunction("alter_table", success, ex, name); } }</code><technical_language>In case new DB name null</technical_language>

Target:
private void alter_table_core(final String catName, final String dbname, final String name, final Table newTable, final EnvironmentContext envContext) throws InvalidOperationException, MetaException { startFunction("alter_table", ": " + TableName.getQualified(catName, dbname, name) + " newtbl=" + newTable.getTableName()); if (newTable.getParameters() == null || newTable.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) { newTable.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(System .currentTimeMillis() / 1000)); } if (newTable.getSd() != null) { String newLocation = newTable.getSd().getLocation(); if (org.apache.commons.lang.StringUtils.isNotEmpty(newLocation)) { Path tblPath = wh.getDnsPath(new Path(newLocation)); newTable.getSd().setLocation(tblPath.toString()); } } if (!newTable.isSetCatName()) { newTable.setCatName(catName); } boolean success = false; Exception ex = null; try { Table oldt = get_table_core(catName, dbname, name); firePreEvent(new PreAlterTableEvent(oldt, newTable, this)); alterHandler.alterTable(getMS(), wh, catName, dbname, name, newTable, envContext, this); success = true; } catch (NoSuchObjectException e) { ex = e; throw new InvalidOperationException(e.getMessage()); } catch (MetaException | InvalidOperationException e) { ex = e; throw e; } catch (Exception e) { ex = e; throw newMetaException(e); } finally { endFunction("alter_table", success, ex, name); } }
Source:
<code>public void update(AccessPoint ap) { AccessPointEntity entity = datastore.findOne(AccessPointEntity.class, Filter.where("_id").is(ap.id)); if (entity != null) { <START> datastore.save(adapt(ap, entity.getOperatorId())); <END> } }</code><technical_language>if replace entity.getOperatorId() else (for example number 5), i tests pass</technical_language>

Target:
public void update(AccessPoint ap) { datastore.save(adapt(ap)); }
Source:
<code><START> void setStatus(final String status) { <END> getEventList().add(Pair.create(EventStrings.CRYPTOGRAPHY_STATUS, status)); }</code><technical_language>setStatus [](start = 9, length = 9) setexception indicating status of failure? #Pending</technical_language>

Target:
void setStatus(final String status) { setEvent(EventStrings.CRYPTOGRAPHY_STATUS, status); }
Source:
<code>private int findObjectsNeedingDelta(ObjectToPack[] list, int cnt, int type) { FIND: for (ObjectToPack otp : objectsLists[type]) { ObjectToPack base = otp.getDeltaBase(); if (base != null) { int d = 0; do { if (d < base.getChainLength()) continue FIND; base.setChainLength(++d); base = base.getDeltaBase(); <START> } while (base != null && base != otp); <END> continue; } if (otp.isDoNotDelta()) continue; if (otp.isDeltaRepresentation()) continue; otp.setWeight(0); list[cnt++] = otp; } return cnt; }</code><technical_language>"base == otp" case trip? If so, prevents cycles involve otp</technical_language>

Target:
private int findObjectsNeedingDelta(ObjectToPack[] list, int cnt, int type) throws IOException { for (ObjectToPack otp : objectsLists[type]) { ObjectToPack b = otp.getDeltaBase(); if (b != null) { otp.setVisited(); int d = 0; do { if (d < b.getChainLength()) break; b.setChainLength(++d); if (b.visited()) { reselectNonDelta(b); break; } b.setVisited(); b = b.getDeltaBase(); } while (b != null); for (b = otp; b != null && b.visited(); b = b.getDeltaBase()) b.clearVisited(); continue; } if (otp.isDoNotDelta()) continue; if (otp.isDeltaRepresentation()) continue; otp.setWeight(0); list[cnt++] = otp; } return cnt; }
Source:
<code>boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { return true; } <START> if (inflight.get(op.getURI()) != null) { <END> return false; } pending.remove(op.getURI()); inFlight.put(e.getURI(), e); } }</code><technical_language>!cancelled fail if cancelled is a primitive. If does, JVM CPU needs out of service</technical_language>

Target:
boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { return true; } if (inFlight.get(op.getURI()) != null) { return false; } pending.remove(op.getURI()); inFlight.put(op.getURI(), op); } return true; }
Source:
<code>private Object fetchObject(RequestScope requestScope, Class recordType, Optional<List<String>> ids, Optional<String> sort, Optional<String> offset, Optional<String> first, Optional<String> filters) { if(!ids.isPresent()) { List<PersistentResource> records = new ArrayList<>(PersistentResource. loadRecords(recordType, requestScope)); return records; } else { List<String> idList = ids.get(); if(idList.isEmpty()) { throw new IllegalArgumentException("Empty list passed to ids"); } HashSet recordSet = new HashSet(); for (String id : idList) { <START> recordSet.add(PersistentResource.loadRecord(recordType, id, requestScope)); <END> } return recordSet; } }</code><technical_language>This result in a bunch of trip calls datastore/DB. A approach add list of IDS filters call loadRecords list of filters</technical_language>

Target:
private Object fetchObject(RequestScope requestScope, Class recordType, Optional<List<String>> ids, Optional<String> sort, Optional<String> offset, Optional<String> first, Optional<String> filters) { if(!ids.isPresent()) { List<PersistentResource> records = new ArrayList<>(PersistentResource. loadRecords(recordType, requestScope, Optional.empty())); return records; } else { List<String> idList = ids.get(); if(idList.isEmpty()) { throw new BadRequestException("Empty list passed to ids"); } Optional<FilterExpression> filterExpression; EntityDictionary dictionary = requestScope.getDictionary(); Class<?> idType = dictionary.getIdType(recordType); String idField = dictionary.getIdFieldName(recordType); String entityTypeName = dictionary.getJsonAliasFor(recordType); filterExpression = Optional.of(new FilterPredicate( new FilterPredicate.PathElement( recordType, entityTypeName, idType, idField), Operator.IN, new ArrayList<>(idList))); return PersistentResource.loadRecords(recordType, requestScope, filterExpression); } }
Source:
<code>public void Test() { Collection<Cat> cats = Lists.newArrayList(); cats.add(new Cat(Optional.<String>absent())); <START> cats.add(new Cat(Optional.of("persan"))); <END> Cat c = alias(Cat.class); for (Cat cat : from(c, cats) .where($(c.getPedigree()).eq(Optional.of("persan"))) .list($(c))) { assertTrue(cat.getPedigree().isPresent()); assertEquals("persan", cat.getPedigree().get()); } }</code><technical_language>*persian</technical_language>

Target:
public void Test() { Collection<Cat> cats = Lists.newArrayList(); cats.add(new Cat(Optional.<String>absent())); cats.add(new Cat(Optional.of("persian"))); Cat c = alias(Cat.class); for (Cat cat : from(c, cats) .where($(c.getPedigree()).eq(Optional.of("persian"))) .list($(c))) { assertTrue(cat.getPedigree().isPresent()); assertEquals("persian", cat.getPedigree().get()); } }
Source:
<code>public String toString() { <START> return String.format("%30s: fboId %s (%sx%s)", this.getClass().getSimpleName(), fbo.getId(), fbo.width(), fbo.height()); <END> }</code><technical_language>Need name/urn in output</technical_language>

Target:
public String toString() { return String.format("%30s: %s (fboId: %s) (%sx%s)", this.getClass().getSimpleName(), fbo.getName(), fbo.getId(), fbo.width(), fbo.height()); }
Source:
<code>public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); List<String> tempList; <START> if (constraint != null) <END> tempList = autoCompleter.completeByPart(constraint.toString()); else tempList = new ArrayList<>(); filterResults.values = tempList; filterResults.count = tempList.size(); return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { clear(); if (results != null && results.count > 0) { addAll((List) results.values); notifyDataSetChanged(); } else notifyDataSetInvalidated(); } }; }</code><technical_language>One-line if possible</technical_language>

Target:
public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); List<String> tempList; if (constraint != null) tempList = autoCompleter.completeByPart(constraint.toString()); else tempList = new ArrayList<>(); filterResults.values = tempList; filterResults.count = tempList.size(); return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { clear(); if (results != null && results.count > 0) { addAll((List) results.values); notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } }; }
Source:
<code>public List<RemoteServerData> getServerList() { <START> return UnmodifiableList.decorate(remoteServerDataList); <END> }</code><technical_language>I Collections.unmodifyableList(...) here. I apache-commons variant is for JDK4 users</technical_language>

Target:
public List<RemoteServerData> getServerList() { return Collections.unmodifiableList(remoteServerDataList); }
Source:
<code>public static Version increment(Version version) { <START> final Version result = create(version.getNumber() + 1, currentTime()); <END> return result; }</code><technical_language>Please check version null. automated null checks fail</technical_language>

Target:
public static Version increment(Version version) { checkNotNull(version); final Version result = create(version.getNumber() + 1, getCurrentTime()); return result; }
Source:
<code>public void testSetupInvalidChildFromBaseClass() throws Exception { final TestBean testBean = new TestBean(); final DefaultConfiguration conf = new DefaultConfiguration("testConf"); final Field field = AutomaticBean.class.getDeclaredField("configuration"); field.setAccessible(true); field.set(testBean, conf); try { testBean.setupChild(conf); fail("expecting checkstyle exception"); } catch (CheckstyleException ex) { <START> assertEquals("expected exception", "testConf is not allowed as a child in testConf", <END> ex.getMessage()); } }</code><technical_language>@rnveach I name for parent child confuse</technical_language>

Target:
public void testSetupInvalidChildFromBaseClass() throws Exception { final TestBean testBean = new TestBean(); final DefaultConfiguration parentConf = new DefaultConfiguration("parentConf"); final DefaultConfiguration childConf = new DefaultConfiguration("childConf"); final Field field = AutomaticBean.class.getDeclaredField("configuration"); field.setAccessible(true); field.set(testBean, parentConf); try { testBean.setupChild(childConf); fail("expecting checkstyle exception"); } catch (CheckstyleException ex) { assertEquals("expected exception", "childConf is not allowed as a child in parentConf", ex.getMessage()); } }
Source:
<code>private void fillFieldsFromMetadataFile(FileformatInterface myRdf) throws PreferencesException { if (myRdf != null) { for (AdditionalField field : this.additionalFields) { if (field.isUghbinding() && field.getShowDependingOnDoctype()) { DocStructInterface myTempStruct = myRdf.getDigitalDocument().getLogicalDocStruct(); if (field.getDocstruct().equals("firstchild")) { try { myTempStruct = myRdf.getDigitalDocument().getLogicalDocStruct().getAllChildren().get(0); } catch (RuntimeException e) { logger.error(e.getMessage(), e); } } if (field.getDocstruct().equals("boundbook")) { myTempStruct = myRdf.getDigitalDocument().getPhysicalDocStruct(); } try { if (field.getMetadata().equals("ListOfCreators")) { StringBuilder authors = new StringBuilder(); if (myTempStruct.getAllPersons() != null) { for (PersonInterface p : myTempStruct.getAllPersons()) { authors.append(p.getLastName()); if (StringUtils.isNotBlank(p.getFirstName())) { authors.append(", "); authors.append(p.getFirstName()); } authors.append("; "); } if (authors.toString().endsWith("; ")) { authors.substring(0, authors.length() - 2); } } field.setValue(authors.toString()); } else { MetadataTypeInterface mdt = UghHelper.getMetadataType( serviceManager.getRulesetService().getPreferences(this.prozessKopie.getRuleset()), field.getMetadata()); MetadataInterface md = UghHelper.getMetadata(myTempStruct, mdt); if (md != null) { field.setValue(md.getValue()); } } } catch (UghHelperException e) { <START> logger.error(e.getMessage(), e); <END> Helper.setFehlerMeldung(e.getMessage(), ""); } } } } }</code><technical_language>setErrorMessage</technical_language>

Target:
private void fillFieldsFromMetadataFile(FileformatInterface myRdf) throws PreferencesException { if (myRdf != null) { for (AdditionalField field : this.additionalFields) { if (field.isUghbinding() && field.getShowDependingOnDoctype()) { DocStructInterface myTempStruct = myRdf.getDigitalDocument().getLogicalDocStruct(); if (field.getDocstruct().equals("firstchild")) { try { myTempStruct = myRdf.getDigitalDocument().getLogicalDocStruct().getAllChildren().get(0); } catch (RuntimeException e) { logger.error(e.getMessage(), e); } } if (field.getDocstruct().equals("boundbook")) { myTempStruct = myRdf.getDigitalDocument().getPhysicalDocStruct(); } try { if (field.getMetadata().equals("ListOfCreators")) { field.setValue(getAuthors(myTempStruct.getAllPersons())); } else { MetadataTypeInterface mdt = UghHelper.getMetadataType( serviceManager.getRulesetService().getPreferences(this.prozessKopie.getRuleset()), field.getMetadata()); MetadataInterface md = UghHelper.getMetadata(myTempStruct, mdt); if (md != null) { field.setValue(md.getValue()); } } } catch (UghHelperException e) { Helper.setErrorMessage(e.getMessage(), logger, e); } } } } }
Source:
<code>public void testGetChangedAttributesWithComments() { TaskAttribute attributeComment = newData.getRoot().createAttribute("custom"); attributeComment.setValue("1"); attributeComment.getMetaData().setType(TaskAttribute.TYPE_COMMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); <START> assertEquals(new ArrayList<>(diff.getNewComments()).get(0).getTaskAttribute(), attributeComment); <END> }</code><technical_language>Collections.singleton for attachments</technical_language>

Target:
public void testGetChangedAttributesWithComments() { TaskAttribute attributeComment = newData.getRoot().createAttribute("custom"); attributeComment.setValue("1"); attributeComment.getMetaData().setType(TaskAttribute.TYPE_COMMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(1, diff.getNewComments().size()); assertEquals(attributeComment, diff.getNewComments().iterator().next().getTaskAttribute()); }
Source:
<code><START> public void onUpdateToFirstVersion(OrienteerWebApplication app, ODatabaseDocument db) <END> { OSchemaHelper helper = OSchemaHelper.bind(db); helper.oClass(WIDGET_OCLASS_NAME, OWidgetsModule.OCLASS_WIDGET) .oProperty(OPROPERTY_PIVOT_TABLE_CONFIG, OType.STRING, 100).assignVisualization("textarea") .oProperty(OPROPERTY_PIVOT_CUSTOM_SQL, OType.STRING, 200).assignVisualization("textarea"); }</code><technical_language>below: a version. Please carefully code onInstall() onUpdate()</technical_language>

Target:
public void onUpdateToFirstVersion(OrienteerWebApplication app, ODatabaseDocument db) { OSchemaHelper helper = OSchemaHelper.bind(db); helper.oClass(WIDGET_OCLASS_NAME, OWidgetsModule.OCLASS_WIDGET) .oProperty(OPROPERTY_PIVOT_TABLE_CONFIG, OType.STRING, 100).assignVisualization("textarea"); }
Source:
<code>public int compareTo(QC t) { SampleQC s = (SampleQC) t; if (getId() != 0L && t.getId() != 0L) { if (getId() < s.getId()) return -1; if (getId() > s.getId()) return 1; } else if (getQcType() != null && s.getQcType() != null && getResults() != null && s.getResults() != null && getQcDate() != null && s.getQcDate() != null) { int type = getQcType().compareTo(s.getQcType()); if (type != 0) return type; int results = getResults().compareTo(s.getResults()); if (results != 0) return results; int creator = getQcDate().compareTo(s.getQcDate()); if (creator != 0) return creator; <START> } <END> return 0; }</code><technical_language>compareTo(QC) abstracted a bit: If compare date data, impl classes do int compare = super.compareTo(t); if (compare == 0) {// impl-specific compare} else {return 0} If date compared data, AbstractQc do generic stuff, call abstract "compareQcData" method, is overridden in of impl classes compare implementation-specific things. If 0, do date comparison. want move null checks (it matter if qcDate is null if ends basing response qcType) thoughts, change necessarily needed. is,</technical_language>

Target:
public int compareTo(QC t) { SampleQC s = (SampleQC) t; int compare = super.compareTo(t); if (compare != 0) { return compare; } else if (getResults() != null && s.getResults() != null) { compare = getResults().compareTo(s.getResults()); return compare; } return compare; }
Source:
<code>public void testPreHandle_not_call_afterPropertiesSet() throws Exception { <START> testTarget.preHandle(mockRequest, mockResponse, null); <END> assertThat(mockRequest.getAttributeNames().hasMoreElements(), is(false)); }</code><technical_language>Please assert a return value</technical_language>

Target:
public void testPreHandle_not_call_afterPropertiesSet() throws Exception { boolean actualReturnValue = testTarget.preHandle(mockRequest, mockResponse, null); assertThat(mockRequest.getAttributeNames().hasMoreElements(), is(false)); assertThat(actualReturnValue, is(true)); }
Source:
<code>private int unlockAndCountExceptions(RemoteLockService lockService, List<Future<LockRefreshToken>> futures) { <START> final int[] exceptionCounter = {0}; <END> futures.forEach(future -> { try { LockRefreshToken token = future.get(); if (token != null) { lockService.unlock(token); } } catch (Exception e) { assertThat(e).hasMessageContaining(TOO_MANY_REQUESTS_CODE); exceptionCounter[0]++; } }); return exceptionCounter[0]; }</code><technical_language>I get this exceptionCounter is final need for forEach(), I prefer AtomicInteger</technical_language>

Target:
private int unlockAndCountExceptions(RemoteLockService lockService, List<Future<LockRefreshToken>> futures) { AtomicInteger exceptionCounter = new AtomicInteger(0); futures.forEach(future -> { try { LockRefreshToken token = future.get(); if (token != null) { lockService.unlock(token); } } catch (Exception e) { assertThat(e).hasMessageContaining(TOO_MANY_REQUESTS_CODE); exceptionCounter.getAndIncrement(); } }); return exceptionCounter.get(); }
Source:
<code><START> public void setBytes(byte[] bytes) { <END> this.bytes = bytes; this.hash = Arrays.hashCode(bytes); }</code><technical_language>ByteString objects immutable, in a lot of places</technical_language>

Target:
void setBytes(byte[] bytes) { this.bytes = bytes; this.hash = Arrays.hashCode(bytes); }
Source:
<code>private String getBrowserScreenHeight(EpdqTemplateData templateData) { var screenHeight = templateData.getAuthCardDetails().getJsScreenHeight().orElse(DEFAULT_BROWSER_SCREEN_HEIGHT); <START> if (isCreatable(screenHeight) && BROWSER_SCREEN_HEIGHT_RANGE.contains(parseInt(screenHeight))) { <END> return screenHeight; } else { return DEFAULT_BROWSER_SCREEN_HEIGHT; } }</code><technical_language>I isCreatable( ) allow numbers parsed integers (like floats). I a regex is possibly right approach here. 0|[1-9][0-9]{0,5} work (either 0, _or_ a digit 1 9 digits 0 9, allowing numbers 0 999999 allowing leading zeroes, get parsed octal give unexpected results). I this method avoid need for Apache Commons altogether if this (assume NUMBER_FROM_0_TO_999999 is a constant Pattern of regex note change of return type int): java private int getBrowserScreenHeight(EpdqTemplateData templateData) { return templateData.getAuthCardDetails().getJsScreenHeight() .filter(screenHeight -> NUMBER_FROM_0_TO_999999.matcher(screenHeight).matches()) .map(Integer::parseInt) .filter(screenHeight -> screenHeight >= 0 && screenHeight <= 999999) .orElse(DEFAULT_BROWSER_SCREEN_HEIGHT); }</technical_language>

Target:
private String getBrowserScreenHeight(EpdqTemplateData templateData) { return templateData.getAuthCardDetails().getJsScreenHeight() .filter(screenHeight -> NUMBER_FROM_0_TO_999999.matcher(screenHeight).matches()) .map(Integer::parseInt) .filter(screenHeight -> screenHeight >= 0 && screenHeight <= 999999) .map(screenHeight -> Integer.toString(screenHeight)) .orElse(DEFAULT_BROWSER_SCREEN_HEIGHT); }
Source:
<code>public FilteredRequest(HttpServletRequest request, String serverName) { super(request); if (request instanceof FilteredRequest) { FilteredRequest filteredRequest = (FilteredRequest) request; contextPath = filteredRequest.contextPath; requestUri = filteredRequest.requestUri; requestUrl = filteredRequest.requestUrl; } else { URL baseUrl = toBaseUrl(serverName); contextPath = isExternalRequest(baseUrl) <START> ? SystemBaseUrl.EXTERNAL.getRootContext().replaceFirst("/$", "") <END> : ""; requestUri = contextPath + request.getRequestURI(); requestUrl = (baseUrl == null) ? serverName.replaceFirst("/$", "") + requestUri : baseUrl.toString() + requestUri; } }</code><technical_language>Stripping trailing slashes is common a library function for it</technical_language>

Target:
public FilteredRequest(HttpServletRequest request, String serverName) { super(request); if (request instanceof FilteredRequest) { FilteredRequest filteredRequest = (FilteredRequest) request; contextPath = filteredRequest.contextPath; requestUri = filteredRequest.requestUri; requestUrl = filteredRequest.requestUrl; } else { URL baseUrl = toBaseUrl(serverName); contextPath = isExternalUrl(baseUrl) ? SystemBaseUrl.EXTERNAL.getRootContext().replaceFirst("/$", "") : ""; requestUri = contextPath + request.getRequestURI(); requestUrl = (baseUrl == null) ? serverName.replaceFirst("/$", "") + requestUri : baseUrl.toString() + requestUri; } }
Source:
<code>public void complete() { <START> this.ownerProductCurator.saveAll(this.ownerProductEntities, false, true); <END> for (Map.Entry<Owner, Map<String, String>> entry : this.ownerProductUuidMap.entrySet()) { this.ownerProductCurator.updateOwnerProductReferences(entry.getKey(), entry.getValue()); } this.ownerProductUuidMap.clear(); this.ownerProductEntities.clear(); }</code><technical_language>ProductManager flush saving core products, saving owner-products. deferring flushing for when? flush CandlepinPoolManager starts processing pools? (same question applies for ContentNodeVisitor.complete)</technical_language>

Target:
public void complete() { this.ownerProductCurator.saveAll(this.ownerProductEntities, false, false); this.ownerProductCurator.flush(); for (Map.Entry<Owner, Map<String, String>> entry : this.ownerProductUuidMap.entrySet()) { this.ownerProductCurator.updateOwnerProductReferences(entry.getKey(), entry.getValue()); } this.ownerProductUuidMap.clear(); this.ownerProductEntities.clear(); }
Source:
<code>public void normalize(List<String> normalized) { String releaseOrTarget = null; if (release != null) { normalized.add("--release"); normalized.add(release); releaseOrTarget = release; } else { if (source != null) { normalized.add("-source"); normalized.add(source); } if (target != null) { normalized.add("-target"); normalized.add(target); releaseOrTarget = target; } } <START> if (parameters && Optional.ofNullable(releaseOrTarget).map(Ints::tryParse).orElse(8) >= 8) { <END> normalized.add("-parameters"); } }</code><technical_language>This complicated hard understand/maintain. suggest int for releaseOrTarget, this: int targetedJavaVersion = 8; if (release != null) { normalized.add("--release"); normalized.add(release); targetedJavaVersion = Integer.parseInt(release); } else { if (source != null) { normalized.add("-source"); normalized.add(source); } if (target != null) { normalized.add("-target"); normalized.add(target); targetedJavaVersion = Integer.parseInt(target); } } // Put -parameters option if target option provided target 8. if (parameters && targetedJavaVersion >= 8) { normalized.add("-parameters"); }</technical_language>

Target:
public void normalize(List<String> normalized) { int targetedJavaVersion = 8; if (release != null) { normalized.add("--release"); normalized.add(release); targetedJavaVersion = Integer.parseInt(release); } else { if (source != null) { normalized.add("-source"); normalized.add(source); } if (target != null) { normalized.add("-target"); normalized.add(target); targetedJavaVersion = Integer.parseInt(target); } } if (parameters && targetedJavaVersion >= 8) { normalized.add("-parameters"); } }
Source:
<code>public void parse(String[] args) throws <START> ParseException { <END> List<String> tcArgs = new ArrayList<>(); boolean found = false; for (String arg : args) { if (arg.equals("--cli")) { found = true; continue; } if (found) { tcArgs.add(arg); } } CommandLineParser cmdLineParser = new PosixParser(); try { fLineParser = cmdLineParser.parse(fOptions, tcArgs.toArray(new String[tcArgs.size()]), false); } catch(ParseException e) { System.out.println(Messages.CliParser_ErrorParsingArguments); System.out.println(e); System.out.println(); printHelpText(); throw e; } }</code><technical_language>third-party exception</technical_language>

Target:
public void parse(String[] args) throws ParseException { List<String> tcArgs = new ArrayList<>(); boolean found = false; boolean addNext = false; for (String arg : args) { if (arg.equals(CLI_ARGS_PREFIX)) { found = true; continue; } if (found) { tcArgs.add(arg); } else if (arg.equals("--open")) { System.out.println(Messages.CliParser_WarningCliPrefix); tcArgs.add(arg); addNext = true; } else if (addNext) { tcArgs.add(arg); addNext = false; } } CommandLineParser cmdLineParser = new PosixParser(); try { CommandLine cmdLine = cmdLineParser.parse(fOptions, tcArgs.toArray(new String[tcArgs.size()]), false); if (cmdLine != null) { fLineParser = new CliCommandLine(cmdLine); } } catch(ParseException e) { System.out.println(Messages.CliParser_ErrorParsingArguments); System.out.println(e); System.out.println(); printHelpText(); throw e; } }
Source:
<code>private static void enablePowerMockSupport() { HotSwapAgent.addTransformer(new BendJavassistToMyWillTransformer( <START> new Glob("javassist/*"), <END> JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistCoverageInterceptor.class))); }</code><technical_language>new Glob vs. toGlobPredicate() -- approach factory method constructor mix both. factory method. do think</technical_language>

Target:
private static void enablePowerMockSupport() { HotSwapAgent.addTransformer(new BendJavassistToMyWillTransformer( Glob.toGlobPredicate(Collections.singleton("javassist/*")), JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistCoverageInterceptor.class))); }
Source:
<code>public static Function<Object, DateTime> createObjectTimestampParser( final String format ) { final Function<String, DateTime> stringFun = createTimestampParser(format); final Function<Number, DateTime> numericFun = createNumericTimestampParser(format); return o -> { Preconditions.checkNotNull(o, "null timestamp"); <START> if (o instanceof Number && isNumericFormat(format)) { <END> return numericFun.apply((Number) o); } else { return stringFun.apply(o.toString()); } }; }</code><technical_language>isNumericFormat(format) need computed for object. compute this function is applied object (on line 125)</technical_language>

Target:
public static Function<Object, DateTime> createObjectTimestampParser( final String format ) { final Function<String, DateTime> stringFun = createTimestampParser(format); final Function<Number, DateTime> numericFun = createNumericTimestampParser(format); final boolean isNumericFormat = isNumericFormat(format); return o -> { Preconditions.checkNotNull(o, "null timestamp"); if (o instanceof Number && isNumericFormat) { return numericFun.apply((Number) o); } else { return stringFun.apply(o.toString()); } }; }
Source:
<code>public void canCreateBlob() throws Exception { final String content = "Content of the blob"; final String body = blob().toString(); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_CREATED, body) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_OK, body)).start(); final RtBlobs blobs = new RtBlobs( new ApacheRequest(container.home()), repo() ); final Blob blob = blobs.create(content, "utf-8"); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( new Blob.Smart(blob).url(), Matchers.equalTo("http://localhost/1") ); <START> container.stop(); <END> }</code><technical_language>please, stop container in finally block</technical_language>

Target:
public void canCreateBlob() throws Exception { final String content = "Content of the blob"; final String body = blob().toString(); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_CREATED, body) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_OK, body)).start(); final RtBlobs blobs = new RtBlobs( new ApacheRequest(container.home()), repo() ); try { final Blob blob = blobs.create(content, "utf-8"); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( new Blob.Smart(blob).url(), Matchers.equalTo("http://localhost/1") ); } finally { container.stop(); } }
Source:
<code>public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { if (!isItemValidForSlot(slot, stack)) { return stack; } ItemStack returnStack = ItemStack.EMPTY; if (stack.getCount() > getSlotLimit(slot)) { returnStack = stack.copy(); returnStack.setCount(stack.getCount() - getSlotLimit(slot)); <START> stack.setCount(getSlotLimit(slot)); <END> } if (!simulate) { setInventorySlotContents(slot, stack); } return returnStack; }</code><technical_language>ItemStack a nice splitStack method this in call. need check stacksize beforehand</technical_language>

Target:
public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { if (!isItemValidForSlot(slot, stack)) { return stack; } ItemStack slotStack = stack.splitStack(getSlotLimit(slot)); if (!simulate) { setInventorySlotContents(slot, slotStack); } return stack; }
Source:
<code>public ChartDataEntity getEntityById(Long entityId) throws EntityRetrievalException { ChartDataEntity entity = null; String queryStr = "from ChartDataEntity " + "where (chart_data_id = :entityid)"; Query query = entityManager.createQuery(queryStr, ChartDataEntity.class ); query.setParameter("entityid", entityId); List<ChartDataEntity> result = query.getResultList(); if (result.size() > 1){ <START> throw new EntityRetrievalException("Data error. Duplicate certificaiton body id in database."); <END> } else if(result.size() == 1) { entity = result.get(0); } return entity; }</code><technical_language>Typo certificaiton; certification</technical_language>

Target:
public ChartDataEntity getEntityById(Long entityId) throws EntityRetrievalException { ChartDataEntity entity = null; String queryStr = "from ChartDataEntity " + "where (chart_data_id = :entityid)"; Query query = entityManager.createQuery(queryStr, ChartDataEntity.class ); query.setParameter("entityid", entityId); List<ChartDataEntity> result = query.getResultList(); if (result.size() > 1){ throw new EntityRetrievalException("Data error. Duplicate certificaton body id in database."); } else if(result.size() == 1) { entity = result.get(0); } return entity; }
Source:
<code>private static <T> ColumnMapper<T> primitiveMapper(ColumnGetter<T> getter) { return (r, i, ctx) -> { T value = getter.get(r, i); if (r.wasNull() && !ctx.getConfig(ColumnMappers.class).getNullPrimitivesToDefaults()) { <START> throw new UnableToProduceResultException("a Java primitive value was attempted to be mapped from a database null value"); <END> } else { return value; } }; }</code><technical_language>If multiple primitives columns, users able column failed map this error message. provide more information column failed mapped. include column number (and column label result set metadata)? want include a suggestion in error message change mapped type a primitive a wrapper</technical_language>

Target:
private static <T> ColumnMapper<T> primitiveMapper(ColumnGetter<T> getter) { return (r, i, ctx) -> { T value = getter.get(r, i); if (r.wasNull() && !ctx.getConfig(ColumnMappers.class).getCoalesceNullPrimitivesToDefaults()) { String msg = String.format("Database null values are not allowed for Java primitives by the current configuration:" + " could not map column %s (%s)." + " Change your result type to a boxed primitive to resolve.", i, r.getMetaData().getColumnLabel(i)); throw new UnableToProduceResultException(msg); } else { return value; } }; }
Source:
<code>public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mContext = getActivity().getApplicationContext(); mDataBaseAdapter = new DataBaseAdapter(getActivity()); mDataBaseAdapter.createDatabase(); mDataBaseAdapter.open(); mItemAdapter = new ATMItemListAdapter(mContext, ((MainActivity) getActivity()).getLocationTracker()); setListAdapter(mItemAdapter); getLoaderManager().initLoader(0, null, this); <START> getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); <END> }</code><technical_language>set in xml</technical_language>

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mContext = getActivity().getApplicationContext(); mDataBaseAdapter = new DataBaseAdapter(getActivity()); mDataBaseAdapter.createDatabase(); mDataBaseAdapter.open(); mItemAdapter = new ATMItemListAdapter(mContext, ((MainActivity) getActivity()).getLocationTracker()); setListAdapter(mItemAdapter); getLoaderManager().initLoader(0, null, this); }
Source:
<code><START> public static String getCpu() { <END> return CPU.name().toLowerCase(LOCALE); }</code><technical_language>this is class is a shell delegates of operations a NativeImpl instance, a design include getCpu() in NativeImpl</technical_language>

Target:
public static String getCpu() { return CPU.toString(); }
Source:
<code>protected CLIReturnCode execute() throws Exception { boolean errorOccurred = false; final Set<String> hs = new HashSet<>(); hs.addAll(views); ViewOptionHandler voh = new ViewOptionHandler(null, null, null); for(String view_s : hs) { View view = null; try { view = voh.getView(view_s); if (view == null) { throw new IllegalArgumentException("View name is empty"); } view.checkPermission(View.DELETE); ViewGroup group = view.getOwner(); if (!group.canDelete(view)) { throw new IllegalStateException(String.format("%s does not allow to delete '%s' view", group.getDisplayName(), view.getViewName())); } group.deleteView(view); } catch (Exception e) { if(hs.size() == 1) { throw e; } stderr.println(view_s + ": " + e.getMessage()); errorOccurred = true; } } if (errorOccurred) { <START> throw new AbortException(CLI_LISTPARAM_SUMMARY_ERROR_TEXT); <END> } return CLIReturnCodeStandard.OK; }</code><technical_language>removing this</technical_language>

Target:
protected CLIReturnCode execute() throws Exception { boolean errorOccurred = false; final Set<String> hs = new HashSet<>(); hs.addAll(views); ViewOptionHandler voh = new ViewOptionHandler(null, null, null); for(String view_s : hs) { View view = null; try { view = voh.getView(view_s); if (view == null) { throw new IllegalArgumentException("View name is empty"); } view.checkPermission(View.DELETE); ViewGroup group = view.getOwner(); if (!group.canDelete(view)) { throw new IllegalStateException(String.format("%s does not allow to delete '%s' view", group.getDisplayName(), view.getViewName())); } group.deleteView(view); } catch (Exception e) { if(hs.size() == 1) { throw e; } stderr.println(view_s + ": " + e.getMessage()); errorOccurred = true; } } if (errorOccurred) { throw new AbortException(CLI_LISTPARAM_SUMMARY_ERROR_TEXT); } return StandardCLIReturnCode.OK; }
Source:
<code><START> private void initUnregisteredVM() { <END> VM vmFromConfiguration = null; OvfHelper ovfHelper = new OvfHelper(); ovfEntityData = getUnregisteredOVFDataDao().getByEntityIdAndStorageDomain(getParameters().getContainerId(), getParameters().getStorageDomainId()); if (ovfEntityData != null) { try { vmFromConfiguration = ovfHelper.readVmFromOvf(ovfEntityData.getOvfData()); } catch (OvfReaderException e) { log.errorFormat("failed to parse a given ovf configuration: \n" + ovfEntityData.getOvfData(), e); } vmFromConfiguration.setVdsGroupId(getParameters().getVdsGroupId()); getParameters().setVm(vmFromConfiguration); getParameters().setDestDomainId(ovfEntityData.getStorageDomainId()); getParameters().setSourceDomainId(ovfEntityData.getStorageDomainId()); } }</code><technical_language>add CDA check if init succeeded, if fails end null vm NPE</technical_language>

Target:
private void initUnregisteredVM() { VM vmFromConfiguration = null; OvfHelper ovfHelper = new OvfHelper(); ovfEntityData = getUnregisteredOVFDataDao().getByEntityIdAndStorageDomain(getParameters().getContainerId(), getParameters().getStorageDomainId()); if (ovfEntityData != null) { try { vmFromConfiguration = ovfHelper.readVmFromOvf(ovfEntityData.getOvfData()); vmFromConfiguration.setVdsGroupId(getParameters().getVdsGroupId()); getParameters().setVm(vmFromConfiguration); getParameters().setDestDomainId(ovfEntityData.getStorageDomainId()); getParameters().setSourceDomainId(ovfEntityData.getStorageDomainId()); } catch (OvfReaderException e) { log.errorFormat("failed to parse a given ovf configuration: \n" + ovfEntityData.getOvfData(), e); } } }
Source:
<code>public static IndexType fromValue(final Object value) { for (IndexType indexType : values()) { <START> if (indexType.type.equals(value) || indexType.name().equals(value)) { <END> return indexType; } } throw new IllegalArgumentException("No enum value found for " + value); }</code><technical_language>allow comparison name value. confusing</technical_language>

Target:
public static IndexType fromValue(final Object value) { for (IndexType indexType : values()) { if (indexType.type.equals(value)) { return indexType; } } throw new IllegalArgumentException("No enum value found for " + value); }
Source:
<code><START> public boolean logTransactionMergeFailure() { <END> return this.logTransactionMergeFailure; }</code><technical_language>this silencing X number of failed/merged transactions happens</technical_language>

Target:
public int logTransactionMergeFailure() { return this.logTransactionMergeFailure; }
Source:
<code>public void visitNode(Tree tree) { if (tree.is(Kind.SCRIPT)) { check(ControlFlowGraph.build((ScriptTree) tree)); <START> } else if (tree.is(Kind.METHOD, Kind.GENERATOR_METHOD)) { <END> MethodDeclarationTree methodTree = (MethodDeclarationTree) tree; check(ControlFlowGraph.build(methodTree.body())); } else { FunctionTree functionTree = (FunctionTree) tree; if (functionTree.body().is(Kind.BLOCK)) { check(ControlFlowGraph.build((BlockTree) functionTree.body())); } } }</code><technical_language>@pynicolas method trees extend FunctionTree</technical_language>

Target:
public void visitNode(Tree tree) { if (tree.is(Kind.SCRIPT)) { check(ControlFlowGraph.build((ScriptTree) tree)); } else { FunctionTree functionTree = (FunctionTree) tree; if (functionTree.body().is(Kind.BLOCK)) { check(ControlFlowGraph.build((BlockTree) functionTree.body())); } } }
Source:
<code>public User createAccount(String userName, String password) throws IOException { User user = User.getById(userName, true); <START> if (password.startsWith(JBCRYPT_HEADER)) { <END> user.addProperty(Details.fromHashedPassword(password)); } else { user.addProperty(Details.fromPlainPassword(password)); } return user; }</code><technical_language>so, changing expected behavior for some weird cases. I prefer a separate method createAccountWithHashedPassword if goal is for CasC. In current approach impacting users desires a real password starting #jbcrypt:. I understand impact is small behavior potentially malicious users achieve things</technical_language>

Target:
public User createAccount(String userName, String password) throws IOException { User user = User.getById(userName, true); user.addProperty(Details.fromPlainPassword(password)); return user; }
Source:
<code>public String toString() { <START> return singleBenchmarkResult.toString() + "_" + problemStatisticType.toString(); <END> }</code><technical_language>concatening strings +, needed do .toString(). This result: return singleBenchmarkResult + "_" + problemStatisticType; Furthermore, avoids a nullpointerexception if for example problemStatisticType is null (which is in this case)</technical_language>

Target:
public String toString() { return singleBenchmarkResult + "_" + problemStatisticType; }
Source:
<code>public SimpleDialogPanel() { infoIconStyle = RESOURCES.iconStyle(); infoIconStyle.ensureInjected(); setWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); infoAnchor.addStyleName(infoIconStyle.infoIconColor()); <START> addAttachHandler(event -> { <END> setDraggable(isAttached()); }); }</code><technical_language>beautiful</technical_language>

Target:
public SimpleDialogPanel() { infoIconStyle = RESOURCES.iconStyle(); infoIconStyle.ensureInjected(); setWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); infoAnchor.addStyleName(infoIconStyle.infoIconColor()); addAttachHandler(event -> setDraggable(isAttached())); }
Source:
<code>public int getColumnCount() { <START> return columnNames.size(); <END> }</code><technical_language>Another is more relevant backing data is results[resultsIndex].length</technical_language>

Target:
public int getColumnCount() { return results[0].length; }
Source:
<code>public String toString() { <START> return String.format("%s, deviceList=%s", super.toString(), getDeviceList()); <END> }</code><technical_language>Add force parameter toString()</technical_language>

Target:
public String toString() { return String.format("%s, deviceList=%s, force=%b", super.toString(), getDeviceList(), isForce()); }
Source:
<code><T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) { internalLockLeaseTime = unit.toMillis(leaseTime); return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command, "redis.call('hincrby', KEYS[1], ARGV[2], 1); " + "redis.call('pexpire', KEYS[1], ARGV[1]); " + "return redis.call('pttl', KEYS[1]);", <START> Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId)); <END> }</code><technical_language>@Aslan11 return statements missed</technical_language>

Target:
<T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) { internalLockLeaseTime = unit.toMillis(leaseTime); return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command, "redis.call('hincrby', KEYS[1], ARGV[2], 1); " + "redis.call('pexpire', KEYS[1], ARGV[1]); " + "return nil; " + "return redis.call('pttl', KEYS[1]);", Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId)); }
Source:
<code>public GremlinServer(final Settings settings) { this.settings = settings; <START> this.isLinuxOS = settings.useEpollEventLoop && SystemUtils.IS_OS_LINUX; <END> Runtime.getRuntime().addShutdownHook(new Thread(() -> this.stop().join(), SERVER_THREAD_PREFIX + "shutdown")); final ThreadFactory threadFactoryBoss = ThreadFactoryUtil.create("boss-%d"); if(isLinuxOS){ bossGroup = new EpollEventLoopGroup(settings.threadPoolBoss, threadFactoryBoss); } else { bossGroup = new NioEventLoopGroup(settings.threadPoolBoss, threadFactoryBoss); } final ThreadFactory threadFactoryWorker = ThreadFactoryUtil.create("worker-%d"); if(isLinuxOS) { workerGroup = new EpollEventLoopGroup(settings.threadPoolWorker, threadFactoryWorker); }else { workerGroup = new NioEventLoopGroup(settings.threadPoolWorker, threadFactoryWorker); } serverGremlinExecutor = new ServerGremlinExecutor<>(settings, null, workerGroup, EventLoopGroup.class); gremlinExecutorService = serverGremlinExecutor.getGremlinExecutorService(); }</code><technical_language>minor nit....can please rename isLinuxOS more fitting, epollEnabled</technical_language>

Target:
public GremlinServer(final Settings settings) { this.settings = settings; this.isEpollEnabled = settings.useEpollEventLoop && SystemUtils.IS_OS_LINUX; if(settings.useEpollEventLoop && !SystemUtils.IS_OS_LINUX){ logger.warn("cannot use epoll in non-linux env, falling back to NIO"); } Runtime.getRuntime().addShutdownHook(new Thread(() -> this.stop().join(), SERVER_THREAD_PREFIX + "shutdown")); final ThreadFactory threadFactoryBoss = ThreadFactoryUtil.create("boss-%d"); if(isEpollEnabled){ bossGroup = new EpollEventLoopGroup(settings.threadPoolBoss, threadFactoryBoss); } else { bossGroup = new NioEventLoopGroup(settings.threadPoolBoss, threadFactoryBoss); } final ThreadFactory threadFactoryWorker = ThreadFactoryUtil.create("worker-%d"); if(isEpollEnabled) { workerGroup = new EpollEventLoopGroup(settings.threadPoolWorker, threadFactoryWorker); }else { workerGroup = new NioEventLoopGroup(settings.threadPoolWorker, threadFactoryWorker); } serverGremlinExecutor = new ServerGremlinExecutor<>(settings, null, workerGroup, EventLoopGroup.class); gremlinExecutorService = serverGremlinExecutor.getGremlinExecutorService(); }
Source:
<code>void showTooltip (int x, int y) { <START> checkWidget (); <END> if (itemToolTip == null) return; itemToolTip.setLocation (x, y); itemToolTip.setVisible (true); }</code><technical_language>For non-public methods checkWidget() is required</technical_language>

Target:
void showTooltip (int x, int y) { if (itemToolTip == null) return; itemToolTip.setLocation (x, y); itemToolTip.setVisible (true); }
Source:
<code>public boolean submitOrderToServer(String orderInfo) { boolean result = true; String submitUrl = getRequestUrl(null, SUBMIT_PAGE); Bundle params = new Bundle(); <START> params.putString("orders", orderInfo); <END> String resultStr = reqHelper.doPost(submitUrl, params); if (resultStr == null || !resultStr.equals(STATUS_SUCCESS)) { result = false; } return result; }</code><technical_language>user OrderTable.TABLE_NAME instead of plain text. FORGET this, there, put constants reassemble work in next phase if a chance in future..</technical_language>

Target:
public static boolean submitOrderToServer(String orderInfo) { boolean result = true; String submitUrl = getRequestUrl(null, SUBMIT_PAGE); Bundle params = new Bundle(); params.putString("orders", orderInfo); String resultStr = RequestHelper.doRequestPost(submitUrl, params); if (resultStr == null || !resultStr.equals(STATUS_SUCCESS)) { result = false; } return result; }