auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void addComponentDescriptorButtons(JToolBar toolBar) { final DescriptorProvider descriptorProvider = _analysisJobBuilder.getConfiguration().getDescriptorProvider(); final Set<ComponentSuperCategory> superCategories = descriptorProvider.getComponentSuperCategories(); for (ComponentSuperCategory superCategory : superCategories) { final String name = superCategory.getName(); final String description = "<html><b>" + name + "</b><br/>" + superCategory.getDescription() + "</html>"; final PopupButton popupButton = new PopupButton(name); applyMenuPopupButttonStyling(popupButton); DCPopupBubble popupBubble = new DCPopupBubble(_glassPane, description, 0, 0, IconUtils.getComponentSuperCategoryIcon(superCategory)); popupBubble.attachTo(popupButton, new DCPopupBubble.PopupCallback() { @Override public boolean onBeforeShow() { for(PopupButton scButton : _superCategoryButtons) { if(scButton.isSelected()){ return false; } } return true; } }); final JPopupMenu menu = popupButton.getMenu(); final DescriptorMenuBuilder menuBuilder = new DescriptorMenuBuilder(_analysisJobBuilder, _usageLogger, superCategory, null); menuBuilder.addItemsToPopupMenu(menu); if (menu.isVisible()) { popupBubble.hide(); } toolBar.add(popupButton); _superCategoryButtons.add(popupButton); } }

Target:
private void addComponentDescriptorButtons(JToolBar toolBar) { final DescriptorProvider descriptorProvider = _analysisJobBuilder.getConfiguration().getDescriptorProvider(); final Set<ComponentSuperCategory> superCategories = descriptorProvider.getComponentSuperCategories(); for (ComponentSuperCategory superCategory : superCategories) { final String name = superCategory.getName(); final String description = "<html><b>" + name + "</b><br/>" + superCategory.getDescription() + "</html>"; final PopupButton popupButton = new PopupButton(name); applyMenuPopupButttonStyling(popupButton); DCPopupBubble popupBubble = new DCPopupBubble(_glassPane, description, 0, 0, IconUtils.getComponentSuperCategoryIcon(superCategory)); popupBubble.attachTo(popupButton, new DCPopupBubble.PopupCallback() { @Override public boolean onBeforeShow() { for(PopupButton scButton : _superCategoryButtons) { if(scButton.isSelected()){ return false; } } return true; } }); final JPopupMenu menu = popupButton.getMenu(); final DescriptorMenuBuilder menuBuilder = new DescriptorMenuBuilder(_analysisJobBuilder, _usageLogger, superCategory, null); menuBuilder.addItemsToPopupMenu(menu); toolBar.add(popupButton); _superCategoryButtons.add(popupButton); } }
Source:
public void testStateIsCleared() throws Exception { final File fileToProcess = new File(getPath("messages_test_de.properties")); final String charset = StandardCharsets.UTF_8.name(); final TranslationCheck check = new TranslationCheck(); check.beginProcessing(charset); check.processFiltered(fileToProcess, new FileText(fileToProcess, charset)); check.beginProcessing(charset); final Field field = check.getClass().getDeclaredField("filesToProcess"); field.setAccessible(true); assertTrue("Stateful field is not cleared on beginProcessiong", ((Collection<File>) field.get(check)).isEmpty()); }

Target:
public void testStateIsCleared() throws Exception { final File fileToProcess = new File( getPath("InputTranslationCheckFireErrors_de.properties") ); final String charset = StandardCharsets.UTF_8.name(); final TranslationCheck check = new TranslationCheck(); check.beginProcessing(charset); check.processFiltered(fileToProcess, new FileText(fileToProcess, charset)); check.beginProcessing(charset); final Field field = check.getClass().getDeclaredField("filesToProcess"); field.setAccessible(true); assertTrue("Stateful field is not cleared on beginProcessing", ((Collection<File>) field.get(check)).isEmpty()); }
Source:
public void visitBinaryComparisonType(VisitableXmlElement<BinaryComparisonOpType> visitable) { JAXBElement<BinaryComparisonOpType> element = visitable.getElement(); String localPart = element.getName().getLocalPart(); LOGGER.debug(localPart); String operator = BINARY_COMPARE_MAPPING.get(localPart); if (operator == null) { throw new IllegalArgumentException( "Cannot find mapping for binary comparison operator: " + localPart); } builder.beginBinaryComparisonType(operator); element.getValue().getExpression().forEach(jax -> makeVisitable(jax).accept(this)); builder.endBinaryComparisonType(); }

Target:
public void visitBinaryComparisonType(VisitableXmlElement<BinaryComparisonOpType> visitable) { JAXBElement<BinaryComparisonOpType> element = visitable.getElement(); String localPart = element.getName().getLocalPart(); traceLocalPart(localPart); String operator = BINARY_COMPARE_MAPPING.get(localPart); if (operator == null) { throw new IllegalArgumentException( "Cannot find mapping for binary comparison operator: " + localPart); } builder.beginBinaryComparisonType(operator); element.getValue().getExpression().forEach(jax -> makeVisitable(jax).accept(this)); builder.endTerminalType(); }
Source:
public Optional<List<FieldSchema>> getFields(String databaseName, String tableName) { try { return retry() .stopOn(MetaException.class, UnknownTableException.class, UnknownDBException.class) .stopOnIllegalExceptions() .run("getFields", stats.getGetFields().wrap(() -> { try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) { return Optional.of(ImmutableList.copyOf(client.getFields(databaseName, tableName))); } })); } catch (NoSuchObjectException e) { return Optional.empty(); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw Throwables.propagate(e); } }

Target:
public Optional<List<FieldSchema>> getFields(String databaseName, String tableName) { try { return retry() .stopOn(MetaException.class, UnknownTableException.class, UnknownDBException.class) .stopOnIllegalExceptions() .run("getFields", stats.getGetFields().wrap(() -> { try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) { return Optional.of(ImmutableList.copyOf(client.getFields(databaseName, tableName))); } })); } catch (NoSuchObjectException e) { return Optional.empty(); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }
Source:
public AsyncQueryResultStorage getResultsByID(String asyncQueryID) { log.debug("getResultsByID"); AsyncQueryResultStorage asyncQueryResultStorages = null; try { asyncQueryResultStorages = (AsyncQueryResultStorage) EIT.executeInTransaction(elide, dataStore, (tx, scope) -> { EntityProjection asyncQueryCollection = EntityProjection.builder() .type(AsyncQueryResultStorage.class) .build(); Object loaded = tx.loadObject(asyncQueryCollection, asyncQueryID, scope); return loaded; }); } catch (Exception e) { log.error("Exception: {}", e); } return asyncQueryResultStorages; }

