auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ResponseEntity<Map<String, Object>> calculate( @PathVariable final String crop, @PathVariable final Integer studyId, @PathVariable final Integer datasetId, @RequestBody final CalculateVariableRequest request) { try { final Map<String, Object> result = this.derivedVariableService .execute(studyId, datasetId, request.getVariableId(), request.getGeoLocationIds(), request.isOverwriteExistingData()); return new ResponseEntity<>(result, HttpStatus.OK); <START> } catch (final ApiRequestValidationException e) { <END> final ErrorResponse errorResponse = new ErrorResponse(); final ObjectError objectError = e.getErrors().get(0); errorResponse.addError( resourceBundleMessageSource.getMessage(objectError.getCode(), objectError.getArguments(), LocaleContextHolder.getLocale())); return new ResponseEntity(errorResponse, HttpStatus.CONFLICT); } catch (final OverwriteDataException e2) { final Map<String, Object> result = new HashMap<>(); result.put(DerivedVariableServiceImpl.HAS_DATA_OVERWRITE_RESULT_KEY, true); return new ResponseEntity<>(result, HttpStatus.OK); } }</code><technical_language>need catch this one, bubble handled DefaultHandlerException OverwriteDataException is good this request</technical_language>

Target:
public ResponseEntity<Map<String, Object>> calculate( @PathVariable final String crop, @PathVariable final Integer studyId, @PathVariable final Integer datasetId, @RequestBody final CalculateVariableRequest request) { try { final Map<String, Object> result = this.derivedVariableService .execute(studyId, datasetId, request.getVariableId(), request.getGeoLocationIds(), request.isOverwriteExistingData()); return new ResponseEntity<>(result, HttpStatus.OK); } catch (final OverwriteDataException e2) { final Map<String, Object> result = new HashMap<>(); result.put(DerivedVariableServiceImpl.HAS_DATA_OVERWRITE_RESULT_KEY, true); return new ResponseEntity<>(result, HttpStatus.OK); } }
Source:
<code>ViewContext(int sortColunm, int sortDirection, ITimeGraphEntry selection, @NonNull Set<@NonNull ITimeGraphEntry> collapsedEntries) { fSortColumnIndex = sortColunm; fSortDirection = sortDirection; fSelection = selection; fCollapsedEntries = <START> collapsedEntries; <END> }</code><technical_language>this need immutable copy, potentially avoid race condition</technical_language>

Target:
ViewContext(int sortColunm, int sortDirection, ITimeGraphEntry selection, @NonNull Set<@NonNull ITimeGraphEntry> collapsedEntries) { fSortColumnIndex = sortColunm; fSortDirection = sortDirection; fSelection = selection; fCollapsedEntries = ImmutableSet.copyOf(collapsedEntries); }
Source:
<code>private void MoveVdssToGoingToMaintenanceMode() { List<VDS> spms = new ArrayList<>(); List<VDS> vdss = new ArrayList<>(vdssToMaintenance.size()); <START> vdss.addAll(vdssToMaintenance.values()); <END> for (VDS vds : vdss) { if (vds.getSpmStatus() != VdsSpmStatus.SPM) { setVdsStatusToPrepareForMaintenance(vds); } else { spms.add(vds); } } for (VDS vds : spms) { setVdsStatusToPrepareForMaintenance(vds); } cancelIncommingMigrations(); freeLock(); }</code><technical_language>in favor of iterator remove iteration..that's unneeded</technical_language>

