text:
describe('Niten Pupil', function() {
    integration(function() {
        describe('Niten Pupil\'s ability', function() {
            beforeEach(function() {
                this.setupTest({
                    phase: 'dynasty',
                    player1: {
                        inPlay: ['niten-pupil', 'kitsuki-investigator'],
                        conflictDiscard: ['defend-your-honor']
                    },
                    player2: {
                        inPlay: ['mirumoto-raitsugu'],
                        conflictDiscard: ['contingency-plan']
                    }
                });

                this.nitenPupil = this.player1.findCardByName('niten-pupil');
                this.kitsukiInvestigator = this.player1.findCardByName('kitsuki-investigator');
                this.defendYourHonor = this.player1.findCardByName('defend-your-honor');

                this.mirumotoRaitsugu = this.player2.findCardByName('mirumoto-raitsugu');
                this.contingencyPlan = this.player2.findCardByName('contingency-plan');
            });

            it('should trigger when dials are revealed for a duel Niten Pupil is participating in', function() {
                this.advancePhases('conflict');
                this.noMoreActions();
                this.initiateConflict({
                    attackers: [this.nitenPupil],
                    defenders: [this.mirumotoRaitsugu]
                });
                this.player2.clickCard(this.mirumotoRaitsugu);
                this.player2.clickCard(this.nitenPupil);
                this.player1.clickPrompt('1');
                this.player2.clickPrompt('1');
                expect(this.player1).toHavePrompt('Triggered Abilities');
                expect(this.player1).toBeAbleToSelect(this.nitenPupil);
            });

            it('should not trigger when dials are revealed for not a duel', function() {
                this.noMoreActions();
                this.player1.clickPrompt('1');
                this.player2.clickPrompt('1');
                expect(this.player1).not.toHavePrompt('Triggered Abilities');
                expect(this.player1).toHavePrompt('Action Window');
            });

            it('should not trigger when dials are revealed for a duel Niten Pupil is not participating in', function() {
                this.advancePhases('conflict');
                this.noMoreActions();
                this.initiateConflict({
                    attackers: [this.nitenPupil],
                    defenders: [this.mirumotoRaitsugu]
                });
                this.player2.clickCard(this.mirumotoRaitsugu);
                this.player2.clickCard(this.nitenPupil);
                this.player1.clickPrompt('1');
                this.player2.clickPrompt('1');
                expect(this.player1).toHavePrompt('Triggered Abilities');
                expect(this.player1).toBeAbleToSelect(this.nitenPupil);
            });

            it('should not trigger when dials are revealed for a nested duel Niten Pupil is not participating in', function() {
                this.advancePhases('conflict');
                this.player1.moveCard(this.defendYourHonor, 'hand');
                this.player2.moveCard(this.contingencyPlan, 'hand');
                this.noMoreActions();
                this.initiateConflict({
                    attackers: [this.nitenPupil, this.kitsukiInvestigator],
                    defenders: [this.mirumotoRaitsugu]
                });
                this.player2.clickCard(this.mirumotoRaitsugu);
                this.player2.clickCard(this.nitenPupil);
                this.player1.clickPrompt('1');
                this.player2.clickPrompt('1');
                this.player1.clickPrompt('Pass');
                this.player2.clickCard(this.contingencyPlan);
                this.player1.clickCard(this.defendYourHonor);
                this.player1.clickCard(this.kitsukiInvestigator);
                this.player2.clickCard(this.mirumotoRaitsugu);
                this.player1.clickPrompt('2');
                this.player2.clickPrompt('2');
                expect(this.player1).not.toHavePrompt('Triggered Abilities');
                expect(this.player2).toHavePrompt('Contingency Plan');
            });

            it('should double both base skills until the end of the phase', function() {
                this.advancePhases('conflict');
                this.noMoreActions();
                this.initiateConflict({
                    attackers: [this.nitenPupil],
                    defenders: [this.mirumotoRaitsugu]
                });
                this.player2.clickCard(this.mirumotoRaitsugu);
                this.player2.clickCard(this.nitenPupil);
                this.player1.clickPrompt('1');
                this.player2.clickPrompt('1');
                this.player1.clickCard(this.nitenPupil);
                expect(this.nitenPupil.getBaseMilitarySkill()).toBe(4);
                expect(this.nitenPupil.getBasePoliticalSkill()).toBe(4);
                expect(this.getChatLogs(5)).toContain('player1 uses Niten Pupil to double Niten Pupil\'s base military and political skills');
                this.noMoreActions();
                this.player1.clickPrompt('No');
                this.player1.clickPrompt('Don\'t Resolve');
                expect(this.player1).toHavePrompt('Action Window');
                expect(this.nitenPupil.getBaseMilitarySkill()).toBe(4);
                expect(this.nitenPupil.getBasePoliticalSkill()).toBe(4);
                this.advancePhases('fate');
                expect(this.nitenPupil.getBaseMilitarySkill()).toBe(2);
                expect(this.nitenPupil.getBasePoliticalSkill()).toBe(2);
            });
        });
    });
});


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

