auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected List<String> getPropertiesToFetch() { Set<String> fetched = ctx.getFetched(ENTITY_TYPE); List<String> propertiesToFetch = DEFAULT_PROPERTIES.stream() .filter(fetched::contains) .collect(Collectors.toList()); propertiesToFetch = propertiesToFetch.isEmpty() ? DEFAULT_PROPERTIES : propertiesToFetch; <START> return propertiesToFetch; <END> }</code><technical_language>be: suggestion return propertiesToFetch.isEmpty() ? DEFAULT_PROPERTIES : propertiesToFetch;</technical_language>

Target:
protected List<String> getPropertiesToFetch() { Set<String> fetched = ctx.getFetched(ENTITY_TYPE); List<String> propertiesToFetch = DEFAULT_PROPERTIES.stream() .filter(fetched::contains) .collect(Collectors.toList()); return propertiesToFetch.isEmpty() ? DEFAULT_PROPERTIES : propertiesToFetch; }
Source:
<code>private void shiftBaseTemplateToSuccessor() { try { <START> getVmTemplateDao().shiftBaseTemplate(getVmTemplateId()); <END> } finally { freeSubTemplatesLock(); } }</code><technical_language>checkstyle</technical_language>

Target:
private void shiftBaseTemplateToSuccessor() { try { getVmTemplateDao().shiftBaseTemplate(getVmTemplateId()); } finally { freeSubTemplateLock(); } }
Source:
<code>public void testNumericDimensionTopNWithNullPreviousStop() { TopNQuery query = new TopNQueryBuilder() .dataSource(QueryRunnerTestHelper.dataSource) .granularity(QueryGranularities.ALL) .dimension(QueryRunnerTestHelper.marketDimension) .metric(new DimensionTopNMetricSpec(null, StringComparators.NUMERIC)) .threshold(2) .intervals(QueryRunnerTestHelper.secondOnly) .aggregators(duplicateAggregators( QueryRunnerTestHelper.rowsCount, <START> new CountAggregatorFactory("rows1", "rows") <END> )) .build(); List<Result<TopNResultValue>> expectedResults = Arrays.asList( new Result<>( new DateTime("2011-04-02T00:00:00.000Z"), new TopNResultValue( withDuplicateResults( Arrays.asList( ImmutableMap.<String, Object>of( "market", "spot", "rows", 9L ), ImmutableMap.<String, Object>of( "market", "total_market", "rows", 2L ) ), "rows", "rows1" ) ) ) ); TestHelper.assertExpectedResults(expectedResults, runner.run(query, new HashMap<String, Object>())); }</code><technical_language>I simply changing name rows rows1 work. changes in CountAggregatorFactory necessary</technical_language>

Target:
public void testNumericDimensionTopNWithNullPreviousStop() { TopNQuery query = new TopNQueryBuilder() .dataSource(QueryRunnerTestHelper.dataSource) .granularity(Granularities.ALL) .dimension(QueryRunnerTestHelper.marketDimension) .metric(new DimensionTopNMetricSpec(null, StringComparators.NUMERIC)) .threshold(2) .intervals(QueryRunnerTestHelper.secondOnly) .aggregators(duplicateAggregators( QueryRunnerTestHelper.rowsCount, new CountAggregatorFactory("rows1") )) .build(); List<Result<TopNResultValue>> expectedResults = Arrays.asList( new Result<>( new DateTime("2011-04-02T00:00:00.000Z"), new TopNResultValue( withDuplicateResults( Arrays.asList( ImmutableMap.<String, Object>of( "market", "spot", "rows", 9L ), ImmutableMap.<String, Object>of( "market", "total_market", "rows", 2L ) ), "rows", "rows1" ) ) ) ); TestHelper.assertExpectedResults(expectedResults, runner.run(query, new HashMap<String, Object>())); }
Source:
<code>public ArrayLiteralTreeImpl(List<Tree> elementsAndCommas) { this.elementsAndCommas = elementsAndCommas; <START> this.elements = getExpressionTrees(elementsAndCommas); <END> }</code><technical_language>@vilchik-elena another approach: ImmutableList.copyOf(Iterables.filter(elementsAndCommas, ExpressionTree.class))</technical_language>

