auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>} catch (Exception e) { throw new <START> RuntimeException(e); <END> }</code><technical_language>AssertionError</technical_language>

Target:
} catch (Exception e) { throw new TestSetupError("Failed to lookup of field", e); }
Source:
<code>public void testProcessVariable() { Map<String, Object> data = new HashMap<>(); data.put("continue", false); CaseFileInstance caseFile = caseService.newCaseFileInstance(deploymentUnit.getIdentifier(), STAGE_WITH_TASK_PROCESS_VARIABLE, data, Collections.emptyMap()); String caseId = caseService.startCase(deploymentUnit.getIdentifier(), STAGE_WITH_TASK_PROCESS_VARIABLE, caseFile); assertThat(caseId).isNotNull().isEqualTo(FIRST_CASE_ID); assertCaseInstanceActive(caseId); CaseInstance caseInstance = caseService.getCaseInstance(caseId); assertThat(caseInstance).isNotNull(); Long processInstanceId = ((CaseInstanceImpl) caseInstance).getProcessInstanceId(); processService.setProcessVariable(processInstanceId, "continue", false); caseService.addDataToCaseFile(caseId, "continue", true); assertCaseInstanceActive(caseId); <START> <END> processService.setProcessVariable(processInstanceId, "continue", true); assertCaseInstanceNotActive(caseId); }</code><technical_language>I expectation? variable is addresses a process variable (not a case variable) in condition of case</technical_language>

Target:
public void testProcessVariable() { Map<String, Object> data = new HashMap<>(); data.put("continue", false); CaseFileInstance caseFile = caseService.newCaseFileInstance(deploymentUnit.getIdentifier(), STAGE_WITH_TASK_PROCESS_VARIABLE, data, Collections.emptyMap()); String caseId = caseService.startCase(deploymentUnit.getIdentifier(), STAGE_WITH_TASK_PROCESS_VARIABLE, caseFile); assertThat(caseId).isNotNull().isEqualTo(FIRST_CASE_ID); assertCaseInstanceActive(caseId); CaseInstance caseInstance = caseService.getCaseInstance(caseId); assertThat(caseInstance).isNotNull(); Long processInstanceId = ((CaseInstanceImpl) caseInstance).getProcessInstanceId(); processService.setProcessVariable(processInstanceId, "continue", false); caseService.addDataToCaseFile(caseId, "continue", true); List<TaskSummary> tasks = runtimeDataService.getTasksAssignedAsPotentialOwner(USER, new QueryFilter()); assertThat(tasks).hasSize(1); TaskSummary insideTask = tasks.get(0); assertThat(insideTask.getName()).isEqualTo(INSIDE_TASK); userTaskService.completeAutoProgress(insideTask.getId(), USER, null); assertCaseInstanceActive(caseId); processService.setProcessVariable(processInstanceId, "continue", true); caseInstance = caseService.getCaseInstance(caseId, false, false, false, true); assertThat(caseInstance).isNotNull(); assertThat(caseInstance.getCaseStages()).hasSize(1); String stageId = caseInstance.getCaseStages().iterator().next().getId(); TaskSpecification dynamicTaskSpecification = caseService.newHumanTaskSpec(DYNAMIC_TASK, "", USER, null, Collections.emptyMap()); caseService.addDynamicTaskToStage(caseId, stageId, dynamicTaskSpecification); tasks = runtimeDataService.getTasksAssignedAsPotentialOwner(USER, new QueryFilter()); assertThat(tasks).hasSize(1); TaskSummary dynamicTask = tasks.get(0); assertThat(dynamicTask.getName()).isEqualTo(DYNAMIC_TASK); userTaskService.completeAutoProgress(dynamicTask.getId(), USER, null); assertCaseInstanceNotActive(caseId); }
Source:
<code>public T getBestOffspring(T offspring1, T offspring2){ for (FitnessFunction<T> fitnessFunction : fitnessFunctions) { fitnessFunction.getFitness(offspring1); notifyEvaluation(offspring1); fitnessFunction.getFitness(offspring2); notifyEvaluation(offspring2); } <START> if(keepOffspring(offspring1, offspring2)) <END> return offspring2; else return offspring1; }</code><technical_language>isBetterOrEqual method GeneticAlgorithm class</technical_language>

Target:
public T getBestOffspring(T offspring1, T offspring2){ for (FitnessFunction<T> fitnessFunction : fitnessFunctions) { fitnessFunction.getFitness(offspring1); notifyEvaluation(offspring1); fitnessFunction.getFitness(offspring2); notifyEvaluation(offspring2); } if(isBetterOrEqual(offspring1, offspring2)) return offspring2; else return offspring1; }
Source:
<code>public boolean checkRequisitionAccountsAreUnique(RequisitionDocument requisitionDocument) { List<RequisitionItem> requisitionItems = requisitionDocument.getItems(); for (RequisitionItem requisitionItem : requisitionItems) { List<PurApAccountingLine> requisitionAccounts = requisitionItem.getSourceAccountingLines(); Set existingAccounts = new HashSet(); for(PurApAccountingLine purApAccountingLine : requisitionAccounts) { if (!existingAccounts.contains(purApAccountingLine.toString())) { existingAccounts.add(purApAccountingLine.toString()); } else { GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, PurapKeyConstants.ERROR_ITEM_ACCOUNTING_NOT_UNIQUE, requisitionItem.getItemIdentifierString()); String errorMessage = getDuplicateAccountErrorMessage(purApAccountingLine, requisitionItem); LOG.error(errorMessage); cuB2BShoppingErrorEmailService.sendDuplicateRequisitionAccountErrorEmail(requisitionDocument, errorMessage); <START> return false; <END> } } } return true; }</code><technical_language>cases more item duplicate accounts used. I a good idea report cases of duplicate accounts, first</technical_language>