Target:
private void MoveVdssToGoingToMaintenanceMode() { List<VDS> spms = new ArrayList<VDS>(); Iterator<VDS> it = vdssToMaintenance.values().iterator(); while (it.hasNext()) { VDS vds = it.next(); if (vds.getSpmStatus() != VdsSpmStatus.SPM) { if (!setVdsStatusToPrepareForMaintenance(vds)) { it.remove(); } } else { spms.add(vds); } } for (VDS vds : spms) { if (!setVdsStatusToPrepareForMaintenance(vds)) { vdssToMaintenance.remove(vds.getId()); } } cancelIncommingMigrations(); freeLock(); }
Source:
<code>static DashboardInfo parse(Project definingProject, String refName, String path, Config config, String project, Set<Project.DashboardType> setTypes) throws UnsupportedEncodingException { DashboardInfo info = new DashboardInfo(refName, path); info.project = project; info.definingProject = definingProject.getName(); info.title = config.getString("dashboard", null, "title"); info.description = config.getString("dashboard", null, "description"); info.foreach = config.getString("dashboard", null, "foreach"); String id = refName + ":" + path; for (Project.DashboardType type : types(definingProject, id)) { if (setTypes.contains(type)) { info.types.add(type); } } UrlEncoded u = new UrlEncoded("/dashboard/"); <START> u.put("title", Objects.firstNonNull(info.title, info.path) <END> if (info.foreach != null) { u.put("foreach", replace(project, info.foreach)); } for (String name : config.getSubsections("section")) { Section s = new Section(); s.name = name; s.query = config.getString("section", name, "query"); u.put(s.name, replace(project, s.query)); info.sections.add(s); } info.parameters = u.getParameters().replace("%3A", ":"); info.url = u.toString().replace("%3A", ":"); return info; }</code><technical_language>Missing ');' end of line, removed accidentally</technical_language>

Target:
static DashboardInfo parse(Project definingProject, String refName, String path, Config config, String project, Set<Project.DashboardType> setTypes) throws UnsupportedEncodingException { DashboardInfo info = new DashboardInfo(refName, path); info.project = project; info.definingProject = definingProject.getName(); info.title = config.getString("dashboard", null, "title"); info.description = config.getString("dashboard", null, "description"); info.foreach = config.getString("dashboard", null, "foreach"); String id = refName + ":" + path; for (Project.DashboardType type : types(definingProject, id)) { if (setTypes.contains(type)) { info.types.add(type); } } UrlEncoded u = new UrlEncoded("/dashboard/"); u.put("title", Objects.firstNonNull(info.title, info.path)); if (info.foreach != null) { u.put("foreach", replace(project, info.foreach)); } for (String name : config.getSubsections("section")) { Section s = new Section(); s.name = name; s.query = config.getString("section", name, "query"); u.put(s.name, replace(project, s.query)); info.sections.add(s); } info.parameters = u.getParameters().replace("%3A", ":"); info.url = u.toString().replace("%3A", ":"); return info; }
Source:
<code>private ArrayList<Map<ActionParameter, String>> getMappedParamToValue(List<Map<String, String>> mappedParamToValue) { <START> ArrayList<Map<ActionParameter, String>> newMappedParamToValue = new ArrayList<Map<ActionParameter, String>>(); for (Map<String, String> map : mappedParamToValue) { Map<ActionParameter, String> tempMap = new HashMap<ActionParameter, String>(); for (Map.Entry<String, String> entry : map.entrySet()) { tempMap.put(new ActionParameter(entry.getKey()), entry.getValue()); } newMappedParamToValue.add(tempMap); } return newMappedParamToValue; <END> }</code><technical_language>a more succinct of this streams</technical_language>

Target:
private List<Map<ActionParameter, String>> getMappedParamToValue(List<Map<String, String>> mappedParamToValue) { return mappedParamToValue.stream().map(m -> m.entrySet().stream().collect(Collectors.toMap(p -> new ActionParameter(p.getKey()), p-> p.getValue()))).collect(Collectors.toList()); }
Source:
<code>private void addMediaToUploadService(@NonNull MediaModel media) { if (!NetworkUtils.isNetworkAvailable(this)) { AppLog.v(AppLog.T.MEDIA, "Unable to start UploadService, internet connection required."); <START> ToastUtils.showToast(this, R.string.no_network_message, ToastUtils.Duration.SHORT); <END> } ArrayList<MediaModel> mediaList = new ArrayList<>(); mediaList.add(media); UploadService.uploadMedia(this, mediaList); }</code><technical_language>dropping return intentional</technical_language>

Target:
private void addMediaToUploadService(@NonNull MediaModel media) { if (!NetworkUtils.isNetworkAvailable(this)) { AppLog.v(AppLog.T.MEDIA, "Unable to start UploadService, internet connection required."); ToastUtils.showToast(this, R.string.no_network_message, ToastUtils.Duration.SHORT); return; } ArrayList<MediaModel> mediaList = new ArrayList<>(); mediaList.add(media); UploadService.uploadMedia(this, mediaList); }
Source:
<code>Map<String, Serializable> getMetadata() throws RepositoryException { if ( metadata == null ) { this.executeOperation( new SessionOperation() { @Override public void execute( Session session ) { try { metadata = JcrRepositoryFileUtils.getFileMetadata( session, getId() ); } catch ( InvalidItemStateException | ItemNotFoundException | PathNotFoundException e ) { <START> getLogger().warn( "InvalidItemStateException. Probable cause: File does not exist anymore" ); <END> } catch ( RepositoryException e ) { getLogger().error( "RepositoryException was found: ", e ); } } } ); } return metadata; }</code><technical_language>catching InvalidItemStateException simply returning false in places, this is tripped. more sense continue throw exception above, catch this log warning</technical_language>

Target:
Map<String, Serializable> getMetadata() throws RepositoryException { if ( metadata == null ) { this.executeOperation( new SessionOperation() { @Override public void execute( Session session ) { try { metadata = JcrRepositoryFileUtils.getFileMetadata( session, getId() ); } catch ( InvalidItemStateException | ItemNotFoundException | PathNotFoundException e ) { getLogger().warn( "InvalidItemStateException in getMetadata. Probable cause: File does not exist anymore" ); } catch ( RepositoryException e ) { getLogger().error( "RepositoryException was found: ", e ); } } } ); } return metadata; }
Source:
<code>public FileSplit[] getSplits(JobConf job, int numSplits) throws IOException { Settings settings = HadoopSettingsManager.loadFrom(job); Log log = LogFactory.getLog(getClass()); InitializationUtils.setValueReaderIfNotSet(settings, HiveValueReader.class, log); if (settings.getOutputAsJson() == false) { settings.setProperty(InternalConfigurationOptions.INTERNAL_ES_TARGET_FIELDS, StringUtils.concatenate(HiveUtils.columnToAlias(settings), ",")); } settings.setResourceRead(settings.getResourceRead()); HiveUtils.init(settings, log); String filterObjectStr = job.get(TableScanDesc.FILTER_OBJECT_CONF_STR); if (filterObjectStr != null && filterObjectStr.length() > 0) { String esQuery = Utilities.deserializeObject(filterObjectStr, String.class); if (esQuery != null && esQuery.length() > 0) { log.info("[EsHiveInputFormat][Pushdown][Es.query] : " + esQuery); <START> settings.setQuery(esQuery); <END> } } InputSplit[] shardSplits = super.getSplits(job, numSplits); FileSplit[] wrappers = new FileSplit[shardSplits.length]; Path path = new Path(job.get(HiveConstants.TABLE_LOCATION)); for (int i = 0; i < wrappers.length; i++) { wrappers[i] = new EsHiveSplit(shardSplits[i], path); } return wrappers; }</code><technical_language>setQuery call is setting a in es.query property is users add a master query limit data queried table instance. Generally this overwritten in connector code a retrieve setting user. For pushdown, this setting property InternalConfigurationOptions.INTERNAL_ES_QUERY_FILTERS. This property is read combined es.query property search time. Additionally, for setting is expected a Base64 String, IOUtils.serializeToBase64(esQuery) setting settings</technical_language>

Target:
public FileSplit[] getSplits(JobConf job, int numSplits) throws IOException { Settings settings = HadoopSettingsManager.loadFrom(job); Log log = LogFactory.getLog(getClass()); InitializationUtils.setValueReaderIfNotSet(settings, HiveValueReader.class, log); InitializationUtils.setUserProviderIfNotSet(settings, HadoopUserProvider.class, log); if (settings.getOutputAsJson() == false) { settings.setProperty(InternalConfigurationOptions.INTERNAL_ES_TARGET_FIELDS, StringUtils.concatenate(HiveUtils.columnToAlias(settings), ",")); } HiveUtils.init(settings, log); String filterObjectStr = job.get(TableScanDesc.FILTER_OBJECT_CONF_STR); if (filterObjectStr != null && filterObjectStr.length() > 0) { String filters = Utilities.deserializeObject(filterObjectStr, String.class); if (filters != null && filters.length() > 0) { log.info(String.format("[EsHiveInputFormat][Pushdown][Filters] %s", filters)); SettingsUtils.setFilters(settings, filters); } } InputSplit[] shardSplits = super.getSplits(job, numSplits); FileSplit[] wrappers = new FileSplit[shardSplits.length]; Path path = new Path(job.get(HiveConstants.TABLE_LOCATION)); for (int i = 0; i < wrappers.length; i++) { wrappers[i] = new EsHiveSplit(shardSplits[i], path); } return wrappers; }
Source:
<code>private List<VoldemortService> createServices() { List<VoldemortService> services = new ArrayList<VoldemortService>(); CoordinatorProxyService coordinator = new CoordinatorProxyService(config, storeClientConfigs); <START> services.add(coordinator); <END> if(config.isAdminServiceEnabled()) { services.add(new CoordinatorAdminService(config, storeClientConfigs)); } return ImmutableList.copyOf(services); }</code><technical_language>this work : services.add(new CoordinatorProxyService(config, storeClientConfigs)); save a line declaring a coordinator object</technical_language>

Target:
private List<VoldemortService> createServices() { List<VoldemortService> services = new ArrayList<VoldemortService>(); services.add(new CoordinatorProxyService(config, storeClientConfigs)); if(config.isAdminServiceEnabled()) { services.add(new CoordinatorAdminService(config, storeClientConfigs)); } return ImmutableList.copyOf(services); }
Source:
<code>public PatientData<Object> load(Patient patient) { try { XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument()); BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE); if (data == null) { throw new NullPointerException("The patient does not have a PatientClass"); } Map<String, Object> result = new LinkedHashMap<String, Object>(); ListProperty allergiesListProperty = (ListProperty) data.get(ALLERGIES); List<String> allergiesList = allergiesListProperty.getList(); result.put(ALLERGIES, allergiesList); IntegerProperty nkdaProperty = (IntegerProperty) data.get(NKDA); Integer nkdaInteger = (Integer) nkdaProperty.getValue(); <START> Boolean nkda = Boolean.TRUE; <END> if (nkdaInteger != 1) { nkda = Boolean.FALSE; } result.put(NKDA, nkda); return new DictionaryPatientData<>(getName(), result); } catch (Exception e) { this.logger.error( "Could not find requested document or some unforeseen error has occurred during controller loading"); } return null; }</code><technical_language>do java Boolean nkda = nkdaInteger == 1;</technical_language>

