auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public VertxOptions setFileResolverCachingEnabled(boolean fileResolverCachingEnabled) { <START> this.fileSystemOptions.setFileResolverCachingEnabled(fileResolverCachingEnabled); <END> return this; }</code><technical_language>missing null check</technical_language>

Target:
public VertxOptions setFileResolverCachingEnabled(boolean fileResolverCachingEnabled) { if (fileSystemOptions == null) { fileSystemOptions = new FileSystemOptions(); } this.fileSystemOptions.setFileResolverCachingEnabled(fileResolverCachingEnabled); return this; }
Source:
<code>public Configuration toConfiguration(final CommandLine commandLine) { final Configuration resultConfiguration = new Configuration(); <START> if (configuration.getOptional(DeploymentOptions.TARGET).isPresent()) { <END> resultConfiguration.set( DeploymentOptions.TARGET, configuration.get(DeploymentOptions.TARGET)); } final String executorName = commandLine.getOptionValue(executorOption.getOpt()); if (executorName != null) { resultConfiguration.setString(DeploymentOptions.TARGET, executorName); } final String targetName = commandLine.getOptionValue(targetOption.getOpt()); if (targetName != null) { resultConfiguration.setString(DeploymentOptions.TARGET, targetName); } DynamicPropertiesUtil.encodeDynamicProperties(commandLine, resultConfiguration); resultConfiguration.set(DeploymentOptionsInternal.CONF_DIR, configurationDir); return resultConfiguration; }</code><technical_language>explain a bit do remove this if() block? If is in base configuration, add later, right</technical_language>

Target:
public Configuration toConfiguration(final CommandLine commandLine) { final Configuration resultConfiguration = new Configuration(); final String executorName = commandLine.getOptionValue(executorOption.getOpt()); if (executorName != null) { resultConfiguration.setString(DeploymentOptions.TARGET, executorName); } final String targetName = commandLine.getOptionValue(targetOption.getOpt()); if (targetName != null) { resultConfiguration.setString(DeploymentOptions.TARGET, targetName); } DynamicPropertiesUtil.encodeDynamicProperties(commandLine, resultConfiguration); resultConfiguration.set(DeploymentOptionsInternal.CONF_DIR, configurationDir); return resultConfiguration; }
Source:
<code>public Transaction process(Transaction transaction) throws IOException, JSONException { LOGGER.info("Attempting to process user with id={}", transaction.getUserId()); <START> System.out.println("Attempting to process user with id=" + transaction.getUserId()); <END> HttpResponse response = fetchMoreUserDetails(transaction.getUserId()); String result = EntityUtils.toString(response.getEntity()); JSONObject userObject = new JSONObject(result); transaction.setAge(Integer.parseInt(userObject.getString("age"))); transaction.setPostCode(userObject.getString("postCode")); return transaction; }</code><technical_language>need for System.out here</technical_language>

Target:
public Transaction process(Transaction transaction) throws IOException, JSONException { LOGGER.info("Attempting to process user with id={}", transaction.getUserId()); HttpResponse response = fetchMoreUserDetails(transaction.getUserId()); String result = EntityUtils.toString(response.getEntity()); JSONObject userObject = new JSONObject(result); transaction.setAge(Integer.parseInt(userObject.getString("age"))); transaction.setPostCode(userObject.getString("postCode")); return transaction; }
Source:
<code>public void print(TaskListener listener) { listener.getLogger().println(Messages.Cause_UserIdCause_ShortDescription( <START> ModelHyperlinkNote.encodeTo(User.getOrCreateByIdOrFullName(getUserIdOrUnknown())))); <END> }</code><technical_language>This produce a bogus hyperlink if user is unknown: <LINK_0> do wish create a hyperlink is link to. want do lookup ID only, full name</technical_language>

Target:
public void print(TaskListener listener) { User user = getUserId() == null ? null : User.getById(getUserId(), false); if (user != null) { listener.getLogger().println(Messages.Cause_UserIdCause_ShortDescription( ModelHyperlinkNote.encodeTo(user))); } else { listener.getLogger().println(Messages.Cause_UserIdCause_ShortDescription( "unknown or anonymous")); } }
Source:
<code>public synchronized void releaseEditor() { if (!locked) { throw new IllegalStateException("Editor not locked!"); } List<Action> singletonList = new ArrayList<>(); <START> singletonList.add((support) -> releaseInternal()); <END> executeAsync(singletonList); }</code><technical_language>Name method 'releaseEditorInternal' instead of 'releaseInternal' for consistency 'lockEditorInternal'</technical_language>

Target:
public synchronized void releaseEditor() { if (!locked) { throw new IllegalStateException("Editor not locked!"); } List<Action> singletonList = new ArrayList<>(); singletonList.add((support) -> releaseEditorInternal()); executeAsync(singletonList); }
Source:
<code>public void clearCooldown() { SplitFileInserterSender s; synchronized(this) { s = sender; } if(s != null) s.clearWakeupTime(context); else <START> Logger.error(this, "Sender is null in clearCooldown()!", new Exception()); <END> }</code><technical_language>happen? Is a bug if is? assert more sense</technical_language>

