auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Authentication authenticate(Authentication authentication) throws AuthenticationException { @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication .getDetails(); String[] credentials = parseCredentials(details.get("Authorization")); String accessKey = credentials[0]; String clientSignature = credentials[1]; ApiUser apiUser = findUser(accessKey); <START> if (apiUser != null) { <END> Date date = parseDate(details.get("Date")); long clientTime = date.getTime(); long serverTime = new Date().getTime(); long timeDelta = 600000; if (serverTime - timeDelta < clientTime && clientTime < serverTime + timeDelta) { String payload = buildPayload(date, details.get("Resource")); String serverSignature = MD5Util.generateHMAC(payload, apiUser.getSecret()); if (clientSignature.equals(serverSignature)) { return new ApiUserAuthentication(apiUser); } } } throw new BadCredentialsException("Authorization Required"); }</code><technical_language>This is a matter of _style_ instead of a long if branch, turn logic around. java if (apiUser == null) { throw new BadCredentialsException("Authorization Required"); } // rest of code remains indented</technical_language>

Target:
public Authentication authenticate(Authentication authentication) throws AuthenticationException { @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication .getDetails(); String[] credentials = parseCredentials(details.get("Authorization")); String accessKey = credentials[0]; String clientSignature = credentials[1]; ApiUser apiUser = findUser(accessKey); if (apiUser == null) { throw new BadCredentialsException("Authorization Required"); } Date date = parseDate(details.get("Date")); long clientTime = date.getTime(); long serverTime = new Date().getTime(); long timeDelta = 600000; if (serverTime - timeDelta < clientTime && clientTime < serverTime + timeDelta) { String payload = buildPayload(details.get("HTTP-Verb"), date, details.get("Resource")); String serverSignature = MD5Util.generateHMAC(payload, apiUser.getSecret()); if (clientSignature.equals(serverSignature)) { return new ApiUserAuthentication(apiUser); } } throw new BadCredentialsException("Authorization Required"); }
Source:
<code>protected void log(int priority, String tag, String message, Throwable t) { NetworkPeerManager peerManager = NetworkPeerManager.getInstanceOrNull(); if (peerManager == null) { return; } Console.MessageLevel logLevel; switch (priority) { case Log.VERBOSE: case Log.DEBUG: logLevel = Console.MessageLevel.DEBUG; break; case Log.INFO: logLevel = Console.MessageLevel.LOG; break; case Log.WARN: logLevel = Console.MessageLevel.WARNING; break; case Log.ERROR: logLevel = Console.MessageLevel.ERROR; break; default: logLevel = Console.MessageLevel.LOG; } <START> CLog.writeToConsole( <END> peerManager, logLevel, Console.MessageSource.OTHER, message ); }</code><technical_language>stumbled unfortunate weakness in API. want NetworkPeerManager (it's a subtle point admittedly this set of peers observing console messages). Instead, want a new ConsolePeerManager a similar hacky API (getInstanceOrNull) is Console (peers added/removed in Console.enable/disable. Strictly speaking this means log messages forwarded peers invoked Console.enable, necessarily called Network.enable</technical_language>

Target:
protected void log(int priority, String tag, String message, Throwable t) { ConsolePeerManager peerManager = ConsolePeerManager.getInstanceOrNull(); if (peerManager == null) { return; } Console.MessageLevel logLevel; switch (priority) { case Log.VERBOSE: case Log.DEBUG: logLevel = Console.MessageLevel.DEBUG; break; case Log.INFO: logLevel = Console.MessageLevel.LOG; break; case Log.WARN: logLevel = Console.MessageLevel.WARNING; break; case Log.ERROR: logLevel = Console.MessageLevel.ERROR; break; default: logLevel = Console.MessageLevel.LOG; } CLog.writeToConsole( logLevel, Console.MessageSource.OTHER, message ); }
Source:
<code>protected void unmapSecondaryIndexes(K key, V value) { if (value == null) { <START> log.trace("Attempting to build an index with a null value, skipping."); <END> return; } try { for (Index.Spec<K, V, ? extends Comparable> index : indexSpec) { String indexName = index.getName().get(); Map<Comparable, Map<K, V>> secondaryIndex = secondaryIndexes.get(indexName); for (Comparable indexKey : index.getMultiValueIndexFunction().apply(key, value)) { Map<K, V> slot = secondaryIndex.get(indexKey); if (slot != null) { slot.remove(key, value); } } } } catch (Exception e) { log.error("Received an exception while computing the index. " + "This is most likely an issue with the client's indexing function. {}", e); clearIndex(); throw e; } }</code><technical_language>This is cheap called frequently. I a condition caller if a secondary index exist shouldn;t called. cleaner calling "implementing a no-op"</technical_language>

Target:
protected void unmapSecondaryIndexes(K key, V value) { if (value == null) { return; } try { for (Index.Spec<K, V, ? extends Comparable> index : indexSpec) { String indexName = index.getName().get(); Map<Comparable, Map<K, V>> secondaryIndex = secondaryIndexes.get(indexName); for (Comparable indexKey : index.getMultiValueIndexFunction().apply(key, value)) { Map<K, V> slot = secondaryIndex.get(indexKey); if (slot != null) { slot.remove(key, value); } } } } catch (Exception e) { log.error("Received an exception while computing the index. " + "This is most likely an issue with the client's indexing function. {}", e); clearIndex(); throw e; } }
Source:
<code>public void deleteErrorLogsByDate() throws Exception { CountDownAsyncJobListener countDownListener = new CountDownAsyncJobListener(2); ((ExecutorServiceImpl) getExecutorService()).addAsyncJobListener(countDownListener); KieSession ksession = createKSession(ASYNC_DATA_EXEC); WorkItemManager wim = ksession.getWorkItemManager(); wim.registerWorkItemHandler("async", new AsyncWorkItemHandler(getExecutorService())); Map<String, Object> pm = new HashMap<String, Object>(); pm.put("command", "org.jbpm.test.jobexec.UserFailingCommand"); ProcessInstance pi = ksession.startProcess(ASYNC_DATA_EXEC_ID, pm); countDownListener.waitTillCompleted(); List<ErrorInfo> errorList = getExecutorService().getAllErrors(new QueryContext()); Assertions.assertThat(errorList).hasSize(2); int resultCount = auditService.errorInfoLogDeleteBuilder() .date(errorList.get(0).getTime()) .build() .execute(); int deleted = 1; int remaining = 1; <START> if (errorList.get(0).getTime().compareTo(errorList.get(1).getTime())==0) { <END> deleted=2; remaining=0; } Assertions.assertThat(resultCount).isEqualTo(deleted); Assertions.assertThat(getExecutorService().getAllErrors(new QueryContext())).hasSize(remaining); ksession.abortProcessInstance(pi.getId()); }</code><technical_language>equals here</technical_language>

Target:
public void deleteErrorLogsByDate() throws Exception { CountDownAsyncJobListener countDownListener = new CountDownAsyncJobListener(2); ((ExecutorServiceImpl) getExecutorService()).addAsyncJobListener(countDownListener); KieSession ksession = createKSession(ASYNC_DATA_EXEC); WorkItemManager wim = ksession.getWorkItemManager(); wim.registerWorkItemHandler("async", new AsyncWorkItemHandler(getExecutorService())); Map<String, Object> pm = new HashMap<String, Object>(); pm.put("command", "org.jbpm.test.jobexec.UserFailingCommand"); ProcessInstance pi = ksession.startProcess(ASYNC_DATA_EXEC_ID, pm); countDownListener.waitTillCompleted(); List<ErrorInfo> errorList = getExecutorService().getAllErrors(new QueryContext()); Assertions.assertThat(errorList).hasSize(2); int resultCount = auditService.errorInfoLogDeleteBuilder() .date(errorList.get(0).getTime()) .build() .execute(); int deleted = 1; int remaining = 1; if (errorList.get(0).getTime().equals(errorList.get(1).getTime())) { deleted=2; remaining=0; } Assertions.assertThat(resultCount).isEqualTo(deleted); Assertions.assertThat(getExecutorService().getAllErrors(new QueryContext())).hasSize(remaining); ksession.abortProcessInstance(pi.getId()); }
Source:
<code>public void addModelSubstitute(String fromClass, String toClass) throws GenerateException { try { Type type = _mapper.constructType(Class.forName(fromClass)); Type toType = _mapper.constructType(Class.forName(toClass)); modelSubtitutes.put(type, toType); } catch (ClassNotFoundException e) { <START> LOGGER.warn("Problem with load " + fromClass + ". Mapping will be ignored."); <END> } }</code><technical_language>This log message is correct. missing toClass class</technical_language>

Target:
public void addModelSubstitute(String fromClass, String toClass) throws GenerateException { Type type = null; Type toType = null; try { type = _mapper.constructType(Class.forName(fromClass)); } catch (ClassNotFoundException e) { LOGGER.warn("Problem with loading " + fromClass + ". Mapping will be ignored."); } try { toType = _mapper.constructType(Class.forName(toClass)); } catch (ClassNotFoundException e) { LOGGER.warn("Problem with loading " + toClass + ". Mapping will be ignored."); } if(type != null && toType != null) { modelSubtitutes.put(type, toType); } }
Source:
<code>public Single<Boolean> put(@NonNull final T id, @NonNull final U item) { checkNotNull(id); checkNotNull(item); final int hash = getHashCodeForId(id); U newItem = item; boolean valuesEqual = false; if (cache.containsKey(hash)) { final U currentItem = cache.get(hash); valuesEqual = newItem.equals(currentItem); if (!valuesEqual) { Log.v(TAG, "Merging values at " + id); try { newItem = putMergeFunction.apply(currentItem, newItem); } catch (Exception e) { <START> Log.e(TAG, "Error merging!", e); <END> } valuesEqual = newItem.equals(currentItem); } } if (valuesEqual) { Log.v(TAG, "Data already up to date at " + id); return Single.just(false); } cache.put(hash, newItem); subject.onNext(new StoreItem<>(id, newItem)); if (subjectCache.containsKey(hash)) { subjectCache.get(hash).onNext(newItem); } return Single.just(true); }</code><technical_language>this Single error</technical_language>

Target:
public Single<Boolean> put(@NonNull final T id, @NonNull final U item) { checkNotNull(id); checkNotNull(item); final int hash = getHashCodeForId(id); U newItem = item; boolean valuesEqual = false; if (cache.containsKey(hash)) { final U currentItem = cache.get(hash); valuesEqual = newItem.equals(currentItem); if (!valuesEqual) { Log.v(TAG, "Merging values at " + id); try { newItem = putMergeFunction.apply(currentItem, newItem); } catch (Exception e) { return Single.error(e); } valuesEqual = newItem.equals(currentItem); } } if (valuesEqual) { Log.v(TAG, "Data already up to date at " + id); return Single.just(false); } cache.put(hash, newItem); subject.onNext(new StoreItem<>(id, newItem)); if (subjectCache.containsKey(hash)) { subjectCache.get(hash).onNext(newItem); } return Single.just(true); }
Source:
<code>private IPath getReferencePointRelativePath(@NotNull VirtualFile file) { String referencePointPath = virtualFile.getPath(); String filePath = file.getPath(); if (!filePath.startsWith(referencePointPath)) { return null; } try { <START> Path relativePath = Paths.get(virtualFile.getPath()).relativize(Paths.get(file.getPath())); <END> return IntelliJPathImpl.fromString(relativePath.toString()); } catch (IllegalArgumentException e) { log.warn( "Could not find a relative path from the base file " + virtualFile + " to the file " + file, e); return null; } }</code><technical_language>suggestion Path relativePath = Paths.get(referencePointPath).relativize(Paths.get(filePath));</technical_language>

Target:
private IPath getReferencePointRelativePath(@NotNull VirtualFile file) { String referencePointPath = virtualFile.getPath(); String filePath = file.getPath(); if (!filePath.startsWith(referencePointPath)) { return null; } try { Path relativePath = Paths.get(referencePointPath).relativize(Paths.get(filePath)); return IntelliJPathImpl.fromString(relativePath.toString()); } catch (IllegalArgumentException e) { log.warn( "Could not find a relative path from the base file " + virtualFile + " to the file " + file, e); return null; } }
Source:
<code>public static ImmutableSet<C_Type> getArrayStructMemberTypes(final ImmutableList<Struct> allOrderedStructs) { final ImmutableSet.Builder<C_Type> arrayStructMemberTypesBuilder = ImmutableSet.builder(); for (final Struct currentStruct : allOrderedStructs) { currentStruct.getStructMembers().stream() .filter(currentStructMember -> currentStructMember.getType().isArray()) .map(StructMember::getType) <START> .collect(Collectors.toCollection(HashSet::new)) <END> .forEach(arrayStructMemberTypesBuilder::add); } return arrayStructMemberTypesBuilder.build(); }</code><technical_language>creating a new hashset, turn iterate it. this point call forEach instead of collect forEach</technical_language>

Target:
public static ImmutableSet<C_Type> getArrayStructMemberTypes(final ImmutableList<Struct> allOrderedStructs) { final ImmutableSet.Builder<C_Type> arrayStructMemberTypesBuilder = ImmutableSet.builder(); for (final Struct currentStruct : allOrderedStructs) { currentStruct.getStructMembers().stream() .filter(currentStructMember -> currentStructMember.getType().isArray()) .map(StructMember::getType) .forEach(arrayStructMemberTypesBuilder::add); } return arrayStructMemberTypesBuilder.build(); }
Source:
<code>public int compare(Tuple tuple, Tuple tuple2) { int levels1 = getLevels(tuple); int levels2 = getLevels(tuple2); ComparisonChain comparisonChain = ComparisonChain.start().compare(levels1, levels2); for(int i = 0; i < levels1; i++) { Pair<Integer, Integer> pair1 = hasArrayIndex(tuple.getMetadata(), i)? <START> new Pair<Integer, Integer>(i, getArrayIndex(tuple.getMetadata(), i)) : new Pair(-1, -1); <END> Pair<Integer, Integer> pair2 = hasArrayIndex(tuple2.getMetadata(), i) ? new Pair<Integer, Integer>(i, getArrayIndex(tuple2.getMetadata(), i)) : new Pair(-1, -1); comparisonChain = comparisonChain.compare(pair1.getOne(), pair2.getOne()); comparisonChain = comparisonChain.compare(pair1.getTwo(), pair2.getTwo()); } comparisonChain = comparisonChain.compare(tuple.getKey(), tuple2.getKey()); return comparisonChain.result(); }</code><technical_language>turn Pair(-1,-1) a constant</technical_language>

Target:
public int compare(Tuple tuple, Tuple tuple2) { int levels1 = getLevels(tuple); int levels2 = getLevels(tuple2); ComparisonChain comparisonChain = ComparisonChain.start(); for(int i = 0; i < Math.max(levels1, levels2); i++) { Pair<Integer, Integer> pair1 = hasArrayIndex(tuple.getMetadata(), i)? new Pair<Integer, Integer>(i, getArrayIndex(tuple.getMetadata(), i)) : DEFAULT_PAIR; Pair<Integer, Integer> pair2 = hasArrayIndex(tuple2.getMetadata(), i) ? new Pair<Integer, Integer>(i, getArrayIndex(tuple2.getMetadata(), i)) : DEFAULT_PAIR; comparisonChain = comparisonChain.compare(pair1.getOne(), pair2.getOne()); comparisonChain = comparisonChain.compare(pair1.getTwo(), pair2.getTwo()); } comparisonChain = comparisonChain.compare(levels1, levels2) .compare(tuple.getKey(), tuple2.getKey()); return comparisonChain.result(); }
Source:
<code>private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); <START> } catch (Exception e) { <END> return; } handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); }</code><technical_language>this Throwable Exception? failures reported in WFLY-8515 LinkageError NoClassDefFoundError, of caught stand</technical_language>