Target:
public PatientData<Object> load(Patient patient) { try { XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument()); BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE); if (data == null) { throw new NullPointerException("The patient does not have a PatientClass"); } Map<String, Object> result = new LinkedHashMap<String, Object>(); ListProperty allergiesListProperty = (ListProperty) data.get(ALLERGIES); List<String> allergiesList = allergiesListProperty.getList(); result.put(ALLERGIES, allergiesList); IntegerProperty nkdaProperty = (IntegerProperty) data.get(NKDA); Integer nkdaInteger = (Integer) nkdaProperty.getValue(); boolean nkda = nkdaInteger == 1; result.put(NKDA, nkda); return new DictionaryPatientData<>(getName(), result); } catch (Exception e) { this.logger.error( "Could not find requested document or some unforeseen error has occurred during controller loading.", e); } return null; }
Source:
<code><START> public String doPost(String api, HashMap<String, String> mapHeaders, String body, HashMap<String, String> queries) { <END> try { HttpHeaders headers = new HttpHeaders(); for (String i : mapHeaders.keySet()) { headers.add(i, mapHeaders.get(i).toString()); } HttpEntity<String> request; if (body != null) { request = new HttpEntity<>(body, headers); } else { request = new HttpEntity<String>(headers); } RestTemplate rest = new RestTemplate(); ResponseEntity<String> response; if (queries != null) { response = rest.postForEntity(api, request, String.class, queries); } else { response = rest.postForEntity(api, request, String.class); } return response.getBody(); } catch (Exception e) { logger.error("Error sending request : ", e); return null; } }</code><technical_language>this method need in interface anymore calling this this class. this method private</technical_language>

Target:
private String doPost(String api, HashMap<String, String> mapHeaders, String body, HashMap<String, String> queries) { try { HttpHeaders headers = new HttpHeaders(); for (String i : mapHeaders.keySet()) { headers.add(i, mapHeaders.get(i).toString()); } HttpEntity<String> request; if (body != null) { request = new HttpEntity<>(body, headers); } else { request = new HttpEntity<String>(headers); } RestTemplate rest = new RestTemplate(); ResponseEntity<String> response; if (queries != null) { response = rest.postForEntity(api, request, String.class, queries); } else { response = rest.postForEntity(api, request, String.class); } return response.getBody(); } catch (Exception e) { logger.error("Error sending request : ", e); return null; } }
Source:
<code>private <K, V> RemoteCache<K, V> createRemoteCache(String cacheName, Boolean forceReturnValueOverride) { synchronized (cacheName2RemoteCache) { RemoteCacheKey key = new RemoteCacheKey(cacheName, forceReturnValueOverride); if (!cacheName2RemoteCache.containsKey(key)) { RemoteCacheImpl<K, V> result = createRemoteCache(cacheName); RemoteCacheHolder rcc = new RemoteCacheHolder(result, forceReturnValueOverride == null ? configuration.forceReturnValues() : forceReturnValueOverride); startRemoteCache(rcc); if (configuration.pingOnStartup()) { if (!cacheName.equals(RemoteCacheManager.DEFAULT_CACHE_NAME) && ping(result) == PingResult.CACHE_DOES_NOT_EXIST) { return null; } } <START> result.resolveCompatibility(); <END> result.start(); cacheName2RemoteCache.put(key, rcc); return result; } else { return (RemoteCache<K, V>) cacheName2RemoteCache.get(key).remoteCache; } } }</code><technical_language>resolveCompatibility() pings, this pingOnStartup() essentially redundant</technical_language>

