text:
from JumpScale import j
from Page import Page
import copy

class PageConfluence(Page):

    def __init__(self, name, content, parent="Home"):
        Page.__init__(self, name, content, parent)
        self.toc = False

    def addMessage(self, message, newline=False):
        message = message.strip()
        message = message.replace("\r", "")
        message = message.replace("text:u", "")

        if newline:
            message += "\n"
        if message != "":
            self.content = "%s%s\n" % (self.content, message)

    def addTOC(self):
        if self.toc is False:
            self.content += "{div:class=TOCPageNumber}{toc:outline=false|style=none|maxLevel=4|indent=15px}{div}\n"
            self.toc = True

    def addBullet(self, message, level=1):
        bullets = ""
        for i in range(level):
            bullets += "*"
        message = "%s %s" % (bullets, message)
        self.addMessage(message)

    def addNewLine(self, nrlines=1):
        for line in range(nrlines):
            self.addMessage("", True)

    def addPageBreak(self):
        self.content += "{pagebreak}\n"

    def addHeading(self, message, level=1):
        message = "h%s. %s" % (level, message)
        self.addMessage(message, True)

    def addList(self, rows, headers="", showcolumns=[], columnAliases={}):
        """
        @param rows [[col1,col2, ...]]  (array of array of column values)
        @param headers [header1, header2, ...]
        """
        if len(rows) == 0:
            return False
        l = len(rows[0])
        if l != len(headers) and headers != "":
            if len(headers) > l:
                while len(headers) != l:
                    headers.pop(0)

        # TODO: put more checks to check on validity  (id:29)
        if showcolumns != []:
            rows2 = rows
            rows = []
            for row in rows2:
                if row[0] in showcolumns:
                    rows.append(row)
            headers.insert(0, " ")

        c = ""  # the content
        if headers != "":
            for item in headers:
                if item == "":
                    item = " "
                c = "%s||%s" % (c, item)
            c += "||\n"
        rows3 = copy.deepcopy(rows)
        for row in rows3:
            if row[0] in columnAliases:
                row[0] = columnAliases[row[0]]
            for col in row:
                if col == "":
                    col = " "
                c += "|%s" % self.getRound(col)
            c += "|\n"
        self.addMessage(c, True)

    def addDict(self, dictobject, description="", keystoshow=[], aliases={}):
        """
        @params aliases is dict with mapping between name in dict and name to use
        """
        if keystoshow == []:
            keystoshow = list(dictobject.keys())
        self.addMessage(description)
        arr = []
        for item in keystoshow:
            if item in aliases:
                name = aliases[item]
            else:
                name = item
            arr.append([name, dictobject[item]])
        self.addList(arr)
        self.addNewLine()

    def getLink(self, description, link):
        return "[%s|%s]" % (description, link)

    def addLink(self, description, link):
        msg = self.getLink(description, link)
        self.addBullet(msg)

    def addPageBreak(self,):
        msg = "{pagebreak}"
        self.addMessage(msg)

    def addActionBox(self, actions):
        """
        @actions is array of array, [[$actionname1,$params1],[$actionname2,$params2]]
        """
        row = []
        for item in actions:
            action = item[0]
            actiondescr = item[1]
            if actiondescr == "":
                actiondescr = action
            params = item[2]

            if action in self.actions:
                link = self.actions[action]
                link = link.replace("{params}", params)
                row.append(self.getLink(actiondescr, link))
            else:
                raise RuntimeError("Could not find action %s" % action)
        self.addList([row])

    def addCodeBlock(self, code):
        content = "{code}\n%s\n{code}\n" % code
        self.addMessage(content)

    def addCodePythonBlock(self, code, title="", removeLeadingTab=True):
        if removeLeadingTab:
            check = True
            for line in code.split("\n"):
                if not(line.find("    ") == 0 or line.strip() == ""):
                    check = False
            if check == True:
                code2 = code
                code = ""
                for line in code2.split("\n"):
                    code += "%s\n" % line[4:]

        if title != "":
            content = "{code:language=python|title=%s|theme=Eclipse}\n%s\n{code}\n" % (title, code)
        else:
            content = "{code:language=python|theme=Eclipse}\n%s\n{code}\n" % (code)
        self.addMessage(content)

    def _getArray2Wiki(self, rows, headers="", showcolumns=[], columnAliases={}, round=0, cursymbol=""):
        """
        @param rows [[rowname,col1,col2, ...]]  (array of array of column values with first item the rowname)
        @param headers [header1, header2, ...]
        """
        # TODO: S4 P3 put more checks to check on validity  (id:84)
        # TODO: S4 P3  remove code duplication with addList( (id:85)
        l = len(rows[0])
        if l != len(headers) and headers != "":
            if len(headers) > l:
                while len(headers) != l:
                    headers.pop(0)

        if showcolumns != []:
            rows2 = rows
            rows = []
            for row in rows2:
                if row[0] in showcolumns:
                    rows.append(row)

        c = ""  # the content
        if headers != "":
            for item in headers:
                if item == "":
                    item = " "
                c = "%s||%s" % (c, item)
            c += "||\n"

        rows3 = copy.deepcopy(rows)
        for row in rows3:
            if row[0] in columnAliases:
                row[0] = columnAliases[row[0]]
            for col in row:
                if col == "":
                    col = " "
                if j.data.types.float.check(col):
                    if round == 0:
                        col = "%s%s" % (cursymbol, int(col))
                    else:
                        col = "%s%.2f" % (cursymbol, float(col))
                c += "|%s" % col
            c += "|\n"
        return c

    def addTable(self, rows, columnAliases=None, columnsToShow=None, defaultCellValue=None):
        '''
        Adds a table to the confluence page.

        *Important!*
        When rows is a list of objects, the columnsToShow argument is required. It is used to
        determine which	attributes should be included in the table. But when rows objects are
        of type dictionary, the columnsToShow argument becomes optional. And used to determine
        which columns should be included in the table. The keys of the dictionaries map to the
        table column names.

        *Code sample:*
        rows = list()
        rows.append({'col_1': 'col_1_val', 'col_3': 'col_3_val'})
        rows.append({'col_1': 'col_1_val', 'col_2': 'col_2_val'})
        rows.append({'col_1': 'col_1_val', 'col_2': 'col_2_val', 'col_3': 'col_3_val'})
        rows.append({'col_2': 'col_2_val', 'col_3': 'col_3_val'})

        page = j.tools.wikigenerator.pageNewConfluence('confluence_test_page')
        columnAliases = {'col_1': 'column 1', 'col_3': 'column 3'}
        columnsToShow = ['col_3', 'col_1']
        defaultCellValue = '    /    '
        page.addTable(rows, columnAliases, columnsToShow, defaultCellValue)

        *Generated table macro:*
        ||column 3||column 1||
        |col_3_val|col_1_val|
        |    /    |col_1_val|
        |col_3_val|col_1_val|
        |col_3_val|    /    |

        @param rows: rows of the table
        @type rows: List(Object)

        @param columnAliases: aliases for the column names, defaults to an empty dict
        @type columnAliases: Dict(String)

        @param columnsToShow: columns to show in the page, defaults to a set containing all available columns
        @type columnsToShow: Set(String)

        @defaultCellValue: default value for an empty or non existing row column (cell) , defaults to a string with one space char
        @type defaultCellValue: String
        '''

        firstRow = rows[0]

        if not isinstance(firstRow, dict) and not columnsToShow:
            raise RuntimeError(
                'Invalid columnsToShow, expected a list of strings because rows is not a list of dictionaries')

        columnAliases = columnAliases or dict()
        defaultCellValue = defaultCellValue or ' '

        # determine columns to show
        if not columnsToShow:
            columnsToShow = set()

            for row in rows:
                columns = set(row.keys())
                columnsToShow.union(columns)

        macroLines = list()

        # generate table header
        headerItems = list()

        for column in columnsToShow:
            headerItem = columnAliases.get(column, column)
            headerItems.append(headerItem)

        line = '||%s||' % '||'.join(headerItems)
        macroLines.append(line)

        # generate table rows
        for row in rows:
            cells = list()

            for column in columnsToShow:
                cell = None

                if isinstance(row, dict) and column in row:
                    cell = row.get(column)
                elif hasattr(row, column):
                    cell = getattr(row, column)

                if not cell:
                    cell = defaultCellValue

                cells.append(cell)

            line = '|%s|' % '|'.join(cells)
            macroLines.append(line)

        macro = '\n'.join(macroLines)

        self.addMessage(macro)

    def addLineChart(self, title, rows, headers="", width=800, height=300):
        """
        @param rows [[values, ...],]  first value of the row is the rowname e.g. cost, revenue
        @param headers [] first value is name of the different rowtypes e.g. P&L
        """
        content =\
            """
{chart:title=%s|type=line|legend=true|width=%s|height=%s}
%s
{chart}
""" % (title, width, height, self._getArray2Wiki(rows, headers))
        self.addMessage(content, True)
        self.addNewLine()

    def addBarChart(self, title, rows, headers="", width=800, height=300, showcolumns=[], columnAliases={}):
        """
        order is list of items in rows & headers, defines the order and which columns to show
        """

        content =\
            """
{chart:title=%s|type=bar|legend=true|width=%s|height=%s}
%s
{chart}
""" % (title, width, height, self._getArray2Wiki(rows, headers, showcolumns, columnAliases))
        self.addMessage(content, True)
        self.addNewLine()

    def _getUnderlineString(self, message):
        line = ""
        for i in range(len(message)):
            line = line + "="
        return "%s\n%s" % (message, line)

    def __repr__(self):
        return self.content

    def __str__(self):
        return self.__repr__()


text:
<!DOCTYPE html>

  <title>Oba - Parent Account Overview</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="generator" content="Clarify http://www.clarify-it.com">
  <meta content="" name="description">
  <meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=2.0" />

  <link href="css/basic.css" media="screen" rel="stylesheet" type="text/css" />
  <link href="css/prettyPhoto.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8" />

Oba - Parent Account Overview

This tutorial will show you how to log in to Oba and view your student's courses. If you need any assistance with your password, please contact me:

shie.benaderet@northwestschool.org

1. Go to https://nws.obaworld.net

2. Use your email address to log in.

3. You will be prompted to change your password.

4. Home screen

5. Course detail

6. If you have multiple students, use the drop-down list to toggle between them

redpajama_set_name: RedPajamaGithub


text:
/**
 * This package contains an implementation of
 * the ChannelConnector for RabbitMQ.
 * @author Henrik Baerbak Christensen, Aarhus University
 *
 */
package dk.au.cs.karibu.producer.rabbitmq;


text:
use crate::consensus_context::ConsensusContext;
use errors::{BlockOperationError, BlockProcessingError, HeaderInvalid};
use rayon::prelude::*;
use safe_arith::{ArithError, SafeArith};
use signature_sets::{block_proposal_signature_set, get_pubkey_from_state, randao_signature_set};
use std::borrow::Cow;
use tree_hash::TreeHash;
use types::*;

pub use self::verify_attester_slashing::{
    get_slashable_indices, get_slashable_indices_modular, verify_attester_slashing,
};
pub use self::verify_proposer_slashing::verify_proposer_slashing;
pub use altair::sync_committee::process_sync_aggregate;
pub use block_signature_verifier::{BlockSignatureVerifier, ParallelSignatureSets};
pub use is_valid_indexed_attestation::is_valid_indexed_attestation;
pub use process_operations::process_operations;
pub use verify_attestation::{
    verify_attestation_for_block_inclusion, verify_attestation_for_state,
};
pub use verify_deposit::{
    get_existing_validator_index, verify_deposit_merkle_proof, verify_deposit_signature,
};
pub use verify_exit::verify_exit;

pub mod altair;
pub mod block_signature_verifier;
pub mod errors;
mod is_valid_indexed_attestation;
pub mod process_operations;
pub mod signature_sets;
pub mod tests;
mod verify_attestation;
mod verify_attester_slashing;
mod verify_deposit;
mod verify_exit;
mod verify_proposer_slashing;

#[cfg(feature = "arbitrary-fuzz")]
use arbitrary::Arbitrary;

