text:
Parse.initialize("iXDvlSh7XJjt7J5a0vB6kgWSljEjtIICxAWTQnrF", "twvM3T7jNdbEB2jlJUSk7iXKjb24xv0IOjpJYUtA");
let _ = require('lodash')
let ParseFetcher = {
	getAllCandidates: () => {
		// Get candidates from Parse
		return new Promise((resolve, reject) => {
			var query = new Parse.Query('Candidates');
			query.limit = 10;

			query.find().then(function(results) {
				var arrCandidates = [];
				var arrKeys = ["first_name", "last_name", "party", "objectId"];
				for (var j = results.length - 1; j >= 0; j--) {
					var candidate = {}
					for (var i = 0; i < 4; i++) {
						switch(arrKeys[i]) {
							case "first_name":
								candidate["first_name"] = results[j].get("first_name");
								break;
							case "last_name":
								candidate["last_name"] = results[j].get("last_name");
								break;
							case "party":
								candidate["party"] = results[j].get("party");
								break;
							case "objectId":
								candidate["id"] = results[j].id;
								break;
						}
					}
					arrCandidates.push(candidate);
				};
				resolve(arrCandidates)
			}, function(error) {
				reject(error)
			});
		})
	},
	getAllIssues: () => {
		// Get candidates from Parse
		return new Promise((resolve, reject) => {
			var query = new Parse.Query('Issues');
			query.limit = 10;

			query.find().then(function(results) {
				var arrIssues = [];
				var arrKeys = ["issueName", "objectId"];
				for (var j = results.length - 1; j >= 0; j--) {
					var issue = {}
					for (var i = 0; i < 2; i++) {
						switch(arrKeys[i]) {
							case "issueName":
								issue["issueName"] = results[j].get("issueName");
								break;
							case "objectId":
								issue["id"] = results[j].id;
								break;
						}
					}
					arrIssues.push(issue);
				};
				resolve(arrIssues)
			}, function(error) {
				reject(error)
			});

		})
	},
	getVideos: (issueIDs, candidateIDs, offset, limit) => {
		// issueID: array, issue ids to filter videos by, don't filter if empty array
		// candidateIDs: array, candidate ids to filter videos by, don't filter if empty array
		// offset: int, skip the first offset # of elements
		// limit: int, only return limit # of elements
		return new Promise((resolve, reject) => {

			var promises = [];

			var countQuery = new Parse.Query('Videos');
			if (typeof issueIDs != "undefined" && issueIDs != null && issueIDs.length > 0) { // checks if issueIDs is populated

				countQuery = countQuery.containedIn("issuesID", issueIDs)
			}
			if (typeof candidateIDs != "undefined" && candidateIDs != null && candidateIDs.length > 0) { // checks if candidateIDs is populated

				countQuery = countQuery.containedIn("candidatesID", candidateIDs)
			}
			promises.push(countQuery.count().then(function(a) {

				return a
			}))

			let recordQuery = new Parse.Query('Videos')
			if (typeof issueIDs != "undefined" && issueIDs != null && issueIDs.length > 0) { // checks if issueIDs is populated

				recordQuery = recordQuery.containedIn("issuesID", issueIDs)
			}
			if (typeof candidateIDs != "undefined" && candidateIDs != null && candidateIDs.length > 0) { // checks if candidateIDs is populated

				recordQuery = recordQuery.containedIn("candidatesID", candidateIDs)
			}
			recordQuery.skip(offset)
			recordQuery.limit(limit)

			promises.push(recordQuery.find().then(function(a) {

				return a
			}))

			return Promise.all(promises).then((results) => {

				let count = results[0], records = results[1].map((record) => {
					let recordObj = {}
					let attributeMap = {
						"videoID": "videoID",
						"confidence": "score",
						"startTime": "startTime",
						"endTime": "endTime",
						"candidatesID": "candidate_id",
						"issuesID": "issue_id",
						"id": "id"
					}
					for (let key in attributeMap) {
						if (key == 'id')
							recordObj.id = record.id
						else
							recordObj[attributeMap[key]] = record.get(key)
					}

					// Add 2s to start and end of video for Indico
					recordObj.startTime = Math.max(0, recordObj.startTime - 2)
					recordObj.endTime += 2

					return recordObj
				})
				resolve({
					count: count,
					videos: records
				})
			})

		})
	}
}

module.exports = ParseFetcher


