text:
/*
  Function name:  max(list);
  Input:          A list (array) of numbers.
  Returns:        The largest number in the list.
  Prints:         Nothing

  In English, the "max" method takes as input a list of numbers and
  returns the largest number in that list.

  Note: This exercise is "complete."
  This is meant to give you a starting point and also illustrate what we're
  looking for. There is ***NO NEED*** to comment line-by-line, although it
  can't hurt. It's not common in everyday, professional JavaScript, but here
  we're in a learning environment.
*/

function max(list) {
  var maxSoFar = list[0];                  // Setting maxSoFar to the first element of the list.
  for (var i = 0; i < list.length; i++) {  // Looping through each item in list
    if (list[i] > maxSoFar) {              // if the current item is greater than maxSoFar,
      maxSoFar = list[i];                  // set maxSoFar to current item.
    }
  }

  return maxSoFar;                         // We've gone through entire list, return the value of maxSoFar.
}

/*
  This "if" statement will be gobblededook, but it means:
    "If this file is the file currently being executed, then..."

  __FILE__ is always the name of the current file.
  $0 is always the name of the program beind executed.

  This means that if we run this file directly, i.e.,
      ruby max.rb
  then everything below will be executed.

  If, however, we include this file in another Ruby program via
      require 'max'
  then the below will *not* be executed
*/

// if __FILE__ == $PROGRAM_NAME
  // "p" prints something to the screen in a way that's better for debugging

console.log(max([1, 2, 3]) === 3);
console.log(max([0, -100, 50, -200]) === 50);
console.log(max([-200, -400, -100, -300]) === -100);
console.log(max([0]) === 0);
console.log(max([1]) === 1);
console.log(max([-1]) === -1);
console.log(max([11, 11, 11]) === 11);
console.log(max([-22, -11, -22]) === -11);

/*
  Each of the lines above will print out "true" or "false" and collectively
  act as a sanity check.  Remember that conceptually "x === y"
  means "are x and y equal?"

  That is, when you run the code, if any lines print out "false"
  then you know something is off in your code.

  This does *not* mean that your code is perfect if each line
  prints out "true.""  For example,
    1. We might have missed a corner case
    2. The code does what it should, but is conceptually confused
    3. Something else we haven't though of

  Remember: Option #3 is *always* possible.

  Think of these like rumble strips on the side of the road.  They're here
  to tell you when you're veering off the road, not to guarantee you're
  driving phenomenally. :)
*/


text:
@implementation NSDate (Apigee)

+ (int64_t) nowAsMilliseconds
{
    struct timeval t;
    gettimeofday(&t, NULL);

    return (((int64_t) t.tv_sec) * kApigeeMillisecondsPerSecond) + (((int64_t) t.tv_usec) / kApigeeMillisecondsPerSecond);
}

- (int64_t) dateAsMilliseconds
{
    return (int64_t) ([self timeIntervalSince1970] * kApigeeMillisecondsPerSecond);
}

+ (NSDate*) dateFromMilliseconds:(int64_t) milliseconds
{
    return [NSDate dateWithTimeIntervalSince1970:(milliseconds / kApigeeMillisecondsPerSecond)];
}

+ (NSString *) stringFromMilliseconds:(int64_t) milliseconds
{
    return [[NSNumber numberWithLongLong:milliseconds] stringValue];
}

+ (NSString*) unixTimestampAsString
{
    return [NSDate stringFromMilliseconds:[NSDate nowAsMilliseconds]];
}

+ (int64_t) unixTimestampAsLong
{
    return [self nowAsMilliseconds];
}

@end

redpajama_set_name: RedPajamaGithub


text:
public class JavaAnnot_1 {
    public static @interface Ann {}
}


text:
package de.hbrs.aspgen.merger.merge;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import de.hbrs.aspgen.api.diff.AnnotationData;
import de.hbrs.aspgen.merger.impl.GeneratorDataImpl;

public class AspectJMergerForDeletedBlocks extends AbstractMergerTest {

    @Test
    public void mergeFileWithNoChangedFieldsAndTwoNewField() throws IOException {
        final String oldFile = FileUtils.readFileToString(new File("src/test/resources/deleted/OldToString.aj"));
        final String newFile = FileUtils.readFileToString(new File("src/test/resources/deleted/NewToString.aj"));
        final String expected = FileUtils.readFileToString(new File("src/test/resources/deleted/MergedToString.aj"));
        assertEquals(expected, aspectJMerger.mergeFiles(oldFile, newFile, getGeneratorDatasForToString()));
    }

    public GeneratorDataImpl getGeneratorDatasForToString() {
        final AnnotationData data = new AnnotationData("1");
        data.addDeleted("ToString");
        final GeneratorDataImpl dataList = new GeneratorDataImpl("Person", "de.hbrs.aspgen.generator.tostring.ToString");
        dataList.addGeneratorData(data);
        return dataList;
    }
}


text:
class FilenamePrintVisitor : public FilenameVisitorBase
{
	public:
		QString run(const FilenameNode &node);

		void visit(const FilenameNodeConditional &node) override;
		void visit(const FilenameNodeConditionIgnore &node) override;
		void visit(const FilenameNodeConditionInvert &node) override;
		void visit(const FilenameNodeConditionJavaScript &node) override;
		void visit(const FilenameNodeConditionOp &node) override;
		void visit(const FilenameNodeConditionTag &node) override;
		void visit(const FilenameNodeConditionToken &node) override;
		void visit(const FilenameNodeJavaScript &node) override;
		void visit(const FilenameNodeRoot &node) override;
		void visit(const FilenameNodeText &node) override;
		void visit(const FilenameNodeVariable &node) override;

	private:
		QString m_result;
};

#endif // FILENAME_PRINT_VISITOR_H


text:
package com.sin.clipanyx.model;

public class TextData extends BaseData {
	private static final long serialVersionUID = 1653680916743768974L;
	public String text;

	public TextData(String text) {
		super();
		this.text = text;
	}
}


text:
import { useRouter } from 'next/router';
import { useEffect, useMemo, useRef, useState } from 'react';
import { JobType } from '@prisma/client';
import { DropdownMenu, Spinner, useToast } from '@tih/ui';

import { useGoogleAnalytics } from '~/components/global/GoogleAnalytics';
import OffersHeader from '~/components/offers/admin/OffersHeader';
import OffersRow from '~/components/offers/admin/OffersRow';
import OffersTablePagination from '~/components/offers/admin/OffersTablePagination';
import type {
  OfferTableColumn,
  OfferTableSortType,
} from '~/components/offers/admin/types';
import {
  FullTimeOfferTableColumns,
  InternOfferTableColumns,
  OFFER_TABLE_SORT_ORDER,
  OfferTableYoeOptions,
  YOE_CATEGORY_PARAM,
} from '~/components/offers/admin/types';

import { getCurrencyForCountry } from '~/utils/offers/currency/CurrencyEnum';
import CurrencySelector from '~/utils/offers/currency/CurrencySelector';
import { useSearchParamSingle } from '~/utils/offers/useSearchParam';
import { trpc } from '~/utils/trpc';

import type {
  AdminDashboardOffer,
  GetAdminOffersResponse,
  Paging,
} from '~/types/offers';

const NUMBER_OF_OFFERS_PER_PAGE = 20;

export type OffersTableProps = Readonly<{
  companyFilter: string;
  companyName?: string;
  country: string | null;
  countryFilter: string;
  jobTitleFilter: string;
}>;

