auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void fixBlackBackground() { flatGroups.clear(); favoriteGroups.clear(); for (FavouritePoint fp : cachedFavoritePoints) { if (fp.getColor() == 0xFF000000) { fp.setColor(0); } FavoriteGroup group = getOrCreateGroup(fp, 0); group.points.add(fp); } sortAll(); saveCurrentPointsIntoFile(); context.runInUIThread(new Runnable() { @Override public void run() { for (FavoritesListener listener : listeners) { listener.onFavoritesLoaded(); } } }); }

Target:
void fixBlackBackground() { flatGroups.clear(); favoriteGroups.clear(); for (FavouritePoint fp : cachedFavoritePoints) { if (fp.getColor() == 0xFF000000 || fp.getColor() == ContextCompat.getColor(context, R.color.color_favorite)) { fp.setColor(0); } if (fp.getBackgroundType() == FavouritePoint.DEFAULT_BACKGROUND_TYPE){ fp.setBackgroundType(null); } if(fp.getIconId()== FavouritePoint.DEFAULT_UI_ICON_ID){ fp.setIconId(0); } FavoriteGroup group = getOrCreateGroup(fp, 0); group.points.add(fp); } sortAll(); saveCurrentPointsIntoFile(); notifyListeners(); }
Source:
public void given__multibranch_with_primary__when__reporting_health__then__non_empty() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "stable"); c.setPrimaryBranch("foo", "stable"); HealthReportingMultiBranchProject prj = r.jenkins.createProject(HealthReportingMultiBranchProject.class, "foo"); prj.setCriteria(null); prj.getSourcesList().add(new BranchSource(new MockSCMSource(c, "foo", new MockSCMDiscoverBranches()))); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); prj.getHealthMetrics().replaceBy(Collections.singletonList(new PrimaryBranchHealthMetric())); prj.invalidateBuildHealthReports(); FreeStyleProject master = prj.getItem("master"); assertThat("We now have the master branch", master, notNullValue()); FreeStyleProject stable = prj.getItem("stable"); assertThat("We now have the stable branch", stable, notNullValue()); assertThat(prj.getBuildHealthReports(), not(containsInAnyOrder( master.getBuildHealthReports().stream().map(Matchers::is).collect(Collectors.toList()) ))); assertThat(prj.getBuildHealthReports(), containsInAnyOrder( stable.getBuildHealthReports().stream().map(Matchers::is).collect(Collectors.toList()) )); } }

Target:
public void given__multibranch_with_primary__when__reporting_health__then__non_empty() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "stable"); c.setPrimaryBranch("foo", "stable"); HealthReportingMultiBranchProject prj = r.jenkins.createProject(HealthReportingMultiBranchProject.class, "foo"); prj.setCriteria(null); prj.getSourcesList().add(new BranchSource(new MockSCMSource(c, "foo", new MockSCMDiscoverBranches()))); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); prj.getHealthMetrics().replaceBy(Collections.singletonList(new PrimaryBranchHealthMetric())); prj.invalidateBuildHealthReports(); FreeStyleProject master = prj.getItem("master"); assertThat("We now have the master branch", master, notNullValue()); FreeStyleProject stable = prj.getItem("stable"); assertThat("We now have the stable branch", stable, notNullValue()); assertThat( "none of 'master' branch's reports should be present as it is not the primary branch", prj.getBuildHealthReports(), everyItem(not(is(in(master.getBuildHealthReports().toArray())))) ); assertThat( "'stable' branch's reports should be exactly the reports as it is the primary branch", prj.getBuildHealthReports(), containsInAnyOrder(stable.getBuildHealthReports().toArray()) ); } }
Source:
public void testThreadNamePatterns() { ThreadNameInfo name = new ThreadNameInfo(100, 1, 2, "nodeX", "eviction"); String threadName = name.format(Thread.currentThread(), "infinispan-%n-%c-p%f-t%t"); assertEquals("infinispan-nodeX-eviction-p2-t1", threadName); }

Target:
public void testThreadNamePatterns() { ThreadNameInfo name = new ThreadNameInfo(100, 1, 2, "nodeX", "eviction"); String threadName = name.format(Thread.currentThread(), "infinispan-%n-%c-p%f-t%t"); assertEquals("infinispan-nodeX-eviction-p2-t1", threadName); threadName = name.format(Thread.currentThread(), "%%-%g%p%"); assertEquals("%-100system:main", threadName); }
Source:
public static void assertDirectoryIsWritable(final File dir) { if (dir == null) { throw new IllegalArgumentException("Cannot check readability of null file."); } else if (!dir.exists()) { throw new SAMException("Directory does not exist: " + dir.getAbsolutePath()); } else if (!dir.isDirectory()) { throw new SAMException("Cannot write to directory because it is not a directory: " + dir.getAbsolutePath()); } else if (!dir.canWrite()) { throw new SAMException("Directory exists but is not writable: " + dir.getAbsolutePath()); } }

Target:
public static void assertDirectoryIsWritable(final File dir) { final Path asPath = (dir == null) ? null : dir.toPath(); assertDirectoryIsWritable(asPath); }
Source:
public boolean isReferencingJSLib(IFile file, String libName) { if(IonicConstants.IONIC_CATEGORY.equals(libName)) { return JSRecognizer.getJSReferenceVersion(file, "ionic") != null; } return false; }

Target:
public boolean isReferencingJSLib(IFile file, String libName) { if(IonicConstants.IONIC_CATEGORY.equals(libName)) { return IonicRecognizer.isReferencingIonicLib(file); } return false; }
Source:
protected Integer calculateRecordsGRAPHQL(String response, String table_name) { Integer rec; try { JSONObject j = new JSONObject(response); try { JSONObject j2 = j.getJSONObject("data"); try { JSONObject j3 = j2.getJSONObject(table_name); try { rec = j3.getJSONArray("edges").length(); } catch (JSONException e4) { rec = null; } } catch (JSONException e3) { rec = null; } } catch (JSONException e2) { rec = null; } } catch (JSONException e) { rec = null; } return rec; }

Target:
protected Integer calculateRecordsGRAPHQL(String response, String table_name) { Integer rec; try { JSONObject j = new JSONObject(response); JSONObject j2 = j.getJSONObject("data"); JSONObject j3 = j2.getJSONObject(table_name); rec = j3.getJSONArray("edges").length(); } catch (JSONException e) { rec = null; } return rec; }
Source:
private boolean isRequestExpired(SamzaResourceRequest request) { long currTime = Instant.now().toEpochMilli(); boolean requestExpired = currTime - request.getRequestTimestamp().toEpochMilli() > getRequestTimeout(request); if (requestExpired) { LOG.info("Request for Processor ID: on host: with creation time: has expired at current time: after timeout: ms.", request.getProcessorId(), request.getPreferredHost(), request.getRequestTimestamp(), currTime, requestExpiryTimeout); } return requestExpired; }

