auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void showLocationPickerOrPopupMenu(@NonNull final View view) { if (!mPost.hasLocation()) { showLocationPicker(); return; } <START> if (!isAdded()) { <END> return; } PopupMenu popupMenu = new PopupMenu(getActivity(), view); popupMenu.inflate(R.menu.post_settings_location_popup); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { if (menuItem.getItemId() == R.id.menu_change_location) { showLocationPicker(); } else if (menuItem.getItemId() == R.id.menu_remove_location) { setLocation(null); } return true; } }); try { Field fieldPopup = popupMenu.getClass().getDeclaredField("mPopup"); fieldPopup.setAccessible(true); Object menuPopupHelper = fieldPopup.get(popupMenu); MenuPopupHelper popupHelper = (MenuPopupHelper) fieldPopup.get(popupMenu); Class<?> classPopupHelper = Class.forName(popupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); setForceIcons.invoke(menuPopupHelper, true); } catch (Exception e) { } popupMenu.show(); }</code><technical_language>Nitpick: this check top avoid extra hasLocation check need isAdded check in showLocationPicker well. I guess this version advantage too, matter much. P.S: Please hate for raising this</technical_language>

Target:
private void showLocationPickerOrPopupMenu(@NonNull final View view) { if (!isAdded()) { return; } if (!mPost.hasLocation()) { showLocationPicker(); return; } PopupMenu popupMenu = new PopupMenu(getActivity(), view); popupMenu.inflate(R.menu.post_settings_location_popup); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { if (menuItem.getItemId() == R.id.menu_change_location) { showLocationPicker(); } else if (menuItem.getItemId() == R.id.menu_remove_location) { setLocation(null); } return true; } }); try { Field fieldPopup = popupMenu.getClass().getDeclaredField("mPopup"); fieldPopup.setAccessible(true); Object menuPopupHelper = fieldPopup.get(popupMenu); MenuPopupHelper popupHelper = (MenuPopupHelper) fieldPopup.get(popupMenu); Class<?> classPopupHelper = Class.forName(popupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); setForceIcons.invoke(menuPopupHelper, true); } catch (Exception e) { } popupMenu.show(); }
Source:
<code>public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> previousToken = null); context.registerSyntaxNodeConsumer(Tree.Kind.TOKEN, ctx -> { Token token = (Token) ctx.syntaxNode(); <START> if (token.isGeneratedCode()) { <END> return; } if (previousToken != null && previousToken.line() != token.line()) { String[] lines = previousToken.value().split("\r?\n|\r", -1); int length = previousToken.column(); for (String line : lines) { length += line.length(); if (length > maximumLineLength) { String message = MessageFormat.format("The line contains {0,number,integer} characters which is greater than {1,number,integer} authorized.", length, maximumLineLength); ctx.addLineIssue(message, previousToken.line()); } length = 0; } } previousToken = token; }); }</code><technical_language>I drop that. I in Python consider generated code. I drop org.sonar.python.api.tree.Token.isGeneratedCode() well</technical_language>

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> previousToken = null); context.registerSyntaxNodeConsumer(Tree.Kind.TOKEN, ctx -> { Token token = (Token) ctx.syntaxNode(); if (token.type().equals(PythonTokenType.NEWLINE)) { return; } if (previousToken != null && previousToken.line() != token.line()) { String[] lines = previousToken.value().split("\r?\n|\r", -1); int length = previousToken.column(); for (String line : lines) { length += line.length(); if (length > maximumLineLength) { String message = MessageFormat.format("The line contains {0,number,integer} characters which is greater than {1,number,integer} authorized.", length, maximumLineLength); ctx.addLineIssue(message, previousToken.line()); } length = 0; } } previousToken = token; }); }
Source:
<code>protected void onResumeFragments() { super.onResumeFragments(); if (shouldFinish()) { setResult(RESULT_OK); this.finish(); return; } if (CommCareApplication._().isConsumerApp()) { uiController.setUsername("t1"); uiController.setPasswordOrPin("123"); <START> localLoginOrPullAndLogin(false); <END> } else { tryAutoLogin(); } }</code><technical_language>lift this a helper method? Also, is a reason for t1 / 123 values is is addressed</technical_language>

Target:
protected void onResumeFragments() { super.onResumeFragments(); if (shouldFinish()) { setResult(RESULT_OK); this.finish(); return; } if (CommCareApplication._().isConsumerApp()) { uiController.setUsername(BuildConfig.CONSUMER_APP_USERNAME); uiController.setPasswordOrPin(BuildConfig.CONSUMER_APP_PASSWORD); localLoginOrPullAndLogin(false); } else { tryAutoLogin(); } }
Source:
<code><START> public Class getRealClass() { <END> return clazz; }</code><technical_language>Class<?></technical_language>

Target:
public Class<?> getRealClass() { return clazz; }
Source:
<code><START> public static Long ifPositive(Long time) { <END> if (time==null || time<=0) return null; return time; }</code><technical_language>this private part of a public API. If want called other things, moved utility place (and renamed clearer return null if positive)</technical_language>

Target:
private static Long ifPositive(Long time) { if (time==null || time<=0) return null; return time; }
Source:
<code>private int calculateDrawingRadius(final MapProjectionImpl projection) { final float[] distanceArray = new float[1]; final Geopoint itemCoord = items.get(0).getCoord().getCoords(); Location.distanceBetween(itemCoord.getLatitude(), itemCoord.getLongitude(), itemCoord.getLatitude(), itemCoord.getLongitude() + 1, distanceArray); final float longitudeLineDistance = distanceArray[0]; final GeoPointImpl itemGeo = mapItemFactory.getGeoPointBase(itemCoord); final Geopoint leftCoords = new Geopoint(itemCoord.getLatitude(), <START> itemCoord.getLongitude() - 160.9344f / longitudeLineDistance); <END> final GeoPointImpl leftGeo = mapItemFactory.getGeoPointBase(leftCoords); final Point center = new Point(); projection.toPixels(itemGeo, center); final Point left = new Point(); projection.toPixels(leftGeo, left); return center.x - left.x; }</code><technical_language>Instead of this constant, I prefer 528 * FEET_TO_KILOMETER * 1000 (constant coming IConversion)</technical_language>

