auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Map<ParameterType, Object> readParameters(DataInputPlus in, int version) throws IOException { int parameterCount = in.readInt(); Map<ParameterType, Object> parameters; if (parameterCount == 0) { return Collections.emptyMap(); } else { ImmutableMap.Builder<ParameterType, Object> builder = ImmutableMap.builder(); for (int i = 0; i < parameterCount; i++) { String key = in.readUTF(); <START> ParameterType type = ParameterType.byName.get(key); <END> byte[] value = new byte[in.readInt()]; in.readFully(value); builder.put(type, type.serializer.deserialize(new DataInputBuffer(value), version)); } return builder.build(); } }</code><technical_language>right throw skip try null a key. silently skip? a useful behavior for a protocol. this illustrates a larger issue. key a string pass parameters recognize. drop them</technical_language>

Target:
public static Map<ParameterType, Object> readParameters(DataInputPlus in, int version) throws IOException { int parameterCount = in.readInt(); Map<ParameterType, Object> parameters; if (parameterCount == 0) { return Collections.emptyMap(); } else { ImmutableMap.Builder<ParameterType, Object> builder = ImmutableMap.builder(); for (int i = 0; i < parameterCount; i++) { String key = in.readUTF(); ParameterType type = ParameterType.byName.get(key); if (type != null) { byte[] value = new byte[in.readInt()]; in.readFully(value); builder.put(type, type.serializer.deserialize(new DataInputBuffer(value), version)); } else { in.skipBytes(in.readInt()); } } return builder.build(); } }
Source:
<code>private void initializeExecThread() { <START> log.debug("Initializing exec thread"); <END> if(scriptFile == null) { log.debug("Using manual script text for exec"); execThread = new ScriptedCommandThread(manualScriptText, manualScriptName, this, availableCommandFactory); } else { log.debug("Using file path for exec"); execThread = new ScriptedCommandThread(scriptFile, this, availableCommandFactory); } execThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { Logger log = Logger.getLogger(ScriptedCommandThread.class); log.error("Uncaught exception in autonomous thread! " + e.toString()); } }); }</code><technical_language>this is invoked - a good candidate for info logging</technical_language>

Target:
private void initializeExecThread() { log.info("Initializing exec thread"); if(manualScriptText != null && manualScriptName != null) { log.info("Using manual script text for exec"); execThread = new ScriptedCommandThread(manualScriptText, manualScriptName, this, availableCommandFactory); } else if (scriptFile != null && scriptFile.canRead() && scriptFile.isFile()) { log.info("Using file path for exec"); execThread = new ScriptedCommandThread(scriptFile, this, availableCommandFactory); } else { log.error("Exec thread not initialized due to lack of viable script source."); return; } execThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { Logger log = Logger.getLogger(ScriptedCommandThread.class); log.error("Uncaught exception in autonomous thread! " + e.toString()); e.printStackTrace(); } }); }
Source:
<code>public static boolean isValidCheckstyleClass(Class<?> clazz) { return AutomaticBean.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers()) <START> && !clazz.getSimpleName().startsWith("Input"); <END> }</code><technical_language>problem "Input"s ? Main code affected test code. If some extra classes picked rename of radar, ignore if do problems. "test" code affect "main" code</technical_language>

Target:
public static boolean isValidCheckstyleClass(Class<?> clazz) { return AutomaticBean.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers()); }
Source:
<code>private void configureChatSetting(Preferences preferences) { chatComboBox.setButtonCell(new StringListCell<>(chatFormat -> i18n.get(chatFormat.getI18nKey()))); chatComboBox.setCellFactory(param -> new StringListCell<>(chatFormat -> i18n.get(chatFormat.getI18nKey()))); chatComboBox.setItems(FXCollections.observableArrayList(ChatFormat.values())); <START> chatComboBox.setDisable(false); <END> chatComboBox.setFocusTraversable(true); chatComboBox.getSelectionModel().select(preferences.getChat().getChatFormat()); }</code><technical_language>needed if needed change thst in fxml</technical_language>

Target:
private void configureChatSetting(Preferences preferences) { chatComboBox.setButtonCell(new StringListCell<>(chatFormat -> i18n.get(chatFormat.getI18nKey()))); chatComboBox.setCellFactory(param -> new StringListCell<>(chatFormat -> i18n.get(chatFormat.getI18nKey()))); chatComboBox.setItems(FXCollections.observableArrayList(ChatFormat.values())); chatComboBox.getSelectionModel().select(preferences.getChat().getChatFormat()); }
Source:
<code>public static StorageConnection map(StorageServerConnections entity, StorageConnection template) { StorageConnection model = template != null ? template : new StorageConnection(); model.setId(entity.getid()); model.setType(map(entity.getstorage_type(), null)); if (entity.getstorage_type() == org.ovirt.engine.core.common.businessentities.storage.StorageType.ISCSI) { model.setAddress(entity.getconnection()); model.setPort(Integer.parseInt(entity.getport())); model.setUsername(entity.getuser_name()); model.setTarget(entity.getiqn()); } if (entity.getstorage_type().isFileDomain()) { setPath(entity, model); } if (entity.getstorage_type().equals(org.ovirt.engine.core.common.businessentities.storage.StorageType.NFS)) { if (entity.getNfsVersion() != null) { model.setNfsVersion(entity.getNfsVersion().toString()); } if (entity.getNfsRetrans() != null) { model.setNfsRetrans(entity.getNfsRetrans().intValue()); } if (entity.getNfsTimeo() != null) { model.setNfsTimeo(entity.getNfsTimeo().intValue()); } if (entity.getMountOptions() != null) { model.setMountOptions(entity.getMountOptions()); } } else if (entity.getstorage_type().equals(org.ovirt.engine.core.common.businessentities.storage.StorageType.POSIXFS) <START> || entity.getstorage_type().equals(StorageType.GLUSTERFS)) { <END> model.setMountOptions(entity.getMountOptions()); model.setVfsType(entity.getVfsType()); } return model; }</code><technical_language>This is comparing for equality values of enum types, equal. intend org.ovirt.engine.core.common.businessentities.storage.StorageType.GLUSTERFS</technical_language>