Target:
private boolean isRequestExpired(SamzaResourceRequest request) { long currTime = Instant.now().toEpochMilli(); boolean requestExpired = currTime - request.getRequestTimestamp().toEpochMilli() > getRequestTimeout(request).toMillis(); if (requestExpired) { LOG.info("Request for Processor ID: on host: with creation time: has expired at current time: after timeout: ms.", request.getProcessorId(), request.getPreferredHost(), request.getRequestTimestamp(), currTime, getRequestTimeout(request).toMillis()); } return requestExpired; }
Source:
public InputRow parse(Object input) { try { if(thriftClass == null) { thriftClass = getThriftClass(); } } catch (IOException e) { throw new IAE(e, "failed to load jar [%s]", jarPath); } catch (ClassNotFoundException e) { throw new IAE(e, "class [%s] not found in jar", thriftClassName); } catch (InstantiationException e) { throw new IAE(e, "instantiation thrift instance failed"); } catch (IllegalAccessException e) { throw new IAE(e, "instantiation thrift instance failed, IllegalAccessException"); } try { final byte[] bytes; if (input instanceof BytesWritable) { bytes = ((BytesWritable) input).getBytes(); } else if (input instanceof ByteBuffer) { bytes = ((ByteBuffer) input).array(); } else { throw new IAE("unsupport input class of [%s]", input.getClass()); } TBase o = thriftClass.newInstance(); deserializer.deserialize(o, bytes); String json = serializer.toString(o); Map<String, Object> record = parser.parse(json); return new MapBasedInputRow( parseSpec.getTimestampSpec().extractTimestamp(record), parseSpec.getDimensionsSpec().getDimensionNames(), record ); } catch (Exception e) { return null; } }

Target:
public InputRow parse(Object input) { try { if (thriftClass == null) { thriftClass = getThriftClass(); } } catch (IOException e) { throw new IAE(e, "failed to load jar [%s]", jarPath); } catch (ClassNotFoundException e) { throw new IAE(e, "class [%s] not found in jar", thriftClassName); } catch (InstantiationException | IllegalAccessException e) { throw new IAE(e, "instantiation thrift instance failed"); } final String json; try { if (input instanceof ByteBuffer) { final byte[] bytes = ((ByteBuffer) input).array(); TBase o = thriftClass.newInstance(); ThriftDeserialization.detectAndDeserialize(bytes, o); json = ThriftDeserialization.SERIALIZER_SIMPLE_JSON.get().toString(o); } else if (input instanceof BytesWritable) { final byte[] bytes = ((BytesWritable) input).getBytes(); TBase o = thriftClass.newInstance(); ThriftDeserialization.detectAndDeserialize(bytes, o); json = ThriftDeserialization.SERIALIZER_SIMPLE_JSON.get().toString(o); } else if (input instanceof ThriftWritable) { TBase o = (TBase) ((ThriftWritable) input).get(); json = ThriftDeserialization.SERIALIZER_SIMPLE_JSON.get().toString(o); } else { throw new IAE("unsupport input class of [%s]", input.getClass()); } } catch (IllegalAccessException | InstantiationException | TException e) { throw new IAE("some thing wrong with your thrift?"); } Map<String, Object> record = parser.parse(json); return new MapBasedInputRow( parseSpec.getTimestampSpec().extractTimestamp(record), parseSpec.getDimensionsSpec().getDimensionNames(), record ); }
Source:
@Override public void processCrossBreedingMethod(CrossSetting crossSetting, ImportedCrossesList importedCrossesList) { final BreedingMethodSetting methodSetting = crossSetting.getBreedingMethodSetting(); for (ImportedCrosses importedCrosses : importedCrossesList.getImportedCrosses()) { if (!StringUtils.isEmpty(importedCrosses.getRawBreedingMethod())) { final Method breedingMethod = this.germplasmDataManager.getMethodByCode(importedCrosses.getRawBreedingMethod()); if (breedingMethod != null && breedingMethod.getMid() != null && breedingMethod.getMid() != 0) { importedCrosses.setBreedingMethodId(breedingMethod.getMid()); } } if (importedCrosses.isBreedingMethodInformationAvailable()) { continue; } if (methodSetting.isBasedOnStatusOfParentalLines()) { final Integer femaleGid = importedCrosses.getGpid1(); final Integer maleGid = importedCrosses.getGpid2(); Triple<Germplasm, Germplasm, Germplasm> femaleLine = retrieveParentGermplasmObjects(femaleGid); Triple<Germplasm, Germplasm, Germplasm> maleLine = retrieveParentGermplasmObjects(maleGid); importedCrosses.setBreedingMethodId(CrossingUtil.determineBreedingMethodBasedOnParentalLine(femaleLine.getLeft(), maleLine.getLeft(), femaleLine.getMiddle(), femaleLine.getRight(), maleLine.getMiddle(), maleLine.getRight())); } else { importedCrosses.setBreedingMethodId(methodSetting.getMethodId()); } } }

Target:
public void processCrossBreedingMethod(CrossSetting crossSetting, ImportedCrossesList importedCrossesList) { final BreedingMethodSetting methodSetting = crossSetting.getBreedingMethodSetting(); for (ImportedCrosses importedCrosses : importedCrossesList.getImportedCrosses()) { if (!StringUtils.isEmpty(importedCrosses.getRawBreedingMethod())) { final Method breedingMethod = this.germplasmDataManager.getMethodByCode(importedCrosses.getRawBreedingMethod()); if (breedingMethod != null && breedingMethod.getMid() != null && breedingMethod.getMid() != 0) { importedCrosses.setBreedingMethodId(breedingMethod.getMid()); } else { importedCrosses.setBreedingMethodId(0); } } if (importedCrosses.isBreedingMethodInformationAvailable()) { continue; } if (methodSetting.getMethodId() == null || methodSetting.getMethodId() == 0) { final Integer femaleGid = Integer.parseInt(importedCrosses.getFemaleGid()); final Integer maleGid = Integer.parseInt(importedCrosses.getMaleGid()); Triple<Germplasm, Germplasm, Germplasm> femaleLine = retrieveParentGermplasmObjects(femaleGid); Triple<Germplasm, Germplasm, Germplasm> maleLine = retrieveParentGermplasmObjects(maleGid); importedCrosses.setBreedingMethodId(CrossingUtil.determineBreedingMethodBasedOnParentalLine(femaleLine.getLeft(), maleLine.getLeft(), femaleLine.getMiddle(), femaleLine.getRight(), maleLine.getMiddle(), maleLine.getRight())); } else { importedCrosses.setBreedingMethodId(methodSetting.getMethodId()); } } }
Source:
public boolean isChildPolicyAllowed(SchedulingPolicy childPolicy) { if (childPolicy instanceof DominantResourceFairnessPolicy) { LOG.info("Queue policies can't be " + DominantResourceFairnessPolicy.NAME + " if the parent policy is " + getName() + ". Please choose " + "other polices for child queues instead."); return false; } return true; }

