auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newArrayList(); ObjectNode rootDocument = getRootDocument(entry); Map<String, String> params = prepareParams(entry); URI uri; for( Map.Entry<String,String> param : params.entrySet()) { uriBuilder = uriBuilder.setParameter(param.getKey(), param.getValue()); } try { uri = uriBuilder.build(); } catch (URISyntaxException e) { <START> LOGGER.error("URI error {}", uriBuilder.toString()); <END> return result; } HttpEntity payload = preparePayload(entry); HttpPost httpPost = prepareHttpPost(uri, payload); CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200 && entity != null) { entityString = EntityUtils.toString(entity); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", uri.toString(), response, e.getMessage()); return result; } finally { try { response.close(); } catch (IOException e) } if( entityString == null ) return result; LOGGER.debug(entityString); ObjectNode extensionFragment = prepareExtensionFragment(entityString); ActivityObject extensionEntity = getEntityToExtend(rootDocument); ExtensionUtil.addExtension(extensionEntity, this.configuration.getExtension(), extensionFragment); rootDocument = setEntityToExtend(rootDocument, extensionEntity); entry.setDocument(rootDocument); result.add(entry); return result; }</code><technical_language>Do want log exception caught here</technical_language>

Target:
public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newArrayList(); ObjectNode rootDocument = getRootDocument(entry); Map<String, String> params = prepareParams(entry); URI uri; for( Map.Entry<String,String> param : params.entrySet()) { uriBuilder = uriBuilder.setParameter(param.getKey(), param.getValue()); } try { uri = uriBuilder.build(); } catch (URISyntaxException e) { LOGGER.error("URI error {}", uriBuilder.toString(), e); return result; } HttpEntity payload = preparePayload(entry); HttpPost httpPost = prepareHttpPost(uri, payload); CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200 && entity != null) { entityString = EntityUtils.toString(entity); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", uri.toString(), response, e); return result; } finally { try { response.close(); } catch (IOException e) } if( entityString == null ) return result; LOGGER.debug(entityString); ObjectNode extensionFragment = prepareExtensionFragment(entityString); ActivityObject extensionEntity = getEntityToExtend(rootDocument); ExtensionUtil.addExtension(extensionEntity, this.configuration.getExtension(), extensionFragment); rootDocument = setEntityToExtend(rootDocument, extensionEntity); entry.setDocument(rootDocument); result.add(entry); return result; }
Source:
<code>public Box(String orient) { setOrient(orient); <START> setAttribute("org.zkoss.zul.css.flex", false); <END> }</code><technical_language>TableLayout</technical_language>

Target:
public Box(String orient) { setOrient(orient); }
Source:
<code>public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { setBorder(BORDER); ScriptWrapper item = (ScriptWrapper) value; if (panel.loadedScript == item) <START> setText("<html><b>" + item.getName() + " (loaded)</b></html>"); <END> else setText(item.getName()); } return this; }</code><technical_language>Is this XSS'able? (I guess XSS but....)</technical_language>

Target:
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { setBorder(BORDER); ScriptWrapper item = (ScriptWrapper) value; if (panel.loadedScript == item) setText( "<html><b>" + StringEscapeUtils.unescapeHtml(item.getName()) + " (loaded)</b></html>"); else setText(item.getName()); } return this; }
Source:
<code>public InsertSelect addColumns(String[] columnNames) { <START> Collections.addAll( this.columnNames,columnNames ); <END> return this; }</code><technical_language>additionally change type of columnNames ArrayList ensureCapacity adding</technical_language>

Target:
public InsertSelect addColumns(String[] columnNames) { this.columnNames.ensureCapacity(this.columnNames.size()+columnNames.length); Collections.addAll( this.columnNames,columnNames ); return this; }
Source:
<code>public static int getStrongSignal(IMultipartContainer container, EnumFacing side, EnumFacing face) { if (container == null) { return 0; } IMultipart part = container.getPartInSlot(PartSlot.getFaceSlot(side)); <START> if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } <END> part = container.getPartInSlot(PartSlot.getEdgeSlot(side, face)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } part = container.getPartInSlot(PartSlot.getFaceSlot(face)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } int max = 0; if (face == null) { part = container.getPartInSlot(PartSlot.CENTER); if (part instanceof IRedstonePart) { max = ((IRedstonePart) part).getStrongSignal(side); } } for (IMultipart p : container.getParts()) { if (!(p instanceof ISlottedRedstonePart) || ((ISlottedRedstonePart) p).getSlotMask().isEmpty()) { if (p instanceof IRedstonePart) { max = Math.max(max, ((IRedstonePart) p).getStrongSignal(side)); } } } return max; }</code><technical_language>instaneof bad bad bad</technical_language>