/// The strategy to be used when validating the block's signatures.
#[cfg_attr(feature = "arbitrary-fuzz", derive(Arbitrary))]
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum BlockSignatureStrategy {
    /// Do not validate any signature. Use with caution.
    NoVerification,
    /// Validate each signature individually, as its object is being processed.
    VerifyIndividual,
    /// Validate only the randao reveal signature.
    VerifyRandao,
    /// Verify all signatures in bulk at the beginning of block processing.
    VerifyBulk,
}

/// The strategy to be used when validating the block's signatures.
#[cfg_attr(feature = "arbitrary-fuzz", derive(Arbitrary))]
#[derive(PartialEq, Clone, Copy)]
pub enum VerifySignatures {
    /// Validate all signatures encountered.
    True,
    /// Do not validate any signature. Use with caution.
    False,
}

impl VerifySignatures {
    pub fn is_true(self) -> bool {
        self == VerifySignatures::True
    }
}

/// Control verification of the latest block header.
#[cfg_attr(feature = "arbitrary-fuzz", derive(Arbitrary))]
#[derive(PartialEq, Clone, Copy)]
pub enum VerifyBlockRoot {
    True,
    False,
}

/// Updates the state for a new block, whilst validating that the block is valid, optionally
/// checking the block proposer signature.
///
/// Returns `Ok(())` if the block is valid and the state was successfully updated. Otherwise
/// returns an error describing why the block was invalid or how the function failed to execute.
///
/// If `block_root` is `Some`, this root is used for verification of the proposer's signature. If it
/// is `None` the signing root is computed from scratch. This parameter only exists to avoid
/// re-calculating the root when it is already known. Note `block_root` should be equal to the
/// tree hash root of the block, NOT the signing root of the block. This function takes
/// care of mixing in the domain.
pub fn per_block_processing<T: EthSpec, Payload: ExecPayload<T>>(
    state: &mut BeaconState<T>,
    signed_block: &SignedBeaconBlock<T, Payload>,
    block_signature_strategy: BlockSignatureStrategy,
    verify_block_root: VerifyBlockRoot,
    ctxt: &mut ConsensusContext<T>,
    spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
    let block = signed_block.message();

    // Verify that the `SignedBeaconBlock` instantiation matches the fork at `signed_block.slot()`.
    signed_block
        .fork_name(spec)
        .map_err(BlockProcessingError::InconsistentBlockFork)?;

    // Verify that the `BeaconState` instantiation matches the fork at `state.slot()`.
    state
        .fork_name(spec)
        .map_err(BlockProcessingError::InconsistentStateFork)?;

    let verify_signatures = match block_signature_strategy {
        BlockSignatureStrategy::VerifyBulk => {
            // Verify all signatures in the block at once.
            let block_root = Some(ctxt.get_current_block_root(signed_block)?);
            let proposer_index = Some(ctxt.get_proposer_index(state, spec)?);
            block_verify!(
                BlockSignatureVerifier::verify_entire_block(
                    state,
                    |i| get_pubkey_from_state(state, i),
                    |pk_bytes| pk_bytes.decompress().ok().map(Cow::Owned),
                    signed_block,
                    block_root,
                    proposer_index,
                    spec
                )
                .is_ok(),
                BlockProcessingError::BulkSignatureVerificationFailed
            );
            VerifySignatures::False
        }
        BlockSignatureStrategy::VerifyIndividual => VerifySignatures::True,
        BlockSignatureStrategy::NoVerification => VerifySignatures::False,
        BlockSignatureStrategy::VerifyRandao => VerifySignatures::False,
    };

    let proposer_index = process_block_header(
        state,
        block.temporary_block_header(),
        verify_block_root,
        ctxt,
        spec,
    )?;

    if verify_signatures.is_true() {
        verify_block_signature(state, signed_block, ctxt, spec)?;
    }

    let verify_randao = if let BlockSignatureStrategy::VerifyRandao = block_signature_strategy {
        VerifySignatures::True
    } else {
        verify_signatures
    };
    // Ensure the current and previous epoch caches are built.
    state.build_committee_cache(RelativeEpoch::Previous, spec)?;
    state.build_committee_cache(RelativeEpoch::Current, spec)?;

    // The call to the `process_execution_payload` must happen before the call to the
    // `process_randao` as the former depends on the `randao_mix` computed with the reveal of the
    // previous block.
    if is_execution_enabled(state, block.body()) {
        let payload = block.body().execution_payload()?;
        process_execution_payload(state, payload, spec)?;
    }

    process_randao(state, block, verify_randao, ctxt, spec)?;
    process_eth1_data(state, block.body().eth1_data())?;
    process_operations(state, block.body(), verify_signatures, ctxt, spec)?;

    if let Ok(sync_aggregate) = block.body().sync_aggregate() {
        process_sync_aggregate(
            state,
            sync_aggregate,
            proposer_index,
            verify_signatures,
            spec,
        )?;
    }

    Ok(())
}

/// Processes the block header, returning the proposer index.
pub fn process_block_header<T: EthSpec>(
    state: &mut BeaconState<T>,
    block_header: BeaconBlockHeader,
    verify_block_root: VerifyBlockRoot,
    ctxt: &mut ConsensusContext<T>,
    spec: &ChainSpec,
) -> Result<u64, BlockOperationError<HeaderInvalid>> {
    // Verify that the slots match
    verify!(
        block_header.slot == state.slot(),
        HeaderInvalid::StateSlotMismatch
    );

    // Verify that the block is newer than the latest block header
    verify!(
        block_header.slot > state.latest_block_header().slot,
        HeaderInvalid::OlderThanLatestBlockHeader {
            block_slot: block_header.slot,
            latest_block_header_slot: state.latest_block_header().slot,
        }
    );

    // Verify that proposer index is the correct index
    let proposer_index = block_header.proposer_index;
    let state_proposer_index = ctxt.get_proposer_index(state, spec)?;
    verify!(
        proposer_index == state_proposer_index,
        HeaderInvalid::ProposerIndexMismatch {
            block_proposer_index: proposer_index,
            state_proposer_index,
        }
    );

    if verify_block_root == VerifyBlockRoot::True {
        let expected_previous_block_root = state.latest_block_header().tree_hash_root();
        verify!(
            block_header.parent_root == expected_previous_block_root,
            HeaderInvalid::ParentBlockRootMismatch {
                state: expected_previous_block_root,
                block: block_header.parent_root,
            }
        );
    }

    *state.latest_block_header_mut() = block_header;

    // Verify proposer is not slashed
    verify!(
        !state.get_validator(proposer_index as usize)?.slashed,
        HeaderInvalid::ProposerSlashed(proposer_index)
    );

    Ok(proposer_index)
}

/// Verifies the signature of a block.
///
/// Spec v0.12.1
pub fn verify_block_signature<T: EthSpec, Payload: ExecPayload<T>>(
    state: &BeaconState<T>,
    block: &SignedBeaconBlock<T, Payload>,
    ctxt: &mut ConsensusContext<T>,
    spec: &ChainSpec,
) -> Result<(), BlockOperationError<HeaderInvalid>> {
    let block_root = Some(ctxt.get_current_block_root(block)?);
    let proposer_index = Some(ctxt.get_proposer_index(state, spec)?);
    verify!(
        block_proposal_signature_set(
            state,
            |i| get_pubkey_from_state(state, i),
            block,
            block_root,
            proposer_index,
            spec
        )?
        .verify(),
        HeaderInvalid::ProposalSignatureInvalid
    );

    Ok(())
}

/// Verifies the `randao_reveal` against the block's proposer pubkey and updates
/// `state.latest_randao_mixes`.
pub fn process_randao<T: EthSpec, Payload: ExecPayload<T>>(
    state: &mut BeaconState<T>,
    block: BeaconBlockRef<'_, T, Payload>,
    verify_signatures: VerifySignatures,
    ctxt: &mut ConsensusContext<T>,
    spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
    if verify_signatures.is_true() {
        // Verify RANDAO reveal signature.
        let proposer_index = ctxt.get_proposer_index(state, spec)?;
        block_verify!(
            randao_signature_set(
                state,
                |i| get_pubkey_from_state(state, i),
                block,
                Some(proposer_index),
                spec
            )?
            .verify(),
            BlockProcessingError::RandaoSignatureInvalid
        );
    }

    // Update the current epoch RANDAO mix.
    state.update_randao_mix(state.current_epoch(), block.body().randao_reveal())?;

    Ok(())
}

/// Update the `state.eth1_data_votes` based upon the `eth1_data` provided.
pub fn process_eth1_data<T: EthSpec>(
    state: &mut BeaconState<T>,
    eth1_data: &Eth1Data,
) -> Result<(), Error> {
    if let Some(new_eth1_data) = get_new_eth1_data(state, eth1_data)? {
        *state.eth1_data_mut() = new_eth1_data;
    }

    state.eth1_data_votes_mut().push(eth1_data.clone())?;

    Ok(())
}

/// Returns `Ok(Some(eth1_data))` if adding the given `eth1_data` to `state.eth1_data_votes` would
/// result in a change to `state.eth1_data`.
pub fn get_new_eth1_data<T: EthSpec>(
    state: &BeaconState<T>,
    eth1_data: &Eth1Data,
) -> Result<Option<Eth1Data>, ArithError> {
    let num_votes = state
        .eth1_data_votes()
        .iter()
        .filter(|vote| *vote == eth1_data)
        .count();

    // The +1 is to account for the `eth1_data` supplied to the function.
    if num_votes.safe_add(1)?.safe_mul(2)? > T::SlotsPerEth1VotingPeriod::to_usize() {
        Ok(Some(eth1_data.clone()))
    } else {
        Ok(None)
    }
}

/// Performs *partial* verification of the `payload`.
///
/// The verification is partial, since the execution payload is not verified against an execution
/// engine. That is expected to be performed by an upstream function.
///
/// ## Specification
///
/// Contains a partial set of checks from the `process_execution_payload` function:
///
/// https://github.com/ethereum/consensus-specs/blob/v1.1.5/specs/merge/beacon-chain.md#process_execution_payload
pub fn partially_verify_execution_payload<T: EthSpec, Payload: ExecPayload<T>>(
    state: &BeaconState<T>,
    payload: &Payload,
    spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
    if is_merge_transition_complete(state) {
        block_verify!(
            payload.parent_hash() == state.latest_execution_payload_header()?.block_hash,
            BlockProcessingError::ExecutionHashChainIncontiguous {
                expected: state.latest_execution_payload_header()?.block_hash,
                found: payload.parent_hash(),
            }
        );
    }
    block_verify!(
        payload.prev_randao() == *state.get_randao_mix(state.current_epoch())?,
        BlockProcessingError::ExecutionRandaoMismatch {
            expected: *state.get_randao_mix(state.current_epoch())?,
            found: payload.prev_randao(),
        }
    );

    let timestamp = compute_timestamp_at_slot(state, spec)?;
    block_verify!(
        payload.timestamp() == timestamp,
        BlockProcessingError::ExecutionInvalidTimestamp {
            expected: timestamp,
            found: payload.timestamp(),
        }
    );

    Ok(())
}

/// Calls `partially_verify_execution_payload` and then updates the payload header in the `state`.
///
/// ## Specification
///
/// Partially equivalent to the `process_execution_payload` function:
///
/// https://github.com/ethereum/consensus-specs/blob/v1.1.5/specs/merge/beacon-chain.md#process_execution_payload
pub fn process_execution_payload<T: EthSpec, Payload: ExecPayload<T>>(
    state: &mut BeaconState<T>,
    payload: &Payload,
    spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
    partially_verify_execution_payload(state, payload, spec)?;

    *state.latest_execution_payload_header_mut()? = payload.to_execution_payload_header();

    Ok(())
}

