text:
package simpledb;

import Zql.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.*;

import jline.ArgumentCompletor;
import jline.ConsoleReader;
import jline.SimpleCompletor;

public class Parser {
    static boolean explain = false;
    private final Function<Void, LogicalPlan> planFactory;

    public Parser(Function<Void, LogicalPlan> planFactory) {
    	this.planFactory = planFactory;
    }

    public Parser(double alpha, boolean imputeAtBase) {
        this(x -> new ImputedLogicalPlan(alpha, imputeAtBase));
    }

    public Parser() {
        // if none specified, we default to best quality but not at base
        this(0.0, false);
    }

    public static Predicate.Op getOp(String s) throws simpledb.ParsingException {
        if (s.equals("="))
            return Predicate.Op.EQUALS;
        if (s.equals(">"))
            return Predicate.Op.GREATER_THAN;
        if (s.equals(">="))
            return Predicate.Op.GREATER_THAN_OR_EQ;
        if (s.equals("<"))
            return Predicate.Op.LESS_THAN;
        if (s.equals("<="))
            return Predicate.Op.LESS_THAN_OR_EQ;
        if (s.equals("LIKE"))
            return Predicate.Op.LIKE;
        if (s.equals("~"))
            return Predicate.Op.LIKE;
        if (s.equals("<>"))
            return Predicate.Op.NOT_EQUALS;
        if (s.equals("!="))
            return Predicate.Op.NOT_EQUALS;

        throw new simpledb.ParsingException("Unknown predicate " + s);
    }

    void processExpression(TransactionId tid, ZExpression wx, LogicalPlan lp)
            throws simpledb.ParsingException {
        if (wx.getOperator().equals("AND")) {
            for (int i = 0; i < wx.nbOperands(); i++) {
                if (!(wx.getOperand(i) instanceof ZExpression)) {
                    throw new simpledb.ParsingException(
                            "Nested queries are currently unsupported.");
                }
                ZExpression newWx = (ZExpression) wx.getOperand(i);
                processExpression(tid, newWx, lp);

            }
        } else if (wx.getOperator().equals("OR")) {
            throw new simpledb.ParsingException(
                    "OR expressions currently unsupported.");
        } else {
            // this is a binary expression comparing two constants
            @SuppressWarnings("unchecked")
            Vector<ZExp> ops = wx.getOperands();
            if (ops.size() != 2) {
                throw new simpledb.ParsingException(
                        "Only simple binary expresssions of the form A op B are currently supported.");
            }

            boolean isJoin = false;
            Predicate.Op op = getOp(wx.getOperator());

            boolean op1const = ops.elementAt(0) instanceof ZConstant; // otherwise
                                                                      // is a
                                                                      // Query
            boolean op2const = ops.elementAt(1) instanceof ZConstant; // otherwise
                                                                      // is a
                                                                      // Query
            if (op1const && op2const) {
                isJoin = ((ZConstant) ops.elementAt(0)).getType() == ZConstant.COLUMNNAME
                        && ((ZConstant) ops.elementAt(1)).getType() == ZConstant.COLUMNNAME;
            } else if (ops.elementAt(0) instanceof ZQuery
                    || ops.elementAt(1) instanceof ZQuery) {
                isJoin = true;
            } else if (ops.elementAt(0) instanceof ZExpression
                    || ops.elementAt(1) instanceof ZExpression) {
                throw new simpledb.ParsingException(
                        "Only simple binary expresssions of the form A op B are currently supported, where A or B are fields, constants, or subqueries.");
            } else
                isJoin = false;

            if (isJoin) { // join node

                String tab1field = "", tab2field = "";

                if (!op1const) { // left op is a nested query
                    // generate a virtual table for the left op
                    // this isn't a valid ZQL query
                } else {
                    tab1field = ((ZConstant) ops.elementAt(0)).getValue();

                }

                if (!op2const) { // right op is a nested query
                    try {
                        LogicalPlan sublp = parseQueryLogicalPlan(tid,
                                (ZQuery) ops.elementAt(1));
                        DbIterator pp = sublp.physicalPlan(tid,
                                TableStats.getStatsMap(), explain);
                        lp.addJoin(tab1field, pp, op);
                    } catch (IOException e) {
                        throw new simpledb.ParsingException("Invalid subquery "
                                + ops.elementAt(1));
                    } catch (Zql.ParseException e) {
                        throw new simpledb.ParsingException("Invalid subquery "
                                + ops.elementAt(1));
                    }
                } else {
                    tab2field = ((ZConstant) ops.elementAt(1)).getValue();
                    lp.addJoin(tab1field, tab2field, op);
                }

            } else { // select node
                String column;
                String compValue;
                ZConstant op1 = (ZConstant) ops.elementAt(0);
                ZConstant op2 = (ZConstant) ops.elementAt(1);
                if (op1.getType() == ZConstant.COLUMNNAME) {
                    column = op1.getValue();
                    compValue = new String(op2.getValue());
                } else {
                    column = op2.getValue();
                    compValue = new String(op1.getValue());
                }

                lp.addFilter(column, op, compValue);

            }
        }

    }

    public LogicalPlan parseQueryLogicalPlan(TransactionId tid, ZQuery q)
            throws IOException, Zql.ParseException, simpledb.ParsingException {
        @SuppressWarnings("unchecked")
        Vector<ZFromItem> from = q.getFrom();
        LogicalPlan lp = planFactory.apply(null);
        lp.setQuery(q.toString());
        // walk through tables in the FROM clause
        for (int i = 0; i < from.size(); i++) {
            ZFromItem fromIt = from.elementAt(i);
            try {

                int id = Database.getCatalog().getTableId(fromIt.getTable()); // will
                                                                              // fall
                                                                              // through
                                                                              // if
                                                                              // table
                                                                              // doesn't
                                                                              // exist
                String name;

                if (fromIt.getAlias() != null)
                    name = fromIt.getAlias();
                else
                    name = fromIt.getTable();

                lp.addScan(id, name);

                // XXX handle subquery?
            } catch (NoSuchElementException e) {
                e.printStackTrace();
                throw new simpledb.ParsingException("Table "
                        + fromIt.getTable() + " is not in catalog");
            }
        }

        // now parse the where clause, creating Filter and Join nodes as needed
        ZExp w = q.getWhere();
        if (w != null) {

            if (!(w instanceof ZExpression)) {
                throw new simpledb.ParsingException(
                        "Nested queries are currently unsupported.");
            }
            ZExpression wx = (ZExpression) w;
            processExpression(tid, wx, lp);

        }

        // now look for group by fields
        ZGroupBy gby = q.getGroupBy();
        String groupByField = null;
        if (gby != null) {
            @SuppressWarnings("unchecked")
            Vector<ZExp> gbs = gby.getGroupBy();
            if (gbs.size() > 1) {
                throw new simpledb.ParsingException(
                        "At most one grouping field expression supported.");
            }
            if (gbs.size() == 1) {
                ZExp gbe = gbs.elementAt(0);
                if (!(gbe instanceof ZConstant)) {
                    throw new simpledb.ParsingException(
                            "Complex grouping expressions (" + gbe
                                    + ") not supported.");
                }
                groupByField = ((ZConstant) gbe).getValue();
                System.out.println("GROUP BY FIELD : " + groupByField);
            }

        }

        // walk the select list, pick out aggregates, and check for query
        // validity
        @SuppressWarnings("unchecked")
        Vector<ZSelectItem> selectList = q.getSelect();
        String aggField = null;
        String aggFun = null;

        for (int i = 0; i < selectList.size(); i++) {
            ZSelectItem si = selectList.elementAt(i);
            if (si.getAggregate() == null
                    && (si.isExpression() && !(si.getExpression() instanceof ZConstant))) {
                throw new simpledb.ParsingException(
                        "Expressions in SELECT list are not supported.");
            }
            if (si.getAggregate() != null) {
                if (aggField != null) {
                    throw new simpledb.ParsingException(
                            "Aggregates over multiple fields not supported.");
                }
                aggField = ((ZConstant) ((ZExpression) si.getExpression())
                        .getOperand(0)).getValue();
                aggFun = si.getAggregate();
                System.out.println("Aggregate field is " + aggField
                        + ", agg fun is : " + aggFun);
                lp.addProjectField(aggField, aggFun);
            } else {
                if (groupByField != null
                        && !(groupByField.equals(si.getTable() + "."
                                + si.getColumn()) || groupByField.equals(si
                                .getColumn()))) {
                    throw new simpledb.ParsingException("Non-aggregate field "
                            + si.getColumn()
                            + " does not appear in GROUP BY list.");
                }
                lp.addProjectField(si.getTable() + "." + si.getColumn(), null);
            }
        }

        if (groupByField != null && aggFun == null) {
            throw new simpledb.ParsingException("GROUP BY without aggregation.");
        }

        if (aggFun != null) {
            lp.addAggregate(aggFun, aggField, groupByField);
        }
        // sort the data

        if (q.getOrderBy() != null) {
            @SuppressWarnings("unchecked")
            Vector<ZOrderBy> obys = q.getOrderBy();
            if (obys.size() > 1) {
                throw new simpledb.ParsingException(
                        "Multi-attribute ORDER BY is not supported.");
            }
            ZOrderBy oby = obys.elementAt(0);
            if (!(oby.getExpression() instanceof ZConstant)) {
                throw new simpledb.ParsingException(
                        "Complex ORDER BY's are not supported");
            }
            ZConstant f = (ZConstant) oby.getExpression();

            lp.addOrderBy(f.getValue(), oby.getAscOrder());

        }
        return lp;
    }

    private Transaction curtrans = null;
    private boolean inUserTrans = false;