export default function OffersTable({
  country,
  countryFilter,
  companyName,
  companyFilter,
  jobTitleFilter,
}: OffersTableProps) {
  const [currency, setCurrency] = useState(
    getCurrencyForCountry(country).toString(),
  );
  const [jobType, setJobType] = useState<JobType>(JobType.FULLTIME);
  const [pagination, setPagination] = useState<Paging>({
    currentPage: 0,
    numOfItems: 0,
    numOfPages: 0,
    totalItems: 0,
  });

  const [offers, setOffers] = useState<Array<AdminDashboardOffer>>([]);

  const { event: gaEvent } = useGoogleAnalytics();
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(true);

  const [
    selectedYoeCategory,
    setSelectedYoeCategory,
    isYoeCategoryInitialized,
  ] = useSearchParamSingle<keyof typeof YOE_CATEGORY_PARAM>('yoeCategory');

  const [
    selectedSortDirection,
    setSelectedSortDirection,
    isSortDirectionInitialized,
  ] = useSearchParamSingle<OFFER_TABLE_SORT_ORDER>('sortDirection');

  const [selectedSortType, setSelectedSortType, isSortTypeInitialized] =
    useSearchParamSingle<OfferTableSortType>('sortType');

  const areFilterParamsInitialized = useMemo(() => {
    return (
      isYoeCategoryInitialized &&
      isSortDirectionInitialized &&
      isSortTypeInitialized
    );
  }, [
    isYoeCategoryInitialized,
    isSortDirectionInitialized,
    isSortTypeInitialized,
  ]);
  const { pathname } = router;

  useEffect(() => {
    if (areFilterParamsInitialized) {
      router.replace(
        {
          pathname,
          query: {
            companyId: companyFilter,
            companyName,
            jobTitleId: jobTitleFilter,
            sortDirection: selectedSortDirection,
            sortType: selectedSortType,
            yoeCategory: selectedYoeCategory,
          },
        },
        undefined,
        { shallow: true },
      );
      setPagination({
        currentPage: 0,
        numOfItems: 0,
        numOfPages: 0,
        totalItems: 0,
      });
      setIsLoading(true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    areFilterParamsInitialized,
    currency,
    countryFilter,
    companyFilter,
    jobTitleFilter,
    selectedSortDirection,
    selectedSortType,
    selectedYoeCategory,
    pathname,
  ]);

  useEffect(() => {
    setSelectedSortDirection(OFFER_TABLE_SORT_ORDER.UNSORTED);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedYoeCategory]);
  const topRef = useRef<HTMLDivElement>(null);
  const { showToast } = useToast();
  const { isLoading: isResultsLoading } = trpc.useQuery(
    [
      'offers.admin.list',
      {
        companyId: companyFilter,
        countryId: countryFilter,
        currency,
        limit: NUMBER_OF_OFFERS_PER_PAGE,
        offset: pagination.currentPage,
        sortBy:
          selectedSortDirection && selectedSortType
            ? `${selectedSortDirection}${selectedSortType}`
            : '-monthYearReceived',
        title: jobTitleFilter,
        yoeCategory: selectedYoeCategory
          ? YOE_CATEGORY_PARAM[selectedYoeCategory as string]
          : undefined,
      },
    ],
    {
      onError: () => {
        showToast({
          title: 'Error loading the page.',
          variant: 'failure',
        });
        setIsLoading(false);
      },
      onSuccess: (response: GetAdminOffersResponse) => {
        setOffers(response.data);
        setPagination(response.paging);
        setJobType(response.jobType);
        setIsLoading(false);
      },
    },
  );

  const onSort = (
    sortDirection: OFFER_TABLE_SORT_ORDER,
    sortType: OfferTableSortType,
  ) => {
    gaEvent({
      action: 'offers_table_sort',
      category: 'engagement',
      label: `${sortType} - ${sortDirection}`,
    });
    setSelectedSortType(sortType);
    setSelectedSortDirection(sortDirection);
  };

  function renderFilters() {
    return (

        <DropdownMenu
          align="start"
          label={
            OfferTableYoeOptions.filter(
              ({ value: itemValue }) => itemValue === selectedYoeCategory,
            ).length > 0
              ? OfferTableYoeOptions.filter(
                  ({ value: itemValue }) => itemValue === selectedYoeCategory,
                )[0].label
              : OfferTableYoeOptions[0].label
          }
          size="md">
          {OfferTableYoeOptions.map(({ label: itemLabel, value }) => (
            <DropdownMenu.Item
              key={value}
              isSelected={value === selectedYoeCategory}
              label={itemLabel}
              onClick={() => {
                setSelectedYoeCategory(value);
                gaEvent({
                  action: `offers.table_filter_yoe_category_${value}`,
                  category: 'engagement',
                  label: 'Filter by YOE category',
                });
              }}
            />
          ))}
        </DropdownMenu>

              Display offers in

            <CurrencySelector
              handleCurrencyChange={(value: string) => setCurrency(value)}
              selectedCurrency={currency}
            />

    );
  }

  function renderHeader() {
    const columns: Array<OfferTableColumn> =
      jobType === JobType.FULLTIME
        ? FullTimeOfferTableColumns
        : InternOfferTableColumns;

    return (

          {columns.map((header, index) => (
            <OffersHeader
              key={header.label}
              header={header.label}
              isLastColumn={index === columns.length - 1}
              sortDirection={
                header.sortType === selectedSortType
                  ? selectedSortDirection
                  : undefined
              }
              sortType={header.sortType}
              onSort={onSort}
            />
          ))}

    );
  }

  const handlePageChange = (currPage: number) => {
    if (0 <= currPage && currPage < pagination.numOfPages) {
      setPagination({ ...pagination, currentPage: currPage });
    }
  };

  return (

{renderFilters()}

      <OffersTablePagination
        endNumber={
          pagination.currentPage * NUMBER_OF_OFFERS_PER_PAGE + offers.length
        }
        handlePageChange={handlePageChange}
        isInitialFetch={isLoading}
        isLoading={isResultsLoading}
        pagination={pagination}
        startNumber={pagination.currentPage * NUMBER_OF_OFFERS_PER_PAGE + 1}
      />

          {renderHeader()}
          {!isLoading && (

              {offers.map((offer) => (
                <OffersRow key={offer.id} jobType={jobType} row={offer} />
              ))}

          )}

        {isLoading && (

            <Spinner display="block" size="lg" />

        )}
        {!isLoading && (!offers || offers.length === 0) && (

No data yet 🥺

        )}

      <OffersTablePagination
        endNumber={
          pagination.currentPage * NUMBER_OF_OFFERS_PER_PAGE + offers.length
        }
        handlePageChange={(number) => {
          topRef?.current?.scrollIntoView({
            block: 'start',
          });
          handlePageChange(number);
        }}
        isInitialFetch={isLoading}
        isLoading={isResultsLoading}
        pagination={pagination}
        startNumber={pagination.currentPage * NUMBER_OF_OFFERS_PER_PAGE + 1}
      />

  );
}


text:
<?php
/* @var $this PurchasesController */
/* @var $model Purchases */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'purchases-form',
    'htmlOptions'=>array('class'=>'form-horizontal'),
	// Please note: When you enable ajax validation, make sure the corresponding
	// controller action is handling ajax validation correctly.
	// There is a call to performAjaxValidation() commented in generated controller code.
	// See class documentation of CActiveForm for details on this.
	'enableAjaxValidation'=>false,
)); ?>

	<?php echo $form->errorSummary($model); ?>

		<?php echo $form->label($model,'userID',array('class'=>'col-sm-2 control-label')); ?>

            <?php echo CHtml::link($model->user->FIO,array('/users/view','id'=>$model->userID),
                array('class'=>'')); ?>
			<?php echo $form->error($model,'userID'); ?>

		<?php echo $form->labelEx($model,'userComment',array('class'=>'col-sm-2 control-label')); ?>

			<?php echo $form->textField($model,'userComment',array('size'=>60,'maxlength'=>500, 'class'=>'form-control')); ?>
			<?php echo $form->error($model,'userComment'); ?>

		<?php echo $form->labelEx($model,'date',array('class'=>'col-sm-2 control-label')); ?>

<?php echo $model->date; ?>

			<?php echo $form->error($model,'date'); ?>

		<?php echo $form->labelEx($model,'paymentState',array('class'=>'col-sm-2 control-label')); ?>

            <?php
            $list = $this->payment_states;
            echo $form->dropDownList($model,'paymentState', $list,
                array('prompt'=>'Выберите состояние...','class'=>'form-control'));
            ?>
			<?php echo $form->error($model,'paymentState'); ?>

        <?php echo $form->labelEx($model,'deliveryState',array('class'=>'col-sm-2 control-label')); ?>

            <?php
            $list = $this->delivery_states;
            echo $form->dropDownList($model,'deliveryState', $list,
                array('prompt'=>'Выберите состояние...','class'=>'form-control'));
            ?>
            <?php echo $form->error($model,'deliveryState'); ?>

        <?php echo $form->labelEx($model,'payment_token',array('class'=>'col-sm-2 control-label')); ?>

<?php echo $model->payment_token; ?>

        <?php echo $form->labelEx($model,'payment_transaction',array('class'=>'col-sm-2 control-label')); ?>

<?php echo $model->payment_transaction; ?>

			<?php echo CHtml::submitButton('Сохранить', array('class'=>'btn btn-default')); ?>

<?php $this->endWidget(); ?>


text:
package com.leanstacks.ws.web.api;

import java.util.NoSuchElementException;