/// These functions will definitely be called before the merge. Their entire purpose is to check if
/// the merge has happened or if we're on the transition block. Thus we don't want to propagate
/// errors from the `BeaconState` being an earlier variant than `BeaconStateMerge` as we'd have to
/// repeaetedly write code to treat these errors as false.
/// https://github.com/ethereum/consensus-specs/blob/dev/specs/merge/beacon-chain.md#is_merge_transition_complete
pub fn is_merge_transition_complete<T: EthSpec>(state: &BeaconState<T>) -> bool {
    state
        .latest_execution_payload_header()
        .map(|header| *header != <ExecutionPayloadHeader<T>>::default())
        .unwrap_or(false)
}
/// https://github.com/ethereum/consensus-specs/blob/dev/specs/merge/beacon-chain.md#is_merge_transition_block
pub fn is_merge_transition_block<T: EthSpec, Payload: ExecPayload<T>>(
    state: &BeaconState<T>,
    body: BeaconBlockBodyRef<T, Payload>,
) -> bool {
    body.execution_payload()
        .map(|payload| !is_merge_transition_complete(state) && *payload != Payload::default())
        .unwrap_or(false)
}
/// https://github.com/ethereum/consensus-specs/blob/dev/specs/merge/beacon-chain.md#is_execution_enabled
pub fn is_execution_enabled<T: EthSpec, Payload: ExecPayload<T>>(
    state: &BeaconState<T>,
    body: BeaconBlockBodyRef<T, Payload>,
) -> bool {
    is_merge_transition_block(state, body) || is_merge_transition_complete(state)
}
/// https://github.com/ethereum/consensus-specs/blob/dev/specs/merge/beacon-chain.md#compute_timestamp_at_slot
pub fn compute_timestamp_at_slot<T: EthSpec>(
    state: &BeaconState<T>,
    spec: &ChainSpec,
) -> Result<u64, ArithError> {
    let slots_since_genesis = state.slot().as_u64().safe_sub(spec.genesis_slot.as_u64())?;
    slots_since_genesis
        .safe_mul(spec.seconds_per_slot)
        .and_then(|since_genesis| state.genesis_time().safe_add(since_genesis))
}


text:
public class BinaryTree {

}


text:
using System.IO;
using Codex.Logging;
using Codex.Search;
using Lucene.Net.Store;
using Directory = Lucene.Net.Store.Directory;

namespace Codex.Lucene.Search
{
    public class LuceneConfiguration : CodexBaseConfiguration
    {
        public string Directory { get; set; }

        private Directory Root { get; set; }

        public Logger Logger = new ConsoleLogger();

        private string GetIndexRoot(SearchType searchType)
        {
            return Path.Combine(Directory, searchType.IndexName);
        }

        public Directory OpenIndexDirectory(SearchType searchType)
        {
            if (Root != null)
            {
                return new ScopedDirectory(Root, searchType.IndexName);
            }

            return FSDirectory.Open(GetIndexRoot(searchType));
        }

        public LuceneConfiguration(string directory)
        {
            Directory = directory;
        }

        private LuceneConfiguration()
        {
        }

        public static LuceneConfiguration CreateFromRoot(Directory root)
        {
            return new LuceneConfiguration() { Root = root };
        }
    }
}


text:
package calcium