Target:
public ArrayLiteralTreeImpl(List<Tree> elementsAndCommas) { this.elementsAndCommas = elementsAndCommas; this.elements = ImmutableList.copyOf(Iterables.filter(elementsAndCommas, ExpressionTree.class)); }
Source:
<code>private void reportInstanceCapacityMetrics(ClusterStatusMonitor clusterStatusMonitor, ResourceControllerDataProvider dataProvider, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { asyncExecute(dataProvider.getAsyncTasksThreadPool(), () -> { try { Map<String, IdealState> idealStateMap = dataProvider.getIdealStates(); <START> Map<String, Resource> metricResourceMap = resourceMap.entrySet().stream() <END> .filter(resourceName -> idealStateMap.containsKey(resourceName)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<String, ResourceAssignment> currentStateAssignment = currentStateOutput.getAssignment(metricResourceMap.keySet()); ClusterModel clusterModel = ClusterModelProvider.generateClusterModelFromCurrentState( dataProvider, metricResourceMap, currentStateAssignment); Map<String, Double> maxUsageMap = new HashMap<>(); for (AssignableNode node : clusterModel.getAssignableNodes().values()) { String instanceName = node.getInstanceName(); double usage = node.getProjectedHighestUtilization(Collections.emptyMap()); maxUsageMap.put(instanceName, usage); } clusterStatusMonitor.updateInstanceMaxUsage(maxUsageMap); } catch (Exception ex) { LOG.error("Failed to report instance capacity metrics.", ex); } return null; }); }</code><technical_language>resourceToMonitorMap</technical_language>

Target:
private void reportInstanceCapacityMetrics(ClusterStatusMonitor clusterStatusMonitor, ResourceControllerDataProvider dataProvider, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { asyncExecute(dataProvider.getAsyncTasksThreadPool(), () -> { try { Map<String, IdealState> idealStateMap = dataProvider.getIdealStates(); Map<String, Resource> resourceToMonitorMap = resourceMap.entrySet().stream() .filter(resourceName -> idealStateMap.containsKey(resourceName)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<String, ResourceAssignment> currentStateAssignment = currentStateOutput.getAssignment(resourceToMonitorMap.keySet()); ClusterModel clusterModel = ClusterModelProvider.generateClusterModelFromCurrentState( dataProvider, resourceToMonitorMap, currentStateAssignment); Map<String, Double> maxUsageMap = new HashMap<>(); for (AssignableNode node : clusterModel.getAssignableNodes().values()) { String instanceName = node.getInstanceName(); double usage = node.getProjectedHighestUtilization(Collections.emptyMap()); maxUsageMap.put(instanceName, usage); } clusterStatusMonitor.updateInstanceMaxUsage(maxUsageMap); } catch (Exception ex) { LOG.error("Failed to report instance capacity metrics.", ex); } return null; }); }
Source:
<code>public void test() { connect(); JQuery jqTrack = jq(".z-multislider-track"); getActions().moveToElement(toElement(jqTrack)) .moveByOffset(jqTrack.width() / 2 - 2, 0) .click() .perform(); waitResponse(); <START> assertEquals(jqTrack.width() + "px", jq("@multislider .z-sliderbuttons-button").eq(1).css("left")); <END> jqTrack = jq(".z-rangeslider-track"); getActions().moveToElement(toElement(jqTrack)) .moveByOffset(jqTrack.width() / 2 - 2, 0) .click() .perform(); waitResponse(); assertEquals(jqTrack.width() + "px", jq("@rangeslider .z-sliderbuttons-button").eq(1).css("left")); }</code><technical_language>positionLeft()</technical_language>

Target:
public void test() { connect(); JQuery jqTrack = jq(".z-multislider-track"); getActions().moveToElement(toElement(jqTrack)) .moveByOffset(jqTrack.width() / 2 - 1, 0) .click() .perform(); waitResponse(); assertEquals(jqTrack.width(), jq("@multislider .z-sliderbuttons-button").eq(1).positionLeft()); jqTrack = jq(".z-rangeslider-track"); getActions().moveToElement(toElement(jqTrack)) .moveByOffset(jqTrack.width() / 2 - 1, 0) .click() .perform(); waitResponse(); assertEquals(jqTrack.width(), jq("@rangeslider .z-sliderbuttons-button").eq(1).positionLeft()); }
Source:
<code>public Mono<DataLakeFileAsyncClient> createFile(String fileName) { try { return createFile(fileName, false); <START> } catch (RuntimeException ex) { <END> return monoError(logger, ex); } }</code><technical_language>Do need duplicate catching RuntimeException in overload</technical_language>

Target:
public Mono<DataLakeFileAsyncClient> createFile(String fileName) { return createFile(fileName, false); }
Source:
<code>private void startFolderMonitor() { if (serverConfiguration.getAppFolderToMonitor() != null) { try { folderMonitor = new FolderMonitor(this); folderMonitor.start(); } catch (Exception e) { <START> log.warning("Couldn't monitor the given folder: " <END> + serverConfiguration.getAppFolderToMonitor()); } } }</code><technical_language>Do need catch Exception vs. a sub-class of Exception? error message include exception message</technical_language>

Target:
private void startFolderMonitor() { if (serverConfiguration.getAppFolderToMonitor() != null) { try { folderMonitor = new FolderMonitor(this, serverConfiguration); folderMonitor.start(); } catch (IOException e) { log.warning("Could not monitor the given folder: " + serverConfiguration.getAppFolderToMonitor()); } } }
Source:
<code><START> public static double[][] parseShifts(String filename, double scaling) throws IOException { <END> ArrayList<double[]> list = new ArrayList<>(); double[][] shift; try (CSVReader reader = getCSVReader(filename)) { String[] line; while ((line = reader.readNext()) != null) { double[] lineDouble = new double[line.length]; for (int loopc = 0; loopc < line.length; loopc++) { lineDouble[loopc] = Double.parseDouble(line[loopc]) * scaling; } list.add(lineDouble); } shift = list.toArray(new double[0][0]); } return shift; }</code><technical_language>Check Args</technical_language>

Target:
public static double[][] parseShifts(String filename, double scaling) throws IOException { ArgumentChecker.notNull(filename, "fine name"); ArrayList<double[]> list = new ArrayList<>(); double[][] shift; try (CSVReader reader = getCSVReader(filename)) { String[] line; while ((line = reader.readNext()) != null) { double[] lineDouble = new double[line.length]; for (int loopc = 0; loopc < line.length; loopc++) { lineDouble[loopc] = Double.parseDouble(line[loopc]) * scaling; } list.add(lineDouble); } shift = list.toArray(new double[0][0]); } return shift; }
Source:
<code>public Indexed<Long> getSortedIndexedValues() { <START> return null; <END> }</code><technical_language>Is this expected called? If so, throw UnsupportedOperationException return null</technical_language>

Target:
public Indexed<Long> getSortedIndexedValues() { throw new UnsupportedOperationException("Numeric columns do not support value dictionaries."); }
Source:
<code>public RunGnuplot(final HttpQuery query, final int max_age, final Plot plot, final String basepath, final HashSet<String>[] aggregated_tags, final int npoints) { this.query = query; this.max_age = max_age; this.plot = plot; <START> if (System.getProperty("os.name").contains("Windows")) <END> this.basepath = basepath.replace("\\", "\\\\").replace("/", "\\\\"); else this.basepath = basepath; this.aggregated_tags = aggregated_tags; this.npoints = npoints; }</code><technical_language>this possibly change while JVM is running, please this a static const evaluate this condition time this code. JVM able optimize out branch executed</technical_language>

Target:
public RunGnuplot(final HttpQuery query, final int max_age, final Plot plot, final String basepath, final HashSet<String>[] aggregated_tags, final int npoints) { this.query = query; this.max_age = max_age; this.plot = plot; if (IS_WINDOWS) this.basepath = basepath.replace("\\", "\\\\").replace("/", "\\\\"); else this.basepath = basepath; this.aggregated_tags = aggregated_tags; this.npoints = npoints; }
Source:
<code>public XpathFilter(String files, String checks, String moduleId, String query) { filePattern = files; fileRegexp = Pattern.compile(files); checkPattern = checks; if (checks == null) { checkRegexp = null; } else { checkRegexp = CommonUtils.createPattern(checks); } this.moduleId = moduleId; xpathQuery = query; if (xpathQuery == null) { xpathExpression = null; } else { final XPathEvaluator xpathEvaluator = new XPathEvaluator(); try { xpathExpression = xpathEvaluator.createExpression(xpathQuery); } catch (XPathException ex) { <START> throw new IllegalStateException("Unexpected xpath query", ex); <END> } } }</code><technical_language>if exception is rethrown, local context collected exception: throw new IllegalStateException("Unexpected xpath query: " + xpathQuery, ex); is guaranty exception print it</technical_language>

Target:
public XpathFilter(String files, String checks, String moduleId, String query) { filePattern = files; fileRegexp = Pattern.compile(files); checkPattern = checks; if (checks == null) { checkRegexp = null; } else { checkRegexp = CommonUtils.createPattern(checks); } this.moduleId = moduleId; xpathQuery = query; if (xpathQuery == null) { xpathExpression = null; } else { final XPathEvaluator xpathEvaluator = new XPathEvaluator(); try { xpathExpression = xpathEvaluator.createExpression(xpathQuery); } catch (XPathException ex) { throw new IllegalStateException("Unexpected xpath query: " + xpathQuery, ex); } } }
Source:
<code>private static void maybeShowTranslateDescriptionUnlockNotification(@NonNull Context context) { if (!WikipediaApp.getInstance().isAnyActivityResumed()) { Intent intent = AddTitleDescriptionsActivity.Companion.newIntent(context, Constants.InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC); NotificationCompat.Builder builder = NotificationPresenter.getDefaultBuilder(context); PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); <START> builder.addAction(0, context.getString(R.string.title_description_get_started), pendingIntent); <END> NotificationPresenter.showNotification(context, 0, context.getString(R.string.translation_description_edit_task_unlock_title), context.getString(R.string.translation_description_edit_task_unlock_body), context.getString(R.string.translation_description_edit_task_unlock_body), R.drawable.ic_mode_edit_white_24dp, R.color.accent50, intent); } }</code><technical_language>Noticed builder NotificationPresenter.showNotification()</technical_language>

Target:
private static void maybeShowTranslateDescriptionUnlockNotification(@NonNull Context context) { if (!WikipediaApp.getInstance().isAnyActivityResumed()) { Intent intent = AddTitleDescriptionsActivity.Companion.newIntent(context, Constants.InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC); NotificationCompat.Builder builder = NotificationPresenter.getDefaultBuilder(context); PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(0, context.getString(R.string.title_description_get_started), pendingIntent); NotificationPresenter.showNotification(context, builder, 0, context.getString(R.string.translation_description_edit_task_unlock_title), context.getString(R.string.translation_description_edit_task_unlock_body), context.getString(R.string.translation_description_edit_task_unlock_body), R.drawable.ic_mode_edit_white_24dp, R.color.accent50, intent); } }
Source:
<code>boolean cleanupOnError(Throwable e, boolean diagActive) { if (SanityManager.DEBUG) SanityManager.ASSERT(cm != null, "cannot cleanup on error with null context manager"); <START> return cm.cleanupOnError(e, diagActive); <END> }</code><technical_language>@dgomezferro mentioned csf.removeContext(cm) is called function cleanupOnError() removed here, I find caller cleanupOnError(), point code</technical_language>

Target:
boolean cleanupOnError(Throwable e, boolean diagActive) { if (SanityManager.DEBUG) SanityManager.ASSERT(cm != null, "cannot cleanup on error with null context manager"); boolean result = cm.cleanupOnError(e, diagActive); csf.removeContext(cm); return result; }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { <START> <END> if (networkExists()) { return Collections.singletonList(new PermissionSubject(getParameters().getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.CONFIGURE_CLUSTER_NETWORK)); } else { Guid networkId = getParameters().getNetwork() == null ? null : getParameters().getNetwork().getId(); return Collections.singletonList(new PermissionSubject(networkId, VdcObjectType.Network, getActionType().getActionGroup())); } }</code><technical_language>I if network exist able edit (attach) parameters if permission network if permission cluster</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { Guid networkId = getParameters().getNetwork() == null ? null : getParameters().getNetwork().getId(); return Collections.singletonList(new PermissionSubject(networkId, VdcObjectType.Network, getActionType().getActionGroup())); }
Source:
<code>private void notifyError(final GraphError error) { if (httpCall.isCanceled()) { return; } Runnable action = () -> { <START> if (error instanceof GraphNetworkError) { <END> graphCallback.onNetworkError((GraphNetworkError) error); } else if (error instanceof GraphHttpError) { graphCallback.onHttpError((GraphHttpError) error); } else if (error instanceof GraphParseError) { graphCallback.onParseError((GraphParseError) error); } else { graphCallback.onFailure(error); } }; if (handler != null) { handler.post(action); } else { action.run(); } }</code><technical_language>Is worthwhile break this out error type? end is calling callback.onFailure() anyway, missing this PR</technical_language>

Target:
private void notifyError(final GraphError error) { Runnable action = () -> graphCallback.onFailure(error); if (handler != null) { handler.post(action); } else { action.run(); } }
Source:
<code>private void loadFrameWidgetFromURI(String fileName, final float duration) { <START> ApplicationAssets assets = controller.getApplicationAssets(); <END> assets.get(fileName, Texture.class, new AssetLoadedCallback<Texture>() { @Override public void loaded(String fileName, Texture asset) { Image image = new Image(); loadTextureIntoImage(asset, image); FrameWidget focusItem = new FrameWidget(image, controller); focusItem.setDuration(duration); addFocusItem(focusItem); } }); }</code><technical_language>AplicationAssets is load assets for application. In this case, frames for game, getEditorGameAssets</technical_language>

Target:
private void loadFrameWidgetFromURI(String fileName, final float duration) { EditorGameAssets assets = controller.getEditorGameAssets(); assets.get(fileName, Texture.class, new AssetLoadedCallback<Texture>() { @Override public void loaded(String fileName, Texture asset) { Image image = new Image(); loadTextureIntoImage(asset, image); FrameWidget focusItem = new FrameWidget(image, controller); focusItem.setDuration(duration); addFocusItem(focusItem); } }); }
Source:
<code>private MistTaskConfigs(@Parameter(NumTasks.class) final int numTasks, @Parameter(TaskMemorySize.class) final int taskMemSize, @Parameter(NumExecutors.class) final int numTaskExecutors, @Parameter(NumTaskCores.class) final int numTaskCores, @Parameter(RPCServerPort.class) final int rpcServerPort) { this.numTasks = numTasks; this.numTaskExecutors = numTaskExecutors; this.taskMemSize = taskMemSize; this.numTaskCores = numTaskCores; <START> this.rpcServerPort = rpcServerPort + 10; <END> }</code><technical_language>rpcServerPort a limitation maximum value, I check allocating port number</technical_language>

Target:
private MistTaskConfigs(@Parameter(NumTasks.class) final int numTasks, @Parameter(TaskMemorySize.class) final int taskMemSize, @Parameter(NumExecutors.class) final int numTaskExecutors, @Parameter(NumTaskCores.class) final int numTaskCores, @Parameter(RPCServerPort.class) final int rpcServerPort) { this.numTasks = numTasks; this.numTaskExecutors = numTaskExecutors; this.taskMemSize = taskMemSize; this.numTaskCores = numTaskCores; this.rpcServerPort = rpcServerPort + 10 > MAX_PORT_NUM ? rpcServerPort - 10 : rpcServerPort + 10; }
Source:
<code>public boolean matchesSafely(Map<? extends K, ? extends V> map) { <START> return map.containsKey(key) && super.valueMatcher.matches(map.get(key)); <END> }</code><technical_language>maps allow null keys (stupidly) throw exception try check for existence. need account for here. suggestion try { return map.containsKey(key) && super.valueMatcher.matches(map.get(key)); catch (NullPointerException ex) { return false; }</technical_language>

Target:
public boolean matchesSafely(Map<? extends K, ? extends V> map) { try{ return map.containsKey(key) && super.valueMatcher.matches(map.get(key)); } catch (NullPointerException e){ return false; } }
Source:
<code>protected void doAsyncAddEntry(final PendingAddOp op) { if (throttler != null) { throttler.acquire(); } boolean wasClosed = false; synchronized (this) { if (metadata.isClosed()) { wasClosed = true; } else { long entryId = ++lastAddPushed; long currentLedgerLength = addToLength(op.payload.readableBytes()); op.setEntryId(entryId); op.setLedgerLength(currentLedgerLength); pendingAddOps.add(op); } } if (wasClosed) { try { bk.getMainWorkerPool().submit(new SafeRunnable() { @Override public void safeRun() { LOG.warn("Attempt to add to closed ledger: {}", ledgerId); op.cb.addComplete(BKException.Code.LedgerClosedException, LedgerHandle.this, INVALID_ENTRY_ID, op.ctx); } @Override public String toString() { return String.format("AsyncAddEntryToClosedLedger(lid=%d)", ledgerId); } }); } catch (RejectedExecutionException e) { op.cb.addComplete(bk.getReturnRc(BKException.Code.InterruptedException), LedgerHandle.this, INVALID_ENTRY_ID, op.ctx); } return; } if (!waitForWritable(distributionSchedule.getWriteSet(op.getEntryId()), op.getEntryId(), 0, waitForWriteSetMs)) { <START> op.allowFastFailOnBlockedServer(); <END> } try { bk.getMainWorkerPool().submitOrdered(ledgerId, op); } catch (RejectedExecutionException e) { op.cb.addComplete(bk.getReturnRc(BKException.Code.InterruptedException), LedgerHandle.this, INVALID_ENTRY_ID, op.ctx); } }</code><technical_language>I loved this logic channel/PCBC level. I live this. :)</technical_language>

Target:
protected void doAsyncAddEntry(final PendingAddOp op) { if (throttler != null) { throttler.acquire(); } boolean wasClosed = false; synchronized (this) { if (metadata.isClosed()) { wasClosed = true; } else { long entryId = ++lastAddPushed; long currentLedgerLength = addToLength(op.payload.readableBytes()); op.setEntryId(entryId); op.setLedgerLength(currentLedgerLength); pendingAddOps.add(op); } } if (wasClosed) { try { bk.getMainWorkerPool().submit(new SafeRunnable() { @Override public void safeRun() { LOG.warn("Attempt to add to closed ledger: {}", ledgerId); op.cb.addCompleteWithLatency(BKException.Code.LedgerClosedException, LedgerHandle.this, INVALID_ENTRY_ID, 0, op.ctx); } @Override public String toString() { return String.format("AsyncAddEntryToClosedLedger(lid=%d)", ledgerId); } }); } catch (RejectedExecutionException e) { op.cb.addCompleteWithLatency(bk.getReturnRc(BKException.Code.InterruptedException), LedgerHandle.this, INVALID_ENTRY_ID, 0, op.ctx); } return; } DistributionSchedule.WriteSet ws = distributionSchedule.getWriteSet(op.getEntryId()); try { if (!waitForWritable(ws, op.getEntryId(), 0, waitForWriteSetMs)) { op.allowFailFastOnUnwritableChannel(); } } finally { ws.recycle(); } try { bk.getMainWorkerPool().executeOrdered(ledgerId, op); } catch (RejectedExecutionException e) { op.cb.addCompleteWithLatency(bk.getReturnRc(BKException.Code.InterruptedException), LedgerHandle.this, INVALID_ENTRY_ID, 0, op.ctx); } }
Source:
<code><START> @Test public void testToAscii() throws UnsupportedEncodingException { <END> String s = "h\u00E9h\u00E9"; assertEquals("hehe", StringUtils.toAscii(s)); }</code><technical_language>Please put @Test line above, line</technical_language>

Target:
public void testToAscii() throws UnsupportedEncodingException { String s = "h\u00E9h\u00E9"; assertEquals("hehe", StringUtils.toAscii(s)); }
Source:
<code>public List<List<Double>> getJointOfForwardsAndBackwards(final ImmutableList<Integer> events) { UnmodifiableListIterator<Integer> iterator = events.listIterator(events.size()); <START> List<Integer> backwardsEvents = Lists.newArrayList(); <END> while (iterator.hasPrevious()) { backwardsEvents.add(iterator.previous()); } final List<List<Double>> forwardProbs = getProbsFromEventSequence(events); final List<List<Double>> backwardProbs = getProbsFromEventSequence(ImmutableList.copyOf(backwardsEvents)); final List<List<Double>> joints = Lists.newArrayList(); for (int iTimeForward = 0; iTimeForward < forwardProbs.size(); iTimeForward++) { final int iTimeBackward = forwardProbs.size() - iTimeForward - 1; final List<Double> forwardProb = forwardProbs.get(iTimeForward); final List<Double> backwardProb = backwardProbs.get(iTimeBackward); final List<Double> joint = Lists.newArrayList(); for (int iState = 0; iState < forwardProb.size(); iState++) { joint.add(forwardProb.get(iState) * backwardProb.get(iState)); } joints.add(joint); } return joints; }</code><technical_language>final</technical_language>

Target:
public List<List<Double>> getJointOfForwardsAndBackwards(final ImmutableList<Integer> events) { final UnmodifiableListIterator<Integer> iterator = events.listIterator(events.size()); final List<Integer> backwardsEvents = Lists.newArrayList(); while (iterator.hasPrevious()) { backwardsEvents.add(iterator.previous()); } final List<List<Double>> forwardProbs = getProbsFromEventSequence(events); final List<List<Double>> backwardProbs = getProbsFromEventSequence(ImmutableList.copyOf(backwardsEvents)); final List<List<Double>> joints = Lists.newArrayList(); for (int iTimeForward = 0; iTimeForward < forwardProbs.size(); iTimeForward++) { final int iTimeBackward = forwardProbs.size() - iTimeForward - 1; final List<Double> forwardProb = forwardProbs.get(iTimeForward); final List<Double> backwardProb = backwardProbs.get(iTimeBackward); final List<Double> joint = Lists.newArrayList(); for (int iState = 0; iState < forwardProb.size(); iState++) { joint.add(forwardProb.get(iState) * backwardProb.get(iState)); } joints.add(joint); } return joints; }
Source:
<code>public Ample.TabletMutator putBulkFile(Ample.FileMeta bulkref, long tid) { Preconditions.checkState(updatesEnabled, "Cannot make updates after calling mutate."); <START> Value tidBytes = new Value(Long.toString(tid).getBytes()); <END> mutation.put(TabletsSection.BulkFileColumnFamily.NAME, bulkref.meta(), tidBytes); return this; }</code><technical_language>constructor takes String</technical_language>

Target:
public Ample.TabletMutator putBulkFile(Ample.FileMeta bulkref, long tid) { Preconditions.checkState(updatesEnabled, "Cannot make updates after calling mutate."); mutation.put(TabletsSection.BulkFileColumnFamily.NAME, bulkref.meta(), new Value(Long.toString(tid))); return this; }
Source:
<code><START> public void explicit_static_method_call() { <END> Expression.Variable arg = UCFGBuilder.variableWithId("arg"); Expression.Variable var0 = UCFGBuilder.variableWithId("%0"); UCFG expectedUCFG = UCFGBuilder.createUCFGForMethod("A#method(Ljava/lang/Integer;)I").addMethodParam(arg) .addStartingBlock( newBasicBlock("1") .assignTo(var0, call("java.lang.String#valueOf(Ljava/lang/Object;)Ljava/lang/String;").withArgs(new Expression.ClassName("java.lang.String"), arg), new LocationInFile(FILE_KEY, 3,11,3,30)) .ret(constant("\"\""), new LocationInFile(FILE_KEY, 3,4,3,31))) .build(); assertCodeToUCfg("class A { \n" + " int method(Integer arg) {\n" + " return String.valueOf(arg);\n" + " }\n" + "}", expectedUCFG); }</code><technical_language>I tend testing else "java.lang.String" better. define static method of java.util.Objects maybe. Especially modification of other test</technical_language>

Target:
public void explicit_static_method_call() { Expression.Variable arg = UCFGBuilder.variableWithId("arg"); Expression.Variable aux0 = UCFGBuilder.variableWithId("%0"); UCFG expectedUCFG = UCFGBuilder.createUCFGForMethod("A#method(Ljava/lang/Integer;)Ljava/lang/String;") .addStartingBlock( newBasicBlock("1") .assignTo(aux0, call("java.util.Objects#toString(Ljava/lang/Object;)Ljava/lang/String;").withArgs(new Expression.ClassName("java.util.Objects"), arg), new LocationInFile(FILE_KEY, 3,11,3,42)) .ret(aux0, new LocationInFile(FILE_KEY, 3,4,3,43))) .build(); assertCodeToUCfg("class A { \n" + " String method(Integer arg) {\n" + " return java.util.Objects.toString(arg);\n" + " }\n" + "}", expectedUCFG); }
Source:
<code>public static <E, K, V> TCollector<E, ?, Map<K, V>> toMap(Function<? super E, ? extends K> keyMapper, Function<? super E, ? extends V> valueMapper) { return TCollector.of(HashMap::new, (map, el) -> { K k = keyMapper.apply(el); V newV = TObjects.requireNonNull(valueMapper.apply(el)); V oldV = map.putIfAbsent(k, newV); if (oldV != null) { throw new IllegalStateException( "Key " + k + " corresponds to values " + oldV + " and " + newV); } }, (m1, m2) -> { <START> m2.forEach((k, v) -> { <END> V newV = TObjects.requireNonNull(v); V oldV = m1.putIfAbsent(k, newV); if (oldV != null) { throw new IllegalStateException( "Key " + k + " corresponds to values " + oldV + " and " + newV); } }); return m1; }, TCollector.Characteristics.IDENTITY_FINISH); }</code><technical_language>for statement map entries forEach, forEach produces extra overhead</technical_language>

Target:
public static <E, K, V> TCollector<E, ?, Map<K, V>> toMap(Function<? super E, ? extends K> keyMapper, Function<? super E, ? extends V> valueMapper) { return TCollector.of(HashMap::new, (map, el) -> { K k = keyMapper.apply(el); V newV = TObjects.requireNonNull(valueMapper.apply(el)); V oldV = map.putIfAbsent(k, newV); if (oldV != null) { throw new IllegalStateException( "Key " + k + " corresponds to values " + oldV + " and " + newV); } }, (m1, m2) -> { for (Map.Entry<K, V> e : m2.entrySet()) { V newV = TObjects.requireNonNull(e.getValue()); V oldV = m1.putIfAbsent(e.getKey(), newV); if (oldV != null) { throw new IllegalStateException( "Key " + e.getKey() + " corresponds to values " + oldV + " and " + newV); } } return m1; }, TCollector.Characteristics.IDENTITY_FINISH); }
Source:
<code>public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { ScheduledFuture<?> future = welcomeFuture; <START> if (future != null && !future.isCancelled()) { <END> future.cancel(true); } ctx.close(); }</code><technical_language>this place need judge if a IdleStateEvent</technical_language>

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { ExecutorUtil.cancelScheduledFuture(welcomeFuture); ctx.close(); } }
Source:
<code>public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case STUDENT_SUBMISSION: case STUDENT_RESULT: StudentAttributes studentAttributes = getStudentOfCourseFromRequest(courseId); checkAccessControlForStudentFeedbackSubmission(studentAttributes, feedbackSession); break; case FULL_DETAIL: gateKeeper.verifyLoggedInUserPrivileges(); <START> gateKeeper.verifyAccessible(logic.getInstructorForGoogleId(courseId, userInfo.getId()), feedbackSession); <END> break; case INSTRUCTOR_SUBMISSION: InstructorAttributes instructorAttributes = getInstructorOfCourseFromRequest(courseId); checkAccessControlForInstructorFeedbackSubmission(instructorAttributes, feedbackSession); break; case INSTRUCTOR_RESULT: checkInstructorForSessionAccessPrivilege(feedbackSession); break; default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }</code><technical_language>update this well. This require MODIFY_SESSION privilege</technical_language>

Target:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case STUDENT_SUBMISSION: case STUDENT_RESULT: StudentAttributes studentAttributes = getStudentOfCourseFromRequest(courseId); checkAccessControlForStudentFeedbackSubmission(studentAttributes, feedbackSession); break; case FULL_DETAIL: gateKeeper.verifyLoggedInUserPrivileges(); gateKeeper.verifyAccessible(logic.getInstructorForGoogleId(courseId, userInfo.getId()), feedbackSession, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); break; case INSTRUCTOR_SUBMISSION: InstructorAttributes instructorAttributes = getInstructorOfCourseFromRequest(courseId); checkAccessControlForInstructorFeedbackSubmission(instructorAttributes, feedbackSession); break; case INSTRUCTOR_RESULT: gateKeeper.verifyLoggedInUserPrivileges(); gateKeeper.verifyAccessible(logic.getInstructorForGoogleId(courseId, userInfo.getId()), feedbackSession, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_SESSION_IN_SECTIONS); break; default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }
Source:
<code>public void setBitreserveRequestInterceptorWithNullTokenShouldSetTheBitreserveCustomHeadersWithoutAuthenticationHeader() throws Exception{ MockRestAdapter<Card> adapter = new MockRestAdapter<>(null, null, null); adapter.request(new RepromiseFunction<BitreserveRestAdapter, Card>() { @Override public Promise<Card> call(BitreserveRestAdapter adapter) { User user = Fixtures.loadUser(); user.setBitreserveRestAdapter(adapter); return user.getCardById("foobar"); } }); Request request = adapter.getRequest(); Assert.assertEquals(request.getHeaders().size(), 3); Assert.assertTrue(request.getHeaders().contains(new Header("Accept", "application/json"))); <START> Assert.assertFalse(request.getHeaders().contains(new Header("Authorization", "Basic Zm9vYmFyOlgtT0F1dGgtQmFzaWM="))); <END> Assert.assertTrue(request.getHeaders().contains(new Header("Content-Type", "application/json"))); Assert.assertTrue(request.getHeaders().contains(new Header("User-Agent", "bitreserve-android-sdk 0.1 (<LINK_0>"))); }</code><technical_language>This is unnecessary asserting 3 headers</technical_language>