Target:
public void clearCooldown() { sender.clearWakeupTime(context); }
Source:
<code>protected void init() { smtpFromAddress = computeFrom(); if (changeMessage != null && changeMessage.getWrittenOn() != null) { setHeader("Date", new Date(changeMessage.getWrittenOn().getTime())); } else { setHeader("Date", new Date()); } headers.put("From", new EmailHeader.AddressList(smtpFromAddress)); headers.put(HDR_TO, new EmailHeader.AddressList()); headers.put(HDR_CC, new EmailHeader.AddressList()); if (change != null) { setChangeSubjectHeader(); } setHeader("Message-ID", ""); setHeader("MIME-Version", "1.0"); setHeader("Content-Type", "text/plain; charset=UTF-8"); setHeader("Content-Disposition", "inline"); setHeader("User-Agent", "Gerrit/" + Version.getVersion()); setHeader("X-Gerrit-MessageType", messageClass); if (change != null) { setHeader("X-Gerrit-ChangeId", "" + change.getChangeId()); setListIdHeader(); setChangeUrlHeader(); setCommitIdHeader(); } body = new StringBuilder(); inFooter = false; if (change != null && db != null) { if (patchSet == null) { try { patchSet = db.patchSets().get(change.currentPatchSetId()); } catch (OrmException err) { patchSet = null; } } if (patchSet != null && patchSetInfo == null) { try { patchSetInfo = <START> PatchSetInfoFactory.patchSetInfoFromPatchSetId(patchSet.getId()); <END> } catch (PatchSetInfoNotAvailableException err) { patchSetInfo = null; } } } }</code><technical_language>accessible static method anymore, is it</technical_language>

Target:
protected void init() { smtpFromAddress = computeFrom(); if (changeMessage != null && changeMessage.getWrittenOn() != null) { setHeader("Date", new Date(changeMessage.getWrittenOn().getTime())); } else { setHeader("Date", new Date()); } headers.put("From", new EmailHeader.AddressList(smtpFromAddress)); headers.put(HDR_TO, new EmailHeader.AddressList()); headers.put(HDR_CC, new EmailHeader.AddressList()); if (change != null) { setChangeSubjectHeader(); } setHeader("Message-ID", ""); setHeader("X-Gerrit-MessageType", messageClass); if (change != null) { setHeader("X-Gerrit-ChangeId", "" + change.getChangeId()); setListIdHeader(); setChangeUrlHeader(); setCommitIdHeader(); } body = new StringBuilder(); inFooter = false; if (change != null && db != null) { if (patchSet == null) { try { patchSet = db.patchSets().get(change.currentPatchSetId()); } catch (OrmException err) { patchSet = null; } } if (patchSet != null && patchSetInfo == null) { try { patchSetInfo = patchSetInfoFactory.get(patchSet.getId()); } catch (PatchSetInfoNotAvailableException err) { patchSetInfo = null; } } } }
Source:
<code>private static void copyAssetFileIfNeeded(RealmConfiguration configuration) { if (configuration.hasAssetFile()) { <START> File realmFile = new File(configuration.getRealmFolder(), configuration.getRealmFileName()); <END> InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = configuration.getAssetFile(); if (inputStream == null) { throw new RealmIOException("Invalid input stream to asset file."); } outputStream = new FileOutputStream(realmFile); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > -1) { outputStream.write(buf, 0, bytesRead); } } catch (IOException e) { throw new RealmIOException("Could not resolve the path to the Realm asset file.", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { } } } } }</code><technical_language>I checks verify file exist, situations racy me, i.e accidentally create file configuration is created this method is called, e.g. Backup/Restore API reintroduce file I think. IMO a safety check ignore assetFile in case. File realmFile = new File(configuration.getRealmFolder(), configuration.getRealmFileName()); if (realmFile.exists()) { return; }</technical_language>

Target:
private static void copyAssetFileIfNeeded(RealmConfiguration configuration) { if (configuration.hasAssetFile()) { File realmFile = new File(configuration.getRealmFolder(), configuration.getRealmFileName()); if (realmFile.exists()) { return; } InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = configuration.getAssetFile(); if (inputStream == null) { throw new RealmIOException("Invalid input stream to asset file."); } outputStream = new FileOutputStream(realmFile); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > -1) { outputStream.write(buf, 0, bytesRead); } } catch (IOException e) { throw new RealmIOException("Could not resolve the path to the Realm asset file.", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { throw new RealmIOException("Invalid output stream to " + realmFile.getPath(), e); } } } } }
Source:
<code>public void run() { Object operationResult = null; Exception exception = null; try { switch (opType) { case GetBlob: BlobOutput blobOutput = coordinator.getBlob(blobId); operationResult = new DataStreamChannel(blobOutput.getStream(), blobOutput.getSize()); break; case GetBlobInfo: blobProperties = coordinator.getBlobProperties(blobId); ByteBuffer usermetadataBuffer = coordinator.getBlobUserMetadata(blobId); if (usermetadataBuffer.hasArray()) { usermetadata = usermetadataBuffer.array(); } else { usermetadata = new byte[usermetadataBuffer.capacity()]; usermetadataBuffer.get(usermetadata); } operationResult = new BlobInfo(blobProperties, usermetadata); break; case PutBlob: operationResult = coordinator .putBlob(blobProperties, ByteBuffer.wrap(usermetadata), new ReadableStreamChannelInputStream(channel)); break; case DeleteBlob: coordinator.deleteBlob(blobId); break; <START> } <END> } catch (CoordinatorException e) { exception = new RouterException(e, RouterErrorCode.convertCoordinatorErrorToRouterErrorCode(e.getErrorCode())); } catch (Exception e) { exception = new RouterException(e, RouterErrorCode.UnexpectedInternalError); } finally { RuntimeException runtimeException = null; if (exception != null) { runtimeException = new RuntimeException(exception); } futureRouterResult.done(operationResult, runtimeException); if (callback != null) { callback.onCompletion(operationResult, exception); } } }</code><technical_language>is customary a default case. possibly allow initialize variables null above</technical_language>