text:
export function changePath(path) {
    if (typeof mixpanel !== "undefined" && typeof mixpanel.track === 'function'){
        try{
            mixpanel.track("Swap_ChangePath", {path: path})
        }catch(e){
            console.log(e)
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import { Text } from '@dlghq/react-l10n';
import Spinner from '../Spinner/Spinner';
import Tooltip from '../Tooltip/Tooltip';
import Icon from '../Icon/Icon';
import styles from './ActivityListMembers.css';
import errorToString from '../../utils/errorToString';

export type Props = {
  error: ?(Error | string),
  pending: boolean,
  onClick: (event: SyntheticMouseEvent) => void
};

function ActivityListMembersKick(props: Props) {
  if (props.pending) {
    return (
      <Spinner type="round" className={styles.kickMemberPending} />
    );
  }

  const error = errorToString(props.error);

  if (error) {
    return (
      <Tooltip
        text={error}
        options={{
          attachment: 'middle right',
          targetAttachment: 'middle left',
          constraints: [
            {
              to: 'window',
              attachment: 'together'
            }
          ]
        }}
      >
        <Icon glyph="error" className={styles.kickMemberError} onClick={props.onClick} />
      </Tooltip>
    );
  }

  return (
    <div className={styles.kickMember} onClick={props.onClick}>
      <Text id="ActivityListMembers.kick" />
    </div>
  );
}

export default ActivityListMembersKick;


text:
package erepnikov.dao;

import erepnikov.DB;
import erepnikov.models.Role;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Class RoleDAO
 *
 * @author Egor Repnikov
 * @version 1.0.0
 * @since 17.09.2017
 */
public class RoleDAO {

    /**
     * Add role
     *
     * @param role
     */
    public void add(Role role) {
        try (PreparedStatement ps = DB.getConnectDB().prepareStatement(
                "insert into roles (name) values (?);"
        )) {
            ps.setString(1, role.getName());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return all roles in List
     */
    public List<Role> getAll() {
        List<Role> result = new ArrayList<>();
        try (Statement statement = DB.getConnectDB().createStatement()) {
            try (ResultSet rs = statement.executeQuery("select * from roles")) {
                while (rs.next()) {
                    result.add(
                            new Role(
                                    rs.getInt("id"),
                                    rs.getString("name")
                            )
                    );
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param id
     * @return role by id
     */
    public Role get(int id) {
        Role result = null;
        try (PreparedStatement ps = DB.getConnectDB().prepareStatement(
                "select * from roles where id = ?;")
        ) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                rs.next();
                result = new Role(
                        rs.getInt("id"),
                        rs.getString("name")
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Edit role
     *
     * @param role
     */
    public void edit(Role role) {
        try (PreparedStatement ps = DB.getConnectDB().prepareStatement(
                "update roles set name = ? where id = ?;")
        ) {
            ps.setString(1, role.getName());
            ps.setInt(2, role.getId());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Delete role
     *
     * @param id
     */
    public void delete(int id) {
        try (PreparedStatement ps = DB.getConnectDB().prepareStatement("delete from roles where id = ?")) {
            ps.setInt(1, id);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Roccella boergesenii Vain.

### Remarks
null


text:
require "spec_helper"

describe Client do
  let(:client) { create(:client) }

  describe "validations" do
    it { should validate_presence_of :name }
    it { should validate_uniqueness_of :name }
  end

  describe "associations" do
    it { should have_many :projects }
  end

  describe "#by_name" do
    it "orders by name case insensitive" do
      create(:client, name: "B")
      a = create(:client, name: "a")
      expect(Client.by_name.first).to eq(a)
    end
  end

  describe "#logo_url" do
    context "when it is set" do
      it "returns the uploaded image" do
        fake_logo = "logo.png"
        client = build(:client, logo: fixture_file_upload(fake_logo))
        expect(client.logo_url).to eq(client.logo.url(:original))
      end
    end
  end
end


text:
package org.apache.phoenix.end2end;

import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.Properties;

import org.apache.phoenix.compile.ExplainPlan;
import org.apache.phoenix.compile.ExplainPlanAttributes;
import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
import org.apache.phoenix.query.BaseTest;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.ReadOnlyProps;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;

@Category(NeedsOwnMiniClusterTest.class)
public class CostBasedDecisionIT extends BaseTest {
    private final String testTable500;
    private final String testTable990;
    private final String testTable1000;

    @BeforeClass
    public static synchronized void doSetup() throws Exception {
        Map<String, String> props = Maps.newHashMapWithExpectedSize(1);
        props.put(QueryServices.STATS_GUIDEPOST_WIDTH_BYTES_ATTRIB, Long.toString(20));
        props.put(QueryServices.STATS_UPDATE_FREQ_MS_ATTRIB, Long.toString(5));
        props.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(true));
        props.put(QueryServices.COST_BASED_OPTIMIZER_ENABLED, Boolean.toString(true));
        props.put(QueryServices.MAX_SERVER_CACHE_SIZE_ATTRIB, Long.toString(150000));
        setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
    }

    public CostBasedDecisionIT() throws Exception {
        testTable500 = initTestTableValues(500);
        testTable990 = initTestTableValues(990);
        testTable1000 = initTestTableValues(1000);
    }

    @Test
    public void testCostOverridesStaticPlanOrdering1() throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(true);
        try {
            String tableName = BaseTest.generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "rowkey VARCHAR PRIMARY KEY,\n" +
                    "c1 VARCHAR,\n" +
                    "c2 VARCHAR)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx ON " + tableName + " (c1)");

            String query = "SELECT rowkey, c1, c2 FROM " + tableName + " where c1 LIKE 'X0%' ORDER BY rowkey";
            // Use the data table plan that opts out order-by when stats are not available.
            verifyQueryPlan(query, "FULL SCAN");

            PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
            for (int i = 0; i < 10000; i++) {
                int c1 = i % 16;
                stmt.setString(1, "k" + i);
                stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
                stmt.setString(3, "c");
                stmt.execute();
            }

            conn.createStatement().execute("UPDATE STATISTICS " + tableName);

            // Use the index table plan that has a lower cost when stats become available.
            verifyQueryPlan(query, "RANGE SCAN");
        } finally {
            conn.close();
        }
    }

    @Test
    public void testCostOverridesStaticPlanOrdering2() throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(true);
        try {
            String tableName = BaseTest.generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "rowkey VARCHAR PRIMARY KEY,\n" +
                    "c1 VARCHAR,\n" +
                    "c2 VARCHAR)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx ON " + tableName + " (c1)");

            String query = "SELECT c1, max(rowkey), max(c2) FROM " + tableName + " where rowkey <= 'z' GROUP BY c1";
            // Use the index table plan that opts out order-by when stats are not available.
            ExplainPlan plan = conn.prepareStatement(query)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            ExplainPlanAttributes explainPlanAttributes =
                plan.getPlanStepsAsAttributes();
            assertEquals("PARALLEL 1-WAY",
                explainPlanAttributes.getIteratorTypeAndScanSize());
            assertEquals("RANGE SCAN ",
                explainPlanAttributes.getExplainScanType());
            assertEquals(tableName, explainPlanAttributes.getTableName());
            assertEquals(" [*] - ['z']", explainPlanAttributes.getKeyRanges());
            assertEquals("SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]",
                explainPlanAttributes.getServerAggregate());
            assertEquals("CLIENT MERGE SORT",
                explainPlanAttributes.getClientSortAlgo());

            PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
            for (int i = 0; i < 10000; i++) {
                int c1 = i % 16;
                stmt.setString(1, "k" + i);
                stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
                stmt.setString(3, "c");
                stmt.execute();
            }

            conn.createStatement().execute("UPDATE STATISTICS " + tableName);

            // Given that the range on C1 is meaningless and group-by becomes
            // order-preserving if using the data table, the data table plan should
            // come out as the best plan based on the costs.
            plan = conn.prepareStatement(query)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            explainPlanAttributes = plan.getPlanStepsAsAttributes();
            assertEquals("PARALLEL 1-WAY",
                explainPlanAttributes.getIteratorTypeAndScanSize());
            assertEquals("RANGE SCAN ",
                explainPlanAttributes.getExplainScanType());
            assertEquals(tableName, explainPlanAttributes.getTableName());
            assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
            assertEquals("SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'",
                explainPlanAttributes.getServerWhereFilter());
            assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]",
                explainPlanAttributes.getServerAggregate());
            assertEquals("CLIENT MERGE SORT",
                explainPlanAttributes.getClientSortAlgo());
        } finally {
            conn.close();
        }
    }

    @Test
    public void testCostOverridesStaticPlanOrdering3() throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(true);
        try {
            String tableName = BaseTest.generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "rowkey VARCHAR PRIMARY KEY,\n" +
                    "c1 INTEGER,\n" +
                    "c2 INTEGER,\n" +
                    "c3 INTEGER)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx1 ON " + tableName + " (c1) INCLUDE (c2, c3)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx2 ON " + tableName + " (c2, c3) INCLUDE (c1)");

            String query = "SELECT * FROM " + tableName + " where c1 BETWEEN 10 AND 20 AND c2 < 9000 AND C3 < 5000";
            // Use the idx2 plan with a wider PK slot span when stats are not available.
            ExplainPlan plan = conn.prepareStatement(query)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            ExplainPlanAttributes explainPlanAttributes =
                plan.getPlanStepsAsAttributes();
            assertEquals("PARALLEL 1-WAY",
                explainPlanAttributes.getIteratorTypeAndScanSize());
            assertEquals("RANGE SCAN ",
                explainPlanAttributes.getExplainScanType());
            assertEquals(tableName, explainPlanAttributes.getTableName());
            assertEquals(" [2,*] - [2,9,000]",
                explainPlanAttributes.getKeyRanges());
            assertEquals("SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)",
                explainPlanAttributes.getServerWhereFilter());
            assertEquals("CLIENT MERGE SORT",
                explainPlanAttributes.getClientSortAlgo());

            PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2, c3) VALUES (?, ?, ?, ?)");
            for (int i = 0; i < 10000; i++) {
                stmt.setString(1, "k" + i);
                stmt.setInt(2, i);
                stmt.setInt(3, i);
                stmt.setInt(4, i);
                stmt.execute();
            }

            conn.createStatement().execute("UPDATE STATISTICS " + tableName);

            // Use the idx2 plan that scans less data when stats become available.
            plan = conn.prepareStatement(query)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            explainPlanAttributes = plan.getPlanStepsAsAttributes();
            assertEquals("PARALLEL 1-WAY",
                explainPlanAttributes.getIteratorTypeAndScanSize());
            assertEquals("RANGE SCAN ",
                explainPlanAttributes.getExplainScanType());
            assertEquals(tableName, explainPlanAttributes.getTableName());
            assertEquals(" [1,10] - [1,20]",
                explainPlanAttributes.getKeyRanges());
            assertEquals("SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)",
                explainPlanAttributes.getServerWhereFilter());
            assertEquals("CLIENT MERGE SORT",
                explainPlanAttributes.getClientSortAlgo());
        } finally {
            conn.close();
        }
    }

    @Test
    public void testCostOverridesStaticPlanOrderingInUpsertQuery() throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(true);
        try {
            String tableName = BaseTest.generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "rowkey VARCHAR PRIMARY KEY,\n" +
                    "c1 INTEGER,\n" +
                    "c2 INTEGER,\n" +
                    "c3 INTEGER)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx1 ON " + tableName + " (c1) INCLUDE (c2, c3)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx2 ON " + tableName + " (c2, c3) INCLUDE (c1)");

            String query = "UPSERT INTO " + tableName + " SELECT * FROM " + tableName + " where c1 BETWEEN 10 AND 20 AND c2 < 9000 AND C3 < 5000";
            // Use the idx2 plan with a wider PK slot span when stats are not available.
            verifyQueryPlan(query,
                    "UPSERT SELECT\n" +
                    "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [2,*] - [2,9,000]\n" +
                            "    SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)\n" +
                            "CLIENT MERGE SORT");

            PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2, c3) VALUES (?, ?, ?, ?)");
            for (int i = 0; i < 10000; i++) {
                stmt.setString(1, "k" + i);
                stmt.setInt(2, i);
                stmt.setInt(3, i);
                stmt.setInt(4, i);
                stmt.execute();
            }

            conn.createStatement().execute("UPDATE STATISTICS " + tableName);

            // Use the idx2 plan that scans less data when stats become available.
            verifyQueryPlan(query,
                    "UPSERT SELECT\n" +
                    "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [1,10] - [1,20]\n" +
                            "    SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)\n" +
                            "CLIENT MERGE SORT");
        } finally {
            conn.close();
        }
    }

    @Test
    public void testCostOverridesStaticPlanOrderingInDeleteQuery() throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(true);
        try {
            String tableName = BaseTest.generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "rowkey VARCHAR PRIMARY KEY,\n" +
                    "c1 INTEGER,\n" +
                    "c2 INTEGER,\n" +
                    "c3 INTEGER)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx1 ON " + tableName + " (c1) INCLUDE (c2, c3)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx2 ON " + tableName + " (c2, c3) INCLUDE (c1)");

            String query = "DELETE FROM " + tableName + " where c1 BETWEEN 10 AND 20 AND c2 < 9000 AND C3 < 5000";
            // Use the idx2 plan with a wider PK slot span when stats are not available.
            verifyQueryPlan(query,
                    "DELETE ROWS CLIENT SELECT\n" +
                    "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [2,*] - [2,9,000]\n" +
                            "    SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)\n" +
                            "CLIENT MERGE SORT");

            PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2, c3) VALUES (?, ?, ?, ?)");
            for (int i = 0; i < 10000; i++) {
                stmt.setString(1, "k" + i);
                stmt.setInt(2, i);
                stmt.setInt(3, i);
                stmt.setInt(4, i);
                stmt.execute();
            }

            conn.createStatement().execute("UPDATE STATISTICS " + tableName);

            // Use the idx2 plan that scans less data when stats become available.
            verifyQueryPlan(query,
                    "DELETE ROWS CLIENT SELECT\n" +
                    "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [1,10] - [1,20]\n" +
                            "    SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)\n" +
                            "CLIENT MERGE SORT");
        } finally {
            conn.close();
        }
    }

    @Test
    public void testCostOverridesStaticPlanOrderingInUnionQuery() throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(true);
        try {
            String tableName = BaseTest.generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "rowkey VARCHAR PRIMARY KEY,\n" +
                    "c1 VARCHAR,\n" +
                    "c2 VARCHAR)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx ON " + tableName + " (c1)");

            String query = "SELECT c1, max(rowkey), max(c2) FROM " + tableName + " where rowkey <= 'z' GROUP BY c1 "
                    + "UNION ALL SELECT c1, max(rowkey), max(c2) FROM " + tableName + " where rowkey >= 'a' GROUP BY c1";
            // Use the default plan when stats are not available.
            verifyQueryPlan(query,
                    "UNION ALL OVER 2 QUERIES\n" +
                    "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [*] - ['z']\n" +
                    "        SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n" +
                    "    CLIENT MERGE SORT\n" +
                    "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " ['a'] - [*]\n" +
                    "        SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n" +
                    "    CLIENT MERGE SORT");

            PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
            for (int i = 0; i < 10000; i++) {
                int c1 = i % 16;
                stmt.setString(1, "k" + i);
                stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
                stmt.setString(3, "c");
                stmt.execute();
            }

            conn.createStatement().execute("UPDATE STATISTICS " + tableName);

            // Use the optimal plan based on cost when stats become available.
            verifyQueryPlan(query,
                    "UNION ALL OVER 2 QUERIES\n" +
                    "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [1]\n" +
                    "        SERVER MERGE [0.C2]\n" +
                    "        SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'\n" +
                    "        SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n" +
                    "    CLIENT MERGE SORT\n" +
                    "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [1]\n" +
                    "        SERVER MERGE [0.C2]\n" +
                    "        SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" >= 'a'\n" +
                    "        SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n" +
                    "    CLIENT MERGE SORT");
        } finally {
            conn.close();
        }
    }

    @Test
    public void testCostOverridesStaticPlanOrderingInJoinQuery() throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(true);
        try {
            String tableName = BaseTest.generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "rowkey VARCHAR PRIMARY KEY,\n" +
                    "c1 VARCHAR,\n" +
                    "c2 VARCHAR)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx ON " + tableName + " (c1)");

            String query = "SELECT t1.rowkey, t1.c1, t1.c2, t2.c1, mc2 FROM " + tableName + " t1 "
                    + "JOIN (SELECT c1, max(rowkey) mrk, max(c2) mc2 FROM " + tableName + " where rowkey <= 'z' GROUP BY c1) t2 "
                    + "ON t1.rowkey = t2.mrk WHERE t1.c1 LIKE 'X0%' ORDER BY t1.rowkey";
            // Use the default plan when stats are not available.
            verifyQueryPlan(query,
                    "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + tableName + "\n" +
                    "    SERVER FILTER BY C1 LIKE 'X0%'\n" +
                    "    PARALLEL INNER-JOIN TABLE 0\n" +
                    "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [*] - ['z']\n" +
                    "            SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n" +
                    "        CLIENT MERGE SORT\n" +
                    "    DYNAMIC SERVER FILTER BY T1.ROWKEY IN (T2.MRK)");

            PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
            for (int i = 0; i < 10000; i++) {
                int c1 = i % 16;
                stmt.setString(1, "k" + i);
                stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
                stmt.setString(3, "c");
                stmt.execute();
            }

            conn.createStatement().execute("UPDATE STATISTICS " + tableName);

            // Use the optimal plan based on cost when stats become available.
            verifyQueryPlan(query,
                    "CLIENT PARALLEL 626-WAY RANGE SCAN OVER " + tableName + " [1,'X0'] - [1,'X1']\n" +
                    "    SERVER MERGE [0.C2]\n" +
                    "    SERVER FILTER BY FIRST KEY ONLY\n" +
                    "    SERVER SORTED BY [\"T1.:ROWKEY\"]\n" +
                    "CLIENT MERGE SORT\n" +
                    "    PARALLEL INNER-JOIN TABLE 0\n" +
                    "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [1]\n" +
                    "            SERVER MERGE [0.C2]\n" +
                    "            SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'\n" +
                    "            SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n" +
                    "        CLIENT MERGE SORT\n" +
                    "    DYNAMIC SERVER FILTER BY \"T1.:ROWKEY\" IN (T2.MRK)");
        } finally {
            conn.close();
        }
    }

    @Test
    public void testHintOverridesCost() throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(true);
        try {
            String tableName = BaseTest.generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "rowkey INTEGER PRIMARY KEY,\n" +
                    "c1 VARCHAR,\n" +
                    "c2 VARCHAR)");
            conn.createStatement().execute("CREATE LOCAL INDEX " + tableName + "_idx ON " + tableName + " (c1)");

            String query = "SELECT rowkey, c1, c2 FROM " + tableName + " where rowkey between 1 and 10 ORDER BY c1";
            String hintedQuery = query.replaceFirst("SELECT",
                    "SELECT  /*+ INDEX(" + tableName + " " + tableName + "_idx) */");
            String dataPlan = "[C1]";
            String indexPlan = "SERVER FILTER BY FIRST KEY ONLY AND (\"ROWKEY\" >= 1 AND \"ROWKEY\" <= 10)";

            // Use the index table plan that opts out order-by when stats are not available.
            ExplainPlan plan = conn.prepareStatement(query)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            ExplainPlanAttributes explainPlanAttributes =
                plan.getPlanStepsAsAttributes();
            assertEquals(indexPlan,
                explainPlanAttributes.getServerWhereFilter());

            PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
            for (int i = 0; i < 10000; i++) {
                int c1 = i % 16;
                stmt.setInt(1, i);
                stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
                stmt.setString(3, "c");
                stmt.execute();
            }

            conn.createStatement().execute("UPDATE STATISTICS " + tableName);

            // Use the data table plan that has a lower cost when stats are available.
            plan = conn.prepareStatement(query)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            explainPlanAttributes =
                plan.getPlanStepsAsAttributes();
            assertEquals(dataPlan,
                explainPlanAttributes.getServerSortedBy());

            // Use the index table plan as has been hinted.
            plan = conn.prepareStatement(hintedQuery)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            explainPlanAttributes =
                plan.getPlanStepsAsAttributes();
            assertEquals(indexPlan,
                explainPlanAttributes.getServerWhereFilter());
        } finally {
            conn.close();
        }
    }

    /** Sort-merge-join w/ both children ordered wins over hash-join. */
    @Test
    public void testJoinStrategy() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n" +
                "ON t1.ID = t2.ID";
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
            ExplainPlan plan = conn.prepareStatement(q)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            ExplainPlanAttributes explainPlanAttributes =
                plan.getPlanStepsAsAttributes();
            assertEquals("SORT-MERGE-JOIN (INNER)",
                explainPlanAttributes.getAbstractExplainPlan());
            assertEquals("PARALLEL 1-WAY",
                explainPlanAttributes.getIteratorTypeAndScanSize());
            assertEquals("FULL SCAN ",
                explainPlanAttributes.getExplainScanType());
            assertEquals(testTable500, explainPlanAttributes.getTableName());
            ExplainPlanAttributes rhsTable =
                explainPlanAttributes.getRhsJoinQueryExplainPlan();
            assertEquals("PARALLEL 1-WAY",
                rhsTable.getIteratorTypeAndScanSize());
            assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
            assertEquals(testTable1000, rhsTable.getTableName());
        }
    }

    /** Sort-merge-join w/ both children ordered wins over hash-join in an un-grouped aggregate query. */
    @Test
    public void testJoinStrategy2() throws Exception {
        String q = "SELECT count(*)\n" +
                "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n" +
                "ON t1.ID = t2.ID\n" +
                "WHERE t1.COL1 < 200";
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
            ExplainPlan plan = conn.prepareStatement(q)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            ExplainPlanAttributes explainPlanAttributes =
                plan.getPlanStepsAsAttributes();
            assertEquals("SORT-MERGE-JOIN (INNER)",
                explainPlanAttributes.getAbstractExplainPlan());
            assertEquals("PARALLEL 1-WAY",
                explainPlanAttributes.getIteratorTypeAndScanSize());
            assertEquals("FULL SCAN ",
                explainPlanAttributes.getExplainScanType());
            assertEquals("SERVER FILTER BY COL1 < 200",
                explainPlanAttributes.getServerWhereFilter());
            assertEquals(testTable500, explainPlanAttributes.getTableName());
            assertEquals("CLIENT AGGREGATE INTO SINGLE ROW",
                explainPlanAttributes.getClientAggregate());
            ExplainPlanAttributes rhsTable =
                explainPlanAttributes.getRhsJoinQueryExplainPlan();
            assertEquals("PARALLEL 1-WAY",
                rhsTable.getIteratorTypeAndScanSize());
            assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
            assertEquals("SERVER FILTER BY FIRST KEY ONLY",
                rhsTable.getServerWhereFilter());
            assertEquals(testTable1000, rhsTable.getTableName());
        }
    }

    /** Hash-join w/ PK/FK optimization wins over sort-merge-join w/ larger side ordered. */
    @Test
    public void testJoinStrategy3() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n" +
                "ON t1.COL1 = t2.ID\n" +
                "WHERE t1.ID > 200";
        String expected =
                "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "    PARALLEL INNER-JOIN TABLE 0\n" +
                "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]\n" +
                "    DYNAMIC SERVER FILTER BY T2.ID IN (T1.COL1)";
        verifyQueryPlan(q, expected);
    }

    /** Hash-join w/ PK/FK optimization wins over hash-join w/o PK/FK optimization when two sides are close in size. */
    @Test
    public void testJoinStrategy4() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable990 + " t1 JOIN " + testTable1000 + " t2\n" +
                "ON t1.ID = t2.COL1";
        String expected =
                "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable990 + "\n" +
                "    PARALLEL INNER-JOIN TABLE 0\n" +
                "        CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "    DYNAMIC SERVER FILTER BY T1.ID IN (T2.COL1)";
        verifyQueryPlan(q, expected);
    }

    /** Hash-join wins over sort-merge-join w/ smaller side ordered. */
    @Test
    public void testJoinStrategy5() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n" +
                "ON t1.ID = t2.COL1\n" +
                "WHERE t1.ID > 200";
        String expected =
                "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "    PARALLEL INNER-JOIN TABLE 0\n" +
                "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]";
        verifyQueryPlan(q, expected);
    }

    /** Hash-join wins over sort-merge-join w/o any side ordered. */
    @Test
    public void testJoinStrategy6() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n" +
                "ON t1.COL1 = t2.COL1\n" +
                "WHERE t1.ID > 200";
        String expected =
                "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "    PARALLEL INNER-JOIN TABLE 0\n" +
                "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]";
        verifyQueryPlan(q, expected);
    }

    /**
     * Hash-join wins over sort-merge-join w/ both sides ordered in an order-by query.
     * This is because order-by can only be done on the client side after sort-merge-join
     * and order-by w/o limit on the client side is very expensive.
     */
    @Test
    public void testJoinStrategy7() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n" +
                "ON t1.ID = t2.ID\n" +
                "ORDER BY t1.COL1";
        String expected =
                "CLIENT PARALLEL 1001-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "    SERVER SORTED BY [T1.COL1]\n" +
                "CLIENT MERGE SORT\n" +
                "    PARALLEL INNER-JOIN TABLE 0\n" +
                "        CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable500 + "\n" +
                "    DYNAMIC SERVER FILTER BY T2.ID IN (T1.ID)";
        verifyQueryPlan(q, expected);
    }

    /**
     * Sort-merge-join w/ both sides ordered wins over hash-join in an order-by limit query.
     * This is because order-by can only be done on the client side after sort-merge-join
     * but order-by w/ limit on the client side is less expensive.
     */
    @Test
    public void testJoinStrategy8() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n" +
                "ON t1.ID = t2.ID\n" +
                "ORDER BY t1.COL1 LIMIT 5";
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
            ExplainPlan plan = conn.prepareStatement(q)
                .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
                .getExplainPlan();
            ExplainPlanAttributes explainPlanAttributes =
                plan.getPlanStepsAsAttributes();
            assertEquals("SORT-MERGE-JOIN (INNER)",
                explainPlanAttributes.getAbstractExplainPlan());
            assertEquals("PARALLEL 1-WAY",
                explainPlanAttributes.getIteratorTypeAndScanSize());
            assertEquals("FULL SCAN ",
                explainPlanAttributes.getExplainScanType());
            assertEquals(testTable500, explainPlanAttributes.getTableName());
            assertEquals("[T1.COL1]",
                explainPlanAttributes.getClientSortedBy());
            assertEquals(new Integer(5),
                explainPlanAttributes.getClientRowLimit());
            ExplainPlanAttributes rhsTable =
                explainPlanAttributes.getRhsJoinQueryExplainPlan();
            assertEquals("PARALLEL 1-WAY",
                rhsTable.getIteratorTypeAndScanSize());
            assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
            assertEquals(testTable1000, rhsTable.getTableName());
        }
    }

    /**
     * Multi-table join: sort-merge-join chosen since all join keys are PK.
     */
    @Test
    public void testJoinStrategy9() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable1000 + " t1 LEFT JOIN " + testTable500 + " t2\n" +
                "ON t1.ID = t2.ID AND t2.ID > 200\n" +
                "LEFT JOIN " + testTable990 + " t3\n" +
                "ON t1.ID = t3.ID AND t3.ID < 100";
        String expected =
                "SORT-MERGE-JOIN (LEFT) TABLES\n" +
                "    SORT-MERGE-JOIN (LEFT) TABLES\n" +
                "        CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "    AND\n" +
                "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]\n" +
                "AND\n" +
                "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
        verifyQueryPlan(q, expected);
    }

    /**
     * Multi-table join: a mix of join strategies chosen based on cost.
     */
    @Test
    public void testJoinStrategy10() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable1000 + " t1 JOIN " + testTable500 + " t2\n" +
                "ON t1.ID = t2.COL1 AND t2.ID > 200\n" +
                "JOIN " + testTable990 + " t3\n" +
                "ON t1.ID = t3.ID AND t3.ID < 100";
        String expected =
                "SORT-MERGE-JOIN (INNER) TABLES\n" +
                "    CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "        PARALLEL INNER-JOIN TABLE 0\n" +
                "            CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]\n" +
                "        DYNAMIC SERVER FILTER BY T1.ID IN (T2.COL1)\n" +
                "AND\n" +
                "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
        verifyQueryPlan(q, expected);
    }

    /**
     * Multi-table join: hash-join two tables in parallel since two RHS tables are both small
     * and can fit in memory at the same time.
     */
    @Test
    public void testJoinStrategy11() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable1000 + " t1 JOIN " + testTable500 + " t2\n" +
                "ON t1.COL2 = t2.COL1 AND t2.ID > 200\n" +
                "JOIN " + testTable990 + " t3\n" +
                "ON t1.COL1 = t3.COL2 AND t3.ID < 100";
        String expected =
                "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "    PARALLEL INNER-JOIN TABLE 0\n" +
                "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]\n" +
                "    PARALLEL INNER-JOIN TABLE 1\n" +
                "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
        verifyQueryPlan(q, expected);
    }

    /**
     * Multi-table join: similar to {@link this#testJoinStrategy11()}, but the two RHS
     * tables cannot fit in memory at the same time, and thus a mix of join strategies
     * is chosen based on cost.
     */
    @Test
    public void testJoinStrategy12() throws Exception {
        String q = "SELECT *\n" +
                "FROM " + testTable1000 + " t1 JOIN " + testTable990 + " t2\n" +
                "ON t1.COL2 = t2.COL1\n" +
                "JOIN " + testTable990 + " t3\n" +
                "ON t1.COL1 = t3.COL2";
        String expected =
                "SORT-MERGE-JOIN (INNER) TABLES\n" +
                "    CLIENT PARALLEL 1001-WAY FULL SCAN OVER " + testTable1000 + "\n" +
                "        SERVER SORTED BY [T1.COL1]\n" +
                "    CLIENT MERGE SORT\n" +
                "        PARALLEL INNER-JOIN TABLE 0\n" +
                "            CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable990 + "\n" +
                "AND\n" +
                "    CLIENT PARALLEL 991-WAY FULL SCAN OVER " + testTable990 + "\n" +
                "        SERVER SORTED BY [T3.COL2]\n" +
                "    CLIENT MERGE SORT";
        verifyQueryPlan(q, expected);
    }

    private static void verifyQueryPlan(String query, String expected) throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        ResultSet rs = conn.createStatement().executeQuery("explain " + query);
        String plan = QueryUtil.getExplainPlan(rs);
        assertTrue("Expected '" + expected + "' in the plan:\n" + plan + ".",
                plan.contains(expected));
    }

    private static String initTestTableValues(int rows) throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
            String tableName = generateUniqueName();
            conn.createStatement().execute("CREATE TABLE " + tableName + " (\n" +
                    "ID INTEGER NOT NULL PRIMARY KEY,\n" +
                    "COL1 INTEGER," +
                    "COL2 INTEGER)");
            PreparedStatement stmt = conn.prepareStatement(
                    "UPSERT INTO " + tableName + " VALUES(?, ?, ?)");
            for (int i = 0; i < rows; i++) {
                stmt.setInt(1, i + 1);
                stmt.setInt(2, rows - i);
                stmt.setInt(3, rows + i);
                stmt.execute();
            }
            conn.commit();
            conn.createStatement().execute("UPDATE STATISTICS " + tableName);
            return tableName;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>MySociety</title>

    <link href="{{ STATIC_URL }}/landing-page/css/bootstrap.css" rel="stylesheet">

    <link href="{{ STATIC_URL }}/landing-page/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>

    <link href="{{ STATIC_URL }}/landing-page/css/landing-page.css" rel="stylesheet">

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

                </button>
                MySociety