Target:
public void setBitreserveRequestInterceptorWithNullTokenShouldSetTheBitreserveCustomHeadersWithoutAuthenticationHeader() throws Exception{ MockRestAdapter<Card> adapter = new MockRestAdapter<>(null, null, null); adapter.request(new RepromiseFunction<BitreserveRestAdapter, Card>() { @Override public Promise<Card> call(BitreserveRestAdapter adapter) { User user = Fixtures.loadUser(); user.setBitreserveRestAdapter(adapter); return user.getCardById("foobar"); } }); Request request = adapter.getRequest(); Assert.assertEquals(request.getHeaders().size(), 3); Assert.assertTrue(request.getHeaders().contains(new Header("Accept", "application/json"))); Assert.assertTrue(request.getHeaders().contains(new Header("Content-Type", "application/json"))); Assert.assertTrue(request.getHeaders().contains(new Header("User-Agent", "bitreserve-android-sdk 0.1 (<LINK_0>"))); }
Source:
<code>public static String getStudioName(final String inputString) { if (inputString == null || inputString.isEmpty()) { <START> return inputString; <END> } StringBuilder outputString = new StringBuilder(); for (int i = 0; i < inputString.length(); i++) { Character c = inputString.charAt(i); outputString.append(Character.isUpperCase(c) && i > 0 ? "_" + c : c); } return outputString.toString().toUpperCase(Locale.ENGLISH); }</code><technical_language>Null is a valid return</technical_language>