Target:
public boolean checkRequisitionAccountsAreUnique(RequisitionDocument requisitionDocument) { boolean requisitionAccountsUnique = true; uniqueRequisitionAccountValidator = getUniqueRequisitionAccountValidator(); List<RequisitionItem> requisitionItems = requisitionDocument.getItems(); for (RequisitionItem requisitionItem : requisitionItems) { uniqueRequisitionAccountValidator.setItemForValidation(requisitionItem); AttributedDocumentEvent attributedDocumentEvent = new AttributedRouteDocumentEvent(requisitionDocument); if (!uniqueRequisitionAccountValidator.validate(attributedDocumentEvent)) { requisitionAccountsUnique = false; handleDuplicateAccountError(requisitionDocument, requisitionItem); } } return requisitionAccountsUnique; }
Source:
<code>public String getRoute() { final UndertowService service = this.undertowService.getValue(); <START> final String defaultServerRoute = service.getInstanceId(); final String route = this.name.equals(service.getDefaultServer()) ? defaultServerRoute : String.join("-", defaultServerRoute, this.name); <END> if (service.isObfuscateInstanceId()) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(this.name.getBytes()); final Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); final String encodedRoute = encoder.encodeToString(md.digest(route.getBytes())); UndertowLogger.ROOT_LOGGER.obfuscatedInstanceIdRoute(encodedRoute, route); return encodedRoute; } catch (NoSuchAlgorithmException e) { UndertowLogger.ROOT_LOGGER.unableToObfuscateInstanceIdRoute(route, e); } } return route; }</code><technical_language>skip this logic service.isObfuscateInstanceId() is true</technical_language>

Target:
public String getRoute() { final UndertowService service = this.undertowService.getValue(); final String defaultServerRoute = service.getInstanceId(); if (service.isObfuscateSessionRoute()) { try { final MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(this.name.getBytes(UTF_8)); final byte[] digestedBytes = md.digest(defaultServerRoute.getBytes(UTF_8)); final Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); final String encodedRoute = new String(encoder.encode(digestedBytes), UTF_8); UndertowLogger.ROOT_LOGGER.obfuscatedSessionRoute(encodedRoute, defaultServerRoute); return encodedRoute; } catch (NoSuchAlgorithmException e) { UndertowLogger.ROOT_LOGGER.unableToObfuscateSessionRoute(defaultServerRoute, e); } } return this.name.equals(service.getDefaultServer()) ? defaultServerRoute : String.join("-", defaultServerRoute, this.name); }
Source:
<code>private static void sanityCheck(File file, int expectedSize) throws IOException { FileInputStream fis = new FileInputStream(file); CheckpointManager manager; try { manager = new CheckpointManager(params, fis); } catch (IOException ioe){ <START> fis.close(); <END> throw ioe; } checkState(manager.numCheckpoints() == expectedSize); if (params.getId().equals(NetworkParameters.ID_MAINNET)) { StoredBlock test = manager.getCheckpointBefore(1390500000); checkState(test.getHeight() == 280224); checkState(test.getHeader().getHashAsString() .equals("00000000000000000b5d59a15f831e1c45cb688a4db6b0a60054d49a9997fa34")); } else if (params.getId().equals(NetworkParameters.ID_TESTNET)) { StoredBlock test = manager.getCheckpointBefore(1390500000); checkState(test.getHeight() == 167328); checkState(test.getHeader().getHashAsString() .equals("0000000000035ae7d5025c2538067fe7adb1cf5d5d9c31b024137d9090ed13a9")); } fis.close(); }</code><technical_language>put fis.close() in a finally block</technical_language>

Target:
private static void sanityCheck(File file, int expectedSize) throws IOException { FileInputStream fis = new FileInputStream(file); CheckpointManager manager; try { manager = new CheckpointManager(params, fis); } finally { fis.close(); } checkState(manager.numCheckpoints() == expectedSize); if (params.getId().equals(NetworkParameters.ID_MAINNET)) { StoredBlock test = manager.getCheckpointBefore(1390500000); checkState(test.getHeight() == 280224); checkState(test.getHeader().getHashAsString() .equals("00000000000000000b5d59a15f831e1c45cb688a4db6b0a60054d49a9997fa34")); } else if (params.getId().equals(NetworkParameters.ID_TESTNET)) { StoredBlock test = manager.getCheckpointBefore(1390500000); checkState(test.getHeight() == 167328); checkState(test.getHeader().getHashAsString() .equals("0000000000035ae7d5025c2538067fe7adb1cf5d5d9c31b024137d9090ed13a9")); } }
Source:
<code>public static Index loadIndex(final String indexFile) { final Index idx = null; InputStream inputStream = null; BufferedInputStream bufferedInputStream = null; final LittleEndianInputStream dis = null; try { <START> inputStream = ParsingUtils.openInputStream(indexFile); <END> if (indexFile.endsWith(".gz")) { inputStream = new GZIPInputStream(inputStream); } else if (indexFile.endsWith(TabixUtils.STANDARD_INDEX_EXTENSION)) { inputStream = new BlockCompressedInputStream(inputStream); } bufferedInputStream = new BufferedInputStream(inputStream, Defaults.NON_ZERO_BUFFER_SIZE); final Class indexClass = IndexType.getIndexType(bufferedInputStream).getIndexType(); final Constructor ctor = indexClass.getConstructor(InputStream.class); return (Index) ctor.newInstance(bufferedInputStream); } catch (final IOException ex) { throw new TribbleException.UnableToReadIndexFile("Unable to read index file", indexFile, ex); } catch (final Exception ex) { throw new RuntimeException(ex); } finally { try { if (inputStream != null) inputStream.close(); if (bufferedInputStream != null) bufferedInputStream.close(); if (dis != null) dis.close(); } catch (final IOException e) { } } }</code><technical_language>a leak original code is odd. opening input stream here, possibly re-assigning inputStream immediately in if (I idea why). move line 173 else block line 179</technical_language>