Target:
public void run() { Object operationResult = null; Exception exception = null; try { switch (opType) { case GetBlob: BlobOutput blobOutput = coordinator.getBlob(blobId); byte[] buf = Utils.readBytesFromStream(blobOutput.getStream(), (int) blobOutput.getSize()); operationResult = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(buf)); break; case GetBlobInfo: blobProperties = coordinator.getBlobProperties(blobId); ByteBuffer usermetadataBuffer = coordinator.getBlobUserMetadata(blobId); if (usermetadataBuffer.hasArray()) { usermetadata = usermetadataBuffer.array(); } else { usermetadata = new byte[usermetadataBuffer.capacity()]; usermetadataBuffer.get(usermetadata); } operationResult = new BlobInfo(blobProperties, usermetadata); break; case PutBlob: operationResult = coordinator .putBlob(blobProperties, ByteBuffer.wrap(usermetadata), new ReadableStreamChannelInputStream(channel)); break; case DeleteBlob: coordinator.deleteBlob(blobId); break; default: throw new IllegalStateException("Unsupported CoordinatorOperationType - " + opType); } } catch (CoordinatorException e) { exception = new RouterException(e, RouterErrorCode.convertCoordinatorErrorToRouterErrorCode(e.getErrorCode())); } catch (Exception e) { exception = new RouterException(e, RouterErrorCode.UnexpectedInternalError); } finally { CoordinatorBackedRouter.completeOperation(futureRouterResult, callback, operationResult, exception); } }
Source:
<code>void handleUncaughtExceptionFromAsyncCall(Throwable t) { <START> final boolean tempClosed = closed; <END> if (closed) { LOG.debug("Caught exception when shutting down the SourceCoordinatorContext.", t); return; } System.out.println(tempClosed); ExceptionUtils.rethrowIfFatalErrorOrOOM(t); LOG.error("Exception while handling result from async call in {}. Triggering job failover.", coordinatorThreadName, t); failJob(t); }</code><technical_language>Leftover code debugging</technical_language>

Target:
void handleUncaughtExceptionFromAsyncCall(Throwable t) { if (closed) { LOG.debug("Caught exception when shutting down the SourceCoordinatorContext.", t); return; } ExceptionUtils.rethrowIfFatalErrorOrOOM(t); LOG.error("Exception while handling result from async call in {}. Triggering job failover.", coordinatorThreadName, t); failJob(t); }
Source:
<code>public static boolean hasValidJarContent(File jarFile) { JarInputStream jarInputStream = null; boolean valid = false; try { jarInputStream = new JarInputStream(new FileInputStream(jarFile)); valid = jarInputStream.getNextJarEntry() != null; } catch (IOException ignore) { } finally { try { if (jarInputStream != null) { <START> jarInputStream.close(); <END> } } catch (IOException ignored) { } } return valid; }</code><technical_language>put try/catch close call (ie: new "if")</technical_language>