Target:
private <K, V> RemoteCache<K, V> createRemoteCache(String cacheName, Boolean forceReturnValueOverride) { synchronized (cacheName2RemoteCache) { RemoteCacheKey key = new RemoteCacheKey(cacheName, forceReturnValueOverride); if (!cacheName2RemoteCache.containsKey(key)) { RemoteCacheImpl<K, V> result = createRemoteCache(cacheName); RemoteCacheHolder rcc = new RemoteCacheHolder(result, forceReturnValueOverride == null ? configuration.forceReturnValues() : forceReturnValueOverride); startRemoteCache(rcc); PingResult pingResult = result.resolveCompatibility(); if (!cacheName.equals(RemoteCacheManager.DEFAULT_CACHE_NAME) && pingResult == PingResult.CACHE_DOES_NOT_EXIST) { return null; } result.start(); cacheName2RemoteCache.put(key, rcc); return result; } else { return (RemoteCache<K, V>) cacheName2RemoteCache.get(key).remoteCache; } } }
Source:
<code><START> private boolean isAllGroupImplicit(XWikiContext context) <END> { return context.getWiki().isAllGroupImplicit(); }</code><technical_language>change visibility. XWikiGroupServiceImpl is a public class do is removing a method API. If build -Pquality get error</technical_language>

Target:
protected boolean isAllGroupImplicit(XWikiContext context) { return context.getWiki().isAllGroupImplicit(); }
Source:
<code>private <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { if (dao instanceof AbstractJpaDao) { try { AbstractJpaDao abstractJpaDao = (AbstractJpaDao) createAndInjectMembers(dao); return (T) abstractJpaDao; } catch (Exception e) { <START> log.error("Can't initialize an AbstractJpaDao for entity " + daoType, e); <END> } } else { return (T) dao; } } } log.error("Can't find dao for " + daoType); return null; }</code><technical_language>log.error("Can't initialize AbstractJpaDao for entity {}", daoType, e);</technical_language>

Target:
private <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { if (dao instanceof AbstractJpaDao) { try { AbstractJpaDao abstractJpaDao = (AbstractJpaDao) createAndInjectMembers(dao); return (T) abstractJpaDao; } catch (Exception e) { log.error("Can't initialize an AbstractJpaDao for entity {}: ", daoType, e.getMessage()); log.debug("Exception: ", e); } } else { return (T) dao; } } } log.error("Can't find dao for " + daoType); return null; }
Source:
<code>protected void executeQueryCommand() { <START> Provider provider = getDbFacade().getProviderDao().get(getParameters().getId()); <END> NetworkProviderProxy client = getProviderProxyFactory().create(provider); getQueryReturnValue().setReturnValue(client.getAll()); }</code><technical_language>provider validated for existence prior accessing it</technical_language>

Target:
protected void executeQueryCommand() { Provider<?> provider = getDbFacade().getProviderDao().get(getParameters().getId()); NetworkProviderProxy client = getProviderProxyFactory().create(provider); getQueryReturnValue().setReturnValue(client.getAll()); }
Source:
<code><START> public static GranularityType fromPeriod(Period period) <END> { int[] vals = period.getValues(); BitSet bs = new BitSet(); for (int i = 0; i < vals.length; i++) { if (vals[i] != 0) { bs.set(i); } } if (bs.cardinality() == 0 || bs.cardinality() > 1) { throw new IAE("Granularity is not supported. [%s]", period); } else { final int index = bs.nextSetBit(0); if (index == 0) { return GranularityType.YEAR; } if (index == 1) { if (vals[index] == 4) { return GranularityType.QUARTER; } else if (vals[index] == 1) { return GranularityType.MONTH; } } if (index == 2) { return GranularityType.WEEK; } if (index == 3) { return GranularityType.DAY; } if (index == 4) { if (vals[index] == 6) { return GranularityType.SIX_HOUR; } else if (vals[index] == 1) { return GranularityType.HOUR; } } if (index == 5) { if (vals[index] == 30) { return GranularityType.THIRTY_MINUTE; } else if (vals[index] == 15) { return GranularityType.FIFTEEN_MINUTE; } else if (vals[index] == 10) { return GranularityType.TEN_MINUTE; } else if (vals[index] == 5) { return GranularityType.FIVE_MINUTE; } else if (vals[index] == 1) { return GranularityType.MINUTE; } } if (index == 6) { return GranularityType.SECOND; } } throw new IAE("Granularity is not supported. [%s]", period); }</code><technical_language>is this called? wondering if throwing of IAE if work is surprise call sites instead of returning null able find one</technical_language>

Target:
public static GranularityType fromPeriod(Period period) { int[] vals = period.getValues(); int index = -1; for (int i = 0; i < vals.length; i++) { if (vals[i] != 0) { if (index < 0) { index = i; } else { throw new IAE("Granularity is not supported. [%s]", period); } } } switch (index) { case 0: return GranularityType.YEAR; case 1: if (vals[index] == 4) { return GranularityType.QUARTER; } else if (vals[index] == 1) { return GranularityType.MONTH; } break; case 2: return GranularityType.WEEK; case 3: return GranularityType.DAY; case 4: if (vals[index] == 6) { return GranularityType.SIX_HOUR; } else if (vals[index] == 1) { return GranularityType.HOUR; } break; case 5: if (vals[index] == 30) { return GranularityType.THIRTY_MINUTE; } else if (vals[index] == 15) { return GranularityType.FIFTEEN_MINUTE; } else if (vals[index] == 10) { return GranularityType.TEN_MINUTE; } else if (vals[index] == 5) { return GranularityType.FIVE_MINUTE; } else if (vals[index] == 1) { return GranularityType.MINUTE; } break; case 6: return GranularityType.SECOND; default: break; } throw new IAE("Granularity is not supported. [%s]", period); }
Source:
<code>private static String getISO8601FormattedLastSyncTime() { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(TimeZone.getTimeZone("UTC")); <START> return df.format(SyncDetailCalculations.getLastSyncTime()); <END> }</code><technical_language>is getLastSyncTime() guaranteed return non-null</technical_language>