Target:
public static StorageConnection map(StorageServerConnections entity, StorageConnection template) { StorageConnection model = template != null ? template : new StorageConnection(); model.setId(entity.getid()); model.setType(map(entity.getstorage_type(), null)); if (entity.getstorage_type() == org.ovirt.engine.core.common.businessentities.storage.StorageType.ISCSI) { model.setAddress(entity.getconnection()); model.setPort(Integer.parseInt(entity.getport())); model.setUsername(entity.getuser_name()); model.setTarget(entity.getiqn()); } if (entity.getstorage_type().isFileDomain()) { setPath(entity, model); } if (entity.getstorage_type().equals(org.ovirt.engine.core.common.businessentities.storage.StorageType.NFS)) { if (entity.getNfsVersion() != null) { model.setNfsVersion(entity.getNfsVersion().toString()); } if (entity.getNfsRetrans() != null) { model.setNfsRetrans(entity.getNfsRetrans().intValue()); } if (entity.getNfsTimeo() != null) { model.setNfsTimeo(entity.getNfsTimeo().intValue()); } if (entity.getMountOptions() != null) { model.setMountOptions(entity.getMountOptions()); } } else if (entity.getstorage_type().equals(org.ovirt.engine.core.common.businessentities.storage.StorageType.POSIXFS) || entity.getstorage_type().equals(org.ovirt.engine.core.common.businessentities.storage.StorageType.GLUSTERFS)) { model.setMountOptions(entity.getMountOptions()); model.setVfsType(entity.getVfsType()); } return model; }
Source:
<code><START> HaxeParameterDescription(String name, <END> String type, String initialValue, boolean isOptional, ResultHolder resultHolder) { this.isOptional = isOptional; this.hasInitialValue = initialValue != null; this.text = compileDescription(name, type, initialValue); this.resultHolder = resultHolder; }</code><technical_language>rewritten this class, more a model ide/info class</technical_language>

Target:
HaxeParameterDescription(String name, String type, String initialValue, boolean isOptional, ResultHolder resultHolder) { this.isOptional = isOptional; this.hasInitialValue = initialValue != null; this.description = compilePresentableDescription(name, type, initialValue); this.resultHolder = resultHolder; }
Source:
<code>public static void preprocess() { File f = new File(home, "OSGI-INF/deployment-container.xml"); if (!f.isFile()) { return; } try { Class<?> klass = loader.loadClass("org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor"); Method main = klass.getMethod("main", String[].class); main.invoke(null, new Object[] { new String[] { home.getAbsolutePath() } }); <START> } catch (ClassNotFoundException | SecurityException | NoSuchMethodException | IllegalAccessException <END> | InvocationTargetException e) { throw new RuntimeException(e); } }</code><technical_language>ReflectiveOperationException for of those, SecurityException is a RuntimeException need re-wrapped</technical_language>

Target:
public static void preprocess() { File f = new File(home, "OSGI-INF/deployment-container.xml"); if (!f.isFile()) { return; } try { Class<?> klass = loader.loadClass("org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor"); Method main = klass.getMethod("main", String[].class); main.invoke(null, new Object[] { new String[] { home.getAbsolutePath() } }); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } }
Source:
<code>public void scanFile(JavaFileScannerContext context) { <START> contexts.clear(); <END> super.scanFile(context); }</code><technical_language>This necessary... safe a bit defensive</technical_language>

Target:
public void scanFile(JavaFileScannerContext context) { assignmentsByMethod.clear(); super.scanFile(context); }
Source:
<code>public void execute() { Account caller = CallContext.current().getCallingAccount(); List<QuotaSummaryResponse> responses; <START> if (caller.getAccountId() <= 2) { END> if (getAccountName() != null && getDomainId() != null) responses = _responseBuilder.createQuotaSummaryResponse(caller.getAccountName(), caller.getDomainId()); else responses = _responseBuilder.createQuotaSummaryResponse(getListAll()); } else { responses = _responseBuilder.createQuotaSummaryResponse(caller.getAccountName(), caller.getDomainId()); } final ListResponse<QuotaSummaryResponse> response = new ListResponse<QuotaSummaryResponse>(); response.setResponses(responses); response.setResponseName(getCommandName()); setResponseObject(response); }</code><technical_language>assume account <=2 root admin privileges is naive. a solid do this. 2 cents.</technical_language>

Target:
public void execute() { Account caller = CallContext.current().getCallingAccount(); List<QuotaSummaryResponse> responses; if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { if (getAccountName() != null && getDomainId() != null) responses = _responseBuilder.createQuotaSummaryResponse(caller.getAccountName(), caller.getDomainId()); else responses = _responseBuilder.createQuotaSummaryResponse(getListAll()); } else { responses = _responseBuilder.createQuotaSummaryResponse(caller.getAccountName(), caller.getDomainId()); } final ListResponse<QuotaSummaryResponse> response = new ListResponse<QuotaSummaryResponse>(); response.setResponses(responses); response.setResponseName(getCommandName()); setResponseObject(response); }
Source:
<code>public void testRelease01() throws Exception { tag.release(); <START> assertNull(getField(tag, "page")); <END> assertNull(getField(tag, "pathTmpl")); assertNull(getField(tag, "queryTmpl")); assertNull(getField(tag, "criteriaQuery")); assertFalse((boolean) getField(tag, "disableHtmlEscapeOfCriteriaQuery")); assertFalse((boolean) getField(tag, "enableLinkOfCurrentPage")); assertNull(getField(tag, "outerElement")); assertNull(getField(tag, "outerElementClass")); assertNull(getField(tag, "innerElement")); assertNull(getField(tag, "innerElementClass")); assertNull(getField(tag, "firstLinkText")); assertNull(getField(tag, "previousLinkText")); assertNull(getField(tag, "nextLinkText")); assertNull(getField(tag, "lastLinkText")); assertNull(getField(tag, "disabledHref")); assertNull(getField(tag, "activeClass")); assertNull(getField(tag, "disabledClass")); }</code><technical_language>[ ] I static import ReflectionTestUtils.getField. common recall ReflectionTestUtils getField</technical_language>