import javax.persistence.NoResultException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * A @ControllerAdvice class which provides exception handling to all REST controllers.
 *
 * @author Matt Warman
 */
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * The Logger for this Class.
     */
    private static final Logger logger = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class);

    /**
     * Handles JPA NoResultExceptions thrown from web service controller methods. Creates a response with an
     * ExceptionDetail body and HTTP status code 404, not found.
     *
     * @param ex A NoResultException instance.
     * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 404.
     */
    @ExceptionHandler(NoResultException.class)
    public ResponseEntity<Object> handleNoResultException(final NoResultException ex, final WebRequest request) {
        logger.info("> handleNoResultException");
        logger.info("- NoResultException: ", ex);
        final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.NOT_FOUND)
                .webRequest(request).build();
        logger.info("< handleNoResultException");
        return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
    }

    /**
     * Handles JPA NoSuchElementException thrown when an empty Optional is accessed. Creates a response with an
     * ExceptionDetail body and HTTP status code 404, not found.
     *
     * @param ex A NoSuchElementException instance.
     * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 404.
     */
    @ExceptionHandler(NoSuchElementException.class)
    public ResponseEntity<Object> handleNoSuchElementException(final NoSuchElementException ex,
            final WebRequest request) {
        logger.info("> handleNoSuchElementException");
        logger.info("- NoSuchElementException: ", ex);
        final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.NOT_FOUND)
                .webRequest(request).build();
        logger.info("< handleNoSuchElementException");
        return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
    }

    /**
     * Handles EmptyResultDataAccessException thrown from web service controller methods. Creates a response with an
     * ExceptionDetail body and HTTP status code 404, not found.
     *
     * @param ex An EmptyResultDataAccessException instance.
     * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 404.
     */
    @ExceptionHandler(EmptyResultDataAccessException.class)
    public ResponseEntity<Object> handleEmptyResultDataAccessException(final EmptyResultDataAccessException ex,
            final WebRequest request) {
        logger.info("> handleEmptyResultDataAccessException");
        logger.info("- EmptyResultDataAccessException: ", ex);
        final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.NOT_FOUND)
                .webRequest(request).build();
        logger.info("< handleEmptyResultDataAccessException");
        return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
    }

    /**
     * Handles IllegalArgumentException thrown from web service controller methods. Creates a response with an
     * ExceptionDetail body and HTTP status code 400, not found.
     *
     * @param ex An IllegalArgumentException instance.
     * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 400.
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Object> handleIllegalArgumentException(final IllegalArgumentException ex,
            final WebRequest request) {
        logger.info("> handleIllegalArgumentException");
        logger.warn("- IllegalArgumentException: ", ex);
        final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.BAD_REQUEST)
                .webRequest(request).build();
        logger.info("< handleIllegalArgumentException");
        return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }

    /**
     * Handles all Exceptions not addressed by more specific @ExceptionHandler methods. Creates a response
     * with the ExceptionDetail in the response body as JSON and a HTTP status code of 500, internal server error.
     *
     * @param ex An Exception instance.
     * @return A ResponseEntity containing a the ExceptionDetail in the response body and a HTTP status code 500.
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleGenericException(final Exception ex, final WebRequest request) {
        logger.info("> handleException");
        logger.error("- Exception: ", ex);
        final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex)
                .httpStatus(HttpStatus.INTERNAL_SERVER_ERROR).webRequest(request).build();
        logger.info("< handleException");
        return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }

}


text:
#include <common.h>
#include <asm/io.h>
#include <asm/arch/freeze_controller.h>
#include <asm/arch/scan_manager.h>

DECLARE_GLOBAL_DATA_PTR;

static const struct socfpga_scan_manager *scan_manager_base =
		(void *)(SOCFPGA_SCANMGR_ADDRESS);
static const struct socfpga_freeze_controller *freeze_controller_base =
		(void *)(SOCFPGA_SYSMGR_ADDRESS + SYSMGR_FRZCTRL_ADDRESS);

/*
 * Function to check IO scan chain engine status and wait if the engine is
 * is active. Poll the IO scan chain engine till maximum iteration reached.
 */
static inline uint32_t scan_chain_engine_is_idle(uint32_t max_iter)
{
	uint32_t scanmgr_status;

	scanmgr_status = readl(&scan_manager_base->stat);

	/* Poll the engine until the scan engine is inactive */
	while (SCANMGR_STAT_ACTIVE_GET(scanmgr_status) ||
	      (SCANMGR_STAT_WFIFOCNT_GET(scanmgr_status) > 0)) {
		max_iter--;
		if (max_iter > 0)
			scanmgr_status = readl(&scan_manager_base->stat);
		else
			return 0;
	}
	return 1;
}

/* Program HPS IO Scan Chain */
uint32_t scan_mgr_io_scan_chain_prg(
	uint32_t io_scan_chain_id,
	uint32_t io_scan_chain_len_in_bits,
	const uint32_t *iocsr_scan_chain)
{
	uint16_t tdi_tdo_header;
	uint32_t io_program_iter;
	uint32_t io_scan_chain_data_residual;
	uint32_t residual;
	uint32_t i;
	uint32_t index = 0;

	/*
	 * De-assert reinit if the IO scan chain is intended for HIO. In
	 * this, its the chain 3.
	 */
	if (io_scan_chain_id == 3)
		clrbits_le32(&freeze_controller_base->hioctrl,
			     SYSMGR_FRZCTRL_HIOCTRL_DLLRST_MASK);

	/*
	 * Check if the scan chain engine is inactive and the
	 * WFIFO is empty before enabling the IO scan chain
	 */
	if (!scan_chain_engine_is_idle(SCAN_MAX_DELAY))
		return 1;

	/*
	 * Enable IO Scan chain based on scan chain id
	 * Note: only one chain can be enabled at a time
	 */
	setbits_le32(&scan_manager_base->en, 1 << io_scan_chain_id);

	/*
	 * Calculate number of iteration needed for full 128-bit (4 x32-bits)
	 * bits shifting. Each TDI_TDO packet can shift in maximum 128-bits
	 */
	io_program_iter	= io_scan_chain_len_in_bits >>
		IO_SCAN_CHAIN_128BIT_SHIFT;
	io_scan_chain_data_residual = io_scan_chain_len_in_bits &
		IO_SCAN_CHAIN_128BIT_MASK;

	/* Construct TDI_TDO packet for 128-bit IO scan chain (2 bytes) */
	tdi_tdo_header = TDI_TDO_HEADER_FIRST_BYTE |
		(TDI_TDO_MAX_PAYLOAD <<	TDI_TDO_HEADER_SECOND_BYTE_SHIFT);

	/* Program IO scan chain in 128-bit iteration */
	for (i = 0; i < io_program_iter; i++) {
		/* write TDI_TDO packet header to scan manager */
		writel(tdi_tdo_header,	&scan_manager_base->fifo_double_byte);

		/* calculate array index. Multiply by 4 as write 4 x 32bits */
		index = i * 4;

		/* write 4 successive 32-bit IO scan chain data into WFIFO */
		writel(iocsr_scan_chain[index],
		       &scan_manager_base->fifo_quad_byte);
		writel(iocsr_scan_chain[index + 1],
		       &scan_manager_base->fifo_quad_byte);
		writel(iocsr_scan_chain[index + 2],
		       &scan_manager_base->fifo_quad_byte);
		writel(iocsr_scan_chain[index + 3],
		       &scan_manager_base->fifo_quad_byte);

		/*
		 * Check if the scan chain engine has completed the
		 * IO scan chain data shifting
		 */
		if (!scan_chain_engine_is_idle(SCAN_MAX_DELAY))
			goto error;
	}

	/* Calculate array index for final TDI_TDO packet */
	index = io_program_iter * 4;

	/* Final TDI_TDO packet if any */
	if (io_scan_chain_data_residual) {
		/*
		 * Calculate number of quad bytes FIFO write
		 * needed for the final TDI_TDO packet
		 */
		io_program_iter	= io_scan_chain_data_residual >>
			IO_SCAN_CHAIN_32BIT_SHIFT;

		/*
		 * Construct TDI_TDO packet for remaining IO
		 * scan chain (2 bytes)
		 */
		tdi_tdo_header	= TDI_TDO_HEADER_FIRST_BYTE |
			((io_scan_chain_data_residual - 1) <<
			TDI_TDO_HEADER_SECOND_BYTE_SHIFT);

		/*
		 * Program the last part of IO scan chain write TDI_TDO packet
		 * header (2 bytes) to scan manager
		 */
		writel(tdi_tdo_header, &scan_manager_base->fifo_double_byte);

		for (i = 0; i < io_program_iter; i++) {
			/*
			 * write remaining scan chain data into scan
			 * manager WFIFO with 4 bytes write
			*/
			writel(iocsr_scan_chain[index + i],
			       &scan_manager_base->fifo_quad_byte);
		}

		index += io_program_iter;
		residual = io_scan_chain_data_residual &
			IO_SCAN_CHAIN_32BIT_MASK;

		if (IO_SCAN_CHAIN_PAYLOAD_24BIT < residual) {
			/*
			 * write the last 4B scan chain data
			 * into scan manager WFIFO
			 */
			writel(iocsr_scan_chain[index],
			       &scan_manager_base->fifo_quad_byte);
		} else {
			/*
			 * write the remaining 1 - 3 bytes scan chain
			 * data into scan manager WFIFO byte by byte
			 * to prevent JTAG engine shifting unused data
			 * from the FIFO and mistaken the data as a
			 * valid command (even though unused bits are
			 * set to 0, but just to prevent hardware
			 * glitch)
			 */
			for (i = 0; i < residual; i += 8) {
				writel(((iocsr_scan_chain[index] >> i)
					& IO_SCAN_CHAIN_BYTE_MASK),
					&scan_manager_base->fifo_single_byte);
			}
		}

		/*
		 * Check if the scan chain engine has completed the
		 * IO scan chain data shifting
		 */
		if (!scan_chain_engine_is_idle(SCAN_MAX_DELAY))
			goto error;
	}

	/* Disable IO Scan chain when configuration done*/
	clrbits_le32(&scan_manager_base->en, 1 << io_scan_chain_id);
	return 0;

error:
	/* Disable IO Scan chain when error detected */
	clrbits_le32(&scan_manager_base->en, 1 << io_scan_chain_id);
	return 1;
}

int scan_mgr_configure_iocsr(void)
{
	int status = 0;

	/* configure the IOCSR through scan chain */
	status |= scan_mgr_io_scan_chain_prg(0,
		CONFIG_HPS_IOCSR_SCANCHAIN0_LENGTH, iocsr_scan_chain0_table);
	status |= scan_mgr_io_scan_chain_prg(1,
		CONFIG_HPS_IOCSR_SCANCHAIN1_LENGTH, iocsr_scan_chain1_table);
	status |= scan_mgr_io_scan_chain_prg(2,
		CONFIG_HPS_IOCSR_SCANCHAIN2_LENGTH, iocsr_scan_chain2_table);
	status |= scan_mgr_io_scan_chain_prg(3,
		CONFIG_HPS_IOCSR_SCANCHAIN3_LENGTH, iocsr_scan_chain3_table);
	return status;
}