Target:
public static Index loadIndex(final String indexFile) { try (BufferedInputStream bufferedInputStream = new BufferedInputStream(indexFileInputStream(indexFile), Defaults.NON_ZERO_BUFFER_SIZE)){ final Class<Index> indexClass = IndexType.getIndexType(bufferedInputStream).getIndexType(); final Constructor<Index> ctor = indexClass.getConstructor(InputStream.class); return ctor.newInstance(bufferedInputStream); } catch (final IOException ex) { throw new TribbleException.UnableToReadIndexFile("Unable to read index file", indexFile, ex); } catch (final Exception ex) { throw new RuntimeException(ex); } }
Source:
<code>public boolean initializeTaskData(TaskRepository repository, TaskData data, ITaskMapping initializationData, IProgressMonitor monitor) throws CoreException { data.setVersion("0"); if (data.isNew()) { BugzillaRestCreateTaskSchema.getDefault().initialize(data); } else { BugzillaRestTaskSchema.getDefault().initialize(data); } if (initializationData != null) { connector.getTaskMapping(data).merge(initializationData); } BugzillaRestConfiguration config = connector.getRepositoryConfiguration(repository); if (config != null) { config.updateInitialTaskData(data); } TaskAttribute addselfCC = data.getRoot().getAttribute(BugzillaRestTaskSchema.getDefault().ADD_SELF_CC.getKey()); <START> addselfCC.putOption("UserName", repository.getUserName()); END> return true; }</code><technical_language>sense store this option attribute this attribute options, store in MetaData</technical_language>

Target:
public boolean initializeTaskData(TaskRepository repository, TaskData data, ITaskMapping initializationData, IProgressMonitor monitor) throws CoreException { data.setVersion("0"); if (data.isNew()) { BugzillaRestCreateTaskSchema.getDefault().initialize(data); } else { BugzillaRestTaskSchema.getDefault().initialize(data); } if (initializationData != null) { connector.getTaskMapping(data).merge(initializationData); } BugzillaRestConfiguration config = connector.getRepositoryConfiguration(repository); if (config != null) { config.updateInitialTaskData(data); } TaskAttribute addSelfCC = data.getRoot().getAttribute(BugzillaRestTaskSchema.getDefault().ADD_SELF_CC.getKey()); if (addSelfCC != null) { addSelfCC.getMetaData().putValue("UserName", repository.getUserName()); } return true; }
Source:
<code><START> public void getLoadDone(IDMContext context, ILoadInfo load, Object arg) <END> { VisualizerModel model = (VisualizerModel) arg; int l = Integer.valueOf(load.getLoad()); Integer wm = null; if (load.getHighLoadWaterMark() != null) { wm = Integer.valueOf(load.getHighLoadWaterMark()); } if (ICPUDMContext.class.isInstance(context)) { ICPUDMContext cpuContext = (ICPUDMContext) context; VisualizerCPU cpu = model.getCPU(Integer.parseInt(cpuContext.getId())); cpu.setLoadInfo(new VisualizerLoadInfo(l, wm)); } else if(ICoreDMContext.class.isInstance(context)) { ICoreDMContext coreContext = (ICoreDMContext) context; VisualizerCore core = model.getCore(Integer.parseInt(coreContext.getId())); core.setLoadInfo(new VisualizerLoadInfo(l, wm)); } }</code><technical_language>diverged "getCores" "getCoresDone" pattern here. I pattern apply in CPULoad case. I suggest making consistent for CPULoad logic itself. rid of this GetLoadDone moving logic a requestMonitor in updateLoads(). deal RMs calling listerner.getLoadDone() also</technical_language>

Target:
public void getLoadDone(IDMContext context, ILoadInfo load, Object arg) { VisualizerModel model = (VisualizerModel) arg; Integer l = null, wm = null; if (load != null) { l = Integer.valueOf(load.getLoad()); if (load.getHighLoadWaterMark() != null) { wm = Integer.valueOf(load.getHighLoadWaterMark()); } } if (context instanceof ICPUDMContext) { ICPUDMContext cpuContext = (ICPUDMContext) context; VisualizerCPU cpu = model.getCPU(Integer.parseInt(cpuContext.getId())); cpu.setLoadInfo(new VisualizerLoadInfo(l, wm)); } else if(context instanceof ICoreDMContext) { ICoreDMContext coreContext = (ICoreDMContext) context; VisualizerCore core = model.getCore(Integer.parseInt(coreContext.getId())); core.setLoadInfo(new VisualizerLoadInfo(l, wm)); } }
Source:
<code>public void close() { try { out.close(); } catch (IOException e) { throw new ParquetRuntimeException("Error closing output stream.", e){ <START> }; <END> } }</code><technical_language>please create a more specific exception extends this one</technical_language>