Target:
public byte[] getResultsByID(String asyncQueryID) { log.debug("getAsyncResultsByID"); AsyncQuery asyncQuery = null; byte[] byteResult = null; try { asyncQuery = (AsyncQuery) DBUtil.executeInTransaction(elideSettings, dataStore, (tx, scope) -> { EntityProjection asyncQueryCollection = EntityProjection.builder() .type(AsyncQuery.class) .build(); Object loaded = tx.loadObject(asyncQueryCollection, asyncQueryID, scope); return loaded; }); if (asyncQuery != null && asyncQuery.getResult().getAttachment() != null) { Blob result = asyncQuery.getResult().getAttachment(); byteResult = result.getBytes(1, (int) result.length()); } } catch (SQLException e) { log.error("Exception: {}", e); throw new IllegalStateException(e); } return byteResult; }
Source:
public static void queueStart(String baseUrl, Report r) { Queue queue = QueueFactory.getDefaultQueue(); TaskOptions options = getTaskOptions(baseUrl, r); log.info("Forking to task with options: " + options.toString()); queue.add(options); }

Target:
public static void queueStart(String baseUrl, Report r) { Queue queue = QueueFactory.getDefaultQueue(); TaskOptions options = getTaskOptions(baseUrl, r); log.fine("Forking to task with options: " + options.toString()); queue.add(options); }
Source:
private VenueEntity adapt(Venue venue) { List<VenueNameInformationEntity> informationEntities = Lists.newArrayList(); for (VenueNameInformation duple : venue.nameInformation) { informationEntities.add(new VenueNameInformationEntity(duple.nameInformation, duple.language.code)); } return new VenueEntity(venue.group.name, venue.type.name, informationEntities); }

Target:
private VenueEntity adapt(Venue venue) { List<VenueNameEntity> nameEntities = Lists.newArrayList(); for (VenueName info : venue.names) { nameEntities.add(new VenueNameEntity(info.name, info.language.code)); } return new VenueEntity(venue.group.name, venue.type.name, nameEntities); }
Source:
private void placeItemsOnBoard() { int numberOfItems = 0; while (((double) numberOfItems) / grid.size() < NUMBER_OF_GRENADES) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { ((Square) grid.get(position)).addItem(new LightGrenade()); numberOfItems++; } } numberOfItems = 0; List<Teleporter> teleporters = new ArrayList<>(); while (((double) numberOfItems) / grid.size() < NUMBER_OF_TELEPORTERS) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { Teleporter teleporter = new Teleporter(getTeleporterDestination(teleporters), grid.get(position)); ((Square) grid.get(position)).addItem(teleporter); teleporters.add(teleporter); numberOfItems++; } } teleporters.remove(0); teleporters.get(0).setDestination(getTeleporterDestination(teleporters)); numberOfItems = 0; while (((double) numberOfItems) / grid.size() < NUMBER_OF_IDENTITY_DISKS) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { ((Square) grid.get(position)).addItem(new ChargedIdentityDisk()); numberOfItems++; } } }

Target:
private void placeItemsOnBoard() { int numberOfItems = 0; while (((double) numberOfItems) / grid.size() < NUMBER_OF_GRENADES) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { ((Square) grid.get(position)).addItem(new LightGrenade()); numberOfItems++; } } numberOfItems = 0; List<Teleporter> teleporters = new ArrayList<>(); while (((double) numberOfItems) / grid.size() < NUMBER_OF_TELEPORTERS) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { Teleporter teleporter = new Teleporter(getTeleporterDestination(teleporters), grid.get(position)); ((Square) grid.get(position)).addItem(teleporter); teleporters.add(teleporter); numberOfItems++; } } teleporters.remove(0); teleporters.get(0).setDestination(getTeleporterDestination(teleporters)); numberOfItems = 0; while (((double) numberOfItems) / grid.size() < NUMBER_OF_IDENTITY_DISKS) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { ((Square) grid.get(position)).addItem(new UnchargedIdentityDisk()); numberOfItems++; } } }
Source:
public void run() { m_trigger.triggered(m_calendar); synchronized (m_leasedThread) { m_leasedThread.set(Thread.currentThread()); } try { if (isExpired()) { cancel(true); } else if (isFinalRun()) { super.run(); } else { super.runAndReset(); } } finally { synchronized (m_leasedThread) { m_leasedThread.set(null); } finishInternal(); releasePermit(); } }

Target:
public void run() { m_trigger.triggered(m_calendar); m_leasedThread = Thread.currentThread(); try { if (isExpired()) { cancel(true); } else if (isFinalRun()) { super.run(); } else { super.runAndReset(); } } finally { synchronized (m_leasedThreadLock) { m_leasedThread = null; } finishInternal(); releasePermit(); } }
Source:
private void generateRequires(StringBuilder buffer) { buffer.append("BuildRequires: maven-local\n"); }

Target:
private void generateRequires(StringBuilder buffer) { for (Map.Entry<String, String> entry : model.getDependencies() .entrySet()) { buffer.append("BuildRequires: mvn(" + entry.getKey() + ":" + entry.getValue() + ")\n"); } buffer.append("BuildRequires: maven-local\n"); }
Source:
private void initOffsets(String toParse) { boolean hasByteOrderMark = toParse.startsWith(Character.toString(JavaScriptNodeBuilder.BYTE_ORDER_MARK)); lineStartOffsets.add(hasByteOrderMark ? -1 : 0); int i = 0; while (i < length) { if (toParse.charAt(i) == '\n' || toParse.charAt(i) == '\r') { int nextLineStartOffset = i + 1; if (i < (length - 1) && toParse.charAt(i) == '\r' && toParse.charAt(i + 1) == '\n') { nextLineStartOffset = i + 2; i++; } lineStartOffsets.add(nextLineStartOffset); } i++; } }

