text:
// Autogenerated by convert_tests.py and process_polyglot.py.
// Do not edit this file directly.
// The template for this file is located at:
// ../../../../../../../templates/Test.java
package com.rethinkdb.gen;

import com.rethinkdb.RethinkDB;
import com.rethinkdb.gen.exc.*;
import com.rethinkdb.gen.ast.*;
import com.rethinkdb.ast.ReqlAst;
import com.rethinkdb.model.MapObject;
import com.rethinkdb.model.OptArgs;
import com.rethinkdb.net.Connection;
import com.rethinkdb.net.Cursor;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.junit.*;
import org.junit.rules.ExpectedException;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.Instant;
import java.util.stream.LongStream;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import java.util.Collections;
import java.nio.charset.StandardCharsets;

import static com.rethinkdb.TestingCommon.*;
import com.rethinkdb.TestingFramework;

public class DatumTypeof {
    // These tests test the type of command
    Logger logger = LoggerFactory.getLogger(DatumTypeof.class);
    public static final RethinkDB r = RethinkDB.r;

    Connection conn;

    @Before
    public void setUp() throws Exception {
        logger.info("Setting up.");
        conn = TestingFramework.createConnection();
        try {
            r.dbCreate("test").run(conn);
            r.db("test").wait_().run(conn);
        }catch (Exception e){}
    }

    @After
    public void tearDown() throws Exception {
        logger.info("Tearing down.");
        r.db("rethinkdb").table("_debug_scratch").delete().run(conn);
        if(!conn.isOpen()){
            conn.close();
            conn = TestingFramework.createConnection();
        }
        r.dbDrop("test").run(conn);
        conn.close(false);
    }

    // Autogenerated tests below

    @Test(timeout=120000)
    public void test() throws Exception {

        {
            // datum/typeof.yaml line #5
            /* 'NULL' */
            String expected_ = "NULL";
            /* r.expr(null).type_of() */
            logger.info("About to run line #5: r.expr((ReqlExpr) null).typeOf()");
            Object obtained = runOrCatch(r.expr((ReqlExpr) null).typeOf(),
                                          new OptArgs()
                                          ,conn);
            try {
                assertEquals(expected_, obtained);
            logger.info("Finished running line #5");
            } catch (Throwable ae) {
                logger.error("Whoops, got exception on line #5:" + ae.toString());
                if(obtained instanceof Throwable) {
                    ae.addSuppressed((Throwable) obtained);
                }
                throw ae;
            }
        }

        {
            // datum/typeof.yaml line #9
            /* 'NULL' */
            String expected_ = "NULL";
            /* r.type_of(null) */
            logger.info("About to run line #9: r.typeOf((ReqlExpr) null)");
            Object obtained = runOrCatch(r.typeOf((ReqlExpr) null),
                                          new OptArgs()
                                          ,conn);
            try {
                assertEquals(expected_, obtained);
            logger.info("Finished running line #9");
            } catch (Throwable ae) {
                logger.error("Whoops, got exception on line #9:" + ae.toString());
                if(obtained instanceof Throwable) {
                    ae.addSuppressed((Throwable) obtained);
                }
                throw ae;
            }
        }
    }
}


text:
About

I'm lazy, but in a productive way. I develop solutions that streamline repetitive processes.

I'm passionate about making Web Applications an enjoyable and intuitive experience.

                         See My Code

redpajama_set_name: RedPajamaGithub


text:
ENV['RAILS_ENV'] ||= 'test'
$:.unshift File.dirname(__FILE__)
require 'rails_app/config/environment'
require 'rails/test_help'
require 'helpers/template_helper'
require 'database_cleaner'
require 'minitest/rails/capybara'

class ActiveSupport::TestCase
  include TemplateHelper

  def setup
    DatabaseCleaner.clean
    remove_templates('pages')
  end
end


text:
package org.batfish.representation.cisco;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;

public final class StandardCommunityList implements Serializable {

  private final List<StandardCommunityListLine> _lines;

  private final String _name;

  public StandardCommunityList(@Nonnull String name) {
    _name = name;
    _lines = new ArrayList<>();
  }

  public List<StandardCommunityListLine> getLines() {
    return _lines;
  }

  public String getName() {
    return _name;
  }
}


text:
<!doctype html>
<html>
<head>
    <title>easyXDM</title>
    <script type="text/javascript" src="../easyXDM.debug.js">
        </script>
    <script type="text/javascript">
        /**
        * Request the use of the JSON object
        */
        easyXDM.DomHelper.requiresJSON("../json2.js");
        </script>
    <script type="text/javascript">

        var REMOTE = location.href;
        REMOTE = REMOTE.substring(0, REMOTE.lastIndexOf("/"));

        var proxy, win;
        function openPopup() {
            if (win) {
                // this allows to open new windows if the popup was closed
                if (win.closed) {
                    win = window.open(REMOTE + '/blank.html', 'mainapp', "width=400, height=400");
                    proxy.open("mainapp");
                }
                return;
            }
            // open up the popup
            win = window.open(REMOTE + '/blank.html', 'mainapp', "width=400, height=400");

            document.getElementById("btn").disabled = "";

            proxy = new easyXDM.Rpc(/** The configuration */{
            /**
            * Register the url to name.html, this must be an absolute path
            * or a path relative to the root.
            * @field
            */
            local: "../name.html",
            swf: REMOTE + "/../easyxdm.swf",
            /**
            * Register the url to the remote interface
            * @field
            */
            remote: REMOTE + "/remote.html",
            remoteHelper: REMOTE + "/../name.html"
        }, {
            remote: {
                open: {},
                postMessage: {}
            },
            local: {
                /**
                * Register the method that should handle incoming data
                * @param {Object} data
                * @param {String} origin
                */
                postMessage: function (data) {
                    var div = document.createElement("div");
                    div.innerHTML = "data from '" + proxy.origin + "'";
                    document.body.appendChild(div);
                    for (var key in data) {
                        if (data.hasOwnProperty(key)) {
                            div = document.createElement("div");
                            div.innerHTML = key + "=" + data[key];
                            document.body.appendChild(div);
                        }
                    }
                }
            }
        });

        // lets tell the proxy to open up the window as soon as possible
        proxy.open("mainapp");
    }
        </script>
</head>
<body>
    <div id="log" style="height: 100px; border: 1px dotted black; overflow: auto">
    </div>
    <input id="btnOpen" type="button" onclick="openPopup();" value="Open popup" /><!-- Send som data to the other side --><input
        id="btn" disabled="disabled" type="button" onclick="proxy.postMessage({a:'b',c:'d',e:'f'});"
        value="send data to remote" />
</body>
</html>


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import update from 'react/lib/update';
import BusyIcon from '../../components/common/BusyIcon';
import FlagRadio from '../../components/item/FlagRadio';
import RecurrenceRadio from '../../components/item/RecurrenceRadio';

import '../../styles/event-form.css';

export default class EventForm extends Component {
  constructor(props, context) {
    super(props, context);

    this.handleTextChange = this.handleTextChange.bind(this);
    this.handleTagChange = this.handleTagChange.bind(this);
    this.handleDateChange = this.handleDateChange.bind(this);
    this.handleFlagChange = this.handleFlagChange.bind(this);
    this.handleRecurrenceChange = this.handleRecurrenceChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.onCancel = this.onCancel.bind(this);
    this.onReset = this.onReset.bind(this);

    this.state = {
      item: {
        ...this.props.item
      },
      error: null
    };
  }

  componentWillReceiveProps(newProps) {
    // Handle this only changing from editing to creating
    if (this.props.item.id && !newProps.item.id) {
      this.setState({
        item: {
          ...newProps.item
        },
        error: null
      });
    }
  }

  onSubmit(e) {
    const item = this.state.item;

    // form validation
    if (item.text.length <= 0) {
      this.setState({
        error: 'text can not be empty'
      });
      return;
    }

    e.preventDefault();
    this.props.onSubmit(item);
  }

  onCancel() {
    this.props.onCancel();
  }

  onReset() {
    this.setState({
      item: {
        ...this.props.item
      },
      error: null
    });
  }

  handleTextChange(e) {
    const newItem = update(this.state.item, {
      [e.target.getAttribute('name')]: { $set: e.target.value }
    });
    this.setState({
      item: newItem,
      error: null
    });
  }

  handleTagChange(tag) {
    const newItem = {
      ...this.state.item,
      tag
    };
    this.setState({
      item: newItem,
      error: null
    });
  }

  handleDateChange(date) {
    // console.log(Date.parse(date.format('YYYY-MM-DD')));
    try {
      const d = new Date(`${date.format('YYYY-M-D')}Z`);
      const newItem = { ...this.state.item,
        year: d.getFullYear(),
        month: d.getMonth() + 1,
        date: d.getDate()
      };
      this.setState({
        item: newItem,
        error: null
      });
    } catch (e) {
      /* eslint-disable */
      console.warn(e);
      /* eslint-disable */
    }
  }

  handleFlagChange(index) {
    const newItem = { ...this.state.item,
      flag: index
    };
    this.setState({
      item: newItem,
      error: null
    });
  }

  handleRecurrenceChange(index) {
    const item = this.state.item;
    item.recurrence = index;
    this.setState({
      item,
      error: null
    });
  }

  render() {
    // tag list
    let tagList = this.props.tags &&

      {this.props.tags.map((tag, index) =>

 this.handleTagChange(tag)}>

{tag}

      )}

;

    // item
    const item = this.state.item;

    // messages
    let errorDOM = this.state.error &&

          Error: {this.state.error}

;

    // action buttons
    let buttons;
    if (this.props.changing) {
      buttons = <BusyIcon />;
    } else {
      buttons = (

          <button type="submit" className="button" onClick={this.onSubmit}>Save</button>
          {this.state.item.id != null &&
            <button type="button" className="button" onClick={this.onCancel}>Cancel</button>
          }
          <button type="button" className="button" onClick={this.onReset}>Reset</button>

      );
    }

