auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (servletRequest instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse; String path = httpServletRequest.getPathInfo(); <START> if (ResourceDomainConfiguration.isResourceRequest(httpServletRequest) <END> && !path.startsWith("/static-files/") && !path.equals("/static-files")) { LOGGER.log(Level.FINE, "Rejecting request to " + httpServletRequest.getRequestURL() + " from " + httpServletRequest.getRemoteAddr() + " on resource domain"); httpServletResponse.sendError(404, "Jenkins serves only static files on this domain."); return; } } filterChain.doFilter(servletRequest, servletResponse); }</code><technical_language>(nit + local, premature optimization) check isResourceRequest moved if, instanceof, reduce computation</technical_language>

Target:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (servletRequest instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse; if (ResourceDomainConfiguration.isResourceRequest(httpServletRequest)) { String path = httpServletRequest.getPathInfo(); if (!path.startsWith("/" + ResourceDomainRootAction.URL + "/") && !ALLOWED_PATHS.contains(path)) { LOGGER.fine(() -> "Rejecting request to " + httpServletRequest.getRequestURL() + " from " + httpServletRequest.getRemoteAddr() + " on resource domain"); httpServletResponse.sendError(404, ERROR_RESPONSE); return; } LOGGER.finer(() -> "Accepting request to " + httpServletRequest.getRequestURL() + " from " + httpServletRequest.getRemoteAddr() + " on resource domain"); } } filterChain.doFilter(servletRequest, servletResponse); }
Source:
<code>public void create_default_instance_according_to_place() { <START> final int currentOffset = timeZone.getRawOffset()/(int)MILLIS_PER_SECOND; <END> final String zoneId = timeZone.getID(); assertEquals(currentOffset, ZoneOffsets.getDefault().getAmountSeconds()); assertEquals(zoneId, ZoneOffsets.getDefault().getId()); }</code><technical_language>repeat this calculation again. create a utility method? E.g. getTimezoneZeconds()</technical_language>

Target:
public void create_default_instance_according_to_place() { final int currentOffset = getOffsetInSeconds(timeZone); final String zoneId = timeZone.getID(); assertEquals(currentOffset, toZoneOffset(timeZone).getAmountSeconds()); assertEquals(zoneId, toZoneOffset(timeZone).getId()); }
Source:
<code>public void onJointAngles(Map<String, Double> angleMap) { for (String name : angleMap.keySet()) { ServiceInterface si = Runtime.getService(name); <START> if (si instanceof Servo) { <END> ((Servo) si).moveTo(angleMap.get(name)); } } }</code><technical_language>instance of ServoControl Servo.. :)</technical_language>

Target:
public void onJointAngles(Map<String, Double> angleMap) { for (String name : angleMap.keySet()) { ServiceInterface si = Runtime.getService(name); if (si instanceof ServoControl) { ((ServoControl) si).moveTo(angleMap.get(name)); } } }
Source:
<code>public Map<String, String> getJobMessageProperties() { DiskImage diskImage = diskImageDao.getSnapshotById(getParameters().getSubchainInfo().getTopImageId()); <START> DiskImage destDiskImage = diskImageDao.getSnapshotById(getParameters().getSubchainInfo().getBaseImageId()); <END> if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.Disk.name().toLowerCase(), diskImage.getDiskAlias()); jobProperties.put("sourcesnapshot", Optional.ofNullable(snapshotDao.get(diskImage.getVmSnapshotId()).getDescription()).orElse("")); jobProperties.put("destinationsnapshot", Optional.ofNullable(snapshotDao.get(destDiskImage.getVmSnapshotId()).getDescription()).orElse("")); } return jobProperties; }</code><technical_language>2 lines in if clause well</technical_language>

Target:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { DiskImage diskImage = diskImageDao.getSnapshotById(getParameters().getSubchainInfo().getTopImageId()); DiskImage destDiskImage = diskImageDao.getSnapshotById(getParameters().getSubchainInfo().getBaseImageId()); jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.Disk.name().toLowerCase(), diskImage.getDiskAlias()); jobProperties.put("sourcesnapshot", Optional.ofNullable(snapshotDao.get(diskImage.getVmSnapshotId()).getDescription()).orElse("")); jobProperties.put("destinationsnapshot", Optional.ofNullable(snapshotDao.get(destDiskImage.getVmSnapshotId()).getDescription()).orElse("")); } return jobProperties; }
Source:
<code>private String getRequestCharset() { String charset = request.getHeader("Accept-Charset"); if(charset != null) { charset = charset.split(",")[0]; } <START> return charset; <END> }</code><technical_language>provide a default, in case of this header is missing. I guess do like: java String charset = Objects.firstNonNull(request.getHeader("Accept-Charset"), "UTF-8"); return charset.split(",")[0];</technical_language>