Target:
public static String getStudioName(final String inputString) { if (inputString == null || inputString.isEmpty()) { return ""; } StringBuilder outputString = new StringBuilder(); for (int i = 0; i < inputString.length(); i++) { Character c = inputString.charAt(i); outputString.append(Character.isUpperCase(c) && i > 0 ? "_" + c : c); } return outputString.toString().toUpperCase(Locale.ENGLISH); }
Source:
<code>public Void call() throws Exception { <START> ClientHttpResponse originalResponse = this.originalRequest.execute(); <END> try { LOGGER.debug("Caching URI resource " + this.originalRequest.getURI()); this.response = new CachedClientHttpResponse(originalResponse); } finally { originalResponse.close(); } return null; }</code><technical_language>sense set a timer get some metrics download times. Similar to: <LINK_0></technical_language>

Target:
public Void call() throws Exception { final String baseMetricName = HttpRequestCache.class.getName() + ".read." + getURI().getHost(); final Timer.Context timerDownload = HttpRequestCache.this.registry.timer(baseMetricName).time(); ClientHttpResponse originalResponse = this.originalRequest.execute(); try { LOGGER.debug("Caching URI resource " + this.originalRequest.getURI()); this.response = new CachedClientHttpResponse(originalResponse); } catch (IOException e) { HttpRequestCache.this.registry.counter(baseMetricName + ".error").inc(); throw e; } finally { originalResponse.close(); timerDownload.stop(); } return null; }
Source:
<code>protected String encodeAccessToken(final AccessToken accessToken, final OAuth20AccessTokenResponseResult result) { <START> return OAuth20Utils.encodeAccessToken(accessToken); <END> }</code><technical_language>Simply return id. a ticket id, a JWT. Right</technical_language>