Target:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); } catch (Throwable e) { return; } handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); }
Source:
<code>private String getCacheSubcommandDesc(CacheCommand cmd) { switch (cmd) { case LIST: return "Show information about caches, groups or sequences that match a regular expression. When executed without parameters, this subcommand prints the list of caches."; case CONTENTION: return "Show the keys that are point of contention for multiple transactions."; case IDLE_VERIFY: return "Verify counters and hash sums of primary and backup partitions for the specified caches on an idle cluster and print out the differences, if any. " + "Cache filtering options configure the set of caches that will be processed by idle_verify command. " + "Default value for the set of cache names is all caches. Default value for --exclude-caches is empty set. " + "Default value for --cache-filter is no filtering. Therefore, the set of all caches is consequently filtered by cache name " + <START> "regexps, by cache type and after all by exclude regexps."; <END> case VALIDATE_INDEXES: return "Validate indexes on an idle cluster and print out the keys that are missing in the indexes."; case DISTRIBUTION: return "Prints the information about partition distribution."; case RESET_LOST_PARTITIONS: return "Reset the state of lost partitions for the specified caches."; default: throw new IllegalArgumentException("Unknown command: " + cmd); } }</code><technical_language>Please class constants instead of strings. I.e. EXCLUDE_CACHES instead of --exclude-caches</technical_language>