Target:
public static int getStrongSignal(IMultipartContainer container, EnumFacing side, EnumFacing face) { if (container == null) { return 0; } IMultipart part = container.getPartInSlot(PartSlot.getFaceSlot(side)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } part = container.getPartInSlot(PartSlot.getEdgeSlot(side, face)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } part = container.getPartInSlot(PartSlot.getFaceSlot(face)); if (part != null) { return part instanceof IRedstonePart ? ((IRedstonePart) part).getStrongSignal(side) : 0; } int max = 0; if (face == null) { part = container.getPartInSlot(PartSlot.CENTER); if (part instanceof IRedstonePart) { max = ((IRedstonePart) part).getStrongSignal(side); } } for (IMultipart p : container.getParts()) { if ((!(p instanceof ISlottedRedstonePart) || ((ISlottedRedstonePart) p).getSlotMask().isEmpty()) && p instanceof IRedstonePart) { max = Math.max(max, ((IRedstonePart) p).getStrongSignal(side)); } } return max; }
Source:
<code>public void testFileWithEmptyLineOnlyWithLfCrCrlf() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF_CR_CRLF.toString()); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify( createChecker(checkConfig), <START> getPath("InputNewlineAtEndOfFileNewlineAtEnd.txt"), <END> expected); }</code><technical_language>/var/tmp $ xxd foo.properties 00000000: 0a test case issue is different. InputNewlineAtEndOfFileNewlineAtEnd \n \r\n depending OS. issue happen this file file is longer 1 byte? try mimic file is reported show issue is fixed. Do want a file is line encoding OSes is controlled .gitattributes file InputNewlineAtEndOfFileLf</technical_language>

Target:
public void testFileWithEmptyLineOnlyWithLfCrCrlf() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF_CR_CRLF.toString()); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify( createChecker(checkConfig), getPath("InputNewlineAtEndOfFileNewlineAtEndLf.txt"), expected); }
Source:
<code>public void testCreateAndGetInSameTransaction(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("test"); ClientModel client = realm.getClientByClientId("test-app"); UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); <START> createClientSession(session, client, userSession, "http://redirect", "state"); <END> UserSessionModel userSessionLoaded = session.sessions().getUserSession(realm, userSession.getId()); AuthenticatedClientSessionModel clientSessionLoaded = userSessionLoaded.getAuthenticatedClientSessions().get(client.getId()); Assert.assertNotNull(userSessionLoaded); Assert.assertNotNull(clientSessionLoaded); Assert.assertEquals(userSession.getId(), clientSessionLoaded.getUserSession().getId()); Assert.assertEquals(1, userSessionLoaded.getAuthenticatedClientSessions().size()); }</code><technical_language>I this change is related this PR's intention</technical_language>

Target:
public void testCreateAndGetInSameTransaction(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("test"); ClientModel client = realm.getClientByClientId("test-app"); UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); AuthenticatedClientSessionModel clientSession = createClientSession(session, client, userSession, "http://redirect", "state"); UserSessionModel userSessionLoaded = session.sessions().getUserSession(realm, userSession.getId()); AuthenticatedClientSessionModel clientSessionLoaded = userSessionLoaded.getAuthenticatedClientSessions().get(client.getId()); Assert.assertNotNull(userSessionLoaded); Assert.assertNotNull(clientSessionLoaded); Assert.assertEquals(userSession.getId(), clientSessionLoaded.getUserSession().getId()); Assert.assertEquals(1, userSessionLoaded.getAuthenticatedClientSessions().size()); }
Source:
<code>private boolean stopTransferIfNecessary(ImageTransfer entity, long ts) { if (getParameters().getKeepaliveInterval() > 0 && (entity.getPhase() == ImageTransferPhase.INITIALIZING || entity.getPhase() == ImageTransferPhase.TRANSFERRING) && (entity.getLastUpdated().getTime() / 1000) + getParameters().getKeepaliveInterval() < ts) { String action = "paused"; ImageTransferPhase phase = ImageTransferPhase.PAUSED_SYSTEM; if (getParameters().getTransferType() == TransferType.Download) { action = "canceled"; phase = ImageTransferPhase.CANCELLED; } log.warn("Transfer was due to no updates in seconds. {}", <START> action, <END> ts - (entity.getLastUpdated().getTime() / 1000), getTransferDescription()); updateEntityPhase(phase); return true; } return false; }</code><technical_language>instead of adding this string, cleaner print enum</technical_language>

Target:
private boolean stopTransferIfNecessary(ImageTransfer entity, long ts) { if (transferImageInactivityTimeoutInSeconds > 0 && (entity.getPhase() == ImageTransferPhase.INITIALIZING || entity.getPhase() == ImageTransferPhase.TRANSFERRING) && (entity.getLastUpdated().getTime() / 1000) + transferImageInactivityTimeoutInSeconds < ts) { ImageTransferPhase phase = ImageTransferPhase.PAUSED_SYSTEM; if (getParameters().getTransferType() == TransferType.Download) { phase = ImageTransferPhase.CANCELLED; } log.warn("Transfer phase was changed to due to no updates in seconds. {}", phase.toString(), ts - (entity.getLastUpdated().getTime() / 1000), getTransferDescription()); updateEntityPhase(phase); return true; } return false; }
Source:
<code>private String extract(final StringValueStyle style) { if <START> (style == null || <END> style.getStringValue() == null || style.getStringValue().isEmpty()) { return null; } return style.getStringValue(); }</code><technical_language>null =</technical_language>

Target:
private String extract(final StringValueStyle style) { if (null == style || null == style.getStringValue() || style.getStringValue().isEmpty()) { return null; } return style.getStringValue(); }
Source:
<code>private void setupViewModels() { backgroundLocationViewModel = ViewModelProviders.of(this, new FormEntryViewModelFactory()).get(BackgroundLocationViewModel.class); identityPromptViewModel = ViewModelProviders.of(this).get(IdentityPromptViewModel.class); identityPromptViewModel.requiresIdentityToContinue().observe(this, requiresIdentity -> { if (requiresIdentity) { IdentifyUserPromptDialogFragment dialog = IdentifyUserPromptDialogFragment.create(getFormController().getFormTitle()); DialogUtils.showIfNotShowing(dialog, getSupportFragmentManager()); } }); identityPromptViewModel.isFormEntryCancelled().observe(this, isFormEntryCancelled -> { if (isFormEntryCancelled) { finish(); } }); FormSaveViewModel.Factory changesReasonViewModelFactory = new FormSaveViewModel.Factory(); formSaveViewModel = ViewModelProviders .of(this, changesReasonViewModelFactory) .get(FormSaveViewModel.class); <START> formSaveViewModel.setAnalytics(analytics); <END> formSaveViewModel.getSavedResult().observe(this, this::handleSaveResult); }</code><technical_language>This constructor dependency right? need nullability risk in object</technical_language>