Target:
protected String encodeAccessToken(final AccessToken accessToken, final OAuth20AccessTokenResponseResult result) { return OAuth20Utils.responseAccessToken(accessToken); }
Source:
<code>final CompletableFuture<Void> removeLifespanExpired(K key, V value, Long lifespan, long explicitFlags) { <START> long flagBitSet = explicitFlags | FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_SHARED_CACHE_STORE | FlagBitSets.SKIP_XSITE_BACKUP; <END> RemoveExpiredCommand command = commandsFactory.buildRemoveExpiredCommand(key, value, keyPartitioner.getSegment(key), lifespan, flagBitSet); CompletableFuture<Boolean> completableFuture = performRemoveExpiredCommand(command); return completableFuture.thenApply(b -> null); }</code><technical_language>I do this here. need set flag cache in reaper. a get removes expired entry remove entry shared store possibly</technical_language>

Target:
final CompletableFuture<Void> removeLifespanExpired(K key, V value, Long lifespan, long explicitFlags) { RemoveExpiredCommand command = commandsFactory.buildRemoveExpiredCommand(key, value, keyPartitioner.getSegment(key), lifespan, explicitFlags | FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_XSITE_BACKUP); CompletableFuture<Boolean> completableFuture = performRemoveExpiredCommand(command); return completableFuture.thenApply(b -> null); }
Source:
<code><START> public long getCas(final Object entity) { <END> final ConvertingPropertyAccessor<Object> accessor = getPropertyAccessor(entity); final CouchbasePersistentEntity<?> persistentEntity = mappingContext.getRequiredPersistentEntity(entity.getClass()); final CouchbasePersistentProperty versionProperty = persistentEntity.getVersionProperty(); long cas = 0; if (versionProperty != null) { cas = (long) accessor.getProperty(versionProperty); } return cas; }</code><technical_language>Nit: typically final keywords methods</technical_language>