Target:
public void testRelease01() throws Exception { tag.release(); assertNull(ReflectionTestUtils.getField(tag, "page")); assertNull(ReflectionTestUtils.getField(tag, "pathTmpl")); assertNull(ReflectionTestUtils.getField(tag, "queryTmpl")); assertNull(ReflectionTestUtils.getField(tag, "criteriaQuery")); assertFalse((boolean) ReflectionTestUtils.getField(tag, "disableHtmlEscapeOfCriteriaQuery")); assertFalse((boolean) ReflectionTestUtils.getField(tag, "enableLinkOfCurrentPage")); assertNull(ReflectionTestUtils.getField(tag, "outerElement")); assertNull(ReflectionTestUtils.getField(tag, "outerElementClass")); assertNull(ReflectionTestUtils.getField(tag, "innerElement")); assertNull(ReflectionTestUtils.getField(tag, "innerElementClass")); assertNull(ReflectionTestUtils.getField(tag, "firstLinkText")); assertNull(ReflectionTestUtils.getField(tag, "previousLinkText")); assertNull(ReflectionTestUtils.getField(tag, "nextLinkText")); assertNull(ReflectionTestUtils.getField(tag, "lastLinkText")); assertNull(ReflectionTestUtils.getField(tag, "disabledHref")); assertNull(ReflectionTestUtils.getField(tag, "activeClass")); assertNull(ReflectionTestUtils.getField(tag, "disabledClass")); }
Source:
<code>public void setNavigator(Person p) { <START> setNavigator(Objects.requireNonNull(p), false); <END> }</code><technical_language>this duplicate nonNull check</technical_language>

Target:
public void setNavigator(Person p) { setNavigator(p, false); }
Source:
<code>private void updateContentFiles(List<Process> processes) { for (Process proz : processes) { try { FileformatInterface myRdf = serviceManager.getProcessService().readMetadataFile(proz); myRdf.getDigitalDocument().addAllContentFiles(); serviceManager.getFileService().writeMetadataFile(myRdf, proz); Helper.setMeldung("kitodoScriptfield", "ContentFiles updated: ", proz.getTitle()); <START> } catch (org.kitodo.api.ugh.exceptions.DocStructHasNoTypeException e) { <END> Helper.setFehlerMeldung("DocStructHasNoTypeException", e.getMessage()); } catch (Exception e) { Helper.setFehlerMeldung("kitodoScriptfield", "Error while updating content files", e); } } Helper.setMeldung("kitodoScriptfield", "", "updateContentFiles finished"); }</code><technical_language>Add this exception in imports</technical_language>

Target:
private void updateContentFiles(List<Process> processes) { for (Process proz : processes) { try { FileformatInterface myRdf = serviceManager.getProcessService().readMetadataFile(proz); myRdf.getDigitalDocument().addAllContentFiles(); serviceManager.getFileService().writeMetadataFile(myRdf, proz); Helper.setMeldung("kitodoScriptfield", "ContentFiles updated: ", proz.getTitle()); } catch (DocStructHasNoTypeException e) { Helper.setFehlerMeldung("DocStructHasNoTypeException", e.getMessage()); } catch (Exception e) { Helper.setFehlerMeldung("kitodoScriptfield", "Error while updating content files", e); } } Helper.setMeldung("kitodoScriptfield", "", "updateContentFiles finished"); }
Source:
<code>protected SqlNode parseAndValidate(String sql) { <START> Objects.requireNonNull(m_validator, "m_validator"); <END> SqlNode sqlNode; try { sqlNode = SqlParserFactory.parse(sql); } catch (Throwable e) { throw new RuntimeException("Error while parsing query: " + sql, e); } return m_validator.validate(sqlNode); }</code><technical_language>I JUnit's assertNotNull("m_validator is null", m_validator); here. In case m_validator is null, Objects.requireNonNull method [throw NPE](<LINK_0></technical_language>

Target:
protected SqlNode parseAndValidate(String sql) { assertNotNull("m_validator is null", m_validator); SqlNode sqlNode; try { sqlNode = SqlParserFactory.parse(sql); } catch (Throwable e) { throw new RuntimeException("Error while parsing query: " + sql, e); } return m_validator.validate(sqlNode); }
Source:
<code>public Optional<Git> getGitRepo() { <START> if (gitRepo != null) { <END> return Optional.of(gitRepo); } else { return Optional.empty(); } }</code><technical_language>This pattern is captured in Optional's [ofNullable](<LINK_0> method, in this case body of method simplified Optional.ofNullable(gitRepo) Similarly for other methods in this class. get rid of boilerplate :)</technical_language>

Target:
public Optional<Git> getGitRepo() { return Optional.ofNullable(gitRepo); }
Source:
<code>public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { <START> ElytronMessages.tls.tracef("AtomicLoadKeyStore loading: stream = %s, password = %b", stream, password); <END> try { KeyStore keyStore = keyStoreFactory.getInstance(); keyStore.load(stream, password); currentStore.set(keyStore); } catch (KeyStoreException e) { throw log.unableToCreateKeyStore(e); } }</code><technical_language>avoid logging passwords, some end users audit log files ensure passwords logged</technical_language>