    return (

          <input
            name="year"
            value={item.year}
            type="number"
            min="1983" max="2083"
            className="form-control"
            style={{ width: '60px' }}
            onChange={this.handleTextChange}
          />
          -
          <input
            name="month"
            value={item.month}
            type="number"
            min="1" max="12"
            className="form-control"
            style={{ width: '40px' }}
            onChange={this.handleTextChange}
          />
          -
          <input
            name="date"
            value={item.date}
            type="number"
            min="1" max="31"
            className="form-control"
            style={{ width: '40px' }}
            onChange={this.handleTextChange}
          />
          {' '}
          (YYYY-M-D)

          <textarea
            name="text" value={item.text} className="form-control"
            style={{ width: '288px', height: '60px' }} placeholder="Text Contents"
            onChange={this.handleTextChange}
          />

Number

            <input
              name="number" value={item.number} type="number" className="form-control"
              style={{ width: '100px' }}
              onChange={this.handleTextChange}
            />

Tag

            <input
              name="tag" type="text" value={item.tag} className="form-control"
              style={{ width: '100px' }}
              onChange={this.handleTextChange}
            />

            {tagList}

Flag

            <FlagRadio selectedIndex={item.flag} onChange={this.handleFlagChange} />

Recurrence

            <RecurrenceRadio selectedIndex={item.recurrence} onChange={this.handleRecurrenceChange} />

        {errorDOM}

            {buttons}

    );
  }
}

EventForm.propTypes = {
  tags: PropTypes.array.isRequired,
  item: PropTypes.object.isRequired,
  onSubmit: PropTypes.func.isRequired,
  onCancel: PropTypes.func.isRequired
};


text:
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit)
// Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus
// Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues
// License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved.

#if EF6 || EFCORE
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Z.EntityFramework.Plus;

namespace Z.Test.EntityFramework.Plus
{
    public partial class BatchDelete_Transaction
    {
        [TestMethod]
        public void Commit()
        {
            TestContext.DeleteAll(x => x.Entity_Basics);
            TestContext.Insert(x => x.Entity_Basics, 50);

            using (var ctx = new TestContext())
            {
                var transaction = ctx.Database.BeginTransaction();

                // BEFORE
                Assert.AreEqual(1225, ctx.Entity_Basics.Sum(x => x.ColumnInt));

                // ACTION
                var rowsAffected = ctx.Entity_Basics.Where(x => x.ColumnInt > 10 && x.ColumnInt <= 40).Delete();
                transaction.Commit();

                // AFTER
                Assert.AreEqual(460, ctx.Entity_Basics.Sum(x => x.ColumnInt));
                Assert.AreEqual(30, rowsAffected);
            }
        }
    }
}

#endif


text:
package org.apache.carbondata.cluster.sdv.generated

import org.apache.spark.sql.common.util.Include
import org.apache.spark.sql.test.util.QueryTest
import org.scalatest.BeforeAndAfterAll

/**
 * Test Class for LuceneIndex Testcase to verify all scenarios
 */

class LuceneTestCase extends QueryTest with BeforeAndAfterAll {

  val csvPath = s"$resourcesPath/source.csv"

  override protected def beforeAll(): Unit = {
    sql("DROP TABLE IF EXISTS index_main")
  }

  // Create Lucene Index With DMProperties(String DataType) on MainTable
  test("Luceneindex_TC001", Include) {
    sql("DROP TABLE IF EXISTS index_main")
    sql(
      "CREATE TABLE index_main (id Int, date date, country string,name String, phonetype " +
      "string, " +
      "serialname String,salary int ) STORED AS carbondata")
    sql(
      s"""
         | CREATE INDEX lucene_index ON TABLE index_main (country)
         | AS 'lucene'
      """.stripMargin)
    checkExistence(sql("show indexes on table index_main"), true, "lucene_index")
    sql("drop index if exists lucene_index on table index_main")
  }

  // Create Lucene Index With DMProperties(Other DataTypes) on MainTable
  test("Luceneindex_TC002", Include) {
    sql("DROP TABLE IF EXISTS index_main")
    sql(
      "CREATE TABLE index_main (id Int, date date, country string,name String, phonetype " +
      "string, serialname String,salary int ) STORED AS carbondata ")
    val exception_otherdataType: Exception = intercept[Exception] {
      sql(
        s"""
           | CREATE INDEX lucene_index
           | ON TABLE index_main (id)
           | AS 'lucene'
      """.stripMargin)
    }
    assert(exception_otherdataType.getMessage
      .contains("Only String column is supported, column 'id' is INT type."))
  }

  // Create Lucene Index With DMProperties on MainTable and Load Data and Query
  ignore("Luceneindex_TC003", Include) {
    sql("DROP TABLE IF EXISTS index_main")
    sql(
      "CREATE TABLE index_main (id Int, date string, country string,name String, phonetype " +
      "string, " +
      "serialname String,salary int ) STORED AS carbondata TBLPROPERTIES" +
      "('SORT_COLUMNS'='country,name','SORT_SCOPE'='LOCAL_SORT')")
    sql(
      s"""
         | CREATE INDEX lucene_index
         | ON TABLE index_main (coutnry)
         | AS 'lucene'
      """.stripMargin)
    sql(s"LOAD DATA INPATH '$csvPath' INTO TABLE index_main")

    checkAnswer(sql("SELECT * FROM index_main WHERE TEXT_MATCH('country:china')"),
      sql("select * from index_main where country='china'"))
    sql("drop index if exists lucene_index on table index_main")
  }

  // Create Different Lucene Index With DMProperties on MainTable and filter using 'like','AND'
  // & 'OR'
  ignore("Luceneindex_TC004", Include) {
    sql("DROP TABLE IF EXISTS index_main")
    sql(
      "CREATE TABLE index_main (id Int, date string, country string,name String, phonetype " +
      "string, " +
      "serialname String,salary int ) STORED AS carbondata ")
    sql(
      s"""
         | CREATE INDEX lucene_index
         | ON TABLE index_main (country,name,serialname)
         | AS 'lucene'
      """.stripMargin)
    sql(s"LOAD DATA LOCAL INPATH '$csvPath' INTO TABLE index_main")
    checkAnswer(sql("SELECT * FROM index_main WHERE TEXT_MATCH('country:ch*')"),
      sql("select * from index_main where country like 'ch%'"))
    checkAnswer(sql(
      "SELECT * FROM index_main WHERE TEXT_MATCH('country:ch* AND name:aa*')"),
      sql("select * from index_main where country like 'ch%' and name like 'aa%'"))
    checkAnswer(sql(
      "SELECT * FROM index_main WHERE TEXT_MATCH('country:u* OR name:aa*')"),
      sql("select * from index_main where country like 'u%'or name like 'aa%'"))
    checkAnswer(sql(
      "SELECT * FROM index_main WHERE TEXT_MATCH('country:u* OR (name:aaa1* AND name:aaa2*)')"),
      sql(
        "select * from index_main where country like 'u%' OR name like 'aaa1%' AND name like " +
        "'aaa2%'"))
    sql("drop index if exists lucene_index on table index_main")
  }

  // Create Different Lucene Index With Properties on MainTable and check index after Delete
  // Segment
  ignore("Luceneindex_TC005", Include) {
    sql("DROP TABLE IF EXISTS index_main")
    sql(
      "CREATE TABLE index_main (id Int, date date, country string,name String, phonetype " +
      "string, " +
      "serialname String,salary int ) STORED AS carbondata")
    sql(
      s"""
         | CREATE INDEX lucene_index
         | ON TABLE index_main (country, name)
         | AS 'lucene'
      """.stripMargin)
    sql(s"LOAD DATA LOCAL INPATH '$csvPath' INTO TABLE index_main")
    sql(s"LOAD DATA LOCAL INPATH '$csvPath' INTO TABLE index_main")
    checkAnswer(sql("SELECT COUNT(*) FROM index_main WHERE TEXT_MATCH('country:china')"),
      sql("select COUNT(*) from index_main where country='china'"))
    sql("delete from table index_main where SEGMENT.ID in (0) ")
    sql("clean files for table index_main")
    checkAnswer(sql("SELECT COUNT(*) FROM index_main WHERE TEXT_MATCH('country:china')"),
      sql("select COUNT(*) from index_main where country='china'"))
    sql("drop index if exists lucene_index on table index_main")
  }

  // Create Different Lucene Index With DMProperties on MainTable with different 'TBLProperties'
  // and Load Data with Differnt OPTIONS & Verify
  ignore("Luceneindex_TC006", Include) {
    sql("DROP TABLE IF EXISTS index_main")
    sql(
      "CREATE TABLE index_main (id Int, date string, country string,name String, phonetype " +
      "string, " +
      "serialname String,salary int ) STORED AS carbondata " +
      "TBLPROPERTIES('SORT_COLUMNS'='country,name','SORT_SCOPE'='LOCAL_SORT')")
    sql(
      s"""
         | CREATE INDEX lucene_index
         | ON TABLE index_main (country)
         | AS 'lucene'
      """.stripMargin)
    sql(s"LOAD DATA LOCAL INPATH '$csvPath' INTO TABLE index_main OPTIONS('header'='false'," +
        s"'BAD_RECORDS_LOGGER_ENABLE'='FALSE','BAD_RECORDS_ACTION'='FORCE')")
    checkAnswer(sql("SELECT COUNT(*) FROM index_main WHERE TEXT_MATCH('country:china')"),
      sql("select COUNT(*) from index_main where country='china'"))
    sql("drop index if exists lucene_index on table index_main")
  }

  // Create LuceneIndex With Properties on MainTable and Insert data and Update and
  // Verify
  ignore("Luceneindex_TC007", Include) {
    sql("DROP TABLE IF EXISTS index_main")
    sql(
      "CREATE TABLE index_main (id Int,country string,name String) " +
      "STORED AS carbondata")
    sql(
      s"""
         | CREATE INDEX lucene_index
         | ON TABLE index_main (country,name)
         | AS 'lucene'
      """.stripMargin)
    sql("insert into index_main select 1,'abc','aa'")
    sql("insert into index_main select 2,'def','ab'")
    sql("insert into index_main select 3,'ghi','ac'")
    sql("insert into index_main select 4,'jkl','ad'")
    checkAnswer(sql("SELECT * FROM index_main WHERE TEXT_MATCH('country:def')"),
      sql("select * from index_main where country='def'"))
    sql("update index_main set (country)=('fed') where id=2")
    checkAnswer(sql("SELECT COUNT(*) FROM index_main WHERE TEXT_MATCH('country:fed')"),
      sql("select COUNT(*) from index_main where country='fed'"))
    sql("drop index if exists lucene_index on table index_main")
  }