Target:
public static boolean hasValidJarContent(File jarFile) { JarInputStream jarInputStream = null; boolean valid = false; try { jarInputStream = new JarInputStream(new FileInputStream(jarFile)); valid = jarInputStream.getNextJarEntry() != null; } catch (IOException ignore) { } finally { if (jarInputStream != null) { try { jarInputStream.close(); } catch (IOException e) { } } } return valid; }
Source:
<code>private String getKeystorePassword(File agentFile) { s_logger.debug("Retrieving keystore password from agent.properties file"); <START> String privatePasswordFormat = "sed -n '/keystore.passphrase/p' '%s' 2>/dev/null | sed 's/keystore.passphrase= END> String privatePasswordCmd = String.format(privatePasswordFormat, agentFile.getAbsolutePath()); return Script.runSimpleBashScript(privatePasswordCmd); }</code><technical_language>suggestion before</technical_language>

Target:
private String getKeystorePassword(File agentFile) { String pass = null; if (agentFile != null) { try { pass = PropertiesUtil.loadFromFile(agentFile).getProperty(KeyStoreUtils.KS_PASSPHRASE_PROPERTY); } catch (IOException e) { s_logger.error("Could not get 'keystore.passphrase' property value due to: " + e.getMessage()); } } return pass; }
Source:
<code>public String toString() { <START> final String headers = this.headers == null ? "null" : this.headers.toString(); <END> final String key = this.key == null ? "null" : this.key.toString(); final String value = this.value == null ? "null" : this.value.toString(); final String recordTime = this.recordTime == null ? "null" : this.recordTime.toString(); return "TestRecord(headers=" + headers + ", key=" + key + ", value=" + value + ", recordTime=" + recordTime + ")"; }</code><technical_language>double-check, I Java automatically do this in string concatenation. (It news I learned a couple of months back)</technical_language>

Target:
public String toString() { return new StringJoiner(", ", TestRecord.class.getSimpleName() + "[", "]") .add("key=" + key) .add("value=" + value) .add("headers=" + headers) .add("recordTime=" + recordTime) .toString(); }
Source:
<code>private Stack<TextLeaf> parse(String text) { while (text.contains("\b")) { <START> text = text.replaceAll("^\b+|[^\b]\b", ""); <END> } int controlStartPosition; int lastControlPosition = 0; int controlEndPosition; while (true) { controlStartPosition = text.indexOf("\033[", lastControlPosition); if (controlStartPosition == -1) { break; } textLeaf.text = text.substring(lastControlPosition, controlStartPosition); if (isResetLineEscape(text, controlStartPosition)) { controlEndPosition = text.indexOf('K', controlStartPosition + 2); int i; while (true) { i = Math.max(textLeaf.text.lastIndexOf("\r"), textLeaf.text.lastIndexOf("\n")); if (i != -1) { break; } if(result.isEmpty()) { break; } textLeaf = result.pop(); } if (textLeaf.text.length() > i && i > 0) { String end = textLeaf.text.substring(i - 1, i + 1); textLeaf.text = textLeaf.text.substring(0, i); if (end.equals("\r\n") || end.equals("\n\r")) { textLeaf.text = textLeaf.text.substring(0, i - 1); } } else { textLeaf.text = ""; } } else { controlEndPosition = text.indexOf('m', controlStartPosition + 2); if (controlEndPosition == -1) { break; } String matchingData = text.substring(controlStartPosition + 2, controlEndPosition); ansiStates = matchingData.split(";"); } if (!textLeaf.text.isEmpty()) { result.add(textLeaf); textLeaf = new TextLeaf(); } textLeaf.addAnsiCodes(ansiStates); lastControlPosition = controlEndPosition + 1; } textLeaf.text = text.substring(lastControlPosition); if (!textLeaf.text.isEmpty() || result.isEmpty()) { result.add(textLeaf); } return result; }</code><technical_language>Android Studio warning here. that</technical_language>

Target:
private Stack<TextLeaf> parse(String text) { while (text.contains("\b")) { text = text.replaceAll("^\b+|[^\b]\b", ""); } int controlStartPosition; int lastControlPosition = 0; int controlEndPosition; while (true) { controlStartPosition = text.indexOf("\033[", lastControlPosition); if (controlStartPosition == -1) { break; } String textBeforeEscape = text.substring(lastControlPosition, controlStartPosition); emitText(textBeforeEscape); if (isResetLineEscape(text, controlStartPosition)) { controlEndPosition = text.indexOf('K', controlStartPosition + 2); removeCurrentLine(); mOptions = new FormattingOptions(); } else { controlEndPosition = text.indexOf('m', controlStartPosition + 2); if (controlEndPosition == -1) { break; } String matchingData = text.substring(controlStartPosition + 2, controlEndPosition); String[] ansiStates = matchingData.split(";"); mOptions = FormattingOptions.fromAnsiCodes(ansiStates); } lastControlPosition = controlEndPosition + 1; } emitText(text.substring(lastControlPosition)); if (mResult.isEmpty()) { mResult.push(new TextLeaf()); } return mResult; }
Source:
<code><START> AmqpOutboundChannelAdapterSpec(AmqpTemplate amqpTemplate) { <END> super(amqpTemplate, false); }</code><technical_language>Gary, ctors final props in AMQP specs protected for extension? So, I include extensions PR #3167 avoid conflicts fixes. Thanks</technical_language>

Target:
protected AmqpOutboundChannelAdapterSpec(AmqpTemplate amqpTemplate) { super(amqpTemplate, false); }
Source:
<code>public void waitUntilDiscussionPageLoaded() { for (int i = 0; i < WAIT_PAGE_LOAD_MAX_RETRY; i++) { if (!isCurrentUrlDiscussion()) { try { Thread.sleep(WAIT_PAGE_LOAD_SLEEP_TIME); } catch (IllegalArgumentException | InterruptedException e) { logger.warn(e); } } else { return; <START> } <END> } }</code><technical_language>guard clauses reduce nesting. a good sign a big chunk of code is nested</technical_language>

Target:
public void waitUntilDiscussionPageLoaded() { for (int i = 0; i < WAIT_PAGE_LOAD_MAX_RETRY && !isCurrentUrlDiscussion(); i++) { try { Thread.sleep(WAIT_PAGE_LOAD_SLEEP_TIME); } catch (IllegalArgumentException | InterruptedException e) { logger.warn(e); } } }
Source:
<code><START> public Project.NameKey getParentName(final Project project) { <END> if (project.getParent() != null) { return project.getParent(); } if (project.getNameKey().equals(allProjectsName)) { return null; } return allProjectsName; }</code><technical_language>Is this method intended public</technical_language>

Target:
private Project.NameKey getParentName(final Project project) { if (project.getParent() != null) { return project.getParent(); } if (project.getNameKey().equals(allProjectsName)) { return null; } return allProjectsName; }
Source:
<code>private static ProxySelector createProxySelector(Optional<ProxyConfiguration> proxyConfig) { if (!proxyConfig.isPresent()) { return ProxySelector.getDefault(); } switch (proxyConfig.get().type()) { case DIRECT: return fixedProxySelectorFor(Proxy.NO_PROXY); case HTTP: HostAndPort hostAndPort = HostAndPort.fromString(proxyConfig.get().hostAndPort() <START> .orElseThrow(() -> new IllegalStateException( <END> "Expected to find proxy hostAndPort configuration for HTTP proxy"))); InetSocketAddress addr = new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort()); return fixedProxySelectorFor(new Proxy(Proxy.Type.HTTP, addr)); default: } throw new IllegalStateException("Failed to create ProxySelector for proxy configuration: " + proxyConfig); }</code><technical_language>this IllegalArgumentException</technical_language>

Target:
private static ProxySelector createProxySelector(Optional<ProxyConfiguration> proxyConfig) { if (!proxyConfig.isPresent()) { return ProxySelector.getDefault(); } switch (proxyConfig.get().type()) { case DIRECT: return fixedProxySelectorFor(Proxy.NO_PROXY); case HTTP: HostAndPort hostAndPort = HostAndPort.fromString(proxyConfig.get().hostAndPort() .orElseThrow(() -> new IllegalArgumentException( "Expected to find proxy hostAndPort configuration for HTTP proxy"))); InetSocketAddress addr = new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort()); return fixedProxySelectorFor(new Proxy(Proxy.Type.HTTP, addr)); default: } throw new IllegalStateException("Failed to create ProxySelector for proxy configuration: " + proxyConfig); }
Source:
<code><START> public boolean hasTasks() { <END> return !(fForegroundTasks.isEmpty() && fBackgroundTasks.isEmpty()); }</code><technical_language>This private too</technical_language>

Target:
private boolean hasTasks() { return !(fForegroundTasks.isEmpty() && fBackgroundTasks.isEmpty()); }
Source:
<code>public ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String studentEmail = getRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); Assumption.assertNotNull(studentEmail); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); new GateKeeper().verifyAccessible( instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); if (student == null) { statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_NOT_FOUND_FOR_EDIT, StatusMessageColor.DANGER)); isError = true; return createRedirectResult(Const.ActionURIs.INSTRUCTOR_HOME_PAGE); } boolean hasSection = logic.hasIndicatedSections(courseId); boolean isAnyEmailSentForTheCourse = logic.isAnyEmailSentForTheCourse(courseId); InstructorCourseStudentDetailsEditPageData data = new InstructorCourseStudentDetailsEditPageData(account, student, student.email, hasSection, <START> isAnyEmailSentForTheCourse); <END> statusToAdmin = "instructorCourseStudentEdit Page Load<br>" + "Editing Student <span class=\"bold\">" + studentEmail + "'s</span> details " + "in Course <span class=\"bold\">[" + courseId + "]</span>"; return createShowPageResult(Const.ViewURIs.INSTRUCTOR_COURSE_STUDENT_EDIT, data); }</code><technical_language>Align [i]sAny... [a]ccount</technical_language>

