auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>@Override public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { <START> if (arguments.length != 2) { <END> throw new UDFArgumentLengthException("The function split_map_privs(s, ' ') takes exactly 2 arguments."); } converters = new ObjectInspectorConverters.Converter[arguments.length]; for (int i = 0; i < arguments.length; i++) { converters[i] = ObjectInspectorConverters .getConverter(arguments[i], PrimitiveObjectInspectorFactory.writableStringObjectInspector); } ObjectInspector rightArg = arguments[1]; if (rightArg instanceof ConstantObjectInspector) { constPattern = Pattern.compile(((ConstantObjectInspector) rightArg). getWritableConstantValue().toString()); } return ObjectInspectorFactory .getStandardListObjectInspector(PrimitiveObjectInspectorFactory.writableStringObjectInspector); }</code><technical_language>refer public class UDFYear extends GenericUDF { validation. checkArgsSize(arguments, 1, 1); checkArgPrimitive(arguments, 0);</technical_language>

Target:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { checkArgsSize(arguments, 1, 1); checkArgPrimitive(arguments, 0); converters[0] = ObjectInspectorConverters .getConverter(arguments[0], PrimitiveObjectInspectorFactory.writableStringObjectInspector); return ObjectInspectorFactory .getStandardListObjectInspector(PrimitiveObjectInspectorFactory.writableStringObjectInspector); }
Source:
<code>public ReadRequest(ByteBuf buf) { <START> address = ICorfuPayload.fromBuffer(buf, Long.class); <END> }</code><technical_language>fyi ICorfuPayload.fromBuffer block. serialize message directly. Example: address = buf.readLong(); buf.writeLong(address)</technical_language>

Target:
public ReadRequest(ByteBuf buf) { address = buf.readLong(); }
Source:
<code>private boolean requiresIncomingDecoration(AbstractAttributeEditor editor, TaskDataModel model, TaskAttribute attribute) { return editor.isDecorationEnabled() && model.hasBeenRead() && model.hasIncomingChanges(attribute) <START> && isCompatibleKind(attribute.getMetaData().getKind()) ? true : false; <END> }</code><technical_language>Remove "? true : false"</technical_language>

Target:
private boolean requiresIncomingDecoration(AbstractAttributeEditor editor, TaskDataModel model, TaskAttribute attribute) { return editor.isDecorationEnabled() && model.hasBeenRead() && model.hasIncomingChanges(attribute) && isCompatibleKind(attribute.getMetaData().getKind()); }
Source:
<code>public void onWikipediaZeroInterstitialEvent(final WikipediaZeroInterstitialEvent event) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.zero_interstitial_title)); alert.setMessage(getString(R.string.zero_interstitial_leave_app)); alert.setPositiveButton(getString(R.string.zero_interstitial_continue), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Utils.visitInExternalBrowser(EditSectionActivity.this, event.getUri()); } }); alert.setNegativeButton(getString(R.string.zero_interstitial_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); alert.setNeutralButton(getString(R.string.nav_item_preferences), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { visitSettings(); } }); <START> final AlertDialog ad = alert.create(); <END> ad.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface d) { ad.getButton(DialogInterface.BUTTON_NEGATIVE).setTypeface(Typeface.DEFAULT, Typeface.BOLD); } }); ad.show(); }</code><technical_language>trigger this? I on/off/on edit screen get this triggered. edit preview/How improve page? screen; same: dialog there</technical_language>

Target:
public void onWikipediaZeroInterstitialEvent(final WikipediaZeroInterstitialEvent event) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.zero_interstitial_title)); alert.setMessage(getString(R.string.zero_interstitial_leave_app)); alert.setPositiveButton(getString(R.string.zero_interstitial_continue), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Utils.visitInExternalBrowser(EditSectionActivity.this, event.getUri()); } }); alert.setNegativeButton(getString(R.string.zero_interstitial_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); AlertDialog ad = alert.create(); ad.show(); }
Source:
<code><START> public void eventDispatched(IExitedDMEvent event) { <END> IMemoryDMContext context = DMContexts.getAncestorOfType(event.getDMContext(), IMemoryDMContext.class); if (context != null) { fAddressSizes.remove(context); } }</code><technical_language>This trigger for thread exists also. dealing a process using: if (event.getDMContext() instanceof IContainerDMContext)</technical_language>

Target:
public void eventDispatched(IExitedDMEvent event) { if (event.getDMContext() instanceof IContainerDMContext) { IMemoryDMContext context = DMContexts.getAncestorOfType(event.getDMContext(), IMemoryDMContext.class); if (context != null) { fAddressSizes.remove(context); } } }
Source:
<code><START> public void setup(OperatorContext context) <END> { super.setup(context); physicalPartitionId = context.getId(); partitionedFileName = String.format(partitionedFileNameformat, outputFileName, physicalPartitionId); }</code><technical_language>wondering need this class; simply add a boolean property base class called "appendPartitionId" ? Also, ticket description "If SingleFileOutputOperator is partitioned **more one** physical instances append partitionId file name" (my emphasis), I check for condition appending partition id</technical_language>