Target:
private String getRequestCharset() { String charset = Objects.firstNonNull(request.getHeader("Accept-Charset"), "UTF-8"); return charset.split(",")[0]; }
Source:
<code>public WizardCustomizeJenkins doInstallSuggested() { <START> By suggestedButtonLocator = By.partialLinkText("Install suggested plugins"); <END> waitFor(suggestedButtonLocator, 30); Control installSuggested = control(suggestedButtonLocator); installSuggested.click(); return this; }</code><technical_language>I suggest if possible, is instance of [ByFactory](<LINK_0>, if need a new selector simply Selenium in PO new selector reused, if add ByFactory is PO, add some validation error control logic easily polluting PO</technical_language>

Target:
public WizardCustomizeJenkins doInstallSuggested() { By suggestedButtonLocator = by.partialLinkText("Install suggested plugins"); waitFor(suggestedButtonLocator, 30); Control installSuggested = control(suggestedButtonLocator); installSuggested.click(); return this; }
Source:
<code>private String getParserType(URL url) { String fileName = url.getPath(); int fileExtesionStartIndex = fileName.lastIndexOf(".") + 1; <START> if (fileExtesionStartIndex == -1) { <END> return Parser.FORMAT_JSON; } String fileExtesion = fileName.substring(fileExtesionStartIndex); if (fileExtesion.equals("txt")) { return Parser.FORMAT_JSON; } return fileExtesion; }</code><technical_language>fileExtesionStartIndex -1 is file extension</technical_language>

Target:
private String getParserType(URL url) { String fileName = url.getPath(); if (fileName.lastIndexOf(".") == -1) { return Parser.FORMAT_JSON; } String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1); if (fileExtension.equals("txt")) { return Parser.FORMAT_JSON; } return fileExtension; }
Source:
<code>private Properties buildProperties() { Properties props = System.getProperties(); <START> final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; <END> props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); props.put("mail.store.protocol", "pop3"); props.put("mail.transport.protocol", "smtp"); return props; }</code><technical_language>string declaration for SSL_FACTORY? If do this, do for strings in property. If not, remove variable. is wrong implementation is varies in style professional</technical_language>

Target:
private Properties buildProperties() { Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); props.put("mail.store.protocol", "pop3"); props.put("mail.transport.protocol", "smtp"); return props; }
Source:
<code><START> void setStudyDataManager(final StudyDataManager studyDataManager) { <END> this.studyDataManager = studyDataManager; }</code><technical_language>Put setters end of file</technical_language>

Target:
public void setStudyDataManager(final StudyDataManager studyDataManager) { this.studyDataManager = studyDataManager; }
Source:
<code>public void onFriendJoinedGame(FriendJoinedGameEvent event) { Player player = event.getPlayer(); Game game = event.getGame(); audioService.playFriendJoinsGameSound(); if (preferencesService.getPreferences().getNotification().isFriendJoinsGameToastEnabled() && !eventList.contains(event)) { <START> eventList.add(event); <END> notificationService.addNotification(new TransientNotification( i18n.get("friend.joinedGameNotification.title", player.getUsername(), game.getTitle()), i18n.get("friend.joinedGameNotification.action"), IdenticonUtil.createIdenticon(player.getId()), event1 -> joinGameHelper.join(player.getGame()) )); } }</code><technical_language>events removed list, this creates a memory leak. notifier a reference events, events a reference players games, references, preventing objects garbage collected. this added; event is fired once, contains() check return false. if remove eventList</technical_language>

Target:
public void onFriendJoinedGame(FriendJoinedGameEvent event) { Player player = event.getPlayer(); Game game = event.getGame(); audioService.playFriendJoinsGameSound(); if (preferencesService.getPreferences().getNotification().isFriendJoinsGameToastEnabled()) { notificationService.addNotification(new TransientNotification( i18n.get("friend.joinedGameNotification.title", player.getUsername(), game.getTitle()), i18n.get("friend.joinedGameNotification.action"), IdenticonUtil.createIdenticon(player.getId()), event1 -> joinGameHelper.join(player.getGame()) )); } }
Source:
<code>protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = AudioWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); if (prompt.isReadOnly()) { binding.captureButton.widgetButton.setVisibility(View.GONE); binding.chooseButton.widgetButton.setVisibility(View.GONE); } else { binding.captureButton.widgetButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.chooseButton.widgetButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); <START> binding.captureButton.widgetButton.setText(getContext().getString(R.string.capture_audio)); <END> binding.chooseButton.widgetButton.setText(getContext().getString(R.string.choose_sound)); binding.captureButton.widgetButton.setOnClickListener(v -> onCaptureAudioButtonClicked()); binding.chooseButton.widgetButton.setOnClickListener(v -> chooseSound()); } return binding.getRoot(); }</code><technical_language>Feels button text live in a layout</technical_language>

Target:
protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = AudioWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); audioController = new AudioControllerView(context); binding.getRoot().addView(audioController); if (prompt.isReadOnly()) { binding.captureButton.setVisibility(View.GONE); binding.chooseButton.setVisibility(View.GONE); } else { binding.captureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.chooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.captureButton.setOnClickListener(v -> onCaptureAudioButtonClicked()); binding.chooseButton.setOnClickListener(v -> chooseSound()); } return binding.getRoot(); }
Source:
<code>public void clickDisplayedToStudentCheckBox(int instrNum) { <START> this.getDisplayedToStudentCheckBox(instrNum).click(); <END> }</code><technical_language>While it, remove redundant this. well</technical_language>

Target:
public void clickDisplayedToStudentCheckBox(int instrNum) { getDisplayedToStudentCheckBox(instrNum).click(); }
Source:
<code>public synchronized void notify(RecordsDeliveryAck recordsDeliveryAck) { final RecordsRetrieved recordsToCheck = peekNextResult(); if (recordsToCheck != null && recordsToCheck.batchUniqueIdentifier() .equals(recordsDeliveryAck.batchUniqueIdentifier())) { evictNextResult(); if(getRecordsResultQueue.isEmpty()) { log.debug("{} : Publisher thread takes over the draining control. Queue Size : {}, Demand : {}", shardId, getRecordsResultQueue.size(), requestedResponses.get()); shouldDrainEventOnAck.set(false); } else { <START> drainQueueForRequests(); <END> } } else { final BatchUniqueIdentifier peekedBatchUniqueIdentifier = recordsToCheck == null ? null : recordsToCheck.batchUniqueIdentifier(); log.info("{} : Received a stale notification with id instead of expected id at {}. Will ignore.", shardId, recordsDeliveryAck.batchUniqueIdentifier(), peekedBatchUniqueIdentifier, Instant.now()); } takeDelayedDeliveryActionIfRequired(shardId, lastEventDeliveryTime, log); }</code><technical_language>In happy case continue receive acks for event delivered, ack-notifier thread draining queue. Publisher thread continue do fetch part. I this conflicts a bit design of this class purpose of publisher thread</technical_language>