  override protected def afterAll(): Unit = {
    sql("DROP TABLE IF EXISTS index_main")
  }
}


text:
package org.apache.directory.server.installers;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import org.apache.directory.server.installers.archive.ArchiveInstallerCommand;
import org.apache.directory.server.installers.archive.ArchiveTarget;
import org.apache.directory.server.installers.bin.BinInstallerCommand;
import org.apache.directory.server.installers.bin.BinTarget;
import org.apache.directory.server.installers.deb.DebInstallerCommand;
import org.apache.directory.server.installers.deb.DebTarget;
import org.apache.directory.server.installers.macosxpkg.MacOsXPkgInstallerCommand;
import org.apache.directory.server.installers.macosxpkg.MacOsXPkgTarget;
import org.apache.directory.server.installers.nsis.NsisInstallerCommand;
import org.apache.directory.server.installers.nsis.NsisTarget;
import org.apache.directory.server.installers.rpm.RpmInstallerCommand;
import org.apache.directory.server.installers.rpm.RpmTarget;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;

/**
 * Maven 2 mojo creating the platform specific installation layout images.
 *
 * @goal generate
 * @description Creates platform specific installation layout images.
 * @phase package
 * @requiresDependencyResolution runtime
 * @author Apache Directory Project
 */
public class GenerateMojo extends AbstractMojo
{
    /**
     * The target directory into which the mojo creates os and platform
     * specific images.
     *
     * @parameter default-value="${project.build.directory}/installers"
     */
    private File outputDirectory;

    /**
     * The associated maven project.
     *
     * @parameter expression="${project}" default-value="${project}"
     * @required
     */
    private MavenProject project;

    /**
     * The RPM installer targets.
     *
     * @parameter
     */
    private RpmTarget[] rpmTargets;

    /**
     * The Mac OS X installer targets.
     *
     * @parameter
     */
    private MacOsXPkgTarget[] macOsXPkgTargets;

    /**
     * The NSIS installer targets.
     *
     * @parameter
     */
    private NsisTarget[] nsisTargets;

    /**
     * The Debian installer targets.
     *
     * @parameter
     */
    private DebTarget[] debTargets;

    /**
     * The Binary installer targets.
     *
     * @parameter
     */
    private BinTarget[] binTargets;

    /**
     * The Archive installers targets.
     *
     * @parameter
     */
    private ArchiveTarget[] archiveTargets;

    /**
     * The exclusions.
     *
     * @parameter
     */
    private Set excludes;

    /**
     *  The dpkg utility executable.
     *
     *  @parameter
     *      expression="${installers.dpkg}"
     *      default-value="/usr/bin/dpkg"
     */
    private File dpkgUtility;

    /**
     *  The PackageMaker utility executable.
     *
     *  @parameter
     *      expression="${installers.packageMaker}"
     *      default-value="/Developer/Applications/Utilities/PackageMaker.app/Contents/MacOS/PackageMaker"
     */
    private File packageMakerUtility;

    /**
     *  The makensis utility executable.
     *
     *  @parameter
     *      expression="${installers.makensis}"
     *      default-value="/usr/bin/makensis"
     */
    private File makensisUtility;

    /**
     *  The rpmbuild utility executable.
     *
     *  @parameter
     *      expression="${installers.rpmbuild}"
     *      default-value="/usr/bin/rpmbuild"
     */
    private File rpmbuildUtility;

    /** The list containing all the targets */
    private List<Target> allTargets = new ArrayList<Target>();

    /**
     * {@inheritDoc}
     */
    public void execute() throws MojoExecutionException, MojoFailureException
    {
        // Collecting all targets
        collectAllTargets();

        // Returning if there is no target to build
        if ( allTargets.isEmpty() )
        {
            getLog().info( "No installers to generate." );
            return;
        }

        getLog().info( "-------------------------------------------------------" );

        // Creating the output directory
        FileUtils.mkdir( outputDirectory.getAbsolutePath() );

        // Generating installers for all targets
        for ( Target target : allTargets )
        {
            getLog().info( "Executing target '" + target.getId() + "'" );
            getLog().info( "--------------------" );
            getLog().info( "OS Name: " + target.getOsName() );
            getLog().info( "OS Arch: " + target.getOsArch() );
            getLog().info( "--------------------" );

            // Archive target
            if ( target instanceof ArchiveTarget )
            {
                ArchiveInstallerCommand archiveCmd = new ArchiveInstallerCommand( this, ( ArchiveTarget ) target );
                archiveCmd.execute();
            }

            // Bin target
            if ( target instanceof BinTarget )
            {
                BinInstallerCommand binCmd = new BinInstallerCommand( this, ( BinTarget ) target );
                binCmd.execute();
            }

            // Deb target
            if ( target instanceof DebTarget )
            {
                DebInstallerCommand debCmd = new DebInstallerCommand( this, ( DebTarget ) target );
                debCmd.execute();
            }

            // Mac OS X PKG target
            if ( target instanceof MacOsXPkgTarget )
            {
                MacOsXPkgInstallerCommand pkgCmd = new MacOsXPkgInstallerCommand( this, ( MacOsXPkgTarget ) target );
                pkgCmd.execute();
            }

            // NSIS target
            if ( target instanceof NsisTarget )
            {
                NsisInstallerCommand nsisCmd = new NsisInstallerCommand( this, ( NsisTarget ) target );
                nsisCmd.execute();
            }

            // RPM target
            if ( target instanceof RpmTarget )
            {
                RpmInstallerCommand rpmCmd = new RpmInstallerCommand( this, ( RpmTarget ) target );
                rpmCmd.execute();
            }

            getLog().info( "-------------------------------------------------------" );
        }
    }

    /**
     * Collects all targets.
     */
    private void collectAllTargets()
    {
        addAllTargets( allTargets, nsisTargets );
        addAllTargets( allTargets, rpmTargets );
        addAllTargets( allTargets, debTargets );
        addAllTargets( allTargets, macOsXPkgTargets );
        addAllTargets( allTargets, binTargets );
        addAllTargets( allTargets, archiveTargets );
    }

    /**
     * Adds an array of targets to the given list.
     *
     * @param list
     *      the list of targets
     * @param array
     *      an array of targets
     */
    private void addAllTargets( List<Target> list, Target[] array )
    {
        if ( ( list != null ) && ( array != null ) )
        {
            list.addAll( Arrays.asList( array ) );
        }
    }

    /**
     * Gets the output directory.
     *
     * @return
     *      the output directory
     */
    public File getOutputDirectory()
    {
        return outputDirectory;
    }

    /**
     * Gets the associated Maven project.
     *
     * @return
     *      the associated Maven project
     */
    public MavenProject getProject()
    {
        return project;
    }

    /**
     * Gets the excluded artifacts.
     *
     * @return
     *      the excluded artifacts
     */
    public Set getExcludes()
    {
        return excludes;
    }

    /**
     * Gets the dpkg utility.
     *
     * @return
     *      the dpkg utility
     */
    public File getDpkgUtility()
    {
        return dpkgUtility;
    }

    /**
     * Gets the dpkg utility.
     *
     * @return
     *      the dpkg utility
     */
    public File getPackageMakerUtility()
    {
        return packageMakerUtility;
    }

    /**
     * Gets the makensis utility.
     *
     * @return
     *      the dpkg utility
     */
    public File getMakensisUtility()
    {
        return makensisUtility;
    }

    public File getRpmbuildUtility()
    {
        return rpmbuildUtility;
    }
}


text:
using Xunit;

namespace System.IO.Compression.Tests
{
    public partial class ZipFileTest_Invalid : ZipFileTestBase
    {
        [Fact]
        public void InvalidInstanceMethods()
        {
            using (TempFile testArchive = CreateTempCopyFile(zfile("normal.zip"), GetTestFilePath()))
            using (ZipArchive archive = ZipFile.Open(testArchive.Path, ZipArchiveMode.Update))
            {
                //non-existent entry
                Assert.True(null == archive.GetEntry("nonExistentEntry"));
                //null/empty string
                Assert.Throws<ArgumentNullException>(() => archive.GetEntry(null));

                ZipArchiveEntry entry = archive.GetEntry("first.txt");

                //null/empty string
                AssertExtensions.Throws<ArgumentException>("entryName", () => archive.CreateEntry(""));
                Assert.Throws<ArgumentNullException>(() => archive.CreateEntry(null));
            }
        }

        [Fact]
        public void InvalidConstructors()
        {
            //out of range enum values
            Assert.Throws<ArgumentOutOfRangeException>(() => ZipFile.Open("bad file", (ZipArchiveMode)(10)));
        }

