text:
import slack
import slack.http_client

def history(channel, **kwargs):
    """
    Returns a portion of messages/events from the
    specified private group.
    """
    params = {
        'token':    slack.api_token,
        'channel':  channel,
    }

    for key, value in kwargs.items():
        params[key] = value

    return slack.http_client.get('groups.history', params)

def list(**kwargs):
    """
    Returns a list of groups in the team that the caller is in and
    archived groups that the caller was in.
    """
    params = { 'token': slack.api_token }

    for key, value in kwargs.items():
        params[key] = value

    return slack.http_client.get('groups.list', params)


text:
/**
 * 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.ksmpartners.ernie.server

import net.liftweb.http._
import service.ServiceRegistry
import RestGenerator._
import ErnieRequestTemplates._
import net.liftweb.json._

/**
 * Object containing the stateless dispatch definition for an ernie server.
 * Generates a dispatch table using the resource tree defined in the api value.
 */
object DispatchRestAPI extends RestGenerator with JsonTranslator {

  case class TimeoutResponse() extends LiftResponse with HeaderDefaults {
    def toResponse = InMemoryResponse(Array(), headers, cookies, 504)
  }

  /**
   * Wrap a TimeoutResponse and message with in an ErnieError case class
   */
  def timeoutErnieError(src: String = null): ErnieError = ErnieError(TimeoutResponse(), Some(new java.util.concurrent.TimeoutException(if (src != null) src + " timed out" else "Timeout")))

  /**
   * Shutdown the ernie server
   */
  def shutdown() {
    ServiceRegistry.shutDown
  }

  /**
   * Set this variable for BASIC HTTP authentication.
   * PartialFunction should:
   * 1. Attempt to authenticate the user
   * 1. If successful, populate userRoles RequestVar with roles (see [[com.ksmpartners.ernie.server.filter.SAMLConstants.]]).
   * 1. Return the result of authentication as a Boolean
   * For example:
   * {{{
   *   basicAuthentication = ({
   *     case (user:String, pass:String, req:Req) =>
   *       MyUserCollection.getUser(user, pass).map( u => {
   *         userRoles(u.getRoles)
   *         true
   *       }) getOrElse false
   *   })
   * }}}
   */
  var basicAuthentication: PartialFunction[(String, String, Req), Boolean] = PartialFunction.empty[(String, String, Req), Boolean]

  val reportDetail = Resource(Left("detail"), "Report details", false, List(getReportDetail, headReportDetail))
  val jobResult = Resource(Left("result"), "Job results", false, List(getJobResult, headJobResult, deleteJobResult), reportDetail)
  val jobStatus = Resource(Left("status"), "Job status", false, List(getJobStatus, headJobStatus))
  val job = Resource(Right(Variable("job_id")), "Job resource", false, List(getJob, headJob), jobStatus, jobResult)
  val expiredCatalog = Resource(Left("expired"), "Expired catalog", false, List(purgeExpired, getExpiredCatalog, headExpiredCatalog))
  val failedCatalog = Resource(Left("failed"), "Failed catalog", false, List(getFailedCatalog, headFailedCatalog))
  val deletedCatalog = Resource(Left("deleted"), "Deleted catalog", false, List(getDeletedCatalog, headDeletedCatalog))
  val completeCatalog = Resource(Left("complete"), "Complete catalog", false, List(getCompleteCatalog, headCompleteCatalog))
  val jobsCatalog = Resource(Left("catalog"), "Full catalog", false, List(getCatalog, headCatalog))
  val jobsSwagger = Resource(Left("jobsapi"), "Jobs JSON", false, jobsJSON :: Nil)
  val jobs = Resource(Left("jobs"), "Jobs api", true, List(getJobsList, headJobsList, postJob), job, jobsCatalog, completeCatalog, expiredCatalog, failedCatalog, deletedCatalog)

  val design = Resource(Left("rptdesign"), "Definition rptdesign", false, List(putDesign))
  val defi = Resource(Right(Variable("def_id")), "Definition resource", false, List(getDef, headDef, deleteDef), design)
  val defsSwagger = Resource(Left("defsapi"), "Defs JSON", false, defsJSON :: Nil)
  val defs = Resource(Left("defs"), "Definitions api", true, List(getDefs, headDefs, postDef), defi)

  val swagger = Resource(Left("resources"), "Resources JSON", false, resourcesJSON :: Nil)

  protected val api = jobs :: defs :: swagger :: jobsSwagger :: defsSwagger :: Nil

  var jobsAPI: JObject = null
  var defsAPI: JObject = null
  var resourceListing: JObject = null

  /**
   * Initialize the ServiceRegistry and serve the API.
   */
  def init() {

    ServiceRegistry.init()

    jobsAPI = SwaggerUtils.buildSwaggerApi(".1", "1.1", "http://localhost:8080", jobs)
    defsAPI = SwaggerUtils.buildSwaggerApi(".1", "1.1", "http://localhost:8080", defs)
    resourceListing = SwaggerUtils.buildSwaggerResourceListing(List(jobs, defs), ".1", "1.1", "http://localhost:8080")

    super.serveApi()

  }

}

redpajama_set_name: RedPajamaGithub


text:
(function ($, dbg, app) {
    function show($ele) {
        $('#about_site').tmpl({}).appendTo($ele);
        $('#help-login').hide();
        $('#demolink').click(function () {
            $.publish('/ph/about/demo');
        });
    }

    app.util.onanon(function () {
        dbg.warn('anon');
        app.url.load(app.paths.about.site);
        $('#help-login').show();
        $('#help-create').hide();
    });

    app.controller.add(app.paths.about.site, show);

})(jQuery, debug, _ph);

(function ($, dbg, app, undefined) {
     app.controller.add(app.paths.about.stats, function ($e) {
         $('#about_stats').tmpl({}).appendTo($e);
     });
 })(jQuery, debug, _ph);

(function ($, dbg, app) {
    app.controller.add(app.paths.about.details, function ($e) {
        $('#about_details').tmpl({}).appendTo($e);
    });
})(jQuery, debug, _ph);


text:
'use strict';
function hasOwn (obj, prop) {
    return obj && obj.hasOwnProperty(prop)
}
module.exports = {
    type: function (obj) {
        return /\[object (\w+)\]/.exec(Object.prototype.toString.call(obj))[1].toLowerCase()
    },
    objEach: function (obj, fn) {
        if (!obj) return
        for(var key in obj) {
            if (hasOwn(obj, key)) {
                if(fn(key, obj[key]) === false) break
            }
        }
    },
    extend: function () {
        if (this.type(obj) != 'object') return obj
        var source, prop
        for (var i = 1, length = arguments.length; i < length; i++) {
            source = arguments[i]
            for (prop in source) {
                if (hasOwn(source, prop)) {
                    obj[prop] = source[prop]
                }
            }
        }
        return obj;
    },
    hasOwn: hasOwn
}


text:
var scene = new THREE.Scene();
var camera;
var mesh;
var renderer = new THREE.WebGLRenderer();

function main()
{
	var width = 500;
	var height = 500;

	var fov = 45;
	var aspect = width / height;
	var near = 1;
	var far = 1000;
	camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
	camera.position.set( 0, 0, 5 );
	camera.lookAt(new THREE.Vector3(0,0,0));
	scene.add( camera );

	renderer.setSize( width, height );
	document.body.appendChild( renderer.domElement );

	var directionalLight = new THREE.DirectionalLight( 0xffffff, 1 );
	directionalLight.position.set( 5, 2, 3 ).normalize();
	scene.add( directionalLight );

	var light = new THREE.AmbientLight( 0x202020 ); // soft white light
	scene.add( light );

	var material = new THREE.MeshToonMaterial({specular:0xffffff, shininess:50, color:0x66ccff,shading: THREE.SmoothShading})
	material.vertexColors = THREE.VertexColors;
	// my code here
	mesh = cube(material);
	scene.add(mesh)

	//for fun!
	//Create outline object
	var outline_geo = new THREE.BoxGeometry(1, 1, 1);
	//Notice the second parameter of the material
	var outline_mat = new THREE.MeshBasicMaterial({color : 0x00ff00, side: THREE.BackSide});
	var outline = cube(outline_mat);
	//Scale the object up to have an outline (as discussed in previous answer)
	outline.scale.multiplyScalar(1.05);
	scene.add(outline);

	loop();

	var t=750
	function loop()
	{
		requestAnimationFrame( loop );
		camera.position.set( Math.sin(5*t/1000)*5, 2, Math.cos(5*t/1000)*5);
		camera.lookAt(new THREE.Vector3(0,0,0));
		renderer.render( scene, camera );
		t+=1
	}
}