Target:
public void close() { out.close(); }
Source:
<code>private void handleChatEvent(AsyncPlayerChatEvent event) { final Player player = event.getPlayer(); String message = event.getMessage().trim(); message = ChatColor.stripColor(message); <START> if (message.length() > 250) <END> { message = message.substring(0, 250); FSync.playerMsg(player, "Message was shortened because it was too long to send."); } if (message.length() >= 6) { int caps = 0; for (char c : message.toCharArray()) { if (Character.isUpperCase(c)) { caps++; } } if (((float) caps / (float) message.length()) > 0.65) { message = message.toLowerCase(); } } final FPlayer fPlayer = plugin.pl.getPlayerSync(player); if (fPlayer.inAdminChat()) { FSync.adminChatMessage(player, message); event.setCancelled(true); return; } event.setMessage(message); String format = "<%1$s> %2$s"; String tag = fPlayer.getTag(); if (tag != null && !tag.isEmpty()) { format = tag.replace("%", "%%") + " " + format; } event.setFormat(format); }</code><technical_language>[the Minecraft wiki page](<LINK_0>, maximum length 256</technical_language>

Target:
private void handleChatEvent(AsyncPlayerChatEvent event) { final Player player = event.getPlayer(); String message = event.getMessage().trim(); message = ChatColor.stripColor(message); if (message.length() > 256) { message = message.substring(0, 256); FSync.playerMsg(player, "Message was shortened because it was too long to send."); } if (message.length() >= 6) { int caps = 0; for (char c : message.toCharArray()) { if (Character.isUpperCase(c)) { caps++; } } if (((float) caps / (float) message.length()) > 0.65) { message = message.toLowerCase(); } } final FPlayer fPlayer = plugin.pl.getPlayerSync(player); if (fPlayer.inAdminChat()) { FSync.adminChatMessage(player, message); event.setCancelled(true); return; } event.setMessage(message); String format = "<%1$s> %2$s"; String tag = fPlayer.getTag(); if (tag != null && !tag.isEmpty()) { format = tag.replace("%", "%%") + " " + format; } event.setFormat(format); }
Source:
<code>public void selectCommitByText(String text) { seleniumWebDriverHelper <START> .waitVisibility(By.xpath(String.format(Locators.ITEM_WITH_TEXT_XPATH_TEMPLATE, text))) <END> .click(); }</code><technical_language>replace exist _waitAndClick(By elementLocator)_</technical_language>

Target:
public void selectCommitByText(String text) { seleniumWebDriverHelper.waitAndClick( By.xpath(String.format(Locators.ITEM_WITH_TEXT_XPATH_TEMPLATE, text))); }
Source:
<code>public static void unregisterFormat(String name) { if (formats.remove(name) == null) throw new JGitInternalException( <START> "Archive format already absent: " + name); <END> }</code><technical_language>string translate these. :-(</technical_language>

Target:
public static void unregisterFormat(String name) { if (formats.remove(name) == null) throw new JGitInternalException(MessageFormat.format( CLIText.get().archiveFormatAlreadyAbsent, name)); }
Source:
<code>public static void refreshAllFeeds(final Context context) { if (!isRefreshing.compareAndSet(false, true)) { Log.d(TAG, "Ignoring request to refresh all feeds: Refresh lock is locked"); return; } if (Looper.myLooper() == Looper.getMainLooper()) { <START> Log.wtf(TAG, "DBTasks.refreshAllFeeds() must not be called from the main thread"); <END> return; } refreshFeeds(context, DBReader.getFeedList()); isRefreshing.set(false); SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE); prefs.edit().putLong(PREF_LAST_REFRESH, System.currentTimeMillis()).apply(); if (ClientConfig.gpodnetCallbacks.gpodnetEnabled()) { GpodnetSyncService.sendSyncIntent(context); } }</code><technical_language>I sense crash app throwing exception. Otherwise, log message overlooked</technical_language>

Target:
public static void refreshAllFeeds(final Context context) { if (!isRefreshing.compareAndSet(false, true)) { Log.d(TAG, "Ignoring request to refresh all feeds: Refresh lock is locked"); return; } if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalStateException("DBTasks.refreshAllFeeds() must not be called from the main thread."); } refreshFeeds(context, DBReader.getFeedList()); isRefreshing.set(false); SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE); prefs.edit().putLong(PREF_LAST_REFRESH, System.currentTimeMillis()).apply(); if (ClientConfig.gpodnetCallbacks.gpodnetEnabled()) { GpodnetSyncService.sendSyncIntent(context); } }
Source:
<code>public void scrape(HttpAction action) { ServletOps.responseSendError(action.response, HttpSC.NOT_IMPLEMENTED_501, <START> "SimpleMeterRegistry isn't scrapeable" ); <END> }</code><technical_language>strange is on. ServletOps.errorNotImplemented do throwing ActionErrorException is caught in ActionBase. Ah - ActionMetrics.doGet is common lifecycle. ServletOps.errorNotImplemented ActionMetrics for common execution c. Is in lifecycle a problem? public class ActionMetrics extends ActionCtl { public ActionMetrics() { } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doCommon(req, resp); } @Override protected void perform(HttpAction action) { MetricsProviderRegistry.get().scrape( action ); } }</technical_language>

Target:
public void scrape(HttpAction action) { ServletOps.errorNotImplemented("SimpleMeterRegistry isn't scrapeable"); }
Source:
<code>ParquetFileWriter(Configuration configuration, MessageType schema, Path file, long rowAndBlockSize, int maxPaddingSize) throws IOException { FileSystem fs = file.getFileSystem(configuration); this.schema = schema; this.alignment = PaddingAlignment.get( rowAndBlockSize, rowAndBlockSize, maxPaddingSize); this.out = HadoopStreams.wrap( fs.create(file, true, 8192, fs.getDefaultReplication(file), rowAndBlockSize)); this.encodingStatsBuilder = new EncodingStats.Builder(); this.columnIndexTruncateLength = Integer.MAX_VALUE; <START> this.pageWriteChecksumEnabled = configuration.getBoolean( <END> ParquetOutputFormat.PAGE_WRITE_CHECKSUM_ENABLED, ParquetProperties.DEFAULT_PAGE_WRITE_CHECKSUM_ENABLED); this.crc = pageWriteChecksumEnabled ? new CRC32() : null; }</code><technical_language>ParquetOutputFormat.getPageWriteChecksumEnabled instead</technical_language>

Target:
ParquetFileWriter(Configuration configuration, MessageType schema, Path file, long rowAndBlockSize, int maxPaddingSize) throws IOException { FileSystem fs = file.getFileSystem(configuration); this.schema = schema; this.alignment = PaddingAlignment.get( rowAndBlockSize, rowAndBlockSize, maxPaddingSize); this.out = HadoopStreams.wrap( fs.create(file, true, 8192, fs.getDefaultReplication(file), rowAndBlockSize)); this.encodingStatsBuilder = new EncodingStats.Builder(); this.columnIndexTruncateLength = Integer.MAX_VALUE; this.pageWriteChecksumEnabled = ParquetOutputFormat.getPageWriteChecksumEnabled(configuration); this.crc = pageWriteChecksumEnabled ? new CRC32() : null; }
Source:
<code>private boolean preDeleteValidation(CloudBlobMetadata metadata, StoreKey key, Map<String, Object> updateFields) throws StoreException { <START> validateAccountAndContainer(Collections.singletonMap(key.getID(), metadata), Collections.singletonList(key)); <END> short requestedLifeVersion = (short) updateFields.get(FIELD_LIFE_VERSION); if (isVcr) { return (!metadata.isDeleted() || metadata.getLifeVersion() < requestedLifeVersion) && (metadata.getLifeVersion() <= requestedLifeVersion); } if (requestedLifeVersion == MessageInfo.LIFE_VERSION_FROM_FRONTEND) { if (metadata.isDeleted()) { throw new StoreException( "Cannot delete id " + metadata.getId() + " since it is already marked as deleted in cloud.", StoreErrorCodes.ID_Deleted); } updateFields.remove(FIELD_LIFE_VERSION); } return true; }</code><technical_language>Do need change metadata.getId() line 554</technical_language>