Target:
public synchronized void notify(RecordsDeliveryAck recordsDeliveryAck) { final RecordsRetrieved recordsToCheck = peekNextResult(); if (recordsToCheck != null && recordsToCheck.batchUniqueIdentifier() .equals(recordsDeliveryAck.batchUniqueIdentifier())) { pollNextResultAndUpdatePrefetchCounters(); if (getRecordsResultQueue.isEmpty()) { log.debug("{} : Publisher thread takes over the draining control. Queue Size : {}, Demand : {}", shardId, getRecordsResultQueue.size(), requestedResponses.get()); shouldDrainEventOnlyOnAck.set(false); } else { drainQueueForRequests(); } } else { final BatchUniqueIdentifier peekedBatchUniqueIdentifier = recordsToCheck == null ? null : recordsToCheck.batchUniqueIdentifier(); log.info("{} : Received a stale notification with id instead of expected id at {}. Will ignore.", shardId, recordsDeliveryAck.batchUniqueIdentifier(), peekedBatchUniqueIdentifier, Instant.now()); } takeDelayedDeliveryActionIfRequired(shardId, lastEventDeliveryTime, log); }
Source:
<code>public Optional<TableLayoutResult> getLayout(Session session, TableHandle table, Constraint<ColumnHandle> constraint, Optional<Set<ColumnHandle>> desiredColumns) { if (constraint.getSummary().isNone()) { return Optional.empty(); } ConnectorId connectorId = table.getConnectorId(); ConnectorTableHandle connectorTable = table.getConnectorHandle(); CatalogMetadata catalogMetadata = getCatalogMetadata(session, connectorId); ConnectorMetadata metadata = catalogMetadata.getMetadataFor(connectorId); ConnectorTransactionHandle transaction = catalogMetadata.getTransactionHandleFor(connectorId); ConnectorSession connectorSession = session.toConnectorSession(connectorId); List<ConnectorTableLayoutResult> layouts = metadata.getTableLayouts(connectorSession, connectorTable, constraint, desiredColumns); if (layouts.isEmpty()) { return Optional.empty(); } <START> if (layouts.size() > 1) { <END> throw new PrestoException(NOT_SUPPORTED, format("Connector returned multiple layouts for table %s", table)); } return Optional.of(new TableLayoutResult(fromConnectorLayout(connectorId, transaction, layouts.get(0).getTableLayout()), layouts.get(0).getUnenforcedConstraint())); }</code><technical_language>change ConnectorMetadata#getTableLayouts ConnectorMetadata#getTableLayout returns a single ConnectorTableLayoutResult</technical_language>

Target:
public TableLayoutResult getLayout(Session session, TableHandle table, Constraint<ColumnHandle> constraint, Optional<Set<ColumnHandle>> desiredColumns) { checkArgument(!constraint.getSummary().isNone(), "Cannot get Layout if constraint is none"); ConnectorId connectorId = table.getConnectorId(); ConnectorTableHandle connectorTable = table.getConnectorHandle(); CatalogMetadata catalogMetadata = getCatalogMetadata(session, connectorId); ConnectorMetadata metadata = catalogMetadata.getMetadataFor(connectorId); ConnectorSession connectorSession = session.toConnectorSession(connectorId); List<ConnectorTableLayoutResult> layouts = metadata.getTableLayouts(connectorSession, connectorTable, constraint, desiredColumns); if (layouts.size() != 1) { throw new PrestoException(NOT_SUPPORTED, "Connector returned multiple layouts for table " + table); } return new TableLayoutResult(fromConnectorLayout(connectorId, table.getConnectorHandle(), table.getTransaction(), layouts.get(0).getTableLayout()), layouts.get(0).getUnenforcedConstraint()); }
Source:
<code>public Item fetch(String uri) { try { YouTubeVideoEntry videoEntry = gdataClient.get(uri); String itemUri = YoutubeUriCanonicaliser.canonicalUriFor(YoutubeUriCanonicaliser.videoIdFrom(uri)); return contentExtractor.extract(new YouTubeSource(videoEntry, itemUri)); } catch (HttpStatusCodeException e) { <START> return null; <END> } catch (Exception e) { throw new FetchException("Failed to fetch: " + uri, e); } }</code><technical_language>return null propagate exception? If want return null exception logged if swallowing it</technical_language>

Target:
public Item fetch(String uri) { try { YouTubeVideoEntry videoEntry = gdataClient.get(uri); String itemUri = YoutubeUriCanonicaliser.canonicalUriFor(YoutubeUriCanonicaliser.videoIdFrom(uri)); return contentExtractor.extract(new YouTubeSource(videoEntry, itemUri)); } catch (HttpStatusCodeException e) { log.error("HTTP Error Status code:", e); return null; } catch (Exception e) { throw new FetchException("Failed to fetch: " + uri, e); } }
Source:
<code>public boolean canMine(Material type) { <START> return type.name().endsWith("_ORE") || (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_16) && type == Material.ANCIENT_DEBRIS && canMineAncientDebris.getValue()); <END> }</code><technical_language>Also, this is a bit long for a single line I think. restructure this: if (ore) { return true; } else if (1.16) { return [debris stuff] } else { return false; }</technical_language>