function mouse_down_event( event )
{
	var x_win = event.clientX;
	var y_win = event.clientY;

	var vx = renderer.domElement.offsetLeft;
	var vy = renderer.domElement.offsetTop;
	var vw = renderer.domElement.width;
	var vh = renderer.domElement.height;
	var x_NDC = 2 * ( x_win - vx ) / vw - 1;
	var y_NDC = -( 2 * ( y_win - vy ) / vh - 1 );

	var p_NDC = new THREE.Vector3( x_NDC, y_NDC, 1 );
	var p_wld = p_NDC.unproject( camera );

	var origin = camera.position;
	var direction = p_wld.normalize();
	var raycaster = new THREE.Raycaster( origin, direction );

	var intersects = raycaster.intersectObject( mesh );
	if ( intersects.length > 0 )
	{
		intersects[0].face.color.setRGB( 1, 0.1, 0.1 );
		intersects[0].object.geometry.colorsNeedUpdate = true;
	}
}

function cube(material)
{
	g = new THREE.Geometry()

	g.vertices.push( new THREE.Vector3(-1, 1, 1) )
	g.vertices.push( new THREE.Vector3(1, 1, 1) )
	g.vertices.push( new THREE.Vector3(-1, -1, 1) )
	g.vertices.push( new THREE.Vector3(1, -1, 1) )
	g.vertices.push( new THREE.Vector3(-1, 1, -1) )
	g.vertices.push( new THREE.Vector3(1, 1, -1) )
	g.vertices.push( new THREE.Vector3(-1, -1, -1) )
	g.vertices.push( new THREE.Vector3(1, -1, -1) )

	var ful = 0  //too much of a brainfuck without renaming things
	var fur = 1
	var fll = 2
	var flr = 3
	var bul = 4
	var bur = 5
	var bll = 6
	var blr = 7

	face(g,ful,fur,fll,flr)
	face(g,bul,ful,bll,fll)
	face(g,bul,bur,ful,fur)
	face(g,fur,bur,flr,blr)
	face(g,fll,flr,bll,blr)
	face(g,bur,bul,blr,bll)

	g.computeFaceNormals();
	return new THREE.Mesh(g,material)
}

function face(g,ul,ur,ll,lr)
{
	triangle(g,ul,ll,ur),triangle(g,ur,ll,lr)
}

function triangle(g,v1,v2,v3)
{
	g.faces.push( new THREE.Face3( v1,v2,v3 ) )
}


text:
#ifndef CCURL_CURL_HPP
#define CCURL_CURL_HPP

#include <iostream>
#include <string>
#include <vector>
#include <curl/curl.h>

#define CERROR(x)  do{std::cerr << "[ERROR] " << x << std::endl;}while(0);
#define CWARN(x) do{std::cout << "[WARN] " << x << std::endl;}while(0)
#define CINFO(x) do{std::cout << "[INFO] " << x << std::endl;}while(0)

namespace ccurl
{
namespace UserAgent
{
   const std::string Firefox = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0";
   const std::string Chrome = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36A";
}
typedef size_t (*writeMemoryHandler)(void */*contents*/, size_t /*size*/, size_t /*nmemb*/, void */*userp*/);
class Curl
{
public:
    static bool init();
    static void setURL(const std::string& url);
    static void setFollowLocation(const bool& follow=true);
    static void setUserAgent(const std::string& ua);
    static void setWriteHandler(writeMemoryHandler wmhi, void* data);

    static bool perform();

    static void print();
    static void getString(std::string& str);

protected:
    Curl();
    ~Curl();

    static size_t defaultWriteHandler(void *contents, size_t size, size_t nmemb, void *userp);

    static writeMemoryHandler _writeMemoryHandler;

    static std::vector<char> _buffer;
    static CURL *_curl;
};
}
#endif //CCURL_CURL_HPP


text:
package com.jasmine.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import com.jasmine.conf.JasmineFactory;
import com.jasmine.conf.SpringFxmlLoader;
import com.jasmine.model.User;
import com.jasmine.service.UserService;

import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * Controller of the main login window
 *
 * @author Élton Nunes <elton_12_nunes@hotmail.com>
 * @since 29/09/2016
 *
 */
@Component
public class LoginController {

	@Autowired
	private UserService userService;
	@FXML
	private TextField txtLogin;
	@FXML
	private PasswordField txtPassword;
	private Stage primaryStage;
	private User user;

	@FXML
	private void login() {
		this.user = this.userService.login(this.txtLogin.getText(), this.txtPassword.getText());
		if (this.user != null) {
			openHome();
		} else {
			Alert alert = new Alert(AlertType.ERROR);
			alert.setHeaderText("Error");
			alert.setContentText("User not found.");
			alert.show();
		}
	}

	/**
	 * Open the home.
	 */
	private void openHome() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JasmineFactory.class);
		SpringFxmlLoader loader = new SpringFxmlLoader(context);

		try {
			Stage newStage = new Stage(); //Create a new Window(Stage)
			StackPane root = (StackPane) loader.loadHome("/fxml/home.fxml", newStage, this.user);
			Scene stackScene = new Scene(root);
			newStage.setScene(stackScene);
			newStage.setTitle("Jasmine IPA - Core");
			newStage.show();
			this.primaryStage.close(); //Close the previous window
			this.primaryStage = newStage; //Set the new stage on primaryStage variable.
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@FXML
	private void exit() {
		System.exit(1);
	}

	/**
	 * Method helper to set the primary stage.
	 *
	 * @param stage
	 *            new stage.
	 */
	public void setPrimaryStage(Stage stage) {
		this.primaryStage = stage;
	}

}


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Magpie::Property" do

  it "produces correct json" do
    property = Magpie::Property.new
    property.name = "property 1"

    property.to_json.should == '{}'
  end

end


text:
set -e

## Generate JSON schemas
./tools/proto2jsonschema/gen.sh

## Generate JSON schema catalog
./tools/jsonschema-catalog/gen.sh

## Generate README catalog
cd ./tools/readme-catalog && npm start

echo "Done"


text:
from bs4 import BeautifulSoup as bs
import requests
import os

f = open('AptiLinks.txt','w+')
links = []

def cred():
    print '''
        https://github.com/Vinay26k/
        All copyrights related this software belongs to Vinay :)
        Mail : vinay@programmer.net
'''
def link():
    url = r'https://www.indiabix.com/aptitude/questions-and-answers/'
    r = requests.get(url).text
    soup = bs(r,'html.parser')
    for x in soup.find_all('div',attrs={'class':'div-topics-index'}):
        for y in x.find_all('a'):
            links.append('https://www.indiabix.com'+y['href'])
            print links[-1]
    return links

singlePage = []
subPages = []
def EpageMax(url):
    r = requests.get(url).text
    soup = bs(r,'html.parser')
    for x in soup.find_all('p',attrs={'class':'mx-pager mx-lpad-25'}):
        for y in x.find_all('a'):
            if 'Next' not in y.get_text():
                singlePage.append('https://www.indiabix.com'+y['href'])
                print singlePage[-1]+' ',
                f.write(singlePage[-1]+'\n')
                print y.get_text()

def subPage(links):
    for url in links:
        print url
        r = requests.get(url).text
        soup = bs(r,'html.parser')
        f.write(url+'\n')
        EpageMax(url)
        for x in soup.find_all('ul',attrs={'class':'ul-top-left'}):
            for y in x.find_all('a'):
                subPages.append('https://www.indiabix.com'+y['href'])
                print subPages[-1]+' ',
                print y.get_text()
                f.write(subPages[-1]+'\n')
                EpageMax(subPages[-1])

#link()
cred()
subPage(link())
f.close()
#EpageMax(link())


text:
require 'logger'
require 'rmagick'
require 'base64'
require 'json'
require 'db'


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.isalnikov.config.auth;

import org.springframework.security.core.GrantedAuthority;

/**
 *
 * @author igor
 */
public enum UserAuthority implements GrantedAuthority {

    ROLE_ADMIN,
    ROLE_USER;

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


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <RelativeLayout
        android:id="@+id/xlistview_footer_content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp" >

        <ProgressBar
            android:id="@+id/xlistview_footer_progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="invisible" />