Target:
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { ElytronMessages.tls.tracef("AtomicLoadKeyStore loading: stream = %s, password = %b", stream, password != null); try { KeyStore keyStore = keyStoreFactory.getInstance(); keyStore.load(stream, password); currentStore.set(keyStore); } catch (KeyStoreException e) { throw log.unableToCreateKeyStore(e); } }
Source:
<code>protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final long start = System.currentTimeMillis(); <START> boolean willBeLogged = false; <END> try { filterChain.doFilter(request, response); if (request.isAsyncStarted()) { request.getAsyncContext().addListener(new AsyncRequestListener(request, response, start)); willBeLogged = true; } } finally { if(!willBeLogged) { writeToAccessLogAndEventType(request, response, start); } } }</code><technical_language>exchanged request.isAsyncStarted()</technical_language>

Target:
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws IOException, ServletException{ final long start = System.currentTimeMillis(); try { filterChain.doFilter(request, response); if (request.isAsyncStarted()) { final String flowId = FlowIdUtils.peek(); request.getAsyncContext().addListener(new AsyncRequestListener(request, response, start, flowId)); } } finally { if(!request.isAsyncStarted()) { final RequestLogInfo requestLogInfo = new RequestLogInfo(request, start); writeToAccessLogAndEventType(requestLogInfo, response); } } }
Source:
<code>public boolean hasNext() { computeNext(); <START> return (next != null); <END> }</code><technical_language>nit: parenthesis extra</technical_language>

Target:
public boolean hasNext() { try { return fileStatusIterator.hasNext(); } catch (IOException e) { throw processException(e); } }
Source:
<code>public void init() { <START> if (this.url.substring(this.url.length() - 1) != "/") { <END> this.url += "/"; } }</code><technical_language>url.endsWith("/") easier comprehend. String comparison done equals, == !=</technical_language>

Target:
public void init() { if (!this.url.endsWith("/")) { this.url += "/"; } }
Source:
<code>public void sendCalendarSyncErrorNotification(String calendarName, Absence absence, String exception) { Map<String, Object> model = new HashMap<>(); model.put(CALENDAR, calendarName); model.put("absence", absence); model.put(EXCEPTION, exception); <START> final Mail toTechnical = Mail.builder() <END> .withRecipient(true) .withSubject("subject.error.calendar.sync") .withTemplate("error_calendar_sync", model) .build(); mailService.send(toTechnical); }</code><technical_language>Rename variable mailToTechnical</technical_language>

Target:
public void sendCalendarSyncErrorNotification(String calendarName, Absence absence, String exception) { Map<String, Object> model = new HashMap<>(); model.put(CALENDAR, calendarName); model.put("absence", absence); model.put(EXCEPTION, exception); final Mail mailToTechnical = Mail.builder() .withTechnicalRecipient(true) .withSubject("subject.error.calendar.sync") .withTemplate("error_calendar_sync", model) .build(); mailService.send(mailToTechnical); }
Source:
<code>protected void demandRemoteResolve(SynchronizedResourceSet resourceSet, URI uri, final ThreadSafeProgressMonitor monitor) { if (isInterruptedOrCanceled(monitor)) { demandResolvingAndUnloadingPoolShutdown(); return; } Collection<URI> uriCollection = dependencyProviderRegistry.getDependencies(uri); for (URI currentUri : uriCollection) { <START> lock.lock(); <END> try { if (resolvedResources.add(currentUri) && currentlyResolving.add(currentUri)) { monitor.setWorkRemaining(1000); ListenableFuture<?> future = resolvingPool.submit(new RemoteResourceResolver(resourceSet, currentUri, monitor)); Futures.addCallback(future, new ResolvingFutureCallback(monitor, currentUri)); } } finally { lock.unlock(); } } }</code><technical_language>lock of this loop? locking unlocking, is useful</technical_language>

Target:
protected void demandRemoteResolve(SynchronizedResourceSet resourceSet, URI uri, final ThreadSafeProgressMonitor monitor) { if (isInterruptedOrCanceled(monitor)) { demandResolvingAndUnloadingPoolShutdown(); return; } Collection<URI> uriCollection = dependencyProviderRegistry.getDependencies(uri); lock.lock(); try { for (URI currentUri : uriCollection) { if (resolvedResources.add(currentUri) && currentlyResolving.add(currentUri)) { monitor.setWorkRemaining(1000); ListenableFuture<?> future = resolvingPool.submit(new RemoteResourceResolver(resourceSet, currentUri, monitor)); Futures.addCallback(future, new ResolvingFutureCallback(monitor, currentUri)); } } } finally { lock.unlock(); } }
Source:
<code>private void setMinScaffoldingSeedLength(GenomixJobConf conf) throws IOException { Counters counters = GraphStatistics.run(curOutput, curOutput + "-kmerLength-stats", conf); long totalNodes = counters.getGroup("totals").getCounter("nodes"); float percentage = 0.2f; long numOfSeeds; if (Math.abs((float) totalNodes * percentage) < 100) numOfSeeds = (long) Math.abs((float) totalNodes * percentage); else numOfSeeds = 100; long curNumOfSeeds = 0; <START> for (Counter c : counters.getGroup("kmerLength-bins")) { <END> curNumOfSeeds += c.getValue(); if (curNumOfSeeds > numOfSeeds) { conf.setInt(GenomixJobConf.MIN_SCAFFOLDING_SEED_LENGTH, Integer.parseInt(c.getName())); return; } } throw new IllegalStateException("It is impossible to reach here!"); }</code><technical_language>this return values in order? this algorithm relies bins ordered (so small first, right?)</technical_language>