Target:
public boolean isChildPolicyAllowed(SchedulingPolicy childPolicy) { if (childPolicy instanceof DominantResourceFairnessPolicy) { LOG.error("Queue policy can't be " + DominantResourceFairnessPolicy.NAME + " if the parent policy is " + getName() + ". Choose " + getName() + " or " + FifoPolicy.NAME + " for child queues instead." + " Please note that " + FifoPolicy.NAME + " is only for leaf queues."); return false; } return true; }
Source:
public static File defaultFile(FilterConfig filterConfig) { String configPath = null; if (configPath == null) { configPath = System.getProperty(PROPERTY_NAME, DEFAULT_PATH); } else if (filterConfig != null) { configPath = filterConfig.getInitParameter(FILTER_CONFIG_PARAM); } return new File(configPath); }

Target:
public static File defaultFile(FilterConfig filterConfig) { String configPath = System.getProperty(PROPERTY_NAME, DEFAULT_PATH); if (configPath == null && filterConfig != null) { configPath = filterConfig.getInitParameter(FILTER_CONFIG_PARAM); } return new File(configPath); }
Source:
public void processConditional(CharSequence chars, IElementType type) { if (PPIF.equals(type)) { currentContext = new Section(currentContext, type); } else if (PPELSE.equals(type)) { currentContext.startBlock(type); } else if (PPELSEIF.equals(type)) { currentContext.startBlock(type); } else if (PPEND.equals(type)) { currentContext.endBlock(getCurrentBlock()); Section parent = currentContext.getParent(); if (null != parent) { currentContext = parent; } } }

Target:
public void processConditional(CharSequence chars, IElementType type) { if (PPIF.equals(type)) { Section newSection = new Section(currentContext, type); currentContext = newSection; } else if (PPELSE.equals(type)) { currentContext.startBlock(type); } else if (PPELSEIF.equals(type)) { currentContext.startBlock(type); } else if (PPEND.equals(type)) { currentContext.endBlock(getCurrentBlock()); Section parent = currentContext.getParent(); if (null != parent) { currentContext = parent; } } }
Source:
public String getJobCoordinationUtilsFactoryClassName() { String className = get(JOB_COORDINATION_UTILS_FACTORY, DEFAULT_COORDINATION_UTILS_FACTORY); if (Strings.isNullOrEmpty(className)) { throw new SamzaException("Failed to read config value for " + JOB_COORDINATION_UTILS_FACTORY + " = " + className); } try { Class.forName(className); } catch (ClassNotFoundException e) { throw new SamzaException( "Failed to validate config value for " + JOB_COORDINATION_UTILS_FACTORY + " = " + className, e); } return className; }

Target:
public String getJobCoordinationUtilsFactoryClassName() { String className = get(JOB_COORDINATION_UTILS_FACTORY, DEFAULT_COORDINATION_UTILS_FACTORY); if (Strings.isNullOrEmpty(className)) { throw new SamzaException("Empty config for " + JOB_COORDINATION_UTILS_FACTORY + " = " + className); } try { Class.forName(className); } catch (ClassNotFoundException e) { throw new SamzaException( "Failed to validate config value for " + JOB_COORDINATION_UTILS_FACTORY + " = " + className, e); } return className; }
Source:
private Map<TableReference, byte[]> filterOutExistingTables( final Map<TableReference, byte[]> tableNamesToTableMetadata) { Map<TableReference, byte[]> filteredTables = Maps.newHashMap(); try { Set<TableReference> existingTablesLowerCased = cassandraTables.getExistingLowerCased().stream() .map(AbstractKeyValueService::fromInternalTableName) .collect(Collectors.toSet()); for (Entry<TableReference, byte[]> tableAndMetadataPair : tableNamesToTableMetadata.entrySet()) { TableReference table = tableAndMetadataPair.getKey(); byte[] metadata = tableAndMetadataPair.getValue(); CassandraVerifier.sanityCheckTableName(table); TableReference tableRefLowerCased = TableReference.createLowerCased(table); if (!existingTablesLowerCased.contains(tableRefLowerCased)) { filteredTables.put(table, metadata); } else { log.debug("Filtering out existing table ({}) that already existed (case insensitive).", LoggingArgs.tableRef(table)); } } } catch (Exception e) { Throwables.unwrapAndThrowDependencyUnavailableException(e); } return filteredTables; }

Target:
private Map<TableReference, byte[]> filterOutExistingTables( final Map<TableReference, byte[]> tableNamesToTableMetadata) { Map<TableReference, byte[]> filteredTables = Maps.newHashMap(); try { Set<TableReference> existingTablesLowerCased = cassandraTables.getExistingLowerCased().stream() .map(AbstractKeyValueService::fromInternalTableName) .collect(Collectors.toSet()); for (Entry<TableReference, byte[]> tableAndMetadataPair : tableNamesToTableMetadata.entrySet()) { TableReference table = tableAndMetadataPair.getKey(); byte[] metadata = tableAndMetadataPair.getValue(); CassandraVerifier.sanityCheckTableName(table); TableReference tableRefLowerCased = TableReference.createLowerCased(table); if (!existingTablesLowerCased.contains(tableRefLowerCased)) { filteredTables.put(table, metadata); } else { log.debug("Filtering out existing table ({}) that already existed (case insensitive).", LoggingArgs.tableRef(table)); } } } catch (Exception e) { throw Throwables.unwrapAndThrowDependencyUnavailableException(e); } return filteredTables; }
Source:
public int partitions() { lock.readLock().lock(); try { return partitions.length; } finally { lock.readLock().unlock(); } }

