auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testFirstWantValidCapabilityNames() throws PackProtocolException { List<String> validNames = Arrays.asList( "c", "cap", "C", "CAP", "1", "1cap", "cap-64k_test", "-", "-cap", "_", "_cap", "agent=pack.age/Version", <START> "cap(this_is_valid!)"); <END> for (String capability: validNames) { FirstWant r = FirstWant.fromLine(makeFirstWantLine(capability)); assertEquals(r.getCapabilities().size(), 1); assertTrue(r.getCapabilities().contains(capability)); } }</code><technical_language>I this example is valid</technical_language>

Target:
public void testFirstWantValidCapabilityNames() throws PackProtocolException { List<String> validNames = Arrays.asList( "c", "cap", "C", "CAP", "1", "1cap", "cap-64k_test", "-", "-cap", "_", "_cap", "agent=pack.age/Version"); for (String capability: validNames) { FirstWant r = FirstWant.fromLine(makeFirstWantLine(capability)); assertEquals(r.getCapabilities().size(), 1); assertTrue(r.getCapabilities().contains(capability)); } }
Source:
<code>private void executeCoordinatorTasks() { applicationEventReceiver = new ApplicationEventReceiver(); applicationEventReceiver.setExecutorService(executorService); applicationEventReceiver.execute(); if (log.isInfoEnabled()) { log.info("Application event receiver thread started"); } clusterStatusTopicReceiver = new ClusterStatusTopicReceiver(); clusterStatusTopicReceiver.setExecutorService(executorService); clusterStatusTopicReceiver.execute(); if (log.isInfoEnabled()) { log.info("Cluster status event receiver thread started"); } instanceStatusTopicReceiver = new InstanceStatusTopicReceiver(); instanceStatusTopicReceiver.setExecutorService(executorService); instanceStatusTopicReceiver.execute(); if (log.isInfoEnabled()) { log.info("Instance status event receiver thread started"); } initializerTopicReceiver = new InitializerTopicReceiver(); initializerTopicReceiver.setExecutorService(executorService); initializerTopicReceiver.execute(); if (log.isInfoEnabled()) { log.info("Initializer event receiver thread started"); } if (log.isInfoEnabled()) { log.info("Scheduling topology synchronizer task"); } ComponentStartUpSynchronizer componentStartUpSynchronizer = ServiceReferenceHolder.getInstance().getComponentStartUpSynchronizer(); if (componentStartUpSynchronizer.isEnabled()) { componentStartUpSynchronizer.addEventListener(new ComponentActivationEventListener() { @Override public void activated(Component component) { <START> if (component == Component.CloudController) { <END> scheduleEventSynchronizers(); } } }); } else { scheduleEventSynchronizers(); } }</code><technical_language>reason for this change</technical_language>

Target:
private void executeCoordinatorTasks() { applicationEventReceiver = new ApplicationEventReceiver(); applicationEventReceiver.setExecutorService(executorService); applicationEventReceiver.execute(); if (log.isInfoEnabled()) { log.info("Application event receiver thread started"); } clusterStatusTopicReceiver = new ClusterStatusTopicReceiver(); clusterStatusTopicReceiver.setExecutorService(executorService); clusterStatusTopicReceiver.execute(); if (log.isInfoEnabled()) { log.info("Cluster status event receiver thread started"); } instanceStatusTopicReceiver = new InstanceStatusTopicReceiver(); instanceStatusTopicReceiver.setExecutorService(executorService); instanceStatusTopicReceiver.execute(); if (log.isInfoEnabled()) { log.info("Instance status event receiver thread started"); } initializerTopicReceiver = new InitializerTopicReceiver(); initializerTopicReceiver.setExecutorService(executorService); initializerTopicReceiver.execute(); if (log.isInfoEnabled()) { log.info("Initializer event receiver thread started"); } if (log.isInfoEnabled()) { log.info("Scheduling topology synchronizer task"); } Runnable topologySynchronizer = new TopologyEventSynchronizer(); scheduler.scheduleAtFixedRate(topologySynchronizer, 0, 1, TimeUnit.MINUTES); }
Source:
<code>private static NamedDataSchema checkForErrorsAndGetTopLevelSchema( File file, String schemaFullname, PegasusSchemaParser parser, StringBuilder errorMessages) { StringBuilder errorMessageBuilder = parser.errorMessageBuilder(); if (errorMessageBuilder.length() > 0) { errorMessages.append("Failed to parse schema: ") .append(file.getAbsolutePath()) .append("\nfullname: ") .append(schemaFullname) .append("\nerrors: ") .append(errorMessageBuilder.toString()) .append("\n"); return null; } List<DataSchema> topLevelSchemas = parser.topLevelDataSchemas(); if (topLevelSchemas.size() != 1) { errorMessages.append("Expected one top level schema for: ") .append(file.getAbsolutePath()) .append(" but got ") .append(topLevelSchemas.size()) .append(" schemas.") .append("\n"); return null; } DataSchema sourceSchema = topLevelSchemas.get(0); <START> if (!(sourceSchema instanceof NamedDataSchema)) <END> { errorMessages.append("Parsed top-level schema does not match the schema file name. File: ") .append(file.getAbsolutePath()) .append("\n parsedSchemaName: ") .append(sourceSchema.getUnionMemberKey()) .append("\n"); return null; } return (NamedDataSchema) sourceSchema; }</code><technical_language>loosen this check ignore incorrect filenames</technical_language>