Target:
private void setMinScaffoldingSeedLength(GenomixJobConf conf) throws IOException { Counters counters = GraphStatistics.run(curOutput, curOutput + "-kmerLength-stats", conf); long totalNodes = counters.getGroup("totals").getCounter("nodes"); float fraction = 0.01f; long numOfSeeds; if (Math.round((float) totalNodes * fraction) < 100) numOfSeeds = (long) Math.round((float) totalNodes * fraction); else numOfSeeds = 100; ArrayList<Long> sortedCounter = new ArrayList<Long>(); int maxLength = sortCounters(counters.getGroup("kmerLength-bins"), sortedCounter); long curNumOfSeeds = 0; for (int i = sortedCounter.size() - 1; i >= 0; i--) { curNumOfSeeds += sortedCounter.get(i); if (curNumOfSeeds > numOfSeeds) { conf.setInt(GenomixJobConf.MIN_SCAFFOLDING_SEED_LENGTH, maxLength - (sortedCounter.size() - 1 - i)); return; } } throw new IllegalStateException("It is impossible to reach here!"); }
Source:
<code>public ResourceNotFoundException(IdString id) { <START> super(id.encoded()); <END> }</code><technical_language>this be: super(id.get()) ? in some other places [1] provide decoded id ResourceNotFoundException(String). in places, decoded id encoded id? [1] <LINK_0></technical_language>

Target:
public ResourceNotFoundException(IdString id) { super(id.get()); }
Source:
<code>private static @Nullable IAnalysisModuleHelper findModule(Iterable<IAnalysisModuleHelper> modules, String moduleName) { <START> for (IAnalysisModuleHelper helper : modules) { if (moduleName.equals(helper.getId())) { return helper; } } return null; } <END></code><technical_language>if Optional, replace Iterables.tryFind(modules, helper -> moduleName.equals(helper.getId()));</technical_language>

Target:
private static @Nullable IAnalysisModuleHelper findModule(Iterable<IAnalysisModuleHelper> modules, String moduleName) { return Iterables.tryFind(modules, helper -> moduleName.equals(helper.getId())).orNull(); }
Source:
<code>public <C extends IdCredentials> ListBoxModel getCredentialIds(@NonNull Class<C> type, @Nullable ItemGroup itemGroup, @Nullable Authentication authentication, @NonNull List<DomainRequirement> domainRequirements, @NonNull CredentialsMatcher matcher) { ListBoxModel result = new ListBoxModel(); Set<String> ids = new HashSet<String>(); if (ACL.SYSTEM.equals(authentication)) { while (itemGroup != null) { if (itemGroup instanceof AbstractFolder) { final AbstractFolder<?> folder = AbstractFolder.class.cast(itemGroup); FolderCredentialsProperty property = folder.getProperties().get(FolderCredentialsProperty.class); if (property != null) { for (C c : DomainCredentials.getCredentials( property.getDomainCredentialsMap(), type, domainRequirements, matcher)) { if (ids.add(c.getId())) { result.add(CredentialsNameProvider.name(c), c.getId()); } } } } if (itemGroup instanceof Item) { <START> itemGroup = Item.class.cast(itemGroup).getParent(); <END> } else { break; } } } return result; }</code><technical_language>java itemGroup = ((Item) itemGroup).getParent();</technical_language>

Target:
public <C extends IdCredentials> ListBoxModel getCredentialIds(@NonNull Class<C> type, @Nullable ItemGroup itemGroup, @Nullable Authentication authentication, @NonNull List<DomainRequirement> domainRequirements, @NonNull CredentialsMatcher matcher) { ListBoxModel result = new ListBoxModel(); Set<String> ids = new HashSet<String>(); if (ACL.SYSTEM.equals(authentication)) { while (itemGroup != null) { if (itemGroup instanceof AbstractFolder) { final AbstractFolder<?> folder = AbstractFolder.class.cast(itemGroup); FolderCredentialsProperty property = folder.getProperties().get(FolderCredentialsProperty.class); if (property != null) { for (C c : DomainCredentials.getCredentials( property.getDomainCredentialsMap(), type, domainRequirements, matcher)) { if (ids.add(c.getId())) { result.add(CredentialsNameProvider.name(c), c.getId()); } } } } if (itemGroup instanceof Item) { itemGroup = ((Item)itemGroup).getParent(); } else { break; } } } return result; }
Source:
<code>public void creatTable( CairoSecurityContext securityContext, AppendMemory mem, Path path, TableStructure struct ) { <START> CairoSecurityContext.checkWritePermission(securityContext); <END> TableUtils.createTable( configuration.getFilesFacade(), mem, path, configuration.getRoot(), struct, configuration.getMkDirMode() ); }</code><technical_language>static call a strange here. I expecting java securityContext.checkWritePermission();</technical_language>

Target:
public void creatTable( CairoSecurityContext securityContext, AppendMemory mem, Path path, TableStructure struct ) { securityContext.checkWritePermission(); TableUtils.createTable( configuration.getFilesFacade(), mem, path, configuration.getRoot(), struct, configuration.getMkDirMode() ); }
Source:
<code>protected void reject(Diff diff, boolean rightToLeft) { final Optional<OpaqueElementBodyChange> possibleBodyChange = getOpaqueElementBodyChange(diff); if (possibleBodyChange.isPresent()) { final OpaqueElementBodyChange bodyChange = possibleBodyChange.get(); if (LOGGER.isDebugEnabled()) { int refinedElementCount = bodyChange.getRefinedBy().size(); <START> LOGGER.debug("Reject OpaqueElement change - " + refinedElementCount + " refined diffs merged"); END> } switch (bodyChange.getKind()) { case ADD: rejectRefiningDiffs(bodyChange, rightToLeft); break; case DELETE: rejectRefiningDiffs(bodyChange, rightToLeft); break; case CHANGE: changeElement(bodyChange, rightToLeft); break; case MOVE: moveElement(bodyChange, rightToLeft); break; default: break; } } }</code><technical_language>This is consistent log in previous method "reject(Diff, boolean) - " + refinedElementCount + " refined diffs reject for diff " + diff.hashCode()</technical_language>