Target:
private static String getISO8601FormattedLastSyncTime() { long lastSyncTime = SyncDetailCalculations.getLastSyncTime(); if (lastSyncTime == 0) { return ""; } else { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(TimeZone.getTimeZone("UTC")); return df.format(lastSyncTime); } }
Source:
<code>public void sendEvent(InputEvent event) throws JadbException { try (InputStream is = device.executeShell("input", event.buildArgs())) { Stream.flushRead(is); } catch (IOException e) { <START> throw new JadbException(e.getMessage()); <END> } }</code><technical_language>important exception lost, please pass e JadbException constructor</technical_language>

Target:
public void sendEvent(InputEvent event) throws JadbException { try (InputStream is = device.executeShell("input", event.buildArgs())) { Stream.flushRead(is); } catch (IOException e) { throw new JadbException(e); } }
Source:
<code><START> private List<String> splitArguments() { <END> final int argLength = arguments.length(); sb = new StringBuffer(argLength); boolean insideQuotas = false; for (int i = 0; i < argLength; i++) { char ch = arguments.charAt(i); if (ch == '"' || ch == '\'') { insideQuotas = !insideQuotas; } if (ch == argumentDelimiter && !insideQuotas) { pushArg(); i++; } sb.append(ch); } pushArg(); return argList; }</code><technical_language>This method improved in ways: - StringBuilder is preffered a StringBuffer - need create a private attribute for StringBuffer - appending element arguments list discarded (you reinstantiating time pushArg is called. - method is confusing. I refactor it, afraid do some tests</technical_language>

Target:
private List<String> splitArguments() { final int argLength = arguments.length(); StringBuilder sb = new StringBuilder(argLength); boolean insideQuotas = false; int bracesBlock = 0; for (int i = 0; i < argLength; i++) { char ch = arguments.charAt(i); if (ch == '"' || ch == '\'') { insideQuotas = !insideQuotas; } else if (ch == '(') { bracesBlock++; } else if (ch == ')') { bracesBlock--; } else if (ch == argumentDelimiter && !insideQuotas && bracesBlock == 0) { pushArg(sb); sb = new StringBuilder(argLength); } sb.append(ch); } pushArg(sb); return argList; }
Source:
<code>public boolean isRecipientOptionDisplayed(FeedbackParticipantType recipientType, int questionNumber) { WebElement recipientOption = browser.driver.findElement( By.cssSelector("#recipienttype-" + questionNumber + " option[value='" + recipientType + "']")); <START> return "block".equals(recipientOption.getCssValue("display")); <END> }</code><technical_language>Displayed elements display values of block, flex, inline, etc. (although case here), check for displayed !"none".equals(...) instead</technical_language>

Target:
public boolean isRecipientOptionDisplayed(FeedbackParticipantType recipientType, int questionNumber) { WebElement recipientOption = browser.driver.findElement( By.cssSelector("#recipienttype-" + questionNumber + " option[value='" + recipientType + "']")); return !"none".equals(recipientOption.getCssValue("display")); }
Source:
<code>public InMemoryCircuitBreakerRegistry() { this.defaultCircuitBreakerConfig = CircuitBreakerConfig.ofDefaults(); this.circuitBreakers = new ConcurrentHashMap<>(); <START> this.postCreationConsumers = new ArrayList<>(); <END> }</code><technical_language>ArrayList is thread safe. a CopyOnWriteArrayList</technical_language>

Target:
public InMemoryCircuitBreakerRegistry() { this(CircuitBreakerConfig.ofDefaults()); }
Source:
<code>public Choice getLL1EBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) { int ebnf = 0; if ( ebnfRoot!=null ) ebnf = ebnfRoot.getType(); Choice c = null; switch ( ebnf ) { case ANTLRParser.OPTIONAL : if ( alts.size()==1 ) c = new LL1OptionalBlockSingleAlt(this, ebnfRoot, alts); else c = new LL1OptionalBlock(this, ebnfRoot, alts); break; case ANTLRParser.CLOSURE : <START> c = new LL1StarBlockSingleAlt(this, ebnfRoot, alts); <END> break; case ANTLRParser.POSITIVE_CLOSURE : c = new LL1PlusBlockSingleAlt(this, ebnfRoot, alts); break; } return c; }</code><technical_language>If LL1StarBlock is removed, this changed ensure code remains correct in future. Constructs do implement specific code for LL1 case fall adaptivePredict, is perfectly acceptable (and preferred -force-atn is command line). java if ( alts.size()==1 ) c = new LL1StarBlockSingleAlt(this, ebnfRoot, alts); else c = getComplexEBNFBlock(ebnfRoot, alts);</technical_language>

Target:
public Choice getLL1EBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) { int ebnf = 0; if ( ebnfRoot!=null ) ebnf = ebnfRoot.getType(); Choice c = null; switch ( ebnf ) { case ANTLRParser.OPTIONAL : if ( alts.size()==1 ) c = new LL1OptionalBlockSingleAlt(this, ebnfRoot, alts); else c = new LL1OptionalBlock(this, ebnfRoot, alts); break; case ANTLRParser.CLOSURE : if ( alts.size()==1 ) c = new LL1StarBlockSingleAlt(this, ebnfRoot, alts); else c = getComplexEBNFBlock(ebnfRoot, alts); break; case ANTLRParser.POSITIVE_CLOSURE : if ( alts.size()==1 ) c = new LL1PlusBlockSingleAlt(this, ebnfRoot, alts); else c = getComplexEBNFBlock(ebnfRoot, alts); break; } return c; }
Source:
<code>protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (Object value : values) { <START> if (value instanceof EObject) { <END> IMergeViewerItem valueToAdd = createMergeViewerItemFrom((EObject)value); if (valueToAdd != null) { ret.add(valueToAdd); } } } return ret; }</code><technical_language>I suspect bug is point, please investigate more</technical_language>