    public Query handleQueryStatement(ZQuery s, TransactionId tId)
            throws TransactionAbortedException, DbException, IOException,
            simpledb.ParsingException, Zql.ParseException {
        Query query = new Query(tId);

        LogicalPlan lp = parseQueryLogicalPlan(tId, s);
        DbIterator physicalPlan = lp.physicalPlan(tId,
                TableStats.getStatsMap(), explain);
        query.setPhysicalPlan(physicalPlan);
        query.setLogicalPlan(lp);

        if (physicalPlan != null) {
            Class<?> c;
            try {
                c = Class.forName("simpledb.OperatorCardinality");

                Class<?> p = Operator.class;
                Class<?> h = Map.class;

                java.lang.reflect.Method m = c.getMethod(
                        "updateOperatorCardinality", p, h, h);

                System.out.println("The query plan is:");
                m.invoke(null, (Operator) physicalPlan,
                        lp.getTableAliasToIdMapping(), TableStats.getStatsMap());
                c = Class.forName("simpledb.QueryPlanVisualizer");
                m = c.getMethod(
                        "printQueryPlanTree", DbIterator.class, System.out.getClass());
                m.invoke(c.newInstance(), physicalPlan,System.out);
            } catch (ClassNotFoundException e) {
            } catch (SecurityException e) {
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }

        return query;
    }

    public Query handleQueryStatementSilent(ZQuery s, TransactionId tId)
            throws TransactionAbortedException, DbException, IOException,
            simpledb.ParsingException, Zql.ParseException {
        Query query = new Query(tId);
        LogicalPlan lp = parseQueryLogicalPlan(tId, s);
        DbIterator physicalPlan = lp.physicalPlan(tId,
                TableStats.getStatsMap(), explain);
        query.setPhysicalPlan(physicalPlan);
        query.setLogicalPlan(lp);
        return query;
    }

    public Query handleInsertStatement(ZInsert s, TransactionId tId)
            throws TransactionAbortedException, DbException, IOException,
            simpledb.ParsingException, Zql.ParseException {
        int tableId;
        try {
            tableId = Database.getCatalog().getTableId(s.getTable()); // will
                                                                      // fall
            // through if
            // table
            // doesn't
            // exist
        } catch (NoSuchElementException e) {
            throw new simpledb.ParsingException("Unknown table : "
                    + s.getTable());
        }

        TupleDesc td = Database.getCatalog().getTupleDesc(tableId);

        Tuple t = new Tuple(td);
        int i = 0;
        DbIterator newTups;

        if (s.getValues() != null) {
            @SuppressWarnings("unchecked")
            Vector<ZExp> values = (Vector<ZExp>) s.getValues();
            if (td.numFields() != values.size()) {
                throw new simpledb.ParsingException(
                        "INSERT statement does not contain same number of fields as table "
                                + s.getTable());
            }
            for (ZExp e : values) {

                if (!(e instanceof ZConstant))
                    throw new simpledb.ParsingException(
                            "Complex expressions not allowed in INSERT statements.");
                ZConstant zc = (ZConstant) e;
                if (zc.getType() == ZConstant.NUMBER) {
                    if (td.getFieldType(i) != Type.INT_TYPE) {
                        throw new simpledb.ParsingException("Value "
                                + zc.getValue()
                                + " is not an integer, expected a string.");
                    }
                    IntField f = new IntField(new Integer(zc.getValue()));
                    t.setField(i, f);
                } else if (zc.getType() == ZConstant.STRING) {
                    if (td.getFieldType(i) != Type.STRING_TYPE) {
                        throw new simpledb.ParsingException("Value "
                                + zc.getValue()
                                + " is a string, expected an integer.");
                    }
                    StringField f = new StringField(zc.getValue(),
                            Type.STRING_LEN);
                    t.setField(i, f);
                } else {
                    throw new simpledb.ParsingException(
                            "Only string or int fields are supported.");
                }

                i++;
            }
            ArrayList<Tuple> tups = new ArrayList<Tuple>();
            tups.add(t);
            newTups = new TupleArrayIterator(tups);

        } else {
            ZQuery zq = (ZQuery) s.getQuery();
            LogicalPlan lp = parseQueryLogicalPlan(tId, zq);
            newTups = lp.physicalPlan(tId, TableStats.getStatsMap(), explain);
        }
        Query insertQ = new Query(tId);
        insertQ.setPhysicalPlan(new Insert(tId, newTups, tableId));
        return insertQ;
    }

    public Query handleDeleteStatement(ZDelete s, TransactionId tid)
            throws TransactionAbortedException, DbException, IOException,
            simpledb.ParsingException, Zql.ParseException {
        int id;
        try {
            id = Database.getCatalog().getTableId(s.getTable()); // will fall
                                                                 // through if
                                                                 // table
                                                                 // doesn't
                                                                 // exist
        } catch (NoSuchElementException e) {
            throw new simpledb.ParsingException("Unknown table : "
                    + s.getTable());
        }
        String name = s.getTable();
        Query sdbq = new Query(tid);

        LogicalPlan lp = new LogicalPlan();
        lp.setQuery(s.toString());

        lp.addScan(id, name);
        if (s.getWhere() != null)
            processExpression(tid, (ZExpression) s.getWhere(), lp);
        lp.addProjectField("null.*", null);

        DbIterator op = new Delete(tid, lp.physicalPlan(tid,
                TableStats.getStatsMap(), false));
        sdbq.setPhysicalPlan(op);

        return sdbq;

    }

    public void handleTransactStatement(ZTransactStmt s)
            throws TransactionAbortedException, DbException, IOException,
            simpledb.ParsingException, Zql.ParseException {
        if (s.getStmtType().equals("COMMIT")) {
            if (curtrans == null)
                throw new simpledb.ParsingException(
                        "No transaction is currently running");
            curtrans.commit();
            curtrans = null;
            inUserTrans = false;
        } else if (s.getStmtType().equals("ROLLBACK")) {
            if (curtrans == null)
                throw new simpledb.ParsingException(
                        "No transaction is currently running");
            curtrans.abort();
            curtrans = null;
            inUserTrans = false;
            System.out.println("Transaction " + curtrans.getId().getId()
                    + " aborted.");

        } else if (s.getStmtType().equals("SET TRANSACTION")) {
            if (curtrans != null)
                throw new simpledb.ParsingException(
                        "Can't start new transactions until current transaction has been committed or rolledback.");
            curtrans = new Transaction();
            curtrans.start();
            inUserTrans = true;
        } else {
            throw new simpledb.ParsingException("Unsupported operation");
        }
    }

    public LogicalPlan generateLogicalPlan(TransactionId tid, String s)
            throws simpledb.ParsingException {
        ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes());
        ZqlParser p = new ZqlParser(bis);
        try {
            ZStatement stmt = p.readStatement();
            if (stmt instanceof ZQuery) {
                LogicalPlan lp = parseQueryLogicalPlan(tid, (ZQuery) stmt);
                return lp;
            }
        } catch (Zql.ParseException e) {
            throw new simpledb.ParsingException(
                    "Invalid SQL expression: \n \t " + e);
        } catch (IOException e) {
            throw new simpledb.ParsingException(e);
        }

        throw new simpledb.ParsingException(
                "Cannot generate logical plan for expression : " + s);
    }

    public void setTransaction(Transaction t) {
        curtrans = t;
    }

    public Transaction getTransaction() {
        return curtrans;
    }