Target:
private int calculateDrawingRadius(final MapProjectionImpl projection) { final float[] distanceArray = new float[1]; final Geopoint itemCoord = items.get(0).getCoord().getCoords(); Location.distanceBetween(itemCoord.getLatitude(), itemCoord.getLongitude(), itemCoord.getLatitude(), itemCoord.getLongitude() + 1, distanceArray); final float longitudeLineDistance = distanceArray[0]; final GeoPointImpl itemGeo = mapItemFactory.getGeoPointBase(itemCoord); final Geopoint leftCoords = new Geopoint(itemCoord.getLatitude(), itemCoord.getLongitude() - 528.0 * IConversion.FEET_TO_KILOMETER * 1000.0 / longitudeLineDistance); final GeoPointImpl leftGeo = mapItemFactory.getGeoPointBase(leftCoords); final Point center = new Point(); projection.toPixels(itemGeo, center); final Point left = new Point(); projection.toPixels(leftGeo, left); return center.x - left.x; }
Source:
<code>public void regenerateChunk(Actor actor, World world, LocalSession session, EditSession editSession, @Selection Region region) throws WorldEditException { Mask mask = session.getMask(); boolean success; try { session.setMask(null); success = world.regenerate(region, editSession); } finally { session.setMask(mask); } if (success) { actor.print("Region regenerated."); } else { <START> actor.print("Unable to regenerate chunks."); <END> } }</code><technical_language>this printError? message, I fine, add a "See console for details." sentence</technical_language>

Target:
public void regenerateChunk(Actor actor, World world, LocalSession session, EditSession editSession, @Selection Region region) throws WorldEditException { Mask mask = session.getMask(); boolean success; try { session.setMask(null); success = world.regenerate(region, editSession); } finally { session.setMask(mask); } if (success) { actor.printInfo(TranslatableComponent.of("worldedit.regen.regenerated")); } else { actor.printError(TranslatableComponent.of("worldedit.regen.failed")); } }
Source:
<code>public Poll clickNthAnswer(int number) { wait.forElementClickable(answersList.get(number)); <START> answersList.get(number).click(); <END> return this; }</code><technical_language>Add a check for index out of bound exception: <LINK_0></technical_language>

Target:
public Poll clickNthAnswer(int number) { try { wait.forElementClickable(answersList.get(number)); answersList.get(number).click(); } catch (Exception e) { PageObjectLogging.log("Could not click nth answer", e, false); } return this; }
Source:
<code>public DerivativeDataSourceMetadata( @JsonProperty("baseDataSource") String baseDataSource, @JsonProperty("dimensions") Set<String> dimensions, @JsonProperty("metrics") Set<String> metrics ) { Preconditions.checkNotNull(baseDataSource, "baseDataSource cannot be null. This is not a valid DerivativeDataSourceMetadata."); Preconditions.checkNotNull(dimensions, "dimensions cannot be null. This is not a valid DerivativeDataSourceMetadata."); Preconditions.checkNotNull(metrics, "metrics cannot be null. This is not a valid DerivativeDataSourceMetadata."); <START> this.baseDataSource = baseDataSource; <END> this.dimensions = dimensions; this.metrics = metrics; }</code><technical_language>nit: simplified this.baseDataSource = Preconditions.checkNotNull(baseDataSource, "baseDataSource null. This is a valid DerivativeDataSourceMetadata.");</technical_language>

Target:
public DerivativeDataSourceMetadata( @JsonProperty("baseDataSource") String baseDataSource, @JsonProperty("dimensions") Set<String> dimensions, @JsonProperty("metrics") Set<String> metrics ) { this.baseDataSource = Preconditions.checkNotNull(baseDataSource, "baseDataSource cannot be null. This is not a valid DerivativeDataSourceMetadata."); this.dimensions = Preconditions.checkNotNull(dimensions, "dimensions cannot be null. This is not a valid DerivativeDataSourceMetadata."); this.metrics = Preconditions.checkNotNull(metrics, "metrics cannot be null. This is not a valid DerivativeDataSourceMetadata."); }
Source:
<code>@Override public Response <START> addFromVmSnapshot(Template <END> template) { validateIconParameters(template); validateSnapshotExistence(template.getVm()); Guid snapshotId = getSnapshotId(template.getVm().getSnapshots()); org.ovirt.engine.core.common.businessentities.VM vmConfiguration = getVmConfiguration(snapshotId); Guid clusterId = null; if (namedCluster(template)) { clusterId = getClusterId(template); } if (template.getVersion() != null) { validateParameters(template.getVersion(), "baseTemplate"); } VmStatic originalVm = vmConfiguration.getStaticData(); VmStatic staticVm = getMapper(Template.class, VmStatic.class).map(template, originalVm); if (namedCluster(template)) { staticVm.setClusterId(clusterId); } AddVmTemplateFromSnapshotParameters params = new AddVmTemplateFromSnapshotParameters( staticVm, template.getName(), template.getDescription(), snapshotId); return addTemplate(template, originalVm, vmConfiguration.getDiskMap().keySet(), params, ActionType.AddVmTemplateFromSnapshot); }</code><technical_language>a lot in common in addFromVmSnapshot in addFromVm. extracted reused</technical_language>

Target:
public Response addFromVmSnapshot(Template template) { validateIconParameters(template); validateSnapshotExistence(template.getVm()); Guid snapshotId = getSnapshotId(template.getVm().getSnapshots()); org.ovirt.engine.core.common.businessentities.VM vmConfiguration = getVmConfiguration(snapshotId); Guid clusterId = null; if (namedCluster(template)) { clusterId = getClusterId(template); } if (template.getVersion() != null) { validateParameters(template.getVersion(), "baseTemplate"); } VmStatic originalVm = vmConfiguration.getStaticData(); VmStatic staticVm = getMapper(Template.class, VmStatic.class).map(template, originalVm); if (namedCluster(template)) { staticVm.setClusterId(clusterId); } AddVmTemplateFromSnapshotParameters params = new AddVmTemplateFromSnapshotParameters( staticVm, template.getName(), template.getDescription(), snapshotId); return addTemplate(template, originalVm, vmConfiguration.getDiskMap().keySet(), params, ActionType.AddVmTemplateFromSnapshot); }
Source:
<code>public void init(Map<String, Serializable> args) throws Exception { if (args.containsKey("ftpHostname")) { ftpHostname = args.get("ftpHostname").toString(); } if (args.containsKey("ftpPort")) { ftpPort = Integer.parseInt(args.get("ftpPort").toString()); } if (args.containsKey("ftpExtractArchive")) { ftpExtractArchive = Boolean.parseBoolean(args.get("ftpExtractArchive").toString()); } <START> if (args.containsKey(FTP_LOCAL_FILE_PATH) && args.get(FTP_LOCAL_FILE_PATH).toString() != null) { <END> ftpLocalFilePath = args.get(FTP_LOCAL_FILE_PATH).toString(); } if (args.containsKey("ftpRemoteFilePath")) { ftpRemoteFilePath = args.get("ftpRemoteFilePath").toString(); } if (args.containsKey("ftpMode")) { ftpMode = args.get("ftpMode").toString(); } ftpUsername = getThirdPartyCredential("FTP_USERNAME"); ftpPassword = getThirdPartyCredential("FTP_PASSWORD"); if (ftpUsername == null || ftpPassword == null) { throw new IllegalArgumentException("You first need to add your ftp username and password (FTP_USERNAME, FTP_PASSWORD) to the third party credentials"); } }</code><technical_language>toString is null, want test if is empty</technical_language>