Target:
private void initOffsets(String toParse) { boolean hasByteOrderMark = toParse.startsWith(Character.toString(JavaScriptNodeBuilder.BYTE_ORDER_MARK)); lineStartOffsets.add(0); int i = 0; while (i < length) { if (toParse.charAt(i) == '\n' || toParse.charAt(i) == '\r') { int nextLineStartOffset = i + 1; if (i < (length - 1) && toParse.charAt(i) == '\r' && toParse.charAt(i + 1) == '\n') { nextLineStartOffset = i + 2; i++; } lineStartOffsets.add(nextLineStartOffset - (hasByteOrderMark ? 1 : 0)); } i++; } }
Source:
public Response deleteToken(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Token id to delete", required = true) @PathParam("tokenId") Long tokenId) { Token token = tokenDAO.findById(tokenId); checkUser(user, token.getUserId()); cachingAuthenticator.invalidate(token.getContent()); tokenDAO.delete(token); if (token.getTokenSource() == TokenType.ORCID_ORG) { User byId = userDAO.findById(user.getId()); byId.setOrcid(""); } token = tokenDAO.findById(tokenId); if (token == null) { return Response.noContent().build(); } else { return Response.serverError().build(); } }

Target:
public Response deleteToken(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Token id to delete", required = true) @PathParam("tokenId") Long tokenId) { Token token = tokenDAO.findById(tokenId); checkUser(user, token.getUserId()); cachingAuthenticator.invalidate(token.getContent()); tokenDAO.delete(token); if (token.getTokenSource() == TokenType.ORCID_ORG) { User byId = userDAO.findById(user.getId()); byId.setOrcid(null); } token = tokenDAO.findById(tokenId); if (token == null) { return Response.noContent().build(); } else { return Response.serverError().build(); } }
Source:
private Supplier<DruidFloatPredicate> getFloatPredicateSupplier() { return new Supplier<DruidFloatPredicate>() { private final Object initLock = new Object(); private DruidFloatPredicate predicate; private void initFloatValues() { if (predicate != null) { return; } synchronized (initLock) { if (predicate != null) { return; } List<Float> floats = new ArrayList<>(); for (String value : values) { Float floatValue = Floats.tryParse(value); if (floatValue != null) { floats.add(floatValue); } } if (floats.size() > FLOAT_HASHING_THRESHOLD) { final HashSet<Float> floatHashSet = new HashSet<>(floats); predicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return floatHashSet.contains(input); } }; } else { final float[] floatArray; floatArray = new float[floats.size()]; for (int i = 0; i < floats.size(); i++) { floatArray[i] = floats.get(i).floatValue(); } Arrays.sort(floatArray); predicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return Arrays.binarySearch(floatArray, input) >= 0; } }; } } } @Override public DruidFloatPredicate get() { initFloatValues(); return predicate; } }; }

Target:
private Supplier<DruidFloatPredicate> getFloatPredicateSupplier() { return new Supplier<DruidFloatPredicate>() { private final Object initLock = new Object(); private DruidFloatPredicate predicate; private void initFloatValues() { if (predicate != null) { return; } synchronized (initLock) { if (predicate != null) { return; } IntArrayList floatBits = new IntArrayList(values.size()); for (String value : values) { Float floatValue = Floats.tryParse(value); if (floatValue != null) { floatBits.add(Float.floatToIntBits(floatValue)); } } if (floatBits.size() > NUMERIC_HASHING_THRESHOLD) { final IntOpenHashSet floatBitsHashSet = new IntOpenHashSet(floatBits); predicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return floatBitsHashSet.contains(Float.floatToIntBits(input)); } }; } else { final int[] floatBitsArray = floatBits.toIntArray(); Arrays.sort(floatBitsArray); predicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return Arrays.binarySearch(floatBitsArray, Float.floatToIntBits(input)) >= 0; } }; } } } @Override public DruidFloatPredicate get() { initFloatValues(); return predicate; } }; }
Source:
DashboardInfo(String ref, String name) throws UnsupportedEncodingException { this.ref = ref; this.path = name; this.id = Joiner.on(':').join(ref, path); }

Target:
DashboardInfo(String ref, String name) throws UnsupportedEncodingException { this.ref = ref; this.path = name; this.id = Joiner.on(':').join(Url.encode(ref), Url.encode(path)); }
Source:
void postConstruct() { Events events = getFromServiceHandle(Globals.getDefaultBaseServiceLocator(), Events.class); if (events != null) { events.register(this); } }

Target:
void postConstruct() { Events events = getFromServiceHandle(Globals.getDefaultBaseServiceLocator(), Events.class); if (events != null) { events.register(this); } else { logger.log(Level.WARNING, "OpenTracing service not registered to Payara Events: " + "The Tracer for an application won't be removed upon undeployment"); } }
Source:
private static void closeMissingProject(IProject p, File projectFile, IProgressMonitor monitor) throws CoreException { boolean closeFailed = false; File projectRoot = projectFile.getParentFile(); if (!projectRoot.isFile()) { boolean hasRoot = projectRoot.exists(); if (!hasRoot) projectRoot.mkdirs(); try { if (projectFile.createNewFile()) p.close(new SubProgressMonitor(monitor, 1)); else closeFailed = true; } catch (IOException e) { closeFailed = true; } finally { try { FileUtils.delete(projectFile, FileUtils.RETRY | FileUtils.SKIP_MISSING); } catch (IOException e) { closeFailed = true; } if (hasRoot) try { FileUtils.delete(projectRoot, FileUtils.RETRY | FileUtils.SKIP_MISSING | FileUtils.RECURSIVE); } catch (IOException e) { closeFailed = true; } } } else closeFailed = true; if (closeFailed) p.delete(false, true, new SubProgressMonitor(monitor, 1)); }