Target:
public int partitions() { return partitions.length; }
Source:
public static boolean tryActivate(@Nonnull Event e, @Nonnull SlimefunItemStack stack) { return (tryActivateAndGet(e, stack.getItem()) != null); }

Target:
public static boolean tryActivate(@Nonnull Event e, @Nonnull SlimefunItemStack stack) { return tryActivateAndGet(e, stack.getItem()) != null; }
Source:
public void testMissingLocalDatacenter() { try (CassandraContainer<?> cassandraContainer = new CassandraContainer<>(CASSANDRA_IMAGE)) { cassandraContainer.start(); CqlSession.builder().addContactPoint(cassandraContainer.getContactPoint()).build(); } }

Target:
public void testMissingLocalDatacenter() { try (CassandraContainer<?> cassandraContainer = new CassandraContainer<>(CASSANDRA_IMAGE)) { cassandraContainer.start(); CqlSession.builder().addContactPoint(cassandraContainer.getContactPoint()).build(); fail("Session build should fail if no local Datacenter provided"); } catch (IllegalStateException ise) { String msg = "Since you provided explicit contact points, the local DC must be explicitly set"; assertThat(ise.getMessage(), containsString(msg)); } }
Source:
private void addGroupTreeItemsField(Composite parent) { Composite groupComposite = createGroup(parent, "Group tree items"); groupEnable = new BooleanFieldEditorWithHelp(CommonPreferencesConstants.PREF_GROUP_ENABLE, "Enable", "This feature handles a new intermediary tree level if the children size is above the threshold.", new Composite(groupComposite, SWT.NONE)); Composite groupTriggerComposite = new Composite(groupComposite, SWT.NONE); groupTriggerComposite.setLayout(new GridLayout(3, false)); groupTriggerComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); groupTrigger = new IntegerFieldEditorWithHelp(CommonPreferencesConstants.PREF_GROUP_TRIGGER, "Threshold", "The threshold needs to be higher or equal to the group size (Else Threshold = Group size).", groupTriggerComposite); groupTrigger.setValidRange(0, Integer.MAX_VALUE); Composite groupSizeComposite = new Composite(groupComposite, SWT.NONE); groupSizeComposite.setLayout(new GridLayout(3, false)); groupSizeComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); groupSize = new IntegerFieldEditorWithHelp(CommonPreferencesConstants.PREF_GROUP_SIZE, "Group size", "Group size needs to be higher than zero.", groupSizeComposite); groupSize.setValidRange(0, Integer.MAX_VALUE); addField(groupEnable); addField(groupTrigger); addField(groupSize); }

Target:
private void addGroupTreeItemsField(Composite parent) { Composite groupComposite = createGroup(parent, "Group tree items"); groupEnable = new BooleanFieldEditorWithHelp(CommonPreferencesConstants.PREF_GROUP_ENABLE, "Enable", "This feature handles a new intermediary tree level if the children size is above the threshold.", new Composite(groupComposite, SWT.NONE)); Composite groupTriggerComposite = new Composite(groupComposite, SWT.NONE); groupTriggerComposite.setLayout(new GridLayout(3, false)); groupTriggerComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); groupTrigger = new IntegerFieldEditorWithHelp(CommonPreferencesConstants.PREF_GROUP_TRIGGER, "Threshold", "The threshold needs to be higher or equal to the group size (otherwise Threshold = Group size).", groupTriggerComposite); groupTrigger.setValidRange(0, Integer.MAX_VALUE); Composite groupSizeComposite = new Composite(groupComposite, SWT.NONE); groupSizeComposite.setLayout(new GridLayout(3, false)); groupSizeComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); groupSize = new IntegerFieldEditorWithHelp(CommonPreferencesConstants.PREF_GROUP_SIZE, "Group size", "Group size needs to be higher than zero.", groupSizeComposite); groupSize.setValidRange(0, Integer.MAX_VALUE); addField(groupEnable); addField(groupTrigger); addField(groupSize); }
Source:
public Map<Parameter, MappingOptions> groupBySourceParameter(List<Mapping> mappings) { Map<Parameter, List<Mapping>> mappingsKeyedByParameterType = new HashMap<Parameter, List<Mapping>>(); for ( Mapping mapping : mappings ) { if ( mapping.getSourceReference() != null && mapping.getSourceReference().isValid() ) { Parameter parameter = mapping.getSourceReference().getParameter(); if ( !mappingsKeyedByParameterType.containsKey( parameter ) ) { mappingsKeyedByParameterType.put( parameter, new ArrayList<Mapping>() ); } mappingsKeyedByParameterType.get( parameter ).add( mapping ); } } Map<Parameter, MappingOptions> result = new HashMap<Parameter, MappingOptions>(); for ( Map.Entry<Parameter, List<Mapping>> entry : mappingsKeyedByParameterType.entrySet() ) { result.put( entry.getKey(), MappingOptions.forMappingsOnly( groupByTargetName( entry.getValue() ) ) ); } return result; }

Target:
public Map<Parameter, List<Mapping>> groupBySourceParameter(List<Mapping> mappings) { Map<Parameter, List<Mapping>> mappingsKeyedByParameter = new HashMap<Parameter, List<Mapping>>(); for ( Mapping mapping : mappings ) { if ( mapping.getSourceReference() != null && mapping.getSourceReference().isValid() ) { Parameter parameter = mapping.getSourceReference().getParameter(); if ( !mappingsKeyedByParameter.containsKey( parameter ) ) { mappingsKeyedByParameter.put( parameter, new ArrayList<Mapping>() ); } mappingsKeyedByParameter.get( parameter ).add( mapping ); } } return mappingsKeyedByParameter; }
Source:
public void setSource(MessageSource<?> source) { ProxyFactory pf = new ProxyFactory(source); class ReceiveAdvice implements MethodInterceptor { private final List<ChannelInterceptor> interceptors = new ArrayList<>(); @Override public Object invoke(MethodInvocation invocation) throws Throwable { Object result = invocation.proceed(); if (result instanceof Message) { Message<?> received = (Message<?>) result; for (ChannelInterceptor interceptor : this.interceptors) { received = interceptor.preSend(received, null); if (received == null) { break; } } return received; } return result; } } final ReceiveAdvice advice = new ReceiveAdvice(); advice.interceptors.addAll(this.interceptors); NameMatchMethodPointcutAdvisor sourceAdvisor = new NameMatchMethodPointcutAdvisor(advice); sourceAdvisor.addMethodName("receive"); pf.addAdvisor(sourceAdvisor); this.source = (MessageSource<?>) pf.getProxy(); this.pollingTemplate = new MessageSourcePollingTemplate(this.source); }

