auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void createDiscrepancyNoteBean(String description, String detailedNotes, int itemDataId, StudyBean studyBean, UserAccountBean ub, DiscrepancyNoteBean parentDiscrepancyNote) { DiscrepancyNoteBean dnb = new DiscrepancyNoteBean(); dnb.setEntityId(itemDataId); dnb.setStudyId(studyBean.getId()); dnb.setEntityType(DiscrepancyNoteBean.ITEM_DATA); dnb.setDescription(description); dnb.setDetailedNotes(detailedNotes); dnb.setDiscrepancyNoteTypeId(parentDiscrepancyNote.getDiscrepancyNoteTypeId()); dnb.setResolutionStatusId(6); dnb.setColumn("value"); dnb.setAssignedUser(null); dnb.setOwner(ub); dnb.setParentDnId(parentDiscrepancyNote.getId()); dnb.setActivated(false); dnb = (DiscrepancyNoteBean) getDnDao().create(dnb); getDnDao().createMapping(dnb); DiscrepancyNoteBean itemParentNote = (DiscrepancyNoteBean) getDnDao().findByPK(dnb.getParentDnId()); <START> itemParentNote.setResolutionStatusId(6); END> itemParentNote.setAssignedUser(null); itemParentNote.setOwner(ub); getDnDao().update(itemParentNote); getDnDao().updateAssignedUserToNull(itemParentNote); }</code><technical_language>I is existing code is remove hard coded numbers for statuses</technical_language>

Target:
private void createDiscrepancyNoteBean(String description, String detailedNotes, int itemDataId, StudyBean studyBean, UserAccountBean ub, DiscrepancyNoteBean parentDiscrepancyNote) { DiscrepancyNoteBean dnb = new DiscrepancyNoteBean(); dnb.setEntityId(itemDataId); dnb.setStudyId(studyBean.getId()); dnb.setEntityType(DiscrepancyNoteBean.ITEM_DATA); dnb.setDescription(description); dnb.setDetailedNotes(detailedNotes); dnb.setDiscrepancyNoteTypeId(parentDiscrepancyNote.getDiscrepancyNoteTypeId()); dnb.setResolutionStatusId(ResolutionStatus.CLOSED_MODIFIED.getId()); dnb.setColumn("value"); dnb.setAssignedUser(null); dnb.setOwner(ub); dnb.setParentDnId(parentDiscrepancyNote.getId()); dnb.setActivated(false); dnb = (DiscrepancyNoteBean) getDnDao().create(dnb); getDnDao().createMapping(dnb); DiscrepancyNoteBean itemParentNote = (DiscrepancyNoteBean) getDnDao().findByPK(dnb.getParentDnId()); itemParentNote.setResolutionStatusId(ResolutionStatus.CLOSED_MODIFIED.getId()); itemParentNote.setAssignedUser(null); itemParentNote.setOwner(ub); getDnDao().update(itemParentNote); getDnDao().updateAssignedUserToNull(itemParentNote); }
Source:
<code>public Environment findOne(String application, String profileList, String label) { final String defaultApplication = configServerProperties .getDefaultApplicationName(); final String defaultProfile = configServerProperties.getDefaultProfile(); if (StringUtils.isEmpty(application)) { application = defaultApplication; } if (StringUtils.isEmpty(profileList)) { profileList = defaultProfile; } <START> String[] profiles = StringUtils.commaDelimitedListToStringArray(profileList); <END> Environment environment = new Environment(application, profiles, label, null, null); Map<String, String> overrides = configServerProperties.getOverrides(); if (!overrides.isEmpty()) { environment.add(new PropertySource("overrides", overrides)); } for (String profile : profiles) { addPropertySource(environment, application, profile); if (!defaultApplication.equals(application)) { addPropertySource(environment, defaultApplication, profile); } } if (!Arrays.asList(profiles).contains(defaultProfile)) { addPropertySource(environment, application, defaultProfile); } if (!Arrays.asList(profiles).contains(defaultProfile) && !defaultApplication.equals(application)) { addPropertySource(environment, defaultApplication, defaultProfile); } if (!defaultApplication.equals(application)) { addPropertySource(environment, application, null); } addPropertySource(environment, defaultApplication, null); return environment; }</code><technical_language>StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(profileList)); in order support profile-1, profile-2 current implementation supports profile-1,profile-2 space</technical_language>

Target:
public Environment findOne(String application, String profileList, String label) { final String defaultApplication = configServerProperties .getDefaultApplicationName(); final String defaultProfile = configServerProperties.getDefaultProfile(); if (StringUtils.isEmpty(application)) { application = defaultApplication; } if (StringUtils.isEmpty(profileList)) { profileList = defaultProfile; } String[] profiles = StringUtils.trimArrayElements( StringUtils.commaDelimitedListToStringArray(profileList)); Environment environment = new Environment(application, profiles, label, null, null); Map<String, String> overrides = configServerProperties.getOverrides(); if (!overrides.isEmpty()) { environment.add(new PropertySource("overrides", overrides)); } for (String profile : profiles) { addPropertySource(environment, application, profile); if (!defaultApplication.equals(application)) { addPropertySource(environment, defaultApplication, profile); } } if (!Arrays.asList(profiles).contains(defaultProfile)) { addPropertySource(environment, application, defaultProfile); } if (!Arrays.asList(profiles).contains(defaultProfile) && !defaultApplication.equals(application)) { addPropertySource(environment, defaultApplication, defaultProfile); } if (!defaultApplication.equals(application)) { addPropertySource(environment, application, null); } addPropertySource(environment, defaultApplication, null); return environment; }
Source:
<code>public long getSizeInBytes() { long buffersSizeInBytes = 0; if (blockEncodingBuffers != null) { for (int i = 0; i < channelCount; i++) { buffersSizeInBytes += blockEncodingBuffers[i].getSizeInBytes(); } } return Integer.BYTES * 2 * positionCount + buffersSizeInBytes; <START> } <END></code><technical_language>Integer.BYTES -> SIZE_OF_INT for consistency getSerializedBuffersSizeInBytes - reason SizeOf.sizeOfIntArray(positionCount)</technical_language>

