text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
O-Index (REPSI Tool)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

C D E F G I M N O P R S T

O

OPERATION_CODE_CREATE_TABLE -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation code - create table.

OPERATION_CODE_DROP_AND_CREATE_TABLE -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation code - drop and create table.

OPERATION_CODE_DROP_TABLE -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation code - drop table.

OPERATION_CODE_EXECUTE_QUERY -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation code - execute query.

OPERATION_CODE_EXECUTE_QUERY_APPLIED -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation code - execute query applied.

OPERATION_CODE_EXECUTE_QUERY_UNAPPLIED -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation code - execute query unapplied.

OPERATION_CODE_INSERT_ROW -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation code - insert row.

OPERATION_TYPE_INSTANCE -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation type - instance.

OPERATION_TYPE_QUERY -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation type - query.

OPERATION_TYPE_SCHEMA -
Static variable in interface edu.ou.weinmann.repsi.model.util.Global

Operation type - schema.

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

C D E F G I M N O P R S T


text:
// ------------------------------------------------------------------------------
// Copyright   版权所有。
// 项目名:Galaxy.Common
// 文件名:UtilY.cs
// 创建标识:梁桐铭  2017-03-20 11:13
// 创建描述:我们是OurGalaxy团队
//
// 修改标识:
// 修改描述:
//  ------------------------------------------------------------------------------

#region 命名空间

using System;
using System.Collections.Generic;
using System.Threading;

#endregion

namespace YoYo.Common.Util
{
    /// <summary>
    ///     业务辅助类
    /// </summary>
    public static class UtilY
    {
        /// <summary>
        ///     进入业务处理
        /// </summary>
        /// <param name="identity">标识</param>
        /// <param name="seconds">默认为30秒. 30秒自动退出</param>
        /// <returns>
        ///     业务需要判断 如果返回false 则终止程序继续往下执行
        ///     只负责处理不允许二个人"同时调用"某个业务代码,业务需要处理"重复调用"逻辑。
        /// </returns>
        public static bool Enter(string identity, int seconds = 30)
        {
            return UtilYManager.Instance.Enter(identity, seconds);
        }

        /// <summary>
        ///     业务处理完毕
        /// </summary>
        /// <param name="identity">标识</param>
        public static void Exit(string identity)
        {
            UtilYManager.Instance.Exit(identity);
        }

        /// <summary>
        ///     清除内存中的数据
        /// </summary>
        public static void Clear()
        {
            UtilYManager.Instance.Clear();
        }
    }

    internal class UtilYManager
    {
        private readonly Dictionary<string, DateTime> _dict = new Dictionary<string, DateTime>();
        private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();

        public bool Enter(string identity, int seconds)
        {
            _locker.EnterWriteLock();
            var flag = false;
            if (_dict.ContainsKey(identity))
            {
                if (_dict[identity].AddSeconds(seconds) < DateTime.Now)
                {
                    _dict[identity] = DateTime.Now;
                    flag = true;
                }
                else
                {
                    flag = false;
                }
            }
            else
            {
                _dict.Add(identity, DateTime.Now);
                flag = true;
            }
            _locker.ExitWriteLock();
            return flag;
        }

        public void Exit(string identity)
        {
            _locker.EnterWriteLock();
            if (_dict.ContainsKey(identity)) _dict.Remove(identity);
            _locker.ExitWriteLock();
        }

        public void Clear()
        {
            _dict.Clear();
        }

        #region singleton

        public static UtilYManager Instance
        {
            get { return Nested.Instance; }
        }

        private class Nested
        {
            internal static readonly UtilYManager Instance = new UtilYManager();

            static Nested()
            {
            }
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
function Export-EventLog
{
    [CmdletBinding()]
    param
    (
        [string] $Name,
        [string] $path,
        [System.Management.Automation.Runspaces.PSSession] $Session
    )
    Write-Verbose "Exporting eventlog $name"
    $local = $false
    $invokeCommandParams = @{ }
    if ($Session)
    {
        $invokeCommandParams.Add('Session', $Session);
    }
    else
    {
        $local = $true
    }

    invoke-command -ErrorAction:Continue @invokeCommandParams -script {
        param ($name, $path)
        $ErrorActionPreference = 'stop'
        Set-StrictMode -Version latest
        Write-Debug "Name: $name"

        Write-Debug "Path: $path"
        Write-Debug "windir: $Env:windir"
        $exePath = Join-Path $Env:windir 'system32\wevtutil.exe'
        $exportFileName = "$($Name -replace '/','-').evtx"

        $ExportCommand = "$exePath epl '$Name' '$Path\$exportFileName' /ow:True 2>&1"
        Invoke-expression -command $ExportCommand
    } -argumentlist @($Name, $path)
}


text:
class Book < AvroRecord
	#has_many :book_lines
end


text:
using System;
using System.Linq;

namespace LawnMowerLib
{
    public class ProblemSet
    {
        private LawnMower mower;

        public LawnMower Mower
        {
            get
            {
                return mower;
            }
        }

        private Instructions instructions;

        public Instructions Instructions
        {
            get
            {
                return instructions;
            }
        }

        public ProblemSet(LawnMower mower, Instructions instructions)
        {
            this.mower = mower;
            this.instructions = instructions;
        }
    }
}


text:
import React from 'react';
// import {  } from 'lodash';

import { PropTypes } from 'helpers/react';
// const { } = PropTypes;

export default class NotFoundPage extends React.Component {
  static propTypes = {

  };

  static defaultProps = {

  };

  render() {
    return (

            Route not found

    );
  }
}


text:
/* eslint-disable */
const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const pkg = require('./package.json');

module.exports = () => {
  const mode = 'production';
  const { version, author, license } = pkg;

  const BANNER = [
    'TOAST UI Map Chart',
    `@version ${version} | ${new Date().toDateString()}`,
    `@author ${author}`,
    `@license ${license}`,
  ].join('\n');

  return {
    mode,
    entry: ['./src/index.ts'],
    output: {
      library: {
        export: 'default',
        type: 'commonjs2',
      },
      filename: `toastui-chart-shared.js`,
      path: path.resolve(__dirname, 'dist'),
      publicPath: '/dist',
    },
    plugins: [
      new webpack.BannerPlugin({
        banner: BANNER,
        entryOnly: true,
      }),
    ],
    module: {
      rules: [
        {
          test: /\.(ts|tsx|js)$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
          options: {
            envName: mode,
          },
        },
      ],
    },
    optimization: {
      minimize: true,
      minimizer: [
        new TerserPlugin({
          extractComments: false,
          terserOptions: {
            compress: {
              drop_console: true,
              warnings: true,
            },
          },
        }),
      ],
    },
    resolve: {
      extensions: ['.ts', '.js', '.json'],
      alias: {
        '@src': path.resolve(__dirname, 'src/'),
        '@t': path.resolve(__dirname, 'types/'),
      },
    },
  };
};


text:
int _ti89, _ti92plus;  // produce code for TI89 and TI92plus

INT_HANDLER oldint5 = NULL;

volatile int mseconds50 = 0; // counts in 50ms steps (not exact 50ms, but 1000/19 ms)
volatile int seconds    = 0; // counts seconds
volatile int minutes    = 0; // counts minutes
volatile int hours      = 0; // counts hours
volatile int resettime  = 1; // used to signal a reset clock
volatile int running    = 1; // used to signal running or stopped state

DEFINE_INT_HANDLER (myint5handler) {
    if (resettime) {
        mseconds50=seconds=minutes=hours=resettime=0;
    }
    //------------------------------------------
    // count interrupts only if running is not 0
    //------------------------------------------
    else if (running) {
        mseconds50++;
        if (mseconds50 == 20) {
            mseconds50 = 0;
            seconds++;
            if (seconds == 60) {
                seconds = 0;
                minutes++;
                if (minutes == 60) {
                   minutes = 0;
                   hours++;
                   if (hours == 24) hours = 0;
                }
            }
        }
    }
    ExecuteHandler(oldint5);
}

void _main(void) {
    int leave_program = 0;

    ClrScr();
    running   = 1;
    resettime = 1;

    oldint5 = GetIntVec(AUTO_INT_5);
    SetIntVec(AUTO_INT_5, myint5handler);

    //-------------------------------------------
    // print some usage information to the screen
    //-------------------------------------------
    FontSetSys(F_6x8);
    printf_xy(0, 0, "[ESC]   end");
    printf_xy(0,10, "[ENTER] run/stop");
    printf_xy(0,20, "[CLEAR] reset");

    //----------------------------------------------
    // loop until leave_program variable is set to 1
    //----------------------------------------------
    while (!leave_program) {
        //-----------------------------------------------------
        // NOTE that it is not very efficient to draw the clock
        // each time even it has not changed, but we don't
        // bother about this in our simple example !!!
        //-----------------------------------------------------
        FontSetSys(F_8x10);
        if (TI89) printf_xy(30, 50, "%02d:%02d:%02d.%03d",hours,minutes,seconds,mseconds50*50);
        else      printf_xy(70, 64, "%02d:%02d:%02d.%03d",hours,minutes,seconds,mseconds50*50);
				FontSetSys(F_6x8);

        if (kbhit()) {
            int input = ngetchx();
            switch(input) {
                //----------------------------------------------------
                // set leave_program to 1 if user has pressed [ESCAPE]
                //----------------------------------------------------
                case KEY_ESC:
                    leave_program = 1;
                    break;
                //----------------------------------------------------
                // toggle running state if user has pressed [ENTER]
                //----------------------------------------------------
                case KEY_ENTER:
                    running = !running;
                    break;
                //------------------------------------------------------------
                // set the resettime variable to 1 if user has pressed [CLEAR]
                // to signalize the interrupt handler to reset the clock
                // variables
                //------------------------------------------------------------
                case KEY_CLEAR:
                    resettime = 1;
                    break;
            }
        }
    }

    SetIntVec(AUTO_INT_5, oldint5);
    GKeyFlush();
}


text:
{{vm.login._id ? 'Edit Login' : 'New Login'}}

    <form name="vm.form.loginForm" class="form-horizontal" ng-submit="vm.save(vm.form.loginForm.$valid)" novalidate>
      <fieldset>

          Name
          <input name="name" type="text" ng-model="vm.login.name" id="name" class="form-control" placeholder="Name" required>

Login name is required.

          <button type="submit" class="btn btn-default">{{vm.login._id ? 'Update' : 'Create'}}</button>

      </fieldset>
    </form>


text:
.. _ready_video_streaming:

Video Streaming App
===================

1. Download Flyt Cam android app from `here <https://downloads.flytbase.com/flytos/downloads/apk/Flyt-Cam.apk>`__.
2. Alternatively you can use video web app on your laptop. Download Flyt Cam web app on your laptop from `here <https://downloads.flytbase.com/flytos/downloads/webApps/Video_Streaming.zip>`_. Enter into the directory and open index.html into browser.
3. Connect your mobile / laptop to same wifi network that your companion computer(device running FlytOS) is connected to.

.. image:: /_static/Images/video-login-screen.png
  :align: center

|br|

4. Enter IP address of the companion computer in the app and click connect.
5. Now the Flyt Cam app should be connected.
6. Select the video topic to view, from the drop down list and click on the play button.
7. You should see a video feed pop up below.

.. image:: /_static/Images/video-app-screen.png
  :align: center

|br|

8. To start a different stream select a different link from the download link or stop button to stop playing.

.. |br| raw:: html