Target:
public void init(Map<String, Serializable> args) throws Exception { if (args.containsKey("ftpHostname")) { ftpHostname = args.get("ftpHostname").toString(); } if (args.containsKey("ftpPort")) { ftpPort = Integer.parseInt(args.get("ftpPort").toString()); } if (args.containsKey("ftpMode")) { ftpMode = args.get("ftpMode").toString(); } if (args.containsKey("ftpExtractArchive")) { ftpExtractArchive = Boolean.parseBoolean(args.get("ftpExtractArchive").toString()); } if (args.containsKey(FTP_LOCAL_RELATIVE_PATH) && !args.get(FTP_LOCAL_RELATIVE_PATH).toString().isEmpty()) { ftpLocalRelativePath = args.get(FTP_LOCAL_RELATIVE_PATH).toString(); } else { if (ftpMode.equals("PUT")) { throw new IllegalArgumentException("You have to specify the local relative path. Empty value is not allowed."); } ftpLocalRelativePath = getLocalSpace(); } if (args.containsKey("ftpRemoteRelativePath")) { ftpRemoteRelativePath = args.get("ftpRemoteRelativePath").toString(); } ftpUsername = getThirdPartyCredential("FTP_USERNAME"); ftpPassword = getThirdPartyCredential("FTP_PASSWORD"); if (ftpUsername == null || ftpPassword == null) { throw new IllegalArgumentException("You first need to add your ftp username and password (FTP_USERNAME, FTP_PASSWORD) to the third party credentials"); } }
Source:
<code>void setUpHomeMenuIcon() { drawerIconDot.setVisibility(AccountUtil.isLoggedIn() && Prefs.showActionFeedIndicator() && ReleaseUtil.isPreBetaRelease() <START> && Prefs.getTotalUserDescriptionsEdited() >= ACTION_DESCRIPTION_EDIT_UNLOCK_THRESHOLD ? <END> VISIBLE : GONE); }</code><technical_language>This is specific logic is spilling a general function. this needs depend is Prefs.showActionFeedIndicator(), does</technical_language>

Target:
void setUpHomeMenuIcon() { drawerIconDot.setVisibility(AccountUtil.isLoggedIn() && Prefs.showActionFeedIndicator() && ReleaseUtil.isPreBetaRelease() ? VISIBLE : GONE); }
Source:
<code>private List<String> getOutputFolder() throws ValueStorageException { String outputDir; try { outputDir = extensionService.getOutputDir(wsPath); } catch (Exception e) { throw new ValueStorageException( <START> format("Failed to get '%s'. Cause: '%s'", OUTPUT_FOLDER, e.getMessage())); <END> } return outputDir.startsWith(wsPath) ? singletonList(outputDir.substring(wsPath.length() + 1)) : singletonList(outputDir); }</code><technical_language>Please consider add cause</technical_language>

Target:
private List<String> getOutputFolder() throws ValueStorageException { String outputDir; try { outputDir = extensionService.getOutputDir(wsPath); } catch (Exception e) { throw new ValueStorageException( format("Failed to get '%s'. ", OUTPUT_FOLDER), e.getCause()); } return outputDir.startsWith(wsPath) ? singletonList(outputDir.substring(wsPath.length() + 1)) : singletonList(outputDir); }
Source:
<code>public void testSearch(String searchTerm) throws DAOException { HomePage homePage = new HomePage(driver); User admin = DBUtility.getAdmin(); UserInfoPage userInfoPage = homePage.logIn(admin.getLogin(), admin.getPassword()); AdministrationPage administrationPage = userInfoPage.clickAdministrationTab(); for (SearchFilters filters : SearchFilters.values()) { for (SearchConditions conditions : SearchConditions.values()) { <START> if (filters == ALL_COLUMNS) { <END> continue; } else { administrationPage.setFilters(filters.getFilterName()) .setCondition(conditions) .fillSearchField(searchTerm) .clickSearchButton(); usersListFromView = administrationPage.getTableFromView(); administrationPage.clearSearchField(); usersListFromDB = DBUtility.getUserDao().getAllUsers(); filteredListFromDB = getFilteredList(usersListFromDB, filters, conditions, searchTerm); Comparator<User> userComparator = Comparator.comparing(User::getLogin); Comparator<UserFromView> userFromViewComparator = Comparator.comparing(UserFromView::getLogin); filteredListFromDB.sort(userComparator); usersListFromView.sort(userFromViewComparator); loggingSoftAssert.assertTrue(areListsEqual(usersListFromView, filteredListFromDB), filters + " " + conditions + " " + searchTerm); loggingSoftAssert.assertAll(); } } } administrationPage.clickLogOutButton(); }</code><technical_language>reverse it: if(filters != ALL_COLUMNS){ ... }</technical_language>