Target:
public ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String studentEmail = getRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); Assumption.assertNotNull(studentEmail); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); gateKeeper.verifyAccessible( instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); if (student == null) { statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_NOT_FOUND_FOR_EDIT, StatusMessageColor.DANGER)); isError = true; return createRedirectResult(Const.ActionURIs.INSTRUCTOR_HOME_PAGE); } boolean hasSection = logic.hasIndicatedSections(courseId); boolean isOpenOrPublishedEmailSentForTheCourse = logic.isOpenOrPublishedEmailSentForTheCourse(courseId); InstructorCourseStudentDetailsEditPageData data = new InstructorCourseStudentDetailsEditPageData(account, student, student.email, hasSection, isOpenOrPublishedEmailSentForTheCourse); statusToAdmin = "instructorCourseStudentEdit Page Load<br>" + "Editing Student <span class=\"bold\">" + studentEmail + "'s</span> details " + "in Course <span class=\"bold\">[" + courseId + "]</span>"; return createShowPageResult(Const.ViewURIs.INSTRUCTOR_COURSE_STUDENT_EDIT, data); }
Source:
<code>private static IStatus createStatusForInternalAutFailure(Throwable e) { <START> return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, IStatus.ERROR, <END> "Internal aut failure. Cause: " + e.getMessage(), e); }</code><technical_language>Wrong error code</technical_language>

Target:
private static IStatus createStatusForInternalAutFailure(Throwable e) { return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, IProcess.INTERNAL_AUT_FAILURE, "Internal aut failure. Cause: " + e.getMessage(), e); }
Source:
<code>public void refresh() { removeAll(); setEnabled(false); for (OutputDataStream outputDataStream : _componentBuilder.getOutputDataStreams()) { setEnabled(true); <START> List<InputColumn<?>> inputColumns = new ArrayList<>(); <END> for (Column column : outputDataStream.getTable().getColumns()) { MetaModelInputColumn inputColumn = new MetaModelInputColumn(column); inputColumns.add(inputColumn); } final JLabel tableNameLabel = new JLabel(outputDataStream.getName(), ImageManager.get().getImageIcon( IconUtils.OUTPUT_DATA_STREAM_PATH, IconUtils.ICON_SIZE_SMALL), JLabel.LEFT); tableNameLabel.setOpaque(false); tableNameLabel.setFont(WidgetUtils.FONT_HEADER1); tableNameLabel.setBorder(new EmptyBorder(5, 5, 0, 5)); final ColumnListTable columnListTable = new ColumnListTable(inputColumns, _componentBuilder.getAnalysisJobBuilder(), true, false, null); columnListTable.setBorder(new EmptyBorder(0, 5, 5, 5)); add(tableNameLabel); add(columnListTable); } }</code><technical_language>Final</technical_language>

Target:
public void refresh() { removeAll(); setEnabled(false); for (OutputDataStream outputDataStream : _componentBuilder.getOutputDataStreams()) { setEnabled(true); final List<InputColumn<?>> inputColumns = new ArrayList<>(); for (Column column : outputDataStream.getTable().getColumns()) { inputColumns.add(new MetaModelInputColumn(column)); } final JLabel tableNameLabel = new JLabel(outputDataStream.getName(), ImageManager.get().getImageIcon( IconUtils.OUTPUT_DATA_STREAM_PATH, IconUtils.ICON_SIZE_SMALL), JLabel.LEFT); tableNameLabel.setOpaque(false); tableNameLabel.setFont(WidgetUtils.FONT_HEADER1); tableNameLabel.setBorder(new EmptyBorder(5, 5, 0, 5)); final ColumnListTable columnListTable = new ColumnListTable(inputColumns, _componentBuilder.getAnalysisJobBuilder(), true, false, null); columnListTable.setBorder(new EmptyBorder(0, 5, 5, 5)); add(tableNameLabel); add(columnListTable); } }
Source:
<code>protected CompletionStage<Collection<KV<K, V>>> handleMessageAsync(KV<K, V> message, MessageCollector collector, TaskCoordinator coordinator) { table.put(message.getKey(), message.getValue()); <START> return CompletableFuture.completedFuture(new ArrayList<KV<K, V>>(Arrays.asList(message))); <END> }</code><technical_language>Do need wrap Arrays.asList in ArrayList</technical_language>

Target:
protected CompletionStage<Collection<KV<K, V>>> handleMessageAsync(KV<K, V> message, MessageCollector collector, TaskCoordinator coordinator) { table.put(message.getKey(), message.getValue()); return CompletableFuture.completedFuture(Collections.singleton(message)); }
Source:
<code>public List<CytoscapeLinkObject> getLinks(List<Link> links){ List<CytoscapeLinkObject> cytoscapeLinkList = new ArrayList<CytoscapeLinkObject>(); for (int i = 0; i < links.size(); i++) { CytoscapeLinkDataObject dataObj = new CytoscapeLinkDataObject(); dataObj.setId(""+i); dataObj.setSource(links.get(i).getSubject().getId()); dataObj.setTarget(links.get(i).getObject().getId()); dataObj.setLabel(links.get(i).getLabel()); dataObj.setSourceReference(links.get(i).getSourceReference()); dataObj.setStatementIds(new ArrayList<String>()); dataObj.getStatementIds().add(links.get(i).getStatementId()) ; CytoscapeLinkObject obj = new CytoscapeLinkObject(); <START> obj.setData(dataObj); <END> cytoscapeLinkList.add(obj); } return cytoscapeLinkList; }</code><technical_language>creating of links in private method</technical_language>