Target:
private String getCacheSubcommandDesc(CacheCommand cmd) { switch (cmd) { case LIST: return "Show information about caches, groups or sequences that match a regular expression. When executed without parameters, this subcommand prints the list of caches."; case CONTENTION: return "Show the keys that are point of contention for multiple transactions."; case IDLE_VERIFY: return "Verify counters and hash sums of primary and backup partitions for the specified caches/cache groups on an idle cluster and print out the differences, if any. " + "Cache filtering options configure the set of caches that will be processed by " + IDLE_VERIFY + " command. " + "Default value for the set of cache names (or cache group names) is all cache groups. Default value for " + EXCLUDE_CACHES + " is empty set. " + "Default value for " + CACHE_FILTER + " is no filtering. Therefore, the set of all caches is sequently filtered by cache name " + "regexps, by cache type and after all by exclude regexps."; case VALIDATE_INDEXES: return "Validate indexes on an idle cluster and print out the keys that are missing in the indexes."; case DISTRIBUTION: return "Prints the information about partition distribution."; case RESET_LOST_PARTITIONS: return "Reset the state of lost partitions for the specified caches."; default: throw new IllegalArgumentException("Unknown command: " + cmd); } }
Source:
<code>public void testAddMultipleClients() throws Exception { <START> final IClientSession session1 = Mockito.mock(IClientSession.class); <END> final IClientSession session2 = Mockito.mock(IClientSession.class); TestMultiClientSessionCookieStore cookieStore = new TestMultiClientSessionCookieStore(); cookieStore.setTestClientSession(session1); cookieStore.add(TESTURI1, COOKIE1); cookieStore.setTestClientSession(session2); cookieStore.add(TESTURI2, COOKIE2); cookieStore.setTestClientSession(session1); List<HttpCookie> storedCookies = cookieStore.get(TESTURI1); assertNotNull(storedCookies); assertEquals(1, storedCookies.size()); checkCookieDeepEquality(COOKIE1, CollectionUtility.firstElement(storedCookies)); cookieStore.setTestClientSession(session2); List<HttpCookie> storedCookies2 = cookieStore.get(TESTURI2); assertNotNull(storedCookies2); assertEquals(1, storedCookies2.size()); checkCookieDeepEquality(COOKIE2, CollectionUtility.firstElement(storedCookies2)); }</code><technical_language>create session1 & 2 fields remove duplicate code</technical_language>