Target:
public boolean canMine(Material type) { if (type.name().endsWith("_ORE")) { return true; } else if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_16)) { return type == Material.ANCIENT_DEBRIS && canMineAncientDebris.getValue(); } else { return false; } }
Source:
<code>public FontMetrics getLineMetrics (int lineIndex) { checkLayout(); computeRuns(null); if (!(0 <= lineIndex && lineIndex < runs.length)) SWT.error(SWT.ERROR_INVALID_RANGE); long hDC = device.internal_new_GC(null); long srcHdc = OS.CreateCompatibleDC(hDC); TEXTMETRIC lptm = OS.IsUnicode ? (TEXTMETRIC)new TEXTMETRICW() : new TEXTMETRICA(); OS.SelectObject(srcHdc, font != null ? font.handle : device.systemFont.handle); OS.GetTextMetrics(srcHdc, lptm); OS.DeleteDC(srcHdc); device.internal_dispose_GC(hDC, null); <START> int ascent = Math.max(DPIUtil.autoScaleDown(lptm.tmAscent), this.ascent); int descent = Math.max(DPIUtil.autoScaleDown(lptm.tmDescent), this.descent); <END> int leading = DPIUtil.autoScaleDown(lptm.tmInternalLeading); if (text.length() != 0) { StyleItem[] lineRuns = runs[lineIndex]; for (int i = 0; i<lineRuns.length; i++) { StyleItem run = lineRuns[i]; if (run.ascent > ascent) { ascent = run.ascent; leading = run.leading; } descent = Math.max(descent, run.descent); } } lptm.tmAscent = DPIUtil.autoScaleUp(ascent); lptm.tmDescent = DPIUtil.autoScaleUp(descent); lptm.tmHeight = DPIUtil.autoScaleUp(ascent + descent); lptm.tmInternalLeading = DPIUtil.autoScaleUp(leading); lptm.tmAveCharWidth = 0; return FontMetrics.win32_new(lptm); }</code><technical_language>this.ascent this.descent in Pixels autoScaleDown applied deciding Math.max</technical_language>

Target:
public FontMetrics getLineMetrics (int lineIndex) { checkLayout(); computeRuns(null); if (!(0 <= lineIndex && lineIndex < runs.length)) SWT.error(SWT.ERROR_INVALID_RANGE); long hDC = device.internal_new_GC(null); long srcHdc = OS.CreateCompatibleDC(hDC); TEXTMETRIC lptm = OS.IsUnicode ? (TEXTMETRIC)new TEXTMETRICW() : new TEXTMETRICA(); OS.SelectObject(srcHdc, font != null ? font.handle : device.systemFont.handle); OS.GetTextMetrics(srcHdc, lptm); OS.DeleteDC(srcHdc); device.internal_dispose_GC(hDC, null); int ascentInPoints = DPIUtil.autoScaleDown(Math.max(lptm.tmAscent, this.ascentInPixels)); int descentInPoints = DPIUtil.autoScaleDown(Math.max(lptm.tmDescent, this.descentInPixels)); int leadingInPoints = DPIUtil.autoScaleDown(lptm.tmInternalLeading); if (text.length() != 0) { StyleItem[] lineRuns = runs[lineIndex]; for (int i = 0; i<lineRuns.length; i++) { StyleItem run = lineRuns[i]; if (run.ascentInPoints > ascentInPoints) { ascentInPoints = run.ascentInPoints; leadingInPoints = run.leadingInPoints; } descentInPoints = Math.max(descentInPoints, run.descentInPoints); } } lptm.tmAscent = DPIUtil.autoScaleUp(ascentInPoints); lptm.tmDescent = DPIUtil.autoScaleUp(descentInPoints); lptm.tmHeight = DPIUtil.autoScaleUp(ascentInPoints + descentInPoints); lptm.tmInternalLeading = DPIUtil.autoScaleUp(leadingInPoints); lptm.tmAveCharWidth = 0; return FontMetrics.win32_new(lptm); }
Source:
<code>public boolean validateIntervals() { boolean repsOK = true, intervalOK = true; if (this.getReps() > 1) { if (this.getReps() > 6) { logger.info("Reps specified exceed the maximum allowed."); logger.info("Use --help for allowed values."); repsOK = false; } if (this.getInterval() < 10) { <START> logger.info("Interval specificed is lower than the minium allowed."); <END> logger.info("Use --help for allowed values."); intervalOK = false; } } return (repsOK && intervalOK); }</code><technical_language>suggestion logger.info("'--interval' is minimum allowed [10].", this.getInterval());</technical_language>

Target:
public boolean validateIntervals() { boolean repsOK = true, intervalOK = true; if (this.getReps() > 1) { if (this.getReps() > 6) { logger.info("'--reps' specified exceed the maximum allowed [6].", this.getReps()); logger.info("Use --help for allowed values."); repsOK = false; } if (this.getInterval() < 10) { logger.info("Interval specificed is lower than the minium allowed."); logger.info("Use --help for allowed values."); intervalOK = false; } } return (repsOK && intervalOK); }
Source:
<code>public DataWord(byte[] data) { if (data == null) <START> this.data = ByteUtil.EMPTY_BYTE_ARRAY; <END> else if (data.length == 32) this.data = data; else if (data.length <= 32) { byte[] bytes = ZERO.getData(); System.arraycopy(data, 0, bytes, 32 - data.length, data.length); this.data = bytes; } else throw new RuntimeException(String.format("Data word can't exceed 32 bytes: 0x%s", ByteUtil.toHexString(data))); }</code><technical_language>constant here</technical_language>