Target:
private static void closeMissingProject(IProject p, File projectFile, IProgressMonitor monitor) throws CoreException { boolean closeFailed = false; File projectRoot = projectFile.getParentFile(); if (!projectRoot.isFile()) { boolean hasRoot = projectRoot.exists(); try { if (!hasRoot) FileUtils.mkdirs(projectRoot, true); if (projectFile.createNewFile()) p.close(new SubProgressMonitor(monitor, 1)); else closeFailed = true; } catch (IOException e) { closeFailed = true; } finally { try { FileUtils.delete(projectFile, FileUtils.RETRY | FileUtils.SKIP_MISSING); } catch (IOException e) { closeFailed = true; } if (hasRoot) try { FileUtils.delete(projectRoot, FileUtils.RETRY | FileUtils.SKIP_MISSING | FileUtils.RECURSIVE); } catch (IOException e) { closeFailed = true; } } } else closeFailed = true; if (closeFailed) p.delete(false, true, new SubProgressMonitor(monitor, 1)); }
Source:
static Map<String, Consumer<Object>> setAttributeConsumers(AzureBlobFileAttributeView view) { Map<String, Consumer<Object>> map = new HashMap<>(); map.put("blobHttpHeaders", obj -> { try { view.setBlobHttpHeaders((BlobHttpHeaders) obj); } catch (IOException e) { throw LoggingUtility.logError(view.logger, new UncheckedIOException(ATTR_CONSUMER_ERROR, e)); } }); map.put("metadata", obj -> { try { Map<String, String> m = (Map<String, String>) obj; if (m == null) { throw LoggingUtility.logError(view.logger, new ClassCastException()); } view.setMetadata((Map<String, String>) obj); } catch (IOException e) { throw LoggingUtility.logError(view.logger, new UncheckedIOException(ATTR_CONSUMER_ERROR, e)); } }); map.put("tier", obj -> { try { view.setTier((AccessTier) obj); } catch (IOException e) { throw LoggingUtility.logError(view.logger, new UncheckedIOException(ATTR_CONSUMER_ERROR, e)); } }); return map; }

Target:
static Map<String, Consumer<Object>> setAttributeConsumers(AzureBlobFileAttributeView view) { Map<String, Consumer<Object>> map = new HashMap<>(); map.put("blobHttpHeaders", obj -> { try { view.setBlobHttpHeaders((BlobHttpHeaders) obj); } catch (IOException e) { throw LoggingUtility.logError(view.logger, new UncheckedIOException(ATTR_CONSUMER_ERROR, e)); } }); map.put("metadata", obj -> { try { Map<String, String> m = (Map<String, String>) obj; if (m == null) { throw LoggingUtility.logError(view.logger, new ClassCastException()); } view.setMetadata(m); } catch (IOException e) { throw LoggingUtility.logError(view.logger, new UncheckedIOException(ATTR_CONSUMER_ERROR, e)); } }); map.put("tier", obj -> { try { view.setTier((AccessTier) obj); } catch (IOException e) { throw LoggingUtility.logError(view.logger, new UncheckedIOException(ATTR_CONSUMER_ERROR, e)); } }); return map; }
Source:
public boolean isFull() { return ctx.inventory.select().size() > Constants.INVENTORY_SIZE-1; }

Target:
public boolean isFull() { return ctx.inventory.select().size() >= Constants.INVENTORY_SIZE; }
Source:
public AuthenticatorAsyncTask(Activity activity) { mContext = activity.getApplicationContext(); mListener = new WeakReference<OnAuthenticatorTaskListener>((OnAuthenticatorTaskListener)activity); mActivity = activity; }

Target:
public AuthenticatorAsyncTask(Activity activity) { mContext = activity.getApplicationContext(); mListener = new WeakReference<OnAuthenticatorTaskListener>((OnAuthenticatorTaskListener)activity); }
Source:
private void invokeOnAllPartitions() { if (memberPartitions.isEmpty()) { future.setResult(Collections.EMPTY_MAP); if (callback != null) { callback.onResponse(Collections.EMPTY_MAP); } return; } for (final Map.Entry<Address, List<Integer>> mp : memberPartitions.entrySet()) { final Address address = mp.getKey(); List<Integer> partitions = mp.getValue(); PartitionIteratingOperation op = new PartitionIteratingOperation(operationFactory, toIntArray(partitions)); operationService.createInvocationBuilder(serviceName, op, address) .setTryCount(TRY_COUNT) .setTryPauseMillis(TRY_PAUSE_MILLIS) .invoke() .andThen(new FirstAttemptExecutionCallback(mp.getValue())); } }

Target:
private void invokeOnAllPartitions() { if (memberPartitions.isEmpty()) { future.setResult(Collections.EMPTY_MAP); return; } for (final Map.Entry<Address, List<Integer>> mp : memberPartitions.entrySet()) { final Address address = mp.getKey(); List<Integer> partitions = mp.getValue(); PartitionIteratingOperation op = new PartitionIteratingOperation(operationFactory, toIntArray(partitions)); operationService.createInvocationBuilder(serviceName, op, address) .setTryCount(TRY_COUNT) .setTryPauseMillis(TRY_PAUSE_MILLIS) .invoke() .andThen(new FirstAttemptExecutionCallback(partitions)); } }
Source:
protected ScenarioResult fillResult(FactMappingValue expectedResult, FactIdentifier factIdentifier, Supplier<ResultWrapper<?>> resultSupplier, ExpressionEvaluator expressionEvaluator) { ResultWrapper<?> resultValue = resultSupplier.get(); if (!resultValue.isSatisfied() && resultValue.getErrorMessage().isPresent()) { expectedResult.setExceptionMessage(resultValue.getErrorMessage().get()); } else if (!resultValue.isSatisfied()) { expectedResult.setErrorValue(expressionEvaluator.reverseFunction(resultValue.getResult())); } else { expectedResult.resetStatus(); } return new ScenarioResult(factIdentifier, expectedResult, resultValue.getResult()).setResult(resultValue.isSatisfied()); }

Target:
protected ScenarioResult fillResult(FactMappingValue expectedResult, FactIdentifier factIdentifier, Supplier<ResultWrapper<?>> resultSupplier, ExpressionEvaluator expressionEvaluator) { ResultWrapper<?> resultValue = resultSupplier.get(); if (!resultValue.isSatisfied() && resultValue.getErrorMessage().isPresent()) { expectedResult.setExceptionMessage(resultValue.getErrorMessage().get()); } else if (!resultValue.isSatisfied()) { expectedResult.setErrorValue(expressionEvaluator.fromObjectToExpression(resultValue.getResult())); } else { expectedResult.resetStatus(); } return new ScenarioResult(factIdentifier, expectedResult, resultValue.getResult()).setResult(resultValue.isSatisfied()); }
Source:
public void testToCalendarWithTimeZoneNull() { try { DateUtils.toCalendar(date1, null); fail("Expected NullPointerException to be thrown when TimeZone is null"); } catch(final NullPointerException npe) { } }