Target:
public List<CytoscapeLinkObject> getLinks(List<Link> links){ List<CytoscapeLinkObject> cytoscapeLinkList = new ArrayList<CytoscapeLinkObject>(); int i = 0; for(Link link : links){ cytoscapeLinkList.add(createCytoscapeLinkObject(link)); cytoscapeLinkList.get(i).getData().setId(""+i); i++; } return cytoscapeLinkList; }
Source:
<code>public void onSubscribe(Subscription s) { this.s = s; <START> s.request(1); <END> }</code><technical_language>@mp911de connection factory absolutely guarantees a Publisher onNext(Connection)? if not, @bsideup worth consider guarding flux-like publishers adding a boolean guard in onNext (doesn't a volatile, onNext read/write it)</technical_language>

Target:
public synchronized void onSubscribe(Subscription s) { this.s = s; if (!cancelled) { s.request(1); } else { s.cancel(); } }
Source:
<code>protected void handleSaveInstanceStateRequest( REQID rid, SocketChannel channel, CheckpointManager.SaveInstanceStateRequest request ) { Checkpoint checkpoint = new Checkpoint(topologyName, request); <START> LOG.info("Got a save checkpoint request for " + checkpoint.getCheckpointId() + " " <END> + checkpoint.getComponent() + " " + checkpoint.getInstance() + " on connection: " + channel.socket().getRemoteSocketAddress()); Common.StatusCode statusCode = Common.StatusCode.OK; try { checkpointsBackend.store(checkpoint); LOG.info("Save checkpoint successful for " + checkpoint.getCheckpointId() + " " + checkpoint.getComponent() + " " + checkpoint.getInstance()); } catch (StatefulStorageException e) { LOG.info("Save checkpoint not successful for " + checkpoint.getCheckpointId() + " " + checkpoint.getComponent() + " " + checkpoint.getInstance() + " error: " + e); statusCode = Common.StatusCode.NOTOK; } CheckpointManager.SaveInstanceStateResponse.Builder responseBuilder = CheckpointManager.SaveInstanceStateResponse.newBuilder(); responseBuilder.setStatus(Common.Status.newBuilder().setStatus(statusCode)); responseBuilder.setCheckpointId(request.getCheckpoint().getCheckpointId()); responseBuilder.setInstance(request.getInstance()); sendResponse(rid, channel, responseBuilder.build()); }</code><technical_language>Please favor String.format(...) for readability elsewhere</technical_language>

Target:
protected void handleSaveInstanceStateRequest( REQID rid, SocketChannel channel, CheckpointManager.SaveInstanceStateRequest request ) { Checkpoint checkpoint = new Checkpoint(topologyName, request.getInstance(), request.getCheckpoint()); LOG.info(String.format("Got a save checkpoint request for checkpointId %s " + " component %s instance %s on connection %s", checkpoint.getCheckpointId(), checkpoint.getComponent(), checkpoint.getInstance(), channel.socket().getRemoteSocketAddress())); Common.StatusCode statusCode = Common.StatusCode.OK; String errorMessage = ""; try { statefulStorage.store(checkpoint); LOG.info(String.format("Saved checkpoint for checkpointId %s compnent %s instance %s", checkpoint.getCheckpointId(), checkpoint.getComponent(), checkpoint.getInstance())); } catch (StatefulStorageException e) { errorMessage = String.format("Save checkpoint not successful for checkpointId " + "%s component %s instance %s", checkpoint.getCheckpointId(), checkpoint.getComponent(), checkpoint.getInstance()); statusCode = Common.StatusCode.NOTOK; LOG.log(Level.WARNING, errorMessage, e); } CheckpointManager.SaveInstanceStateResponse.Builder responseBuilder = CheckpointManager.SaveInstanceStateResponse.newBuilder(); responseBuilder.setStatus(Common.Status.newBuilder().setStatus(statusCode) .setMessage(errorMessage)); responseBuilder.setCheckpointId(request.getCheckpoint().getCheckpointId()); responseBuilder.setInstance(request.getInstance()); sendResponse(rid, channel, responseBuilder.build()); }
Source:
<code>public void propertyChange(PropertyChangeEvent evt) { if (renderingConfig.isDynamicShadows()) { int shadowMapResFromSettings = (int) evt.getNewValue(); shadowMapResolution = new FBO.Dimensions(shadowMapResFromSettings, shadowMapResFromSettings); <START> <END> for (Map.Entry<ResourceUrn, FBOConfig> entry : fboConfigs.entrySet()) { ResourceUrn resourceUrn = entry.getKey(); FBOConfig fboConfig = entry.getValue(); if (fboLookup.containsKey(resourceUrn)) { FBO fbo = fboLookup.get(resourceUrn); if (fbo != null) { fbo.dispose(); } } FBO shadowMapResDependentFBO = generateWithDimensions(fboConfig, shadowMapResolution); if (shadowMapResDependentFBO.getStatus() == FBO.Status.DISPOSED) { logger.warn("Failed to generate ShadowMap FBO. Turning off shadows."); renderingConfig.setDynamicShadows(false); break; } fboLookup.put(resourceUrn, shadowMapResDependentFBO); } } }</code><technical_language>remove unnecessary empty line here</technical_language>

Target:
public void propertyChange(PropertyChangeEvent evt) { if (renderingConfig.isDynamicShadows()) { int shadowMapResFromSettings = (int) evt.getNewValue(); shadowMapResolution = new FBO.Dimensions(shadowMapResFromSettings, shadowMapResFromSettings); for (Map.Entry<ResourceUrn, FBOConfig> entry : fboConfigs.entrySet()) { ResourceUrn fboName = entry.getKey(); FBOConfig fboConfig = entry.getValue(); if (fboLookup.containsKey(fboName)) { FBO fbo = fboLookup.get(fboName); if (fbo != null) { fbo.dispose(); } } FBO shadowMapResDependentFBO = generateWithDimensions(fboConfig, shadowMapResolution); if (shadowMapResDependentFBO.getStatus() == FBO.Status.DISPOSED) { logger.warn("Failed to generate ShadowMap FBO. Turning off shadows."); renderingConfig.setDynamicShadows(false); break; } fboLookup.put(fboName, shadowMapResDependentFBO); } } }
Source:
<code>public PageTitle getFirstResult() { <START> if (totalResults != null) { <END> return totalResults.get(0); } else { return null; } }</code><technical_language>check size() > 0, crashes results, press keyboard</technical_language>

Target:
public PageTitle getFirstResult() { if (totalResults != null && !totalResults.isEmpty()) { return totalResults.get(0); } else { return null; } }
Source:
<code>public void testTriggerRedisStopEffector() throws InterruptedException { ClientResponse response = client().resource("/v1/applications/redis-app/entities/redis-ent/effectors/stop") .post(ClientResponse.class, ImmutableMap.of()); assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); URI stateSensor = URI.create("/v1/applications/redis-app/entities/redis-ent/sensors/service.state"); String expectedStatus = String.format("\"%s\"", Lifecycle.STOPPED.toString()); String actualStatus = null; <START> for (int iter = 0; iter < 30 && !expectedStatus.equals(actualStatus); iter++) { <END> Thread.sleep(2000); actualStatus = client().resource(stateSensor).get(String.class); } assertEquals(actualStatus, expectedStatus); }</code><technical_language>about: Asserts.succeedsEventually(MutableMap.of("timeout", 60*1000), new Runnable() { public void run() { assertEquals(client().resource(stateSensor).get(String.class), expectedStatus); }}); code, of is boilerplate common in other tests, is visually easier filter out. some nice stuff starts polling frequently backs off, allowing tests run faster possible</technical_language>