Target:
public void testSearch(String searchTerm) throws DAOException { HomePage homePage = new HomePage(driver); User admin = DBUtility.getAdmin(); UserInfoPage userInfoPage = homePage.logIn(admin.getLogin(), admin.getPassword()); AdministrationPage administrationPage = userInfoPage.clickAdministrationTab(); for (SearchFilters filter : SearchFilters.values()) { for (SearchConditions conditions : SearchConditions.values()) { if (filter == ALL_COLUMNS) { continue; } else { administrationPage.setFilters(filter) .setCondition(conditions) .fillSearchField(searchTerm) .clickSearchButton(); usersListFromView = administrationPage.getTableFromView(); administrationPage.clearSearchField(); usersListFromDB = DBUtility.getUserDao().getAllUsers(); filteredListFromDB = getFilteredList(usersListFromDB, filter, conditions, searchTerm); filteredListFromDB.sort(Comparator.comparing(User::getLogin)); usersListFromView.sort(Comparator.comparing(UserFromView::getLogin)); loggingSoftAssert.assertTrue(areListsEqual(usersListFromView, filteredListFromDB), filter + " " + conditions + " " + searchTerm); loggingSoftAssert.assertAll(); } } } administrationPage.clickLogOutButton(); }
Source:
<code>public void testUnionAllCorrectTuples() throws DbException { TupleBatchBuffer[] randomTuples = new TupleBatchBuffer[2]; randomTuples[0] = generateRandomTuples(123, false); randomTuples[1] = generateRandomTuples(42, false); TupleSource[] children = new TupleSource[2]; children[0] = new TupleSource(randomTuples[0]); children[1] = new TupleSource(randomTuples[1]); UnionAll union = new UnionAll(children); union.open(null); TupleBatch tb; <START> HashSet<Long> idCollector = new HashSet<Long>(); <END> while (!union.eos()) { tb = union.nextReady(); if (tb != null) { for (int i = 0; i < tb.numTuples(); i++) { idCollector.add(tb.getLong(0, i)); } } } union.close(); for (TupleBatchBuffer randomTuple : randomTuples) { for (TupleBatch tuples : randomTuple.getAll()) { for (int j = 0; j < tuples.numTuples(); j++) { assert idCollector.contains(tuples.getLong(0, j)); } } } }</code><technical_language>this a counter instead? (e.g., Guava's Multiset <LINK_0> check number correct of tuples in go. Note current code check values right multiplicity</technical_language>

Target:
public void testUnionAllCorrectTuples() throws DbException { TupleBatchBuffer[] randomTuples = new TupleBatchBuffer[2]; randomTuples[0] = generateRandomTuples(123, false); randomTuples[1] = generateRandomTuples(42, false); TupleSource[] children = new TupleSource[2]; children[0] = new TupleSource(randomTuples[0]); children[1] = new TupleSource(randomTuples[1]); UnionAll union = new UnionAll(children); union.open(null); TupleBatch tb; Multiset<Long> actualCounts = HashMultiset.create(); while (!union.eos()) { tb = union.nextReady(); if (tb != null) { for (int i = 0; i < tb.numTuples(); i++) { long index = tb.getLong(0, i); actualCounts.add(index); } } } union.close(); Multiset<Long> expectedCounts = HashMultiset.create(); for (TupleBatchBuffer randomTuple : randomTuples) { for (TupleBatch tuples : randomTuple.getAll()) { for (int j = 0; j < tuples.numTuples(); j++) { Long index = tuples.getLong(0, j); expectedCounts.add(index); } } } for (Multiset.Entry<Long> expectedEntry : expectedCounts.entrySet()) { assertEquals(expectedEntry.getCount(), actualCounts.count(expectedEntry.getElement())); } }
Source:
<code>private int checkMissingStates() { int numMatchingEvals = 0; for (MissingState missingState : missingStates) { MissingConditionEval eval = new MissingConditionEval(missingState.getCondition(), missingState.getPreviousTime(), System.currentTimeMillis()); <START> if (eval.isMatch()) { <END> rules.removeFact(missingState); missingState.setPreviousTime(System.currentTimeMillis()); missingState.setTime(System.currentTimeMillis()); rules.addFact(missingState); rules.addFact(eval); numMatchingEvals++; } } return numMatchingEvals; }</code><technical_language>a blocker save some Object creation if do: long = System.currentTimeMillis(); ... if ( missingState.condition.match(previousTime, now)) { MissingConditionEval eval = new..</technical_language>

Target:
private int checkMissingStates() { int numMatchingEvals = 0; for (MissingState missingState : missingStates) { long now = System.currentTimeMillis(); if (missingState.getCondition().match(missingState.getPreviousTime(), now)) { MissingConditionEval eval = new MissingConditionEval(missingState.getCondition(), missingState.getPreviousTime(), now); rules.removeFact(missingState); missingState.setPreviousTime(System.currentTimeMillis()); missingState.setTime(System.currentTimeMillis()); rules.addFact(missingState); rules.addFact(eval); numMatchingEvals++; } } return numMatchingEvals; }
Source:
<code>public Coordinate[] getFinPointsWithTab() { final Coordinate[] finPoints = getFinPoints(); final Coordinate[] tabPoints = getTabPoints(); Coordinate[] combinedPoints = Arrays.copyOf(finPoints, finPoints.length + tabPoints.length); <START> combinedPoints[finPoints.length + 3] = tabPoints[0]; combinedPoints[finPoints.length + 2] = tabPoints[1]; combinedPoints[finPoints.length + 1] = tabPoints[2]; combinedPoints[finPoints.length + 0] = tabPoints[3]; <END> return combinedPoints; }</code><technical_language>turns out a method takes care of this FinSet.java itself. This method simply replaced with: java public Coordinate[] getFinPointsWithTab() { return combineCurves(getFinPoints(), getTabPoints()); }</technical_language>

Target:
public Coordinate[] getFinPointsWithTab() { return combineCurves(getFinPoints(), getTabPoints()); }
Source:
<code>private static long fillNextLeafNode(HistoryTreeStub ht, long leafNodeStart) { int prevCount = ht.getNodeCount(); int prevDepth = ht.getDepth(); HTNode node = ht.getLatestLeaf(); <START> int intervalSize = new HTInterval(10, 20, 1, STRING_VALUE).getIntervalSize(); <END> int nodeFreeSpace = node.getNodeFreeSpace(); int nbIntervals = nodeFreeSpace / intervalSize; long ret = fillValues(ht, STRING_VALUE, nbIntervals, leafNodeStart); assertEquals(prevCount, ht.getNodeCount()); assertEquals(prevDepth, ht.getDepth()); return ret; }</code><technical_language>hard-code values (static final int, for type), instead of creating a dummy interval time</technical_language>

Target:
private static long fillNextLeafNode(HistoryTreeStub ht, long leafNodeStart) { int prevCount = ht.getNodeCount(); int prevDepth = ht.getDepth(); HTNode node = ht.getLatestLeaf(); int intervalSize = STRING_INTERVAL.getIntervalSizeOnDisk(); int nodeFreeSpace = node.getNodeFreeSpace(); int nbIntervals = nodeFreeSpace / intervalSize; long ret = fillValues(ht, STRING_VALUE, nbIntervals, leafNodeStart); assertEquals(prevCount, ht.getNodeCount()); assertEquals(prevDepth, ht.getDepth()); return ret; }
Source:
<code>protected String getFileName(ITask task, Predicate<String> fileExists) { String encodedFileName = CoreUtil.asFileName(task.getTaskId()); <START> if (encodedFileName.length() <= FILENAME_MAX_LEN && fileExists.test(encodedFileName)) { <END> return encodedFileName; } String fileName; if (requiresEncoding(task.getTaskId())) { fileName = encodedFileName; } else { fileName = task.getTaskId(); } return trimFilenameIfRequired(fileName); }</code><technical_language>In case file exist long? If a system a longer filename limit, existing file worry length, I think</technical_language>

Target:
protected String getFileName(ITask task, Predicate<String> fileExists) { String encodedFileName = CoreUtil.asFileName(task.getTaskId()); if (fileExists.test(encodedFileName)) { return encodedFileName; } String fileName; if (requiresEncoding(task.getTaskId())) { fileName = encodedFileName; } else { fileName = task.getTaskId(); } return trimFilenameIfRequired(fileName); }
Source:
<code>public void badInstantiationTest() throws Exception { Set<ZkInfo> zkInfos = new HashSet<>(dcsToZkInfo.values()); zkInfos.iterator().next().port = 0; JSONObject invalidZkJson = constructZkLayoutJSON(zkInfos); Properties props = new Properties(); props.setProperty("clustermap.host.name", hostname); props.setProperty("clustermap.cluster.name", clusterNamePrefixInHelix + clusterNameStatic); props.setProperty("clustermap.datacenter.name", "DC0"); props.setProperty("clustermap.dcs.zk.connect.strings", invalidZkJson.toString(2)); ClusterMapConfig invalidClusterMapConfig = new ClusterMapConfig(new VerifiableProperties(props)); metricRegistry = new MetricRegistry(); try { new HelixClusterManager(invalidClusterMapConfig, hostname, new MockHelixManagerFactory(helixCluster), metricRegistry); fail("Instantiation should have failed with invalid zk addresses"); } catch (IOException e) { assertEquals(true, metricRegistry.getGauges() <START> .get(HelixClusterManager.class.getName() + ".helixClusterManagerInstantiationFailed") <END> .getValue()); } }</code><technical_language>assertTrue() - a message helpful</technical_language>

Target:
public void badInstantiationTest() throws Exception { assertEquals(false, metricRegistry.getGauges() .get(HelixClusterManager.class.getName() + ".instantiationFailed") .getValue()); Set<ZkInfo> zkInfos = new HashSet<>(dcsToZkInfo.values()); zkInfos.iterator().next().port = 0; JSONObject invalidZkJson = constructZkLayoutJSON(zkInfos); Properties props = new Properties(); props.setProperty("clustermap.host.name", hostname); props.setProperty("clustermap.cluster.name", clusterNamePrefixInHelix + clusterNameStatic); props.setProperty("clustermap.datacenter.name", "DC0"); props.setProperty("clustermap.dcs.zk.connect.strings", invalidZkJson.toString(2)); ClusterMapConfig invalidClusterMapConfig = new ClusterMapConfig(new VerifiableProperties(props)); metricRegistry = new MetricRegistry(); try { new HelixClusterManager(invalidClusterMapConfig, hostname, new MockHelixManagerFactory(helixCluster), metricRegistry); fail("Instantiation should have failed with invalid zk addresses"); } catch (IOException e) { assertEquals(true, metricRegistry.getGauges() .get(HelixClusterManager.class.getName() + ".instantiationFailed") .getValue()); } }
Source:
<code>public void setupMenu() { <START> adminPage.addScreen( "root", "Settings" ); <END> adminPage.addPreference( "root", "LibraryPreferences", "Library", "fa-cubes", "preferences" ); final AbstractWorkbenchPerspectiveActivity defaultPerspective = menusHelper.getDefaultPerspectiveActivity(); menusHelper.addRolesMenuItems(); menusHelper.addUtilitiesMenuItems(); final Menus menus = MenuFactory .newTopLevelMenu( constants.Home() ) .respondsWith( () -> { if ( defaultPerspective != null ) { placeManager.goTo( new DefaultPlaceRequest( defaultPerspective.getIdentifier() ) ); } else { Window.alert( "Default perspective not found." ); } } ) .endMenu() .newTopLevelMenu( MenuFactory.newSimpleItem( "Admin - Preferences" ) .respondsWith( adminPageHelper.getAdminToolCommand( "root" ) ) .endMenu() .build().getItems().get( 0 ) ) .endMenu() .newTopLevelMenu( constants.Perspectives() ) .withItems( menusHelper.getPerspectivesMenuItems() ) .endMenu() .newTopLevelCustomMenu( iocManager.lookupBean( SearchMenuBuilder.class ).getInstance() ) .endMenu() .build(); menuBar.addMenus( menus ); }</code><technical_language>i18n? (I this is drools-wb-webapp nice treat fairly)</technical_language>

Target:
public void setupMenu() { adminPage.addScreen( "root", AppConstants.INSTANCE.Settings() ); adminPage.addPreference( "root", "LibraryPreferences", AppConstants.INSTANCE.Library(), "fa-cubes", "preferences" ); final AbstractWorkbenchPerspectiveActivity defaultPerspective = menusHelper.getDefaultPerspectiveActivity(); menusHelper.addRolesMenuItems(); menusHelper.addUtilitiesMenuItems(); final Menus menus = MenuFactory .newTopLevelMenu( constants.Home() ) .respondsWith( () -> { if ( defaultPerspective != null ) { placeManager.goTo( new DefaultPlaceRequest( defaultPerspective.getIdentifier() ) ); } else { Window.alert( "Default perspective not found." ); } } ) .endMenu() .newTopLevelMenu( MenuFactory.newSimpleItem( AppConstants.INSTANCE.AdminPreferences() ) .respondsWith( adminPageHelper.getAdminToolCommand( "root" ) ) .endMenu() .build().getItems().get( 0 ) ) .endMenu() .newTopLevelMenu( constants.Perspectives() ) .withItems( menusHelper.getPerspectivesMenuItems() ) .endMenu() .newTopLevelCustomMenu( iocManager.lookupBean( SearchMenuBuilder.class ).getInstance() ) .endMenu() .build(); menuBar.addMenus( menus ); }
Source:
<code>public static OptionSet prepareEoptions(OptionSet options) { OptionSet ret = new OptionSet(); for (Option o : options.asSortedList()) { switch (o.getNumber()) { case OptionNumberRegistry.OBSERVE: options.removeObserve(); break; case OptionNumberRegistry.URI_HOST: case OptionNumberRegistry.URI_PORT: case OptionNumberRegistry.PROXY_SCHEME: case OptionNumberRegistry.OSCORE: break; case OptionNumberRegistry.PROXY_URI: String proxyUri = o.getStringValue(); proxyUri = proxyUri.replace("coap://", ""); proxyUri = proxyUri.replace("coaps://", ""); int i = proxyUri.indexOf('/'); if (i >= 0) { proxyUri = proxyUri.substring(i + 1, proxyUri.length()); } else { break; } i = proxyUri.indexOf("?"); String uriPath = proxyUri; String uriQuery = null; if (i >= 0) { uriPath = proxyUri.substring(0, i); uriQuery = proxyUri.substring(i + 1, proxyUri.length()); } if (uriPath != null) { <START> String[] uriPaths = uriPath.split("/"); <END> for (int idx = 0; idx < uriPaths.length; idx++) { ret.addOption(new Option(OptionNumberRegistry.URI_PATH, uriPaths[idx])); } } if (uriQuery != null) { String[] uriQueries = uriQuery.split("&"); for (int idx = 0; idx < uriQueries.length; idx++) { ret.addOption(new Option(OptionNumberRegistry.URI_QUERY, uriQueries[idx])); } } break; default: ret.addOption(o); } } return ret; }</code><technical_language>reason OptionSet.setUriPath</technical_language>

Target:
public static OptionSet prepareEoptions(OptionSet options) { OptionSet ret = new OptionSet(); for (Option o : options.asSortedList()) { switch (o.getNumber()) { case OptionNumberRegistry.OBSERVE: options.removeObserve(); break; case OptionNumberRegistry.URI_HOST: case OptionNumberRegistry.URI_PORT: case OptionNumberRegistry.PROXY_SCHEME: case OptionNumberRegistry.OSCORE: break; case OptionNumberRegistry.PROXY_URI: String proxyUri = o.getStringValue(); proxyUri = proxyUri.replace("coap://", ""); proxyUri = proxyUri.replace("coaps://", ""); int i = proxyUri.indexOf('/'); if (i >= 0) { proxyUri = proxyUri.substring(i + 1, proxyUri.length()); } else { break; } i = proxyUri.indexOf("?"); String uriPath = proxyUri; String uriQuery = null; if (i >= 0) { uriPath = proxyUri.substring(0, i); uriQuery = proxyUri.substring(i + 1, proxyUri.length()); } if (uriPath != null) { ret.setUriPath(uriPath); } if (uriQuery != null) { String[] uriQueries = uriQuery.split("&"); for (int idx = 0; idx < uriQueries.length; idx++) { ret.setUriQuery(uriQueries[idx]); } } break; default: ret.addOption(o); } } return ret; }
Source:
<code>public void readFromNBT(NBTTagCompound nbt) { if (nbt.hasKey("activeAction")) { <START> deactivateAction(VampirismAPI.entityActionManager().getRegistry().getValue(new ResourceLocation("vampirism", nbt.getString("activeAction")))); <END> isPlayerTarget = true; } }</code><technical_language>"Vampirism" hardcoded here, in theory other mods register actions. modid part of saved nbt string</technical_language>

Target:
public void readFromNBT(NBTTagCompound nbt) { if (nbt.hasKey("activeAction")) { deactivateAction(VampirismAPI.entityActionManager().getRegistry().getValue(new ResourceLocation(nbt.getString("activeAction")))); isPlayerTarget = true; } }
Source:
<code>private AbstractPlanNode handleWindowedOperators(AbstractPlanNode root) { SchemaColumn windowedSchemaColumn = null; for (ParsedColInfo colInfo : m_parsedSelect.m_displayColumns) { AbstractExpression colExpr = colInfo.expression; if (colExpr instanceof WindowedExpression) { windowedSchemaColumn = new SchemaColumn(colInfo.tableName, colInfo.tableAlias, colInfo.columnName, colInfo.alias, colExpr); break; } } assert(windowedSchemaColumn != null); PartitionByPlanNode pnode = new PartitionByPlanNode(windowedSchemaColumn); OrderByPlanNode onode = new OrderByPlanNode(); <START> pnode.setWindowedColumn(windowedSchemaColumn); <END> WindowedExpression windowedExpression = (WindowedExpression)windowedSchemaColumn.getExpression(); for (AbstractExpression partitionByExpr : windowedExpression.getPartitionByExpressions()) { SortDirectionType pdir = windowedExpression.getOrderByDirectionOfExpression(partitionByExpr); onode.addSort(partitionByExpr, pdir); } for (int idx = 0; idx < windowedExpression.getOrderbySize(); idx += 1) { AbstractExpression orderByExpr = windowedExpression.getOrderByExpressions().get(idx); SortDirectionType orderByDir = windowedExpression.getOrderByDirections().get(idx); if (false == windowedExpression.getPartitionByExpressions().contains(orderByExpr)) { onode.addSort(orderByExpr, orderByDir); } } onode.addAndLinkChild(root); pnode.addAndLinkChild(onode); return pnode; }</code><technical_language>Calling a setter function set a field set in constructor</technical_language>

Target:
private AbstractPlanNode handleWindowedOperators(AbstractPlanNode root) { ParsedColInfo colInfo = m_parsedSelect.getWindowedColinfo(); assert(colInfo != null); SchemaColumn windowedSchemaColumn = colInfo.asSchemaColumn(); PartitionByPlanNode pnode = new PartitionByPlanNode(); pnode.setWindowedColumn(windowedSchemaColumn); OrderByPlanNode onode = new OrderByPlanNode(); WindowedExpression windowedExpression = (WindowedExpression)windowedSchemaColumn.getExpression(); List<AbstractExpression> partitionByExpressions = windowedExpression.getPartitionByExpressions(); for (AbstractExpression partitionByExpression : partitionByExpressions) { SortDirectionType pdir = SortDirectionType.DESC; onode.addSort(partitionByExpression, pdir); } for (int idx = 0; idx < windowedExpression.getOrderbySize(); idx += 1) { AbstractExpression orderByExpr = windowedExpression.getOrderByExpressions().get(idx); SortDirectionType orderByDir = windowedExpression.getOrderByDirections().get(idx); if (false == windowedExpression.getPartitionByExpressions().contains(orderByExpr)) { onode.addSort(orderByExpr, orderByDir); } } onode.addAndLinkChild(root); pnode.addAndLinkChild(onode); return pnode; }
Source:
<code>public void testTieredStore() throws Exception { CacheConfiguration<Long, String> tieredCacheConfiguration = newCacheConfigurationBuilder() .persistenceMode(CacheConfiguration.PersistenceMode.SWAP) <START> .withResourcePools(newResourcePoolsBuilder().with("heap").with("disk").build()) <END> .addServiceConfig(new OnHeapStoreServiceConfig().storeByValue(true)) .addServiceConfig(new DiskStoreServiceConfig()) .buildConfig(Long.class, String.class); CacheManager cacheManager = newCacheManagerBuilder().withCache("tieredCache", tieredCacheConfiguration).build(); Cache<Long, String> tieredCache = cacheManager.getCache("tieredCache", Long.class, String.class); tieredCache.put(1L, "one"); assertThat(tieredCache.get(1L), equalTo("one")); assertThat(tieredCache.get(1L), equalTo("one")); cacheManager.close(); }</code><technical_language>names: .withCapacityConstraints(newCapacityConstraintsBuilder().heap(10).disk(100).build())</technical_language>

Target:
public void testTieredStore() throws Exception { CacheConfiguration<Long, String> tieredCacheConfiguration = newCacheConfigurationBuilder() .persistenceMode(CacheConfiguration.PersistenceMode.SWAP) .withResourcePools(newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).disk(100, EntryUnit.ENTRIES).build()) .buildConfig(Long.class, String.class); CacheManager cacheManager = newCacheManagerBuilder().withCache("tieredCache", tieredCacheConfiguration).build(); Cache<Long, String> tieredCache = cacheManager.getCache("tieredCache", Long.class, String.class); tieredCache.put(1L, "one"); assertThat(tieredCache.get(1L), equalTo("one")); assertThat(tieredCache.get(1L), equalTo("one")); cacheManager.close(); }
Source:
<code>public Response sendStreamingRequest(Request request) throws IOException, AppException { OkHttpClient client = getStreamClient(); okhttp3.Request okRequest = makeRequest(request.getMethod(), request.getUrl(), request.getHeaders(), request.getBody()); Call call = client.newCall(okRequest); okhttp3.Response response = call.execute(); if((response.code() >= 300) || ((response.code() < 200) && (response.code() != 0))) { <START> throw new AppException(ErrorCode.fromNativeError(ErrorCode.Type.HTTP, response.code()), "http error code considered fatal"); <END> } return OkHttpResponse.httpResponse(response.code(), parseHeaders(response.headers()), response.body().source()); }</code><technical_language>underlying http exception message instead? server sends useful information there. "Http error code considered fatal" provide useful</technical_language>

Target:
public OsJavaNetworkTransport.Response sendStreamingRequest(Request request) throws IOException, AppException { OkHttpClient client = getStreamClient(); okhttp3.Request okRequest = makeRequest(request.getMethod(), request.getUrl(), request.getHeaders(), request.getBody()); Call call = client.newCall(okRequest); okhttp3.Response response = call.execute(); if((response.code() >= 300) || ((response.code() < 200) && (response.code() != 0))) { throw new AppException(ErrorCode.fromNativeError(ErrorCode.Type.HTTP, response.code()), response.message()); } return Response.httpResponse(response.code(), parseHeaders(response.headers()), response.body().source()); }
Source:
<code>public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongAttributeAssignmentException, InternalErrorException, WrongReferenceAttributeValueException { try { <START> Attribute foundAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GroupsManager.GROUPSYNCHROINTERVAL_ATTRNAME); <END> if(foundAttribute.getValue() != null) { throw new WrongReferenceAttributeValueException(attribute, foundAttribute, group, null, group, null, "Attribute " + attribute.getName() + " cannot be set because attribute " + GroupsManager.GROUPSYNCHROINTERVAL_ATTRNAME + " is already set."); } } catch (AttributeNotExistsException exc) { throw new ConsistencyErrorException("Attribute " + GroupsManager.GROUPSYNCHROINTERVAL_ATTRNAME + " is supposed to exist", exc); } }</code><technical_language>skipped null value</technical_language>