Target:
public void setup(OperatorContext context) { super.setup(context); physicalPartitionId = context.getId(); if (StringUtils.isEmpty(partitionedFileNameformat)) { partitionedFileName = outputFileName; } else { partitionedFileName = String.format(partitionedFileNameformat, outputFileName, physicalPartitionId); } }
Source:
<code>public void execute() throws Exception { if (!ElasticsearchProcessMonitor.isElasticsearchStarted()) { String exceptionMsg = "Elasticsearch is not yet started, check back again later"; logger.info(exceptionMsg); return; } HealthBean healthBean = new HealthBean(); try { Client esTransportClient = ESTransportClient.instance(config).getTransportClient(); ClusterHealthStatus clusterHealthStatus = esTransportClient.admin().cluster().prepareHealth().setTimeout(MASTER_NODE_TIMEOUT).execute().get().getStatus(); ClusterHealthResponse clusterHealthResponse = esTransportClient.admin().cluster().prepareHealth().execute().actionGet(MASTER_NODE_TIMEOUT); if (clusterHealthStatus == null) { logger.info("ClusterHealthStatus is null,hence returning (No Health)."); resetHealthStats(healthBean); return; } if (clusterHealthStatus.name().equalsIgnoreCase("GREEN")) { healthBean.greenorredstatus = 0; healthBean.greenoryellowstatus = 0; } else if (clusterHealthStatus.name().equalsIgnoreCase("YELLOW")) { healthBean.greenoryellowstatus = 1; healthBean.greenorredstatus = 0; } else if (clusterHealthStatus.name().equalsIgnoreCase("RED")) { healthBean.greenorredstatus = 1; healthBean.greenoryellowstatus = 0; } if(config.isNodeMismatchWithDiscoveryEnabled()) healthBean.nodematch = (clusterHealthResponse.getNumberOfNodes() == instanceManager.getAllInstances().size()) ? 0 : 1; else healthBean.nodematch = (clusterHealthResponse.getNumberOfNodes() == config.getDesiredNumberOfNodesInCluster()) ? 0 : 1; if(config.isEurekaHealthCheckEnabled()) healthBean.eurekanodematch = (clusterHealthResponse.getNumberOfNodes() == discoveryClient.getApplication(config.getAppName()).getInstances().size()) ? 0 : 1; } catch(Exception e) { resetHealthStats(healthBean); logger.warn("failed to load Cluster Health Status", e); } <START> healthBean.esuponinstance = ElasticsearchProcessMonitor.isElasticsearchStarted() ? 1 : 0; <END> healthReporter.healthBean.set(healthBean); }</code><technical_language>This check true. Meaning, able catch if ES is running, of Initial Check in beginning of execute() method. please consider 0 expected/correct 1 error consistent across</technical_language>

Target:
public void execute() throws Exception { HealthBean healthBean = new HealthBean(); if (instanceManager.isMaster()) { reportClusterMetrics(healthBean); } healthBean.esuponinstance = ElasticsearchProcessMonitor.isElasticsearchStarted() ? 1 : 0; healthReporter.healthBean.set(healthBean); }
Source:
<code>public void onAutoConnectClicked() { autoConnectStep.showProgressBar(); String lastKnowReader = RetailSDK.getDeviceManager().getLastActiveBluetoothReader(); <START> RetailSDK.getDeviceManager().scanAndAutoConnectToBluetoothReader(null, new DeviceManager.ConnectionCallback() { <END> @Override public void connection(final RetailSDKException error, final PaymentDevice cardReader) { ReaderConnectionActivity.this.runOnUiThread(new Runnable() { @Override public void run() { autoConnectStep.hideProgressBarShowButton(); if (error == null && cardReader != null) { onReaderConnected(cardReader); } else if (error != null) { Toast.makeText(getApplicationContext(), "Connection to a reader failed with error: " + error, Toast.LENGTH_SHORT).show(); Log.e(LOG_TAG, "Connection to a reader failed with error: " + error); } else { Toast.makeText(getApplicationContext(), "Could not find the last card reader to connect to", Toast.LENGTH_SHORT).show(); Log.d(LOG_TAG, "Could not find the last card reader to connect to"); } } }); } }); }</code><technical_language>pass null here</technical_language>

Target:
public void onAutoConnectClicked() { autoConnectStep.showProgressBar(); String lastKnowReader = RetailSDK.getDeviceManager().getLastActiveBluetoothReader(); RetailSDK.getDeviceManager().scanAndAutoConnectToBluetoothReader(lastKnowReader, new DeviceManager.ConnectionCallback() { @Override public void connection(final RetailSDKException error, final PaymentDevice cardReader) { ReaderConnectionActivity.this.runOnUiThread(new Runnable() { @Override public void run() { autoConnectStep.hideProgressBarShowButton(); if (error == null && cardReader != null) { onReaderConnected(cardReader); } else if (error != null) { Toast.makeText(getApplicationContext(), "Connection to a reader failed with error: " + error, Toast.LENGTH_SHORT).show(); Log.e(LOG_TAG, "Connection to a reader failed with error: " + error); } else { Toast.makeText(getApplicationContext(), "Could not find the last card reader to connect to", Toast.LENGTH_SHORT).show(); Log.d(LOG_TAG, "Could not find the last card reader to connect to"); } } }); } }); }
Source:
<code>public Object[] resolve(Method method) { DroneContext context = droneContext.get(); InjectionPoint<?>[] injectionPoints = InjectionPoints.parametersInMethod(method); Object[] resolution = new Object[injectionPoints.length]; for (int i = 0; i < injectionPoints.length; i++) { InjectionPoint<?> injectionPoint = injectionPoints[i]; if (injectionPoint == null) { resolution[i] = null; continue; } log.log(Level.FINE, "Injecting @Drone for method {0}, argument {1} @{2} ", new Object[] { method.getName(), injectionPoint.getDroneType().getSimpleName(), injectionPoint.getQualifier().getSimpleName() }); Object drone = context.getDrone(injectionPoint); <START> Validate.notNull(drone, "Retrieved a null from Drone Context, which is not a valid Drone browser object"); <END> resolution[i] = drone; } return resolution; }</code><technical_language>Useless exception</technical_language>

Target:
public Object[] resolve(Method method) { DroneContext context = droneContext.get(); InjectionPoint<?>[] injectionPoints = InjectionPoints.parametersInMethod(method); Object[] resolution = new Object[injectionPoints.length]; for (int i = 0; i < injectionPoints.length; i++) { InjectionPoint<?> injectionPoint = injectionPoints[i]; if (injectionPoint == null) { resolution[i] = null; continue; } ensureInjectionPointPrepared(injectionPoint); log.log(Level.FINE, "Injecting @Drone for method {0}, injection point {1}", new Object[] { method.getName(), injectionPoint } ); Object drone = context.getDrone(injectionPoint); Validate.stateNotNull(drone, "Retrieved a null from Drone Context, which is not a valid Drone browser object" + ".\nMethod: {0}, injection point: {1},", method.getName(), injectionPoint); resolution[i] = drone; } return resolution; }
Source:
<code>public String toString() { <START> return String.format("ProductBranding [id: %s, name: %s, productId: %s, type: %s]", <END> this.getId(), this.getName(), this.getProductId(), this.getType()); }</code><technical_language>here: Branding, ProductBranding</technical_language>