Target:
private static NamedDataSchema checkForErrorsAndGetTopLevelSchema( File file, String schemaFullname, PegasusSchemaParser parser, StringBuilder errorMessages) { StringBuilder errorMessageBuilder = parser.errorMessageBuilder(); if (errorMessageBuilder.length() > 0) { errorMessages.append("Failed to parse schema: ") .append(file.getAbsolutePath()) .append("\nfullname: ") .append(schemaFullname) .append("\nerrors: ") .append(errorMessageBuilder.toString()) .append("\n"); return null; } List<DataSchema> topLevelSchemas = parser.topLevelDataSchemas(); if (topLevelSchemas.size() != 1) { errorMessages.append("Expected one top level schema for: ") .append(file.getAbsolutePath()) .append(" but got ") .append(topLevelSchemas.size()) .append(" schemas.") .append("\n"); return null; } DataSchema sourceSchema = topLevelSchemas.get(0); if (!(sourceSchema instanceof NamedDataSchema) || !((NamedDataSchema) sourceSchema).getFullName().equals(schemaFullname)) { errorMessages.append("Parsed top-level schema does not match the schema file name. File: ") .append(file.getAbsolutePath()) .append("\n parsedSchemaName: ") .append(sourceSchema.getUnionMemberKey()) .append("\n"); return null; } return (NamedDataSchema) sourceSchema; }
Source:
<code>public void run() { try { if(ESReindexationProcessStatus.inFullReindexation()) return; } catch (DotDataException e2) { Logger.warn(this, "can't determine if we're in full reindex",e2); } int minutes = Config.getIntProperty("DIST_REINDEX_JOURNAL_CLEANUP_MINUTES", 30); try { Logger.debug(this, "About to delete dist_reindex_journal entries older than "+ minutes +" minute(s)"); HibernateUtil.startTransaction(); APILocator.getDistributedJournalAPI().distReindexJournalCleanup(minutes, false, true, DateType.MINUTE); HibernateUtil.closeAndCommitTransaction(); } catch (Exception e) { Logger.error(this, "Error ocurred while trying to delete dist_reindex_journal entries older than "+ minutes +" minute(s)", e); try { HibernateUtil.rollbackTransaction(); } catch (DotHibernateException e1) { Logger.error(this, e1.getMessage(), e1); } } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.error(this, e.getMessage(), e); <START> } <END> } }</code><technical_language>Undo</technical_language>

Target:
public void run() { try { if(ESReindexationProcessStatus.inFullReindexation()) return; } catch (DotDataException e2) { Logger.warn(this, "can't determine if we're in full reindex",e2); } int minutes = Config.getIntProperty("DIST_REINDEX_JOURNAL_CLEANUP_MINUTES", 30); try { Logger.debug(this, "About to delete dist_reindex_journal entries older than "+ minutes +" minute(s)"); HibernateUtil.startTransaction(); APILocator.getDistributedJournalAPI().distReindexJournalCleanup(minutes, false, true, DateType.MINUTE); HibernateUtil.closeAndCommitTransaction(); } catch (Exception e) { Logger.error(this, "Error ocurred while trying to delete dist_reindex_journal entries older than "+ minutes +" minute(s)", e); try { HibernateUtil.rollbackTransaction(); } catch (DotHibernateException e1) { Logger.error(this, e1.getMessage(), e1); } } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.error(this, e.getMessage(), e); } DbConnectionFactory.closeConnection(); } }
Source:
<code>public Object[] factory() { <START> return Arrays.stream(StorageType.values()) <END> .flatMap(type -> Stream.builder() .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(false)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(false)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.SCATTERED_SYNC).transactional(false)) .build() ).toArray(); }</code><technical_language>1, this is eviction test a storage test</technical_language>

Target:
public Object[] factory() { return Arrays.stream(StorageType.values()) .flatMap(type -> Stream.builder() .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(false)) .add(new ClusterExpirationFunctionalTest().storageType(type).cacheMode(CacheMode.SCATTERED_SYNC).transactional(false)) .build() ).toArray(); }
Source:
<code>public InvalidOperatorNegationException() { <START> super(HttpStatus.SC_FORBIDDEN, "Invalid Usage of NOT in FilterExpression."); <END> }</code><technical_language>500 error</technical_language>