Target:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (Object value : values) { IMergeViewerItem valueToAdd = createMergeViewerItemFrom((EObject)value); if (valueToAdd != null) { ret.add(valueToAdd); } } return ret; }
Source:
<code>public SingleDimensionPartitionsSpec( @JsonProperty(DimensionBasedPartitionsSpec.TARGET_ROWS_PER_SEGMENT) @Nullable Integer targetRowsPerSegment, @JsonProperty(PartitionsSpec.MAX_ROWS_PER_SEGMENT) @Nullable Integer maxRowsPerSegment, @JsonProperty("partitionDimension") @Nullable String partitionDimension, @JsonProperty("assumeGrouped") boolean assumeGrouped, @Deprecated @JsonProperty(DimensionBasedPartitionsSpec.TARGET_PARTITION_SIZE) @Nullable Integer targetPartitionSize, @Deprecated @JsonProperty(MAX_PARTITION_SIZE) @Nullable Integer maxPartitionSize ) { Property<Integer> target = checkAtMostOneNotNull( TARGET_ROWS_PER_SEGMENT, targetRowsPerSegment, TARGET_PARTITION_SIZE, targetPartitionSize ); Property<Integer> max = checkAtMostOneNotNull( MAX_ROWS_PER_SEGMENT, maxRowsPerSegment, MAX_PARTITION_SIZE, maxPartitionSize ); Preconditions.checkArgument( (target.value == null) != (max.value == null), <START> "Exactly one of " + target.name + " or " + max.name + " must be present" <END> ); this.partitionDimension = partitionDimension; this.assumeGrouped = assumeGrouped; this.targetRowsPerSegment = target.value; this.maxRowsPerSegment = max.value; this.resolvedMaxRowPerSegment = resolveMaxRowsPerSegment(target, max); }</code><technical_language>StringUtils here, StringUtils.format("Exactly of %s %s present", target.name, max.name)</technical_language>

Target:
public SingleDimensionPartitionsSpec( @JsonProperty(DimensionBasedPartitionsSpec.TARGET_ROWS_PER_SEGMENT) @Nullable Integer targetRowsPerSegment, @JsonProperty(PartitionsSpec.MAX_ROWS_PER_SEGMENT) @Nullable Integer maxRowsPerSegment, @JsonProperty("partitionDimension") @Nullable String partitionDimension, @JsonProperty("assumeGrouped") boolean assumeGrouped, @Deprecated @JsonProperty(DimensionBasedPartitionsSpec.TARGET_PARTITION_SIZE) @Nullable Integer targetPartitionSize, @Deprecated @JsonProperty(MAX_PARTITION_SIZE) @Nullable Integer maxPartitionSize ) { Property<Integer> target = Checks.checkAtMostOneNotNull( DimensionBasedPartitionsSpec.TARGET_ROWS_PER_SEGMENT, targetRowsPerSegment, DimensionBasedPartitionsSpec.TARGET_PARTITION_SIZE, targetPartitionSize ); Property<Integer> max = Checks.checkAtMostOneNotNull( PartitionsSpec.MAX_ROWS_PER_SEGMENT, maxRowsPerSegment, MAX_PARTITION_SIZE, maxPartitionSize ); Preconditions.checkArgument( (target.getValue() == null) != (max.getValue() == null), "Exactly one of " + target.getName() + " or " + max.getName() + " must be present" ); this.partitionDimension = partitionDimension; this.assumeGrouped = assumeGrouped; this.targetRowsPerSegment = target.getValue(); this.maxRowsPerSegment = max.getValue(); this.resolvedMaxRowPerSegment = resolveMaxRowsPerSegment(target, max); }
Source:
<code>public URL getResource(String name) { try { return new URL("jar", "", name); } catch(MalformedURLException e) { <START> e.printStackTrace(); <END> fail("Could not even create disfunct library URL."); return null; } }</code><technical_language>I need print stack trace here. wind polluting test output</technical_language>

Target:
public URL getResource(String name) { try { return new URL("jar", "", name); } catch(MalformedURLException e) { fail("Could not even create disfunct library URL: " + e.getMessage()); return null; } }
Source:
<code>public void testBindFilteredEventsToMethod() { final MultipleEventSource src = new MultipleEventSource(); final EventCounter counter = new EventCounter(); EventUtils.bindEventsToMethod(counter, "eventOccurred", src, MultipleEventListener.class, "event1"); assertEquals(0, counter.getCount()); <START> src.listeners.fire().event1(new PropertyChangeEvent(new Date(), "Day", 0, 1)); <END> assertEquals(1, counter.getCount()); src.listeners.fire().event2(new PropertyChangeEvent(new Date(), "Day", 1, 2)); assertEquals(1, counter.getCount()); }</code><technical_language>prefer explicit boxing of primitve values</technical_language>

Target:
public void testBindFilteredEventsToMethod() { final MultipleEventSource src = new MultipleEventSource(); final EventCounter counter = new EventCounter(); EventUtils.bindEventsToMethod(counter, "eventOccurred", src, MultipleEventListener.class, "event1"); assertEquals(0, counter.getCount()); src.listeners.fire().event1(new PropertyChangeEvent(new Date(), "Day", Integer.valueOf(0), Integer.valueOf(1))); assertEquals(1, counter.getCount()); src.listeners.fire().event2(new PropertyChangeEvent(new Date(), "Day", Integer.valueOf(1), Integer.valueOf(2))); assertEquals(1, counter.getCount()); }
Source:
<code>public void push(RowMap r) throws Exception { String key = r.pkToJson(keyFormat); String value = r.toJSON(); ProducerRecord<String, String> record = new ProducerRecord<>(topic, this.partitioner.kafkaPartition(r, this.numPartitions), key, value); if ( r.isTXCommit() ) inflightMessages.addMessage(r.getPosition()); KafkaCallback callback; if ( KafkaCallback.LOGGER.isDebugEnabled() ) callback = new KafkaCallback(inflightMessages, r.getPosition(), r.isTXCommit(), this.context, key, value); else <START> callback = new KafkaCallback(inflightMessages, r.getPosition(), r.isTXCommit(), this.context, null, null); <END> kafka.send(record, callback); }</code><technical_language>key is for error logging</technical_language>