        [Fact]
        public void InvalidFiles()
        {
            Assert.Throws<InvalidDataException>(() => ZipFile.OpenRead(bad("EOCDmissing.zip")));
            using (TempFile testArchive = CreateTempCopyFile(bad("EOCDmissing.zip"), GetTestFilePath()))
            {
                Assert.Throws<InvalidDataException>(() => ZipFile.Open(testArchive.Path, ZipArchiveMode.Update));
            }

            Assert.Throws<InvalidDataException>(() => ZipFile.OpenRead(bad("CDoffsetOutOfBounds.zip")));
            using (TempFile testArchive = CreateTempCopyFile(bad("CDoffsetOutOfBounds.zip"), GetTestFilePath()))
            {
                Assert.Throws<InvalidDataException>(() => ZipFile.Open(testArchive.Path, ZipArchiveMode.Update));
            }

            using (ZipArchive archive = ZipFile.OpenRead(bad("CDoffsetInBoundsWrong.zip")))
            {
                Assert.Throws<InvalidDataException>(() => { var x = archive.Entries; });
            }

            using (TempFile testArchive = CreateTempCopyFile(bad("CDoffsetInBoundsWrong.zip"), GetTestFilePath()))
            {
                Assert.Throws<InvalidDataException>(() => ZipFile.Open(testArchive.Path, ZipArchiveMode.Update));
            }

            using (ZipArchive archive = ZipFile.OpenRead(bad("numberOfEntriesDifferent.zip")))
            {
                Assert.Throws<InvalidDataException>(() => { var x = archive.Entries; });
            }
            using (TempFile testArchive = CreateTempCopyFile(bad("numberOfEntriesDifferent.zip"), GetTestFilePath()))
            {
                Assert.Throws<InvalidDataException>(() => ZipFile.Open(testArchive.Path, ZipArchiveMode.Update));
            }

            //read mode on empty file
            using (var memoryStream = new MemoryStream())
            {
                Assert.Throws<InvalidDataException>(() => new ZipArchive(memoryStream));
            }

            //offset out of bounds
            using (ZipArchive archive = ZipFile.OpenRead(bad("localFileOffsetOutOfBounds.zip")))
            {
                ZipArchiveEntry e = archive.Entries[0];
                Assert.Throws<InvalidDataException>(() => e.Open());
            }

            using (TempFile testArchive = CreateTempCopyFile(bad("localFileOffsetOutOfBounds.zip"), GetTestFilePath()))
            {
                Assert.Throws<InvalidDataException>(() => ZipFile.Open(testArchive.Path, ZipArchiveMode.Update));
            }

            //compressed data offset + compressed size out of bounds
            using (ZipArchive archive = ZipFile.OpenRead(bad("compressedSizeOutOfBounds.zip")))
            {
                ZipArchiveEntry e = archive.Entries[0];
                Assert.Throws<InvalidDataException>(() => e.Open());
            }

            using (TempFile testArchive = CreateTempCopyFile(bad("compressedSizeOutOfBounds.zip"), GetTestFilePath()))
            {
                Assert.Throws<InvalidDataException>(() => ZipFile.Open(testArchive.Path, ZipArchiveMode.Update));
            }

            //signature wrong
            using (ZipArchive archive = ZipFile.OpenRead(bad("localFileHeaderSignatureWrong.zip")))
            {
                ZipArchiveEntry e = archive.Entries[0];
                Assert.Throws<InvalidDataException>(() => e.Open());
            }

            using (TempFile testArchive = CreateTempCopyFile(bad("localFileHeaderSignatureWrong.zip"), GetTestFilePath()))
            {
                Assert.Throws<InvalidDataException>(() => ZipFile.Open(testArchive.Path, ZipArchiveMode.Update));
            }
        }

        [Theory]
        [InlineData("LZMA.zip", true)]
        [InlineData("invalidDeflate.zip", false)]
        public void UnsupportedCompressionRoutine(string zipName, bool throwsOnOpen)
        {
            string filename = bad(zipName);
            using (ZipArchive archive = ZipFile.OpenRead(filename))
            {
                ZipArchiveEntry e = archive.Entries[0];
                if (throwsOnOpen)
                {
                    Assert.Throws<InvalidDataException>(() => e.Open());
                }
                else
                {
                    using (Stream s = e.Open())
                    {
                        Assert.Throws<InvalidDataException>(() => s.ReadByte());
                    }
                }
            }

            using (TempFile updatedCopy = CreateTempCopyFile(filename, GetTestFilePath()))
            {
                string name;
                long length, compressedLength;
                DateTimeOffset lastWriteTime;
                using (ZipArchive archive = ZipFile.Open(updatedCopy.Path, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry e = archive.Entries[0];
                    name = e.FullName;
                    lastWriteTime = e.LastWriteTime;
                    length = e.Length;
                    compressedLength = e.CompressedLength;
                    Assert.Throws<InvalidDataException>(() => e.Open());
                }

                //make sure that update mode preserves that unreadable file
                using (ZipArchive archive = ZipFile.Open(updatedCopy.Path, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry e = archive.Entries[0];
                    Assert.Equal(name, e.FullName);
                    Assert.Equal(lastWriteTime, e.LastWriteTime);
                    Assert.Equal(length, e.Length);
                    Assert.Equal(compressedLength, e.CompressedLength);
                    Assert.Throws<InvalidDataException>(() => e.Open());
                }
            }
        }

        [Fact]
        public void InvalidDates()
        {
            using (ZipArchive archive = ZipFile.OpenRead(bad("invaliddate.zip")))
            {
                Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime);
            }

            FileInfo fileWithBadDate = new FileInfo(GetTestFilePath());
            fileWithBadDate.Create().Dispose();
            fileWithBadDate.LastWriteTimeUtc = new DateTime(1970, 1, 1, 1, 1, 1);

            string archivePath = GetTestFilePath();
            using (FileStream output = File.Open(archivePath, FileMode.Create))
            using (ZipArchive archive = new ZipArchive(output, ZipArchiveMode.Create))
            {
                archive.CreateEntryFromFile(fileWithBadDate.FullName, "SomeEntryName");
            }
            using (ZipArchive archive = ZipFile.OpenRead(archivePath))
            {
                Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime);
            }
        }

        [Fact]
        public void FilesOutsideDirectory()
        {
            string archivePath = GetTestFilePath();
            using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
            using (StreamWriter writer = new StreamWriter(archive.CreateEntry(Path.Combine("..", "entry1"), CompressionLevel.Optimal).Open()))
            {
                writer.Write("This is a test.");
            }
            Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(archivePath, GetTestFilePath()));
        }

        [Fact]
        public void DirectoryEntryWithData()
        {
            string archivePath = GetTestFilePath();
            using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
            using (StreamWriter writer = new StreamWriter(archive.CreateEntry("testdir" + Path.DirectorySeparatorChar, CompressionLevel.Optimal).Open()))
            {
                writer.Write("This is a test.");
            }
            Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(archivePath, GetTestFilePath()));
        }

        /// <summary>
        /// This test ensures that a zipfile with path names that are invalid to this OS will throw errors
        /// when an attempt is made to extract them.
        /// </summary>
        [ActiveIssue(25665)]
        [Theory]
        [InlineData("NullCharFileName_FromWindows")]
        [InlineData("NullCharFileName_FromUnix")]
        [PlatformSpecific(TestPlatforms.AnyUnix)]  // Checks Unix-specific invalid file path
        public void Unix_ZipWithInvalidFileNames_ThrowsArgumentException(string zipName)
        {
            AssertExtensions.Throws<ArgumentException>("path", () => ZipFile.ExtractToDirectory(compat(zipName) + ".zip", GetTestFilePath()));
        }

        [Theory]
        [InlineData("backslashes_FromUnix", "aa\\bb\\cc\\dd")]
        [InlineData("backslashes_FromWindows", "aa\\bb\\cc\\dd")]
        [InlineData("WindowsInvalid_FromUnix", "aa<b>d")]
        [InlineData("WindowsInvalid_FromWindows", "aa<b>d")]
        [PlatformSpecific(TestPlatforms.AnyUnix)]  // Checks Unix-specific invalid file path
        public void Unix_ZipWithOSSpecificFileNames(string zipName, string fileName)
        {
            string tempDir = GetTestFilePath();
            ZipFile.ExtractToDirectory(compat(zipName) + ".zip", tempDir);
            string[] results = Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories);
            Assert.Equal(1, results.Length);
            Assert.Equal(fileName, Path.GetFileName(results[0]));
        }

        /// <summary>
        /// This test ensures that a zipfile with path names that are invalid to this OS will throw errors
        /// when an attempt is made to extract them.
        /// </summary>
        [Theory]
        [ActiveIssue(27269)]
        [InlineData("WindowsInvalid_FromUnix", null)]
        [InlineData("WindowsInvalid_FromWindows", null)]
        [InlineData("NullCharFileName_FromWindows", "path")]
        [InlineData("NullCharFileName_FromUnix", "path")]
        [PlatformSpecific(TestPlatforms.Windows)]  // Checks Windows-specific invalid file path
        public void Windows_ZipWithInvalidFileNames_ThrowsArgumentException(string zipName, string paramName)
        {
            AssertExtensions.Throws<ArgumentException>(paramName, null, () => ZipFile.ExtractToDirectory(compat(zipName) + ".zip", GetTestFilePath()));
        }

        [Theory]
        [InlineData("backslashes_FromUnix", "dd")]
        [InlineData("backslashes_FromWindows", "dd")]
        [PlatformSpecific(TestPlatforms.Windows)]  // Checks Windows-specific invalid file path
        public void Windows_ZipWithOSSpecificFileNames(string zipName, string fileName)
        {
            string tempDir = GetTestFilePath();
            ZipFile.ExtractToDirectory(compat(zipName) + ".zip", tempDir);
            string[] results = Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories);
            Assert.Equal(1, results.Length);
            Assert.Equal(fileName, Path.GetFileName(results[0]));
        }
    }
}