Target:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongAttributeAssignmentException, InternalErrorException, WrongReferenceAttributeValueException { if (attribute.getValue() == null) return; try { Attribute foundAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GroupsManager.GROUPSYNCHROINTERVAL_ATTRNAME); if(foundAttribute.getValue() != null) { throw new WrongReferenceAttributeValueException(attribute, foundAttribute, group, null, group, null, "Attribute " + attribute.getName() + " cannot be set because attribute " + GroupsManager.GROUPSYNCHROINTERVAL_ATTRNAME + " is already set."); } } catch (AttributeNotExistsException exc) { throw new ConsistencyErrorException("Attribute " + GroupsManager.GROUPSYNCHROINTERVAL_ATTRNAME + " is supposed to exist", exc); } }
Source:
<code>public void testBuildMessageNumberSetsWithStartEnd() throws ImapAsyncClientException { final String msgSetStr = "1:100"; final MessageNumberSet[] messageNumberSets = MessageNumberSet.buildMessageNumberSets(msgSetStr); Assert.assertNotNull(messageNumberSets, "Result mismatched."); Assert.assertEquals(messageNumberSets.length, 1, "Result mismatched."); <START> Assert.assertEquals(MessageNumberSet.buildString(messageNumberSets), msgSetStr, "Result mismatched"); <END> }</code><technical_language>testing buildString() method here, test is validate buildMessageNumberSets() test values of messageNumberSets[0]</technical_language>