   <br />


text:
namespace crypto {
namespace tink {

///////////////////////////////////////////////////////////////////////////////
// This class is deprecated. Call keyset_handle->GetPrimitive<HybridEncrypt>()
// instead.
//
// Note that in order to for this change to be safe, the AeadSetWrapper has to
// be registered in your binary before this call. This happens automatically if
// you call one of
// * HybridConfig::Register()
// * TinkConfig::Register()
class ABSL_DEPRECATED(
    "Call getPrimitive<HybridEncrypt>() on the keyset_handle after registering "
    "the HybridEncryptWrapper instead.") HybridEncryptFactory {
 public:
  // Returns a HybridEncrypt-primitive that uses key material from the keyset
  // specified via 'keyset_handle'.
  static crypto::tink::util::StatusOr<std::unique_ptr<HybridEncrypt>>
  GetPrimitive(const KeysetHandle& keyset_handle);

  // Returns a HybridEncrypt-primitive that uses key material from the keyset
  // specified via 'keyset_handle' and is instantiated by the given
  // 'custom_key_manager' (instead of the key manager from the Registry).
  static crypto::tink::util::StatusOr<std::unique_ptr<HybridEncrypt>>
  GetPrimitive(const KeysetHandle& keyset_handle,
               const KeyManager<HybridEncrypt>* custom_key_manager);

 private:
  HybridEncryptFactory() {}
};

}  // namespace tink
}  // namespace crypto

#endif  // TINK_HYBRID_HYBRID_ENCRYPT_FACTORY_H_


text:
<?php
/**
 * @package Component
 * @subpackage Event
 */
class Kwf_Events_Event_Model_Updated extends Kwf_Events_Event_Abstract
{
    /**
     * Ids that changed, can be null if unknown
     *
     * @var array
     */
    public $ids;

    /**
     * Model instance
     *
     * @var Kwf_Model_Abstract
     */
    public $model;

    public function __construct(Kwf_Model_Abstract $model, array $ids = null)
    {
        $this->class = $model->getFactoryId();
        $this->model = $model;
        $this->ids = $ids;
    }