import (
	"bytes"
	"context"
	"encoding/json"
	"io/ioutil"
	"testing"

	enginemocks "github.com/projecteru2/core/engine/mocks"
	storemocks "github.com/projecteru2/core/store/mocks"
	"github.com/projecteru2/core/types"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

type inStream struct {
	*bytes.Buffer
}

func (i *inStream) Close() error {
	return nil
}

func TestExecuteWorkload(t *testing.T) {
	c := NewTestCluster()
	ctx := context.Background()
	store := &storemocks.Store{}
	c.store = store

	// failed by GetWorkload
	store.On("GetWorkload", mock.Anything, mock.Anything).Return(nil, types.ErrBadCount).Once()
	ID := "abc"
	ch := c.ExecuteWorkload(ctx, &types.ExecuteWorkloadOptions{WorkloadID: ID}, nil)
	for ac := range ch {
		assert.NotEmpty(t, ac.Data)
	}

	engine := &enginemocks.API{}
	workload := &types.Workload{
		ID:     ID,
		Engine: engine,
	}
	store.On("GetWorkload", mock.Anything, mock.Anything).Return(workload, nil)

	// failed by Execute
	result := "def"
	engine.On("Execute", mock.Anything, mock.Anything, mock.Anything).Return(result, nil, nil, nil, types.ErrCannotGetEngine).Once()
	ch = c.ExecuteWorkload(ctx, &types.ExecuteWorkloadOptions{WorkloadID: ID}, nil)
	for ac := range ch {
		assert.Equal(t, ac.WorkloadID, ID)
	}
	buf := ioutil.NopCloser(bytes.NewBufferString(`echo 1\n`))
	engine.On("Execute", mock.Anything, mock.Anything, mock.Anything).Return(result, buf, nil, nil, nil).Twice()

	// failed by ExecExitCode
	engine.On("ExecExitCode", mock.Anything, mock.Anything, mock.Anything).Return(-1, types.ErrCannotGetEngine).Once()
	ch = c.ExecuteWorkload(ctx, &types.ExecuteWorkloadOptions{WorkloadID: ID}, nil)
	data := []byte{}
	for ac := range ch {
		assert.Equal(t, ac.WorkloadID, ID)
		data = append(data, ac.Data...)
	}
	assert.Contains(t, string(data), "echo")
	engine.On("ExecExitCode", mock.Anything, mock.Anything, mock.Anything).Return(0, nil)
	ch = c.ExecuteWorkload(ctx, &types.ExecuteWorkloadOptions{WorkloadID: ID}, nil)
	for ac := range ch {
		assert.Equal(t, ac.WorkloadID, ID)
		data = append(data, ac.Data...)
	}
	assert.Contains(t, string(data), "exitcode")
	assert.Contains(t, string(data), "0")
	inChan := make(chan []byte)
	inS := &inStream{bytes.NewBufferString("")}
	engine.On("Execute", mock.Anything, mock.Anything, mock.Anything).Return(ID, buf, nil, inS, nil)
	ch = c.ExecuteWorkload(ctx, &types.ExecuteWorkloadOptions{WorkloadID: ID, OpenStdin: true}, inChan)
	inChan <- []byte("a")
	inChan <- escapeCommand
	engine.On("ExecResize", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(types.ErrAlreadyFilled)
	w := &window{100, 100}
	b, err := json.Marshal(w)
	assert.NoError(t, err)
	inChan <- append(winchCommand, []byte(`{Row: 100, Col: 100}`)...)
	inChan <- append(winchCommand, b...)
	for ac := range ch {
		assert.Equal(t, ac.WorkloadID, ID)
		data = append(data, ac.Data...)
	}
	assert.Contains(t, inS.String(), "a")
}


text:
"""Module for ProcessTargetedEvent event."""

from typing import Callable
from typing import TYPE_CHECKING

from ...event import Event

if TYPE_CHECKING:
    from ...actions import ExecuteProcess  # noqa: F401

class ProcessTargetedEvent(Event):
    """Event base class that is targeted at some running process."""

    name = 'launch.events.process.ProcessTargetedEvent'

    def __init__(self, *, process_matcher: Callable[['ExecuteProcess'], bool]) -> None:
        """
        Create a ProcessTargetedEvent.

        Some standard matchers are also available, like:

        - :func:`launch.events.matches_action()`
        - :func:`launch.events.process.matches_pid()`
        - :func:`launch.events.process.matches_name()`
        - :func:`launch.events.process.matches_executable()`

        :param: process_matcher is a predicate which can determine if an
            ExecuteProcess action matches this event or not
        """
        super().__init__()
        self.__process_matcher = process_matcher

    @property
    def process_matcher(self) -> Callable[['ExecuteProcess'], bool]:
        """Getter for process_matcher."""
        return self.__process_matcher


text:
/**
 * highlight
 */

export default function () {
  document.querySelectorAll('.chroma>table')
    .forEach((element) => {
      const sub = element.querySelector('code[data-lang]');
      if (sub !== null) {
        element.setAttribute('data-lang', mapLang(sub.getAttribute('data-lang')));
      }
    });
}

function mapLang(name) {
  return {
    coffeescript: 'CoffeeScript',
    cpp: 'C++',
    cs: 'C#',
    css: 'CSS',
    html: 'HTML',
    http: 'HTTP',
    js: 'JavaScript',
    json: 'JSON',
    objectivec: 'Objective-C',
    php: 'PHP',
    sql: 'SQL',
    toml: 'TOML',
    ts: 'TypeScript',
    typescript: 'TypeScript',
    xml: 'XML',
    yaml: 'YAML',
  }[name] || name;
}


text:
@interface ThreeNavigationController : UINavigationController

@end


text:
from test.models import *

class Tasks:
	def __init__(self):
		self.postgres = Postgres()

	def bindWithColumn(self,data,columns):
		data_dict = {}
		for idx,column in enumerate(columns):
			data_dict[column[0]] = data[idx]
		return data_dict

	def getTask(self, task_id, page=0):
		"""
		=================================================================================
			Check this first if multiple task is coming. this could contain the error.
		=================================================================================
		"""
		task_dict = {
			'column_name' : 'id',
			'column_value' : task_id
		}
		if len(task_dict.keys()) :
			tasks,columns = self.postgres.getByAppName('tasks',task_dict)
		else:
			tasks,columns = self.postgres.getByAppName('tasks',page= page)
		task_data = []
		for task in tasks:
			data = self.bindWithColumn(task, columns)
			task_data.append(data)
		return task_data

	def getUser(self, dict1):

		creator, columns = self.postgres.getByAppName('users',dict1)
		# print creator, columns
		data = self.bindWithColumn(creator[0], columns)
		dict_creator={}
		dict_creator['id'] = data['id']
		dict_creator['displayName'] = data['display_name']
		dict_creator['email'] = data['email']
		dict_creator['logo'] = data['logo']
		return dict_creator

	def getAssignee(self, dict1):
		# print task_id
		assignees, columns = self.postgres.getByAppName('tasks_assignees',dict1)
		assignee_list = []
		assignee_task_id_list = []
		for assignee in assignees:
			data = self.bindWithColumn(assignee, columns)
			# print data
			assignee_task_id_list.append(data['task_id'])
			dict1 = {
				'column_name' : 'id',
				'column_value' : data['assignee_id']
			}
			dict_assignee = self.getUser(dict1)
			assignee_list.append(dict_assignee)
		return assignee_list,assignee_task_id_list

	def getFollower(self, dict1):
		followers, columns = self.postgres.getByAppName('task_followers',dict1)
		follower_list = []
		follower_task_id_list = []
		for follower in followers:
			data = self.bindWithColumn(follower, columns)
			follower_task_id_list.append(data['task_id'])
			dict1 = {
				'column_name' : 'id',
				'column_value' : data['follower_id']
			}
			dict_follower = self.getUser(dict1)
			follower_list.append(dict_follower)
		return follower_list, follower_task_id_list

	def getCLS(self, dict1):
		clss, columns = self.postgres.getByAppName(dict1['table_name'],dict1)
		clss = clss[0]
		data = self.bindWithColumn(clss, columns)
		cls_dict = {
			"code" : data['code'],
			"name" : data['name'],
			"created_at" : data['created_at'],
			"updated_at" : data['updated_at']
		}
		return cls_dict

	def getPSData(self, dict1):
		ps = self.postgres.getPSFromTable(dict1)
		return ps[0][1]
		# data = self.bindWithColumn(ps, columns)
		# return data['status'] if data['status'] else data['priority']

	def getTableId(self, dict1):
		return self.postgres.getIdFormAnyTable(dict1)

	def getTableIdByDueDate(self, dict1):
		return self.postgres.getIdFromTaskTableByDueDate(dict1)


text:
package org.trimou.trimness.test;

import org.junit.Assert;
import org.junit.Test;

public class TimerTest {

    @Test
    public void testInterval() throws InterruptedException {
        long start = System.currentTimeMillis();
        Timer.of(60).countDown();
        Assert.assertTrue((System.currentTimeMillis() - start) >= 60);
    }

    @Test
    public void testCondition() throws InterruptedException {
        long start = System.currentTimeMillis();
        Timer.of(200).setSleepInterval(50).stopIf(() -> true).countDown();
        Assert.assertTrue((System.currentTimeMillis() - start) < 200);
    }

    @Test(expected = AssertionError.class)
    public void testFailIfElapsed() throws InterruptedException {
        Timer.of(60).stopIf(() -> false).setFailIfElapsed(true).countDown();
    }

}


text:
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using MvcTemplate.Controllers;
using MvcTemplate.Services;
using NSubstitute;
using System;
using Xunit;

namespace MvcTemplate.Tests.Unit.Controllers
{
    public class ServicedControllerTests : ControllerTests
    {
        private ServicedController<IService> controller;
        private IService service;

        public ServicedControllerTests()
        {
            service = Substitute.For<IService>();
            controller = Substitute.ForPartsOf<ServicedController<IService>>(service);
        }

        #region Constructor: ServicedController(TService service)

        [Fact]
        public void ServicedController_SetsService()
        {
            Object actual = controller.Service;
            Object expected = service;

            Assert.Same(expected, actual);
        }

        #endregion

        #region Method: OnActionExecuting(ActionExecutingContext context)

        [Fact]
        public void OnActionExecuting_SetsServiceCurrentAccountId()
        {
            ReturnCurrentAccountId(controller, "Test");

            controller.OnActionExecuting(new ActionExecutingContext(new ActionContext(), null, null, null));

            String expected = controller.CurrentAccountId;
            String actual = service.CurrentAccountId;

            Assert.Equal(expected, actual);
        }

        #endregion

        #region Method: Dispose()

        [Fact]
        public void Dispose_Service()
        {
            controller.Dispose();

            service.Received().Dispose();
        }

        [Fact]
        public void Dispose_MultipleTimes()
        {
            controller.Dispose();
            controller.Dispose();
        }

        #endregion
    }
}


text:
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { InfiniteScrollHarnessTestComponent } from './fixtures/infinite-scroll-harness-test.component';
import { InfiniteScrollHarnessTestModule } from './fixtures/infinite-scroll-harness-test.module';
import { SkyInfiniteScrollHarness } from './infinite-scroll-harness';

describe('Infinite scroll harness', () => {
  async function setupTest(options: { dataSkyId?: string } = {}) {
    await TestBed.configureTestingModule({
      imports: [InfiniteScrollHarnessTestModule],
    }).compileComponents();

    const fixture = TestBed.createComponent(InfiniteScrollHarnessTestComponent);
    const loader = TestbedHarnessEnvironment.loader(fixture);

    const infiniteScrollHarness: SkyInfiniteScrollHarness = options.dataSkyId
      ? await loader.getHarness(
          SkyInfiniteScrollHarness.with({ dataSkyId: options.dataSkyId })
        )
      : await loader.getHarness(SkyInfiniteScrollHarness);

    return { fixture, infiniteScrollHarness, loader };
  }

  function verifyNumListItems(
    fixture: ComponentFixture<InfiniteScrollHarnessTestComponent>,
    count: number
  ) {
    expect(fixture.debugElement.queryAll(By.css('li')).length).toEqual(count);
  }

  it('should click the "Load more" button', async () => {
    const { fixture, infiniteScrollHarness } = await setupTest({
      dataSkyId: 'my-infinite-scroll',
    });

    verifyNumListItems(fixture, 0);

    await infiniteScrollHarness.loadMore();

    verifyNumListItems(fixture, 10);
  });

  it('should throw error if clicking "Load more" button when scroll loading', async () => {
    const { fixture, infiniteScrollHarness } = await setupTest({
      dataSkyId: 'my-infinite-scroll',
    });

    fixture.componentInstance.loading = true;

    await expectAsync(infiniteScrollHarness.isLoading()).toBeResolvedTo(true);
    await expectAsync(infiniteScrollHarness.loadMore()).toBeRejectedWithError(
      'Unable to click the "Load more" button because the infinite scroll is loading.'
    );
  });

  it('should throw error if clicking "Load more" button when scroll not enabled', async () => {
    const { fixture, infiniteScrollHarness } = await setupTest({
      dataSkyId: 'my-infinite-scroll',
    });

    fixture.componentInstance.enabled = false;

    await expectAsync(infiniteScrollHarness.isEnabled()).toBeResolvedTo(false);
    await expectAsync(infiniteScrollHarness.loadMore()).toBeRejectedWithError(
      'Unable to click the "Load more" button because the infinite scroll is not enabled.'
    );
  });
});


text:
"""Example usage of colorclass.

Just prints sample text and exits.

Usage:
    example.py print [--light-bg|--no-colors]
    example.py -h | --help

Options:
    -h --help       Show this screen.
    --light-bg      Autocolors adapt to white/light backgrounds for Linux/OSX.
    --no-colors     Strip out any foreground or background colors.
"""

from __future__ import print_function

import os

from docopt import docopt

from colorclass import Color, disable_all_colors, set_light_background, Windows

OPTIONS = docopt(__doc__) if __name__ == '__main__' else dict()

def main():
    """Main function called upon script execution."""
    if OPTIONS.get('--no-colors'):
        disable_all_colors()
    elif os.name == 'nt':
        Windows.enable(auto_colors=True, reset_atexit=True)
    elif OPTIONS.get('--light-bg'):
        set_light_background()

    # Light or dark colors.
    print('Autocolors for all backgrounds:')
    print(Color('    {autoblack}Black{/black} {autored}Red{/red} {autogreen}Green{/green} '), end='')
    print(Color('{autoyellow}Yellow{/yellow} {autoblue}Blue{/blue} {automagenta}Magenta{/magenta} '), end='')
    print(Color('{autocyan}Cyan{/cyan} {autowhite}White{/white}'))

    print(Color('    {autobgblack}{autoblack}Black{/black}{/bgblack} '), end='')
    print(Color('{autobgblack}{autored}Red{/red}{/bgblack} {autobgblack}{autogreen}Green{/green}{/bgblack} '), end='')
    print(Color('{autobgblack}{autoyellow}Yellow{/yellow}{/bgblack} '), end='')
    print(Color('{autobgblack}{autoblue}Blue{/blue}{/bgblack} '), end='')
    print(Color('{autobgblack}{automagenta}Magenta{/magenta}{/bgblack} '), end='')
    print(Color('{autobgblack}{autocyan}Cyan{/cyan}{/bgblack} {autobgblack}{autowhite}White{/white}{/bgblack}'))

    print(Color('    {autobgred}{autoblack}Black{/black}{/bgred} {autobgred}{autored}Red{/red}{/bgred} '), end='')
    print(Color('{autobgred}{autogreen}Green{/green}{/bgred} {autobgred}{autoyellow}Yellow{/yellow}{/bgred} '), end='')
    print(Color('{autobgred}{autoblue}Blue{/blue}{/bgred} {autobgred}{automagenta}Magenta{/magenta}{/bgred} '), end='')
    print(Color('{autobgred}{autocyan}Cyan{/cyan}{/bgred} {autobgred}{autowhite}White{/white}{/bgred}'))

    print(Color('    {autobggreen}{autoblack}Black{/black}{/bggreen} '), end='')
    print(Color('{autobggreen}{autored}Red{/red}{/bggreen} {autobggreen}{autogreen}Green{/green}{/bggreen} '), end='')
    print(Color('{autobggreen}{autoyellow}Yellow{/yellow}{/bggreen} '), end='')
    print(Color('{autobggreen}{autoblue}Blue{/blue}{/bggreen} '), end='')
    print(Color('{autobggreen}{automagenta}Magenta{/magenta}{/bggreen} '), end='')
    print(Color('{autobggreen}{autocyan}Cyan{/cyan}{/bggreen} {autobggreen}{autowhite}White{/white}{/bggreen}'))

    print(Color('    {autobgyellow}{autoblack}Black{/black}{/bgyellow} '), end='')
    print(Color('{autobgyellow}{autored}Red{/red}{/bgyellow} '), end='')
    print(Color('{autobgyellow}{autogreen}Green{/green}{/bgyellow} '), end='')
    print(Color('{autobgyellow}{autoyellow}Yellow{/yellow}{/bgyellow} '), end='')
    print(Color('{autobgyellow}{autoblue}Blue{/blue}{/bgyellow} '), end='')
    print(Color('{autobgyellow}{automagenta}Magenta{/magenta}{/bgyellow} '), end='')
    print(Color('{autobgyellow}{autocyan}Cyan{/cyan}{/bgyellow} {autobgyellow}{autowhite}White{/white}{/bgyellow}'))

    print(Color('    {autobgblue}{autoblack}Black{/black}{/bgblue} {autobgblue}{autored}Red{/red}{/bgblue} '), end='')
    print(Color('{autobgblue}{autogreen}Green{/green}{/bgblue} '), end='')
    print(Color('{autobgblue}{autoyellow}Yellow{/yellow}{/bgblue} {autobgblue}{autoblue}Blue{/blue}{/bgblue} '), end='')
    print(Color('{autobgblue}{automagenta}Magenta{/magenta}{/bgblue} '), end='')
    print(Color('{autobgblue}{autocyan}Cyan{/cyan}{/bgblue} {autobgblue}{autowhite}White{/white}{/bgblue}'))

    print(Color('    {autobgmagenta}{autoblack}Black{/black}{/bgmagenta} '), end='')
    print(Color('{autobgmagenta}{autored}Red{/red}{/bgmagenta} '), end='')
    print(Color('{autobgmagenta}{autogreen}Green{/green}{/bgmagenta} '), end='')
    print(Color('{autobgmagenta}{autoyellow}Yellow{/yellow}{/bgmagenta} '), end='')
    print(Color('{autobgmagenta}{autoblue}Blue{/blue}{/bgmagenta} '), end='')
    print(Color('{autobgmagenta}{automagenta}Magenta{/magenta}{/bgmagenta} '), end='')
    print(Color('{autobgmagenta}{autocyan}Cyan{/cyan}{/bgmagenta} '), end='')
    print(Color('{autobgmagenta}{autowhite}White{/white}{/bgmagenta}'))

    print(Color('    {autobgcyan}{autoblack}Black{/black}{/bgcyan} {autobgcyan}{autored}Red{/red}{/bgcyan} '), end='')
    print(Color('{autobgcyan}{autogreen}Green{/green}{/bgcyan} '), end='')
    print(Color('{autobgcyan}{autoyellow}Yellow{/yellow}{/bgcyan} {autobgcyan}{autoblue}Blue{/blue}{/bgcyan} '), end='')
    print(Color('{autobgcyan}{automagenta}Magenta{/magenta}{/bgcyan} '), end='')
    print(Color('{autobgcyan}{autocyan}Cyan{/cyan}{/bgcyan} {autobgcyan}{autowhite}White{/white}{/bgcyan}'))

    print(Color('    {autobgwhite}{autoblack}Black{/black}{/bgwhite} '), end='')
    print(Color('{autobgwhite}{autored}Red{/red}{/bgwhite} {autobgwhite}{autogreen}Green{/green}{/bgwhite} '), end='')
    print(Color('{autobgwhite}{autoyellow}Yellow{/yellow}{/bgwhite} '), end='')
    print(Color('{autobgwhite}{autoblue}Blue{/blue}{/bgwhite} '), end='')
    print(Color('{autobgwhite}{automagenta}Magenta{/magenta}{/bgwhite} '), end='')
    print(Color('{autobgwhite}{autocyan}Cyan{/cyan}{/bgwhite} {autobgwhite}{autowhite}White{/white}{/bgwhite}'))
    print()

    # Light colors.
    print('Light colors for dark backgrounds:')
    print(Color('    {hiblack}Black{/black} {hired}Red{/red} {higreen}Green{/green} '), end='')
    print(Color('{hiyellow}Yellow{/yellow} {hiblue}Blue{/blue} {himagenta}Magenta{/magenta} '), end='')
    print(Color('{hicyan}Cyan{/cyan} {hiwhite}White{/white}'))

    print(Color('    {hibgblack}{hiblack}Black{/black}{/bgblack} '), end='')
    print(Color('{hibgblack}{hired}Red{/red}{/bgblack} {hibgblack}{higreen}Green{/green}{/bgblack} '), end='')
    print(Color('{hibgblack}{hiyellow}Yellow{/yellow}{/bgblack} '), end='')
    print(Color('{hibgblack}{hiblue}Blue{/blue}{/bgblack} '), end='')
    print(Color('{hibgblack}{himagenta}Magenta{/magenta}{/bgblack} '), end='')
    print(Color('{hibgblack}{hicyan}Cyan{/cyan}{/bgblack} {hibgblack}{hiwhite}White{/white}{/bgblack}'))

    print(Color('    {hibgred}{hiblack}Black{/black}{/bgred} {hibgred}{hired}Red{/red}{/bgred} '), end='')
    print(Color('{hibgred}{higreen}Green{/green}{/bgred} {hibgred}{hiyellow}Yellow{/yellow}{/bgred} '), end='')
    print(Color('{hibgred}{hiblue}Blue{/blue}{/bgred} {hibgred}{himagenta}Magenta{/magenta}{/bgred} '), end='')
    print(Color('{hibgred}{hicyan}Cyan{/cyan}{/bgred} {hibgred}{hiwhite}White{/white}{/bgred}'))

    print(Color('    {hibggreen}{hiblack}Black{/black}{/bggreen} '), end='')
    print(Color('{hibggreen}{hired}Red{/red}{/bggreen} {hibggreen}{higreen}Green{/green}{/bggreen} '), end='')
    print(Color('{hibggreen}{hiyellow}Yellow{/yellow}{/bggreen} '), end='')
    print(Color('{hibggreen}{hiblue}Blue{/blue}{/bggreen} '), end='')
    print(Color('{hibggreen}{himagenta}Magenta{/magenta}{/bggreen} '), end='')
    print(Color('{hibggreen}{hicyan}Cyan{/cyan}{/bggreen} {hibggreen}{hiwhite}White{/white}{/bggreen}'))

    print(Color('    {hibgyellow}{hiblack}Black{/black}{/bgyellow} '), end='')
    print(Color('{hibgyellow}{hired}Red{/red}{/bgyellow} '), end='')
    print(Color('{hibgyellow}{higreen}Green{/green}{/bgyellow} '), end='')
    print(Color('{hibgyellow}{hiyellow}Yellow{/yellow}{/bgyellow} '), end='')
    print(Color('{hibgyellow}{hiblue}Blue{/blue}{/bgyellow} '), end='')
    print(Color('{hibgyellow}{himagenta}Magenta{/magenta}{/bgyellow} '), end='')
    print(Color('{hibgyellow}{hicyan}Cyan{/cyan}{/bgyellow} {hibgyellow}{hiwhite}White{/white}{/bgyellow}'))

    print(Color('    {hibgblue}{hiblack}Black{/black}{/bgblue} {hibgblue}{hired}Red{/red}{/bgblue} '), end='')
    print(Color('{hibgblue}{higreen}Green{/green}{/bgblue} '), end='')
    print(Color('{hibgblue}{hiyellow}Yellow{/yellow}{/bgblue} {hibgblue}{hiblue}Blue{/blue}{/bgblue} '), end='')
    print(Color('{hibgblue}{himagenta}Magenta{/magenta}{/bgblue} '), end='')
    print(Color('{hibgblue}{hicyan}Cyan{/cyan}{/bgblue} {hibgblue}{hiwhite}White{/white}{/bgblue}'))

    print(Color('    {hibgmagenta}{hiblack}Black{/black}{/bgmagenta} '), end='')
    print(Color('{hibgmagenta}{hired}Red{/red}{/bgmagenta} '), end='')
    print(Color('{hibgmagenta}{higreen}Green{/green}{/bgmagenta} '), end='')
    print(Color('{hibgmagenta}{hiyellow}Yellow{/yellow}{/bgmagenta} '), end='')
    print(Color('{hibgmagenta}{hiblue}Blue{/blue}{/bgmagenta} '), end='')
    print(Color('{hibgmagenta}{himagenta}Magenta{/magenta}{/bgmagenta} '), end='')
    print(Color('{hibgmagenta}{hicyan}Cyan{/cyan}{/bgmagenta} '), end='')
    print(Color('{hibgmagenta}{hiwhite}White{/white}{/bgmagenta}'))

    print(Color('    {hibgcyan}{hiblack}Black{/black}{/bgcyan} {hibgcyan}{hired}Red{/red}{/bgcyan} '), end='')
    print(Color('{hibgcyan}{higreen}Green{/green}{/bgcyan} '), end='')
    print(Color('{hibgcyan}{hiyellow}Yellow{/yellow}{/bgcyan} {hibgcyan}{hiblue}Blue{/blue}{/bgcyan} '), end='')
    print(Color('{hibgcyan}{himagenta}Magenta{/magenta}{/bgcyan} '), end='')
    print(Color('{hibgcyan}{hicyan}Cyan{/cyan}{/bgcyan} {hibgcyan}{hiwhite}White{/white}{/bgcyan}'))

    print(Color('    {hibgwhite}{hiblack}Black{/black}{/bgwhite} '), end='')
    print(Color('{hibgwhite}{hired}Red{/red}{/bgwhite} {hibgwhite}{higreen}Green{/green}{/bgwhite} '), end='')
    print(Color('{hibgwhite}{hiyellow}Yellow{/yellow}{/bgwhite} '), end='')
    print(Color('{hibgwhite}{hiblue}Blue{/blue}{/bgwhite} '), end='')
    print(Color('{hibgwhite}{himagenta}Magenta{/magenta}{/bgwhite} '), end='')
    print(Color('{hibgwhite}{hicyan}Cyan{/cyan}{/bgwhite} {hibgwhite}{hiwhite}White{/white}{/bgwhite}'))
    print()

    # Dark colors.
    print('Dark colors for light backgrounds:')
    print(Color('    {black}Black{/black} {red}Red{/red} {green}Green{/green} {yellow}Yellow{/yellow} '), end='')
    print(Color('{blue}Blue{/blue} {magenta}Magenta{/magenta} {cyan}Cyan{/cyan} {white}White{/white}'))

    print(Color('    {bgblack}{black}Black{/black}{/bgblack} {bgblack}{red}Red{/red}{/bgblack} '), end='')
    print(Color('{bgblack}{green}Green{/green}{/bgblack} {bgblack}{yellow}Yellow{/yellow}{/bgblack} '), end='')
    print(Color('{bgblack}{blue}Blue{/blue}{/bgblack} {bgblack}{magenta}Magenta{/magenta}{/bgblack} '), end='')
    print(Color('{bgblack}{cyan}Cyan{/cyan}{/bgblack} {bgblack}{white}White{/white}{/bgblack}'))

    print(Color('    {bgred}{black}Black{/black}{/bgred} {bgred}{red}Red{/red}{/bgred} '), end='')
    print(Color('{bgred}{green}Green{/green}{/bgred} {bgred}{yellow}Yellow{/yellow}{/bgred} '), end='')
    print(Color('{bgred}{blue}Blue{/blue}{/bgred} {bgred}{magenta}Magenta{/magenta}{/bgred} '), end='')
    print(Color('{bgred}{cyan}Cyan{/cyan}{/bgred} {bgred}{white}White{/white}{/bgred}'))

    print(Color('    {bggreen}{black}Black{/black}{/bggreen} {bggreen}{red}Red{/red}{/bggreen} '), end='')
    print(Color('{bggreen}{green}Green{/green}{/bggreen} {bggreen}{yellow}Yellow{/yellow}{/bggreen} '), end='')
    print(Color('{bggreen}{blue}Blue{/blue}{/bggreen} {bggreen}{magenta}Magenta{/magenta}{/bggreen} '), end='')
    print(Color('{bggreen}{cyan}Cyan{/cyan}{/bggreen} {bggreen}{white}White{/white}{/bggreen}'))

    print(Color('    {bgyellow}{black}Black{/black}{/bgyellow} {bgyellow}{red}Red{/red}{/bgyellow} '), end='')
    print(Color('{bgyellow}{green}Green{/green}{/bgyellow} {bgyellow}{yellow}Yellow{/yellow}{/bgyellow} '), end='')
    print(Color('{bgyellow}{blue}Blue{/blue}{/bgyellow} {bgyellow}{magenta}Magenta{/magenta}{/bgyellow} '), end='')
    print(Color('{bgyellow}{cyan}Cyan{/cyan}{/bgyellow} {bgyellow}{white}White{/white}{/bgyellow}'))

    print(Color('    {bgblue}{black}Black{/black}{/bgblue} {bgblue}{red}Red{/red}{/bgblue} '), end='')
    print(Color('{bgblue}{green}Green{/green}{/bgblue} {bgblue}{yellow}Yellow{/yellow}{/bgblue} '), end='')
    print(Color('{bgblue}{blue}Blue{/blue}{/bgblue} {bgblue}{magenta}Magenta{/magenta}{/bgblue} '), end='')
    print(Color('{bgblue}{cyan}Cyan{/cyan}{/bgblue} {bgblue}{white}White{/white}{/bgblue}'))

    print(Color('    {bgmagenta}{black}Black{/black}{/bgmagenta} {bgmagenta}{red}Red{/red}{/bgmagenta} '), end='')
    print(Color('{bgmagenta}{green}Green{/green}{/bgmagenta} {bgmagenta}{yellow}Yellow{/yellow}{/bgmagenta} '), end='')
    print(Color('{bgmagenta}{blue}Blue{/blue}{/bgmagenta} {bgmagenta}{magenta}Magenta{/magenta}{/bgmagenta} '), end='')
    print(Color('{bgmagenta}{cyan}Cyan{/cyan}{/bgmagenta} {bgmagenta}{white}White{/white}{/bgmagenta}'))

    print(Color('    {bgcyan}{black}Black{/black}{/bgcyan} {bgcyan}{red}Red{/red}{/bgcyan} '), end='')
    print(Color('{bgcyan}{green}Green{/green}{/bgcyan} {bgcyan}{yellow}Yellow{/yellow}{/bgcyan} '), end='')
    print(Color('{bgcyan}{blue}Blue{/blue}{/bgcyan} {bgcyan}{magenta}Magenta{/magenta}{/bgcyan} '), end='')
    print(Color('{bgcyan}{cyan}Cyan{/cyan}{/bgcyan} {bgcyan}{white}White{/white}{/bgcyan}'))

    print(Color('    {bgwhite}{black}Black{/black}{/bgwhite} {bgwhite}{red}Red{/red}{/bgwhite} '), end='')
    print(Color('{bgwhite}{green}Green{/green}{/bgwhite} {bgwhite}{yellow}Yellow{/yellow}{/bgwhite} '), end='')
    print(Color('{bgwhite}{blue}Blue{/blue}{/bgwhite} {bgwhite}{magenta}Magenta{/magenta}{/bgwhite} '), end='')
    print(Color('{bgwhite}{cyan}Cyan{/cyan}{/bgwhite} {bgwhite}{white}White{/white}{/bgwhite}'))

if __name__ == '__main__':
    main()


text:
/*
 * This is the UA StyleSheet for <object> and <embed> elements.
 *
 * Such elements, when snapshotted (paused), will contain a ShadowRoot
 * with the following structure:
 *
 * <object>
 *     #ShadowRoot
 *

 *

 *

 *
[Title]

 *
[Subtitle]

 *

 *

 *

 */

embed::-webkit-snapshotted-plugin-content,
object::-webkit-snapshotted-plugin-content
{
    position: relative;
    display: inline-block;
    width: 100%;
    height: 100%;
}

embed::-webkit-snapshotted-plugin-content > .snapshot-overlay,
object::-webkit-snapshotted-plugin-content > .snapshot-overlay
{
    position: absolute;
    top: 5px;
    right: 5px;
    bottom: 5px;
    left: 5px;
    background-color: rgba(255, 255, 255, 0.75);
    cursor: pointer;
    display: -webkit-flex;
    -webkit-justify-content: center;
    -webkit-align-items: center;
}

embed::-webkit-snapshotted-plugin-content > .snapshot-overlay > .snapshot-label,
object::-webkit-snapshotted-plugin-content > .snapshot-overlay > .snapshot-label
{
    color: black;
    -webkit-user-select: none;
}

embed::-webkit-snapshotted-plugin-content > .snapshot-overlay > .snapshot-label > div,
object::-webkit-snapshotted-plugin-content > .snapshot-overlay > .snapshot-label > div
{
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

embed::-webkit-snapshotted-plugin-content > .snapshot-overlay > .snapshot-label > .snapshot-title,
object::-webkit-snapshotted-plugin-content > .snapshot-overlay > .snapshot-label > .snapshot-title
{
    font-weight: bold;
}

embed::-webkit-snapshotted-plugin-content > .snapshot-overlay > .snapshot-label > .snapshot-subtitle,
object::-webkit-snapshotted-plugin-content > .snapshot-overlay > .snapshot-label > .snapshot-subtitle
{
    font-style: italic;
    color: #444;
}


text:
package org.elasticsearch.action.admin.indices.forcemerge;

import org.elasticsearch.action.Action;

public class ForceMergeAction extends Action<ForceMergeResponse> {

    public static final ForceMergeAction INSTANCE = new ForceMergeAction();
    public static final String NAME = "indices:admin/forcemerge";

    private ForceMergeAction() {
        super(NAME);
    }

    @Override
    public ForceMergeResponse newResponse() {
        return new ForceMergeResponse();
    }
}


text:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["CardSlider"] = factory();
	else
		root["CardSlider"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/test/";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	"use strict";
	__webpack_require__(1);

	function CardSlider($el, opt) {
	    var method, _self = this,
	        _clzName = 'card-slider',
	        itemWidth, itemSpace, activeNum, startPos = {},
	        endPos = {};
	    opt = opt || {
	        bar: true
	    };
	    this.events = {
	        'change': []
	    };
	    this.$el = $el;
	    this.$el.addClass(_clzName);
	    this.$elLiList = $el.children('ul').children('li');
	    itemWidth = this.$elLiList.eq(0).width();
	    method = {
	        init: function() {
	            this.initSpace();
	            this.initPos(0);
	            if (opt && opt.bar) {
	                this.initBar();
	            }
	            this.bindEvent();

	        },
	        toRun: function() {
	            var tThis = this;
	            var dir = tThis.checkDir(endPos.x, startPos.x, endPos.y, startPos.y);
	            if (dir === 'left2right') {
	                //向右滑动
	                if (activeNum == 0) {
	                    return;
	                }
	                activeNum--;
	                tThis.activeNumChange(activeNum);
	                $el.children('ul').css({
	                    '-webkit-transform' : 'translateX(' + -itemSpace * (activeNum) + 'px)',
	                    'transform': 'translateX(' + -itemSpace * (activeNum) + 'px)'
	                });
	                Array.prototype.forEach.call(_self.$elLiList, function(item, index) {
	                    var _val = (90 - 90 / _self.$elLiList.length * Math.abs(activeNum - index)) * Math.PI / 180;
	                    var scale = Math.sin(_val);
	                    var zIndex = $(item).css('zIndex');
	                    if (activeNum == index) {
	                        $(item).css({
	                            '-webkit-transform-origin': 'center center',
	                            'transform-origin': 'center center',
	                            '-webkit-transform': 'scale(1)',
	                            'transform': 'scale(' + scale + ')',
	                            'zIndex': zIndex - 0 + 1
	                        });
	                    } else if (activeNum > index) {
	                        $(item).css({
	                            '-webkit-transform-origin': 'left center',
	                            'transform-origin': 'left center',
	                            '-webkit-transform': 'scale(' + scale + ')',
	                            'transform': 'scale(' + scale + ')',
	                            'zIndex': zIndex - 0 + 1
	                        });
	                    } else {
	                        $(item).css({
	                            '-webkit-transform-origin': 'right center',
	                            'transform-origin': 'right center',
	                            '-webkit-transform': 'scale(' + scale + ')',
	                            'transform': 'scale(' + scale + ')',
	                            'zIndex': zIndex - 1
	                        });
	                    }
	                });
	            } else if (dir === 'right2left') {
	                //向左滑动
	                if (activeNum == _self.$elLiList.length - 1) {
	                    return;
	                }
	                activeNum++;
	                tThis.activeNumChange(activeNum);
	                $el.children('ul').css({
	                    '-webkit-transform': 'translateX(' + -itemSpace * (activeNum) + 'px)',
	                    'transform': 'translateX(' + -itemSpace * (activeNum) + 'px)'
	                });
	                Array.prototype.forEach.call(_self.$elLiList, function(item, index) {
	                    var _val = (90 - 90 / _self.$elLiList.length * Math.abs(activeNum - index)) * Math.PI / 180;
	                    var scale = Math.sin(_val);
	                    var zIndex = $(item).css('zIndex');
	                    if (activeNum == index) {
	                        $(item).css({
	                            '-webkit-transform-origin': 'center center',
	                            'transform-origin': 'center center',
	                            '-webkit-transform': 'scale(1)',
	                            'transform': 'scale(' + scale + ')',
	                            'zIndex': zIndex - 0 + 1
	                        });
	                    } else if (activeNum > index) {
	                        $(item).css({
	                            '-webkit-transform-origin': 'left center',
	                            'transform-origin': 'left center',
	                            '-webkit-transform': 'scale(' + scale + ')',
	                            'transform': 'scale(' + scale + ')',
	                            'zIndex': zIndex - 1
	                        });
	                    } else {
	                        $(item).css({
	                            '-webkit-transform-origin': 'right center',
	                            'transform-origin': 'right center',
	                            '-webkit-transform': 'scale(' + scale + ')',
	                            'transform': 'scale(' + scale + ')',
	                            'zIndex': zIndex - 0 + 1
	                        });
	                    }
	                });
	            }
	        },
	        bindEvent: function() {
	            var tThis = this;
	            _self.$elLiList.on('touchstart', function(e) {
	                var touch = e.touches[0];
	                startPos.x = touch.pageX;
	                startPos.y = touch.pageY;
	            });
	            _self.$elLiList.on('touchmove', function(e) {
	                var touch = e.touches[0],
	                    dir;
	                endPos.x = touch.pageX;
	                endPos.y = touch.pageY;
	                throttle(tThis.toRun,tThis);
	            });

	            function throttle(cb, context) {
	                clearTimeout(cb.timmer);
	                cb.timmer = setTimeout(function() {
	                    cb.call(context);
	                }, 50);
	            }
	        },
	        initPos: function(i) {
	            activeNum = i;
	            Array.prototype.forEach.call(_self.$elLiList, function(item, index) {
	                var left = (_self.$el.width() - itemWidth) / 2;
	                var _val = (90 - 90 / _self.$elLiList.length * index) * Math.PI / 180;
	                var scale = Math.sin(_val);

	                $(item).css({
	                    'left': left + index * itemSpace,
	                    'z-index': _self.$elLiList.length - index + 100,
	                    '-ms-transform': 'scale(' + scale + ')',
	                    '-o-transform': 'scale(' + scale + ')',
	                    '-moz-transform': 'scale(' + scale + ')',
	                    '-webkit-transform': 'scale(' + scale + ')',
	                    'transform': 'scale(' + scale + ')',
	                    '-ms-transform-origin': 'right center',
	                    '-o-transform-origin': 'right center',
	                    '-webkit-transform-origin': 'right center',
	                    '-moz-transform-origin': 'right center',
	                    'transform-origin': 'right center'
	                });
	            });
	        },
	        activeNumChange: function(num) {
	            //TODO activeNumChange
	            if (opt.bar) {
	                this.initBarPos();
	            }
	            this.noti('change', num);
	        },
	        initSpace: function() {
	            var width = _self.$el.width();
	            var length = _self.$elLiList.length;
	            itemSpace = (width - itemWidth) / 2 / (length - 1);
	        },
	        initBar: function() {
	            $el.append('

');
	            this.$bar = $el.find('.card-scroll-bar');
	            this.$barBtn = $el.find('.card-bar');
	            this.$barWidth = this.$bar.width();
	            this.$barBtnWidth = this.$barWidth / _self.$elLiList.length;
	            this.$barBtn.css({
	                width: this.$barBtnWidth + 'px'
	            });
	            this.initBarPos();
	        },
	        initBarPos: function() {
	            this.$barBtn.css({
	                '-webkit-transform': 'translateX(' + this.$barBtnWidth * (activeNum) + 'px)',
	                'transform': 'translateX(' + this.$barBtnWidth * (activeNum) + 'px)',
	            });
	        },
	        noti: function() {
	            var name = Array.prototype.slice.call(arguments, 0, 1)[0];
	            var args = Array.prototype.slice.call(arguments, 1);
	            Array.prototype.forEach.call(_self.events[name], function(item) {
	                item.cb.apply(item.scope || null, args);
	            });
	        },
	        /**
	         * 获取手指滑动的方向
	         * @param moveEndX
	         * @param startX
	         * @param moveEndY
	         * @param startY
	         * @returns {*}
	         */
	        checkDir: function(moveEndX, startX, moveEndY, startY) {
	            var X = moveEndX - startX;
	            var Y = moveEndY - startY;
	            if (Math.abs(X) > Math.abs(Y) && X > 0) {
	                return "left2right";
	            } else if (Math.abs(X) > Math.abs(Y) && X < 0) {
	                return "right2left";
	            } else if (Math.abs(Y) > Math.abs(X) && Y > 0) {
	                return "top2bottom";
	            } else if (Math.abs(Y) > Math.abs(X) && Y < 0) {
	                return "bottom2top";
	            }
	        }
	    }
	    method.init();
	}

	CardSlider.prototype.on = function(name, cb, scope) {
	    if (this.events[name]) {
	        this.events[name].push({
	            cb: cb,
	            scope: scope
	        });
	    }
	};

	module.exports = CardSlider;

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	// style-loader: Adds some css to the DOM by adding a


text:
package org.vaadin.spring.sample.nested;

import java.io.Serializable;

@SuppressWarnings("serial")
public class NestedPresenterEvent implements Serializable {

	private final String message;

	public NestedPresenterEvent(final String message) {
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

}


text:
import {
  updateSettings,
  updateFetching,
  updateUserError,
} from '../actions';

import {
  UPDATE_SETTINGS,
  UPDATE_FETCHING,
  UPDATE_USER_ERROR,
} from '../constants';

describe('Settings actions', () => {
  describe('Update Settings Action', () => {
    it('has a type of UPDATE_SETTINGS', () => {
      const form = {
        foo: 'bar',
      };
      const expected = {
        type: UPDATE_SETTINGS,
        form,
      };
      expect(updateSettings(form)).toEqual(expected);
    });
  });
  describe('Update Fetching Action', () => {
    it('has a type of UPDATE_FETCHING', () => {
      const expected = {
        type: UPDATE_FETCHING,
      };
      expect(updateFetching()).toEqual(expected);
    });
  });
  describe('Update User Error Action', () => {
    it('has a type of UPDATE_USER_ERROR', () => {
      const expected = {
        type: UPDATE_USER_ERROR,
      };
      expect(updateUserError()).toEqual(expected);
    });
  });
});


text:
<?php if (!defined('IDIR')) { die; }

/**
* ipb Import Posts
*
*
* @package 		ImpEx.ipb
*
*/
class ipb_007 extends ipb_000
{
	var $_dependent 	= '006';

	function ipb_007(&$displayobject)
	{
		$this->_modulestring = $displayobject->phrases['import_post'];
	}

	function init(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		if ($this->check_order($sessionobject,$this->_dependent))
		{
			if ($this->_restart)
			{
				if ($this->restart($sessionobject, $displayobject, $Db_target, $Db_source,'clear_imported_posts'))
				{
					$displayobject->display_now("
{$displayobject->phrases['post_restart_ok']}
");
					$this->_restart = true;
				}
				else
				{
					$sessionobject->add_error(substr(get_class($this) , -3), $displayobject->phrases['post_restart_failed'], $displayobject->phrases['check_db_permissions']);
				}
			}

			// Start up the table
			$displayobject->update_basic('title', $displayobject->phrases['import_post']);
			$displayobject->update_html($displayobject->do_form_header('index',substr(get_class($this) , -3)));
			$displayobject->update_html($displayobject->make_hidden_code(substr(get_class($this) , -3),'WORKING'));
			$displayobject->update_html($displayobject->make_table_header($displayobject->phrases['import_post']));

			// Ask some questions
			$displayobject->update_html($displayobject->make_input_code($displayobject->phrases['posts_per_page'],'postperpage',2000));

			// End the table
			$displayobject->update_html($displayobject->do_form_footer($displayobject->phrases['continue'],$displayobject->phrases['reset']));

			// Reset/Setup counters for this
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_done', '0');
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_failed', '0');
			$sessionobject->add_session_var('poststartat','0');
		}
		else
		{
			// Dependant has not been run
			$displayobject->update_html($displayobject->do_form_header('index',''));
			$displayobject->update_html($displayobject->make_description("
{$displayobject->phrases['dependant_on']} " . $sessionobject->get_module_title($this->_dependent) . " {$displayobject->phrases['cant_run']} ."));
			$displayobject->update_html($displayobject->do_form_footer($displayobject->phrases['continue'], ''));
			$sessionobject->set_session_var(substr(get_class($this) , -3),'FALSE');
			$sessionobject->set_session_var('module','000');
		}
	}

	function resume(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		$displayobject->update_basic('displaymodules','FALSE');
		// Set up working variables.
		$target_database_type 	= $sessionobject->get_session_var('targetdatabasetype');
		$target_table_prefix  	= $sessionobject->get_session_var('targettableprefix');
		$source_database_type 	= $sessionobject->get_session_var('sourcedatabasetype');
		$source_table_prefix  	= $sessionobject->get_session_var('sourcetableprefix');

		// Called this, though it is actuall the number of threads "worth" of posts per page.
		$post_start_at 			= $sessionobject->get_session_var('poststartat');
		$posts_per_page 		= $sessionobject->get_session_var('postperpage');
		$class_num				= substr(get_class($this), -3);
		$idcache 				= new ImpExCache($Db_target, $target_database_type, $target_table_prefix);

		if(!$sessionobject->get_session_var($class_num . '_start'))
		{
			$sessionobject->timing($class_num,'start' ,$sessionobject->get_session_var('autosubmit'));
		}

		if(intval($posts_per_page) == 0)
		{
			$posts_per_page = 500;
		}

		#$post_array				= $this->get_ipb_posts_details($Db_source, $source_database_type, $source_table_prefix, $post_start_at, $posts_per_page);
		$post_array = $this->get_source_data($Db_source, $source_database_type, "{$source_table_prefix}posts", 'pid', 0, $post_start_at, $posts_per_page);
		#$thread_ids				= $this->get_threads_ids($Db_target, $target_database_type, $target_table_prefix);
		#$users_ids 				= $this->get_user_ids($Db_target, $target_database_type, $target_table_prefix);

		$displayobject->display_now("
{$displayobject->phrases['importing']} " . $post_array['count'] . " {$displayobject->phrases['posts']}

{$displayobject->phrases['from']} : " . $post_start_at . " ::  {$displayobject->phrases['to']} : " . ($post_start_at + $post_array['count']) . "
");

		$post_object = new ImpExData($Db_target,$sessionobject,'post');

		foreach($post_array['data'] as $post_id => $post)
		{
			$try = (phpversion() < '5' ? $post_object : clone($post_object));

			$try->set_value('mandatory', 'threadid', 			$idcache->get_id('thread', $post['topic_id']));
			$try->set_value('mandatory', 'userid', 				$idcache->get_id('user', $post['author_id']));
			$try->set_value('mandatory', 'importthreadid', 		$post['topic_id']);

			$try->set_value('nonmandatory', 'importpostid',		$post_id);
			$try->set_value('nonmandatory', 'dateline',			$post['post_date']);
			$try->set_value('nonmandatory', 'showsignature', 	$post['use_sig']);
			$try->set_value('nonmandatory', 'username', 		$post['author_name']);
			$try->set_value('nonmandatory', 'allowsmilie',		$post['use_emo']);
			$try->set_value('nonmandatory', 'ipaddress',		$post['ip_address']);
			$try->set_value('nonmandatory', 'pagetext', 		$this->html_2_bb($this->ipb_html($post['post'])));
			$try->set_value('nonmandatory', 'visible',			'1');
			$try->set_value('nonmandatory', 'title', 			$post['post_title']);

			if($try->is_valid())
			{
				if($try->import_post($Db_target,$target_database_type,$target_table_prefix))
				{
					$displayobject->display_now('
' . $try->how_complete() . '% ' . $displayobject->phrases['post'] . ' -> ' . $try->get_value('nonmandatory','username'));
					$sessionobject->add_session_var($class_num . '_objects_done',intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1 );
				}
				else
				{
					$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
					$sessionobject->add_error($post_id, $displayobject->phrases['post_not_imported'], $displayobject->phrases['post_not_imported_rem']);
					$displayobject->display_now("
{$displayobject->phrases['failed']} :: {$displayobject->phrases['post_not_imported']}");
				}
			}
			else
			{
				$displayobject->display_now("
{$displayobject->phrases['invalid_object']}" . $try->_failedon);
				$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
			}
			unset($try);
		}

		if ($post_array['count'] == 0 OR $post_array['count'] < $posts_per_page)
		{
			$displayobject->display_now($displayobject->phrases['updating_parent_id']);

			if ($this->update_post_parent_ids($Db_target, $target_database_type, $target_table_prefix))
			{
				$displayobject->display_now($displayobject->phrases['successful']);
			}
			else
			{
				$displayobject->display_now($displayobject->phrases['failed']);
			}

			$sessionobject->timing($class_num,'stop', $sessionobject->get_session_var('autosubmit'));
			$sessionobject->remove_session_var($class_num . '_start');

			$displayobject->update_html($displayobject->module_finished($this->_modulestring,
				$sessionobject->return_stats($class_num, '_time_taken'),
				$sessionobject->return_stats($class_num, '_objects_done'),
				$sessionobject->return_stats($class_num, '_objects_failed')
			));

			$sessionobject->set_session_var($class_num, 'FINISHED');
			$sessionobject->set_session_var('module','000');
			$sessionobject->set_session_var('autosubmit','0');
		}

		$sessionobject->set_session_var('poststartat', $post_array['lastid']);
		$displayobject->update_html($displayobject->print_redirect('index.php',$sessionobject->get_session_var('pagespeed')));
	}// End resume
}//End Class
/*======================================================================*/
?>


text:
{{! Initialize Reveal and call any other JavaScripts you like from here}}
<script>
  Reveal.initialize({{source options}});
</script>


text:
NS_ASSUME_NONNULL_BEGIN

@interface NSString (Extended)

- (BOOL)isEmpty;

@end

NS_ASSUME_NONNULL_END


text:
layout: post #
title: 241 Por # Generat automàticament
date: 2018-03-04 # Data
description:  # Argument
keywords:  # Paraules clau
coments:  # Comentaris
---

Quan **evitem** el que **temem**,

els nostres **temors creixen**

fins que comencen a **controlar**

tots els aspectes

de la nostra vida.

A mesura que augmenten,

la nostra **autoestima**,

la nostra **autoconfiança**

i el nostre **autorespecte** disminueixen.

Bryan Traci


text:
/**
 * @module multi-model-requests/batch-write
 */
import * as DynamoDB from 'aws-sdk/clients/dynamodb'
import { promiseDelay } from '../../helper/promise-delay.function'
import { DynamoDbWrapper } from '../dynamo-db-wrapper'

/**
 * Function which executes batchWriteItem operations until all given items (as params) are processed (written).
 * Between each follow-up request (in case of unprocessed items) a delay is interposed calculated by the given backoffTime and throttleTimeSlot.
 * @param dynamoDBWrapper
 * @param params containing the items per table to create the batchWrite operation
 * @param backoffTimer used to determine how many time slots the follow-up request should be delayed
 * @param throttleTimeSlot used to calculate the effective wait time
 * @hidden
 */
export function batchWriteItemsWriteAll(
  dynamoDBWrapper: DynamoDbWrapper,
  params: DynamoDB.BatchWriteItemInput,
  backoffTimer: IterableIterator<number>,
  throttleTimeSlot: number,
): Promise<DynamoDB.BatchGetItemOutput> {
  return dynamoDBWrapper.batchWriteItem(params).then((response) => {
    if (hasUnprocessedItems(response)) {
      // in case of unprocessedItems do a follow-up requests
      return (
        Promise.resolve(response.UnprocessedItems)
          // delay before doing the follow-up request
          .then(promiseDelay(backoffTimer.next().value * throttleTimeSlot))
          .then((unprocessedKeys) => {
            const nextParams: DynamoDB.BatchWriteItemInput = { ...params, RequestItems: unprocessedKeys }
            // call recursively batchWriteItemsWriteAll with the returned UnprocessedItems params
            return batchWriteItemsWriteAll(dynamoDBWrapper, nextParams, backoffTimer, throttleTimeSlot)
          })
      )
      // no combining of responses necessary, only the last response is returned
    }
    // no follow-up request necessary, return result
    return response
  })
}

/**
 * @hidden
 */
export type BatchWriteItemOutputWithUnprocessedItems = DynamoDB.BatchWriteItemOutput & {
  UnprocessedItems: DynamoDB.BatchWriteItemRequestMap
}

/**
 * @hidden
 */
export function hasUnprocessedItems(
  response: DynamoDB.BatchWriteItemOutput,
): response is BatchWriteItemOutputWithUnprocessedItems {
  if (!response.UnprocessedItems) {
    return false
  }
  return Object.values(response.UnprocessedItems).some((t) => !!t && t.length > 0)
}


text:
@class NSString;

@interface WCCardAcceptSeed : MMObject
{
    unsigned int _fromScene;
    unsigned int _statScene;
    unsigned int _followService;
    NSString *_cardId;
    NSString *_cardExt;
    NSString *_fromUserName;
    NSString *_chatName;
    NSString *_webUrl;
    NSString *_templateMsgId;
    NSString *_recommendCardId;
}

@property(retain, nonatomic) NSString *recommendCardId; // @synthesize recommendCardId=_recommendCardId;
@property(retain, nonatomic) NSString *templateMsgId; // @synthesize templateMsgId=_templateMsgId;
@property(nonatomic) unsigned int followService; // @synthesize followService=_followService;
@property(nonatomic) unsigned int statScene; // @synthesize statScene=_statScene;
@property(retain, nonatomic) NSString *webUrl; // @synthesize webUrl=_webUrl;
@property(retain, nonatomic) NSString *chatName; // @synthesize chatName=_chatName;
@property(nonatomic) unsigned int fromScene; // @synthesize fromScene=_fromScene;
@property(retain, nonatomic) NSString *fromUserName; // @synthesize fromUserName=_fromUserName;
@property(retain, nonatomic) NSString *cardExt; // @synthesize cardExt=_cardExt;
@property(retain, nonatomic) NSString *cardId; // @synthesize cardId=_cardId;
- (void).cxx_destruct;
- (void)dealloc;

@end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$_site_config_routes = _multisite_get_config('routes');

include_once($_site_config_routes);


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.RegularExpressions;
using BenchmarkDotNet.Helpers;
using BenchmarkDotNet.Portability.Cpu;
using JetBrains.Annotations;
using Perfolizer.Horology;
using NotNullAttribute = JetBrains.Annotations.NotNullAttribute;

namespace BenchmarkDotNet.Environments
{
    public static class ProcessorBrandStringHelper
    {
        /// <summary>
        /// Transform a processor brand string to a nice form for summary.
        /// </summary>
        /// <param name="cpuInfo">The CPU information</param>
        /// <param name="includeMaxFrequency">Whether to include determined max frequency information</param>
        /// <returns>Prettified version</returns>
        [NotNull]
        public static string Prettify(CpuInfo cpuInfo, bool includeMaxFrequency = false)
        {
            if (cpuInfo == null || string.IsNullOrEmpty(cpuInfo.ProcessorName))
            {
                return "Unknown processor";
            }

            // Remove parts which don't provide any useful information for user
            var processorName = cpuInfo.ProcessorName.Replace("@", "").Replace("(R)", "").Replace("(TM)", "");

            // If we have found physical core(s), we can safely assume we can drop extra info from brand
            if (cpuInfo.PhysicalCoreCount.HasValue && cpuInfo.PhysicalCoreCount.Value > 0)
                processorName = Regex.Replace(processorName, @"(\w+?-Core Processor)", "").Trim();

            string frequencyString = GetBrandStyledActualFrequency(cpuInfo.NominalFrequency);
            if (includeMaxFrequency && frequencyString != null && !processorName.Contains(frequencyString))
            {
                // show Max only if there's already a frequency name to differentiate the two
                string maxFrequency = processorName.Contains("Hz") ? $"(Max: {frequencyString})" : frequencyString;
                processorName = $"{processorName} {maxFrequency}";
            }

            // Remove double spaces
            processorName = Regex.Replace(processorName.Trim(), @"\s+", " ");

            // Add microarchitecture name if known
            string microarchitecture = ParseMicroarchitecture(processorName);
            if (microarchitecture != null)
                processorName = $"{processorName} ({microarchitecture})";

            return processorName;
        }

        /// <summary>
        /// Presents actual processor's frequency into brand string format
        /// </summary>
        /// <param name="frequency"></param>
        private static string GetBrandStyledActualFrequency(Frequency? frequency)
        {
            if (frequency == null)
                return null;
            return $"{frequency.Value.ToGHz().ToString("N2", DefaultCultureInfo.Instance)}GHz";
        }

        /// <summary>
        /// Parse a processor name and tries to return a microarchitecture name.
        /// Works only for well-known microarchitectures.
        /// </summary>
        [CanBeNull]
        private static string ParseMicroarchitecture([NotNull] string processorName)
        {
            if (processorName.StartsWith("Intel Core"))
            {
                string model = processorName.Substring("Intel Core".Length).Trim();

                // Core i3/5/7/9
                if (
                    model.Length > 4 &&
                    model[0] == 'i' &&
                    (model[1] == '3' || model[1] == '5' || model[1] == '7' || model[1] == '9') &&
                    (model[2] == '-' || model[2] == ' '))
                {
                    string modelNumber = model.Substring(3);
                    if (modelNumber.StartsWith("CPU"))
                        modelNumber = modelNumber.Substring(3).Trim();
                    if (modelNumber.Contains("CPU"))
                        modelNumber = modelNumber.Substring(0, modelNumber.IndexOf("CPU", StringComparison.Ordinal)).Trim();
                    return ParseIntelCoreMicroarchitecture(modelNumber);
                }
            }

            return null;
        }

        private static readonly Lazy<Dictionary<string, string>> KnownMicroarchitectures = new Lazy<Dictionary<string, string>>(() =>
        {
            var data = ResourceHelper.LoadResource("BenchmarkDotNet.Environments.microarchitectures.txt").Split('\r', '\n');
            var dictionary = new Dictionary<string, string>();
            string currentMicroarchitecture = null;
            foreach (string line in data)
            {
               if (line.StartsWith("//") || string.IsNullOrWhiteSpace(line))
                   continue;
               if (line.StartsWith("#"))
               {
                   currentMicroarchitecture = line.Substring(1).Trim();
                   continue;
               }

               string modelNumber = line.Trim();
               if (dictionary.ContainsKey(modelNumber))
                   throw new Exception($"{modelNumber} is defined twice in microarchitectures.txt");
               if (currentMicroarchitecture == null)
                   throw new Exception($"{modelNumber} doesn't have defined microarchitecture in microarchitectures.txt");
               dictionary[modelNumber] = currentMicroarchitecture;
            }

            return dictionary;
        });

        // see http://www.intel.com/content/www/us/en/processors/processor-numbers.html
        [CanBeNull]
        [SuppressMessage("ReSharper", "StringLiteralTypo")]
        internal static string ParseIntelCoreMicroarchitecture([NotNull] string modelNumber)
        {
            if (KnownMicroarchitectures.Value.ContainsKey(modelNumber))
                return KnownMicroarchitectures.Value[modelNumber];

            if (modelNumber.Length >= 3 && modelNumber.Substring(0, 3).All(char.IsDigit) &&
                (modelNumber.Length == 3 || !char.IsDigit(modelNumber[3])))
                return "Nehalem";
            if (modelNumber.Length >= 4 && modelNumber.Substring(0, 4).All(char.IsDigit))
            {
                char generation = modelNumber[0];
                switch (generation)
                {
                    case '2':
                        return "Sandy Bridge";
                    case '3':
                        return "Ivy Bridge";
                    case '4':
                        return "Haswell";
                    case '5':
                        return "Broadwell";
                    case '6':
                        return "Skylake";
                    case '7':
                        return "Kaby Lake";
                    case '8':
                        return "Coffee Lake";
                    default:
                        return null;
                }
            }
            return null;
        }
    }
}


text:
(function($) {

var ver = '0.2';

jQuery.fn.blockify = function(options) {

	// iterate and reformat each matched element
	return this.each(function() {
		var $this = $(this);
		var opts = $.extend({}, $.fn.blockify.defaults, options);

		var elm = $this.find(opts.selector);

		//	exit if there's no link found-based on
		if (elm.length < 1) return;

		//	if user option true, use mouse pointer on hover:
		if (opts.pointer) $(this).css({cursor:'pointer'});

		//	add hover class to element for custom styling
		if (opts.hoverClass) {
			$this.hover(function(){
				$(this).addClass(opts.hoverClass);
			},function(){
				$(this).removeClass(opts.hoverClass);
			});
		};

		$this.click(function(e){
			if (e.target.nodeName.toLowerCase() != 'a') {
				//	target is not a standard <a> link.

				//	make sure no text has been selected:
				if(getSelectedText() == "") {
					/*
						tried to trigger click on elm here, but got stuck on recursion
						equivalent to elm.click() would be ideal and we could get rid of externalClass crap
					*/
					if (elm.hasClass(opts.externalClass)) {
						window.open(elm.attr('href'));
					}else{
						window.location = elm.attr('href');
					};
				};
			};
		});

	});
};

//	defaults
$.fn.blockify.defaults = {
	selector:'a:last',		//	selector to specific anchor (or other element), in case there's more than one!
	pointer:true,			//	if true, sets css cursor to pointer
	hoverClass:'hover',		//	class attached to element on hover
	externalClass:'ext'		//	if target anchor has this class, link will be opened in a new window
};

//	public function/method
$.fn.blockify.ver = function() { return "jquery.blockify ver. " + ver; };

//	get selected text:
//	from http://newism.com.au/blog/post/58/bigtarget-js-increasing-the-size-of-clickable-targets/
function getSelectedText(){
	if(window.getSelection){
		return window.getSelection().toString();
	}
	else if(document.getSelection){
		return document.getSelection();
	}
	else if(document.selection){
		return document.selection.createRange().text;
	}
};

// end of closure
})(jQuery);


text:
iIt's not that different for ARM-Linux targets, it's almost same as [Build for Linux](Build-for-Linux.md) page.

### Prerequisite

Install arm linux cross compiler

```
sudo apt-get install gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf
```

### Raspberry Pi 2 build
Giving `target-arch` and `target-os` will do. Rest is up to cross compiler and make system.

```
./tools/build.py --buildtype=release --noinit-submodule \
--target-arch=arm --target-os=linux
```

### Running in Raspberry Pi 2

Output program will be `build/arm-linux/release/iotjs/iotjs` or `build/arm-linux/debug/iotjs/iotjs`.
Copy using your favorite tool or `scp` like below.

```
scp build/arm-linux/release/iotjs/iotjs pi@(your RPi2 IP):/home/pi/.
```

Open a shell and run with your test program.

```
ssh pi@(your RPi2 IP)
./iotjs (your test program)
```

### Building in Raspberry Pi 2 ?

Not yet. Maybe someone out there?


text:
Add the power of events to your projects. We even have 3 flavors for you.

[![Build Status](https://github.com/KeesCBakker/Strongly-Typed-Events-for-TypeScript/actions/workflows/node.js.yml/badge.svg)](https://github.com/KeesCBakker/Strongly-Typed-Events-for-TypeScript/actions/workflows/node.js.yml)
[![npm version](https://badge.fury.io/js/strongly-typed-events.svg)](https://badge.fury.io/js/strongly-typed-events)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Event types
This project gives you the following event types:
- **Events** - styled after the way .Net implements events. With each event you'll get a `sender` and an `argument` object. If you use typescript, you can implement them using generics.
`npm install ste-events` or `npm install ste-promise-events` for event handlers that support `Promise`.
- **Simple events** - basically the same thing, with only an argument.
`npm install ste-simple-events` or `npm install ste-promise-simple-events` for event handlers that support `Promise`.
- **Signals** - for when no data is needed, just the firing of the event is enough.
`npm install ste-signals` or `npm install ste-promise-signals` for event handlers that support `Promise`.
- You want them all? Just use
`npm install strongly-typed-events`.

### Subscription made easy
An example says more than a 1000 words. Imagine if you have events like this on your class:
```typescript
let clock = new Clock("Smu", 1000);

//log the ticks to the console - this is a signal event
clock.onTick.subscribe(() => console.log("Tick!"));

//log the sequence parameter to the console - this is a simple event
clock.onSequenceTick.subscribe(s => console.log(`Sequence: ${s}`));

//log the name of the clock and the tick argument to the console - this is an event
clock.onClockTick.subscribe((c, n) =>
  console.log(`${c.name} ticked ${n} times.`)
);
```

### Events made easy
So let's look at the implementation from a TypeScript perspective. (Do you program NodeJs without typescript? Check this.)

```typescript
import { SignalDispatcher, SimpleEventDispatcher, EventDispatcher } from "strongly-typed-events";

class Clock {
  private _onTick = new SignalDispatcher();
  private _onSequenceTick = new SimpleEventDispatcher<number>();
  private _onClockTick = new EventDispatcher<Clock, number>();
  private _ticks: number = 0;

  constructor(public name: string, timeout: number) {
    setInterval(() => {
      this._ticks += 1;
      this._onTick.dispatch();
      this._onSequenceTick.dispatch(this._ticks);
      this._onClockTick.dispatch(this, this._ticks);
    }, timeout);
  }

  public get onTick() {
    return this._onTick.asEvent();
  }

  public get onSequenceTick() {
    return this._onSequenceTick.asEvent();
  }

  public get onClockTick() {
    return this._onClockTick.asEvent();
  }
}
```

### Stopping events
You can stop events from being propagated.

```typescript
let dispatcher = new SignalDispatcher();

  let a = 0;
  dispatcher.sub(ev => {
    a++;
    if (a > 2) {
      ev.stopPropagation();
    }
  });

  let b = 0;
  dispatcher.sub(() => { b++; });

  dispatcher.dispatch();
  dispatcher.dispatch();
  dispatcher.dispatch();
  dispatcher.dispatch();

  // a should be 4, because 4 dispatches are done.");
  // b should be 2, because events after the 2nd dispatch are stopped."

```

Check the documentation or the examples for more information.

## Documentation
This project will help you to add events, event handling en event dispatching to your classes. To get you started, check:

- How to add an event to a class?
- How to add an event to an interface?
- How to add multiple events to a class?
- How to add dynamic named events to a class?
- How to do asynchronous event dispatching?
- On events, dispatchers and lists (a general explanation of the system)
- How to use Strongly Typed Events in Node.js?
- Some unsubscribe strategies

## History
Click here for more history...

## Packages
Want a smaller package? Check out on of these:

|Package|Description|
|-------|-----------|
|`ste-core`|Package that contains all the building blocks for the creation of events. The dispatcher implementation is its main hero.|
|`ste-events` or `ste-promise-events`|Events that are modeled after .Net with a `sender` and `argument`. If you use typescript, you can leverage the support for generics and get strongly typed code.|
|`ste-simple-events` or `ste-promise-simple-events`|A simpler version of the `ste-event`-event. No sender, just an argument.|
|`ste-signals` or `ste-promise-signals`|A signal is even simpler, it is just a callback for when you need to be alerted without any scope.|
|`strongly-typed-events`|This package includes everything.|
|`ste-browser`|Helps to host events in the browser.|

## Maintenance
This project is maintained by Kees C. Bakker.


text:
/*
 * Created on Oct 14, 2004
 */
package com.foc.list;

import com.foc.db.*;
import com.foc.desc.FocDesc;
import com.foc.desc.FocObject;

/**
 * @author 01Barmaja
 */
public class FocLinkSimple extends FocLink {

  public FocLinkSimple(FocDesc slaveDesc) {
    super(null, slaveDesc);
  }

  public FocDesc getLinkTableDesc() {
    return null;
  }

  public void adaptSQLFilter(FocList list, SQLFilter filter) {
  }

  public boolean saveDB(FocList focList) {
    /*
     * Iterator iter = focList.focObjectIterator(); while(iter.hasNext()){
     * FocObject obj = (FocObject)iter.next(); if(obj != null){ obj.save(); } }
     */

    return false;
  }

  public boolean canDeleteDB(FocList focList) {
    return true;
  }

  public boolean deleteDB(FocList focList) {
    return false;
  }

	@Override
	public boolean loadDB(FocList focList, long refToUpdateIncementally) {
		return loadDBDefault(focList, refToUpdateIncementally);
	}

  public boolean loadDB(FocList focList) {
    return loadDB(focList, 0);
  }

  public boolean disposeList(FocList list){
    list.dispose();
    return true;
  }

  /* (non-Javadoc)
   * @see b01.foc.list.FocLink#copy(b01.foc.list.FocList, b01.foc.list.FocList)
   */
  public void copy(FocList targetList, FocList sourceList) {
    super.copyDefault(targetList, sourceList, true);
  }

  public FocObject getSingleTableDisplayObject(FocList list){
    return null;
  }

}