Target:
private void setupViewModels() { backgroundLocationViewModel = ViewModelProviders.of(this, new FormEntryViewModelFactory()).get(BackgroundLocationViewModel.class); identityPromptViewModel = ViewModelProviders.of(this).get(IdentityPromptViewModel.class); identityPromptViewModel.requiresIdentityToContinue().observe(this, requiresIdentity -> { if (requiresIdentity) { IdentifyUserPromptDialogFragment dialog = IdentifyUserPromptDialogFragment.create(getFormController().getFormTitle()); DialogUtils.showIfNotShowing(dialog, getSupportFragmentManager()); } }); identityPromptViewModel.isFormEntryCancelled().observe(this, isFormEntryCancelled -> { if (isFormEntryCancelled) { finish(); } }); FormSaveViewModel.Factory changesReasonViewModelFactory = new FormSaveViewModel.Factory(analytics); formSaveViewModel = ViewModelProviders .of(this, changesReasonViewModelFactory) .get(FormSaveViewModel.class); formSaveViewModel.getSavedResult().observe(this, this::handleSaveResult); }
Source:
<code>public void delete() throws IOException { super.delete(); for(MatrixRun run : getExactRuns()) { <START> if (run.getWhyKeepLog() != null) continue; <END> run.delete(); } }</code><technical_language>I expect MatrixBuild.getWhyKeepLog return non-null in this case, is a unit</technical_language>

Target:
public void delete() throws IOException { super.delete(); for(MatrixRun run : getExactRuns()) { run.delete(); } }
Source:
<code>protected void updateIteration() { <START> refreshIteration = refreshIteration++ % NUMBER_VMS_REFRESHES_BEFORE_SAVE; <END> }</code><technical_language>separate incerement check</technical_language>

Target:
protected void updateIteration() { refreshIteration = (++refreshIteration) % NUMBER_VMS_REFRESHES_BEFORE_SAVE; }
Source:
<code>public boolean isModelerResource() { <START> if (resource.getURI() != null) { <END> return new FileQuery(resource.getURI().fileExtension()).isVSMFile(); } return false; }</code><technical_language>need try catch here</technical_language>

Target:
public boolean isModelerResource() { try { if (resource.getURI() != null) { return new FileQuery(resource.getURI().fileExtension()).isVSMFile(); } } catch (IllegalStateException e) { } return false; }
Source:
<code>public static void main(String args[]) throws Exception { VerifiableProperties verifiableProperties = StoreToolsUtil.getVerifiableProperties(args); <START> String storeId = verifiableProperties.getString("storeId", "dummy"); <END> MetricRegistry registry = new MetricRegistry(); StoreToolsMetrics metrics = new StoreToolsMetrics(registry, storeId); JmxReporter reporter = null; try { reporter = JmxReporter.forRegistry(registry).build(); reporter.start(); DumpDataTool dumpDataTool = new DumpDataTool(verifiableProperties, metrics); dumpDataTool.doOperation(); } finally { if (reporter != null) { reporter.stop(); } } }</code><technical_language>is intent store id in StoreToolsMetrics? pass in dummy values</technical_language>

Target:
public static void main(String args[]) throws Exception { VerifiableProperties verifiableProperties = StoreToolsUtil.getVerifiableProperties(args); MetricRegistry registry = new MetricRegistry(); StoreToolsMetrics metrics = new StoreToolsMetrics(registry); JmxReporter reporter = null; try { reporter = JmxReporter.forRegistry(registry).build(); reporter.start(); DumpDataTool dumpDataTool = new DumpDataTool(verifiableProperties, metrics); dumpDataTool.doOperation(); } finally { if (reporter != null) { reporter.stop(); } } }
Source:
<code>public static ICleanUpFixCore createCleanUp(CompilationUnit root, boolean addMissingMethod, boolean makeTypeAbstract, IProblemLocationCore[] problems) { Assert.isLegal(!addMissingMethod || !makeTypeAbstract); if (!addMissingMethod && !makeTypeAbstract) return null; if (problems.length == 0) return null; ArrayList<CompilationUnitRewriteOperation> operations= new ArrayList<>(); for (IProblemLocationCore problem : problems) { if (addMissingMethod) { ASTNode typeNode= getSelectedTypeNode(root, problem); if (typeNode != null && !isTypeBindingNull(typeNode)) { operations.add(new AddUnimplementedMethodsOperation(typeNode)); } } else { ASTNode typeNode= getSelectedTypeNode(root, problem); if (typeNode instanceof TypeDeclaration) { operations.add(new MakeTypeAbstractOperation((TypeDeclaration) typeNode)); } } } if <START> (operations.size() <END> == 0) return null; String label; if (addMissingMethod) { label= CorrectionMessages.UnimplementedMethodsCorrectionProposal_description; } else { label= CorrectionMessages.UnimplementedCodeFix_MakeAbstractFix_label; } return new UnimplementedCodeFixCore(label, root, operations.toArray(new CompilationUnitRewriteOperation[operations.size()])); }</code><technical_language>Isempty()</technical_language>

