auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void performGo(boolean inNewTab) { String memorySpace = null; if (fGotoMemorySpaceControl.isVisible()) { memorySpace = fGotoMemorySpaceControl.getText(); if (memorySpace.equals(NA_MEMORY_SPACE_ID)) { memorySpace = null; } assert (memorySpace == null) || (memorySpace.length() > 0); } String expression = fGotoAddressBar.getExpressionText(); if (expression.length() > 0) { final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; Object context = null; if (activeFolder != null) { context = activeFolder.getData(KEY_CONTEXT); } fGotoAddressBar.addExpressionToHistory(context, expression, memorySpace); try { performGo(inNewTab, expression, memorySpace); } catch (DebugException e) { <START> } <END> } }</code><technical_language>swallow exceptions please</technical_language>

Target:
private void performGo(boolean inNewTab) { String memorySpace = null; if (fGotoMemorySpaceControl.isVisible()) { memorySpace = fGotoMemorySpaceControl.getText(); if (memorySpace.equals(NA_MEMORY_SPACE_ID)) { memorySpace = null; } assert (memorySpace == null) || (memorySpace.length() > 0); } String expression = fGotoAddressBar.getExpressionText(); if (expression.length() > 0) { final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; Object context = null; if (activeFolder != null) { context = activeFolder.getData(KEY_CONTEXT); } fGotoAddressBar.addExpressionToHistory(context, expression, memorySpace); performGo(inNewTab, expression, memorySpace); } }
Source:
<code><START> protected void doc(Class c) throws IOException { <END> open("tr class='TableRowColor'"); open("td"); around("span class='modifiers'",getModifiers(c)); close("td"); open("td"); link(c.getType()); tag("br"); around("span class='doc'", getDoc(c)); close("td"); close("tr"); }</code><technical_language>Indentation crazy! thinking this some mismatch (between IDE github) in number of spaces a tab is worth</technical_language>