Target:
public void setSource(MessageSource<?> source) { ProxyFactory pf = new ProxyFactory(source); class ReceiveAdvice implements MethodInterceptor { private final List<ChannelInterceptor> interceptors = new ArrayList<>(); @Override public Object invoke(MethodInvocation invocation) throws Throwable { Object result = invocation.proceed(); if (result instanceof Message) { Message<?> received = (Message<?>) result; for (ChannelInterceptor interceptor : this.interceptors) { received = interceptor.preSend(received, null); if (received == null) { return null; } } return received; } return result; } } final ReceiveAdvice advice = new ReceiveAdvice(); advice.interceptors.addAll(this.interceptors); NameMatchMethodPointcutAdvisor sourceAdvisor = new NameMatchMethodPointcutAdvisor(advice); sourceAdvisor.addMethodName("receive"); pf.addAdvisor(sourceAdvisor); this.source = (MessageSource<?>) pf.getProxy(); }
Source:
public void setPlayer(Player player) { this.player = player; CountryCode countryCode = CountryCode.getByCode(player.getCountry()); usernameLabel.setText(player.getUsername()); userImageView.setImage(IdenticonUtil.createIdenticon(player.getId())); countryFlagService.loadCountryFlag(player.getCountry()).ifPresent(image -> countryImageView.setImage(image)); countryLabel.setText(countryCode == null ? player.getCountry() : countryCode.getName()); JavaFxUtil.addListener(player.globalRatingMeanProperty(), (observable) -> loadReceiverGlobalRatingInformation(player)); JavaFxUtil.addListener(player.globalRatingDeviationProperty(), (observable) -> loadReceiverGlobalRatingInformation(player)); loadReceiverGlobalRatingInformation(player); JavaFxUtil.addListener(player.leaderboardRatingMeanProperty(), (observable) -> loadReceiverLadderRatingInformation(player)); JavaFxUtil.addListener(player.leaderboardRatingDeviationProperty(), (observable) -> loadReceiverLadderRatingInformation(player)); loadReceiverLadderRatingInformation(player); JavaFxUtil.addListener(player.gameProperty(), observable -> onPlayerGameChanged(player.getGame())); onPlayerGameChanged(player.getGame()); gamesPlayedLabel.textProperty().bind(player.numberOfGamesProperty().asString()); populateUnlockedAchievementsLabel(player); }

Target:
public void setPlayer(Player player) { CountryCode countryCode = CountryCode.getByCode(player.getCountry()); usernameLabel.setText(player.getUsername()); userImageView.setImage(IdenticonUtil.createIdenticon(player.getId())); countryFlagService.loadCountryFlag(player.getCountry()).ifPresent(image -> countryImageView.setImage(image)); countryLabel.setText(countryCode == null ? player.getCountry() : countryCode.getName()); globalRatingInvalidationListener = (observable) -> loadReceiverGlobalRatingInformation(player); JavaFxUtil.addListener(player.globalRatingMeanProperty(), new WeakInvalidationListener(globalRatingInvalidationListener)); JavaFxUtil.addListener(player.globalRatingDeviationProperty(), new WeakInvalidationListener(globalRatingInvalidationListener)); loadReceiverGlobalRatingInformation(player); leaderboardRatingInvalidationListener = (observable) -> loadReceiverLadderRatingInformation(player); JavaFxUtil.addListener(player.leaderboardRatingMeanProperty(), new WeakInvalidationListener(leaderboardRatingInvalidationListener)); JavaFxUtil.addListener(player.leaderboardRatingDeviationProperty(), new WeakInvalidationListener(leaderboardRatingInvalidationListener)); loadReceiverLadderRatingInformation(player); gameInvalidationListener = observable -> onPlayerGameChanged(player.getGame()); JavaFxUtil.addListener(player.gameProperty(), new WeakInvalidationListener(gameInvalidationListener)); onPlayerGameChanged(player.getGame()); JavaFxUtil.bind(gamesPlayedLabel.textProperty(), player.numberOfGamesProperty().asString()); populateUnlockedAchievementsLabel(player); }
Source:
protected List<RawUsageRecord> getUsageFromPlugin(final LocalDate startDate, final LocalDate endDate, final TenantContext tenantContext) { final Set<String> allServices = pluginRegistry.getAllServices(); if (allServices.isEmpty()) { return null; } for (final String service : allServices) { final UsagePluginApi plugin = pluginRegistry.getServiceForName(service); final List<RawUsageRecord> result = plugin.geUsageForAccount(startDate, endDate, tenantContext); if (result != null) { for (final RawUsageRecord cur : result) { if (cur.getDate().compareTo(startDate) < 0 || cur.getDate().compareTo(endDate) >=0) { logger.warn("Usage plugin returned usage data with date %s, not in the specified range [%s -> %s[", cur.getDate(), startDate, endDate); } } return result; } } return null; }

Target:
protected List<RawUsageRecord> getUsageFromPlugin(final LocalDate startDate, final LocalDate endDate, final TenantContext tenantContext) { final Set<String> allServices = pluginRegistry.getAllServices(); if (allServices.isEmpty()) { return null; } for (final String service : allServices) { final UsagePluginApi plugin = pluginRegistry.getServiceForName(service); final List<RawUsageRecord> result = plugin.geUsageForAccount(startDate, endDate, tenantContext); if (result != null) { for (final RawUsageRecord cur : result) { if (cur.getDate().compareTo(startDate) < 0 || cur.getDate().compareTo(endDate) >=0) { logger.warn("Usage plugin returned usage data with date {}, not in the specified range [{} -> {}[", cur.getDate(), startDate, endDate); } } return result; } } return null; }
Source:
public Object get(Object key) { String strKey = (String) key; if (super.containsKey(strKey)) { return super.get(strKey); } if (parameterMetaObject == null) { return null; } if (fallbackParameterObject) { return parameterMetaObject.hasGetter(strKey) ? parameterMetaObject.getValue(strKey) : parameterMetaObject.getOriginalObject(); } else { return parameterMetaObject.getValue(strKey); } }