Target:
public long getSizeInBytes() { long buffersSizeInBytes = 0; if (blockEncodingBuffers != null) { for (int i = 0; i < channelCount; i++) { buffersSizeInBytes += blockEncodingBuffers[i].getSizeInBytes(); } } return SIZE_OF_INT * 2 * positionCount + buffersSizeInBytes; }
Source:
<code>public JSONObject toJSONObject() throws JSONException { JSONObject jsonObject = new JSONObject().put("hostname", hostname).put("port", port) .put("hardwareState", dataNodeStatePolicy.isHardDown() ? HardwareState.UNAVAILABLE : HardwareState.AVAILABLE) .put("disks", new JSONArray()); for (Disk disk : disks) { jsonObject.accumulate("disks", disk.toJSONObject()); } for (String portType : ports.keySet()) { <START> if (!portType.equalsIgnoreCase("plaintext")) { <END> jsonObject.put(portType, ports.get(portType)); } } return jsonObject; }</code><technical_language>is plaintext a special case</technical_language>

Target:
public JSONObject toJSONObject() throws JSONException { JSONObject jsonObject = new JSONObject().put("hostname", hostname).put("port", port); addSSLPortToJson(jsonObject); jsonObject .put("hardwareState", dataNodeStatePolicy.isHardDown() ? HardwareState.UNAVAILABLE : HardwareState.AVAILABLE) .put("disks", new JSONArray()); for (Disk disk : disks) { jsonObject.accumulate("disks", disk.toJSONObject()); } return jsonObject; }
Source:
<code>public long getSize(ParticipantStatus participantStatus, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { <START> return 0; <END> }</code><technical_language>spec says: of JAX-RS 2.0, method deprecated returned method is a JAX-RS runtime. MessageBodyWriter implementations advised return -1 method</technical_language>

Target:
public long getSize(ParticipantStatus participantStatus, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; }
Source:
<code>private DefaultLightblueBulkDataResponse simpleSetUp() throws Exception { DataBulkRequest bulkRequest = new DataBulkRequest(); DataFindRequest dfr = new DataFindRequest("foo", "bar"); dfr.select(Projection.includeField("*")); dfr.where(Query.regex("foo", "*", 0)); DataFindRequest dfr2 = new DataFindRequest("fooz", "bar"); dfr2.select(Projection.includeField("*")); dfr2.where(Query.regex("fooz", "*", 0)); bulkRequest.add(dfr); bulkRequest.add(dfr2); <START> return new DefaultLightblueBulkDataResponse(jsonResponse, null, bulkRequest); <END> }</code><technical_language>DefaultLightblueBulkDataResponse(jsonResponse, bulkRequest) constructor for cases headers</technical_language>

Target:
private DefaultLightblueBulkDataResponse simpleSetUp() throws Exception { DataBulkRequest bulkRequest = new DataBulkRequest(); DataFindRequest dfr = new DataFindRequest("foo", "bar"); dfr.select(Projection.includeField("*")); dfr.where(Query.regex("foo", "*", 0)); DataFindRequest dfr2 = new DataFindRequest("fooz", "bar"); dfr2.select(Projection.includeField("*")); dfr2.where(Query.regex("fooz", "*", 0)); bulkRequest.add(dfr); bulkRequest.add(dfr2); return new DefaultLightblueBulkDataResponse(jsonResponse, bulkRequest); }
Source:
<code><START> public void onApplicationEvent(ContextRefreshedEvent event) { <END> if (!this.initialized.getAndSet(true)) { ConversionService conversionService = getConversionService(); if (conversionService == null) { conversionService = DefaultConversionService.getSharedInstance(); } for (Map.Entry<Object, NamedComponent> entry : this.mapping.entrySet()) { Object key = entry.getKey(); String channelKey; if (key instanceof String) { channelKey = (String) key; } else if (key instanceof Class) { channelKey = ((Class<?>) key).getName(); } else if (conversionService.canConvert(key.getClass(), String.class)) { channelKey = conversionService.convert(key, String.class); } else { throw new MessagingException("Unsupported channel mapping type for router [" + key.getClass() + "]"); } this.router.setChannelMapping(channelKey, entry.getValue().getComponentName()); } } }</code><technical_language>confirm event context is this bean's declaring context</technical_language>

Target:
public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext() == getApplicationContext() && !this.initialized.getAndSet(true)) { ConversionService conversionService = getConversionService(); if (conversionService == null) { conversionService = DefaultConversionService.getSharedInstance(); } for (Map.Entry<Object, NamedComponent> entry : this.mapping.entrySet()) { Object key = entry.getKey(); String channelKey; if (key instanceof String) { channelKey = (String) key; } else if (key instanceof Class) { channelKey = ((Class<?>) key).getName(); } else if (conversionService.canConvert(key.getClass(), String.class)) { channelKey = conversionService.convert(key, String.class); } else { throw new MessagingException("Unsupported channel mapping type for router [" + key.getClass() + "]"); } this.router.setChannelMapping(channelKey, entry.getValue().getComponentName()); } } }
Source:
<code><START> public PluginSelectionDialog(Shell parentShell, IPluginModelBase[] models, boolean multipleSelection) { <END> super(parentShell, multipleSelection); fModels = models; setTitle(PDEUIMessages.PluginSelectionDialog_title); setMessage(PDEUIMessages.PluginSelectionDialog_message); PDEPlugin.getDefault().getLabelProvider().connect(this); setListLabelProvider(PDEPlugin.getDefault().getLabelProvider()); }</code><technical_language>Is this constructor used</technical_language>