Target:
protected void reject(Diff diff, boolean rightToLeft) { final Optional<OpaqueElementBodyChange> possibleBodyChange = getOpaqueElementBodyChange(diff); if (possibleBodyChange.isPresent()) { final OpaqueElementBodyChange bodyChange = possibleBodyChange.get(); if (LOGGER.isDebugEnabled()) { int refinedElementCount = bodyChange.getRefinedBy().size(); LOGGER.debug("Reject(Diff, boolean)" + refinedElementCount + " refined diffs to merge for diff " + diff.hashCode()); } switch (bodyChange.getKind()) { case ADD: rejectRefiningDiffs(bodyChange, rightToLeft); break; case DELETE: rejectRefiningDiffs(bodyChange, rightToLeft); break; case CHANGE: changeElement(bodyChange, rightToLeft); break; case MOVE: moveElement(bodyChange, rightToLeft); break; default: break; } } }
Source:
<code>private Set<Class<?>> getParentTypes(String name, Class<?> type) { String[] path = name.split("\\."); try { for (int i = 0; i < path.length - 1; i++) { Field field = checkNotNull(new Mirror().on(type).reflect().field(path[i])); type = getActualType(field.getGenericType()); } if (!isIgnoreFieldNotFound()) checkNotNull(new Mirror().on(type).reflect().field(path[path.length -1])); <START> } catch (NullPointerException e) { <END> throw new IllegalArgumentException("Field path '" + name + "' doesn't exists in " + type, e); } Set<Class<?>> types = new HashSet<>(); while (type != Object.class) { types.add(type); type = type.getSuperclass(); } return types; }</code><technical_language>This work for fields in between: object.sub.path if exist object, throw IllegalArgExc</technical_language>

Target:
private Set<Class<?>> getParentTypes(String name, Class<?> type) { String[] path = name.split("\\."); try { for (int i = 0; i < path.length; i++) { Field field = reflectField(path[i], type); if (field == null) break; if (i < path.length - 1) type = getActualType(field.getGenericType()); } } catch (NullPointerException e) { throw new IllegalArgumentException("Field path '" + name + "' doesn't exists in " + type, e); } Set<Class<?>> types = new HashSet<>(); while (type != Object.class) { types.add(type); type = type.getSuperclass(); } return types; }
Source:
<code>public void setMaxWriteDelay(int maxWriteDelay) { if (maxWriteDelay < 0) { throw new IllegalArgumentException("Maximum write delay cannot be less than 1"); } else if (maxWriteDelay < minWriteDelay) { <START> throw new IllegalArgumentException("Maximum write delay must be larger than minimum write delay"); <END> } this.maxWriteDelay = maxWriteDelay; }</code><technical_language>larger equal</technical_language>

Target:
public void setMaxWriteDelay(int maxWriteDelay) { if (maxWriteDelay < 0) { throw new IllegalArgumentException("Maximum write delay cannot be less than 1"); } else if (maxWriteDelay < minWriteDelay) { throw new IllegalArgumentException("Maximum write delay (" + maxWriteDelay + ") must be larger than or equal to minimum write delay (" + minWriteDelay + ")"); } this.maxWriteDelay = maxWriteDelay; }
Source:
<code>public void testEnsureNextSequenceIsCalledLazilyInToYielder() throws Exception { final AtomicBoolean lastSeqFullyRead = new AtomicBoolean(true); Sequence<Integer> seq = Sequences.concat( Sequences.map( Sequences.simple( ImmutableList.of( ImmutableList.of(1, 2, 3), ImmutableList.of(4, 5, 6) ) ), new Function<ImmutableList<Integer>, Sequence<Integer>>() { @Override public Sequence<Integer> apply(final ImmutableList<Integer> input) { if (lastSeqFullyRead.getAndSet(false)) { return Sequences.simple( new Iterable<Integer>() { private Iterator<Integer> baseIter = input.iterator(); @Override <START> public Iterator<Integer> iterator() <END> { return new Iterator<Integer>() { @Override public boolean hasNext() { boolean result = baseIter.hasNext(); if(!result) { lastSeqFullyRead.set(true); } return result; } @Override public Integer next() { return baseIter.next(); } }; } } ); } else { throw new IllegalStateException("called before previous sequence is read fully"); } } } ) ); Yielder<Integer> yielder = seq.toYielder( null, new YieldingAccumulator<Integer, Integer>() { @Override public Integer accumulate(Integer accumulated, Integer in) { yield(); return in; } } ); List<Integer> result = new ArrayList<>(); while(!yielder.isDone()) { result.add(yielder.get()); yielder = yielder.next(null); } yielder.close(); Assert.assertEquals(ImmutableList.of(1,2,3,4,5,6), result); }</code><technical_language>coding in java8 :) this is missing some stuff causing unit tests fail in java7</technical_language>