Target:
public void push(RowMap r) throws Exception { String key = r.pkToJson(keyFormat); String value = r.toJSON(); ProducerRecord<String, String> record = new ProducerRecord<>(topic, this.partitioner.kafkaPartition(r, this.numPartitions), key, value); if ( r.isTXCommit() ) inflightMessages.addMessage(r.getPosition()); if ( !KafkaCallback.LOGGER.isDebugEnabled() ) value = null; KafkaCallback callback = new KafkaCallback(inflightMessages, r.getPosition(), r.isTXCommit(), this.context, key, value); kafka.send(record, callback); }
Source:
<code>private void onSendCallback(DatastreamRecordMetadata metadata, Exception exception, SendCallback sendCallback, DatastreamTask task, DatastreamProducerRecord record) { SendFailedException sendFailedException = null; if (exception != null) { sendFailedException = new SendFailedException(_safeCheckpoints); if (_onUnrecoverableError != null) { _onUnrecoverableError.accept(this); } } else { for (Pair<byte[], byte[]> event : record.getEvents()) { try { <START> DatastreamEvent datastreamEvent = AvroUtils.decodeAvroSpecificRecord(DatastreamEvent.class, event.getValue()); <END> DatastreamUtils.processEventMetadata(datastreamEvent); Optional<Long> eventLatency = Optional.ofNullable(datastreamEvent.metadata.get(DatastreamEventMetadata.EVENT_TIMESTAMP)) .map(metaVal -> metaVal.toString()) .map(eventTimestamp -> System.currentTimeMillis() - Long.valueOf(eventTimestamp)); eventLatency.ifPresent(latency -> { if (latency <= _availabilityThresholdSlaMs) { EVENTS_PRODUCED_WITHIN_SLA.inc(); } TOTAL_EVENTS_PRODUCED.inc(); }); } catch (IOException e) { _logger.warn("Unable to decode DatastreamEvent " + event.getValue(), e); } } try { _checkpointRWLock.readLock().lock(); if (!_safeCheckpoints.containsKey(task)) { _logger.warn(String.format("Event of unknown task is being acknowledged: task=%s, record=%s", task, record)); } else { _safeCheckpoints.get(task).put(metadata.getPartition(), record.getCheckpoint()); _pendingCheckpoints.set(true); } } finally { _checkpointRWLock.readLock().unlock(); } } if (sendCallback != null) { sendCallback.onCompletion(metadata, sendFailedException); } if (exception != null) { shutdown(); } }</code><technical_language>I concerned overhead of this operation this is called for single event. capacity issues callback mechanism added. option I of is add a timestamp field in DatastreamEvent need decode AVRO record</technical_language>

Target:
private void onSendCallback(DatastreamRecordMetadata metadata, Exception exception, SendCallback sendCallback, DatastreamTask task, DatastreamProducerRecord record) { SendFailedException sendFailedException = null; if (exception != null) { sendFailedException = new SendFailedException(_safeCheckpoints); if (_onUnrecoverableError != null) { _onUnrecoverableError.accept(this); } } else { if (System.currentTimeMillis() - record.getEventsTimestamp() <= _availabilityThresholdSlaMs) { EVENTS_PRODUCED_WITHIN_SLA.inc(); } TOTAL_EVENTS_PRODUCED.inc(); try { _checkpointRWLock.readLock().lock(); if (!_safeCheckpoints.containsKey(task)) { _logger.warn(String.format("Event of unknown task is being acknowledged: task=%s, record=%s", task, record)); } else { _safeCheckpoints.get(task).put(metadata.getPartition(), record.getCheckpoint()); _pendingCheckpoints.set(true); } } finally { _checkpointRWLock.readLock().unlock(); } } if (sendCallback != null) { sendCallback.onCompletion(metadata, sendFailedException); } if (exception != null) { shutdown(); } }
Source:
<code>public Parser<String, Object> makeParser() { <START> parser = parser == null ? new JavaScriptParser(function) : parser; <END> return parser; }</code><technical_language>Is this thread-safe? I guess, maybe, do extra work threads update time. if ParseSpecs need thread-safe; if issue please double-check it</technical_language>

Target:
public Parser<String, Object> makeParser() { Preconditions.checkState(config.isEnabled(), "JavaScript is disabled"); parser = parser == null ? new JavaScriptParser(function) : parser; return parser; }
Source:
<code>public RestApp() { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); register(new SuggesterAppBinder()); <START> register(CorsFilter.class); <END> packages("org.opengrok.web.api.constraints", "org.opengrok.web.api.error"); packages(true, "org.opengrok.web.api.v1"); }</code><technical_language>if move org.opengrok.web.api.v1 this is longer necessary</technical_language>