Target:
public PluginSelectionDialog(Shell parentShell, IPluginModelBase[] models, boolean multipleSelection) { super(parentShell, multipleSelection); configureModels(models, null); }
Source:
<code>private static List<Concept> getConceptsFromFieldDescription( @Nullable String fieldDescription) { if (fieldDescription == null) { return Collections.emptyList(); } List<Concept> returnValue = new ArrayList<>(); try { SimpleObject extendedData = SimpleObject.parseJson(fieldDescription); Object object = extendedData.get("concepts"); if (! (object instanceof List)) { return Collections.emptyList(); } <START> List list = (List) extendedData.get("concepts"); <END> for (Object obj : list) { if (obj == null) { continue; } Integer conceptId = (Integer) obj; Concept concept = Context.getConceptService().getConcept(conceptId); if (concept == null) { continue; } returnValue.add(concept); } } catch (IOException ignore) { } return returnValue; }</code><technical_language>this List list = (List) object;</technical_language>

Target:
private static List<Concept> getConceptsFromFieldDescription( @Nullable String fieldDescription) { if (fieldDescription == null) { return Collections.emptyList(); } List<Concept> returnValue = new ArrayList<>(); try { SimpleObject extendedData = SimpleObject.parseJson(fieldDescription); Object object = extendedData.get("concepts"); if (! (object instanceof List)) { return Collections.emptyList(); } List list = (List) object; for (Object obj : list) { if (obj == null) { continue; } Integer conceptId = (Integer) obj; Concept concept = Context.getConceptService().getConcept(conceptId); if (concept == null) { continue; } returnValue.add(concept); } } catch (IOException ignore) { } return returnValue; }
Source:
<code>private synchronized boolean tryAcquirePersistentLock() { <START> if (isShutDown) { <END> log.info("The PersistentLockManager is shut down, and therefore rejected a request to acquire the lock."); return true; } Preconditions.checkState(lockId == null, "Acquiring a lock is unsupported when we've already acquired a lock"); try { lockId = persistentLockService.acquireBackupLock("Sweep"); log.info("Successfully acquired persistent lock for sweep: {}", SafeArg.of("lock id", lockId)); return true; } catch (CheckAndSetException e) { lockFailureMeter.mark(); log.info("Failed to acquire persistent lock for sweep. Waiting and retrying."); return false; } }</code><technical_language>isShutDown volatile</technical_language>

Target:
private synchronized boolean tryAcquirePersistentLock() { Preconditions.checkState(!isShutDown, "This PersistentLockManager is shut down, and cannot be used to acquire locks."); Preconditions.checkState(lockId == null, "Acquiring a lock is unsupported when we've already acquired a lock"); try { lockId = persistentLockService.acquireBackupLock("Sweep"); log.info("Successfully acquired persistent lock for sweep: {}", SafeArg.of("lock id", lockId)); return true; } catch (CheckAndSetException e) { lockFailureMeter.mark(); log.info("Failed to acquire persistent lock for sweep. Waiting and retrying."); return false; } }
Source:
<code>public StyledString getStyledText(Object element) { String text = getText(element); if (text != null) { StyledString styledString = new StyledString(text); <START> String reviewText = MessageFormat.format(" ({0}, {1})", END> ((ActivityEvent) element).getAttributes().get("author"), ((ActivityEvent) element).getDate()); styledString.append(reviewText, StyledString.DECORATIONS_STYLER); return styledString; } return new StyledString(); }</code><technical_language>NLS.bind() instead of MessageFormat.format() Eclipse guidelines</technical_language>

Target:
public StyledString getStyledText(Object element) { String text = getText(element); if (text != null) { StyledString styledString = new StyledString(text); String reviewText = NLS.bind(" ({0}, {1})", ((ActivityEvent) element).getAttributes().get("author"), ((ActivityEvent) element).getDate()); styledString.append(reviewText, StyledString.DECORATIONS_STYLER); return styledString; } return new StyledString(); }
Source:
<code>protected void showDialog(Bundle state) { Context context = getContext(); Set<String> selected = getSharedPreferences().getStringSet(getKey(), new HashSet<>()); selected = new HashSet<>(selected); List<String> all = new ArrayList<>(selected); boolean connected = false; WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { WifiInfo info = wifiManager.getConnectionInfo(); if (info != null) { String ssid = info.getSSID(); <START> if (ssid != "" && !ssid.contains("unknown ssid") && !selected.contains(ssid)) { <END> all.add(ssid); connected = true; } } } if (!connected) { Toast.makeText(context, R.string.sync_only_wifi_ssids_connect_to_wifi, Toast.LENGTH_LONG).show(); } if (all.size() > 0 ) { setEntries(stripQuotes(all)); setEntryValues(all.toArray(new CharSequence[all.size()])); setValues(selected); super.showDialog(state); } String[] perms = Constants.getLocationPermissions(); boolean granted = true; for (int i = 0; i < perms.length; i++) { if (ContextCompat.checkSelfPermission(context, perms[i]) != PackageManager.PERMISSION_GRANTED) { granted = false; break; } } if (!granted) { if (context instanceof Activity) { Activity activity = (Activity) context; ActivityCompat.requestPermissions(activity, perms, Constants.PermissionRequestType.LOCATION.ordinal()); this.getDialog().dismiss(); } else { Toast.makeText(context, R.string.sync_only_wifi_ssids_need_to_grant_location_permission, Toast.LENGTH_LONG).show(); } } }</code><technical_language>This lost null check, blow NPE</technical_language>