text:
namespace rpcz {

workers_commander::workers_commander(int workers)
    : workers_(workers),
      worker_cmd_queues_(new worker_cmd_queue_ptr[workers]) {  // scoped_ptr
  GOOGLE_CHECK(workers > 0);
}

// Non-thread-safe.
void workers_commander::set_cmd_queue(unsigned int worker_index,
    const worker_cmd_queue_ptr& cmd_queue) {
  GOOGLE_CHECK(worker_index < (unsigned int)workers_);
  GOOGLE_CHECK(cmd_queue);
  // Should set once only.
  GOOGLE_CHECK(!worker_cmd_queues_[worker_index]);
  worker_cmd_queues_[worker_index] = cmd_queue;
}

void workers_commander::handle_timeout(
    unsigned int worker_index, uint64 event_id) {
  GOOGLE_CHECK(is_worker_index_legal(worker_index));
  worker_cmd_ptr cmd(new b2w::handle_timeout_cmd(event_id));  // shared_ptr
  worker_cmd_queues_[worker_index]->push(std::move(cmd));
}

void workers_commander::handle_cancel() {
  for (int worker_index = 0; worker_index < workers_; worker_index++) {
    worker_cmd_ptr cmd(new b2w::handle_cancel_cmd());  // shared_ptr
    worker_cmd_queues_[worker_index]->push(std::move(cmd));
  }
}

void workers_commander::register_svc(
    unsigned int worker_index,
    const connection_info_ptr& info,
    const std::string& name,
    iservice* svc) {
  GOOGLE_CHECK(is_worker_index_legal(worker_index));
  GOOGLE_CHECK(svc);
  worker_cmd_ptr cmd(new b2w::register_svc_cmd(info, name, svc));  // shared_ptr
  worker_cmd_queues_[worker_index]->push(std::move(cmd));
}

void workers_commander::monitor_socket(unsigned int worker_index, const std::string& endpoint, zmq_event_t event) {
  GOOGLE_CHECK(is_worker_index_legal(worker_index));
  worker_cmd_ptr cmd(new b2w::monitor_socket_cmd(endpoint, event));  // shared_ptr
  worker_cmd_queues_[worker_index]->push(std::move(cmd));
}

void workers_commander::quit_worker(
    unsigned int worker_index) {
  GOOGLE_CHECK(is_worker_index_legal(worker_index));
  worker_cmd_ptr cmd(new b2w::quit_worker_cmd);  // shared_ptr
  worker_cmd_queues_[worker_index]->push(std::move(cmd));
}

bool workers_commander::is_worker_index_legal(
    unsigned int worker_index) const {
  return worker_index < (unsigned int)workers_
      && worker_cmd_queues_[worker_index];
}

}  // namespace rpcz


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

<TITLE>
TierFactory
</TITLE>

<META NAME="keywords" CONTENT="apollo.gui.detailviewers.sequencealigner.TierFactory class">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

apollo.gui.detailviewers.sequencealigner

Class TierFactory

java.lang.Object
  apollo.gui.detailviewers.sequencealigner.TierFactory

All Implemented Interfaces:
TierFactoryI

public class TierFactory
extends java.lang.Object
implements TierFactoryI

Constructor Summary

TierFactory(ReferenceFactoryI ref,
            Strand s,
            ReadingFrame rf)

Method Summary

 ReadingFrame
getReadingFrame()

 Strand
getStrand()

 TierI
makeTier()

 TierI
makeTier(SequenceI reference,
         Strand s,
         ReadingFrame rf)

 void
setReadingFrame(ReadingFrame rf)

 void
setStrand(Strand s)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TierFactory

public TierFactory(ReferenceFactoryI ref,
                   Strand s,
                   ReadingFrame rf)

Method Detail

makeTier

public TierI makeTier()

Specified by:
makeTier in interface TierFactoryI

makeTier

public TierI makeTier(SequenceI reference,
                      Strand s,
                      ReadingFrame rf)

Specified by:
makeTier in interface TierFactoryI

getStrand

public Strand getStrand()

setStrand

public void setStrand(Strand s)

getReadingFrame

public ReadingFrame getReadingFrame()

setReadingFrame

public void setReadingFrame(ReadingFrame rf)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import app from '../../app';
import { guid } from '../../utils';
import BaseModel from '../BaseModel';
import Image from './Image';

export default class extends BaseModel {
  constructor(attrs = {}, options = {}) {
    super({
      ...attrs,
      _clientID: attrs._clientID || guid(),
    }, options);
  }

  defaults() {
    return {
      name: '',
    };
  }

  get idAttribute() {
    return '_clientID';
  }

  get nested() {
    return {
      image: Image,
    };
  }

  get max() {
    return {
      nameLength: 40,
    };
  }

  validate(attrs) {
    const errObj = {};

    const addError = (fieldName, error) => {
      errObj[fieldName] = errObj[fieldName] || [];
      errObj[fieldName].push(error);
    };

    if (!attrs.name) {
      addError('name', app.polyglot.t('variantModelErrors.provideName'));
    } else if (attrs.name.length > this.max.nameLength) {
      addError('name', app.polyglot.t('variantModelErrors.nameTooLong', {
        name: attrs.name,
        maxLength: this.max.nameLength,
      }));
    }

    if (Object.keys(errObj).length) return errObj;

    return undefined;
  }
}


text:
@protocol BugsnagMetaDataDelegate;

@interface BugsnagMetaData : NSObject < NSMutableCopying >

- (id) initWithDictionary:(NSMutableDictionary*)dict;
- (NSMutableDictionary *) getTab:(NSString*)tabName;
- (void) clearTab:(NSString*)tabName;
- (void) mergeWith:(NSDictionary*)data;
- (NSDictionary*) toDictionary;
- (void) addAttribute:(NSString*)attributeName withValue:(id)value toTabWithName:(NSString*)tabName;
@property(unsafe_unretained) id<BugsnagMetaDataDelegate> delegate;

@end

@protocol BugsnagMetaDataDelegate <NSObject>
- (void) metaDataChanged: (BugsnagMetaData *) metaData;
@end


text:
package com.dev.geochallenger.models.entities.directions;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Polyline {

    @SerializedName("points")
    @Expose
    private String points;

    /**
     *
     * @return
     *     The points
     */
    public String getPoints() {
        return points;
    }

    /**
     *
     * @param points
     *     The points
     */
    public void setPoints(String points) {
        this.points = points;
    }

}


text:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->

        <!-- 设置activity切换动画 -->
        <item name="android:windowAnimationStyle">@style/slideActivityAnimation</item>
    </style>

    <style name="slideActivityAnimation" parent="@android:style/Animation">
    	<item name="android:activityOpenEnterAnimation">@anim/slide_right_in</item>
        <item name="android:activityOpenExitAnimation">@anim/slide_left_out</item>
        <item name="android:activityCloseEnterAnimation">@anim/slide_left_in</item>
        <item name="android:activityCloseExitAnimation">@anim/slide_right_out</item>
	</style>

    <!-- PopupMenu theme -->
    <style name="Theme.PopupMenu"
       parent="@android:style/Widget.Holo.Light.ListPopupWindow">
       <item name="android:popupBackground">@color/popupMenuBgColor</item>
	</style>

    <style name="Theme.InCallScreen"
        parent="AppTheme">
        <item name="android:popupMenuStyle">@style/Theme.PopupMenu</item>
	</style>

    <!-- 自定义loading dialog -->
	<style name="loading_dialog" parent="android:style/Theme.Dialog">
	    <item name="android:windowFrame">@null</item>
	    <item name="android:windowNoTitle">true</item>
	    <item name="android:windowIsFloating">true</item>
	    <item name="android:windowContentOverlay">@null</item>
	    <item name="android:windowBackground">@drawable/progress_dialog_bk</item>
	</style>

</resources>


text:
classdef LinearFilterFigure2 < edu.washington.riekelab.turner.figures.LinearFilterFigure
    methods
        function obj = LinearFilterFigure2(ampDevice, frameMonitor, varargin)
            obj@edu.washington.riekelab.turner.figures.LinearFilterFigure(ampDevice, frameMonitor, varargin{:});
        end
    end
end


text:
package demo

import core.clientView.ClientView
import core.spatial.Zone

class DemoClientView(id : String) extends ClientView(id) {

  override def dataToViewZone(): Zone = new SquareZone(0,0,600,600)

  override def onNotify(any: Any): Unit ={}

  override def fromListToClientMsg(list: List[Any]) = {
    Left(list.asInstanceOf[List[Ball]] map (_.toJson) mkString("[",",","]"))
  }
}


text:
"""
Unit Tests for remote procedure calls using queue
"""

import mock
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_db import exception as db_exc

from cinder import context
from cinder import db
from cinder import exception
from cinder import manager
from cinder import rpc
from cinder import service
from cinder import test
from cinder import wsgi

test_service_opts = [
    cfg.StrOpt("fake_manager",
               default="cinder.tests.unit.test_service.FakeManager",
               help="Manager for testing"),
    cfg.StrOpt("test_service_listen",
               default=None,
               help="Host to bind test service to"),
    cfg.IntOpt("test_service_listen_port",
               default=0,
               help="Port number to bind test service to"), ]

CONF = cfg.CONF
CONF.register_opts(test_service_opts)

class FakeManager(manager.Manager):
    """Fake manager for tests."""
    def __init__(self, host=None,
                 db_driver=None, service_name=None):
        super(FakeManager, self).__init__(host=host,
                                          db_driver=db_driver)

    def test_method(self):
        return 'manager'

class ExtendedService(service.Service):
    def test_method(self):
        return 'service'

class ServiceManagerTestCase(test.TestCase):
    """Test cases for Services."""

    def test_message_gets_to_manager(self):
        serv = service.Service('test',
                               'test',
                               'test',
                               'cinder.tests.unit.test_service.FakeManager')
        serv.start()
        self.assertEqual('manager', serv.test_method())

    def test_override_manager_method(self):
        serv = ExtendedService('test',
                               'test',
                               'test',
                               'cinder.tests.unit.test_service.FakeManager')
        serv.start()
        self.assertEqual('service', serv.test_method())

class ServiceFlagsTestCase(test.TestCase):
    def test_service_enabled_on_create_based_on_flag(self):
        self.flags(enable_new_services=True)
        host = 'foo'
        binary = 'cinder-fake'
        app = service.Service.create(host=host, binary=binary)
        app.start()
        app.stop()
        ref = db.service_get(context.get_admin_context(), app.service_id)
        db.service_destroy(context.get_admin_context(), app.service_id)
        self.assertFalse(ref['disabled'])

    def test_service_disabled_on_create_based_on_flag(self):
        self.flags(enable_new_services=False)
        host = 'foo'
        binary = 'cinder-fake'
        app = service.Service.create(host=host, binary=binary)
        app.start()
        app.stop()
        ref = db.service_get(context.get_admin_context(), app.service_id)
        db.service_destroy(context.get_admin_context(), app.service_id)
        self.assertTrue(ref['disabled'])