Target:
private DataWord(byte[] data) { if (data == null || data.length != 32) throw new RuntimeException("Input byte array should have 32 bytes in it!"); this.data = data; }
Source:
<code>public void doRun(IProgressMonitor monitor, String projectID) throws CoreException { Object[] selection = getCheckedElements(); int totalSelected = selection.length; if (totalSelected > 0) { if (monitor == null) { monitor = new NullProgressMonitor(); } SubMonitor submonitor = SubMonitor.convert(monitor, 1); <START> submonitor.subTask(CUIPlugin.getResourceString(KEY_TITLE)); <END> convertProjects(selection, submonitor.split(1), projectID); } }</code><technical_language>subtask != task lines be: SubMonitor.convert(monitor, /title/, 1); (other cases of marked ditto2)</technical_language>

Target:
public void doRun(IProgressMonitor monitor, String projectID) throws CoreException { Object[] selection = getCheckedElements(); int totalSelected = selection.length; if (totalSelected > 0) { SubMonitor submonitor = SubMonitor.convert(monitor, CUIPlugin.getResourceString(KEY_TITLE), 1); convertProjects(selection, submonitor.split(1), projectID); } }
Source:
<code>public EntityType(Type type) { <START> this(type, new LinkedHashSet<Supertype>(), new DefaultVariableNameFunction()); <END> }</code><technical_language>a singleton instance of DefaultVariableNameFunction</technical_language>

Target:
public EntityType(Type type) { this(type, new LinkedHashSet<Supertype>(), DefaultVariableNameFunction.INSTANCE); }
Source:
<code>private URI moveSegmentToOutputPinotFS(Map<String, String> taskConfigs, File localSegmentTarFile) throws Exception { URI outputSegmentDirURI = URI.create(taskConfigs.get(BatchConfigProperties.OUTPUT_SEGMENT_DIR_URI)); <START> PinotFS outputFileFS = getPinotFS(outputSegmentDirURI); <END> URI outputSegmentTarURI = URI.create(outputSegmentDirURI + localSegmentTarFile.getName()); if (!Boolean.parseBoolean(taskConfigs.get(BatchConfigProperties.OVERWRITE_OUTPUT)) && outputFileFS .exists(outputSegmentDirURI)) { LOGGER.warn("Not overwrite existing output segment tar file: {}", outputFileFS.exists(outputSegmentDirURI)); } else { outputFileFS.copyFromLocalFile(localSegmentTarFile, outputSegmentTarURI); } return outputSegmentTarURI; }</code><technical_language>output FS need registered if present? is assumption input fs</technical_language>

Target:
private URI moveSegmentToOutputPinotFS(Map<String, String> taskConfigs, File localSegmentTarFile) throws Exception { if (!taskConfigs.containsKey(BatchConfigProperties.OUTPUT_SEGMENT_DIR_URI)) { return localSegmentTarFile.toURI(); } URI outputSegmentDirURI = URI.create(taskConfigs.get(BatchConfigProperties.OUTPUT_SEGMENT_DIR_URI)); PinotFS outputFileFS = getOutputPinotFS(taskConfigs, outputSegmentDirURI); URI outputSegmentTarURI = URI.create(outputSegmentDirURI + localSegmentTarFile.getName()); if (!Boolean.parseBoolean(taskConfigs.get(BatchConfigProperties.OVERWRITE_OUTPUT)) && outputFileFS .exists(outputSegmentDirURI)) { LOGGER.warn("Not overwrite existing output segment tar file: {}", outputFileFS.exists(outputSegmentDirURI)); } else { outputFileFS.copyFromLocalFile(localSegmentTarFile, outputSegmentTarURI); } return outputSegmentTarURI; }
Source:
<code>public void shouldReadAllLines() throws Exception { ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext(); <START> final String inputFilePath = "/aggregated.vcf.gz"; <END> String input = AggregatedVcfReaderTest.class.getResource(inputFilePath).getFile(); String fileId = "5"; String studyId = "7"; String studyName = "study name"; VcfHeaderReader headerReader = new VcfHeaderReader(new File(input), fileId, studyId, studyName, VariantStudy.StudyType.COLLECTION, VariantSource.Aggregation.NONE); VariantSource source = headerReader.read(); AggregatedVcfReader vcfReader = new AggregatedVcfReader(source, input); vcfReader.setSaveState(false); vcfReader.open(executionContext); consumeReader(input, vcfReader); }</code><technical_language>This a private static final String class level</technical_language>

Target:
public void shouldReadAllLines() throws Exception { ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext(); File input = TestFileUtils.getResource(INPUT_FILE_PATH); VcfHeaderReader headerReader = new VcfHeaderReader(input, FILE_ID, STUDY_ID, STUDY_NAME, VariantStudy.StudyType.COLLECTION, VariantSource.Aggregation.NONE); VariantSource source = headerReader.read(); AggregatedVcfReader vcfReader = new AggregatedVcfReader(source, input); vcfReader.setSaveState(false); vcfReader.open(executionContext); consumeReader(input, vcfReader); }
Source:
<code>public List<Path> search(RepositorySearchRequest request) { List<Path> result = new LinkedList<Path>(); Storage storage = configurationManager.getConfiguration().getStorage(request.getStorageId()); Repository repository = storage.getRepository(request.getRepositoryId()); LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); List<ArtifactEntry> artifactEntryList = artifactEntryService.findByCoordinates(request.getStorageId(), request.getRepositoryId(), request.getCoordinates(), request.getSkip(), request.getLimit(), request.getOrderBy(), false); for (ArtifactEntry artifactEntry : artifactEntryList) { RepositoryPath repositoryPath; try { repositoryPath = layoutProvider.resolve(repository, artifactEntry.getArtifactCoordinates()); } catch (IOException e) { <START> logger.error(String.format("Failed to resolve Remote Artifact [%s]", artifactEntry.getArtifactPath()), <END> e); continue; } result.add(repositoryPath); } return result; }</code><technical_language>Failed resolve Remote Artifact Remote ? hosted repository</technical_language>