Target:
public void testToCalendarWithTimeZoneNull() { DateUtils.toCalendar(date1, null); }
Source:
public JSONObject createJsonFromLog(String log) throws JSONException { Pattern compile = Pattern.compile(this.pattern); Matcher m = compile.matcher(log); int count = m.groupCount(); int i = 1; JSONObject logObject = null; if (m.find()) { logObject = new JSONObject(); for(String field: this.getFieldNames()) { if (i > count) { break; } logObject.put(field, m.group(i)); i++; } } return logObject; }

Target:
public JSONObject createJsonFromLog(String log) throws JSONException { JSONObject logObject = null; if (this.compiledPattern != null) { Matcher m = this.compiledPattern.matcher(log); int count = m.groupCount(); if (m.find()) { int i = 1; logObject = new JSONObject(); for(String field: this.getFieldNames()) { if (i > count) { break; } logObject.put(field, m.group(i)); i++; } } } return logObject; }
Source:
public void beforeScenario() { this.deviceSimulatorSteps.removeAllTemporaryPropertiesFiles(); this.dlmsDatabaseSteps.prepareDatabaseForScenario(); this.prepareServiceEndpoint(); }

Target:
public void beforeScenario() { this.deviceSimulatorSteps.clearDlmsAttributeValues(); this.dlmsDatabaseSteps.prepareDatabaseForScenario(); this.prepareServiceEndpoint(); }
Source:
protected String getColorByProgress(int progress) { return "#669966"; }

Target:
protected String getColorByProgress(int progress) { return color.asCode(); }
Source:
private static File confirmFileSave(File file, File currentFile) { int reply = JOptionPane.NO_OPTION; while (file != null && file.exists() && !file.equals(currentFile) && reply == JOptionPane.NO_OPTION) { reply = JOptionPane.showConfirmDialog(null, file.getAbsoluteFile() + " already exists. Do you want to overwrite it?", "File already exists", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.NO_OPTION) { file = FileChooserService.getSelectedFile("tex", "TeX files", FileChooserService.DialogType.SAVE, true); } } return file; }

Target:
private static File confirmFileSave(File file, File currentFile) { int reply = JOptionPane.NO_OPTION; while (file != null && file.exists() && !file.equals(currentFile) && reply == JOptionPane.NO_OPTION) { reply = JOptionPane.showConfirmDialog(null, file.getAbsoluteFile() + " already exists. Do you want to overwrite it?", "File already exists", JOptionPane.YES_NO_OPTION); if (reply != JOptionPane.YES_OPTION) { file = FileChooserService.getSelectedFile("tex", "TeX files", FileChooserService.DialogType.SAVE, true); } } return file; }
Source:
public static void main(String[] args) { String filename = null; try { filename = args[0]; if (args.length > 1) throw new Exception(); } catch (Exception e) { logger.error("usage: java edu.illinois.cs.cogcomp.lbjava.edu.illinois.cs.cogcomp.lbjava.nlp.WordSplitter <file name>"); System.exit(1); } WordSplitter splitter = new WordSplitter(new SentenceSplitter(filename)); for (LinkedVector s = (LinkedVector) splitter.next(); s != null; s = (LinkedVector) splitter.next()) { if (s.size() > 0) { Word w = (Word) s.get(0); logger.info(w.form); for (w = (Word) w.next; w != null; w = (Word) w.next) logger.info(" " + w.form); } logger.info("\n"); } }

Target:
public static void main(String[] args) { String filename = null; try { filename = args[0]; if (args.length > 1) throw new Exception(); } catch (Exception e) { System.err.println("usage: java edu.illinois.cs.cogcomp.lbjava.edu.illinois.cs.cogcomp.lbjava.nlp.WordSplitter <file name>"); System.exit(1); } WordSplitter splitter = new WordSplitter(new SentenceSplitter(filename)); for (LinkedVector s = (LinkedVector) splitter.next(); s != null; s = (LinkedVector) splitter.next()) { if (s.size() > 0) { Word w = (Word) s.get(0); System.out.print(w.form); for (w = (Word) w.next; w != null; w = (Word) w.next) System.out.print(" " + w.form); } System.out.println(); } }
Source:
protected void showChannelFilters() { List<RemoteRssChannel> feedLabels = new ArrayList<>(feeds.size() +1); feedLabels.add(new RemoteRssChannel() { @Override public String getName() { return "(All recent)"; } @Override public void writeToParcel(Parcel dest, int flags) { } }); feedLabels.addAll(feeds); drawerList.setAdapter(new SimpleListItemAdapter(this, feedLabels)); }

Target:
protected void showChannelFilters() { List<RemoteRssChannel> feedLabels = new ArrayList<>(feeds.size() +1); feedLabels.add(new RemoteRssChannel() { @Override public String getName() { return getString(R.string.remoterss_filter_allrecent); } @Override public void writeToParcel(Parcel dest, int flags) { } }); feedLabels.addAll(feeds); drawerList.setAdapter(new SimpleListItemAdapter(this, feedLabels)); }
Source:
public void testGetAccount() throws Exception { server.enqueue(jsonResponse("/account.json")); Account account = api.getAccountApi().getMyAccount(); assertNotNull(account); assertEquals("devlab1-online-vendor-devuser1", account.userName()); assertEquals("Donal Lunny", account.fullName()); assertEquals("Donal", account.firstName()); assertEquals("Lunny", account.lastName()); assertEquals("devlab1-online-vendor-devuser1@opsource.net", account.emailAddress()); assertThat(account.roles().contains(Account.RoleType.create("storage"))); assertThat(account.roles().contains(Account.RoleType.create("primary administrator"))); assertEquals("1", account.phone().countryCode()); assertEquals("1234567", account.phone().number()); assertEquals("Marketing", account.department()); assertEquals("custom defined 1", account.customDefined1()); assertEquals("custom defined 2", account.customDefined2()); assertEquals("6ac1e746-b1ea-4da5-a24e-caf1a978789d", account.organization().id()); assertEquals("Eng Customer of DevLab1-homed online sign-up Vendor", account.organization().name()); assertEquals("DevLab1Geo1", account.organization().homeGeoName()); assertEquals("apidevlab1.opsourcecloud.net", account.organization().homeGeoApiHost()); assertEquals("DEVLAB1GEO1", account.organization().homeGeoId()); assertEquals("NORMAL", account.state()); assertSent(server, "GET", "/caas/2.4/user/myUser"); }