Target:
public void testAddMultipleClients() throws Exception { TestMultiClientSessionCookieStore cookieStore = new TestMultiClientSessionCookieStore(); cookieStore.setTestClientSession(SESSION1); cookieStore.add(s_testuri1, COOKIE1); cookieStore.setTestClientSession(SESSION2); cookieStore.add(s_testuri2, COOKIE2); cookieStore.setTestClientSession(SESSION1); List<HttpCookie> storedCookies = cookieStore.get(s_testuri1); assertNotNull(storedCookies); assertEquals(1, storedCookies.size()); assertCookieEquals(COOKIE1, CollectionUtility.firstElement(storedCookies)); cookieStore.setTestClientSession(SESSION2); List<HttpCookie> storedCookies2 = cookieStore.get(s_testuri2); assertNotNull(storedCookies2); assertEquals(1, storedCookies2.size()); assertCookieEquals(COOKIE2, CollectionUtility.firstElement(storedCookies2)); }
Source:
<code>private void testAddCommentsToQuestionsWithResponses() throws IOException { ______TS("add new comments on questions with responses and verify add comments without responses action"); submitPage = loginToInstructorEditStudentFeedbackPage( "IESFPTCourseinstr", "student1InIESFPTCourse@gmail.tmt", "session1InIESFPTCourse"); submitPage.waitForPageToLoad(); submitPage.addFeedbackResponseComment("-3-0", "New MCQ Comment 1"); submitPage.submitWithoutConfirmationEmail(); submitPage.verifyAndCloseSuccessfulSubmissionModal(""); submitPage.waitForTextsForAllStatusMessagesToUserEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED); <START> submitPage.verifyHtmlMainContent("/instructorEditStudentFeedbackPageModifiedAddedCommentOnResponses.html"); <END> }</code><technical_language>here. Multiple places</technical_language>

Target:
private void testAddCommentsToQuestionsWithResponses() { submitPage = loginToInstructorEditStudentFeedbackPage( "IESFPTCourseinstr", "student1InIESFPTCourse@gmail.tmt", "session1InIESFPTCourse"); submitPage.waitForPageToLoad(); submitPage.chooseMcqOption(3, 0, "It's good"); submitPage.addFeedbackParticipantComment("-3-0", "New MCQ Comment 1"); submitPage.submitWithoutConfirmationEmail(); submitPage.verifyAndCloseSuccessfulSubmissionModal("2."); submitPage.waitForTextsForAllStatusMessagesToUserEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, Const.StatusMessages.FEEDBACK_UNANSWERED_QUESTIONS + "2."); submitPage.verifyCommentRowContent("-3-0", "New MCQ Comment 1"); }
Source:
<code>private void init() { if (!appInit.compareAndSet(false, true)) { logger.info("ZEP already initialized"); return; } logger.info("Initializing ZEP"); long sleep = 5; boolean done = false; try { while (!done) { try { this.config = configDao.getConfig(); done = true; } catch (Exception e) { logger.warn("Could not get config dao; {}; {}", e.getMessage(), e.getCause() != null ? e.getMessage() : ""); Thread.sleep(Math.max(sleep, 1)); <START> sleep = sleep * 2; <END> } } if (!done) { logger.error("Could not start ZEP"); } this.applicationEventPublisher.publishEvent(new ZepConfigUpdatedEvent(this, config)); this.pluginService.initializePlugins(); initializePartitions(); this.eventSummaryRebuilder.init(); this.eventArchiveRebuilder.init(); startEventSummaryAging(); startEventSummaryArchiving(); startEventArchivePurging(); startEventTimePurging(); startDbMaintenance(); startHeartbeatProcessing(); startQueueListeners(); logger.info("Completed ZEP initialization"); } catch (Exception e) { logger.error("Could not start ZEP", e); } }</code><technical_language>I cap this sleep a couple of minutes maybe. Otherwise, if ZEP unable initialize for hour, exponential backoff reached 30 minutes, wait entire time for ZEP database is available</technical_language>