Target:
private boolean preDeleteValidation(CloudBlobMetadata metadata, StoreKey key, Map<String, Object> updateFields) throws StoreException { validateAccountAndContainer(Collections.singletonMap(key.getID(), metadata), Collections.singletonList(key)); short requestedLifeVersion = (short) updateFields.get(FIELD_LIFE_VERSION); if (isVcr) { return (!metadata.isDeleted() || metadata.getLifeVersion() < requestedLifeVersion) && (metadata.getLifeVersion() <= requestedLifeVersion); } if (requestedLifeVersion == MessageInfo.LIFE_VERSION_FROM_FRONTEND) { if (metadata.isDeleted()) { throw new StoreException( "Cannot delete id " + key.getID() + " since it is already marked as deleted in cloud.", StoreErrorCodes.ID_Deleted); } updateFields.remove(FIELD_LIFE_VERSION); } return true; }
Source:
<code>private static Object getValue(ValueReference ref) { <START> NumberLiterals literals = new NumberLiterals(); <END> Object value = null; if (ref instanceof BoolValue) { value = ((BoolValue)ref).getValue().isIsTrue(); } else if (ref instanceof NumberValue) { XNumberLiteral xLiteral = ((NumberValue)ref).getValue(); value = literals.numberValue(xLiteral, literals.getJavaType(xLiteral)); } else if (ref instanceof StringValue) { value = ((StringValue)ref).getValue(); } else if (ref instanceof VariableReference) { value = new ParameterReference(((VariableReference) ref).getVar()); } else if (ref instanceof VariableValue) { value = new ParameterReference(((VariableValue)ref).getValue().getVar()); } else if (ref instanceof ListValue) { value = Lists.transform(((ListValue) ref).getValues(), new Function<ValueReference, Object>() { @Override public Object apply(ValueReference ref) { return getValue(ref); } }); } else { throw new UnsupportedOperationException("Unknown attribute parameter type"); } return value; }</code><technical_language>Is a cost instantiating this object? - If yes, saved in a field. - If not, I hope, extract branch of NumberValue case</technical_language>

Target:
private static Object getValue(ValueReference ref) { Object value = null; if (ref instanceof BoolValue) { value = ((BoolValue)ref).getValue().isIsTrue(); } else if (ref instanceof NumberValue) { NumberLiterals literals = new NumberLiterals(); XNumberLiteral xLiteral = ((NumberValue)ref).getValue(); value = literals.numberValue(xLiteral, literals.getJavaType(xLiteral)); } else if (ref instanceof StringValue) { value = ((StringValue)ref).getValue(); } else if (ref instanceof VariableReference) { value = new ParameterReference(((VariableReference) ref).getVar()); } else if (ref instanceof VariableValue) { value = new ParameterReference(((VariableValue)ref).getValue().getVar()); } else if (ref instanceof ListValue) { value = Lists.transform(((ListValue) ref).getValues(), new Function<ValueReference, Object>() { @Override public Object apply(ValueReference ref) { return getValue(ref); } }); } else { throw new UnsupportedOperationException("Unknown attribute parameter type"); } return value; }
Source:
<code>private void updateVerbs(RepositoryDTO repositoryDTO) { this.verbsManager.fetchAvailableVerbs(repositoryDTO, <START> verbs -> Platform.runLater(() -> this.verbs = verbs)); <END> }</code><technical_language>I this require Platform.runLater affect gui</technical_language>

Target:
private void updateVerbs(RepositoryDTO repositoryDTO) { this.verbsManager.fetchAvailableVerbs(repositoryDTO, verbs -> this.verbs = verbs); }
Source:
<code>private List<Integer> parsePorts(URI connectionURI) { String uriString = connectionURI.toString(); String withoutProtocol = uriString.substring(13); String[] stripes = withoutProtocol.split(STRIPE_SEPARATOR); List<Integer> ports = new ArrayList<>(stripes.length); <START> for (String stripe : stripes) { <END> String portString = stripe.substring(stripe.indexOf(":") + 1); int port = Integer.parseInt(portString); ports.add(port); } return ports; }</code><technical_language>Arrays.stream(stripes).map(stripe -> stripe.substring(stripe.indexOf(":") + 1)).mapToInt(Integer::parseInt).collector(Collectors::toList());</technical_language>

Target:
private List<Integer> parsePorts(URI connectionURI) { String uriString = connectionURI.toString(); String withoutProtocol = uriString.substring(13); String[] stripes = withoutProtocol.split(STRIPE_SEPARATOR); return Arrays.stream(stripes) .map(stripe -> stripe.substring(stripe.indexOf(":") + 1)) .mapToInt(Integer::parseInt) .boxed() .collect(Collectors.toList()); }
Source:
<code><START> public void shouldErrorIfTriesToSaveTheSameTokenTwice() throws Exception { <END> app.getDatabaseHelper().insertAccount(BEARER_TOKEN, ACCOUNT_ID); authTokenDao.createToken(BEARER_TOKEN, ACCOUNT_ID); }</code><technical_language>Is this expected behaviour? caller (in this case PublicAuthResource) opportunity work a duplicate token hash (ie generate a new token store it)? story requirements: > 1. Developer keys bearer tokens (for this story) > - short (ie. 32 hex digits equivalent, similar UUID) > - **There is need ensure unique**</technical_language>

Target:
public void shouldErrorIfTriesToSaveTheSameTokenTwice() throws Exception { app.getDatabaseHelper().insertAccount(BEARER_TOKEN, ACCOUNT_ID); authTokenDao.storeToken(BEARER_TOKEN, ACCOUNT_ID); }
Source:
<code>public int isApplicable(VElement vElement, ViewModelContext viewModelContext) { if (!VControl.class.isInstance(vElement)) { return NOT_APPLICABLE; } final VControl control = (VControl) vElement; IValueProperty valueProperty; try { valueProperty = Activator.getDefault().getEMFFormsDatabinding() <START> .getValueProperty(control.getDomainModelReference(), viewModelContext.getDomainModel()); <END> } catch (final DatabindingFailedException ex) { Activator.getDefault().getReportService().report(new DatabindingFailedReport(ex)); return NOT_APPLICABLE; } catch (final IllegalArgumentException ex) { Activator.getDefault().getReportService().report(new AbstractReport(ex)); return NOT_APPLICABLE; } final EStructuralFeature feature = (EStructuralFeature) valueProperty.getValueType(); if (feature.isMany()) { return NOT_APPLICABLE; } if (!EAttribute.class.isInstance(feature)) { return NOT_APPLICABLE; } final EAttribute eAttribute = EAttribute.class.cast(feature); if (eAttribute.getEContainingClass().equals(VStackPackage.eINSTANCE.getStackItem())) { return 3; } return NOT_APPLICABLE; }</code><technical_language>check for null</technical_language>