Target:
public void testEnsureNextSequenceIsCalledLazilyInToYielder() throws Exception { final AtomicBoolean lastSeqFullyRead = new AtomicBoolean(true); Sequence<Integer> seq = Sequences.concat( Sequences.map( Sequences.simple( ImmutableList.of( ImmutableList.of(1, 2, 3), ImmutableList.of(4, 5, 6) ) ), new Function<ImmutableList<Integer>, Sequence<Integer>>() { @Override public Sequence<Integer> apply(final ImmutableList<Integer> input) { if (lastSeqFullyRead.getAndSet(false)) { return Sequences.simple( new Iterable<Integer>() { private Iterator<Integer> baseIter = input.iterator(); @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { boolean result = baseIter.hasNext(); if(!result) { lastSeqFullyRead.set(true); } return result; } @Override public Integer next() { return baseIter.next(); } @Override public void remove() { throw new UnsupportedOperationException("Remove Not Supported"); } }; } } ); } else { throw new IllegalStateException("called before previous sequence is read fully"); } } } ) ); Yielder<Integer> yielder = seq.toYielder( null, new YieldingAccumulator<Integer, Integer>() { @Override public Integer accumulate(Integer accumulated, Integer in) { yield(); return in; } } ); List<Integer> result = new ArrayList<>(); while(!yielder.isDone()) { result.add(yielder.get()); yielder = yielder.next(null); } yielder.close(); Assert.assertEquals(ImmutableList.of(1,2,3,4,5,6), result); }
Source:
<code>public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { boolean doSetGamemode = false; GameMode targetGamemode = GameMode.CREATIVE; if (args.length != 0) { if (args[0].equals("-c")) { doSetGamemode = true; targetGamemode = GameMode.CREATIVE; } else if (args[0].equals("-s")) { doSetGamemode = true; targetGamemode = GameMode.SURVIVAL; } } <START> <END> for (Player player : server.getOnlinePlayers()) { if (!player.isOp()) { TFM_Util.adminAction(sender.getName(), "Opping all players on the server", false); player.setOp(true); player.sendMessage(TFM_Command.YOU_ARE_OP); } else { playerMsg("All players are currently Op."); return false; } if (doSetGamemode) { player.setGameMode(targetGamemode); } } return true; }</code><technical_language>this is here.. a big deal, idea here</technical_language>

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { boolean doSetGamemode = false; GameMode targetGamemode = GameMode.CREATIVE; if (args.length != 0) { if (args[0].equals("-c")) { doSetGamemode = true; targetGamemode = GameMode.CREATIVE; } else if (args[0].equals("-s")) { doSetGamemode = true; targetGamemode = GameMode.SURVIVAL; } } for (Player player : server.getOnlinePlayers()) { if (!player.isOp()) { TFM_Util.adminAction(sender.getName(), "Opping all players on the server", false); player.setOp(true); player.sendMessage(TFM_Command.YOU_ARE_OP); } else { playerMsg("All players are currently Op."); } if (doSetGamemode) { player.setGameMode(targetGamemode); } } return true; }
Source:
<code>public ExerciseUpdateHandler(ExerciseChecksumCache cache, TmcApi tmcApi) throws TmcCoreException { super(tmcApi); exerciseChecksums = new HashMap<>(); if (cache == null) { String errorMessage = "ExerciseUpdateHandler requires non-null cacheFile to function"; <START> throw new TmcCoreException(errorMessage); <END> } this.cache = cache; }</code><technical_language>inline error message</technical_language>

Target:
public ExerciseUpdateHandler(ExerciseChecksumCache cache, TmcApi tmcApi) throws TmcCoreException { super(tmcApi); exerciseChecksums = new HashMap<>(); if (cache == null) { throw new TmcCoreException( "ExerciseUpdateHandler requires non-null cacheFile to function"); } this.cache = cache; }
Source:
<code>private void addShellOutputListener(final IHostShell shell, final IControllableServerBehavior behavior) { if( shell == null ) return; IHostShellOutputListener listener = null; listener = new IHostShellOutputListener() { public void shellOutputChanged(IHostShellChangeEvent event) { IHostOutput[] out = event.getLines(); for (int i = 0; i < out.length; i++) { <START> if( out[i].toString().startsWith(ECHO_KEY_DISCOVER_PID)) { <END> int lastColon = out[i].toString().lastIndexOf(DELIMETER); String pid = out[i].toString().substring(lastColon+1); behavior.putSharedData(IDeployableServerBehaviorProperties.PROCESS_ID, pid); } } } }; shell.addOutputListener(listener); }</code><technical_language>out[i].toString() instead of 3 times in this loop</technical_language>

Target:
private void addShellOutputListener(final IHostShell shell, final IControllableServerBehavior behavior) { if( shell == null ) return; IHostShellOutputListener listener = null; listener = new IHostShellOutputListener() { public void shellOutputChanged(IHostShellChangeEvent event) { IHostOutput[] out = event.getLines(); String s = null; for (int i = 0; i < out.length; i++) { s = out[i].toString(); if( s.startsWith(ECHO_KEY_DISCOVER_PID)) { int lastColon = s.lastIndexOf(DELIMETER); String pid = s.substring(lastColon+1); behavior.putSharedData(IDeployableServerBehaviorProperties.PROCESS_ID, pid); } } } }; shell.addOutputListener(listener); }
Source:
<code>public void cleanupExpiredPools() { List<Pool> pools = poolCurator.listExpiredPools(); log.info("Expired pools: " + pools.size()); for (Pool p : pools) { if (p.hasAttribute("derived_pool")) { continue; } log.info("Cleaning up expired pool: " + p.getId() + " (" + p.getEndDate() + ")"); if (!subAdapter.isReadOnly()) { Subscription sub = subAdapter.getSubscription(p.getSubscriptionId()); if (sub != null) { subAdapter.deleteSubscription(sub); } deletePool(p); <START> } <END> } }</code><technical_language>pool deletion happen if subs r/o</technical_language>

Target:
public void cleanupExpiredPools() { List<Pool> pools = poolCurator.listExpiredPools(); log.info("Expired pools: " + pools.size()); for (Pool p : pools) { if (p.hasAttribute("derived_pool")) { continue; } log.info("Cleaning up expired pool: " + p.getId() + " (" + p.getEndDate() + ")"); if (!subAdapter.isReadOnly()) { Subscription sub = subAdapter.getSubscription(p.getSubscriptionId()); if (sub != null) { subAdapter.deleteSubscription(sub); } } deletePool(p); } }
Source:
<code>public void EditAccount_003_reopenAccount() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); EditAccount editAccount = new EditAccount(driver, testedWiki, credentials.userNameClosedAccount); <START> editAccount.reopenAccount(credentials.passwordClosedAccount); <END> }</code><technical_language>add verifying step</technical_language>