Login

Signup

|

About

Contact

Organise Your Society

Free tool to help you manage your
finances, minutes & society members.

 Login

 Sign up (free!)

Intuitive book keeping:

Keep your society's ledgers in one place.

 No more lost data from treasurer to treasurer.

3D Device Mockups

by PSDCovers

Turn your 2D designs into high quality, 3D product shots in seconds using free Photoshop actions by PSDCovers! Visit their website to download some of their awesome, free photoshop actions!

Google Web Fonts and

Font Awesome Icons

This template features the 'Lato' font, part of the Google Web Font library, as well as icons from Font Awesome.

Connect to Start Bootstrap:

 Twitter

 Github

 Linkedin

Home

⋅

About

⋅

Services

⋅

Contact

Copyright © Your Company 2013. All Rights Reserved


text:
package io.airlift.drift.javadoc;

import io.airlift.drift.annotations.ThriftEnum;
import io.airlift.drift.annotations.ThriftService;
import io.airlift.drift.annotations.ThriftStruct;
import org.junit.Test;

import static io.airlift.drift.javadoc.ThriftAnnotations.THRIFT_ENUM;
import static io.airlift.drift.javadoc.ThriftAnnotations.THRIFT_SERVICE;
import static io.airlift.drift.javadoc.ThriftAnnotations.THRIFT_STRUCT;
import static org.assertj.core.api.Assertions.assertThat;

