auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<String> filterGroups(DocumentModel registrationDoc, UserRegistrationConfiguration configuration) { List<String> wantedGroup = (List<String>) registrationDoc.getPropertyValue( configuration.getUserInfoGroupsField()); String originatingUser = registrationDoc.getProperty(UserInvitationComponent.PARAM_ORIGINATING_USER) <START> .getValue(String.class); <END> UserManager userManager = Framework.getService(UserManager.class); NuxeoPrincipal originatingPrincipal = userManager.getPrincipal(originatingUser); return wantedGroup.stream().filter(g -> acceptGroup(originatingPrincipal, g)).collect(Collectors.toList()); }</code><technical_language>This works deprecate some point. Try getPropertyValue instead, if requires a cast (which generic version hides)</technical_language>

Target:
protected List<String> filterGroups(DocumentModel registrationDoc, UserRegistrationConfiguration configuration) { List<String> wantedGroup = (List<String>) registrationDoc.getPropertyValue( configuration.getUserInfoGroupsField()); NuxeoPrincipal originatingPrincipal = getOriginatingPrincipal(registrationDoc); if (originatingPrincipal == null) { return Collections.emptyList(); } return wantedGroup.stream().filter(g -> acceptGroup(originatingPrincipal, g)).collect(Collectors.toList()); }
Source:
<code>public File deobfBinary(File original, String mappings, String... cachePath) throws IOException { project.getLogger().debug("Deobfuscating binary file with mappings {}", original.getName(), mappings); File names = findMapping(mappings); if (names == null || !names.exists()) { return null; } File cacheDir = getOrCreateCacheDir(cachePath); <START> String mappedName = addMappingsToName(original.getName(), mappings); <END> File input = new File(cacheDir, mappedName + ".input"); File output = new File(cacheDir, mappedName); HashStore cache = new HashStore() .load(input) .add("names", names) .add("orig", original); if (!cache.isSame() || !output.exists()) { SrgJarRenamer.rename(original, output, names); Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; }</code><technical_language>This is asking for collisions supporting unique identifiers, this is main reason I bothered add direct file dep support. ivy/maven format</technical_language>

Target:
public File deobfBinary(File original, String mappings, String... cachePath) throws IOException { project.getLogger().debug("Deobfuscating binary file with mappings {}", original.getName(), mappings); File names = findMapping(mappings); if (names == null || !names.exists()) { return null; } File output = getCacheFile(cachePath); File input = new File(output.getParent(), output.getName() + ".input"); HashStore cache = new HashStore() .load(input) .add("names", names) .add("orig", original); if (!cache.isSame() || !output.exists()) { SrgJarRenamer.rename(original, output, names); Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; }
Source:
<code>public void registerSelf(final String authId, final String itemId, final School.ItemType itemType, final String registrationKey, final DbAuthChecker authChecker) throws AuthenticationException, DatabaseAccessException { if (!School.ItemType.COURSE.equals(itemType) && !School.ItemType.BANK_PROBLEM.equals(itemType)) { throw new AuthenticationException("Can only register users in a course or a bank problem", AuthenticationException.OTHER); } final DBCollection collection = database.getCollection(getCollectionFromType(itemType)); final DBObject result = collection.findOne(new ObjectId(itemId), new BasicDBObject(DatabaseStringConstants.USER_LIST, true) .append(DatabaseStringConstants.REGISTRATION_KEY, true)); if (result == null) { <START> throw new DatabaseAccessException("The item with the id " + itemId + " Was not found in the database"); <END> } if (!result.get(DatabaseStringConstants.REGISTRATION_KEY).equals(registrationKey)) { throw new AuthenticationException("Invalid Registration key", AuthenticationException.INVALID_PERMISSION); } final List<String> userGroups = (List<String>) result.get(DatabaseStringConstants.USER_LIST); insertUserIntoGroup(authId, userGroups.get(0), Authentication.AuthResponse.PermissionLevel.STUDENT); }</code><technical_language>Lowercase "W" in "Was"</technical_language>

Target:
public void registerSelf(final String authId, final String itemId, final School.ItemType itemType, final String registrationKey, final DbAuthChecker authChecker) throws AuthenticationException, DatabaseAccessException { if (!School.ItemType.COURSE.equals(itemType) && !School.ItemType.BANK_PROBLEM.equals(itemType)) { throw new AuthenticationException("Can only register users in a course or a bank problem.", AuthenticationException.OTHER); } final DBCollection collection = database.getCollection(getCollectionFromType(itemType)); final DBObject result = collection.findOne(new ObjectId(itemId), new BasicDBObject(DatabaseStringConstants.USER_LIST, true) .append(DatabaseStringConstants.REGISTRATION_KEY, true)); if (result == null) { throw new DatabaseAccessException("The item with the id: " + itemId + " was not found in the database."); } if (!result.get(DatabaseStringConstants.REGISTRATION_KEY).equals(registrationKey)) { throw new AuthenticationException("Invalid Registration key", AuthenticationException.INVALID_PERMISSION); } final List<String> userGroups = (List<String>) result.get(DatabaseStringConstants.USER_LIST); insertUserIntoGroup(authId, userGroups.get(0), Authentication.AuthResponse.PermissionLevel.STUDENT); }
Source:
<code>protected byte[] bufferForTransferring( Resource resource ) { long contentLength = resource.getContentLength(); if ( contentLength <= 0 ) { return new byte[DEFAULT_BUFFER_SIZE]; } <START> int numberOf4KbSegmentsFor100Chunks = ( ( int ) ( contentLength / ( 4 * 1024 * 100 ) ) ); <END> int bufferSizeFor100Chunks = numberOf4KbSegmentsFor100Chunks * 4 * 1024; int effectiveBufferSize = min( MAXIMUM_BUFFER_SIZE, max( DEFAULT_BUFFER_SIZE, bufferSizeFor100Chunks ) ); return new byte[effectiveBufferSize]; }</code><technical_language>Please static final for 4 * 1024 move 100 a static final. add code chosen 100</technical_language>

Target:
protected byte[] bufferForTransferring( Resource resource ) { final long contentLength = resource.getContentLength(); if ( contentLength <= 0 ) { return new byte[DEFAULT_BUFFER_SIZE]; } final int numberOfBufferSegments = ( ( int ) ( contentLength / ( BUFFER_SEGMENT_SIZE * MINIMUM_AMOUNT_OF_TRANSFER_CHUNKS ) ) ); final int potentialBufferSize = numberOfBufferSegments * BUFFER_SEGMENT_SIZE; final int effectiveBufferSize = min( MAXIMUM_BUFFER_SIZE, max( DEFAULT_BUFFER_SIZE, potentialBufferSize ) ); return new byte[effectiveBufferSize]; }
Source:
<code>public static Actor buildActor(Tweet tweet) { Actor actor = new Actor(); User user = tweet.getUser(); actor.setId(formatId( Optional.fromNullable( user.getIdStr()) .or(Optional.of(user.getId().toString())) .orNull() )); actor.setDisplayName(user.getName()); actor.setAdditionalProperty("handle", user.getScreenName()); actor.setSummary(user.getDescription()); if (user.getUrl()!=null){ actor.setUrl(user.getUrl()); } Map<String, Object> extensions = new HashMap<String, Object>(); extensions.put("location", user.getLocation()); extensions.put("posts", user.getStatusesCount()); extensions.put("favorites", user.getFavouritesCount()); extensions.put("followers", user.getFollowersCount()); Map<String, Object> image = new HashMap<String, Object>(); <START> image.put("url", user.getProfileImageUrlHttps()); <END> extensions.put("image", image); extensions.put("screenName", user.getScreenName()); actor.setAdditionalProperty("extensions", extensions); return actor; }</code><technical_language>I profile image a media link in image property of actor object <LINK_0></technical_language>

Target:
public static Actor buildActor(Tweet tweet) { Actor actor = new Actor(); User user = tweet.getUser(); actor.setId(formatId( Optional.fromNullable( user.getIdStr()) .or(Optional.of(user.getId().toString())) .orNull() )); actor.setDisplayName(user.getName()); actor.setAdditionalProperty("handle", user.getScreenName()); actor.setSummary(user.getDescription()); if (user.getUrl()!=null){ actor.setUrl(user.getUrl()); } Map<String, Object> extensions = new HashMap<String, Object>(); extensions.put("location", user.getLocation()); extensions.put("posts", user.getStatusesCount()); extensions.put("favorites", user.getFavouritesCount()); extensions.put("followers", user.getFollowersCount()); Image profileImage = new Image(); profileImage.setUrl(user.getProfileImageUrlHttps()); actor.setImage(profileImage); extensions.put("screenName", user.getScreenName()); actor.setAdditionalProperty("extensions", extensions); return actor; }
Source:
<code>public static String buildThreadDiagnosticString() { <START> StringWriter sw = new StringWriter(); <END> PrintWriter output = new PrintWriter(sw); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS"); output.println(String.format("Timestamp: %s", dateFormat.format(new Date()))); output.println(); output.println(buildThreadsDump()); String deadlocksInfo = buildDeadlockInfo(); if (deadlocksInfo != null) { output.println("====> DEADLOCKS DETECTED <===="); output.println(); output.println(deadlocksInfo); } return sw.toString(); }</code><technical_language>StringBuilder instead of StringWriter PrintWriter do String concatenation</technical_language>

Target:
public static String buildThreadDiagnosticString() { StringBuilder sb = new StringBuilder(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS"); sb.append(String.format("Timestamp: %s", dateFormat.format(new Date()))); sb.append(System.getProperty("line.separator")); sb.append(System.getProperty("line.separator")); sb.append(System.getProperty("line.separator")); sb.append(buildThreadsDump()); String deadlocksInfo = buildDeadlockInfo(); if (deadlocksInfo != null) { sb.append("====> DEADLOCKS DETECTED <===="); sb.append(System.getProperty("line.separator")); sb.append(System.getProperty("line.separator")); sb.append(deadlocksInfo); sb.append(System.getProperty("line.separator")); } return sb.toString(); }
Source:
<code>public ListenableFuture<Image> createImage(ImageTemplate template) { <START> checkState(template instanceof CloneImageTemplate, " digitalocean only supports creating images through cloning."); <END> final CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; int powerOffEvent = api.getDropletApi().powerOff(Integer.parseInt(cloneTemplate.getSourceNodeId())); nodeStoppedPredicate.apply(powerOffEvent); int snapshotEvent = api.getDropletApi().snapshot(Integer.parseInt(cloneTemplate.getSourceNodeId()), cloneTemplate.getName()); logger.info(">> registered new Image, waiting for it to become available"); imageAvailablePredicate.apply(snapshotEvent); Optional<org.jclouds.digitalocean.domain.Image> snapshot = tryFind(api.getImageApi().list(), new Predicate<org.jclouds.digitalocean.domain.Image>() { @Override public boolean apply(org.jclouds.digitalocean.domain.Image input) { return input.getName().equals(cloneTemplate.getName()); } }); if (!snapshot.isPresent()) { throw new NoSuchElementException("Cannot find image with name: " + cloneTemplate.getName()); } return immediateFuture(imageTransformer.apply(snapshot.get())); }</code><technical_language>[minor] Space in " digi...? "DigitalOcean" "digitalocean"</technical_language>

Target:
public ListenableFuture<Image> createImage(ImageTemplate template) { checkState(template instanceof CloneImageTemplate, "DigitalOcean only supports creating images through cloning."); final CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; int powerOffEvent = api.getDropletApi().powerOff(Integer.parseInt(cloneTemplate.getSourceNodeId())); nodeStoppedPredicate.apply(powerOffEvent); int snapshotEvent = api.getDropletApi().snapshot(Integer.parseInt(cloneTemplate.getSourceNodeId()), cloneTemplate.getName()); logger.info(">> registered new Image, waiting for it to become available"); imageAvailablePredicate.apply(snapshotEvent); org.jclouds.digitalocean.domain.Image snapshot = find(api.getImageApi().list(), new Predicate<org.jclouds.digitalocean.domain.Image>() { @Override public boolean apply(org.jclouds.digitalocean.domain.Image input) { return input.getName().equals(cloneTemplate.getName()); } }); return immediateFuture(imageTransformer.apply(snapshot)); }
Source:
<code>byte[] toBytes() { List<byte[]> segmentNamesBytes = new ArrayList<>(); int size = VERSION_SIZE + REFERENCE_TIME_SIZE + SEGMENT_COUNT_SIZE + logSegmentsUnderCompaction.size() * SEGMENT_NAME_LENGTH_SIZE; for (String segmentName : logSegmentsUnderCompaction) { byte[] segmentNameBytes = segmentName.getBytes(); <START> segmentNamesBytes.add(segmentNameBytes); <END> size += segmentNameBytes.length; } byte[] extraSegmentNameBytes = extraSegmentName == null ? ZERO_LENGTH_ARRAY : extraSegmentName.getBytes(); size += SEGMENT_NAME_LENGTH_SIZE + extraSegmentNameBytes.length + SWAP_SPACE_COUNT_SIZE; byte[] buf = new byte[size]; ByteBuffer bufWrap = ByteBuffer.wrap(buf); bufWrap.putShort(VERSION_0); bufWrap.putLong(referenceTime); bufWrap.putInt(logSegmentsUnderCompaction.size()); for (byte[] segmentNameBytes : segmentNamesBytes) { bufWrap.putInt(segmentNameBytes.length); bufWrap.put(segmentNameBytes); } bufWrap.putInt(extraSegmentNameBytes.length); bufWrap.put(extraSegmentNameBytes); bufWrap.putInt(swapSpaceCount); return buf; }</code><technical_language>name segmentNamesBytes is similar segmentNameBytes. list named segmentNameBytesList</technical_language>

Target:
byte[] toBytes() { List<byte[]> segmentNameBytesList = new ArrayList<>(); int size = VERSION_SIZE + REFERENCE_TIME_SIZE + SEGMENT_COUNT_SIZE; for (String segmentName : logSegmentsUnderCompaction) { byte[] segmentNameBytes = segmentName.getBytes(); segmentNameBytesList.add(segmentNameBytes); size += SEGMENT_NAME_LENGTH_SIZE + segmentNameBytes.length; } byte[] extraSegmentNameBytes = extraSegmentName == null ? ZERO_LENGTH_ARRAY : extraSegmentName.getBytes(); size += SEGMENT_NAME_LENGTH_SIZE + extraSegmentNameBytes.length + SWAP_SPACE_COUNT_SIZE; byte[] buf = new byte[size]; ByteBuffer bufWrap = ByteBuffer.wrap(buf); bufWrap.putShort(VERSION_0); bufWrap.putLong(referenceTime); bufWrap.putInt(logSegmentsUnderCompaction.size()); for (byte[] segmentNameBytes : segmentNameBytesList) { bufWrap.putInt(segmentNameBytes.length); bufWrap.put(segmentNameBytes); } bufWrap.putInt(extraSegmentNameBytes.length); bufWrap.put(extraSegmentNameBytes); bufWrap.putInt(swapSpaceCount); return buf; }
Source:
<code>public void dispose() { <START> super.dispose(); <END> }</code><technical_language>I dispose ShapeRenderer here</technical_language>

Target:
public void dispose() { super.dispose(); shapeRenderer.dispose(); }
Source:
<code><START> void migrateWorkspaces() { <END> LOGGER.trace("Beginning workspace query data migration"); Filter workspaceFilter = filterBuilder.allOf( filterBuilder.attribute(Core.METACARD_TAGS).like().text(WORKSPACE_TAG), filterBuilder.attribute(WORKSPACE_QUERIES).is().like().text("*")); Query query = new QueryImpl(workspaceFilter); QueryRequest queryRequest = new QueryRequestImpl(query); ResultIterable.resultIterable(catalogFramework::query, queryRequest) .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .forEach(this::migrateWorkspaceMetacard); LOGGER.trace("Completed workspace query data migration"); }</code><technical_language>is necessary this protected? If subject is mocked, challenging call migrate instead of migrateWorkspaces correctly relaxing access this method</technical_language>

Target:
private void migrateWorkspaces() { LOGGER.trace("Beginning workspace query data migration"); Filter workspaceFilter = filterBuilder.allOf( filterBuilder.attribute(Core.METACARD_TAGS).like().text(WORKSPACE_TAG), filterBuilder.attribute(WORKSPACE_QUERIES).is().like().text("*")); Query query = new QueryImpl(workspaceFilter); QueryRequest queryRequest = new QueryRequestImpl(query); ResultIterable.resultIterable(catalogFramework::query, queryRequest) .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .forEach(this::migrateWorkspaceMetacard); LOGGER.trace("Completed workspace query data migration"); }
Source:
<code>static Set<String> getDisabledTests(Path testMappingsRootPath, String testGroup) { Set<String> disabledTests = new HashSet<>(); <START> if (testGroup.equals(PRESUBMIT)) { <END> File disabledPresubmitTestsFile = new File(testMappingsRootPath.toString(), DISABLED_PRESUBMIT_TESTS); try { disabledTests.addAll( Arrays.asList( FileUtil.readStringFromFile(disabledPresubmitTestsFile) .split("\\r?\\n"))); } catch (IOException e) { RuntimeException runtimeException = new RuntimeException( String.format( "IO error (%s) when reading disabled tests from file (%s)", e.getMessage(), disabledPresubmitTestsFile.getAbsolutePath()), e); throw runtimeException; } } return disabledTests; }</code><technical_language>flip logic. Return empty set if testGroup is PRESUBMIT</technical_language>

Target:
static Set<String> getDisabledTests(Path testMappingsRootPath, String testGroup) { Set<String> disabledTests = new HashSet<>(); if (!testGroup.equals(PRESUBMIT)) { return disabledTests; } File disabledPresubmitTestsFile = new File(testMappingsRootPath.toString(), DISABLED_PRESUBMIT_TESTS); try { disabledTests.addAll( Arrays.asList( FileUtil.readStringFromFile(disabledPresubmitTestsFile) .split("\\r?\\n"))); } catch (IOException e) { RuntimeException runtimeException = new RuntimeException( String.format( "IO error (%s) when reading disabled tests from file (%s)", e.getMessage(), disabledPresubmitTestsFile.getAbsolutePath()), e); throw runtimeException; } return disabledTests; }
Source:
<code>public ZNRecord computePartitionAssignment(final List<String> allNodes, final List<String> liveNodes, final Map<String, Map<String, String>> currentMapping, ResourceControllerDataProvider clusterData) { Topology allNodeTopology = new Topology(allNodes, allNodes, clusterData.getInstanceConfigMap(), clusterData.getClusterConfig()); List<String> allNodesWithSpaces = allNodeTopology.getAllNodesWithAvailableSpaces(); <START> return computeBestPartitionAssignment(allNodesWithSpaces, liveNodes, currentMapping, <END> clusterData); }</code><technical_language>I mentioned want clean 0 weight nodes liveNodes well</technical_language>

Target:
public ZNRecord computePartitionAssignment(final List<String> allNodes, final List<String> liveNodes, final Map<String, Map<String, String>> currentMapping, ResourceControllerDataProvider clusterData) { Map<String, InstanceConfig> instanceConfigMap = clusterData.getInstanceConfigMap(); if (instanceConfigMap == null || !instanceConfigMap.keySet().containsAll(allNodes)) { throw new HelixException(String.format("Config for instances %s is not found!", allNodes.removeAll(instanceConfigMap.keySet()))); } return computeBestPartitionAssignment(getNonZeroWeightNodes(allNodes, instanceConfigMap), liveNodes, currentMapping, clusterData); }
Source:
<code>public void testTimerStreamCallingWithNullHandlerCancelsTheTimer() throws Exception { ReadStream<Long> timer = vertx.timerStream(10); AtomicInteger count = new AtomicInteger(); timer.handler(l -> { if (count.incrementAndGet() == 1) { timer.handler(null); vertx.setTimer(200, id -> { <START> assertEquals(1, count.get()); <END> testComplete(); }); } else { fail(); } }); await(); }</code><technical_language>If want verify a timer is called once, need wait a bit for completing test</technical_language>

Target:
public void testTimerStreamCallingWithNullHandlerCancelsTheTimer() throws Exception { vertx.runOnContext(v -> { ReadStream<Long> timer = vertx.timerStream(200); AtomicInteger count = new AtomicInteger(); timer.handler(l -> { if (count.incrementAndGet() == 1) { timer.handler(null); vertx.setTimer(200, id -> { assertEquals(1, count.get()); testComplete(); }); } else { fail(); } }); }); await(); }
Source:
<code>public String readLine() throws IOException { String output = new String(outStream.toByteArray(), StandardCharsets.UTF_8); processLine(index, output); String ret = args[index++]; outStream.reset(); <START> return ret; <END> }</code><technical_language>confused this method returns 1 of steps</technical_language>

Target:
public String readLine() throws IOException { String output = new String(outStream.toByteArray(), StandardCharsets.UTF_8); processLine(stepIndex, output); String ret = steps[stepIndex++]; outStream.reset(); return ret; }
Source:
<code>protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); mc.getTextureManager().bindTexture(Constants.ENG_GUI_TEXTURES); int k = (width - xSize) / 2; int l = (height - ySize) / 2; GL11.glEnable(3042); drawTexturedModalRect(k, l, 0, 0, xSize, ySize); IItemHandler itemHandler = tileEntity.getCapability(ITEM_HANDLER_CAPABILITY, null); <START> assert itemHandler != null; <END> Item engineeringItem = itemHandler.getStackInSlot(0).getItem(); if (engineeringItem instanceof Engineerable) { Engineerable item = (Engineerable) engineeringItem; item.drawBackground(this, 0, k + 52, l + 8); int i = 0; for (Pair<Integer, Integer> pair : item.engineerCoordinates()) { int x = pair.getLeft(); int y = pair.getRight(); item.drawSlot(this, i, k + x + 52, l + y + 8); i++; } } }</code><technical_language>assert testing. Change if statement, exception</technical_language>

Target:
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); mc.getTextureManager().bindTexture(Constants.ENG_GUI_TEXTURES); int k = (width - xSize) / 2; int l = (height - ySize) / 2; GL11.glEnable(3042); drawTexturedModalRect(k, l, 0, 0, xSize, ySize); IItemHandler itemHandler = tileEntity.getCapability(ITEM_HANDLER_CAPABILITY, null); if (itemHandler == null) { return; } Item engineeringItem = itemHandler.getStackInSlot(0).getItem(); if (engineeringItem instanceof Engineerable) { Engineerable item = (Engineerable) engineeringItem; item.drawBackground(this, 0, k + 52, l + 8); int i = 0; for (Pair<Integer, Integer> pair : item.engineerCoordinates()) { int x = pair.getLeft(); int y = pair.getRight(); item.drawSlot(this, i, k + x + 52, l + y + 8); i++; } } }
Source:
<code>public void getConstraintEntryFromSimplePredicates() { final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = new HashMap<>(); String fieldName = "FIELD_NAME"; List<SimplePredicate> simplePredicates = IntStream.range(0, 2) <START> .mapToObj(index -> KiePMMLASTTestUtils.getSimplePredicate(fieldName, DataType.STRING, "VALUE-" + index, SimplePredicate.Operator.LESS_THAN, fieldTypeMap)).collect(Collectors.toList()); <END> final KiePMMLFieldOperatorValue retrieved = KiePMMLASTFactoryUtils.getConstraintEntryFromSimplePredicates(fieldName, "or", simplePredicates, fieldTypeMap); assertEquals(fieldName, retrieved.getName()); assertNotNull(retrieved.getConstraintsAsString()); String expected = "value < \"VALUE-0\" or value < \"VALUE-1\""; assertEquals(expected, retrieved.getConstraintsAsString()); }</code><technical_language>Please split multiple lines</technical_language>

Target:
public void getConstraintEntryFromSimplePredicates() { final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = new HashMap<>(); String fieldName = "FIELD_NAME"; List<SimplePredicate> simplePredicates = IntStream.range(0, 2) .mapToObj(index -> KiePMMLASTTestUtils .getSimplePredicate(fieldName, DataType.STRING, "VALUE-" + index, SimplePredicate.Operator.LESS_THAN, fieldTypeMap)).collect(Collectors.toList()); final KiePMMLFieldOperatorValue retrieved = KiePMMLASTFactoryUtils .getConstraintEntryFromSimplePredicates(fieldName, BOOLEAN_OPERATOR.OR, simplePredicates, fieldTypeMap); assertEquals(fieldName, retrieved.getName()); assertNotNull(retrieved.getConstraintsAsString()); String expected = "value < \"VALUE-0\" || value < \"VALUE-1\""; assertEquals(expected, retrieved.getConstraintsAsString()); }
Source:
<code><START> public BigDecimal convert(Object value) throws TalendRuntimeException { <END> if (value == null) { return returnDefaultValue(); } else { if (value instanceof BigDecimal) { BigDecimal castedValue = (BigDecimal) value; if (properties.containsKey(BigDecimalConverter.SCALE)) { if (properties.containsKey(BigDecimalConverter.ROUNDING_MODE)) { return castedValue.setScale(getScale(), getRoundingMode()); } else { return castedValue.setScale(getScale()); } } else { return castedValue; } } else { if (properties.containsKey(BigDecimalConverter.DECIMAL_FORMAT)){ Number convertedValue = null; try { convertedValue = getDecimalFormat().parse(value.toString()); } catch (ParseException e) { throw TalendRuntimeException.createUnexpectedException("Unable to parse " + value); } return new BigDecimal(convertedValue.toString()); } else if (properties.containsKey(BigDecimalConverter.PRECISION)) { if (properties.containsKey(BigDecimalConverter.ROUNDING_MODE)) { return convertValue(value, new MathContext(getPrecision(), getRoundingMode())); } else { return convertValue(value, new MathContext(getPrecision())); } } else { return convertValue(value); } } } }</code><technical_language>need throw a RuntimeException</technical_language>

Target:
public BigDecimal convert(Object value) { if (value == null) { return returnDefaultValue(); } else { if (value instanceof BigDecimal) { BigDecimal castedValue = (BigDecimal) value; if (properties.containsKey(BigDecimalConverter.SCALE)) { if (properties.containsKey(BigDecimalConverter.ROUNDING_MODE)) { return castedValue.setScale(getScale(), getRoundingMode()); } else { return castedValue.setScale(getScale()); } } else { return castedValue; } } else { if (properties.containsKey(BigDecimalConverter.DECIMAL_FORMAT)) { Number convertedValue = null; try { convertedValue = getDecimalFormat().parse(value.toString()); } catch (ParseException e) { throw TalendRuntimeException.createUnexpectedException("Unable to parse " + value); } return new BigDecimal(convertedValue.toString()); } else if (properties.containsKey(BigDecimalConverter.PRECISION)) { if (properties.containsKey(BigDecimalConverter.ROUNDING_MODE)) { return convertValue(value, new MathContext(getPrecision(), getRoundingMode())); } else { return convertValue(value, new MathContext(getPrecision())); } } else { return convertValue(value); } } } }
Source:
<code>boolean updateGame(final ApiKey apiKey, final String gameId, final LobbyGame lobbyGame) { final GameId listedGameId = new GameId(apiKey, gameId); return Optional.ofNullable(games.getIfPresent(listedGameId)) .map( game -> { games.put(listedGameId, lobbyGame); return true; }) <START> .orElse(false); <END> }</code><technical_language>this, this: java return games.asMap().replace(listedGameId, lobbyGame) != null</technical_language>

Target:
boolean updateGame(final ApiKey apiKey, final String gameId, final LobbyGame lobbyGame) { final var listedGameId = new GameId(apiKey, gameId); final var existingValue = games.asMap().replace(listedGameId, lobbyGame); return existingValue != null; }
Source:
<code>private boolean isMaintenanceOrDerivative(final String methodType) { <START> return methodType.equals("DER") || methodType.equals("MAN"); <END> }</code><technical_language>MethodType.DERIVATIVE.getCode() MethodType.MAINTENANCE.getCode()</technical_language>

Target:
private boolean isMaintenanceOrDerivative(final String methodType) { return methodType.equals(MethodType.DERIVATIVE.getCode()) || methodType.equals(MethodType.MAINTENANCE.getCode()); }
Source:
<code>public void testValidRequest() throws Exception { String serviceId = setupTestService(); while(baragonServiceClient.getRequest(serviceId).get().getLoadBalancerState().equals(BaragonRequestState.WAITING)) { } if(baragonServiceClient.getRequest(serviceId).get().getLoadBalancerState().equals(BaragonRequestState.SUCCESS)) { testGetService(); testState(); testClusterBasePaths(); removeService(serviceId); } else { BaragonResponse resp = baragonServiceClient.getRequest(serviceId).get(); <START> throw new Exception("Request did not succeed: " + resp.getMessage().get().toString() <END> + "\nState: " + resp.getLoadBalancerState()); } }</code><technical_language>getMessage().get() is a String, need for toString()</technical_language>

Target:
public void testValidRequest() throws Exception { String serviceId = setupTestService(); waitForStatus(serviceId, BaragonRequestState.SUCCESS); testGetService(serviceId); testState(serviceId); testClusterBasePaths(serviceId); }
Source:
<code><START> public SpeechSynthesis startMouth() { <END> if (speechSynthesizer.getSpeechEngine() != null) { if (mouth == null) { mouth = (SpeechSynthesis) Runtime.loadAndStart(this.getIntanceName() + ".mouth", speechSynthesizer.getSpeechEngine()); } this.attach((Attachable) mouth); speakBlocking(languagePack.get("STARTINGMOUTH")); speakBlocking(languagePack.get("WHATISTHISLANGUAGE")); } else { speakAlert(languagePack.get("MYVOICETYPE")); } return mouth; }</code><technical_language>change this.. working before</technical_language>

Target:
public SpeechSynthesis startMouth() { if (mouth == null) { mouth = (SpeechSynthesis) startPeer("mouth"); } this.attach((Attachable) mouth); speakBlocking(languagePack.get("STARTINGMOUTH")); speakBlocking(languagePack.get("WHATISTHISLANGUAGE")); return mouth; }
Source:
<code>public void setManagementContext(ManagementContextInternal val) { if (val == null && (val instanceof NonDeploymentManagementContext)) { <START> System.out.println("fafe"); <END> } this.initialManagementContext = checkNotNull(val, "initialManagementContext"); this.entityManager = new NonDeploymentEntityManager(val); this.locationManager = new NonDeploymentLocationManager(val); this.accessManager = new NonDeploymentAccessManager(val); this.usageManager = new NonDeploymentUsageManager(val); }</code><technical_language>Delete this - debugging</technical_language>

Target:
public void setManagementContext(ManagementContextInternal val) { this.initialManagementContext = checkNotNull(val, "initialManagementContext"); this.entityManager = new NonDeploymentEntityManager(val); this.locationManager = new NonDeploymentLocationManager(val); this.accessManager = new NonDeploymentAccessManager(val); this.usageManager = new NonDeploymentUsageManager(val); }
Source:
<code>public RuleResult validate(final PasswordData passwordData) { final List<Rule> rulesByLength = getRulesByLength(passwordData.getPassword().length()); <START> if (rulesByLength == null || rulesByLength.isEmpty()) { <END> throw new IllegalStateException( "No rules have been configured for password length " + passwordData.getPassword().length()); } int successCount = 0; final RuleResult result = new RuleResult(true); for (Rule rule : rulesByLength) { final RuleResult rr = rule.validate(passwordData); if (!rr.isValid()) { if (reportRuleFailures) { result.getDetails().addAll(rr.getDetails()); } } else { successCount++; } } if (successCount < rulesByLength.size()) { result.setValid(false); result.getDetails().add( new RuleResultDetail(ERROR_CODE, createRuleResultDetailParameters(successCount, rulesByLength.size()))); } return result; }</code><technical_language>I move empty list check rule setup methods. I empty ruleset is more a sign of bad usage misconfiguration a valid case</technical_language>

Target:
public RuleResult validate(final PasswordData passwordData) { final int passwordLength = passwordData.getPassword().length(); final List<Rule> rulesByLength = getRulesByLength(passwordLength); if (rulesByLength == null) { return new RuleResult( false, new RuleResultDetail(ERROR_CODE_RULES, createRuleResultDetailParameters(passwordLength, 0, 0))); } int successCount = 0; final RuleResult result = new RuleResult(true); for (Rule rule : rulesByLength) { final RuleResult rr = rule.validate(passwordData); if (!rr.isValid()) { if (reportRuleFailures) { result.getDetails().addAll(rr.getDetails()); } } else { successCount++; } } if (successCount < rulesByLength.size()) { result.setValid(false); result.getDetails().add( new RuleResultDetail( ERROR_CODE, createRuleResultDetailParameters(passwordLength, successCount, rulesByLength.size()))); } return result; }
Source:
<code>public Project getProjectByAlias(String projectAlias) throws IOException { <START> if (projectStore != null) { <END> return projectStore.getByAlias(projectAlias); } else { throw new IOException("No projectStore available. Check that it has been declared in the Spring config."); } }</code><technical_language>please :fire: boilerplate if (projectStore != null) ...else blocks</technical_language>

Target:
public Project getProjectByAlias(String projectAlias) throws IOException { Project project = projectStore.getByAlias(projectAlias); authorizationManager.throwIfNotReadable(project); return project; }
Source:
<code>public StructuredRecord joinOn(String stageName, StructuredRecord record) { List<Schema.Field> fields = new ArrayList<>(); Schema schema = record.getSchema(); List<String> joinKeys = perStageJoinKeys.get(stageName); int i = 1; for (String joinKey : joinKeys) { Schema.Field field = schema.getField(joinKey); if (field == null) { <START> collector.addFailure( <END> String.format("Join key field '%s' is not present in input stage of '%s'.", joinKey, stageName), null) .withConfigProperty(conf.JOIN_KEYS); collector.getOrThrowException(); return null; } Schema.Field joinField = Schema.Field.of(String.valueOf(i++), field.getSchema()); fields.add(joinField); } Schema keySchema = Schema.recordOf("join.key", fields); StructuredRecord.Builder keyRecordBuilder = StructuredRecord.builder(keySchema); i = 1; for (String joinKey : joinKeys) { keyRecordBuilder.set(String.valueOf(i++), record.get(joinKey)); } return keyRecordBuilder.build(); }</code><technical_language>collector needed in this scenario, throw exception directly. collector is useful configure time, collect more failure display user once</technical_language>

Target:
public StructuredRecord joinOn(String stageName, StructuredRecord record) { List<Schema.Field> fields = new ArrayList<>(); Schema schema = record.getSchema(); List<String> joinKeys = perStageJoinKeys.get(stageName); int i = 1; for (String joinKey : joinKeys) { Schema.Field field = schema.getField(joinKey); if (field == null) { throw new IllegalArgumentException(String.format("Join key field '%s' does not exist in schema from '%s'.", joinKey, stageName)); } Schema.Field joinField = Schema.Field.of(String.valueOf(i++), field.getSchema()); fields.add(joinField); } Schema keySchema = Schema.recordOf("join.key", fields); StructuredRecord.Builder keyRecordBuilder = StructuredRecord.builder(keySchema); i = 1; for (String joinKey : joinKeys) { keyRecordBuilder.set(String.valueOf(i++), record.get(joinKey)); } return keyRecordBuilder.build(); }
Source:
<code>private static PartitionsSpec getDefaultPartitionsSpec( boolean forceGuaranteedRollup, @Nullable PartitionsSpec partitionsSpec, @Nullable Integer maxRowsPerSegment, @Nullable Long maxTotalRows, @Nullable Integer numShards, @Nullable List<String> partitionDimensions ) { if (partitionsSpec == null) { if (forceGuaranteedRollup) { if (maxRowsPerSegment != null || numShards != null || (partitionDimensions != null && !partitionDimensions.isEmpty())) { return new HashedPartitionsSpec(maxRowsPerSegment, numShards, partitionDimensions); } else { return null; } } else { if (maxRowsPerSegment != null || maxTotalRows != null) { return new DynamicPartitionsSpec(maxRowsPerSegment, maxTotalRows); } else { return null; } } } else { if (forceGuaranteedRollup) { if (!(partitionsSpec instanceof HashedPartitionsSpec)) { <START> throw new ISE("HashedPartitonsSpec must be used for perfect rollup"); <END> } } else { if (!(partitionsSpec instanceof DynamicPartitionsSpec)) { throw new ISE("DynamicPartitionsSpec must be used for best-effort rollup"); } } return partitionsSpec; } }</code><technical_language>Typo: HashedPartitionsSpec</technical_language>

Target:
private static PartitionsSpec getDefaultPartitionsSpec( boolean forceGuaranteedRollup, @Nullable PartitionsSpec partitionsSpec, @Nullable Integer maxRowsPerSegment, @Nullable Long maxTotalRows, @Nullable Integer numShards, @Nullable List<String> partitionDimensions ) { if (partitionsSpec == null) { if (forceGuaranteedRollup) { if (maxRowsPerSegment != null || numShards != null || (partitionDimensions != null && !partitionDimensions.isEmpty())) { return new HashedPartitionsSpec(maxRowsPerSegment, numShards, partitionDimensions); } else { return null; } } else { if (maxRowsPerSegment != null || maxTotalRows != null) { return new DynamicPartitionsSpec(maxRowsPerSegment, maxTotalRows); } else { return null; } } } else { if (forceGuaranteedRollup) { if (!(partitionsSpec instanceof HashedPartitionsSpec)) { throw new ISE("HashedPartitionsSpec must be used for perfect rollup"); } } else { if (!(partitionsSpec instanceof DynamicPartitionsSpec)) { throw new ISE("DynamicPartitionsSpec must be used for best-effort rollup"); } } return partitionsSpec; } }
Source:
<code>private boolean drainQueue() { boolean busy = false; while (true) { try { long cursor; while ((cursor = sequence.next()) < 0) { if (cursor == -1) { return busy; } } busy = true; LineTcpMeasurementEvent event = queue.get(cursor); boolean eventProcessed; try { if (event.threadId == id) { eventProcessed = processNextEvent(event); } else { if (event.isRebalanceEvent()) { eventProcessed = processRebalance(event); } else { eventProcessed = true; } } } catch (RuntimeException ex) { LOG.error().$(ex).$(); eventProcessed = true; } if (eventProcessed) { sequence.done(cursor); } <START> } catch (RuntimeException ex) { <END> LOG.error().$(ex).$(); } } }</code><technical_language>exception typing is lacking. This code is untested</technical_language>

Target:
private boolean drainQueue() { boolean busy = false; while (true) { long cursor; while ((cursor = sequence.next()) < 0) { if (cursor == -1) { return busy; } } busy = true; LineTcpMeasurementEvent event = queue.get(cursor); boolean eventProcessed; if (event.threadId == id) { eventProcessed = processNextEvent(event); } else { if (event.isRebalanceEvent()) { eventProcessed = processRebalance(event); } else { eventProcessed = true; } } if (eventProcessed) { sequence.done(cursor); } } }
Source:
<code>public GeneEvidence(Evidence e) { this.setGene(e.getGene()); this.setEvidenceId(e.getEvidenceId()); this.setEvidenceType(e.getEvidenceType()); this.setStatus(e.getStatus()); this.setLastEdit(e.getLastEdit()); this.setArticles(e.getArticles()); <START> this.setShortDesc(e.getShortDescription()); <END> this.setDesc(e.getDescription()); }</code><technical_language>In Evidence, is attribute called shortDescription, get method. This cased error I build, need add it</technical_language>

Target:
public GeneEvidence(Evidence e) { this.setGene(e.getGene()); this.setEvidenceId(e.getEvidenceId()); this.setEvidenceType(e.getEvidenceType()); this.setStatus(e.getStatus()); this.setLastEdit(e.getLastEdit()); this.setArticles(e.getArticles()); this.setDesc(e.getDescription()); }
Source:
<code>public MandateConnectorResponseBuilder withLinks(List<PaymentConnectorResponseLink> links) { <START> this.links = links; <END> return this; }</code><technical_language>this.links = List.copyOf(links) give warm reassurance of knowing this list mutated set this class</technical_language>

Target:
public MandateConnectorResponseBuilder withLinks(List<PaymentConnectorResponseLink> links) { this.links = List.copyOf(links); return this; }
Source:
<code>private HttpResponse executePost(String bucketName, String objectName, Map<String,String> headerMap, Map<String,String> queryParamMap, Object data) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { updateRegionCache(bucketName); int len = -1; if (data instanceof String) { len = ((String) data).length(); } if (data instanceof CompleteMultipartUpload) { len = ((CompleteMultipartUpload) data).toString().length(); <START> } <END> return execute(Method.POST, BucketRegionCache.INSTANCE.region(bucketName), bucketName, objectName, headerMap, queryParamMap, null, data, len); }</code><technical_language>execute{Head,Get,Post,Put,Delete} wrappers execute() for convenience readability APIs Spreading logic of type checking lead confusion in future a good idea</technical_language>

Target:
private HttpResponse executePost(String bucketName, String objectName, Map<String,String> headerMap, Map<String,String> queryParamMap, Object data) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { updateRegionCache(bucketName); return execute(Method.POST, BucketRegionCache.INSTANCE.region(bucketName), bucketName, objectName, headerMap, queryParamMap, data, 0); }
Source:
<code>private void select() { Intent i = new Intent(EntitySelectActivity.this.getIntent()); i.putExtra(SessionFrame.STATE_DATUM_VAL, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL)); <START> ACRAUtil.addCustomData(ACRAUtil.CURRENT_CASE, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL)); <END> setResult(RESULT_OK, i); finish(); }</code><technical_language>a bit mixed OK for submit Case Id's ACRA's stuff convinced a full chain of custody acceptable. host server for htis data, right</technical_language>