Target:
public InvalidOperatorNegationException() { super(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Invalid usage of NOT in FilterExpression."); }
Source:
<code>public BitVectorImpl(long initialSize) { if (initialSize < 0) { throw new IllegalArgumentException("Wrong bit vector size '" + initialSize + "'. Bit vector size must be non-negative."); } this.array = new long[getMinimumArraySize(initialSize)]; <START> this.size = 0; <END> }</code><technical_language>is some confusion naming here. If I construct a parameter called "initialSize", I expect return this asking for size(). "size" for concepts. "initaliSize" "initialCapacity"? In this case, other need renamed, e.g., MINIMUM_ARRAY_SIZE MINIMUM_ARRAY_CAPACITY, getMinimumArraySize() getMinimumArrayCapacity() ..</technical_language>

Target:
public BitVectorImpl(long initialSize) { if (initialSize < 0) { throw new IllegalArgumentException("Wrong bit vector size '" + initialSize + "'. Bit vector size must be non-negative."); } this.arrayOfBits = new long[getMinimumArraySize(initialSize)]; this.size = initialSize; }
Source:
<code><START> public void testDistributedSQLForOnlyVALUEIterationType() throws InterruptedException { <END> dsDistributedMap4.put(1, new User(1, "TestName1", "TestSurname1", 10)); dsDistributedMap4.put(2, new User(2, "TestName2", "TestSurname2", 20)); dsDistributedMap4.put(3, new User(3, "TestName3", "TestSurname3", 30)); dsDistributedMap4.put(4, new User(4, "TestName4", "TestSurname4", 40)); dsDistributedMap4.put(5, new User(5, "TestName5", "TestSurname5", 50)); Message<?> msg = null; for (int i = 0; i < 10; i++) { msg = dsMapChannel4.receive(); if (((Collection) msg.getPayload()).iterator().hasNext()) { break; } Thread.sleep(1_000); } Assert.assertNotNull(msg); Assert.assertNotNull(msg.getPayload()); Assert.assertTrue(msg.getPayload() instanceof Collection); Assert.assertEquals(3, ((User) (((Collection) msg.getPayload()).iterator().next())).getId()); Assert.assertEquals("TestName3", ((User) (((Collection) msg.getPayload()).iterator().next())).getName()); Assert.assertEquals("TestSurname3", ((User) (((Collection) msg.getPayload()).iterator().next())).getSurname()); }</code><technical_language>Duration pass 4.002s Please, a tests faster. metrics: org.springframework.integration.hazelcast.inbound 29 0 0 7.319s 100% org.springframework.integration.hazelcast.outbound 8 0 0 0.047s 100%</technical_language>

Target:
public void testDistributedSQLForOnlyVALUEIterationType() throws InterruptedException { dsDistributedMap4.put(1, new HazelcastIntegrationTestUser(1, "TestName1", "TestSurname1", 10)); dsDistributedMap4.put(2, new HazelcastIntegrationTestUser(2, "TestName2", "TestSurname2", 20)); dsDistributedMap4.put(3, new HazelcastIntegrationTestUser(3, "TestName3", "TestSurname3", 30)); dsDistributedMap4.put(4, new HazelcastIntegrationTestUser(4, "TestName4", "TestSurname4", 40)); dsDistributedMap4.put(5, new HazelcastIntegrationTestUser(5, "TestName5", "TestSurname5", 50)); Message<?> msg = dsMapChannel4.receive(2_000); Assert.assertNotNull(msg); Assert.assertNotNull(msg.getPayload()); Assert.assertTrue(msg.getPayload() instanceof Collection); Assert.assertEquals(3, ((HazelcastIntegrationTestUser) (((Collection<?>) msg.getPayload()).iterator().next())).getId()); Assert.assertEquals("TestName3", ((HazelcastIntegrationTestUser) (((Collection<?>) msg.getPayload()).iterator().next())).getName()); Assert.assertEquals("TestSurname3", ((HazelcastIntegrationTestUser) (((Collection<?>) msg.getPayload()).iterator().next())).getSurname()); }
Source:
<code>static public void checkInterfaceMethods(final HaxeClassModel clazz, final HaxeClassReferenceModel intReference, final AnnotationHolder holder) { final List<HaxeMethodModel> missingMethods = new ArrayList<HaxeMethodModel>(); final List<String> missingMethodsNames = new ArrayList<String>(); if (intReference.getHaxeClass() != null) { for (HaxeMethodModel method : intReference.getHaxeClass().getMethods()) { if (!method.isStatic()) { if (!clazz.hasMethodSelf(method.getName())) { missingMethods.add(method); missingMethodsNames.add(method.getName()); } } } } if (missingMethods.size() > 0) { Annotation annotation = holder.createErrorAnnotation(intReference.getPsi(), "Not implemented methods: " + StringUtils.join(missingMethodsNames, ", ")); annotation.registerFix(new HaxeSemanticIntentionAction("Implement methods") { @Override public void run() { <START> clazz.addMethodsFromPrototype(missingMethods); <END> } }); } }</code><technical_language>clazz.addMethodsFromPrototype(..) This is I pop UI, simply adding implementations class</technical_language>

Target:
static public void checkInterfaceMethods(final HaxeClassModel clazz, final HaxeClassReferenceModel intReference, final AnnotationHolder holder) { final List<HaxeMethodModel> missingMethods = new ArrayList<HaxeMethodModel>(); final List<String> missingMethodsNames = new ArrayList<String>(); if (intReference.getHaxeClass() != null) { for (HaxeMethodModel method : intReference.getHaxeClass().getMethods()) { if (!method.isStatic()) { if (!clazz.hasMethodSelf(method.getName())) { missingMethods.add(method); missingMethodsNames.add(method.getName()); } } } } if (missingMethods.size() > 0) { Annotation annotation = holder.createErrorAnnotation(intReference.getPsi(), "Not implemented methods: " + StringUtils.join(missingMethodsNames, ", ")); annotation.registerFix(new HaxeFixer("Implement methods") { @Override public void run() { clazz.addMethodsFromPrototype(missingMethods); } }); } }
Source:
<code><START> public void waitForMessage() { <END> try { latch.await(); } catch (final InterruptedException e) { throw new RuntimeException("Unexpected exception", e); } latch = new CountDownLatch(1); }</code><technical_language>this method public</technical_language>

Target:
void waitForMessage() { try { latch.await(); } catch (final InterruptedException e) { throw new RuntimeException("Unexpected exception", e); } latch = new CountDownLatch(1); }
Source:
<code>private void checkIndex(int index) { if (index < 0) { throw new IAE("Index[%s] < 0", index); } if (index >= size) { <START> throw new IAE(StringUtils.safeFormat("Index[%s] >= size[%s]", index, size)); <END> } }</code><technical_language>need wrap safeFormat</technical_language>

Target:
private void checkIndex(int index) { if (index < 0) { throw new IAE("Index[%s] < 0", index); } if (index >= size) { throw new IAE("Index[%d] >= size[%d]", index, size); } }
Source:
<code>void removeContent(PathAddress address, List<byte[]> hashes) { for (byte[] hash : hashes) { try { <START> if (fileRepository != null) { <END> if(contentRepository != null && contentRepository.hasContent(hash)) { contentRepository.removeContent(ModelContentReference.fromModelAddress(address, hash)); } else { fileRepository.deleteDeployment(ModelContentReference.fromModelAddress(address, hash)); } } } catch (Exception e) { DEPLOYMENT_LOGGER.debugf(e, "Exception occurred removing %s", Arrays.asList(hash)); } } }</code><technical_language>This is a pre-existing issue, fileRepository null. assert a L140</technical_language>

Target:
void removeContent(PathAddress address, List<byte[]> hashes) { for (byte[] hash : hashes) { try { if (contentRepository.hasContent(hash)) { contentRepository.removeContent(ModelContentReference.fromModelAddress(address, hash)); } else { fileRepository.deleteDeployment(ModelContentReference.fromModelAddress(address, hash)); } } catch (Exception e) { DEPLOYMENT_LOGGER.debugf(e, "Exception occurred removing %s", Arrays.asList(hash)); } } }
Source:
<code>public void setupServer() throws Exception { Logging.initialize(); server = new TestingPrestoServer( true, <START> ImmutableMap.of("testing-warning-collector.add-warnings", "true", <END> "testing-warning-collector.preloaded-warnings", String.valueOf(PRELOADED_WARNINGS)), null, null, new SqlParserOptions(), ImmutableList.of()); server.installPlugin(new BlackHolePlugin()); server.createCatalog("blackhole", "blackhole"); }</code><technical_language>ImmutableMap.builder() this cleaner</technical_language>

Target:
public void setupServer() throws Exception { server = new TestingPrestoServer( true, ImmutableMap.<String, String>builder() .put("testing-warning-collector.add-warnings", "true") .put("testing-warning-collector.preloaded-warnings", String.valueOf(PRELOADED_WARNINGS)) .build(), null, null, new SqlParserOptions(), ImmutableList.of()); server.installPlugin(new TpchPlugin()); server.createCatalog("tpch", "tpch"); server.installPlugin(new BlackHolePlugin()); server.createCatalog("blackhole", "blackhole"); waitForNodeRefresh(server); }
Source:
<code>private void logExecutorState() { ExecutorStateEvent executorStateEvent = new ExecutorStateEvent(executorService, leaseCoordinator); <START> DiagnosticEventHandler debugHandler = new DiagnosticEventHandler() { <END> @Override public void visit(ExecutorStateEvent event) { log.debug(event.message()); } @Override public void visit(RejectedTaskEvent event) { } }; if (System.currentTimeMillis() >= nextExecutorLogTime) { executorStateEvent.accept(diagnosticEventHandler); nextExecutorLogTime = System.currentTimeMillis() + executorLogIntervalMillis; } else { executorStateEvent.accept(debugHandler); } }</code><technical_language>move this logic DiagnosticEventLogger. class responsible for logging details. DiagnosticEventLogger deciding log debug/info frequency</technical_language>

Target:
private void logExecutorState() { ExecutorStateEvent executorStateEvent = diagnosticEventFactory.executorStateEvent(executorService, leaseCoordinator); executorStateEvent.accept(diagnosticEventHandler); }
Source:
<code>public void handle(Request wsRequest, Response wsResponse) { userSession.checkIsSystemAdministrator(); String taskId = wsRequest.mandatoryParam(PARAM_TASK_ID); try (DbSession dbSession = dbClient.openSession(false)) { Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskId); queueDto.ifPresent(dto -> { queue.cancel(dbSession, dto); <START> }); <END> } wsResponse.noContent(); }</code><technical_language>minor: inlined</technical_language>

Target:
public void handle(Request wsRequest, Response wsResponse) { String taskId = wsRequest.mandatoryParam(PARAM_TASK_ID); try (DbSession dbSession = dbClient.openSession(false)) { Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskId); queueDto.ifPresent(dto -> { checkPermission(dbSession, dto); queue.cancel(dbSession, dto); }); } wsResponse.noContent(); }
Source:
<code>private boolean runningTaskMustBeResetToPending(InternalTask task, RMProxy rmProxy) { boolean resetToPending; if (rmProxy != null) { NodeSet nodes = task.getExecuterInformation().getNodes(); boolean taskNodesKnownByRM = rmProxy.areNodesKnown(nodes); if (taskNodesKnownByRM) { TaskLauncher launcher = task.getExecuterInformation().getLauncher(); logger.debug("Checking whether task launcher has called its doTask method: " + launcher.getDoTaskInvoked()); if (launcher.getDoTaskInvoked()) { logger.info("Recover running task " + task.getId() + " (" + task.getName() + ") successfully with task launcher " + launcher); resetToPending = false; } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because its task launcher has not started to execute the task"); <START> resetToPending = true; <END> } } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because the task's node is not known by the resource manager"); resetToPending = true; } } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because the resource manager is not reachable"); resetToPending = true; } return resetToPending; }</code><technical_language>I suppose need do task launcher. rm takes care of (kill) release node</technical_language>