public class TestThriftAnnotations
{
    @Test
    public void testNames()
    {
        assertThat(THRIFT_ENUM).isEqualTo(ThriftEnum.class.getName());
        assertThat(THRIFT_SERVICE).isEqualTo(ThriftService.class.getName());
        assertThat(THRIFT_STRUCT).isEqualTo(ThriftStruct.class.getName());
    }
}


text:
"""
Experimental features for machine translation.
These interfaces are prone to change.
"""

from nltk.translate.api import AlignedSent, Alignment, PhraseTable
from nltk.translate.ibm_model import IBMModel
from nltk.translate.ibm1 import IBMModel1
from nltk.translate.ibm2 import IBMModel2
from nltk.translate.ibm3 import IBMModel3
from nltk.translate.ibm4 import IBMModel4
from nltk.translate.ibm5 import IBMModel5
from nltk.translate.bleu_score import sentence_bleu as bleu
from nltk.translate.ribes_score import sentence_ribes as ribes
from nltk.translate.metrics import alignment_error_rate
from nltk.translate.stack_decoder import StackDecoder


text:
![Alt](https://raw.github.com/nthmain/hobbled-tone/master/images/hobbled-tone.png)
![Alt](https://raw.github.com/nthmain/hobbled-tone/master/images/newtonehome.png)
##Hobbled-Tone Project for NewToneHome

###Project Overview

I have a 60's vintage Newtone Intercom System. The main unit is where I am currently
focussed, a large box on the wall in the kitchen with plenty of room for a Raspberry Pi,
small display, and hardware interfaces to the existing vintage switches and knobs.

This project is someone of a one-off from many existing Raspberry Pi Smart Home / Home Automation
builds that currently exist. I intend to use the existing Newtone hardware switches instead of
relying only on an Android tablet connected to the Pi. The Pi will run a 7" display, but with no
input devices other than the hardware switches.

The transformer, tubes, and any unnecessary hardware will be removed from the Newtone case,
making way for the Pi and it's supporting hardware. An arduino of some sort is planned to be added
to monitor the garage door.

Currently this project is planned to be a local monitor and local control, with no internet connectivity.
I am not looking to have every aspect of my home accessable anywhere in the world quite yet.
Once the system is efficiently montoring the home systems and controlling what it needs, expansions may be made.

This repository contains the source code for the NewToneHome project,
which consists of scrips designed for the Raspberry Pi (running Arch Linux Arm),
an Android app for home monitoring, and instructions for installation.

###License
[MIT License](http://opensource.org/licenses/MIT)

### Goal of Project
The goal of this project is an installed Pi and display within the enclosure
and interfaced with the existing hardware. The software will be developed
iteratively, building on a function base that will hopefully be established soon.
This Rev. 0 development is aptly named, Hobble-Tone!

###Status of Project
This project is currently in very early development stages. Instructions
and source code will be heavily modified and added to as the project
evolves.

###Contributing
As stated earlier, it will be difficult to contribute until a more stable code base is reached.
Any contributions are greatly appreciated and welcomed.

Commonality
-----------
I do not wish to develop this as a one-off system that no one else can utilize. I plan on adapting the
software installation to be tailored to various units and hardware interfaces.

The goal is to have one single global system config file listing the devices on the monitoring network,
whether the devices are interfaced via Ethernet, Bluetooth, Zigbee, RS-485, etc.

Hardware
--------
The hardware schematics for the system will be developed along with the software. Below is a basic example of what
a typical Rev. 0 hardware layout is planned to look like.

                                                                       +-----------------------+
      +---------------+                               RS-232?          |                       |
      |               |                              +---------------> |   Arduino based       |
      |  Newtone      |         GPIO                 |                 |   Garage Door Monitor |
      |  Hardware     |+-------------+               |                 +-----------------------+
      |               |              v               +
      +---------------+           +------------------------------+
                                  |                              |
      +---------------+           |                              |
      |               |      GPIO |   Raspberry Pi               |
      | *New* Radio HW|<---------+|                              |
      |               |           |     Control/Monitor GPIO     |
      +---------------+           |                              |
                                  |                              |
                                  |                              |
                                  +------------------------------+
                                                ^
                                                +
                                                v
                                         +--------------+
        +--------------------+           | Home Network |
        | Android App        | <+-----+> +--------------+
        | Monitor/Log/Control|
        +--------------------+

Raspberry Pi Setup
------------------
I opted to install a Raspberry Pi build of Arch Linux ARM for this project.
Instructions will be added soon to get from a minimal Arch install to
what is needed for monitoring, providing a server, and a lightweight display.


text:
/** Script ACLs do not delete
 read=nobody
write=nobody
execute=authenticated
  **/

 var clientModule = require("./client.js");
var mappings = require("./mappings.js");
var config = require("./oauth2/config.js");
var common = require("./common.js");
var userModule = require("./user.js");
var util = require("./util.js");

/**
 * This class allows you to subscribe to any type of notification, as made available by carvoyant
 * It is used by the Vehicle class for vehicle-based notifications
 * @class NotificationManager
 * @constructor NotificationManager
 */
function NotificationManager(dto) {

  if (!dto || !dto.username) {

    throw {
      "errorCode": "Invalid_Parameter",
      "errorDetail": "NotificationManager - dto.username cannot be null or empty. You should specify the name of the user"
    };
  }

  this.username = dto.username;
  this.client = new clientModule.Client({"username": this.username});
}

/**
 * @method listSubscriptions
 * @param {Object} params
 *	{String} vehicleId // notifications on this vehicle (not compatible with accountId)
 *  {String} accountId // notifications on this account (not compatible with vehicleId)
 * @return {Array} list of notification objects
 */
NotificationManager.prototype.listSubscriptions = function(params) {

  if (!params) {

    throw {
      "errorCode": "Invalid_Parameter",
      "errorDetail": "NotificationManager.listSubscriptions : params cannot be null or empty"
    };
  }

  if (!params.vehicleId && !params.accountId) {

    throw {
      "errorCode": "Invalid_Parameter",
      "errorDetail": "NotificationManager.listSubscriptions : you need to provide a vehicleId or an accountId"
    };
  }

  var url = config.apiUrl;
  if (params.accountId) {
    url += "/account/" + params.accountId + "/eventSubscription/";
  }else {
    url += "/vehicle/" +  params.vehicleId + "/eventSubscription/";
  }

  var query = {

    url : url,
    method : "GET"
  };

  var result = this.client.callApi(query);
  var subscriptions = result.subscriptions;
  for (var i = 0; i < subscriptions.length; i++) {
    subscriptions[i]._timestamp = util.toReadableDateTime(subscriptions[i]._timestamp);
  }

  return {
    "subscriptions": subscriptions,
    "totalRecords": result.totalRecords
  };
};

/**
 * @method listSubscriptions
 * @param {Object} params
 *	{String} vehicleId // notifications on this vehicle (not compatible with accountId)
 *  {String} accountId // notifications on this account (not compatible with vehicleId)
 * 	{String} notificationType : the type of notification to subscribe to. Mandatory. Possible values
 *	are defined in "/carvoyant/mappings", "eventTypes".
 * @return {Array} list of notification objects
 */
NotificationManager.prototype.subscribeToNotification = function(params) {

  if (!params || !params.notificationType) {

    throw {
      "errorCode": "Invalid_Parameter",
      "errorDetail": "NotificationManager.subscribeToNotification : notificationType cannot be null or empty"
    };
  }

  var notificationType = mappings.eventTypes[params.notificationType];
  if (!notificationType) {

    throw {
      "errorCode": "Invalid_Parameter",
      "errorDetail": "Vehicle.subscribeToNotification : the provided value of notificationType does not match any supported type"
    };
  }

  if (notificationType.supportedPeriods.indexOf(params.notificationPeriod) == -1) {

     throw {
      "errorCode": "Invalid_Parameter",
      "errorDetail": "NotificationManager.subscribeToNotification : the provided value of notificationPeriod is not supported by the requested notification type"
    };
  }

  var user = new userModule.User({username:this.username});
  user.persistAccountIds();

  var url = config.apiUrl;
  if (params.accountId) {
    url += "/account/" + params.accountId;
  }else {
    url += "/vehicle/" +  params.vehicleId;
  }
  var request = {

    url :   url + "/eventSubscription/" + notificationType.path,
    method : "POST",
    headers: {
      "Content-Type": "application/json"
    }
  };

  var requestBody = {

    "minimumTime": params.minimumTime ? params.minimumTime : "0",
    "postUrl": common.notificationConfig.callback,
    //"notificationType": params.notificationType,
    "notificationPeriod": params.notificationPeriod,
    "postHeaders": {
        "Authorization": "Bearer " + common.notificationConfig.authToken
     }
  };

  var keys = Object.keys(params);
  for (var i = 0; i < keys.length; i++) {
  	if (["notificationType", "notificationPeriod", "vehicleId"].indexOf(keys[i]) == -1 ) {
      requestBody[keys[i]] = params[keys[i]];
    }
  }

  request.bodyString = JSON.stringify(requestBody);
  console.log(JSON.stringify(request))
  var result = this.client.callApi(request);
  return result.susbscription;
};

/**
 * @method listSubscriptions
 * @param {Object} params
 *	{String} subscriptionId : the identifier of the subscription to delete
 *	{String} vehicleId // notifications on this vehicle (not compatible with accountId)
 *  {String} accountId // notifications on this account (not compatible with vehicleId)
 * 	{String} notificationType : optional, the type of notification to subscribe to. Possible values
 *	are defined in "/carvoyant/mappings", "eventTypes".
 * @return {String} the result of the operationm usually "marked for deletion"
 */
NotificationManager.prototype.deleteSubscription = function(params) {

  if (!params || !params.subscriptionId) {

    throw {
      "errorCode": "Invalid_Parameter",
      "errorDetail": "NotificationManager.deleteNotification : params and params.subscriptionId cannot be null or empty"
    };
  }

  var url = config.apiUrl;
  if (params.accountId) {
    url += "/account/" + params.accountId;
  }else {
    url += "/vehicle/" +  params.vehicleId;
  }

  var notificationType = mappings.eventTypes[params.notificationType];
  url += "/eventSubscription/" + (notificationType ? notificationType.path : "") + params.subscriptionId;
  var request = {

    url : url,
    method : "DELETE"
  };

  var result = this.client.callApi(request);
  return result;
};


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.6-4-470
description: >
    ES5 Attributes - property ([[Get]] is undefined, [[Set]] is a
    Function, [[Enumerable]] is true, [[Configurable]] is false) is
    undeletable
includes: [propertyHelper.js]
---*/

var obj = {};

var verifySetFunc = "data";
var setFunc = function (value) {
    verifySetFunc = value;
};

Object.defineProperty(obj, "prop", {
    get: undefined,
    set: setFunc,
    enumerable: true,
    configurable: false
});

assert(obj.hasOwnProperty("prop"));

var desc = Object.getOwnPropertyDescriptor(obj, "prop");

verifyNotWritable(obj, "prop");
verifyNotConfigurable(obj, "prop");

assert.sameValue(desc.configurable, false);

assert(obj.hasOwnProperty("prop"));


text:
function staticClickHandlerAddHandlers() {
  console.log("staticClickHandlerAddHandlers");
}


text:
import { TextNode, TEXT } from 'substance'
import { ANNOS_AND_INLINE_NODES } from './TestArticleConstants'

const MIN_LEVEL = 1
const MAX_LEVEL = 3

export default class Heading extends TextNode {
  get canIndent () { return true }

  indent () {
    let level = this.level
    if (level < MAX_LEVEL) {
      this.level = this.level + 1
    }
  }

  get canDedent () { return true }

  dedent () {
    let level = this.level
    if (level > MIN_LEVEL) {
      this.level = this.level - 1
    }
  }

  static get MIN_LEVEL () { return MIN_LEVEL }

  static get MAX_LEVEL () { return MAX_LEVEL }

  define () {
    return {
      type: 'heading',
      level: { type: 'number', default: 1 },
      content: TEXT(ANNOS_AND_INLINE_NODES)
    }
  }
}


text:
package edu.crest.dlt.utils;

import java.util.HashMap;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import edu.crest.dlt.ui.utils.img.Icons;

public class Status
{
	public enum ui_status {
		depot_connected, depot_not_connected, download_ready, upload_ready, metadata_error, mappings_inaccessible, not_enough_depots, file_not_found, download_failed, upload_failed, transfer_failed, transfer_sucess, transfer_aborting, transfer_aborted, processing, downloading, uploading, file_registering
	}

	private static Map<ui_status, String> status_text = new HashMap<ui_status, String>()
	{
		{
			put(ui_status.depot_connected, "");
			put(ui_status.depot_not_connected, "Connection to depot failed. Try to refresh.");

			put(ui_status.download_ready, "Ready to download file.");
			put(ui_status.upload_ready, "Ready to upload file.");
			put(ui_status.metadata_error, "Failed to parse file metadata.");
			put(ui_status.mappings_inaccessible,
					"One or more mapping(s) of the file not currently accessible.");
			put(ui_status.not_enough_depots,
					"Not enough depot(s) accessible for hosting required copies of file.");
			put(ui_status.file_not_found, "Invalid file path or failed to read file.");

			put(ui_status.download_failed, "Failed to download file.");
			put(ui_status.upload_failed, "Failed to publish file.");

			put(ui_status.transfer_failed, "Failed to transfer file.");
			put(ui_status.transfer_aborting, "File transfer aborted/cancelled.");
			put(ui_status.transfer_aborted, "File transfer aborted/cancelled.");
			put(ui_status.transfer_sucess, "File transfer successful.");

			put(ui_status.processing, "Processing. Please wait.");
			put(ui_status.downloading, "File download in progress.");
			put(ui_status.uploading, "File upload in progress.");
			put(ui_status.file_registering, "Registering file metadata.");
		}
	};

	private static Map<ui_status, Icon> status_icon = new HashMap<ui_status, Icon>()
	{
		{
			put(ui_status.depot_connected, Icons.icon_depot_connected);
			put(ui_status.depot_not_connected, Icons.icon_depot_not_connected);

			put(ui_status.download_ready, Icons.icon_ready);
			put(ui_status.upload_ready, Icons.icon_ready);
			put(ui_status.metadata_error, Icons.icon_failure);
			put(ui_status.mappings_inaccessible, Icons.icon_depot_not_connected);
			put(ui_status.not_enough_depots, Icons.icon_depot_not_connected);
			put(ui_status.file_not_found, Icons.icon_failure);

			put(ui_status.download_failed, Icons.icon_failure);
			put(ui_status.upload_failed, Icons.icon_depot_not_connected);

			put(ui_status.transfer_failed, Icons.icon_failure);
			put(ui_status.transfer_aborting, Icons.icon_processing);
			put(ui_status.transfer_aborted, Icons.icon_failure);
			put(ui_status.transfer_sucess, Icons.icon_success);

			put(ui_status.processing, Icons.icon_processing);
			put(ui_status.downloading, Icons.icon_file_download);
			put(ui_status.uploading, Icons.icon_file_upload);
			put(ui_status.file_registering, Icons.icon_file_write);
		}
	};

	public static String message(ui_status status)
	{
		return status_text.containsKey(status) ? status_text.get(status) : "";
	}

	public static Icon icon(ui_status status)
	{
		return status_text.containsKey(status) ? status_icon.get(status) : new ImageIcon();
	}
}


text:
import os
from celery import task
from github.models import Repo
import github.gh as gh
from rss_gen import Atom

BASE_DIR = os.path.dirname(__file__)

@task()
def rss_gen():
    t = Repo.objects.all()
    S = gh.Auth().get_session()
    for col in t:
        owner = col.owner
        repo = col.repo
        print("owner: %s, repo: %s" % (owner, repo))
        gh_repo = gh.Repo()
        repo_info = gh_repo.get_repo_info(S, owner, repo)
        commits_info = gh_repo.get_commits_info(S, owner, repo)
        # make RSS output dirs recursively
        rss_root = os.path.join(BASE_DIR, 'output')
        owner_path = os.path.join(rss_root, owner)
        repo_path = os.path.join(owner_path, repo)
        mkdir_p(repo_path)
        # generate Atom
        atom_fn = os.path.join(repo_path, 'diff.xml')
        atom = Atom()
        atom.gen_atom(repo_info, commits_info, atom_fn)

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError:
        if not os.path.isdir(path):
            raise


text:
<?php
namespace app\modules\core\components\behaviors;

use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;

class FileUploadBehavior extends Behavior
{
    public $attributeName = 'file';

    public $path = 'files';

    public $minSize = 0;

    public $maxSize = 5368709120; /* 5 Mb */

    public $types = 'jpg, jpeg, gif, png';

    public $file;

    public $filename;

    /**
     * @return array
     */
    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
            ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
        ];
    }

    /**
     * Before validate
     */
    public function beforeValidate()
    {
        $model = $this->owner;

        if ($model->{$this->attributeName} instanceof UploadedFile) {
            $this->file = $model->{$this->attributeName};
            $this->filename = $this->file->name;
            $model->{$this->attributeName} = $this->filename;
        }
        elseif ($this->file = UploadedFile::getInstance($model, $this->attributeName)) {
            $this->filename = $this->file->name;
        }
    }

    /**
     * Before insert
     */
    public function beforeInsert()
    {
        $this->saveFile();
    }

    /**
     * Before update
     */
    public function beforeUpdate()
    {
        /* If not change then set old attribute filename */
        $model = $this->owner;
        $model->{$this->attributeName} = $model->getOldAttribute($this->attributeName);

        if ($this->file !== null) {
            $this->saveFile();
        }
    }

    /**
     * Before delete
     */
    public function beforeDelete()
    {
        $this->deleteFile();
    }

    /**
     * Save file to disk
     */
    protected function saveFile()
    {
        $model = $this->owner;
        $file = $this->file;

        if (!$file instanceof UploadedFile) {
            return;
        }

        /* Delete old file */
        $this->deleteFile();

        /* Check and create target directory */
        if (!is_dir($this->uploadPath)) {
            mkdir($this->uploadPath, 0755, true);
        }

        /* Save current file or generate new name as filename_1,2,3..n */
        $this->filename = $this->generateFilename();
        $file->saveAs($this->getFilePath($this->filename));

        /* Set new filename to model->attribute */
        $model->{$this->attributeName} = $this->filename;
    }

    /**
     * Delete file
     */
    protected function deleteFile()
    {
        $model = $this->owner;

        if (!$old_filename = $model->getOldAttribute($this->attributeName)) {
            return;
        }

        if (@is_file($this->getFilePath($old_filename))) {
            @unlink($this->getFilePath($old_filename));
        }
    }

    /**
     * @return string
     */
    protected function generateFilename()
    {
        $i = 1;
        $filename = $this->filename;
        while(file_exists($this->getFilePath($filename)) || is_dir($this->getFilePath($filename)))
        {
            $filename = $this->file->baseName . '_' . $i++ . '.' . $this->file->extension;
        }

        return $filename;
    }

    /**
     * @return string
     */
    protected function getBasePath()
    {
        $module = Yii::$app->getModule('core');
        return Yii::getAlias('@webroot' . D_S . $module->uploadPath);
    }

    /**
     * @return string
     */
    protected function getUploadPath()
    {
        return $this->getBasePath() . D_S . $this->path;
    }

    /**
     * @return string
     */
    public function getFilePath($filename = null)
    {
        $filename = ($filename === null) ? $this->owner->{$this->attributeName} : $filename;

        return $this->getUploadPath() . D_S . $filename;
    }

    /**
     * @return string
     */
    protected function getUploadUrl()
    {
        $module = Yii::$app->getModule('core');
        return Yii::$app->request->baseUrl . '/' . $module->uploadPath . '/' . $this->path;
    }

    /**
     * @return string
     */
    public function getFileUrl()
    {
        return $this->getUploadUrl() . '/' . $this->owner->{$this->attributeName};
    }
}


text:
package org.kie.workbench.common.dmn.client.editors.expressions.types.function.parameters;

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

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import com.google.gwt.user.client.Event;
import org.jboss.errai.common.client.dom.DOMUtil;
import org.jboss.errai.common.client.dom.Div;
import org.jboss.errai.ioc.client.api.ManagedInstance;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.SinkNative;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.kie.workbench.common.dmn.api.definition.v1_1.InformationItem;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.popover.AbstractPopoverViewImpl;
import org.uberfire.client.views.pfly.widgets.JQueryProducer;
import org.uberfire.client.views.pfly.widgets.Popover;

@Templated
@ApplicationScoped
public class ParametersPopoverViewImpl extends AbstractPopoverViewImpl implements ParametersPopoverView {

    @DataField("parametersContainer")
    private Div parametersContainer;

    @DataField("addParameter")
    private Div addParameter;

    private ManagedInstance<ParameterView> parameterViews;
    private final List<ParameterView> parameterViewInstances = new ArrayList<>();

    private Presenter presenter;

    public ParametersPopoverViewImpl() {
        //CDI proxy
    }

    @Inject
    public ParametersPopoverViewImpl(final Div parametersContainer,
                                     final Div addParameter,
                                     final ManagedInstance<ParameterView> parameterViews,
                                     final Div popoverElement,
                                     final Div popoverContentElement,
                                     final JQueryProducer.JQuery<Popover> jQueryPopover) {
        super(popoverElement,
              popoverContentElement,
              jQueryPopover);

        this.parametersContainer = parametersContainer;
        this.addParameter = addParameter;
        this.parameterViews = parameterViews;
    }

    @Override
    public void init(final Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void setParameters(final List<InformationItem> parameters) {
        parameterViewInstances.clear();
        parameterViewInstances.addAll(parameters
                                              .stream()
                                              .map(this::makeParameterView)
                                              .collect(Collectors.toList()));

        DOMUtil.removeAllChildren(parametersContainer);
        parameterViewInstances.forEach(parameterView -> parametersContainer.appendChild(parameterView.getElement()));
    }

    private ParameterView makeParameterView(final InformationItem parameter) {
        final ParameterView parameterView = parameterViews.get();
        parameterView.setName(parameter.getName().getValue());
        parameterView.setTypeRef(parameter);
        parameterView.addRemoveClickHandler(() -> presenter.removeParameter(parameter));
        parameterView.addParameterNameChangeHandler((name) -> presenter.updateParameterName(parameter, name));
        parameterView.addParameterTypeRefChangeHandler((typeRef) -> presenter.updateParameterTypeRef(parameter, typeRef));
        return parameterView;
    }

    @Override
    public void focusParameter(final int index) {
        if (index < 0 || index >= parameterViewInstances.size()) {
            return;
        }
        parameterViewInstances.get(index).focus();
    }

    @EventHandler("addParameter")
    @SinkNative(Event.ONCLICK)
    @SuppressWarnings("unused")
    public void onClickAddParameter(final Event event) {
        presenter.addParameter();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace yycms.admin.Models
{
   public class WechatModel
    {
        public String[] IDs { get; set; }

        public String Message { get; set; }

        public String Type { get; set; }

        public String MaterialID { get; set; }

        public article[] News { get; set; }
    }

    public class article
    {
        public String title { get; set; }
        public String description { get; set; }
        public String url { get; set; }
        public String picurl { get; set; }
    }
}


text:
import React from 'react';
import { stringify, validate } from 'rebem-classname';

let buildClassName = stringify;

// validation
// istanbul ignore next
if (process.env.NODE_ENV !== 'production') {
    buildClassName = props => stringify(validate(props));
}

function BEM(props, ...children) {
    const { tag, block, elem, mods, mix, className, ...restProps } = props;
    const finalClassName = buildClassName({ block, elem, mods, mix, className });
    const finalProps = finalClassName ? { ...restProps, className: finalClassName } : restProps;

    return React.createElement(tag || 'div', finalProps, ...children);
}

function blockFactory(block) {
    return function (props, ...children) {
        return BEM({ ...props, block }, ...children);
    };
}

export { BEM, blockFactory };


text:
`Generates json files that contains lottery results.
The code obviously uses go language so you'll need go packages to compile.`

## RUN!
```shell
./lotto-scraper-ph
```

...and check your results directory for the results.

## Credits
- [mxaddict/lotto-scrapper-ph-cpp](https://github.com/mxaddict/lotto-scrapper-ph-cpp) `for the CPP version remake`
- [mxaddict/lotto-scrapper-ph-nodejs](https://github.com/mxaddict/lotto-scraper-ph-nodejs) `for the NodeJS version remake`
- [rroble/pcso](https://github.com/rroble/pcso) `for the PHP version remake`
- [beanmoss/lotto-scraper-ph-perl](https://github.com/beanmoss/lotto-scraper-ph-perl) `for the PERL version remake`


text:
package net.glowstone.entity.projectile;

import lombok.Getter;
import lombok.Setter;
import net.glowstone.EventFactory;
import net.glowstone.entity.EntityNetworkUtil;
import net.glowstone.util.EntityUtils;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.SplashPotion;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionEffect;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class GlowSplashPotion extends GlowProjectile implements SplashPotion {
    private static final double MAX_VERTICAL_DISTANCE = 2.125;
    private static final double MAX_DISTANCE = 4.0;
    private static final double MAX_DISTANCE_SQUARED = MAX_DISTANCE * MAX_DISTANCE;
    @Getter
    @Setter
    private ItemStack item;

    public GlowSplashPotion(Location location) {
        super(location);
    }

    @Override
    public void collide(Block block) {
        applyEffects();
    }

    @Override
    public void collide(LivingEntity entity) {
        applyEffects();
    }

    private void applyEffects() {
        Collection<PotionEffect> effects = getEffects();
        if (effects.isEmpty()) {
            return;
        }
        double y = location.getY();
        Map<LivingEntity, Double> affectedIntensities = new HashMap<>();
        world.getNearbyEntities(location, MAX_DISTANCE, MAX_VERTICAL_DISTANCE, MAX_DISTANCE)
            .stream()
            .filter(LivingEntity.class::isInstance)
            .forEach(entity -> {
                Location entityLoc = entity.getLocation();
                double distFractionSquared = entityLoc.distanceSquared(location)
                    / MAX_DISTANCE_SQUARED;
                if (distFractionSquared < 1) {
                    // intensity is 1 - (distance / max distance)
                    affectedIntensities.put((LivingEntity) entity,
                        1 - Math.sqrt(distFractionSquared));
                }
            });
        PotionSplashEvent event = EventFactory.getInstance().callEvent(
            new PotionSplashEvent(this, affectedIntensities));
        if (!event.isCancelled()) {
            for (LivingEntity splashed : event.getAffectedEntities()) {
                for (PotionEffect effect : effects) {
                    double intensity = event.getIntensity(splashed);
                    EntityUtils.applyPotionEffectWithIntensity(
                        effect, splashed, intensity, intensity);
                }
            }
        }
        remove();
    }

    @Override
    protected int getObjectId() {
        return EntityNetworkUtil.getObjectId(EntityType.SPLASH_POTION);
    }

    @Override
    public Collection<PotionEffect> getEffects() {
        if (item == null) {
            return Collections.emptyList();
        }
        ItemMeta meta = item.getItemMeta();
        return meta instanceof PotionMeta ? ((PotionMeta) meta).getCustomEffects()
            : Collections.emptyList();
    }
}


text:
[![GoDoc](https://godoc.org/github.com/messagedb/messagedb?status.svg)](http://godoc.org/github.com/messagedb/messagedb/client)

## Description

A Go client library written and maintained by the **MessageDB** team.
This package provides convenience functions to read and write time series data.
It uses the HTTP protocol to communicate with your **MessageDB** cluster.

## Getting Started

### Connecting To Your Database

Connecting to an **MessageDB** database is straightforward. You will need a host
name, a port and the cluster user credentials if applicable. The default port is 8086.
You can customize these settings to your specific installation via the
**MessageDB** configuration file.

Thought not necessary for experimentation, you may want to create a new user
and authenticate the connection to your database.

For more information please check out the
[Cluster Admin Docs](http://messagedb.com/docs/v0.9/query_language/database_administration.html).

For the impatient, you can create a new admin user _bubba_ by firing off the
[MessageDB CLI](https://github.com/messagedb/messagedb/blob/master/cmd/messagedb/main.go).

```shell
messagedb
> create user bubba with password 'bumblebeetuna'
> grant all privileges to bubba
```

And now for good measure set the credentials in you shell environment.
In the example below we will use $MESSAGEDB_USER and $MESSAGEDB_PWD

Now with the administrivia out of the way, let's connect to our database.

NOTE: If you've opted out of creating a user, you can omit Username and Password in
the configuration below.

```go
package main

import "github.com/messagedb/messagedb/client"

const (
	MyHost        = "localhost"
	MyPort        = 8086
	MyDB          = "square_holes"
	MyMeasurement = "shapes"
)

func main() {
	u, err := url.Parse(fmt.Sprintf("http://%s:%d", MyHost, MyPort))
	if err != nil {
		log.Fatal(err)
	}

	conf := client.Config{
		URL:      *u,
		Username: os.Getenv("MESSAGEDB_USER"),
		Password: os.Getenv("MESSAGEDB_PWD"),
	}

	con, err := client.NewClient(conf)
	if err != nil {
		log.Fatal(err)
	}

	dur, ver, err := con.Ping()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Happy as a Hippo! %v, %s", dur, ver)
}

```

### Inserting Data

Time series data aka *points* are written to the database using batch inserts.
The mechanism is to create one or more points and then create a batch aka *batch points*
and write these to a given database and series. A series is a combination of a
measurement (time/values) and a set of tags.

In this sample we will create a batch of a 1,000 points. Each point has a time and
a single value as well as 2 tags indicating a shape and color. We write these points
to a database called _square_holes_ using a measurement named _shapes_.

NOTE: You can specify a RetentionPolicy as part of the batch points. If not
provided MessageDB will use the database _default_ retention policy. By default, the _default_
retention policy never deletes any data it contains.

```go
func writePoints(con *client.Client) {
	var (
		shapes     = []string{"circle", "rectangle", "square", "triangle"}
		colors     = []string{"red", "blue", "green"}
		sampleSize = 1000
		pts        = make([]client.Point, sampleSize)
	)

	rand.Seed(42)
	for i := 0; i < sampleSize; i++ {
		pts[i] = client.Point{
			Measurement: "shapes",
			Tags: map[string]string{
				"color": strconv.Itoa(rand.Intn(len(colors))),
				"shape": strconv.Itoa(rand.Intn(len(shapes))),
			},
			Fields: map[string]interface{}{
				"value": rand.Intn(sampleSize),
			},
			Time: time.Now(),
			Precision: "s",
		}
	}

	bps := client.BatchPoints{
		Points:          pts,
		Database:        MyDB,
		RetentionPolicy: "default",
	}
	_, err := con.Write(bps)
	if err != nil {
		log.Fatal(err)
	}
}
```

### Querying Data

One nice advantage of using **MessageDB** the ability to query your data using familiar
SQL constructs. In this example we can create a convenience function to query the database
as follows:

```go
// queryDB convenience function to query the database
func queryDB(con *client.Client, cmd string) (res []client.Result, err error) {
	q := client.Query{
		Command:  cmd,
		Database: MyDB,
	}
	if response, err := con.Query(q); err == nil {
		if response.Error() != nil {
			return res, response.Error()
		}
		res = response.Results
	}
	return
}
```

#### Creating a Database
```go
_, err := queryDB(con, fmt.Sprintf("create database %s", MyDB))
if err != nil {
	log.Fatal(err)
}
```

#### Count Records
```go
q := fmt.Sprintf("select count(%s) from %s", "value", MyMeasurement)
res, err := queryDB(con, q)
if err != nil {
	log.Fatal(err)
}
count := res[0].Series[0].Values[0][1]
log.Printf("Found a total of `%v records", count)

```

#### Find the last 10 _shapes_ records

```go
q := fmt.Sprintf("select * from %s limit %d", MyMeasurement, 20)
res, err = queryDB(con, q)
if err != nil {
	log.Fatal(err)
}

for i, row := range res[0].Series[0].Values {
	t, err := time.Parse(time.RFC3339, row[0].(string))
	if err != nil {
		log.Fatal(err)
	}
	val, err := row[1].(json.Number).Int64()
	log.Printf("[%2d] %s: %03d\n", i, t.Format(time.Stamp), val)
}
```

## Go Docs

Please refer to
[http://godoc.org/github.com/messagedb/messagedb/client](http://godoc.org/github.com/messagedb/messagedb/client)
for documentation.

## See Also

You can also examine how the client library is used by the
[MessageDB CLI](https://github.com/messagedb/messagedb/blob/master/cmd/messagedb/main.go).


text:
package com.google.gdata.data.projecthosting;

import com.google.gdata.data.BaseEntry;
import com.google.gdata.data.ExtensionProfile;
import com.google.gdata.data.Link;

/**
 * Describes an issue comments entry.
 *
 *
 */
public class IssueCommentsEntry extends BaseEntry<IssueCommentsEntry> {

  /**
   * Default mutable constructor.
   */
  public IssueCommentsEntry() {
    super();
  }

  /**
   * Constructs a new instance by doing a shallow copy of data from an existing
   * {@link BaseEntry} instance.
   *
   * @param sourceEntry source entry
   */
  public IssueCommentsEntry(BaseEntry<?> sourceEntry) {
    super(sourceEntry);
  }

  @Override
  public void declareExtensions(ExtensionProfile extProfile) {
    if (extProfile.isDeclared(IssueCommentsEntry.class)) {
      return;
    }
    super.declareExtensions(extProfile);
    extProfile.declare(IssueCommentsEntry.class,
        IssuesLink.getDefaultDescription(false, true));
    extProfile.declare(IssueCommentsEntry.class, SendEmail.class);
    extProfile.declare(IssueCommentsEntry.class, Updates.class);
    new Updates().declareExtensions(extProfile);
  }

  /**
   * Returns the send email.
   *
   * @return send email
   */
  public SendEmail getSendEmail() {
    return getExtension(SendEmail.class);
  }

  /**
   * Sets the send email.
   *
   * @param sendEmail send email or null to reset
   */
  public void setSendEmail(SendEmail sendEmail) {
    if (sendEmail == null) {
      removeExtension(SendEmail.class);
    } else {
      setExtension(sendEmail);
    }
  }

  /**
   * Returns whether it has the send email.
   *
   * @return whether it has the send email
   */
  public boolean hasSendEmail() {
    return hasExtension(SendEmail.class);
  }

  /**
   * Returns the updates list.
   *
   * @return updates list
   */
  public Updates getUpdates() {
    return getExtension(Updates.class);
  }

  /**
   * Sets the updates list.
   *
   * @param updates updates list or null to reset
   */
  public void setUpdates(Updates updates) {
    if (updates == null) {
      removeExtension(Updates.class);
    } else {
      setExtension(updates);
    }
  }

  /**
   * Returns whether it has the updates list.
   *
   * @return whether it has the updates list
   */
  public boolean hasUpdates() {
    return hasExtension(Updates.class);
  }

  /**
   * Returns the replies Project Hosting Issue Tracker Link class.
   *
   * @return Replies Project Hosting Issue Tracker Link class or {@code null}
   *     for none.
   */
  public Link getAtomRepliesLink() {
    return getLink(IssuesLink.Rel.REPLIES, Link.Type.ATOM);
  }

  @Override
  protected void validate() {
  }

  @Override
  public String toString() {
    return "{IssueCommentsEntry " + super.toString() + "}";
  }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sbe:messageSchema xmlns:sbe="http://fixprotocol.io/2016/sbe"
                   package="composite"
                   id="1"
                   version="0"
                   semanticVersion="5.2"
                   description="Example Simple4"
                   byteOrder="littleEndian">
  <types>
    <composite name="messageHeader" description="Message identifiers and length of message root">
      <type name="blockLength" primitiveType="uint16"/>
      <type name="templateId" primitiveType="uint16"/>
      <type name="schemaId" primitiveType="uint16"/>
      <type name="version" primitiveType="uint16"/>
    </composite>
  </types>

  <types>

    <enum name="booleanEnum" encodingType="uint8" semanticType="Boolean">
      <validValue name="F">0</validValue>
      <validValue name="T">1</validValue>
    </enum>

    <composite name="point">
      <type name="name" primitiveType="char" length="5" />
      <type name="d" primitiveType="double" />
      <type name="i" primitiveType="int32" />
      <type name="u" primitiveType="uint8" length="2" />
      <ref name="truthval1" type="booleanEnum"/>
      <ref name="truthval2" type="booleanEnum"/>
    </composite>

  </types>

  <sbe:message name="Composite" id="1" description="A very simple composite example">
    <field name="start" id="2" type="point" />
    <field name="end" id="3" type="point" />
  </sbe:message>
</sbe:messageSchema>


text:
namespace math
{

class Line
{
public:
	math::Vector3f o;
	math::Vector3f d;

	Line();
	Line(const math::Vector3f& o, const math::Vector3f& d);

	math::Vector3f operator*(float q) const;
};

} // namespace math


text:
const $ = require('trip.dom').$;

const body =
  `<div id="graphs">
  </div>`;
$('body').html(body);

const DashboardController = require('./mvc/controllers/DashboardController');
new DashboardController();


text:
  <input ng-switch-when="String" class="form-control" type="text"
         ng-model="user.plainAttrs[schema.key].values[index]"
         ng-required="{{schema.mandatoryCondition}}" validate="true"
         ng-disabled="schema.readonly" ng-init="initAttribute(schema, index)" name="{{schema.key}}"/>

      <button type="button" class="btn btn-default btn-flat"
              confirm="{{'CONFIRM_REMOVE'| translate}}"
              onclick="var pwd = $(this).parent().next('input');
                  if (pwd.is('[readonly]')) {
                    if (pwd.val() === '') {
                      pwd.removeAttr('readonly');
                      $(this).children().attr('class', 'fa fa-unlock');
                    } else {
                      var response = confirm($(this).attr('confirm'));
                      if (response == true) {
                        pwd.removeAttr('readonly');
                        pwd.val('');
                        $(this).children().attr('class', 'fa fa-unlock');
                      }
                    }
                  }
              ">

      </button>

    <input class="form-control" type="password" readonly="true"
           ng-model="user.plainAttrs[schema.key].values[index]"
           ng-required="{{schema.mandatoryCondition}}" validate="true"
           ng-disabled="schema.readonly" ng-init="initAttribute(schema, index)" name="{{schema.key}}"/>

      <button type="button" class="btn btn-default btn-flat"
              onmousedown="var pwd = $(this).parent().prev('input');
                  if (!pwd.is('[readonly]')) {
                    pwd.attr('type', 'text');
                    $(this).children().attr('class', 'fa fa-eye-slash');
                  }"
              onmouseup="var pwd = $(this).parent().prev('input');
                  if (!pwd.is('[readonly]')) {
                    pwd.attr('type', 'password');
                    $(this).children().attr('class', 'fa fa-eye');
                  }"
              >

      </button>

    <input type="checkbox" ng-model="user.plainAttrs[schema.key].values[index]" ng-required="{{schema.mandatoryCondition}}"
           ng-init="initAttribute(schema, index)" />

  <input ng-switch-when="Long" class="form-control" type="number" ng-model="user.plainAttrs[schema.key].values[index]"
         ng-required="{{schema.mandatoryCondition}}" validate="true"
         ng-init="initAttribute(schema, index)" name="{{schema.key}}"/>

  <input ng-switch-when="Double" class="form-control" type="number" ng-model="user.plainAttrs[schema.key].values[index]"
         ng-required="{{schema.mandatoryCondition}}" validate="true"
         ng-init="initAttribute(schema, index)" name="{{schema.key}}"/>

      <input type="text" class="form-control"
             uib-datepicker-popup
             ng-model="selectedDate"
             ng-change="bindDateToModel(selectedDate, selectedTime)"
             min-date="minDate" max-date="maxDate"
             is-open="status.opened" datepicker-options="dateOptions"
             ng-required="{{schema.mandatoryCondition}}" close-text="Close"
             ng-init="initAttribute(schema, index)"/>
      <button type="button" class="btn btn-default" ng-click="open($event)" >

      </button>

     -1 ||
                schema.conversionPattern.indexOf('h') > -1)">
      <uib-timepicker ng-model="selectedTime"
                      ng-change="bindDateToModel(selectedDate, selectedTime)"
                      hour-step="hstep" minute-step="mstep" show-meridian="ismeridian">
      </uib-timepicker>

    <select class="form-control"
            ng-model="user.plainAttrs[schema.key].values[index]"
            ng-required="{{schema.mandatoryCondition}}">
      <option ng-repeat="value in enumerationValues" value="{{value}}">
        {{schema.enumerationKeys[$index]|| value}}
      </option>
    </select>

    <input file-input type="file" id="fileInput" name="fileInput"/>
    <button type="button" title="Download file" class="fileButton btn btn-default btn-sm" ng-click="download()">

    </button>

  <input ng-switch-default class="form-control" type="text"
         ng-model="user.plainAttrs[schema.key].values[index]"
         ng-required="{{schema.mandatoryCondition}}"
         ng-disabled="schema.readonly" ng-init="initAttribute(schema, index)"/>


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>web2py.gluon.http</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

web2py Web Framework

        Package web2py ::
        Package gluon ::
        Module http

[hide private]

[frames] | no frames]

Module http
source code

This file is part of the web2py Web Framework Copyrighted by Massimo
  Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3
  (http://www.gnu.org/licenses/lgpl.html)

        Classes
        [hide private]

        BaseException

      Common base class for all non-exit exceptions.

        HTTP

        Functions
        [hide private]

          redirect(location,
        how=303)

            source code

        Variables
        [hide private]

        defined_status = {200: 'OK', 201: 'CREATED', 202: 'ACCEPTED', ...

        Variables Details
        [hide private]

defined_status

Value:

{200: 'OK',
 201: 'CREATED',
 202: 'ACCEPTED',
 203: 'NON-AUTHORITATIVE INFORMATION',
 204: 'NO CONTENT',
 205: 'RESET CONTENT',
 206: 'PARTIAL CONTENT',
 301: 'MOVED PERMANENTLY',
...

         Home

         Trees

         Indices

         Help

web2py Web Framework

    Generated by Epydoc 3.0beta1 on Mon Apr 25 15:04:05 2011

      http://epydoc.sourceforge.net


text:
from MDAnalysis import *
import numpy.linalg

u = Universe("sampled.pos.pdb")
calphas = u.selectAtoms('name CA')
bg = calphas.selectAtoms('segid A and resid 3:77 or segid B and resid 1:90')

g = open('rgyr_bg','w')

for ts in u.trajectory:

	rgyr_bg = bg.radiusOfGyration()

	g.write('%f\n' % (rgyr_bg,))

g.close()


text:
package org.apereo.cas.logout;

import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.services.RegisteredService;

import java.net.URL;
import java.util.Collection;

/**
 * This is {@link SingleLogoutServiceLogoutUrlBuilder}, which determines
 * which given endpoint of a registered service must receive logout messages.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@FunctionalInterface
public interface SingleLogoutServiceLogoutUrlBuilder {

    /**
     * Determine logout url.
     *
     * @param registeredService   the registered service
     * @param singleLogoutService the single logout service
     * @return the URL
     */
    Collection<URL> determineLogoutUrl(RegisteredService registeredService, WebApplicationService singleLogoutService);
}