Target:
private void doc(Class c) throws IOException { open("tr class='TableRowColor'"); open("td"); around("span class='modifiers'", getModifiers(c)); close("td"); open("td"); link(c.getType()); tag("br"); around("span class='doc'", getDoc(c)); close("td"); close("tr"); }
Source:
<code>private String[] getStringValuesFromDatabase(String sqlStmt, Object... params) throws UserStoreException { if(log.isDebugEnabled()) { <START> log.debug("Execuring Query: " + sqlStmt); <END> for (int i = 0; i < params.length; i++) { Object param = params[i]; log.debug("Input value: " + param); } } String[] values = new String[0]; Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { dbConnection = getDBConnection(); values = DatabaseUtil.getStringValuesFromDatabase(dbConnection, sqlStmt, params); } catch (SQLException e) { String errorMessage = "Error Occurred Using sql :"+sqlStmt; if(log.isDebugEnabled()){ log.debug(errorMessage,e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } return values; }</code><technical_language>Typo, Executing</technical_language>

Target:
private String[] getStringValuesFromDatabase(String sqlStmt, Object... params) throws UserStoreException { if(log.isDebugEnabled()) { log.debug("Executing Query: " + sqlStmt); for (int i = 0; i < params.length; i++) { Object param = params[i]; log.debug("Input value: " + param); } } String[] values = new String[0]; Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { dbConnection = getDBConnection(); values = DatabaseUtil.getStringValuesFromDatabase(dbConnection, sqlStmt, params); } catch (SQLException e) { String errorMessage = "Error Occurred while get String values from database : " + sqlStmt; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } return values; }
Source:
<code>protected void doWork(IProgressMonitor monitor) throws Exception { Branch branch = BranchManager.getBranch(this.branch); BranchState originalState = branch.getBranchState(); BranchArchivedState originalArchivedState = branch.getArchiveState(); ArtifactCache.deCache(this.branch); try { branch.setBranchState(BranchState.DELETE_IN_PROGRESS); branch.setArchived(true); OseeEventManager.kickBranchEvent(this, new BranchEvent(BranchEventType.Deleting, branch.getGuid())); BranchManager.persist(branch); branch.setBranchState(BranchState.DELETED); OseeEventManager.kickBranchEvent(this, new BranchEvent(BranchEventType.Deleted, branch.getGuid())); BranchManager.persist(branch); <START> } catch (Exception ex) { <END> branch.setBranchState(originalState); branch.setArchived(originalArchivedState.isArchived()); OseeEventManager.kickBranchEvent(this, new BranchEvent(BranchEventType.StateUpdated, branch.getGuid())); BranchManager.persist(branch); throw ex; } }</code><technical_language>need store original exceptions guard calls a try{ }catch block prevent masking original exception</technical_language>

Target:
protected void doWork(IProgressMonitor monitor) throws Exception { Branch branch = BranchManager.getBranch(this.branch); BranchState originalState = branch.getBranchState(); BranchArchivedState originalArchivedState = branch.getArchiveState(); ArtifactCache.deCache(this.branch); try { branch.setBranchState(BranchState.DELETE_IN_PROGRESS); branch.setArchived(true); OseeEventManager.kickBranchEvent(this, new BranchEvent(BranchEventType.Deleting, branch.getGuid())); BranchManager.persist(branch); branch.setBranchState(BranchState.DELETED); OseeEventManager.kickBranchEvent(this, new BranchEvent(BranchEventType.Deleted, branch.getGuid())); BranchManager.persist(branch); } catch (Exception ex) { try { branch.setBranchState(originalState); branch.setArchived(originalArchivedState.isArchived()); OseeEventManager.kickBranchEvent(this, new BranchEvent(BranchEventType.StateUpdated, branch.getGuid())); BranchManager.persist(branch); } catch (Exception ex2) { log(ex2); } throw ex; } }
Source:
<code>public void testContinueInitializationOnError() throws Exception { testAcceptorApplication = new TestAcceptorApplication(3); int freePort1 = AvailablePortFinder.getNextAvailable(); int freePort2 = AvailablePortFinder.getNextAvailable(); int freePort3 = AvailablePortFinder.getNextAvailable(); Acceptor acceptor = createAcceptor(freePort1, freePort2, freePort3, true); acceptor.start(); List<SessionID> acceptorSessions = acceptor.getSessions(); assertEquals(2, acceptorSessions.size()); SessionID session1 = new SessionID(FixVersions.BEGINSTRING_FIX42, "ACCEPTOR-" + 1, "INITIATOR"); SessionID session3 = new SessionID(FixVersions.BEGINSTRING_FIX42, "ACCEPTOR-" + 3, "INITIATOR"); <START> assertTrue(acceptorSessions.contains(session1)); <END> assertTrue(acceptorSessions.contains(session3)); acceptor.stop(true); }</code><technical_language>assertFalse(acceptorSessions.contains(session2)); good</technical_language>

Target:
public void testContinueInitializationOnError() throws Exception { testAcceptorApplication = new TestAcceptorApplication(3); int freePort1 = AvailablePortFinder.getNextAvailable(); int freePort2 = AvailablePortFinder.getNextAvailable(); int freePort3 = AvailablePortFinder.getNextAvailable(); Acceptor acceptor = createAcceptor(freePort1, freePort2, freePort3, true); acceptor.start(); List<SessionID> acceptorSessions = acceptor.getSessions(); assertEquals(2, acceptorSessions.size()); SessionID session1 = new SessionID(FixVersions.BEGINSTRING_FIX42, "ACCEPTOR-" + 1, "INITIATOR"); SessionID session2 = new SessionID(FixVersions.BEGINSTRING_FIX42, "ACCEPTOR-" + 2, "INITIATOR"); SessionID session3 = new SessionID(FixVersions.BEGINSTRING_FIX42, "ACCEPTOR-" + 3, "INITIATOR"); assertTrue(acceptorSessions.contains(session1)); assertFalse(acceptorSessions.contains(session2)); assertTrue(acceptorSessions.contains(session3)); acceptor.stop(true); }
Source:
<code>public static void sendPlainText(final String content, final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { <START> final String enc = Constants.CHARACTER_ENCODING; <END> final byte[] raw = content.getBytes(enc); rsp.setContentType("text/plain"); rsp.setCharacterEncoding(enc); send(raw, req, rsp); }</code><technical_language>in-line 'enc'</technical_language>

Target:
public static void sendPlainText(final String content, final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final byte[] raw = content.getBytes(Constants.CHARACTER_ENCODING); rsp.setContentType(TEXT_PLAIN); rsp.setCharacterEncoding(Constants.CHARACTER_ENCODING); send(raw, req, rsp); }
Source:
<code>public void testRetriesWhenRetryableError() { <START> String nonRetryable = "{\"error\":{\"code\":\"RetryableError\",\"message\":\"Resource busy\"}}"; <END> HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http://localhost").build()); HttpResponse response = HttpResponse.builder().statusCode(429).payload(nonRetryable).build(); assertTrue(handler.shouldRetryRequest(command, response)); }</code><technical_language>this retryable</technical_language>

Target:
public void testRetriesWhenRetryableError() { String retryable = "{\"error\":{\"code\":\"RetryableError\",\"message\":\"Resource busy\"}}"; HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http://localhost").build()); HttpResponse response = HttpResponse.builder().statusCode(429).payload(retryable).build(); assertTrue(handler.shouldRetryRequest(command, response)); }
Source:
<code>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getDateHeader("If-Modified-Since") > startupTime) { resp.setStatus(304); return; } String category = getCategory(req); Format format = getFormat(req); String state = getState(req); String iconSetId = getIconSetId(req); IconProvider topProvider = null; int maxPrio = Integer.MIN_VALUE; for (IconProvider provider : iconProvider) { Integer prio = provider.hasIcon(category, iconSetId, format); if (prio != null && prio > maxPrio) { maxPrio = prio; topProvider = provider; } } if (topProvider == null) { logger.debug( "Requested icon category provided by no icon provider; try to failback to category \"none\"", category); category = "none"; <START> for (IconProvider provider : iconProvider) { <END> Integer prio = provider.hasIcon(category, iconSetId, format); if (prio != null && prio > maxPrio) { maxPrio = prio; topProvider = provider; } } } if (topProvider != null) { if (format.equals(Format.SVG)) { resp.setContentType("image/svg+xml"); } else { resp.setContentType("image/png"); } resp.setDateHeader("Last-Modified", new Date().getTime()); ServletOutputStream os = resp.getOutputStream(); try (InputStream is = topProvider.getIcon(category, iconSetId, state, format)) { IOUtils.copy(is, os); resp.flushBuffer(); } catch (IOException e) { logger.error("Failed sending the icon byte stream as a response: {}", e.getMessage()); resp.sendError(500, e.getMessage()); } } else { resp.sendError(404); } }</code><technical_language>duplicating logic - cleaner extract a method, wdyt</technical_language>

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getDateHeader("If-Modified-Since") > startupTime) { resp.setStatus(304); return; } String category = getCategory(req); Format format = getFormat(req); String state = getState(req); String iconSetId = getIconSetId(req); IconProvider topProvider = getIconProvider(category, iconSetId, format); if (topProvider == null) { logger.debug( "Requested icon category provided by no icon provider; try to failback to category \"none\"", category); category = "none"; topProvider = getIconProvider(category, iconSetId, format); } if (topProvider != null) { if (format.equals(Format.SVG)) { resp.setContentType("image/svg+xml"); } else { resp.setContentType("image/png"); } resp.setDateHeader("Last-Modified", new Date().getTime()); ServletOutputStream os = resp.getOutputStream(); try (InputStream is = topProvider.getIcon(category, iconSetId, state, format)) { IOUtils.copy(is, os); resp.flushBuffer(); } catch (IOException e) { logger.error("Failed sending the icon byte stream as a response: {}", e.getMessage()); resp.sendError(500, e.getMessage()); } } else { resp.sendError(404); } }
Source:
<code>private void addComponent(Map<String, String> flatConfigurations, Service service, String componentName, List<String> hosts) { Component component = environmentService.initializeComponent(service, componentName); List<ComponentProcess> componentProcesses = hosts.stream().map(host -> { ComponentProcess cp = new ComponentProcess(); cp.setHost(host); return cp; }).collect(toList()); <START> environmentService.injectProtocolAndPortToComponent(flatConfigurations, component, componentProcesses); <END> if (componentName.equals(ServiceConfigurations.KAFKA.name())) { final String brokerSecurityProtocol = flatConfigurations.get(KafkaServiceRegistrar.PARAM_SECURITY_INTER_BROKER_PROTOCOL); for (ComponentProcess componentProcess : componentProcesses) { KafkaBrokerListeners.Protocol protocol = KafkaBrokerListeners.Protocol.SASL_PLAINTEXT.hasAlias(brokerSecurityProtocol) ? KafkaBrokerListeners.Protocol.SASL_PLAINTEXT : KafkaBrokerListeners.Protocol.find(componentProcess.getProtocol()); componentProcess.setProtocol(protocol.name()); } } final Component storedComponent = environmentService.addComponent(component); componentProcesses.forEach(cp -> { cp.setComponentId(storedComponent.getId()); environmentService.addComponentProcess(cp); }); }</code><technical_language>I put of this in private method, call **setKafkaProtocol** some name</technical_language>

Target:
private void addComponent(Map<String, String> flatConfigurations, Service service, String componentName, List<String> hosts) { Component component = environmentService.createComponent(service, componentName); List<ComponentProcess> componentProcesses = hosts.stream().map(host -> { ComponentProcess cp = new ComponentProcess(); cp.setHost(host); return cp; }).collect(toList()); environmentService.injectProtocolAndPortToComponent(flatConfigurations, component, componentProcesses); if (componentName.equals(ServiceConfigurations.KAFKA.name())) { setKafkaProtocol(flatConfigurations, componentProcesses); } final Component storedComponent = environmentService.addComponent(component); componentProcesses.forEach(cp -> { cp.setComponentId(storedComponent.getId()); environmentService.addComponentProcess(cp); }); }
Source:
<code>public void install() { final VDS host = getSelectedItem(); InstallModel model = new InstallModel(); model.setVds(host); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().installHostTitle()); model.setHelpTag(HelpTag.install_host); model.setHashName("install_host"); model.getOVirtISO().setIsAvailable(false); model.getOverrideIpTables().setIsAvailable(false); model.getHostVersion().setEntity(host.getHostOs()); model.getHostVersion().setIsAvailable(false); getWindow().startProgress(); model.getUserPassword().setIsAvailable(true); model.getUserPassword().setIsChangeable(true); model.getOverrideIpTables().setIsAvailable(true); model.getOverrideIpTables().setEntity(true); model.getActivateHostAfterInstall().setEntity(true); <START> model.getReconfigureGluster().setIsAvailable(true); <END> model.getReconfigureGluster().setEntity(true); addInstallCommands(model, host, false); getWindow().stopProgress(); }</code><technical_language>restrict appearance for gluster clusters</technical_language>