Target:
public String toString() { return String.format("Branding [id: %s, name: %s, productId: %s, type: %s]", this.getId(), this.getName(), this.getProductId(), this.getType()); }
Source:
<code>private boolean isRemoveService(OperationContext context, ModelNode operation) { if (context.isNormalServer()) { if (operation.hasDefined(OPERATION_HEADERS) && operation.get(OPERATION_HEADERS).hasDefined(ALLOW_RESOURCE_SERVICE_RESTART) <START> && operation.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).asBoolean()) { <END> context.removeService(MBeanServerService.SERVICE_NAME); return true; } } return false; }</code><technical_language>OperationContext.isResourceServiceRestartAllowed()</technical_language>

Target:
private boolean isRemoveService(OperationContext context, ModelNode operation) { if (context.isNormalServer()) { if (context.isResourceServiceRestartAllowed()) { context.removeService(MBeanServerService.SERVICE_NAME); return true; } } return false; }
Source:
<code><START> private long createConfigurableDependencyMap(Configuration config, SelectableFeature feature) { <END> if (!(feature.getFeature().getFeatureModel() instanceof ExtendedFeatureModel)) { return 0; } int numberOfConfigurableAttributes = 0; for (IFeatureStructure child : feature.getFeature().getStructure().getChildren()) { numberOfConfigurableAttributes += createConfigurableDependencyMap(config, config.getSelectableFeature(child.getFeature())); } if (feature.getSelection() == Selection.SELECTED) { ExtendedFeature extFeature = (ExtendedFeature) feature.getFeature(); numberOfConfigurableAttributes += extFeature.getAttributes().stream().filter(att -> att.isConfigurable()).count(); if (numberOfConfigurableAttributes > 0) { configurableFilterList.add(feature.getFeature().getName()); } } return numberOfConfigurableAttributes; }</code><technical_language>this return int this method is wild, some explanation nice</technical_language>

Target:
private int createConfigurableDependencyMap(Configuration config, SelectableFeature feature) { if (!(feature.getFeature().getFeatureModel() instanceof ExtendedFeatureModel)) { return 0; } int numberOfConfigurableAttributes = 0; for (IFeatureStructure child : feature.getFeature().getStructure().getChildren()) { numberOfConfigurableAttributes += createConfigurableDependencyMap(config, config.getSelectableFeature(child.getFeature())); } if (feature.getSelection() == Selection.SELECTED) { ExtendedFeature extFeature = (ExtendedFeature) feature.getFeature(); numberOfConfigurableAttributes += extFeature.getAttributes().stream().filter(att -> att.isConfigurable()).count(); if (numberOfConfigurableAttributes > 0) { configurableFilterList.add(feature.getFeature().getName()); } } return numberOfConfigurableAttributes; }
Source:
<code>public void processEvent(GlusterEvent event) { if (event == null) { return; } GlusterServer glusterServer = glusterServerDao.getByGlusterServerUuid(Guid.createGuidFromString(event.getNodeId())); <START> if (glusterServer == null) { <END> return; } VDS host = vdsDao.get(glusterServer.getId()); if (host == null) { return; } if (event.getEvent().equalsIgnoreCase("EVENT_GEOREP_CHECKPOINT_COMPLETED")) { GlusterVolumeEntity masterVol = glusterVolumeDao.getByName(host.getClusterId(), (String) event.getMessage().get("master_volume")); if (masterVol == null) { log.debug("Could not determine master volume from event '{}'", event); return; } GlusterGeoRepSession session = geoRepDao.getGeoRepSession(masterVol.getId(), (String) event.getMessage().get("slave_host"), (String) event.getMessage().get("slave_volume")); if (session != null) { log.debug("received event for session '{}'", session.getSessionKey()); } GlusterGeoRepSyncJob.getInstance().refreshGeoRepDataForVolume(masterVol); } }</code><technical_language>need log case</technical_language>

Target:
public void processEvent(GlusterEvent event) { if (event == null) { log.debug("No event to process!"); return; } GlusterServer glusterServer = glusterServerDao.getByGlusterServerUuid(Guid.createGuidFromString(event.getNodeId())); if (glusterServer == null) { log.debug("Could not determine gluster server from event '{}'", event); return; } VdsStatic host = vdsStaticDao.get(glusterServer.getId()); if (host == null) { log.debug("No host corresponding to gluster server in '{}'", event); return; } if (event.getEvent().equalsIgnoreCase(EVENT_GEOREP_CHECKPOINT_COMPLETED)) { GlusterVolumeEntity masterVol = glusterVolumeDao.getByName(host.getClusterId(), (String) event.getMessage().get(MASTER_VOLUME)); if (masterVol == null) { log.debug("Could not determine master volume from event '{}'", event); return; } GlusterGeoRepSession session = geoRepDao.getGeoRepSession(masterVol.getId(), (String) event.getMessage().get(SLAVE_HOST), (String) event.getMessage().get(SLAVE_VOLUME)); if (session != null) { log.debug("received event for session '{}'", session.getSessionKey()); } GlusterGeoRepSyncJob.getInstance().refreshGeoRepDataForVolume(masterVol); } }
Source:
<code>private void write(SetMultimap<ModelWithPayload<Series>, ModelWithPayload<Episode>> seriesAndEpisodes, Brand brand) { for (Entry<ModelWithPayload<Series>, Collection<ModelWithPayload<Episode>>> seryAndEpisodes : seriesAndEpisodes.asMap().entrySet()) { Series series = null; ModelWithPayload<Series> seryModelWithPayload = seryAndEpisodes.getKey(); if (seryModelWithPayload.getModel().getCanonicalUri() != null) { series = resolveAndUpdate(seryModelWithPayload.getModel()); series.setParent(brand); checkUri(series); checkSource(brand); writer.createOrUpdate(seryModelWithPayload.getModel(), (seryModelWithPayload.getPayload() != null) ? seryModelWithPayload.getPayload() : ""); } for (ModelWithPayload<Episode> episodeModelWithPayload : seryAndEpisodes.getValue()) { try { Episode episode = episodeModelWithPayload.getModel(); episode = resolveAndUpdate(episode); episode.setContainer(brand); if (series != null) { episode.setSeries(series); } checkUri(episode); checkSource(episode); writer.createOrUpdate(episode, <START> (episodeModelWithPayload.getPayload() != null) ? episodeModelWithPayload.getPayload() : ""); <END> } catch (Exception e) { log.warn("Failed to write " + episodeModelWithPayload.getModel().getCanonicalUri(), e); } } } }</code><technical_language>Extract payload a variable for readability</technical_language>