Target:
protected void showDialog(Bundle state) { Context context = getContext(); Set<String> selected = getSharedPreferences().getStringSet(getKey(), new HashSet<>()); selected = new HashSet<>(selected); List<String> all = new ArrayList<>(selected); boolean connected = false; WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { WifiInfo info = wifiManager.getConnectionInfo(); if (info != null) { String ssid = info.getSSID(); if (ssid != null && ssid != "" && !ssid.contains("unknown ssid")) { if (!selected.contains(ssid)) { all.add(ssid); } connected = true; } } } boolean hasPerms = hasLocationPermissions(); if (!connected) { if (!hasPerms) { Toast.makeText(context, R.string.sync_only_wifi_ssids_need_to_grant_location_permission, Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, R.string.sync_only_wifi_ssids_connect_to_wifi, Toast.LENGTH_LONG).show(); } } if (all.size() > 0 ) { setEntries(stripQuotes(all)); setEntryValues(all.toArray(new CharSequence[all.size()])); setValues(selected); super.showDialog(state); } if (!hasPerms && context instanceof Activity) { Activity activity = (Activity) context; ActivityCompat.requestPermissions(activity, Constants.getLocationPermissions(), Constants.PermissionRequestType.LOCATION.ordinal()); } }
Source:
<code>public int execute() { try { Hive hiveDb = getHive(); Path dumpRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLDIR), Base64.getEncoder().encodeToString(work.dbNameOrPattern.toLowerCase() .getBytes(StandardCharsets.UTF_8.name()))); Path previousDumpMetaPath = getPreviousDumpMetadataPath(dumpRoot); Path previousHiveDumpPath = previousDumpMetaPath != null ? new Path(previousDumpMetaPath, ReplUtils.REPL_HIVE_BASE_DIR) : null; if (shouldDump(previousHiveDumpPath)) { Path currentDumpPath = new Path(dumpRoot, getNextDumpDir()); Path hiveDumpRoot = new Path(currentDumpPath, ReplUtils.REPL_HIVE_BASE_DIR); DumpMetaData dmd = new DumpMetaData(hiveDumpRoot, conf); ReplChangeManager.getInstance(conf); Path cmRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLCMDIR)); Long lastReplId; if (previousHiveDumpPath == null) { lastReplId = bootStrapDump(hiveDumpRoot, dmd, cmRoot, hiveDb); } else { work.setEventFrom(getEventFromPreviousDumpMetadata(previousHiveDumpPath)); lastReplId = incrementalDump(hiveDumpRoot, dmd, cmRoot, hiveDb); } prepareReturnValues(Arrays.asList(currentDumpPath.toUri().toString(), String.valueOf(lastReplId))); writeDumpCompleteAck(hiveDumpRoot); <START> deletePreviousDumpMeta(previousDumpMetaPath); <END> } else { LOG.warn("Previous Dump is not yet loaded"); } } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } return 0; }</code><technical_language>if delete fails /system dump ..how cleanup previous dump directory</technical_language>

Target:
public int execute() { try { Hive hiveDb = getHive(); Path dumpRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLDIR), Base64.getEncoder().encodeToString(work.dbNameOrPattern.toLowerCase() .getBytes(StandardCharsets.UTF_8.name()))); Path previousDumpMetaPath = getPreviousDumpMetadataPath(dumpRoot); Path previousHiveDumpPath = previousDumpMetaPath != null ? new Path(previousDumpMetaPath, ReplUtils.REPL_HIVE_BASE_DIR) : null; if (shouldDump(previousHiveDumpPath)) { Path currentDumpPath = new Path(dumpRoot, getNextDumpDir()); Path hiveDumpRoot = new Path(currentDumpPath, ReplUtils.REPL_HIVE_BASE_DIR); DumpMetaData dmd = new DumpMetaData(hiveDumpRoot, conf); ReplChangeManager.getInstance(conf); Path cmRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLCMDIR)); Long lastReplId; if (previousHiveDumpPath == null) { lastReplId = bootStrapDump(hiveDumpRoot, dmd, cmRoot, hiveDb); } else { work.setEventFrom(getEventFromPreviousDumpMetadata(previousHiveDumpPath)); lastReplId = incrementalDump(hiveDumpRoot, dmd, cmRoot, hiveDb); } prepareReturnValues(Arrays.asList(currentDumpPath.toUri().toString(), String.valueOf(lastReplId))); writeDumpCompleteAck(hiveDumpRoot); deleteAllPreviousDumpMeta(dumpRoot, currentDumpPath); } else { LOG.warn("Previous Dump is not yet loaded"); } } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } return 0; }
Source:
<code>private void onAssignmentRemoved(SubscriptionAssignment assignment) { <START> assignments.remove(assignment); <END> if (consumerNodeId.equals(assignment.getConsumerNodeId())) { callbacks.forEach(callback -> callback.onAssignmentRemoved(assignment.getSubscriptionName()) ); } removeSubscriptionEntryIfEmpty(assignment.getSubscriptionName()); }</code><technical_language>i check if this assignment added, need do job callbacks</technical_language>

Target:
private void onAssignmentRemoved(SubscriptionAssignment assignment) { try { if (assignments.remove(assignment) && consumerNodeId.equals(assignment.getConsumerNodeId())) { callbacks.forEach(callback -> callback.onAssignmentRemoved(assignment.getSubscriptionName())); } removeSubscriptionEntryIfEmpty(assignment.getSubscriptionName()); } catch (Exception e) { logger.error("Exception while removing assignment {}", assignment, e); } }
Source:
<code>public static ColumnVector from(ColumnDescriptor descriptor) { switch (descriptor.getType()) { case BOOLEAN: return new BooleanColumnVector(); case DOUBLE: return new DoubleColumnVector(); case FLOAT: return new FloatColumnVector(); case INT32: return new IntColumnVector(); case INT64: return new LongColumnVector(); case BINARY: return new ByteColumnVector(1); case INT96: <START> return new ByteColumnVector(12); <END> case FIXED_LEN_BYTE_ARRAY: return new ByteColumnVector(descriptor.getTypeLength()); default: throw new IllegalArgumentException("Unhandled column type " + descriptor.getType()); } }</code><technical_language>sounds right</technical_language>