        <TextView
            android:id="@+id/xlistview_footer_hint_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="visible"
            android:text="查看更多" />
        <TextView
            android:id="@+id/lastitem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="gone"
            android:text="已经是最后一条了" />
    </RelativeLayout>

</LinearLayout>


text:
package com.intellij.util.containers;

/**
 * see also {@link com.intellij.openapi.util.Condition} and {@link java.util.function.Predicate}
 */
public interface Predicate<T> {
  boolean apply(T input);
}


text:
var redis = require('redis');
var fakeredis = require('fakeredis');
var namespace = "resque_test";
var queue = "test_queue";

var package = 'redis';
if(process.env.FAKEREDIS === 'true'){ package = 'fakeredis';  }

console.log("Using " + package);

exports.specHelper = {
  package: package,
  NR: require(__dirname + "/../index.js"),
  namespace: namespace,
  queue: queue,
  timeout: 500,
  connectionDetails: {
    package:   package,
    host:      "127.0.0.1",
    password:  "",
    port:      6379,
    database:  1,
    namespace: namespace,
    // looping: true
  },
  connect: function(callback){
    var self = this;
    if(package != 'fakeredis'){
      self.redis = redis.createClient(self.connectionDetails.port, self.connectionDetails.host, self.connectionDetails.options);
      self.redis.setMaxListeners(9999);
      if(self.connectionDetails.password != null && self.connectionDetails.password != ""){
        self.redis.auth(self.connectionDetails.password, function(err){
          self.redis.select(self.connectionDetails.database, function(err){
            // self.connectionDetails.redis = self.redis;
            callback(err);
          });
        });
      }else{
        self.redis.select(self.connectionDetails.database, function(err){
          self.connectionDetails.redis = self.redis;
          callback(err);
        });
      }
    }else{
      self.redis = fakeredis.createClient('test');
      self.redis.select(self.connectionDetails.database, function(err){
        process.nextTick(function(){
          self.connectionDetails.redis = self.redis;
          callback(err);
        });
      });
    }
  },
  cleanup: function(callback){
    var self = this;
    setTimeout(function(){
      self.redis.keys(self.namespace + "*", function(err, keys){
        if(keys.length == 0){
          callback();
        }else{
          self.redis.del(keys, function(){
            callback();
          });
        }
      });
    }, 200);
  },
  startAll: function(jobs, callback){
    var self = this;
    self.worker = new self.NR.worker({connection: {redis: self.redis}, queues: self.queue, timeout: self.timeout}, jobs, function(){
      self.scheduler = new self.NR.scheduler({connection: {redis: self.redis}, timeout: self.timeout}, function(){
        self.queue = new self.NR.queue({connection: {redis: self.redis}}, function(){
          callback();
        });
      });
    });
  },
  endAll: function(callback){
    var self = this;
    self.worker.end(function(){
      self.scheduler.end(function(){
        callback()
      })
    });
  },
  popFromQueue: function(callback){
    var self = this;
    self.redis.lpop(self.namespace + ":queue:" + self.queue, function(err, obj){
      callback(err, obj)
    });
  },
  cleanConnectionDetails: function(){
    var self = this;
    var out = {};
    if(self.package === 'fakeredis'){
      return self.connectionDetails;
    }
    for(var i in self.connectionDetails){
      if(i !== 'redis'){
        out[i] = self.connectionDetails[i];
      }
    }

    return out;
  }
}


text:
import * as d3 from 'd3'
import _ from 'lodash'

import util from './util'

function positionEdgeLabels (selection, g) {
  const created = selection.filter(function () { return !d3.select(this).classed('update') })

  function translate (e) {
    const edge = g.edge(e)
    return _.has(edge, 'x') ? 'translate(' + edge.x + ',' + edge.y + ')' : ''
  }

  created.attr('transform', translate)

  util.applyTransition(selection, g)
    .style('opacity', 1)
    .attr('transform', translate)
}

export default positionEdgeLabels


text:
package v4

/*

   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.
*/

import (
	"strings"
	"testing"
	"time"

	"github.com/apache/trafficcontrol/lib/go-tc"
	toclient "github.com/apache/trafficcontrol/traffic_ops/v4-client"
)

func TestReadOnlyCannotModify(t *testing.T) {
	WithObjs(t, []TCObj{CDNs, Types, Tenants, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, Topologies, DeliveryServices, Users}, func() {
		CreateTestCDNWithReadOnlyUser(t)
	})
}

func CreateTestCDNWithReadOnlyUser(t *testing.T) {
	if len(testData.CDNs) == 0 {
		t.Fatal("Can't test readonly user creating a cdns: test data has no cdns")
	}

	toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs)
	readonlyTOClient, _, err := toclient.LoginWithAgent(TOSession.URL, "readonlyuser", "pa$$word", true, "to-api-v3-client-tests/readonlyuser", true, toReqTimeout)
	if err != nil {
		t.Fatalf("failed to get log in with readonlyuser: " + err.Error())
	}

	cdn := tc.CDN{
		Name:       "cdn-test-readonly-create-failure",
		DomainName: "createfailure.invalid",
	}

	alerts, _, err := readonlyTOClient.CreateCDN(cdn)

	if err == nil {
		t.Error("readonlyuser creating cdn error expected: not nil, actual: nil error")
	}

	if !strings.Contains(strings.ToLower(err.Error()), "forbidden") {
		t.Errorf("readonlyuser creating cdn error expected: contains 'forbidden', actual: '" + err.Error() + "'")
	}

	for _, alert := range alerts.Alerts {
		if alert.Level == tc.SuccessLevel.String() {
			t.Errorf("readonlyuser creating cdn, alerts expected: no success alert, actual: got success alert '" + alert.Text + "'")
		}
	}

	cdns, _, _ := TOSession.GetCDNByName(cdn.Name)
	if len(cdns) > 0 {
		t.Errorf("readonlyuser getting created cdn, len(cdns) expected: 0, actual: %+v %+v", len(cdns), cdns)
	}
}


text:
User Accounts

{{accountsCount}} accounts found.

      <form [formGroup]="searchForm" (ngSubmit)="search(0)">

          <input type="text" class="form-control border-right-0" formControlName="filter" placeholder="Filter by user ID, social provider ID, device ID, or username (use '%' for prefix or suffix wildcard search)"/>

              <button type="button" class="btn btn-primary dropdown-radius" (click)="f.filter_type.setValue(0); search(0)">Search</button>

                <button type="button" [disabled]="!f.filter.value || f.filter.value === ''" class="btn btn-primary dropdown-toggle-split" ngbDropdownToggle></button>

                  <button type="button" ngbDropdownItem (click)="f.filter_type.setValue(1); search(0)">Tombstones</button>

      </form>

          <button type="button" class="btn btn-outline-secondary" (click)="search(0)" [disabled]="accounts.length === 0"></button>

          <button type="button" class="btn btn-outline-secondary" (click)="search(1)" [disabled]="nextCursor === ''"></button>

<ngb-alert [dismissible]="false" type="danger" class="mb-3" *ngIf="error">

Error when querying accounts: {{error}}

</ngb-alert>

        User ID
        Username
        Display Name
        Last Update
        Remove

        No users found - change the filter criteria or add new user accounts.

        {{u.id}}
        {{u.username}}
        {{u.display_name}}
        {{u.update_time}}

        <button type="button" class="btn btn-sm btn-danger" (click)="deleteAccount($event, i, u);">Delete</button>


text:
<?php
namespace App\Test\TestCase\Model\Table;

use App\Model\Table\DeviceDataTable;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;

/**
 * App\Model\Table\DeviceDataTable Test Case
 */
class DeviceDataTableTest extends TestCase
{

    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [
        'app.device_data',
        'app.devices'
    ];

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $config = TableRegistry::exists('DeviceData') ? [] : ['className' => 'App\Model\Table\DeviceDataTable'];
        $this->DeviceData = TableRegistry::get('DeviceData', $config);
    }

    /**
     * tearDown method
     *
     * @return void
     */
    public function tearDown()
    {
        unset($this->DeviceData);

        parent::tearDown();
    }

    /**
     * Test initialize method
     *
     * @return void
     */
    public function testInitialize()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test validationDefault method
     *
     * @return void
     */
    public function testValidationDefault()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test buildRules method
     *
     * @return void
     */
    public function testBuildRules()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }
}


text:
Brooklyn CLI
============

This is the Command Line Interface that you can use to interact with Brooklyn.

Commands available
==================

```
$ brooklyn help
usage: brooklyn [(-v | --verbose)] [(-q | --quiet)] <command> [<args>]

The most commonly used brooklyn commands are:
    help     Display help information
    launch   Starts a brooklyn application. Note that a BROOKLYN_CLASSPATH environment variable needs to be set up beforehand to point to the user application classpath.

See 'brooklyn help <command>' for more information on a specific command.
```

Launch command options
======================