Target:
private void write(SetMultimap<ModelWithPayload<Series>, ModelWithPayload<Episode>> seriesAndEpisodes, Brand brand) { for (Entry<ModelWithPayload<Series>, Collection<ModelWithPayload<Episode>>> seryAndEpisodes : seriesAndEpisodes.asMap().entrySet()) { Series series = null; ModelWithPayload<Series> seryModelWithPayload = seryAndEpisodes.getKey(); if (seryModelWithPayload.getModel().getCanonicalUri() != null) { series = resolveAndUpdate(seryModelWithPayload.getModel()); series.setParent(brand); checkUri(series); checkSource(brand); writer.createOrUpdate(seryModelWithPayload.getModel(), seryModelWithPayload.getPayload()); } for (ModelWithPayload<Episode> episodeModelWithPayload : seryAndEpisodes.getValue()) { try { Episode episode = episodeModelWithPayload.getModel(); episode = resolveAndUpdate(episode); episode.setContainer(brand); if (series != null) { episode.setSeries(series); } checkUri(episode); checkSource(episode); writer.createOrUpdate(episode, episodeModelWithPayload.getPayload()); } catch (Exception e) { log.warn("Failed to write " + episodeModelWithPayload.getModel().getCanonicalUri(), e); } } } }
Source:
<code>private static void refreshBorderFigure(final BorderedStyle borderedStyle, final StyledFigure styledFigure) { LineBorder lineBorder = null; if (styledFigure.getBorder() instanceof LineBorder) { lineBorder = (LineBorder) styledFigure.getBorder(); } else { lineBorder = new LineBorder(); if (styledFigure instanceof Shape) { styledFigure.setBorder(null); ((Shape) styledFigure).setOutline(false); ((Shape) <START> styledFigure).setOutlineXOR(false); <END> } else { styledFigure.setBorder(lineBorder); } } int borderSize = 0; if (borderedStyle.getBorderSize() != null) { borderSize = borderedStyle.getBorderSize().intValue(); } lineBorder.setWidth(borderSize); final RGBValues borderColor = borderedStyle.getBorderColor(); if (borderColor != null) { lineBorder.setColor(VisualBindingManager.getDefault().getColorFromRGBValues(borderColor)); } if (borderSize == 0) { if (!(styledFigure instanceof NoteFigure)) { styledFigure.setBorder(null); } } }</code><technical_language>container operations</technical_language>

