auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void refreshGroup(GroupInfo info) { Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { ((IJobProgressManagerListener)element).refreshGroup(info); } }

Target:
public void refreshGroup(GroupInfo info) { for (Object element : listeners.getListeners()) { ((IJobProgressManagerListener)element).refreshGroup(info); } }
Source:
public <T extends StreamOperator<OUT>> T createStreamOperator(StreamOperatorParameters<OUT> parameters) { final OperatorID operatorId = parameters.getStreamConfig().getOperatorID(); final OperatorEventGateway gateway = parameters.getOperatorEventDispatcher().getOperatorEventGateway(operatorId); final SourceOperator<OUT, ?> sourceOperator = instantiateSourceOperator( source::createReader, gateway, source.getSplitSerializer(), eventTimeConfig); sourceOperator.setup(parameters.getContainingTask(), parameters.getStreamConfig(), parameters.getOutput()); sourceOperator.processingTimeService = parameters.getProcessingTimeService(); parameters.getOperatorEventDispatcher().registerEventHandler(operatorId, sourceOperator); @SuppressWarnings("unchecked") final T castedOperator = (T) sourceOperator; return castedOperator; }

Target:
public <T extends StreamOperator<OUT>> T createStreamOperator(StreamOperatorParameters<OUT> parameters) { final OperatorID operatorId = parameters.getStreamConfig().getOperatorID(); final OperatorEventGateway gateway = parameters.getOperatorEventDispatcher().getOperatorEventGateway(operatorId); final SourceOperator<OUT, ?> sourceOperator = instantiateSourceOperator( source::createReader, gateway, source.getSplitSerializer(), watermarkStrategy, parameters.getProcessingTimeService()); sourceOperator.setup(parameters.getContainingTask(), parameters.getStreamConfig(), parameters.getOutput()); parameters.getOperatorEventDispatcher().registerEventHandler(operatorId, sourceOperator); @SuppressWarnings("unchecked") final T castedOperator = (T) sourceOperator; return castedOperator; }
Source:
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, EurekaInstanceConfig instance, @Autowired(required = false) HealthCheckHandler healthCheckHandler) { ApplicationInfoManager appManager; if(AopUtils.isAopProxy(manager)) { appManager = ProxyUtils.getTargetObject(manager); } else { appManager = manager; } appManager.getInfo(); CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, config, this.optionalArgs, this.context); cloudEurekaClient.registerHealthCheck(healthCheckHandler); return cloudEurekaClient; }

Target:
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, EurekaInstanceConfig instance, @Autowired(required = false) HealthCheckHandler healthCheckHandler) { ApplicationInfoManager appManager; if(AopUtils.isAopProxy(manager)) { appManager = ProxyUtils.getTargetObject(manager); } else { appManager = manager; } CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, config, this.optionalArgs, this.context); cloudEurekaClient.registerHealthCheck(healthCheckHandler); return cloudEurekaClient; }
Source:
public static Collection<Thread> findThreadsByName(final String threadName, final String threadGroupName) { if (threadName == null) { throw new IllegalArgumentException("The thread name must not be null"); } if (threadGroupName == null) { throw new IllegalArgumentException("The thread group name must not be null"); } final Collection<Thread> result = new ArrayList<Thread>(); for(final ThreadGroup group : findThreadGroups(new NamePredicate(threadGroupName))) { result.addAll(findThreads(group, false, new NamePredicate(threadName))); } return Collections.unmodifiableCollection(result); }