class ServiceTestCase(test.TestCase):
    """Test cases for Services."""

    def setUp(self):
        super(ServiceTestCase, self).setUp()
        self.host = 'foo'
        self.binary = 'cinder-fake'
        self.topic = 'fake'

    def test_create(self):
        # NOTE(vish): Create was moved out of mock replay to make sure that
        #             the looping calls are created in StartService.
        app = service.Service.create(host=self.host,
                                     binary=self.binary,
                                     topic=self.topic)

        self.assertTrue(app)

    def test_report_state_newly_disconnected(self):
        service_ref = {'host': self.host,
                       'binary': self.binary,
                       'topic': self.topic,
                       'report_count': 0,
                       'availability_zone': 'nova',
                       'id': 1}
        with mock.patch.object(service, 'db') as mock_db:
            mock_db.service_get_by_args.side_effect = exception.NotFound()
            mock_db.service_create.return_value = service_ref
            mock_db.service_get.side_effect = db_exc.DBConnectionError()

            serv = service.Service(
                self.host,
                self.binary,
                self.topic,
                'cinder.tests.unit.test_service.FakeManager'
            )
            serv.start()
            serv.report_state()
            self.assertTrue(serv.model_disconnected)
            self.assertFalse(mock_db.service_update.called)

    def test_report_state_disconnected_DBError(self):
        service_ref = {'host': self.host,
                       'binary': self.binary,
                       'topic': self.topic,
                       'report_count': 0,
                       'availability_zone': 'nova',
                       'id': 1}
        with mock.patch.object(service, 'db') as mock_db:
            mock_db.service_get_by_args.side_effect = exception.NotFound()
            mock_db.service_create.return_value = service_ref
            mock_db.service_get.side_effect = db_exc.DBError()

            serv = service.Service(
                self.host,
                self.binary,
                self.topic,
                'cinder.tests.unit.test_service.FakeManager'
            )
            serv.start()
            serv.report_state()
            self.assertTrue(serv.model_disconnected)
            self.assertFalse(mock_db.service_update.called)

    def test_report_state_newly_connected(self):
        service_ref = {'host': self.host,
                       'binary': self.binary,
                       'topic': self.topic,
                       'report_count': 0,
                       'availability_zone': 'nova',
                       'id': 1}
        with mock.patch.object(service, 'db') as mock_db:
            mock_db.service_get_by_args.side_effect = exception.NotFound()
            mock_db.service_create.return_value = service_ref
            mock_db.service_get.return_value = service_ref

            serv = service.Service(
                self.host,
                self.binary,
                self.topic,
                'cinder.tests.unit.test_service.FakeManager'
            )
            serv.start()
            serv.model_disconnected = True
            serv.report_state()

            self.assertFalse(serv.model_disconnected)
            self.assertTrue(mock_db.service_update.called)

    def test_report_state_manager_not_working(self):
        service_ref = {'host': self.host,
                       'binary': self.binary,
                       'topic': self.topic,
                       'report_count': 0,
                       'availability_zone': 'nova',
                       'id': 1}
        with mock.patch.object(service, 'db') as mock_db:
            mock_db.service_get.return_value = service_ref

            serv = service.Service(
                self.host,
                self.binary,
                self.topic,
                'cinder.tests.unit.test_service.FakeManager'
            )
            serv.manager.is_working = mock.Mock(return_value=False)
            serv.start()
            serv.report_state()

            serv.manager.is_working.assert_called_once_with()
            self.assertFalse(mock_db.service_update.called)

    def test_service_with_long_report_interval(self):
        self.override_config('service_down_time', 10)
        self.override_config('report_interval', 10)
        service.Service.create(
            binary="test_service",
            manager="cinder.tests.unit.test_service.FakeManager")
        self.assertEqual(25, CONF.service_down_time)

    @mock.patch.object(rpc, 'get_server')
    @mock.patch.object(service, 'db')
    def test_service_stop_waits_for_rpcserver(self, mock_db, mock_rpc):
        serv = service.Service(
            self.host,
            self.binary,
            self.topic,
            'cinder.tests.unit.test_service.FakeManager'
        )
        serv.start()
        serv.stop()
        serv.wait()
        serv.rpcserver.start.assert_called_once_with()
        serv.rpcserver.stop.assert_called_once_with()
        serv.rpcserver.wait.assert_called_once_with()

class TestWSGIService(test.TestCase):

    def setUp(self):
        super(TestWSGIService, self).setUp()

    def test_service_random_port(self):
        with mock.patch.object(wsgi.Loader, 'load_app') as mock_load_app:
            test_service = service.WSGIService("test_service")
            self.assertEqual(0, test_service.port)
            test_service.start()
            self.assertNotEqual(0, test_service.port)
            test_service.stop()
            self.assertTrue(mock_load_app.called)

    def test_reset_pool_size_to_default(self):
        with mock.patch.object(wsgi.Loader, 'load_app') as mock_load_app:
            test_service = service.WSGIService("test_service")
            test_service.start()

            # Stopping the service, which in turn sets pool size to 0
            test_service.stop()
            self.assertEqual(test_service.server._pool.size, 0)

            # Resetting pool size to default
            test_service.reset()
            test_service.start()
            self.assertEqual(test_service.server._pool.size,
                             1000)
            self.assertTrue(mock_load_app.called)

    @mock.patch('cinder.wsgi.Server')
    def test_workers_set_default(self, wsgi_server):
        test_service = service.WSGIService("osapi_volume")
        self.assertEqual(processutils.get_worker_count(), test_service.workers)

    @mock.patch('cinder.wsgi.Server')
    def test_workers_set_good_user_setting(self, wsgi_server):
        self.override_config('osapi_volume_workers', 8)
        test_service = service.WSGIService("osapi_volume")
        self.assertEqual(8, test_service.workers)

    @mock.patch('cinder.wsgi.Server')
    def test_workers_set_zero_user_setting(self, wsgi_server):
        self.override_config('osapi_volume_workers', 0)
        test_service = service.WSGIService("osapi_volume")
        # If a value less than 1 is used, defaults to number of procs available
        self.assertEqual(processutils.get_worker_count(), test_service.workers)

    @mock.patch('cinder.wsgi.Server')
    def test_workers_set_negative_user_setting(self, wsgi_server):
        self.override_config('osapi_volume_workers', -1)
        self.assertRaises(exception.InvalidInput,
                          service.WSGIService,
                          "osapi_volume")
        self.assertFalse(wsgi_server.called)

class OSCompatibilityTestCase(test.TestCase):
    def _test_service_launcher(self, fake_os):
        # Note(lpetrut): The cinder-volume service needs to be spawned
        # differently on Windows due to an eventlet bug. For this reason,
        # we must check the process launcher used.
        fake_process_launcher = mock.MagicMock()
        with mock.patch('os.name', fake_os):
            with mock.patch('cinder.service.process_launcher',
                            fake_process_launcher):
                launcher = service.get_launcher()
                if fake_os == 'nt':
                    self.assertEqual(service.Launcher, type(launcher))
                else:
                    self.assertEqual(fake_process_launcher(), launcher)

    def test_process_launcher_on_windows(self):
        self._test_service_launcher('nt')

    def test_process_launcher_on_linux(self):
        self._test_service_launcher('posix')


text:
"""Methods for checking EcmaScript files for indentation issues."""

__author__ = ('robbyw@google.com (Robert Walker)')

import gflags as flags

import ecmametadatapass
import errors
import javascripttokens
import tokenutil
from common import error
from common import position

flags.DEFINE_boolean('debug_indentation', False,
                     'Whether to print debugging information for indentation.')

# Shorthand
Context = ecmametadatapass.EcmaContext
Error = error.Error
Position = position.Position
Type = javascripttokens.JavaScriptTokenType

# The general approach:
#
# 1. Build a stack of tokens that can affect indentation.
#    For each token, we determine if it is a block or continuation token.
#    Some tokens need to be temporarily overwritten in case they are removed
#    before the end of the line.
#    Much of the work here is determining which tokens to keep on the stack
#    at each point.  Operators, for example, should be removed once their
#    expression or line is gone, while parentheses must stay until the matching
#    end parentheses is found.
#
# 2. Given that stack, determine the allowable indentations.
#    Due to flexible indentation rules in JavaScript, there may be many
#    allowable indentations for each stack.  We follows the general
#    "no false positives" approach of GJsLint and build the most permissive
#    set possible.

class TokenInfo(object):
    """Stores information about a token.

    Attributes:
      token: The token
      is_block: Whether the token represents a block indentation.
      is_transient: Whether the token should be automatically removed without
        finding a matching end token.
      overridden_by: TokenInfo for a token that overrides the indentation that
        this token would require.
      is_permanent_override: Whether the override on this token should persist
        even after the overriding token is removed from the stack.  For example:
        x([
          1],
        2);
        needs this to be set so the last line is not required to be a continuation
        indent.
      line_number: The effective line number of this token.  Will either be the
        actual line number or the one before it in the case of a mis-wrapped
        operator.
    """

    def __init__(self, token, is_block=False):
        """Initializes a TokenInfo object.

        Args:
          token: The token
          is_block: Whether the token represents a block indentation.
        """
        self.token = token
        self.overridden_by = None
        self.is_permanent_override = False
        self.is_block = is_block
        self.is_transient = not is_block and token.type not in (
            Type.START_PAREN, Type.START_PARAMETERS)
        self.line_number = token.line_number

    def __repr__(self):
        result = '\n  %s' % self.token
        if self.overridden_by:
            result = '%s OVERRIDDEN [by "%s"]' % (
                result, self.overridden_by.token.string)
        result += ' {is_block: %s, is_transient: %s}' % (
            self.is_block, self.is_transient)
        return result