    public void processNextStatement(String s) {
        try {
            processNextStatement(new ByteArrayInputStream(s.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void processNextStatement(InputStream is) {
        try {
            ZqlParser p = new ZqlParser(is);
            ZStatement s = p.readStatement();

            Query query = null;
            if (s instanceof ZTransactStmt)
                handleTransactStatement((ZTransactStmt) s);
            else {
                if (!this.inUserTrans) {
                    curtrans = new Transaction();
                    curtrans.start();
                    System.out.println("Started a new transaction tid = "
                            + curtrans.getId().getId());
                }
                try {
                    if (s instanceof ZInsert)
                        query = handleInsertStatement((ZInsert) s,
                                curtrans.getId());
                    else if (s instanceof ZDelete)
                        query = handleDeleteStatement((ZDelete) s,
                                curtrans.getId());
                    else if (s instanceof ZQuery)
                        query = handleQueryStatement((ZQuery) s,
                                curtrans.getId());
                    else {
                        System.out
                                .println("Can't parse "
                                        + s
                                        + "\n -- parser only handles SQL transactions, insert, delete, and select statements");
                    }
                    if (query != null)
                        query.execute();

                    if (!inUserTrans && curtrans != null) {
                        curtrans.commit();
                        System.out.println("Transaction "
                                + curtrans.getId().getId() + " committed.");
                    }
                } catch (Throwable a) {
                    // Whenever error happens, abort the current transaction
                    if (curtrans != null) {
                        curtrans.abort();
                        System.out.println("Transaction "
                                + curtrans.getId().getId()
                                + " aborted because of unhandled error");
                    }
                    this.inUserTrans = false;

                    if (a instanceof simpledb.ParsingException
                            || a instanceof Zql.ParseException)
                        throw new ParsingException((Exception) a);
                    if (a instanceof Zql.TokenMgrError)
                        throw (Zql.TokenMgrError) a;
                    throw new DbException(a.getMessage());
                } finally {
                    if (!inUserTrans)
                        curtrans = null;
                }
            }

        } catch (TransactionAbortedException e) {
            e.printStackTrace();
        } catch (DbException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (simpledb.ParsingException e) {
            System.out
                    .println("Invalid SQL expression: \n \t" + e.getMessage());
        } catch (Zql.ParseException e) {
            System.out.println("Invalid SQL expression: \n \t " + e);
        } catch (Zql.TokenMgrError e) {
            System.out.println("Invalid SQL expression: \n \t " + e);
        }
    }

    // Basic SQL completions
    public static final String[] SQL_COMMANDS = { "select", "from", "where",
            "group by", "max(", "min(", "avg(", "count", "rollback", "commit",
            "insert", "delete", "values", "into" };

    static final String usage = "Usage: parser catalogFile [-explain] [-f queryFile] [--alpha <double>] [--base]";

    protected void shutdown() {
        System.out.println("Bye");
    }

    protected int start(File catalogFile, Boolean shouldExplain) {
        explain = shouldExplain;

        // first add tables to database
        Database.getCatalog().loadSchema(catalogFile.toString());
        TableStats.computeStatistics();

        ConsoleReader reader;
        try {
            reader = new ConsoleReader();
        } catch (IOException e) {
            System.err.println("Error: opening console failed.");
            return 1;
        }

        // Add really stupid tab completion for simple SQL
        ArgumentCompletor completor = new ArgumentCompletor(
                new SimpleCompletor(SQL_COMMANDS));
        completor.setStrict(false); // match at any position
        reader.addCompletor(completor);

        StringBuilder buffer = new StringBuilder();
        String line;
        boolean quit = false;

        try {
            while (!quit && (line = reader.readLine("SimpleDB> ")) != null) {
                // Split statements at ';': handles multiple statements on one
                // line, or one
                // statement spread across many lines
                while (line.indexOf(';') >= 0) {
                    int split = line.indexOf(';');
                    buffer.append(line.substring(0, split + 1));
                    String cmd = buffer.toString().trim();
                    cmd = cmd.substring(0, cmd.length() - 1).trim() + ";";
                    byte[] statementBytes = cmd.getBytes("UTF-8");
                    if (cmd.equalsIgnoreCase("quit;")
                            || cmd.equalsIgnoreCase("exit;")) {
                        shutdown();
                        quit = true;
                        break;
                    }

                    long startTime = System.currentTimeMillis();
                    processNextStatement(new ByteArrayInputStream(
                            statementBytes));
                    long time = System.currentTimeMillis() - startTime;
                    System.out.printf("----------------\n%.2f seconds\n\n",
                            ((double) time / 1000.0));

                    // Grab the remainder of the line
                    line = line.substring(split + 1);
                    buffer = new StringBuilder();
                }
                if (line.length() > 0) {
                    buffer.append(line);
                    buffer.append("\n");
                }
            }
        } catch (IOException e) {
            System.err.println("Error: Reading from console failed.");
            return 1;
        }

        return 0;
    }
}

class TupleArrayIterator implements DbIterator {
    /**
	 *
	 */
    private static final long serialVersionUID = 1L;
    ArrayList<Tuple> tups;
    Iterator<Tuple> it = null;

    public TupleArrayIterator(ArrayList<Tuple> tups) {
        this.tups = tups;
    }

    public void open() throws DbException, TransactionAbortedException {
        it = tups.iterator();
    }

    /** @return true if the iterator has more items. */
    public boolean hasNext() throws DbException, TransactionAbortedException {
        return it.hasNext();
    }

    /**
     * Gets the next tuple from the operator (typically implementing by reading
     * from a child operator or an access method).
     *
     * @return The next tuple in the iterator, or null if there are no more
     *         tuples.
     */
    public Tuple next() throws DbException, TransactionAbortedException,
            NoSuchElementException {
        return it.next();
    }

    /**
     * Resets the iterator to the start.
     *
     * @throws DbException
     *             When rewind is unsupported.
     */
    public void rewind() throws DbException, TransactionAbortedException {
        it = tups.iterator();
    }

    /**
     * Returns the TupleDesc associated with this DbIterator.
     */
    public TupleDesc getTupleDesc() {
        return tups.get(0).getTupleDesc();
    }

    /**
     * Closes the iterator.
     */
    public void close() {
    }

    @Override
	public DbIterator[] getChildren() {
		return new DbIterator[]{};
	}

}


text:
    Use of Google Maps API

    This appilication uses the Google Maps API. See Google Privacy Policy for
    details.

redpajama_set_name: RedPajamaGithub


text:
namespace mojo {
class View;
}

namespace html_viewer {

class HTMLDocumentOOPIF;
class GlobalState;

// DocumentResourceWaiter waits for the necessary resources needed to load an
// HTMLDocument. Use IsReady() to determine when everything is available. Once
// ready it is assumed HTMLDocument will call back for the FrameTreeClient and
// FrameData.
class DocumentResourceWaiter : public mandoline::FrameTreeClient {
 public:
  DocumentResourceWaiter(GlobalState* global_state,
                         mojo::URLResponsePtr response,
                         HTMLDocumentOOPIF* document);
  ~DocumentResourceWaiter() override;

  // Releases all the resources that have been accumulated.
  void Release(mojo::InterfaceRequest<mandoline::FrameTreeClient>*
                   frame_tree_client_request,
               mandoline::FrameTreeServerPtr* frame_tree_server,
               mojo::Array<mandoline::FrameDataPtr>* frame_data,
               mojo::URLResponsePtr* response);

  // See class description.
  bool IsReady() const;

  void set_root(mojo::View* root) { root_ = root; }
  mojo::View* root() { return root_; }

  void Bind(mojo::InterfaceRequest<mandoline::FrameTreeClient> request);

 private:
  // mandoline::FrameTreeClient:
  void OnConnect(mandoline::FrameTreeServerPtr server,
                 mojo::Array<mandoline::FrameDataPtr> frame_data) override;
  void OnFrameAdded(mandoline::FrameDataPtr frame_data) override;
  void OnFrameRemoved(uint32_t frame_id) override;
  void OnFrameNameChanged(uint32_t frame_id, const mojo::String& name) override;

  GlobalState* global_state_;
  HTMLDocumentOOPIF* document_;
  mojo::URLResponsePtr response_;
  mojo::View* root_;
  mandoline::FrameTreeServerPtr server_;
  mojo::Array<mandoline::FrameDataPtr> frame_data_;

  // Once we get OnConnect() we unbind |frame_tree_client_binding_| and put it
  // here.
  mojo::InterfaceRequest<mandoline::FrameTreeClient> frame_tree_client_request_;
  mojo::Binding<mandoline::FrameTreeClient> frame_tree_client_binding_;

  DISALLOW_COPY_AND_ASSIGN(DocumentResourceWaiter);
};

}  // namespace html_viewer

#endif  // COMPONENTS_HTML_VIEWER_DOCUMENT_RESOURCE_WAITER_H_


text:
PEGASUS_USING_PEGASUS;

class IndicationTestProvider:
    public CIMMethodProvider,
    public CIMIndicationProvider
{
public:
    IndicationTestProvider() throw();
    virtual ~IndicationTestProvider() throw();

    // CIMProvider interface
    virtual void initialize(CIMOMHandle& cimom);
    virtual void terminate();

    // CIMIndicationProvider interface
    virtual void enableIndications(IndicationResponseHandler& handler);
    virtual void disableIndications();

    virtual void createSubscription(
        const OperationContext& context,
        const CIMObjectPath& subscriptionName,
        const Array <CIMObjectPath>& classNames,
        const CIMPropertyList& propertyList,
        const Uint16 repeatNotificationPolicy);

    virtual void modifySubscription(
        const OperationContext& context,
        const CIMObjectPath& subscriptionName,
        const Array <CIMObjectPath>& classNames,
        const CIMPropertyList& propertyList,
        const Uint16 repeatNotificationPolicy);

    virtual void deleteSubscription(
        const OperationContext& context,
        const CIMObjectPath& subscriptionName,
        const Array <CIMObjectPath>& classNames);

    // CIMMethodProvider Interface
    virtual void invokeMethod(
        const OperationContext& context,
        const CIMObjectPath& objectReference,
        const CIMName& methodName,
        const Array<CIMParamValue>& inParameters,
        MethodResultResponseHandler& handler);

protected:

     void _checkOperationContext(
         const OperationContext& context,
         const String& funcName);

private:

     CIMOMHandle _cimom;

};

#endif


text:
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO
Imports System.Threading

Module ServerSocket
    Public objFrmServer As frmServer
    Public isServerOn As Boolean = False
    Public clients As New List(Of Client)
    Private serverSocket As Socket
    Private byteData(8191) As Byte

    Public Function GetIPaddress() As String
        Dim myHost As String = System.Net.Dns.GetHostName
        Dim myIPs As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(myHost)
        For Each ipAddress As System.Net.IPAddress In myIPs.AddressList
            If ipAddress.ToString.ElementAt(3) = "." Then
                Return ipAddress.ToString()
            End If
        Next
        Return "Get Ip Fail"
    End Function

    Public Function GetRealIPaddress() As String
        Dim wc As New WebClient
        Dim html = wc.DownloadString("http://whereismyip.com/")
        Dim nStart = html.IndexOf("""verdana"">") + 10
        Dim nStop = html.IndexOf("")
        Return html.Substring(nStart, nStop - nStart)
    End Function

    Public Function startServer() As Boolean
        Try
            serverSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Dim IpEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 5566)
            serverSocket.Bind(IpEndPoint)
            serverSocket.Listen(511) ' 最多提供512人同時連線
            serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)

            Dim sqlStart = String.Format("UPDATE Sys SET Term='{0}',ServerIp='{1}',ServerStart='{2}',ServerVersion='{3}' WHERE Id=1;", _
                                         frmServer.nowTerm, GetRealIPaddress(), Format(Now, "yyyyMMdd-hhmmss"), frmServer.version)
            exeCmd(sqlStart)
        Catch ex As Exception
            log("伺服器啟動失敗! " & ex.Message, LogType_ERROR)
            Return False
        End Try
        isServerOn = True
        log("伺服器已啟動", LogType_NORMAL)
        Return True
    End Function

    Public Sub stopServer()
        isServerOn = False
        Try
            For Each client In clients
                Try
                    Dim sendBytes As Byte() = Encoding.UTF8.GetBytes("BYE;")
                    client._socket.Send(sendBytes)
                    client._socket.Shutdown(SocketShutdown.Both)
                    client._socket.Close()
                    objFrmServer.RemoveClient(client)
                Catch ex As Exception
                    log("stopServer異常! IP:" & client._ip & "-" & ex.Message, LogType_ERROR)
                End Try
                log("強制踢除: " & client._ip & "-" & client._name, LogType_SYSTEM)
            Next
            serverSocket.Close()
            serverSocket = Nothing
            clients.Clear()

            log("伺服器已關閉", LogType_NORMAL)
        Catch ex As Exception
            log("stopServer異常! " & ex.Message, LogType_ERROR)
            serverSocket = Nothing
            clients = New List(Of Client)
        End Try
        'objFrmServer.RemoveAllClient()
    End Sub

    Private Sub OnAccept(ByVal ar As IAsyncResult)
        Dim dataLength = 0
        Dim clientSocket As Socket

        Try
            clientSocket = serverSocket.EndAccept(ar)
            Dim clientIp = clientSocket.RemoteEndPoint.ToString.Split(":")(0)
            log(clientIp & ": 連線", LogType_NORMAL)

            ' 客戶端回傳: 帳號;密碼;使用者型態
            dataLength = clientSocket.Receive(byteData)
            Dim message = Encoding.UTF8.GetString(byteData, 0, dataLength)
            Dim returns() = message.Split(";")
            Dim clientUid = returns(0)
            Dim clientUserType = returns(2)

            ' 登入驗證(帳號,密碼,型態),回傳"ID;姓名",回傳空字串為登入失敗
            Dim loginStatus = login(returns(0), returns(1), returns(2))

            If loginStatus <> "" Then
                returns = loginStatus.Split(";")

                ' =====重複登入=====
                If checkIfLogined(returns(0), clientUserType) Then
                    log(clientIp & ": 帳號" & clientUid & " 登入失敗(重複登入)", LogType_NORMAL)
                    ' 重複登入,回傳"RELOGIN"
                    Dim sendBytes_RE As Byte() = Encoding.UTF8.GetBytes("RELOGIN;")
                    clientSocket.Send(sendBytes_RE)
                    ' 關閉連線,結束此socket所有動作
                    clientSocket.Close()

                Else ' =====登入成功=====
                    Dim loginTime = Format(Now, "yyyyMMdd-HHmmss")

                    ' 回傳(ID;姓名)
                    Dim sendBytes As Byte() = Encoding.UTF8.GetBytes(returns(0) & ";" & returns(1))
                    clientSocket.Send(sendBytes)

                    ' 加入資料到視窗畫面,開始監聽
                    Dim client As New Client(clientSocket, clientIp, returns(0), returns(1), clientUserType, loginTime)
                    clients.Add(client)
                    objFrmServer.AddClient(client)
                    clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), clientSocket)
                    log(clientIp & ": " & returns(1) & " 登入成功", LogType_NORMAL)
                End If

            Else ' =====登入失敗=====
                log(clientIp & ": 帳號" & clientUid & " 登入失敗(帳密錯誤)", LogType_NORMAL)
                ' 回傳"loginFail"
                Dim sendBytes As Byte() = Encoding.UTF8.GetBytes("LOGINFAIL;")
                clientSocket.Send(sendBytes)
                ' 關閉連線,結束此socket所有動作
                clientSocket.Close()
            End If

            serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
        Catch ex As Exception
            If isServerOn Then
                log("伺服器接收連線建立異常! " & ex.Message, LogType_ERROR)
            Else
                serverSocket = Nothing
            End If
        End Try
    End Sub

    Private Sub OnRecieve(ByVal ar As IAsyncResult)
        Dim clientSocket As Socket = ar.AsyncState
        getClientInfo(clientSocket)._eventTime = Now
        Try
            clientSocket.EndReceive(ar)
            ' 讀取對方要求
            Dim returnFunc = Encoding.UTF8.GetString(byteData).Split(";")(0)

            Select Case returnFunc
                Case "PING" ' 測試連線狀態
                    log(clientSocket.RemoteEndPoint.ToString & ": 要求測試連線PING", LogType_NORMAL)
                    Dim sendBytes As Byte() = Encoding.UTF8.GetBytes("PONG;")
                    clientSocket.Send(sendBytes)

                Case "LOGOUT" ' 登出
                    log(clientSocket.RemoteEndPoint.ToString & ": 要求LOGOUT", LogType_NORMAL)
                    Dim sendBytes As Byte() = Encoding.UTF8.GetBytes("BYE;")
                    clientSocket.Send(sendBytes)
                    Dim client = getClientInfo(clientSocket)
                    log(client._ip & ": " & client._name & "已登出", LogType_NORMAL)

                    objFrmServer.RemoveClient(client)
                    clients.Remove(client)
                    clientSocket.Shutdown(SocketShutdown.Both)
                    clientSocket.Close()
                    Exit Sub

                Case "DBQUERY" ' 資料庫查詢
                    clientSocket.Receive(byteData)
                    Dim sql = Encoding.UTF8.GetString(byteData).Split(";")(0)
                    log(clientSocket.RemoteEndPoint.ToString & ": 要求DBQUERY(" & sql & ")", LogType_NORMAL)
                    clientSocket.Send(Encoding.UTF8.GetBytes("DATATABLE;"))
                    Dim result = selectCmd(sql)
                    ' 序列化DataTable
                    Dim bf As New BinaryFormatter()
                    Dim ms As New MemoryStream()
                    bf.Serialize(ms, result)
                    Dim ObjectBytes() = ms.ToArray()
                    clientSocket.Send(Encoding.UTF8.GetBytes(ObjectBytes.Length & ";"))
                    Thread.Sleep(500)
                    clientSocket.Send(ObjectBytes)

                Case "DBCMD" ' 資料庫命令
                    clientSocket.Receive(byteData)
                    Dim sql = Encoding.UTF8.GetString(byteData).Split(";")(0)
                    log(clientSocket.RemoteEndPoint.ToString & ": 要求DBCMD(" & sql & ")", LogType_NORMAL)
                    clientSocket.Send(Encoding.UTF8.GetBytes("DBCMDRESULT;"))
                    If exeCmd(sql) Then
                        clientSocket.Send(Encoding.UTF8.GetBytes("SUCCESS;"))
                    Else
                        clientSocket.Send(Encoding.UTF8.GetBytes("FAIL;" & sqlCmdErr & ";"))
                    End If

                Case "DBCMDS" ' 一次多筆資料庫命令(傳入時以#號分行,執行前改回;號)
                    clientSocket.Receive(byteData)
                    Dim sSql = Encoding.UTF8.GetString(byteData).Split(";")(0)
                    sSql = sSql.Replace("#", ";")
                    log(clientSocket.RemoteEndPoint.ToString & ": 要求DBCMDS(" & sSql & ")", LogType_NORMAL)
                    clientSocket.Send(Encoding.UTF8.GetBytes("DBCMDRESULT;"))
                    If exeCmd(sSql) Then
                        clientSocket.Send(Encoding.UTF8.GetBytes("SUCCESS;"))
                    Else
                        clientSocket.Send(Encoding.UTF8.GetBytes("FAIL;" & sqlCmdErr & ";"))
                    End If
            End Select

            If clientSocket.Connected Then
                clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), clientSocket)
            End If
        Catch ex As Exception
            If isServerOn Then
                Dim client = getClientInfo(clientSocket)
                If client IsNot Nothing Then
                    log(client._ip & ": 接收資料異常! " & ex.Message, LogType_ERROR)
                    log(client._ip & ": 連線已斷開", LogType_NORMAL)
                    objFrmServer.RemoveClient(client)
                    clients.Remove(client)
                End If
                clientSocket.Close()
            Else
                clientSocket.Close()
            End If
        End Try

    End Sub

    Public Function getClientInfo(ByVal clientSocket As Socket) As Client
        For Each client In clients
            If client._socket.Equals(clientSocket) Then
                Return client
            End If
        Next
        Return Nothing
    End Function

    Public Function checkIfLogined(ByVal id As String, ByVal type As String) As Boolean
        For Each client In clients
            If client._id = id And client._type = type Then
                If client._socket.Connected Then
                    Return True
                Else
                    objFrmServer.RemoveClient(client)
                    Return False
                End If
            End If
        Next
        Return False
    End Function

End Module

Public Class Client
    Property _socket As Socket
    Property _ip As String
    Property _id As String
    Property _name As String
    Property _type As String
    Property _loginTime As String
    Property _eventTime As Date

    Public Sub New(ByVal socket As Socket, ByVal ip As String, ByVal id As String, ByVal name As String, ByVal type As String, ByVal loginTime As String)
        _socket = socket
        _ip = ip
        _id = id
        _name = name
        _type = type
        _loginTime = loginTime
        _eventTime = Now
    End Sub
End Class


text:
from collections import ChainMap
from random import choice
from xml.etree.ElementTree import fromstring as parsexml

from bot import Command, categories
from bot.utils import img_embed

search_types = {
    'e621': {
        'url': 'https://e621.net/posts.json?limit=30&tags={}',
        'name': 'e621.net'
    },
    'gelbooru': {
        'url': 'https://gelbooru.com/index.php?page=dapi&s=post&q=index&tags={}',
        'aliases': ['gelb', 'gb']
    },
    'rule34': {
        'url': 'https://rule34.xxx/index.php?page=dapi&s=post&q=index&tags={}',
        'aliases': ['r34'],
        'format': 'xml'
    },
    'danbooru': {
        'url': 'https://danbooru.donmai.us/posts.json?limit=30&tags={}',
        'aliases': ['danb']
    },
    'konachan': {
        'url': 'https://konachan.net/post.json?limit=30&tags={}',
        'aliases': ['kona'],
        'name': 'konachan.net (sfw)'
    },
    'konachan18': {
        'url': 'https://konachan.com/post.json?limit=30&tags={}',
        'aliases': ['kona18'],
        'name': 'konachan.com (nsfw)'
    },
    'hypnohub': {
        'url': 'https://hypnohub.net/post/index.json?limit=30&tags={}',
        'aliases': ['hypno'],
        'image_format': 'https:{}'
    },
    'xbooru': {
        'url': 'https://xbooru.com/index.php?page=dapi&s=post&q=index&tags={}',
        'format': 'xml'
    },
    'realbooru': {
        'url': 'https://realbooru.com/index.php?page=dapi&s=post&q=index&tags={}',
        'format': 'xml'
    },
    'furrybooru': {
        'url': 'https://furry.booru.org/index.php?page=dapi&s=post&q=index&tags={}',
        'format': 'xml'
    }
}

aliases_map = ChainMap(*[{j: x for j in v.get('aliases', [])} for x, v in search_types.items()])
aliases = [*aliases_map] + [*search_types]

class BooruSearch(Command):
    __author__ = 'makzk'
    __version__ = '1.0.1'

    def __init__(self, bot):
        super().__init__(bot)
        self.name = 'booru'
        self.aliases = aliases
        self.help = '$[booru-help]'
        self.format = '$[booru-format]'
        self.nsfw_only = True
        self.category = categories.IMAGES

    async def handle(self, cmd):
        if cmd.cmdname in self.name:
            if cmd.argc > 0:
                if cmd.args[0] in aliases:
                    search_type = cmd.args[0]
                    search_text = ' '.join(cmd.args[1:])
                elif cmd.args[0] == 'list':
                    await cmd.answer('$[booru-list]', locales={'types': ', '.join([*search_types])})
                    return
                else:
                    search_type = choice([*search_types])
                    search_text = cmd.text
            else:
                search_type = choice([*search_types])
                search_text = cmd.text
        else:
            search_type = cmd.cmdname
            search_text = cmd.text

        if search_type in aliases_map:
            search_type = aliases_map[search_type]

        if search_text == '':
            search_text = search_types[search_type].get('default_search', '*')

        search_url = search_types[search_type]['url'].format(search_text)

        self.log.debug('Loading %s', search_url)
        await cmd.typing()
        async with self.http.get(search_url) as r:
            if search_types[search_type].get('format', 'json') == 'xml':
                posts = parsexml(await r.text()).findall('post')
            else:
                posts = await r.json()
                if search_type == 'e621':
                    posts = filter(lambda x: x['file']['ext'] != 'webm', posts['posts'])

            if len(posts) == 0:
                await cmd.answer('$[booru-no-results]')
                return

            post = choice(posts)
            image_url = post['file']['url'] if search_type == 'e621' else post.get('file_url')

            if 'image_format' in search_types[search_type]:
                image_url = search_types[search_type]['image_format'].format(post.get('file_url'))

            await cmd.answer(
                img_embed(image_url, footer='$[booru-results-footer]'),
                locales={'site': search_types[search_type].get('name', search_type)}
            )


text:
package io.atomix.protocols.raft.session.impl;

import io.atomix.cluster.MemberId;
import io.atomix.primitive.PrimitiveState;
import io.atomix.primitive.PrimitiveType;
import io.atomix.primitive.session.SessionClient;
import io.atomix.primitive.event.EventType;
import io.atomix.primitive.event.PrimitiveEvent;
import io.atomix.primitive.operation.PrimitiveOperation;
import io.atomix.primitive.partition.PartitionId;
import io.atomix.primitive.service.ServiceConfig;
import io.atomix.primitive.session.SessionId;
import io.atomix.protocols.raft.ReadConsistency;
import io.atomix.protocols.raft.protocol.RaftClientProtocol;
import io.atomix.protocols.raft.session.CommunicationStrategy;
import io.atomix.protocols.raft.session.RaftSessionClient;
import io.atomix.utils.concurrent.Futures;
import io.atomix.utils.concurrent.ThreadContext;
import io.atomix.utils.logging.LoggerContext;

import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Handles submitting state machine {@link PrimitiveOperation operations} to the Raft cluster.
 *

 * The client session is responsible for maintaining a client's connection to a Raft cluster and coordinating
 * the submission of {@link PrimitiveOperation operations} to various nodes in the cluster. Client
 * sessions are single-use objects that represent the context within which a cluster can guarantee linearizable
 * semantics for state machine operations. When a session is opened, the session will register
 * itself with the cluster by attempting to contact each of the known servers. Once the session has been successfully
 * registered, kee-alive requests will be periodically sent to keep the session alive.
 *

 * Sessions are responsible for sequencing concurrent operations to ensure they're applied to the system state
 * in the order in which they were submitted by the client. To do so, the session coordinates with its server-side
 * counterpart using unique per-operation sequence numbers.
 *

 * In the event that the client session expires, clients are responsible for opening a new session by creating and
 * opening a new session object.
 */
public class DefaultRaftSessionClient implements RaftSessionClient {
  private final String serviceName;
  private final PrimitiveType primitiveType;
  private final ServiceConfig serviceConfig;
  private final PartitionId partitionId;
  private final Duration minTimeout;
  private final Duration maxTimeout;
  private final RaftClientProtocol protocol;
  private final MemberSelectorManager selectorManager;
  private final RaftSessionManager sessionManager;
  private final ReadConsistency readConsistency;
  private final CommunicationStrategy communicationStrategy;
  private final ThreadContext context;
  private volatile RaftSessionListener proxyListener;
  private volatile RaftSessionInvoker proxyInvoker;
  private volatile RaftSessionState state;
  private final Consumer<MemberId> leaderChangeListener = this::onLeaderChange;

  public DefaultRaftSessionClient(
      String serviceName,
      PrimitiveType primitiveType,
      ServiceConfig serviceConfig,
      PartitionId partitionId,
      RaftClientProtocol protocol,
      MemberSelectorManager selectorManager,
      RaftSessionManager sessionManager,
      ReadConsistency readConsistency,
      CommunicationStrategy communicationStrategy,
      ThreadContext context,
      Duration minTimeout,
      Duration maxTimeout) {
    this.serviceName = checkNotNull(serviceName, "serviceName cannot be null");
    this.primitiveType = checkNotNull(primitiveType, "serviceType cannot be null");
    this.serviceConfig = checkNotNull(serviceConfig, "serviceConfig cannot be null");
    this.partitionId = checkNotNull(partitionId, "partitionId cannot be null");
    this.protocol = checkNotNull(protocol, "protocol cannot be null");
    this.selectorManager = checkNotNull(selectorManager, "selectorManager cannot be null");
    this.readConsistency = checkNotNull(readConsistency, "readConsistency cannot be null");
    this.communicationStrategy = checkNotNull(communicationStrategy, "communicationStrategy cannot be null");
    this.context = checkNotNull(context, "context cannot be null");
    this.minTimeout = checkNotNull(minTimeout, "minTimeout cannot be null");
    this.maxTimeout = checkNotNull(maxTimeout, "maxTimeout cannot be null");
    this.sessionManager = checkNotNull(sessionManager, "sessionManager cannot be null");
  }

  @Override
  public String name() {
    return serviceName;
  }

  @Override
  public PrimitiveType type() {
    return primitiveType;
  }

  @Override
  public ThreadContext context() {
    return context;
  }

  @Override
  public SessionId sessionId() {
    return state != null ? state.getSessionId() : null;
  }

  @Override
  public PartitionId partitionId() {
    return partitionId;
  }

  @Override
  public PrimitiveState getState() {
    return state.getState();
  }

  @Override
  public void addStateChangeListener(Consumer<PrimitiveState> listener) {
    if (state != null) {
      state.addStateChangeListener(listener);
    }
  }

  @Override
  public void removeStateChangeListener(Consumer<PrimitiveState> listener) {
    if (state != null) {
      state.removeStateChangeListener(listener);
    }
  }

  @Override
  public CompletableFuture<byte[]> execute(PrimitiveOperation operation) {
    RaftSessionInvoker invoker = this.proxyInvoker;
    if (invoker == null) {
      return Futures.exceptionalFuture(new IllegalStateException("Session not open"));
    }
    return invoker.invoke(operation);
  }

  @Override
  public void addEventListener(EventType eventType, Consumer<PrimitiveEvent> listener) {
    if (proxyListener != null) {
      proxyListener.addEventListener(eventType, listener);
    }
  }

  @Override
  public void removeEventListener(EventType eventType, Consumer<PrimitiveEvent> listener) {
    if (proxyListener != null) {
      proxyListener.removeEventListener(eventType, listener);
    }
  }

  @Override
  public CompletableFuture<SessionClient> connect() {
    return sessionManager.openSession(
        serviceName,
        primitiveType,
        serviceConfig,
        readConsistency,
        communicationStrategy,
        minTimeout,
        maxTimeout)
        .thenApply(state -> {
          this.state = state;

          // Create command/query connections.
          RaftSessionConnection leaderConnection = new RaftSessionConnection(
              protocol,
              selectorManager.createSelector(CommunicationStrategy.LEADER),
              context,
              LoggerContext.builder(SessionClient.class)
                  .addValue(state.getSessionId())
                  .add("type", state.getPrimitiveType())
                  .add("name", state.getPrimitiveName())
                  .build());
          RaftSessionConnection sessionConnection = new RaftSessionConnection(
              protocol,
              selectorManager.createSelector(communicationStrategy),
              context,
              LoggerContext.builder(SessionClient.class)
                  .addValue(state.getSessionId())
                  .add("type", state.getPrimitiveType())
                  .add("name", state.getPrimitiveName())
                  .build());

          // Create proxy submitter/listener.
          RaftSessionSequencer sequencer = new RaftSessionSequencer(state);
          this.proxyListener = new RaftSessionListener(
              protocol,
              selectorManager.createSelector(CommunicationStrategy.ANY),
              state,
              sequencer,
              context);
          this.proxyInvoker = new RaftSessionInvoker(
              leaderConnection,
              sessionConnection,
              state,
              sequencer,
              sessionManager,
              context);

          selectorManager.addLeaderChangeListener(leaderChangeListener);
          state.addStateChangeListener(s -> {
            if (s == PrimitiveState.EXPIRED || s == PrimitiveState.CLOSED) {
              selectorManager.removeLeaderChangeListener(leaderChangeListener);
              proxyListener.close();
              proxyInvoker.close();
            }
          });

          return this;
        });
  }

  private void onLeaderChange(MemberId memberId) {
    if (memberId != null) {
      proxyInvoker.reset();
    }
  }

  @Override
  public CompletableFuture<Void> close() {
    if (state != null) {
      return sessionManager.closeSession(state.getSessionId(), false)
          .whenComplete((result, error) -> state.setState(PrimitiveState.CLOSED));
    }
    return CompletableFuture.completedFuture(null);
  }

  @Override
  public CompletableFuture<Void> delete() {
    if (state != null) {
      return sessionManager.closeSession(state.getSessionId(), true)
          .whenComplete((result, error) -> state.setState(PrimitiveState.CLOSED));
    }
    return CompletableFuture.completedFuture(null);
  }

  @Override
  public int hashCode() {
    return Objects.hash(state);
  }

  @Override
  public boolean equals(Object object) {
    return object instanceof DefaultRaftSessionClient
        && ((DefaultRaftSessionClient) object).state.getSessionId() == state.getSessionId();
  }

  @Override
  public String toString() {
    return toStringHelper(this)
        .add("session", state != null ? state.getSessionId() : null)
        .toString();
  }
}


text:
import {
  AMP_TEMPLATED_CREATIVE_HEADER_NAME,
  DEPRECATED_AMP_TEMPLATED_CREATIVE_HEADER_NAME,
  TemplateValidator,
  getAmpAdTemplateHelper,
} from '../template-validator';
import {AdResponseType, ValidatorResult} from '../amp-ad-type-defs';
import {data} from './testdata/valid_css_at_rules_amp.reserialized';
import {utf8Encode} from '../../../../src/utils/bytes';

const realWinConfig = {
  amp: {},
  ampAdCss: true,
  allowExternalResources: true,
};

describes.realWin('TemplateValidator', realWinConfig, env => {

  const templateUrl = 'https://adnetwork.com/amp-template.html';
  const headers = {
    get: name => {
      if (name == AMP_TEMPLATED_CREATIVE_HEADER_NAME) {
        return 'amp-mustache';
      }
    },
  };
  let validator;

  beforeEach(() => {
    validator = new TemplateValidator();
  });

  describe('AMP Result', () => {

    let sandbox;
    let validatorPromise;

    beforeEach(() => {
      sandbox = sinon.sandbox;
      sandbox.stub(getAmpAdTemplateHelper(env.win), 'fetch').callsFake(url => {
        expect(url).to.equal(templateUrl);
        return Promise.resolve(data.adTemplate);
      });

      validatorPromise = validator.validate({win: env.win},
          utf8Encode(JSON.stringify({
            templateUrl,
            data: {url: 'https://buy.com/buy-1'},
            analytics: {foo: 'bar'},
          })), headers);
    });

    afterEach(() => sandbox.restore());

    it('should have AMP validator result', () => {
      return validatorPromise.then(validatorOutput => {
        expect(validatorOutput).to.be.ok;
        expect(validatorOutput.type).to.equal(ValidatorResult.AMP);
      });
    });

    it('should have AMP validator result w/ deprecated header name', () => {
      validator.validate({win: env.win},
          utf8Encode(JSON.stringify({
            templateUrl,
            data: {url: 'https://buy.com/buy-1'},
            analytics: {foo: 'bar'},
          })), {
            get: name => {
              if (name == DEPRECATED_AMP_TEMPLATED_CREATIVE_HEADER_NAME) {
                return 'amp-mustache';
              }
            },
          }).then(validatorOutput => {
        expect(validatorOutput).to.be.ok;
        expect(validatorOutput.type).to.equal(ValidatorResult.AMP);
      });
    });

    it('should have TEMPLATE ad response type', () => {
      return validatorPromise.then(validatorOutput => {
        expect(validatorOutput).to.be.ok;
        expect(validatorOutput.adResponseType).to.equal(
            AdResponseType.TEMPLATE);
      });
    });

    it('should have creativeData with minified creative in metadata', () => {
      return validatorPromise.then(validatorOutput => {
        expect(validatorOutput).to.be.ok;
        expect(validatorOutput.creativeData).to.be.ok;
        const {creativeMetadata} = validatorOutput.creativeData;
        expect(creativeMetadata.minifiedCreative)
            .to.equal(data.minifiedTemplateCreative);
      });
    });

    it('should have amp-analytics and mustache in customElementExtensions',
        () => {
          return validatorPromise.then(validatorOutput => {
            expect(validatorOutput).to.be.ok;
            expect(validatorOutput.creativeData).to.be.ok;
            const {creativeMetadata} = validatorOutput.creativeData;
            expect(creativeMetadata.customElementExtensions)
                .to.deep.equal(['amp-analytics', 'amp-mustache']);
          });
        });
  });

  describe('Non-AMP Result', () => {
    it('should have NON_AMP validator result due to lack of headers', () => {
      return validator.validate({win: env.win},
          utf8Encode(JSON.stringify({
            templateUrl,
            data: {url: 'https://buy.com/buy-1'},
            analytics: {foo: 'bar'},
          }))).then(validatorOutput => {
        expect(validatorOutput).to.be.ok;
        expect(validatorOutput.type).to.equal(ValidatorResult.NON_AMP);
      });
    });

    it('should have NON_AMP validator result due to lack of mustache header',
        () => {
          return validator.validate({win: env.win},
              utf8Encode(JSON.stringify({
                templateUrl,
                data: {url: 'https://buy.com/buy-1'},
                analytics: {foo: 'bar'},
              })),
              {
                get: () => null,
              }).then(validatorOutput => {
            expect(validatorOutput).to.be.ok;
            expect(validatorOutput.type).to.equal(ValidatorResult.NON_AMP);
          });
        });

    it('should have TEMPLATE ad response type', () => {
      return validator.validate({win: env.win},
          utf8Encode(JSON.stringify({
            templateUrl,
            data: {url: 'https://buy.com/buy-1'},
            analytics: {foo: 'bar'},
          }))).then(validatorOutput => {
        expect(validatorOutput).to.be.ok;
        expect(validatorOutput.adResponseType)
            .to.equal(AdResponseType.TEMPLATE);
      });
    });

    it('should have the response body as the creative in creativeData', () => {
      return validator.validate({win: env.win},
          utf8Encode(JSON.stringify({templateUrl})),
          {
            get: () => null,
          }).then(validatorOutput => {
        expect(validatorOutput).to.be.ok;
        expect(validatorOutput.creativeData).to.be.ok;
        const {creativeData} = validatorOutput;
        expect(creativeData).to.be.ok;
        expect(creativeData.creative).to.deep.equal(
            '{"templateUrl":"https://adnetwork.com/amp-template.html"}');
      });
    });
  });
});


text:
const Generator = require("yeoman-generator");
const commandExists = require("command-exists");
const humps = require("humps");

module.exports = class ReactZeal extends Generator {
  prompting() {
    return this.prompt([
      {
        type: "input",
        name: "name",
        message: "Your project name",
        default: kabob(this.appname)
      }
    ]).then(
      function(answers) {
        this.appName = kabob(answers.name);
      }.bind(this)
    );
  }

  writing() {
    this._installPackageJson();

    this.fs.copy(this.templatePath("client"), this.destinationPath("client"), {
      globOptions: { dot: true }
    });

    this.fs.copy(this.templatePath(".env"), this.destinationPath(".env"));
    this.fs.copy(
      this.templatePath(".env.development"),
      this.destinationPath(".env.development")
    );

    this.fs.copy(
      this.templatePath(".eslintrc.js"),
      this.destinationPath(".eslintrc.js")
    );

    this.fs.copy(
      this.templatePath(".sass-lint.yml"),
      this.destinationPath(".sass-lint.yml")
    );

    this.fs.copy(
      this.templatePath("yarn.lock"),
      this.destinationPath("yarn.lock")
    );

    this._mergeGitIgnore();
  }

  install() {
    const isYarnAvailable = commandExists.sync("yarnpkg");
    this.installDependencies({
      yarn: isYarnAvailable,
      npm: !isYarnAvailable,
      bower: false
    });
  }

  _installPackageJson() {
    const json = this.fs.readJSON(this.templatePath("package.json"));

    json.name = this.appName;
    delete json["lint-staged"].gitDir;

    this.fs.writeJSON(this.destinationPath("package.json"), json);
  }

  _mergeGitIgnore() {
    const template = this.fs.read(this.templatePath("gitignore"));
    const existing = this.fs.read(this.destinationPath(".gitignore"), {
      defaults: ""
    });

    this.fs.write(
      this.destinationPath(".gitignore"),
      existing + "\n\n" + template
    );
  }
};

function kabob(string) {
  return humps.decamelize(humps.camelize(string), { separator: "-" });
}


text:
<?php

	use yii\helpers\Url;
	use yii\helpers\Html;
	use app\components\FooterMenu\FooterMenuWidget;

?>

				<?= Yii::t('Dictionary', 'Player registration'); ?>

				<?= Yii::t('Dictionary', 'To register, please complete all form fields. E-mail and password will later be used for authorization. All informational messages will be sent to the specified email address.'); ?>

			<?=
				$this -> render('formUserData', [
					'Model' => $Model,
					'Field' => [
						'Name' => true,
						'Email' => true,
						'Password' => true,
						'ControlPassword' => true,
						'ControlCode' => true,
					],
					'Button' => [
						'Name' => Yii::t('Dictionary', 'Registration'),
					],
				]);
			?>

<?=
	// Выводится меню "В начало".
	FooterMenuWidget::widget([
		'ItemList' => [
			Yii::t('Dictionary', 'Start') => Url::to(['site/index'])
		]
	]);
?>


text:
var esVersion = require('@balena/es-version').get(['es2015', 'es2018']);
var sdkBuild = require('./' + esVersion);
module.exports = sdkBuild;
// The following explicit assignments enable named imports in mjs files.
module.exports.getSdk = sdkBuild.getSdk;
module.exports.setSharedOptions = sdkBuild.setSharedOptions;
module.exports.fromSharedOptions = sdkBuild.fromSharedOptions;


text:
@interface Sub1InterfaceController : WKInterfaceController

@end


text:
package net.clanwolf.starmap.server.util;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Log {
	private static final Logger sLogger = Logger.getLogger(Log.class);

	/*
	 * Private Constructor to prevent instantiation.
	 */
	private Log() {
		// nothing
	}

	public static void setLogLevel(Level level) {
		sLogger.setLevel(level);
	}

	public static Level getLogLevel() {
		return sLogger.getLevel();
	}

	public static void error(String text, Throwable th) {
		sLogger.error(text, th);
	}

	public static void warn(String text) {
		sLogger.warn("C3/W> " + text);
	}

	public static void debug(String text) {
		sLogger.debug("C3/W> " + text);
	}

	public static void print(String text) {
		sLogger.info("C3/P> " + text);
	}

	public static void info(String text) {
		info(null, text);
	}

	public static void info(Object source, String text) {
		if (source != null) {
			sLogger.info("C3/I> (" + source.getClass().getName() + ") " + text);
		} else {
			sLogger.info("C3/I> " + text);
		}
	}

	public static void exception(Object source, Throwable e) {
		if (source != null) {
			sLogger.error("C3/E> (" + source.getClass().getName() + ") " + e.getMessage());
		} else {
			sLogger.error("C3/E> " + e);
		}
	}

	public static void exception(Object source, Exception e, String message) {
		if (source != null) {
			sLogger.error("C3/E> (" + source.getClass().getName() + ") " + e.getMessage());
		} else {
			sLogger.error("C3/E> " + e + " - " + message);
		}
	}
}


text:
var x = "Ha!"
console.log(x)

// Complete one of the exercises: Looping a Triangle, FizzBuzz, or Chess Board
var food = prompt("What is your B food?")
alert("Woow, this is my best too!")

for (var i=1; i <= 20; i++)
{
    if (i % 15 == 0)
        console.log("FizzBuzz");
    else if (i % 3 == 0)
        console.log("Fizz");
    else if (i % 5 == 0)
        console.log("Buzz");
    else
        console.log(i);
}

// Functions

// Complete the `minimum` exercise.

// Data Structures: Objects and Arrays
// Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below.

var me =  {
	name: "Alex",
	age: 20,
	food: ["Sushi", "Blueberries", "Banan-Shake"],
	quirk: "I am a hitchhiker"

}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="myzend.com" type="PhpLocalRunConfigurationType" factoryName="PHP Console" path="$PROJECT_DIR$">
    <RunnerSettings RunnerId="PhpRunner" />
    <RunnerSettings RunnerId="PhpScriptDebugRunner" />
    <ConfigurationWrapper RunnerId="PhpRunner" />
    <ConfigurationWrapper RunnerId="PhpScriptDebugRunner" />
    <method />
  </configuration>
</component>


text:
namespace MB
{
  struct BasicConfig
  {
    ProgramInfo Program;
    std::string ToolStatement;
    std::string NamespaceName;
    std::string APIName;
    std::string APIVersion;
	// The header file version this is based upon
    VersionRecord CurrentAPIVersion;

    BasicConfig()
      : Program()
    {
    }

    BasicConfig(const ProgramInfo& programInfo, const std::string& toolStatement, const std::string& namespaceName, const std::string& apiName,
                const std::string& apiVersion, const VersionRecord& currentAPIVersion)
      : Program(programInfo)
      , ToolStatement(toolStatement)
      , NamespaceName(namespaceName)
      , APIName(apiName)
      , APIVersion(apiVersion)
      , CurrentAPIVersion(currentAPIVersion)
    {
    }
  };

}

#endif


text:
namespace Wilderness.Game.MapGenerator
{
  public interface ITiledMap<T>
    where T : struct
  {
    /// <summary>
    /// Size of tiles in game distance unit.
    /// </summary>
    double TileSize { get; }

    /// <summary>
    /// Access tiles by tile index.
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <returns></returns>
    Tile<T> this[int x, int y] { get; set; }

    /// <summary>
    /// Access tiles by game distance unit.
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <returns></returns>
    Tile<T> this[double x, double y] { get; set; }
  }
}


text:
define(['share_model'], function (ShareModel) {
	var ShareDialog = Backbone.View.extend({

		events: {
			'click .btn-primary': 'accept',
			'shown': 'shown'
		},

		accept: function() {
			this.model.title = this.titleInput.val();
			this.model.content = this.contentInput.val();
            this.model.attachment = this.attachmentInput[0].files[0];
			this.created = new Date();

            // It would be nice to be able to use this, but currently Backbone doesn't handle multipart on sync
            // There are a bunch of interesting solutions out there, such as this one https://gist.github.com/unixcharles/1278188
            // but assuming that we have HTML5, it seems easier to use the JQuery code in 'upload'
            // Backbone.sync('create', this.model);
            this.upload(this.model);
		},

        initialize: function() {
            this.titleInput = this.$('#share-title');
			this.contentInput = this.$('#share-content');
            this.attachmentInput = this.$('#share-attachment');
        },

        onComplete: function() {
            // Hide the dialog
			$('#share-dialog').modal('hide');
            //this.attributes.router.navigate('browse', {trigger: true});
			Backbone.Mediator.trigger('onBrowse');
        },

        onFailure: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus);
        },

        onInvalid: function(jqXHR, textStatus, errorThrown) {
            var errors = $.parseJSON(jqXHR.responseText);

            for ( var key in errors) {
                var selector = '[name="' + key + '"]';
                var error = errors[key][0];
                var $input = $(selector);
                $input.after('' + error + '');
                $input.closest('.control-group').addClass('error');
            }
        },

		render: function() {
			this.model = new ShareModel();

			this.titleInput.val('');
			this.contentInput.val('');
            this.attachmentInput.val('');

			return this;
		},

		shown: function() {
			this.render();
		},

        upload: function(model) {
            var data = new FormData();
			if (model.title != null)
                data.append('share_title', model.title);
            if (model.content != null)
                data.append('share_content', model.content);
            if (model.attachment != null)
                data.append('share_attachment', model.attachment);

			$.ajax({
                url : '/api/share',
                data : data,
                processData : false,
                contentType : false,
                type : 'POST',
                statusCode : {
                    200 : this.onComplete,
                    400 : this.onInvalid,
                    500 : this.onFailure,
                }
            });
        }

	});
	return ShareDialog;
});


text:
namespace ash {

namespace {

constexpr char kStartTime[] = "1 Jan 2020 21:00";

void SetScreenOff(bool is_screen_off) {
  power_manager::ScreenIdleState screen_idle_state;
  screen_idle_state.set_off(is_screen_off);
  FakePowerManagerClient::Get()->SendScreenIdleStateChanged(screen_idle_state);
}

void SetSuspendImminent() {
  FakePowerManagerClient::Get()->SendSuspendImminent(
      power_manager::SuspendImminent_Reason_OTHER);
}

}  // namespace

class FamilyUserMetricsServiceTestObserver
    : public FamilyUserMetricsService::Observer {
 public:
  MOCK_METHOD(void, OnNewDay, (), (override));
};

// Tests for family user metrics service.
class FamilyUserMetricsServiceTest : public testing::Test {
 public:
  void SetUp() override {
    base::Time start_time;
    EXPECT_TRUE(base::Time::FromString(kStartTime, &start_time));
    base::TimeDelta forward_by = start_time - base::Time::Now();
    EXPECT_LT(base::TimeDelta(), forward_by);
    task_environment_.AdvanceClock(forward_by);

    PowerManagerClient::InitializeFake();
    family_user_metrics_service_ =
        std::make_unique<FamilyUserMetricsService>(&testing_profile_);

    family_user_metrics_service_->AddObserver(&mock_observer_);
  }

  void TearDown() override {
    family_user_metrics_service_->Shutdown();
    family_user_metrics_service_.reset();
    PowerManagerClient::Shutdown();
  }

 protected:
  sync_preferences::TestingPrefServiceSyncable* GetPrefService() {
    return testing_profile_.GetTestingPrefService();
  }

  int GetDayIdPref() {
    return GetPrefService()->GetInteger(prefs::kFamilyUserMetricsDayId);
  }

  content::BrowserTaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};

  FamilyUserMetricsServiceTestObserver mock_observer_;

 private:
  // We need this member variable, even if it's unused, so
  // FamilyUserSessionMetrics doesn't crash.
  session_manager::SessionManager session_manager_;
  TestingProfile testing_profile_;
  std::unique_ptr<FamilyUserMetricsService> family_user_metrics_service_;
};

using DetectingNewDayTest = FamilyUserMetricsServiceTest;

// Tests OnNewDay() is called after more than one day passes.
TEST_F(DetectingNewDayTest, MoreThanOneDay) {
  EXPECT_CALL(mock_observer_, OnNewDay()).Times(1);
  task_environment_.FastForwardBy(base::Days(1) + base::Hours(1));
  EXPECT_EQ(FamilyUserMetricsService::GetDayIdForTesting(base::Time::Now()),
            GetDayIdPref());
}

// Tests OnNewDay() is called at midnight.
TEST_F(DetectingNewDayTest, UntilMidnight) {
  EXPECT_CALL(mock_observer_, OnNewDay()).Times(1);
  task_environment_.FastForwardBy(base::Hours(3));
  EXPECT_EQ(FamilyUserMetricsService::GetDayIdForTesting(base::Time::Now()),
            GetDayIdPref());
}

// Tests OnNewDay() is not called before midnight.
TEST_F(DetectingNewDayTest, LessThanOneDay) {
  EXPECT_CALL(mock_observer_, OnNewDay()).Times(0);
  task_environment_.FastForwardBy(base::Hours(1));
  EXPECT_EQ(FamilyUserMetricsService::GetDayIdForTesting(base::Time::Now()),
            GetDayIdPref());
}

// Tests OnNewDay() is called after one day passes, even when the device is
// idle.
TEST_F(DetectingNewDayTest, MoreThanOneDayDeviceIdle) {
  EXPECT_CALL(mock_observer_, OnNewDay()).Times(1);
  SetScreenOff(true);
  SetSuspendImminent();
  task_environment_.FastForwardBy(base::Days(1));
  EXPECT_EQ(FamilyUserMetricsService::GetDayIdForTesting(base::Time::Now()),
            GetDayIdPref());
}

}  // namespace ash


text:
using System;
using System.Collections.Generic;
using System.Windows.Documents;
using System.Windows.Markup;

namespace DocumentMerge
{
    /// <summary>
    ///     Maintains data needed to generate a DocumentReference to be added to a RollUpDocument
    /// </summary>
    public class RollUpFixedDocument
    {
        public RollUpFixedDocument()
        {
            Pages = new List<RollUpFixedPage>();
        }

        public RollUpFixedDocument(FixedDocument fixedDocument)
            : this()
        {
            FixedDocument = fixedDocument;
        }

        public RollUpFixedDocument(Uri source, Uri baseUri)
            : this()
        {
            Source = source;
            BaseUri = baseUri;
        }

        public FixedDocument FixedDocument { get; set; }
        public List<RollUpFixedPage> Pages { get; set; }
        public Uri BaseUri { get; set; }
        public Uri Source { get; set; }

        internal void CreatePagesFromSource()
        {
            var documentReference = new DocumentReference {Source = Source};
            ((IUriContext) documentReference).BaseUri = BaseUri;
            var fixedDocument = documentReference.GetDocument(true);
            PrivateCreatePagesFromFixedDocument(fixedDocument);
        }

        internal void CreatePagesFromFixedDocument()
        {
            PrivateCreatePagesFromFixedDocument(FixedDocument);
        }

        private void PrivateCreatePagesFromFixedDocument(FixedDocument fixedDocument)
        {
            foreach (var pageContent in fixedDocument.Pages)
            {
                Pages.Add(((IUriContext) pageContent).BaseUri != null
                    ? new RollUpFixedPage(pageContent.Source, ((IUriContext) pageContent).BaseUri)
                    : new RollUpFixedPage(pageContent.Child));
            }
            Source = null;
            BaseUri = null;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:id="@+id/coordinator_layout"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="38dp"
        android:background="@color/tab_bg">

        <android.support.design.widget.TabLayout
            android:id="@+id/subTabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/vLine"
            app:tabSelectedTextColor="@color/subtab_text_selected"
            app:tabTextColor="@color/subtab_text_default"/>

        <View
            android:id="@+id/vLine"
            android:layout_width="1px"
            android:layout_height="match_parent"
            android:layout_marginBottom="3dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@+id/ivMore"
            android:background="@color/gray_split"/>

        <ImageView
            android:id="@+id/ivMore"
            android:layout_width="42dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@drawable/bg_touch_tab"
            android:scaleType="center"
            android:src="@drawable/ic_more_down"/>
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="@color/gray_split"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/subPages"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"/>
</LinearLayout>


text:
/*
 * This file is generated by jOOQ.
*/
package com.jbsc.jooq.domain.tables;

import com.jbsc.jooq.domain.Keys;
import com.jbsc.jooq.domain.Public;
import com.jbsc.jooq.domain.tables.records.RatePlanRecord;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.9.1"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class RatePlan extends TableImpl<RatePlanRecord> {

    private static final long serialVersionUID = -1027117668;

    /**
     * The reference instance of public.rate_plan
     */
    public static final RatePlan RATE_PLAN = new RatePlan();

    /**
     * The class holding records for this type
     */
    @Override
    public Class<RatePlanRecord> getRecordType() {
        return RatePlanRecord.class;
    }

    /**
     * The column public.rate_plan.id.
     */
    public final TableField<RatePlanRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('rateplan_id_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");

    /**
     * The column public.rate_plan.type.
     */
    public final TableField<RatePlanRecord, Integer> TYPE = createField("type", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('rateplan_type_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");

    /**
     * The column public.rate_plan.price.
     */
    public final TableField<RatePlanRecord, BigDecimal> PRICE = createField("price", org.jooq.impl.SQLDataType.NUMERIC.precision(4, 2).nullable(false), this, "");

    /**
     * The column public.rate_plan.currency.
     */
    public final TableField<RatePlanRecord, String> CURRENCY = createField("currency", org.jooq.impl.SQLDataType.CLOB, this, "");

    /**
     * The column public.rate_plan.frequency_days.
     */
    public final TableField<RatePlanRecord, Integer> FREQUENCY_DAYS = createField("frequency_days", org.jooq.impl.SQLDataType.INTEGER, this, "");

    /**
     * Create a public.rate_plan table reference
     */
    public RatePlan() {
        this("rate_plan", null);
    }

    /**
     * Create an aliased public.rate_plan table reference
     */
    public RatePlan(String alias) {
        this(alias, RATE_PLAN);
    }

    private RatePlan(String alias, Table<RatePlanRecord> aliased) {
        this(alias, aliased, null);
    }

    private RatePlan(String alias, Table<RatePlanRecord> aliased, Field<?>[] parameters) {
        super(alias, null, aliased, parameters, "");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Schema getSchema() {
        return Public.PUBLIC;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Identity<RatePlanRecord, Integer> getIdentity() {
        return Keys.IDENTITY_RATE_PLAN;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UniqueKey<RatePlanRecord> getPrimaryKey() {
        return Keys.PK_RATEPLAN_01;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<UniqueKey<RatePlanRecord>> getKeys() {
        return Arrays.<UniqueKey<RatePlanRecord>>asList(Keys.PK_RATEPLAN_01);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<ForeignKey<RatePlanRecord, ?>> getReferences() {
        return Arrays.<ForeignKey<RatePlanRecord, ?>>asList(Keys.RATE_PLAN__FK_PRODUCTTYPE_01);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public RatePlan as(String alias) {
        return new RatePlan(alias, this);
    }

    /**
     * Rename this table
     */
    @Override
    public RatePlan rename(String name) {
        return new RatePlan(name, null);
    }
}


text:
package es.sidelab.apirest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RestApplication{

	public static void main(String[] args) {
		SpringApplication.run(RestApplication.class, args);
	}
}


text:
class ActiveSupport::IntegrationCase < ActiveSupport::TestCase
  include Capybara::DSL
  include Rails.application.routes.url_helpers

  teardown do
    DatabaseCleaner.clean       # Truncate the database
    Capybara.reset_sessions!    # Forget the (simulated) browser state
    Capybara.use_default_driver # Revert Capybara.current_driver to Capybara.default_driver
  end

end


text:
var resources = function (page, meta) {
    return {
        js: ['api_subscriptions.js'],
        code: ['api_subscriptions/api-subscriptions-metadata.hbs']
    };
};


text:
function(e, match) {
    var $$this = $$(this);
    if (API.videoHints) {
        if (!$$this.helperInserted) {
            var helper = $('<div class="helper" />');

            $('.container-main-column', this).append(helper);
            helper.evently('videoHints', APPS["teamfm-core"], []);

            $$this.helperInserted = true;
        }
    }
}


text:
<!DOCTYPE html>

		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<title>Tob the Bot</title>
		<meta name="generator" content="Bootply" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link href="css/bootstrap.min.css" rel="stylesheet">

		<link href="css/styles.css" rel="stylesheet">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

      </button>
      Control Panel