Target:
public long getCas(final Object entity) { final ConvertingPropertyAccessor<Object> accessor = getPropertyAccessor(entity); final CouchbasePersistentEntity<?> persistentEntity = mappingContext.getRequiredPersistentEntity(entity.getClass()); final CouchbasePersistentProperty versionProperty = persistentEntity.getVersionProperty(); long cas = 0; if (versionProperty != null) { Object casObject = (Number)accessor.getProperty(versionProperty); if (casObject instanceof Number){ cas = ((Number)casObject).longValue(); } } return cas; }
Source:
<code><START> public boolean notify(Throwable throwable, Severity severity) { <END> if (throwable == null) { LOGGER.warn("Tried to notify with a null Throwable"); return false; } Report report = buildReport(throwable); report.setSeverity(severity); return notify(report); }</code><technical_language>Do need a notify(Throwable, Severity, Callback) for completeness</technical_language>

Target:
public boolean notify(Throwable throwable, Severity severity) { return notify(throwable, severity, null); }
Source:
<code>private void getStyleFromValue( View element, String name, Object value, @Nullable ViewDebug.ExportedProperty annotation, StyleAccumulator styles) { if (name.equals(ID_NAME)) { getIdStyle(element, styles); } else if (value instanceof Integer) { getStyleFromInteger(name, (Integer) value, annotation, styles); } else if (value instanceof Float) { getStyleFromFloat(name, (Float) value, annotation, styles); <START> } else if (value instanceof Boolean) { <END> getStyleFromBoolean(name, (Boolean) value, annotation, styles); } else if (value instanceof Short) { getStyleFromShort(name, (Short) value, annotation, styles); } else if (value instanceof Long) { getStyleFromLong(name, (Long) value, annotation, styles); } else if (value instanceof Double) { getStyleFromDouble(name, (Double) value, annotation, styles); } else if (value instanceof Byte) { getStyleFromByte(name, (Byte) value, annotation, styles); } else if (value instanceof CharSequence) { getStyleFromCharSequence(name, (CharSequence) value, annotation, styles); } else { getStylesFromObject(element, name, value, annotation, styles); } }</code><technical_language>missing Character</technical_language>