Target:
public int isApplicable(VElement vElement, ViewModelContext viewModelContext) { if (!VControl.class.isInstance(vElement)) { return NOT_APPLICABLE; } final VControl control = (VControl) vElement; if (control.getDomainModelReference() == null) { return NOT_APPLICABLE; } IValueProperty valueProperty; try { valueProperty = Activator.getDefault().getEMFFormsDatabinding() .getValueProperty(control.getDomainModelReference(), viewModelContext.getDomainModel()); } catch (final DatabindingFailedException ex) { Activator.getDefault().getReportService().report(new DatabindingFailedReport(ex)); return NOT_APPLICABLE; } catch (final IllegalArgumentException ex) { Activator.getDefault().getReportService().report(new AbstractReport(ex)); return NOT_APPLICABLE; } final EStructuralFeature feature = (EStructuralFeature) valueProperty.getValueType(); if (feature.isMany()) { return NOT_APPLICABLE; } if (!EAttribute.class.isInstance(feature)) { return NOT_APPLICABLE; } final EAttribute eAttribute = EAttribute.class.cast(feature); if (eAttribute.getEContainingClass().equals(VStackPackage.eINSTANCE.getStackItem())) { return 3; } return NOT_APPLICABLE; }
Source:
<code>public void secondBackupFileCorrectModifiedDate() throws IOException { long expectedLastModifiedDate; <START> final int kNumberOfBackups = 2; <END> Process process = new Process(); process.setId(2); process.setProcessBaseUri(URI.create("2")); expectedLastModifiedDate = getLastModifiedFileDate( processService.getProcessDataDirectory(process) + BACKUP_FILE_NAME); runBackup(kNumberOfBackups, process); fileService.createResource(processService.getProcessDataDirectory(process), BACKUP_FILE_NAME); runBackup(kNumberOfBackups, process); assertLastModifiedDate(processService.getProcessDataDirectory(process) + BACKUP_FILE_NAME + ".2", expectedLastModifiedDate); }</code><technical_language>mentioned above: do introduce unreadable variable names</technical_language>

Target:
public void secondBackupFileCorrectModifiedDate() throws IOException { long expectedLastModifiedDate; final int numberOfBackups = 2; Process process = new Process(); process.setId(2); process.setProcessBaseUri(URI.create("2")); expectedLastModifiedDate = getLastModifiedFileDate( processService.getProcessDataDirectory(process) + BACKUP_FILE_NAME); runBackup(numberOfBackups, process); fileService.createResource(processService.getProcessDataDirectory(process), BACKUP_FILE_NAME); runBackup(numberOfBackups, process); assertLastModifiedDate(processService.getProcessDataDirectory(process) + BACKUP_FILE_NAME + ".2", expectedLastModifiedDate); }
Source:
<code>public void printTrader() { System.out.println("Trader Name: " + name); System.out.println("====================="); System.out.println("Cash: " + cashInHand); System.out.println("Stocks Owned: "); <START> for (Order o : position) { <END> o.printStockNameInOrder(); } System.out.println("Stocks Desired: "); for (Order o : ordersPlaced) { o.printOrder(); } System.out.println("+++++++++++++++++++++"); System.out.println("+++++++++++++++++++++"); }</code><technical_language>change variable more meaningful</technical_language>

Target:
public void printTrader() { System.out.println("Trader Name: " + name); System.out.println("====================="); System.out.println("Cash: " + cashInHand); System.out.println("Stocks Owned: "); for (Order order : position) { o.printStockNameInOrder(); } System.out.println("Stocks Desired: "); for (Order order : ordersPlaced) { o.printOrder(); } System.out.println("+++++++++++++++++++++"); System.out.println("+++++++++++++++++++++"); }
Source:
<code>public Results calculateResults(LocalDate valuationDate, TradeSource tradeSource, List<Measure> measures) { ExampleMarketDataBuilder marketDataBuilder = ExampleMarketData.builder(); CalculationRules rules = CalculationRules.builder() .pricingRules(StandardComponents.pricingRules()) .marketDataRules(marketDataBuilder.rules()) .reportingRules(ReportingRules.fixedCurrency(Currency.USD)) .build(); MarketEnvironment marketSnapshot = marketDataBuilder.buildSnapshot(valuationDate); List<Column> columns = measures.stream().map(Column::of).collect(Collectors.toList()); ImmutableList<Trade> trades = ImmutableList.of(tradeSource.apply()); <START> try (CalculationRunner runner = CalculationRunner.of(MoreExecutors.newDirectExecutorService())) { <END> return runner.calculateSingleScenario(trades, columns, rules, marketSnapshot); } }</code><technical_language>need for try-with-resources</technical_language>