Target:
public static ICleanUpFixCore createCleanUp(CompilationUnit root, boolean addMissingMethod, boolean makeTypeAbstract, IProblemLocationCore[] problems) { Assert.isLegal(!addMissingMethod || !makeTypeAbstract); if (!addMissingMethod && !makeTypeAbstract) return null; if (problems.length == 0) return null; ArrayList<CompilationUnitRewriteOperation> operations= new ArrayList<>(); for (IProblemLocationCore problem : problems) { if (addMissingMethod) { ASTNode typeNode= getSelectedTypeNode(root, problem); if (typeNode != null && !isTypeBindingNull(typeNode)) { operations.add(new AddUnimplementedMethodsOperation(typeNode)); } } else { ASTNode typeNode= getSelectedTypeNode(root, problem); if (typeNode instanceof TypeDeclaration) { operations.add(new MakeTypeAbstractOperation((TypeDeclaration) typeNode)); } } } if (operations.isEmpty()) return null; String label; if (addMissingMethod) { label= CorrectionMessages.UnimplementedMethodsCorrectionProposal_description; } else { label= CorrectionMessages.UnimplementedCodeFix_MakeAbstractFix_label; } return new UnimplementedCodeFixCore(label, root, operations.toArray(new CompilationUnitRewriteOperation[operations.size()])); }
Source:
<code>public CsvLoader(Map<String, String> config) { CSVFormat format = CSVFormat.EXCEL; if (config.containsKey("delimiter")) { <START> format = format.withDelimiter(config.get("delimiter").charAt(0)); <END> } if (config.containsKey("quoteChar")) { format = format.withQuote(config.get("quoteChar").charAt(0)); } if (config.containsKey("quoteMode")) { format = format.withQuoteMode(QuoteMode.valueOf(config.get("quoteMode"))); } if (config.containsKey("commentStart")) { format = format.withCommentMarker(config.get("commentStart").charAt(0)); } if (config.containsKey("escape")) { format = format.withCommentMarker(config.get("escape").charAt(0)); } if (config.containsKey("ignoreSurroundingSpaces")) { format = format.withIgnoreSurroundingSpaces(config.get("ignoreSurroundingSpaces").equals("true")); } if (config.containsKey("ignoreEmptyLines")) { format = format.withIgnoreEmptyLines(config.get("ignoreEmptyLines").equals("true")); } if (config.containsKey("recordSeparator")) { format = format.withRecordSeparator(config.get("recordSeparator")); } if (config.containsKey("nullString")) { format = format.withNullString(config.get("nullString")); } if (config.containsKey("trim")) { format = format.withTrim(config.get("trim").equals("true")); } if (config.containsKey("trailingDelimiter")) { format = format.withTrailingDelimiter(config.get("trailingDelimiter").equals("true")); } this.format = format .withAllowMissingColumnNames() .withHeader(); }</code><technical_language>yes, safer in cases... I typed in reverted due a temporary lack of pro-activity part</technical_language>

Target:
public CsvLoader(Map<String, String> config) { CSVFormat format = CSVFormat.EXCEL; if (config.containsKey("delimiter")) { format = format.withDelimiter(onlyChar(config, "delimiter")); } if (config.containsKey("quoteChar")) { format = format.withQuote(onlyChar(config, "quoteChar")); } if (config.containsKey("quoteMode")) { format = format.withQuoteMode(QuoteMode.valueOf(config.get("quoteMode"))); } if (config.containsKey("commentStart")) { format = format.withCommentMarker(onlyChar(config, "commentStart")); } if (config.containsKey("escape")) { format = format.withCommentMarker(onlyChar(config, "escape")); } if (config.containsKey("ignoreSurroundingSpaces")) { format = format.withIgnoreSurroundingSpaces(config.get("ignoreSurroundingSpaces").equals("true")); } if (config.containsKey("ignoreEmptyLines")) { format = format.withIgnoreEmptyLines(config.get("ignoreEmptyLines").equals("true")); } if (config.containsKey("recordSeparator")) { format = format.withRecordSeparator(config.get("recordSeparator")); } if (config.containsKey("nullString")) { format = format.withNullString(config.get("nullString")); } if (config.containsKey("trim")) { format = format.withTrim(config.get("trim").equals("true")); } if (config.containsKey("trailingDelimiter")) { format = format.withTrailingDelimiter(config.get("trailingDelimiter").equals("true")); } this.format = format .withAllowMissingColumnNames() .withHeader(); }
Source:
<code>public synchronized void stop() { if (driver != null) { driver.stop(); <START> } <END> }</code><technical_language>please add a WARN log stating attempt stop driver null</technical_language>

Target:
public synchronized void stop() { if (driver != null) { driver.stop(); } else { LOGGER.warning("Unable to stop Mesos driver: driver is null."); } }
Source:
<code>void addVolume(FsVolumeReference ref) { FsVolumeImpl volume = (FsVolumeImpl) ref.getVolume(); volumes.add(volume); <START> if (enableSameDiskTiering && <END> (volume.getStorageType() == StorageType.DISK || volume.getStorageType() == StorageType.ARCHIVE)) { mountVolumeMap.addVolume(volume); } if (blockScanner != null) { blockScanner.addVolumeScanner(ref); } else { IOUtils.cleanup(null, ref); } removeVolumeFailureInfo(volume.getStorageLocation()); FsDatasetImpl.LOG.info("Added new volume: " + volume.getStorageID()); }</code><technical_language>consider putting this check a method</technical_language>