Target:
public void testTriggerRedisStopEffector() throws InterruptedException { ClientResponse response = client().resource("/v1/applications/redis-app/entities/redis-ent/effectors/stop") .post(ClientResponse.class, ImmutableMap.of()); assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); final URI stateSensor = URI.create("/v1/applications/redis-app/entities/redis-ent/sensors/service.state"); final String expectedStatus = String.format("\"%s\"", Lifecycle.STOPPED.toString()); Asserts.succeedsEventually(MutableMap.of("timeout", 60 * 1000), new Runnable() { public void run() { assertEquals(client().resource(stateSensor).get(String.class), expectedStatus); } }); }
Source:
<code>public JSONObject getAnnouncements() { LOG.debug("get announcements"); final SqlSession session = factory.openSession(); JSONObject data = new JSONObject(); try { final AnnouncementsMapper mapper = session.getMapper(AnnouncementsMapper.class); data = parser.parseAnnouncementsMap(mapper.getAnnouncements()); session.commit(); } catch (Exception e) { throw new RuntimeException("Failed to get announcements", e); } finally { <START> session.close(); <END> } return data; }</code><technical_language>try-with-resources need manually close session</technical_language>

Target:
public JSONObject getAnnouncements() { try (final SqlSession session = factory.openSession()) { final AnnouncementsMapper mapper = session.getMapper(AnnouncementsMapper.class); return parser.parseAnnouncementsMap(mapper.getAnnouncements(LocalDate.now())); } catch (Exception e) { throw new ServiceRuntimeException("Failed to get announcements", e); } }
Source:
<code>public int getNumUnits(final String dataType) { <START> if (typeToBlocks.containsKey(dataType)) { <END> return 0; } int numUnits = 0; final Collection<Block> blocks = typeToBlocks.get(dataType).values(); for (final Block block : blocks) { numUnits += block.getNumUnits(); } return numUnits; }</code><technical_language>(!typeToBlocks.containsKey(dataType))</technical_language>

Target:
public int getNumUnits(final String dataType) { if (!typeToBlocks.containsKey(dataType)) { return 0; } int numUnits = 0; final Collection<Block> blocks = typeToBlocks.get(dataType).values(); for (final Block block : blocks) { numUnits += block.getNumUnits(); } return numUnits; }
Source:
<code>private void _putWithoutTag(Metric metric) { String rowKeyScopeTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, SCOPE_SCHEMA_TABLENAME); String rowKeyMetricTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, METRIC_SCHEMA_TABLENAME); boolean exists = false; if(_cacheEnabled) { exists = _trie.getValueForExactKey(rowKeyScopeTable) != null; } if(!exists) { _put(SCOPE_SCHEMA_TABLENAME, rowKeyScopeTable); _put(METRIC_SCHEMA_TABLENAME, rowKeyMetricTable); if(_cacheEnabled) { <START> _trie.putIfAbsent(rowKeyScopeTable, VoidValue.SINGLETON); <END> } _monitorService.modifyCounter(MonitorService.Counter.SCHEMARECORDS_WRITTEN, 2, null); } }</code><technical_language>refactor Lines 684-693 in _putWithoutTag() lines in _putWithTag() a common private method</technical_language>

Target:
private void _putWithoutTag(Metric metric) { String rowKeyScopeTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, SCOPE_SCHEMA_TABLENAME); String rowKeyMetricTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, METRIC_SCHEMA_TABLENAME); _putIfAbsent(rowKeyScopeTable, rowKeyMetricTable); }
Source:
<code>public SearchResults stepAll(int steps) throws KRunExecutionException { if (currentState == null) { throw new IllegalStateException("Cannot step without a current state to step from. " + "If you previously used the search command you must" + "first select a solution with the select command before executing steps of rewrites!"); } <START> SearchResults results = executor.search(null, steps, SearchType.PLUS, defaultPattern, getState(currentState).getRawResult(), defaultPatternInfo, false); <END> mergeSearchGraph(results.getGraph()); currentState = null; return results; }</code><technical_language>This true</technical_language>