```
$ brooklyn help launch
NAME
        brooklyn launch - Starts a brooklyn application. Note that a
        BROOKLYN_CLASSPATH environment variable needs to be set up beforehand to
        point to the user application classpath.

SYNOPSIS
        brooklyn [(-q | --quiet)] [(-v | --verbose)] launch
                [(-s <script URI> | --script <script URI>)] [(-nc | --noConsole)] [(-l <location list> | --location <location list> | --locations <location list>)...]
                (-a <application class or file> | --app <application class or file>)
                [(-p <port number> | --port <port number>)]

OPTIONS
        -a <application class or file>, --app <application class or file>
            The Application to start. For example my.AppName or
            file://my/AppName.groovy or classpath://my/AppName.groovy

        -l <location list>, --location <location list>, --locations <location
        list>
            Specifies the locations where the application will be launched.

        -nc, --noConsole
            Whether to start the web console

        -p <port number>, --port <port number>
            Specifies the port to be used by the Brooklyn Management Console.

        -q, --quiet
            Quiet mode

        -s <script URI>, --script <script URI>
            EXPERIMENTAL. URI for a Groovy script to parse and load. This script
            will run before starting the app.

        -v, --verbose
            Verbose mode
```

Example usage
=============

Launching one of the examples on localhost:
```
$ BROOKLYN_HOME=/path/to/brooklyn
$ PATH=$PATH:${BROOKLYN_HOME}/usage/dist/brooklyn-0.4.0-SNAPSHOT-dist/bin              # use right BROOKLYN_VERSION
$ export BROOKLYN_CLASSPATH=${BROOKLYN_HOME}/examples/simple-web-cluster/target/classes/   # point this to your app
$ brooklyn launch --app brooklyn.demo.SingleWebServerExample            # --location is set to localhost by default
```


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>statsmodels.tsa.statespace.sarimax.SARIMAX.simulate — statsmodels v0.10.1 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.tsa.statespace.sarimax.SARIMAX.simulation_smoother" href="statsmodels.tsa.statespace.sarimax.SARIMAX.simulation_smoother.html" />
    <link rel="prev" title="statsmodels.tsa.statespace.sarimax.SARIMAX.set_stability_method" href="statsmodels.tsa.statespace.sarimax.SARIMAX.set_stability_method.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Time Series Analysis by State Space Methods statespace |

statsmodels.tsa.statespace.sarimax.SARIMAX |

statsmodels.tsa.statespace.sarimax.SARIMAX.simulate¶

method

SARIMAX.simulate(params, nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None)¶

Simulate a new time series following the state space model

Parameters

paramsarray_like

Array of model parameters.

nsimulationsint

The number of observations to simulate. If the model is
time-invariant this can be any number. If the model is
time-varying, then this number must be less than or equal to the
number

measurement_shocksarray_like, optional

If specified, these are the shocks to the measurement equation,
\(\varepsilon_t\). If unspecified, these are automatically
generated using a pseudo-random number generator. If specified,
must be shaped nsimulations x k_endog, where k_endog is the
same as in the state space model.

state_shocksarray_like, optional

If specified, these are the shocks to the state equation,
\(\eta_t\). If unspecified, these are automatically
generated using a pseudo-random number generator. If specified,
must be shaped nsimulations x k_posdef where k_posdef is the
same as in the state space model.

initial_statearray_like, optional

If specified, this is the state vector at time zero, which should
be shaped (k_states x 1), where k_states is the same as in the
state space model. If unspecified, but the model has been
initialized, then that initialization is used. If unspecified and
the model has not been initialized, then a vector of zeros is used.
Note that this is not included in the returned simulated_states
array.

Returns

simulated_obsarray

An (nsimulations x k_endog) array of simulated observations.

Previous topic

statsmodels.tsa.statespace.sarimax.SARIMAX.set_stability_method

Next topic

statsmodels.tsa.statespace.sarimax.SARIMAX.simulation_smoother

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

        © Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 2.1.2.


text:
<?php

namespace Site\LessonBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SiteLessonBundle extends Bundle
{
}


text:
using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime;
using System.Linq;
using System.Text;
using System.Collections.Generic;

namespace Libraries.Messaging
{
  public class Message : TaggedObject
  {
    private Guid receiver, sender;
    public Guid Sender { get { return sender; } protected set { sender = value; } }
    public Guid Receiver { get { return receiver; } protected set { receiver = value; } }
    private MessageOperationType operationType;
    public MessageOperationType OperationType { get { return operationType; } protected set { operationType = value; } }
    private object value;
    public object Value { get { return value; } protected set { this.value = value; } }

    public Message(Guid id, Guid sender, Guid receiver, MessageOperationType type, object value)
      : base(id)
    {
      this.sender = sender;
      this.receiver = receiver;
      this.operationType = type;
      this.value = value;
    }
    public Message(Guid sender, Guid receiver, MessageOperationType type, object value)
      : this(Guid.NewGuid(), sender, receiver, type, value)
    {

    }
  }
  public enum MessageOperationType
  {
    ///
    /// Tells the receiever that they are passing data. This is
    /// the default action.
    ///
    Pass,
    ///
    /// Tells the receiever to execute the data they are
    /// being sent. This is usually a function. Most of the
    /// time an execute message is sent before a pass message to
    /// tell another domain to get ready to execute something.
    ///
    Execute,
    ///
    /// Tells the reciever that this the result of an
    /// execution that occured remotely
    ///
    Return,
    ///
    /// Tells the reciever that a message runtime action is occuring.
    /// This is how this library can extend functionality without needing
    /// a recompile.
    ///
    System,
    ///
    /// Used by the message back end to ensure that a link can be
    /// established and a pipe can be created.
    ///
    Init,
    ///
    /// Message used to describe a failure to another node.
    /// This is an internal type used by the library
    ///
    Failure,
  }
}