Target:
public List<Path> search(RepositorySearchRequest request) { List<Path> result = new LinkedList<Path>(); Storage storage = configurationManager.getConfiguration().getStorage(request.getStorageId()); Repository repository = storage.getRepository(request.getRepositoryId()); LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); List<ArtifactEntry> artifactEntryList = artifactEntryService.findByCoordinates(request.getStorageId(), request.getRepositoryId(), request.getCoordinates(), request.getSkip(), request.getLimit(), request.getOrderBy(), false); for (ArtifactEntry artifactEntry : artifactEntryList) { RepositoryPath repositoryPath; try { repositoryPath = layoutProvider.resolve(repository, artifactEntry.getArtifactCoordinates()); } catch (IOException e) { logger.error(String.format("Failed to resolve Artifact [%s]", artifactEntry.getArtifactPath()), e); continue; } result.add(repositoryPath); } return result; }
Source:
<code>public void handleSuccess() { super.handleSuccess(); if (isCompleteTrace(trace)) { disposeProvider(false); } else { fNbRead += getNbRead(); synchronized (fRequestSyncObj) { <START> if (!getRange().equals(fTimeRange)) { <END> startRequest(); } } } }</code><technical_language>is rationale this check? if (getRange().getEndTime() > fTimeRange.getEndTime()) { for instance</technical_language>

Target:
public void handleSuccess() { super.handleSuccess(); if (isCompleteTrace(trace)) { disposeProvider(false); } else { fNbRead += getNbRead(); synchronized (fRequestSyncObj) { final TmfTimeRange timeRange = fTimeRange; if (timeRange != null) { if (getRange().getEndTime().getValue() > timeRange.getEndTime().getValue()) { startRequest(); } } } } }
Source:
<code>private boolean isMaterialFromTypes(Map material, List<String> pollerPluginIds) { if (((String) material.get("type")).equalsIgnoreCase("scm")) { <START> for (String pollerPluginId : pollerPluginIds) { if(((String) material.get("plugin-id")).equalsIgnoreCase(pollerPluginId)) { return true; } } <END> } return false; }</code><technical_language>This refactored contains method List</technical_language>

Target:
private boolean isMaterialFromTypes(Map material, List<String> pollerPluginIds) { if (((String) material.get("type")).equalsIgnoreCase("scm")) { return pollerPluginIds.contains((String) material.get("plugin-id")); } return false; }
Source:
<code>public AdSkinHelper(String pathToLeftPart, String pathToRightPart, WebDriver driver) { this.pathToLeftPart = pathToLeftPart; this.pathToRightPart = pathToRightPart; this.driver = driver; this.adsComparison = new AdsComparison(); this.imageEditor = new ImageEditor(); this.shooter = new Shooter(); this.imageComparison = new ImageComparison(); WebElement wikiaArticle = driver.findElement(By.id("WikiaPageBackground")); WebElement globalNavigation = driver.findElement(By.id("globalNavigation")); this.viewPortWidth = globalNavigation.getSize().getWidth(); <START> this.startSkinY = globalNavigation.getSize().getHeight(); <END> this.articleLeftSideX = wikiaArticle.getLocation().x; this.articleRightSideX = wikiaArticle.getLocation().x + wikiaArticle.getSize().getWidth(); }</code><technical_language>is a lot of staff happening in constructor, move init method, a lazy loading? is a situation when, a add a filed in object throw exception construction</technical_language>

Target:
public AdSkinHelper(String pathToLeftPart, String pathToRightPart, WebDriver driver) { this.pathToLeftPart = pathToLeftPart; this.pathToRightPart = pathToRightPart; this.driver = driver; }
Source:
<code>protected Endpoint createEndpoint(String urispec, String remaining, Map<String, Object> params) throws Exception { WekaConfiguration config = new WekaConfiguration(this); <START> setProperties(config, params); <END> Command command = Command.valueOf(remaining); config.setCommand(command); return new WekaEndpoint(urispec, this, config); }</code><technical_language>I recall, do setProperties config endpoint. @oscerd @davsclaus confirm this</technical_language>

Target:
protected Endpoint createEndpoint(String urispec, String remaining, Map<String, Object> params) throws Exception { WekaConfiguration config = new WekaConfiguration(); WekaEndpoint endpoint = new WekaEndpoint(urispec, this, config); setProperties(endpoint, params); Command command = Command.valueOf(remaining); config.setCommand(command); return endpoint; }
Source:
<code>public void testAccessControl_instructorAccessProfileFromHisCourse_shouldPass() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); loginAsInstructor(instructor1OfCourse1.googleId); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, instructor1OfCourse1.courseId, Const.ParamsNames.STUDENT_EMAIL, student1InCourse1.getEmail(), }; <START> verifyCanAccess(submissionParams); <END> }</code><technical_language>of instructor test cases (such this) simplified running helper methods in BaseActionTest instead of of manually. easier understand parse. utilize methods verifyUnaccessibleForInstructorsOfOtherCourses(submissionParams); verifyAccessibleForInstructorsOfTheSameCourse(submissionParams); verifyAccessibleForAdminToMasqueradeAsInstructor(submissionParams); instead of now. Check other test methods too. In vein, for students: verifyUnaccessibleForStudentsOfOtherCourses(submissionParams); verifyAccessibleForStudentsOfTheSameCourse(submissionParams); verifyAccessibleForAdminToMasqueradeAsStudent(submissionParams); etc</technical_language>