Target:
public void testBuildMessageNumberSetsWithStartEnd() throws ImapAsyncClientException { final MessageNumberSet[] expectedMsgSets = { new MessageNumberSet(1, 100) }; final String msgSetStr = MessageNumberSet.buildString(expectedMsgSets); final MessageNumberSet[] actualMsgSets = MessageNumberSet.buildMessageNumberSets(msgSetStr); Assert.assertNotNull(actualMsgSets, "buildMessageNumberSets() should not return null."); Assert.assertEquals(actualMsgSets.length, 1, "buildMessageNumberSets() size mismatched."); Assert.assertEquals(actualMsgSets[0], expectedMsgSets[0], "buildMessageNumberSets() mismatched."); }
Source:
<code>protected void doParse(BeanDefinitionBuilder builder, Element element, BeanMetadataElement processor, ParserContext parserContext){ this.injectPropertyWithAdapter(CORRELATION_STRATEGY_REF_ATTRIBUTE, CORRELATION_STRATEGY_METHOD_ATTRIBUTE, CORRELATION_STRATEGY_EXPRESSION_ATTRIBUTE, CORRELATION_STRATEGY_PROPERTY, "CorrelationStrategy", element, builder, processor, parserContext); String messageStore = element.getAttribute(MESSAGE_STORE_ATTRIBUTE); if (!StringUtils.hasText(messageStore)) { messageStore = BeanDefinitionReaderUtils.registerWithGeneratedName(new RootBeanDefinition(SimpleMessageStore.class), parserContext.getRegistry()); <START> element.setAttribute(MESSAGE_STORE_ATTRIBUTE, messageStore); <END> } builder.addPropertyReference("messageStore", messageStore); this.injectPropertyWithAdapter(RELEASE_STRATEGY_REF_ATTRIBUTE, RELEASE_STRATEGY_METHOD_ATTRIBUTE, RELEASE_STRATEGY_EXPRESSION_ATTRIBUTE, RELEASE_STRATEGY_PROPERTY, "ReleaseStrategy", element, builder, processor, parserContext); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, DISCARD_CHANNEL_ATTRIBUTE); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, SEND_TIMEOUT_ATTRIBUTE); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, SEND_PARTIAL_RESULT_ON_EXPIRY_ATTRIBUTE); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "empty-group-min-timeout", "minimumTimeoutForEmptyGroups"); }</code><technical_language>is purpose of adding attribute element</technical_language>