Target:
public Results calculateResults(LocalDate valuationDate, TradeSource tradeSource, List<Measure> measures) { ExampleMarketDataBuilder marketDataBuilder = ExampleMarketData.builder(); CalculationRules rules = CalculationRules.builder() .pricingRules(StandardComponents.pricingRules()) .marketDataRules(marketDataBuilder.rules()) .reportingRules(ReportingRules.fixedCurrency(Currency.USD)) .build(); MarketEnvironment marketSnapshot = marketDataBuilder.buildSnapshot(valuationDate); List<Column> columns = measures.stream().map(Column::of).collect(Collectors.toList()); ImmutableList<Trade> trades = ImmutableList.of(tradeSource.apply()); CalculationRunner runner = CalculationRunner.of(MoreExecutors.newDirectExecutorService()); return runner.calculateSingleScenario(trades, columns, rules, marketSnapshot); }
Source:
<code>public void loadRunningCluster(MesosCluster cluster) { String clusterId = cluster.getClusterId(); List<ClusterProcess> containers = cluster.getMemberProcesses(); List<Container> dockerContainers = DockerClientFactory.build().listContainersCmd().exec(); Collections.sort(dockerContainers, (c1, c2) -> Long.compare(c1.getCreated(), c2.getCreated())); for (Container container : dockerContainers) { String name = ContainerName.getFromDockerNames(container.getNames()); if (ContainerName.belongsToCluster(name, clusterId)) { String containerId = container.getId(); String[] parts = name.split("-"); <START> String role = parts[1]; <END> String uuid = parts[3]; switch (role) { case "zookeeper": containers.add(createZooKeeper(cluster, uuid, containerId)); break; case "agent": containers.add(createMesosAgent(cluster, uuid, containerId)); break; case "master": MesosMaster master = createMesosMaster(cluster, uuid, containerId); containers.add(master); Container.Port[] ports = container.getPorts(); if (ports != null) { for (Container.Port port : ports) { if (port.getIp() != null && port.getPrivatePort() == MesosMasterConfig.MESOS_MASTER_PORT) { cluster.setExposedHostPorts(true); } } } break; case "marathon": containers.add(createMarathon(cluster, uuid, containerId)); break; case "consul": containers.add(createConsul(cluster, uuid, containerId)); break; case "registrator": containers.add(createRegistrator(cluster, uuid, containerId)); break; } } } }</code><technical_language>This benefit checking for IndexOutOfBoundException</technical_language>

Target:
public void loadRunningCluster(MesosCluster cluster) { String clusterId = cluster.getClusterId(); List<ClusterProcess> containers = cluster.getMemberProcesses(); List<Container> dockerContainers = DockerClientFactory.build().listContainersCmd().exec(); Collections.sort(dockerContainers, (c1, c2) -> Long.compare(c1.getCreated(), c2.getCreated())); for (Container container : dockerContainers) { String name = ContainerName.getFromDockerNames(container.getNames()); if (ContainerName.belongsToCluster(name, clusterId)) { String containerId = container.getId(); String[] parts = name.split("-"); if (parts.length > 3) { String role = parts[1]; String uuid = parts[3]; switch (role) { case "zookeeper": containers.add(createZooKeeper(cluster, uuid, containerId)); break; case "agent": containers.add(createMesosAgent(cluster, uuid, containerId)); break; case "master": MesosMaster master = createMesosMaster(cluster, uuid, containerId); containers.add(master); Container.Port[] ports = container.getPorts(); if (ports != null) { for (Container.Port port : ports) { if (port.getIp() != null && port.getPrivatePort() == MesosMasterConfig.MESOS_MASTER_PORT) { cluster.setExposedHostPorts(true); } } } break; case "marathon": containers.add(createMarathon(cluster, uuid, containerId)); break; case "consul": containers.add(createConsul(cluster, uuid, containerId)); break; case "registrator": containers.add(createRegistrator(cluster, uuid, containerId)); break; } } } } }
Source:
<code>public void notifyBegin(List<Response.ResponseListener> listeners, Response response) { for (int i = 0; i < listeners.size(); i++) { <START> Response.ResponseListener listener = listeners.get(i); <END> if (listener instanceof Response.BeginListener) notifyBegin((Response.BeginListener)listener, response); } }</code><technical_language>I need do this - List iterator is supposed simple in this case JIT eliminate allocation</technical_language>

Target:
public void notifyBegin(List<Response.ResponseListener> listeners, Response response) { for (Response.ResponseListener listener : listeners) { if (listener instanceof Response.BeginListener) notifyBegin((Response.BeginListener)listener, response); } }
Source:
<code>public NettyConfig(VerifiableProperties verifiableProperties) { nettyServerBossThreadCount = verifiableProperties.getInt("netty.server.boss.thread.count", 1); nettyServerIdleTimeSeconds = verifiableProperties.getInt("netty.server.idle.time.seconds", 60); nettyServerPort = verifiableProperties.getInt("netty.server.port", 1174); nettyServerSoBacklog = verifiableProperties.getInt("netty.server.so.backlog", 100); nettyServerWorkerThreadCount = verifiableProperties.getInt("netty.server.worker.thread.count", 1); nettyServerMaxInitialLineLength = verifiableProperties.getInt("netty.server.max.initial.line.length", 4096); nettyServerMaxHeaderSize = verifiableProperties.getInt("netty.server.max.header.size", 8192); nettyServerMaxChunkSize = verifiableProperties.getInt("netty.server.max.chunk.size", 8192); <START> nettyServerRequestBufferWatermark = verifiableProperties.getInt("netty.server.request.buffer.watermark", 33554432); <END> }</code><technical_language>32 * 1024 * 1024 well</technical_language>