Target:
public void testGetAccount() throws Exception { server.enqueue(jsonResponse("/account.json")); Account account = api.getAccountApi().getMyAccount(); assertNotNull(account); assertSent("GET", "/caas/2.4/user/myUser"); }
Source:
public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } return format("<%s>", getTypeSignature()).getBytes(); }

Target:
public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } Slice slice = block.getSlice(position, 0, block.getSliceLength(position)); return slice.getInput().readInt(); }
Source:
public String apply(String dimValue) { if (Strings.isNullOrEmpty(dimValue)) { return null; } int len = dimValue.length(); if (index < len) { if (length > 0) { return dimValue.substring(index, Math.min(end, len)); } else { return dimValue.substring(index); } } else { return null; } }

Target:
public String apply(String dimValue) { if (Strings.isNullOrEmpty(dimValue)) { return null; } int len = dimValue.length(); if (index < len) { if (end > 0) { return dimValue.substring(index, Math.min(end, len)); } else { return dimValue.substring(index); } } else { return null; } }
Source:
public Response processStats(BatchedOperatorStats batchedOperatorStats) { Response response = new Response(); int operatorId = batchedOperatorStats.getOperatorId(); long windowId = batchedOperatorStats.getCurrentWindowId(); currentWindowIds.put(operatorId, windowId); long minWindow = Long.MAX_VALUE; long maxWindow = Long.MIN_VALUE; for (Long value : currentWindowIds.values()) { if (value < minWindow) minWindow = value; if (value > maxWindow) maxWindow = value; } logger.debug("Operator min window max window {}", operatorId, minWindow, maxWindow); if (normalState && ((maxWindow - minWindow) > windowThreshold)) { logger.info("Setting suspend"); normalState = false; } else if (!normalState && ((maxWindow - minWindow) <= windowThreshold)) { logger.info("Setting normal"); normalState = true; } if (!normalState) { List<OperatorRequest> operatorRequests = new ArrayList<OperatorRequest>(); operatorRequests.add(new InputSlowdownRequest()); response.operatorRequests = operatorRequests; } else { List<OperatorRequest> operatorRequests = new ArrayList<OperatorRequest>(); operatorRequests.add(new InputNormalRequest()); response.operatorRequests = operatorRequests; } return response; }

Target:
public Response processStats(BatchedOperatorStats batchedOperatorStats) { Response response = new Response(); int operatorId = batchedOperatorStats.getOperatorId(); long windowId = batchedOperatorStats.getCurrentWindowId(); currentWindowIds.put(operatorId, windowId); long minWindow = Long.MAX_VALUE; long maxWindow = Long.MIN_VALUE; for (Long value : currentWindowIds.values()) { if (value < minWindow) minWindow = value; if (value > maxWindow) maxWindow = value; } logger.debug("Operator min window max window {}", operatorId, minWindow, maxWindow); if (normalState && ((maxWindow - minWindow) > maxThreshold)) { logger.info("Setting suspend"); normalState = false; } else if (!normalState && ((maxWindow - minWindow) <= minThreshold)) { logger.info("Setting normal"); normalState = true; } if (!normalState) { List<OperatorRequest> operatorRequests = new ArrayList<OperatorRequest>(); operatorRequests.add(new InputSlowdownRequest()); response.operatorRequests = operatorRequests; } else { List<OperatorRequest> operatorRequests = new ArrayList<OperatorRequest>(); operatorRequests.add(new InputNormalRequest()); response.operatorRequests = operatorRequests; } return response; }
Source:
public static void main(String[] args) { MessageCodeGenerator codeGenerator = new MessageCodeGenerator(); try { if (args.length != 3) { String classname = MessageCodeGenerator.class.getName(); System.err.println("usage: " + classname + " specDir xformDir outputBaseDir"); return; } boolean overwrite = getOption(OVERWRITE_OPTION, true); boolean orderedFields = getOption(ORDERED_FIELDS_OPTION, false); boolean useDecimal = getOption(BIGDECIMAL_TYPE_OPTION, false); long start = System.currentTimeMillis(); final String[] versions = { "FIXT 1.1", "FIX 5.0", "FIX 4.4", "FIX 4.3", "FIX 4.2", "FIX 4.1", "FIX 4.0" }; for (String ver : versions) { Task task = new Task(); task.setName(ver); final String version = ver.replaceAll("[ .]", ""); task.setSpecification(new File(args[0] + "/" + version + ".xml")); task.setTransformDirectory(new File(args[1])); task.setMessagePackage("quickfix." + version.toLowerCase()); task.setOutputBaseDirectory(new File(args[2])); task.setFieldPackage("quickfix.field"); task.setUtcTimestampPrecision(task.utcTimestampPrecision); task.setOverwrite(overwrite); task.setOrderedFields(orderedFields); task.setDecimalGenerated(useDecimal); codeGenerator.generate(task); } double duration = System.currentTimeMillis() - start; DecimalFormat durationFormat = new DecimalFormat("#.###"); codeGenerator.logInfo("Time for generation: " + durationFormat.format(duration / 1000L) + " seconds"); } catch (Exception e) { codeGenerator.logError("error during code generation", e); System.exit(1); } }