Target:
private void select() { Intent i = new Intent(EntitySelectActivity.this.getIntent()); i.putExtra(SessionFrame.STATE_DATUM_VAL, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL)); setResult(RESULT_OK, i); finish(); }
Source:
<code>public int hashCode() { <START> return new HashCodeBuilder(17, 37) <END> .append(id) .append(gatewayName) .append(credentials) .toHashCode(); }</code><technical_language>Objects.hash( ) basically is part of standard library</technical_language>

Target:
public int hashCode() { return Objects.hash(id, gatewayName, credentials); }
Source:
<code>Queue<ReplicaId> orderReplicaIds(String datacenterName, List<ReplicaId> replicaIds, boolean crossDCProxyCallEnabled) { Queue<ReplicaId> orderedReplicaIds = new ArrayDeque<ReplicaId>(replicaIdCount); List<ReplicaId> localReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); for (ReplicaId replicaId : replicaIds) { String dcName = replicaId.getDataNodeId().getDatacenterName(); if (dcName.equals(datacenterName)) { localReplicaIds.add(replicaId); this.localRequests.add(replicaId); } else if (crossDCProxyCallEnabled) { if(remoteReplicasPerDatacentre.containsKey(dcName)){ remoteReplicasPerDatacentre.get(dcName).add(replicaId); } else{ List<ReplicaId> replicaIdList = new ArrayList<ReplicaId>(); replicaIdList.add(replicaId); remoteReplicasPerDatacentre.put(dcName, replicaIdList); dataCentreCount++; } } } Collections.shuffle(localReplicaIds); orderedReplicaIds.addAll(localReplicaIds); for(String remoteDataCentre : remoteReplicasPerDatacentre.keySet()) { List<ReplicaId> remoteReplicaList = remoteReplicasPerDatacentre.get(remoteDataCentre); Collections.shuffle(remoteReplicaList); orderedReplicaIds.addAll(remoteReplicaList); } <START> <END> return orderedReplicaIds; }</code><technical_language>replicas</technical_language>