class C_auth extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		if(!empty($_SESSION['id']))
		{
			redirect(site_url('adm'));
		}
		$this->load->view('Manage/header');
		$this->load->view('Manage/footer');
		$this->load->model('m_admin');
	}

	public function index()
	{
		$this->load->view('Manage/adm_login');
	}

	public function auth()
	{
		if(empty($_SESSION['id'])){
			$data = $this->input->post();
	        $result = $this->m_admin->login($data);
        	if($result['status'] == 'loginfailed'){
        		$status['status'] = 'loginfailed';
				$this->session->set_flashdata('msg','
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Wrong username or password.
');
	 			redirect(site_url('sysladm'));
        	} else if ($result['status'] == 'ok') {
        		$newdata = array(
				        'id'  => $result['id'],
				        'name'  => $result['user'],
				        'role' => $result['role']
				);

				$this->session->set_userdata($newdata);

				$status['status'] = 'ok';
	 			redirect(site_url('adm'));
        	}
	 		echo json_encode($status);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import os
import unittest
import tempfile
import shutil
import yaml

from six.moves import cStringIO

from ooinstall.oo_config import OOConfig, Host, OOConfigInvalidHostError
import ooinstall.openshift_ansible

SAMPLE_CONFIG = """
variant: openshift-enterprise
variant_version: 3.3
version: v2
deployment:
    ansible_ssh_user: root
    hosts:
      - connect_to: master-private.example.com
        ip: 10.0.0.1
        hostname: master-private.example.com
        public_ip: 24.222.0.1
        public_hostname: master.example.com
        roles:
            - master
            - node
      - connect_to: node1-private.example.com
        ip: 10.0.0.2
        hostname: node1-private.example.com
        public_ip: 24.222.0.2
        public_hostname: node1.example.com
        roles:
            - node
      - connect_to: node2-private.example.com
        ip: 10.0.0.3
        hostname: node2-private.example.com
        public_ip: 24.222.0.3
        public_hostname: node2.example.com
        roles:
            - node
    roles:
        master:
        node:
"""

CONFIG_INCOMPLETE_FACTS = """
version: v2
deployment:
    ansible_ssh_user: root
    hosts:
      - connect_to: 10.0.0.1
        ip: 10.0.0.1
        hostname: master-private.example.com
        public_ip: 24.222.0.1
        public_hostname: master.example.com
        roles:
            - master
      - connect_to: 10.0.0.2
        ip: 10.0.0.2
        hostname: 24.222.0.2
        public_ip: 24.222.0.2
        roles:
            - node
      - connect_to: 10.0.0.3
        ip: 10.0.0.3
        roles:
            - node
    roles:
        master:
        node:
"""

CONFIG_BAD = """
variant: openshift-enterprise
version: v2
deployment:
    ansible_ssh_user: root
    hosts:
      - connect_to: master-private.example.com
        ip: 10.0.0.1
        hostname: master-private.example.com
        public_ip: 24.222.0.1
        public_hostname: master.example.com
        roles:
            - master
            - node
      - ip: 10.0.0.2
        hostname: node1-private.example.com
        public_ip: 24.222.0.2
        public_hostname: node1.example.com
        roles:
            - node
      - connect_to: node2-private.example.com
        ip: 10.0.0.3
        hostname: node2-private.example.com
        public_ip: 24.222.0.3
        public_hostname: node2.example.com
        roles:
            - node
    roles:
        master:
        node:
"""

class OOInstallFixture(unittest.TestCase):

    def setUp(self):
        self.tempfiles = []
        self.work_dir = tempfile.mkdtemp(prefix='ooconfigtests')
        self.tempfiles.append(self.work_dir)

    def tearDown(self):
        for path in self.tempfiles:
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)

    def write_config(self, path, config_str):
        """
        Write given config to a temporary file which will be cleaned
        up in teardown.
        Returns full path to the file.
        """
        cfg_file = open(path, 'w')
        cfg_file.write(config_str)
        cfg_file.close()
        return path

class OOConfigTests(OOInstallFixture):

    def test_load_config(self):

        cfg_path = self.write_config(os.path.join(self.work_dir,
            'ooinstall.conf'), SAMPLE_CONFIG)
        ooconfig = OOConfig(cfg_path)

        self.assertEquals(3, len(ooconfig.deployment.hosts))
        self.assertEquals("master-private.example.com", ooconfig.deployment.hosts[0].connect_to)
        self.assertEquals("10.0.0.1", ooconfig.deployment.hosts[0].ip)
        self.assertEquals("master-private.example.com", ooconfig.deployment.hosts[0].hostname)

        self.assertEquals(["10.0.0.1", "10.0.0.2", "10.0.0.3"],
                          [host.ip for host in ooconfig.deployment.hosts])

        self.assertEquals('openshift-enterprise', ooconfig.settings['variant'])
        self.assertEquals('v2', ooconfig.settings['version'])

    def test_load_bad_config(self):

        cfg_path = self.write_config(os.path.join(self.work_dir,
            'ooinstall.conf'), CONFIG_BAD)
        try:
            OOConfig(cfg_path)
            assert False
        except OOConfigInvalidHostError:
            assert True

    def test_load_complete_facts(self):
        cfg_path = self.write_config(os.path.join(self.work_dir,
            'ooinstall.conf'), SAMPLE_CONFIG)
        ooconfig = OOConfig(cfg_path)
        missing_host_facts = ooconfig.calc_missing_facts()
        self.assertEquals(0, len(missing_host_facts))

    # Test missing optional facts the user must confirm:
    def test_load_host_incomplete_facts(self):
        cfg_path = self.write_config(os.path.join(self.work_dir,
            'ooinstall.conf'), CONFIG_INCOMPLETE_FACTS)
        ooconfig = OOConfig(cfg_path)
        missing_host_facts = ooconfig.calc_missing_facts()
        self.assertEquals(2, len(missing_host_facts))
        self.assertEquals(1, len(missing_host_facts['10.0.0.2']))
        self.assertEquals(3, len(missing_host_facts['10.0.0.3']))

    def test_write_config(self):
        cfg_path = self.write_config(os.path.join(self.work_dir,
            'ooinstall.conf'), SAMPLE_CONFIG)
        ooconfig = OOConfig(cfg_path)
        ooconfig.save_to_disk()

        f = open(cfg_path, 'r')
        written_config = yaml.safe_load(f.read())
        f.close()

        self.assertEquals(3, len(written_config['deployment']['hosts']))
        for h in written_config['deployment']['hosts']:
            self.assertTrue('ip' in h)
            self.assertTrue('public_ip' in h)
            self.assertTrue('hostname' in h)
            self.assertTrue('public_hostname' in h)

        self.assertTrue('ansible_ssh_user' in written_config['deployment'])
        self.assertTrue('variant' in written_config)
        self.assertEquals('v2', written_config['version'])

        # Some advanced settings should not get written out if they
        # were not specified by the user:
        self.assertFalse('ansible_inventory_directory' in written_config)

class HostTests(OOInstallFixture):

    def test_load_host_no_ip_or_hostname(self):
        yaml_props = {
            'public_ip': '192.168.0.1',
            'public_hostname': 'a.example.com',
            'master': True
        }
        self.assertRaises(OOConfigInvalidHostError, Host, **yaml_props)

    def test_load_host_no_master_or_node_specified(self):
        yaml_props = {
            'ip': '192.168.0.1',
            'hostname': 'a.example.com',
            'public_ip': '192.168.0.1',
            'public_hostname': 'a.example.com',
        }
        self.assertRaises(OOConfigInvalidHostError, Host, **yaml_props)

    def test_inventory_file_quotes_node_labels(self):
        """Verify a host entry wraps openshift_node_labels value in double quotes"""
        yaml_props = {
            'ip': '192.168.0.1',
            'hostname': 'a.example.com',
            'connect_to': 'a-private.example.com',
            'public_ip': '192.168.0.1',
            'public_hostname': 'a.example.com',
            'new_host': True,
            'roles': ['node'],
            'node_labels': {
                'region': 'infra'
            },

        }

        new_node = Host(**yaml_props)
        inventory = cStringIO()
        # This is what the 'write_host' function generates. write_host
        # has no return value, it just writes directly to the file
        # 'inventory' which in this test-case is a StringIO object
        ooinstall.openshift_ansible.write_host(
            new_node,
            'node',
            inventory,
            schedulable=True)
        # read the value of what was written to the inventory "file"
        legacy_inventory_line = inventory.getvalue()

        # Given the `yaml_props` above we should see a line like this:
        #     openshift_node_labels="{'region': 'infra'}"
        node_labels_expected = '''openshift_node_labels="{'region': 'infra'}"'''  # Quotes around the hash
        node_labels_bad = '''openshift_node_labels={'region': 'infra'}'''  # No quotes around the hash

        # The good line is present in the written inventory line
        self.assertIn(node_labels_expected, legacy_inventory_line)
        # An unquoted version is not present
        self.assertNotIn(node_labels_bad, legacy_inventory_line)


text:
require 'spec_helper'

describe CivicAide::Elections do

  before do
    @client = CivicAide::Client.new("AIzaSyDWJSisG_4Azd6nVJTU5gdKPiKKTCovupY")
  end

  describe "get all elections" do

    let(:info) { @client.elections.all }

    before do
      VCR.insert_cassette 'elections/all', :record => :new_episodes
      @election = info.elections.first
    end

    after do
      VCR.eject_cassette
    end

    it "must parse the response from JSON to Hash" do
      expect(info).to be_a Hash
    end

    it "should have elections" do
      expect(info).to respond_to(:elections)
    end

    it "should have multiple elections" do
      info.elections.should_not be_empty
    end

    it "should have an id" do
      expect(@election.id).to eq("2000")
    end

    it "should have a name" do
      expect(@election.name).to eq("VIP Test Election")
    end

    it "should have an election day" do
      expect(@election.election_day).to eq("2015-06-06")
    end

  end

  describe "get info for specific election" do

    let(:info) { @client.elections(4015).at('4910 Willet Drive, Annandale, VA 22003') }

    before do
      VCR.insert_cassette 'elections/single', :record => :new_episodes
    end

    after do
      VCR.eject_cassette
    end

    it "must parse the response from JSON to Hash" do
      expect(info).to be_a Hash
    end

    it "should have an election" do
      expect(info.election).to be_a Hash
    end

    it "should have an election id" do
      expect(info.election.id).to eq("4015")
    end

    it "should have an election name" do
      expect(info.election.name).to eq("VA State Election")
    end

    it "should have an election day" do
      expect(info.election.election_day).to eq("2013-11-05")
    end

    it "should have normalized input" do
      expect(info).to respond_to(:normalized_input)
    end

    it "should have normalized input hash" do
      expect(info.normalized_input).to be_a Hash
    end

    it "should have normalized input line 1" do
      expect(info.normalized_input.line1).to eq("4910 willet dr")
    end

    it "should have normalized input city" do
      expect(info.normalized_input.city).to eq("annandale")
    end

    it "should have normalized input state" do
      expect(info.normalized_input.state).to eq("VA")
    end

    it "should have normalized input zip" do
      expect(info.normalized_input.zip_code).to eq("22003")
    end

    it "should have contests" do
      expect(info).to respond_to(:contests)
    end

    it "should have contests as array" do
      expect(info.contests).to be_a Array
    end

    it "should have candidates" do
      expect(info.contests[0]).to respond_to(:candidates)
    end

    it "should have candidates array" do
      expect(info.contests[0].candidates).to be_a Array
    end

    it "should have sources" do
      expect(info.contests[0]).to respond_to(:sources)
    end

    it "should have sources array" do
      expect(info.contests[0].sources).to be_a Array
    end

  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Contact__c</name>
    <help>この言語を話す個人。</help>
    <relationshipLabel>取引先責任者の言語</relationshipLabel>
    <label>取引先責任者</label>
</CustomFieldTranslation>


text:
$('#json, #schema').on('click', function(e){
  $(e.target).siblings().removeClass('active');
  $(e.target).addClass('active');
  $('.view').addClass('hidden');
  $('.view_'+$(e.target).attr('id')).removeClass('hidden');
  $('.target').removeClass('hidden');

  $('#editor').addClass('hidden');
  setSchema(forms[form]);
});
$('#cobler').on('click', function(e) {
  $(e.target).siblings().removeClass('active');
  $(e.target).addClass('active');
  $('.view, .target').addClass('hidden');
  $('.view_result, .view_source, #editor').removeClass('hidden');

    if(typeof cb === 'undefined'){
      // cb = new cobler({target: '#editor', types: ['form']});

      cb = new Cobler({formTarget: $('#form'), targets: [document.getElementById('editor')], items: [[]]})
      list = document.getElementById('sortableList');
      cb.addSource(list);
      cb.on('activate', function(){
        if(list.className.indexOf('hidden') == -1){
          list.className += ' hidden';
        }
      })
      cb.on('deactivate', function(){
        list.className = list.className.replace('hidden', '');
      })
      document.getElementById('sortableList').addEventListener('click', function(e) {
        cb.collections[0].addItem(e.target.dataset.type);
      })
      cb.on("change", function(){
        if(typeof forms[form] !== 'undefined' && form !== 'builder'){
          $.extend(forms[form], {fields: cb.toJSON()[0]});
        }else{

          $.extend(forms[form], {fields: cb.toJSON()[0]});
          $.jStorage.set('form', JSON.stringify(forms[form], undefined, "\t"));
        }
      })

    }

    if(typeof forms[form] !== 'undefined'){
      var temp = $.extend(true, {}, forms[form]);
      for(var i in temp.fields){

        temp.fields[i] = Berry.normalizeItem(Berry.processOpts(temp.fields[i]), i);
        switch(temp.fields[i].type) {
          case "select":
          case "radio":
            temp.fields[i].widgetType = 'select';
            break;
          case "checkbox":
            temp.fields[i].widgetType = 'checkbox';
            break;
          default:
            temp.fields[i].widgetType = 'textbox';
        }

      }

      list.className = list.className.replace('hidden', '');
      cb.collections[0].load(temp.fields);
    }else{
      // cb.load(JSON.parse(($.jStorage.get('form') || "{}")));

      cb.collections[0].load(JSON.parse(($.jStorage.get('form') || "{}")));
    }

});

document.addEventListener('DOMContentLoaded', function(){

  editor = ace.edit("schema_editor");
  editor.getSession().setMode("ace/mode/javascript");
  editor.getSession().setTabSize(2);
  editor.getSession().on('change', function(e) {
    try {
      forms[form] = JSON.parse(editor.getValue());
      for(var i in Berry.instances){
        Berry.instances[i].destroy();
      }
      $('.target').berry(
        $.extend({autoFocus: false, actions: ['save'], name: 'myForm', attributes: QueryStringToHash(document.location.hash.substr(1) || "") }, forms[form] ) )
      .delay('change', function(){
        $('.result').html("<pre>"+JSON.stringify(this.toJSON(), undefined, "\t")+"</pre>");
      }, true)
      .on('save', function(){
        if(this.validate()) { location.hash = '#'+$.param(this.toJSON());}}
      );
    } catch (e) {
      return false;
    }
  });

  forms['builder'] = JSON.parse(($.jStorage.get('form') || "{}"));
  for(var i in forms['builder']){
    delete forms['builder'][i].widgetType;
  }

  form = (urlParams['demo'] || 'example');

  setSchema(forms[form])
});

function setSchema(obj){
  forms[form] = obj;
  for(var i in forms[form].fields){
    delete forms[form].fields[i].widgetType;
  }
  editor.setValue(JSON.stringify(forms[form], undefined, "\t"));
}

//data
forms = {
  "auto": {
    "fields": {
      "Text": {},
      "Text 2": "",
      "Color": "color",
      "Options 1": ["hello"],
      "Options 2": ["hello","goodbye"],
      "Options 3": ["hello", "more","Another", "dasdf"],
      "Options 5": ["hello", "more","Another", "final","past"],
      "Is?": {"type": "checkbox"}
    }
  },
  "nonfields": {
    "attributes":{"name": "John Doe", "candy": "Other"},
    "inline": true,
    "fields": [
      {
        "label": "Name"
      },
      {
        "label": "Title"
      },
      {
        "label": "Favorite Candy",
        "name": "candy",
        "type": "select",
        "value": "",
        "choices": [
          "Lolipops",
          "Chocolate",
          "Other"
        ]
      }
    ]
  },
  "duplicate": {
    "fields": [
      {
        "label": "Name"
      },
      {
        "label": "Title"
      },
      {"name": "fc_container", "legend": "Favorite Candies", "fields": {
        "fc": {"label":false, "multiple": {"duplicate": true, "max": 4, "min": 2}, "fields": {
          "Candy Type": {}
        }
      }}}
    ]
  },
  "conditional": {
    "fields": [
      {
        "label": "Name"
      },
      {
        "label": "Title"
      },
      {
        "label": "Favorite Candy",
        "name": "candy",
        "choices": [
          "Lolipops",
          "Chocolate",
          "Other"
        ]
      },
      {"label": "Reason", "type": "textarea", "show": {"matches": {"name": "candy", "value": "Chocolate"}}}
    ]
  },
  "basic": {
    "fields": [
      {
        "label": "Name"
      },
      {
        "label": "Job Title",
        "name": "title"
      },
      {
        "label": "Favorite State",
        "choices": "data/states.json"
      }
    ]
  },
  "example": {
    "attributes": {"first_name": "John", "name_last": "Doe"},
    "fields":[
      {"label": "First Name"},
      {"label": "Last Name", "name": "name_last"},
      {"label": "Age", "type": "number"},
      {"label": "Favorite Color", "type": "color"}
    ]
  }
}

/*utils*/

var urlParams;
(window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

var QueryStringToHash = function QueryStringToHash  (query) {
  var query_string = {};
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    pair[0] = decodeURIComponent(pair[0]);
    pair[1] = decodeURIComponent((pair[1] || "").split('+').join(' '));
      // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = pair[1];
      // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
      // If third or later entry with this name
    } else {
      query_string[pair[0]].push(pair[1]);
    }
  }
  return query_string;
};


text:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';

import { InputCourseDataModule } from '../shared/input-course-data';

import { CourseCreateComponent } from './course-create.component';

@NgModule({
    declarations: [
        CourseCreateComponent],
    imports: [
        RouterModule.forChild([]),
        CommonModule,
        ReactiveFormsModule,
        InputCourseDataModule],
    exports: [
        CourseCreateComponent]
})
export class CourseCreateModule {
    constructor() { }
}


text:
//
//  XMGModelOperationTool.h
//  XMGSQLite
//
//  Created by 王顺子 on 16/11/23.
//  Copyright © 2016年 王顺子. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol XMGModelOperationToolDelegate <NSObject>

@optional
- (NSArray *)ignoreColumn;

@required
- (NSString *)primaryKey;

@end

@interface XMGModelOperationTool : NSObject

+ (BOOL)createTableWithModelClass: (Class)modelClass withUserID: (NSString *)userID;
+ (BOOL)dropTableWithModelClass: (Class)modelClass withUserID: (NSString *)userID;
/**
 根据模型对应的类, 创建表格, 然后插入数据, 如果发现该条数据的主键已经存在, 则执行更新操作

 @param model 模型

 @return 是否保存/更新成功
 */
+ (BOOL)saveModel: (id)model  withUserID: (NSString *)userID;

/**
 根据主键, 删除这个模型

 @param model 模型

 @return 是否操作成功
 */
+ (BOOL)deleteModel: (id)model  withUserID: (NSString *)userID;
+ (BOOL)deleteModels: (Class)modelClass whereColumnName: (NSString *)column isValue: (id)value  withUserID: (NSString *)userID;
+ (BOOL)deleteModels: (Class)modelClass withCondition: (NSString *)whereSQL withUserID: (NSString *)userID;

/**
 查询

 */
+ (NSArray *)queryModels: (Class)modelClass whereColumnName: (NSString *)column isValue: (id)value  withUserID: (NSString *)userID;
+ (NSArray *)queryModels:(Class)modelClass withCondition: (NSString *)condition withUserID: (NSString *)userID;

+ (NSArray *)queryModelsWithSql:(NSString *)sql withUserID:(NSString *)userID;

@end


text:
Originally published: 2003-06-05 05:51:52
Last updated: 2003-09-24 17:24:43
Author: Tim Lesher

A thread pool class that takes arbitrary callables as work units, and supports callbacks when the work unit is complete.


text:
provides 'cpu'

cpu Mash.new
cpu[:real] = from('sysctl -n hw.physicalcpu').to_i
cpu[:total] = from('sysctl -n hw.logicalcpu').to_i


text:
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.extensions.restapi;

/**
 * Any type of view, see {@link RestReadView} for reads, {@link RestModifyView}
 * for updates, and {@link RestCollection} for nested collections.
 */
public interface RestView<R extends RestResource> {
}


text:
require 'spec_helper'

describe 'opscenter-datastax-agent' do

  it 'installs, enables & runs the agent' do
    expect(package 'opscenter').to be_installed
    expect(service 'opscenterd').to be_enabled
    expect(service 'opscenterd').to be_running
  end

end


text:
#include "config.h"
#include "core/html/forms/ColorInputType.h"

#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "bindings/core/v8/ScriptController.h"
#include "core/CSSPropertyNames.h"
#include "core/InputTypeNames.h"
#include "core/events/MouseEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLDataListElement.h"
#include "core/html/HTMLDataListOptionsCollection.h"
#include "core/html/HTMLDivElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLOptionElement.h"
#include "core/page/Chrome.h"
#include "core/rendering/RenderView.h"
#include "platform/ColorChooser.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/UserGestureIndicator.h"
#include "platform/graphics/Color.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"

namespace blink {

using namespace HTMLNames;

// Upper limit of number of datalist suggestions shown.
static const unsigned maxSuggestions = 1000;
// Upper limit for the length of the labels for datalist suggestions.
static const unsigned maxSuggestionLabelLength = 1000;

static bool isValidColorString(const String& value)
{
    if (value.isEmpty())
        return false;
    if (value[0] != '#')
        return false;

    // We don't accept #rgb and #aarrggbb formats.
    if (value.length() != 7)
        return false;
    Color color;
    return color.setFromString(value) && !color.hasAlpha();
}

PassRefPtrWillBeRawPtr<InputType> ColorInputType::create(HTMLInputElement& element)
{
    return adoptRefWillBeNoop(new ColorInputType(element));
}

ColorInputType::~ColorInputType()
{
    endColorChooser();
}

void ColorInputType::countUsage()
{
    countUsageIfVisible(UseCounter::InputTypeColor);
}

bool ColorInputType::isColorControl() const
{
    return true;
}

const AtomicString& ColorInputType::formControlType() const
{
    return InputTypeNames::color;
}

bool ColorInputType::supportsRequired() const
{
    return false;
}

String ColorInputType::fallbackValue() const
{
    return String("#000000");
}

String ColorInputType::sanitizeValue(const String& proposedValue) const
{
    if (!isValidColorString(proposedValue))
        return fallbackValue();

    return proposedValue.lower();
}

Color ColorInputType::valueAsColor() const
{
    Color color;
    bool success = color.setFromString(element().value());
    ASSERT_UNUSED(success, success);
    return color;
}

void ColorInputType::createShadowSubtree()
{
    ASSERT(element().shadow());

    Document& document = element().document();
    RefPtrWillBeRawPtr<HTMLDivElement> wrapperElement = HTMLDivElement::create(document);
    wrapperElement->setShadowPseudoId(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
    RefPtrWillBeRawPtr<HTMLDivElement> colorSwatch = HTMLDivElement::create(document);
    colorSwatch->setShadowPseudoId(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
    wrapperElement->appendChild(colorSwatch.release());
    element().userAgentShadowRoot()->appendChild(wrapperElement.release());

    element().updateView();
}

void ColorInputType::setValue(const String& value, bool valueChanged, TextFieldEventBehavior eventBehavior)
{
    InputType::setValue(value, valueChanged, eventBehavior);

    if (!valueChanged)
        return;

    element().updateView();
    if (m_chooser)
        m_chooser->setSelectedColor(valueAsColor());
}

void ColorInputType::handleDOMActivateEvent(Event* event)
{
    if (element().isDisabledFormControl() || !element().renderer())
        return;

    if (!UserGestureIndicator::processingUserGesture())
        return;

    Chrome* chrome = this->chrome();
    if (chrome && !m_chooser)
        m_chooser = chrome->createColorChooser(element().document().frame(), this, valueAsColor());

    event->setDefaultHandled();
}

void ColorInputType::closePopupView()
{
    endColorChooser();
}

bool ColorInputType::shouldRespectListAttribute()
{
    return true;
}

bool ColorInputType::typeMismatchFor(const String& value) const
{
    return !isValidColorString(value);
}

void ColorInputType::didChooseColor(const Color& color)
{
    if (element().isDisabledFormControl() || color == valueAsColor())
        return;
    element().setValueFromRenderer(color.serialized());
    element().updateView();
    element().dispatchFormControlChangeEvent();
}

void ColorInputType::didEndChooser()
{
    m_chooser.clear();
}

void ColorInputType::endColorChooser()
{
    if (m_chooser)
        m_chooser->endChooser();
}

void ColorInputType::updateView()
{
    HTMLElement* colorSwatch = shadowColorSwatch();
    if (!colorSwatch)
        return;

    colorSwatch->setInlineStyleProperty(CSSPropertyBackgroundColor, element().value());
}

HTMLElement* ColorInputType::shadowColorSwatch() const
{
    ShadowRoot* shadow = element().userAgentShadowRoot();
    return shadow ? toHTMLElement(shadow->firstChild()->firstChild()) : 0;
}

IntRect ColorInputType::elementRectRelativeToRootView() const
{
    return element().document().view()->contentsToRootView(element().pixelSnappedBoundingBox());
}

Color ColorInputType::currentColor()
{
    return valueAsColor();
}

bool ColorInputType::shouldShowSuggestions() const
{
    return element().fastHasAttribute(listAttr);
}

Vector<ColorSuggestion> ColorInputType::suggestions() const
{
    Vector<ColorSuggestion> suggestions;
    HTMLDataListElement* dataList = element().dataList();
    if (dataList) {
        RefPtrWillBeRawPtr<HTMLDataListOptionsCollection> options = dataList->options();
        for (unsigned i = 0; HTMLOptionElement* option = options->item(i); i++) {
            if (!element().isValidValue(option->value()))
                continue;
            Color color;
            if (!color.setFromString(option->value()))
                continue;
            ColorSuggestion suggestion(color, option->label().left(maxSuggestionLabelLength));
            suggestions.append(suggestion);
            if (suggestions.size() >= maxSuggestions)
                break;
        }
    }
    return suggestions;
}

} // namespace blink


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../">
  <title data-ice="title">BeaconEvent | @3846masa/linebot | ESDoc API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

<link data-ice="userStyle" rel="stylesheet" href="user/css/0-styles.css">

  Home
  Manual
  Reference
  Source

  Repository

    <input class="search-input">

TLineBotConfig

TLineProfile

TRectangle

TSize

EEventEmitter2

EExpress.Application

Ehttp.Server

Estream.Readable

LineActions
CImagemapAction

CImagemapMessageAction

CImagemapURIAction

CTemplateAction

CTemplateMessageAction

CTemplatePostbackAction

CTemplateURIAction

LineBot
CLineBot

LineEvents
CBeaconEvent

CFollowEvent

CJoinEvent

CLeaveEvent

CLineEvent

CMessageEvent

CPostbackEvent

CReplyableEvent

CUnfollowEvent

LineMessages
CAudioMessage

CImageMessage

CImagemapMessage

CLineMessage

CLocationMessage

CStickerMessage

CTemplateMessage

CTextMessage

CVideoMessage

LineSources
CGroupSource

CLineSource

CRoomSource

CUserSource

LineTemplates
CTemplateButtons

CTemplateCarousel

CTemplateColumn

CTemplateComponent

CTemplateConfirm

import {BeaconEvent} from '@3846masa/linebot/lib/LineEvents'

  public
  class

  | source

BeaconEvent

Extends:

LineEvent → ReplyableEvent → BeaconEvent

See:

https://devdocs.line.me/en/#beacon-event

Member Summary

Public Members

      public

           beacon: Object

Beacon data

Inherited Summary

 From class LineEvent

      public

           source: LineSource

Object which contains the source of the event

      public

           timestamp: Date

Time of the event in milliseconds

      public

           type: string

Identifier for the type of event

 From class ReplyableEvent

      public

           replyToken: string

Token for replying to this event

      public

           reply(msg: LineMessage[]  |  LineMessage  |  any): Promise<void, Error>

Respond to events from users, groups, and rooms.

Public Members

    public

    beacon: Object

      source

Beacon data

Properties:

Name	Type	Attribute	Description

      beacon.hwid
      string

Hardware ID of the beacon that was detected

      beacon.type
      string

Type of beacon event

  Generated by ESDoc(0.4.8)


text:
module Behave
  # The #behaviors collection of the subject class is populated by instances of Behave::Behavior.
  # Each such behavior has a relationship to a Behave::Decorator instance with the same name, registered in the repository (registered_behaviors hash).
  # A Behave::Decorator instance has a Behave::Decorator::Configuration object that knows how to configure the behavior
  # for a Class (i.e in a given context).

  class Decorator
    autoload_modules :Configuration

    attr_accessor :name
    attr_accessor :configuration_class

    def initialize name
      @name = name
    end

    def internal_api name
    end

    def public_api name
    end

    def configuration_class
      @configuration_class || Behave::Decorator::Configuration
    end

    def decorate subject_class
      create_behavior_for(subject_class).apply!
    end

    def create_behavior_for subject_class
      Behave::Behavior.new name, subject_class, configuration_class
    end
  end
end


text:
<TITLE>The RtAudio Home Page</TITLE>
<LINK HREF="doxygen.css" REL="stylesheet" TYPE="text/css">
<LINK REL="SHORTCUT ICON" HREF="http://www.music.mcgill.ca/~gary/favicon.ico">

Home   Class/Enum List   File List   Compound Members

Class Index

D | R | S

  D

  R

	RtError   	RtAudio::StreamOptions   	RtAudio::StreamParameters

RtAudio::DeviceInfo   	RtAudio

  S

D | R | S

  ©2001-2010 Gary P. Scavone, McGill University. All Rights Reserved.
Maintained by Gary P. Scavone.


text:
/* $Id: cppunit_proxy.h 2221 2006-03-27 20:20:34Z dums $ */

#ifndef _CPPUNITPROXYINTERFACE_H_
#define _CPPUNITPROXYINTERFACE_H_

/*
 * STLport specific
 */
#if !defined (CPPUNIT_MINI_USE_EXCEPTIONS) && \
    (!defined (STLPORT) || defined (_STLP_USE_EXCEPTIONS))
#  define CPPUNIT_MINI_USE_EXCEPTIONS
#endif

#include "cppunit_mini.h"

#endif


text:
id: bad87fee1348bd9aedf08815
title: Створіть круглі зображення з радіусом, що межує
challengeType: 0
videoUrl: 'https://scrimba.com/c/c2MvrcB'
forumTopicId: 18229
dashedName: make-circular-images-with-a-border-radius
---

# --description--

В додаток до пікселів, ви також можете вказати `border-radius`, використовуючи відсоткові відношення.

# --instructions--

Задайте світлину з котом `border-radius` на `50%`.

# --hints--

Ваше зображення має радіус, що межує з `50%`, роблячи його при цьому ідеально круглим.

```js
assert(parseInt($('img').css('border-top-left-radius')) > 48);
```

Значення `border-radius` повинне використовувати відсоткове відношення значення `50%`.

```js
assert(code.match(/50%/g));
```

# --seed--

## --seed-contents--

```html
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
  .red-text {
    color: red;
  }

  h2 {
    font-family: Lobster, monospace;
  }

  p {
    font-size: 16px;
    font-family: monospace;
  }

  .thick-green-border {
    border-color: green;
    border-width: 10px;
    border-style: solid;
    border-radius: 10px;
  }

  .smaller-image {
    width: 100px;
  }
</style>

<h2 class="red-text">CatPhotoApp</h2>
<main>
  <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img class="smaller-image thick-green-border" src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <div>
    <p>Things cats love:</p>
    <ul>
      <li>cat nip</li>
      <li>laser pointers</li>
      <li>lasagna</li>
    </ul>
    <p>Top 3 things cats hate:</p>
    <ol>
      <li>flea treatment</li>
      <li>thunder</li>
      <li>other cats</li>
    </ol>
  </div>

  <form action="https://freecatphotoapp.com/submit-cat-photo">
    <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
    <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
    <label><input type="checkbox" name="personality" checked> Loving</label>
    <label><input type="checkbox" name="personality"> Lazy</label>
    <label><input type="checkbox" name="personality"> Energetic</label><br>
    <input type="text" placeholder="cat photo URL" required>
    <button type="submit">Submit</button>
  </form>
</main>
```

# --solutions--

```html
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
  .red-text {
    color: red;
  }

  h2 {
    font-family: Lobster, monospace;
  }

  p {
    font-size: 16px;
    font-family: monospace;
  }

  .thick-green-border {
    border-color: green;
    border-width: 10px;
    border-style: solid;
    border-radius: 10px;
  }

  .smaller-image {
    width: 100px;
    border-radius: 50%;
  }
</style>

<h2 class="red-text">CatPhotoApp</h2>
<main>
  <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img class="smaller-image thick-green-border" src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <div>
    <p>Things cats love:</p>
    <ul>
      <li>cat nip</li>
      <li>laser pointers</li>
      <li>lasagna</li>
    </ul>
    <p>Top 3 things cats hate:</p>
    <ol>
      <li>flea treatment</li>
      <li>thunder</li>
      <li>other cats</li>
    </ol>
  </div>

  <form action="https://freecatphotoapp.com/submit-cat-photo">
    <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
    <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
    <label><input type="checkbox" name="personality" checked> Loving</label>
    <label><input type="checkbox" name="personality"> Lazy</label>
    <label><input type="checkbox" name="personality"> Energetic</label><br>
    <input type="text" placeholder="cat photo URL" required>
    <button type="submit">Submit</button>
  </form>
</main>
```


text:
package com.kk.taurus.avplayer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.kk.taurus.avplayer.ui.InputUrlPlayActivity;
import com.kk.taurus.avplayer.ui.MultiPlayActivity;
import com.kk.taurus.avplayer.ui.MusicPlayActivity;
import com.kk.taurus.avplayer.ui.RecyclerBaseVideoActivity;
import com.kk.taurus.avplayer.ui.ViewPagerPlayActivity;
import com.kk.taurus.avplayer.ui.listplay.MultiListActivity;
import com.kk.taurus.avplayer.ui.ShareAnimationActivityA;
import com.kk.taurus.playerbase.config.PlayerConfig;
import com.kk.taurus.playerbase.entity.DecoderPlan;

import com.kk.taurus.avplayer.ui.listplay.ListPlayActivity;
import com.kk.taurus.avplayer.ui.BaseVideoViewActivity;
import com.kk.taurus.avplayer.ui.window.FloatWindowActivity;
import com.kk.taurus.avplayer.ui.window.WindowVideoViewActivity;

public class HomeActivity extends AppCompatActivity {

    private TextView mInfo;
    private Toolbar mToolBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        mToolBar = findViewById(R.id.id_toolbar);
        mInfo = findViewById(R.id.tv_info);

        setSupportActionBar(mToolBar);

        updateDecoderInfo();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.switchIjkPlayer:
                PlayerConfig.setDefaultPlanId(App.PLAN_ID_IJK);
                updateDecoderInfo();
                break;
            case R.id.switchMediaPlayer:
                PlayerConfig.setDefaultPlanId(PlayerConfig.DEFAULT_PLAN_ID);
                updateDecoderInfo();
                break;
            case R.id.switchExoPlayer:
                PlayerConfig.setDefaultPlanId(App.PLAN_ID_EXO);
                updateDecoderInfo();
                break;
            case R.id.inputUrlPlay:
                intentTo(InputUrlPlayActivity.class);
                break;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateDecoderInfo();
    }

    private void updateDecoderInfo() {
        DecoderPlan defaultPlan = PlayerConfig.getDefaultPlan();
        mInfo.setText("当前解码方案为:" + defaultPlan.getDesc());
    }

    public void useBaseVideoViewWithRecycler(View view){
        intentTo(RecyclerBaseVideoActivity.class);
    }

    public void useBaseVideoView(View view){
        intentTo(BaseVideoViewActivity.class);
    }

    public void useWindowVideoView(View view){
        intentTo(WindowVideoViewActivity.class);
    }

    public void useFloatWindow(View view){
        intentTo(FloatWindowActivity.class);
    }

    public void multiVideoPlay(View view){
        intentTo(MultiPlayActivity.class);
    }

    public void musicPlay(View view){
        intentTo(MusicPlayActivity.class);
    }

    public void viewPagerPlay(View view){
        intentTo(ViewPagerPlayActivity.class);
    }

    public void singleListPlay(View view){
        intentTo(ListPlayActivity.class);
    }

    public void multiListPlay(View view){
        intentTo(MultiListActivity.class);
    }

    public void shareAnimationVideos(View view){
        intentTo(ShareAnimationActivityA.class);
    }

    private void intentTo(Class<? extends Activity> cls){
        Intent intent = new Intent(getApplicationContext(), cls);
        startActivity(intent);
    }
}


text:
"""Runs characterization tests for XLS IR binary operations.

A more-or-less simple driver for LecCharacterizer.Run; creates test case protos
and feeds them (and other config info) into a LecCharacterizer object.
"""

from absl import app
from absl import flags

from google.protobuf import text_format
from xls.common import gfile
from xls.ir import op_pb2
from xls.ir import xls_type_pb2
from xls.solvers.python import lec_characterizer as lc_mod
from xls.solvers.python import lec_characterizer_pb2 as lc_pb2
from xls.solvers.python import z3_lec

flags.DEFINE_string(
    'cell_library_textproto_path', None,
    'Path to the cell library [as a text-format proto] '
    'to use to define the netlist.')
flags.DEFINE_integer(
    'runs_per_type', 8, 'The number of tests to run per set of input types. '
    'If a results file already has at least this many samples '
    'for a set of input types, then no more will be run.')
flags.DEFINE_string('op', None, 'The operator to characterize.')
flags.DEFINE_string(
    'results_path', None,
    'Path at which to write the results. If this file already '
    'exists, new results will be appended there (as '
    'text-format protos.')
flags.DEFINE_string(
    'synthesis_server_address', None,
    'hostname:port on which a synthesis server is running '
    '(to convert generated IR into a netlist).')
flags.DEFINE_list(
    'widths', [], 'Comma-separated list of bit widths to test. Each width will '
    'be applied to the input and output args from each operator.')

flags.mark_flag_as_required('cell_library_textproto_path')
flags.mark_flag_as_required('op')
flags.mark_flag_as_required('results_path')
flags.mark_flag_as_required('synthesis_server_address')
FLAGS = flags.FLAGS

def _save_results(results: lc_pb2.LecTiming) -> None:
  """Callback to save the results proto after every LEC."""
  with gfile.open(FLAGS.results_path, 'w') as fd:
    fd.write(text_format.MessageToString(results))

def main(argv):
  if len(argv) > 3:
    raise app.UsageError('Too many command-line arguments.')

  # Read in the results file to see what configs to test.
  results = lc_pb2.LecTiming()
  if FLAGS.results_path and gfile.exists(FLAGS.results_path):
    with gfile.open(FLAGS.results_path, 'r') as fd:
      results = text_format.ParseLines(fd, lc_pb2.LecTiming())

  with gfile.open(FLAGS.cell_library_textproto_path, 'r') as fd:
    cell_library_textproto = fd.read()

  lc = lc_mod.LecCharacterizer(FLAGS.synthesis_server_address)

  for width in FLAGS.widths:
    bits_type = xls_type_pb2.TypeProto(
        type_enum=xls_type_pb2.TypeProto.BITS, bit_count=int(width))

    function_type = xls_type_pb2.FunctionTypeProto()
    function_type.parameters.add().CopyFrom(bits_type)
    function_type.parameters.add().CopyFrom(bits_type)
    function_type.return_type.CopyFrom(bits_type)

    test_case = None
    for result_case in results.test_cases:
      # Find or create a matching test case for this function type.
      if result_case.function_type == function_type:
        test_case = result_case

    if test_case is None:
      test_case = results.test_cases.add()
      test_case.function_type.CopyFrom(function_type)

    runs_left = FLAGS.runs_per_type - len(test_case.exec_times_us)
    if runs_left > 0:
      lc.run(results, op_pb2.OpProto.Value(FLAGS.op), function_type,
             int(runs_left), cell_library_textproto, z3_lec.run, _save_results)

if __name__ == '__main__':
  app.run(main)


text:
module Moneta
  module Api
    module Responses
      # Ответ на запрос перевода денежных средств.
      # Money transfer registration response.
      class TransferResponse < Types::TransactionResponseType; end
    end
  end
end


text:
import { IHandler, IMiddleware, IMiddlewareMap } from './types';

const ALL_KEY = '*';

export default class Middleware implements IMiddleware {

  private middleware: IMiddlewareMap = {};

  public addMiddleware(action: string | IHandler, middleware?: IHandler) {
    const actionKey = typeof action === 'string' ? action : ALL_KEY;
    const handler = typeof action === 'string' ? middleware : action;
    this.middleware[actionKey] = (this.middleware[actionKey] || []);
    this.middleware[actionKey].push(handler);
  }

  public getAllMiddleware(action: string): IHandler[] {
    let middleware = [];

    if (this.middleware[ALL_KEY]) {
      middleware = middleware.concat(this.middleware[ALL_KEY]);
    }

    if (this.middleware[action]) {
      middleware = middleware.concat(this.middleware[action]);
    }

    return middleware;
  }

}


text:
==========================
NumPy 1.15.0 Release Notes
==========================

Highlights
==========

* NumPy has switched to pytest for testing.

New functions
=============

* `np.gcd` and `np.lcm`, to compute the greatest common divisor and least
  common multiple.
* `np.ma.stack`, the `np.stack` array-joining function generalized to masked
  arrays.
* ``quantile`` function, an interface to ``percentile`` without factors of 100
* ``nanquantile`` function, an interface to ``nanpercentile`` without factors
  of 100

* `np.printoptions`, a context manager that sets print options temporarily
  for the scope of the ``with`` block::

    >>> with np.printoptions(precision=2):
    ...     print(np.array([2.0]) / 3)
    [0.67]

* `np.histogram_bin_edges`, a function to get the edges of the bins used by a histogram
  without needing to calculate the histogram.

* `npy_get_floatstatus_barrier`` and ``npy_clear_floatstatus_barrier`` have been added to
  deal with compiler optimization changing the order of operations. See below for details.

Deprecations
============

* Aliases of builtin `pickle` functions are deprecated, in favor of their
  unaliased ``pickle.<func>`` names:

  * `np.loads`
  * `np.core.numeric.load`
  * `np.core.numeric.loads`
  * `np.ma.loads`, `np.ma.dumps`
  * `np.ma.load`, `np.ma.dump` - these functions already failed on python 3,
    when called with a string.

* Multidimensional indexing with anything but a tuple is
  deprecated. This means that code such as ``ind = [slice(None), 0]``,
  ``arr[[slice(None), 0]]`` should be changed to ``arr[tuple(ind)]``. This is
  necessary to avoid ambiguity in expressions such as ``arr[[[0, 1], [0, 1]]]``
  which currently is interpreted as ``arr[array([0, 1]), array([0, 1])]``.
  In future, this will be interpreted as ``arr[array([[0, 1], [0, 1]])]``.

* Direct imports from the following modules is deprecated. All testing related
  imports should come from `numpy.testing`.
  * `np.testing.utils`
  * `np.testing.decorators`
  * `np.testing.nosetester`
  * `np.testing.noseclasses`
  * `np.core.umath_tests`

* Giving a generator to `np.sum` is now deprecated. This was undocumented, but
  worked. Previously, it would calculate the sum of the generator expression.
  In the future, it might return a different result. Use `np.sum(np.from_iter(generator))`
  or the built-in Python `sum` instead.

* Users of the C-API should call ``PyArrayResolveWriteBackIfCopy`` or
  ``PyArray_DiscardWritbackIfCopy`` on any array with the ``WRITEBACKIFCOPY``
  flag set, before the array is deallocated. A deprecation warning will be
  emitted if those calls are not used when needed.

* Users of ``nditer`` should use the nditer object as a context manager
  anytime one of the iterator operands is writeable, so that numpy can
  manage writeback semantics, or should call ``it.close()``. A
 `RuntimeWarning` will be emitted otherwise in these cases. Users of the C-API
  should call ``NpyIter_Close`` before ``NpyIter_Deallocate``.

* The ``normed`` argument of ``np.histogram``, deprecated long ago in 1.6.0,
  now emits a ``DeprecationWarning``.

Future Changes
==============

Compatibility notes
===================

The ``NpzFile`` returned by ``np.savez`` is now a `collections.abc.Mapping`
---------------------------------------------------------------------------
This means it behaves like a readonly dictionary, and has a new ``.values()``
method and ``len()`` implementation.

On python 3, this means that ``.iteritems()``, ``.iterkeys()`` have been
deprecated, and ``.keys()`` and ``.items()`` now return views and not lists.
This is consistent with how the builtin ``dict`` type changed between python 2
and python 3.

Under certain conditions, nditer must be used in a context manager
------------------------------------------------------------------
When using an nditer with the ``"writeonly"`` or ``"readwrite"`` flags, there
are some circumstances where nditer doesn't actually give you a view onto the
writable array. Instead, it gives you a copy, and if you make changes to the
copy, nditer later writes those changes back into your actual array. Currently,
this writeback occurs when the array objects are garbage collected, which makes
this API error-prone on CPython and entirely broken on PyPy. Therefore,
``nditer`` should now be used as a context manager whenever using ``nditer``
with writeable arrays (``with np.nditer(...) as it: ...``). You may also
explicitly call ``it.close()`` for cases where a context manager is unusable,
for instance in generator expressions.

Numpy has switched to using pytest instead of nose for testing
--------------------------------------------------------------
The last nose release was 1.3.7 in June, 2015, and development of that tool has
ended, consequently NumPy has now switched to using pytest. The old decorators
and nose tools that were previously used by some downstream projects remain
available, but will not be maintained. The standard testing utilities,
`assert_almost_equal` and such, are not be affected by this change except for
the nose specific functions `import_nose` and `raises`. Those functions are
not used in numpy, but are kept for downstream compatibility.

Numpy no longer monkey-patches ``ctypes`` with ``__array_interface__``
----------------------------------------------------------------------
Previously numpy added ``__array_interface__`` attributes to all the integer
types from ``ctypes``.

``np.ma.notmasked_contiguous`` and ``np.ma.flatnotmasked_contiguous`` always return lists
-----------------------------------------------------------------------------------------
This was always the documented behavior, but in reality the result used to be
any of slice, None, or list.

All downstream users seem to use detect the `None` result from
``flatnotmasked_contiguous`` and replace it with ``[]``.
These callers will continue to work as before.

``np.squeeze`` now respects the API expectation of objects that do not handle an ``axis`` argument
--------------------------------------------------------------------------------------------------
Prior to version ``1.7.0`` ``np.squeeze`` did not have an ``axis`` argument and all empty axes were removed
by default. After incorporation of an ``axis`` argument, it was possible to selectively squeeze single
or multiple empty axes, but the old API expectation was not respected because the axes could still be
selectively removed (silent success) in an object depending on the old API. The silent success is no
longer possible, and objects expecting the old API are respected. The silent success was prevented
by removing the interception of an otherwise-normal Exception when ``axis`` was provided to an object
using the old API.

unstructured void array's ``.item`` method now returns a bytes object
---------------------------------------------------------------------
``.item`` now returns a ``bytes`` object instead of a buffer or byte array.
This may affect code which assumed the return value was mutable, which is no
longer the case.

``copy.copy`` and ``copy.deepcopy`` no longer turn ``masked`` into an array
----------------------------------------------------------------------------
Since ``np.ma.masked`` is a readonly scalar, copying should be a no-op. These
functions now behave consistently with ``np.copy()``.

Multifield Indexing of Structured Arrays will still return a copy
-----------------------------------------------------------------
The change that multi-field indexing of structured arrays returns a view
instead of a copy is pushed back to 1.16. A new method
``numpy.lib.recfunctions.repack_fields`` has been introduced to help mitigate
the effects of this change, which can be used to write code compatible with
both numpy 1.15 and 1.16. For more information on how to update code to account
for this future change see "basics/structured arrays/accessing multiple fields"
in the user guide.

C API changes
=============

* ``NpyIter_Close`` has been added and should be called before
  ``NpyIter_Deallocate`` to resolve possible writeback-enabled arrays.

* Functions ``npy_get_floatstatus_barrier`` and ``npy_clear_floatstatus_barrier``
  have been added and should be used in place of the ``npy_get_floatstatus``and
  ``npy_clear_status`` functions. Optimizing compilers like GCC 8.1 and Clang
  were rearranging the order of operations when the previous functions were
  used in the ufunc SIMD functions, resulting in the floatstatus flags being '
  checked before the operation whose status we wanted to check was run.
  See `#10339 <https://github.com/numpy/numpy/issues/10370>`__.

* ``PyArray_GetDTypeTransferFunction`` now defaults to using user-defined
  ``copyswapn`` / ``copyswap`` for user-defined dtypes. If this causes a
  significant performance hit, consider implementing ``copyswapn`` to reflect
  the implementation of ``PyArray_GetStridedCopyFn``.
  See `#10898 <https://github.com/numpy/numpy/pull/10898>`__.

New Features
============

``np.gcd`` and ``np.lcm`` ufuncs added for integer and objects types
--------------------------------------------------------------------
These compute the greatest common divisor, and lowest common multiple,
respectively. These work on all the numpy integer types, as well as the
builtin arbitrary-precision `Decimal` and `long` types.

Support for cross-platform builds for iOS
-----------------------------------------
The build system has been modified to add support for the
``_PYTHON_HOST_PLATFORM`` environment variable, used by ``distutils`` when
compiling on one platform for another platform. This makes it possible to
compile NumPy for iOS targets.

This only enables you to compile NumPy for one specific platform at a time.
Creating a full iOS-compatible NumPy package requires building for the 5
architectures supported by iOS (i386, x86_64, armv7, armv7s and arm64), and
combining these 5 compiled builds products into a single "fat" binary.

``return_indices`` keyword added for ``np.intersect1d``
-------------------------------------------------------
New keyword ``return_indices`` returns the indices of the two input arrays
that correspond to the common elements.

``np.quantile`` and ``np.nanquantile``
--------------------------------------
Like ``np.percentile`` and ``np.nanpercentile``, but takes quantiles in [0, 1]
rather than percentiles in [0, 100]. ``np.percentile`` is now a thin wrapper
around ``np.quantile`` with the extra step of dividing by 100.

Build system
------------
Added experimental support for the 64-bit RISC-V architecture.

Improvements
============

``np.ufunc.reduce`` and related functions now accept an initial value
---------------------------------------------------------------------
``np.ufunc.reduce``, ``np.sum``, ``np.prod``, ``np.min`` and ``np.max`` all
now accept an ``initial`` keyword argument that specifies the value to start
the reduction with.

``np.flip`` can operate over multiple axes
------------------------------------------
``np.flip`` now accepts None, or tuples of int, in its ``axis`` argument. If
axis is None, it will flip over all the axes.

``histogram`` and ``histogramdd`` functions have moved to ``np.lib.histograms``
------------------------------------------------------------------------------
These were originally found in ``np.lib.function_base``. They are still
available under their un-scoped ``np.histogram(dd)`` names, and
to maintain compatibility, aliased at ``np.lib.function_base.histogram(dd)``.

Code that does ``from np.lib.function_base import *`` will need to be updated
with the new location, and should consider not using ``import *`` in future.

``histogram`` will accept NaN values when explicit bins are given
-----------------------------------------------------------------
Previously it would fail when trying to compute a finite range for the data.
Since the range is ignored anyway when the bins are given explicitly, this error
was needless.

Note that calling `histogram` on NaN values continues to raise the
`RuntimeWarning`s typical of working with nan values, which can be silenced
as usual with `errstate`.

``histogram`` works on datetime types, when explicit bin edges are given
------------------------------------------------------------------------
Dates, times, and timedeltas can now be histogrammed. The bin edges must be
passed explicitly, and are not yet computed automatically.

``histogram`` "auto" estimator handles limited variance better
------------------------------------------------------------------------
No longer does an IQR of 0 result in `n_bins=1`, rather the number of bins
chosen is related to the data size in this situation.

``histogram`` and ``histogramdd`` return edges matching the float type of the data
----------------------------------------------------------------------------------
When passed ``float16``, ``np.float32``, or ``np.longdouble`` data, the
returned edges are now of the same dtype. Previously, ``histogram`` would only
return the same type if explicit bins were given, and ``histogram`` would
produce ``float64`` bins no matter what the inputs.

``histogramdd`` allows explicit ranges to be given in a subset of axes
----------------------------------------------------------------------
The ``range`` argument of `histogramdd` can now contain ``None`` values to
indicate that the range for the corresponding axis should be computed from the
data. Previously, this could not be specified on a per-axis basis.

``np.r_`` works with 0d arrays, and ``np.ma.mr_`` works with ``np.ma.masked``
----------------------------------------------------------------------------
0d arrays passed to the `r_` and `mr_` concatenation helpers are now treated as
though they are arrays of length 1. Previously, passing these was an error.
As a result, ``np.ma.mr_`` now works correctly on the ``masked`` constant.

``np.ptp`` accepts a ``keepdims`` argument, and extended axis tuples
--------------------------------------------------------------------
``np.ptp`` (peak-to-peak) can now work over multiple axes, just like `max` and
`min`.

``MaskedArray.astype`` now is identical to ``ndarray.astype``
-------------------------------------------------------------
This means it takes all the same arguments, making more code written for
ndarray work for masked array too.

Enable AVX2/AVX512 at compile time
-------------------------------------------------------------
Change to simd.inc.src to use AVX2 or AVX512 at compile time. Solving the gap
that if compile numpy for avx2 (or 512) with -march=native, still get the SSE
code for the simd functions even though rest of the code gets AVX2.

``nan_to_num`` always returns scalars when receiving scalar or 0d inputs
------------------------------------------------------------------------
Previously an array was returned for integer scalar inputs, which is
inconsistent with the behavior for float inputs, and that of ufuncs in general.
For all types of scalar or 0d input, the result is now a scalar.

``np.flatnonzero`` works on numpy-convertible types
---------------------------------------------------
``np.flatnonzero`` now uses ``np.ravel(a)`` instead of ``a.ravel()``, so it
works for lists, tuples, etc.

``np.interp`` returns numpy scalars rather than builtin scalars
---------------------------------------------------------------
Previously ``np.interp(0.5, [0, 1], [10, 20])`` would return a ``float``, but
now it returns a ``np.float64`` object, which more closely matches the behavior
of other functions.

Additionally, the special case of ``np.interp(object_array_0d, ...)`` is no
longer supported, as ``np.interp(object_array_nd)`` was never supported anyway.

As a result of this change, the ``period`` argument can now be used on 0d
arrays.

Allow dtype field names to be unicode in Python 2
---------------------------------------------------------------
Previously ``np.dtype([(u'name', float)])`` would raise a ``TypeError`` in
Python 2, as only bytestrings were allowed in field names. Now any unicode
string field names will be encoded with the ``ascii`` codec, raising a
``UnicodeEncodeError`` upon failure.

This change makes it easier to write Python 2/3 compatible code using
``from __future__ import unicode_literals``, which previously would cause
string literal field names to raise a TypeError in Python 2.

Comparison ufuncs accept ``dtype=object``, overriding the default ``bool``
--------------------------------------------------------------------------
This allows object arrays of symbolic types, which override ``==`` and other
operators to return expressions, to be compared elementwise with
``np.equal(a, b, dtype=object)``.

``sort`` functions accept ``kind='stable'``
-------------------------------------------
Up until now, to perform a stable sort on the data, the user must do:

    >>> np.sort([5, 2, 6, 2, 1], kind='mergesort')
    [1, 2, 2, 5, 6]

because merge sort is the only stable sorting algorithm available in
NumPy. However, having kind='mergesort' does not make it explicit that
the user wants to perform a stable sort thus harming the readability.

This change allows the user to specify kind='stable' thus clarifying
the intent.

Do not make temporary copies for in-place accumulation
------------------------------------------------------
When ufuncs perform accumulation they no longer make temporary copies because
of the overlap between input an output, that is, the next element accumulated
is added before the accumulated result is stored in its place, hence the
overlap is safe. Avoiding the copy results in faster execution.

``linalg.matrix_power`` can now handle stacks of matrices
---------------------------------------------------------
Like other functions in ``linalg``, ``matrix_power`` can now deal with arrays
of dimension larger than 2, which are treated as stacks of matrices. As part
of the change, to further improve consistency, the name of the first argument
has been changed to ``a`` (from ``M``), and the exceptions for non-square
matrices have been changed to ``LinAlgError`` (from ``ValueError``).

Increased performance in ``random.permutation`` for multidimensional arrays
---------------------------------------------------------------------------
``permutation`` uses the fast path in ``random.shuffle`` for all input
array dimensions.  Previously the fast path was only used for 1-d arrays.

Generalized ufuncs now accept ``axes``, ``axis`` and ``keepdims`` arguments
---------------------------------------------------------------------------
One can control over which axes a generalized ufunc operates by passing in an
``axes`` argument, a list of tuples with indices of particular axes.  For
instance, for a signature of ``(i,j),(j,k)->(i,k)`` appropriate for matrix
multiplication, the base elements are two-dimensional matrices and these are
taken to be stored in the two last axes of each argument.  The corresponding
axes keyword would be ``[(-2, -1), (-2, -1), (-2, -1)]``. If one wanted to
use leading dimensions instead, one would pass in ``[(0, 1), (0, 1), (0, 1)]``.

For simplicity, for generalized ufuncs that operate on 1-dimensional arrays
(vectors), a single integer is accepted instead of a single-element tuple, and
for generalized ufuncs for which all outputs are scalars, the (empty) output
tuples can be omitted.  Hence, for a signature of ``(i),(i)->()`` appropriate
for an inner product, one could pass in ``axes=[0, 0]`` to indicate that the
vectors are stored in the first dimensions of the two inputs arguments.

As a short-cut for generalized ufuncs that are similar to reductions, i.e.,
that act on a single, shared core dimension such as the inner product example
above, one can pass an ``axis`` argument. This is equivalent to passing in
``axes`` with identical entries for all arguments with that core dimension
(e.g., for the example above, ``axes=[(axis,), (axis,)]``).

Furthermore, like for reductions, for generalized ufuncs that have inputs that
all have the same number of core dimensions and outputs with no core dimension,
one can pass in ``keepdims`` to leave a dimension with size 1 in the outputs,
thus allowing proper broadcasting against the original inputs. The location of
the extra dimension can be controlled with ``axes``. For instance, for the
inner-product example, ``keepdims=True, axes=[-2, -2, -2]`` would act on the
inner-product example, ``keepdims=True, axis=-2`` would act on the
one-but-last dimension of the input arguments, and leave a size 1 dimension in
that place in the output.

float128 values now print correctly on ppc systems
--------------------------------------------------
Previously printing float128 values was buggy on ppc, since the special
double-double floating-point-format on these systems was not accounted for.
float128s now print with correct rounding and uniqueness.

Warning to ppc users: You should upgrade glibc if it is version <=2.23,
especially if using float128. On ppc, glibc's malloc in these version often
misaligns allocated memory which can crash numpy when using float128 values.

New ``np.take_along_axis`` and ``np.put_along_axis`` functions
--------------------------------------------------------------
When used on multidimensional arrays, ``argsort``, ``argmin``, ``argmax``, and
``argpartition`` return arrays that are difficult to use as indices.
``take_along_axis`` provides an easy way to use these indices to lookup values
within an array, so that::

    np.take_along_axis(a, np.argsort(a, axis=axis), axis=axis)

is the same as::

    np.sort(a, axis=axis)

``np.put_along_axis`` acts as the dual operation for writing to these indices
within an array.

.. note:: Implementations of ``__array_ufunc__`` should ensure that they can
          handle either ``axis`` or ``axes``.  In future, we may convert
          ``axis`` to ``axes`` before passing it on.

Changes
=======


text:
<?php
/**
 * WPSEO plugin file.
 *
 * @package WPSEO\Admin\Filters
 */

/**
 * Class WPSEO_Abstract_Post_Filter.
 */
abstract class WPSEO_Abstract_Post_Filter implements WPSEO_WordPress_Integration {

	/**
	 * The filter's query argument.
	 *
	 * @var string
	 */
	const FILTER_QUERY_ARG = 'yoast_filter';

	/**
	 * Modify the query based on the FILTER_QUERY_ARG variable in $_GET.
	 *
	 * @param string $where Query variables.
	 *
	 * @return string The modified query.
	 */
	abstract public function filter_posts( $where );

	/**
	 * Returns the query value this filter uses.
	 *
	 * @return string The query value this filter uses.
	 */
	abstract public function get_query_val();

	/**
	 * Returns the total number of posts that match this filter.
	 *
	 * @return int The total number of posts that match this filter.
	 */
	abstract protected function get_post_total();

	/**
	 * Returns the label for this filter.
	 *
	 * @return string The label for this filter.
	 */
	abstract protected function get_label();

	/**
	 * Registers the hooks.
	 */
	public function register_hooks() {
		add_action( 'admin_init', array( $this, 'add_filter_links' ), 11 );

		add_filter( 'posts_where', array( $this, 'filter_posts' ) );

		if ( $this->is_filter_active() ) {
			add_action( 'restrict_manage_posts', array( $this, 'render_hidden_input' ) );
		}

		if ( $this->is_filter_active() && $this->get_explanation() !== null ) {
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_explanation_assets' ) );
		}
	}

	/**
	 * Adds the filter links to the view_edit screens to give the user a filter link.
	 *
	 * @return void
	 */
	public function add_filter_links() {
		foreach ( $this->get_post_types() as $post_type ) {
			add_filter( 'views_edit-' . $post_type, array( $this, 'add_filter_link' ) );
		}
	}

	/**
	 * Enqueues the necessary assets to display a filter explanation.
	 *
	 * @return void
	 */
	public function enqueue_explanation_assets() {
		$asset_manager = new WPSEO_Admin_Asset_Manager();
		$asset_manager->enqueue_script( 'filter-explanation' );
		$asset_manager->enqueue_style( 'filter-explanation' );
		wp_localize_script(
			WPSEO_Admin_Asset_Manager::PREFIX . 'filter-explanation',
			'yoastFilterExplanation',
			array( 'text' => $this->get_explanation() )
		);
	}

	/**
	 * Adds a filter link to the views.
	 *
	 * @param array $views Array with the views.
	 *
	 * @return array Array of views including the added view.
	 */
	public function add_filter_link( array $views ) {
		$views[ 'yoast_' . $this->get_query_val() ] = sprintf(
			'%3$s (%4$s)',
			esc_url( $this->get_filter_url() ),
			( $this->is_filter_active() ) ? ' class="current" aria-current="page"' : '',
			$this->get_label(),
			$this->get_post_total()
		);

		return $views;
	}

	/**
	 * Returns a text explaining this filter. Null if no explanation is necessary.
	 *
	 * @return string|null The explanation or null.
	 */
	protected function get_explanation() {
		return null;
	}

	/**
	 * Renders a hidden input to preserve this filter's state when using sub-filters.
	 *
	 * @return void
	 */
	public function render_hidden_input() {
		echo '<input type="hidden" name="' . esc_attr( self::FILTER_QUERY_ARG ) . '" value="' . esc_attr( $this->get_query_val() ) . '">';
	}

	/**
	 * Returns an url to edit.php with post_type and this filter as the query arguments.
	 *
	 * @return string The url to activate this filter.
	 */
	protected function get_filter_url() {
		$query_args = array(
			self::FILTER_QUERY_ARG => $this->get_query_val(),
			'post_type'            => $this->get_current_post_type(),
		);

		return add_query_arg( $query_args, 'edit.php' );
	}

	/**
	 * Returns true when the filter is active.
	 *
	 * @return bool Whether or not the filter is active.
	 */
	protected function is_filter_active() {
		return ( $this->is_supported_post_type( $this->get_current_post_type() )
			&& filter_input( INPUT_GET, self::FILTER_QUERY_ARG ) === $this->get_query_val() );
	}

	/**
	 * Returns the current post type.
	 *
	 * @return string The current post type.
	 */
	protected function get_current_post_type() {
		$filter_options = array(
			'options' => array( 'default' => 'post' ),
		);

		return filter_input( INPUT_GET, 'post_type', FILTER_DEFAULT, $filter_options );
	}

	/**
	 * Returns the post types to which this filter should be added.
	 *
	 * @return array The post types to which this filter should be added.
	 */
	protected function get_post_types() {
		return WPSEO_Post_Type::get_accessible_post_types();
	}

	/**
	 * Checks if the post type is supported.
	 *
	 * @param string $post_type Post type to check against.
	 *
	 * @return bool True when it is supported.
	 */
	protected function is_supported_post_type( $post_type ) {
		return in_array( $post_type, $this->get_post_types(), true );
	}
}


text:
<?php

namespace Enrise\Maparea\tests;

use Enrise\Maparea\Loader\LoaderInterface;
use Enrise\Maparea\Loader\YamlLoader;
use Enrise\Maparea\Mapper;
use Enrise\Maparea\tests\Helper\TestMapperService;
use PHPUnit\Framework\TestCase;

/**
 * Class YamlLoaderTest
 */
class YamlLoaderTest extends TestCase
{
    /**
     * @var Mapper
     */
    private $mapper;

    /**
     * @var LoaderInterface
     */
    private $loader;

    protected function setUp()
    {
        $this->loader = new YamlLoader(__DIR__."/resources/yaml");
        $this->mapper = Mapper::withLoader($this->loader);

        $this->mapper->addService('test.service', new TestMapperService());
    }

    /**
     * Tests the mapping data with loader usage.
     */
    public function testDataMappingWithLoader()
    {
        $mappedData = $this->mapper->mapDataWithLoader(
            $this->getRawData(),
            'simple.yml'
        );

        $this->assertSame($mappedData, $this->getDesiredOutput());
    }

    /**
     * @return array
     */
    private function getRawData(): array
    {
        return [
            "uuid" => 1,
            "customer_name" => "John doe",
            "roles" => [
                "admin" => true
            ],
            "distance" => 1223
        ];
    }

    /**
     * @return array
     */
    private function getDesiredOutput(): array
    {
        return [
            "id" => 1,
            "name" => "John doe",
            "admin" => true,
            "distance" => 1.223
        ];
    }
}


text:
/* 要求:
 * (子类化)2D
 * Shapes and 3D Shapes
 * Write down all the shapes you can think of-- both two dimensional and three dimensional -- and form
 * those shapes into a shape hierarchy(类层次结构).
 * a) Your hierarchy should have base class Shape from which class TwoDimensionalShape and class
 * ThreeDimensionalShape are derived. Then, for example, Circle is derived from
 * TwoDimensionalShape, with private data radius; Cylinder is derived from
 * ThreeDimensionalShape with private data radius and height; and so on.
 * b) Once you have developed the hierarchy, define each of the classes in the hierarchy. Each
 * TwoDimensionalShape should contain function getArea() to calculate the area of the
 * two-dimensional shape. Each ThreeDimensionalShape should have member functions getArea()
 * and getVolume() to calculate the surface area and volume.
 * c) Create a program that uses a vector of Shape pointers to objects to each concrete class in the
 * hierarchy. The program should print the objects determine whether each shape is a
 * TwoDimensionalShape or a ThreeDimensionalShape. If a shape is 2D display its area. If it is a
 * 3D display its area and volume.
 */
#include <vector>
#include <iostream>
#include <stdexcept>
using namespace std;

#include "Shape.h"
#include "Circle.h"
#include "Cuboid.h"
#include "Cylinder.h"
#include "Rectangle.h"
#include "Square.h"
#include "Ball.h"

// test function
int main()
{
	try
	{
		vector<Shape*> shape_vec;
		shape_vec.push_back(new Circle(1));
		shape_vec.push_back(new Square(3));
		shape_vec.push_back(new Rectangle(8.5, 13.5));
		shape_vec.push_back(new Cylinder(2, 3));
		shape_vec.push_back(new Cuboid(3, 4, 5));
		shape_vec.push_back(new Ball(5));

		for (vector<Shape*>::iterator itr = shape_vec.begin(); itr != shape_vec.end(); ++itr)
		{
			(*itr)->print(cout);
			delete (*itr);
		}
	}
	catch (exception& e)
	{
		cerr << e.what() << endl;
	}

	return 0;
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>read_until (6 of 18 overloads)</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../read_until.html" title="read_until">
<link rel="prev" href="overload5.html" title="read_until (5 of 18 overloads)">
<link rel="next" href="overload7.html" title="read_until (7 of 18 overloads)">

read_until (6
        of 18 overloads)

          Read data into a dynamic buffer sequence until some part of the data it
          contains matches a regular expression.

template<
    typename SyncReadStream,
    typename DynamicBufferSequence>
std::size_t read_until(
    SyncReadStream & s,
    DynamicBufferSequence && buffers,
    const boost::regex & expr,
    asio::error_code & ec);

          This function is used to read data into the specified dynamic buffer sequence
          until the dynamic buffer sequence's get area contains some data that matches
          a regular expression. The call will block until one of the following conditions
          is true:

              A substring of the dynamic buffer sequence's get area matches the regular
              expression.

              An error occurred.

          This operation is implemented in terms of zero or more calls to the stream's
          read_some function. If the dynamic buffer sequence's get area already contains
          data that matches the regular expression, the function returns immediately.

          Parameters

s

                The stream from which the data is to be read. The type must support
                the SyncReadStream concept.

buffers

                A dynamic buffer sequence into which the data will be read.

expr

                The regular expression.

ec

                Set to indicate what error occurred, if any.

          Return
          Value

          The number of bytes in the dynamic buffer sequence's get area up to and
          including the substring that matches the regular expression. Returns 0
          if an error occurred.

          Remarks

          After a successful read_until operation, the dynamic buffer sequence may
          contain additional data beyond that which matched the regular expression.
          An application will typically leave that data in the dynamic buffer sequence
          for a subsequent read_until operation to examine.

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.archetypeone.rockpaperscissors.engine;

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

import com.archetypeone.rockpaperscissors.weapons.RockPaperScissorsWeaponsFactory;
import com.archetypeone.rockpaperscissors.weapons.WeaponCompareResult;

public class GameStateTest {

	private GameState sut;

	@Before
	public void setUp() {
		sut = new GameState(GameType.ROBOT_VS_ROBOT, 5);
	}

	@Test
	public void updateRoundStateStillInPlayPlayer1WinsRound() {
		// given
		RoundState state = new RoundState();
		state.setPlayer1Weapon(RockPaperScissorsWeaponsFactory.ROCK);
		state.setPlayer2Weapon(RockPaperScissorsWeaponsFactory.SCISSORS);
		state.setResult(WeaponCompareResult.LHS_WINS);
		// when
		sut.updateRoundState(state);
		// then
		Assert.assertNull(sut.getWinner());
		Assert.assertFalse(sut.isCompleted());
	}

	@Test
	public void updateRoundStateStillInPlayPlayer2WinsRound() {
		// given
		RoundState state = new RoundState();
		state.setPlayer1Weapon(RockPaperScissorsWeaponsFactory.SCISSORS);
		state.setPlayer2Weapon(RockPaperScissorsWeaponsFactory.ROCK);
		state.setResult(WeaponCompareResult.RHS_WINS);
		// when
		sut.updateRoundState(state);
		// then
		Assert.assertNull(sut.getWinner());
		Assert.assertFalse(sut.isCompleted());
	}

	@Test
	public void updateRoundStateWonPlayer1() {
		// given
		RoundState state = new RoundState();
		state.setPlayer1Weapon(RockPaperScissorsWeaponsFactory.ROCK);
		state.setPlayer2Weapon(RockPaperScissorsWeaponsFactory.SCISSORS);
		state.setResult(WeaponCompareResult.LHS_WINS);
		sut.setWinsRemaining(1);
		sut.setWinsToPlayFor(1);
		// when
		sut.updateRoundState(state);
		// then
		Assert.assertEquals("Player 1", sut.getWinner());
		Assert.assertTrue(sut.isCompleted());
	}

	@Test
	public void updateRoundStateWonPlayer2() {
		// given
		RoundState state = new RoundState();
		state.setPlayer1Weapon(RockPaperScissorsWeaponsFactory.SCISSORS);
		state.setPlayer2Weapon(RockPaperScissorsWeaponsFactory.ROCK);
		state.setResult(WeaponCompareResult.RHS_WINS);
		sut.setWinsRemaining(1);
		sut.setWinsToPlayFor(1);
		// when
		sut.updateRoundState(state);
		// then
		Assert.assertEquals("Player 2", sut.getWinner());
		Assert.assertTrue(sut.isCompleted());
	}

	@Test
	public void updateRoundStateDraw() {
		// given
		RoundState state = new RoundState();
		state.setPlayer1Weapon(RockPaperScissorsWeaponsFactory.SCISSORS);
		state.setPlayer2Weapon(RockPaperScissorsWeaponsFactory.SCISSORS);
		state.setResult(WeaponCompareResult.DRAW);
		// when
		sut.updateRoundState(state);
		// then
		Assert.assertNull(sut.getWinner());
		Assert.assertFalse(sut.isCompleted());
	}

	@Test
	public void updateRoundStateWinsRemainingDraw() {
		// given
		RoundState state = new RoundState();
		state.setResult(WeaponCompareResult.DRAW);
		// when
		sut.updateRoundState(state);
		// then
		Assert.assertNull(sut.getWinner());
		Assert.assertEquals(sut.getWinsToPlayFor(), sut.getWinsRemaining());
	}

	@Test
	public void updateRoundStateWinsRemainingPlayer1() {
		// given
		RoundState state = new RoundState();
		state.setResult(WeaponCompareResult.LHS_WINS);
		// when
		sut.updateRoundState(state);
		// then
		Assert.assertNull(sut.getWinner());
		Assert.assertEquals(sut.getWinsToPlayFor() - 1, sut.getWinsRemaining());
	}

	@Test
	public void updateRoundStateWinsRemainingPlayer2() {
		// given
		RoundState state = new RoundState();
		state.setResult(WeaponCompareResult.RHS_WINS);
		// when
		sut.updateRoundState(state);
		// then
		Assert.assertNull(sut.getWinner());
		Assert.assertEquals(sut.getWinsToPlayFor() - 1, sut.getWinsRemaining());
	}
}