Target:
public static void main(String[] args) { MessageCodeGenerator codeGenerator = new MessageCodeGenerator(); try { if (args.length != 3) { String classname = MessageCodeGenerator.class.getName(); System.err.println("usage: " + classname + " specDir xformDir outputBaseDir"); return; } String utcTimestampPrecision = getOption(UTC_TIMESTAMP_PRECISION_OPTION, null); boolean overwrite = getOption(OVERWRITE_OPTION, true); boolean orderedFields = getOption(ORDERED_FIELDS_OPTION, false); boolean useDecimal = getOption(BIGDECIMAL_TYPE_OPTION, false); long start = System.currentTimeMillis(); final String[] versions = { "FIXT 1.1", "FIX 5.0", "FIX 4.4", "FIX 4.3", "FIX 4.2", "FIX 4.1", "FIX 4.0" }; for (String ver : versions) { Task task = new Task(); task.setName(ver); final String version = ver.replaceAll("[ .]", ""); task.setSpecification(new File(args[0] + "/" + version + ".xml")); task.setTransformDirectory(new File(args[1])); task.setMessagePackage("quickfix." + version.toLowerCase()); task.setOutputBaseDirectory(new File(args[2])); task.setFieldPackage("quickfix.field"); task.setUtcTimestampPrecision(utcTimestampPrecision); task.setOverwrite(overwrite); task.setOrderedFields(orderedFields); task.setDecimalGenerated(useDecimal); codeGenerator.generate(task); } double duration = System.currentTimeMillis() - start; DecimalFormat durationFormat = new DecimalFormat("#.###"); codeGenerator.logInfo("Time for generation: " + durationFormat.format(duration / 1000L) + " seconds"); } catch (Exception e) { codeGenerator.logError("error during code generation", e); System.exit(1); } }
Source:
public void deleteUser(TestUser testUser) { checkNotNull(testUser); if (testUser.getSession() != null) { String userId = testUser.getId(); authService.signOut(testUser.getSession()); deleteUser(testUser.getStudy(), userId); } }

Target:
public void deleteUser(TestUser testUser) { checkNotNull(testUser); String userId = testUser.getId(); if (testUser.getSession() != null) { authService.signOut(testUser.getSession()); } deleteUser(testUser.getStudy(), userId); }
Source:
synchronized void processResponse(TrieNodeRequest req) { dbWriteQueue.add(req); knownHashes.remove(req.nodeHash); nodesInserted++; for (TrieNodeRequest childRequest : req.createChildRequests()) { if (nodesQueue.size() > NODE_QUEUE_BEST_SIZE) { nodesQueue.addFirst(childRequest); } else { nodesQueue.add(childRequest); } knownHashes.add(childRequest.nodeHash); } }

Target:
synchronized void processResponse(TrieNodeRequest req) { dbWriteQueue.add(req); for (TrieNodeRequest childRequest : req.createChildRequests()) { if (nodesQueue.size() > NODE_QUEUE_BEST_SIZE) { nodesQueue.addFirst(childRequest); } else { nodesQueue.add(childRequest); } } }
Source:
public void shouldRecordOnlyFirstErrorBeforeGetOnFailedCompletion() throws Exception { final Throwable expectedError = new Throwable(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); testCallback.onCompletion(expectedError, null); testCallback.onCompletion(new RuntimeException(), null); testCallback.cancel(true); testCallback.onCompletion(null, "420"); assertEquals(0, testCallback.numberOfConversions()); try { testCallback.get(); } catch (ExecutionException e) { assertEquals(expectedError, e.getCause()); } }

Target:
public void shouldRecordOnlyFirstErrorBeforeGetOnFailedCompletion() throws Exception { final Throwable expectedError = new Throwable(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); testCallback.onCompletion(expectedError, null); testCallback.onCompletion(new RuntimeException(), null); testCallback.cancel(true); testCallback.onCompletion(null, "420"); assertEquals(0, testCallback.numberOfConversions()); try { testCallback.get(); fail("Expected ExecutionException"); } catch (ExecutionException e) { assertEquals(expectedError, e.getCause()); } }
Source:
public boolean setPoint(EntityPlayer player, WorldCoordinate coord) { if (!isTargetLoaded(player, coord, getLocalizationTag())) { return false; } IBlockState state = WorldPlugin.getBlockState(worldObj, coord.getPos()); if (RailcraftBlocks.WORLDSPIKE_POINT.isEqual(state)) { int xChunk = getPos().getX() >> 4; int zChunk = getPos().getZ() >> 4; int xPointChunk = coord.getX() >> 4; int zPointChunk = coord.getZ() >> 4; if (xChunk != xPointChunk && zChunk != zPointChunk) { ChatPlugin.sendLocalizedChatFromServer(player, "gui.railcraft.worldspike.pair.fail.alignment", getLocalizationTag(), state.getBlock().getUnlocalizedName()); return false; } int max = getMaxPointChunks(); if (Math.abs(xChunk - xPointChunk) >= max || Math.abs(zChunk - zPointChunk) >= max) { ChatPlugin.sendLocalizedChatFromServer(player, "gui.railcraft.worldspike.pair.fail.distance", getLocalizationTag(), state.getBlock().getUnlocalizedName()); return false; } pointPos = coord.getPos(); requestTicket(); sendUpdateToClient(); removeTarget(player); ChatPlugin.sendLocalizedChatFromServer(player, "gui.railcraft.worldspike.pair.success", getLocalizationTag()); return true; } ChatPlugin.sendLocalizedChatFromServer(player, "gui.railcraft.worldspike.pair.fail.invalid", getLocalizationTag()); return false; }

Target:
public boolean setPoint(EntityPlayer player, WorldCoordinate coord) { if (!isTargetLoaded(player, coord, getLocalizationTag())) { return false; } IBlockState state = WorldPlugin.getBlockState(worldObj, coord.getPos()); if (RailcraftBlocks.WORLDSPIKE_POINT.isEqual(state)) { int xChunk = getPos().getX() >> 4; int zChunk = getPos().getZ() >> 4; int xPointChunk = coord.getX() >> 4; int zPointChunk = coord.getZ() >> 4; if (xChunk != xPointChunk && zChunk != zPointChunk) { ChatPlugin.sendLocalizedChatFromServer(player, "gui.railcraft.worldspike.pair.fail.alignment", getLocalizationTag(), state.getBlock().getLocalizedName()); return false; } int max = getMaxPointChunks(); if (Math.abs(xChunk - xPointChunk) >= max || Math.abs(zChunk - zPointChunk) >= max) { ChatPlugin.sendLocalizedChatFromServer(player, "gui.railcraft.worldspike.pair.fail.distance", getLocalizationTag(), state.getBlock().getLocalizedName()); return false; } pointPos = coord.getPos(); requestTicket(); sendUpdateToClient(); removeTarget(player); ChatPlugin.sendLocalizedChatFromServer(player, "gui.railcraft.worldspike.pair.success", getLocalizationTag()); return true; } ChatPlugin.sendLocalizedChatFromServer(player, "gui.railcraft.worldspike.pair.fail.invalid", getLocalizationTag()); return false; }
Source:
public void handle(Willie bot, Command cmd, CommandType type, Channel channel, User sender, String[] args) { ConfigurationBuilder cb = new ConfigurationBuilder(); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { Trends trend = twitter.getPlaceTrends(1); StringBuilder sb = new StringBuilder(); int trendsToShow = 5; int trendsToShowLeft = 5; for (Trend t : trend.getTrends()) { if (trendsToShow > 0) { trendsToShowLeft--; if (trendsToShowLeft == 0) { sb.append(t.getName()); } else { sb.append(t.getName() + ", "); } } else { bot.send("This command has been configured incorrectly! No trends have been set to be displayed.", channel, sender, CommandType.NOTICE_SENDER); } } if (trendsToShow > 1) { bot.send("Top " + trendsToShow + " Trends on Twitter right now: " + sb.toString(), channel, sender, CommandType.SEND_CHANNEL); } else { bot.send("The top Trend on Twitter right now is " + sb.toString(), channel, sender, CommandType.SEND_CHANNEL); } } catch (TwitterException e) { bot.send("TwitterException occured while executing this command!", channel, sender, CommandType.SEND_CHANNEL); e.printStackTrace(); } }