Target:
private void init() { if (!appInit.compareAndSet(false, true)) { logger.info("ZEP already initialized"); return; } logger.info("Initializing ZEP"); long sleep = 1; boolean done = false; try { while (!done) { try { this.config = configDao.getConfig(); done = true; } catch (Exception e) { logger.warn("Could not get config dao; {}; {}", e.getMessage(), e.getCause() != null ? e.getMessage() : ""); Thread.sleep(Math.min(sleep, 5000)); sleep = sleep * 2; } } if (!done) { logger.error("Could not start ZEP"); } this.applicationEventPublisher.publishEvent(new ZepConfigUpdatedEvent(this, config)); this.pluginService.initializePlugins(); initializePartitions(); this.eventSummaryRebuilder.init(); this.eventArchiveRebuilder.init(); startEventSummaryAging(); startEventSummaryArchiving(); startEventArchivePurging(); startEventTimePurging(); startDbMaintenance(); startHeartbeatProcessing(); startQueueListeners(); logger.info("Completed ZEP initialization"); } catch (Exception e) { logger.error("Could not start ZEP", e); } }
Source:
<code>public boolean extractQuestionDetails( Map<String, String[]> requestParameters, FeedbackQuestionType questionType) { String isNotSureAllowedString = HttpRequestHelper.getValueFromParamMap( requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED); Boolean isNotSureAllowed = (isNotSureAllowedString == null) ? false <START> : (isNotSureAllowedString.equals("on") ? true : false); <END> this.setContributionQuestionDetails(isNotSureAllowed); return true; }</code><technical_language>if else statements this more readable</technical_language>

Target:
public boolean extractQuestionDetails( Map<String, String[]> requestParameters, FeedbackQuestionType questionType) { String isNotSureAllowedString = HttpRequestHelper.getValueFromParamMap( requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED); Boolean isNotSureAllowed; if (isNotSureAllowedString == null) { isNotSureAllowed = false; } else { isNotSureAllowed = isNotSureAllowedString.equals("on"); } this.setContributionQuestionDetails(isNotSureAllowed); return true; }
Source:
<code>public void tearDown() { <START> IServer[] all = ServerCore.getServers(); <END> for( int i = 0; i < all.length; i++ ) { try { all[i].delete(); } catch(CoreException ce) { ce.printStackTrace(); } } }</code><technical_language>refactor in a test utility class</technical_language>

Target:
public void tearDown() { OpenShiftServerTestUtility.cleanup(); }
Source:
<code>protected JoinGroupRequestData.JoinGroupRequestProtocolCollection metadata() { log.debug("Joining group with current subscription: {}", subscriptions.subscription()); this.joinedSubscription = subscriptions.subscription(); JoinGroupRequestData.JoinGroupRequestProtocolCollection protocolSet = new JoinGroupRequestData.JoinGroupRequestProtocolCollection(); for (PartitionAssignor assignor : assignors) { Subscription subscription = assignor.subscription(joinedSubscription); <START> subscription.setOwnedPartitions(new ArrayList<>(subscriptions.assignedPartitions())); <END> ByteBuffer metadata = ConsumerProtocol.serializeSubscription(subscription); protocolSet.add(new JoinGroupRequestData.JoinGroupRequestProtocol() .setName(assignor.name()) .setMetadata(Utils.toArray(metadata))); } return protocolSet; }</code><technical_language>this I push this Assignor well, *just* more symmetric. I arguments for this way: 1) PartitionAssignor necessarily ownedPartitions 2) if does, updates (such metadata/subscription change, missed rebalance) while ConsumerCoordinator's subscriptions.assignedPartitions is date. address 1), I is reasonable assume/force a **Cooperative** assignor some knowledge of ownedPartitions especially ok assume able handle "adjust assignment" logic. 2), pass current assignment PartitionAssignor prior, a separate PartitionAssignor.cooperativeSubscription(topics, assignment) method is called in cooperative mode instead of above. upside of setting ownedPartitions in ConsumerCoordinator is PartitionAssignor longer needs know/save assignment. lose is ability for PartitionAssignor react other currently owned partitions.Imagine a heavily stateful app a consumer misses a rebalance. partitions get assigned another consumer state restore get consumer manages rejoin. consumer's state is date while consumer is behind, consumer join a non-empty ownedPartitions is more get partitions again. (this scenario requires a more advanced assignment strategy currently employ, current sticky assignor leverages this information improve stickiness possible) @guozhangwang @hachikuji</technical_language>

Target:
protected JoinGroupRequestData.JoinGroupRequestProtocolCollection metadata() { log.debug("Joining group with current subscription: {}", subscriptions.subscription()); this.joinedSubscription = subscriptions.subscription(); JoinGroupRequestData.JoinGroupRequestProtocolCollection protocolSet = new JoinGroupRequestData.JoinGroupRequestProtocolCollection(); List<String> topics = new ArrayList<>(joinedSubscription); for (ConsumerPartitionAssignor assignor : assignors) { Subscription subscription = new Subscription(topics, assignor.subscriptionUserData(joinedSubscription), subscriptions.assignedPartitionsList()); ByteBuffer metadata = ConsumerProtocol.serializeSubscription(subscription); protocolSet.add(new JoinGroupRequestData.JoinGroupRequestProtocol() .setName(assignor.name()) .setMetadata(Utils.toArray(metadata))); } return protocolSet; }
Source:
<code>private Champ copyAndSetValue(final int setIndex, final int payloadIndex, final MaybeMultihash val) { final HashPrefixPayload[] src = this.contents; final HashPrefixPayload[] dst = new HashPrefixPayload[src.length]; System.arraycopy(src, 0, dst, 0, src.length); <START> HashPrefixPayload existing = dst[setIndex]; <END> KeyElement[] updated = new KeyElement[existing.mappings.length]; System.arraycopy(existing.mappings, 0, updated, 0, existing.mappings.length); updated[payloadIndex] = new KeyElement(existing.mappings[payloadIndex].key, val); dst[setIndex] = new HashPrefixPayload(updated, null); return new Champ(dataMap, nodeMap, dst); }</code><technical_language>Replace lines dst = java.util.Arrays.copyOf(this.contents, this.contents.length)</technical_language>