Target:
private boolean runningTaskMustBeResetToPending(InternalTask task, RMProxy rmProxy) { boolean resetToPending; if (rmProxy != null) { NodeSet nodes = task.getExecuterInformation().getNodes(); boolean taskNodesKnownByRM = rmProxy.areNodesKnown(nodes); if (taskNodesKnownByRM) { TaskLauncher launcher = task.getExecuterInformation().getLauncher(); logger.debug("Checking whether task launcher has called its doTask method: " + launcher.isTaskStarted()); if (launcher.isTaskStarted()) { logger.info("Recover running task " + task.getId() + " (" + task.getName() + ") successfully with task launcher " + launcher); resetToPending = false; } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because its task launcher has not started to execute the task"); resetToPending = true; } } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because the task's node is not known by the resource manager"); resetToPending = true; } } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because the resource manager is not reachable"); resetToPending = true; } return resetToPending; }
Source:
<code>public void testGetAllForNetwork() { List<VDSGroup> result = dao.getAllForNetwork(FixturesTool.NETWORK_ENGINE_2); <START> assertEquals(existingVdsGroups, result); <END> }</code><technical_language>This test fail if returned list differs in order expected list contains elements. I a loop expected results if contained in returned collection</technical_language>

Target:
public void testGetAllForNetwork() { List<VDSGroup> result = dao.getAllForNetwork(FixturesTool.NETWORK_ENGINE_2); assertEqualsIgnoreOrder(existingVdsGroups, result); }
Source:
<code>private static Properties loadBuildProperties() { Properties prop = new Properties(); try { <START> prop.load(Update.class.getClassLoader().getResourceAsStream("git.properties")); <END> } catch (IOException e) { log.warn("Failed to load properties file"); } return prop; }</code><technical_language>stream closed</technical_language>