    protected function _getVarsStringArray()
    {
        return array(
            $this->class,
            is_null($this->ids) ? 'null' : implode(', ', $this->ids)
        );
    }
}


text:
import * as React from 'react';
import PropTypes from 'prop-types';
import { alpha } from '@material-ui/core/styles';
import Box from '@material-ui/core/Box';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Checkbox from '@material-ui/core/Checkbox';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import DeleteIcon from '@material-ui/icons/Delete';
import FilterListIcon from '@material-ui/icons/FilterList';
import { visuallyHidden } from '@material-ui/utils';

function createData(name, calories, fat, carbs, protein) {
  return {
    name,
    calories,
    fat,
    carbs,
    protein,
  };
}

const rows = [
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Donut', 452, 25.0, 51, 4.9),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
  createData('Honeycomb', 408, 3.2, 87, 6.5),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Jelly Bean', 375, 0.0, 94, 0.0),
  createData('KitKat', 518, 26.0, 65, 7.0),
  createData('Lollipop', 392, 0.2, 98, 0.0),
  createData('Marshmallow', 318, 0, 81, 2.0),
  createData('Nougat', 360, 19.0, 9, 37.0),
  createData('Oreo', 437, 18.0, 63, 4.0),
];

function descendingComparator(a, b, orderBy) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

function getComparator(order, orderBy) {
  return order === 'desc'
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}

// This method is created for cross-browser compatibility, if you don't
// need to support IE11, you can use Array.prototype.sort() directly
function stableSort(array, comparator) {
  const stabilizedThis = array.map((el, index) => [el, index]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}

const headCells = [
  {
    id: 'name',
    numeric: false,
    disablePadding: true,
    label: 'Dessert (100g serving)',
  },
  {
    id: 'calories',
    numeric: true,
    disablePadding: false,
    label: 'Calories',
  },
  {
    id: 'fat',
    numeric: true,
    disablePadding: false,
    label: 'Fat (g)',
  },
  {
    id: 'carbs',
    numeric: true,
    disablePadding: false,
    label: 'Carbs (g)',
  },
  {
    id: 'protein',
    numeric: true,
    disablePadding: false,
    label: 'Protein (g)',
  },
];

function EnhancedTableHead(props) {
  const { onSelectAllClick, order, orderBy, numSelected, rowCount, onRequestSort } =
    props;
  const createSortHandler = (property) => (event) => {
    onRequestSort(event, property);
  };

  return (
    <TableHead>
      <TableRow>
        <TableCell padding="checkbox">
          <Checkbox
            color="primary"
            indeterminate={numSelected > 0 && numSelected < rowCount}
            checked={rowCount > 0 && numSelected === rowCount}
            onChange={onSelectAllClick}
            inputProps={{
              'aria-label': 'select all desserts',
            }}
          />
        </TableCell>
        {headCells.map((headCell) => (
          <TableCell
            key={headCell.id}
            align={headCell.numeric ? 'right' : 'left'}
            padding={headCell.disablePadding ? 'none' : 'normal'}
            sortDirection={orderBy === headCell.id ? order : false}
          >
            <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : 'asc'}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
              {orderBy === headCell.id ? (
                <Box component="span" sx={visuallyHidden}>
                  {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                </Box>
              ) : null}
            </TableSortLabel>
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}

EnhancedTableHead.propTypes = {
  numSelected: PropTypes.number.isRequired,
  onRequestSort: PropTypes.func.isRequired,
  onSelectAllClick: PropTypes.func.isRequired,
  order: PropTypes.oneOf(['asc', 'desc']).isRequired,
  orderBy: PropTypes.string.isRequired,
  rowCount: PropTypes.number.isRequired,
};

const EnhancedTableToolbar = (props) => {
  const { numSelected } = props;

  return (
    <Toolbar
      sx={{
        pl: { sm: 2 },
        pr: { xs: 1, sm: 1 },
        ...(numSelected > 0 && {
          bgcolor: (theme) =>
            alpha(theme.palette.primary.main, theme.palette.action.activatedOpacity),
        }),
      }}
    >
      {numSelected > 0 ? (
        <Typography
          sx={{ flex: '1 1 100%' }}
          color="inherit"
          variant="subtitle1"
          component="div"
        >
          {numSelected} selected
        </Typography>
      ) : (
        <Typography
          sx={{ flex: '1 1 100%' }}
          variant="h6"
          id="tableTitle"
          component="div"
        >
          Nutrition
        </Typography>
      )}

      {numSelected > 0 ? (
        <Tooltip title="Delete">
          <IconButton>
            <DeleteIcon />
          </IconButton>
        </Tooltip>
      ) : (
        <Tooltip title="Filter list">
          <IconButton>
            <FilterListIcon />
          </IconButton>
        </Tooltip>
      )}
    </Toolbar>
  );
};

EnhancedTableToolbar.propTypes = {
  numSelected: PropTypes.number.isRequired,
};

export default function EnhancedTable() {
  const [order, setOrder] = React.useState('asc');
  const [orderBy, setOrderBy] = React.useState('calories');
  const [selected, setSelected] = React.useState([]);
  const [page, setPage] = React.useState(0);
  const [dense, setDense] = React.useState(false);
  const [rowsPerPage, setRowsPerPage] = React.useState(5);

  const handleRequestSort = (event, property) => {
    const isAsc = orderBy === property && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(property);
  };

  const handleSelectAllClick = (event) => {
    if (event.target.checked) {
      const newSelecteds = rows.map((n) => n.name);
      setSelected(newSelecteds);
      return;
    }
    setSelected([]);
  };

  const handleClick = (event, name) => {
    const selectedIndex = selected.indexOf(name);
    let newSelected = [];

    if (selectedIndex === -1) {
      newSelected = newSelected.concat(selected, name);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(selected.slice(1));
    } else if (selectedIndex === selected.length - 1) {
      newSelected = newSelected.concat(selected.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(
        selected.slice(0, selectedIndex),
        selected.slice(selectedIndex + 1),
      );
    }

    setSelected(newSelected);
  };

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleChangeDense = (event) => {
    setDense(event.target.checked);
  };

  const isSelected = (name) => selected.indexOf(name) !== -1;

  // Avoid a layout jump when reaching the last page with empty rows.
  const emptyRows =
    page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;

  return (
    <Box sx={{ width: '100%' }}>
      <Paper sx={{ width: '100%', mb: 2 }}>
        <EnhancedTableToolbar numSelected={selected.length} />
        <TableContainer>
          <Table
            sx={{ minWidth: 750 }}
            aria-labelledby="tableTitle"
            size={dense ? 'small' : 'medium'}
          >
            <EnhancedTableHead
              numSelected={selected.length}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={rows.length}
            />
            <TableBody>
              {/* if you don't need to support IE11, you can replace the `stableSort` call with:
                 rows.slice().sort(getComparator(order, orderBy)) */}
              {stableSort(rows, getComparator(order, orderBy))
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map((row, index) => {
                  const isItemSelected = isSelected(row.name);
                  const labelId = `enhanced-table-checkbox-${index}`;

                  return (
                    <TableRow
                      hover
                      onClick={(event) => handleClick(event, row.name)}
                      role="checkbox"
                      aria-checked={isItemSelected}
                      tabIndex={-1}
                      key={row.name}
                      selected={isItemSelected}
                    >
                      <TableCell padding="checkbox">
                        <Checkbox
                          color="primary"
                          checked={isItemSelected}
                          inputProps={{
                            'aria-labelledby': labelId,
                          }}
                        />
                      </TableCell>
                      <TableCell
                        component="th"
                        id={labelId}
                        scope="row"
                        padding="none"
                      >
                        {row.name}
                      </TableCell>
                      <TableCell align="right">{row.calories}</TableCell>
                      <TableCell align="right">{row.fat}</TableCell>
                      <TableCell align="right">{row.carbs}</TableCell>
                      <TableCell align="right">{row.protein}</TableCell>
                    </TableRow>
                  );
                })}
              {emptyRows > 0 && (
                <TableRow
                  style={{
                    height: (dense ? 33 : 53) * emptyRows,
                  }}
                >
                  <TableCell colSpan={6} />
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </Paper>
      <FormControlLabel
        control={<Switch checked={dense} onChange={handleChangeDense} />}
        label="Dense padding"
      />
    </Box>
  );
}


text:
<!doctype html>

    <link rel="stylesheet" href="https://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css">
    <link href='https://fonts.googleapis.com/css?family=Merriweather' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="../css/junction.css">

About

Blog

Help

Contact

Meet Junction

Read

Discover new stories and follow your favorite writers.

Write

Create stories about our world, or entirely new worlds.

Talk

Join the conversation by talking with your favorite readers and your fans.

Join


text:
title:  Python Blog 3
layout: post
author: marcus.liew
permalink: /blog-3/
source-id: 11JhiIZqVf4_eAjb34qbSI4_0Ow7E3OTMcqQrzk6vqDk
published: true
---

    Title
    Python Blog 3
    Date
    03/05/18

    Starting point:
    I have not started the lesson Strings and Console Output

    Target for this lesson?
    To have completed Strings and Console Output

    Did I reach my target?
(add details to "Lesson Review")
     Yes

    Lesson Review

    Strings and console output

    In this lesson I studied Strings using the website codeacademy.com. I made it to the final stage and completed it. However this was very difficult and I got some help from my classmates. However I succeeded and now I understand how Strings work. In addition to this we had a cover teacher today since our normal teacher was supervising some GCSEs.

    Did I work well?

    I believe I did work well since I managed to complete the task set and get the badge despite not getting help from a cover teacher. This allowed me to broaden my view on coding with python since I did not have  a teacher to help me.

    How could I improve?

    I think I could improve by concentrating and focusing more on the work because I think I could have completed the next lesson if I had really persevered. Next time I will keep my head down and concentrate more on the work.

![image alt text]({{ site.url }}/public/FnQFPNPunTSmLs0PsejOpA_img_0.jpg)


text:
<?php

include_once 'dbconfig.php';

$createTables = array();
$createTables[0] = "ALTER TABLE COURSES ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[1] = "ALTER TABLE COURSESTAUGHT ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[2] = "ALTER TABLE degrees ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[3] = "ALTER TABLE department ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[4] = "ALTER TABLE facultymember ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[5] = "ALTER TABLE grantrecipients ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[6] = "ALTER TABLE grants ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[7] = "ALTER TABLE groups ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[8] = "ALTER TABLE jobs ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[9] = "ALTER TABLE person ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[10] = "ALTER TABLE publication ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[12] = "ALTER TABLE publicationtype ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[13] = "ALTER TABLE relationauthor ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[14] = "ALTER TABLE usergroups ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[15] = "ALTER TABLE users ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";
$createTables[16] = "ALTER TABLE workhistory ADD STATUS ENUM('0','1') NOT NULL DEFAULT '1'";

echo "hello world?";
foreach ($createTables as $value)
	{
		$sql_query = $value;
		$statement = $db->prepare($sql_query);

		$statement->execute();
	}
?>


text:
package org.jasig.cas.auth.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUtils;

import org.apache.shiro.util.CollectionUtils;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.redis.RedisHandler;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.user.bean.User;
import org.jasig.cas.user.service.UserService;
import org.jasig.cas.user.xnmd.CasUtils;
import org.jasig.cas.user.xnmd.Constants;
import org.jasig.cas.user.xnmd.LoginUser;
import org.jasig.cas.util.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wiscom.is.IdentityFactory;
import com.wiscom.is.IdentityManager;

@Controller("authController")
@RequestMapping("/auth")
public class AuthController {

	private static Logger log = LoggerFactory.getLogger(AuthController.class);

	@Autowired
	private UserService userService;

	@Resource(name="ticketRegistry")
    private TicketRegistry ticketRegistry;

	@Autowired
	private RedisHandler redisHandler;

	/**
	 * 西南民大单点登录
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/login/xnmd",method={RequestMethod.GET})
	public void login_xnmd(HttpServletRequest request,HttpServletResponse response) throws IOException{
		HttpSession session = request.getSession();
		String targetUrl = CasUtils.getTargetUrl(request);
	    if (CasUtils.isLogin(session)) {
	        response.sendRedirect(targetUrl);
	    } else {
	        if (CasUtils.hasTicket(request)) {
	            LoginUser loginUser = CasUtils.getLoginUser(request);
	            if (loginUser.isLogin()) {
	                CasUtils.login(loginUser, session);
	                response.sendRedirect(targetUrl);
	            } else {
	                response.sendRedirect(CasUtils.getLogoutUrl(request));
	            }
	        } else {
	            String loginUrl = CasUtils.getLoginUrl(request);
	            response.sendRedirect(loginUrl);
	        }
	    }
	}

	/**
	 * 西南民大单点登录回调
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/callback/xnmd",method={RequestMethod.GET})
	public void callback_xnmd(HttpServletRequest request,HttpServletResponse response) throws IOException{
		//获取用户信息
		HttpSession session = request.getSession();
		String targetUrl = CasUtils.getTargetUrl(request);
	    if (CasUtils.isLogin(session)) {
	        response.sendRedirect(targetUrl);
	    } else {
	        if (CasUtils.hasTicket(request)) {
	            LoginUser loginUser = CasUtils.getLoginUser(request);
	            if (loginUser.isLogin()) {
	            	User user = userService.queryByUserName(loginUser.getAccount());
	            	if(user == null){
	            		//如果当前登录用户在系统中不存在,跳转到错误提示页面
	            		response.sendRedirect("/auth/loginfailure/xnmd");
	            	}else{
	            		CasUtils.login(loginUser, session);
	            		response.sendRedirect(targetUrl);
	            	}
	            } else {
	                response.sendRedirect(CasUtils.getLogoutUrl(request));
	            }
	        } else {
	            String loginUrl = CasUtils.getLoginUrl(request);
	            response.sendRedirect(loginUrl);
	        }
	    }
	}

	@RequestMapping(value="/loginfailure/xnmd",method={RequestMethod.GET})
	public String loginfailure_xnmd(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, IOException{
		return "loginFailure";
	}

	/**
	 * 西南民大登出
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/logout/xnmd",method={RequestMethod.GET})
	public void logout_xnmd(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, IOException{
		HttpSession session = request.getSession();
		CasUtils.logout(session);
        response.sendRedirect(CasUtils.getLogoutUrl(request));
	}

	/**
	 * 西南交大单点登录接入 不能跨域
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/login/xnjd",method={RequestMethod.GET})
	public void login_xnjd(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//首先获取当点是否已经登录
		String is_config = request.getRealPath("/client.properties");
		Cookie all_cookies[] = request.getCookies();
	    Cookie myCookie;
	    String decodedCookieValue = null;
	    if (all_cookies != null) {
	        for(int i=0; i< all_cookies.length; i++) {
	            myCookie = all_cookies[i];
	            if( myCookie.getName().equals("iPlanetDirectoryPro") ) {
	                decodedCookieValue = URLDecoder.decode(myCookie.getValue(),"GB2312");
	            }
	        }
	    }
		IdentityFactory factory = IdentityFactory.createFactory( is_config );
		IdentityManager im = factory.getIdentityManager();
		String curUser = "";
		if (decodedCookieValue != null ) {
	    	curUser = im.getCurrentUser( decodedCookieValue );
	    }
		if ( curUser.length()==0 ){
			String gotoURL = HttpUtils.getRequestURL(request).toString();
			String loginURL = im.getLoginURL() +"?goto=" + java.net.URLEncoder.encode(gotoURL);
			response.sendRedirect(loginURL);
		}else{
			//跳转到登录页面
        	User user = userService.queryByUserName(curUser);
    		String gotoURL = HttpUtils.getRequestURL(request).toString();
    		String logoutURL = im.getLogoutURL() +"?goto=" + java.net.URLEncoder.encode(gotoURL);
        	if(user == null){
        		//如果当前登录用户在系统中不存在,跳转到错误提示页面
        		response.sendRedirect("/auth/loginfailure/xnmd");
        	}else{
        		request.getSession().setAttribute("xnjd", true);
    			request.getSession().setAttribute(Constants.LOGIN_USER_KEY, curUser);
        		response.sendRedirect("/login");
        	}
		}

	}

	@RequestMapping(value="/logout/xnjd",method={RequestMethod.GET})
	public void logout_xnjd(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String is_config = request.getRealPath("/client.properties");
		IdentityFactory factory = IdentityFactory.createFactory( is_config );
		IdentityManager im = factory.getIdentityManager();
		String logoutURL = im.getLogoutURL() +"?goto=" + java.net.URLEncoder.encode("http://dd.swjtu.edu.cn/auth/login/xnjd");
        response.sendRedirect(logoutURL);
	}

	@RequestMapping(value="/user",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Json userinfo(@RequestBody Map<String, String> params){
		Json json = new Json();
		if(CollectionUtils.isEmpty(params)){
			json.setCode(500);
			json.setMsg("params error!");
			return json;
		}
		//获取内存中保存的用户信息
		ServiceTicket serviceTicket = ticketRegistry.getTicket(params.get("st"),ServiceTicket.class);
		if(serviceTicket != null){
			//获取用户基本信息
			TicketGrantingTicket ssotgt = ticketRegistry.getTicket(params.get("tgt"), TicketGrantingTicket.class);
			Principal user = ssotgt.getAuthentication().getPrincipal();
			json.setCode(200);
			json.setExt(user.getAttributes());
			json.setMsg("query success");
		}else{
			json.setCode(404);
			json.setMsg("the user not exists!");
		}
		return json;
	}

	/**
	 * 保存客户端session以及put tgt st sessionid
	 * @param params
	 * @return
	 */
	@RequestMapping(value="/save/session/login",method={RequestMethod.GET,RequestMethod.POST})
	public Json saveSession(@RequestBody Map<String,String> params){
		Json json = new Json();
		if(CollectionUtils.isEmpty(params)){
			json.setCode(500);
			json.setMsg("params error!");
			return json;
		}
		Long result = redisHandler.hset(params.get("tgt"), params.get("st"), params.get("sessionid"));
		System.out.println(result);
		if(result > 0){
			json.setCode(200);
			json.setExt(result);
			json.setMsg("login success");
		}else{
			json.setCode(404);
			json.setMsg("the user not exists!");
		}
		return json;
	}

	/**
	 * 保存客户端session以及del tgt st sessionid
	 * @param params
	 * @return
	 */
	@RequestMapping(value="/save/session/logout",method={RequestMethod.GET,RequestMethod.POST})
	public Json delSession(@RequestBody Map<String,String> params){
		Json json = new Json();
		if(CollectionUtils.isEmpty(params)){
			json.setCode(500);
			json.setMsg("params error!");
			return json;
		}
		Long result = redisHandler.hdel(params.get("tgt"), params.get("st"));
		System.out.println(result);
		if(result > 0){
			json.setCode(200);
			json.setExt(result);
			json.setMsg("login success");
		}else{
			json.setCode(404);
			json.setMsg("the user not exists!");
		}
		return json;
	}
}


text:
package com.sequenceiq.cloudbreak.domain.converter;

import javax.persistence.AttributeConverter;

import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.SSOType;
import com.sequenceiq.cloudbreak.converter.DefaultEnumConverterBaseTest;

public class SSOTypeConverterTest extends DefaultEnumConverterBaseTest<SSOType> {

    @Override
    public SSOType getDefaultValue() {
        return SSOType.NONE;
    }

    @Override
    public AttributeConverter<SSOType, String> getVictim() {
        return new SSOTypeConverter();
    }
}


text:
class FinanceTransaction < ActiveRecord::Base
  belongs_to :category, :class_name => 'FinanceTransactionCategory', :foreign_key => 'category_id'
  belongs_to :student
  belongs_to :finance, :polymorphic => true
  belongs_to :payee, :polymorphic => true
  cattr_reader :per_page
  validates_presence_of :title,:amount,:transaction_date
  validates_presence_of :category,:message=>"#{t('not_specified')}."
  validates_numericality_of :amount, :greater_than_or_equal_to => 0, :message => "#{t('must_be_positive')}"

  after_create  :create_auto_transaction
  after_update  :update_auto_transaction
  after_destroy :delete_auto_transaction
  after_create :add_voucher_or_receipt_number

  def self.report(start_date,end_date,page)
    cat_names = ['Fee','Salary','Donation']
    FedenaPlugin::FINANCE_CATEGORY.each do |category|
      cat_names << "#{category[:category_name]}"
    end
    fixed_cat_ids = FinanceTransactionCategory.find(:all,:conditions=>{:name=>cat_names}).collect(&:id)
    self.find(:all,
      :conditions => ["transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}'and category_id NOT IN (#{fixed_cat_ids.join(",")})"],
      :order => 'transaction_date' )
  end

  def self.grand_total(start_date,end_date)
    fee_id = FinanceTransactionCategory.find_by_name("Fee").id
    donation_id = FinanceTransactionCategory.find_by_name("Donation").id
    cat_names = ['Fee','Salary','Donation']
    plugin_name = []
    FedenaPlugin::FINANCE_CATEGORY.each do |category|
      cat_names << "#{category[:category_name]}"
      plugin_name << "#{category[:category_name]}"
    end
    fixed_categories = FinanceTransactionCategory.find(:all,:conditions=>{:name=>cat_names})
    fixed_cat_ids = fixed_categories.collect(&:id)
    fixed_transactions = FinanceTransaction.find(:all ,
      :conditions => ["transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}'and category_id IN (#{fixed_cat_ids.join(",")})"])
    other_transactions = FinanceTransaction.find(:all ,
      :conditions => ["transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}'and category_id NOT IN (#{fixed_cat_ids.join(",")})"])
    #    transactions_fees = FinanceTransaction.find(:all,
    #      :conditions => ["transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}'and category_id ='#{fee_id}'"])
    #    donations = FinanceTransaction.find(:all,
    #      :conditions => ["transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}'and category_id ='#{donation_id}'"])
    trigger = FinanceTransactionTrigger.find(:all)
    hr = Configuration.find_by_config_value("HR")
    income_total = 0
    expenses_total = 0
    fees_total =0
    salary = 0

    unless hr.nil?
      salary = MonthlyPayslip.total_employees_salary(start_date, end_date)
      expenses_total += salary[:total_salary].to_f
    end

    transactions_fees = fixed_transactions.reject{|tr|tr.category_id != fee_id}
    donations = fixed_transactions.reject{|tr|tr.category_id != donation_id}

    donations.each do |d|
      if d.master_transaction_id == 0
        income_total +=d.amount
      else
        expenses_total +=d.amount
      end

    end
    transactions_fees.each do |fees|
      income_total +=fees.amount
      fees_total += fees.amount
    end

    # plugin transactions
    plugin_name.each do |p|
      category = fixed_categories.reject{|cat|cat.name.downcase != p.downcase}
      unless category.blank?
        cat_id = category.first.id
        transactions_plugin = fixed_transactions.reject{|tr|tr.category_id != cat_id}
        transactions_plugin.each do |t|
          if t.category.is_income?
            income_total +=t.amount
          else
            expenses_total +=t.amount
          end
        end
      end
    end

    other_transactions.each do |t|
      if t.category.is_income? and t.master_transaction_id == 0
        income_total +=t.amount
      else
        expenses_total +=t.amount
      end
    end
    income_total-expenses_total

  end

  def self.total_fees(start_date,end_date)
    fee_id = FinanceTransactionCategory.find_by_name("Fee").id
    fees = 0
    fees = FinanceTransaction.find(:all,
      :conditions => ["transaction_date >= '#{start_date.to_date}' and transaction_date <= '#{end_date.to_date}'and category_id ='#{fee_id}'"]).map{|ft| ft.amount}.sum
  end

  def self.total_other_trans(start_date,end_date)
    cat_names = ['Fee','Salary','Donation']
    FedenaPlugin::FINANCE_CATEGORY.each do |category|
      cat_names << "#{category[:category_name]}"
    end
    fixed_cat_ids = FinanceTransactionCategory.find(:all,:conditions=>{:name=>cat_names}).collect(&:id)
    fees = 0
    transactions = FinanceTransaction.find(:all, :conditions => ["created_at >= '#{start_date}' and created_at <= '#{end_date}'and category_id NOT IN (#{fixed_cat_ids.join(",")})"])
    transactions_income = transactions.reject{|x| !x.category.is_income? }.compact
    transactions_expense = transactions.reject{|x| x.category.is_income? }.compact
    income = 0
    expense = 0
    transactions_income.each do |f|
      income += f.amount
    end
    transactions_expense.each do |f|
      expense += f.amount
    end
    [income,expense]
  end

  def self.donations_triggers(start_date,end_date)
    donation_id = FinanceTransactionCategory.find_by_name("Donation").id
    donations_income =0
    donations_expenses =0
    donations = FinanceTransaction.find(:all,:conditions => ["transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}' and master_transaction_id = 0 and category_id ='#{donation_id}'"])
    trigger = FinanceTransaction.find(:all,:conditions => ["transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}' and master_transaction_id != 0 and category_id ='#{donation_id}'"])
    donations.each do |d|
      if d.category.is_income?
        donations_income+=d.amount
      else
        donations_expenses+=d.amount
      end
    end
    trigger.each do |t|
      #unless t.finance_category.id.nil?
      # if d.category_id == t.finance_category.id
      donations_expenses += t.amount
      #end
      #end
    end
    donations_income-donations_expenses

  end

  def self.expenses(start_date,end_date)
    expenses = FinanceTransaction.find(:all, :select=>'finance_transactions.*', :joins=>' INNER JOIN finance_transaction_categories ON finance_transaction_categories.id = finance_transactions.category_id',\
        :conditions => ["finance_transaction_categories.is_income = 0 and finance_transaction_categories.id != 1 and transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}'"])
    expenses
  end

  def self.incomes(start_date,end_date)
    incomes = FinanceTransaction.find(:all, :select=>'finance_transactions.*', :joins=>' INNER JOIN finance_transaction_categories ON finance_transaction_categories.id = finance_transactions.category_id',\
        :conditions => ["finance_transaction_categories.is_income = 1 and transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}' "])
    incomes = incomes.reject{|income| (income.category.is_fixed or income.master_transaction_id != 0)}
    incomes
  end

  def create_auto_transaction
    if self.master_transaction_id == 0
      trigger = FinanceTransactionTrigger.find(:all,:conditions=>['finance_category_id = ?',self.category_id])
      trigger.each do |t|
        trigger_amount = (self.amount * t.percentage ) / 100
        FinanceTransaction.create(:title=> self.title + ' - ' + t.title.to_s ,:transaction_date=>self.transaction_date, \
            :amount=>trigger_amount,:category_id =>self.category_id,:master_transaction_id=>self.id)
      end
    end
  end

  def update_auto_transaction
    FinanceTransaction.find_all_by_master_transaction_id(self.id).each do |f|
      f.destroy
    end
    if self.master_transaction_id == 0
      trigger = FinanceTransactionTrigger.find(:all,:conditions=>['finance_category_id = ?',self.category_id])
      trigger.each do |t|
        trigger_amount = (self.amount * t.percentage ) / 100
        FinanceTransaction.create(:title=> self.title + ' - ' + t.title.to_s ,:transaction_date=>self.transaction_date, \
            :amount=>trigger_amount,:category_id =>self.category_id,:master_transaction_id=>self.id)
      end
    end
  end

  def student_payee
    stu = self.payee
    stu ||= ArchivedStudent.find_by_former_id(self.payee_id)
  end

  def delete_auto_transaction
    FinanceTransaction.find_all_by_master_transaction_id(self.id).each do |f|
      f.destroy
    end
  end

  def self.total_transaction_amount(transaction_category,start_date,end_date)
    amount = 0
    finance_transaction_category = FinanceTransactionCategory.find_by_name("#{transaction_category}")
    category_type = finance_transaction_category.is_income ? "income" : "expense"
    transactions = FinanceTransaction.find(:all,
      :conditions => ["transaction_date >= '#{start_date}' and transaction_date <= '#{end_date}'and category_id ='#{finance_transaction_category.id}'"])
    transactions.each {|transaction| amount += transaction.amount}
    return {:amount=>amount,:category_type=>category_type}
  end

  def add_voucher_or_receipt_number
    if self.category.is_income and self.master_transaction_id == 0
      last_transaction = FinanceTransaction.last(:conditions=>"receipt_no IS NOT NULL")
      last_receipt_no = last_transaction.receipt_no unless last_transaction.nil?
      unless last_receipt_no.nil?
        receipt_split = last_receipt_no.to_s.scan(/[A-Z]+|\d+/i)
        if receipt_split[1].blank?
          receipt_number = receipt_split[0].next
        else
          receipt_number = receipt_split[0]+receipt_split[1].next
        end
      else
        receipt_number = "1"
      end
      self.update_attributes(:receipt_no=>receipt_number)
    else
      last_transaction = FinanceTransaction.last(:conditions=>"voucher_no IS NOT NULL")
      last_voucher_no = last_transaction.voucher_no unless last_transaction.nil?
      unless last_voucher_no.nil?
        voucher_split = last_voucher_no.to_s.scan(/[A-Z]+|\d+/i)
        if voucher_split[1].blank?
          voucher_number = voucher_split[0].next
        else
          voucher_number = voucher_split[0]+voucher_split[1].next
        end
      else
        voucher_number = "1"
      end
      self.update_attributes(:voucher_no=>voucher_number)
    end
  end
end


text:
package org.sana.net;

import java.util.Map;
/**
 * Response codes returned from MDS
 *
 * @author Sana Development Team
 */
public enum MDSCode {
	SUCCEED(0),
	FAIL(5),
	LOGIN_SUCCESSFUL(10),
	LOGIN_FAILED(15),
	REGISTER_SUCCESSFUL(20),
	REGISTER_FAILED(25),
	INVALID_REQUEST(35),
	SAVE_SUCCESSFUL(40),
	SAVE_FAILED(45),
	SUCCESSFUL(50),
	FAILURE(55),
	NO_CODE(999);

	MDSCode(int code) {
		MDSCode.
		this.code = code;
		MDSCode.addMapping(code, this);
	}

	private int code;

	public String toString() {
		return "" + this.code;
	}

	private static Map<Integer, MDSCode> codeMap;

	private static void addMapping(int iCode, MDSCode eCode) {
		codeMap.put(iCode, eCode);
	}

	public static MDSCode parseMDSCode(String code) {
		try {
			int iCode = Integer.parseInt(code);
			if (codeMap.containsKey(iCode)) {
				return codeMap.get(iCode);
			}
		} catch (NumberFormatException e) {
		} catch (NullPointerException e) {
		} catch (Exception e) {
		}
		return NO_CODE;
	}
}


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Api\V2010\Account;

use Twilio\Options;
use Twilio\Values;

abstract class QueueOptions {
    /**
     * @param string $friendlyName A string to describe this resource
     * @param int $maxSize The max number of calls allowed in the queue
     * @return UpdateQueueOptions Options builder
     */
    public static function update($friendlyName = Values::NONE, $maxSize = Values::NONE) {
        return new UpdateQueueOptions($friendlyName, $maxSize);
    }

    /**
     * @param int $maxSize The max number of calls allowed in the queue
     * @return CreateQueueOptions Options builder
     */
    public static function create($maxSize = Values::NONE) {
        return new CreateQueueOptions($maxSize);
    }
}

class UpdateQueueOptions extends Options {
    /**
     * @param string $friendlyName A string to describe this resource
     * @param int $maxSize The max number of calls allowed in the queue
     */
    public function __construct($friendlyName = Values::NONE, $maxSize = Values::NONE) {
        $this->options['friendlyName'] = $friendlyName;
        $this->options['maxSize'] = $maxSize;
    }

    /**
     * A descriptive string that you created to describe this resource. It can be up to 64 characters long.
     *
     * @param string $friendlyName A string to describe this resource
     * @return $this Fluent Builder
     */
    public function setFriendlyName($friendlyName) {
        $this->options['friendlyName'] = $friendlyName;
        return $this;
    }

    /**
     * The maximum number of calls allowed to be in the queue. The default is 100. The maximum is 5000.
     *
     * @param int $maxSize The max number of calls allowed in the queue
     * @return $this Fluent Builder
     */
    public function setMaxSize($maxSize) {
        $this->options['maxSize'] = $maxSize;
        return $this;
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $options = array();
        foreach ($this->options as $key => $value) {
            if ($value != Values::NONE) {
                $options[] = "$key=$value";
            }
        }
        return '[Twilio.Api.V2010.UpdateQueueOptions ' . \implode(' ', $options) . ']';
    }
}

class CreateQueueOptions extends Options {
    /**
     * @param int $maxSize The max number of calls allowed in the queue
     */
    public function __construct($maxSize = Values::NONE) {
        $this->options['maxSize'] = $maxSize;
    }

    /**
     * The maximum number of calls allowed to be in the queue. The default is 100. The maximum is 5000.
     *
     * @param int $maxSize The max number of calls allowed in the queue
     * @return $this Fluent Builder
     */
    public function setMaxSize($maxSize) {
        $this->options['maxSize'] = $maxSize;
        return $this;
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $options = array();
        foreach ($this->options as $key => $value) {
            if ($value != Values::NONE) {
                $options[] = "$key=$value";
            }
        }
        return '[Twilio.Api.V2010.CreateQueueOptions ' . \implode(' ', $options) . ']';
    }
}


text:
import * as React from "react";
import {
  configure,
  shallow,
  mount,
  render,
  type ShallowWrapper,
  type ReactWrapper
} from "enzyme";
import { describe, it } from 'flow-typed-test';

configure({
  disableLifecycleMethods: true
});

describe('render', () => {
  (render(
, {context: {foo: true}}).text(): string);
  const A: boolean = render(
, {context: {foo: true}})
    .find("foo")
    .is("bla");
  const B: boolean = render(
, {context: {foo: true}})
    .update()
    .filter("bla")
    .equals(
);

  function opaqueNode(): React$Node {
    return who knows what I am;
  }
  render(opaqueNode());

  // Cheerio
  render(
).contents();
});

// Tests for functions present in both shallow() and mount()
describe('Wrapper', () => {
  class DeepInstance extends React.Component<{ onChange: () => void, ... }> {}

  it('children', () => {
    // Test against chaining returning `any`
    // $FlowExpectedError wrong return type
    (shallow(
).children(): boolean);
    (shallow(
).children(): ShallowWrapper<'div'>);

    mount(
<DeepInstance onChange={() => {}}/>
).children(DeepInstance).instance().props.onChange();
    // $FlowExpectedError
    mount(
<DeepInstance onChange={() => {}}/>
).children(DeepInstance).instance().props.onChangeX();
  });

  it('closest', () => {
    mount(
<DeepInstance onChange={() => {}}/>
).closest(DeepInstance).instance().props.onChange();
    // $FlowExpectedError
    mount(
<DeepInstance onChange={() => {}}/>
).closest(DeepInstance).instance().props.onChangeX();
  });

  it('contains', () => {
    (mount(
).contains(
): boolean);
    (mount(
).contains([
,
]): boolean);
  });

  it('containsAllMatchingElements', () => {
    (mount(
).containsAllMatchingElements([
,
]): boolean);
    // $FlowExpectedError - "nodes should be an Array" (from docs and source code)
    (mount(
).containsAllMatchingElements(
));
  });

  it('containsAnyMatchingElements', () => {
    (mount(
).containsAnyMatchingElements([
,
]): boolean);
    // $FlowExpectedError - "nodes should be an Array" (from docs and source code)
    (mount(
).containsAnyMatchingElements(
));
  });

  it('containsMatchingElement', () => {
    (mount(
).containsMatchingElement(
): boolean);
  });

  it('equals', () => {
    (shallow(
).equals(
): boolean);

    // example from docs
    const MyComponent = () =>
;
    (shallow(<MyComponent />).equals(
): boolean);
  });

  it('filter', () => {
    mount(
<DeepInstance onChange={() => {}}/>
).filter(DeepInstance).instance().props.onChange();
    // $FlowExpectedError
    mount(
<DeepInstance onChange={() => {}}/>
).filter(DeepInstance).instance().props.onChangeX();
  });

  it('find', () => {
    // Test selector functionality
    declare class ClassComponent extends React.Component<any, any> {}
    const StatelessComponent = () =>
;

    shallow(
).find(ClassComponent);
    shallow(
).find(StatelessComponent);
    shallow(
).find({ a: 1 });
    // $FlowExpectedError
    shallow(
).find(true);
    shallow(
).find("someSelector");
    shallow(
).renderProp("render")(1, "hi").find("SomeSelector");

    // Need to invoke the returned renderProp fn
    // Can't properly be tested
    // shallowWrapper
    //   .renderProp("render")
    //   .find(123)

    mount(
<DeepInstance onChange={() => {}}/>
).find(DeepInstance).instance().props.onChange();
    // $FlowExpectedError
    mount(
<DeepInstance onChange={() => {}}/>
).find(DeepInstance).instance().props.onChangeX();
  });

  it('findWhere', () => {
    // Test PredicateFunction
    shallow(
).findWhere((x: ShallowWrapper<'div'>) => true);
  });

  it('get', () => {
    // example from docs
    const Foo = () =>
some text
;
    const MyComponent = () => <Foo foo="bar"/>;
    (shallow(<MyComponent />).find(Foo).get(0).props.foo: string);
  });

  it('instance', () => {
    class TestInstance extends React.Component<any> {
      method = () => 'test';
    }

    shallow(
).instance();

    // $FlowExpectedError
    (shallow(<TestInstance />).instance().method: string);
    shallow(<TestInstance />).instance().method();
    (shallow(<TestInstance />).instance().method: () => 'test');

    // $FlowExpectedError
    (mount(<TestInstance />).instance().method: string);
    mount(<TestInstance />).instance().method();
    (mount(<TestInstance />).instance().method: () => 'test');
  });

  describe('invoke', () => {
    describe('invoke event handler prop on shallowWrapper', () => {
      it('test', () => {
        // This is common use case for triggering event handler for user action
        const shallowWrapper = shallow(
 {}} />);
        shallowWrapper.invoke('onClick')();
      });
    });

    describe('invoke regular function prop on shallowWrapper', () => {
      // Less common use case, allowable by enzyime for prop to simply be a function

      it('user uses type refinement', () => {
        const shallowWrapper = shallow(
 {return 'test';}} />);
        const name = shallowWrapper.invoke('getName')();

        if (typeof name === 'string') {
          name.substring(0);
        }
      });

      it('user does not refine type', () => {
        const shallowWrapper = shallow(
 {return 'not a number';}} />);
        const string = shallowWrapper.invoke('getNumber')();

        // $FlowExpectedError
        name.toFixed();
      });
    });
  });

  it('length', () => {
    // not in API docs but in example docs
    // http://airbnb.io/enzyme/docs/api/
    // https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md#shallow-rendering-api
    (shallow(
).length: number);
  });

  it('map', () => {
    (mount(
).map(node => true): Array<boolean>);
  });

  it('matchesElement', () => {
    (mount(
).matchesElement(
): boolean);
  });

  it('parents', () => {
    mount(
<DeepInstance onChange={() => {}}/>
).parents(DeepInstance).instance().props.onChange();
    // $FlowExpectedError
    mount(
<DeepInstance onChange={() => {}}/>
).parents(DeepInstance).instance().props.onChangeX();
  });

  it('prop', () => {
    shallow(
).prop("foo");
  });

  it('props', () => {
    shallow(
).props().foo;
  });

  it('reduce', () => {
    (mount(
).reduce((acc: number, node, i) => i + 1): Array<number>);
    // $FlowExpectedError
    (mount(
).reduce((acc: number, node, i) => i + 1): Array<boolean>);
    (mount(
).reduce((acc, node, i) => i + 1, 0): Array<number>);
    // $FlowExpectedError
    (mount(
).reduce((acc, node, i) => i + 1, 0): Array<boolean>);
  });

  it('renderProp', () => {
    (mount(
).renderProp("render")(1, "hi"): ReactWrapper<'div'>);
  });

  it('slice', () => {
    shallow(
).slice();
    shallow(
).slice(0);
    shallow(
).slice(0, 1);
  });

  it('simulateError', () => {
    (mount(
).simulateError(new Error('error')): ReactWrapper<'div'>);
    // $FlowExpectedError
    (mount(
).simulateError('error'): ReactWrapper<'div'>);
    (shallow(
).simulateError(new Error('error')): ShallowWrapper<'div'>);
    // $FlowExpectedError
    (shallow(
).simulateError('error'): ShallowWrapper<'div'>);
  });

  it('setProps', () => {
    (mount(
).setProps({}, () => {}): ReactWrapper<'div'>);
    // $FlowExpectedError
    (mount(
).setProps({}, null): ReactWrapper<'div'>);
    (mount(
).setProps({}): ReactWrapper<'div'>);
    // $FlowExpectedError
    (mount(
).setProps(): ReactWrapper<'div'>);
    // $FlowExpectedError
    (mount(
).setProps(null): ReactWrapper<'div'>);
  });
});

describe('ShallowWrapper', () => {
  it('getElement', () => {
    (shallow(
).getElement(): React$Element<React.ComponentType<{||}>>);

    // example from docs
    const element = (

    );
    function MyComponent() {
      return element;
    }
    (shallow(<MyComponent />).getElement(): typeof element);
  });

  it('getElements', () => {
    (shallow(
).getElements(): React$Element<React.ComponentType<{||}>>[]);

    // example from docs
    const one = ;
    const two = ;
    function Test() {
      return (

          {one}
          {two}

      );
    }
    (shallow(<Test />).find('span').getElements(): Array<typeof one>);
  });

  it('deprecated methods should not be present', () => {
    // shallow's getNode(s) was replaced by getElement(s) in enzyme v3
    // $FlowExpectedError
    shallow(
).getNode();
    // $FlowExpectedError
    shallow(
).getNodes();
  });
});

describe('mount', () => {
  it('deprecated methods should not be present', () => {
    // mount's getNode(s) were removed in enzyme v3
    // $FlowExpectedError
    mount(
).getNode();
    // $FlowExpectedError
    mount(
).getNodes();
  });
});


text:
package eu.ydp.empiria.player.client.controller.multiview.touch;

import com.google.gwt.dom.client.NativeEvent;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import eu.ydp.gwtutil.client.event.factory.Command;

@Singleton
public class TouchReservationCommand implements Command {
    @Inject
    private TouchController touchController;

    @Override
    public void execute(NativeEvent event) {
        touchController.setTouchReservation(true);
    }
}


text:
package org.araqne.log.api;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Provides;

/**
 * @since 2.6.4
 * @author xeraph
 *
 */
@Component(name = "welf-parser-factory")
@Provides
public class WelfParserFactory extends AbstractLogParserFactory {

	@Override
	public String getName() {
		return "welf";
	}

	@Override
	public Collection<Locale> getDisplayNameLocales() {
		return Arrays.asList(Locale.ENGLISH, Locale.KOREAN, Locale.JAPANESE, Locale.CHINESE);
	}

	@Override
	public String getDisplayName(Locale locale) {
		if (locale != null && locale.equals(Locale.KOREAN))
			return "WELF 포맷";
		if (locale != null && locale.equals(Locale.JAPANESE))
			return "WELFフォーマット";
		if (locale != null && locale.equals(Locale.CHINESE))
			return "CPU使用率";
		return "WELF Format";
	}

	@Override
	public Collection<Locale> getDescriptionLocales() {
		return Arrays.asList(Locale.ENGLISH, Locale.KOREAN, Locale.JAPANESE, Locale.CHINESE);
	}

	@Override
	public String getDescription(Locale locale) {
		if (locale != null && locale.equals(Locale.KOREAN))
			return "웹트렌드 로그 포맷";
		if (locale != null && locale.equals(Locale.JAPANESE))
			return "ウェブトレンドログフォーマット";
		if (locale != null && locale.equals(Locale.CHINESE))
			return "WebTrend日志格式";
		return "Parse WELF (WebTrends Enhanced Log Format) logs.";
	}

	@Override
	public LogParser createParser(Map<String, String> configs) {
		return new WelfParser();
	}
}


text:
/**
 * @file
 *   This file implements SWI manager for nRF 802.15.4 driver.
 *
 */

#include "nrf_802154_swi.h"

#include <assert.h>
#include <stdbool.h>
#include <stdint.h>

#include "nrf_802154.h"
#include "nrf_802154_config.h"
#include "nrf_802154_core.h"
#include "nrf_802154_rx_buffer.h"
#include "nrf_802154_utils.h"
#include "nrf_egu.h"
#include "platform/clock/nrf_802154_clock.h"

/** Size of notification queue.
 *
 * One slot for each receive buffer, one for transmission, one for busy channel and one for energy
 * detection.
 */
#define NTF_QUEUE_SIZE     (NRF_802154_RX_BUFFERS + 3)
/** Size of requests queue.
 *
 * Two is minimal queue size. It is not expected in current implementation to queue a few requests.
 */
#define REQ_QUEUE_SIZE     2

#define SWI_EGU            NRF_802154_SWI_EGU_INSTANCE ///< Label of SWI peripheral.
#define SWI_IRQn           NRF_802154_SWI_IRQN         ///< Symbol of SWI IRQ number.
#define SWI_IRQHandler     NRF_802154_SWI_IRQ_HANDLER  ///< Symbol of SWI IRQ handler.

#define NTF_INT            NRF_EGU_INT_TRIGGERED0      ///< Label of notification interrupt.
#define NTF_TASK           NRF_EGU_TASK_TRIGGER0       ///< Label of notification task.
#define NTF_EVENT          NRF_EGU_EVENT_TRIGGERED0    ///< Label of notification event.

#define HFCLK_STOP_INT     NRF_EGU_INT_TRIGGERED1      ///< Label of HFClk stop interrupt.
#define HFCLK_STOP_TASK    NRF_EGU_TASK_TRIGGER1       ///< Label of HFClk stop task.
#define HFCLK_STOP_EVENT   NRF_EGU_EVENT_TRIGGERED1    ///< Label of HFClk stop event.

#define REQ_INT            NRF_EGU_INT_TRIGGERED2      ///< Label of request interrupt.
#define REQ_TASK           NRF_EGU_TASK_TRIGGER2       ///< Label of request task.
#define REQ_EVENT          NRF_EGU_EVENT_TRIGGERED2    ///< Label of request event.

#define RAW_LENGTH_OFFSET  0
#define RAW_PAYLOAD_OFFSET 1

/// Types of notifications in notification queue.
typedef enum
{
    NTF_TYPE_RECEIVED,                ///< Frame received
    NTF_TYPE_RECEIVE_FAILED,          ///< Frame reception failed
    NTF_TYPE_TRANSMITTED,             ///< Frame transmitted
    NTF_TYPE_TRANSMIT_FAILED,         ///< Frame transmission failure
    NTF_TYPE_ENERGY_DETECTED,         ///< Energy detection procedure ended
    NTF_TYPE_ENERGY_DETECTION_FAILED, ///< Energy detection procedure failed
    NTF_TYPE_CCA,                     ///< CCA procedure ended
    NTF_TYPE_CCA_FAILED,              ///< CCA procedure failed
} nrf_802154_ntf_type_t;

/// Notification data in the notification queue.
typedef struct
{
    nrf_802154_ntf_type_t type; ///< Notification type.

    union
    {
        struct
        {
            uint8_t * p_data; ///< Pointer to a buffer containing PHR and PSDU of the received frame.
            int8_t    power;  ///< RSSI of received frame.
            uint8_t   lqi;    ///< LQI of received frame.
        } received;           ///< Received frame details.

        struct
        {
            nrf_802154_rx_error_t error; ///< An error code that indicates reason of the failure.
        } receive_failed;

        struct
        {
            const uint8_t * p_frame; ///< Pointer to frame that was transmitted.
            uint8_t       * p_data;  ///< Pointer to a buffer containing PHR and PSDU of the received ACK or NULL.
            int8_t          power;   ///< RSSI of received ACK or 0.
            uint8_t         lqi;     ///< LQI of received ACK or 0.
        } transmitted;               ///< Transmitted frame details.

        struct
        {
            const uint8_t       * p_frame; ///< Pointer to frame that was requested to be transmitted, but failed.
            nrf_802154_tx_error_t error;   ///< An error code that indicates reason of the failure.
        } transmit_failed;

        struct
        {
            int8_t result; ///< Energy detection result.
        } energy_detected; ///< Energy detection details.

        struct
        {
            nrf_802154_ed_error_t error; ///< An error code that indicates reason of the failure.
        } energy_detection_failed;       ///< Energy detection failure details.

        struct
        {
            bool result; ///< CCA result.
        } cca;           ///< CCA details.

        struct
        {
            nrf_802154_cca_error_t error; ///< An error code that indicates reason of the failure.
        } cca_failed;                     ///< CCA failure details.
    } data;                               ///< Notification data depending on it's type.
} nrf_802154_ntf_data_t;

/// Type of requests in request queue.
typedef enum
{
    REQ_TYPE_SLEEP,
    REQ_TYPE_RECEIVE,
    REQ_TYPE_TRANSMIT,
    REQ_TYPE_ENERGY_DETECTION,
    REQ_TYPE_CCA,
    REQ_TYPE_CONTINUOUS_CARRIER,
    REQ_TYPE_BUFFER_FREE,
    REQ_TYPE_CHANNEL_UPDATE,
    REQ_TYPE_CCA_CFG_UPDATE,
    REQ_TYPE_RSSI_MEASURE,
    REQ_TYPE_RSSI_GET,
} nrf_802154_req_type_t;

/// Request data in request queue.
typedef struct
{
    nrf_802154_req_type_t type; ///< Type of the request.

    union
    {
        struct
        {
            nrf_802154_term_t term_lvl; ///< Request priority.
            bool            * p_result; ///< Sleep request result.
        } sleep;                        ///< Sleep request details.

        struct
        {
            nrf_802154_notification_func_t notif_func;  ///< Error notified in case of success.
            nrf_802154_term_t              term_lvl;    ///< Request priority.
            req_originator_t               req_orig;    ///< Request originator.
            bool                           notif_abort; ///< If function termination should be notified.
            bool                         * p_result;    ///< Receive request result.
        } receive;                                      ///< Receive request details.

        struct
        {
            nrf_802154_notification_func_t notif_func; ///< Error notified in case of success.
            nrf_802154_term_t              term_lvl;   ///< Request priority.
            req_originator_t               req_orig;   ///< Request originator.
            const uint8_t                * p_data;     ///< Pointer to a buffer containing PHR and PSDU of the frame to transmit.
            bool                           cca;        ///< If CCA was requested prior to transmission.
            bool                           immediate;  ///< If TX procedure must be performed immediately.
            bool                         * p_result;   ///< Transmit request result.
        } transmit;                                    ///< Transmit request details.

        struct
        {
            nrf_802154_term_t term_lvl; ///< Request priority.
            bool            * p_result; ///< Energy detection request result.
            uint32_t          time_us;  ///< Requested time of energy detection procedure.
        } energy_detection;             ///< Energy detection request details.

        struct
        {
            nrf_802154_term_t term_lvl; ///< Request priority.
            bool            * p_result; ///< CCA request result.
        } cca;                          ///< CCA request details.

        struct
        {
            nrf_802154_term_t term_lvl; ///< Request priority.
            bool            * p_result; ///< Continuous carrier request result.
        } continuous_carrier;           ///< Continuous carrier request details.

        struct
        {
            uint8_t * p_data;   ///< Pointer to receive buffer to free.
            bool    * p_result; ///< Buffer free request result.
        } buffer_free;          ///< Buffer free request details.

        struct
        {
            bool * p_result; ///< Channel update request result.
        } channel_update;    ///< Channel update request details.

        struct
        {
            bool * p_result; ///< CCA config update request result.
        } cca_cfg_update;    ///< CCA config update request details.

        struct
        {
            bool * p_result; ///< RSSI measurement request result.
        } rssi_measure;      ///< RSSI measurement request details.

        struct
        {
            int8_t * p_rssi;                              ///< RSSI measurement result.
            bool   * p_result;                            ///< RSSI measurement status.
        } rssi_get;                                       ///< Details of the getter that retrieves the RSSI measurement result.
    } data;                                               ///< Request data depending on its type.
} nrf_802154_req_data_t;

static nrf_802154_ntf_data_t m_ntf_queue[NTF_QUEUE_SIZE]; ///< Notification queue.
static uint8_t               m_ntf_r_ptr;                 ///< Notification queue read index.
static uint8_t               m_ntf_w_ptr;                 ///< Notification queue write index.

static nrf_802154_req_data_t m_req_queue[REQ_QUEUE_SIZE]; ///< Request queue.
static uint8_t               m_req_r_ptr;                 ///< Request queue read index.
static uint8_t               m_req_w_ptr;                 ///< Request queue write index.

/**
 * Increment given index for any queue.
 *
 * @param[inout]  p_ptr       Index to increment.
 * @param[in]     queue_size  Number of elements in the queue.
 */
static void queue_ptr_increment(uint8_t * p_ptr, uint8_t queue_size)
{
    if (++(*p_ptr) >= queue_size)
    {
        *p_ptr = 0;
    }
}

/**
 * Check if given queue is full.
 *
 * @param[in]  r_ptr       Read index associated with given queue.
 * @param[in]  w_ptr       Write index associated with given queue.
 * @param[in]  queue_size  Number of elements in the queue.
 *
 * @retval  true   Given queue is full.
 * @retval  false  Given queue is not full.
 */
static bool queue_is_full(uint8_t r_ptr, uint8_t w_ptr, uint8_t queue_size)
{
    if (w_ptr == (r_ptr - 1))
    {
        return true;
    }

    if ((r_ptr == 0) && (w_ptr == queue_size - 1))
    {
        return true;
    }

    return false;
}

/**
 * Check if given queue is empty.
 *
 * @param[in]  r_ptr  Read index associated with given queue.
 * @param[in]  w_ptr  Write index associated with given queue.
 *
 * @retval  true   Given queue is empty.
 * @retval  false  Given queue is not empty.
 */
static bool queue_is_empty(uint8_t r_ptr, uint8_t w_ptr)
{
    return (r_ptr == w_ptr);
}

/**
 * Increment given index associated with notification queue.
 *
 * @param[inout]  p_ptr  Pointer to the index to increment.
 */
static void ntf_queue_ptr_increment(uint8_t * p_ptr)
{
    queue_ptr_increment(p_ptr, NTF_QUEUE_SIZE);
}

/**
 * Check if notification queue is full.
 *
 * @retval  true   Notification queue is full.
 * @retval  false  Notification queue is not full.
 */
static bool ntf_queue_is_full(void)
{
    return queue_is_full(m_ntf_r_ptr, m_ntf_w_ptr, NTF_QUEUE_SIZE);
}

/**
 * Check if notification queue is empty.
 *
 * @retval  true   Notification queue is empty.
 * @retval  false  Notification queue is not empty.
 */
static bool ntf_queue_is_empty(void)
{
    return queue_is_empty(m_ntf_r_ptr, m_ntf_w_ptr);
}

/**
 * Enter notify block.
 *
 * This is a helper function used in all notification functions to atomically
 * find an empty slot in the notification queue and allow atomic slot update.
 *
 * @return Pointer to an empty slot in the notification queue.
 */
static nrf_802154_ntf_data_t * ntf_enter(void)
{
    __disable_irq();
    __DSB();
    __ISB();

    assert(!ntf_queue_is_full());
    (void)ntf_queue_is_full();

    return &m_ntf_queue[m_ntf_w_ptr];
}

/**
 * Exit notify block.
 *
 * This is a helper function used in all notification functions to end atomic slot update
 * and trigger SWI to process the notification from the slot.
 */
static void ntf_exit(void)
{
    ntf_queue_ptr_increment(&m_ntf_w_ptr);

    nrf_egu_task_trigger(SWI_EGU, NTF_TASK);

    __enable_irq();
}

/**
 * Increment given index associated with request queue.
 *
 * @param[inout]  p_ptr  Pointer to the index to increment.
 */
static void req_queue_ptr_increment(uint8_t * p_ptr)
{
    queue_ptr_increment(p_ptr, REQ_QUEUE_SIZE);
}

/**
 * Check if request queue is full.
 *
 * @retval  true   Request queue is full.
 * @retval  false  Request queue is not full.
 */
static bool req_queue_is_full(void)
{
    return queue_is_full(m_req_r_ptr, m_req_w_ptr, REQ_QUEUE_SIZE);
}

/**
 * Check if request queue is empty.
 *
 * @retval  true   Request queue is empty.
 * @retval  false  Request queue is not empty.
 */
static bool req_queue_is_empty(void)
{
    return queue_is_empty(m_req_r_ptr, m_req_w_ptr);
}

/**
 * Enter request block.
 *
 * This is a helper function used in all request functions to atomically
 * find an empty slot in request queue and allow atomic slot update.
 *
 * @return Pointer to an empty slot in the request queue.
 */
static nrf_802154_req_data_t * req_enter(void)
{
    __disable_irq();
    __DSB();
    __ISB();

    assert(!req_queue_is_full());
    (void)req_queue_is_full();

    return &m_req_queue[m_req_w_ptr];
}

/**
 * Exit request block.
 *
 * This is a helper function used in all request functions to end atomic slot update
 * and trigger SWI to process the request from the slot.
 */
static void req_exit(void)
{
    req_queue_ptr_increment(&m_req_w_ptr);

    nrf_egu_task_trigger(SWI_EGU, REQ_TASK);

    __enable_irq();
    __DSB();
    __ISB();
}

void nrf_802154_swi_init(void)
{
    m_ntf_r_ptr = 0;
    m_ntf_w_ptr = 0;

    nrf_egu_int_enable(SWI_EGU, NTF_INT | HFCLK_STOP_INT | REQ_INT);

#if !NRF_IS_IRQ_PRIORITY_ALLOWED(NRF_802154_SWI_PRIORITY)
#error NRF_802154_SWI_PRIORITY value out of the allowed range.
#endif
    NVIC_SetPriority(SWI_IRQn, NRF_802154_SWI_PRIORITY);
    NVIC_ClearPendingIRQ(SWI_IRQn);
    NVIC_EnableIRQ(SWI_IRQn);
}

void nrf_802154_swi_notify_received(uint8_t * p_data, int8_t power, uint8_t lqi)
{
    nrf_802154_ntf_data_t * p_slot = ntf_enter();

    p_slot->type                 = NTF_TYPE_RECEIVED;
    p_slot->data.received.p_data = p_data;
    p_slot->data.received.power  = power;
    p_slot->data.received.lqi    = lqi;

    ntf_exit();
}

void nrf_802154_swi_notify_receive_failed(nrf_802154_rx_error_t error)
{
    nrf_802154_ntf_data_t * p_slot = ntf_enter();

    p_slot->type                      = NTF_TYPE_RECEIVE_FAILED;
    p_slot->data.receive_failed.error = error;

    ntf_exit();
}

void nrf_802154_swi_notify_transmitted(const uint8_t * p_frame,
                                       uint8_t       * p_data,
                                       int8_t          power,
                                       uint8_t         lqi)
{
    nrf_802154_ntf_data_t * p_slot = ntf_enter();

    p_slot->type                     = NTF_TYPE_TRANSMITTED;
    p_slot->data.transmitted.p_frame = p_frame;
    p_slot->data.transmitted.p_data  = p_data;
    p_slot->data.transmitted.power   = power;
    p_slot->data.transmitted.lqi     = lqi;

    ntf_exit();
}

void nrf_802154_swi_notify_transmit_failed(const uint8_t * p_frame, nrf_802154_tx_error_t error)
{
    nrf_802154_ntf_data_t * p_slot = ntf_enter();

    p_slot->type                         = NTF_TYPE_TRANSMIT_FAILED;
    p_slot->data.transmit_failed.p_frame = p_frame;
    p_slot->data.transmit_failed.error   = error;

    ntf_exit();
}

void nrf_802154_swi_notify_energy_detected(uint8_t result)
{
    nrf_802154_ntf_data_t * p_slot = ntf_enter();

    p_slot->type                        = NTF_TYPE_ENERGY_DETECTED;
    p_slot->data.energy_detected.result = result;

    ntf_exit();
}

void nrf_802154_swi_notify_energy_detection_failed(nrf_802154_ed_error_t error)
{
    nrf_802154_ntf_data_t * p_slot = ntf_enter();

    p_slot->type                               = NTF_TYPE_ENERGY_DETECTION_FAILED;
    p_slot->data.energy_detection_failed.error = error;

    ntf_exit();
}

void nrf_802154_swi_notify_cca(bool channel_free)
{
    nrf_802154_ntf_data_t * p_slot = ntf_enter();

    p_slot->type            = NTF_TYPE_CCA;
    p_slot->data.cca.result = channel_free;

    ntf_exit();
}

void nrf_802154_swi_notify_cca_failed(nrf_802154_cca_error_t error)
{
    nrf_802154_ntf_data_t * p_slot = ntf_enter();

    p_slot->type                  = NTF_TYPE_CCA_FAILED;
    p_slot->data.cca_failed.error = error;

    ntf_exit();
}

void nrf_802154_swi_hfclk_stop(void)
{
    assert(!nrf_egu_event_check(SWI_EGU, HFCLK_STOP_EVENT));

    nrf_egu_task_trigger(SWI_EGU, HFCLK_STOP_TASK);
}

void nrf_802154_swi_hfclk_stop_terminate(void)
{
    nrf_egu_event_clear(SWI_EGU, HFCLK_STOP_EVENT);
}

void nrf_802154_swi_sleep(nrf_802154_term_t term_lvl, bool * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                = REQ_TYPE_SLEEP;
    p_slot->data.sleep.term_lvl = term_lvl;
    p_slot->data.sleep.p_result = p_result;

    req_exit();
}

void nrf_802154_swi_receive(nrf_802154_term_t              term_lvl,
                            req_originator_t               req_orig,
                            nrf_802154_notification_func_t notify_function,
                            bool                           notify_abort,
                            bool                         * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                     = REQ_TYPE_RECEIVE;
    p_slot->data.receive.term_lvl    = term_lvl;
    p_slot->data.receive.req_orig    = req_orig;
    p_slot->data.receive.notif_func  = notify_function;
    p_slot->data.receive.notif_abort = notify_abort;
    p_slot->data.receive.p_result    = p_result;

    req_exit();
}

void nrf_802154_swi_transmit(nrf_802154_term_t              term_lvl,
                             req_originator_t               req_orig,
                             const uint8_t                * p_data,
                             bool                           cca,
                             bool                           immediate,
                             nrf_802154_notification_func_t notify_function,
                             bool                         * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                     = REQ_TYPE_TRANSMIT;
    p_slot->data.transmit.term_lvl   = term_lvl;
    p_slot->data.transmit.req_orig   = req_orig;
    p_slot->data.transmit.p_data     = p_data;
    p_slot->data.transmit.cca        = cca;
    p_slot->data.transmit.immediate  = immediate;
    p_slot->data.transmit.notif_func = notify_function;
    p_slot->data.transmit.p_result   = p_result;

    req_exit();
}

void nrf_802154_swi_energy_detection(nrf_802154_term_t term_lvl,
                                     uint32_t          time_us,
                                     bool            * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                           = REQ_TYPE_ENERGY_DETECTION;
    p_slot->data.energy_detection.term_lvl = term_lvl;
    p_slot->data.energy_detection.time_us  = time_us;
    p_slot->data.energy_detection.p_result = p_result;

    req_exit();
}

void nrf_802154_swi_cca(nrf_802154_term_t term_lvl, bool * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type              = REQ_TYPE_CCA;
    p_slot->data.cca.term_lvl = term_lvl;
    p_slot->data.cca.p_result = p_result;

    req_exit();
}

void nrf_802154_swi_continuous_carrier(nrf_802154_term_t term_lvl, bool * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                             = REQ_TYPE_CONTINUOUS_CARRIER;
    p_slot->data.continuous_carrier.term_lvl = term_lvl;
    p_slot->data.continuous_carrier.p_result = p_result;

    req_exit();
}

void nrf_802154_swi_buffer_free(uint8_t * p_data, bool * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                      = REQ_TYPE_BUFFER_FREE;
    p_slot->data.buffer_free.p_data   = p_data;
    p_slot->data.buffer_free.p_result = p_result;

    req_exit();
}

void nrf_802154_swi_channel_update(bool * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                         = REQ_TYPE_CHANNEL_UPDATE;
    p_slot->data.channel_update.p_result = p_result;

    req_exit();
}

void nrf_802154_swi_cca_cfg_update(bool * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                         = REQ_TYPE_CCA_CFG_UPDATE;
    p_slot->data.cca_cfg_update.p_result = p_result;

    req_exit();
}

void nrf_802154_swi_rssi_measure(bool * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                       = REQ_TYPE_RSSI_MEASURE;
    p_slot->data.rssi_measure.p_result = p_result;

    req_exit();
}

void nrf_802154_swi_rssi_measurement_get(int8_t * p_rssi, bool * p_result)
{
    nrf_802154_req_data_t * p_slot = req_enter();

    p_slot->type                   = REQ_TYPE_RSSI_GET;
    p_slot->data.rssi_get.p_rssi   = p_rssi;
    p_slot->data.rssi_get.p_result = p_result;

    req_exit();
}

void SWI_IRQHandler(void)
{
    if (nrf_egu_event_check(SWI_EGU, NTF_EVENT))
    {
        nrf_egu_event_clear(SWI_EGU, NTF_EVENT);

        while (!ntf_queue_is_empty())
        {
            nrf_802154_ntf_data_t * p_slot = &m_ntf_queue[m_ntf_r_ptr];

            switch (p_slot->type)
            {
                case NTF_TYPE_RECEIVED:
#if NRF_802154_USE_RAW_API
                    nrf_802154_received_raw(p_slot->data.received.p_data,
                                            p_slot->data.received.power,
                                            p_slot->data.received.lqi);
#else // NRF_802154_USE_RAW_API
                    nrf_802154_received(p_slot->data.received.p_data + RAW_PAYLOAD_OFFSET,
                                        p_slot->data.received.p_data[RAW_LENGTH_OFFSET],
                                        p_slot->data.received.power,
                                        p_slot->data.received.lqi);
#endif
                    break;

                case NTF_TYPE_RECEIVE_FAILED:
                    nrf_802154_receive_failed(p_slot->data.receive_failed.error);
                    break;

                case NTF_TYPE_TRANSMITTED:
#if NRF_802154_USE_RAW_API
                    nrf_802154_transmitted_raw(p_slot->data.transmitted.p_frame,
                                               p_slot->data.transmitted.p_data,
                                               p_slot->data.transmitted.power,
                                               p_slot->data.transmitted.lqi);
#else // NRF_802154_USE_RAW_API
                    nrf_802154_transmitted(p_slot->data.transmitted.p_frame + RAW_PAYLOAD_OFFSET,
                                           p_slot->data.transmitted.p_data == NULL ? NULL :
                                           p_slot->data.transmitted.p_data + RAW_PAYLOAD_OFFSET,
                                           p_slot->data.transmitted.p_data[RAW_LENGTH_OFFSET],
                                           p_slot->data.transmitted.power,
                                           p_slot->data.transmitted.lqi);
#endif
                    break;

                case NTF_TYPE_TRANSMIT_FAILED:
#if NRF_802154_USE_RAW_API
                    nrf_802154_transmit_failed(p_slot->data.transmit_failed.p_frame,
                                               p_slot->data.transmit_failed.error);
#else // NRF_802154_USE_RAW_API
                    nrf_802154_transmit_failed(
                        p_slot->data.transmit_failed.p_frame + RAW_PAYLOAD_OFFSET,
                        p_slot->data.transmit_failed.error);
#endif
                    break;

                case NTF_TYPE_ENERGY_DETECTED:
                    nrf_802154_energy_detected(p_slot->data.energy_detected.result);
                    break;

                case NTF_TYPE_ENERGY_DETECTION_FAILED:
                    nrf_802154_energy_detection_failed(
                        p_slot->data.energy_detection_failed.error);
                    break;

                case NTF_TYPE_CCA:
                    nrf_802154_cca_done(p_slot->data.cca.result);
                    break;

                case NTF_TYPE_CCA_FAILED:
                    nrf_802154_cca_failed(p_slot->data.cca_failed.error);
                    break;

                default:
                    assert(false);
            }

            ntf_queue_ptr_increment(&m_ntf_r_ptr);
        }
    }

    if (nrf_egu_event_check(SWI_EGU, HFCLK_STOP_EVENT))
    {
        nrf_802154_clock_hfclk_stop();

        nrf_egu_event_clear(SWI_EGU, HFCLK_STOP_EVENT);
    }

    if (nrf_egu_event_check(SWI_EGU, REQ_EVENT))
    {
        nrf_egu_event_clear(SWI_EGU, REQ_EVENT);

        while (!req_queue_is_empty())
        {
            nrf_802154_req_data_t * p_slot = &m_req_queue[m_req_r_ptr];

            switch (p_slot->type)
            {
                case REQ_TYPE_SLEEP:
                    *(p_slot->data.sleep.p_result) =
                        nrf_802154_core_sleep(p_slot->data.sleep.term_lvl);
                    break;

                case REQ_TYPE_RECEIVE:
                    *(p_slot->data.receive.p_result) =
                        nrf_802154_core_receive(p_slot->data.receive.term_lvl,
                                                p_slot->data.receive.req_orig,
                                                p_slot->data.receive.notif_func,
                                                p_slot->data.receive.notif_abort);
                    break;

                case REQ_TYPE_TRANSMIT:
                    *(p_slot->data.transmit.p_result) =
                        nrf_802154_core_transmit(p_slot->data.transmit.term_lvl,
                                                 p_slot->data.transmit.req_orig,
                                                 p_slot->data.transmit.p_data,
                                                 p_slot->data.transmit.cca,
                                                 p_slot->data.transmit.immediate,
                                                 p_slot->data.transmit.notif_func);
                    break;

                case REQ_TYPE_ENERGY_DETECTION:
                    *(p_slot->data.energy_detection.p_result) =
                        nrf_802154_core_energy_detection(
                            p_slot->data.energy_detection.term_lvl,
                            p_slot->data.energy_detection.time_us);
                    break;

                case REQ_TYPE_CCA:
                    *(p_slot->data.cca.p_result) = nrf_802154_core_cca(p_slot->data.cca.term_lvl);
                    break;

                case REQ_TYPE_CONTINUOUS_CARRIER:
                    *(p_slot->data.continuous_carrier.p_result) =
                        nrf_802154_core_continuous_carrier(
                            p_slot->data.continuous_carrier.term_lvl);
                    break;

                case REQ_TYPE_BUFFER_FREE:
                    *(p_slot->data.buffer_free.p_result) =
                        nrf_802154_core_notify_buffer_free(p_slot->data.buffer_free.p_data);
                    break;

                case REQ_TYPE_CHANNEL_UPDATE:
                    *(p_slot->data.channel_update.p_result) = nrf_802154_core_channel_update();
                    break;

                case REQ_TYPE_CCA_CFG_UPDATE:
                    *(p_slot->data.cca_cfg_update.p_result) = nrf_802154_core_cca_cfg_update();
                    break;

                case REQ_TYPE_RSSI_MEASURE:
                    *(p_slot->data.rssi_measure.p_result) = nrf_802154_core_rssi_measure();
                    break;

                case REQ_TYPE_RSSI_GET:
                    *(p_slot->data.rssi_get.p_result) =
                        nrf_802154_core_last_rssi_measurement_get(p_slot->data.rssi_get.p_rssi);
                    break;

                default:
                    assert(false);
            }

            req_queue_ptr_increment(&m_req_r_ptr);
        }
    }
}


text:
require "method_struct/version"
require "method_struct/defaults"
require "method_struct/argument_verifier"
require "method_struct/argument_parser"

module MethodStruct
  def self.new(*fields, &block)
    if fields.last.is_a?(Hash)
      options = fields.last
      fields = fields.take(fields.size - 1)
    else
      options = {}
    end

    unless fields.all?{ |f| f.is_a?(Symbol) }
      invalid_fields = fields.select{ |f| !f.is_a?(Symbol) }
      raise ArgumentError, "only symbol fields allowed: #{invalid_fields.inspect}"
    end

    method_name = options.fetch(:method_name, Defaults.get[:method_name])
    require_all = options.fetch(:require_all, Defaults.get[:require_all])
    require_presence = options.fetch(:require_presence, Defaults.get[:require_presence])

    Class.new do
      singleton_class = (class << self; self; end)

      singleton_class.instance_eval do
        define_method(method_name) do |*field_values, &blk|
          new(*field_values).send(method_name, &blk)
        end

        define_method(:[]) do |*args|
          send(method_name, *args)
        end

        define_method(:to_proc) do
          Proc.new { |*args| send(method_name, *args) }
        end
      end

      define_method(:[]) do |&blk|
        send(method_name, &blk)
      end

      define_method(:initialize) do |*values|
        arguments = ArgumentParser.new(
          :fields => fields,
          :raw_arguments => values,
          :require_all => require_all,
          :require_presence => require_presence
        ).call

        arguments.each do |field, value|
          instance_variable_set("@#{field}", value)
        end
      end

      define_method(:==) do |other|
        self.class == other.class && fields.all? do |field|
          send(field) == other.send(field)
        end
      end
      alias_method :eql?, :==

      define_method(:hash) do
        fields.map { |field| send(field).hash }.inject(&:^)
      end

      fields.each do |field|
        attr_reader(field)
        protected field
      end

      class_eval(&block) if block_given?
    end
  end
end


text:
<?php

class f_form_radio extends f_form_element
{

    protected $_type   = 'radio';
    protected $_helper = 'formRadio';

    /**
     * Statyczny konstruktor
     *
     * @param array $config
     * @return f_form_radio
     */
    public static function _(array $config = array())
    {
        return new self($config);
    }

}


text:
<?php

namespace AppBundle\Extensions\DataTag;

use Biz\Announcement\Service\AnnouncementService;

/**
 * @todo
 */
class CourseAnnouncementsDataTag extends BaseDataTag implements DataTag
{
    /**
     * 获取课程公告列表.
     *
     * 可传入的参数:
     *   courseSetId  必需
     *   courseId     可选
     *   count        必需 取值不超过10
     *
     * @param array $arguments 参数
     *
     * @return array 公告列表
     */
    public function getData(array $arguments)
    {
        $this->checkCount($arguments);

        $conditions = array(
            'targetType' => 'course',
            'endTime' => time(),
        );

        if (!empty($arguments['courseId'])) {
            $conditions['targetId'] = $arguments['courseId'];
        }

        $announcements = $this->getAnnouncementService()->searchAnnouncements($conditions, array('createdTime' => 'DESC'), 0, $arguments['count']);

        return $announcements;
    }

    /**
     * @return AnnouncementService
     */
    protected function getAnnouncementService()
    {
        return $this->getServiceKernel()->createService('Announcement:AnnouncementService');
    }

    protected function getCourseService()
    {
        return $this->getServiceKernel()->getBiz()->service('Course:CourseService');
    }

    protected function checkCount(array $arguments)
    {
        if (empty($arguments['count'])) {
            throw new \InvalidArgumentException('count argument missing');
        }
        if ($arguments['count'] > 100) {
            throw new \InvalidArgumentException('invalid arguments');
        }

        if (empty($arguments['courseId'])) {
            throw new \InvalidArgumentException('invalid arguments');
        }
    }
}


text:
/**
 * 复杂产品,需要逐步构建
 * Author: markliu
 * Time  : 16-8-28 上午11:03
 */
public class Actor {
	private String type;
	private String sex;
	private String face;
	private String costume;
	private String hairstyle;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getFace() {
		return face;
	}

	public void setFace(String face) {
		this.face = face;
	}

	public String getCostume() {
		return costume;
	}

	public void setCostume(String costume) {
		this.costume = costume;
	}

	public String getHairstyle() {
		return hairstyle;
	}

	public void setHairstyle(String hairstyle) {
		this.hairstyle = hairstyle;
	}

	@Override
	public String toString() {
		return "Actor{" +
				"type='" + type + '\'' +
				", sex='" + sex + '\'' +
				", face='" + face + '\'' +
				", costume='" + costume + '\'' +
				", hairstyle='" + hairstyle + '\'' +
				'}';
	}
}