Target:
private static void refreshBorderFigure(final BorderedStyle borderedStyle, final StyledFigure styledFigure) { LineBorder lineBorder = null; if (styledFigure.getBorder() instanceof LineBorder) { lineBorder = (LineBorder) styledFigure.getBorder(); } else { lineBorder = new LineBorder(); if (styledFigure instanceof Shape) { styledFigure.setBorder(null); ((Shape) styledFigure).setOutline(false); } else { styledFigure.setBorder(lineBorder); } } int borderSize = 0; if (borderedStyle.getBorderSize() != null) { borderSize = borderedStyle.getBorderSize().intValue(); } lineBorder.setWidth(borderSize); final RGBValues borderColor = borderedStyle.getBorderColor(); if (borderColor != null) { lineBorder.setColor(VisualBindingManager.getDefault().getColorFromRGBValues(borderColor)); } if (borderSize == 0) { if (!(styledFigure instanceof NoteFigure)) { styledFigure.setBorder(null); if (styledFigure instanceof Shape) { ((Shape) styledFigure).setOutline(false); } } else { if (styledFigure instanceof Shape) { ((Shape) styledFigure).setOutline(true); } } } }
Source:
<code>public static void cleanDirectBuffer(ByteBuffer buf) { if (cleanMethod != null) { try { cleanMethod.invoke(cleanerMethod.invoke(buf)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { } } else if (invokeCleanerMethod != null) { try { invokeCleanerMethod.invoke(unsafe, buf); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { <START> e.printStackTrace(); <END> } } }</code><technical_language>I print stderr. I suggest a logger in cases (cleanMethod invokeCleanerMethod)</technical_language>

Target:
public static void cleanDirectBuffer(ByteBuffer buf) { if (cleanMethod != null) { try { cleanMethod.invoke(cleanerMethod.invoke(buf)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { logger.warn("Error while cleaning up the DirectBuffer", e); } } else if (invokeCleanerMethod != null) { try { invokeCleanerMethod.invoke(unsafe, buf); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { logger.warn("Error while cleaning up the DirectBuffer", e); } } }
Source:
<code>void addChild(final PlotCommit c) { final int cnt = children.length; if (cnt == 0) children = new PlotCommit[] { c }; else if (cnt == 1) { if (!c.getId().equals(children[0].getId())) children = new PlotCommit[] { children[0], c }; } else { <START> for (int i = 0; i < children.length; i++) <END> if (c.getId().equals(children[i].getId())) return; final PlotCommit[] n = new PlotCommit[cnt + 1]; System.arraycopy(children, 0, n, 0, cnt); n[cnt] = c; children = n; } }</code><technical_language>this is a normal iteration, following?: for (PlotCommit child : children)</technical_language>

Target:
void addChild(final PlotCommit c) { final int cnt = children.length; if (cnt == 0) children = new PlotCommit[] { c }; else if (cnt == 1) { if (!c.getId().equals(children[0].getId())) children = new PlotCommit[] { children[0], c }; } else { for (PlotCommit pc : children) if (c.getId().equals(pc.getId())) return; final PlotCommit[] n = new PlotCommit[cnt + 1]; System.arraycopy(children, 0, n, 0, cnt); n[cnt] = c; children = n; } }
Source:
<code>private int displayPackageFilePath(String pckg, int userId) throws RemoteException { final PrintWriter pw = getOutPrintWriter(); PackageInfo info = mInterface.getPackageInfo(pckg, 0, userId); if (info != null && info.applicationInfo != null) { pw.print("package:"); pw.println(info.applicationInfo.sourceDir); if (!ArrayUtils.isEmpty(info.applicationInfo.splitSourceDirs)) { for (String splitSourceDir : info.applicationInfo.splitSourceDirs) { pw.print("package:"); pw.println(splitSourceDir); } } return 0; } else { final int getApexFlags = PackageManager.MATCH_APEX | <START> PackageManager.MATCH_UNINSTALLED_PACKAGES; <END> @SuppressWarnings("unchecked") final ParceledListSlice<PackageInfo> slice = mInterface .getInstalledPackages(getApexFlags, userId); for (PackageInfo pi : slice.getList()) { if (pi.packageName.equals(pckg)) { info = pi; break; } } if (info != null && info.applicationInfo != null) { pw.print("package:"); pw.println(info.applicationInfo.sourceDir); return 0; } } return 1; }</code><technical_language>want match uninstalled packages here</technical_language>

Target:
private int displayPackageFilePath(String pckg, int userId) throws RemoteException { PackageInfo info = mInterface.getPackageInfo(pckg, PackageManager.MATCH_APEX, userId); if (info != null && info.applicationInfo != null) { final PrintWriter pw = getOutPrintWriter(); pw.print("package:"); pw.println(info.applicationInfo.sourceDir); if (!ArrayUtils.isEmpty(info.applicationInfo.splitSourceDirs)) { for (String splitSourceDir : info.applicationInfo.splitSourceDirs) { pw.print("package:"); pw.println(splitSourceDir); } } return 0; } return 1; }
Source:
<code>public ContainerChillModeRule(String ruleName, EventQueue eventQueue, Configuration conf, List<ContainerInfo> containers, SCMChillModeManager manager) { super(manager, ruleName); chillModeCutoff = conf.getDouble( HddsConfigKeys.HDDS_SCM_CHILLMODE_THRESHOLD_PCT, HddsConfigKeys.HDDS_SCM_CHILLMODE_THRESHOLD_PCT_DEFAULT); <START> if (chillModeCutoff > 1.0 || chillModeCutoff < 0.0) { <END> throw new IllegalArgumentException(HddsConfigKeys. HDDS_SCM_CHILLMODE_THRESHOLD_PCT + " value should be >= 0.0 and <= " + "1.0"); } containerMap = new ConcurrentHashMap<>(); if(containers != null) { containers.forEach(c -> { if (c != null && c.getState() != null && !c.getState().equals(HddsProtos.LifeCycleState.OPEN)) { containerMap.put(c.getContainerID(), c); } }); maxContainer = containerMap.size(); } eventQueue.addHandler(SCMEvents.NODE_REGISTRATION_CONT_REPORT, this); }</code><technical_language>FFT: Guava preconditions improve readability here</technical_language>

Target:
public ContainerChillModeRule(String ruleName, EventQueue eventQueue, Configuration conf, List<ContainerInfo> containers, SCMChillModeManager manager) { super(manager, ruleName, eventQueue); chillModeCutoff = conf.getDouble( HddsConfigKeys.HDDS_SCM_CHILLMODE_THRESHOLD_PCT, HddsConfigKeys.HDDS_SCM_CHILLMODE_THRESHOLD_PCT_DEFAULT); Preconditions.checkArgument( (chillModeCutoff >= 0.0 && chillModeCutoff <= 1.0), HddsConfigKeys.HDDS_SCM_CHILLMODE_THRESHOLD_PCT + " value should be >= 0.0 and <= 1.0"); containerMap = new ConcurrentHashMap<>(); if(containers != null) { containers.forEach(c -> { if (c != null && c.getState() != null && !c.getState().equals(HddsProtos.LifeCycleState.OPEN)) { containerMap.put(c.getContainerID(), c); } }); maxContainer = containerMap.size(); } }
Source:
<code>public String call(SQLDatabase db) throws Exception { Cursor cursor = null; try { cursor = db.rawQuery("SELECT value FROM info WHERE key='publicUUID'", null); if (cursor.moveToFirst()) { return "touchdb_" + cursor.getString(0); } else { throw new IllegalStateException("Error querying PublicUUID, " + <START> "it is probably because the sqlDatabase is not probably " + <END> "initialized."); } } finally { DatabaseUtils.closeCursorQuietly(cursor); } }</code><technical_language>Change ...sqlDatabase is properly..</technical_language>

Target:
public String call(SQLDatabase db) throws Exception { Cursor cursor = null; try { cursor = db.rawQuery("SELECT value FROM info WHERE key='publicUUID'", null); if (cursor.moveToFirst()) { return "touchdb_" + cursor.getString(0); } else { throw new IllegalStateException("Error querying PublicUUID, " + "it is probably because the sqlDatabase is not properly " + "initialized."); } } finally { DatabaseUtils.closeCursorQuietly(cursor); } }
Source:
<code>public void after() throws Exception { String output = docker.exec(options("-T"), "geode", arguments("cat", "server-dolores/server-dolores.log")); <START> System.out.println("Server log file--------------------------------\n" + output); <END> if (cache != null) { cache.close(); } }</code><technical_language>do need this log in test output</technical_language>

Target:
public void after() throws Exception { if (cache != null) { cache.close(); } }
Source:
<code>public List<CinderVolumeType> getVolumeTypes() { ArrayList<CinderVolumeType> cinderVolumeTypes = new ArrayList<>(); OpenStackRequest<VolumeTypes> listRequest = getClient(getTenantId()).volumeTypes().list(); VolumeTypes volumeTypes = listRequest.execute(); for (VolumeType volumeType : volumeTypes) { CinderVolumeType cinderVolumeType = new CinderVolumeType(); cinderVolumeType.setId(volumeType.getId()); cinderVolumeType.setName(volumeType.getName()); <START> cinderVolumeType.setExtraSpecs(volumeType.getExtraSpecs()); <END> cinderVolumeTypes.add(cinderVolumeType); } return cinderVolumeTypes; }</code><technical_language>nice if a ctor for of properties</technical_language>

Target:
public List<CinderVolumeType> getVolumeTypes() { ArrayList<CinderVolumeType> cinderVolumeTypes = new ArrayList<>(); OpenStackRequest<VolumeTypes> listRequest = getClient(getTenantId()).volumeTypes().list(); VolumeTypes volumeTypes = listRequest.execute(); for (VolumeType volumeType : volumeTypes) { CinderVolumeType cinderVolumeType = new CinderVolumeType( volumeType.getId(), volumeType.getName(), volumeType.getExtraSpecs()); cinderVolumeTypes.add(cinderVolumeType); } return cinderVolumeTypes; }
Source:
<code>public void testExecutePrimaryKeyLookupQuery() throws Exception { indexType2TweeterDocuments(); final Table table = dataContext.getDefaultSchema().getTableByName(DEFAULT_TABLE_NAME); <START> final Column[] pks = table.getPrimaryKeys().toArray(new Column[0]); <END> try (DataSet ds = dataContext.query().from(table).selectAll().where(pks[0]).eq("tweet_tweet2_1").execute()) { assertTrue(ds.next()); final Object dateValue = ds.getRow().getValue(1); assertEquals("Row[values=[tweet_tweet2_1, " + dateValue + ", 1, user1]]", ds.getRow().toString()); assertFalse(ds.next()); assertEquals(InMemoryDataSet.class, ds.getClass()); } }</code><technical_language>Please a name (primaryKeys, primaryKeyColumns)</technical_language>

Target:
public void testExecutePrimaryKeyLookupQuery() throws Exception { indexType2TweeterDocuments(); final Table table = dataContext.getDefaultSchema().getTableByName(DEFAULT_TABLE_NAME); final Column[] primaryKeys = table.getPrimaryKeys().toArray(new Column[0]); try (final DataSet dataSet = dataContext .query() .from(table) .selectAll() .where(primaryKeys[0]) .eq("tweet_tweet2_1") .execute()) { assertTrue(dataSet.next()); final Object dateValue = dataSet.getRow().getValue(1); assertEquals("Row[values=[tweet_tweet2_1, " + dateValue + ", 1, user1]]", dataSet.getRow().toString()); assertFalse(dataSet.next()); assertEquals(InMemoryDataSet.class, dataSet.getClass()); } }
Source:
<code>private boolean userHasNoWorkspaces() { boolean userHasNoWorkspaces = false; String userId = getSessionUserIdOrUndefined(); if (!"undefined".equals(userId)) { try { Page<WorkspaceImpl> workspaces = workspaceManager.getWorkspaces(userId, false, 30, 0); if (workspaces.isEmpty()) { log.debug("User '{}' has no more workspaces left", userId); <START> userHasNoWorkspaces = true; <END> } } catch (ServerException e) { log.error( "Unable to get the number of workspaces for user '{}'. Cause: {}", userId, e.getMessage(), e); } } return userHasNoWorkspaces; }</code><technical_language>Personally I prefer early return java private boolean userHasNoWorkspaces() { String userId = getSessionUserIdOrUndefined(); if (!"undefined".equals(userId)) { try { Page<WorkspaceImpl> workspaces = workspaceManager.getWorkspaces(userId, false, 1, 0); if (workspaces.isEmpty()) { log.debug("User '{}' more workspaces left", userId); return true; } } catch (ServerException e) { log.error( "Unable get number of workspaces for user '{}'. Cause: {}", userId, e.getMessage(), e); } } return false; } Also, I need fetch 30 workspaces, enough</technical_language>

Target:
private boolean userHasNoWorkspaces() { String userId = getSessionUserIdOrUndefined(); if (!"undefined".equals(userId)) { try { Page<WorkspaceImpl> workspaces = workspaceManager.getWorkspaces(userId, false, 1, 0); if (workspaces.isEmpty()) { log.debug("User '{}' has no more workspaces left", userId); return true; } } catch (ServerException e) { log.error( "Unable to get the number of workspaces for user '{}'. Cause: {}", userId, e.getMessage(), e); } } return false; }
Source:
<code>default Collection<String> eventsNetworkSend() { <START> return Collections.singleton("net_dev_queue"); END> }</code><technical_language>This create a new set time method is called. define statically return it, set is used: private static final Collection<String> EVENTS_NETWORK_SEND = Collections.singleton("net_dev_queue"); ... default default Collection<String> eventsNetworkSend() { return EVENTS_NETWORK_SEND; }</technical_language>

Target:
default Collection<String> eventsNetworkSend() { return Collections.EMPTY_SET; }
Source:
<code>public void checkWrite(Object key) { <START> log.tracef("Check write for key=%s, status=%s", key, state); <END> if (state == PartitionState.AVAILABLE) return; if (state == PartitionState.UNAVAILABLE) throw new AvailabilityException("Cluster is UNAVAILABLE because of node failures."); List<Address> owners = distributionManager.locate(key); if (! rpcManager.getTransport().getMembers().containsAll(owners)) { log.tracef("Partition is in %s mode, access is not allowed for key %s", state, key); throw new AvailabilityException("Not all owners of key '" + key + "' are in this partition"); } else { log.tracef("Key %s is writable.", key); } }</code><technical_language>surround isTraceEnabled</technical_language>

Target:
public void checkWrite(Object key) { doCheck(key); }
Source:
<code>static <T> Try<T> ofCallable(Callable<? extends T> callable) { <START> return of(callable::call); <END> }</code><technical_language>java Objects.requireNonNull(callable, "callable is null");</technical_language>

Target:
static <T> Try<T> ofCallable(Callable<? extends T> callable) { Objects.requireNonNull(callable, "callable is null"); return of(callable::call); }
Source:
<code>protected void executeRuntimeStep(final OperationContext context, final ModelNode operation) throws OperationFailedException { ModifiableKeyStoreService keyStoreService = getModifiableKeyStoreService(context); KeyStore keyStore = keyStoreService.getModifiableValue(); String alias = ALIAS.resolveModelAttribute(context, operation).asString(); String path = PATH.resolveModelAttribute(context, operation).asString(); String relativeTo = RELATIVE_TO.resolveModelAttribute(context, operation).asStringOrNull(); PathResolver pathResolver = pathResolver(); File resolvedPath = ((KeyStoreService) keyStoreService).getResolvedPath(pathResolver, path, relativeTo); boolean pem = PEM.resolveModelAttribute(context, operation).asBoolean(); try { if (! keyStore.containsAlias(alias)) { throw ROOT_LOGGER.keyStoreAliasDoesNotExist(alias); } final X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); if (certificate == null) { throw ROOT_LOGGER.unableToObtainCertificate(alias); } try (FileOutputStream fos = new FileOutputStream(resolvedPath)) { if (pem) { ByteStringBuilder pemCertificate = new ByteStringBuilder(); Pem.generatePemX509Certificate(pemCertificate, certificate); fos.write(pemCertificate.toArray()); } else { fos.write(certificate.getEncoded()); } } } catch (Exception e) { if (e instanceof OperationFailedException) { throw (OperationFailedException) e; } else { <START> throw new OperationFailedException(e); <END> } } }</code><technical_language>more time. :)</technical_language>

Target:
protected void executeRuntimeStep(final OperationContext context, final ModelNode operation) throws OperationFailedException { ModifiableKeyStoreService keyStoreService = getModifiableKeyStoreService(context); KeyStore keyStore = keyStoreService.getModifiableValue(); String alias = ALIAS.resolveModelAttribute(context, operation).asString(); String path = PATH.resolveModelAttribute(context, operation).asString(); String relativeTo = RELATIVE_TO.resolveModelAttribute(context, operation).asStringOrNull(); PathResolver pathResolver = pathResolver(); File resolvedPath = ((KeyStoreService) keyStoreService).getResolvedPath(pathResolver, path, relativeTo); boolean pem = PEM.resolveModelAttribute(context, operation).asBoolean(); try { if (! keyStore.containsAlias(alias)) { throw ROOT_LOGGER.keyStoreAliasDoesNotExist(alias); } final X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); if (certificate == null) { throw ROOT_LOGGER.unableToObtainCertificate(alias); } try (FileOutputStream fos = new FileOutputStream(resolvedPath)) { if (pem) { ByteStringBuilder pemCertificate = new ByteStringBuilder(); Pem.generatePemX509Certificate(pemCertificate, certificate); fos.write(pemCertificate.toArray()); } else { fos.write(certificate.getEncoded()); } } } catch (Exception e) { if (e instanceof OperationFailedException) { throw (OperationFailedException) e; } else { throw new RuntimeException(e); } } }
Source:
<code>public static Date lastModified(Resource resource) { if (resource != null) { try { <START> Value value = resource.adaptTo(Node.class).getProperty("cq:lastModified").getValue(); <END> return value.getDate().getTime(); } catch (RepositoryException e) { e.printStackTrace(); } } return new Date(); }</code><technical_language>resource.getValueMap().get(NameConstants.PN_LAST_MODIFIED, new Date()); safer? JCR APIs want guard non-existent properties prior else throw exception. Sling APIs happier</technical_language>

Target:
static Date lastModified(Resource resource) { if (resource != null) { return resource.getValueMap().get(NameConstants.PN_LAST_MOD, new Date()); } return new Date(); }
Source:
<code>protected Processor createLogger() throws Exception { Processor answer; CamelLogger camelLogger; LoggingLevel loggingLevel = LoggingLevel.INFO; if (level != null) { loggingLevel = LoggingLevel.valueOf(level); } if (providedLogger == null) { camelLogger = new CamelLogger(loggerName, loggingLevel, getMarker()); } else { camelLogger = new CamelLogger(providedLogger, loggingLevel, getMarker()); } if (getGroupSize() != null) { answer = new ThroughputLogger(camelLogger, getGroupSize()); } else if (getGroupInterval() != null) { Boolean groupActiveOnly = getGroupActiveOnly() != null ? getGroupActiveOnly() : Boolean.TRUE; Long groupDelay = getGroupDelay(); answer = new ThroughputLogger(camelLogger, this.getCamelContext(), getGroupInterval(), groupDelay, groupActiveOnly); } else { <START> CamelLogProcessor processor = new CamelLogProcessor(camelLogger, localFormatter, getMaskingFormatter()); <END> getCamelContext().getLogListeners().forEach(listener -> { if (listener != null) { processor.addLogListener(listener); } }); answer = processor; } setProcessor(answer); return answer; }</code><technical_language>add a ctr parameter takes Set<LogListener> call this instead of adding forEeach</technical_language>

Target:
protected Processor createLogger() throws Exception { Processor answer; CamelLogger camelLogger; LoggingLevel loggingLevel = LoggingLevel.INFO; if (level != null) { loggingLevel = LoggingLevel.valueOf(level); } if (providedLogger == null) { camelLogger = new CamelLogger(loggerName, loggingLevel, getMarker()); } else { camelLogger = new CamelLogger(providedLogger, loggingLevel, getMarker()); } if (getGroupSize() != null) { answer = new ThroughputLogger(camelLogger, getGroupSize()); } else if (getGroupInterval() != null) { Boolean groupActiveOnly = getGroupActiveOnly() != null ? getGroupActiveOnly() : Boolean.TRUE; Long groupDelay = getGroupDelay(); answer = new ThroughputLogger(camelLogger, this.getCamelContext(), getGroupInterval(), groupDelay, groupActiveOnly); } else { answer = new CamelLogProcessor(camelLogger, localFormatter, getMaskingFormatter(), getCamelContext().getLogListeners()); } setProcessor(answer); return answer; }
Source:
<code>public void register(ParseAuthenticationProvider provider) { <START> final String authType = provider.getAuthType(); <END> synchronized (lock) { if (authenticationProviders.containsKey(authType)) { throw new IllegalStateException("Another " + authType + " provider was already registered: " + authenticationProviders.get(authType)); } authenticationProviders.put(provider.getAuthType(), provider); } if (provider instanceof AnonymousAuthenticationProvider) { return; } controller.getAsync(false).onSuccess(new Continuation<ParseUser, Void>() { @Override public Void then(Task<ParseUser> task) throws Exception { ParseUser user = task.getResult(); if (user != null) { user.synchronizeAuthData(authType); } return null; } }); }</code><technical_language>add exception authType nil</technical_language>

Target:
public void register(ParseAuthenticationProvider provider) { final String authType = provider.getAuthType(); if (authType == null) { throw new IllegalArgumentException("Invalid authType: " + null); } synchronized (lock) { if (authenticationProviders.containsKey(authType)) { throw new IllegalStateException("Another " + authType + " provider was already registered: " + authenticationProviders.get(authType)); } authenticationProviders.put(provider.getAuthType(), provider); } if (provider instanceof AnonymousAuthenticationProvider) { return; } controller.getAsync(false).onSuccess(new Continuation<ParseUser, Void>() { @Override public Void then(Task<ParseUser> task) throws Exception { ParseUser user = task.getResult(); if (user != null) { user.synchronizeAuthData(authType); } return null; } }); }
Source:
<code>private static void createMarkers(IFile target, IStatus validationStatus, DiagramEditPart diagramEditPart) { if (validationStatus.isOK()) { return; } final IStatus rootStatus = validationStatus; List allStatuses = new ArrayList(); SiriusDiagramEditorUtil.LazyElement2ViewMap <START> element2ViewMap = <END> new SiriusDiagramEditorUtil.LazyElement2ViewMap(diagramEditPart.getDiagramView(), collectTargetElements(rootStatus, new HashSet(), allStatuses)); for (Iterator it = allStatuses.iterator(); it.hasNext();) { IConstraintStatus nextStatus = (IConstraintStatus) it.next(); DSemanticDecorator dSemanticDecorator = getDSemanticDecorator(nextStatus.getTarget(), diagramEditPart); if (dSemanticDecorator != null) { View view = SiriusGMFHelper.getGmfView(dSemanticDecorator); String qualifiedName = EMFCoreUtil.getQualifiedName(nextStatus.getTarget(), true); if (nextStatus instanceof RuleWrappingStatus) { createValidationRuleMarker((RuleWrappingStatus) nextStatus, diagramEditPart.getViewer(), target, view, qualifiedName, nextStatus.getMessage(), nextStatus.getSeverity()); } else { addMarker(diagramEditPart.getViewer(), target, view, qualifiedName, nextStatus.getMessage(), nextStatus.getSeverity()); } } } }</code><technical_language>"The of local variable element2ViewMap is used."</technical_language>

Target:
private static void createMarkers(IFile target, IStatus validationStatus, DiagramEditPart diagramEditPart) { if (validationStatus.isOK()) { return; } final IStatus rootStatus = validationStatus; List allStatuses = new ArrayList(); collectTargetElements(rootStatus, new HashSet(), allStatuses); for (Iterator it = allStatuses.iterator(); it.hasNext();) { IConstraintStatus nextStatus = (IConstraintStatus) it.next(); DSemanticDecorator dSemanticDecorator = getDSemanticDecorator(nextStatus.getTarget(), diagramEditPart); if (dSemanticDecorator != null) { View view = SiriusGMFHelper.getGmfView(dSemanticDecorator); String qualifiedName = EMFCoreUtil.getQualifiedName(nextStatus.getTarget(), true); if (nextStatus instanceof RuleWrappingStatus) { createValidationRuleMarker((RuleWrappingStatus) nextStatus, diagramEditPart.getViewer(), target, view, qualifiedName, nextStatus.getMessage(), nextStatus.getSeverity()); } else { addMarker(diagramEditPart.getViewer(), target, view, qualifiedName, nextStatus.getMessage(), nextStatus.getSeverity()); } } } }
Source:
<code>public List<ConditionImpl> getConditions() { <START> return conditions; <END> }</code><technical_language>(return copy)</technical_language>

Target:
public List<Condition> getConditions() { return conditions; }
Source:
<code>public ImmutableMap<K, V> getAllPresent(final Iterable<K> keys) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (K key : keys <START> ) { <END> V value = getIfPresent(key); if (value != null) { builder.put(key, value); } } return builder.build(); }</code><technical_language>formatting weird</technical_language>

Target:
public Map<K, V> getAllPresent(final Iterable<K> keys) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (K key : keys ) { V value = getIfPresent(key); if (value != null) { builder.put(key, value); } } return builder.build(); }
Source:
<code>public FormValidation doCheckAdminlist(@QueryParameter String value) throws ServletException { <START> for (String admin : value.split("\\s")) { <END> if (!admin.trim().isEmpty() && !adminlistPattern.matcher(admin).matches()) { return FormValidation.error("GitHub username may only contain alphanumeric characters or dashes " + "and cannot begin with a dash. Separate them with whitespaces."); } } return FormValidation.ok(); }</code><technical_language>This line is ultimately concern. I some users want enter newline characters whitespace. need catch in form validation. want a test for that. sense</technical_language>

Target:
public FormValidation doCheckAdminlist(@QueryParameter String value) throws ServletException { for (String admin : value.split("\\p{Space}")) { if (!admin.trim().isEmpty() && !adminlistPattern.matcher(admin).matches()) { return FormValidation.error("GitHub username may only contain alphanumeric characters or dashes " + "and cannot begin with a dash. Separate them with whitespaces."); } } return FormValidation.ok(); }