Target:
void addVolume(FsVolumeReference ref) { FsVolumeImpl volume = (FsVolumeImpl) ref.getVolume(); volumes.add(volume); if (isSameDiskTieringApplied(volume)) { mountVolumeMap.addVolume(volume); } if (blockScanner != null) { blockScanner.addVolumeScanner(ref); } else { IOUtils.cleanup(null, ref); } removeVolumeFailureInfo(volume.getStorageLocation()); FsDatasetImpl.LOG.info("Added new volume: " + volume.getStorageID()); }
Source:
<code>public List<ChePlugin> execute() throws InfrastructureException { Span tracingSpan = tracer.buildSpan(SPAN_NAME).start(); TracingUtil.setWorkspaceId(tracingSpan, workspaceId); try { volumesStrategy.prepare( brokerEnvironment, workspaceId, startSynchronizer.getStartTimeoutMillis()); } catch (InfrastructureException e) { TracingUtil.setErrorStatus(tracingSpan, e); tracingSpan.finish(); throw e; } <START> tracingSpan.finish(); <END> return nextPhase.execute(); }</code><technical_language>finally here? if unchecked exception is thrown for some reason</technical_language>

Target:
public List<ChePlugin> execute() throws InfrastructureException { Span tracingSpan = tracer.buildSpan(PREPARE_STORAGE_PHASE).start(); TracingTags.WORKSPACE_ID.set(tracingSpan, workspaceId); try { volumesStrategy.prepare( brokerEnvironment, workspaceId, startSynchronizer.getStartTimeoutMillis()); } catch (InfrastructureException e) { TracingTags.setErrorStatus(tracingSpan, e); throw e; } finally { tracingSpan.finish(); } return nextPhase.execute(); }
Source:
<code>protected void generateComponent() { String normalizationProcessorId = addNormalizationProcessorBuilder(); String boltId = "normalizationBolt" + UUID_FOR_COMPONENTS; <START> String boltClassName = "com.hortonworks.iotas.streams.layout.component.impl.normalization.NormalizationBolt"; <END> List boltConstructorArgs = new ArrayList(); Map ref = getRefYaml(normalizationProcessorId); boltConstructorArgs.add(ref); component = createComponent(boltId, boltClassName, null, boltConstructorArgs, null); addParallelismToComponent(); }</code><technical_language>this "com.hortonworks.iotas.streams.runtime.storm.bolt.normalization.NormalizationBolt"</technical_language>

Target:
protected void generateComponent() { String normalizationProcessorId = addNormalizationProcessorBuilder(); String boltId = "normalizationBolt" + UUID_FOR_COMPONENTS; String boltClassName = "com.hortonworks.iotas.streams.runtime.storm.bolt.normalization.NormalizationBolt"; List boltConstructorArgs = new ArrayList(); Map ref = getRefYaml(normalizationProcessorId); boltConstructorArgs.add(ref); component = createComponent(boltId, boltClassName, null, boltConstructorArgs, null); addParallelismToComponent(); }
Source:
<code>private boolean transitionState(ExecutionState currentState, ExecutionState targetState, Throwable error) { if (currentState.isTerminal()) { throw new IllegalStateException("Cannot leave terminal state " + currentState + " to transition to " + targetState + '.'); } if (state == currentState) { state = targetState; markTimestamp(targetState); if (error == null) { LOG.info("{} ({}) switched from to {}.", getVertex().getTaskNameWithSubtaskIndex(), getAttemptId(), currentState, targetState); } else { if (LOG.isInfoEnabled()) { final String locationInformation = getAssignedResource() != null ? getAssignedResource().toString() : "not deployed"; LOG.info( "{} ({}) switched from to on {}.", getVertex().getTaskNameWithSubtaskIndex(), getAttemptId(), currentState, targetState, locationInformation, error); } } <START> getExecutionGraph().getExecutionStateUpdateListener().onStateUpdate(attemptId, state); <END> if (targetState.isTerminal()) { terminalStateFuture.complete(targetState); } try { vertex.notifyStateTransition(this, targetState, error); } catch (Throwable t) { LOG.error("Error while notifying execution graph of execution state transition.", t); } return true; } else { return false; } }</code><technical_language>I move this ExecutionGraph.notifyExecutionChange. react signals coming a valid Execution</technical_language>

Target:
private boolean transitionState(ExecutionState currentState, ExecutionState targetState, Throwable error) { if (currentState.isTerminal()) { throw new IllegalStateException("Cannot leave terminal state " + currentState + " to transition to " + targetState + '.'); } if (state == currentState) { state = targetState; markTimestamp(targetState); if (error == null) { LOG.info("{} ({}) switched from to {}.", getVertex().getTaskNameWithSubtaskIndex(), getAttemptId(), currentState, targetState); } else { if (LOG.isInfoEnabled()) { final String locationInformation = getAssignedResource() != null ? getAssignedResource().toString() : "not deployed"; LOG.info( "{} ({}) switched from to on {}.", getVertex().getTaskNameWithSubtaskIndex(), getAttemptId(), currentState, targetState, locationInformation, error); } } if (targetState.isTerminal()) { terminalStateFuture.complete(targetState); } try { vertex.notifyStateTransition(this, targetState, error); } catch (Throwable t) { LOG.error("Error while notifying execution graph of execution state transition.", t); } return true; } else { return false; } }
Source:
<code>Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } throw logger.logExceptionAsError( <START> new TextAnalyticsException("None key Phrases extracted.", <END> TextAnalyticsErrorCode.fromString("NoneKeyPhrasesExtracted").toString(), null)); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }</code><technical_language>Is this new introducing in this PR? if keyPhraseResultCollection is empty return client-side? do other languages do here</technical_language>