Target:
Queue<ReplicaId> orderReplicaIds(String datacenterName, List<ReplicaId> replicaIds, boolean crossDCProxyCallEnabled) { Queue<ReplicaId> orderedReplicaIds = new ArrayDeque<ReplicaId>(replicaIdCount); List<ReplicaId> localReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); List<ReplicaId> remoteReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); List<ReplicaId> downReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); for (ReplicaId replicaId : replicaIds) { if (replicaId.isDown()) { downReplicaIds.add(replicaId); } else if (replicaId.getDataNodeId().getDatacenterName().equals(datacenterName)) { localReplicaIds.add(replicaId); } else if (crossDCProxyCallEnabled) { remoteReplicaIds.add(replicaId); } } Collections.shuffle(localReplicaIds); orderedReplicaIds.addAll(localReplicaIds); Collections.shuffle(remoteReplicaIds); orderedReplicaIds.addAll(remoteReplicaIds); Collections.shuffle(downReplicaIds); orderedReplicaIds.addAll(downReplicaIds); return orderedReplicaIds; }
Source:
<code>public String toString() { final StringBuilder sb = new StringBuilder( "S3AFileSystem{"); sb.append("uri=").append(uri); sb.append(", workingDir=").append(workingDir); sb.append(", inputPolicy=").append(inputPolicy); sb.append(", partSize=").append(partSize); sb.append(", enableMultiObjectsDelete=").append(enableMultiObjectsDelete); sb.append(", maxKeys=").append(maxKeys); if (cannedACL != null) { sb.append(", cannedACL=").append(cannedACL.toString()); } sb.append(", readAhead=").append(readAhead); sb.append(", blockSize=").append(getDefaultBlockSize()); sb.append(", multiPartThreshold=").append(multiPartThreshold); if (serverSideEncryptionAlgorithm != null) { sb.append(", serverSideEncryptionAlgorithm='") .append(serverSideEncryptionAlgorithm) .append('\''); } <START> if (S3AUtils.getServerSideEncryptionKey(getConf()) != null) { <END> sb.append(", serverSideEncryptionKey='*********'"); } if (blockFactory != null) { sb.append(", blockFactory=").append(blockFactory); } sb.append(", executor=").append(threadPoolExecutor); sb.append(", statistics {") .append(statistics) .append("}"); sb.append(", metrics {") .append(instrumentation.dump("{", "=", "} ", true)) .append("}"); sb.append('}'); return sb.toString(); }</code><technical_language>cut this</technical_language>