Target:
public void testAccessControl_instructorAccessProfileFromHisCourse_shouldPass() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, instructor1OfCourse1.courseId, Const.ParamsNames.STUDENT_EMAIL, student1InCourse1.getEmail(), }; verifyAccessibleForInstructorsOfTheSameCourse(submissionParams); }
Source:
<code>public void teardownTest() throws InterruptedException { firewallPolicyApi().delete(currentFirewallPolicy.id()); <START> Thread.sleep(15000); <END> assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }</code><technical_language>this in a live test is a symptom of users do themselves. build-in Predicates2.retry construct wait server is deleted consider binding guice context reused needed</technical_language>

Target:
public void teardownTest() throws InterruptedException { assertNodeAvailable(currentServer); firewallPolicyApi().delete(currentFirewallPolicy.id()); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }
Source:
<code>protected String getTableNameFromQuery(String jsonStr) { JSONObject j = new JSONObject(jsonStr); String s = (String) j.get("query"); <START> String str = ""; <END> for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '{' || s.charAt(i) == '}') { continue; } else { str = str + s.charAt(i); } } String[] queryTerms = str.trim().split("\\s+"); return queryTerms[0]; }</code><technical_language>lets StringBuilder for str changing loop multiple times</technical_language>

Target:
protected String getTableNameFromQuery(String jsonStr) { StringBuilder str = new StringBuilder(); try { JSONObject j = new JSONObject(jsonStr); String s = (String) j.get("query"); Integer countBrackets = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '{' || s.charAt(i) == '}') { countBrackets++; if (countBrackets == 2) { break; } } else { str.append(s.charAt(i)); } } } catch (JSONException e) { log.error("Exception: {}", e); } return str.toString().trim().split("\\s+")[0]; }
Source:
<code>public void messageTrackedAndRemovedWhenClientLeaves() throws Exception { assertThat(activeMessageHandler.getTrackedClients().count()).isZero(); storeProxy.getAndAppend(42L, createPayload(42L)); <START> Map<Long, EhcacheEntityResponse> responses = activeMessageHandler.getRecordedMessages().filter(r->r.getClientSourceId().toLong() == activeMessageHandler.getTrackedClients().findFirst().get().toLong()) <END> .collect(Collectors.toMap(r->r.getTransactionId(), r->r.getResponse())); assertThat(responses).hasSize(1); assertThat(activeEntity.getConnectedClients()).hasSize(1); service.stop(); activeEntity.notifyDestroyed(activeMessageHandler.getTrackedClients().iterator().next()); waitForPredicate(e -> activeEntity.getConnectedClients().size() > 0, 2000); assertThat(activeMessageHandler.getTrackedClients().count()).isZero(); }</code><technical_language>code originally filtering mapping pretty pointless: java assertThat(activeMessageHandler.getRecordedMessages().collect(toList())).hasSize(1);</technical_language>

Target:
public void messageTrackedAndRemovedWhenClientLeaves() throws Exception { assertThat(activeMessageHandler.getTrackedClients().count()).isZero(); storeProxy.getAndAppend(42L, createPayload(42L)); assertThat(activeMessageHandler.getRecordedMessages().collect(Collectors.toList())).hasSize(1); assertThat(activeEntity.getConnectedClients()).hasSize(1); service.stop(); activeEntity.notifyDestroyed(activeMessageHandler.getTrackedClients().iterator().next()); waitForPredicate(e -> activeEntity.getConnectedClients().size() > 0, 2000); assertThat(activeMessageHandler.getTrackedClients().count()).isZero(); }
Source:
<code>public void showImage() { this.displayImage = !this.displayImage; if (this.displayImage) { try { identifyImage(this.imageNumber); } catch (Exception e) { Helper.setFehlerMeldung("Error while generating image", e.getMessage()); <START> logger.error(e.getMessage(), e); <END> } } }</code><technical_language>setErrorMessage</technical_language>

Target:
public void showImage() { this.displayImage = !this.displayImage; if (this.displayImage) { try { identifyImage(this.imageNumber); } catch (RuntimeException e) { Helper.setErrorMessage("Error while generating image", logger, e); } } }
Source:
<code>private void initializeDefaultsFromPropertiesFile() throws Exception { Properties props = new Properties(); try (FileReader fr = new FileReader(config.trim())) { props.load(fr); } catch (Exception e) { } <START> String prop = props.getProperty("group.id", ""); <END> if (prop.isEmpty()) { groupid = "voltdb-" + (useSuppliedProcedure ? procedure : table); } else { groupid = prop; } prop = props.getProperty("socket.timeout.ms", null); if (prop != null) { timeout = Integer.parseInt(prop); } prop = props.getProperty("socket.receive.buffer.bytes", null); if (prop != null) { buffersize = Integer.parseInt(prop); } }</code><technical_language>simplify this "groupid = props.getProperty(..." drop else case. a review blocker though</technical_language>

Target:
private void initializeDefaultsFromPropertiesFile() throws Exception { if (config.trim().isEmpty()) { return; } Properties props = new Properties(); try (FileReader fr = new FileReader(config.trim())) { props.load(fr); } String prop = props.getProperty("group.id", ""); if (prop.isEmpty()) { groupid = "voltdb-" + (useSuppliedProcedure ? procedure : table); } else { groupid = prop; } prop = props.getProperty("socket.timeout.ms", null); if (prop != null) { timeout = Integer.parseInt(prop); } prop = props.getProperty("socket.receive.buffer.bytes", null); if (prop != null) { buffersize = Integer.parseInt(prop); } prop = props.getProperty("zookeeper.session.timeout.millis", null); if (prop != null) { zookeeperSessionTimeoutMillis = Integer.parseInt(prop); } }
Source:
<code>public static void main(String[] args) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); DiskReformatterConfig config = new DiskReformatterConfig(properties); StoreConfig storeConfig = new StoreConfig(properties); try (ClusterMap clusterMap = new StaticClusterAgentsFactory(new ClusterMapConfig(properties), config.hardwareLayoutFilePath, config.partitionLayoutFilePath).getClusterMap()) { StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap); DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort); if (dataNodeId == null) { throw new IllegalArgumentException( "Did not find node in clustermap with hostname:port - " + config.datanodeHostname + ":" <START> + config.datanodePort); <END> } DiskReformatter reformatter = new DiskReformatter(dataNodeId, config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance()); reformatter.reformat(config.diskMountPath, new File(config.scratchPath)); } }</code><technical_language>I is easier work static cluster map for things, moved Helix static cluster map is deprecated, build in dependencies Helix instead</technical_language>