Target:
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
<code>private void registerGlueCodeScope(ConfigurableApplicationContext context) { do { <START> synchronized (context) { <END> context.getBeanFactory().registerScope(SCOPE_CUCUMBER_GLUE, new GlueCodeScope()); context = (ConfigurableApplicationContext) context.getParent(); } } while (context != null); }</code><technical_language>I this works. swapping out context a instance. a constant a monitor</technical_language>

Target:
private void registerGlueCodeScope(ConfigurableApplicationContext context) { do { context.getBeanFactory().registerScope(SCOPE_CUCUMBER_GLUE, new GlueCodeScope()); context = (ConfigurableApplicationContext) context.getParent(); } while (context != null); }
Source:
<code>public CallStatus run() { <START> RequestMetrics.Context context = metrics.startLockRequest(getLockCommandName(), domain); <END> LOGGER.debug("run: domain={}, resource={}, caller={}", domain, resource, caller); Error.reset(); Error.push("rest"); Error.push(getClass().getSimpleName()); Error.push(resource); try { Locking locking = RestConfiguration.getFactory().getLocking(domain); JsonNode result = runLockCommand(locking); ObjectNode o = NODE_FACTORY.objectNode(); o.set("result", result); return new CallStatus(new SimpleJsonObject(o)); } catch (Error e) { context.markRequestException(e); LOGGER.error("failure: {}", e); return new CallStatus(e); } catch (Exception e) { context.markRequestException(e); LOGGER.error("failure: {}", e); return new CallStatus(Error.get(RestCrudConstants.ERR_REST_ERROR, e.toString())); } finally { context.endRequestMonitoring(); } }</code><technical_language>this done HTTP layer? I understand if locking is special, wondering</technical_language>

Target:
public CallStatus run() { RequestMetrics.Context metricCtx = metrics.startLockRequest(getLockCommandName(), domain); LOGGER.debug("run: domain={}, resource={}, caller={}", domain, resource, caller); Error.reset(); Error.push("rest"); Error.push(getClass().getSimpleName()); Error.push(resource); try { Locking locking = RestConfiguration.getFactory().getLocking(domain); JsonNode result = runLockCommand(locking); ObjectNode o = NODE_FACTORY.objectNode(); o.set("result", result); return new CallStatus(new SimpleJsonObject(o)); } catch (Error e) { metricCtx.markRequestException(e); LOGGER.error("failure: {}", e); return new CallStatus(e); } catch (Exception e) { Error error = Error.get(RestCrudConstants.ERR_REST_ERROR, e.toString()); metricCtx.markRequestException(error); LOGGER.error("failure: {}", e); return new CallStatus(error); } finally { metricCtx.endRequestMonitoring(); } }
Source:
<code>public static <T extends AbstractModelObject> List<ObjectComponentDescriptor<T>> for_(T item) { <START> return Jenkins.get().getExtensionList(ObjectComponent.class).stream() <END> .filter(component -> component.isApplicable(item.getClass())) .map(component -> ((ObjectComponent<T>) component)) .filter(component -> component.isApplicable(item)) .map(ObjectComponent::getDescriptor) .collect(Collectors.toList()); }</code><technical_language>this previous method avoid duplication</technical_language>

Target:
public static <T extends AbstractModelObject> List<ObjectComponentDescriptor<T>> for_(T item) { return allInstances(item).stream() .map(ObjectComponent::getDescriptor) .collect(Collectors.toList()); }
Source:
<code>public void biteEntity(int entityId) { Entity e = player.getEntityWorld().getEntityByID(entityId); if (player.isSpectator()) { VampirismMod.log.w(TAG, "Player can't bite in spectator mode"); return; } if (e != null && e instanceof EntityLivingBase) { if (e.getDistance(player) <= player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue() + 1) { if (determineBiteType(((EntityLivingBase) e)) == BITE_TYPE.ATTACK) { biteEntity(((EntityLivingBase) e)); } else { victim = e.getEntityId(); <START> PotionEffect effect = new PotionEffect(Potion.getPotionFromResourceLocation("slowness"), 20, 7); <END> ((EntityLivingBase) e).addPotionEffect(effect); PotionEffect feedingEffect = new PotionEffect(PotionFeeding.POTION, 25); player.addPotionEffect(feedingEffect); } } else { VampirismMod.log.w(TAG, "Entity sent by client is not in reach " + entityId); } } }</code><technical_language>a custom potion effect too, this if a player is bitten render screen red</technical_language>