Target:
public String toString() { final StringBuilder sb = new StringBuilder( "S3AFileSystem{"); sb.append("uri=").append(uri); sb.append(", workingDir=").append(workingDir); sb.append(", inputPolicy=").append(inputPolicy); sb.append(", partSize=").append(partSize); sb.append(", enableMultiObjectsDelete=").append(enableMultiObjectsDelete); sb.append(", maxKeys=").append(maxKeys); if (cannedACL != null) { sb.append(", cannedACL=").append(cannedACL.toString()); } sb.append(", readAhead=").append(readAhead); sb.append(", blockSize=").append(getDefaultBlockSize()); sb.append(", multiPartThreshold=").append(multiPartThreshold); if (serverSideEncryptionAlgorithm != null) { sb.append(", serverSideEncryptionAlgorithm='") .append(serverSideEncryptionAlgorithm) .append('\''); } if (blockFactory != null) { sb.append(", blockFactory=").append(blockFactory); } sb.append(", executor=").append(threadPoolExecutor); sb.append(", statistics {") .append(statistics) .append("}"); sb.append(", metrics {") .append(instrumentation.dump("{", "=", "} ", true)) .append("}"); sb.append('}'); return sb.toString(); }
Source:
<code>@Test public void verifyThrowsOffMainThread() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { try { MainThreadSubscription.verifyMainThread(); fail(); } catch (IllegalStateException e) { <START> latch.countDown(); <END> } } }).start(); assertTrue(latch.await(1, SECONDS)); }</code><technical_language>check exception message here</technical_language>

Target:
@Test public void verifyThrowsOffMainThread() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { try { MainThreadSubscription.verifyMainThread(); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage().startsWith("Expected to be called on the main thread")); latch.countDown(); } } }).start(); assertTrue(latch.await(1, SECONDS)); }