Target:
private static Properties loadBuildProperties() { Properties prop = new Properties(); try(InputStream instream = Update.class.getClassLoader().getResourceAsStream("git.properties")) { prop.load(instream); } catch (IOException e) { log.warn("Failed to load properties file"); } return prop; }
Source:
<code>private Runnable _confirmSignIn(final Map<String, String> signInChallengeResponse, final Callback<SignInResult> callback) { return new Runnable() { @Override public void run() { if (signInState == null) { <START> callback.onError(new IllegalStateException("Cannot call confirmMFA(Map<String, String>, Callback) " + <END> "without initiating sign-in. This call is used for CUSTOM_CHALLENGE sign-in state.")); return; } final CognitoIdentityProviderContinuation detectedContinuation; switch (signInState) { case SMS_MFA: case NEW_PASSWORD_REQUIRED: callback.onError(new IllegalStateException( "Please use confirmSignIn(String, Callback) " + "for SMS_MFA and NEW_PASSWORD_REQUIRED challenges")); case CUSTOM_CHALLENGE: for (final String key : signInChallengeResponse.keySet()) { signInChallengeContinuation.setChallengeResponse(key, signInChallengeResponse.get(key)); } detectedContinuation = signInChallengeContinuation; signInCallback = new InternalCallback<SignInResult>(callback); break; case DONE: detectedContinuation = null; Log.d(TAG, "confirmSignIn called after signIn has succeeded"); break; default: callback.onError(new IllegalStateException("confirmSignIn called on unsupported operation, " + "please file a feature request")); return; } if (detectedContinuation != null) { detectedContinuation.continueTask(); } } }; }</code><technical_language>Do confirmSignIn confirmMFA</technical_language>

Target:
private Runnable _confirmSignIn(final Map<String, String> signInChallengeResponse, final Callback<SignInResult> callback) { return new Runnable() { @Override public void run() { if (signInState == null) { callback.onError(new IllegalStateException("Cannot call confirmSignIn(Map<String, String>, Callback) " + "without initiating sign-in. This call is used for CUSTOM_CHALLENGE sign-in state.")); return; } final CognitoIdentityProviderContinuation detectedContinuation; switch (signInState) { case SMS_MFA: case NEW_PASSWORD_REQUIRED: callback.onError(new IllegalStateException( "Please use confirmSignIn(String, Callback) " + "for SMS_MFA and NEW_PASSWORD_REQUIRED challenges")); case CUSTOM_CHALLENGE: for (final String key : signInChallengeResponse.keySet()) { signInChallengeContinuation.setChallengeResponse(key, signInChallengeResponse.get(key)); } detectedContinuation = signInChallengeContinuation; signInCallback = new InternalCallback<SignInResult>(callback); break; case DONE: detectedContinuation = null; callback.onError(new IllegalStateException("confirmSignIn called after signIn has succeeded")); break; default: callback.onError(new IllegalStateException("confirmSignIn called on unsupported operation, " + "please file a feature request")); return; } if (detectedContinuation != null) { detectedContinuation.continueTask(); } } }; }
Source:
<code>private void setAllApprovals(ChangeData cd, Map<String, LabelInfo> labels) throws OrmException { Set<Account.Id> allUsers = Sets.newHashSet(); for (PatchSetApproval psa : cd.allApprovals(db)) { allUsers.add(psa.getAccountId()); } Multimap<Account.Id, PatchSetApproval> current = HashMultimap.create(); for (PatchSetApproval a : cd.currentApprovals(db)) { current.put(a.getAccountId(), a); } <START> allUsers.addAll(current.keySet()); <END> for (Account.Id accountId : allUsers) { IdentifiedUser user = userFactory.create(accountId); ChangeControl ctl = control(cd).forUser(user); Map<String, ApprovalInfo> byLabel = Maps.newHashMapWithExpectedSize(labels.size()); for (String name : labels.keySet()) { ApprovalInfo ai = new ApprovalInfo(accountId); accountLoader.put(ai); byLabel.put(name, ai); labels.get(name).addApproval(ai); } for (PatchSetApproval psa : current.get(accountId)) { LabelType lt = labelTypes.byId(psa.getCategoryId().get()); if (lt == null) { continue; } ApprovalInfo info = byLabel.get(lt.getName()); if (info == null) { continue; } PermissionRange range = ctl.getRange(lt.getName()); info.value = range != null ? range.squash(psa.getValue()) : 0; } } }</code><technical_language>entries in currentApprovals in allApprovals</technical_language>