Target:
public SearchResults stepAll(int steps) throws KRunExecutionException { if (currentState == null) { throw new IllegalStateException("Cannot step without a current state to step from. " + "If you previously used the search command you must" + "first select a solution with the select command before executing steps of rewrites!"); } SearchResults results = executor.search(null, steps, SearchType.PLUS, defaultPattern, getState(currentState).getRawResult(), defaultPatternInfo, true); mergeSearchGraph(results.getGraph()); currentState = null; return results; }
Source:
<code>public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException { <START> if (!resourceModel.has(attribute.getName())) { <END> return; } String wrapper = wrapperElement == null ? attribute.getName() : wrapperElement; resourceModel = resourceModel.get(attribute.getName()); if (!resourceModel.isDefined()){ writer.writeEmptyElement(wrapper); return; } if (wrapElement) { writer.writeStartElement(wrapper); } for (ModelNode property : resourceModel.asList()) { writer.writeEmptyElement(elementName); writer.writeAttribute(org.jboss.as.controller.parsing.Attribute.NAME.getLocalName(), property.asProperty().getName()); writer.writeAttribute(org.jboss.as.controller.parsing.Attribute.VALUE.getLocalName(), property.asProperty().getValue().asString()); } if (wrapElement) { writer.writeEndElement(); } }</code><technical_language>For a properly implemented resource, this return 'true' AbstractAddHandler.populateModel() iterate attributes, for adding a child (defined undefined) resource's model. I behavior be: if (!resourceModel.hasDefined(attribute.getName())) -> return marshalling for attribute List<ModelNode> list = resource.get(attribute.getName()).asList(); if (list.isEmpty()) { if (wrapElement) -> marshal empty wrapper else -> return marshalling (see below) } else -> [marshal a start element] / iterate list / [marshal end element]. A problem is "if (list.isEmpty() && !wrapElement)". This a subtle programming error, developer provide xml schema prevents ambiguity 'null' 'empty collection' cases. I try deal this this stage of release process though, other adding a TODO filing a JIRA. A fix involve throwing ISE AssertionError in some cases ^^^ is true, risky right now</technical_language>

Target:
public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException { String wrapper = wrapperElement == null ? attribute.getName() : wrapperElement; resourceModel = resourceModel.get(attribute.getName()); if (!resourceModel.isDefined()){ writer.writeEmptyElement(wrapper); return; } if (wrapElement) { writer.writeStartElement(wrapper); } for (ModelNode property : resourceModel.asList()) { writer.writeEmptyElement(elementName); writer.writeAttribute(org.jboss.as.controller.parsing.Attribute.NAME.getLocalName(), property.asProperty().getName()); writer.writeAttribute(org.jboss.as.controller.parsing.Attribute.VALUE.getLocalName(), property.asProperty().getValue().asString()); } if (wrapElement) { writer.writeEndElement(); } }
Source:
<code>public boolean hasCategoryMembers() { <START> wait.forElementVisible(categoryMembers); <END> return driver.findElements(categoryMembers).size() > 0; }</code><technical_language>log successful assertion? do in methods in below</technical_language>

Target:
public boolean hasCategoryMembers() { wait.forElementVisible(categoryMembers); PageObjectLogging.logInfo("Category has members."); return driver.findElements(categoryMembers).size() > 0; }
Source:
<code>public synchronized PrintWriter getWriter() { checkState(outputStream == null, "getOutputStream() already called"); if (writer == null) { <START> writer = new PrintWriter(actualBody); <END> } return writer; }</code><technical_language>This platform default encoding. UTF-8. assert encoding set UTF-8. uhm good. Wrap this OutputStreamWriter explicitly calls for UTF-8 encoding</technical_language>

Target:
public synchronized PrintWriter getWriter() { checkState(outputStream == null, "getOutputStream() already called"); if (writer == null) { writer = new PrintWriter(new OutputStreamWriter(actualBody, Charsets.UTF_8)); } return writer; }
Source:
<code>public int deleteReport(final UUID identifier, final Organization organization) { assertIsOpen(); LOGGER.debug() .setMessage("Deleting report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .log(); final Optional<models.ebean.Report> report; try (Transaction transaction = _ebeanServer.beginTransaction()) { report = getBeanReport(identifier, organization); report.ifPresent(r -> { _ebeanServer.delete(r); LOGGER.debug() .setMessage("Deleted report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .log(); }); transaction.commit(); } catch (final RuntimeException e) { LOGGER.error() .setMessage("Failed to delete report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .setThrowable(e) .log(); <START> throw new PersistenceException(e); <END> } if (report.isPresent()) { return 1; } return 0; }</code><technical_language>Is a reason wrap exception instead of rethrowing? (not common practice in this project is moment) Also, a general rule of thumb log throw, both. If throw, caller decide severity log (or if act) log confuse matter. If swallow exception (e.g. recover, default, etc.), need log level happened. I bet Play log uncaught exception handler</technical_language>

Target:
public int deleteReport(final UUID identifier, final Organization organization) { assertIsOpen(); LOGGER.debug() .setMessage("Deleting report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .log(); final int deleted = _ebeanServer.update(models.ebean.Report.class) .set("deleted", true) .where() .eq("uuid", identifier) .eq("organization.uuid", organization.getId()) .eq("deleted", false) .update(); if (deleted > 0) { LOGGER.debug() .setMessage("Deleted report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .log(); } return deleted; }
Source:
<code>public void trackMap(String eventName, Map<String, Object> properties) { <START> if (null == properties) { <END> Log.e(LOGTAG, "trackMap does not accept null properties"); return; } track(eventName, new JSONObject(properties)); }</code><technical_language>need limit null here</technical_language>

Target:
public void trackMap(String eventName, Map<String, Object> properties) { if (null == properties) { track(eventName, null); } else { try { track(eventName, new JSONObject(properties)); } catch (NullPointerException e) { Log.w(LOGTAG, "Can't have null keys in the properties of trackMap!"); } } }