Target:
public static ColumnVector from(ColumnDescriptor descriptor) { switch (descriptor.getType()) { case BOOLEAN: return new BooleanColumnVector(); case DOUBLE: return new DoubleColumnVector(); case FLOAT: return new FloatColumnVector(); case INT32: return new IntColumnVector(); case INT64: return new LongColumnVector(); case BINARY: case INT96: case FIXED_LEN_BYTE_ARRAY: return new ByteColumnVector(); default: throw new IllegalArgumentException("Unhandled column type " + descriptor.getType()); } }
Source:
<code><START> public <V> V columnValue(ColumnName columnName, ColumnMapping<V> columnMapping) { <END> checkNotNull(columnName); checkNotNull(columnMapping); if (!storageFields.containsKey(columnName)) { throw newIllegalStateException("Column with the name `%s` was not found.", columnName); } Object columnValue = storageFields.get(columnName); if (columnValue == null) { V result = columnMapping.ofNull() .apply(null); return result; } V result = columnMapping.of(columnValue.getClass()) .applyTo(columnValue); return result; }</code><technical_language>this method final</technical_language>

Target:
public final <V> V columnValue(ColumnName columnName, ColumnMapping<V> columnMapping) { checkNotNull(columnName); checkNotNull(columnMapping); if (!storageFields.containsKey(columnName)) { throw newIllegalStateException("Column with the name `%s` was not found.", columnName); } Object columnValue = storageFields.get(columnName); if (columnValue == null) { V result = columnMapping.ofNull() .apply(null); return result; } V result = columnMapping.of(columnValue.getClass()) .applyTo(columnValue); return result; }
Source:
<code>public static long extractLong(final Metric m) { if (m instanceof Counting) { return ((Counting) m).getCount(); } if (m instanceof Gauge) { final Object value = ((Gauge) m).getValue(); <START> if (value instanceof Long) { <END> return (long) value; } if (value instanceof Integer) { return ((Integer) value).longValue(); } } throw new IllegalArgumentException("could not extract long value"); }</code><technical_language>Consider ((Number)value).longValue()</technical_language>

Target:
public static long extractLong(final Metric m) { if (m instanceof Counting) { return ((Counting) m).getCount(); } if (m instanceof Gauge) { final Object value = ((Gauge) m).getValue(); if (value instanceof Number) { return ((Number) value).longValue(); } } throw new IllegalArgumentException(String.format("could not extract long value from %s", m.getClass())); }
Source:
<code>private int[] getSelectedArray(ProjectionBlock projectionBlock) { int[] selected = new int[DocIdSetPlanNode.MAX_DOC_PER_CALL]; for (int i = 0; i < _numberWhenStatements; i++) { <START> TransformFunction transformFunction = _whenStatements.get(i); <END> int[] conditions = transformFunction.transformToIntValuesSV(projectionBlock); for (int j = 0; j < conditions.length; j++) { if (selected[j] == 0 && conditions[j] == 1) { selected[j] = i + 1; } } } return selected; }</code><technical_language>this is gathering bitmap invoking BinaryOperatorTransformFunction</technical_language>

Target:
private int[] getSelectedArray(ProjectionBlock projectionBlock) { if (_selectedResults == null) { _selectedResults = new int[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } else { Arrays.fill(_selectedResults, 0); } for (int i = 0; i < _numberWhenStatements; i++) { TransformFunction transformFunction = _whenStatements.get(i); int[] conditions = transformFunction.transformToIntValuesSV(projectionBlock); for (int j = 0; j < conditions.length; j++) { if (_selectedResults[j] == 0 && conditions[j] == 1) { _selectedResults[j] = i + 1; } } } return _selectedResults; }
Source:
<code>public ThemeFingerprintRegistry themeFingerprintRegistry() throws IOException, MolgenisStyleException { ThemeFingerprintRegistry themeFingerprintRegistry = mock(ThemeFingerprintRegistry.class); <START> when(themeFingerprintRegistry.getFingerprint("")).thenReturn(""); <END> return themeFingerprintRegistry; }</code><technical_language>getFingerprint("") --> getFingerprint(anyString()) prevent future integration test issues this registry</technical_language>

Target:
public ThemeFingerprintRegistry themeFingerprintRegistry() throws IOException, MolgenisStyleException { ThemeFingerprintRegistry themeFingerprintRegistry = mock(ThemeFingerprintRegistry.class); when(themeFingerprintRegistry.getFingerprint(anyString())).thenReturn(""); return themeFingerprintRegistry; }
Source:
<code>public Response getDatasourceRuleHistory( @QueryParam("interval") final String interval ) { <START> Interval theInterval = interval == null ? null : new Interval(interval); <END> return Response.ok(auditManager.fetchAuditHistory("rules", theInterval)) .build(); }</code><technical_language>handle parse error here</technical_language>

Target:
public Response getDatasourceRuleHistory( @QueryParam("interval") final String interval ) { try { Interval theInterval = interval == null ? null : new Interval(interval); return Response.ok(auditManager.fetchAuditHistory("rules", theInterval)) .build(); } catch (IllegalArgumentException e) { return Response.serverError().entity(ImmutableMap.<String, Object>of("error", e.getMessage())).build(); } }
Source:
<code>private void checkFileContainsDRepresentation(URI uri, boolean expectedDRepresentation, final WhereToFindDRep whereToFindDRep, String errorMessage) { boolean containsDRepresentation = false; ExtensibleURIConverterImpl uriConverterImpl = new ExtensibleURIConverterImpl(); InputStream inputStream = null; try { inputStream = uriConverterImpl.createInputStream(uri); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(inputStream, new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (WhereToFindDRep.IN_DVIEW.equals(whereToFindDRep)) { if (qName.equals("ownedRepresentations") && attributes.getValue("xmi:type").equals(TablePackage.eINSTANCE.getNsPrefix() + ":" + "DTable")) { throw new SAXException(DREPRESENTATION_FOUND); } } else if (WhereToFindDRep.AS_ROOT_OBJECTS.equals(whereToFindDRep)) { if (qName.equals(TablePackage.eINSTANCE.getNsPrefix() + ":" + "DTable")) { throw new SAXException(DREPRESENTATION_FOUND); } } } }); } catch (SAXException e) { if <START> (e.getMessage().contains(DREPRESENTATION_FOUND)) <END> { containsDRepresentation = true; } } catch (Exception e) { failCheckData(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (final IOException e) { failCheckData(); } } } assertEquals(errorMessage, expectedDRepresentation, containsDRepresentation); }</code><technical_language>"equals" enough</technical_language>