Target:
private void setAllApprovals(ChangeData cd, Map<String, LabelInfo> labels) throws OrmException { ChangeControl baseCtrl = control(cd); if (baseCtrl == null) { return; } Set<Account.Id> allUsers = Sets.newHashSet(); for (PatchSetApproval psa : cd.allApprovals(db)) { allUsers.add(psa.getAccountId()); } Multimap<Account.Id, PatchSetApproval> current = HashMultimap.create(); for (PatchSetApproval a : cd.currentApprovals(db)) { current.put(a.getAccountId(), a); } for (Account.Id accountId : allUsers) { IdentifiedUser user = userFactory.create(accountId); ChangeControl ctl = baseCtrl.forUser(user); Map<String, ApprovalInfo> byLabel = Maps.newHashMapWithExpectedSize(labels.size()); for (String name : labels.keySet()) { ApprovalInfo ai = approvalInfo(accountId, 0); byLabel.put(name, ai); labels.get(name).addApproval(ai); } for (PatchSetApproval psa : current.get(accountId)) { LabelType lt = labelTypes.byId(psa.getCategoryId().get()); if (lt == null) { continue; } ApprovalInfo info = byLabel.get(lt.getName()); if (info == null) { continue; } PermissionRange range = ctl.getRange(lt.getName()); info.value = range != null ? range.squash(psa.getValue()) : 0; } } }
Source:
<code>public void propagateExceptionToGlobalExceptionHandler() { final Object LOCK = new Object(); Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { synchronized (LOCK) { propagatedExceptionToGlobalExceptionHandler = true; LOCK.notify(); } } }); propagatedExceptionToGlobalExceptionHandler = false; activity.backgroundThrowException(); waitOn(LOCK, 2000); Assert.assertTrue("Exception should have been caught in the DefaultUncaughtExceptionHandler during @Background call.", propagatedExceptionToGlobalExceptionHandler); <START> Thread.setDefaultUncaughtExceptionHandler(handler); <END> }</code><technical_language>Sorry, in case of exception 325 345 lines (e.g. assertion fails) handler restored. @Before @After suits for that</technical_language>

Target:
public void propagateExceptionToGlobalExceptionHandler() { final Object LOCK = new Object(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { synchronized (LOCK) { propagatedExceptionToGlobalExceptionHandler = true; LOCK.notify(); } } }); propagatedExceptionToGlobalExceptionHandler = false; activity.backgroundThrowException(); waitOn(LOCK, 2000); Assert.assertTrue("Exception should have been caught in the DefaultUncaughtExceptionHandler during @Background call.", propagatedExceptionToGlobalExceptionHandler); }
Source:
<code>EmbeddedCacheManager smallCacheManager() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.eviction().maxEntries(4); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder); <START> System.out.println("Create small cache manager " + cm); <END> return cm; }</code><technical_language>log instead of System.out.println</technical_language>

Target:
EmbeddedCacheManager smallCacheManager() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.eviction().maxEntries(4); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder); log.tracef("Create small cache manager %s", cm); return cm; }
Source:
<code>public String getImplementationBeanName() { <START> return configurationSource.getBeanNameGenerator().generateBeanName(definition) + getImplementationPostfix(); <END> }</code><technical_language>Assign generator local variable. Avoid double spaces +</technical_language>

Target:
public String getImplementationBeanName() { return configurationSource.generateBeanName(definition) + configurationSource.getRepositoryImplementationPostfix().orElse("Impl"); }
Source:
<code>public void shouldGetDiagnosisByUuid() { <START> String uuid = "4e663d66-6b78-11e0-93c3-18a905e044dc"; <END> int diagnosisId = 1; Diagnosis diagnosis = diagnosisDAO.getDiagnosisByUuid(uuid); assertEquals(diagnosisId, (int) diagnosis.getId()); }</code><technical_language>get rid of variables if in place</technical_language>

Target:
public void shouldGetDiagnosisByUuid() { Diagnosis diagnosis = diagnosisDAO.getDiagnosisByUuid("4e663d66-6b78-11e0-93c3-18a905e044dc"); assertEquals(1, (int) diagnosis.getId()); }
Source:
<code>public URI toURI() throws IOException, InterruptedException { return act(new SecureFileCallable<URI>() { private static final long serialVersionUID = 1L; public URI invoke(File f, VirtualChannel channel) { <START> return f.toPath().toUri(); <END> } }); }</code><technical_language>is strong benefit. However, in case risk of a new InvalidPathException, thrown toPath()</technical_language>

Target:
public URI toURI() throws IOException, InterruptedException { return act(new SecureFileCallable<URI>() { private static final long serialVersionUID = 1L; public URI invoke(File f, VirtualChannel channel) { return f.toURI(); } }); }
Source:
<code>private MessageProcessor getMessageProcessor(final String jmsType) throws JMSException { final MessageProcessor messageProcessor = this.messageProcessors.get(this.getMessageType(jmsType)); if (messageProcessor == null) { <START> LOGGER.error("No message processor found for message type: {}", jmsType); <END> throw new JMSException("Message processor not configured"); } return messageProcessor; }</code><technical_language>include messageProcessorMapName in error remove messageProcessorMapName is for logging</technical_language>