Target:
public static Collection<Thread> findThreadsByName(final String threadName, final String threadGroupName) { if (threadName == null) { throw new IllegalArgumentException("The thread name must not be null"); } if (threadGroupName == null) { throw new IllegalArgumentException("The thread group name must not be null"); } final Collection<ThreadGroup> threadGroups = findThreadGroups(new NamePredicate(threadGroupName)); if(threadGroups.isEmpty()) { return Collections.EMPTY_LIST; } final Collection<Thread> result = new ArrayList<Thread>(); final NamePredicate threadNamePredicate = new NamePredicate(threadName); for(final ThreadGroup group : threadGroups) { result.addAll(findThreads(group, false, threadNamePredicate)); } return Collections.unmodifiableCollection(result); }
Source:
default Token refreshToken(String refreshUrl, Token token, HttpClient client, TokenDAO tokenDAO, String clientID, String clientSecret, String payload) { try { Optional<String> asString = ResourceUtilities.refreshPost(refreshUrl, null, client, clientID, clientSecret, payload); if (asString.isPresent()) { String accessToken; String refreshToken; LOG.info(token.getUsername() + ": RESOURCE CALL: {}", refreshUrl); String json = asString.get(); Gson gson = new Gson(); Map<String, String> map = new HashMap<>(); map = (Map<String, String>)gson.fromJson(json, map.getClass()); accessToken = map.get("access_token"); refreshToken = map.get("refresh_token"); token.setContent(accessToken); token.setRefreshToken(refreshToken); long create = tokenDAO.create(token); return tokenDAO.findById(create); } else { throw new CustomWebApplicationException("Could not retrieve " + refreshUrl + " token based on code", HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (UnsupportedEncodingException ex) { LOG.info(token.getUsername() + ": " + ex.toString()); throw new CustomWebApplicationException(ex.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } }

Target:
default Token refreshToken(String refreshUrl, Token token, HttpClient client, TokenDAO tokenDAO, String clientID, String clientSecret, String payload) { try { Optional<String> asString = ResourceUtilities.refreshPost(refreshUrl, null, client, clientID, clientSecret, payload); if (asString.isPresent()) { String accessToken; String refreshToken; LOG.info(token.getUsername() + ": RESOURCE CALL: {}", refreshUrl); String json = asString.get(); Gson gson = new Gson(); Map<String, String> map = new HashMap<>(); map = (Map<String, String>)gson.fromJson(json, map.getClass()); accessToken = map.get("access_token"); refreshToken = map.get("refresh_token"); token.setContent(accessToken); token.setRefreshToken(refreshToken); long create = tokenDAO.create(token); return tokenDAO.findById(create); } else { String domain; try { URI uri = new URI(refreshUrl); domain = uri.getHost(); } catch (URISyntaxException e) { domain = "web site"; } throw new CustomWebApplicationException("Could not retrieve " + domain + " token based on code", HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (UnsupportedEncodingException ex) { LOG.info(token.getUsername() + ": " + ex.toString()); throw new CustomWebApplicationException(ex.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
Source:
private int getGivenRecipientIndex(int questionNum, String recipient) { List<WebElement> recipients = getQuestionResponsesSection(questionNum) .findElements(By.cssSelector("#given-responses #response-recipient")); for (int i = 0; i < recipients.size(); i++) { if (recipients.get(i).getText().split("To: ")[1].equals(recipient)) { return i; } } throw new RuntimeException("Recipient not found: " + recipient); }

Target:
private int getGivenRecipientIndex(int questionNum, String recipient) { List<WebElement> recipients = getQuestionResponsesSection(questionNum) .findElements(By.cssSelector("#given-responses #response-recipient")); for (int i = 0; i < recipients.size(); i++) { if (recipients.get(i).getText().split("To: ")[1].equals(recipient)) { return i; } } throw new AssertionError("Recipient not found: " + recipient); }
Source:
private boolean checkIfCollapsed() { boolean result = false; if (titleAnchor != null) { String styleString = titleAnchor.getStyleName(); if (styleString != null) { String[] styles = styleString.split(" "); for (String style: styles) { if (style.equals(PatternflyConstants.COLLAPSED)) { result = true; break; } } } } else { result = startCollapsed; } return result; }

Target:
private boolean checkIfCollapsed() { boolean result = false; if (titleAnchor != null) { String styleString = titleAnchor.getStyleName(); if (styleString != null) { String[] styles = styleString.split(" "); Optional<String> found = Arrays.asList(styles).stream().filter( s -> s.equals(PatternflyConstants.COLLAPSED)).findFirst(); result = found.isPresent(); } } else { result = startCollapsed; } return result; }
Source:
HistogramMetricImpl histogram(String srvcName, Method mtd) { MethodHistogramHolder histogramHolder = Optional.ofNullable(invocationHistograms.get(srvcName)) .orElse(Collections.emptyMap()).get(mtd.getName()); return histogramHolder == null ? null : histogramHolder.getHistogram(mtd); }

Target:
HistogramMetricImpl histogram(String srvcName, Method mtd) { Map<String, HistogramHolder> srvHistograms = invocationHistograms.get(srvcName); if (srvHistograms == null) return null; HistogramHolder holder = srvHistograms.get(mtd.getName()); return holder == null ? null : holder.histogram(mtd); }
Source:
public void a_message_is_shown_under_the_field(String msg, String field) throws Throwable { String nameOrPhoneErrorSelector = ".list-unstyled > li:nth-child(1)"; String phoneErrorSelector = "#phoneDiv > div > div > ul > li:nth-child(1)"; WebDriverWait webDriverWait = new WebDriverWait(getDriver(), TIMEOUT); if (field.equals("phone")) { assertTrue(webDriverWait.until(textToBe(By.cssSelector(phoneErrorSelector), msg))); } else { assertTrue(webDriverWait.until(textToBe(By.cssSelector(nameOrPhoneErrorSelector), msg))); } }

Target:
public void a_message_is_shown_under_the_field(String msg, String field) { WebDriverWait webDriverWait = new WebDriverWait(getDriver(), TIMEOUT); switch (field) { case "name": assertTrue(webDriverWait.until( textToBe(By.cssSelector("#" + NAME_ERRORS_DIV_ID + FIRST_CHILD_OF_UNORDERED_LIST), msg))); break; case "email": assertTrue(webDriverWait.until( textToBe(By.cssSelector("#" + EMAIL_ERRORS_DIV_ID + FIRST_CHILD_OF_UNORDERED_LIST), msg))); break; case "phone": assertTrue(webDriverWait.until( textToBe(By.cssSelector("#" + PHONE_ERRORS_DIV_ID + FIRST_CHILD_OF_UNORDERED_LIST), msg))); break; } }
Source:
protected Network getNetworkFromDb(Guid vdsGroupId) { List<Network> networks = getNetworkDAO().getAllForCluster(vdsGroupId); for (Network network : networks) { if (network.getName().equals(getNetworkName())) { return network; } } return null; }

Target:
protected Network getNetworkFromDb(Guid vdsGroupId) { for (Network network : getNetworkDAO().getAllForCluster(vdsGroupId)) { if (network.getName().equals(getNetworkName())) { return network; } } return null; }
Source:
private void decodeRowType2() throws IOException { if(optionByteAligned) resetBuffer(); decode1D(); }

Target:
private void decodeRowType2() throws IOException { if (optionByteAligned) { resetBuffer(); } decode1D(); }
Source:
public String toString() { return "Capabilities{" + "poolName='" + poolName + '\'' + ", qosSupport='" + qosSupport + '\'' + ", allocatedCapacityGb='" + allocatedCapacityGb + '\'' + ", driverVersion='" + driverVersion + '\'' + ", freeCapacityGb='" + freeCapacityGb + '\'' + ", locationInfo='" + locationInfo + '\'' + ", timestamp='" + timestamp + '\'' + ", volumeBackendName='" + volumeBackendName + '\'' + ", totalCapacityGb='" + totalCapacityGb + '\'' + ", reservedPercentage='" + reservedPercentage + '\'' + ", vendorName='" + vendorName + '\'' + ", storageProtocol='" + storageProtocol + '\'' + ", extraSpecs='" + extraSpecs + '\'' + '}'; }

Target:
public String toString() { return "Capabilities{" + "poolName='" + poolName + ", qosSupport='" + qosSupport + ", allocatedCapacityGb='" + allocatedCapacityGb + ", driverVersion='" + driverVersion + ", freeCapacityGb='" + freeCapacityGb + ", locationInfo='" + locationInfo + ", timestamp='" + timestamp + ", volumeBackendName='" + volumeBackendName + ", totalCapacityGb='" + totalCapacityGb + ", reservedPercentage='" + reservedPercentage + ", vendorName='" + vendorName + ", storageProtocol='" + storageProtocol + ", extraSpecs='" + extraSpecs + '}'; }
Source:
private void applyTransformations(GLTF gltf, TFloatList vertices, TFloatList normals) { GLTFNode node = null; for(GLTFNode curr : gltf.getNodes()) { if(curr.getMesh() == 0) { node = curr; break; } } Matrix4f transform = new Matrix4f(Matrix4f.IDENTITY); if(node != null) { if (node.getMatrix() == null) { Vector3f position = new Vector3f(); Quat4f rotation = new Quat4f(Quat4f.IDENTITY); Vector3f scale = new Vector3f(Vector3f.one()); if (node.getTranslation() != null) { position.set(node.getTranslation()); } if (node.getRotation() != null) { rotation.set(node.getRotation()); } if (node.getScale() != null) { scale.set(node.getScale()); } transform.set(new Matrix4f(rotation, position, 1.0f)); transform.set(0, 0, scale.getX()*transform.get(0, 0)); transform.set(0, 1, scale.getX()*transform.get(0, 1)); transform.set(0, 2, scale.getX()*transform.get(0, 2)); transform.set(1, 0, scale.getY()*transform.get(1, 0)); transform.set(1, 1, scale.getY()*transform.get(1, 1)); transform.set(1, 2, scale.getY()*transform.get(1, 2)); transform.set(2, 0, scale.getZ()*transform.get(2, 0)); transform.set(2, 1, scale.getZ()*transform.get(2, 1)); transform.set(2, 2, scale.getZ()*transform.get(2, 2)); } else { transform.set(node.getMatrix()); } } applyTransformations(vertices, transform, false); transform.setTranslation(new Vector3f()); applyTransformations(normals, transform, true); }

Target:
private void applyTransformations(GLTF gltf, TFloatList vertices, TFloatList normals) { int nodeIndex = -1; for (int i = 0; i < gltf.getNodes().size(); i++) { if (gltf.getNodes().get(i).getMesh() == 0) { nodeIndex = i; break; } } Matrix4f transform = getMatrix(gltf, nodeIndex); applyTransformations(vertices, transform, false); transform.setTranslation(new Vector3f()); applyTransformations(normals, transform, true); }
Source:
public boolean accept(File dir, String name) { return name.contains(baseLogfile) || name.matches(logPattern); }

Target:
public boolean accept(File dir, String name) { return name.contains(baseLogFile) || logPattern.matcher(name).matches(); }
Source:
public CompletionStage<Void> setAvailabilityMode(AvailabilityMode availabilityMode) { if (availabilityMode != this.availabilityMode) { if (notifier.hasListener(PartitionStatusChanged.class)) { return notifier.notifyPartitionStatusChanged(availabilityMode, true) .thenCompose(ignore -> { updateAvailabilityMode(availabilityMode); return notifier.notifyPartitionStatusChanged(availabilityMode, false); }); } else { return updateAvailabilityMode(availabilityMode); } } else { return CompletableFutures.completedNull(); } }

Target:
public CompletionStage<Void> setAvailabilityMode(AvailabilityMode availabilityMode) { if (availabilityMode != this.availabilityMode) { return notifier.notifyPartitionStatusChanged(availabilityMode, true) .thenCompose(ignore -> { updateAvailabilityMode(availabilityMode); return notifier.notifyPartitionStatusChanged(availabilityMode, false); }); } else { return CompletableFutures.completedNull(); } }
Source:
private Transactional getTransactionalAnnotationRecursive(Annotation... annotationsOnMember) { if(annotationsOnMember == null) return null; Class<? extends Annotation> stereotypeAnnotation = null; for(Annotation annotation: annotationsOnMember) { if(annotation.annotationType().equals(Transactional.class)) { return (Transactional) annotation; } if (beanManager.isStereotype(annotation.annotationType())) { stereotypeAnnotation = annotation.annotationType(); } } if(stereotypeAnnotation != null) { return getTransactionalAnnotationRecursive(stereotypeAnnotation.getAnnotations()); } return null; }

Target:
private Transactional getTransactionalAnnotationRecursive(Annotation... annotationsOnMember) { if(annotationsOnMember == null) return null; Set<Class<? extends Annotation>> stereotypeAnnotations = new HashSet<>(); for(Annotation annotation: annotationsOnMember) { if(annotation.annotationType().equals(Transactional.class)) { return (Transactional) annotation; } if (beanManager.isStereotype(annotation.annotationType())) { stereotypeAnnotations.add(annotation.annotationType()); } } for(Class<? extends Annotation> stereotypeAnnotation: stereotypeAnnotations) { return getTransactionalAnnotationRecursive(beanManager.getStereotypeDefinition(stereotypeAnnotation)); } return null; }
Source:
private List<Partition> batchGetPartitions(AWSGlueAsync glueClient, String tableName) throws IOException { List<Partition> partitions = new ArrayList<>(); String nextToken = null; try { do { GetPartitionsRequest getPartitionsRequest = new GetPartitionsRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withDatabaseName(mGlueDbName) .withTableName(tableName) .withMaxResults(mGlueConfiguration.getInt(Property.MAX_GLUE_FETCH_PARTITIONS)) .withNextToken(nextToken); GetPartitionsResult getPartitionsResult = glueClient.getPartitions(getPartitionsRequest); getPartitionsResult.getPartitions().forEach(partition -> partitions.add(partition)); nextToken = getPartitionsResult.getNextToken(); LOG.debug("Glue table {}.{} added partitions.", mGlueDbName, tableName, partitions.size()); } while (nextToken != null); if (partitions != null) { LOG.info("Glue table {}.{} has partitions.", mGlueDbName, tableName, partitions.size()); if (LOG.isDebugEnabled()) { partitions.stream().forEach(partition -> LOG.debug("Glue table {}.{} with partition: {}.", partition.getDatabaseName(), tableName, partition.toString())); } } return partitions; } catch (AWSGlueException e) { throw new IOException("Cannot get partition information for table: " + tableName + " in Database: " + mGlueDbName + "; Catalog ID: " + mGlueConfiguration.get(Property.CATALOG_ID) + ". error: " + e.getMessage(), e); } }

Target:
private List<Partition> batchGetPartitions(AWSGlueAsync glueClient, String tableName) throws IOException { List<Partition> partitions = new ArrayList<>(); String nextToken = null; try { do { GetPartitionsRequest getPartitionsRequest = new GetPartitionsRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withDatabaseName(mGlueDbName) .withTableName(tableName) .withMaxResults(mGlueConfiguration.getInt(Property.MAX_GLUE_FETCH_PARTITIONS)) .withNextToken(nextToken); GetPartitionsResult getPartitionsResult = glueClient.getPartitions(getPartitionsRequest); partitions.addAll(getPartitionsResult.getPartitions()); nextToken = getPartitionsResult.getNextToken(); LOG.debug("Glue table {}.{} adding batch partitions with total partitions.", mGlueDbName, tableName, getPartitionsResult.getPartitions().size(), partitions.size()); } while (nextToken != null); if (partitions != null) { LOG.info("Glue table {}.{} has partitions.", mGlueDbName, tableName, partitions.size()); if (LOG.isDebugEnabled()) { partitions.stream().forEach(partition -> LOG.debug("Glue table {}.{} with partition: {}.", partition.getDatabaseName(), tableName, partition.toString())); } } return partitions; } catch (AWSGlueException e) { throw new IOException("Cannot get partition information for table: " + tableName + " in Database: " + mGlueDbName + "; Catalog ID: " + mGlueConfiguration.get(Property.CATALOG_ID) + ". error: " + e.getMessage(), e); } }
Source:
private static boolean isReturnValueUsed(CallExpressionTree tree) { Tree parent = ((JavaScriptTree) tree).getParent(); if (parent.is(CONDITIONAL_OR, CONDITIONAL_AND)) { return ((BinaryExpressionTree) parent).leftOperand().equals(tree); } if (parent.is(CONDITIONAL_EXPRESSION)) { return ((ConditionalExpressionTree) parent).condition().equals(tree); } return !parent.is(Kind.EXPRESSION_STATEMENT); }

Target:
private static boolean isReturnValueUsed(CallExpressionTree tree) { Tree parent = getParentIgnoreParenthesis(tree); if (parent.is(CONDITIONAL_OR, CONDITIONAL_AND)) { return ((BinaryExpressionTree) parent).leftOperand().equals(tree); } if (parent.is(CONDITIONAL_EXPRESSION)) { return ((ConditionalExpressionTree) parent).condition().equals(tree); } return !parent.is(Kind.EXPRESSION_STATEMENT); }
Source:
public boolean accept(File dir, String name) { if (new Date().getTime() - dir.lastModified() < MAX_TIME_AGENT_LOG_RETRIEVAL) { return name.endsWith(".log"); } return false; }

Target:
public boolean accept(File dir, String name) { if (name.endsWith(".log") && new Date().getTime() - dir.lastModified() < MAX_TIME_AGENT_LOG_RETRIEVAL) { return true; } return false; }
Source:
public void onRestoreInstanceState(Bundle savedInstanceStateBundle) { if (mHasStableIds) { if (savedInstanceStateBundle == null) { return; } if (!savedInstanceStateBundle.containsKey(STABLE_ID_MAP)) { return; } mStableIdMap = (HashMap<Long, Boolean>) savedInstanceStateBundle.getSerializable(STABLE_ID_MAP); Log.d(TAG, mStableIdMap.toString()); int i = 0; while (i < mItemList.size()) { if (mItemList.get(i) instanceof ParentObject) { ParentObject parentObject = (ParentObject) mItemList.get(i); if (mStableIdMap.containsKey(parentObject.getStableId())) { parentObject.setExpanded(mStableIdMap.get(parentObject.getStableId())); if (parentObject.isExpanded()) { i++; mItemList.add(i, parentObject.getChildObject()); } } else { parentObject.setExpanded(false); } } i++; } notifyDataSetChanged(); } }

Target:
public void onRestoreInstanceState(Bundle savedInstanceStateBundle) { if (!mHasStableIds) { return; } if (savedInstanceStateBundle == null) { return; } if (!savedInstanceStateBundle.containsKey(STABLE_ID_MAP)) { return; } mStableIdMap = (HashMap<Long, Boolean>) savedInstanceStateBundle.getSerializable(STABLE_ID_MAP); Log.d(TAG, mStableIdMap.toString()); int i = 0; while (i < mItemList.size()) { if (mItemList.get(i) instanceof ParentObject) { ParentObject parentObject = (ParentObject) mItemList.get(i); if (mStableIdMap.containsKey(parentObject.getStableId())) { parentObject.setExpanded(mStableIdMap.get(parentObject.getStableId())); if (parentObject.isExpanded()) { i++; mItemList.add(i, parentObject.getChildObject()); } } else { parentObject.setExpanded(false); } } i++; } notifyDataSetChanged(); }
Source:
public void transform(StructuredRecord in, Emitter<StructuredRecord> emitter) throws Exception { List<Schema.Field> fields = in.getSchema().getFields(); String[] records = String.valueOf(in.get(config.fieldToSplit)).split(config.delimiter); for (String record : records) { StructuredRecord.Builder builder = StructuredRecord.builder(outSchema); for (Schema.Field field : fields) { String name = field.getName(); if (outSchema.getField(name) != null && !name.equals(config.fieldToSplit)) { builder.set(name, in.get(name)); } } builder.set(config.outputField, record.trim()); emitter.emit(builder.build()); } }

Target:
public void transform(StructuredRecord in, Emitter<StructuredRecord> emitter) throws Exception { List<Schema.Field> fields = in.getSchema().getFields(); Object valueToSplit = in.get(config.fieldToSplit); if (valueToSplit != null) { String[] records = String.valueOf(valueToSplit).split(config.delimiter); for (String record : records) { StructuredRecord.Builder builder = StructuredRecord.builder(outSchema); for (Schema.Field field : fields) { String name = field.getName(); if (outSchema.getField(name) != null && !name.equals(config.fieldToSplit)) { builder.set(name, in.get(name)); } } builder.set(config.outputField, record.trim()); emitter.emit(builder.build()); } } }
Source:
public void setUpSessionDataContainer() { MockitoAnnotations.initMocks(this); if (Config.getConfigUtils() == null) { Config.setConfigUtils(mock(IConfigUtilsInterface.class)); } when(Config.getConfigUtils().getValue(ConfigValues.CoCoCommandLifeInMinutes, ConfigCommon.defaultConfigurationVersion)).thenReturn(300); }

Target:
public void setUpSessionDataContainer() { MockitoAnnotations.initMocks(this); }
Source:
private void initializeAnnouncer() { if (announcer == null) { final Announcer announcer = new Announcer(getCuratorFramework(), Execs.singleThreaded("Announcer-%s")); lifecycle.addManagedInstance(announcer); final ZkDataSegmentAnnouncerConfig config = getConfigFactory().build(ZkDataSegmentAnnouncerConfig.class); final String announcerType = config.getAnnouncerType(); final DataSegmentAnnouncer dataSegmentAnnouncer; if ("curator".equalsIgnoreCase(announcerType)) { dataSegmentAnnouncer = new CuratorDataSegmentAnnouncer( getDruidServerMetadata(), getZkPaths(), announcer, getJsonMapper() ); } else if ("batch".equalsIgnoreCase(announcerType)) { dataSegmentAnnouncer = new BatchingCuratorDataSegmentAnnouncer( getDruidServerMetadata(), config, announcer, getJsonMapper() ); } else if ("multiple".equalsIgnoreCase(announcerType)) { dataSegmentAnnouncer = new MultipleDataSegmentAnnouncerDataSegmentAnnouncer( Arrays.<AbstractDataSegmentAnnouncer>asList( new BatchingCuratorDataSegmentAnnouncer( getDruidServerMetadata(), config, announcer, getJsonMapper() ), new CuratorDataSegmentAnnouncer( getDruidServerMetadata(), getZkPaths(), announcer, getJsonMapper() ) ) ); } else { throw new ISE("Unknown announcer type [%s]", announcerType); } setAnnouncer(dataSegmentAnnouncer); lifecycle.addManagedInstance(getAnnouncer(), Lifecycle.Stage.LAST); } }

Target:
private void initializeAnnouncer() { if (announcer == null) { final Announcer announcer = new Announcer(getCuratorFramework(), Execs.singleThreaded("Announcer-%s")); lifecycle.addManagedInstance(announcer); final ZkDataSegmentAnnouncerConfig config = getConfigFactory().build(ZkDataSegmentAnnouncerConfig.class); final String announcerType = config.getAnnouncerType(); final DataSegmentAnnouncer dataSegmentAnnouncer; if ("batch".equalsIgnoreCase(announcerType)) { dataSegmentAnnouncer = new BatchDataSegmentAnnouncer( getDruidServerMetadata(), config, announcer, getJsonMapper() ); } else if ("legacy".equalsIgnoreCase(announcerType)) { dataSegmentAnnouncer = new MultipleDataSegmentAnnouncerDataSegmentAnnouncer( Arrays.<AbstractDataSegmentAnnouncer>asList( new BatchDataSegmentAnnouncer( getDruidServerMetadata(), config, announcer, getJsonMapper() ), new SingleDataSegmentAnnouncer( getDruidServerMetadata(), getZkPaths(), announcer, getJsonMapper() ) ) ); } else { throw new ISE("Unknown announcer type [%s]", announcerType); } setAnnouncer(dataSegmentAnnouncer); lifecycle.addManagedInstance(getAnnouncer(), Lifecycle.Stage.LAST); } }
Source:
public void update() throws Exception { String id = "id"; ServiceProviderDTO dto = new ServiceProviderDTO("id", "name", "description"); final ServiceProvider provider = new ServiceProvider(new ID(id), dto.name, dto.description); Request request = makeRequestThatContains(dto); context.checking(new Expectations() {{ oneOf(repository).update(with(matching(provider))); }}); Reply<?> reply = service.update(id, request); assertThat(reply, isOk()); }

Target:
public void update() throws Exception { String id = "id123"; ServiceProviderDTO dto = new ServiceProviderDTO("id", "name", "description"); final ServiceProvider provider = new ServiceProvider(new ID(id), dto.name, dto.description); Request request = makeRequestThatContains(dto); context.checking(new Expectations() {{ oneOf(repository).update(with(matching(provider))); }}); Reply<?> reply = service.update(id, request); assertThat(reply, isOk()); }
Source:
private void rehash() { int newCapacity = capacity * 2; long[] newKeys = new long[newCapacity]; V[] newValues = (V[]) new Object[newCapacity]; for (int i = 0; i < keys.length; i++) { long storedKey = keys[i]; V storedValue = values[i]; if (storedValue != EmptyValue && storedValue != DeletedValue) { insertKeyValueNoLock(newKeys, newValues, storedKey, storedValue); } } keys = newKeys; values = newValues; usedBuckets = size; CAPACITY_UPDATER.lazySet(this, newCapacity); resizeThreshold = (int) (capacity * MapFillFactor); }

Target:
private void rehash() { int newCapacity = capacity * 2; long[] newKeys = new long[newCapacity]; V[] newValues = (V[]) new Object[newCapacity]; for (int i = 0; i < keys.length; i++) { long storedKey = keys[i]; V storedValue = values[i]; if (storedValue != EmptyValue && storedValue != DeletedValue) { insertKeyValueNoLock(newKeys, newValues, storedKey, storedValue); } } keys = newKeys; values = newValues; usedBuckets = size; CAPACITY_UPDATER.lazySet(this, newCapacity); resizeThreshold = (int) (newCapacity * MapFillFactor); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message); YieldsApplication.setApplicationContext(getApplicationContext()); YieldsApplication.setResources(getResources()); try { YieldsClientUser.createInstance("Client user", new Id(117), "email", Bitmap.createBitmap(80, 80, Bitmap.Config.RGB_565)); YieldsApplication.setGroup(new Group("Presentation", new Id(2), new ArrayList<User>())); } catch (InstantiationException | ExecutionException | InterruptedException | IOException e) { e.printStackTrace(); } mUser = YieldsApplication.getUser(); mGroup = YieldsApplication.getGroup(); mMessages = new ArrayList<>(); mImage = null; mSendImage = false; mAdapter = new ListAdapterMessages(YieldsApplication.getApplicationContext(), R.layout.messagelayout, mMessages); ListView listView = (ListView) findViewById(R.id.messageScrollLayout); listView.setAdapter(mAdapter); mInputField = (EditText) findViewById(R.id.inputMessageField); if(mUser == null || mGroup == null) { showErrorToast("Couldn't get group informations."); TextView groupName = (TextView) findViewById(R.id.groupName); groupName.setText("Unknown group"); }else { setHeaderBar(); try { retrieveGroupMessages(); } catch (IOException e) { showErrorToast("Couldn't retrieve messages."); } } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message); YieldsApplication.setApplicationContext(getApplicationContext()); YieldsApplication.setResources(getResources()); try { Bitmap image1 = Bitmap.createBitmap(80, 80, Bitmap.Config.RGB_565); YieldsApplication.setUser(new MockClientUser("Mock User", new Id(117), "Mock Email", image1)); YieldsApplication.setGroup(createFakeGroup()); } catch (NodeException e) { e.printStackTrace(); } mUser = YieldsApplication.getUser(); mGroup = YieldsApplication.getGroup(); mMessages = new ArrayList<>(); mImage = null; mSendImage = false; mAdapter = new ListAdapterMessages(YieldsApplication.getApplicationContext(), R.layout.messagelayout, mMessages); mMessageScrollLayout = (ListView) findViewById(R.id.messageScrollLayout); mMessageScrollLayout.setAdapter(mAdapter); mInputField = (EditText) findViewById(R.id.inputMessageField); if(mUser == null || mGroup == null) { showErrorToast("Couldn't get group informations."); TextView groupName = (TextView) findViewById(R.id.groupName); groupName.setText("Unknown group"); }else { setHeaderBar(); try { new RetrieveMessageTask().execute().get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
Source:
protected void persist(String mountPath, List<ReplicaTokenInfo> tokenInfoList) throws IOException { File temp = new File(mountPath, replicaTokenFileName + ".tmp"); File actual = new File(mountPath, replicaTokenFileName); try (FileOutputStream fileStream = new FileOutputStream(temp)) { replicaTokenSerde.serializeTokens(tokenInfoList, fileStream); temp.renameTo(actual); logger.debug("Completed writing replica tokens to file {}", actual.getAbsolutePath()); } catch (IOException e) { logger.error("IO error while persisting tokens to disk {}", temp.getAbsoluteFile()); if (!storageManager.isDiskAvailableAtMountPath(mountPath)) { mountPathsToSkip.add(mountPath); } throw e; } }

Target:
protected void persist(String mountPath, List<ReplicaTokenInfo> tokenInfoList) throws IOException { File temp = new File(mountPath, replicaTokenFileName + ".tmp"); File actual = new File(mountPath, replicaTokenFileName); try (FileOutputStream fileStream = new FileOutputStream(temp)) { replicaTokenSerde.serializeTokens(tokenInfoList, fileStream); temp.renameTo(actual); logger.debug("Completed writing replica tokens to file {}", actual.getAbsolutePath()); } catch (IOException e) { logger.error("IO error while persisting tokens to disk {}", temp.getAbsoluteFile()); PartitionInfo partitionInfo = partitionGroupedByMountPath.get(mountPath).iterator().next(); if (storeManager.checkLocalPartitionStatus(partitionInfo.getPartitionId(), partitionInfo.getLocalReplicaId()) == ServerErrorCode.Disk_Unavailable) { mountPathsToSkip.add(mountPath); } throw e; } }
Source:
protected String toString(Operator operator) { if (Operator.STARTSWITH.equals(operator)) return LIKE; return operator.toString(); }

Target:
protected String toString(Operator operator) { if (Operator.STARTSWITH.equals(operator)) { return LIKE; } return operator.toString(); }
Source:
private static void computeVersion(ServletContext context) { Properties props = new Properties(); try (InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties")) { if(is!=null) props.load(is); } catch (IOException e) { e.printStackTrace(); } String ver = props.getProperty("version"); if(ver==null) ver = UNCOMPUTED_VERSION; if(Main.isDevelopmentMode && "${build.version}".equals(ver)) { try { File dir = new File(".").getAbsoluteFile(); while(dir != null) { File pom = new File(dir, "pom.xml"); if (pom.exists() && "pom".equals(XMLUtils.getValue("/project/artifactId", pom))) { pom = pom.getCanonicalFile(); LOGGER.info("Reading version from: " + pom.getAbsolutePath()); ver = XMLUtils.getValue("/project/version", pom); break; } dir = dir.getParentFile(); } LOGGER.info("Jenkins is in dev mode, using version: " + ver); } catch (Exception e) { LOGGER.log(Level.WARNING, "Unable to read Jenkins version: " + e.getMessage(), e); } } VERSION = ver; context.setAttribute("version",ver); VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); if(ver.equals(UNCOMPUTED_VERSION) || SystemProperties.getBoolean("hudson.script.noCache")) RESOURCE_PATH = ""; else RESOURCE_PATH = "static/"+SESSION_HASH; VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH; }

Target:
private static void computeVersion(ServletContext context) { Properties props = new Properties(); try (InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties")) { if(is!=null) props.load(is); } catch (IOException e) { e.printStackTrace(); } String ver = props.getProperty("version"); if(ver==null) ver = UNCOMPUTED_VERSION; if(Main.isDevelopmentMode && "${build.version}".equals(ver)) { try { File dir = new File(".").getAbsoluteFile(); while(dir != null) { File pom = new File(dir, "pom.xml"); if (pom.exists() && "pom".equals(XMLUtils.getValue("/project/artifactId", pom))) { pom = pom.getCanonicalFile(); LOGGER.info("Reading version from: " + pom.getAbsolutePath()); ver = XMLUtils.getValue("/project/version", pom); break; } dir = dir.getParentFile(); } LOGGER.info("Jenkins is in dev mode, using version: " + ver); } catch (Exception e) { LOGGER.log(Level.WARNING, "Unable to read Jenkins version: " + e.getMessage(), e); } } VERSION = ver; context.setAttribute("version",ver); VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); if(ver.equals(UNCOMPUTED_VERSION) || SystemProperties.getBoolean("hudson.script.noCache")) RESOURCE_PATH = ""; else RESOURCE_PATH = "/static/"+SESSION_HASH; VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH; }
Source:
public Pair<VM, FullEntityOvfData> readVmFromOvf(String ovf) throws OvfReaderException { VM vm = new VM(); ArrayList<VmNetworkInterface> interfaces = new ArrayList<>(); FullEntityOvfData fullEntityOvfData = new FullEntityOvfData(vm); ovfManager.importVm(ovf, vm, fullEntityOvfData); vm.setImages((ArrayList) fullEntityOvfData.getDiskImages()); vm.setInterfaces(interfaces); Map<Guid, List<DiskImage>> images = ImagesHandler .getImagesLeaf(fullEntityOvfData.getDiskImages()); for (Map.Entry<Guid, List<DiskImage>> entry : images.entrySet()) { List<DiskImage> list = entry.getValue(); vm.getDiskMap().put(entry.getKey(), list.get(list.size() - 1)); } for (LunDisk lunDisk : fullEntityOvfData.getLunDisks()) { vm.getDiskMap().put(lunDisk.getId(), lunDisk); } return new Pair<>(vm, fullEntityOvfData); }

Target:
public Pair<VM, FullEntityOvfData> readVmFromOvf(String ovf) throws OvfReaderException { VM vm = new VM(); FullEntityOvfData fullEntityOvfData = new FullEntityOvfData(vm); ovfManager.importVm(ovf, vm, fullEntityOvfData); vm.setImages((ArrayList) fullEntityOvfData.getDiskImages()); vm.setInterfaces(fullEntityOvfData.getInterfaces()); Map<Guid, List<DiskImage>> images = ImagesHandler .getImagesLeaf(fullEntityOvfData.getDiskImages()); for (Map.Entry<Guid, List<DiskImage>> entry : images.entrySet()) { List<DiskImage> list = entry.getValue(); vm.getDiskMap().put(entry.getKey(), list.get(list.size() - 1)); } for (LunDisk lunDisk : fullEntityOvfData.getLunDisks()) { vm.getDiskMap().put(lunDisk.getId(), lunDisk); } return new Pair<>(vm, fullEntityOvfData); }
Source:
private static String getURLEncoded(String url) { try { return URLEncoder.encode(url, Charsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return null; } }

Target:
private static String getURLEncoded(String url) { try { return URLEncoder.encode(url, Charsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( "Failed to use UTF-8 encoding charset", e); } }
Source:
public void saveMappings() throws PMException, ProjectDeletedException, IncompatibleTypeException { try { for (IAUTMainPO aut : m_objectMappings.keySet()) { if (aut != null) { EditSupport editSupport = new EditSupport(aut, null); editSupport.reinitializeEditSupport(); editSupport.lockWorkVersion(); IAUTMainPO workVersion = (IAUTMainPO) editSupport.getWorkVersion(); IObjectMappingPO objMap = workVersion.getObjMap(); Map<IComponentIdentifier, String> autObjectMapping = m_objectMappings.get(aut); if (autObjectMapping != null) { for (IComponentIdentifier ci : autObjectMapping.keySet()) { objMap.addObjectMappingAssoziation( autObjectMapping.get(ci), ci); } } editSupport.saveWorkVersion(); DataEventDispatcher.getInstance().fireDataChangedListener( objMap, DataState.StructureModified, UpdateState.all); DataEventDispatcher.getInstance().fireProjectStateChanged( ProjectState.revise_project); } } } catch (PersistenceException e) { PersistenceManager.handleDBExceptionForMasterSession(null, e); } }

Target:
public void saveMappings() throws PMException, ProjectDeletedException, IncompatibleTypeException { try { for (IAUTMainPO aut : m_objectMappings.keySet()) { if (aut != null) { EditSupport editSupport = new EditSupport(aut, null); editSupport.reinitializeEditSupport(); editSupport.lockWorkVersion(); IAUTMainPO workVersion = (IAUTMainPO) editSupport.getWorkVersion(); IObjectMappingPO objMap = workVersion.getObjMap(); Map<IComponentIdentifier, String> autObjectMapping = m_objectMappings.get(aut); if (autObjectMapping != null) { for (IComponentIdentifier ci : autObjectMapping.keySet()) { objMap.addObjectMappingAssoziation( autObjectMapping.get(ci), ci); } } editSupport.saveWorkVersion(); DataEventDispatcher.getInstance().fireDataChangedListener( objMap, DataState.StructureModified, UpdateState.all); } } } catch (PersistenceException e) { PersistenceManager.handleDBExceptionForMasterSession(null, e); } }
Source:
public void setEventList(List<ITimeEvent> eventList) { if (eventList != null) { super.setEventList(eventList.stream().map(timeEvent -> isValidEvent(timeEvent) ? timeEvent : null).collect(Collectors.toList())); } }

Target:
public void setEventList(List<ITimeEvent> eventList) { sanitizeList(eventList, super::setEventList); }
Source:
public void close() throws IOException { if (!isComplete() && wsChannel.isOpen()) { throw new IOException("Closed before all bytes where read"); } closed = true; ChannelListeners.invokeChannelListener(this, closeSetter.get()); }

Target:
public void close() throws IOException { if (!isComplete() && wsChannel.isOpen()) { wsChannel.markBroken(); throw WebSocketMessages.MESSAGES.closedBeforeAllBytesWereRead(); } closed = true; ChannelListeners.invokeChannelListener(this, closeSetter.get()); }
Source:
private Map<String, String> getTraceProperties() { for (ITmfTrace fTrace : TmfTraceManager.getInstance().getOpenedTraces()) { if (fTrace.getResource().equals(this.getResource())) { if (fTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) fTrace; return traceProperties.getTraceProperties(); } } } return null; }

Target:
private Map<String, String> getTraceProperties() { for (ITmfTrace fTrace : TmfTraceManager.getInstance().getOpenedTraces()) { if (fTrace.getResource().equals(this.getResource())) { if (fTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) fTrace; return traceProperties.getTraceProperties(); } } } return new HashMap<String, String>(); }
Source:
public String toString() { return "ServiceDiscoveryEvent{" + "type=" + type + ", groupId='" + groupId + '\'' + ", serviceEndpoint=" + Optional.ofNullable(serviceEndpoint) .map(ServiceEndpoint::id) .orElse(null) + ", serviceEndpoints=" + serviceEndpoints.stream() .map(se -> se.id() + "( " + se.address() + ")") .collect(Collectors.joining(",", "[", "]")) + '}'; }

Target:
public String toString() { return "ServiceDiscoveryEvent{" + "type=" + type + ", groupId='" + groupId + '\'' + ", serviceEndpoint=" + Optional.ofNullable(serviceEndpoint) .map(ServiceEndpoint::id) .orElse(null) + ", serviceEndpoints=" + serviceEndpoints.stream() .map(se -> se.id() + "@" + se.address()) .collect(Collectors.joining(",", "[", "]")) + '}'; }
Source:
public static void main(String[] args) throws Exception { String in = args[0], out = args[1]; LogSource source = new FileLogSource(new File(in)); try (Writer output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out)))) { FlamegraphData data = FlamegraphCollector.readFlamegraph(source); data.writeTo(output); } }

Target:
public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.print( "Usage: java com.insightfullogic.honest_profiler.ports.Flamegraph <profile.hpl> <profile.txt>\n" + "\n" + "The output needs to be processed with the tools at <LINK_0> to produce the actual flamegraph\n"); System.exit(1); } String in = args[0], out = args[1]; LogSource source = new FileLogSource(new File(in)); try (Writer output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out)))) { FlamegraphData data = FlamegraphCollector.readFlamegraph(source); data.writeTo(output); } }
Source:
public void run() { try { final String statusPath = JOINER.join(config.getStatusPath(), workerId, taskId); final String taskPath = JOINER.join(config.getTaskPath(), workerId, taskId); cf.delete().guaranteed().forPath(statusPath); cf.delete().guaranteed().forPath(taskPath); } catch (Exception e) { log.warn("Tried to delete a path that didn't exist! Must've gone away already!"); } }

Target:
public void run() { try { final String statusPath = JOINER.join(config.getStatusPath(), workerId, taskId); cf.delete().guaranteed().forPath(statusPath); } catch (Exception e) { log.warn("Tried to delete a status path that didn't exist! Must've gone away already?"); } try { final String taskPath = JOINER.join(config.getTaskPath(), workerId, taskId); cf.delete().guaranteed().forPath(taskPath); } catch (Exception e) { log.warn("Tried to delete a task path that didn't exist! Must've gone away already?"); } }
Source:
private void updateVmStatistics() { if (getVdsManager().isTimeToRefreshStatistics()) { dbVm.updateRunTimeStatisticsData(vdsmVm.getVmStatistics(), dbVm); saveStatistics(); saveVmInterfaces(); updateInterfaceStatistics(); updateVmNumaNodeRuntimeInfo(); for (DiskImageDynamic diskImageDynamic : vdsmVm.getVmDynamic().getDisks()) { vmsMonitoring.addDiskImageDynamicToSave(new Pair<>(dbVm.getId(), diskImageDynamic)); } } }

Target:
protected void updateVmStatistics() { if (vdsmVm.getVmStatistics() != null) { dbVm.updateRunTimeStatisticsData(vdsmVm.getVmStatistics(), dbVm); saveStatistics(); saveVmInterfaces(); updateInterfaceStatistics(); updateVmNumaNodeRuntimeInfo(); for (DiskImageDynamic diskImageDynamic : vdsmVm.getVmDynamic().getDisks()) { vmsMonitoring.addDiskImageDynamicToSave(new Pair<>(dbVm.getId(), diskImageDynamic)); } } }
Source:
public double determinant() { if (rows != columns) { throw new IllegalStateException("Can't compute determinant for " + "non-square matrix."); } if (rows == 0) { return 0.0; } else if (rows == 1) { return get(0, 0); } else if (rows == 2) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } else if (rows == 3) { return get(0, 0) * get(1, 1) * get(2, 2) + get(0, 1) * get(1, 2) * get(2, 0) + get(0, 2) * get(1, 0) * get(2, 1) - get(0, 2) * get(1, 1) * get(2, 0) - get(0, 1) * get(1, 0) * get(2, 2) - get(0, 0) * get(1, 2) * get(2, 1); } if (rows < 0) { return determinantByCrout(); } else { return determinantByLUDecomposition(); } }

Target:
public double determinant() { if (rows != columns) { throw new IllegalStateException("Can't compute determinant for " + "non-square matrix."); } if (rows == 0) { return 0.0; } else if (rows == 1) { return get(0, 0); } else if (rows == 2) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } else if (rows == 3) { return get(0, 0) * get(1, 1) * get(2, 2) + get(0, 1) * get(1, 2) * get(2, 0) + get(0, 2) * get(1, 0) * get(2, 1) - get(0, 2) * get(1, 1) * get(2, 0) - get(0, 1) * get(1, 0) * get(2, 2) - get(0, 0) * get(1, 2) * get(2, 1); } Matrix lup[] = decompose(Matrices.LU_DECOMPOSITOR); Matrix u = lup[Matrices.LU_U]; Matrix p = lup[Matrices.LU_P]; double result = u.diagonalProduct(); int permutations[] = new int[p.rows()]; for (int i = 0; i < p.rows(); i++) { for (int j = 0; j < p.columns(); j++) { if (p.get(i, j) > 0.0) { permutations[i] = j; break; } } } int sign = 1; for (int i = 0; i < permutations.length; i++) { for (int j = i + 1; j < permutations.length; j++) { if (permutations[j] < permutations[i]) { sign *= -1; } } } return sign * result; }
Source:
private void printMacroData(String eventName, String name, Map<String, String> parameters, String content, boolean isInline) { StringBuilder parametersBuffer = new StringBuilder(); for (Iterator<Map.Entry<String, String>> paramsIt = parameters.entrySet().iterator(); paramsIt.hasNext();) { Map.Entry<String, String> entry = paramsIt.next(); parametersBuffer.append(entry.getKey()).append(String.valueOf('=')).append(entry.getValue()); if (paramsIt.hasNext()) { parametersBuffer.append(String.valueOf('|')); } } StringBuilder macroBuffer = new StringBuilder(); macroBuffer.append(eventName); macroBuffer.append(isInline ? "Inline" : "Standalone"); macroBuffer.append(" ["); macroBuffer.append(name); macroBuffer.append(String.valueOf(']')); macroBuffer.append(" ["); macroBuffer.append(parametersBuffer); macroBuffer.append(String.valueOf(']')); if (content != null) { macroBuffer.append(" ["); macroBuffer.append(content); macroBuffer.append(String.valueOf(']')); } getPrinter().println(macroBuffer.toString()); }

Target:
private void printMacroData(String eventName, String name, Map<String, String> parameters, String content, boolean isInline) { StringBuilder parametersBuffer = new StringBuilder(); for (Iterator<Map.Entry<String, String>> paramsIt = parameters.entrySet().iterator(); paramsIt.hasNext();) { Map.Entry<String, String> entry = paramsIt.next(); parametersBuffer.append(entry.getKey()).append('=').append(entry.getValue()); if (paramsIt.hasNext()) { parametersBuffer.append('|'); } } StringBuilder macroBuffer = new StringBuilder(); macroBuffer.append(eventName); macroBuffer.append(isInline ? "Inline" : "Standalone"); macroBuffer.append(" ["); macroBuffer.append(name); macroBuffer.append(']'); macroBuffer.append(" ["); macroBuffer.append(parametersBuffer); macroBuffer.append(']'); if (content != null) { macroBuffer.append(" ["); macroBuffer.append(content); macroBuffer.append(']'); } getPrinter().println(macroBuffer.toString()); }