Target:
public NettyConfig(VerifiableProperties verifiableProperties) { nettyServerBossThreadCount = verifiableProperties.getInt("netty.server.boss.thread.count", 1); nettyServerIdleTimeSeconds = verifiableProperties.getInt("netty.server.idle.time.seconds", 60); nettyServerPort = verifiableProperties.getInt("netty.server.port", 1174); nettyServerSoBacklog = verifiableProperties.getInt("netty.server.so.backlog", 100); nettyServerWorkerThreadCount = verifiableProperties.getInt("netty.server.worker.thread.count", 1); nettyServerMaxInitialLineLength = verifiableProperties.getInt("netty.server.max.initial.line.length", 4096); nettyServerMaxHeaderSize = verifiableProperties.getInt("netty.server.max.header.size", 8192); nettyServerMaxChunkSize = verifiableProperties.getInt("netty.server.max.chunk.size", 8192); nettyServerRequestBufferWatermark = verifiableProperties.getInt("netty.server.request.buffer.watermark", 32 * 1024 * 1024); }
Source:
<code><START> public void testIsDrawable_UserTask() throws Exception { <END> testIsDrawable(AdHocSubprocess.class, UserTask.class, true); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void testIsDrawable_UserTask() { testIsDrawable(AdHocSubprocess.class, UserTask.class, true); }
Source:
<code>public void testTranslateServiceCreationConfiguration() { ManagementRegistryServiceConfigurationParser configTranslator = new ManagementRegistryServiceConfigurationParser(); DefaultManagementRegistryConfiguration defaultManagementRegistryConfiguration = new DefaultManagementRegistryConfiguration().setCacheManagerAlias("my-cache-alias"). setCollectorExecutorAlias("my-executor").addTag("tag1").addTag("tag2"); Node retElement = configTranslator.unparseServiceCreationConfiguration(defaultManagementRegistryConfiguration); assertThat(retElement, is(notNullValue())); assertThat(retElement.getNodeName(), is("mgm:management")); assertThat(retElement.getAttributes(), is(notNullValue())); assertThat(retElement.getAttributes().getLength(), is(3)); assertThat(retElement.getAttributes().item(0).getNodeName(), is("cache-manager-alias")); assertThat(retElement.getAttributes().item(0).getNodeValue(), is("my-cache-alias")); assertThat(retElement.getAttributes().item(1).getNodeName(), is("collector-executor-alias")); assertThat(retElement.getAttributes().item(1).getNodeValue(), is("my-executor")); assertThat(retElement.getAttributes().item(2).getNodeName(), is("xmlns:mgm")); assertThat(retElement.getAttributes().item(2).getNodeValue(), is("<LINK_0>")); Node tagsElement = retElement.getFirstChild(); assertThat(tagsElement, is(notNullValue())); assertThat(tagsElement.getNodeName(), is("mgm:tags")); assertThat(tagsElement.getAttributes().getLength(), is(0)); <START> Node tag1 = tagsElement.getFirstChild(); <END> assertThat(tag1, is(notNullValue())); assertThat(tag1.getFirstChild(), is(notNullValue())); assertThat(tag1.getFirstChild().getNodeValue(), is("tag1")); Node tag2 = tagsElement.getLastChild(); assertThat(tag2, is(notNullValue())); assertThat(tag2.getFirstChild(), is(notNullValue())); assertThat(tag2.getFirstChild().getNodeValue(), is("tag2")); }</code><technical_language>extract a method checking tags</technical_language>

Target:
public void testTranslateServiceCreationConfiguration() { ManagementRegistryServiceConfigurationParser configTranslator = new ManagementRegistryServiceConfigurationParser(); DefaultManagementRegistryConfiguration defaultManagementRegistryConfiguration = new DefaultManagementRegistryConfiguration().setCacheManagerAlias("my-cache-alias"). setCollectorExecutorAlias("my-executor").addTag("tag1").addTag("tag2"); Node retElement = configTranslator.unparseServiceCreationConfiguration(defaultManagementRegistryConfiguration); assertThat(retElement, is(notNullValue())); assertThat(retElement.getNodeName(), is("mgm:management")); checkAttributeItems(retElement); checkTags(retElement); }
Source:
<code>private Constraint distanceFromLastVisitToDomicile(ConstraintFactory constraintFactory) { return constraintFactory.from(Visit.class) <START> .ifNotExists(Visit.class, Joiners.equal(visit -> visit, Visit::getPreviousStandstill)) <END> .join(Domicile.class) .penalizeLong("Distance from last visit to domicile", SimpleLongScore.of(1), Visit::getDistanceTo); }</code><technical_language>I guess "visit -> visit" is "Function.identity()"? experiment thisEqual() equalToThat() ? I guess overkill..</technical_language>

Target:
private Constraint distanceFromLastVisitToDomicile(ConstraintFactory constraintFactory) { return constraintFactory.from(Visit.class) .ifNotExists(Visit.class, Joiners.equal(visit -> visit, Visit::getPreviousStandstill)) .join(Domicile.class) .penalizeLong("Distance from last visit to domicile", SimpleLongScore.ONE, Visit::getDistanceTo); }
Source:
<code>private void translateSupremeCourt(SolrDocument document, JudgmentSearchResult result) { String personnelType = fieldFetcher.fetchValue(document, JudgmentIndexField.SC_PERSONNEL_TYPE); result.setPersonnelType(personnelType); List<Pair<String, List<String>>> chambers = fieldFetcher.fetchValuesWithAttributes(document, JudgmentIndexField.SC_CHAMBER); List<SupremeCourtChamberResult> chambersResult = Lists.newLinkedList(); for (Pair<String, List<String>> singleChamber : chambers) { try { int scChamberId = Integer.parseInt(singleChamber.getLeft()); if (singleChamber.getRight().size() > 0) { SupremeCourtChamberResult scChamberResult = new SupremeCourtChamberResult(scChamberId, singleChamber.getRight().get(0)); chambersResult.add(scChamberResult); } <START> } catch (NumberFormatException e) { <END> } } result.setCourtChambers(chambersResult); Integer divisionId = fieldFetcher.fetchIntValue(document, JudgmentIndexField.SC_DIVISION_ID); String divisionName = fieldFetcher.fetchValue(document, JudgmentIndexField.SC_DIVISION_NAME); result.setCourtChamberDivisionId(divisionId); result.setCourtChamberDivisionName(divisionName); }</code><technical_language>do this</technical_language>

Target:
private void translateSupremeCourt(SolrDocument document, JudgmentSearchResult result) { String personnelType = fieldFetcher.fetchValue(document, JudgmentIndexField.SC_PERSONNEL_TYPE); result.setPersonnelType(personnelType); List<Pair<String, List<String>>> chambers = fieldFetcher.fetchValuesWithAttributes(document, JudgmentIndexField.SC_CHAMBER); List<SupremeCourtChamberResult> chambersResult = Lists.newLinkedList(); chambers .stream() .filter(x -> x.getRight().size() > 0) .forEach(x -> chambersResult.add(new SupremeCourtChamberResult(Integer.parseInt(x.getLeft()), x.getRight().get(0)))); result.setCourtChambers(chambersResult); Integer divisionId = fieldFetcher.fetchIntValue(document, JudgmentIndexField.SC_DIVISION_ID); String divisionName = fieldFetcher.fetchValue(document, JudgmentIndexField.SC_DIVISION_NAME); result.setCourtChamberDivisionId(divisionId); result.setCourtChamberDivisionName(divisionName); }