Target:
private MessageProcessor getMessageProcessor(final String jmsType) throws JMSException { final MessageProcessor messageProcessor = this.messageProcessors.get(this.getMessageType(jmsType)); if (messageProcessor == null) { LOGGER.error("No message processor found in for message type: {}", this.messageProcessorMapName, jmsType); throw new JMSException("Message processor not configured"); } return messageProcessor; }
Source:
<code><START> StepSprite(BoardView1 boardView1, final MoveStep step, <END> boolean isLastStep) { super(boardView1); this.step = step; this.isLastStep = isLastStep; bounds = new Rectangle(bv.getHexLocation(step.getPosition()), bv.hex_size); image = null; baseScaleImage = null; }</code><technical_language>suggestion public StepSprite(BoardView1 boardView1, final MoveStep step,</technical_language>

Target:
public StepSprite(BoardView1 boardView1, final MoveStep step, boolean isLastStep) { super(boardView1); this.step = step; this.isLastStep = isLastStep; bounds = new Rectangle(bv.getHexLocation(step.getPosition()), bv.hex_size); image = null; baseScaleImage = null; }
Source:
<code>public Object execute() throws Exception { transactionOperations.execute(status -> { try { final OnmsNode onmsNode = this.nodeDao.get(this.node); if (onmsNode == null) { <START> System.out.printf("Cannot find node with ID/FS:FID=%s.\n", this.node); <END> return null; } final Scope nodeScope = this.entityScopeProvider.getScopeForNode(onmsNode.getId()); final Scope interfaceScope = this.entityScopeProvider.getScopeForInterface(onmsNode.getId(), this.interfaceAddress); final Scope serviceScope = this.entityScopeProvider.getScopeForService(onmsNode.getId(), InetAddressUtils.getInetAddress(this.interfaceAddress), this.serviceName); System.out.printf("---\nMeta-Data for node (id=%d)\n", onmsNode.getId()); printScope(nodeScope); if (this.interfaceAddress != null) { System.out.printf("---\nMeta-Data for interface (ipAddress=%s):\n", this.interfaceAddress); printScope(interfaceScope); } if (this.serviceName != null) { System.out.printf("---\nMeta-Data for service (name=%s):\n", this.serviceName); printScope(serviceScope); } System.out.printf("---\n"); if (!Strings.isNullOrEmpty(this.expression)) { final String result = Interpolator.interpolate(this.expression, new FallbackScope(nodeScope, interfaceScope, serviceScope)); System.out.printf("Input: '%s'\nOutput: '%s'\n", this.expression, result); } return null; } catch (final Exception e) { e.printStackTrace(); } return null; }); return null; }</code><technical_language>This is misleading. onmsNode is node object, this.node is a node id a FS:FID. In graph world I term nodeRef nodeReference id FS:FID. I suggest terminology well, more clear</technical_language>

Target:
public Object execute() throws Exception { sessionUtils.withReadOnlyTransaction(() -> { try { final OnmsNode onmsNode = this.nodeDao.get(this.nodeRef); if (onmsNode == null) { System.out.printf("Cannot find node with ID/FS:FID=%s.\n", this.nodeRef); return null; } final Scope nodeScope = this.entityScopeProvider.getScopeForNode(onmsNode.getId()); final Scope interfaceScope = this.entityScopeProvider.getScopeForInterface(onmsNode.getId(), this.interfaceAddress); final Scope serviceScope = this.entityScopeProvider.getScopeForService(onmsNode.getId(), InetAddressUtils.getInetAddress(this.interfaceAddress), this.serviceName); System.out.printf("---\nMeta-Data for node (id=%d)\n", onmsNode.getId()); printScope(nodeScope); if (this.interfaceAddress != null) { System.out.printf("---\nMeta-Data for interface (ipAddress=%s):\n", this.interfaceAddress); printScope(interfaceScope); } if (this.serviceName != null) { System.out.printf("---\nMeta-Data for service (name=%s):\n", this.serviceName); printScope(serviceScope); } System.out.printf("---\n"); if (!Strings.isNullOrEmpty(this.expression)) { final String result = Interpolator.interpolate(this.expression, new FallbackScope(nodeScope, interfaceScope, serviceScope)); System.out.printf("Input: '%s'\nOutput: '%s'\n", this.expression, result); } return null; } catch (final Exception e) { e.printStackTrace(); } return null; }); return null; }
Source:
<code>private QueryTemplate( String template, String name, Iterable<String> values, Charset charset, CollectionFormat collectionFormat) { super(template, false, true, true, charset); <START> this.name = new Template(name, false, true, false, charset); <END> this.collectionFormat = collectionFormat; this.values = StreamSupport.stream(values.spliterator(), false) .filter(Util::isNotBlank) .collect(Collectors.toList()); if (this.values.isEmpty()) { this.pure = true; } }</code><technical_language>some point replace this booleans enums communicate is on.. new Template(name, Resolution.REQUIRED, Encoding.REQUIRED, Encoding.DISABLED, charset); a problem for today</technical_language>

Target:
private QueryTemplate( String template, String name, Iterable<String> values, Charset charset, CollectionFormat collectionFormat) { super(template, ExpansionOptions.REQUIRED, EncodingOptions.REQUIRED, true, charset); this.name = new Template(name, ExpansionOptions.ALLOW_UNRESOLVED, EncodingOptions.REQUIRED, false, charset); this.collectionFormat = collectionFormat; this.values = StreamSupport.stream(values.spliterator(), false) .filter(Util::isNotBlank) .collect(Collectors.toList()); if (this.values.isEmpty()) { this.pure = true; } }
Source:
<code>public void requestInterstitialAd(Context context, MediationInterstitialListener mediationInterstitialListener, Bundle serverParameters, MediationAdRequest mediationAdRequest, Bundle mediationExtras) { <START> String[] placements = mediationExtras.getStringArray(VungleExtrasBuilder.EXTRA_ALL_PLACEMENTS); <END> if (placements == null || placements.length == 0) { Log.e(TAG, "Placements should be specified!"); if (mediationInterstitialListener != null) mediationInterstitialListener.onAdFailedToLoad(VungleInterstitialAdapter.this, 0); return; } mMediationInterstitialListener = mediationInterstitialListener; String appId = serverParameters.getString("appid"); mVunglePub = VungleManager.getInstance(appId, placements, context); placementForPlay = mVunglePub.findPlacemnt(mediationExtras); adConfig = VungleExtrasBuilder.adConfigWithNetworkExtras(mediationExtras); mVunglePub.addListener(ID, vungleListener); if (mVunglePub.isInitialized()) { loadAd(); } else { vungleListener.setWaitingInit(true); mVunglePub.init(); } }</code><technical_language>rewarded adapter, mediationExtras null null checked accessing</technical_language>

Target:
public void requestInterstitialAd(Context context, MediationInterstitialListener mediationInterstitialListener, Bundle serverParameters, MediationAdRequest mediationAdRequest, Bundle mediationExtras) { String[] placements; if (mediationExtras != null) { placements = mediationExtras.getStringArray(VungleExtrasBuilder.EXTRA_ALL_PLACEMENTS); if (placements == null || placements.length == 0) { Log.e(TAG, "Placements should be specified!"); if (mediationInterstitialListener != null) { mediationInterstitialListener.onAdFailedToLoad(VungleInterstitialAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } } else { Log.e(TAG, "mediationExtras is null."); if (mediationInterstitialListener != null) mediationInterstitialListener.onAdFailedToLoad(VungleInterstitialAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } mMediationInterstitialListener = mediationInterstitialListener; String appId = serverParameters.getString("appid"); mVungleManager = VungleManager.getInstance(appId, placements); placementForPlay = mVungleManager.findPlacemnt(mediationExtras); adConfig = VungleExtrasBuilder.adConfigWithNetworkExtras(mediationExtras); adapterId = ID + String.valueOf(counter); counter++; mVungleManager.addListener(adapterId, vungleListener); if (mVungleManager.isInitialized()) { loadAd(); } else { vungleListener.setWaitingInit(true); mVungleManager.init(context); } }
Source:
<code>public void beforeEachTest() throws Exception { firstResponse = secondResponse = null; blankActivityController = Robolectric.buildActivity(BlankActivity.class).create(); blankActivity = blankActivityController.get(); TestHelpers.beforeTestInitAndCleanup(); <START> OneSignal.setAppContext(blankActivity); <END> }</code><technical_language>ApplicationProvider.getApplicationContext() is set context more consistent other UnitTests. However, I call this of UnitTests individually easier understand this is important part of new OneSignal init</technical_language>

Target:
public void beforeEachTest() throws Exception { firstResponse = secondResponse = null; TestHelpers.beforeTestInitAndCleanup(); }
Source:
<code>PatchSetSelectBox2(DiffTable table, final DisplaySide side, final Change.Id changeId, final PatchSet.Id revision, String path) { initWidget(uiBinder.createAndBindUi(this)); icon.setTitle(PatchUtil.C.addFileCommentToolTip()); icon.addStyleName(Gerrit.RESOURCES.css().link()); this.table = table; this.side = side; this.sideA = side == DisplaySide.A; this.changeId = changeId; this.path = path; setTitle(PatchUtil.C.addFileCommentByDoubleClick()); addDomHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { onIconClick(null); } }, DoubleClickEvent.getType()); RestApi call = ChangeApi.detail(changeId.get()); ChangeList.addOptions(call, EnumSet.of( ListChangesOption.ALL_REVISIONS, ListChangesOption.ALL_COMMITS)); call.get(new GerritCallback<ChangeInfo>() { @Override public void onSuccess(ChangeInfo info) { info.revisions().copyKeysIntoChildren("name"); JsArray<RevisionInfo> list = info.revisions().values(); RevisionInfo.sortRevisionInfoByNumber(list); int selected = 0; if (list.length() > 0 && sideA) { if (list.get(0).commit().parents().length() > 1) { revisionList.addItem(PatchUtil.C.patchBaseAutoMerge()); } else { revisionList.addItem(PatchUtil.C.patchBase()); } } for (int i = 0; i < list.length(); i++) { RevisionInfo r = list.get(i); revisionList.addItem( r._number() + ": " + r.name().substring(0, 6), "" + r._number()); if (revision != null && r._number() == revision.get()) { selected = i + 1; } } if (0 < selected) { idActive = new PatchSet.Id(changeId, <START> selected); <END> revisionList.setSelectedIndex(sideA ? selected : selected - 1); } else if (sideA && selected == 0) { idActive = null; revisionList.setSelectedIndex(0); } } }); }</code><technical_language>gaps in numbering. assume position in list is actual PatchSet.Id</technical_language>

Target:
PatchSetSelectBox2(DiffTable table, final DisplaySide side, final Change.Id changeId, final PatchSet.Id revision, String path) { initWidget(uiBinder.createAndBindUi(this)); icon.setTitle(PatchUtil.C.addFileCommentToolTip()); icon.addStyleName(Gerrit.RESOURCES.css().link()); this.table = table; this.side = side; this.sideA = side == DisplaySide.A; this.changeId = changeId; this.revision = revision; this.idActive = (sideA && revision == null) ? null : revision; this.path = path; setTitle(PatchUtil.C.addFileCommentByDoubleClick()); addDomHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { onIconClick(null); } }, DoubleClickEvent.getType()); }
Source:
<code>public void testBatchRequestEncoding() throws Exception { InstanceInfo instance = InstanceInfoGenerator.takeOne(); List<ReplicationInstance> replicationInstances = new ArrayList<>(); replicationInstances.add(new ReplicationInstance( instance.getAppName(), instance.getId(), System.currentTimeMillis(), null, instance.getStatus().name(), instance, Action.Register )); final ReplicationList replicationList = new ReplicationList(replicationInstances); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(replicationList); ReplicationList decodedValue = decodingCodec.decode(encodedString, ReplicationList.class); assertThat(decodedValue.getReplicationList().size(), is(equalTo(1))); } }; <START> List<CodecWrapper> jsonCodes = Arrays.asList( <END> new CodecWrappers.JacksonJson(), new CodecWrappers.LegacyJacksonJson() ); verifyAllPairs(codingAction, Applications.class, jsonCodes); }</code><technical_language>reverse (encoded JacksonJson decoded Legacy)</technical_language>

Target:
public void testBatchRequestEncoding() throws Exception { InstanceInfo instance = InstanceInfoGenerator.takeOne(); List<ReplicationInstance> replicationInstances = new ArrayList<>(); replicationInstances.add(new ReplicationInstance( instance.getAppName(), instance.getId(), System.currentTimeMillis(), null, instance.getStatus().name(), instance, Action.Register )); final ReplicationList replicationList = new ReplicationList(replicationInstances); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(replicationList); ReplicationList decodedValue = decodingCodec.decode(encodedString, ReplicationList.class); assertThat(decodedValue.getReplicationList().size(), is(equalTo(1))); } }; List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.JacksonJson(), new CodecWrappers.LegacyJacksonJson() ); verifyAllPairs(codingAction, ReplicationList.class, jsonCodes); }