Target:
public Object get(Object key) { String strKey = (String) key; if (super.containsKey(strKey)) { return super.get(strKey); } if (parameterMetaObject == null) { return null; } if (fallbackParameterObject && !parameterMetaObject.hasGetter(strKey)) { return parameterMetaObject.getOriginalObject(); } else { return parameterMetaObject.getValue(strKey); } }
Source:
private boolean updateTaskProgress(TaskExecutionProgress progress, TaskActivity activity) { boolean taskFinished = progress.getActionsSucceeded() + progress.getActionsFiltered() == progress.getTotalActions(); if (taskFinished) { activity.setActivityType(TaskActivityType.SUCCESS); if (progress.getActionsFiltered() > 0) { activity.setMessage(TASK_SUCCEEDED_WITH_FILTERED_ACTIONS); } else { activity.setMessage(TASK_SUCCEEDED); } activity.getFields().clear(); } updateTaskInProgressMessage(activity); taskActivitiesDataService.update(activity); return taskFinished; }

Target:
private boolean updateTaskProgress(TaskExecutionProgress progress, TaskActivity activity) { boolean taskFinished = (progress.getActionsSucceeded() + progress.getActionsFiltered()) == progress.getTotalActions(); if (taskFinished) { activity.setActivityType(TaskActivityType.SUCCESS); if (progress.getActionsFiltered() > 0) { activity.setMessage(TASK_SUCCEEDED_WITH_FILTERED_ACTIONS); } else { activity.setMessage(TASK_SUCCEEDED); } activity.getFields().clear(); } updateTaskInProgressMessage(activity); taskActivitiesDataService.update(activity); return taskFinished; }
Source:
public DeleteTableCallback(Table table, CompiledCondition compiledCondition, int matchingStreamIndex, boolean convertToStreamEvent, StateEventPool stateEventPool, StreamEventPool streamEventPool, StreamEventConverter streamEventConverter, String queryName) { this.matchingStreamIndex = matchingStreamIndex; this.table = table; this.compiledCondition = compiledCondition; this.convertToStreamEvent = convertToStreamEvent; this.stateEventPool = stateEventPool; this.streamEventPool = streamEventPool; this.streamEventConverter = streamEventConverter; setQueryName(queryName); }

Target:
public DeleteTableCallback(Table table, CompiledCondition compiledCondition, int matchingStreamIndex, boolean convertToStreamEvent, StateEventPool stateEventPool, StreamEventPool streamEventPool, StreamEventConverter streamEventConverter, String queryName) { super(queryName); this.matchingStreamIndex = matchingStreamIndex; this.table = table; this.compiledCondition = compiledCondition; this.convertToStreamEvent = convertToStreamEvent; this.stateEventPool = stateEventPool; this.streamEventPool = streamEventPool; this.streamEventConverter = streamEventConverter; }
Source:
public void testTooLowSCNWithTTL() throws Exception { int ttl = 2; String fullTableName = createTableWithTTL(ttl); Thread.sleep(ttl * 1000 + 1000); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(EnvironmentEdgeManager.currentTime() - (ttl + 1)* 1000)); try (Connection connscn = DriverManager.getConnection(getUrl(), props)) { connscn.createStatement().executeQuery("select * from " + fullTableName); } catch (SQLException se){ assertEquals(SQLExceptionCode.CANNOT_QUERY_TABLE_WITH_SCN_OLDER_THAN_TTL.getErrorCode(), se.getErrorCode()); assertTrue("Wrong error message", se.getMessage(). contains(SQLExceptionCode.CANNOT_QUERY_TABLE_WITH_SCN_OLDER_THAN_TTL.getMessage())); assertEquals(SQLExceptionCode.CANNOT_QUERY_TABLE_WITH_SCN_OLDER_THAN_TTL.getSQLState(), se.getSQLState()); return; } Assert.fail("We should have thrown an exception for the too-early SCN"); }

Target:
public void testTooLowSCNWithTTL() throws Exception { int ttl = 2; String fullTableName = createTableWithTTL(ttl); int sleepTime = (ttl + 1)* 1000; Thread.sleep(sleepTime); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(EnvironmentEdgeManager.currentTime() - sleepTime)); try (Connection connscn = DriverManager.getConnection(getUrl(), props)) { connscn.createStatement(). executeQuery(String.format("select * from %s", fullTableName)); } catch (SQLException se){ SQLExceptionCode code = SQLExceptionCode.CANNOT_QUERY_TABLE_WITH_SCN_OLDER_THAN_TTL; assertSqlExceptionCode(code, se); return; } Assert.fail("We should have thrown an exception for the too-early SCN"); }
Source:
public Parameters empiBatchOnAllTargets( @OperationParam(name= ProviderConstants.EMPI_BATCH_RUN_CRITERIA,min = 0 , max = 1) StringType theCriteria, ServletRequestDetails theRequestDetails) { String criteria = convertCriteriaToString(theCriteria); long submittedCount = myEmpiSubmitSvc.runEmpiOnAllTargetTypes(criteria); return buildEmpiOutParametersWithCount(submittedCount); }

Target:
public Parameters empiBatchOnAllTargets( @OperationParam(name= ProviderConstants.EMPI_BATCH_RUN_CRITERIA,min = 0 , max = 1) StringType theCriteria, ServletRequestDetails theRequestDetails) { String criteria = convertCriteriaToString(theCriteria); long submittedCount = myEmpiSubmitSvc.submitAllTargetTypesToEmpi(criteria); return buildEmpiOutParametersWithCount(submittedCount); }
Source:
protected TransportWriteAction(Settings settings, String actionName, TransportService transportService, ClusterService clusterService, IndicesService indicesService, ThreadPool threadPool, ShardStateAction shardStateAction, ActionFilters actionFilters, Writeable.Reader<Request> request, Writeable.Reader<ReplicaRequest> replicaRequest, String executor, boolean forceExecutionOnPrimary, WriteMemoryLimits writeMemoryLimits) { super(settings, actionName, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters, request, replicaRequest, ThreadPool.Names.SAME, true, forceExecutionOnPrimary); this.executor = executor; this.writeMemoryLimits = writeMemoryLimits; }