Target:
public static void main(String[] args) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); DiskReformatterConfig config = new DiskReformatterConfig(properties); StoreConfig storeConfig = new StoreConfig(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties); ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath); try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) { StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap); DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort); if (dataNodeId == null) { throw new IllegalArgumentException( "Did not find node in clustermap with hostname:port - " + config.datanodeHostname + ":" + config.datanodePort); } DiskReformatter reformatter = new DiskReformatter(dataNodeId, Collections.EMPTY_LIST, config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance()); AtomicInteger exitStatus = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(config.diskMountPaths.length); for (int i = 0; i < config.diskMountPaths.length; i++) { int finalI = i; Runnable runnable = () -> { try { reformatter.reformat(config.diskMountPaths[finalI], new File(config.scratchPaths[finalI])); latch.countDown(); } catch (Exception e) { throw new IllegalStateException(e); } }; Thread thread = Utils.newThread(config.diskMountPaths[finalI] + "-reformatter", runnable, true); thread.setUncaughtExceptionHandler((t, e) -> { exitStatus.set(1); logger.error("Reformatting failed", config.diskMountPaths[finalI], e); latch.countDown(); }); thread.start(); } latch.await(); System.exit(exitStatus.get()); } }
Source:
<code>public String getOpenTagPattern() { <START> return String.format("<[ ]*%s[ ]*>", this.xmlName); <END> }</code><technical_language>u extract a final constant a readable name out of "<[ ]*%s[ ]*>"</technical_language>

Target:
public String getOpenTagPattern() { return String.format(OPEN_TAG_PATTERN, this.xmlName); }
Source:
<code>public void run(DiagnosticsLogWriter writer) { probeRenderer.writer = writer; probeRenderer.timeMillis = System.currentTimeMillis(); <START> probeRenderContext.renderAt(ProbeLevel.DEBUG, probeRenderer); <END> probeRenderer.writer = null; }</code><technical_language>This is currently case I do rendered. configured probe level</technical_language>

Target:
public void run(DiagnosticsLogWriter writer) { collector.writer = writer; collector.timeMillis = System.currentTimeMillis(); context.collectAll(collector); collector.writer = null; }
Source:
<code>private void persistModel(long modelId, String modelName, MLModel model) throws MLModelBuilderException { try { MLStorage storage = databaseService.getModelStorage(modelId); if (storage == null) { throw new MLModelBuilderException("Invalid model ID: " + modelId); } String storageType = storage.getType(); String storageLocation = storage.getLocation(); <START> if (model.getAlgorithmClass().equalsIgnoreCase(MLConstants.DEEPLEARNING)) { <END> MLDeeplearningModel mlDeeplearningModel = (MLDeeplearningModel) model.getModel(); mlDeeplearningModel.setStorageLocation(storageLocation); model.setModel(mlDeeplearningModel); } MLIOFactory ioFactory = new MLIOFactory(mlProperties); MLOutputAdapter outputAdapter = ioFactory.getOutputAdapter(storageType + MLConstants.OUT_SUFFIX); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(model); oos.flush(); oos.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); String outPath = storageLocation + File.separator + modelName; outputAdapter.write(outPath, is); databaseService.updateModelStorage(modelId, storageType, outPath); log.info(String.format("Successfully persisted the model [id] %s", modelId)); } catch (Exception e) { throw new MLModelBuilderException("Failed to persist the model [id] " + modelId + ". " + e.getMessage(), e); } }</code><technical_language>avoid NPEs use; MLConstants.DEEPLEARNING.equalsIgnoreCase(model.getAlgorithmClass())</technical_language>

Target:
private void persistModel(long modelId, String modelName, MLModel model) throws MLModelBuilderException { try { MLStorage storage = databaseService.getModelStorage(modelId); if (storage == null) { throw new MLModelBuilderException("Invalid model ID: " + modelId); } String storageType = storage.getType(); String storageLocation = storage.getLocation(); if (MLConstants.DEEPLEARNING.equalsIgnoreCase(model.getAlgorithmClass())) { MLDeeplearningModel mlDeeplearningModel = (MLDeeplearningModel) model.getModel(); mlDeeplearningModel.setStorageLocation(storageLocation); model.setModel(mlDeeplearningModel); } MLIOFactory ioFactory = new MLIOFactory(mlProperties); MLOutputAdapter outputAdapter = ioFactory.getOutputAdapter(storageType + MLConstants.OUT_SUFFIX); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(model); oos.flush(); oos.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); String outPath = storageLocation + File.separator + modelName; outputAdapter.write(outPath, is); databaseService.updateModelStorage(modelId, storageType, outPath); log.info(String.format("Successfully persisted the model [id] %s", modelId)); } catch (Exception e) { throw new MLModelBuilderException("Failed to persist the model [id] " + modelId + ". " + e.getMessage(), e); } }