Target:
private Champ copyAndSetValue(final int setIndex, final int payloadIndex, final MaybeMultihash val) { final HashPrefixPayload[] src = this.contents; final HashPrefixPayload[] dst = Arrays.copyOf(src, src.length); HashPrefixPayload existing = dst[setIndex]; KeyElement[] updated = new KeyElement[existing.mappings.length]; System.arraycopy(existing.mappings, 0, updated, 0, existing.mappings.length); updated[payloadIndex] = new KeyElement(existing.mappings[payloadIndex].key, val); dst[setIndex] = new HashPrefixPayload(updated); return new Champ(dataMap, nodeMap, dst); }
Source:
<code>private TemporalValue attachTimeZone( TemporalValue temporal, ZoneId zoneIdToAttach ) { if ( temporal.isSupported( ChronoField.MONTH_OF_YEAR ) ) { return datetime( ZonedDateTime.of( temporal.getDatePart(), temporal.getLocalTimePart(), zoneIdToAttach ) ); } else { if ( zoneIdToAttach instanceof ZoneOffset ) { return time( OffsetTime.of( temporal.getLocalTimePart(), (ZoneOffset) zoneIdToAttach ) ); } else { <START> throw new UnsupportedTemporalUnitException( "Should only attach offsets to local times, not zone ids." ); <END> } } }</code><technical_language>IllegalStateException before, is this code path a case expect happen? If not, IllegalStateException is right choice, signals _we_ wrong, user of product</technical_language>

Target:
private TemporalValue attachTimeZone( TemporalValue temporal, ZoneId zoneIdToAttach ) { if ( temporal.isSupported( ChronoField.MONTH_OF_YEAR ) ) { return datetime( ZonedDateTime.of( temporal.getDatePart(), temporal.getLocalTimePart(), zoneIdToAttach ) ); } else { if ( zoneIdToAttach instanceof ZoneOffset ) { return time( OffsetTime.of( temporal.getLocalTimePart(), (ZoneOffset) zoneIdToAttach ) ); } else { throw new IllegalStateException( "Should only attach offsets to local times, not zone ids." ); } } }
Source:
<code>public int parseArguments(final Parameters params) throws CmdLineException { final String name = params.getParameter(0); if (new File(name).isDirectory()) { <START> setter.addValue(new FileTreeIterator(new File(name), FS.DETECTED, new WorkingTreeOptions(false))); <END> return 1; } if (new File(name).isFile()) { final DirCache dirc; try { dirc = DirCache.read(new File(name), FS.DETECTED); } catch (IOException e) { throw new CmdLineException(MessageFormat.format(CLIText.get().notAnIndexFile, name), e); } setter.addValue(new DirCacheIterator(dirc)); return 1; } final ObjectId id; try { id = clp.getRepository().resolve(name); } catch (IOException e) { throw new CmdLineException(e.getMessage()); } if (id == null) throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); final CanonicalTreeParser p = new CanonicalTreeParser(); final ObjectReader curs = clp.getRepository().newObjectReader(); try { p.reset(curs, clp.getRevWalk().parseTree(id)); } catch (MissingObjectException e) { throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); } catch (IncorrectObjectTypeException e) { throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); } catch (IOException e) { throw new CmdLineException(MessageFormat.format(CLIText.get().cannotReadBecause, name, e.getMessage())); } finally { curs.release(); } setter.addValue(p); return 1; }</code><technical_language>default instance</technical_language>

Target:
public int parseArguments(final Parameters params) throws CmdLineException { final String name = params.getParameter(0); if (new File(name).isDirectory()) { setter.addValue(new FileTreeIterator(new File(name), FS.DETECTED, WorkingTreeOptions.createDefaultInstance())); return 1; } if (new File(name).isFile()) { final DirCache dirc; try { dirc = DirCache.read(new File(name), FS.DETECTED); } catch (IOException e) { throw new CmdLineException(MessageFormat.format(CLIText.get().notAnIndexFile, name), e); } setter.addValue(new DirCacheIterator(dirc)); return 1; } final ObjectId id; try { id = clp.getRepository().resolve(name); } catch (IOException e) { throw new CmdLineException(e.getMessage()); } if (id == null) throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); final CanonicalTreeParser p = new CanonicalTreeParser(); final ObjectReader curs = clp.getRepository().newObjectReader(); try { p.reset(curs, clp.getRevWalk().parseTree(id)); } catch (MissingObjectException e) { throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); } catch (IncorrectObjectTypeException e) { throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); } catch (IOException e) { throw new CmdLineException(MessageFormat.format(CLIText.get().cannotReadBecause, name, e.getMessage())); } finally { curs.release(); } setter.addValue(p); return 1; }
Source:
<code>private int runCurrentRecords() { List<RunnableRecord> current = getCurrentRecords(); int executedNum = 0; myRunning = true; try { for (RunnableRecord r : current) { executedNum++; r.myRunnable.run(); } } finally { <START> myRunning = false; <END> myRecords.removeAll(current.subList(0, executedNum)); } return executedNum; }</code><technical_language>ThrowableHandlers here</technical_language>

Target:
private int runCurrentRecords() { List<RunnableRecord> current = getCurrentRecords(); int executedNum = 0; myRunning = true; try { for (RunnableRecord r : current) { executedNum++; try { r.myRunnable.run(); } catch (Exception e) { ThrowableHandlers.handle(e); } } } finally { myRunning = false; myRecords.removeAll(current.subList(0, executedNum)); } return executedNum; }
Source:
<code>public void validateFullRepresentation() throws Exception { super.validateFullRepresentation(); assertPropEquals("uuid", getObject().getUuid()); assertPropEquals("condition", getObject().getCondition()); assertPropEquals("clinicalStatus", getObject().getClinicalStatus()); assertPropEquals("verificationStatus", getObject().getVerificationStatus()); assertPropEquals("previousVersion", getObject().getPreviousVersion()); assertPropEquals("onsetDate", getObject().getOnsetDate()); assertPropEquals("additionalDetail", getObject().getAdditionalDetail()); assertPropEquals("voided", getObject().getVoided()); <START> assertPropEquals("voided_by", getObject().getVoidedBy()); <END> }</code><technical_language>this test pass</technical_language>