class IndentationRules(object):
    """EmcaScript indentation rules.

    Can be used to find common indentation errors in JavaScript, ActionScript and
    other Ecma like scripting languages.
    """

    def __init__(self):
        """Initializes the IndentationRules checker."""
        self._stack = []

        # Map from line number to number of characters it is off in indentation.
        self._start_index_offset = {}

    def Finalize(self):
        if self._stack:
            old_stack = self._stack
            self._stack = []
            raise Exception(
                'INTERNAL ERROR: indentation stack is not empty: %r' %
                old_stack)

    def CheckToken(self, token, state):
        """Checks a token for indentation errors.

        Args:
          token: The current token under consideration
          state: Additional information about the current tree state

        Returns:
          An error array [error code, error string, error token] if the token is
          improperly indented, or None if indentation is correct.
        """

        token_type = token.type
        indentation_errors = []
        stack = self._stack
        is_first = self._IsFirstNonWhitespaceTokenInLine(token)

        # Add tokens that could decrease indentation before checking.
        if token_type == Type.END_PAREN:
            self._PopTo(Type.START_PAREN)

        elif token_type == Type.END_PARAMETERS:
            self._PopTo(Type.START_PARAMETERS)

        elif token_type == Type.END_BRACKET:
            self._PopTo(Type.START_BRACKET)

        elif token_type == Type.END_BLOCK:
            start_token = self._PopTo(Type.START_BLOCK)
            # Check for required goog.scope comment.
            if start_token:
                goog_scope = tokenutil.GoogScopeOrNoneFromStartBlock(
                    start_token.token)
                if goog_scope is not None:
                    if not token.line.endswith(';  // goog.scope\n'):
                        if (token.line.find('//') > -1 and
                                    token.line.find('goog.scope') >
                                    token.line.find('//')):
                            indentation_errors.append([
                                errors.MALFORMED_END_OF_SCOPE_COMMENT,
                                (
                                'Malformed end of goog.scope comment. Please use the '
                                'exact following syntax to close the scope:\n'
                                '});  // goog.scope'),
                                token,
                                Position(token.start_index, token.length)])
                        else:
                            indentation_errors.append([
                                errors.MISSING_END_OF_SCOPE_COMMENT,
                                (
                                'Missing comment for end of goog.scope which opened at line '
                                '%d. End the scope with:\n'
                                '});  // goog.scope' %
                                (start_token.line_number)),
                                token,
                                Position(token.start_index, token.length)])

        elif token_type == Type.KEYWORD and token.string in ('case', 'default'):
            self._Add(self._PopTo(Type.START_BLOCK))

        elif is_first and token.string == '.':
            # This token should have been on the previous line, so treat it as if it
            # was there.
            info = TokenInfo(token)
            info.line_number = token.line_number - 1
            self._Add(info)

        elif token_type == Type.SEMICOLON:
            self._PopTransient()

        not_binary_operator = (token_type != Type.OPERATOR or
                               token.metadata.IsUnaryOperator())
        not_dot = token.string != '.'
        if is_first and not_binary_operator and not_dot and token.type not in (
            Type.COMMENT, Type.DOC_PREFIX, Type.STRING_TEXT):
            if flags.FLAGS.debug_indentation:
                print 'Line #%d: stack %r' % (token.line_number, stack)

            # Ignore lines that start in JsDoc since we don't check them properly yet.
            # TODO(robbyw): Support checking JsDoc indentation.
            # Ignore lines that start as multi-line strings since indentation is N/A.
            # Ignore lines that start with operators since we report that already.
            # Ignore lines with tabs since we report that already.
            expected = self._GetAllowableIndentations()
            actual = self._GetActualIndentation(token)

            # Special case comments describing else, case, and default.  Allow them
            # to outdent to the parent block.
            if token_type in Type.COMMENT_TYPES:
                next_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES)
                if next_code and next_code.type == Type.END_BLOCK:
                    next_code = tokenutil.SearchExcept(next_code,
                                                       Type.NON_CODE_TYPES)
                if next_code and next_code.string in (
                'else', 'case', 'default'):
                    # TODO(robbyw): This almost certainly introduces false negatives.
                    expected |= self._AddToEach(expected, -2)

            if actual >= 0 and actual not in expected:
                expected = sorted(expected)
                indentation_errors.append([
                    errors.WRONG_INDENTATION,
                    'Wrong indentation: expected any of {%s} but got %d' % (
                        ', '.join(
                            ['%d' % x for x in expected]), actual),
                    token,
                    Position(actual, expected[0])])
                self._start_index_offset[token.line_number] = expected[
                                                                  0] - actual

        # Add tokens that could increase indentation.
        if token_type == Type.START_BRACKET:
            self._Add(TokenInfo(
                token=token,
                is_block=token.metadata.context.type == Context.ARRAY_LITERAL))

        elif token_type == Type.START_BLOCK or token.metadata.is_implied_block:
            self._Add(TokenInfo(token=token, is_block=True))

        elif token_type in (Type.START_PAREN, Type.START_PARAMETERS):
            self._Add(TokenInfo(token=token, is_block=False))

        elif token_type == Type.KEYWORD and token.string == 'return':
            self._Add(TokenInfo(token))

        elif not token.IsLastInLine() and (
                token.IsAssignment() or token.IsOperator('?')):
            self._Add(TokenInfo(token=token))

        # Handle implied block closes.
        if token.metadata.is_implied_block_close:
            self._PopToImpliedBlock()

        # Add some tokens only if they appear at the end of the line.
        is_last = self._IsLastCodeInLine(token)
        if is_last:
            if token_type == Type.OPERATOR:
                if token.string == ':':
                    if stack and stack[-1].token.string == '?':
                        # When a ternary : is on a different line than its '?', it doesn't
                        # add indentation.
                        if token.line_number == stack[-1].token.line_number:
                            self._Add(TokenInfo(token))
                    elif token.metadata.context.type == Context.CASE_BLOCK:
                        # Pop transient tokens from say, line continuations, e.g.,
                        # case x.
                        #     y:
                        # Want to pop the transient 4 space continuation indent.
                        self._PopTransient()
                        # Starting the body of the case statement, which is a type of
                        # block.
                        self._Add(TokenInfo(token=token, is_block=True))
                    elif token.metadata.context.type == Context.LITERAL_ELEMENT:
                        # When in an object literal, acts as operator indicating line
                        # continuations.
                        self._Add(TokenInfo(token))
                        pass
                    else:
                        # ':' might also be a statement label, no effect on indentation in
                        # this case.
                        pass

                elif token.string != ',':
                    self._Add(TokenInfo(token))
                else:
                    # The token is a comma.
                    if token.metadata.context.type == Context.VAR:
                        self._Add(TokenInfo(token))
                    elif token.metadata.context.type != Context.PARAMETERS:
                        self._PopTransient()

            elif (token.string.endswith('.')
                  and token_type in (Type.IDENTIFIER, Type.NORMAL)):
                self._Add(TokenInfo(token))
            elif token_type == Type.PARAMETERS and token.string.endswith(','):
                # Parameter lists.
                self._Add(TokenInfo(token))
            elif token.IsKeyword('var'):
                self._Add(TokenInfo(token))
            elif token.metadata.is_implied_semicolon:
                self._PopTransient()
        elif token.IsAssignment():
            self._Add(TokenInfo(token))

        return indentation_errors

    def _AddToEach(self, original, amount):
        """Returns a new set with the given amount added to each element.

        Args:
          original: The original set of numbers
          amount: The amount to add to each element

        Returns:
          A new set containing each element of the original set added to the amount.
        """
        return set([x + amount for x in original])

    _HARD_STOP_TYPES = (Type.START_PAREN, Type.START_PARAMETERS,
                        Type.START_BRACKET)

    _HARD_STOP_STRINGS = ('return', '?')

    def _IsHardStop(self, token):
        """Determines if the given token can have a hard stop after it.

        Args:
          token: token to examine

        Returns:
          Whether the token can have a hard stop after it.

        Hard stops are indentations defined by the position of another token as in
        indentation lined up with return, (, [, and ?.
        """
        return (token.type in self._HARD_STOP_TYPES or
                token.string in self._HARD_STOP_STRINGS or
                token.IsAssignment())

    def _GetAllowableIndentations(self):
        """Computes the set of allowable indentations.

        Returns:
          The set of allowable indentations, given the current stack.
        """
        expected = set([0])
        hard_stops = set([])

        # Whether the tokens are still in the same continuation, meaning additional
        # indentation is optional.  As an example:
        # x = 5 +
        #     6 +
        #     7;
        # The second '+' does not add any required indentation.
        in_same_continuation = False

        for token_info in self._stack:
            token = token_info.token

            # Handle normal additive indentation tokens.
            if not token_info.overridden_by and token.string != 'return':
                if token_info.is_block:
                    expected = self._AddToEach(expected, 2)
                    hard_stops = self._AddToEach(hard_stops, 2)
                    in_same_continuation = False
                elif in_same_continuation:
                    expected |= self._AddToEach(expected, 4)
                    hard_stops |= self._AddToEach(hard_stops, 4)
                else:
                    expected = self._AddToEach(expected, 4)
                    hard_stops |= self._AddToEach(hard_stops, 4)
                    in_same_continuation = True

            # Handle hard stops after (, [, return, =, and ?
            if self._IsHardStop(token):
                override_is_hard_stop = (token_info.overridden_by and
                                         self._IsHardStop(
                                             token_info.overridden_by.token))
                if not override_is_hard_stop:
                    start_index = token.start_index
                    if token.line_number in self._start_index_offset:
                        start_index += self._start_index_offset[
                            token.line_number]
                    if (token.type in (
                    Type.START_PAREN, Type.START_PARAMETERS) and
                            not token_info.overridden_by):
                        hard_stops.add(start_index + 1)

                    elif token.string == 'return' and not token_info.overridden_by:
                        hard_stops.add(start_index + 7)

                    elif token.type == Type.START_BRACKET:
                        hard_stops.add(start_index + 1)

                    elif token.IsAssignment():
                        hard_stops.add(start_index + len(token.string) + 1)

                    elif token.IsOperator('?') and not token_info.overridden_by:
                        hard_stops.add(start_index + 2)

        return (expected | hard_stops) or set([0])

    def _GetActualIndentation(self, token):
        """Gets the actual indentation of the line containing the given token.

        Args:
          token: Any token on the line.

        Returns:
          The actual indentation of the line containing the given token.  Returns
          -1 if this line should be ignored due to the presence of tabs.
        """
        # Move to the first token in the line
        token = tokenutil.GetFirstTokenInSameLine(token)

        # If it is whitespace, it is the indentation.
        if token.type == Type.WHITESPACE:
            if token.string.find('\t') >= 0:
                return -1
            else:
                return len(token.string)
        elif token.type == Type.PARAMETERS:
            return len(token.string) - len(token.string.lstrip())
        else:
            return 0

    def _IsFirstNonWhitespaceTokenInLine(self, token):
        """Determines if the given token is the first non-space token on its line.

        Args:
          token: The token.

        Returns:
          True if the token is the first non-whitespace token on its line.
        """
        if token.type in (Type.WHITESPACE, Type.BLANK_LINE):
            return False
        if token.IsFirstInLine():
            return True
        return (token.previous and token.previous.IsFirstInLine() and
                token.previous.type == Type.WHITESPACE)

    def _IsLastCodeInLine(self, token):
        """Determines if the given token is the last code token on its line.

        Args:
          token: The token.

        Returns:
          True if the token is the last code token on its line.
        """
        if token.type in Type.NON_CODE_TYPES:
            return False
        start_token = token
        while True:
            token = token.next
            if not token or token.line_number != start_token.line_number:
                return True
            if token.type not in Type.NON_CODE_TYPES:
                return False

    def _Add(self, token_info):
        """Adds the given token info to the stack.

        Args:
          token_info: The token information to add.
        """
        if self._stack and self._stack[-1].token == token_info.token:
            # Don't add the same token twice.
            return

        if token_info.is_block or token_info.token.type == Type.START_PAREN:
            token_info.overridden_by = (
                tokenutil.GoogScopeOrNoneFromStartBlock(token_info.token))
            index = 1
            while index <= len(self._stack):
                stack_info = self._stack[-index]
                stack_token = stack_info.token

                if stack_info.line_number == token_info.line_number:
                    # In general, tokens only override each other when they are on
                    # the same line.
                    stack_info.overridden_by = token_info
                    if (token_info.token.type == Type.START_BLOCK and
                            (stack_token.IsAssignment() or
                                     stack_token.type in (
                                 Type.IDENTIFIER, Type.START_PAREN))):
                        # Multi-line blocks have lasting overrides, as in:
                        # callFn({
                        #   a: 10
                        # },
                        # 30);
                        # b/11450054. If a string is not closed properly then close_block
                        # could be null.
                        close_block = token_info.token.metadata.context.end_token
                        stack_info.is_permanent_override = close_block and (
                            close_block.line_number != token_info.token.line_number)
                elif (token_info.token.type == Type.START_BLOCK and
                              token_info.token.metadata.context.type == Context.BLOCK and
                          (stack_token.IsAssignment() or
                                   stack_token.type == Type.IDENTIFIER)):
                    # When starting a function block, the override can transcend lines.
                    # For example
                    # long.long.name = function(
                    #     a) {
                    # In this case the { and the = are on different lines.  But the
                    # override should still apply.
                    stack_info.overridden_by = token_info
                    stack_info.is_permanent_override = True
                else:
                    break
                index += 1

        self._stack.append(token_info)

    def _Pop(self):
        """Pops the top token from the stack.

        Returns:
          The popped token info.
        """
        token_info = self._stack.pop()
        if token_info.token.type not in (Type.START_BLOCK, Type.START_BRACKET):
            # Remove any temporary overrides.
            self._RemoveOverrides(token_info)
        else:
            # For braces and brackets, which can be object and array literals, remove
            # overrides when the literal is closed on the same line.
            token_check = token_info.token
            same_type = token_check.type
            goal_type = None
            if token_info.token.type == Type.START_BRACKET:
                goal_type = Type.END_BRACKET
            else:
                goal_type = Type.END_BLOCK
            line_number = token_info.token.line_number
            count = 0
            while token_check and token_check.line_number == line_number:
                if token_check.type == goal_type:
                    count -= 1
                    if not count:
                        self._RemoveOverrides(token_info)
                        break
                if token_check.type == same_type:
                    count += 1
                token_check = token_check.next
        return token_info

    def _PopToImpliedBlock(self):
        """Pops the stack until an implied block token is found."""
        while not self._Pop().token.metadata.is_implied_block:
            pass

    def _PopTo(self, stop_type):
        """Pops the stack until a token of the given type is popped.

        Args:
          stop_type: The type of token to pop to.

        Returns:
          The token info of the given type that was popped.
        """
        last = None
        while True:
            last = self._Pop()
            if last.token.type == stop_type:
                break
        return last

    def _RemoveOverrides(self, token_info):
        """Marks any token that was overridden by this token as active again.

        Args:
          token_info: The token that is being removed from the stack.
        """
        for stack_token in self._stack:
            if (stack_token.overridden_by == token_info and
                    not stack_token.is_permanent_override):
                stack_token.overridden_by = None

    def _PopTransient(self):
        """Pops all transient tokens - i.e. not blocks, literals, or parens."""
        while self._stack and self._stack[-1].is_transient:
            self._Pop()