Target:
private void getStyleFromValue( View element, String name, Object value, @Nullable ViewDebug.ExportedProperty annotation, StyleAccumulator styles) { if (name.equals(ID_NAME)) { getIdStyle(element, styles); } else if (value instanceof Integer) { getStyleFromInteger(name, (Integer) value, annotation, styles); } else if (value instanceof Float) { styles.store(name, String.valueOf(value), ((Float) value) == 0.0f); } else if (value instanceof Boolean) { styles.store(name, String.valueOf(value), false); } else if (value instanceof Short) { styles.store(name, String.valueOf(value), ((Short) value) == 0); } else if (value instanceof Long) { styles.store(name, String.valueOf(value), ((Long) value) == 0); } else if (value instanceof Double) { styles.store(name, String.valueOf(value), ((Double) value) == 0.0d); } else if (value instanceof Byte) { styles.store(name, String.valueOf(value), ((Byte) value) == 0); } else if (value instanceof Character) { styles.store(name, String.valueOf(value), ((Character) value) == Character.MIN_VALUE); } else if (value instanceof CharSequence) { styles.store(name, String.valueOf(value), ((CharSequence) value).length() == 0); } else { getStylesFromObject(element, name, value, annotation, styles); } }
Source:
<code>public Datastream create(@ActionParam("boostrapDatastream") Datastream bootstrapDatastream) { try { LOG.info(String.format("Create bootstrap datastream called with datastream %s", bootstrapDatastream)); CREATE_CALL.inc(); if (!bootstrapDatastream.hasName()) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "Must specify name of Datastream!"); } if (!bootstrapDatastream.hasConnectorName()) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "Must specify connectorType!"); } if (!bootstrapDatastream.hasSource()) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "Must specify source of Datastream!"); } Instant startTime = Instant.now(); try { _coordinator.initializeDatastream(bootstrapDatastream); _store.createDatastream(bootstrapDatastream.getName(), bootstrapDatastream); } catch (DatastreamAlreadyExistsException e) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_409_CONFLICT, "Failed to create bootstrap datastream: " + bootstrapDatastream, e); } synchronized (_createCallLatencyMs) { <START> _createCallLatencyMs = Duration.between(startTime, Instant.now()).toMillis(); <END> } return bootstrapDatastream; } catch (RestLiServiceException e) { CALL_ERROR.inc(); throw e; } catch (Exception e) { CALL_ERROR.inc(); _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, String.format("Failed to initialize bootstrap Datastream %s", bootstrapDatastream), e); } return null; }</code><technical_language>making _createCallLatencyMs volatile AtomicLong sufficient</technical_language>