Target:
public void validateFullRepresentation() throws Exception { super.validateFullRepresentation(); assertPropEquals("condition", getObject().getCondition()); assertPropEquals("clinicalStatus", getObject().getClinicalStatus()); assertPropEquals("verificationStatus", getObject().getVerificationStatus()); assertPropEquals("previousVersion", getObject().getPreviousVersion()); assertPropEquals("onsetDate", getObject().getOnsetDate()); assertPropEquals("additionalDetail", getObject().getAdditionalDetail()); assertPropEquals("voided", getObject().getVoided()); }
Source:
<code><START> @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { <END> return super.getConfiguration(igniteInstanceName) .setCacheConfiguration(new CacheConfiguration("cache") .setCacheMode(CacheMode.PARTITIONED) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL) .setRebalanceMode(CacheRebalanceMode.SYNC) .setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC) .setMaxConcurrentAsyncOperations(0) .setBackups(0)); }</code><technical_language>Apache license header is absent</technical_language>

Target:
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); CacheConfiguration cacheCfg = new CacheConfiguration("cache"); cacheCfg.setCacheMode(CacheMode.PARTITIONED); cacheCfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL); cacheCfg.setRebalanceMode(CacheRebalanceMode.SYNC); cacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); cacheCfg.setMaxConcurrentAsyncOperations(0); cacheCfg.setBackups(0); cfg.setCacheConfiguration(cacheCfg); return cfg; }
Source:
<code>public static int compare(StarlarkInt x, StarlarkInt y) { if (x instanceof Int32 && y instanceof Int32) { return Integer.compare(((Int32) x).v, ((Int32) y).v); } try { return Long.compare(x.toLongFast(), y.toLongFast()); <START> } catch (OverflowException ignore) { <END> } return x.toBigInteger().compareTo(y.toBigInteger()); }</code><technical_language>Call 'unused', this suppresses annoying static check runs Google's Java code</technical_language>

Target:
public static int compare(StarlarkInt x, StarlarkInt y) { if (x instanceof Int32 && y instanceof Int32) { return Integer.compare(((Int32) x).v, ((Int32) y).v); } try { return Long.compare(x.toLongFast(), y.toLongFast()); } catch (Overflow unused) { } return x.toBigInteger().compareTo(y.toBigInteger()); }
Source:
<code>private XmlSuite getXmlSuite() { XmlSuite testSuite = new XmlSuite(); testSuite.setName("tempto-tests"); testSuite.setFileName("tempto-tests"); XmlTest test = new XmlTest(testSuite); test.setName("all"); XmlPackage testPackage = new XmlPackage(options.getTestsPackage()); List<XmlPackage> testPackages = new ArrayList<>(); testPackages.add(testPackage); test.setPackages(testPackages); <START> XmlClass conventionBasedTestsClass = new XmlClass("com.teradata.tempto.internal.convention.ConventionBasedTestFactory"); <END> List<XmlClass> classes = new ArrayList<>(); classes.add(conventionBasedTestsClass); test.setClasses(classes); return testSuite; }</code><technical_language>Class object get class name</technical_language>

Target:
private XmlSuite getXmlSuite() { XmlSuite testSuite = new XmlSuite(); testSuite.setName("tempto-tests"); testSuite.setFileName("tempto-tests"); XmlTest test = new XmlTest(testSuite); test.setName("all"); XmlPackage testPackage = new XmlPackage(options.getTestsPackage()); List<XmlPackage> testPackages = newArrayList(testPackage); test.setPackages(testPackages); XmlClass conventionBasedTestsClass = new XmlClass("com.teradata.tempto.internal.convention.ConventionBasedTestFactory"); List<XmlClass> classes = newArrayList(conventionBasedTestsClass); test.setClasses(classes); return testSuite; }
Source:
<code>public void run() { int adminPort = VoltDB.DEFAULT_ADMIN_PORT; if (m_deployment.getAdminMode() != null) { if (m_isRejoin == false) { if (m_deployment.getAdminMode().isAdminstartup()) { m_rvdb.setStartMode(OperationMode.PAUSED); } } adminPort = m_deployment.getAdminMode().getPort(); } if (m_config.m_adminPort > 0) adminPort = m_config.m_adminPort; m_config.m_adminPort = adminPort; if (m_config.m_isPaused.get()) { <START> m_rvdb.setStartMode(OperationMode.PAUSED); <END> } }</code><technical_language>do this in VoltDB.Configuration instead? if</technical_language>

Target:
public void run() { int adminPort = VoltDB.DEFAULT_ADMIN_PORT; if (m_deployment.getAdminMode() != null) { if (m_isRejoin == false) { if (m_deployment.getAdminMode().isAdminstartup()) { m_rvdb.setStartMode(OperationMode.PAUSED); } } adminPort = m_deployment.getAdminMode().getPort(); } if (m_config.m_adminPort > 0) adminPort = m_config.m_adminPort; m_config.m_adminPort = adminPort; }
Source:
<code>AesCipher(AesMode mode, byte[] keyBytes) throws IllegalArgumentException, IOException { <START> if (null == keyBytes) { <END> throw new IllegalArgumentException("Null key bytes"); } aesKey = new EncryptionKey(keyBytes); randomGenerator = new SecureRandom(); localNonce = new byte[NONCE_LENGTH]; wipedOut = false; }</code><technical_language>Is empty keyBytes allowed</technical_language>