Target:
private void checkFileContainsDRepresentation(URI uri, boolean expectedDRepresentation, final WhereToFindDRep whereToFindDRep, String errorMessage) { boolean containsDRepresentation = false; ExtensibleURIConverterImpl uriConverterImpl = new ExtensibleURIConverterImpl(); InputStream inputStream = null; try { inputStream = uriConverterImpl.createInputStream(uri); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(inputStream, new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (WhereToFindDRep.IN_DVIEW.equals(whereToFindDRep)) { if (qName.equals("ownedRepresentations") && attributes.getValue("xmi:type").equals(TablePackage.eINSTANCE.getNsPrefix() + ":" + "DTable")) { throw new SAXException(DREPRESENTATION_FOUND); } } else if (WhereToFindDRep.AS_ROOT_OBJECTS.equals(whereToFindDRep)) { if (qName.equals(TablePackage.eINSTANCE.getNsPrefix() + ":" + "DTable")) { throw new SAXException(DREPRESENTATION_FOUND); } } } }); } catch (SAXException e) { if (e.getMessage().equals(DREPRESENTATION_FOUND)) { containsDRepresentation = true; } } catch (Exception e) { failCheckData(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (final IOException e) { failCheckData(); } } } assertEquals(errorMessage, expectedDRepresentation, containsDRepresentation); }
Source:
<code>private void removeReadArrayKeys(StatementTree statementTree) { Map<String, Map<String, AssignmentExpressionTree>> cleanedWrittenAndUnread = new HashMap<>(); <START> for (Map.Entry<String, Map<String, AssignmentExpressionTree>> entry : writtenAndUnread.entrySet()) { if (!symbolWasUsedInTree(namesToSymbols.get(entry.getKey()), statementTree)) { cleanedWrittenAndUnread.put(entry.getKey(), entry.getValue()); } } <END> writtenAndUnread = cleanedWrittenAndUnread; }</code><technical_language>do need lines? Unit tests green if I remove them</technical_language>

Target:
private void removeReadArrayKeys(StatementTree statementTree) { writtenAndUnread = writtenAndUnread.entrySet().stream() .filter(entry -> !symbolWasUsedInTree(namesToSymbols.get(entry.getKey()), statementTree)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); }
Source:
<code>public void handleEvent(@NonNull ITmfStateSystemBuilder ss, @NonNull ITmfEvent event) throws AttributeNotFoundException { int quark = ss.getQuarkAbsoluteAndAdd(NetworkStrings.RX_KEY); ITmfStateValue value = ss.queryOngoingState(quark); <START> Long size = (Long) event.getContent().getField(getLayout().fieldLen()).getValue(); <END> ss.modifyAttribute(event.getTimestamp().toNanos(), TmfStateValue.newValueLong(value.unboxLong() + size), quark); }</code><technical_language>getFieldValue(Long.class, getLayout().fieldLen()) null check safer</technical_language>

Target:
public void handleEvent(@NonNull ITmfStateSystemBuilder ss, @NonNull ITmfEvent event) throws AttributeNotFoundException { int quark = ss.getQuarkAbsoluteAndAdd(NetworkStrings.RX_KEY); Long size = event.getContent().getFieldValue(Long.class, getLayout().fieldLen()); if( size != null) { StateSystemBuilderUtils.incrementAttributeLong(ss, event.getTimestamp().toNanos(), quark, size); } }
Source:
<code><START> public List<GooglePubSubSender> senders() { <END> if (pubsubPrefixes != null) { try { final PubSub pubsub = PubSubOptions.getDefaultInstance().getService(); return pubsubPrefixes.stream() .map(prefix -> new GooglePubSubSender(pubsub, prefix)) .collect(toList()); } catch (Exception e) { log.warn("Failed to set up google pubsub service", e); return emptyList(); } } else { return emptyList(); } }</code><technical_language>Write a test for this function</technical_language>