Target:
public void install() { final VDS host = getSelectedItem(); InstallModel model = new InstallModel(); model.setVds(host); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().installHostTitle()); model.setHelpTag(HelpTag.install_host); model.setHashName("install_host"); model.getOVirtISO().setIsAvailable(false); model.getOverrideIpTables().setIsAvailable(false); model.getHostVersion().setEntity(host.getHostOs()); model.getHostVersion().setIsAvailable(false); getWindow().startProgress(); model.getUserPassword().setIsAvailable(true); model.getUserPassword().setIsChangeable(true); model.getOverrideIpTables().setIsAvailable(true); model.getOverrideIpTables().setEntity(true); model.getActivateHostAfterInstall().setEntity(true); if(host.getClusterSupportsGlusterService()) { model.getReconfigureGluster().setIsAvailable(true); } else { model.getReconfigureGluster().setIsAvailable(false); } model.getReconfigureGluster().setEntity(model.getReconfigureGluster().getEntity()); addInstallCommands(model, host, false); getWindow().stopProgress(); }
Source:
<code><START> protected void setActionMessageParameters() { <END> addCanDoActionMessage(VdcBllMessages.VAR__ACTION__PAUSE); }</code><technical_language>call super.setActionMessageParameters();</technical_language>

Target:
protected void setActionMessageParameters() { super.setActionMessageParameters(); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__PAUSE); }
Source:
<code>public boolean start() { String oldVersion = manager.getVersion(extractionNamespace.getNamespace()); if (manager.scheduleOrUpdateIndividual(extractionNamespace)) { String newVersion = manager.getVersion(extractionNamespace.getNamespace()); while(newVersion == null || newVersion.equals(oldVersion)) { try { Thread.sleep(10); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } newVersion = manager.getVersion(extractionNamespace.getNamespace()); } } return true; }</code><technical_language>log interrupted (probably error) return false</technical_language>

Target:
public boolean start() { final Lock writeLock = startStopSync.writeLock(); writeLock.lock(); try { if (!started.compareAndSet(false, true)) { LOG.warn("Already started!"); return false; } if (!manager.scheduleAndWait(extractorID, extractionNamespace, SCHEDULE_TIMEOUT)) { LOG.warn("Failed to schedule lookup [%s]", extractorID); return false; } LOG.debug("NamespaceLookupExtractorFactory[%s] started", extractorID); return true; } finally { writeLock.unlock(); } }
Source:
<code>public Builder withGoogleId(String googleId) { <START> profileAttributes.googleId = googleId; <END> return this; }</code><technical_language>I aware this handled before, chance passed in parameter null lead unexpected behavior? (applies other fields well)</technical_language>

Target:
public Builder withGoogleId(String googleId) { if (googleId != null) { profileAttributes.googleId = googleId; } return this; }
Source:
<code>public void start() { startStopLock.writeLock().lock(); try { if (!started) { LOG.info("LookupReferencesManager is starting."); if (lookupSnapshotTaker != null) { final List<LookupBean> lookupBeanList = lookupSnapshotTaker.pullExistingSnapshot(); for (LookupBean lookupBean : lookupBeanList) { LookupExtractorFactoryContainer container = lookupBean.getContainer(); if (container.getLookupExtractorFactory().start()) { lookupMap.put(lookupBean.getName(), container); } else { throw new ISE("Failed to start lookup [%s]:[%s]", lookupBean.getName(), container); } } } if (exec == null && !testMode) { exec = Execs.singleThreaded("lookup-reference-manager-%d"); exec.execute( new Runnable() { @Override public void run() { try { while (started && !Thread.currentThread().isInterrupted()) { try { queue.take().handle(); } catch (InterruptedException ex) { LOG.warn("interrupted, going down... lookups are not managed anymore"); Thread.currentThread().interrupt(); } catch (Exception ex) { LOG.makeAlert(ex, "Exception occured while lookup notice handling.").emit(); } catch (Throwable t) { LOG.makeAlert(t, "Fatal error occured while lookup notice handling.").emit(); throw t; } } } finally { <START> LOG.info("Lookup Mgmt loop exited, Lookup notices are not handled anymore."); <END> } } } ); } started = true; LOG.info("LookupReferencesManager is started."); } } finally { startStopLock.writeLock().unlock(); } }</code><technical_language>Spell out please</technical_language>

Target:
public void start() { if (!lifecycleLock.canStart()) { throw new ISE("can't start."); } try { LOG.info("LookupReferencesManager is starting."); loadSnapshotAndInitStateRef(); if (!testMode) { mainThread = Execs.makeThread( "LookupReferencesManager-MainThread", new Runnable() { @Override public void run() { try { if (!lifecycleLock.awaitStarted()) { LOG.error("WTF! lifecycle not started, lookup update notices will not be handled."); return; } while (!Thread.interrupted() && lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)) { try { handlePendingNotices(); LockSupport.parkNanos(LookupReferencesManager.this, TimeUnit.MINUTES.toNanos(1)); } catch (Throwable t) { LOG.makeAlert(t, "Error occured while lookup notice handling.").emit(); } } } catch (Throwable t) { LOG.error(t, "Error while waiting for lifecycle start. lookup updates notices will not be handled"); } finally { LOG.info("Lookup Management loop exited, Lookup notices are not handled anymore."); } } }, true ); mainThread.start(); } LOG.info("LookupReferencesManager is started."); lifecycleLock.started(); } finally { lifecycleLock.exitStart(); } }
Source:
<code>protected void configure() { super.configure(); <START> install(new GlacierParserModule()); <END> bind(RequestAuthorizeSignature.class).in(Scopes.SINGLETON); }</code><technical_language>Personally, I prefer separate modules. This module work parser one, prefer remove this line add GlacierParserModule list of default modules in ApiMetadata</technical_language>

Target:
protected void configure() { super.configure(); bind(RequestAuthorizeSignature.class).in(Scopes.SINGLETON); }
Source:
<code>public ManifestIdentifier identify(Config config) { FsFile manifestFile = getFsFileFromProperty("android_merged_manifest"); FsFile resourcesDir = getFsFileFromProperty("android_merged_resources"); FsFile assetsDir = getFsFileFromProperty("android_merged_assets"); <START> FsFile apkFile = getFsFileFromProperty("android_resources_apk"); <END> String packageName = properties.getProperty("android_custom_package"); String manifestConfig = config.manifest(); if (Config.NONE.equals(manifestConfig)) { Logger.info("@Config(manifest = Config.NONE) specified while using Build System API, ignoring"); } else if (!Config.DEFAULT_MANIFEST_NAME.equals(manifestConfig)) { manifestFile = resolveFile(manifestConfig); } if (!Config.DEFAULT_RES_FOLDER.equals(config.resourceDir())) { resourcesDir = resolveFile(config.resourceDir()); } if (!Config.DEFAULT_ASSET_FOLDER.equals(config.assetDir())) { assetsDir = resolveFile(config.assetDir()); } if (!Config.DEFAULT_PACKAGE_NAME.equals(config.packageName())) { packageName = config.packageName(); } List<ManifestIdentifier> libraryDirs = emptyList(); if (config.libraries().length > 0) { Logger.info("@Config(libraries) specified while using Build System API, ignoring"); } return new ManifestIdentifier(packageName, manifestFile, resourcesDir, assetsDir, libraryDirs, apkFile); }</code><technical_language>need update Bazel right</technical_language>

Target:
public ManifestIdentifier identify(Config config) { FsFile manifestFile = getFsFileFromProperty("android_merged_manifest"); FsFile resourcesDir = getFsFileFromProperty("android_merged_resources"); FsFile assetsDir = getFsFileFromProperty("android_merged_assets"); FsFile apkFile = getFsFileFromProperty("android_resource_apk"); String packageName = properties.getProperty("android_custom_package"); String manifestConfig = config.manifest(); if (Config.NONE.equals(manifestConfig)) { Logger.info("@Config(manifest = Config.NONE) specified while using Build System API, ignoring"); } else if (!Config.DEFAULT_MANIFEST_NAME.equals(manifestConfig)) { manifestFile = resolveFile(manifestConfig); } if (!Config.DEFAULT_RES_FOLDER.equals(config.resourceDir())) { resourcesDir = resolveFile(config.resourceDir()); } if (!Config.DEFAULT_ASSET_FOLDER.equals(config.assetDir())) { assetsDir = resolveFile(config.assetDir()); } if (!Config.DEFAULT_PACKAGE_NAME.equals(config.packageName())) { packageName = config.packageName(); } List<ManifestIdentifier> libraryDirs = emptyList(); if (config.libraries().length > 0) { Logger.info("@Config(libraries) specified while using Build System API, ignoring"); } return new ManifestIdentifier(packageName, manifestFile, resourcesDir, assetsDir, libraryDirs, apkFile); }
Source:
<code>public Void visit(GenContext state, Fn ast) { <START> return null; <END> }</code><technical_language>lambda body</technical_language>