Target:
AesCipher(AesMode mode, byte[] keyBytes) throws IllegalArgumentException, IOException { if (null == keyBytes) { throw new IllegalArgumentException("Null key bytes"); } boolean allZeroKey = true; for (byte kb : keyBytes) { if (kb != 0) { allZeroKey = false; break; } } if (allZeroKey) { throw new IllegalArgumentException("All key bytes are zero"); } aesKey = new SecretKeySpec(keyBytes, "AES"); randomGenerator = new SecureRandom(); localNonce = new byte[NONCE_LENGTH]; }
Source:
<code>private void lookupNonPaginatedGetChildren() { try { _getChildrenMethod = ZooKeeper.class.getMethod("getChildren", String.class, boolean.class); } catch (NoSuchMethodException e2) { <START> LOG.error("getChildren is not supported in this zookeeper version!"); <END> } }</code><technical_language>throw exception. Fail earlier block logic starting up. This is safer allowing a partially working client</technical_language>

Target:
private Method lookupNonPaginatedGetChildren() { try { return ZooKeeper.class.getMethod("getChildren", String.class, boolean.class); } catch (NoSuchMethodException e) { throw ExceptionUtil.convertToRuntimeException(e.getCause()); } }
Source:
<code>protected void initializeExecutors() { final int maxPendingPersists = config.getMaxPendingPersists(); if (persistExecutor == null) { persistExecutor = Execs.newBlockingSingleThreaded( <START> "plumber_persist_%d", maxPendingPersists, Thread.MIN_PRIORITY <END> ); } if (mergeExecutor == null) { mergeExecutor = Execs.newBlockingSingleThreaded( "plumber_merge_%d", 1, Thread.MIN_PRIORITY ); } if (scheduledExecutor == null) { scheduledExecutor = Executors.newScheduledThreadPool( 1, Execs.makeThreadFactory("plumber_scheduled_%d", Thread.MIN_PRIORITY) ); } }</code><technical_language>this configurable leave null default. user decide priority run persist threads</technical_language>

Target:
protected void initializeExecutors() { final int maxPendingPersists = config.getMaxPendingPersists(); if (persistExecutor == null) { persistExecutor = Execs.newBlockingSingleThreaded( "plumber_persist_%d", maxPendingPersists, TaskThreadPriority.getThreadPriorityFromTaskPriority(config.getPersistThreadPriority()) ); } if (mergeExecutor == null) { mergeExecutor = Execs.newBlockingSingleThreaded( "plumber_merge_%d", 1, TaskThreadPriority.getThreadPriorityFromTaskPriority(config.getMergeThreadPriority()) ); } if (scheduledExecutor == null) { scheduledExecutor = Execs.scheduledSingleThreaded("plumber_scheduled_%d"); } }
Source:
<code>public Optional<Image> loadImage(final String imageName) { final URL url = getResource(imageName); if (url == null) { return Optional.empty(); } try { <START> return Optional.ofNullable(ImageIO.read(url)); <END> } catch (final IOException e) { log.log(Level.SEVERE, "Image loading failed: " + imageName, e); return Optional.empty(); } }</code><technical_language>Hmm suggest logging some kind of error message if ImageIO.read returns null. map makers realize invalid image attempted get loaded</technical_language>

Target:
public Optional<Image> loadImage(final String imageName) { final URL url = getResource(imageName); if (url == null) { return Optional.empty(); } try { final BufferedImage bufferedImage = ImageIO.read(url); if (bufferedImage == null) { log.severe("Unsupported Image Format: " + url); } return Optional.ofNullable(bufferedImage); } catch (final IOException e) { log.log(Level.SEVERE, "Image loading failed: " + imageName, e); return Optional.empty(); } }
Source:
<code>private String appendDomainRealms(List<String> realms) throws AuthenticationException { StringBuffer text = new StringBuffer(" [domain_realm]\n"); if (!domainRealmMappingFileExits()) { for (String realm : realms) { text.append("\t" + realm.toLowerCase() + " = " + realm.toUpperCase() + "\n"); } } else { try (BufferedReader reader = <START> new BufferedReader(new InputStreamReader(new FileInputStream(domainRealmMappingFile), "UTF-8"))) { <END> while (true) { String readLine = reader.readLine(); if (readLine == null) { break; } text.append("\t").append(readLine).append("\n"); } } catch (FileNotFoundException e) { } catch (IOException e) { } } return text.toString(); }</code><technical_language>This works in case (since of users UTF-8 today), safer java.nio.charset.Charset.defaultCharset()</technical_language>

Target:
private String appendDomainRealms(List<String> realms) throws AuthenticationException { StringBuffer text = new StringBuffer(" [domain_realm]\n"); if (!domainRealmMappingFileExits()) { for (String realm : realms) { text.append("\t" + realm.toLowerCase() + " = " + realm.toUpperCase() + "\n"); } } else { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(domainRealmMappingFile), java.nio.charset.Charset.defaultCharset().displayName()))) { while (true) { String readLine = reader.readLine(); if (readLine == null) { break; } text.append("\t").append(readLine).append("\n"); } } catch (FileNotFoundException e) { } catch (IOException e) { } } return text.toString(); }
Source:
<code>public Contentlet findContentletForLanguage(long languageId, Identifier contentletId) throws DotDataException, DotSecurityException { try { return findContentletByIdentifier(contentletId.getId(), false, languageId, APILocator.systemUser(), false); } catch (DotContentletStateException dcs) { <START> Logger.debug(this, "No working contentlet found for language: "+ languageId); <END> } return null; }</code><technical_language>add identifier exception message, is useful</technical_language>

Target:
public Contentlet findContentletForLanguage(long languageId, Identifier contentletId) throws DotDataException, DotSecurityException { try { return findContentletByIdentifier(contentletId.getId(), false, languageId, APILocator.systemUser(), false); } catch (DotContentletStateException dcs) { Logger.debug(this, ()->String.format("No working contentlet found for language: %d and identifier: %s ", languageId, null != contentletId ? contentletId.getId() : "Unkown")); } return null; }