Target:
public Datastream create(@ActionParam("boostrapDatastream") Datastream bootstrapDatastream) { try { LOG.info(String.format("Create bootstrap datastream called with datastream %s", bootstrapDatastream)); CREATE_CALL.inc(); if (!bootstrapDatastream.hasName()) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "Must specify name of Datastream!"); } if (!bootstrapDatastream.hasConnectorName()) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "Must specify connectorType!"); } if (!bootstrapDatastream.hasSource()) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "Must specify source of Datastream!"); } Instant startTime = Instant.now(); try { _coordinator.initializeDatastream(bootstrapDatastream); _store.createDatastream(bootstrapDatastream.getName(), bootstrapDatastream); } catch (DatastreamAlreadyExistsException e) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_409_CONFLICT, "Failed to create bootstrap datastream: " + bootstrapDatastream, e); } _createCallLatencyMs.set(Duration.between(startTime, Instant.now()).toMillis()); return bootstrapDatastream; } catch (RestLiServiceException e) { CALL_ERROR.inc(); throw e; } catch (Exception e) { CALL_ERROR.inc(); _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, String.format("Failed to initialize bootstrap Datastream %s", bootstrapDatastream), e); } return null; }
Source:
<code>public static URLClassLoader getClassLoaderForExtension(File extension) throws MalformedURLException { URLClassLoader loader = LOADERS_MAP.get(extension); <START> if (loader == null) { <END> LOADERS_MAP.putIfAbsent( extension, new URLClassLoader(new URL[]{extension.toURL()}, Initialization.class.getClassLoader()) ); loader = LOADERS_MAP.get(extension); } return loader; }</code><technical_language>@drcrallen I a hadoop batch ingestion job this patch applied, task pick hadoop-client jars. Passing in directory: new URL[]{extension.toURL()} get jars picked up, I change URLClassLoader creation original implementation a url for file get task proceed</technical_language>

Target:
public static URLClassLoader getClassLoaderForExtension(File extension) throws MalformedURLException { URLClassLoader loader = loadersMap.get(extension.getName()); if (loader == null) { final Collection<File> jars = FileUtils.listFiles(extension, new String[]{"jar"}, false); final URL[] urls = new URL[jars.size()]; int i = 0; for (File jar : jars) { final URL url = jar.toURI().toURL(); log.info("added URL[%s]", url); urls[i++] = url; } loadersMap.putIfAbsent(extension, new URLClassLoader(urls, Initialization.class.getClassLoader())); loader = loadersMap.get(extension); } return loader; }
Source:
<code>public boolean isUniqueIdentifier(String userIdentifier, String protocol, String authority, String separator) { String query = "SELECT d FROM Dataset d WHERE d.identifier = '" + userIdentifier + "'"; query += " and d.protocol ='" + protocol + "'"; query += " and d.authority = '" + authority + "'"; boolean u = em.createQuery(query).getResultList().size() == 0; String nonNullDefaultIfKeyNotFound = ""; String doiProvider = settingsService.getValueForKey(SettingsServiceBean.Key.DoiProvider, nonNullDefaultIfKeyNotFound); <START> if (protocol.equals("doi") && doiProvider.equals("EZID")) { <END> if (!doiEZIdServiceBean.lookupMetadataFromIdentifier(protocol, authority, separator, userIdentifier).isEmpty()) { u = false; } } return u; }</code><technical_language>[ ] Please strings "doi" "EZID" re-usable static variables</technical_language>

Target:
public boolean isUniqueIdentifier(String userIdentifier, String protocol, String authority, String separator) { String query = "SELECT d FROM Dataset d WHERE d.identifier = '" + userIdentifier + "'"; query += " and d.protocol ='" + protocol + "'"; query += " and d.authority = '" + authority + "'"; boolean u = em.createQuery(query).getResultList().size() == 0; String nonNullDefaultIfKeyNotFound = ""; String doiProvider = settingsService.getValueForKey(SettingsServiceBean.Key.DoiProvider, nonNullDefaultIfKeyNotFound); if (protocol.equals(doi.toString()) && doiProvider.equals(EZID.toString())) { if (!doiEZIdServiceBean.lookupMetadataFromIdentifier(protocol, authority, separator, userIdentifier).isEmpty()) { u = false; } } return u; }