Target:
public void biteEntity(int entityId) { Entity e = player.getEntityWorld().getEntityByID(entityId); if (player.isSpectator()) { VampirismMod.log.w(TAG, "Player can't bite in spectator mode"); return; } if (e != null && e instanceof EntityLivingBase) { if (e.getDistance(player) <= player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue() + 1) { feed_victim_bite_type = determineBiteType((EntityLivingBase) e); if (feed_victim_bite_type == BITE_TYPE.ATTACK || feed_victim_bite_type == BITE_TYPE.ATTACK_HUNTER) { biteAttack((EntityLivingBase) e, feed_victim_bite_type == BITE_TYPE.ATTACK_HUNTER); } else if (feed_victim_bite_type == BITE_TYPE.NONE) { return; } else { if (feed_victim == -1) feedBiteTickCounter = 0; feed_victim = e.getEntityId(); PotionEffect effect = new PotionEffect(Potion.getPotionById(2), 20, 7, false, false); ((EntityLivingBase) e).addPotionEffect(effect); PotionEffect feedingEffect = new PotionEffect(Potion.getPotionById(2), 25, 1, false, false); player.addPotionEffect(feedingEffect); NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger(KEY_VICTIM_ID, feed_victim); sync(nbt, true); } } else { VampirismMod.log.w(TAG, "Entity sent by client is not in reach " + entityId); } } }
Source:
<code>public void shouldSaveEncounterTypeWhenEncounterTypesAreNotLocked() throws Exception { EncounterService es = Context.getEncounterService(); EncounterTypeFormController controller = (EncounterTypeFormController) applicationContext .getBean("encounterTypeForm"); controller.setApplicationContext(applicationContext); controller.setSuccessView("index.htm"); controller.setFormView("EncounterType.form"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/encounters/encounterType.form?encounterTypeId=1"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); request.setMethod("POST"); request.addParameter("action", "Save EncounterType"); ModelAndView mav = controller.handleRequest(request, response); <START> Assert.assertNotSame("The save attempt should have passed!", "index.htm", mav.getViewName()); <END> Assert.assertNotNull(es.getEncounterType(1)); }</code><technical_language>This is wrong, index.htm is success view defined above, same, i prefer assertEquals instead of assertSame checks object equality equals method</technical_language>

Target:
public void shouldSaveEncounterTypeWhenEncounterTypesAreNotLocked() throws Exception { EncounterService es = Context.getEncounterService(); EncounterTypeFormController controller = (EncounterTypeFormController) applicationContext .getBean("encounterTypeForm"); controller.setApplicationContext(applicationContext); controller.setSuccessView("index.htm"); controller.setFormView("EncounterType.form"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/encounters/encounterType.form?encounterTypeId=1"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); request.setMethod("POST"); request.addParameter("action", "Save EncounterType"); ModelAndView mav = controller.handleRequest(request, response); Assert.assertSame(controller.getFormView(), mav.getViewName()); Assert.assertNotEquals("The save attempt should have passed!", "index.htm", mav.getViewName()); Assert.assertNotNull(es.getEncounterType(1)); }
Source:
<code>public FormulaDto update(final FormulaDto formulaDto) { final Formula formula = this.daoFactory.getFormulaDAO().getById(formulaDto.getFormulaId()); <START> formula.setInputs(FormulaUtils.convertFormulaVariableListToCVTermList(formulaDto.getInputs())); <END> formula.setDefinition(formulaDto.getDefinition()); this.daoFactory.getFormulaDAO().update(formula); return FormulaUtils.convertToFormulaDto(formula); }</code><technical_language>convertToFormula here</technical_language>

Target:
public FormulaDto update(final FormulaDto formulaDto) { final Formula formula = FormulaUtils.convertToFormula(formulaDto); this.daoFactory.getFormulaDAO().merge(formula); return formulaDto; }
Source:
<code>public DocumentWriteOperation makeDocumentWriteOperation(UriMaker uriMaker, long count, T handle) { if (handle == null) { throw new IllegalArgumentException("Handle cannot be null"); } <START> String uri = uriMaker.makeUri((int) count, (JSONWriteHandle) handle); <END> return new DocumentWriteOperationImpl( DocumentWriteOperation.OperationType.DOCUMENT_WRITE, uri, null, handle ); }</code><technical_language>count a consistent data type in signatures. way, strong typing in compiler eliminate possibility of a runtime error cast. design long throughout. Apologies for design error</technical_language>

Target:
public DocumentWriteOperation makeDocumentWriteOperation(UriMaker uriMaker, long count, T handle) { if (handle == null) { throw new IllegalArgumentException("Handle cannot be null"); } String uri = uriMaker.makeUri(count, (JSONWriteHandle) handle); return new DocumentWriteOperationImpl( DocumentWriteOperation.OperationType.DOCUMENT_WRITE, uri, null, handle ); }
Source:
<code>private Object readResolve() { <START> if (isLeapDay() || isYearDay()) { <END> return InternationalFixedDate.of(prolepticYear, isLeapDay(), isYearDay()); } return InternationalFixedDate.of(prolepticYear, getMonth(), getDayOfMonth()); }</code><technical_language>I recommend ducting create(...), more optional</technical_language>

Target:
private Object readResolve() { return InternationalFixedDate.of(this.prolepticYear, this.month, this.day); }
Source:
<code>public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { List<String> pshell = (List<String>) attribute.getValue(); if (pshell != null){ for(String shell : pshell){ if(shell != null){ if(shell.isEmpty()){ <START> throw new WrongAttributeValueException("shell cannot be empty"); <END> }else{ sess.getPerunBl().getModulesUtilsBl().checkFormatOfShell(shell, attribute); } }else{ throw new WrongAttributeValueException("shell cannot be null"); } } } }</code><technical_language>good practice provide inforamtion possible. Please, constructor of WrongAttributeValueException additional parameters Attribute AttributeHolder</technical_language>

Target:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { List<String> pshell = (List<String>) attribute.getValue(); if (pshell != null){ for(String shell : pshell){ if(shell != null){ if(shell.isEmpty()){ throw new WrongAttributeValueException("shell cannot be empty"); }else{ sess.getPerunBl().getModulesUtilsBl().checkFormatOfShell(shell, attribute); } }else{ throw new WrongAttributeValueException(attribute, user, "shell cannot be empty"); } } } }
Source:
<code>public static void setVisibility (boolean visible, Context context) { PreferenceUtils.setValue(context, PreferenceUtils.KEY_SETTING_VISIBILITY, String.valueOf(visible ? 0 : 1)); try { MainApplication.visible = visible; ServerAPI.setVisibility(context, visible); if (visible == false) { LocationService.stop(context); } else { LocationService.start(context); } } catch (Exception ex) { <START> ex.printStackTrace(); <END> } }</code><technical_language>I improve exception handling</technical_language>

Target:
public static void setVisibility (boolean visible, Context context) { PreferenceUtils.setValue(context, PreferenceUtils.KEY_SETTING_VISIBILITY, String.valueOf(visible ? 0 : 1)); try { MainApplication.visible = visible; ServerAPI.setVisibility(context, visible); if (visible == false) { LocationService.stop(context); } else { LocationService.start(context); } } catch (Exception ex) { Log.e(TAG, "Could not set visibility:" + ex.getMessage()); } }
Source:
<code>public void testCreateSuccess() { AccountService accountService = Mockito.mock(AccountService.class); Account account = Mockito.mock(Account.class); Mockito.when(accountService.getAccount(anyLong())).thenReturn(account); VolumeApiService volumeApiService = Mockito.mock(VolumeApiService.class); Snapshot snapshot = Mockito.mock(Snapshot.class); try { Mockito.when(volumeApiService.takeSnapshot(anyLong(), anyLong(), anyLong(), any(Account.class), anyBoolean(), isNull(Snapshot.LocationType.class))).thenReturn(snapshot); } catch (Exception e) { Assert.fail("Received exception when success expected " + e.getMessage()); } responseGenerator = Mockito.mock(ResponseGenerator.class); SnapshotResponse snapshotResponse = Mockito.mock(SnapshotResponse.class); Mockito.when(responseGenerator.createSnapshotResponse(snapshot)).thenReturn(snapshotResponse); Mockito.doNothing().when(snapshotResponse).setAccountName(anyString()); createSnapshotCmd._accountService = accountService; createSnapshotCmd._responseGenerator = responseGenerator; createSnapshotCmd._volumeService = volumeApiService; <START> createSnapshotCmd.execute(); <END> }</code><technical_language>assertions in this test method? validate response returned createSnapshotCmd.execute()</technical_language>

Target:
public void testCreateSuccess() { AccountService accountService = Mockito.mock(AccountService.class); Account account = Mockito.mock(Account.class); Mockito.when(accountService.getAccount(anyLong())).thenReturn(account); VolumeApiService volumeApiService = Mockito.mock(VolumeApiService.class); Snapshot snapshot = Mockito.mock(Snapshot.class); try { Mockito.when(volumeApiService.takeSnapshot(anyLong(), anyLong(), anyLong(), any(Account.class), anyBoolean(), isNull(Snapshot.LocationType.class))).thenReturn(snapshot); } catch (Exception e) { Assert.fail("Received exception when success expected " + e.getMessage()); } responseGenerator = Mockito.mock(ResponseGenerator.class); SnapshotResponse snapshotResponse = Mockito.mock(SnapshotResponse.class); Mockito.when(responseGenerator.createSnapshotResponse(snapshot)).thenReturn(snapshotResponse); Mockito.doNothing().when(snapshotResponse).setAccountName(anyString()); createSnapshotCmd._accountService = accountService; createSnapshotCmd._responseGenerator = responseGenerator; createSnapshotCmd._volumeService = volumeApiService; try { createSnapshotCmd.execute(); } catch (Exception e) { Assert.fail("Received exception when success expected " + e.getMessage()); } }
Source:
<code>public IDEWorkflow(@Named(CTX_SERVERS) List<IServerDescriptor> endpoints, ILogEventsQueue queue, ISystemSettings settings, IEventBroker broker, MylynNotificationsSupport notificationSupport, UploadReportsScheduler uploadService, IEclipseContext context, @Named(IDEWorkflow.CTX_REPORT_PROCESSORS) List<IProcessorDescriptor> descriptors) { this.servers = endpoints; this.queue = queue; this.system = settings; this.broker = broker; this.notificationSupport = notificationSupport; this.uploadService = uploadService; this.context = context; <START> this.descriptors = descriptors; <END> }</code><technical_language>please fields final, if possible</technical_language>

Target:
public IDEWorkflow(@Named(CTX_SERVERS) List<IServerDescriptor> endpoints, ILogEventsQueue queue, ISystemSettings settings, IEventBroker broker, MylynNotificationsSupport notificationSupport, UploadReportsScheduler uploadService, IEclipseContext context, @Named(IDEWorkflow.CTX_REPORT_PROCESSORS) List<IProcessorDescriptor> descriptors) { this.servers = endpoints; this.queue = queue; this.settings = settings; this.broker = broker; this.notificationSupport = notificationSupport; this.uploadService = uploadService; this.context = context; this.descriptors = descriptors; }
Source:
<code>private void copyFiles(File src, File dest) throws IOException { <START> FileOutputStream fos; <END> try (FileInputStream fis = new FileInputStream(src)) { fos = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } fos.close(); }</code><technical_language>fos try ()</technical_language>

Target:
private void copyFiles(File src, File dest) throws IOException { try (FileOutputStream fos = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src)) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } }