auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testExecuteSimpleRuleFlowProcessWithAsyncResponseHandler() { Marshaller marshaller = MarshallerFactory.getMarshaller(new HashSet<Class<?>>(extraClasses.values()), configuration.getMarshallingFormat(), client.getClassLoader()); ResponseCallback responseCallback = new BlockingResponseCallback(marshaller); ResponseHandler asyncResponseHandler = new AsyncResponseHandler(responseCallback); ruleClient.setResponseHandler(asyncResponseHandler); List<Command<?>> commands = new ArrayList<Command<?>>(); commands.add(commandsFactory.newSetGlobal(LIST_NAME, new ArrayList<String>(), LIST_OUTPUT_NAME)); commands.add(commandsFactory.newStartProcess(PROCESS_ID)); commands.add(commandsFactory.newFireAllRules()); commands.add(commandsFactory.newGetGlobal(LIST_NAME, LIST_OUTPUT_NAME)); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands, KIE_SESSION); <START> assertNoResponse(ruleClient.executeCommandsWithResults(CONTAINER_ID, batchExecution)); <END> ExecutionResults result = responseCallback.get(ExecutionResults.class); List<String> outcome = (List<String>) result.getValue(LIST_OUTPUT_NAME); assertThat(outcome).isNotNull(); assertThat(outcome).containsExactly("Rule from first ruleflow group executed", "Rule from second ruleflow group executed"); }</code><technical_language>this assertNoResponse is wrongly assuming response - idea for async/fire forget is returns null callback get response. response handler internally returns NO_RESPONSE response is changed client return null. this in jbpm tests well</technical_language>

Target:
public void testExecuteSimpleRuleFlowProcessWithAsyncResponseHandler() { Marshaller marshaller = MarshallerFactory.getMarshaller(new HashSet<Class<?>>(extraClasses.values()), configuration.getMarshallingFormat(), client.getClassLoader()); ResponseCallback responseCallback = new BlockingResponseCallback(marshaller); ResponseHandler asyncResponseHandler = new AsyncResponseHandler(responseCallback); ruleClient.setResponseHandler(asyncResponseHandler); List<Command<?>> commands = new ArrayList<Command<?>>(); commands.add(commandsFactory.newSetGlobal(LIST_NAME, new ArrayList<String>(), LIST_OUTPUT_NAME)); commands.add(commandsFactory.newStartProcess(PROCESS_ID)); commands.add(commandsFactory.newFireAllRules()); commands.add(commandsFactory.newGetGlobal(LIST_NAME, LIST_OUTPUT_NAME)); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands, KIE_SESSION); ServiceResponse<?> response = ruleClient.executeCommandsWithResults(CONTAINER_ID, batchExecution); assertThat(response).isNull(); ExecutionResults result = responseCallback.get(ExecutionResultImpl.class); List<String> outcome = (List<String>) result.getValue(LIST_OUTPUT_NAME); assertThat(outcome).isNotNull(); assertThat(outcome).containsExactly("Rule from first ruleflow group executed", "Rule from second ruleflow group executed"); }
Source:
<code>public String[] getLocalOnlyIfaces() { <START> ArrayList<String> list = new ArrayList<String>(); synchronized (mPublicSync) { for (int i = 0; i < mTetherStates.size(); i++) { TetherState tetherState = mTetherStates.valueAt(i); if (tetherState.lastState == IpServer.STATE_LOCAL_ONLY) { list.add(mTetherStates.keyAt(i)); } } } <END> return list.toArray(new String[list.size()]); }</code><technical_language>I replace this import com.android.internal.util.CollectionUtils; public String[] getLocalOnlyIfaces() { final List<String> list; synchronized(mPublicSync) { list = CollectionUtils.filter(mTetherStates, state -> state.lastState == IpServer.STATE_LOCAL_ONLY)); } return list.toArray(new String[0]); } (note passing a new String[0] is typically faster passing a new String[list.size()] thanks intrinsics, marginal)</technical_language>

Target:
public String[] getLocalOnlyIfaces() { final List<String> list; synchronized (mPublicSync) { list = CollectionUtils.filter( mTetherStates, state -> state.lastState == IpServer.STATE_LOCAL_ONLY); } return list.toArray(new String[0]); }
Source:
<code>public void convertFromStructuredJsonIntoString() throws Exception { String payload = "{\"id\":1}"; Message message = MessageBuilder.withPayload(payload.getBytes()).setHeader(MessageHeaders.CONTENT_TYPE,"application/json").build(); CustomJackson2MappingMessageConverter converter = new CustomJackson2MappingMessageConverter(); <START> Object converted = converter.convertFromInternal(message, String.class,null); <END> }</code><technical_language>Assertions missing test</technical_language>

Target:
public void convertFromStructuredJsonIntoString() throws Exception { String payload = "{\"id\":1}"; Message message = MessageBuilder.withPayload(payload.getBytes()).setHeader(MessageHeaders.CONTENT_TYPE,"application/json").build(); CustomJackson2MappingMessageConverter converter = new CustomJackson2MappingMessageConverter(); Object converted = converter.convertFromInternal(message, String.class,null); assertThat(converted).isNotNull(); assertThat(payload).isEqualTo(new String((byte[])converted)); }
Source:
<code>private File getRunDirectory(Repository repository, @NonNull String hookName) { if (repository.isBare()) { return repository.getDirectory(); <START> } else { <END> switch (hookName) { case "pre-receive": case "update": case "post-receive": case "post-update": case "push-to-checkout": return repository.getDirectory(); default: return repository.getWorkTree(); } } }</code><technical_language>remove unnecessary else clause</technical_language>

Target:
private File getRunDirectory(Repository repository, @NonNull String hookName) { if (repository.isBare()) { return repository.getDirectory(); } switch (hookName) { case "pre-receive": case "update": case "post-receive": case "post-update": case "push-to-checkout": return repository.getDirectory(); default: return repository.getWorkTree(); } }
Source:
<code>@Test public void testInterpretIntersectAllWithNullValue() throws Exception { final String sql = "select * from\n" + "(select x, y from (values (cast(NULL as int), cast(NULL as varchar(1))),\n" + " (cast(NULL as int), cast(NULL as varchar(1)))) as t(x, y))\n" + "intersect all\n" + "(select x, y from (values (cast(NULL as int), cast(NULL as varchar(1)))) as t2(x, y))\n"; SqlNode validate = planner.validate(planner.parse(sql)); RelNode convert = planner.rel(validate).rel; final Interpreter interpreter = new Interpreter(dataContext, convert); <START> assertRows(interpreter, "[null, null]", "[null, null]"); <END> }</code><technical_language>[null, null]</technical_language>

Target:
@Test public void testInterpretIntersectAllWithNullValue() throws Exception { final String sql = "select * from\n" + "(select x, y from (values (cast(NULL as int), cast(NULL as varchar(1))),\n" + " (cast(NULL as int), cast(NULL as varchar(1)))) as t(x, y))\n" + "intersect all\n" + "(select x, y from (values (cast(NULL as int), cast(NULL as varchar(1)))) as t2(x, y))"; interpretSqlAndCheck(sql, "[null, null]"); }
Source:
<code>public static void send(InternalDistributedMember recipient, int processorId, ReplySender replySender, boolean result, ReplyException ex) { <START> Assert.assertTrue(recipient != null, "ClearReplyMessage NULL recipient."); <END> ClearReplyMessage message = new ClearReplyMessage(processorId, result, ex); message.setRecipient(recipient); replySender.putOutgoing(message); }</code><technical_language>is Assert.assertNotNull() assertTrue(). Also, clearer a message of "ClearReplyMessage recipient NULL."</technical_language>

Target:
public static void send(InternalDistributedMember recipient, int processorId, ReplySender replySender, boolean result, ReplyException ex) { Assert.assertNotNull(recipient, "ClearReplyMessage recipient was NULL."); ClearReplyMessage message = new ClearReplyMessage(processorId, result, ex); message.setRecipient(recipient); replySender.putOutgoing(message); }
Source:
<code>public String getRuleLogsForVms() { <START> final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); <END> cmd.add("get_rule_logs_for_vms"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = cmd.execute(parser); if (result == null) { return parser.getLine(); } return null; }</code><technical_language>Please consider adding overridden version of Script(String, int, Logger) constructor accepts Duration encapsulate this type conversion</technical_language>

Target:
public String getRuleLogsForVms() { final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("get_rule_logs_for_vms"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = cmd.execute(parser); if (result == null) { return parser.getLine(); } return null; }
Source:
<code>private void verifyUCFValueInSysCat(String tableName, String createTableString, Properties props, long expectedUCFInSysCat) throws SQLException { String readSysCatQuery = "SELECT TABLE_NAME, UPDATE_CACHE_FREQUENCY FROM SYSTEM.CATALOG WHERE " + "TABLE_NAME = '" + tableName + "' AND TABLE_TYPE='u'"; <START> Connection connection = DriverManager.getConnection(getUrl(), props); <END> connection.createStatement().execute(createTableString); ResultSet rs = connection.createStatement().executeQuery(readSysCatQuery); assertTrue(rs.next()); assertEquals(expectedUCFInSysCat, rs.getLong(2)); connection.createStatement().execute("drop table " + tableName); connection.close(); }</code><technical_language>nit: Put connection object in a try-with-resources</technical_language>

Target:
private void verifyUCFValueInSysCat(String tableName, String createTableString, Properties props, long expectedUCFInSysCat) throws SQLException { String readSysCatQuery = "SELECT TABLE_NAME, UPDATE_CACHE_FREQUENCY FROM SYSTEM.CATALOG " + "WHERE TABLE_NAME = '" + tableName + "' AND TABLE_TYPE='u'"; try (Connection connection = DriverManager.getConnection(getUrl(), props); Statement stmt = connection.createStatement()) { stmt.execute(createTableString); try (ResultSet rs = stmt.executeQuery(readSysCatQuery)) { assertTrue(rs.next()); assertEquals(expectedUCFInSysCat, rs.getLong(2)); } stmt.execute("drop table " + tableName); } }
Source:
<code>protected String getIndexesAsString(String[] indexNames) { String indexes = ""; if (indexNames != null && indexNames.length > 0) { indexes = String.join(",", indexNames); <START> } <END> return indexes; }</code><technical_language>do double assignment, need for "return end of method", case indexNames.length == 0 is dealt String.join, do: return indexNames == null ? "" : String.join(",", indexNames);</technical_language>

Target:
protected String getIndexesAsString(String[] indexNames) { return indexNames == null ? "" : String.join(",", indexNames); }
Source:
<code>public RowFilter adapt(FilterAdapterContext context, FuzzyRowFilter filter) throws IOException { Interleave.Builder interleaveBuilder = Interleave.newBuilder(); List<Pair<byte[], byte[]>> pairs = extractFuzzyRowFilterPairs(filter); <START> if (pairs.size() == 0) { <END> return ALL_VALUES_FILTER; } for (Pair<byte[], byte[]> pair : pairs) { Preconditions.checkArgument( pair.getFirst().length == pair.getSecond().length, "Fuzzy info and match mask must have the same length"); interleaveBuilder.addFilters( createSingleRowFilter( pair.getFirst(), pair.getSecond())); } return RowFilter.newBuilder().setInterleave(interleaveBuilder).build(); }</code><technical_language>isEmpty()</technical_language>

Target:
public RowFilter adapt(FilterAdapterContext context, FuzzyRowFilter filter) throws IOException { Interleave.Builder interleaveBuilder = Interleave.newBuilder(); List<Pair<byte[], byte[]>> pairs = extractFuzzyRowFilterPairs(filter); if (pairs.isEmpty()) { return ALL_VALUES_FILTER; } for (Pair<byte[], byte[]> pair : pairs) { Preconditions.checkArgument( pair.getFirst().length == pair.getSecond().length, "Fuzzy info and match mask must have the same length"); interleaveBuilder.addFilters( createSingleRowFilter( pair.getFirst(), pair.getSecond())); } return RowFilter.newBuilder().setInterleave(interleaveBuilder).build(); }
Source:
<code><START> public void validate(final EventType eventType) throws InvalidEventTypeException { <END> if (eventType.getCategory() == EventCategory.UNDEFINED && !eventType.getEnrichmentStrategies().isEmpty()) { throw new InvalidEventTypeException("must not define enrichment strategy for undefined event type"); } final Set<EnrichmentStrategyDescriptor> uniqueStrategies = new HashSet<EnrichmentStrategyDescriptor>(); uniqueStrategies.addAll(eventType.getEnrichmentStrategies()); if (eventType.getEnrichmentStrategies().size() != uniqueStrategies.size()) { throw new InvalidEventTypeException("enrichment strategies must not contain duplicated entries"); } if (eventType.getCategory() != EventCategory.UNDEFINED && !eventType.getEnrichmentStrategies().contains(EnrichmentStrategyDescriptor.METADATA_ENRICHMENT)) { throw new InvalidEventTypeException("must define metadata enrichment strategy"); } }</code><technical_language>is check enrichment strategy is Nakadi</technical_language>

Target:
public void validate(final EventType eventType) throws InvalidEventTypeException { if (eventType.getCategory() == EventCategory.UNDEFINED && !eventType.getEnrichmentStrategies().isEmpty()) { throw new InvalidEventTypeException("must not define enrichment strategy for undefined event type"); } final Set<EnrichmentStrategyDescriptor> uniqueStrategies = new HashSet<>(eventType.getEnrichmentStrategies()); if (eventType.getEnrichmentStrategies().size() != uniqueStrategies.size()) { throw new InvalidEventTypeException("enrichment strategies must not contain duplicated entries"); } if (eventType.getCategory() != EventCategory.UNDEFINED && !eventType.getEnrichmentStrategies().contains(EnrichmentStrategyDescriptor.METADATA_ENRICHMENT)) { throw new InvalidEventTypeException("must define metadata enrichment strategy"); } }
Source:
<code><START> default public boolean noTransaction() { return false; } <END></code><technical_language>minor: need "public" modifier</technical_language>

Target:
default boolean noTransaction() { return false; }
Source:
<code><START> public Fake(final String... dispositions) throws IOException { <END> this( new RqWithHeaders( new RqFake(), Arrays.asList( "Host: www.example.com", "Content-Type: multipart/form-data; boundary=AaB02x", "Content-Length: 100001" ) ), dispositions ); }</code><technical_language>brr... I understand this ctor. do this: this(new RqFake(), dispositions). else</technical_language>

Target:
public Fake(final String... dispositions) throws IOException { this(new RqFake(), dispositions); }
Source:
<code>private static File fetchSystemVmKeyFile() { String filePath = s_relativePathSystemVmKeyFileInstallDir; s_logger.debug("Looking for file [" + filePath + "] in the classpath."); URL url = Script.class.getClassLoader().getResource(filePath); File keyFile = null; if (url != null) { keyFile = new File(url.getPath()); } if (keyFile == null || !keyFile.exists()) { filePath = s_defaultPathSystemVmKeyFile; keyFile = new File(filePath); s_logger.debug("Looking for file [" + filePath + "] in the classpath."); } <START> assert (keyFile != null); <END> if (!keyFile.exists()) { s_logger.error("Unable to locate id_rsa.cloud in your setup at " + keyFile.toString()); } return keyFile; }</code><technical_language>This assert statement is true. needed here. Rest code changes LGTM</technical_language>

Target:
private static File fetchSystemVmKeyFile() { String filePath = s_relativePathSystemVmKeyFileInstallDir; s_logger.debug("Looking for file [" + filePath + "] in the classpath."); URL url = Script.class.getClassLoader().getResource(filePath); File keyFile = null; if (url != null) { keyFile = new File(url.getPath()); } if (keyFile == null || !keyFile.exists()) { filePath = s_defaultPathSystemVmKeyFile; keyFile = new File(filePath); s_logger.debug("Looking for file [" + filePath + "] in the classpath."); } if (!keyFile.exists()) { s_logger.error("Unable to locate id_rsa.cloud in your setup at " + keyFile.toString()); } return keyFile; }
Source:
<code>static void keepNewServicesOnly(Map<String,Map<String,Set<String>>> recommendedLayout, Map<String,Map<String,Set<String>>> newServices) { <START> recommendedLayout.keySet().removeIf(service -> !newServices.containsKey(service)); <END> }</code><technical_language>suggestion recommendedLayout.keySet().retainAll(newServices.keySet());</technical_language>

Target:
static void keepNewServicesOnly(Map<String,Map<String,Set<String>>> recommendedLayout, Map<String,Map<String,Set<String>>> newServices) { recommendedLayout.keySet().retainAll(newServices.keySet()); }
Source:
<code>private boolean isJTATransactionAvailable() { Transaction transaction = null; try { transaction = TransactionManager.transactionManager(new InitialContext()).getTransaction(); <START> } catch (javax.transaction.SystemException | NamingException e) { <END> } return transaction != null; }</code><technical_language>For exceptions I prefer variable name ignore (so is design)</technical_language>

Target:
private boolean isJTATransactionAvailable() { Transaction transaction = null; try { transaction = TransactionManager.transactionManager(new InitialContext()).getTransaction(); } catch (javax.transaction.SystemException | NamingException ignore) { } return transaction != null; }
Source:
<code>public void testClone() throws Exception { createInitialCommit(); File gitDir = db.getDirectory(); String sourcePath = gitDir.getAbsolutePath(); String targetPath = (new File(sourcePath)).getParentFile() .getParentFile().getAbsolutePath() <START> + "/target"; <END> StringBuilder cmd = new StringBuilder("git clone ").append(sourcePath + " " + targetPath); String[] result = execute(cmd.toString()); assertArrayEquals(new String[] { "Cloning into '" + targetPath + "'...", "", "" }, result); Git git2 = Git.open(new File(targetPath)); List<Ref> branches = git2.branchList().call(); assertEquals("expected 1 branch", 1, branches.size()); }</code><technical_language>"targetPath=createTempDirectory("target")"</technical_language>

Target:
public void testClone() throws Exception { createInitialCommit(); File gitDir = db.getDirectory(); String sourceURI = gitDir.toURI().toString(); File target = createTempDirectory("target"); StringBuilder cmd = new StringBuilder("git clone ").append(sourceURI + " " + target.getPath()); String[] result = execute(cmd.toString()); assertArrayEquals(new String[] { "Cloning into '" + target.getPath() + "'...", "", "" }, result); Git git2 = Git.open(target); List<Ref> branches = git2.branchList().call(); assertEquals("expected 1 branch", 1, branches.size()); }
Source:
<code>public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { Context contextForHandler = Context.get(); OAuthHandler oaHandler = (OAuthHandler) contextForHandler.getSessionMap().get( Configuration.OAUTH_HANDLER); OAProvider oaProvider = (OAProvider) contextForHandler.getSessionMap().get("oaProvider"); String authorizationheader = null; if (oaHandler.getClass().equals(HMACOAuth1Handler.class)) { Map<String, String> mapOfParams = new TreeMap<String, String>(); String requestUri = request.getRequestLine().getUri().toString(); if (requestUri.contains("?")) { String queryStr = requestUri.substring(requestUri.indexOf("?") + 1, requestUri.length()); requestUri = requestUri.substring(0, requestUri.indexOf("?")); String[] paramsList = queryStr.split("&"); for (String i : paramsList) { String[] parameter = i.split("="); mapOfParams.put(parameter[0], parameter[1]); } } try { requestUri = PathUtil.concat(oaProvider.getUrl(), requestUri, '/'); authorizationheader = ((HMACOAuth1Handler) oaHandler).createAuthorizationHeader( requestUri, mapOfParams); } catch (OAuthException e) { throw new HttpException( "OAuthException thrown while creating Authorization header in OAuthInterceptor", e); } request.addHeader("Authorization", authorizationheader); } else { authorizationheader = oaHandler.createAuthorizationHeader(); <START> request.addHeader("Authorization", authorizationheader); <END> } }</code><technical_language>setting authorization header if-else need do this in case</technical_language>

Target:
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { Context contextForHandler = Context.get(); OAuthHandler oaHandler = (OAuthHandler) contextForHandler.getSessionMap().get( Configuration.OAUTH_HANDLER); contextForHandler.getSessionMap().get("oaProvider"); String authorizationheader = null; if (oaHandler.getClass().equals(HMACOAuth1Handler.class)) { Map<String, String> mapOfParams = new TreeMap<String, String>(); String requestUri = request.getRequestLine().getUri().toString(); if (requestUri.contains("?")) { String queryStr = requestUri.substring(requestUri.indexOf("?") + 1, requestUri.length()); requestUri = requestUri.substring(0, requestUri.indexOf("?")); String[] paramsList = queryStr.split("&"); for (String i : paramsList) { String[] parameter = i.split("="); mapOfParams.put(parameter[0], parameter[1]); } } try { requestUri = PathUtil.concat(applicationUrl, requestUri, '/'); authorizationheader = ((HMACOAuth1Handler) oaHandler).createAuthorizationHeader( requestUri, mapOfParams); } catch (OAuthException e) { throw new HttpException( "OAuthException thrown while creating Authorization header in OAuthInterceptor", e); } request.addHeader("Authorization", authorizationheader); } else { authorizationheader = oaHandler.createAuthorizationHeader(); request.addHeader("Authorization", authorizationheader); } }
Source:
<code>public void exceptionInCleanupClosesTransactionManager() { RuntimeException cause = new RuntimeException("VALID REASON"); doThrow(cause).when(mockCallback).runWithRetry(); setInitializationStatus(true, true, true, true); <START> assertClosedWitoutInitializingWithinTwoSeconds(); <END> Assertions.assertThatThrownBy(() -> manager.runTaskWithRetry($ -> null)) .isInstanceOf(IllegalStateException.class) .hasCause(cause); }</code><technical_language>spelling nit: Witout -></technical_language>

Target:
public void exceptionInCleanupClosesTransactionManager() { RuntimeException cause = new RuntimeException("VALID REASON"); doThrow(cause).when(mockCallback).runWithRetry(any(SerializableTransactionManager.class)); everythingInitialized(); assertNotInitializedWithinTwoSecondsBecauseClosed(); assertTrue(((SerializableTransactionManager.InitializeCheckingWrapper) manager).isClosedByCallbackFailure()); Assertions.assertThatThrownBy(() -> manager.runTaskWithRetry($ -> null)) .isInstanceOf(IllegalStateException.class) .hasCause(cause); }
Source:
<code>private BuildCommand info(String workingDir) { <START> return exec("svn", "info").setWorkingDirectory(workingDir); <END> }</code><technical_language>This is replacement for [this](<LINK_0> want consider --non-interactive least</technical_language>

Target:
private BuildCommand info(String workingDir) { return exec("svn", "info", "--non-interactive").setWorkingDirectory(workingDir); }
Source:
<code>public static String readString(ByteArrayInputStream inputStream) { <START> StringBuilder sb = new StringBuilder(); <END> byte readByte; while (((readByte = (byte)inputStream.read()) != 0x00) && readByte != -1) sb.append((char)readByte); return sb.toString(); }</code><technical_language>Check if inputStream is null</technical_language>

Target:
public static String readString(ByteArrayInputStream inputStream) { if (inputStream == null) throw new NullPointerException("Input stream cannot be null."); StringBuilder sb = new StringBuilder(); byte readByte; while (((readByte = (byte)inputStream.read()) != 0x00) && readByte != -1) sb.append((char)readByte); return sb.toString(); }
Source:
<code>public static <T> T buildInterface(Class<T> clazz, Context context) { RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(context); <START> restAdapter.setLogLevel(RestAdapter.LogLevel.FULL); <END> return restAdapter.create(clazz); }</code><technical_language>in prod, way</technical_language>

Target:
public static <T> T buildInterface(Class<T> clazz, Context context) { RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(context); restAdapter.setLogLevel(LOG_LEVEL); return restAdapter.create(clazz); }
Source:
<code>private boolean isCheckmarkDeselectOther() { if (_ckDeselectOther == null) _ckDeselectOther = Boolean .valueOf("true".equals(Library.getProperty("org.zkoss.zul.tree.checkmarkDeselectOthers"))); return Utils.testAttribute(this, "org.zkoss.zul.listbox.checkmarkDeselectOthers", _ckDeselectOther.booleanValue(), true); <START> } <END></code><technical_language>listbox</technical_language>

Target:
private boolean isCheckmarkDeselectOther() { if (_ckDeselectOther == null) _ckDeselectOther = Boolean .valueOf("true".equals(Library.getProperty("org.zkoss.zul.tree.checkmarkDeselectOthers"))); return Utils.testAttribute(this, "org.zkoss.zul.tree.checkmarkDeselectOthers", _ckDeselectOther.booleanValue(), true); }
Source:
<code>public void propertyChange(PropertyChangeEvent event) { <START> if(event.getProperty() == serverChoice.VALUE && event.getSource() == serverChoice) { <END> serverPath.setStringValue(CPPStreamConnectionProvider.getDefaultLSLocation((String) event.getNewValue()).getAbsolutePath()); serverPath.load(); } }</code><technical_language>is a static field of FieldEditor, accessing object instance (serverChoice is this case) is misleading. access FieldEditor.VALUE</technical_language>

Target:
public void propertyChange(PropertyChangeEvent event) { if(event.getSource() == serverChoice && event.getProperty() == FieldEditor.VALUE) { String changedLSLocation = CPPStreamConnectionProvider.getDefaultLSLocation((String) event.getNewValue()).getAbsolutePath(); if(changedLSLocation != null) { serverPath.setStringValue(changedLSLocation); } } }
Source:
<code>public void register(final StateRestorer restorer) { if (!stateRestorers.containsKey(restorer.partition())) { restorer.setUserRestoreListener(userStateRestoreListener); stateRestorers.put(restorer.partition(), restorer); log.trace("Added restorer for changelog {}", restorer.partition()); } else { <START> log.trace("Already added restorer for changelog {}", restorer.partition()); <END> } needsInitializing.add(restorer.partition()); }</code><technical_language>nit: Skip adding restorer ... exist in registered restorer. I this DEBUG</technical_language>

Target:
public void register(final StateRestorer restorer) { if (!stateRestorers.containsKey(restorer.partition())) { restorer.setUserRestoreListener(userStateRestoreListener); stateRestorers.put(restorer.partition(), restorer); log.trace("Added restorer for changelog {}", restorer.partition()); } else { log.debug("Skip re-adding restorer for changelog {}", restorer.partition()); } needsInitializing.add(restorer.partition()); }
Source:
<code>public void modelChanged(String modelName, EventType type) { if (modelName.endsWith(SITEMAP_FILEEXT)) { if (type == EventType.REMOVED) { sitemapModelCache.remove(modelName); } else { EObject sitemap = modelRepo.getModel(modelName); if (sitemap instanceof Sitemap) { <START> sitemapModelCache.put(modelName, (Sitemap) modelRepo.getModel(modelName)); <END> } } } for (ModelRepositoryChangeListener listener : modelChangeListeners) { listener.modelChanged(modelName, type); } }</code><technical_language>reuse sitemap variable instead of requesting again</technical_language>

Target:
public void modelChanged(String modelName, EventType type) { if (modelName.endsWith(SITEMAP_FILEEXT)) { if (type == EventType.REMOVED) { sitemapModelCache.remove(modelName); } else { EObject sitemap = modelRepo.getModel(modelName); if (sitemap instanceof Sitemap) { sitemapModelCache.put(modelName, (Sitemap) sitemap); } } } for (ModelRepositoryChangeListener listener : modelChangeListeners) { listener.modelChanged(modelName, type); } }
Source:
<code>protected void validateSubject(final Assertion assertion) throws WSSecurityException { <START> if (assertion.getStatements() == null || assertion.getStatements().isEmpty()) { <END> assertAttAuthzStatements(assertion); } if (!assertion.getAuthnStatements().isEmpty() && assertion.getSubject() == null) { throw new WSSecurityException(ErrorCode.FAILURE, "Assertions containing AuthnStatements require a Subject"); } if (!assertion.getAuthzDecisionStatements().isEmpty() && assertion.getSubject() == null) { throw new WSSecurityException(ErrorCode.FAILURE, "Assertions containing AuthzDecisionStatements require a Subject"); } if (assertion.getSubject() != null) { validateSubject(assertion.getSubject()); } }</code><technical_language>this converted a single emptiness check</technical_language>

Target:
protected void validateSubject(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getStatements())) { assertAttAuthzStatements(assertion); } if (CollectionUtils.isNotEmpty(assertion.getAuthnStatements()) && assertion.getSubject() == null) { throw new WSSecurityException(ErrorCode.FAILURE, "Assertions containing AuthnStatements require a Subject"); } if (CollectionUtils.isNotEmpty(assertion.getAuthzDecisionStatements()) && assertion.getSubject() == null) { throw new WSSecurityException(ErrorCode.FAILURE, "Assertions containing AuthzDecisionStatements require a Subject"); } if (assertion.getSubject() != null) { validateSubject(assertion.getSubject()); } }
Source:
<code>protected void onUIDNotExecuted(Exception e) { if (e.getMessage() == null) { return; } notificationService.addNotification(new ImmediateNotification(i18n.get("UIDNotExecuted"), e.getMessage(), Severity.ERROR, Collections.singletonList(new ReportAction(i18n, reportingService, e)))); <START> logger.error("UID.exe not executed", e); <END> }</code><technical_language>In case is exception a message, logged (because if(e.getMessage() == null) return; above). If move this log statement line of method solve this problem</technical_language>

Target:
protected void onUIDNotExecuted(Exception e) { logger.error("UID.exe not executed", e); if (e.getMessage() == null) { return; } notificationService.addNotification(new ImmediateNotification(i18n.get("UIDNotExecuted"), e.getMessage(), Severity.ERROR, Collections.singletonList(new ReportAction(i18n, reportingService, e)))); }
Source:
<code>public synchronized ArrayList<String> getNames() { if (names == null) { names = new ArrayList<String>(proto.getNameIdsCount()); for (int id : proto.getNameIdsList()) { <START> names.add("TestElement"); <END> } } return names; }</code><technical_language>this change</technical_language>

Target:
public synchronized ArrayList<String> getNames() { if (names == null) { names = new ArrayList<String>(proto.getNameIdsCount()); for (int id : proto.getNameIdsList()) { names.add(resources.getString(id)); } } return names; }
Source:
<code>private Database restoreDatabase(int id, String name, String encoding) throws SQLException { Statement s = connection.createStatement(); Database d = new Database(name, encoding); ResultSet tRS = s.executeQuery("SELECT * from `maxwell`.`tables` where database_id = " + id + " ORDER by id"); while (tRS.next()) { String tName = tRS.getString("name"); String tEncoding = tRS.getString("encoding"); String tPKs = null; try { tPKs = tRS.getString("pk"); } catch ( SQLException e ) <START> <END> int tID = tRS.getInt("id"); restoreTable(d, tName, tID, tEncoding, tPKs); } return d; }</code><technical_language>do maxwell starts is: migrate maxwell db, capture table pks, update current maxwell tables.. do need a try block? get NULL anyway</technical_language>

Target:
private Database restoreDatabase(int id, String name, String encoding) throws SQLException { Statement s = connection.createStatement(); Database d = new Database(name, encoding); ResultSet tRS = s.executeQuery("SELECT * from `maxwell`.`tables` where database_id = " + id + " ORDER by id"); while (tRS.next()) { String tName = tRS.getString("name"); String tEncoding = tRS.getString("encoding"); String tPKs = tRS.getString("pk"); int tID = tRS.getInt("id"); restoreTable(d, tName, tID, tEncoding, tPKs); } return d; }
Source:
<code>public void eventDispatched(final MIStoppedEvent e) { <START> if (fRunToLineActiveOperation != null) { <END> if (runToLineContinue(e)) { return; } } if (fStepInToSelectionActiveOperation != null) { evaluateStepIntoSelection(e); return; } broadcastStop(e); }</code><technical_language>put line in method. method a runToLine op is active, is check</technical_language>

Target:
public void eventDispatched(final MIStoppedEvent e) { if (processRunToLineStoppedEvent(e)) { return; } if (!processStepIntoSelection(e)) { broadcastStop(e); } }
Source:
<code>private boolean notRacyClean(long read) { <START> return read - lastModified > fsTimestampResolution.toMillis() * 11 / 10; <END> }</code><technical_language>PS 6. Again, 4_998_000ns truncated 4ms (so small, 5ms), 4 * 11 / 10 == 4, safety margin</technical_language>

Target:
private boolean notRacyClean(long read) { return read - lastModified > (fsTimestampResolution.toNanos() + 1) * 11 / 10_000_000; }
Source:
<code>private Mono<TransactionCoordinator> createTransactionCoordinator() { if (isDisposed()) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot create coordinator send link '%s' from a closed session.", TRANSACTION_LINK_NAME)))); } final TransactionCoordinator existing = transactionCoordinator.get(); if (existing != null) { logger.verbose("Coordinator[{}]: Returning existing transaction coordinator.", TRANSACTION_LINK_NAME); return Mono.just(existing); } <START> final String linkName = TRANSACTION_LINK_NAME; <END> return createProducer(linkName, linkName, new Coordinator(), retryOptions, null, false) .map(link -> { final TransactionCoordinator newCoordinator = new TransactionCoordinator(link, messageSerializer); if (transactionCoordinator.compareAndSet(null, newCoordinator)) { return newCoordinator; } else { return transactionCoordinator.get(); } }); }</code><technical_language>Is this needed? assigning a constant a local constant</technical_language>

Target:
private Mono<TransactionCoordinator> createTransactionCoordinator() { if (isDisposed()) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot create coordinator send link '%s' from a closed session.", TRANSACTION_LINK_NAME)))); } final TransactionCoordinator existing = transactionCoordinator.get(); if (existing != null) { logger.verbose("Coordinator[{}]: Returning existing transaction coordinator.", TRANSACTION_LINK_NAME); return Mono.just(existing); } return createProducer(TRANSACTION_LINK_NAME, TRANSACTION_LINK_NAME, new Coordinator(), retryOptions, null, false) .map(link -> { final TransactionCoordinator newCoordinator = new TransactionCoordinator(link, messageSerializer); if (transactionCoordinator.compareAndSet(null, newCoordinator)) { return newCoordinator; } else { return transactionCoordinator.get(); } }); }
Source:
<code>public static int[] intArrayFromString(String str) { <START> if (str.isEmpty()) return new int[0]; <END> String[] split = str.split(","); int[] result = new int[split.length]; for (int i = 0; i < split.length; i++) { result[i] = Integer.parseInt(split[i]); } return result; }</code><technical_language>Run formatter</technical_language>

Target:
public static int[] intArrayFromString(String str) { if (str.isEmpty()) { return new int[0]; } String[] split = str.split(","); int[] result = new int[split.length]; for (int i = 0; i < split.length; i++) { result[i] = Integer.parseInt(split[i]); } return result; }
Source:
<code>public String contents() { <START> return abstractContent; <END> }</code><technical_language>contents() is index search - title abstract</technical_language>

Target:
public String contents() { return title + "\n" + abstractContent; }
Source:
<code>public ComponentWsResponse component(ComponentWsRequest request) { GetRequest getRequest = new GetRequest(path(ACTION_COMPONENT)) .setParam(DEPRECATED_PARAM_COMPONENT_ID, request.getComponentId()) .setParam(PARAM_COMPONENT, request.getComponent()) .setParam(PARAM_ADDITIONAL_FIELDS, inlineMultipleParamValue(request.getAdditionalFields())) .setParam(PARAM_METRIC_KEYS, inlineMultipleParamValue(request.getMetricKeys())) <START> .setParam(PARAM_DEVELOPER_ID, request.getDeveloperId()) <END> .setParam(PARAM_DEVELOPER_KEY, request.getDeveloperKey()); return call(getRequest, ComponentWsResponse.parser()); }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove this of "getComponentId"; is deprecated. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public ComponentWsResponse component(ComponentWsRequest request) { GetRequest getRequest = new GetRequest(path(ACTION_COMPONENT)) .setParam(DEPRECATED_PARAM_COMPONENT_ID, request.getComponentId()) .setParam(DEPRECATED_PARAM_COMPONENT_KEY, request.getComponentKey()) .setParam(PARAM_COMPONENT, request.getComponent()) .setParam(PARAM_BRANCH, request.getBranch()) .setParam(PARAM_ADDITIONAL_FIELDS, inlineMultipleParamValue(request.getAdditionalFields())) .setParam(PARAM_METRIC_KEYS, inlineMultipleParamValue(request.getMetricKeys())) .setParam(PARAM_DEVELOPER_ID, request.getDeveloperId()) .setParam(PARAM_DEVELOPER_KEY, request.getDeveloperKey()); return call(getRequest, ComponentWsResponse.parser()); }
Source:
<code>private void scrollIntoView(WebElement e, WebDriver driver) { int eYCoord = e.getLocation().getY(); int eXCoord = e.getLocation().getX(); String id = e.getAttribute("id"); WebElement response = (WebElement) ((JavascriptExecutor)driver).executeScript(scrollJs, eYCoord, eXCoord, id); <START> if(response!=null && response.getAttribute("style").contains("bottom: 0px")){ <END> try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } }</code><technical_language>add custom handling for some elements scrolling logic, I suggest fully in javascript land java land. I speculate reason for split is sleeping in JS is tricky. some suggestion I consider cleaner: - Return JS a clear indicator hit a specific condition handle (so java code do inspect CSS attached). - provided this is a temporary condition, return true if scrolled false if hit special condition java code sleep _retry_ scrolling logic succeeds</technical_language>

Target:
private void scrollIntoView(WebElement e, WebDriver driver) { final int eYCoord = e.getLocation().getY(); final int eXCoord = e.getLocation().getX(); final String id = e.getAttribute("id"); final JavascriptExecutor executor = (JavascriptExecutor) driver; new Wait<>(Boolean.TRUE) .withTimeout(5, TimeUnit.SECONDS) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return (Boolean)executor.executeScript(scrollJs, eYCoord, eXCoord, id); } }) ; }
Source:
<code>public void testRebaseWithUnstagedTopicChange() throws Exception { writeTrashFile(FILE1, "file1"); git.add().addFilepattern(FILE1).call(); RevCommit commit = git.commit().setMessage("commit1").call(); createBranch(commit, "refs/heads/topic"); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("commit2").call(); checkoutBranch("refs/heads/master"); writeTrashFile(FILE1, "modified file1"); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("commit3").call(); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "unstaged file2"); RebaseResult result = git.rebase().setUpstream("refs/heads/master") .call(); assertEquals(result.getStatus(), Status.CONFLICTS); assertEquals(result.getConflicts().size(), 1); <START> assertEquals(result.getConflicts().get(0), "file2"); <END> }</code><technical_language>JUnit expected left actual right. Please swap avoid confusion debugging</technical_language>

Target:
public void testRebaseWithUnstagedTopicChange() throws Exception { writeTrashFile(FILE1, "file1"); git.add().addFilepattern(FILE1).call(); RevCommit commit = git.commit().setMessage("commit1").call(); createBranch(commit, "refs/heads/topic"); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("commit2").call(); checkoutBranch("refs/heads/master"); writeTrashFile(FILE1, "modified file1"); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("commit3").call(); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "unstaged file2"); RebaseResult result = git.rebase().setUpstream("refs/heads/master") .call(); assertEquals(Status.CONFLICTS, result.getStatus()); assertEquals(1, result.getConflicts().size()); assertEquals("file2", result.getConflicts().get(0)); }
Source:
<code>Datapoint poll(int pollerIndex) { final long now = clock.now(); final long step = Pollers.POLLING_INTERVALS[pollerIndex]; <START> final long stepTime = now / step; <END> rollCount(pollerIndex, now); final int prevPos = 2 * pollerIndex + PREVIOUS; final long value = data[prevPos].getAndSet(init); final long last = lastPollTime[pollerIndex].getAndSet(now); final long missed = (now - last) / step - 1; if (last / step == now / step) { REPOLLED_INTERVALS.increment(); return new Datapoint(now / step * step, value); } else if (last > 0L && missed > 0L) { MISSED_INTERVALS.increment(missed); return Datapoint.UNKNOWN; } else { POLLED_INTERVALS.increment(); return new Datapoint(now / step * step, value); } }</code><technical_language>This is longer used</technical_language>

Target:
Datapoint poll(int pollerIndex) { final long now = clock.now(); final long step = Pollers.POLLING_INTERVALS[pollerIndex]; rollCount(pollerIndex, now); final int prevPos = 2 * pollerIndex + PREVIOUS; final long value = data[prevPos].getAndSet(init); final long last = lastPollTime[pollerIndex].getAndSet(now); final long missed = (now - last) / step - 1; if (last / step == now / step) { REPOLLED_INTERVALS.increment(); return new Datapoint(now / step * step, value); } else if (last > 0L && missed > 0L) { MISSED_INTERVALS.increment(missed); return Datapoint.UNKNOWN; } else { POLLED_INTERVALS.increment(); return new Datapoint(now / step * step, value); } }
Source:
<code>public boolean applyDefaultNetworkRulesOnNic(final Connect conn, final String vmName, final Long vmId, final NicTO nic, boolean isFirstNic, boolean checkBeforeApply) { final List<String> nicSecIps = nic.getNicSecIps(); String secIpsStr; final StringBuilder sb = new StringBuilder(); if (nicSecIps != null) { for (final String ip : nicSecIps) { <START> sb.append(ip).append(";"); <END> } secIpsStr = sb.toString(); } else { secIpsStr = "0;"; } return defaultNetworkRules(conn, vmName, nic, vmId, secIpsStr, isFirstNic, checkBeforeApply); }</code><technical_language>separator</technical_language>

Target:
public boolean applyDefaultNetworkRulesOnNic(final Connect conn, final String vmName, final Long vmId, final NicTO nic, boolean isFirstNic, boolean checkBeforeApply) { final List<String> nicSecIps = nic.getNicSecIps(); String secIpsStr; final StringBuilder sb = new StringBuilder(); if (nicSecIps != null) { for (final String ip : nicSecIps) { sb.append(ip).append(SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR); } secIpsStr = sb.toString(); } else { secIpsStr = "0" + SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR; } return defaultNetworkRules(conn, vmName, nic, vmId, secIpsStr, isFirstNic, checkBeforeApply); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { IResource[] resources = LaunchUtils.getContext(HandlerUtil .getCurrentSelection(event)); final IQ7NamedElement[] elements = TestSuiteUtils.getElements(resources, false, false); List<String> disabledTags = null; if (elements.length == 1) { try { disabledTags = TagsUtil.extractTags(elements[0].getTags()); } catch (ModelException e) { e.printStackTrace(); } } if (disabledTags == null) { disabledTags = new ArrayList<String>(); } final SelectTagDialog dialog = new SelectTagDialog( HandlerUtil.getActiveShell(event), disabledTags); if (dialog.open() == SelectTagDialog.OK) { Job job = new Job(Messages.AddTagAction_Job) { @Override protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask(Messages.AddTagAction_Task, elements.length); try { <START> WriteAccessChecker writeAccessChecker = new WriteAccessChecker(); <END> if (!writeAccessChecker.makeResourceWritable(elements)) { return Status.CANCEL_STATUS; } } catch (CoreException e) { return e.getStatus(); } for (IQ7NamedElement element : elements) { if (monitor.isCanceled()) break; try { doAddTag(element, dialog.getResult(), dialog.getTagName(), monitor); } catch (ModelException e) { RcpttPlugin.log(e); } monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } return null; }</code><technical_language>default shell, dialog one</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IResource[] resources = LaunchUtils.getContext(HandlerUtil .getCurrentSelection(event)); final IQ7NamedElement[] elements = TestSuiteUtils.getElements(resources, false, false); List<String> disabledTags = null; if (elements.length == 1) { try { disabledTags = TagsUtil.extractTags(elements[0].getTags()); } catch (ModelException e) { e.printStackTrace(); } } if (disabledTags == null) { disabledTags = new ArrayList<String>(); } final SelectTagDialog dialog = new SelectTagDialog( HandlerUtil.getActiveShell(event), disabledTags); if (dialog.open() == SelectTagDialog.OK) { Job job = new Job(Messages.AddTagAction_Job) { @Override protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask(Messages.AddTagAction_Task, elements.length); try { WriteAccessChecker writeAccessChecker = new WriteAccessChecker(dialog.getShell()); if (!writeAccessChecker.makeResourceWritable(elements)) { return Status.CANCEL_STATUS; } } catch (CoreException e) { return e.getStatus(); } for (IQ7NamedElement element : elements) { if (monitor.isCanceled()) break; try { doAddTag(element, dialog.getResult(), dialog.getTagName(), monitor); } catch (ModelException e) { RcpttPlugin.log(e); } monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } return null; }
Source:
<code>public Injector getParentInjector() { ISuite suite = m_testContext.getSuite(); Injector injector = suite.getParentInjector(); if (injector == null) { <START> Module parentModule = GuiceHelper.getParentModule(m_testContext); <END> List<Module> modules = new ArrayList<>(); if (parentModule != null) { modules.add(parentModule); } injector = GuiceHelper.createInjector(m_testContext, modules); suite.setParentInjector(injector); } return injector; }</code><technical_language>do if add parentModule logic createInjector method</technical_language>

Target:
public Injector getParentInjector() { ISuite suite = m_testContext.getSuite(); Injector injector = suite.getParentInjector(); if (injector == null) { injector = GuiceHelper.createInjector(m_testContext, Collections.emptyList()); suite.setParentInjector(injector); } return injector; }
Source:
<code>public void flush() throws IOException, SQLException { File file = closeCurrentFile(); UploadAndCopyTask task = new UploadAndCopyTask(file, batchRows, s3KeyPrefix + UUID.randomUUID().toString()); <START> executorService.submit(task); <END> fileCount++; totalRows += batchRows; batchRows = 0; openNewFile(); }</code><technical_language>I error handling is necessary stop a bulk import job appropriately upload COPY failed. ExecutorService#submit() returns Future<Void> Future#get() throws ExecutionException if callable throws exception</technical_language>

Target:
public void flush() throws IOException, SQLException { File file = closeCurrentFile(); String s3KeyName = s3KeyPrefix + UUID.randomUUID().toString(); UploadTask uploadTask = new UploadTask(file, batchRows, s3KeyName); Future<Void> uploadFuture = executorService.submit(uploadTask); uploadAndCopyFutures.add(uploadFuture); CopyTask copyTask = new CopyTask(uploadFuture, s3KeyName); uploadAndCopyFutures.add(executorService.submit(copyTask)); fileCount++; totalRows += batchRows; batchRows = 0; openNewFile(); }