Target:
protected void doParse(BeanDefinitionBuilder builder, Element element, BeanMetadataElement processor, ParserContext parserContext){ this.injectPropertyWithAdapter(CORRELATION_STRATEGY_REF_ATTRIBUTE, CORRELATION_STRATEGY_METHOD_ATTRIBUTE, CORRELATION_STRATEGY_EXPRESSION_ATTRIBUTE, CORRELATION_STRATEGY_PROPERTY, "CorrelationStrategy", element, builder, processor, parserContext); this.injectPropertyWithAdapter(RELEASE_STRATEGY_REF_ATTRIBUTE, RELEASE_STRATEGY_METHOD_ATTRIBUTE, RELEASE_STRATEGY_EXPRESSION_ATTRIBUTE, RELEASE_STRATEGY_PROPERTY, "ReleaseStrategy", element, builder, processor, parserContext); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, MESSAGE_STORE_ATTRIBUTE); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "scheduler", "taskScheduler"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, DISCARD_CHANNEL_ATTRIBUTE); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "lock-registry"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, SEND_TIMEOUT_ATTRIBUTE); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, SEND_PARTIAL_RESULT_ON_EXPIRY_ATTRIBUTE); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "empty-group-min-timeout", "minimumTimeoutForEmptyGroups"); BeanDefinition expressionDef = IntegrationNamespaceUtils.createExpressionDefinitionFromValueOrExpression("group-timeout", "group-timeout-expression", parserContext, element, false); builder.addPropertyValue("groupTimeoutExpression", expressionDef); }
Source:
<code>private void waitTillCertainPercentageOfProcessHasStarted(OozieClient oozieClient, String bundleId, int percentage) throws Exception { CoordinatorJob defaultCoordinator = getDefaultOozieCoordinator(oozieClient, bundleId); <START> for (int i=0; null == defaultCoordinator && i < 10; i++) { <END> TimeUnit.SECONDS.sleep(10); defaultCoordinator = getDefaultOozieCoordinator(oozieClient, bundleId); } Assert.assertNotNull(defaultCoordinator, "default coordinator is null"); for (int i = 0; i < 120 && defaultCoordinator.getStatus() == CoordinatorJob.Status.PREP; ++i) { TimeUnit.SECONDS.sleep(10); defaultCoordinator = getDefaultOozieCoordinator(oozieClient, bundleId); } Assert.assertNotEquals(defaultCoordinator.getStatus(), CoordinatorJob.Status.PREP, "Unexpected state for coordinator job: " + defaultCoordinator.getId()); int totalCount = defaultCoordinator.getActions().size(); int percentageConversion = (percentage * totalCount) / 100; while (percentageConversion > 0) { int doneBynow = 0; for (CoordinatorAction action : defaultCoordinator.getActions()) { CoordinatorAction actionInfo = oozieClient.getCoordActionInfo(action.getId()); if (actionInfo.getStatus() == CoordinatorAction.Status.RUNNING) { doneBynow++; } } if (doneBynow >= percentageConversion) { break; } TimeUnit.SECONDS.sleep(10); } }</code><technical_language>I loop: <LINK_0></technical_language>