Target:
public void handle(Willie bot, Command cmd, CommandType type, Channel channel, User sender, String[] args) { ConfigurationBuilder cb = new ConfigurationBuilder(); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { Trends trend = twitter.getPlaceTrends(1); StringBuilder sb = new StringBuilder(); int trendsToShow = 5; int trendsToShowLeft = 5; for (Trend t : trend.getTrends()) { if (trendsToShow > 0) { trendsToShowLeft--; if (trendsToShowLeft == 0) { sb.append(t.getName()); } else { sb.append(t.getName() + ", "); } } else { bot.send("This command has been configured incorrectly! No trends have been set to be displayed.", channel, sender, type); } } if (trendsToShow > 1) { bot.send("Top " + trendsToShow + " Trends on Twitter right now: " + sb.toString(), channel, sender, type); } else { bot.send("The top Trend on Twitter right now is " + sb.toString(), channel, sender, type); } } catch (TwitterException e) { bot.send("TwitterException occured while executing this command!", channel, sender, type); e.printStackTrace(); } }
Source:
public static Predicate<AbstractProject> isBuildable() { return new Predicate<AbstractProject>() { public boolean apply(AbstractProject job) { return job.isBuildable(); } }; }

Target:
public static Predicate<Job> isBuildable() { return new Predicate<Job>() { public boolean apply(Job job) { return job.isBuildable(); } }; }
Source:
public void testFailure_unableToPullFile() throws DeviceNotAvailableException { doReturn(NATIVE_COVERAGE_DEVICE_PATH + "/some/path/to/coverage.gcda\n") .when(mMockDevice) .executeShellCommand(anyString()); doReturn(false).when(mMockDevice).pullFile(anyString(), any()); mCodeCoverageListener.testRunStarted(RUN_NAME, TEST_COUNT); try { Map<String, String> metric = new HashMap<>(); mCodeCoverageListener.testRunEnded( ELAPSED_TIME, TfMetricProtoUtil.upgradeConvert(metric)); fail("Exception not thrown"); } catch (VerifyException expected) { } verify(mFakeListener, never()) .testLog(anyString(), eq(LogDataType.COVERAGE), any(InputStreamSource.class)); }

Target:
public void testFailure_unableToPullFile() throws DeviceNotAvailableException { doReturn("/data/misc/gcov/some/path/to/coverage.gcda\n") .when(mMockDevice) .executeShellCommand(anyString()); doReturn(false).when(mMockDevice).pullFile(anyString(), any()); mCodeCoverageListener.testRunStarted(RUN_NAME, TEST_COUNT); Map<String, String> metric = new HashMap<>(); assertThrows( VerifyException.class, () -> mCodeCoverageListener.testRunEnded( ELAPSED_TIME, TfMetricProtoUtil.upgradeConvert(metric))); assertThat(mFakeListener.getLogs()).isEmpty(); }
Source:
public void refuseBalloonOnPPC() { final ImportVmCommand<ImportVmParameters> c = setupDiskSpaceTest(0); c.getParameters().getVm().setBalloonEnabled(true); c.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); VDSGroup cluster = new VDSGroup(); cluster.setArchitecture(ArchitectureType.ppc64); cluster.setcompatibility_version(Version.getLast()); doReturn(cluster).when(c).getVdsGroup(); when(osRepository.isBalloonEnabled(c.getParameters().getVm().getVmOsId(), cluster.getcompatibility_version())).thenReturn(false); assertFalse(c.canDoAction()); assertTrue(c.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH.toString())); }

Target:
public void refuseBalloonOnPPC() { final ImportVmCommand<ImportVmParameters> c = setupDiskSpaceTest(createParameters()); c.getParameters().getVm().setBalloonEnabled(true); c.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); VDSGroup cluster = new VDSGroup(); cluster.setArchitecture(ArchitectureType.ppc64); cluster.setcompatibility_version(Version.getLast()); doReturn(cluster).when(c).getVdsGroup(); when(osRepository.isBalloonEnabled(c.getParameters().getVm().getVmOsId(), cluster.getcompatibility_version())).thenReturn(false); assertFalse(c.canDoAction()); assertTrue(c.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH.toString())); }
Source:
private boolean isWrapperFunction(AstNode node) { if (!node.is(PythonGrammar.FUNCDEF) || node.equals(currentFunction)) { return false; } AstNode parentStatement = node.getParent().getParent(); List<AstNode> ancestorStatements = node.getFirstAncestor(PythonGrammar.FUNCDEF) .getFirstChild(PythonGrammar.SUITE) .getChildren(PythonGrammar.STATEMENT); return ancestorStatements.stream() .filter(statement -> statement != parentStatement) .filter(statement -> !isSimpleReturn(statement)) .count() == 0; }

Target:
private boolean isWrapperFunction(AstNode node) { if (!node.is(PythonGrammar.FUNCDEF) || node.equals(currentFunction)) { return false; } AstNode parentStatement = node.getParent().getParent(); List<AstNode> ancestorStatements = node.getFirstAncestor(PythonGrammar.FUNCDEF) .getFirstChild(PythonGrammar.SUITE) .getChildren(PythonGrammar.STATEMENT); return ancestorStatements.stream() .filter(statement -> statement != parentStatement) .allMatch(CognitiveComplexityFunctionCheck::isSimpleReturn); }