Target:
public List<GooglePubSubSender> senders() { return senders(() -> PubSubOptions.getDefaultInstance().getService()); }
Source:
<code>private void internalEndSuccessfully() { log.info("Ending command '{}' successfully.", getClass().getName()); <START> endSuccessfully(); <END> if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { getCompensationContext().cleanupCompensationDataAfterSuccessfulCommand(); } }</code><technical_language>Hmm...while this ok, I 'harden' a bit prevent cases of leaving compensation context uncleared in DB. suggest following: boolean clearCompensation = true; try { endSuccessfully(); } catch (Exception e) { clearCompensation = false; } finally { if (clearCompensation) { if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { getCompensationContext().cleanupCompensationDataAfterSuccessfulCommand(); } } else { if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { compensate(); } } code improved, this is direction reduce leaving compensation trace in case of a failure end action</technical_language>

Target:
private void internalEndSuccessfully() { log.info("Ending command '{}' successfully.", getClass().getName()); boolean clearCompensation = true; try { endSuccessfully(); } catch (Exception e) { clearCompensation = false; } finally { if (clearCompensation) { if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { getCompensationContext().cleanupCompensationDataAfterSuccessfulCommand(); } } else { if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { compensate(); } } } }
Source:
<code>public JdbcAclService(DataSource dataSource, LookupStrategy lookupStrategy) { Assert.notNull(dataSource, "DataSource required"); <START> Assert.notNull(lookupStrategy, "LookupStrategy required"); <END> this.jdbcOperations = new JdbcTemplate(dataSource); this.lookupStrategy = lookupStrategy; this.aclClassIdUtils = new AclClassIdUtils(); }</code><technical_language>This constructor invoke this(new JdbcTemplate(dataSource), lookupStrategy)</technical_language>

Target:
public JdbcAclService(DataSource dataSource, LookupStrategy lookupStrategy) { this(new JdbcTemplate(dataSource), lookupStrategy); }
Source:
<code><START> private int getLayoutPosition(final int position) { <END> return this.isRTL ? getCount() - 1 - position : position; }</code><technical_language>this method is duplicated thrice, static util function, int getLayoutPosition(boolean isRTL, int count, int position)</technical_language>

Target:
private int getLayoutPosition(final int position) { return LocalizeLayoutUtils.getLayoutPosition(this.isRTL, getCount(), position); }
Source:
<code>private void verify(Channel channel, Publisher publisher) { if (!channel.getSource().equals(publisher)) { <START> throw new IllegalArgumentException(); <END> } }</code><technical_language>add information this exception</technical_language>

Target:
private void verify(Channel channel, Publisher publisher) { if (!channel.getSource().equals(publisher)) { throw new IllegalArgumentException("Channel source does not match updater source"); } }
Source:
<code>public void reportServices(Appendable out) throws InvalidSyntaxException { checkNonNullArgument(out, "Output destination instance cannot be null"); try (Formatter f = new Formatter(out)) { Stream.of(framework.getBundleContext() <START> .getServiceReferences((String) null, null)) <END> .forEach(sref -> f.format("%s%n", sref)); f.flush(); } }</code><technical_language>This is a semantic change a change for older API. getAllServiceReferences care if service type is assignable caller's bundle. This change return services give incorrect results. getAllServiceReferences added in R4.0, this method used</technical_language>

Target:
public void reportServices(Appendable out) throws InvalidSyntaxException { requireNonNull(out, "Output destination instance cannot be null"); try (Formatter f = new Formatter(out)) { Stream.of(framework.getBundleContext() .getAllServiceReferences((String) null, null)) .forEach(sref -> f.format("%s%n", sref)); f.flush(); } }
Source:
<code>public void testToCompletionStageDelayedCompletion() { waitFor(2); Thread mainThread = Thread.currentThread(); Promise<String> willSucceed = Promise.promise(); Promise<String> willFail = Promise.promise(); willSucceed.future().toCompletionStage().whenComplete((str, err) -> { assertEquals("Yo", str); assertNull(err); assertNotSame(mainThread, Thread.currentThread()); complete(); }); willFail.future().toCompletionStage().whenComplete((str, err) -> { assertNull(str); assertTrue(err instanceof RuntimeException); assertEquals("Woops", err.getMessage()); assertNotSame(mainThread, Thread.currentThread()); complete(); }); disableThreadChecks(); new Thread(() -> willSucceed.complete("Yo")).start(); new Thread(() -> willFail.fail(new RuntimeException("Woops"))).start(); <START> await(5, SECONDS); <END> }</code><technical_language>need set number of seconds (also 5 seconds timeout in slow CIs a GC), simply await() do job, is default timeout set of 2 minutes</technical_language>

Target:
public void testToCompletionStageDelayedCompletion() { waitFor(2); Thread mainThread = Thread.currentThread(); Promise<String> willSucceed = Promise.promise(); Promise<String> willFail = Promise.promise(); willSucceed.future().toCompletionStage().whenComplete((str, err) -> { assertEquals("Yo", str); assertNull(err); assertNotSame(mainThread, Thread.currentThread()); complete(); }); willFail.future().toCompletionStage().whenComplete((str, err) -> { assertNull(str); assertTrue(err instanceof RuntimeException); assertEquals("Woops", err.getMessage()); assertNotSame(mainThread, Thread.currentThread()); complete(); }); disableThreadChecks(); new Thread(() -> willSucceed.complete("Yo")).start(); new Thread(() -> willFail.fail(new RuntimeException("Woops"))).start(); await(); }
Source:
<code>public final String toDot() { build(); StringBuilder sb = new StringBuilder("graph " + name() + "{"); <START> for (DotGraph.Node node : nodes) { <END> sb.append(node.toDot()); } for (DotGraph.Edge edge : edges) { sb.append(edge.toDot()); } return sb.append("}").toString(); }</code><technical_language>matter of taste I for stream api nodes.map(Node::toDot).forEach(sb::append) ? end similar lines for node edges</technical_language>

Target:
public final String toDot() { build(); StringBuilder sb = new StringBuilder() .append("graph ") .append(name()) .append(" {") .append(NEW_LINE); elements.build().map(DotElement::toDot).forEach(sb::append); return sb.append(NEW_LINE) .append("}") .toString(); }
Source:
<code>public void testProjectImportWithOptional() throws Exception { String filePath = rootTestResourcesPath + "project_with_optional.xml"; saxParser.parse(inputStream = DatabaseProjectXmlHandlerTest.class.getResourceAsStream(filePath), handler); assertEquals(1, projectsReceiver.getProjects().size()); <START> Project project = projectsReceiver.getProjects().iterator().next(); <END> assertEquals(projectId, project.getId()); assertEquals(projectGrantId, project.getProjectGrantId()); assertEquals(projectAcronym, project.getProjectAcronym()); assertEquals(fundingClass, project.getFundingClass()); assertEquals(optional1, project.getOptional1()); assertEquals(optional2, project.getOptional2()); }</code><technical_language>getProjects() returns list, simply .get(0) instead of iterator? Question concerns tests in this test class</technical_language>

Target:
public void testProjectImportWithOptional() throws Exception { String filePath = rootTestResourcesPath + "project_with_optional.xml"; saxParser.parse(inputStream = DatabaseProjectXmlHandlerTest.class.getResourceAsStream(filePath), handler); assertEquals(1, projectsReceiver.getProjects().size()); Project project = projectsReceiver.getProjects().get(0); assertEquals(projectId, project.getId()); assertEquals(projectGrantId, project.getProjectGrantId()); assertEquals(projectAcronym, project.getProjectAcronym()); assertEquals(fundingClass, project.getFundingClass()); assertEquals(optional1, project.getOptional1()); assertEquals(optional2, project.getOptional2()); }
Source:
<code>public String getWorkspaceLocation() { IEclipseContext context = getWorkbenchConfigurer().getWorkbench().getService(IEclipseContext.class); <START> return IDEWorkspacePreferencePage.getWorkspaceLocationForWindowTitle(context); <END> }</code><technical_language>I suggest move calculation logic preference page this place logic is applied</technical_language>

Target:
public String getWorkspaceLocation() { IEclipseContext context = getWorkbenchConfigurer().getWorkbench().getService(IEclipseContext.class); String location = (String) context.get(E4Workbench.SHOW_LOCATION); if (location != null) { return location; } if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean(IDEInternalPreferences.SHOW_LOCATION)) { return Platform.getLocation().toOSString(); } return null; }
Source:
<code><START> private Response createResponse(Status status, Object entity) { <END> ResponseBuilder rp = responseBuilder(status); PipedOutputStream out = new PipedOutputStream(); try { PipedInputStream in = new PipedInputStream(out); rp.entity(in); } catch (IOException e) { throw new RuntimeException(e); } new Thread(new Runnable() { @Override public void run() { try (JsonWriter jsonWriter = GSON.newJsonWriter(new BufferedWriter(new OutputStreamWriter(out)))) { if (entity != null) { GSON.toJson(entity, entity.getClass(), jsonWriter); jsonWriter.flush(); } } catch (IOException | JsonIOException e) { logger.error("Error streaming JSON through PipedInpuStream/PipedOutputStream: ", e); } } }).start(); return rp.build(); }</code><technical_language>need close in out ever</technical_language>