Target:
public Void visit(GenContext state, Fn ast) { ast.getBody().acceptVisitor(this, state); return null; }
Source:
<code>public void tesDuplicatedReturnLogicalSlotFails() { CompletableFuture<PhysicalSlot> slotContextFuture = CompletableFuture .completedFuture(new TestingPhysicalSlot(RP, new AllocationID())); AtomicInteger released = new AtomicInteger(0); SharedSlot sharedSlot = SharedSlotBuilder .newBuilder() .withSlotContextFuture(slotContextFuture) <START> .withReleaseCallback(g -> released.incrementAndGet()) <END> .build(); LogicalSlot logicalSlot = sharedSlot.allocateLogicalSlot(EV1).join(); sharedSlot.returnLogicalSlot(logicalSlot); try { sharedSlot.returnLogicalSlot(logicalSlot); fail("Duplicated 'returnLogicalSlot' call should fail with IllegalStateException"); } catch (IllegalStateException e) { } }</code><technical_language>adding a case invoke SharedSlot#release() in release callback? This happen in production code path</technical_language>

Target:
public void tesDuplicatedReturnLogicalSlotFails() { CompletableFuture<PhysicalSlot> slotContextFuture = CompletableFuture .completedFuture(new TestingPhysicalSlot(RP, new AllocationID())); AtomicInteger released = new AtomicInteger(0); SharedSlot sharedSlot = SharedSlotBuilder .newBuilder() .withSlotContextFuture(slotContextFuture) .withExternalReleaseCallback(g -> released.incrementAndGet()) .build(); LogicalSlot logicalSlot = sharedSlot.allocateLogicalSlot(EV1).join(); sharedSlot.returnLogicalSlot(logicalSlot); try { sharedSlot.returnLogicalSlot(logicalSlot); fail("Duplicated 'returnLogicalSlot' call should fail with IllegalStateException"); } catch (IllegalStateException e) { } }
Source:
<code>public void setup() { retrieveDocumentSetRequestType = mock(RetrieveDocumentSetRequestType.class); retrieveDocumentSetResponseType = mock(RetrieveDocumentSetResponseType.class); webContextProp = mock(Properties.class); nhinTargetSystemType = mock(NhinTargetSystemType.class); <START> assertionType = mock(AssertionType.class); <END> }</code><technical_language>mock objects used</technical_language>

Target:
public void setup() { logger = mock(DocRetrieveAuditLogger.class); }
Source:
<code><START> @Override protected void setUp() throws Exception { <END> productFileLocation = TestData.getFile("ProductActionTest/productWithConfig", "sample.product").toString(); noLauncherFlag = new ProductFile(TestData.getFile("ProductActionTest/launcherFlags", "noLauncherFlag.product").toString()); falseLauncherFlag = new ProductFile(TestData.getFile("ProductActionTest/launcherFlags", "falseLauncherFlag.product").toString()); trueLauncherFlag = new ProductFile(TestData.getFile("ProductActionTest/launcherFlags", "trueLauncherFlag.product").toString()); productFile = new ProductFile(productFileLocation); uidProductFileLocation = TestData.getFile("ProductActionTest/productWithConfig", "uidproduct.product").toString(); uidProductFile = new ProductFile(uidProductFileLocation); rootFeaturesProduct = new ProductFile(TestData.getFile("ProductActionTest", "rootFeatures.product").toString()); }</code><technical_language>common Override line method. Please way</technical_language>