Target:
public RestApp() { register(new SuggesterAppBinder()); packages("org.opengrok.web.api.constraints", "org.opengrok.web.api.error"); packages(true, "org.opengrok.web.api.v1"); }
Source:
<code>public Collection<SnomedConceptIndexEntry> getProximalPrimitiveParents(String nodeId) { final Set<String> proximalPrimitiveParentIds = newHashSet(); for (SnomedConceptIndexEntry ancestor : getAncestors(nodeId)) { if (ancestor.isPrimitive()) { final String primitiveAncestorId = ancestor.getId(); if (proximalPrimitiveParentIds.isEmpty()) { proximalPrimitiveParentIds.add(primitiveAncestorId); } else { boolean doAdd = true; for (String id : newHashSet(proximalPrimitiveParentIds)) { if (isSubTypeOf(primitiveAncestorId, id)) { proximalPrimitiveParentIds.remove(id); <START> proximalPrimitiveParentIds.add(primitiveAncestorId); <END> doAdd = false; } else if (doAdd && isSuperTypeOf(primitiveAncestorId, id)) { doAdd = false; } } if (doAdd) { proximalPrimitiveParentIds.add(primitiveAncestorId); } } } } return getNodes(proximalPrimitiveParentIds); }</code><technical_language>scenario happen: - primitiveAncestorId wins 1..n existing ids in set, removing them; - of remaining ids (let's call winningId) wins primitiveAncestorId? In this case, is good figured out winningId removed 1-n ids before, add primitiveAncestorId either</technical_language>

Target:
public Collection<SnomedConceptIndexEntry> getProximalPrimitiveParents(String nodeId) { return getNodes(getProximalPrimitiveParentIds(nodeId)); }
Source:
<code>public Position center() { <START> int halfWidth = width() >> 1; <END> int centerX = southWestX + halfWidth; int centerY = southWestY + halfWidth; return new Position(centerX, centerY); }</code><technical_language>Divide operator is fine more readable this a performance critical piece of code</technical_language>

Target:
public Position center() { int halfWidth = width() / 2; int centerX = southWestX + halfWidth; int centerY = southWestY + halfWidth; return new Position(centerX, centerY); }
Source:
<code><START> public synchronized File getTemporaryDirectory() <END> { if ( temporaryDirectory == null ) { final File file = new File( System.getProperty( "java.io.tmpdir" ) ); if ( !file.exists() ) { file.mkdirs(); } temporaryDirectory = canonicalize( file ); } return temporaryDirectory; }</code><technical_language>sync</technical_language>

Target:
public synchronized File getTemporaryDirectory() { if ( temporaryDirectory == null ) { final File file = new File( System.getProperty( "java.io.tmpdir" ) ); forceMkdir( file ); temporaryDirectory = canonicalize( file ); } return temporaryDirectory; }
Source:
<code>private EndpointIterator(final List<Endpoint> endpoints) { this.endpoints = checkNotNull(endpoints); <START> size = endpoints.size(); <END> cursor = size == 0 ? 0 : new Random().nextInt(size); }</code><technical_language>constructor copy list stores size here, modifications passed-in list weird side effects</technical_language>

Target:
private EndpointIterator(final List<Endpoint> endpoints) { this.endpoints = ImmutableList.copyOf(checkNotNull(endpoints)); size = this.endpoints.size(); cursor = size == 0 ? 0 : new Random().nextInt(size); }
Source:
<code>public Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { ImmutableMap.Builder<SchemaTableName, ConnectorViewDefinition> views = ImmutableMap.builder(); List<SchemaTableName> tableNames; if (prefix.getTableName() != null) { tableNames = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } else { tableNames = listViews(session, prefix.getSchemaName()); } for (SchemaTableName schemaTableName : tableNames) { Optional<Table> table = metastore.getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()); if (table.isPresent() && HiveUtil.isPrestoView(table.get())) { views.put(schemaTableName, new ConnectorViewDefinition( schemaTableName, Optional.ofNullable(table.get().getOwner()), decodeViewData(table.get().getViewOriginalText().get()), Optional.empty())); } <START> } <END> return views.build(); }</code><technical_language>is this needed here</technical_language>

Target:
public Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { ImmutableMap.Builder<SchemaTableName, ConnectorViewDefinition> views = ImmutableMap.builder(); List<SchemaTableName> tableNames; if (prefix.getTableName() != null) { tableNames = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } else { tableNames = listViews(session, prefix.getSchemaName()); } for (SchemaTableName schemaTableName : tableNames) { Optional<Table> table = metastore.getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()); if (table.isPresent() && HiveUtil.isPrestoView(table.get())) { views.put(schemaTableName, new ConnectorViewDefinition( schemaTableName, Optional.ofNullable(table.get().getOwner()), decodeViewData(table.get().getViewOriginalText().get()), Optional.ofNullable(table.get().getParameters().get(TABLE_COMMENT)))); } } return views.build(); }
Source:
<code>public CosemDateTimeDto getDaylightSavingsBegin() { <START> return new CosemDateTimeDto(this.daylightSavingsBegin); <END> }</code><technical_language>I CosemDateTimeDto is immutable, is need create a new protect field in this class changes outside</technical_language>

Target:
public CosemDateTimeDto getDaylightSavingsBegin() { return this.daylightSavingsBegin; }
Source:
<code>public RepositoryVersion(@NonNull String version) { Matcher matcher1 = MAJOR_MINOR_MICRO_VERSION_PATTERN.matcher(version); Matcher matcher2 = MAJOR_MINOR_QUALIFIER_VERSION_PATTERN.matcher(version); <START> Matcher matcher3 = MAJOR_MINOR_MICRO_QUALIFIER_VERSION_PATTERN.matcher(version); <END> if (matcher1.matches()) { major = parseInt(matcher1.group(1)); minor = parseInt(matcher1.group(2)); if (matcher1.group(4) != null) { micro = parseInt(matcher1.group(4)); } else { micro = null; } qualifier = null; } else if (matcher3.matches()) { major = parseInt(matcher3.group(1)); minor = parseInt(matcher3.group(2)); micro = parseInt(matcher3.group(3)); qualifier = (matcher3.group(4)); } else if (matcher2.matches()) { major = parseInt(matcher2.group(1)); minor = parseInt(matcher2.group(2)); micro = null; qualifier = matcher2.group(3); } else { qualifier = version; } }</code><technical_language>declare matchers patterns in order used</technical_language>

Target:
public RepositoryVersion(@NonNull String version) { orgVersion = version; Matcher versionMatcher = VERSION_PATTERN.matcher(version); if (versionMatcher.matches()) { major = parseInt(versionMatcher.group(2)); if (versionMatcher.group(5) != null) { minor = parseInt(versionMatcher.group(5)); } else { minor = null; } if (versionMatcher.group(7) != null) { micro = parseInt(versionMatcher.group(7)); } else { micro = null; } if (versionMatcher.group(8) != null) { qualifier = (versionMatcher.group(8)); } else { qualifier = null; } } else { qualifier = version; } }
Source:
<code><START> private void forAll(List<Traversable<?>> traversables, boolean value) { <END> for (Traversable<?> traversable1 : traversables) { for (Traversable<?> traversable2 : traversables) { if (traversable1 != traversable2) { assertThat(traversable1.equals(traversable2)).isEqualTo(value); } } } }</code><technical_language>do think, sense create additional private method check hashCode equality</technical_language>

Target:
private void forAll(List<Traversable<?>> traversables, boolean value) { for (Traversable<?> traversable1 : traversables) { for (Traversable<?> traversable2 : traversables) { if (traversable1 != traversable2) { assertThat(traversable1.equals(traversable2)).isEqualTo(value); if (value) { assertThat(traversable1.hashCode() == traversable2.hashCode()).isTrue(); } } } } }