text:
> Only the **free** all-purpose ones will be showcased here.

---

![](http://1.bp.blogspot.com/-O7BocqJD-wA/UpDpMIb2bqI/AAAAAAAABdw/xt7BvLnVHOw/s1600/aboutme-logo.png)

## [about.me](http://about.me)

> About.me makes it easy for people to learn about you and find your content. Create a free page in minutes with no coding required.

---

![](http://teksocial.com/storage/flavorsme-logo.jpg)

## [Flavors.me](http://flavors.me)

> Flavors.me allows anyone to easily create a beautiful branded website with content from around the internet and Flavors' simple design tools.

---

![](http://www.wired.com/wp-content/uploads/2014/10/Froont%E2%80%94GoogleStore-07.jpg)

## [Froont](https://froont.com/)

> Work in the environment you're designing for – the browser. You have full control over desktop and mobile layouts, which are responsive from the start.

---

![](http://bluemonkeydev.com/wp-content/uploads/2014/08/strikingly-dark-transparent-85e8001d.png)

## [Strikingly](http://strikingly.com)

> Strikingly is the best website builder for anyone to build a gorgeous, mobile-friendly website easily. Quick, simple and stylish. Get started today.

---

![](http://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Tumblr_Logo.svg/2000px-Tumblr_Logo.svg.png)

## [Tumblr](https://www.tumblr.com/)

> Post anything (from anywhere!), customize everything, and find and follow what you love. Create your own Tumblr blog today.

---

![](https://d2aezjsmcp2rsz.cloudfront.net/companylogos/webflow.png)

## [Webflow](https://webflow.com/)

> Webflow is the top drag-and-drop website builder for creating professional responsive websites.

- [Designing an App With Webflow](https://www.bloc.io/tutorials/webflow-tutorial-design-responsive-sites-with-webflow)

---

![](http://aztechbeat.com/wp-content/uploads/2014/06/Weebly-1-700x325.jpg)

## [Weebly](http://weebly.com)

> Weebly makes it surprisingly easy to create a high-quality website, blog or online store. Over 25 million people use Weebly to bring their unique ideas to life.

---

![](http://cloudproxy.sucuri.net/images/wordpress.jpg)

## [Wordpress](http://wordpress.com)

> Create a free website or easily build a blog on WordPress.com. Hundreds of free, customizable, mobile-ready designs and themes. Free hosting and support.


text:
FOUNDATION_EXPORT double Pods_ProcrastyLogger_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_ProcrastyLogger_ExampleVersionString[];


text:
APIKit
======

[![Build Status](https://travis-ci.org/ishkawa/APIKit.svg?branch=master)](https://travis-ci.org/ishkawa/APIKit)
[![codecov](https://codecov.io/gh/ishkawa/APIKit/branch/master/graph/badge.svg)](https://codecov.io/gh/ishkawa/APIKit)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Version](https://img.shields.io/cocoapods/v/APIKit.svg?style=flat)](http://cocoadocs.org/docsets/APIKit)
[![Platform](https://img.shields.io/cocoapods/p/APIKit.svg?style=flat)](http://cocoadocs.org/docsets/APIKit)
[![Swift Package Manager](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager)

APIKit is a type-safe networking abstraction layer that associates request type with response type.

```swift
// SearchRepositoriesRequest conforms to Request protocol.
let request = SearchRepositoriesRequest(query: "swift")

// Session receives an instance of a type that conforms to Request.
Session.send(request) { result in
    switch result {
    case .success(let response):
        // Type of `response` is `[Repository]`,
        // which is inferred from `SearchRepositoriesRequest`.
        print(response)

    case .failure(let error):
        self.printError(error)
    }
}
```

## Requirements

- Swift 5.3 or later
- iOS 9.0 or later
- Mac OS 10.10 or later
- watchOS 2.0 or later
- tvOS 9.0 or later

If you use Swift 2.2 or 2.3, try [APIKit 2.0.5](https://github.com/ishkawa/APIKit/tree/2.0.5).

If you use Swift 4.2 or before, try [APIKit 4.1.0](https://github.com/ishkawa/APIKit/tree/4.1.0).

If you use Swift 5.2 or before, try [APIKit 5.3.0](https://github.com/ishkawa/APIKit/tree/5.3.0).

## Installation

#### [Carthage](https://github.com/Carthage/Carthage)

- Insert `github "ishkawa/APIKit" ~> 5.0` to your Cartfile.
- Run `carthage update`.
- Link your app with `APIKit.framework` in `Carthage/Build`.

#### [CocoaPods](https://github.com/cocoapods/cocoapods)

- Insert `pod 'APIKit', '~> 5.0'` to your Podfile.
- Run `pod install`.

Note: CocoaPods 1.4.0 is required to install APIKit 5.

## Documentation

- [Getting started](Documentation/GettingStarted.md)
- [Defining Request Protocol for Web Service](Documentation/DefiningRequestProtocolForWebService.md)
- [Convenience Parameters and Actual Parameters](Documentation/ConvenienceParametersAndActualParameters.md)

### Advanced Guides

- [Customizing Networking Backend](Documentation/CustomizingNetworkingBackend.md)

### Migration Guides

- [APIKit 3 Migration Guide](Documentation/APIKit3MigrationGuide.md)
- [APIKit 2 Migration Guide](Documentation/APIKit2MigrationGuide.md)