Target:
public void EditAccount_003_reopenAccount() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); EditAccount editAccount = new EditAccount(driver, testedWiki, credentials.userNameClosedAccount); editAccount.reopenAccount(credentials.passwordClosedAccount); editAccount.verifyAccountReopenedMessage(); }
Source:
<code>public void setup() { cache = mock(InternalCache.class); command = spy(new ClearCommand()); region = mock(Region.class); dataResult = mock(DataCommandResult.class); <START> membersList = new HashSet<DistributedMember>(); <END> membersList.add(member); doNothing().when(command).authorize(any(), any(), anyString()); doReturn(cache).when(command).getCache(); doReturn(membersList).when(command).findAnyMembersForRegion(anyString()); ResultModel result = ResultModel.createInfo(success); doReturn(result).when(dataResult).toResultModel(); }</code><technical_language>necessary DistributedMember here, implicit in declaration of membersList set</technical_language>

Target:
public void setup() { cache = mock(InternalCache.class); command = spy(new ClearCommand()); region = mock(Region.class); dataResult = mock(DataCommandResult.class); membersList = new HashSet<>(); membersList.add(member); doNothing().when(command).authorize(any(), any(), anyString()); doReturn(cache).when(command).getCache(); doReturn(membersList).when(command).findAnyMembersForRegion(anyString()); ResultModel result = ResultModel.createInfo(success); doReturn(result).when(dataResult).toResultModel(); }
Source:
<code>public File toFile(URI fileURI, InputStream templateStream, ParamsTree<String, String> documentParams) throws ExportServiceException { File pdffile = new File(fileURI); OutputStream out; <START> try { <END> out = new FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); FileOutputStream str = new FileOutputStream(pdffile); this.transformToStream(templateStream, documentParams, out); str.close(); out.close(); return pdffile; } catch (FileNotFoundException e) { throw new ExportServiceException("Could not create pdf file", e); } catch (IOException e) { throw new ExportServiceException( "IO error while saving the pdf file", e); } }</code><technical_language>please java7 auto-close facility</technical_language>

Target:
public File toFile(URI fileURI, InputStream templateStream, ParamsTree<String, String> documentParams) throws ExportServiceException { File pdffile = new File(fileURI); try (OutputStream out = new java.io.BufferedOutputStream(new FileOutputStream(pdffile))) { this.transformToStream(templateStream, documentParams, out); return pdffile; } catch (FileNotFoundException e) { throw new ExportServiceException("Could not create pdf file", e); } catch (IOException e) { throw new ExportServiceException("IO error while saving the pdf file", e); } }
Source:
<code>public void tearDown() throws Exception { <START> System.setProperty("curator-default-connection-timeout", "15000"); <END> }</code><technical_language>remove property, set it</technical_language>

Target:
public void tearDown() throws Exception { System.clearProperty("curator-default-connection-timeout"); }
Source:
<code>public ExecutionInterval getBegin() { <START> return Collections.min(getBeginContextExecutionYears(), ExecutionYear.COMPARATOR_BY_YEAR); <END> }</code><technical_language>Beware if DCP execution year, this throw a NoSuchElementException, instead of returning null</technical_language>

Target:
public ExecutionInterval getBegin() { Set<ExecutionYear> beginContextExecutionYears = getBeginContextExecutionYears(); return beginContextExecutionYears.isEmpty() ? null : Collections.min(beginContextExecutionYears, ExecutionYear.COMPARATOR_BY_YEAR); }
Source:
<code>public void remove() { if (this.lastRetIndex < 0) { logger.logAndThrow(new IllegalStateException()); return; } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { <START> logger.logAndThrow(new ConcurrentModificationException()); <END> return; } } }</code><technical_language>Wrap ConcurrentModificationException IndexOutOfBoundsException cause</technical_language>

Target:
public void remove() { if (this.lastRetIndex < 0) { throw logger.logExceptionAsError(new IllegalStateException()); } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw logger.logExceptionAsError(new ConcurrentModificationException(ex)); } } }
Source:
<code>public void commit() throws IOException { close(); try { <START> Files.move(tmpFile, destFile, StandardCopyOption.ATOMIC_MOVE); <END> } catch (IOException e) { Files.move(tmpFile, destFile, StandardCopyOption.REPLACE_EXISTING); } }</code><technical_language>Do _also_ want REPLACE_EXISTING here? In case destFile existed? (Is this case tested?)</technical_language>

Target:
public void commit() throws IOException { close(); try { Files.move(tmpPath, destPath, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { if (e instanceof AtomicMoveNotSupportedException) { LOGGER.log(Level.WARNING, "Atomic move not supported. falling back to non-atomic move.", e); } else { LOGGER.log(Level.WARNING, "Unable to move atomically, falling back to non-atomic move.", e); } if (destPath.toFile().exists()) { LOGGER.log(Level.INFO, "The target file {0} was already existing", destPath); } try { Files.move(tmpPath, destPath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e1) { e1.addSuppressed(e); LOGGER.log(Level.WARNING, "Unable to move {0} to {1}. Attempting to delete {0} and abandoning.", new Path[]{tmpPath, destPath}); try { Files.deleteIfExists(tmpPath); } catch (IOException e2) { e2.addSuppressed(e1); LOGGER.log(Level.WARNING, "Unable to delete {0}, good bye then!", tmpPath); throw e2; } throw e1; } } }
Source:
<code>protected void handleNotificationEvent(Notification notification) { super.handleNotificationEvent(notification); <START> super.refresh(); <END> }</code><technical_language>try check notifier force a refresh</technical_language>

Target:
protected void handleNotificationEvent(Notification notification) { super.handleNotificationEvent(notification); Object notifier = notification.getNotifier(); Object oldValue = notification.getOldValue(); if (notifier instanceof EAnnotation) { if (((EAnnotation) notifier).getSource().equalsIgnoreCase(NamedStyleProperties.CSS_FORCE_VALUE)) { super.refresh(); } } else if (oldValue instanceof EAnnotation) { if (((EAnnotation) oldValue).getSource().equalsIgnoreCase(NamedStyleProperties.CSS_FORCE_VALUE)) { super.refresh(); } } }