Target:
protected TransportWriteAction(Settings settings, String actionName, TransportService transportService, ClusterService clusterService, IndicesService indicesService, ThreadPool threadPool, ShardStateAction shardStateAction, ActionFilters actionFilters, Writeable.Reader<Request> request, Writeable.Reader<ReplicaRequest> replicaRequest, String executor, boolean forceExecutionOnPrimary, WriteMemoryLimits writeMemoryLimits) { super(settings, actionName, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters, request, replicaRequest, ThreadPool.Names.SAME, true, forceExecutionOnPrimary); this.executor = executor; this.forceExecutionOnPrimary = forceExecutionOnPrimary; this.writeMemoryLimits = writeMemoryLimits; }
Source:
private void processSnapshotMessage(LogReplicationEntry message) { switch (message.getMetadata().getMessageMetadataType()) { case SNAPSHOT_MESSAGE: snapshotWriter.apply(message); break; case SNAPSHOT_END: dataConsistent.set(false); logReplicationMetadataManager.setDataConsistentOnStandby(dataConsistent.get()); snapshotWriter.snapshotTransferDone(message); completeSnapshotApply(message); dataConsistent.set(true); logReplicationMetadataManager.setDataConsistentOnStandby(dataConsistent.get()); break; default: log.warn("Message type should not be applied as snapshot sync.", message.getMetadata().getMessageMetadataType()); } }

Target:
private void processSnapshotMessage(LogReplicationEntry message) { switch (message.getMetadata().getMessageMetadataType()) { case SNAPSHOT_MESSAGE: snapshotWriter.apply(message); break; case SNAPSHOT_END: setDataConsistent(false); snapshotWriter.snapshotTransferDone(message); completeSnapshotApply(message); setDataConsistent(true); break; default: log.warn("Message type should not be applied as snapshot sync.", message.getMetadata().getMessageMetadataType()); } }
Source:
public void test_of_CurrencyAndValueSchedule() { ValueSchedule valueSchedule = ValueSchedule.of(1000d, ValueStep.of(1, ValueAdjustment.ofReplace(2000d))); NotionalSchedule test = NotionalSchedule.of(GBP, valueSchedule); assertEquals(test.getCurrency(), GBP); assertEquals(test.getAmount(), valueSchedule); assertEquals(test.getFxReset(), Optional.empty()); assertEquals(test.isInitialExchange(), false); assertEquals(test.isInitialExchange(), false); assertEquals(test.isIntermediateExchange(), false); assertEquals(test.isFinalExchange(), false); }

Target:
public void test_of_CurrencyAndValueSchedule() { ValueSchedule valueSchedule = ValueSchedule.of(1000d, ValueStep.of(1, ValueAdjustment.ofReplace(2000d))); NotionalSchedule test = NotionalSchedule.of(GBP, valueSchedule); assertEquals(test.getCurrency(), GBP); assertEquals(test.getAmount(), valueSchedule); assertEquals(test.getFxReset(), Optional.empty()); assertEquals(test.isInitialExchange(), false); assertEquals(test.isIntermediateExchange(), false); assertEquals(test.isFinalExchange(), false); }
Source:
public void trackCreateChannel(String userId) { Bundle bundle = new Bundle(); bundle.putString(USER_ID, userId); firebaseAnalytics.logEvent("create_channel", bundle); }

Target:
public void trackCreateChannel(String userId) { Bundle bundle = new Bundle(); bundle.putString(PARAM_USER_ID, userId); firebaseAnalytics.logEvent(EVENT_CREATE_CHANNEL, bundle); }
Source:
private void startAllOperatorCoordinators() { final Collection<OperatorCoordinatorHolder> coordinators = getAllCoordinators(); try { for (OperatorCoordinatorHolder coordinator : coordinators) { coordinator.start(); } } catch (Throwable t) { ExceptionUtils.rethrowIfFatalErrorOrOOM(t); coordinators.forEach(IOUtils::closeQuietly); failJob(new FlinkRuntimeException("Failed to start the operator coordinators", t)); } }

Target:
private void startAllOperatorCoordinators() { final Collection<OperatorCoordinatorHolder> coordinators = getAllCoordinators(); try { for (OperatorCoordinatorHolder coordinator : coordinators) { coordinator.start(); } } catch (Throwable t) { ExceptionUtils.rethrowIfFatalErrorOrOOM(t); coordinators.forEach(IOUtils::closeQuietly); throw new FlinkRuntimeException("Failed to start the operator coordinators", t); } }
Source:
private void updateExistingPaymentWorksVendorInStagingTable(Integer id, String pmwRequestStatus, String kfsVendorProcessingStatus, String kfsAchProcessingStatus, String kfsVendorDocumentNumber, String supplierUploadStatus, Timestamp processingTimeStamp, Integer vendorHeaderGeneratedIdentifier, Integer vendorDetailAssignedIdentifier, String kfsAchDocumentNumber) { try { PreparedStatement preparedSqlStatement = buildUpdateExistingPaymentWorksVendorInStagingTableSql(id, pmwRequestStatus, kfsVendorProcessingStatus, kfsAchProcessingStatus, kfsVendorDocumentNumber, supplierUploadStatus, processingTimeStamp, vendorHeaderGeneratedIdentifier, vendorDetailAssignedIdentifier, kfsAchDocumentNumber); preparedSqlStatement.executeUpdate(); int updatedRowCount = preparedSqlStatement.getUpdateCount(); LOG.info("updateExistingPaymentWorksVendorInStagingTable updated " + updatedRowCount + " record" + (updatedRowCount == 1 ? "" : "s")); } catch (SQLException ex) { LOG.error("updateExistingPaymentWorksVendorInStagingTable", ex); } }

Target:
private void updateExistingPaymentWorksVendorInStagingTable(Integer id, String pmwRequestStatus, String kfsVendorProcessingStatus, String kfsAchProcessingStatus, String kfsVendorDocumentNumber, String supplierUploadStatus, Timestamp processingTimeStamp, Integer vendorHeaderGeneratedIdentifier, Integer vendorDetailAssignedIdentifier, String kfsAchDocumentNumber) { int updatedRowCount = buildUpdateExistingPaymentWorksVendorInStagingTableSql(id, pmwRequestStatus, kfsVendorProcessingStatus, kfsAchProcessingStatus, kfsVendorDocumentNumber, supplierUploadStatus, processingTimeStamp, vendorHeaderGeneratedIdentifier, vendorDetailAssignedIdentifier, kfsAchDocumentNumber); LOG.info("updateExistingPaymentWorksVendorInStagingTable updated " + updatedRowCount + " record" + (updatedRowCount == 1 ? "" : "s")); }
Source:
private void send() { if (json) { try { requestBuilder.async().post(Entity.entity(objectMapper.writeValueAsString(payload), mediaType), this); } catch (JsonProcessingException e) { throw new RuntimeException("Failed to serialize payload to json: " + payload); } } else { requestBuilder.async().get(this); } }