text: The DNAT function enables servers that share the same EIPs in a VPC to provide services accessible from the Internet through the IP address mapping and port mapping.


text:
package org.apache.causeway.viewer.wicket.ui.components.layout.bs.tabs;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.extensions.markup.html.tabs.TabbedPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;

import org.apache.causeway.applib.layout.grid.bootstrap.BSTab;
import org.apache.causeway.applib.layout.grid.bootstrap.BSTabGroup;
import org.apache.causeway.commons.internal.base._NullSafe;
import org.apache.causeway.viewer.wicket.model.models.UiObjectWkt;
import org.apache.causeway.viewer.wicket.model.util.ComponentHintKey;
import org.apache.causeway.viewer.wicket.ui.panels.HasDynamicallyVisibleContent;

import de.agilecoders.wicket.core.markup.html.bootstrap.tabs.AjaxBootstrapTabbedPanel;
import lombok.val;

// hmmm... not sure how to make this implement HasDynamicallyVisibleContent
public class TabGroupPanel
extends AjaxBootstrapTabbedPanel<ITab>
implements HasDynamicallyVisibleContent {

    private static final long serialVersionUID = 1L;

    public static final String SESSION_ATTR_SELECTED_TAB = "selectedTab";

    // the view metadata
    private final ComponentHintKey selectedTabHintKey;
    private final UiObjectWkt entityModel;

    private static List<ITab> tabsFor(final UiObjectWkt entityModel, final BSTabGroup bsTabGroup) {
        final List<ITab> tabs = new ArrayList<>();

        final List<BSTab> tablist = _NullSafe.stream(bsTabGroup.getTabs())
                .filter(BSTab.Predicates.notEmpty())
                .collect(Collectors.toList());

        for (val bsTab : tablist) {
            val repeatingViewWithDynamicallyVisibleContent = TabPanel.newRows(entityModel, bsTab);
            String tabName = bsTab.getName();
            tabs.add(new AbstractTab(Model.of(tabName)) {
                private static final long serialVersionUID = 1L;

                @Override
                public Panel getPanel(final String panelId) {
                    return new TabPanel(panelId, entityModel, bsTab, repeatingViewWithDynamicallyVisibleContent);
                }

                @Override
                public boolean isVisible() {
                    return repeatingViewWithDynamicallyVisibleContent.isVisible();
                }
            });
        }
        return tabs;
    }

    public TabGroupPanel(final String id, final UiObjectWkt entityModel, final BSTabGroup bsTabGroup) {
        super(id, tabsFor(entityModel, bsTabGroup));
        this.entityModel = entityModel;

        this.selectedTabHintKey = ComponentHintKey.create(entityModel.getMetaModelContext(), this, SESSION_ATTR_SELECTED_TAB);
    }

    @Override
    protected void onInitialize() {
        setSelectedTabFromSessionIfAny(this);
        super.onInitialize();
    }

    @Override
    public TabbedPanel<ITab> setSelectedTab(final int index) {
        selectedTabHintKey.set(entityModel.getOwnerBookmark(), ""+index);
        return super.setSelectedTab(index);
    }

    private void setSelectedTabFromSessionIfAny(
            final AjaxBootstrapTabbedPanel<ITab> ajaxBootstrapTabbedPanel) {
        final String selectedTabStr = selectedTabHintKey.get(entityModel.getOwnerBookmark());
        final Integer tabIndex = parse(selectedTabStr);
        if (tabIndex != null) {
            final int numTabs = ajaxBootstrapTabbedPanel.getTabs().size();
            if (tabIndex < numTabs) {
                // to support dynamic reloading; the data in the session might not be compatible with current layout.
                ajaxBootstrapTabbedPanel.setSelectedTab(tabIndex);
            }
        }
    }

    private Integer parse(final String selectedTabStr) {
        try {
            return Integer.parseInt(selectedTabStr);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public boolean isVisible() {
        return _NullSafe.stream(getTabs())
                .anyMatch(ITab::isVisible);
    }

}


text:
<?php

namespace App\Exceptions;

class ValidationFailed extends \RuntimeException
{
    public static function validatorQuitUnexpectedly()
    {
        return new self('Validator quit unexpectedly.');
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: purwadi
 * Date: 09/03/17
 * Time: 8:01
 */

namespace Pw\Core\Console\Commands;

use Pw\Core\Modules;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Database\Migrations\Migrator;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class ModuleMigrateResetCommand extends Command
{
    use ConfirmableTrait;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:migrate:reset';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback semua migrations untuk module tertentu atau semua module';

    /**
     * @var Modules
     */
    protected $module;

    /**
     * @var Migrator
     */
    protected $migrator;

    /**
     * @var Filesystem
     */
    protected $files;

    /**
     * Create a new command instance.
     *
     * @param Modules    $module
     * @param Filesystem $files
     * @param Migrator   $migrator
     */
    public function __construct(Modules $module, Filesystem $files, Migrator $migrator)
    {
        parent::__construct();

        $this->module = $module;
        $this->files = $files;
        $this->migrator = $migrator;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        if (!$this->confirmToProceed()) {
            return;
        }

        $this->reset();
    }

    /**
     * Run the migration reset for the current list of slugs.
     *
     * Migrations should be reset in the reverse order that they were
     * migrated up as. This ensures the database is properly reversed
     * without conflict.
     *
     * @param string $slug
     *
     * @return mixed
     */
    protected function reset()
    {
        $this->migrator->setconnection($this->input->getOption('database'));

        $files = $this->migrator->getMigrationFiles($this->getMigrationPaths());

        $migrations = array_reverse($this->migrator->getRepository()->getRan());

        if(count($migrations) == 0){
            $this->output("Tidak ada rollback.");
        } else {
            $this->migrator->requireFiles($files);

            foreach($migrations as $migration){
                if(!array_key_exists($migration, $files)){
                    continue;
                }

                $this->runDown($files[$migration], (object) ["migration" => $migration]);
            }
        }

        foreach($this->migrator->getNotes() as $note){
            $this->output->writeln($note);
        }
    }

    /**
     * Run "down" a migration instance.
     *
     * @param string $slug
     * @param object $migration
     * @param bool   $pretend
     */
    protected function runDown($file, $migration)
    {
        $file = $this->migrator->getMigrationName($file);

        $instance = $this->migrator->resolve($file);

        $instance->down();

        $this->migrator->getRepository()->delete($migration);

        $this->info("Rolledback: ".$file);
    }

    /**
     * Generate a list of all migration paths, given the arguments/operations supplied.
     *
     * @return array
     */
    protected function getMigrationPaths(){
        $migrationPaths = [];

        foreach ($this->getSlugsToReset() as $slug) {
            $migrationPaths[] = $this->getMigrationPath($slug);

            event($slug.'.module.reset', [$this->module, $this->option()]);
        }

        return $migrationPaths;
    }

    /**
     * Using the arguments, generate a list of slugs to reset the migrations for.
     *
     * @return array
     */
    protected function getSlugsToReset(){
        if($this->validSlugProvided()){
            return [$this->argument("slug")];
        }

        if($this->option("force")){
            return $this->module->all()->pluck("slug");
        }

        return $this->module->enabled()->pluck("slug");
    }

    /**
     * Determine if a valid slug has been provided as an argument.
     *
     * We will accept a slug as long as it is not empty and is enalbed (or force is passed).
     *
     * @return bool
     */
    protected function validSlugProvided(){
        if(empty($this->argument("slug"))){
            return false;
        }

        if($this->module->isEnabled($this->argument("slug"))){
            return true;
        }

        if($this->option("force")){
            return true;
        }

        return false;
    }

    /**
     * Get the console command parameters.
     *
     * @param string $slug
     *
     * @return array
     */
    protected function getParameters($slug)
    {
        $params = [];

        $params['--path'] = $this->getMigrationPath($slug);

        if ($option = $this->option('database')) {
            $params['--database'] = $option;
        }

        if ($option = $this->option('pretend')) {
            $params['--pretend'] = $option;
        }

        if ($option = $this->option('seed')) {
            $params['--seed'] = $option;
        }

        return $params;
    }

    /**
     * Get migrations path.
     *
     * @return string
     */
    protected function getMigrationPath($slug)
    {
        return module_path($slug, 'Database/Migrations');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [['slug', InputArgument::OPTIONAL, 'Module slug.']];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'],
            ['force', null, InputOption::VALUE_NONE, 'Force the operation to run while in production.'],
            ['pretend', null, InputOption::VALUE_OPTIONAL, 'Dump the SQL queries that would be run.'],
            ['seed', null, InputOption::VALUE_OPTIONAL, 'Indicates if the seed task should be re-run.'],
        ];
    }
}


text:
<?php

namespace AppBundle\Controller\Report;

use AppBundle\Controller\AbstractController;
use AppBundle\Entity as EntityDir;
use AppBundle\Form as FormDir;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class LifestyleController extends AbstractController
{
    private static $jmsGroups = [
        'lifestyle',
        'lifestyle-state',
    ];

    /**
     * @Route("/report/{reportId}/lifestyle", name="lifestyle")
     * @Template("AppBundle:Report/Lifestyle:start.html.twig")
     */
    public function startAction(Request $request, $reportId)
    {
        $report = $this->getReportIfNotSubmitted($reportId, self::$jmsGroups);
        if ($report->getStatus()->getLifestyleState()['state'] != EntityDir\Report\Status::STATE_NOT_STARTED) {
            return $this->redirectToRoute('lifestyle_summary', ['reportId' => $reportId]);
        }

        return [
            'report' => $report,
        ];
    }

    /**
     * @Route("/report/{reportId}/lifestyle/step/{step}", name="lifestyle_step")
     * @Template("AppBundle:Report/Lifestyle:step.html.twig")
     */
    public function stepAction(Request $request, $reportId, $step)
    {
        $totalSteps = 2;
        if ($step < 1 || $step > $totalSteps) {
            return $this->redirectToRoute('lifestyle_summary', ['reportId' => $reportId]);
        }
        $report = $this->getReportIfNotSubmitted($reportId, self::$jmsGroups);
        $lifestyle = $report->getLifestyle() ?: new EntityDir\Report\Lifestyle();
        $fromPage = $request->get('from');

        $stepRedirector = $this->stepRedirector()
            ->setRoutes('lifestyle', 'lifestyle_step', 'lifestyle_summary')
            ->setFromPage($fromPage)
            ->setCurrentStep($step)
            ->setTotalSteps($totalSteps)
            ->setRouteBaseParams(['reportId' => $reportId]);

        $form = $this->createForm(FormDir\Report\LifestyleType::class, $lifestyle, ['step' => $step]);
        $form->handleRequest($request);

        if ($form->get('save')->isClicked() && $form->isValid()) {
            $data = $form->getData();
            /* @var $data EntityDir\Report\Lifestyle */
            $data
                ->setReport($report)
                ->keepOnlyRelevantLifestyleData();

            if ($lifestyle->getId() == null) {
                $this->getRestClient()->post('report/lifestyle', $data, ['lifestyle', 'report-id']);
            } else {
                $this->getRestClient()->put('report/lifestyle/' . $lifestyle->getId(), $data, self::$jmsGroups);
            }

            if ($fromPage == 'summary') {
                $request->getSession()->getFlashBag()->add(
                    'notice',
                    'Answer edited'
                );
            }

            return $this->redirect($stepRedirector->getRedirectLinkAfterSaving());
        }

        return [
            'report'       => $report,
            'step'         => $step,
            'reportStatus' => $report->getStatus(),
            'form'         => $form->createView(),
            'backLink'     => $stepRedirector->getBackLink(),
            'skipLink'     => $stepRedirector->getSkipLink(),
        ];
    }

    /**
     * @Route("/report/{reportId}/lifestyle/summary", name="lifestyle_summary")
     * @Template("AppBundle:Report/Lifestyle:summary.html.twig")
     */
    public function summaryAction(Request $request, $reportId)
    {
        $fromPage = $request->get('from');
        $report = $this->getReportIfNotSubmitted($reportId, self::$jmsGroups);
        if ($report->getStatus()->getLifestyleState()['state'] == EntityDir\Report\Status::STATE_NOT_STARTED && $fromPage != 'skip-step') {
            return $this->redirectToRoute('lifestyle', ['reportId' => $reportId]);
        }

        if (!$report->getLifestyle()) { //allow validation with answers all skipped
            $report->setLifestyle(new EntityDir\Report\Lifestyle());
        }

        return [
            'comingFromLastStep' => $fromPage == 'skip-step' || $fromPage == 'last-step',
            'report'             => $report,
            'status'             => $report->getStatus()
        ];
    }

    /**
     * @return string
     */
    protected function getSectionId()
    {
        return 'lifestyle';
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>statsmodels.tsa.vector_ar.vecm.coint_johansen — statsmodels 0.9.0 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.tsa.regime_switching.markov_regression.MarkovRegression" href="statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.html" />
    <link rel="prev" title="statsmodels.tsa.vector_ar.vecm.VECMResults.var_rep" href="statsmodels.tsa.vector_ar.vecm.VECMResults.var_rep.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Time Series analysis tsa |

statsmodels.tsa.vector_ar.vecm.coint_johansen¶

statsmodels.tsa.vector_ar.vecm.coint_johansen(endog, det_order, k_ar_diff)[source]¶

Perform the Johansen cointegration test for determining the cointegration
rank of a VECM.

<col class="field-name" />
<col class="field-body" />

Parameters:

endog (array-like (nobs_tot x neqs)) – The data with presample.

det_order (int) –

-1 - no deterministic terms

0 - constant term

1 - linear trend

k_ar_diff (int, nonnegative) – Number of lagged differences in the model.

Returns:

result – An object containing the results which can be accessed using
dot-notation. The object's attributes are

eig: (neqs)

Eigenvalues.

evec: (neqs x neqs)

Eigenvectors.

lr1: (neqs)

Trace statistic.

lr2: (neqs)

Maximum eigenvalue statistic.

cvt: (neqs x 3)

Critical values (90%, 95%, 99%) for trace statistic.

cvm: (neqs x 3)

Critical values (90%, 95%, 99%) for maximum eigenvalue
statistic.

method: str
"johansen"

r0t: (nobs x neqs)

Residuals for \(\Delta Y\). See p. 292 in [1].

rkt: (nobs x neqs)

Residuals for \(Y_{-1}\). See p. 292 in [1].

ind: (neqs)

Order of eigenvalues.

Return type:
Holder

Notes

The implementation might change to make more use of the existing VECM
framework.

References

<colgroup><col class="label" /><col /></colgroup>

[1]	(1, 2) Lütkepohl, H. 2005. New Introduction to Multiple Time Series Analysis. Springer.

Previous topic

statsmodels.tsa.vector_ar.vecm.VECMResults.var_rep

Next topic

statsmodels.tsa.regime_switching.markov_regression.MarkovRegression

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

        © Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.7.4.


text:
class Motor
  attr_reader :speed
  def initialize
    @speed = 0
  end

  def run(speed: 0)
    @speed = speed
    run_motor
  end

  private
    def run_motor
      puts "motor speed is #{speed}"
    end
end


text:
package com.java110.job.adapt.hcGov.car;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.dto.community.CommunityAttrDto;
import com.java110.dto.community.CommunityDto;
import com.java110.dto.owner.OwnerCarDto;
import com.java110.dto.parking.ParkingAreaDto;
import com.java110.dto.parking.ParkingSpaceDto;
import com.java110.dto.parkingAreaAttr.ParkingAreaAttrDto;
import com.java110.entity.order.Business;
import com.java110.intf.community.ICommunityInnerServiceSMO;
import com.java110.intf.community.IParkingAreaInnerServiceSMO;
import com.java110.intf.community.IParkingSpaceInnerServiceSMO;
import com.java110.intf.user.IOwnerCarInnerServiceSMO;
import com.java110.job.adapt.DatabusAdaptImpl;
import com.java110.job.adapt.hcGov.HcGovConstant;
import com.java110.job.adapt.hcGov.asyn.BaseHcGovSendAsyn;
import com.java110.po.car.OwnerCarPo;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.DateUtil;
import com.java110.utils.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 新增车辆同步HC政务接口
 * <p>
 * 接口协议地址: https://gitee.com/java110/microCommunityInformation/tree/master/info-doc#1%E6%A5%BC%E6%A0%8B%E4%B8%8A%E4%BC%A0
 *
 * @desc add by 吴学文 16:20
 */
@Component(value = "addCarToHcGovAdapt")
public class AddCarToHcGovAdapt extends DatabusAdaptImpl {

    @Autowired
    private ICommunityInnerServiceSMO communityInnerServiceSMOImpl;

    @Autowired
    private IOwnerCarInnerServiceSMO ownerCarInnerServiceSMOImpl;
    @Autowired
    private BaseHcGovSendAsyn baseHcGovSendAsynImpl;

    @Autowired
    private IParkingSpaceInnerServiceSMO parkingSpaceInnerServiceSMOImpl;

    @Autowired
    private IParkingAreaInnerServiceSMO parkingAreaInnerServiceSMOImpl;

    /**
     * @param business   当前处理业务
     * @param businesses 所有业务信息
     */
    @Override
    public void execute(Business business, List<Business> businesses) {
        JSONObject data = business.getData();
        if (data.containsKey(OwnerCarPo.class.getSimpleName())) {
            Object bObj = data.get(OwnerCarPo.class.getSimpleName());
            JSONArray businessOwnerCars = null;
            if (bObj instanceof JSONObject) {
                businessOwnerCars = new JSONArray();
                businessOwnerCars.add(bObj);
            } else if (bObj instanceof List) {
                businessOwnerCars = JSONArray.parseArray(JSONObject.toJSONString(bObj));
            } else {
                businessOwnerCars = (JSONArray) bObj;
            }
            //JSONObject businessOwnerCar = data.getJSONObject("businessOwnerCar");
            for (int bOwnerCarIndex = 0; bOwnerCarIndex < businessOwnerCars.size(); bOwnerCarIndex++) {
                JSONObject businessOwnerCar = businessOwnerCars.getJSONObject(bOwnerCarIndex);
                doAddOwnerCar(business, businessOwnerCar);
            }
        }
    }

    private void doAddOwnerCar(Business business, JSONObject businessFloor) {

        OwnerCarPo ownerCarPo = BeanConvertUtil.covertBean(businessFloor, OwnerCarPo.class);

        CommunityDto communityDto = new CommunityDto();
        communityDto.setCommunityId(ownerCarPo.getCommunityId());
        List<CommunityDto> communityDtos = communityInnerServiceSMOImpl.queryCommunitys(communityDto);
        Assert.listNotNull(communityDtos, "未包含小区信息");
        CommunityDto tmpCommunityDto = communityDtos.get(0);
        String extCommunityId = "";
        String communityId = tmpCommunityDto.getCommunityId();
        if (tmpCommunityDto.getCommunityAttrDtos() != null && tmpCommunityDto.getCommunityAttrDtos().size() > 0) {
            for (CommunityAttrDto communityAttrDto : tmpCommunityDto.getCommunityAttrDtos()) {
                if (HcGovConstant.EXT_COMMUNITY_ID.equals(communityAttrDto.getSpecCd())) {
                    extCommunityId = communityAttrDto.getValue();
                }
            }
        }
        //查询车辆
        OwnerCarDto ownerCarDto = new OwnerCarDto();
        ownerCarDto.setCommunityId(ownerCarPo.getCommunityId());
        ownerCarDto.setCarId(ownerCarPo.getCarId());
        List<OwnerCarDto> ownerCarDtos = ownerCarInnerServiceSMOImpl.queryOwnerCars(ownerCarDto);

        Assert.listOnlyOne(ownerCarDtos, "车辆不存在");

        //查询外部停车场
        ParkingSpaceDto parkingSpaceDto = new ParkingSpaceDto();
        parkingSpaceDto.setPsId(ownerCarDtos.get(0).getPsId());
        List<ParkingSpaceDto> parkingSpaceDtos = parkingSpaceInnerServiceSMOImpl.queryParkingSpaces(parkingSpaceDto);
        Assert.listOnlyOne(parkingSpaceDtos, "车位不存在");

        //查询 外部停车
        ParkingAreaDto parkingAreaDto = new ParkingAreaDto();
        parkingAreaDto.setPaId(parkingSpaceDtos.get(0).getPaId());
        parkingAreaDto.setCommunityId(parkingSpaceDtos.get(0).getCommunityId());
        List<ParkingAreaDto> parkingAreaDtos = parkingAreaInnerServiceSMOImpl.queryParkingAreas(parkingAreaDto);
        Assert.listOnlyOne(parkingAreaDtos, "停车场不存在");

        String extPaId = getExtPaId(parkingAreaDtos.get(0).getAttrs());

        if (StringUtil.isEmpty(extPaId)) {
            return;
        }

        JSONObject body = new JSONObject();
        body.put("carNum", ownerCarDtos.get(0).getCarNum());
        body.put("carBrand", ownerCarDtos.get(0).getCarBrand());
        body.put("carType", ownerCarDtos.get(0).getCarType());
        body.put("carColor", ownerCarDtos.get(0).getCarColor());
        body.put("startTime", DateUtil.getFormatTimeString(ownerCarDtos.get(0).getStartTime(), DateUtil.DATE_FORMATE_STRING_A));
        body.put("endTime", DateUtil.getFormatTimeString(ownerCarDtos.get(0).getEndTime(), DateUtil.DATE_FORMATE_STRING_A));
        body.put("personName", ownerCarDtos.get(0).getOwnerName());
        body.put("personTel", ownerCarDtos.get(0).getLink());
        body.put("extPaId", extPaId);

        JSONObject kafkaData = baseHcGovSendAsynImpl.createHeadersOrBody(body, extCommunityId, HcGovConstant.ADD_CAR_ACTION, HcGovConstant.COMMUNITY_SECURE);
        baseHcGovSendAsynImpl.sendKafka(HcGovConstant.GOV_TOPIC, kafkaData, communityId, ownerCarPo.getCarId(), HcGovConstant.COMMUNITY_SECURE);
    }

    private String getExtPaId(List<ParkingAreaAttrDto> attrs) {

        if (attrs == null || attrs.size() < 1) {
            return "";
        }

        for (ParkingAreaAttrDto parkingAreaAttrDto : attrs) {
            if (parkingAreaAttrDto.getSpecCd().equals(HcGovConstant.EXT_COMMUNITY_ID)) {
                return parkingAreaAttrDto.getValue();
            }
        }
        return "";
    }

}


text:
layout: single
title: "SEO Early On, Part 1"
description: "While starting a business, there are many things one must think of, from permitting to supply chain management; however, an oft overlooked thing is SEO!"
category: SEO
tags: [SEO, Startup]
blog: true
comments: true
redirect_from: /blog/2012/12/17/seo-early-on/
---

While starting a business, there are many things one must think of, from permitting to supply chain management; however, an oft overlooked thing is SEO!

SEO, or search engine optimization, is the process of helping people find your site and your products through search engines.  SEO has often gotten a bad rap because of people offering things that simply aren't possible and then disappearing with your money.  Most search marketers aren't like that at all but those that are leave a bad taste in everybody's mouth.

## Where Do I Start?

SEO involves getting found.  In a perfect world, search engines would be able to rank your site simply by the quality and accuracy of the content you provide; however, this is not an ideal world.  Search engines rely on other web sites linking to you to rank your site.  The basic idea is that other sites will link to you if they believe you have quality information.  High quality sites tend to link to other high quality sites.

To be interesting to anybody, not just search engines, you need to have unique, quality content!  Start writing that blog you've heard about.  Identify something unique about your business and talk about it!  Get out there and generate some content.

People used to say "Build it and they will come"1, but that hasn't been true for a LONG time.  People have to know how to find your content so you need to tell people about them.  Talk about interesting things on social media.  Talk about other people's things on social media!  Ge to know other people that are out there making amazing content.

As you build relationships with people and have people interested in what you have to say, then that old saying becomes more true!  People start finding your content because they're interested in what you're saying, not because you told them about it.  If it's good *enough* though, they will tell others about it(link to it)!

Stay tuned for [Part 2][]!

1 - SEOMoz
[Part 2]: /blog/2012/12/28/seo-early-on-part-2/


text:
package org.cellularautomaton.space.builder.expression;

import java.util.Collection;
import java.util.HashSet;

public abstract class ComposedExpression implements Expression {
	private final Collection<Expression> expressions = new HashSet<Expression>(2);

	public Collection<Expression> getExpressions() {
		return expressions;
	}

	public void addExpression(Expression expression) {
		expressions.add(expression);
	}

}


text:
"""
Law example tasks to demonstrate HTCondor workflows at VISPA.

In this file, some really basic tasks are defined that can be inherited by
other tasks to receive the same features. This is usually called "framework"
and only needs to be defined once per user / group / etc.
"""

import os

import luigi
import law

# the htcondor workflow implementation is part of a law contrib package
# so we need to explicitly load it
law.contrib.load("htcondor")

class Task(law.Task):
    """
    Base task that we use to force a version parameter on all inheriting tasks, and that provides
    some convenience methods to create local file and directory targets at the default data path.
    """

    version = luigi.Parameter()

    def store_parts(self):
        return (self.__class__.__name__, self.version)

    def local_path(self, *path):
        # ANALYSIS_DATA_PATH is defined in setup.sh
        parts = (os.getenv("ANALYSIS_DATA_PATH"),) + self.store_parts() + path
        return os.path.join(*parts)

    def local_target(self, *path):
        return law.LocalFileTarget(self.local_path(*path))

class HTCondorWorkflow(law.htcondor.HTCondorWorkflow):
    """
    Batch systems are typically very heterogeneous by design, and so is HTCondor. Law does not aim
    to "magically" adapt to all possible HTCondor setups which would certainly end in a mess.
    Therefore we have to configure the base HTCondor workflow in law.contrib.htcondor to work with
    the VISPA environment. In most cases, like in this example, only a minimal amount of
    configuration is required.
    """

    max_runtime = law.DurationParameter(
        default=1.0,
        unit="h",
        significant=False,
        description="maximum runtime; default unit is hours; default: 1",
    )
    htcondor_gpus = luigi.IntParameter(
        default=law.NO_INT,
        significant=False,
        description="number of GPUs to request on the VISPA cluster; leave empty to use only CPUs",
    )

    def htcondor_output_directory(self):
        # the directory where submission meta data should be stored
        return law.LocalDirectoryTarget(self.local_path())

    def htcondor_bootstrap_file(self):
        # each job can define a bootstrap file that is executed prior to the actual job
        # configure it to be shared across jobs and rendered as part of the job itself
        bootstrap_file = law.util.rel_path(__file__, "bootstrap.sh")
        return law.JobInputFile(bootstrap_file, share=True, render_job=True)

    def htcondor_job_config(self, config, job_num, branches):
        # render_variables are rendered into all files sent with a job
        config.render_variables["analysis_path"] = os.getenv("ANALYSIS_PATH")

        # copy the entire environment
        config.custom_content.append(("getenv", "true"))

        # tell the job config if GPUs are requested
        if not law.is_no_param(self.htcondor_gpus):
            config.custom_content.append(("request_gpus", self.htcondor_gpus))

        return config


text:
Tool to browse all kinds of API docs.

[![Build Status](https://secure.travis-ci.org/rickardlindberg/alldoc.png)](http://travis-ci.org/rickardlindberg/alldoc)


text:
package com.happydroids.droidtowers.gamestate.server;

import java.util.UUID;

import com.happydroids.droidtowers.gui.VibrateClickListener;
import com.happydroids.droidtowers.jackson.Vector2Serializer;
import com.happydroids.droidtowers.jackson.Vector3Serializer;
import com.happydroids.jackson.HappyDroidObjectMapper;
import com.happydroids.security.SecurePreferences;

public class TowerGameService {
	private static final String TAG = TowerGameService.class.getSimpleName();

	public static final String SESSION_TOKEN = "SESSION_TOKEN";
	public static final String DEVICE_ID = "DEVICE_ID";

	protected static TowerGameService _instance;

	private static String deviceType;
	private static String deviceOSVersion;
	private static String deviceOSMarketName = "none";
	private SecurePreferences preferences;
	private boolean authenticated;
	private RunnableQueue postAuthRunnables;
	private boolean authenticationFinished;

	protected HappyDroidObjectMapper objectMapper;

	public TowerGameService() {
		super();

		postAuthRunnables = new RunnableQueue();

		getObjectMapper().addSerializer(new Vector3Serializer());
		getObjectMapper().addSerializer(new Vector2Serializer());
	}

	public static TowerGameService instance() {
		if (_instance == null) {
			_instance = new TowerGameService();
		}

		return (TowerGameService) _instance;
	}

	public HappyDroidObjectMapper getObjectMapper() {
		if (objectMapper == null) {
			objectMapper = new HappyDroidObjectMapper();
		}

		return objectMapper;
	}

	public static void setInstance(TowerGameService instance) {
		TowerGameService._instance = instance;
	}

	public static boolean hasBeenInitialised() {
		return _instance != null;
	}

	public String getSessionToken() {
		return getPreferences().getString(SESSION_TOKEN, null);
	}

	public String getDeviceId() {
		return getPreferences().getString(DEVICE_ID);
	}

	public synchronized void setSessionToken(String token) {
		if (token != null) {
			getPreferences().putString(SESSION_TOKEN, token);
			getPreferences().flush();

			authenticationFinished = true;
			authenticated = true;
			postAuthRunnables.runAll();
		} else {
			getPreferences().remove(SESSION_TOKEN);
			getPreferences().flush();
		}
	}

	public boolean isAuthenticated() {
		return authenticated;
	}

	public static void setDeviceType(String dt) {
		deviceType = dt;
	}

	public static void setDeviceOSMarketName(String name) {
		deviceOSMarketName = name;
	}

	public static void setDeviceOSVersion(String osVersion) {
		deviceOSVersion = osVersion;
	}

	public static String getDeviceOSVersion() {
		return deviceOSVersion;
	}

	public static String getDeviceOSMarketName() {
		return deviceOSMarketName;
	}

	public static String getDeviceType() {
		return deviceType;
	}

	public void afterDeviceIdentification(Runnable runnable) {
		if (!authenticationFinished) {
			postAuthRunnables.push(runnable);
		} else {
			runnable.run();
		}
	}

	public void resetAuthentication() {
		setSessionToken(null);

		authenticated = false;
		authenticationFinished = false;
		postAuthRunnables.clear();
	}

	public void setAudioState(boolean audioEnabled) {
		getPreferences().putBoolean("audioState", audioEnabled);
		getPreferences().flush();
	}

	public boolean getAudioState() {
		return getPreferences().getBoolean("audioState", true);
	}

	public RunnableQueue getPostAuthRunnables() {
		return postAuthRunnables;
	}

	public void setAuthenticated(boolean authenticated) {
		this.authenticated = authenticated;

		if (!this.authenticated) {
			setSessionToken(null);
		}

		authenticationFinished = true;
		postAuthRunnables.runAll();
	}

	public void setDeviceId(String deviceId) {
		getPreferences().putString(DEVICE_ID, deviceId);
		getPreferences().flush();
	}

	public SecurePreferences getPreferences() {
		if (preferences == null) {
			preferences = new SecurePreferences("com.happydroids.droidtowers." + getDeviceOSMarketName());
			if (!preferences.contains(DEVICE_ID)) {
				preferences.putString(DEVICE_ID, UUID.randomUUID().toString().replaceAll("-", ""));
				preferences.flush();
			}

			VibrateClickListener.setVibrateEnabled(preferences.getBoolean("vibrateOnTouch", true));
		}

		return preferences;
	}
}


text:
package cz.jcode.auto.value.step.builder.example.generic;

import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import cz.jcode.auto.value.step.builder.AutoValueStepBuilder;

import javax.annotation.Nullable;

@AutoValue
@AutoValueStepBuilder
public abstract class NoBuilderAddress<T> {
    public abstract T title();

    public abstract T street();

    @Nullable
    public abstract ImmutableList<T> streetParts();

    public abstract T city();

    public abstract T postcode();

    public abstract T countryCode();

    public static <T> AutoValue_NoBuilderAddress.TitleStep<T> step() {
        return AutoValue_NoBuilderAddress.<T>step();
    }

    public static <T> AutoValue_NoBuilderAddress.TitleLazyStep<T> lazyStep() {
        return AutoValue_NoBuilderAddress.<T>lazyStep();
    }
}


text:
<?php

namespace Sylius\Component\Taxation\Model;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface TaxableInterface
{
    /**
     * @return TaxCategoryInterface
     */
    public function getTaxCategory();
}


text:
class SocialIconsController {
    constructor() {
        'ngInject';
    }

    $onInit(){

    }
}

export const SocialIconsComponent = {
    templateUrl: './views/app/components/social-icons/social-icons.component.html',
    controller: SocialIconsController,
    controllerAs: 'vm',
    bindings: {}
}


text:
package io.druid.segment.data;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.io.ByteSink;
import com.google.common.io.CountingOutputStream;
import com.google.common.math.LongMath;
import com.google.common.primitives.Longs;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.nio.channels.WritableByteChannel;

public class IntermediateLongSupplierSerializer implements LongSupplierSerializer
{

  private final IOPeon ioPeon;
  private final String filenameBase;
  private final String tempFile;
  private final ByteOrder order;
  private final CompressedObjectStrategy.CompressionStrategy compression;
  private CountingOutputStream tempOut = null;

  private int numInserted = 0;

  private BiMap<Long, Integer> uniqueValues = HashBiMap.create();
  private long maxVal = Long.MIN_VALUE;
  private long minVal = Long.MAX_VALUE;

  private LongSupplierSerializer delegate;

  public IntermediateLongSupplierSerializer(
      IOPeon ioPeon,
      String filenameBase,
      ByteOrder order,
      CompressedObjectStrategy.CompressionStrategy compression
  )
  {
    this.ioPeon = ioPeon;
    this.tempFile = filenameBase + ".temp";
    this.filenameBase = filenameBase;
    this.order = order;
    this.compression = compression;
  }

  public void open() throws IOException
  {
    tempOut = new CountingOutputStream(ioPeon.makeOutputStream(tempFile));
  }

  public int size()
  {
    return numInserted;
  }

  public void add(long value) throws IOException
  {
    tempOut.write(Longs.toByteArray(value));
    ++numInserted;
    if (uniqueValues.size() <= CompressionFactory.MAX_TABLE_SIZE && !uniqueValues.containsKey(value)) {
      uniqueValues.put(value, uniqueValues.size());
    }
    if (value > maxVal) {
      maxVal = value;
    }
    if (value < minVal) {
      minVal = value;
    }
  }

  private void makeDelegate() throws IOException
  {
    CompressionFactory.LongEncodingWriter writer;
    long delta;
    try {
      delta = LongMath.checkedSubtract(maxVal, minVal);
    }
    catch (ArithmeticException e) {
      delta = -1;
    }
    if (uniqueValues.size() <= CompressionFactory.MAX_TABLE_SIZE) {
      writer = new TableLongEncodingWriter(uniqueValues);
    } else if (delta != -1 && delta != Long.MAX_VALUE) {
      writer = new DeltaLongEncodingWriter(minVal, delta);
    } else {
      writer = new LongsLongEncodingWriter(order);
    }

    if (compression == CompressedObjectStrategy.CompressionStrategy.NONE) {
      delegate = new EntireLayoutLongSupplierSerializer(
          ioPeon, filenameBase, order, writer
      );
    } else {
      delegate = new BlockLayoutLongSupplierSerializer(
          ioPeon, filenameBase, order, writer, compression
      );
    }

    try (DataInputStream tempIn = new DataInputStream(new BufferedInputStream(ioPeon.makeInputStream(tempFile)))) {
      delegate.open();
      while (tempIn.available() > 0) {
        delegate.add(tempIn.readLong());
      }
    }
  }

  public void closeAndConsolidate(ByteSink consolidatedOut) throws IOException
  {
    tempOut.close();
    makeDelegate();
    delegate.closeAndConsolidate(consolidatedOut);
  }

  public void close() throws IOException
  {
    tempOut.close();
    makeDelegate();
    delegate.close();
  }

  public long getSerializedSize()
  {
    return delegate.getSerializedSize();
  }

  public void writeToChannel(WritableByteChannel channel) throws IOException
  {
    delegate.writeToChannel(channel);
  }
}


text:
package EstructuraControlRepetitiva;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author KHANAKAT
 */
public class SumaNNumeros {

    public static void main(String[]args)throws IOException{

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int suma = 0;

        System.out.print("Ingresar el valor del numero de veces que quieres sumar un numero: ");
        int nVeces = Integer.parseInt(br.readLine());
        System.out.print("Ingresar el valor del numero que se va a sumar 'n' veces: ");
        int numero = Integer.parseInt(br.readLine());

        for(int i = 1; i <= nVeces; i++){
            suma = suma + numero;
        }

        System.out.println("\n"+nVeces+" veces "+numero+" es "+suma);
    }

}


text:
@class MCPinView;

@protocol MCPinViewDelegate <NSObject>

- (void)mcPinViewDidEndFillingAll:(MCPinView *)pinView pinNumber:(NSString *)pinNumber;

@end

IB_DESIGNABLE @interface MCPinView : UIView <MCPinTextFieldDelegate>

@property (weak, nonatomic) IBOutlet id <MCPinViewDelegate> delegate;

@property (strong, nonatomic) IBInspectable UIImage *backgroundImage;

@property (assign, nonatomic) IBInspectable NSInteger fieldsNumber;
@property (assign, nonatomic) IBInspectable CGFloat fieldsWidth;
@property (assign, nonatomic) IBInspectable CGFloat fieldsHeight;
@property (assign, nonatomic) IBInspectable CGFloat marginBetweenFields;
@property (strong, nonatomic) IBInspectable UIColor *fieldsColor;
@property (assign, nonatomic) IBInspectable NSInteger fieldsBorderWidth;
@property (strong, nonatomic) IBInspectable UIColor *fieldsBorderColor;
@property (assign, nonatomic) IBInspectable CGFloat fieldsCornerRadius;
@property (strong, nonatomic) IBInspectable UIImage *fieldsBackgroundImage;
@property (strong, nonatomic) IBInspectable UIColor *pinFailColor;
@property (assign, nonatomic) IBInspectable CGFloat failFlashDuration;
@property (assign, nonatomic) IBInspectable BOOL centerContent;

- (void)failFlash;
- (void)restartAll;
@end


text:
package org.sakaiproject.evaluation.tool.producers;

import java.util.ArrayList;
import java.util.List;

import org.sakaiproject.evaluation.logic.EvalAuthoringService;
import org.sakaiproject.evaluation.model.EvalItem;
import org.sakaiproject.evaluation.model.EvalItemGroup;
import org.sakaiproject.evaluation.tool.utils.ScaledUtils;
import org.sakaiproject.evaluation.tool.viewparams.ExpertItemViewParameters;
import org.sakaiproject.evaluation.tool.viewparams.TemplateViewParameters;

import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.components.decorators.DecoratorList;
import uk.org.ponder.rsf.components.decorators.UILabelTargetDecorator;
import uk.org.ponder.rsf.components.decorators.UIStyleDecorator;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParamsReporter;

/**
 * Handles the expert items view
 *
 * @author Aaron Zeckoski (aaronz@vt.edu)
 */
public class ExpertItemsProducer extends EvalCommonProducer implements NavigationCaseReporter, ViewParamsReporter {

    /**
     * Used for navigation within the system, this must match with the template name
     */
    public static final String VIEW_ID = "choose_expert_items"; //$NON-NLS-1$
    public String getViewID() {
        return VIEW_ID;
    }

    private EvalAuthoringService authoringService;
    public void setAuthoringService(EvalAuthoringService authoringService) {
        this.authoringService = authoringService;
    }

    /* (non-Javadoc)
     * @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker)
     */
    public void fill(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

        ExpertItemViewParameters expertItemViewParameters = (ExpertItemViewParameters) viewparams;
        Long templateId = expertItemViewParameters.templateId;
        Long categoryId = expertItemViewParameters.categoryId;
        Long objectiveId = expertItemViewParameters.objectiveId;

        UIMessage.make(tofill, "page-title", "expert.items.page.title"); //$NON-NLS-1$ //$NON-NLS-2$

        UIInternalLink.make(tofill, "modify-template", UIMessage.make("modifytemplate.page.title"), //$NON-NLS-1$ //$NON-NLS-2$
                new TemplateViewParameters(ModifyTemplateItemsProducer.VIEW_ID, templateId) );

        // create a copy of the VP and then set it to the right view (to avoid corrupting the original)
        ExpertItemViewParameters eivp = (ExpertItemViewParameters) expertItemViewParameters.copyBase();
        eivp.viewID = ExpertCategoryProducer.VIEW_ID;

        UIMessage.make(tofill, "expert-items", "expert.expert.items");
        UIInternalLink.make(tofill, "expert-items-category-link", UIMessage.make("expert.category"), eivp ); //$NON-NLS-1$ //$NON-NLS-2$
        UIMessage.make(tofill, "expert-items-items", "expert.items");

        UIInternalLink.make(tofill, "choose-category-1-link", UIMessage.make("expert.choose.category"), eivp ); //$NON-NLS-1$ //$NON-NLS-2$

        eivp.viewID = ExpertObjectiveProducer.VIEW_ID;

        UIInternalLink.make(tofill, "expert-items-objective-link", UIMessage.make("expert.objective"), eivp ); //$NON-NLS-1$ //$NON-NLS-2$

        UIInternalLink.make(tofill, "choose-objective-2-link", UIMessage.make("expert.choose.objective"), eivp ); //$NON-NLS-1$ //$NON-NLS-2$
        UIMessage.make(tofill, "choose-items-3", "expert.choose.items");

        UIMessage.make(tofill, "category", "expert.category");
        EvalItemGroup category = authoringService.getItemGroupById(categoryId);
        UIOutput.make(tofill, "category-current", category.getTitle() );
        UIMessage.make(tofill, "objective", "expert.objective");
        EvalItemGroup objective = authoringService.getItemGroupById(objectiveId);
        UIOutput.make(tofill, "objective-current", objective.getTitle() );
        UIMessage.make(tofill, "items", "expert.items");
        UIMessage.make(tofill, "items-instructions", "expert.items.instructions");
        UIMessage.make(tofill, "expert-items-summary", "expert.items.summary");
        UIMessage.make(tofill, "description", "expert.description");

        UIForm form = UIForm.make(tofill, "insert-items-form");

        UIBranchContainer expertItemHeaderBranch = UIBranchContainer.make(tofill, "expert-item-header-row:");
       	UIMessage.make(expertItemHeaderBranch, "expert-item-col", "expert.items");
       	UIBranchContainer selectAllBranch = UIBranchContainer.make(expertItemHeaderBranch, "select-all-col:");

        // loop through all expert items
        List<EvalItem> expertItems = authoringService.getItemsInItemGroup(objectiveId, true);
        for (int i = 0; i < expertItems.size(); i++) {
            EvalItem expertItem = (EvalItem) expertItems.get(i);
            UIBranchContainer items = UIBranchContainer.make(form, "expert-item-list:", expertItem.getId().toString());
            if (i % 2 == 0) {
                items.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class
            }

            UIBoundBoolean checkbox = UIBoundBoolean.make(items, "insert-item-checkbox", "#{expertItemsBean.selectedIds." + expertItem.getId() + "}");
            UILabelTargetDecorator.targetLabel(UIOutput.make(items, "item-label"), checkbox);
            UIVerbatim.make(items, "item-text", expertItem.getItemText()); //$NON-NLS-1$
            if (expertItem.getScale() != null) {
                UIOutput.make(items, "item-scale", ScaledUtils.makeScaleText(expertItem.getScale(), 0)); //$NON-NLS-1$
            }
            if (expertItem.getExpertDescription() != null) {
                UIVerbatim.make(items, "item-expert-desc", expertItem.getExpertDescription()); //$NON-NLS-1$
            }
        }

        // create the cancel button
        UIMessage.make(tofill, "cancel-button", "expert.items.cancel");

        // create the Insert Items button
        UICommand addItemsCommand = UICommand.make(form, "insert-items-command", UIMessage.make("expert.items.insert"), //$NON-NLS-1$
        "#{expertItemsBean.processActionAddItems}"); //$NON-NLS-1$
        addItemsCommand.parameters.add(new UIELBinding("#{expertItemsBean.templateId}", templateId)); //$NON-NLS-1$
    }

    /*
     * (non-Javadoc)
     * @see uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter#reportNavigationCases()
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public List reportNavigationCases() {
        List i = new ArrayList();
        i.add(new NavigationCase("success", new TemplateViewParameters(ModifyTemplateItemsProducer.VIEW_ID, null) ) );
        return i;
    }

    /* (non-Javadoc)
     * @see uk.org.ponder.rsf.viewstate.ViewParamsReporter#getViewParameters()
     */
    public ViewParameters getViewParameters() {
        return new ExpertItemViewParameters();
    }

}


text:
import { Component, EventEmitter, Input, Output } from '@angular/core';

import { Hero } from '../model/hero';
import {BaseComponent} from "../../frameworks/core/decorators/base.component";

@BaseComponent({
  moduleId: module.id,
  selector:    'dashboard-hero',
  templateUrl: 'dashboard-hero.component.html',
  styleUrls: [ 'dashboard-hero.component.css' ]
})
export class DashboardHeroComponent {
  @Input() hero: Hero;
  @Output() selected = new EventEmitter<Hero>();
  click() { this.selected.next(this.hero); }
}