Target:
private void waitTillCertainPercentageOfProcessHasStarted(OozieClient oozieClient, String bundleId, int percentage) throws Exception { CoordinatorJob defaultCoordinator = getDefaultOozieCoordinator(oozieClient, bundleId); for (int i = 0; i < 120 && (defaultCoordinator == null || defaultCoordinator.getStatus() == CoordinatorJob.Status.PREP); ++i) { TimeUnit.SECONDS.sleep(10); defaultCoordinator = getDefaultOozieCoordinator(oozieClient, bundleId); } Assert.assertNotNull(defaultCoordinator, "default coordinator is null"); Assert.assertNotEquals(defaultCoordinator.getStatus(), CoordinatorJob.Status.PREP, "Unexpected state for coordinator job: " + defaultCoordinator.getId()); int totalCount = defaultCoordinator.getActions().size(); int percentageConversion = (percentage * totalCount) / 100; while (percentageConversion > 0) { int doneBynow = 0; for (CoordinatorAction action : defaultCoordinator.getActions()) { CoordinatorAction actionInfo = oozieClient.getCoordActionInfo(action.getId()); if (actionInfo.getStatus() == CoordinatorAction.Status.RUNNING) { doneBynow++; } } if (doneBynow >= percentageConversion) { break; } TimeUnit.SECONDS.sleep(10); } }