Target:
private void send() { if (json) { try { Entity<String> entity = Entity.entity(objectMapper.writeValueAsString(payload), mediaType); requestBuilder.async().post(entity, this); } catch (JsonProcessingException e) { throw new RuntimeException("Failed to serialize location to json", e); } } else { requestBuilder.async().get(this); } }
Source:
private static List<String> parseCommaSeparatedAttributes(String body, String attribute) { Pattern pattern = Pattern.compile(attribute + "(.*)"); Matcher matcher = pattern.matcher(body); if (matcher.find()) { return Arrays.asList(matcher.group(1).split(",")); } return Collections.emptyList(); }

Target:
private static String[] parseCommaSeparatedAttributes(String body, String attribute) { Pattern pattern = Pattern.compile(Pattern.quote(attribute) + ":\\s*(.*)"); Matcher matcher = pattern.matcher(body); if (matcher.find()) { return matcher.group(1).split(","); } return new String[0]; }
Source:
public static Expression filterConjuncts(Expression expression, Predicate<Expression> predicate) { List<Expression> conjuncts = extractConjuncts(expression).stream() .filter(predicate) .collect(toList()); return combineConjuncts(conjuncts); }

Target:
private static Expression filterConjuncts(Expression expression, Predicate<Expression> predicate) { List<Expression> conjuncts = extractConjuncts(expression).stream() .filter(predicate) .collect(toList()); return combineConjuncts(conjuncts); }
Source:
private AESKeyVersion(Builder builder) throws BuilderException { super(builder); this.keySize = builder.keySize; this.mode = builder.mode; this.padding = builder.padding; this.algModePadding = "AES/" + this.mode + "/" + padding + "padding"; try { if (builder.keyVersionMatterInitVectorProvided) { initVector = builder.initVector; secretKey = new SecretKeySpec(builder.keyVersionMatter, 0, keySize.bytes(), "AES"); } else { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(keySize.bits()); secretKey = keyGen.generateKey(); SecureRandom prng = new SecureRandom(); initVector = new byte[16]; prng.nextBytes(initVector); } this.encryptingCipher = Cipher.getInstance(this.algModePadding); switch (this.mode) { case ECB: encryptingCipher.init(Cipher.ENCRYPT_MODE, this.secretKey); break; default: encryptingCipher.init(Cipher.ENCRYPT_MODE, this.secretKey, new IvParameterSpec(this.initVector)); } this.decryptingCipher = Cipher.getInstance(this.algModePadding); switch (this.mode) { case ECB: decryptingCipher.init(Cipher.DECRYPT_MODE, secretKey); break; default: decryptingCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(initVector)); } } catch (Exception e) { throw new BuilderException("Building AESKeyVersion failed", e); } }

Target:
private AESKeyVersion(Builder builder) throws BuilderException { super(builder); this.keyVersionLengthInBytes = builder.keyVersionLengthInBytes; this.mode = builder.mode; this.padding = builder.padding; this.algModePadding = "AES/" + this.mode + "/" + padding + "padding"; try { if (builder.keyVersionMatterInitVectorProvided) { initVector = builder.initVector.clone(); secretKey = new SecretKeySpec(builder.keyVersionMatter, 0, this.keyLengthInBytes(), "AES"); } else { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(this.keyLengthInBits()); secretKey = keyGen.generateKey(); SecureRandom prng = new SecureRandom(); initVector = new byte[IV_SIZE]; prng.nextBytes(initVector); } this.encryptingCipher = Cipher.getInstance(this.algModePadding); switch (this.mode) { case ECB: encryptingCipher.init(Cipher.ENCRYPT_MODE, this.secretKey); break; case CBC: case OFB: case CFB: case CTR: encryptingCipher.init(Cipher.ENCRYPT_MODE, this.secretKey, new IvParameterSpec(this.initVector)); break; default: throw new BuilderException("Unrecognized mode"); } this.decryptingCipher = Cipher.getInstance(this.algModePadding); switch (this.mode) { case ECB: decryptingCipher.init(Cipher.DECRYPT_MODE, secretKey); break; case CBC: case OFB: case CFB: case CTR: decryptingCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(initVector)); break; default: throw new BuilderException("Unrecognized mode"); } } catch (Exception e) { throw new BuilderException("Building AESKeyVersion failed", e); } }
Source:
protected boolean needsBalance(TableName tableName, Cluster c) { ClusterLoadState cs = new ClusterLoadState(c.clusterState); if (cs.getNumServers() < MIN_SERVER_BALANCE) { if (LOG.isDebugEnabled()) { LOG.debug("Not running balancer because only " + cs.getNumServers() + " active regionserver(s)"); } return false; } if(areSomeRegionReplicasColocated(c)) return true; if(idleRegionExist(c)) return true; float average = cs.getLoadAverage(); int floor = (int) Math.floor(average * (1 - slop)); int ceiling = (int) Math.ceil(average * (1 + slop)); if (!(cs.getMaxLoad() > ceiling || cs.getMinLoad() < floor)) { NavigableMap<ServerAndLoad, List<RegionInfo>> serversByLoad = cs.getServersByLoad(); if (LOG.isTraceEnabled()) { LOG.trace("Skipping load balancing because balanced cluster; " + "servers=" + cs.getNumServers() + " regions=" + cs.getNumRegions() + " average=" + average + " mostloaded=" + serversByLoad.lastKey().getLoad() + " leastloaded=" + serversByLoad.firstKey().getLoad()); } return false; } return true; }

Target:
protected boolean needsBalance(TableName tableName, Cluster c) { ClusterLoadState cs = new ClusterLoadState(c.clusterState); if (cs.getNumServers() < MIN_SERVER_BALANCE) { if (LOG.isDebugEnabled()) { LOG.debug("Not running balancer because only " + cs.getNumServers() + " active regionserver(s)"); } return false; } if(areSomeRegionReplicasColocated(c)) return true; if(idleRegionServerExist(c)) { return true; } float average = cs.getLoadAverage(); int floor = (int) Math.floor(average * (1 - slop)); int ceiling = (int) Math.ceil(average * (1 + slop)); if (!(cs.getMaxLoad() > ceiling || cs.getMinLoad() < floor)) { NavigableMap<ServerAndLoad, List<RegionInfo>> serversByLoad = cs.getServersByLoad(); if (LOG.isTraceEnabled()) { LOG.trace("Skipping load balancing because balanced cluster; " + "servers=" + cs.getNumServers() + " regions=" + cs.getNumRegions() + " average=" + average + " mostloaded=" + serversByLoad.lastKey().getLoad() + " leastloaded=" + serversByLoad.firstKey().getLoad()); } return false; } return true; }