text:
[![pattern-matching CI](https://github.com/ace411/pattern-matching/actions/workflows/php.yml/badge.svg?branch=master)](https://github.com/ace411/pattern-matching/actions/workflows/php.yml)
[![StyleCI](https://github.styleci.io/repos/341440518/shield?branch=master)](https://github.styleci.io/repos/341440518?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/functional-php/pattern-matching/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/functional-php/pattern-matching/?branch=master)
[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/functional-php/pattern-matching.svg)](http://isitmaintained.com/project/functional-php/pattern-matching 'Average time to resolve an issue')
[![Percentage of issues still open](http://isitmaintained.com/badge/open/functional-php/pattern-matching.svg)](http://isitmaintained.com/project/functional-php/pattern-matching 'Percentage of issues still open')
[![Chat on Gitter](https://img.shields.io/gitter/room/gitterHQ/gitter.svg)](https://gitter.im/functional-php)

Pattern matching is the process of checking a series of token against a pattern.
It is different from pattern recognition as the match needs to be exact.
The process does not only match as a switch statement does, it also assigns the value
a bit like the `list` construct in PHP, a process called **destructuring**.

Most functional languages implement it as a core feature. Here is are some small examples in Haskell:

```haskell

fact :: (Integral a) => a -> a
fact 0 = 1
fact n = n * fact (n-1)

head :: [a] -> a
head xs = case xs of []    -> error "empty list"
                     (x:_) -> x

firstThree :: [a] -> (a, a, a)
firstThree (x:y:z:_) = (x, y, z)
firstThree _ = error "need at least 3 elements"

```

If you want to read more about the topic, you can head over to Wikipedia : [Pattern matching](https://en.wikipedia.org/wiki/Pattern_matching)

## Installation

    composer require functional-php/pattern-matching

## Basic Usage

As we cannot extend the syntax of PHP, the choice was made to use a syntax based on arrays.
The key representes the pattern and the value is the function to call with the value or a constant if
you want to do nothing with it.

Let's see how we could implement our 3 Haskell examples:

```php

use FunctionalPHP\PatternMatching as m;

$fact = m\func([
    '0' => 1,
    'n' => function($n) use(&$fact) {
        return $n * $fact($n - 1);
    }
]);

$head = m\func([
    '(x:_)' => function($x) { return $x; },
    '_' => function() { throw new RuntimeException('empty list'); }
]);

$firstThree= m\func([
    '(x:y:z:_)' => function($x, $y, $z) { return [$x, $y, $z]; },
    '_' => function() { throw new RuntimeException('need at least 3 elements'); }
]);

```

You can also use the `match` function if you want to have a beefed up version of the `switch` statement or if you don't like anonymous functions:

```php

use FunctionalPHP\PatternMatching as m;

function factorial($n) {
    return m\pmatch([
        '0' => 1,
        'n' => function($n) use(&$fact) {
            return $n * factorial($n - 1);
        }
    ], $n);
}

echo m\pmatch([
    '"toto"' => 'first',
    '[a, [b, c], d]' => 'second',
    '[a, _, (x:xs), c]' => 'third',
    '_' => 'default',
], [1, 2, ['a', 'b'], true]);
// third

```

If you are just interested in destructuring your values, there is also a helper for that:

```php

use FunctionalPHP\PatternMatching as m;

print_r(m\extract([1, 2, ['a', 'b'], true], '[a, _, (x:xs), c]'));
// Array (
//     [a] => 1
//     [x] => a
//     [xs] => Array ( [0] => b )
//     [c] => 1
// )

```

## Patterns

Here is a quick recap of the available patterns:

| Name     | Format                                         | Example                  |
| -------- | ---------------------------------------------- | ------------------------ |
| Constant | Any scalar value (int, float, string, boolean) | `1.0`, `42`, "test"      |
| Variable | `identifier`                                   | `a`, `name`, `anything`  |
| Array    | `[<pattern>, ..., <pattern>]`                  | `[]`, `[a]`, `[a, b, c]` |
| Cons     | `(identifier:list-identifier)`                 | `(x:xs)`, `(x:y:z:xs)`   |
| Wildcard | `_`                                            | `_`                      |
| As       | `identifier@(<pattern>)`                       | `all@(x:xs)`             |

## Testing

You can run the test suite for the library using:

    composer test

A test report will be available in the `reports` directory.

## Contributing

Any contribution welcome :

- Ideas
- Pull requests
- Issues


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// 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.devtools.build.lib.remote;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.devtools.build.lib.actions.Executor.ActionContext;
import com.google.devtools.build.lib.buildtool.BuildRequest;
import com.google.devtools.build.lib.exec.ActionContextProvider;
import com.google.devtools.build.lib.exec.ExecutionOptions;
import com.google.devtools.build.lib.runtime.CommandEnvironment;

/**
 * Provide a remote execution context.
 */
final class RemoteActionContextProvider extends ActionContextProvider {
  private final ImmutableList<ActionContext> strategies;

  RemoteActionContextProvider(
      CommandEnvironment env,
      BuildRequest buildRequest) {
    boolean verboseFailures = buildRequest.getOptions(ExecutionOptions.class).verboseFailures;
    Builder<ActionContext> strategiesBuilder = ImmutableList.builder();
    strategiesBuilder.add(
        new RemoteSpawnStrategy(
            env.getClientEnv(),
            env.getExecRoot(),
            buildRequest.getOptions(RemoteOptions.class),
            verboseFailures,
            env.getRuntime().getProductName()));
    this.strategies = strategiesBuilder.build();
  }

  @Override
  public Iterable<ActionContext> getActionContexts() {
    return strategies;
  }
}


text:
(function (app) {
  'use strict';

  app.registerModule('project');
  app.registerModule('project.services');
  app.registerModule('project.routes', ['ui.router', 'core.routes']);
}(ApplicationConfiguration));


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru_RU">
<context>
    <name>pioneerKitInterpreter::PioneerKitInterpreterPlugin</name>
    <message>
        <location filename="../../../../plugins/robots/interpreters/pioneerKitInterpreter/src/pioneerKitInterpreterPlugin.cpp" line="32"/>
        <source>Pioneer Kit</source>
        <translation>Квадрокоптер "Пионер"</translation>
    </message>
</context>
<context>
    <name>pioneerKitInterpreter::PioneerRobotModel</name>
    <message>
        <source>Pioneer model</source>
        <translation type="vanished">Модель "Пионер"</translation>
    </message>
</context>
</TS>


text:
@import StoreKit;

@interface PFTestSKPaymentQueue : SKPaymentQueue

+ (void)setCanMakePayments:(BOOL)canMakePayments;

@end


text:
.timepicker__container {
  display: inline-block;
  font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
}

.timepicker__container__open > div.timepicker__droplist {
  transform: scale(1,1)
}

.timepicker__container__closed > div.timepicker__droplist {
  transform: scale(1,0)
}

.timepicker__display {
  cursor: pointer;
  border: solid 1px black;
  display: flex;
  justify-content: space-between;
  font-size: 11pt;
}

.timepicker__display>i.fa, .timepicker__display>span {
  padding:4px 4px;
}

.timepicker__display>input {
  width: 150px;
}

.timepicker__display>input, .timepicker__display>input:focus {
  border: none;
  outline: none;
}

div.timepicker__droplist {
  position: absolute;
  z-index: 1000;
  background-color: white;
  border: 1px solid black;
  font-size: 10pt;
}

.timepicker__droplist>div {
  cursor: pointer;
  background: white;
}

.timepicker__droplist>div>div {
}

.timepicker__droplist>div>div:hover {
  background:#F0F0F0;
}

.timegrid__container {
}

.timegrid__amcol, .timegrid__pmcol {
  float: left;
}

.timegrid__colheader {
  background-color: gray
}

.timegrid__hour {
  width: 100%;
  display: table-row;
}

.timegrid__colheader, .timegrid__hour>div, .timegrid__min {
  padding: 1px 2px;
}

.timegrid__hourtext {
  display: table-cell;
}

/* show minutes on hover over hour */
.timegrid__hour:hover > .timegrid__minutes {
  transform: scale(1,1)
}

.timegrid__hourtext-unselected + .timegrid__minutes {
  transform: scale(0,1)
}

.timegrid__min {
  display: table-cell;
}

.timegrid__min:hover {
  background-color: lightgray;
}

.timegrid__min00, .timegrid__min15, .timegrid__min30, .timegrid__min45 {
}

.timegrid__hourtext-unselected, .timegrid__min-unselected {
}

.timegrid__hourtext-selected, .timegrid__min-selected {
  background-color: lightblue;
}


text:
namespace retdec {
namespace internal {
namespace tests {

///
/// Mock for Connection::Response.
///
class ResponseMock: public Connection::Response {
public:
	ResponseMock() = default;
	virtual ~ResponseMock() override = default;

	MOCK_CONST_METHOD0(statusCode, int());
	MOCK_CONST_METHOD0(statusMessage, std::string ());
	MOCK_CONST_METHOD0(body, std::string ());
	MOCK_CONST_METHOD0(bodyAsJson, Json::Value ());

	// A workaround is needed due to the lack of support of non-copyable return
	// types/parameters in Google Mock.
	// http://stackoverflow.com/a/11548191/2580955
	virtual std::unique_ptr<File> bodyAsFile() const override {
		return std::unique_ptr<File>(bodyAsFileProxy());
	}
	MOCK_CONST_METHOD0(bodyAsFileProxy, File * ());
};

///
/// Mock for Connection.
///
class ConnectionMock: public Connection {
public:
	ConnectionMock() = default;
	virtual ~ConnectionMock() override = default;

	MOCK_CONST_METHOD0(getApiUrl, Url());

	// Workarounds are needed due to the lack of support of non-copyable return
	// types/parameters in Google Mock.
	// http://stackoverflow.com/a/11548191/2580955

	virtual std::unique_ptr<Response> sendGetRequest(const Url &url) override {
		return std::unique_ptr<Response>(sendGetRequestProxy(url));
	}
	MOCK_METHOD1(sendGetRequestProxy, Response * (const Url &));

	virtual std::unique_ptr<Response> sendGetRequest(const Url &url,
			const RequestArguments &args) override {
		return std::unique_ptr<Response>(sendGetRequestProxy(url, args));
	}
	MOCK_METHOD2(sendGetRequestProxy, Response * (const Url &,
		const RequestArguments &));

	virtual std::unique_ptr<Response> sendPostRequest(const Url &url,
			const RequestArguments &args,
			const RequestFiles &files) override {
		return std::unique_ptr<Response>(sendPostRequestProxy(url, args, files));
	}
	MOCK_METHOD3(sendPostRequestProxy, Response * (const Url &,
		const RequestArguments &, const RequestFiles &));
};

} // namespace tests
} // namespace internal
} // namespace retdec

#endif


text:
import sys
import unittest
import os

sys.path.append('../bin/')

from yeomaninsight import main, Analytics

class YeomanInsightTest(unittest.TestCase):

  def test_init_should_error_when_no_tracking_code_is_passed(self):
    self.assertRaises(Exception, Analytics, tracking_code='')

  def test_init_should_error_when_no_av_is_passed(self):
    self.assertRaises(Exception, Analytics, av='')

  def test_main_should_error_when_arguments_are_less_than_two(self):
    # temporally disables print function, because it's used on main.
    # just to keep the tests output clean.
    sys.stdout = open(os.devnull, 'w')
    self.assertRaises(SystemExit, main, args='')
    # restores print function.
    sys.stdout = sys.__stdout__

if __name__ == '__main__':
  unittest.main()


text:
  define(
  ['flight/lib/component',
    'component/templates/issue_template',
    'component/ui/copyable',
    'component/ui/issue'],
    function (defineComponent, withIssueTemplate, copyable, issueComponent) {
      return defineComponent(track, withIssueTemplate, copyable);

      function track() {
        this.defaultAttrs({
          issueItemSelector: '.issue',
          issuesCount: 0,
          extraAllowedTags: ['1 - Ready', '2 - Development', '3 - Quality Assurance'],
          columns: ['ready', 'development', 'quality-assurance']
        });

        this.isIssueOnThisTrack = function (issue) {
          var allowedTags = this.attr.extraAllowedTags.concat(['0 - Backlog', '4 - Done']);

          var customName;
          if (issue.state === "open") {
            if (issue.labels.length === 0) {
              customName = "0 - Backlog";
            } else {
              var allowed = _.find(issue.labels, function (value, key, list) {
                return _.contains(allowedTags, value.name);
              });
              if (allowed) {
                customName = allowed.name;
              } else {
                customName = '0 - Backlog';
              }
            }
          } else if (issue.state === "closed") {
            customName = "4 - Done";
          }

          if (issue.labels.length === 0) {
            issue.labels.push({
              name: customName
            });
          }

          return customName === this.attr.trackType;

        };

        this.filterAndReorderIssues = function (issues) {
          var filteredIssues;
          filteredIssues = _.filter(issues, this.isIssueOnThisTrack, this);
          this.attr.issues = filteredIssues;

          return filteredIssues;
        };

        this.sortIssues = function () {
          var divList = $(".issue", this.node);
          divList.sort(function (a, b) {
            return $(a).attr('data-priority') - $(b).attr('data-priority')
          });

          //$(".issue-track", this.node).html(divList);
          divList.appendTo(this.node);
        };

        this.displayIssues = function (ev, data) {
          var issues = this.filterAndReorderIssues(data.issues);
          this.attr.issuesCount += issues.length;

          issues.forEach(function (issue) {
            if (issue.labels[0].name != "4 - Done") {
              var renderedIssue = this.renderIssue(issue);
              this.$node.prepend(renderedIssue);
              issueComponent.attachTo(renderedIssue, { issue: issue });
            }
          }.bind(this));

          $('.panel-heading.backlog-header .issues-count').text(' (' + $('.issue-track.backlog .issue').length + ')');
          $('.backlog-vertical-title .issues-count').text(' (' + $('.issue-track.backlog .issue').length + ')');

          _.each(this.attr.columns, function (column) {
            $('.panel-heading.' + column + '-header .issues-count').text(' (' + $('.issue-track.' + column + ' .issue').length + ')');
          });

          if (this.attr.trackType === "4 - Done") {
            $('.panel-heading.done .issues-count').text(' (' + this.attr.issuesCount + ')');
          }

          this.trigger('ui:issues:displayed');
        };

        this.cleanCount = function () {
          this.attr.issuesCount = 0;
        };

        this.moveIssue = function (movedToTrackName, params) {
          var labelDone = "4 - Done";
          if (this.attr.trackType === labelDone && params.label === labelDone) {
            this.attr.issuesCount++;
            $('.panel-heading.done .issues-count').text(' (' + this.attr.issuesCount + ')');
          }
        };

        this.priorityChanged = function (event, elementChanged) {
          $("#" + elementChanged.id).attr('data-priority', elementChanged.priority);
        };

        this.renderIssue = function (issue) {
          var renderedIssue = $(this.render(issue));
          if (renderedIssue.find('.assignee-avatar').attr('src') != "") {
            renderedIssue.find('.assigns-myself').addClass('assigned');
            renderedIssue.find('.empty-avatar').hide();
            renderedIssue.find('.empty-avatar-label').hide();
          }
          renderedIssue.find('a.assigns-myself').click(function () {
            this.trigger('ui:assigns:user', {
              issue: issue
            });
          }.bind(this));
          return renderedIssue;
        };

        this.getIssues = function (event, eventCallback) {
          var issues = $(".issue", this.$node);

          var map = {
            track: this.attr.trackType,
            issues: _.map(issues, function (val) {
              return {
                id: val.id,
                priority: val.dataset.priority
              };
            })
          };

          this.trigger(eventCallback.eventCallback, map);
        };

        this.fillPriority = function (event, issues) {
          var UIissues = $('.issue', this.$node);

          _.each(UIissues, function (val) {

            var objIssue = _.findWhere(issues.issues, {
              id: val.id
            });
            if (objIssue)
              val.dataset.priority = objIssue.priority;
            else if (!val.dataset.priority)
              val.dataset.priority = val.id;

          });

          this.trigger(document, 'ui:issues:ended');
        };

        this.after('initialize', function () {
          this.on(document, 'data:issues:refreshed', this.displayIssues);
          this.on(document, 'data:issues:cleanCount', this.cleanCount);
          this.on(document, 'data:issues:issueMoved', this.moveIssue);
          this.on(document, 'data:issue:priorityChanged', this.priorityChanged);
          this.on(document, 'ui:issues:ended', this.sortIssues);
          this.on(document, 'data:needs:issues', this.getIssues);
          this.on(document, 'data:got:priority', this.fillPriority);
          this.on(this.$node, 'ui:issues:displayed', this.makeCopyable);
        });
      }
    });


text:
namespace Epilog {
	namespace Parser {
		class EpilogParser: public pegmatite::ASTParserDelegate {
			BindAST<AST::Clauses> clauses = EpilogGrammar::get().clauses;
			BindAST<AST::Identifier> identifier = EpilogGrammar::get().identifier;
			BindAST<AST::VariableIdentifier> variableIdentifier = EpilogGrammar::get().variableIdentifier;
			BindAST<AST::Variable> variable = EpilogGrammar::get().variable;
			BindAST<AST::Number> number = EpilogGrammar::get().number;
			BindAST<AST::List> list = EpilogGrammar::get().list;
			BindAST<AST::ElementList> elementList = EpilogGrammar::get().elements;
			BindAST<AST::String> string = EpilogGrammar::get().string;
			BindAST<AST::StringContent> stringContent = EpilogGrammar::get().content;
			BindAST<AST::CompoundTerm> compoundTerm = EpilogGrammar::get().compoundTerm;
			BindAST<AST::EnrichedCompoundTerm> enrichedCompoundTerm = EpilogGrammar::get().enrichedCompoundTerm;
			BindAST<AST::Modifier> modifier = EpilogGrammar::get().modifier;
			BindAST<AST::Body> body = EpilogGrammar::get().compoundTerms;
			BindAST<AST::ParameterList> parameterList = EpilogGrammar::get().parameters;
			BindAST<AST::Fact> fact = EpilogGrammar::get().fact;
			BindAST<AST::Rule> rule = EpilogGrammar::get().rule;
			BindAST<AST::Query> query = EpilogGrammar::get().query;
			public:
			EpilogGrammar& grammar = EpilogGrammar::get();
		};
	}
}


text:
<?php

declare(strict_types=1);

namespace Tests\Unit;

use Barryvanveen\Lastfm\Constants;
use Barryvanveen\Lastfm\Exceptions\InvalidPeriodException;
use Barryvanveen\Lastfm\Lastfm;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
use Tests\LastfmMockResponses;
use Tests\TestCase;

class LastfmTest extends TestCase
{
    /**
     * @param int    $code
     * @param string $response
     * @param array  $callHistory
     *
     * @return Client
     */
    private function getPreparedHttpClient(int $code, string $response, array &$callHistory): Client
    {
        $history = Middleware::history($callHistory);

        $mock = new MockHandler([
            new Response($code, [], $response),
        ]);

        $stack = HandlerStack::create($mock);
        $stack->push($history);

        return new Client(['handler' => $stack]);
    }

    /**
     * @param array $callHistory
     *
     * @return string
     */
    private function getQueryFromCallHistory($callHistory): string
    {
        return $callHistory[0]['request']->getUri()->getQuery();
    }

    /** @test */
    public function constructor_sets_base_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userInfo(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userInfo('myUserName')->get();

        $this->assertHasSubstring('format=json', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('api_key='.$this->lastfm_api_key, $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userinfo_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userInfo(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userInfo('myUserName')->get();

        $this->assertHasSubstring('method=user.getInfo', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userTopAlbums_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userTopAlbums(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userTopAlbums('myUserName')->get();

        $this->assertHasSubstring('method=user.getTopAlbums', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userTopArtists_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userTopArtists(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userTopArtists('myUserName')->get();

        $this->assertHasSubstring('method=user.getTopArtists', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userWeeklyTopAlbums_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userWeeklyTopAlbums(), $callHistory);

        $startDate = new \DateTime('2017-01-01');

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userWeeklyTopAlbums('myUserName', $startDate)->get();

        $this->assertHasSubstring('method=user.getWeeklyAlbumChart', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('from=1483228800', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('to=1483833600', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userWeeklyTopArtists_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userWeeklyTopArtists(), $callHistory);

        $startDate = new \DateTime('2017-01-01');

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userWeeklyTopArtists('myUserName', $startDate)->get();

        $this->assertHasSubstring('method=user.getWeeklyArtistChart', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('from=1483228800', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('to=1483833600', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userWeeklyTopTracks_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userWeeklyTopTracks(), $callHistory);

        $startDate = new \DateTime('2017-01-01');

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userWeeklyTopTracks('myUserName', $startDate)->get();

        $this->assertHasSubstring('method=user.getWeeklyTrackChart', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('from=1483228800', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('to=1483833600', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userWeeklyChartList_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userWeeklyChartList(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userWeeklyChartList('myUserName')->get();

        $this->assertHasSubstring('method=user.getWeeklyChartList', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userTopTracks_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userTopTracks(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userTopTracks('myUserName')->get();

        $this->assertHasSubstring('method=user.getTopTracks', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function userRecentTracks_sets_required_query_parameters()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::userRecentTracks(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->userRecentTracks('myUserName')->get();

        $this->assertHasSubstring('method=user.getRecentTracks', $this->getQueryFromCallHistory($callHistory));
        $this->assertHasSubstring('user=myUserName', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function it_throws_an_exception_when_requesting_an_invalid_period()
    {
        $client = new Client();

        $lastfm = new Lastfm($client, $this->lastfm_api_key);

        $this->expectException(InvalidPeriodException::class);

        $lastfm->period('not-existing-period');

        $this->fail('This statement should not be reached.');
    }

    /** @test */
    public function it_adds_the_period_query_to_the_request()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::empty(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->period(Constants::PERIOD_YEAR)->get();

        $this->assertHasSubstring('period=12month', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function it_overrides_an_existing_period_query()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::empty(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->period(Constants::PERIOD_YEAR)->period(Constants::PERIOD_WEEK)->get();

        $this->assertHasSubstring('period=7day', $this->getQueryFromCallHistory($callHistory));
        $this->assertNotHasSubstring('period=12month', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function it_adds_the_limit_query_to_the_request()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::empty(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->limit(5)->get();

        $this->assertHasSubstring('limit=5', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function it_overrides_an_existing_limit_query()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::empty(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->limit(5)->limit(321)->get();

        $this->assertHasSubstring('limit=321', $this->getQueryFromCallHistory($callHistory));
        $this->assertNotHasSubstring('limit=5', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function it_adds_the_page_query_to_the_request()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::empty(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->page(1)->get();

        $this->assertHasSubstring('page=1', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function it_overrides_an_existing_page_query()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::empty(), $callHistory);

        $lastfm = new Lastfm($client, $this->lastfm_api_key);
        $lastfm->page(1)->page(2)->get();

        $this->assertHasSubstring('page=2', $this->getQueryFromCallHistory($callHistory));
        $this->assertNotHasSubstring('page=1', $this->getQueryFromCallHistory($callHistory));
    }

    /** @test */
    public function it_returns_false_if_not_currently_playing_anything()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::notNowListening(), $callHistory);

        $lastfm = new Lastfm($client, 'fakeApiKey');
        $now_playing = $lastfm->nowListening('anyUserName');

        $this->assertEquals(false, $now_playing);
    }

    /** @test */
    public function it_returns_the_track_that_is_currently_playing()
    {
        $callHistory = [];

        $client = $this->getPreparedHttpClient(200, LastfmMockResponses::nowListening(), $callHistory);

        $lastfm = new Lastfm($client, 'fakeApiKey');
        $now_playing = $lastfm->nowListening('anyUserName');

        $this->assertNotEmpty($now_playing);
        $this->assertArrayHasKey('artist', $now_playing);
    }
}


text:
---
id: 5a9036ee38fddaf9a66b5d37
title: Add Gaps Faster with grid-gap
challengeType: 0
videoUrl: 'https://scrimba.com/p/pByETK/ca2qVtv'
---

## Description

grid-gap is a shorthand property for grid-row-gap and grid-column-gap from the previous two challenges that's more convenient to use. If grid-gap has one value, it will create a gap between all rows and columns. However, if there are two values, it will use the first one to set the gap between the rows and the second value for the columns.

## Instructions

Use grid-gap to introduce a 10px gap between the rows and 20px gap between the columns.

## Tests

```yml
tests:
  - text: <code>container</code> class should have a <code>grid-gap</code> property that introduces <code>10px</code> gap between the rows and <code>20px</code> gap between the columns.
    testString: assert(code.match(/.container\s*?{[\s\S]*grid-gap\s*?:\s*?10px\s+?20px\s*?;[\s\S]*}/gi), '<code>container</code> class should have a <code>grid-gap</code> property that introduces <code>10px</code> gap between the rows and <code>20px</code> gap between the columns.');

```

## Challenge Seed

```html
<style>
  .d1{background:LightSkyBlue;}
  .d2{background:LightSalmon;}
  .d3{background:PaleTurquoise;}
  .d4{background:LightPink;}
  .d5{background:PaleGreen;}

  .container {
    font-size: 40px;
    min-height: 300px;
    width: 100%;
    background: LightGray;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    /* add your code below this line */

    /* add your code above this line */
  }
</style>
<div class="container">
  <div class="d1">1</div>
  <div class="d2">2</div>
  <div class="d3">3</div>
  <div class="d4">4</div>
  <div class="d5">5</div>
</div>
```

## Solution

```js
var code = ".container {grid-gap: 10px 20px;}"
```


text:
local m3, s3, frm
local filename = "/etc/unbound/unbound_srv.conf"
local description =  translatef("Here you may edit the 'server:' clause in an internal 'include:'")
description = description .. " (" .. filename .. ")"

m3 = SimpleForm("editing", nil)
m3:append(Template("unbound/css-editing"))
m3.submit = translate("Save")
m3.reset = false
s3 = m3:section(SimpleSection, "Unbound Server Conf", description)
frm = s3:option(TextValue, "data")
frm.datatype = "string"
frm.rows = 20

function frm.cfgvalue()
  return nixio.fs.readfile(filename) or ""
end

function frm.write(self, section, data)
  return nixio.fs.writefile(filename, luci.util.trim(data:gsub("\r\n", "\n")))
end

return m3


text:
package com.rhm.pwn.home;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.browser.customtabs.CustomTabsIntent;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.fragment.app.DialogFragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;

import com.rhm.pwn.BuildConfig;
import com.rhm.pwn.R;
import com.rhm.pwn.debug.DebugActivity;
import com.rhm.pwn.getting_started.GetStartedFragment;
import com.rhm.pwn.model.PWNDatabase;
import com.rhm.pwn.model.URLCheck;
import com.rhm.pwn.model.URLCheckChangeNotifier;
import com.rhm.pwn.utils.PWNUtils;

import io.reactivex.Completable;
import io.reactivex.schedulers.Schedulers;

@Deprecated
public class PWNHomeActivity extends AppCompatActivity {
    private static boolean gettingStartedChecked = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!gettingStartedChecked) {
            checkForGettingStarted();
        }

        setContentView(R.layout.activity_pwnhome);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> {
            // Create an instance of the dialog fragment and show it
            DialogFragment dialog = new URLCheckDialog();
            dialog.show(getSupportFragmentManager(), URLCheckDialog.class.getName());
        });

        checkForDeepLink();
    }

    private void checkForDeepLink() {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            int value = extras.getInt(URLCheck.CLASSNAME, -1);
//            String url = extras.getString(URLCheck.URL, "");
            if (value > 0) {
                CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
                CustomTabsIntent customTabsIntent = builder.build();
                Completable.fromAction(() -> {
                            URLCheck urlc = PWNDatabase.getInstance(this).urlCheckDao().get(value);
                            String urlTarget = urlc.getUrl();
                            if (!TextUtils.isEmpty(urlTarget)) {
                                customTabsIntent.launchUrl(this, Uri.parse(urlTarget));
                            }
                            urlc.setHasBeenUpdated(false);
                            PWNDatabase.getInstance(this).urlCheckDao().update(urlc);
                        }
                ).subscribeOn(Schedulers.io())
                        .subscribe(() ->
                            URLCheckChangeNotifier.getNotifier().update(true)
                        );

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        if (BuildConfig.DEBUG) {
            getMenuInflater().inflate(R.menu.menu_pwn_home, menu);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_debug && BuildConfig.DEBUG) {
            Intent i = new Intent(this, DebugActivity.class);
            startActivity(i);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void checkForGettingStarted() {
        if (!PWNUtils.wasGettingStartedShown(this)) {
            PWNUtils.setGettingStartedShown(this);
            // Create and show the dialog.
            GetStartedFragment.newInstance().show(getSupportFragmentManager(), GetStartedFragment.TAG);
        }
        gettingStartedChecked = true;
    }

}


text:
"""Tests the Forseti Server explain service."""

from builtins import object
import unittest

from grpc._channel import _Rendezvous

from tests.services import test_models
from tests.services.api_tests.api_tester import ModelTestRunner
from tests.services.inventory import gcp_api_mocks
from tests.services.util.db import create_test_engine
from tests.unittest_utils import ForsetiTestCase
from google.cloud.forseti.services.base.config import InventoryConfig
from google.cloud.forseti.services.dao import ModelManager
from google.cloud.forseti.services.explain.service import GrpcExplainerFactory
from google.cloud.forseti.services.inventory.service import GrpcInventoryFactory
from google.cloud.forseti.services.model.service import GrpcModellerFactory

class TestServiceConfig(object):
    """ServiceConfig stub."""

    def __init__(self, inventory_config):
        self.engine = create_test_engine()
        self.model_manager = ModelManager(self.engine)
        self.inventory_config = inventory_config

    def run_in_background(self, function):
        """Stub."""
        function()
        return self

    def get_engine(self):
        """Stub."""
        return self.engine

def create_tester(inventory_config):
    """Creates a model based test runner.

    Args:
        inventory_config (InventoryConfig): the inventory configuration

    Returns:
        ModelTestRunner: the model test runner

    """
    return ModelTestRunner(
        test_models.COMPLEX_MODEL, TestServiceConfig(inventory_config),
        [
            GrpcExplainerFactory,
            GrpcInventoryFactory,
            GrpcModellerFactory,
        ])

class ExplainerTest(ForsetiTestCase):
    """Test based on declarative model."""

    def test_explain_is_supported(self):
        """Test explain is supported."""

        inventory_config_with_organization_root = (
            InventoryConfig(gcp_api_mocks.ORGANIZATION_ID, '', {}, '', {}))
        setup = create_tester(
            inventory_config_with_organization_root)

        def test(client):
            """Test implementation with API client."""
            expected_reply = set([
                                 'role/a',
                                 'role/b',
                                 'role/c',
                                 'role/d',
                                 'roles/owner',
                                 'roles/editor',
                                 'roles/viewer',
                                 ])
            actual_reply = set(r.role_name for r in client.explain.list_roles(''))
            self.assertEqual(expected_reply,
                             actual_reply)

        setup.run(test)

    def test_explain_is_not_supported(self):
        """Test explain is not supported."""

        inventory_config_with_folder_root = (
            InventoryConfig(gcp_api_mocks.FOLDER_ID, '', {}, '', {}))
        setup = create_tester(inventory_config_with_folder_root)

        def test(client):
            """Test implementation with API client."""
            self.assertRaisesRegexp(
                _Rendezvous,
                'FAILED_PRECONDITION',
                lambda r: list(client.explain.list_roles('')),
                '')

        setup.run(test)

if __name__ == '__main__':
    unittest.main()


text:
require "test_helper"

class Admin::ErrorSummaryComponentTest < ViewComponent::TestCase
  setup do
    @object_with_no_errors = ErrorSummaryTestObject.new("title", Time.zone.today)
    @object_with_errors = ErrorSummaryTestObject.new(nil, nil)
    @object_with_errors.validate
  end

  test "does not render if there are no errors on the object passed in" do
    render_inline(Admin::ErrorSummaryComponent.new(object: @object_with_no_errors))
    assert_empty page.text
  end

  test "uses the noun to construct the title if one is passed in" do
    render_inline(Admin::ErrorSummaryComponent.new(object: @object_with_errors, noun: "withdrawal explanation"))
    assert_selector "h2", text: "To save the withdrawal explanation please fix the following issues:"
  end

  test "editions use the self.format_name method to construct the noun in the title if one is not passed in" do
    detailed_guide = build(:detailed_guide, title: nil)
    detailed_guide.validate
    render_inline(Admin::ErrorSummaryComponent.new(object: detailed_guide))

    assert_selector "h2", text: "To save the detailed guidance please fix the following issues:"
  end

  test "other objects use the class of the object to construct the title if no noun is passed in" do
    render_inline(Admin::ErrorSummaryComponent.new(object: @object_with_errors))

    assert_selector "h2", text: "To save the error summary test object please fix the following issues:"
  end

  test "uses the `verb` to constuct the title if passed in" do
    render_inline(Admin::ErrorSummaryComponent.new(object: @object_with_errors, verb: "karate chop"))
    assert_selector "h2", text: "To karate chop the error summary test object please fix the following issues:"
  end

  test "defaults the verb of the to `save` if a verb is not passed in" do
    render_inline(Admin::ErrorSummaryComponent.new(object: @object_with_errors))
    assert_selector "h2", text: "To save the error summary test object please fix the following issues:"
  end

  test "constructs a list of links which link to an id based on the objects class and attribute of the error" do
    render_inline(Admin::ErrorSummaryComponent.new(object: @object_with_errors))

    first_link = page.all(".gem-c-error-summary__list-item")[0].find("a")
    second_link = page.all(".gem-c-error-summary__list-item")[1].find("a")
    third_link = page.all(".gem-c-error-summary__list-item")[2].find("a")

    assert_equal page.all(".gem-c-error-summary__list-item").count, 3
    assert_equal page.all(".gem-c-error-summary__list-item a").count, 3
    assert_equal first_link.text, "Title can't be blank"
    assert_equal first_link[:href], "#error_summary_test_object_title"
    assert_equal second_link.text, "Date can't be blank"
    assert_equal second_link[:href], "#error_summary_test_object_date"
    assert_equal third_link.text, "Date is invalid"
    assert_equal third_link[:href], "#error_summary_test_object_date"
  end

  test "overrides the class in the href with `parent class` if passed in" do
    render_inline(Admin::ErrorSummaryComponent.new(object: @object_with_errors, parent_class: "parent_class"))

    first_link = page.all(".gem-c-error-summary__list-item")[0].find("a")
    second_link = page.all(".gem-c-error-summary__list-item")[1].find("a")
    third_link = page.all(".gem-c-error-summary__list-item")[2].find("a")

    assert_equal page.all(".gem-c-error-summary__list-item").count, 3
    assert_equal page.all(".gem-c-error-summary__list-item a").count, 3
    assert_equal first_link.text, "Title can't be blank"
    assert_equal first_link[:href], "#parent_class_title"
    assert_equal second_link.text, "Date can't be blank"
    assert_equal second_link[:href], "#parent_class_date"
    assert_equal third_link.text, "Date is invalid"
    assert_equal third_link[:href], "#parent_class_date"
  end

  test "constructs data modules for tracking analytics based on the class name and error message" do
    render_inline(Admin::ErrorSummaryComponent.new(object: @object_with_errors))

    first_link = page.all(".gem-c-error-summary__list-item")[0].find("a")
    second_link = page.all(".gem-c-error-summary__list-item")[1].find("a")
    third_link = page.all(".gem-c-error-summary__list-item")[2].find("a")

    assert_equal first_link["data-module"], "auto-track-event"
    assert_equal first_link["data-track-category"], "form-error"
    assert_equal first_link["data-track-action"], "error summary test object-error"
    assert_equal first_link["data-track-label"], "Title can't be blank"
    assert_equal second_link["data-module"], "auto-track-event"
    assert_equal second_link["data-track-category"], "form-error"
    assert_equal second_link["data-track-action"], "error summary test object-error"
    assert_equal second_link["data-track-label"], "Date can't be blank"
    assert_equal third_link["data-module"], "auto-track-event"
    assert_equal third_link["data-track-category"], "form-error"
    assert_equal third_link["data-track-action"], "error summary test object-error"
    assert_equal third_link["data-track-label"], "Date is invalid"
  end

  test "when an errors attribute is base it renders the error as text not a link" do
    object = ErrorSummaryTestObject.new("title", Time.zone.today)
    object.errors.add(:base, "This is a top level error that is agnostic of model level validations. It has probably been added by an updater service or a controller and does not link to an input.")
    render_inline(Admin::ErrorSummaryComponent.new(object:))

    assert_selector ".gem-c-error-summary__list-item a", count: 0
    assert_selector ".gem-c-error-summary__list-item span", text: "This is a top level error that is agnostic of model level validations. It has probably been added by an updater service or a controller and does not link to an input."
  end
end

class ErrorSummaryTestObject
  include ActiveModel::Model
  attr_accessor :title, :date

  validates :title, :date, presence: true
  validate :date_is_a_date

  def initialize(title, date)
    @title = title
    @date = date
  end

  def date_is_a_date
    errors.add(:date, :invalid) unless date.is_a?(Date)
  end
end