Target:
protected void setUp() throws Exception { productFileLocation = TestData.getFile("ProductActionTest/productWithConfig", "sample.product").toString(); noLauncherFlag = new ProductFile(TestData.getFile("ProductActionTest/launcherFlags", "noLauncherFlag.product").toString()); falseLauncherFlag = new ProductFile(TestData.getFile("ProductActionTest/launcherFlags", "falseLauncherFlag.product").toString()); trueLauncherFlag = new ProductFile(TestData.getFile("ProductActionTest/launcherFlags", "trueLauncherFlag.product").toString()); productFile = new ProductFile(productFileLocation); uidProductFileLocation = TestData.getFile("ProductActionTest/productWithConfig", "uidproduct.product").toString(); uidProductFile = new ProductFile(uidProductFileLocation); rootFeaturesProduct = new ProductFile(TestData.getFile("ProductActionTest", "rootFeatures.product").toString()); }
Source:
<code>protected void streamResponseToFile(HttpResponse response, String destination) { try { int status = checkResponseCode(response); org.apache.http.HttpEntity entity = response.getEntity(); InputStream responseStream = entity.getContent(); <START> FileOutputStream fos = new FileOutputStream(destination); <END> IOUtils.copy(responseStream, fos); if (status == 200) { logger.log(SystemProperties.DIAG, "File was retrieved and saved to disk.", destination); } else{ logger.log(SystemProperties.DIAG, "File was retrieved and saved to disk with errors.", destination); } } catch (Exception e) { logger.error("Error processing response", e); } }</code><technical_language>close output stream opening (using Java 7's [try-with-resources](<LINK_0> diff +try (FileOutputStream fos = new FileOutputStream(destination)) { + IOUtils.copy(responseStream, fos); +} -FileOutputStream fos = new FileOutputStream(destination); -IOUtils.copy(responseStream, fos);</technical_language>

Target:
protected void streamResponseToFile(HttpResponse response, String destination) { try(FileOutputStream fos = new FileOutputStream(destination)) { int status = checkResponseCode(response); org.apache.http.HttpEntity entity = response.getEntity(); InputStream responseStream = entity.getContent(); IOUtils.copy(responseStream, fos); if (status == 200) { logger.log(SystemProperties.DIAG, "File was retrieved and saved to disk.", destination); } else { logger.log(SystemProperties.DIAG, "File was retrieved and saved to disk with errors.", destination); } } catch (Exception e) { logger.error("Error processing response", e); } }
Source:
<code>public List<PerunPolicy> loadPerunPolicies() { List<PerunPolicy> policies = new ArrayList<>(); JsonNode rootNode = loadConfigurationFile(); JsonNode policiesNode = rootNode.get("perun_policies"); Iterator<String> policyNames = policiesNode.fieldNames(); while(policyNames.hasNext()) { String policyName = policyNames.next(); JsonNode policyNode = policiesNode.get(policyName); List<Map<String, String>> perunRoles = new ArrayList<>(); JsonNode perunRolesNode = policyNode.get("policy_roles"); for (JsonNode perunRoleNode : perunRolesNode) { Map<String, String> innerRoleMap = new HashMap<>(); Iterator<String> roleArrayKeys = perunRoleNode.fieldNames(); while (roleArrayKeys.hasNext()) { String role = roleArrayKeys.next(); JsonNode roleObjectNode = perunRoleNode.get(role); String object = roleObjectNode.isNull() ? null : roleObjectNode.textValue(); innerRoleMap.put(role, object); } perunRoles.add(innerRoleMap); } <START> List<String> includePolicies = new ArrayList<>(new ObjectMapper().convertValue(policyNode.get("include_policies"), new TypeReference<List<String>>() {})); <END> policies.add(new PerunPolicy(policyName, perunRoles, includePolicies)); } return policies; }</code><technical_language>@zlamalp mentioned, ObjectMapper reused a static member</technical_language>

Target:
public List<PerunPolicy> loadPerunPolicies() { List<PerunPolicy> policies = new ArrayList<>(); JsonNode rootNode = loadConfigurationFile(); JsonNode policiesNode = rootNode.get("perun_policies"); Iterator<String> policyNames = policiesNode.fieldNames(); while(policyNames.hasNext()) { String policyName = policyNames.next(); JsonNode policyNode = policiesNode.get(policyName); List<Map<String, String>> perunRoles = new ArrayList<>(); JsonNode perunRolesNode = policyNode.get("policy_roles"); for (JsonNode perunRoleNode : perunRolesNode) { Map<String, String> innerRoleMap = new HashMap<>(); Iterator<String> roleArrayKeys = perunRoleNode.fieldNames(); while (roleArrayKeys.hasNext()) { String role = roleArrayKeys.next(); JsonNode roleObjectNode = perunRoleNode.get(role); String object = roleObjectNode.isNull() ? null : roleObjectNode.textValue(); innerRoleMap.put(role, object); } perunRoles.add(innerRoleMap); } List<String> includePolicies = new ArrayList<>(objectMapper.convertValue(policyNode.get("include_policies"), new TypeReference<List<String>>() {})); policies.add(new PerunPolicy(policyName, perunRoles, includePolicies)); } return policies; }
Source:
<code>private FactHandle[] insertFacts(KieSession ksession, int n) { FactHandle[] fhs = new FactHandle[n]; for (int i = 0; i < n; i++) { fhs[i] = ksession.insert(i); <START> ksession.insert("" + String.valueOf(i)); <END> } return fhs; }</code><technical_language>ksession.insert(String.valueOf(i));</technical_language>

Target:
private FactHandle[] insertFacts(KieSession ksession, int n) { FactHandle[] fhs = new FactHandle[n]; for (int i = 0; i < n; i++) { fhs[i] = ksession.insert(i); ksession.insert(String.valueOf(i)); } return fhs; }
Source:
<code>public void doNotExpireDynamicConfigWithCustomExpirationUsedBySource() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpirationForSource", "heisenbergWithCustomExpirationForSource", "Walter Blanco"); try { assertExpired(config, 10000, 1000); fail("Config should not have been expired"); } catch (AssertionError e) { <START> assertThat(e.getMessage(), is(not("Config should not have been expired"))); <END> } assertInitialised(config); sourceWithDynamicConfig.stop(); assertExpired(config, 6000, 100); }</code><technical_language>elegant. throw illegalStateException instead of fail</technical_language>

Target:
public void doNotExpireDynamicConfigWithCustomExpirationUsedBySource() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpirationForSource", "heisenbergWithCustomExpirationForSource", "Walter Blanco"); try { assertExpired(config, 10000, 1000); throw new IllegalStateException("Config should not have been expired"); } catch (AssertionError e) { } assertInitialised(config); sourceWithDynamicConfig.stop(); assertExpired(config, 6000, 100); }
Source:
<code>public JsonObject getClientOfAccount(String deploymentUrl, JsonObject account) { String url = getClientUrl(deploymentUrl, account); JsonObject jsonResponse = null; String authToken = getAuthorizationToken(account.get("email_address").toString(), account.get("auth_token").toString()); <START> System.out.println("***************************************************************"); <END> System.out.println("*** URL: " + url); System.out.println("Auth Token: " + authToken); System.out.println("Account Auth: " + account.get("auth_token")); System.out.println("Account Sid: " + account.get("sid")); System.out.println("***************************************************************"); try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Authorization", "Basic " + authToken); HttpResponse response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String res = EntityUtils.toString(entity); JsonParser parser = new JsonParser(); jsonResponse = parser.parse(res).getAsJsonObject(); } httpGet.releaseConnection(); }catch (ClientProtocolException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return jsonResponse; }</code><technical_language>important this is in testing only, remove sysout statements replace logging if needed</technical_language>

Target:
public JsonObject getClientOfAccount(String deploymentUrl, JsonObject account) { String url = getClientUrl(deploymentUrl, account); JsonObject jsonResponse = null; String authToken = getAuthorizationToken(account.get("email_address").toString(), account.get("auth_token").toString()); try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Authorization", "Basic " + authToken); HttpResponse response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String res = EntityUtils.toString(entity); JsonParser parser = new JsonParser(); jsonResponse = parser.parse(res).getAsJsonObject(); } httpGet.releaseConnection(); }catch (ClientProtocolException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return jsonResponse; }
Source:
<code>public T nextRecord() { <START> byte[] blob = <END> c.getBlob(c.getColumnIndexOrThrow(DatabaseHelper.DATA_COL)); if (blob != null) { return storage.newObject(blob, nextID()); } else { String filename = c.getString(c.getColumnIndexOrThrow(DatabaseHelper.FILE_COL)); byte[] aesKeyBlob = c.getBlob(c.getColumnIndexOrThrow(DatabaseHelper.AES_COL)); InputStream fileInputStream = ((HybridFileBackedSqlStorage<T>)storage).getInputStreamFromFile(filename, aesKeyBlob); return storage.newObject(fileInputStream, nextID()); } }</code><technical_language>This a path follow if "includeData" flag set false</technical_language>

Target:
public T nextRecord() { byte[] blob = c.getBlob(c.getColumnIndexOrThrow(DatabaseHelper.DATA_COL)); if (blob != null) { return storage.newObject(blob, nextID()); } else { String filename = c.getString(c.getColumnIndexOrThrow(DatabaseHelper.FILE_COL)); byte[] aesKeyBlob = c.getBlob(c.getColumnIndexOrThrow(DatabaseHelper.AES_COL)); try { InputStream fileInputStream = ((HybridFileBackedSqlStorage<T>)storage).getInputStreamFromFile(filename, aesKeyBlob); return storage.newObject(fileInputStream, nextID()); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } }
Source:
<code>protected Number calculateHorizontalDiff(final ILayerCell cell, final int toRow, final IConfigRegistry configRegistry) { Number diff = super.calculateHorizontalDiff(cell, toRow, configRegistry); if (command instanceof PapyrusFillHandlePasteCommand) { <START> if ((command.direction == MoveDirectionEnum.UP && !((PapyrusFillHandlePasteCommand) command).isIncrement()) <END> || (command.direction == MoveDirectionEnum.DOWN && !((PapyrusFillHandlePasteCommand) command).isIncrement())) { if (diff instanceof Byte) { diff = 0 - diff.byteValue(); } else if (diff instanceof Short) { diff = 0 - diff.shortValue(); } else if (diff instanceof Integer) { diff = 0 - diff.intValue(); } else if (diff instanceof Long) { diff = 0 - diff.longValue(); } else if (diff instanceof Float) { diff = 0 - diff.floatValue(); } else if (diff instanceof Double) { diff = 0 - diff.doubleValue(); } else if (diff instanceof BigInteger) { diff = BigInteger.ZERO.subtract((BigInteger) diff); } else if (diff instanceof BigDecimal) { diff = BigDecimal.ZERO.subtract((BigDecimal) diff); } } } return diff; }</code><technical_language>invert conditions</technical_language>

Target:
protected Number calculateHorizontalDiff(final ILayerCell cell, final int toRow, final IConfigRegistry configRegistry) { Number diff = super.calculateHorizontalDiff(cell, toRow, configRegistry); if (command instanceof PapyrusFillHandlePasteCommand) { if ((MoveDirectionEnum.UP == command.direction && !((PapyrusFillHandlePasteCommand) command).isIncrement()) || (MoveDirectionEnum.DOWN == command.direction && !((PapyrusFillHandlePasteCommand) command).isIncrement())) { if (diff instanceof Byte) { diff = 0 - diff.byteValue(); } else if (diff instanceof Short) { diff = 0 - diff.shortValue(); } else if (diff instanceof Integer) { diff = 0 - diff.intValue(); } else if (diff instanceof Long) { diff = 0 - diff.longValue(); } else if (diff instanceof Float) { diff = 0 - diff.floatValue(); } else if (diff instanceof Double) { diff = 0 - diff.doubleValue(); } else if (diff instanceof BigInteger) { diff = BigInteger.ZERO.subtract((BigInteger) diff); } else if (diff instanceof BigDecimal) { diff = BigDecimal.ZERO.subtract((BigDecimal) diff); } } } return diff; }
Source:
<code>protected Event doExecute(final RequestContext requestContext) { val auth = WebUtils.getAuthentication(requestContext); val uid = auth.getPrincipal().getId(); val keyUriFmt = "otpauth://totp/" + this.label + ":" + uid + "?secret=%s&issuer=" + this.issuer; if (auth.getAttributes().containsKey("isNewOtpRegistration")) { LOGGER.debug("Arrrived back at registration check with isNewOtpRegistration set; returning register"); return new EventFactorySupport().event(this, "register"); } val acct = repository.get(uid); if (acct == null || StringUtils.isBlank(acct.getSecretKey())) { val keyAccount = this.repository.create(uid); val keyUri = String.format(keyUriFmt, keyAccount.getSecretKey()); <START> requestContext.getFlowScope().put("key", keyAccount); <END> requestContext.getFlowScope().put("keyUri", keyUri); LOGGER.debug("Registration key URI is [{}]", keyUri); auth.addAttribute("isNewOtpRegistration", true); return new EventFactorySupport().event(this, "register"); } return success(); }</code><technical_language>concatenating components generate this URI safe? if benefit encoding here</technical_language>

Target:
protected Event doExecute(final RequestContext requestContext) { val uid = WebUtils.getAuthentication(requestContext).getPrincipal().getId(); val acct = repository.get(uid); if (acct == null || StringUtils.isBlank(acct.getSecretKey())) { val keyAccount = this.repository.create(uid); val keyUri = "otpauth://totp/" + this.label + ':' + uid + "?secret=" + keyAccount.getSecretKey() + "&issuer=" + this.issuer; val flowScope = requestContext.getFlowScope(); flowScope.put(FLOW_SCOPE_ATTR_ACCOUNT, keyAccount); flowScope.put(FLOW_SCOPE_ATTR_ACCOUNT_URI, keyUri); LOGGER.debug("Registration key URI is [{}]", keyUri); return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_REGISTER); } return success(); }
Source:
<code>protected void verify_internal_effects() { <START> verify(comparables).assertEqual(getInfo(assertions), getActual(assertions), "A and 8"); <END> }</code><technical_language>adjust this changes -> pr build travis</technical_language>

Target:
protected void verify_internal_effects() { verify(objects).assertEqual(getInfo(assertions), getActual(assertions), "A and 8"); }
Source:
<code>public ActiveMQBuffer toActiveMQBuffer() throws Exception { if (buffer == null) { if (bytesBody != null) { buffer = ActiveMQBuffers.dynamicBuffer(bytesBody.length + 512); } else { buffer = ActiveMQBuffers.dynamicBuffer(512); } if (isPing()) { buffer.writeByte((byte) 10); return buffer; } <START> StringBuilder head = new StringBuilder(512); <END> head.append(command); head.append(Stomp.NEWLINE); encodeHeaders(head); if (bytesBody != null && bytesBody.length > 0 && !hasHeader(Stomp.Headers.CONTENT_LENGTH) && !(this instanceof StompFrameV10)) { head.append(Stomp.Headers.CONTENT_LENGTH); head.append(Stomp.Headers.SEPARATOR); head.append(bytesBody.length); head.append(Stomp.NEWLINE); } head.append(Stomp.NEWLINE); buffer.writeBytes(head.toString().getBytes(StandardCharsets.UTF_8)); if (bytesBody != null) { buffer.writeBytes(bytesBody); } buffer.writeBytes(END_OF_FRAME); size = buffer.writerIndex(); } else { buffer.readerIndex(0); } return buffer; }</code><technical_language>run benchmarks find this? I agree .. wondering bad it</technical_language>

Target:
public ActiveMQBuffer toActiveMQBuffer() throws Exception { if (buffer == null) { if (isPing()) { buffer = ActiveMQBuffers.fixedBuffer(1); buffer.writeByte((byte)10); size = buffer.writerIndex(); return buffer; } StringBuilder head = new StringBuilder(512); head.append(command); head.append(Stomp.NEWLINE); encodeHeaders(head); if (bytesBody != null && bytesBody.length > 0 && !hasHeader(Stomp.Headers.CONTENT_LENGTH) && !(this instanceof StompFrameV10)) { head.append(Stomp.Headers.CONTENT_LENGTH); head.append(Stomp.Headers.SEPARATOR); head.append(bytesBody.length); head.append(Stomp.NEWLINE); } head.append(Stomp.NEWLINE); byte[] headBytes = head.toString().getBytes(StandardCharsets.UTF_8); int bodyLength = (bytesBody == null) ? 0 : bytesBody.length; buffer = ActiveMQBuffers.fixedBuffer(headBytes.length + bodyLength + END_OF_FRAME.length); buffer.writeBytes(headBytes); if (bytesBody != null) { buffer.writeBytes(bytesBody); } buffer.writeBytes(END_OF_FRAME); size = buffer.writerIndex(); } else { buffer.readerIndex(0); } return buffer; }
Source:
<code>public String execute(Connection<?> connection) { User user = userHelper.createUser(connection); AccountRequest accountRequest = new AccountRequest(); accountRequest.setUsername(user.getUserName()); accountRequest.setName( user.getName()); accountRequest.setEmail(user.getEmail()); accountRequest.setSocialSignIn(true); accountRequest.setProvider(user.getProvider()); accountRequest.setUserIdOfProvider(user.getUserIdOfProvider()); try { <START> userManager.addNewUser(accountRequest); <END> } catch (QuadrigaStorageException | QuadrigaNotificationException | UsernameExistsException e) { logger.error("Could not store user.", e); return null; } return user.getUserName(); }</code><technical_language>if this return false, what</technical_language>

Target:
public String execute(Connection<?> connection) { try { return userHelper.createUserName(connection); } catch (QuadrigaStorageException e) { logger.error("Error while creating username", e); return null; } }
Source:
<code>private boolean checkExpressionsUnique(List<SortEntry> sortList){ List<String> list = new ArrayList<>(); for(SortEntry elm: sortList){ list.add(elm.match.expression.getRegex()); } <START> return new HashSet<>(list).size() == list.size(); <END> }</code><technical_language>@treblereel , do need 'list' instance here? build HashSet compare size sortList size? better, point simply return time HashSet#add method invocation returns false</technical_language>

Target:
private boolean checkExpressionsUnique(List<SortEntry> sortList){ Set<String> regexps = new HashSet<>(); for(SortEntry elm: sortList){ regexps.add(elm.match.expression.getRegex()); } return regexps.size() == sortList.size(); }
Source:
<code>public boolean validate(Context context, HttpServletRequest request, List<String> uriList, Class clazz) throws AuthorizeException { if (uriList.size() > 1) { return false; } if (clazz != Item.class) { return false; } String owningCollectionString = request.getParameter("owningCollection"); if (StringUtils.isBlank(owningCollectionString)) { return false; } try { Collection collection = collectionService.find(context, UUID.fromString(owningCollectionString)); if (collection == null) { return false; } if (!authorizeService.isAdmin(context)) { throw new AuthorizeException("Only admins are allowed to create items using external data"); } } catch (SQLException e) { <START> log.error(e.getMessage(), e); <END> return false; } return true; }</code><technical_language>Please log a more descriptive message here. Remember e.getMessage() null. This "Search for owningCollection UUID = [parsed uuid] resulted in error"</technical_language>

Target:
public boolean validate(Context context, HttpServletRequest request, List<String> uriList, Class clazz) throws AuthorizeException { if (uriList.size() > 1) { return false; } if (clazz != Item.class) { return false; } String owningCollectionString = request.getParameter("owningCollection"); if (StringUtils.isBlank(owningCollectionString)) { return false; } try { if (!authorizeService.isAdmin(context)) { throw new AuthorizeException("Only admins are allowed to create items using external data"); } Collection collection = collectionService.find(context, UUID.fromString(owningCollectionString)); if (collection == null) { return false; } } catch (SQLException e) { log.error("Search for owningCollection with UUID:" + owningCollectionString + " resulted in an error", e); return false; } return true; }
Source:
<code>public void send(byte[] message) { outbox.addFirst(ByteBuffer.wrap(message)); <START> LOG.debug("Message sent: " + new String(message, UTF8)); <END> final ReactorClient client = this; scheduleTask(new Callable<Void>() { @Override public Void call() throws ClientConnectionException { client.updateInterestedOps(); return null; } }); }</code><technical_language>Please wrap in isDebugEnabled call</technical_language>

Target:
public void send(byte[] message) { outbox.addFirst(ByteBuffer.wrap(message)); if (LOG.isDebugEnabled()) { LOG.debug("Message sent: " + new String(message, UTF8)); } final ReactorClient client = this; scheduleTask(new Callable<Void>() { @Override public Void call() throws ClientConnectionException { client.updateInterestedOps(); return null; } }); }