Target:
private Response createResponse(Status status, Object entity) { ResponseBuilder rp = responseBuilder(status); PipedOutputStream out = new PipedOutputStream(); try { PipedInputStream in = new PipedInputStream(out); rp.entity(in); } catch (IOException e) { throw new RuntimeException(e); } Thread writerThread = new Thread(() -> { try (JsonWriter jsonWriter = gson.newJsonWriter(new BufferedWriter(new OutputStreamWriter(out)))) { if (entity != null) { gson.toJson(entity, entity.getClass(), jsonWriter); jsonWriter.flush(); } } catch (IOException | JsonIOException e) { logger.error("Error streaming JSON through PipedInpuStream/PipedOutputStream: ", e); } }); writerThread.setDaemon(true); writerThread.start(); return rp.build(); }
Source:
<code>public static DateTime getTargetDate(final boolean isDaySleeper, final DateTime queryDate, final DateTime currentTimeLocal, final Optional<Integer> queryHourOptional, final TimeZoneOffsetMap timeZoneOffsetMap){ final long queryDateLocal = queryDate.getMillis() - timeZoneOffsetMap.getOffsetWithDefaultAsZero(queryDate.getMillis()); final boolean isStillQueryDate; if (queryHourOptional.isPresent()) { <START> isStillQueryDate = (currentTimeLocal.withTimeAtStartOfDay().getMillis() - queryDateLocal) < DateTimeConstants.MILLIS_PER_DAY; <END> } else { isStillQueryDate = false; } final DateTime targetDate; if(isStillQueryDate && !isDaySleeper){ targetDate = queryDate.minusDays(1); } else { targetDate = queryDate; } return targetDate; }</code><technical_language>Minutes.between(currentTimeLocal.withTimeAtStartOfDay(), queryDateLocal) compute difference a.isAfter(b)</technical_language>

Target:
public static DateTime getTargetDate(final boolean isDaySleeper, final DateTime queryDate, final DateTime currentTimeLocal, final Optional<Integer> queryHourOptional, final TimeZoneOffsetMap timeZoneOffsetMap){ final long endQueryDate = queryDate.getMillis() - timeZoneOffsetMap.getOffsetWithDefaultAsZero(queryDate.getMillis()) + DateTimeConstants.MILLIS_PER_DAY; final boolean isStillQueryDate; if (queryHourOptional.isPresent()) { isStillQueryDate = currentTimeLocal.withTimeAtStartOfDay().isBefore(endQueryDate); } else { isStillQueryDate = false; } final DateTime targetDate; if(isStillQueryDate && !isDaySleeper){ targetDate = queryDate.minusDays(1); } else { targetDate = queryDate; } return targetDate; }
Source:
<code>public static void customizeTable(JTable table) { <START> table.setGridColor(Color.lightGray); <END> table.setRowHeight(28); }</code><technical_language>Same: static import lightGray Color</technical_language>

Target:
public static void customizeTable(JTable table) { table.setGridColor(lightGray); table.setRowHeight(28); }
Source:
<code>public boolean isValid(T value, ConstraintValidatorContext context) { if ( value == null ) { return true; } Clock reference; try { ClockProvider clockProvider = context.getClockProvider(); reference = clockProvider.getClock(); } <START> catch (Exception e) { <END> throw LOG.getUnableToGetCurrentTimeFromClockProvider( e ); } int result = value.compareTo( getReferenceValue( reference ) ); if ( isPast ) { return isPresentValid ? ( result <= 0 ) : ( result < 0 ); } else { return isPresentValid ? ( result >= 0 ) : ( result > 0 ); } }</code><technical_language>Is specific reason for wrapping this exception here</technical_language>

Target:
public boolean isValid(T value, ConstraintValidatorContext context) { if ( value == null ) { return true; } Clock reference; try { ClockProvider clockProvider = context.getClockProvider(); reference = clockProvider.getClock(); } catch (Exception e) { throw LOG.getUnableToGetCurrentTimeFromClockProvider( e ); } int result = value.compareTo( getReferenceValue( reference ) ); return isValid( result ); }
Source:
<code><START> public int getClientDestinationPort() { <END> if (clientRemoteAddress instanceof InetSocketAddress) { return ((InetSocketAddress) clientRemoteAddress).getPort(); } else { return getOriginalPort(); } }</code><technical_language>This absent, API express this. Optional<Integer> a @Nullable Integer</technical_language>

Target:
public Optional<Integer> getClientDestinationPort() { if (clientRemoteAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) this.clientRemoteAddress; return Optional.of(inetSocketAddress.getPort()); } else { return Optional.empty(); } }