text:
<?php

namespace Kunstmaan\PagePartBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $root = $treeBuilder->root('kunstmaan_page_part');
        $root->children()
            ->booleanNode('extended_pagepart_chooser')
                ->defaultFalse()
            ->end();

        /** @var ArrayNodeDefinition $pageparts */
        $pageparts = $root->children()->arrayNode('pageparts')->prototype('array');
        $pageparts->children()->scalarNode('name')->isRequired();
        $pageparts->children()->scalarNode('context')->isRequired();
        $pageparts->children()->scalarNode('extends');
        $pageparts->children()->scalarNode('widget_template');

        /** @var ArrayNodeDefinition $types */
        $types = $pageparts->children()->arrayNode('types')->defaultValue([])->prototype('array');
        $types->children()->scalarNode('name')->isRequired();
        $types->children()->scalarNode('class')->isRequired();
        $types->children()->scalarNode('preview');
        $types->children()->scalarNode('pagelimit');

        // *************************************************************************************************************

        /** @var ArrayNodeDefinition $pagetemplates */
        $pagetemplates = $root->children()->arrayNode('pagetemplates')->defaultValue([])->prototype('array');

        $pagetemplates->children()->scalarNode('template')->isRequired();
        $pagetemplates->children()->scalarNode('name')->isRequired();

        /** @var ArrayNodeDefinition $rows */
        $rows = $pagetemplates->children()->arrayNode('rows')->prototype('array');

        /** @var ArrayNodeDefinition $regions */
        $regions = $rows->children()->arrayNode('regions')->prototype('array');

        // no subregions this way, sorry. feel free to implement it: https://gist.github.com/Lumbendil/3249173
        $regions
            ->children()
                ->scalarNode('name')->end()
                ->scalarNode('span')->defaultValue(12)->end()
                ->scalarNode('template')->end()
                ->variableNode('rows')
                    ->validate()->ifTrue(function ($element) {
                        return !is_array($element);
                    })->thenInvalid('The rows element must be an array.')->end()
                    ->validate()->always(function ($children) {
                        array_walk($children, array($this, 'evaluateRows'));

                        return $children;
                    })->end()
                ->end()
            ->end();

        return $treeBuilder;
    }

    protected function evaluateRows(&$child, $name)
    {
        $child = $this->getRowNode($name)->finalize($child);
    }

    protected function getRowNode($name = '')
    {
        $treeBuilder = new TreeBuilder();
        $definition = $treeBuilder->root($name);
        $this->buildRowNode($definition);

        return $definition->getNode(true);
    }

    protected function buildRowNode(NodeDefinition $node)
    {
        return $node
                ->validate()->always(function ($children) {
                    array_walk($children, array($this, 'evaluateRegions'));

                    return $children;
                })
            ->end();
    }

    protected function evaluateRegions(&$child, $name)
    {
        $child = $this->getRegionNode($name)->finalize($child);
    }

    protected function getRegionNode($name = '')
    {
        $treeBuilder = new TreeBuilder();
        $definition = $treeBuilder->root($name);
        $this->buildRegionNode($definition);

        return $definition->getNode(true);
    }

    protected function buildRegionNode(NodeDefinition $node)
    {
        return $node
            ->children()
                ->scalarNode('name')->isRequired()->end()
                ->scalarNode('span')->defaultValue(12)->end()
                ->variableNode('rows')
                    ->validate()->ifTrue(function ($element) {
                        return !is_array($element);
                    })->thenInvalid('The rows element must be an array.')->end()
                    ->validate()->always(function ($children) {
                        array_walk($children, array($this, 'evaluateRows'));

                        return $children;
                    })->end()
                ->end()
            ->end();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;

using Amazon.Runtime;
namespace Amazon.RDS.Model
{
    /// <summary>
    /// The results from the CreateDBSnapshot action.
    /// </summary>
    public class CreateDBSnapshotResult
    {
        private DBSnapshot dBSnapshotValue;

        /// <summary>
        /// Gets and sets the CreateDBSnapshotResult property.
        /// Contains the result of a successful invocation of the CreateDBSnapshot
        /// action.
        /// </summary>
        public DBSnapshot DBSnapshot
        {
            get { return this.dBSnapshotValue; }
            set { this.dBSnapshotValue = value; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var TodoItemsView = Backbone.View.extend({
	id: "todoItemsContainer",

	initialize: function(options){
		if (!(options && options.model))
			throw new Error("model is not specified.");

		this.model.on("add", this.onAddTodoItem, this);
		this.model.on("remove", this.onRemoveTodoItem, this);
	},

	onRemoveTodoItem: function(todoItem){
		this.$("li#" + todoItem.id).remove();
	},

	onAddTodoItem: function(todoItem){
		var view = new TodoItemView({ model: todoItem });
		this.$("#todoItems").append(view.render().$el);
	},

	events: {
		"keypress #newTodoItem": "onKeyPress"
	},

	onKeyPress: function(e){
		if (e.keyCode == 13){
			var $textBox = this.$("#newTodoItem");

			if ($textBox.val()){
				var todoItem = new TodoItem({ title: $textBox.val() });
				this.model.create(todoItem);

				$textBox.val("");
			}
		}
	},

	render: function(){
		var template = $("#todoItemsTemplate").html();
		var html = Mustache.render(template);
		this.$el.html(html);

		return this;
	}
});


text:
package dao

import (
	"fmt"
	"testing"

	"github.com/goharbor/harbor/src/common"
	"github.com/goharbor/harbor/src/common/utils"
	"github.com/goharbor/harbor/src/lib/errors"
	"github.com/goharbor/harbor/src/lib/orm"
	"github.com/goharbor/harbor/src/lib/q"
	"github.com/goharbor/harbor/src/pkg/project/models"
	htesting "github.com/goharbor/harbor/src/testing"
	"github.com/stretchr/testify/suite"
)

type DaoTestSuite struct {
	htesting.Suite
	dao DAO
}

func (suite *DaoTestSuite) SetupSuite() {
	suite.Suite.SetupSuite()
	suite.dao = New()
}

func (suite *DaoTestSuite) WithUser(f func(int64, string), usernames ...string) {
	var username string
	if len(usernames) > 0 {
		username = usernames[0]
	} else {
		username = suite.RandString(5)
	}

	o, err := orm.FromContext(orm.Context())
	if err != nil {
		suite.Fail("got error %v", err)
	}

	var userID int64

	email := fmt.Sprintf("%s@example.com", username)
	sql := "INSERT INTO harbor_user (username, realname, email, password) VALUES (?, ?, ?, 'Harbor12345') RETURNING user_id"
	suite.Nil(o.Raw(sql, username, username, email).QueryRow(&userID))

	defer func() {
		o.Raw("UPDATE harbor_user SET deleted=True, username=concat_ws('#', username, user_id), email=concat_ws('#', email, user_id) WHERE user_id = ?", userID).Exec()
	}()

	f(userID, username)
}

func (suite *DaoTestSuite) WithUserGroup(f func(int64, string), groupNames ...string) {
	var groupName string
	if len(groupNames) > 0 {
		groupName = groupNames[0]
	} else {
		groupName = suite.RandString(5)
	}

	o, err := orm.FromContext(orm.Context())
	if err != nil {
		suite.Fail("got error %v", err)
	}

	var groupID int64

	groupDN := fmt.Sprintf("cn=%s,dc=goharbor,dc=io", groupName)
	suite.Nil(o.Raw("INSERT INTO user_group (group_name, ldap_group_dn) VALUES (?, ?) RETURNING id", groupName, groupDN).QueryRow(&groupID))

	defer func() {
		o.Raw("DELETE FROM user_group WHERE id = ?", groupID).Exec()
	}()

	f(groupID, groupName)
}

func (suite *DaoTestSuite) TestCreate() {
	{
		project := &models.Project{
			Name:    "foobar",
			OwnerID: 1,
		}

		projectID, err := suite.dao.Create(orm.Context(), project)
		suite.Nil(err)
		suite.dao.Delete(orm.Context(), projectID)
	}

	{
		// project name duplicated
		project := &models.Project{
			Name:    "library",
			OwnerID: 1,
		}

		projectID, err := suite.dao.Create(orm.Context(), project)
		suite.Error(err)
		suite.True(errors.IsConflictErr(err))
		suite.Equal(int64(0), projectID)
	}
}

func (suite *DaoTestSuite) TestCount() {
	{
		count, err := suite.dao.Count(orm.Context(), q.New(q.KeyWords{"project_id": 1}))
		suite.Nil(err)
		suite.Equal(int64(1), count)
	}
}

func (suite *DaoTestSuite) TestDelete() {
	project := &models.Project{
		Name:    "foobar",
		OwnerID: 1,
	}

	projectID, err := suite.dao.Create(orm.Context(), project)
	suite.Nil(err)

	p1, err := suite.dao.Get(orm.Context(), projectID)
	suite.Nil(err)
	suite.Equal("foobar", p1.Name)

	suite.dao.Delete(orm.Context(), projectID)

	p2, err := suite.dao.Get(orm.Context(), projectID)
	suite.Error(err)
	suite.True(errors.IsNotFoundErr(err))
	suite.Nil(p2)
}

func (suite *DaoTestSuite) TestGet() {
	{
		project, err := suite.dao.Get(orm.Context(), 1)
		suite.Nil(err)
		suite.Equal("library", project.Name)
	}

	{
		// not found
		project, err := suite.dao.Get(orm.Context(), 10000)
		suite.Error(err)
		suite.True(errors.IsNotFoundErr(err))
		suite.Nil(project)
	}
}

func (suite *DaoTestSuite) TestGetByName() {
	{
		project, err := suite.dao.GetByName(orm.Context(), "library")
		suite.Nil(err)
		suite.Equal("library", project.Name)
	}

	{
		// not found
		project, err := suite.dao.GetByName(orm.Context(), "project10000")
		suite.Error(err)
		suite.True(errors.IsNotFoundErr(err))
		suite.Nil(project)
	}
}

func (suite *DaoTestSuite) TestList() {
	projectNames := []string{"foo1", "foo2", "foo3"}

	var projectIDs []int64
	for _, projectName := range projectNames {
		project := &models.Project{
			Name:    projectName,
			OwnerID: 1,
		}
		projectID, err := suite.dao.Create(orm.Context(), project)
		if suite.Nil(err) {
			projectIDs = append(projectIDs, projectID)
		}
	}

	defer func() {
		for _, projectID := range projectIDs {
			suite.dao.Delete(orm.Context(), projectID)
		}
	}()

	{
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"project_id__in": projectIDs}))
		suite.Nil(err)
		suite.Len(projects, len(projectNames))
	}
}

func (suite *DaoTestSuite) TestListByPublic() {
	{
		// default library project
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"public": true}))
		suite.Nil(err)
		suite.Len(projects, 1)
	}

	{
		// default library project
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"public": "true"}))
		suite.Nil(err)
		suite.Len(projects, 1)
	}

	{
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"public": false}))
		suite.Nil(err)
		suite.Len(projects, 0)
	}

	{
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"public": "false"}))
		suite.Nil(err)
		suite.Len(projects, 0)
	}
}

func (suite *DaoTestSuite) TestListByOwner() {
	{
		// default library project
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"owner": "admin"}))
		suite.Nil(err)
		suite.Len(projects, 1)
	}

	{
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"owner": "owner-not-found"}))
		suite.Nil(err)
		suite.Len(projects, 0)
	}

	{
		// single quotes in owner
		suite.WithUser(func(userID int64, username string) {
			project := &models.Project{
				Name:    "project-owner-name-include-single-quotes",
				OwnerID: int(userID),
			}
			projectID, err := suite.dao.Create(orm.Context(), project)
			suite.Nil(err)

			defer suite.dao.Delete(orm.Context(), projectID)

			projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"owner": username}))
			suite.Nil(err)
			suite.Len(projects, 1)
		}, "owner include single quotes ' in it")
	}

	{
		// sql inject
		suite.WithUser(func(userID int64, username string) {
			project := &models.Project{
				Name:    "project-sql-inject",
				OwnerID: int(userID),
			}
			projectID, err := suite.dao.Create(orm.Context(), project)
			suite.Nil(err)

			defer suite.dao.Delete(orm.Context(), projectID)

			projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"owner": username}))
			suite.Nil(err)
			suite.Len(projects, 1)
		}, "'owner' OR 1=1")
	}
}

func (suite *DaoTestSuite) TestListByMember() {
	{
		// project admin
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"member": &models.MemberQuery{UserID: 1, Role: common.RoleProjectAdmin}}))
		suite.Nil(err)
		suite.Len(projects, 1)
	}

	{
		// guest
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"member": &models.MemberQuery{UserID: 1, Role: common.RoleGuest}}))
		suite.Nil(err)
		suite.Len(projects, 0)
	}

	{
		// guest with public projects
		projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"member": &models.MemberQuery{UserID: 1, Role: common.RoleGuest, WithPublic: true}}))
		suite.Nil(err)
		suite.Len(projects, 1)
	}

	{
		suite.WithUser(func(userID int64, username string) {
			project := &models.Project{
				Name:    "project-with-user-group",
				OwnerID: int(userID),
			}
			projectID, err := suite.dao.Create(orm.Context(), project)
			suite.Nil(err)

			defer suite.dao.Delete(orm.Context(), projectID)

			suite.WithUserGroup(func(groupID int64, groupName string) {

				o, err := orm.FromContext(orm.Context())
				if err != nil {
					suite.Fail("got error %v", err)
				}

				var pid int64
				suite.Nil(o.Raw("INSERT INTO project_member (project_id, entity_id, role, entity_type) values (?, ?, ?, ?) RETURNING id", projectID, groupID, common.RoleGuest, "g").QueryRow(&pid))
				defer o.Raw("DELETE FROM project_member WHERE id = ?", pid)

				memberQuery := &models.MemberQuery{
					UserID:   1,
					Role:     common.RoleProjectAdmin,
					GroupIDs: []int{int(groupID)},
				}
				projects, err := suite.dao.List(orm.Context(), q.New(q.KeyWords{"member": memberQuery}))
				suite.Nil(err)
				suite.Len(projects, 2)
			})
		})
	}
}

func (suite *DaoTestSuite) TestListRoles() {
	{
		// only projectAdmin
		suite.WithUser(func(userID int64, username string) {
			project := &models.Project{
				Name:    utils.GenerateRandomString(),
				OwnerID: int(userID),
			}
			projectID, err := suite.dao.Create(orm.Context(), project)
			suite.Nil(err)
			defer suite.dao.Delete(orm.Context(), projectID)

			roles, err := suite.dao.ListRoles(orm.Context(), projectID, int(userID))
			suite.Nil(err)
			suite.Len(roles, 1)
			suite.Contains(roles, common.RoleProjectAdmin)
		})
	}

	{
		// projectAdmin and user groups
		suite.WithUser(func(userID int64, username string) {
			project := &models.Project{
				Name:    utils.GenerateRandomString(),
				OwnerID: int(userID),
			}
			projectID, err := suite.dao.Create(orm.Context(), project)
			suite.Nil(err)

			defer suite.dao.Delete(orm.Context(), projectID)

			suite.WithUserGroup(func(groupID int64, groupName string) {

				o, err := orm.FromContext(orm.Context())
				if err != nil {
					suite.Fail("got error %v", err)
				}

				var pid int64
				suite.Nil(o.Raw("INSERT INTO project_member (project_id, entity_id, role, entity_type) values (?, ?, ?, ?) RETURNING id", projectID, groupID, common.RoleGuest, "g").QueryRow(&pid))
				defer o.Raw("DELETE FROM project_member WHERE id = ?", pid)

				roles, err := suite.dao.ListRoles(orm.Context(), projectID, int(userID), int(groupID))
				suite.Nil(err)
				suite.Len(roles, 2)
				suite.Contains(roles, common.RoleProjectAdmin)
				suite.Contains(roles, common.RoleGuest)
			})
		})
	}
}

func TestDaoTestSuite(t *testing.T) {
	suite.Run(t, &DaoTestSuite{})
}


text:
require 'rails_helper'

RSpec.describe "talks/new", :type => :view do
  before(:each) do
    assign(:talk, Talk.new(
      :title => "MyString",
      :description => "MyText",
      :url => "MyString",
      :event => nil
    ))
  end

  it "renders new talk form" do
    render

    assert_select "form[action=?][method=?]", talks_path, "post" do

      assert_select "input#talk_title[name=?]", "talk[title]"

      assert_select "textarea#talk_description[name=?]", "talk[description]"

      assert_select "input#talk_url[name=?]", "talk[url]"

      assert_select "input#talk_event_id[name=?]", "talk[event_id]"
    end
  end
end


text:
import unittest2 as unittest
import copy
import numpy as np
from gmm_specializer.gmm import GMM, compute_distance_BIC

class BasicTests(unittest.TestCase):
    def test_init(self):
        gmm = GMM(3, 2, cvtype='diag')
        self.assertIsNotNone(gmm)

class SyntheticDataTests(unittest.TestCase):
    def setUp(self):
        self.D = 2
        self.N = 600
        self.M = 3
        np.random.seed(0)
        C = np.array([[0., -0.7], [3.5, .7]])
        C1 = np.array([[-0.4, 1.7], [0.3, .7]])
        Y = np.r_[
            np.dot(np.random.randn(self.N/3, 2), C1),
            np.dot(np.random.randn(self.N/3, 2), C),
            np.random.randn(self.N/3, 2) + np.array([3, 3]),
            ]
        self.X = Y.astype(np.float32)

    def test_pure_python(self):
        gmm = GMM(self.M, self.D, cvtype='diag')
        means, covars = gmm.train_using_python(self.X)
        Y = gmm.predict_using_python(self.X)
        self.assertTrue(len(set(Y)) > 1)

    def test_training_once(self):
        gmm0 = GMM(self.M, self.D, cvtype='diag')
        likelihood0 = gmm0.train(self.X)
        means0  = gmm0.components.means.flatten()
        covars0 = gmm0.components.covars.flatten()

        gmm1 = GMM(self.M, self.D, cvtype='diag')
        likelihood1 = gmm1.train(self.X)
        means1  = gmm1.components.means.flatten()
        covars1 = gmm1.components.covars.flatten()

        self.assertAlmostEqual(likelihood0, likelihood1, delta=1)
        for a,b in zip(means0, means1):   self.assertAlmostEqual(a,b,places=2)
        for a,b in zip(covars0, covars1): self.assertAlmostEqual(a,b,places=2)

    def test_prediction_once(self):
        gmm0 = GMM(self.M, self.D, cvtype='diag')
        likelihood0 = gmm0.train(self.X)
        Y0 = gmm0.predict(self.X)

        gmm1 = GMM(self.M, self.D, cvtype='diag')
        likelihood1 = gmm1.train(self.X)
        Y1 = gmm1.predict(self.X)

        for a,b in zip(Y0, Y1): self.assertAlmostEqual(a,b)
        self.assertTrue(len(set(Y0)) > 1)

    def test_training_repeat(self):
        gmm0 = GMM(self.M, self.D, cvtype='diag')
        likelihood0 = gmm0.train(self.X)
        likelihood0 = gmm0.train(self.X)
        likelihood0 = gmm0.train(self.X)
        likelihood0 = gmm0.train(self.X)
        likelihood0 = gmm0.train(self.X)
        means0  = gmm0.components.means.flatten()
        covars0 = gmm0.components.covars.flatten()

        gmm1 = GMM(self.M, self.D, cvtype='diag')
        likelihood1 = gmm1.train(self.X)
        likelihood1 = gmm1.train(self.X)
        likelihood1 = gmm1.train(self.X)
        likelihood1 = gmm1.train(self.X)
        likelihood1 = gmm1.train(self.X)
        means1  = gmm1.components.means.flatten()
        covars1 = gmm1.components.covars.flatten()

        self.assertAlmostEqual(likelihood0, likelihood1, delta=1)
        for a,b in zip(means0, means1):   self.assertAlmostEqual(a,b,places=2)
        for a,b in zip(covars0, covars1): self.assertAlmostEqual(a,b,places=2)

    def test_prediction_full(self):
        gmm0 = GMM(self.M, self.D, cvtype='full')
        likelihood0 = gmm0.train(self.X)
        Y0 = gmm0.predict(self.X)

        gmm1 = GMM(self.M, self.D, cvtype='full')
        likelihood1 = gmm1.train(self.X)
        Y1 = gmm1.predict(self.X)

        for a,b in zip(Y0, Y1): self.assertAlmostEqual(a,b)
        self.assertTrue(len(set(Y0)) > 1)

class SpeechDataTests(unittest.TestCase):
    def setUp(self):
        self.X = np.ndfromtxt('./tests/speech_data.csv', delimiter=',', dtype=np.float32)
        self.N = self.X.shape[0]
        self.D = self.X.shape[1]
        self.M = 5
        self.init_num_clusters = 16

    def do_bic_agglomeration(self, gmm_list):
        # Get the events, divide them into an initial k clusters and train each GMM on a cluster
        per_cluster = self.N/self.init_num_clusters
        init_training = zip(gmm_list,np.vsplit(self.X, range(per_cluster, self.N, per_cluster)))
        for g, x in init_training:
            g.train(x)

        # Perform hierarchical agglomeration based on BIC scores
        best_BIC_score = 1.0
        while (best_BIC_score > 0 and len(gmm_list) > 1):
            num_clusters = len(gmm_list)
            # Resegment data based on likelihood scoring
            likelihoods = gmm_list[0].score(self.X)
            for g in gmm_list[1:]:
                likelihoods = np.column_stack((likelihoods, g.score(self.X)))
            most_likely = likelihoods.argmax(axis=1)
            # Across 2.5 secs of observations, vote on which cluster they should be associated with
            iter_training = {}
            for i in range(250, self.N, 250):
                votes = np.zeros(num_clusters)
                for j in range(i-250, i):
                    votes[most_likely[j]] += 1
                iter_training.setdefault(gmm_list[votes.argmax()],[]).append(self.X[i-250:i,:])
            votes = np.zeros(num_clusters)
            for j in range((self.N/250)*250, self.N):
                votes[most_likely[j]] += 1
            iter_training.setdefault(gmm_list[votes.argmax()],[]).append(self.X[(self.N/250)*250:self.N,:])
            # Retrain the GMMs on the clusters for which they were voted most likely and
            # make a list of candidates for merging
            iter_bic_list = []
            for g, data_list in iter_training.iteritems():
                cluster_data =  data_list[0]
                for d in data_list[1:]:
                    cluster_data = np.concatenate((cluster_data, d))
                cluster_data = np.ascontiguousarray(cluster_data)
                g.train(cluster_data)
                iter_bic_list.append((g,cluster_data))

            # Keep any GMMs that lost all votes in candidate list for merging
            for g in gmm_list:
                if g not in iter_training.keys():
                    iter_bic_list.append((g,None))

            # Score all pairs of GMMs using BIC
            best_merged_gmm = None
            best_BIC_score = 0.0
            merged_tuple = None
            for gmm1idx in range(len(iter_bic_list)):
                for gmm2idx in range(gmm1idx+1, len(iter_bic_list)):
                    g1, d1 = iter_bic_list[gmm1idx]
                    g2, d2 = iter_bic_list[gmm2idx]
                    score = 0.0
                    if d1 is not None or d2 is not None:
                        if d1 is not None and d2 is not None:
                            new_gmm, score = compute_distance_BIC(g1, g2, np.ascontiguousarray(np.concatenate((d1, d2))))
                        elif d1 is not None:
                            new_gmm, score = compute_distance_BIC(g1, g2, d1)
                        else:
                            new_gmm, score = compute_distance_BIC(g1, g2, d2)
                    if score > best_BIC_score:
                        best_merged_gmm = new_gmm
                        merged_tuple = (g1, g2)
                        best_BIC_score = score

            # Merge the winning candidate pair if its deriable to do so
            if best_BIC_score > 0.0:
                gmm_list.remove(merged_tuple[0])
                gmm_list.remove(merged_tuple[1])
                gmm_list.append(best_merged_gmm)

        return [ g.M for g in gmm_list]

    def test_training_once(self):
        gmm0 = GMM(self.M, self.D, cvtype='diag')
        likelihood0 = gmm0.train(self.X)
        means0  = gmm0.components.means.flatten()
        covars0 = gmm0.components.covars.flatten()

        gmm1 = GMM(self.M, self.D, cvtype='diag')
        likelihood1 = gmm1.train(self.X)
        means1  = gmm1.components.means.flatten()
        covars1 = gmm1.components.covars.flatten()

        self.assertAlmostEqual(likelihood0, likelihood1, delta=1)
        for a,b in zip(means0, means1):   self.assertAlmostEqual(a,b,places=2)
        for a,b in zip(covars0, covars1): self.assertAlmostEqual(a,b,places=2)

    def test_prediction_once(self):
        gmm0 = GMM(self.M, self.D, cvtype='diag')
        likelihood0 = gmm0.train(self.X)
        Y0 = gmm0.predict(self.X)

        gmm1 = GMM(self.M, self.D, cvtype='diag')
        likelihood1 = gmm1.train(self.X)
        Y1 = gmm1.predict(self.X)

        for a,b in zip(Y0, Y1): self.assertAlmostEqual(a,b)
        self.assertTrue(len(set(Y0)) > 1)

    #TODO: Sometimes generates mysterious m-step cuda launch failures
    #def test_bic_agglomeration_diag(self):
    #    gmm_list = [GMM(self.M, self.D, cvtype='diag') for i in range(self.init_num_clusters)]
    #    ms = self.do_bic_agglomeration(gmm_list)
    #    self.assertItemsEqual(ms, [5, 10, 65])
    #
    #def test_bic_agglomeration_full(self):
    #    gmm_list = [GMM(self.M, self.D, cvtype='full') for i in range(self.init_num_clusters)]
    #    ms = self.do_bic_agglomeration(gmm_list)
    #    self.assertItemsEqual(ms, [5, 5, 5, 10, 15])

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


text:
package com.cango.palmcartreasure.trailer.task;

import com.cango.palmcartreasure.MtApplication;
import com.cango.palmcartreasure.api.Api;
import com.cango.palmcartreasure.api.TrailerTaskService;
import com.cango.palmcartreasure.model.TypeTaskData;
import com.cango.palmcartreasure.net.NetManager;
import com.cango.palmcartreasure.net.RxSubscriber;
import com.cango.palmcartreasure.util.CommUtil;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by cango on 2017/4/7.
 */

public class TrailerTaskPresenter implements TaskContract.Presenter {
    private TaskContract.View mTaskView;
    private TrailerTaskService mTaskService;
    private Subscription subscription1,subscription2;
    public TrailerTaskPresenter(TaskContract.View taskView) {
        mTaskView = taskView;
        mTaskView.setPresenter(this);
        mTaskService = NetManager.getInstance().create(TrailerTaskService.class);
    }

    @Override
    public void start() {
    }

    @Override
    public void onDetach() {
        if (!CommUtil.checkIsNull(subscription1))
            subscription1.unsubscribe();
        if (!CommUtil.checkIsNull(subscription2))
            subscription2.unsubscribe();
    }

    @Override
    public void openDetailTask(TypeTaskData.DataBean.TaskListBean taskListBean) {
        mTaskView.showTaskDetailUi(taskListBean);
    }

    @Override
    public void loadTasks(String type, double lat, double lon, boolean showRefreshLoadingUI, int pageCount, int pageSize) {
        if (mTaskView.isActive()){
            mTaskView.showTasksIndicator(showRefreshLoadingUI);
        }
        Observable<TypeTaskData> taskDataObservable = null;
        int userId = MtApplication.mSPUtils.getInt(Api.USERID);
        if (type.equals(TrailerTasksFragment.NEW_TASK)) {
            taskDataObservable = mTaskService.getNewTaskList(userId, lat, lon,pageCount,pageSize);
        } else if (type.equals(TrailerTasksFragment.INPROGRESS_TASK)) {
            taskDataObservable = mTaskService.getTaskInprogressList(userId, lat, lon,pageCount,pageSize);
        } else if (type.equals(TrailerTasksFragment.DONE_TASK)) {
            taskDataObservable = mTaskService.getTaskDoneList(userId, lat, lon,pageCount,pageSize);
        } else {
            //search
            taskDataObservable = mTaskService.taskQuery(userId, "", "",0,pageCount,pageSize);
        }
        subscription1 = taskDataObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<TypeTaskData>() {
                    @Override
                    protected void _onNext(TypeTaskData o) {
                        if (mTaskView.isActive()){
                            mTaskView.showTasksIndicator(false);
                            int code = o.getCode();
                            if (code == 0) {
                                if (CommUtil.checkIsNull(o.getData())) {
                                    mTaskView.showTasksError();
                                } else {
                                    if (!CommUtil.checkIsNull(o.getData().getTaskList()) && o.getData().getTaskList().size() > 0)
                                        mTaskView.showTasks(o.getData().getTaskList());
                                    else {
                                        mTaskView.showNoTasks();
                                    }
                                }
                            } else
                                mTaskView.showTasksError();
                        }
                    }

                    @Override
                    protected void _onError() {
                        if (mTaskView.isActive()) {
                            mTaskView.showTasksIndicator(false);
                            mTaskView.showTasksError();
                        }
                    }
                });
    }

    @Override
    public void taskQuery(boolean showRefreshLoadingUI,String type, String applyCD, String customerName, int timeFlag, int pageIndex, int pageSize) {
        if (mTaskView.isActive()){
            mTaskView.showTasksIndicator(showRefreshLoadingUI);
        }
        subscription2 = mTaskService.taskQuery(MtApplication.mSPUtils.getInt(Api.USERID),applyCD,customerName,timeFlag,pageIndex,pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<TypeTaskData>() {
                    @Override
                    protected void _onNext(TypeTaskData o) {
                        if (mTaskView.isActive()){
                            mTaskView.showTasksIndicator(false);
                            int code = o.getCode();
                            if (code == 0) {
                                if (CommUtil.checkIsNull(o.getData())) {
                                    mTaskView.showTasksError();
                                } else {
                                    if (!CommUtil.checkIsNull(o.getData().getTaskList()) && o.getData().getTaskList().size() > 0)
                                        mTaskView.showTasks(o.getData().getTaskList());
                                    else {
                                        mTaskView.showNoTasks();
                                    }
                                }
                            } else
                                mTaskView.showTasksError();
                        }
                    }

                    @Override
                    protected void _onError() {
                        if (mTaskView.isActive()) {
                            mTaskView.showTasksIndicator(false);
                            mTaskView.showTasksError();
                        }
                    }
                });
    }
}


text:
<nlg-business-card></nlg-business-card>

<mat-toolbar>
  Google-Maps & Geolocation
</mat-toolbar>

<mat-card class="googleMaps-card">

  <mat-card-header>
    <mat-card-title>Angular 8</mat-card-title>
    <mat-card-subtitle>Google-Maps & Geolocation</mat-card-subtitle>
  </mat-card-header>

  <mat-card-content>

Now that your app has been created, you'll want to start building out features and components.
      Check out some of the resources below for next steps.

  </mat-card-content>

  <button (click)="locateSelf()">Locate Me</button>

</mat-card>


text:
require 'spec_helper'

RSpec.describe Github::Client::Orgs::Memberships, '#create' do
  let(:orgname) { 'CodeCu' }
  let(:status) { 200 }

  before {
    stub_put(request_path).with(body: inputs).
      to_return(body: body, status: status,
      headers: {content_type: 'application/json; charset=utf-8'})
  }

  after { reset_authentication_for(subject) }

  context 'Add/update organization membership - unaffiliated user' do
    let(:username) { 'anujaware' }
    let(:request_path) { "/orgs/#{orgname}/memberships/#{username}" }
    let(:body) { fixture('orgs/membership_to_unaffiliated_user.json') }
    let(:inputs) {{role: 'member'}}

    it 'should create organization membership with pending state' do
      response = subject.create(orgname, username, inputs)
      expect(response.state).to eq('pending')
    end

    it 'should create organization membership with role member' do
      response = subject.create orgname, username, inputs
      expect(response.role).to eq('member')
    end

    it "failse without role option" do
      expect {
        subject.create(orgname, username)
      }.to raise_error(Github::Error::RequiredParams,
                       /Required parameters are: role/)
    end
  end

  context 'Add/update organization membership - affiliated user' do
    let(:username) { 'anuja-joshi' }
    let(:request_path) { "/orgs/#{orgname}/memberships/#{username}" }
    let(:body) { fixture('orgs/membership_to_affilliated_user.json') }
    let(:inputs) {{role: 'admin'}}

    it 'should create organization membership with active state' do
      response = subject.create(orgname, username, inputs)
      expect(response.state).to eq('active')
    end

    it 'should update organization membership with role admin' do
      response = subject.create(orgname, username, inputs)
      expect(response.role).to eq('admin')
    end
  end
end # create


text:
package org.ovirt.engine.core.bll.tasks;

import java.util.List;
import java.util.Set;

import org.ovirt.engine.core.common.businessentities.CommandEntity;
import org.ovirt.engine.core.compat.CommandStatus;
import org.ovirt.engine.core.compat.DateTime;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;

import javax.transaction.Transaction;

public class CommandsCacheImpl implements CommandsCache {

    private static final String COMMAND_MAP_NAME = "commandMap";
    CacheWrapper<Guid, CommandEntity> commandMap;
    private volatile boolean cacheInitialized;
    private Object LOCK = new Object();

    public CommandsCacheImpl() {
        commandMap = CacheProviderFactory.<Guid, CommandEntity> getCacheWrapper(COMMAND_MAP_NAME);
    }

    private void initializeCache() {
        if (!cacheInitialized) {
            synchronized(LOCK) {
                if (!cacheInitialized) {
                    List<CommandEntity> cmdEntities = DbFacade.getInstance().getCommandEntityDao().getAll();
                    for (CommandEntity cmdEntity : cmdEntities) {
                        commandMap.put(cmdEntity.getId(), cmdEntity);
                    }
                    cacheInitialized = true;
                }
            }
        }
    }

    public Set<Guid> keySet() {
        initializeCache();
        return commandMap.keySet();
    }

    @Override
    public CommandEntity get(Guid commandId) {
        initializeCache();
        return commandMap.get(commandId);
    }

    @Override
    public void remove(final Guid commandId) {
        commandMap.remove(commandId);
        DbFacade.getInstance().getCommandEntityDao().remove(commandId);
    }

    @Override
    public void put(final CommandEntity cmdEntity) {
        commandMap.put(cmdEntity.getId(), cmdEntity);
        saveOrUpdateWithoutTransaction(cmdEntity);
    }

    public void removeAllCommandsBeforeDate(DateTime cutoff) {
        DbFacade.getInstance().getCommandEntityDao().removeAllBeforeDate(cutoff);
        cacheInitialized = false;
        initializeCache();
    }

    public void updateCommandStatus(Guid commandId, CommandStatus status) {
        final CommandEntity cmdEntity = get(commandId);
        if (cmdEntity != null) {
            cmdEntity.setCommandStatus(status);
            saveOrUpdateWithoutTransaction(cmdEntity);
        }
    }

    public void updateCommandExecuted(final Guid commandId) {
        CommandEntity cmdEntity = get(commandId);
        if (cmdEntity != null) {
            cmdEntity.setExecuted(true);
            DbFacade.getInstance().getCommandEntityDao().updateExecuted(commandId);
        }
    }

    public void saveOrUpdateWithoutTransaction(CommandEntity cmdEntity) {
        Transaction transaction = TransactionSupport.suspend();
        try {
            DbFacade.getInstance().getCommandEntityDao().saveOrUpdate(cmdEntity);
        } finally {
            if (transaction != null) {
                TransactionSupport.resume(transaction);
            }
        }
    }

    public void updateCallBackNotified(final Guid commandId) {
        CommandEntity cmdEntity = get(commandId);
        if (cmdEntity != null) {
            cmdEntity.setCallBackNotified(true);
            DbFacade.getInstance().getCommandEntityDao().updateNotified(commandId);
        }
    }
}


text:
/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
import { typedDependencies } from './dependenciesTyped.generated';
import { createFilter } from '../../factoriesAny.js';
export var filterDependencies = {
  typedDependencies: typedDependencies,
  createFilter: createFilter
};


text:
namespace content {

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  std::vector<uint8_t> cbor;
  crdtp::json::ConvertJSONToCBOR(crdtp::span<uint8_t>(data, size), &cbor);
  return 0;
}
}  // namespace content


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Heliamphora neblinae Maguire

### Remarks
null


text:
from typing import List

from Src.Core.Entity.EntityBase import EntityBase

class MicroRnaGeneTarget(EntityBase):
    """description of class"""

    def __init__(self, **kargs):
        """

        :param kargs:
        """
        self.__id_entrez_genes = kargs.get("id_entrez_genes", [])
        self.__microrna_symbol = kargs.get('microrna_symbol', '')

    def __hash__(self):
        return hash(self.microrna_symbol)

    def __eq__(self, other):
        return isinstance(other, MicroRnaGeneTarget) and \
               self.microrna_symbol == other.microrna_symbol

    @property
    def id_entrez_genes(self) -> List[int]:
        """description of property"""
        return self.__id_entrez_genes[:]

    @id_entrez_genes.setter
    def id_entrez_genes(self, value):
        """

        :param value:
        :return:
        """
        self.__id_entrez_genes = value

    @property
    def microrna_symbol(self) -> str:
        """description of property"""
        return self.__microrna_symbol

    @microrna_symbol.setter
    def microrna_symbol(self, value):
        """

        :param value:
        :return:
        """
        self.__microrna_symbol = value

    def validate(self):
        if not self.__id_entrez_genes:
            raise ValueError('id_entrez_genes is required.')

        if not self.__microrna_symbol:
            raise ValueError('microrna_symbol is required.')

    def as_dict(self):
        return {'microrna_symbol': self.__microrna_symbol,
                'id_entrez_genes': self.__id_entrez_genes}


text:
<svg class="svg-icon svg-icon-{{ include.icon }}">
  <use xlink:href="/assets/images/icons.svg#svg-icon-{{ include.icon }}"></use>
</svg>


text:
<?php
/* user model */
class User extends MY_Model
{
    public function __construct()
    {
        parent::__construct('users', 'id');
    }

    /**
     * @return array of all of the users in the database
     * PORTED OVER, needs testing
     */
    public function getUsers() {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('role', 'player');
        $query = $this->db->get();
        return $query->result_array();
    }

    public function getUserNames(){
        $this->db->select('username')->from('users');
        $query = $this->db->get();
        $init_result = $query->result_array();
        $result = array();
        foreach($init_result as $value){
            foreach($value as $name)
                $result[$name] = $name;
        }
        return $result;
    }
    /* gets the user by the username */
    public function getUserByUserName($username)
    {
        $this->db->where('username', $username);
        $this->db->from('users');
        $query = $this->db->get();
        if ($query->num_rows() < 1)
            return null;
        return $query->row();
    }

    /**
     * return array of specific user info
     * @param $name
     * @return mixed
     */
    public function getUserInfo($name){
        // Query gets user with specific name
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('username', $name);
        $query = $this->db->get();
        return $query->result_array();
    }

    /**
     * Get the holdings of specific user
     * @param $name
     * @return mixed
     */
    public function getUserHoldings($name) {
        $this->db->select('*');
        $this->db->from('holdings');
        $this->db->where('player', $name);
        $query = $this->db->get();
        return $query->result_array();
    }

    /**
     * get the selected players transactions
     * @param $name
     * @return mixed
     */
    public function getUserTransaction($name){
        $this->db->select('*');
        $this->db->from('transactions');
        $this->db->where('player', $name);
        $query = $this->db->get();
        return $query->result_array();
    }

    /**
     * @param $username
     * @param $filetype
     */
    public function register($username, $filetype){
        $data = array  (
                    'username' => $this->input->post('username'),
                    'avatar' => $username . "." . $filetype,
                    'password' => password_hash($this -> input -> post('password'), PASSWORD_DEFAULT),
                    'role' => 'player'
	        );
	    $this->db->insert('users', $data);
    }

    /**
     * Save Current Holdings
     * @param $info
     */
    public function addToHoldings($info){

        $data = array(
            'token' => $info->token,
            'stock' => $info->stock,
            'player' => $this->session->userdata('username'),
            'quantity' => $info->amount
        );
        $this->db->insert('holdings', $data);

        $data = array(
            'Stock' => $info->stock,
            'DateTime' => $info->datetime,
            'Player' => $this->session->userdata('username'),
            'Trans' => 'buy',
            'Quantity' => $info->amount
        );
        $this->db->insert('transactions', $data);
    }

}


text:
module CO2Equivalents
  module Measurements
    class Lightbulbs < CO2Equivalents::Group
      description 'Average lightbulb energy usage'
      citation 'http://www.popularmechanics.com/home_journal/home_improvement/4215199.html'
      citation 'http://www.energystar.gov/ia/partners/promotions/change_light/downloads/CALFacts_and_Assumptions.pdf'

      equivalent :lightbulbs_for_a_year, 0.001846
      equivalent :lightbulbs_for_a_month, 0.022465
      equivalent :lightbulbs_for_a_week, 0.096278
      equivalent :lightbulbs_for_a_day, 0.673949
      equivalent :lightbulbs_for_an_evening, 4.043695
      equivalent :lightbulbs_to_CFLs_for_a_day, 11.471476
      equivalent :lightbulbs_to_CFLs_for_a_week, 1.638782
      equivalent :lightbulbs_to_CFLs_for_a_month, 0.382383
      equivalent :lightbulbs_to_CFLs_for_a_year, 0.031429
      equivalent :days_with_lightbulbs_to_CFLs, 0.254922
      equivalent :weeks_with_lightbulbs_to_CFLs, 0.036417
      equivalent :months_with_lightbulbs_to_CFLs, 0.008497
      equivalent :years_with_lightbulbs_to_CFLs, 0.000698
    end
  end
end


text:
include(FindPackageHandleStandardArgs)

if(SAGE_FIND_REQUIRED)
  set(_SAGE_required REQUIRED)
  set(_SAGE_version_output_type FATAL_ERROR)
  set(_SAGE_output 1)
else()
  set(_SAGE__version_output_type STATUS)
  if(NOT SAGE_FIND_QUIETLY)
    set(_SAGE_output 1)
  endif()
endif()
if(SAGE_FIND_QUIETLY)
  set(_SAGE_quiet QUIET)
endif()

find_path(_SAGE_INCLUDE_DIR sage.h
  HINTS ${PROJECT_SOURCE_DIR}/../../.. $ENV{SAGE_ROOT} ${SAGE_ROOT}
  PATH_SUFFIXES include sage/include
  PATHS /usr/local/sage /usr /usr/local /opt /opt/local)

if(_SAGE_INCLUDE_DIR AND EXISTS "${_SAGE_INCLUDE_DIR}/sage.h")
  set(_SAGE_Version_file "${_SAGE_INCLUDE_DIR}/sage.h")
  file(READ ${_SAGE_Version_file} _SAGE_header_contents)
  string(REGEX REPLACE ".*define SAGE_VERSION[ \t]+\"([0-9].+)\".*"
    "\\1" _SAGE_VERSION ${_SAGE_header_contents})

  set(SAGE_VERSION ${_SAGE_VERSION}
    CACHE INTERNAL "The version of SAGE which was detected")
else()
  set(_SAGE_EPIC_FAIL TRUE)
  if(_SAGE_output)
    message(${_SAGE_version_output_type} "Can't find SAGE header file sage.h.")
  endif()
endif()

# Version checking
if(SAGE_FIND_VERSION AND SAGE_VERSION)
  if(SAGE_FIND_VERSION_EXACT)
    if(NOT SAGE_VERSION VERSION_EQUAL ${SAGE_FIND_VERSION})
      set(_SAGE_version_not_exact TRUE)
    endif()
  else()
    # version is too low
    if(NOT SAGE_VERSION VERSION_EQUAL ${SAGE_FIND_VERSION} AND
        NOT SAGE_VERSION VERSION_GREATER ${SAGE_FIND_VERSION})
      set(_SAGE_version_not_high_enough TRUE)
    endif()
  endif()
endif()

find_library(SAGE_SAIL_LIBRARY sail
  HINTS ${PROJECT_SOURCE_DIR}/../../.. $ENV{SAGE_ROOT} ${SAGE_ROOT}
  PATH_SUFFIXES lib lib64 sage/lib sage/lib64
  PATHS /usr/local/sage /usr /usr/local /opt /opt/local)

find_library(SAGE_QUANTA_LIBRARY quanta
  HINTS ${PROJECT_SOURCE_DIR}/../../.. $ENV{SAGE_ROOT} ${SAGE_ROOT}
  PATH_SUFFIXES lib lib64 sage/lib sage/lib64
  PATHS /usr/local/sage /usr /usr/local /opt /opt/local)

# Inform the users with an error message based on what version they
# have vs. what version was required.
if(NOT SAGE_VERSION)
  set(_SAGE_EPIC_FAIL TRUE)
  find_package_handle_standard_args(SAGE DEFAULT_MSG
                                    SAGE_SAIL_LIBRARY _SAGE_INCLUDE_DIR)
elseif(_SAGE_version_not_high_enough)
  set(_SAGE_EPIC_FAIL TRUE)
  message(${_SAGE_version_output_type}
    "Version ${SAGE_FIND_VERSION} or higher of SAGE is required. "
    "Version ${SAGE_VERSION} was found in ${_SAGE_Version_file}.")
elseif(_SAGE_version_not_exact)
  set(_SAGE_EPIC_FAIL TRUE)
  message(${_SAGE_version_output_type}
    "Version ${SAGE_FIND_VERSION} of SAGE is required exactly. "
    "Version ${SAGE_VERSION} was found.")
else()
  if(SAGE_FIND_REQUIRED)
    if(SAGE_SAIL_LIBRARY MATCHES "SAGE_SAIL_LIBRARY-NOTFOUND")
      message(FATAL_ERROR "Missing the SAGE sail library.\n"
        "Consider using CMAKE_PREFIX_PATH or the SAGE_ROOT environment variable. "
        "See the ${CMAKE_CURRENT_LIST_FILE} for more details.")
    endif()
    if(SAGE_QUANTA_LIBRARY MATCHES "SAGE_QUANTA_LIBRARY-NOTFOUND")
      message(FATAL_ERROR "Missing the SAGE quanta library.\n"
        "Consider using CMAKE_PREFIX_PATH or the SAGE_ROOT environment variable. "
        "See the ${CMAKE_CURRENT_LIST_FILE} for more details.")
    endif()
  endif()
  find_package_handle_standard_args(SAGE DEFAULT_MSG
                                    SAGE_SAIL_LIBRARY _SAGE_INCLUDE_DIR)
endif()

if(_SAGE_EPIC_FAIL)
  # Zero out everything, we didn't meet version requirements
  set(SAGE_FOUND FALSE)
  set(SAGE_SAIL_LIBRARY)
  set(SAGE_QUANTA_LIBRARY)
  set(_SAGE_INCLUDE_DIR)
  set(SAGE_INCLUDE_DIRS)
  set(SAGE_LIBRARIES)
else()
  set(SAGE_INCLUDE_DIRS ${_SAGE_INCLUDE_DIR})
  set(SAGE_LIBRARIES ${SAGE_SAIL_LIBRARY} ${SAGE_QUANTA_LIBRARY})
endif()


text:
When /^I try to find the asin "([^\"]*)"$/ do |asin|
  @products = Ramazon::Product.find(:item_id => asin, :response_group => ["Medium", "BrowseNodes", "Offers"])
  @product = @products[0]
end

Given /^I am searching with the "([^\"]*)" of "([^\"]*)"$/ do |attr, value|
  @search_options ||= {}
  @search_options[attr.to_sym] = value
end

When /^I perform the product search$/ do
  begin
    @search_options ||= {}
    @products = Ramazon::Product.find(@search_options)
  rescue Ramazon::Error => e
    @error = e
  end
end

Then /^I should get a list of products$/ do
  raise @error if @error
  @products.should_not be_empty
end

Then /^the list of products should have more than (\d+) product$/ do |count|
  @products.should have_at_least(count.to_i + 1).items
end

Then /^each product should have the "([^\"]*)" "([^\"]*)"$/ do |attr, value|
  @products.each do |p|
    p.send(attr).should eql(value)
  end
end

Then /^I should get a product$/ do
  raise @error if @error
  @product = @products[0] unless @product
  @product.should_not be_nil
end

Then /^the product should have (the\s)?"([^\"]*)" "([^\"]*)"$/ do |the, attr, value|
  @product.send(attr).should eql(value)
end

Then /^the product should have (a\s)?"([^\"]*)"$/ do |a, attr|
  @product.send(attr).should_not be_nil
end

Then /^each of the product's "([^\"]*)" should have a "([^\"]*)"$/ do |collection_name, attr|
  @product.send(collection_name).should_not be_empty
  @product.send(collection_name).each do |i|
    i.send(attr).should_not be_nil
  end
end

Then /^each of the product's "([^\"]*)" should have a "([^\"]*)" of "([^\"]*)"$/ do |collection_name, attr, value|
  @product.send(collection_name).should_not be_empty
  @product.send(collection_name).each do |i|
    i.send(attr).should_not be_nil
  end
end

Then /^the product should have a category tree for "([^\"]*)"$/ do |category_name|
  @product.category_tree[category_name].should_not be_nil
end

Then /^each product should have (a\s)?"([^\"]*)"$/ do |a, attr|
  @products.each do |p|
    p.send(attr).should_not be_nil
  end
end


text:
FROM node:alpine as build
ADD / /app
WORKDIR  /app
RUN pwd && ls -la
RUN npm install
RUN npm run compile
RUN npm prune --production

FROM node:alpine
COPY --from=build /app/node_modules /app/node_modules
COPY --from=build /app/out /app/out
COPY --from=build /app/resources /app/resources
COPY --from=build /app/package.json /app/package.json
COPY --from=build /app/LICENSE.md /app/LICENSE.md
ENV NODE_ENV=production
WORKDIR  /app
CMD node /app/out/index.js


text:
    <meta name="description" content="Pmw - a toolkit for building high-level compound widgets in Python">
    <meta name="content" content="python, megawidget, mega widget, compound widget, gui, tkinter">
    <title>Pmw.Group reference manual</title>

Pmw.Group

Name

Pmw.Group() -
    frame with ring border and tag

Inherits

Pmw.MegaWidget

Description

    This megawidget consists of an interior frame with an exterior
    ring border and an identifying tag displayed over the top edge of
    the ring.  The programmer can create other widgets within the
    interior frame.

Options

Options for this megawidget and its base
classes are described below.

 collapsedsize

Initialisation option. The distance from the bottom of the tag to the bottom of the ring
    when the groupchildsite is collapsed. The default is 6.

 tagindent

Initialisation option. The distance from the left edge of the ring to the left side of
    the tag component. The default is 10.

Components

Components created by this megawidget and its base
classes are described below.

 groupchildsite

The frame which can contain other widgets to be grouped. By default, this component is a Tkinter.Frame.

 hull

This acts as the body for the entire megawidget.  Other components
    are created as children of the hull to further specialise this
    class. By default, this component is a Tkinter.Frame.

 ring

This component acts as the enclosing ring around the
    groupchildsite.  The default borderwidth is 2 and the
    default relief is 'groove'. By default, this component is a Tkinter.Frame.

 tag

The identifying tag displayed over the top edge of the enclosing
    ring.  If the pyclass for this component is None, (ie:
    tag_pyclass = None, then no tag component is created. By default, this component is a Tkinter.Label.

Methods

Only methods specific to this megawidget are described below.
For a description of its inherited methods, see the
manual for its base class
Pmw.MegaWidget.

 collapse()

Do not display the groupchildsite component.

 expand()

Display the groupchildsite component.

 interior()

Return the frame within which the programmer may create widgets.
    This is the same as component('groupchildsite').

 toggle()

Display the groupchildsite component if it is currently hidden and
    hide it if it is currently displayed.

Example

The image at the top of this manual is a snapshot
of the window (or part of the window) produced
by the following code.

class Demo:
    def __init__(self, parent):

        # Create and pack the Groups.
        w = Pmw.Group(parent, tag_text='label')
        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
        cw = Tkinter.Label(w.interior(),
                text = 'A group with the\ndefault Label tag')
        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')

        w = Pmw.Group(parent, tag_pyclass = None)
        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
        cw = Tkinter.Label(w.interior(), text = 'A group\nwithout a tag')
        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')

        radiogroups = []
        self.var = Tkinter.IntVar()
        self.var.set(0)
        radioframe = Tkinter.Frame(parent)
        w = Pmw.Group(radioframe,
                tag_pyclass = Tkinter.Radiobutton,
                tag_text='radiobutton 1',
                tag_value = 0,
                tag_variable = self.var)
        w.pack(fill = 'both', expand = 1, side='left')
        cw = Tkinter.Frame(w.interior(),width=200,height=20)
        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
        radiogroups.append(w)

        w = Pmw.Group(radioframe,
                tag_pyclass = Tkinter.Radiobutton,
                tag_text='radiobutton 2',
                tag_font = Pmw.logicalfont('Helvetica', 4),
                tag_value = 1,
                tag_variable = self.var)
        w.pack(fill = 'both', expand = 1, side='left')
        cw = Tkinter.Frame(w.interior(),width=200,height=20)
        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
        radiogroups.append(w)
        radioframe.pack(padx = 6, pady = 6, expand='yes', fill='both')
        Pmw.aligngrouptags(radiogroups)

        w = Pmw.Group(parent,
                tag_pyclass = Tkinter.Checkbutton,
                tag_text='checkbutton',
                tag_foreground='blue')
        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
        cw = Tkinter.Frame(w.interior(),width=150,height=20)
        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')

        w = Pmw.Group(parent,
                tag_pyclass = Tkinter.Button,
                tag_text='Tkinter.Button')
        w.configure(tag_command = w.toggle)
        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
        cw = Tkinter.Label(w.interior(),
                background = 'aliceblue',
                text = 'A group with\na Button tag!?'
        )
        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')

        w = Pmw.Group(parent,
                tag_pyclass = Tkinter.Button,
                tag_text='Show/Hide')
        w.configure(tag_command = w.toggle)
        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
        cw = Tkinter.Label(w.interior(),
                background = 'aliceblue',
                text = 'Now you see me.\nNow you don\'t.'
        )
        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')

    Pmw 1.3 -
     6 Aug 2007
     - Home

Manual page last reviewed: 15 November 1998


text:
<?php namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;

class Controller extends BaseController
{

    use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;

    /**
     * Setup the layout used by the controller.
     *
     * @return void
     */
    protected function setupLayout()
    {
        if (! is_null($this->layout)) {
            $this->layout = view($this->layout);
        }
    }
}


text:
/// <reference path='../fourslash.ts' />

// @Filename: /lib/tsconfig.json
//// {}

// @Filename: /lib/index.ts
//// const unrelatedLocalVariable = 123;
//// export const someExportedVariable = unrelatedLocalVariable;

// @Filename: /src/tsconfig.json
//// {}

// @Filename: /src/index.ts
//// import * as /*i*/lib from '../lib/index';
//// lib.someExportedVariable;

// @Filename: /tsconfig.json
//// {}

goTo.file("/lib/index.ts");
goTo.file("/src/index.ts");
verify.baselineRename("i", {});


text:
<?php
/**
 * @category   PSystem
 * @package    PSystem_Base
 * @author     Pascal System <info@pascalsystem.pl>
 * @version    1.1.2
 */

/**
 * Pascal Catalog Ajax config block
 *
 * @category   PSystem
 * @package    PSystem_Base
 * @author     Pascal System <info@pascalsystem.pl>
 * @version    1.1.2
 */
class PSystem_Base_Block_Headerjs extends Mage_Core_Block_Abstract {
/**
 * Prepare additional js to head
 *
 * @return string
 */
	public function _toHtml() {
		if (Mage::getStoreConfig('psbase/quickimages/disable'))
			return '';

		if (!$selector = Mage::getStoreConfig('psbase/quickimages/selector')) {
			$selector = 'a.product-image';
		}

		//outer div - ie7,ie8 - bug
		$html = '

';
		return $html;
	}
}


text:
'use strict';

// Configuring the Articles module
angular.module('audioupload' ,['ngUpload']).run(['Menus',
	function(Menus) {
		// Set top bar menu items
		Menus.addMenuItem('topbar', 'AudioFiles', 'audioupload', 'dropdown');
		Menus.addSubMenuItem('topbar', 'audioupload', 'Add File', 'addfile');
        Menus.addSubMenuItem('topbar', 'audioupload', 'Record File', 'recordfile');
	}
]);


text:
import template from './template.html'

// eslint-disable-next-line
@Inject('$log', '$state', 'appResources', 'errorHelpers', '$scope')
class CatCreationController {
  createCat = async () => {
    if (!this.catForm.$valid) {
      return
    }

    const cat = await this.appResources.Cat.save(null, this.cat).$promiseHandled(this.$scope)
    this.$state.go('global.main.cat', { id: cat.id })
  }

  updateCatData = (catData) => {
    this.$log.debug('CatController.updateCatData', catData)
    this.cat = catData
  }
}

const catCreation = {
  template: template,
  controller: CatCreationController,
  bindings: {
    cat: '<'
  }
}

export default catCreation


text:
package io.github.kewne.jackson.hal;

import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class HalModule extends SimpleModule {

    public HalModule() {
        super("hal",
                new Version(0, 1, 0,
                        null, "io.github.kewne", "jackson-datatype-hal"));
        addSerializer(HalLinks.class, new HalLinksSerializer());
        addSerializer(HalRel.class, new HalRelSerializer());
        addDeserializer(HalLinks.class, new HalLinksDeserializer());
        addDeserializer(HalRel.class, new HalRelDeserializer());
    }
}


text:
Ext.define('SlateAdmin.view.progress.terms.SectionsGrid', {
    extend: 'Ext.grid.Panel',
    xtype: 'progress-terms-sectionsgrid',
    requires: [
        'Ext.form.field.ComboBox',
        'Ext.form.field.Checkbox',
        'Ext.data.ChainedStore'
    ],

    width: 250,
    store: 'progress.terms.Sections',
    componentCls: 'progress-terms-grid',
    dockedItems: [
        {
            dock: 'top',

            xtype: 'toolbar',
            items: [
                {
                    itemId: 'termSelector',
                    flex: 1,

                    xtype: 'combobox',

                    store: {
                        type: 'chained',
                        source: 'Terms'
                    },
                    queryMode: 'local',
                    valueField: 'Handle',
                    displayField: 'Title',

                    forceSelection: true
                }
            ]
        },
        {
            dock: 'top',

            xtype: 'toolbar',
            items: [
                {
                    xtype: 'checkboxfield',
                    boxLabel: 'Show only my classes',
                    name: 'myClassesOnly'
                }
            ]
        }
    ],
    columns: [{
        flex: 1,

        text: 'Section',
        dataIndex: 'Code'
    }]
});


text:
package com.primateer.daikoku.model.vos;

import java.util.Date;

import com.primateer.daikoku.Application;
import com.primateer.daikoku.R;

public class Meal extends Recipe {

	public enum State {
		SCHEDULED(R.string.meal_state_scheduled,
				Application.ICON_STATE_SCHEDULED), RESERVED(
				R.string.meal_state_reserved, Application.ICON_STATE_RESERVED), PREPARED(
				R.string.meal_state_prepared, Application.ICON_STATE_PREPARED), CONSUMED(
				R.string.meal_state_consumed, Application.ICON_STATE_CONSUMED);

		public final int string;
		public final int icon;

		private State(int string, int icon) {
			this.string = string;
			this.icon = icon;
		}
	}

	private Date due;
	private State state;

	public Meal() {
	}

	public Meal(Recipe recipe) {
		this.setId(recipe.getId());
		this.setLabel(recipe.getLabel());
		this.setFavorite(recipe.isFavorite());
		this.setIngredients(recipe.getIngredients());
		this.setExtraNutrition(recipe.getExtraNutrition());
	}

	public Date getDue() {
		return due;
	}

	public void setDue(Date due) {
		this.due = due;
	}

	public static State getDefaultState() {
		return State.SCHEDULED;
	}

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}

}


text:
package lila.study

import actorApi.Who
import akka.stream.scaladsl._
import chess.Centis
import chess.format.pgn.{ Glyph, Tags }
import scala.concurrent.duration._

import lila.chat.{ Chat, ChatApi }
import lila.common.Bus
import lila.hub.actorApi.timeline.{ Propagate, StudyLike }
import lila.security.Granter
import lila.socket.Socket.Sri
import lila.tree.Node.{ Comment, Gamebook, Shapes }
import lila.user.{ Holder, User }

final class StudyApi(
    studyRepo: StudyRepo,
    chapterRepo: ChapterRepo,
    sequencer: StudySequencer,
    studyMaker: StudyMaker,
    chapterMaker: ChapterMaker,
    inviter: StudyInvite,
    explorerGameHandler: ExplorerGame,
    topicApi: StudyTopicApi,
    lightUserApi: lila.user.LightUserApi,
    scheduler: akka.actor.Scheduler,
    chatApi: ChatApi,
    timeline: lila.hub.actors.Timeline,
    serverEvalRequester: ServerEval.Requester
)(implicit
    ec: scala.concurrent.ExecutionContext,
    mat: akka.stream.Materializer
) {

  import sequencer._

  def byId = studyRepo byId _

  def byIds = studyRepo byOrderedIds _

  def publicIdNames = studyRepo publicIdNames _

  def publicByIds(ids: Seq[Study.Id]) = byIds(ids) map { _.filter(_.isPublic) }

  def byIdAndOwner(id: Study.Id, owner: User) =
    byId(id) map {
      _.filter(s => s isOwner owner.id)
    }

  def isOwner(id: Study.Id, owner: User) = byIdAndOwner(id, owner).map(_.isDefined)

  def byIdAndOwnerOrAdmin(id: Study.Id, owner: User) =
    byId(id) map {
      _.filter(s => s.isOwner(owner.id) || Granter(_.StudyAdmin)(owner))
    }

  def isOwnerOrAdmin(id: Study.Id, owner: User) = byIdAndOwnerOrAdmin(id, owner).map(_.isDefined)

  def byIdWithChapter(id: Study.Id): Fu[Option[Study.WithChapter]] =
    byId(id) flatMap {
      _ ?? { study =>
        chapterRepo byId study.position.chapterId flatMap {
          case None =>
            chapterRepo firstByStudy study.id flatMap {
              case None => fixNoChapter(study)
              case Some(chapter) =>
                val fixed = study withChapter chapter
                studyRepo updateSomeFields fixed inject
                  Study.WithChapter(fixed, chapter).some
            }
          case Some(chapter) => fuccess(Study.WithChapter(study, chapter).some)
        }
      }
    }

  def byIdWithChapter(id: Study.Id, chapterId: Chapter.Id): Fu[Option[Study.WithChapter]] =
    byId(id) flatMap {
      _ ?? { study =>
        chapterRepo byId chapterId map {
          _.filter(_.studyId == study.id) map { Study.WithChapter(study, _) }
        } orElse byIdWithChapter(id)
      }
    }

  def byIdWithFirstChapter(id: Study.Id): Fu[Option[Study.WithChapter]] =
    byIdWithChapterFinder(id, chapterRepo firstByStudy id)

  private[study] def byIdWithLastChapter(id: Study.Id): Fu[Option[Study.WithChapter]] =
    byIdWithChapterFinder(id, chapterRepo lastByStudy id)

  private def byIdWithChapterFinder(
      id: Study.Id,
      chapterFinder: => Fu[Option[Chapter]]
  ): Fu[Option[Study.WithChapter]] =
    byId(id) flatMap {
      _ ?? { study =>
        chapterFinder map {
          _ ?? { Study.WithChapter(study, _).some }
        } orElse byIdWithChapter(id)
      }
    }

  private def fixNoChapter(study: Study): Fu[Option[Study.WithChapter]] =
    sequenceStudy(study.id) { study =>
      chapterRepo existsByStudy study.id flatMap {
        case true => funit
        case _ =>
          chapterMaker.fromFenOrPgnOrBlank(
            study,
            ChapterMaker.Data(Chapter.Name("Chapter 1")),
            order = 1,
            userId = study.ownerId
          ) flatMap chapterRepo.insert
      }
    } >> byIdWithFirstChapter(study.id)

  def studyIdOf = chapterRepo.studyIdOf _

  def members(id: Study.Id): Fu[Option[StudyMembers]] = studyRepo membersById id

  def importGame(data: StudyMaker.ImportGame, user: User): Fu[Option[Study.WithChapter]] =
    (data.form.as match {
      case StudyForm.importGame.AsNewStudy => create(data, user)
      case StudyForm.importGame.AsChapterOf(studyId) =>
        byId(studyId) flatMap {
          case Some(study) if study.canContribute(user.id) =>
            addChapter(
              studyId = study.id,
              data = data.form.toChapterData,
              sticky = study.settings.sticky
            )(Who(user.id, Sri(""))) >> byIdWithLastChapter(studyId)
          case _ => fuccess(none)
        } orElse importGame(data.copy(form = data.form.copy(asStr = none)), user)
    }) addEffect {
      _ ?? { sc =>
        Bus.publish(actorApi.StartStudy(sc.study.id), "startStudy")
      }
    }

  def create(
      data: StudyMaker.ImportGame,
      user: User,
      transform: Study => Study = identity
  ): Fu[Option[Study.WithChapter]] =
    studyMaker(data, user) map { sc =>
      sc.copy(study = transform(sc.study))
    } flatMap { sc =>
      studyRepo.insert(sc.study) >>
        chapterRepo.insert(sc.chapter) >>-
        indexStudy(sc.study) inject sc.some
    }

  def clone(me: User, prev: Study): Fu[Option[Study]] =
    Settings.UserSelection.allows(prev.settings.cloneable, prev, me.id.some) ?? {
      val study1 = prev.cloneFor(me)
      chapterRepo
        .orderedByStudySource(prev.id)
        .map(_ cloneFor study1)
        .mapAsync(4) { c =>
          chapterRepo.insert(c) inject c
        }
        .toMat(Sink.reduce[Chapter] { case (prev, _) => prev })(Keep.right)
        .run()
        .flatMap { (first: Chapter) =>
          val study = study1 rewindTo first
          studyRepo.insert(study) >>
            chatApi.userChat.system(
              Chat.Id(study.id.value),
              s"Cloned from lichess.org/study/${prev.id}",
              _.Study
            ) inject study.some
        }
    }

  def resetIfOld(study: Study, chapters: List[Chapter.Metadata]): Fu[(Study, Option[Chapter])] =
    chapters.headOption match {
      case Some(c) if study.isOld && study.position != c.initialPosition =>
        val newStudy = study rewindTo c
        studyRepo.updateSomeFields(newStudy) zip chapterRepo.byId(c.id) map { case (_, chapter) =>
          newStudy -> chapter
        }
      case _ => fuccess(study -> none)
    }

  def talk(userId: User.ID, studyId: Study.Id, text: String) =
    byId(studyId) foreach {
      _ foreach { study =>
        (study canChat userId) ?? {
          chatApi.userChat.write(
            Chat.Id(studyId.value),
            userId = userId,
            text = text,
            publicSource = lila.hub.actorApi.shutup.PublicSource.Study(studyId.value).some,
            busChan = _.Study
          )
        }
      }
    }

  def setPath(studyId: Study.Id, position: Position.Ref)(who: Who): Funit =
    sequenceStudy(studyId) { study =>
      Contribute(who.u, study) {
        chapterRepo.byId(position.chapterId).map {
          _ filter { c =>
            c.root.pathExists(position.path) && study.position.chapterId == c.id
          }
        } flatMap {
          case None => funit >>- sendTo(study.id)(_.reloadSri(who.sri))
          case Some(chapter) if study.position.path != position.path =>
            studyRepo.setPosition(study.id, position) >>
              updateConceal(study, chapter, position) >>-
              sendTo(study.id)(_.setPath(position, who))
          case _ => funit
        }
      }
    }

  def addNode(
      studyId: Study.Id,
      position: Position.Ref,
      node: Node,
      opts: MoveOpts,
      relay: Option[Chapter.Relay] = None
  )(who: Who): Funit =
    sequenceStudyWithChapter(studyId, position.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        doAddNode(study, Position(chapter, position.path), node, opts, relay)(who)
      }
    } flatMap { _ ?? { _() } } // this one is for you, Lakin <3

  private def doAddNode(
      study: Study,
      position: Position,
      rawNode: Node,
      opts: MoveOpts,
      relay: Option[Chapter.Relay]
  )(who: Who): Fu[Option[() => Funit]] = {
    val singleNode   = rawNode.withoutChildren
    def failReload() = reloadSriBecauseOf(study, who.sri, position.chapter.id)
    if (position.chapter.isOverweight) {
      logger.info(s"Overweight chapter ${study.id}/${position.chapter.id}")
      failReload()
      fuccess(none)
    } else
      position.chapter.addNode(singleNode, position.path, relay) match {
        case None =>
          failReload()
          fufail(s"Invalid addNode ${study.id} ${position.ref} $singleNode")
        case Some(chapter) =>
          chapter.root.nodeAt(position.path) ?? { parent =>
            parent.children.get(singleNode.id) ?? { node =>
              val newPosition = position.ref + node
              chapterRepo.addSubTree(node, parent addChild node, position.path)(chapter) >>
                (relay ?? { chapterRepo.setRelay(chapter.id, _) }) >>
                (opts.sticky ?? studyRepo.setPosition(study.id, newPosition)) >>
                updateConceal(study, chapter, newPosition) >>-
                sendTo(study.id)(
                  _.addNode(
                    position.ref,
                    node,
                    chapter.setup.variant,
                    sticky = opts.sticky,
                    relay = relay,
                    who
                  )
                ) inject {
                  (opts.promoteToMainline && !Path.isMainline(chapter.root, newPosition.path)) option { () =>
                    promote(study.id, position.ref + node, toMainline = true)(who)
                  }
                }
            }
          }
      }
  }

  private def updateConceal(study: Study, chapter: Chapter, position: Position.Ref) =
    chapter.conceal ?? { conceal =>
      chapter.root.lastMainlinePlyOf(position.path).some.filter(_ > conceal) ?? { newConceal =>
        if (newConceal >= chapter.root.lastMainlinePly)
          chapterRepo.removeConceal(chapter.id) >>-
            sendTo(study.id)(_.setConceal(position, none))
        else
          chapterRepo.setConceal(chapter.id, newConceal) >>-
            sendTo(study.id)(_.setConceal(position, newConceal.some))
      }
    }

  def deleteNodeAt(studyId: Study.Id, position: Position.Ref)(who: Who) =
    sequenceStudyWithChapter(studyId, position.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        chapter.updateRoot { root =>
          root.withChildren(_.deleteNodeAt(position.path))
        } match {
          case Some(newChapter) =>
            chapterRepo.update(newChapter) >>-
              sendTo(study.id)(_.deleteNode(position, who))
          case None =>
            fufail(s"Invalid delNode $studyId $position") >>-
              reloadSriBecauseOf(study, who.sri, chapter.id)
        }
      }
    }

  def clearAnnotations(studyId: Study.Id, chapterId: Chapter.Id)(who: Who) =
    sequenceStudyWithChapter(studyId, chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        chapterRepo.update(chapter.updateRoot { root =>
          root.withChildren(_.updateAllWith(_.clearAnnotations).some)
        } | chapter) >>- sendTo(study.id)(_.updateChapter(chapter.id, who))
      }
    }

  // rewrites the whole chapter because of `forceVariation`. Very inefficient.
  def promote(studyId: Study.Id, position: Position.Ref, toMainline: Boolean)(who: Who): Funit =
    sequenceStudyWithChapter(studyId, position.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        chapter.updateRoot { root =>
          root.withChildren { children =>
            if (toMainline) children.promoteToMainlineAt(position.path)
            else children.promoteUpAt(position.path).map(_._1)
          }
        } match {
          case Some(newChapter) =>
            chapterRepo.update(newChapter) >>-
              sendTo(study.id)(_.promote(position, toMainline, who)) >>
              newChapter.root.children
                .nodesOn {
                  newChapter.root.mainlinePath.intersect(position.path)
                }
                .collect {
                  case (node, path) if node.forceVariation =>
                    doForceVariation(Study.WithChapter(study, newChapter), path, force = false, who)
                }
                .sequenceFu
                .void
          case None =>
            fufail(s"Invalid promoteToMainline $studyId $position") >>-
              reloadSriBecauseOf(study, who.sri, chapter.id)
        }
      }
    }

  def forceVariation(studyId: Study.Id, position: Position.Ref, force: Boolean)(who: Who): Funit =
    sequenceStudyWithChapter(studyId, position.chapterId) { sc =>
      Contribute(who.u, sc.study) {
        doForceVariation(sc, position.path, force, who)
      }
    }

  private def doForceVariation(sc: Study.WithChapter, path: Path, force: Boolean, who: Who): Funit =
    sc.chapter.forceVariation(force, path) match {
      case Some(newChapter) =>
        chapterRepo.forceVariation(force)(newChapter, path) >>-
          sendTo(sc.study.id)(_.forceVariation(Position(newChapter, path).ref, force, who))
      case None =>
        fufail(s"Invalid forceVariation ${Position(sc.chapter, path)} $force") >>-
          reloadSriBecauseOf(sc.study, who.sri, sc.chapter.id)
    }

  def setRole(studyId: Study.Id, userId: User.ID, roleStr: String)(who: Who) =
    sequenceStudy(studyId) { study =>
      canActAsOwner(study, who.u) flatMap {
        _ ?? {
          val role    = StudyMember.Role.byId.getOrElse(roleStr, StudyMember.Role.Read)
          val members = study.members.update(userId, _.copy(role = role))
          studyRepo.setRole(study, userId, role) >>- onMembersChange(study, members, members.ids)
        }
      }
    }

  def invite(
      byUserId: User.ID,
      studyId: Study.Id,
      username: String,
      isPresent: User.ID => Fu[Boolean],
      onError: String => Unit
  ) =
    sequenceStudy(studyId) { study =>
      inviter(byUserId, study, username, isPresent)
        .addEffects(
          err => onError(err.getMessage),
          user => {
            val members = study.members + StudyMember.make(user)
            onMembersChange(study, members, members.ids)
          }
        )
        .void
    }

  def kick(studyId: Study.Id, userId: User.ID)(who: Who) =
    sequenceStudy(studyId) { study =>
      studyRepo.isAdminMember(study, who.u) flatMap { isAdmin =>
        val allowed = study.isMember(userId) && {
          (isAdmin && !study.isOwner(userId)) || (study.isOwner(who.u) ^ (who.u == userId))
        }
        allowed ?? {
          studyRepo.removeMember(study, userId) >>-
            onMembersChange(study, (study.members - userId), study.members.ids)
        }
      }
    }

  def isContributor = studyRepo.isContributor _
  def isMember      = studyRepo.isMember _

  private def onMembersChange(
      study: Study,
      members: StudyMembers,
      sendToUserIds: Iterable[User.ID]
  ): Unit = {
    sendTo(study.id)(_.reloadMembers(members, sendToUserIds))
    indexStudy(study)
  }

  def setShapes(studyId: Study.Id, position: Position.Ref, shapes: Shapes)(who: Who) =
    sequenceStudy(studyId) { study =>
      Contribute(who.u, study) {
        chapterRepo.byIdAndStudy(position.chapterId, study.id) flatMap {
          _ ?? { chapter =>
            chapter.setShapes(shapes, position.path) match {
              case Some(newChapter) =>
                studyRepo.updateNow(study)
                chapterRepo.setShapes(shapes)(newChapter, position.path) >>-
                  sendTo(study.id)(_.setShapes(position, shapes, who))
              case None =>
                fufail(s"Invalid setShapes $position $shapes") >>-
                  reloadSriBecauseOf(study, who.sri, chapter.id)
            }
          }
        }
      }
    }

  def setClock(studyId: Study.Id, position: Position.Ref, clock: Option[Centis])(who: Who): Funit =
    sequenceStudyWithChapter(studyId, position.chapterId) {
      doSetClock(_, position, clock)(who)
    }

  private def doSetClock(sc: Study.WithChapter, position: Position.Ref, clock: Option[Centis])(
      who: Who
  ): Funit =
    sc.chapter.setClock(clock, position.path) match {
      case Some(newChapter) =>
        studyRepo.updateNow(sc.study)
        chapterRepo.setClock(clock)(newChapter, position.path) >>-
          sendTo(sc.study.id)(_.setClock(position, clock, who))
      case None =>
        fufail(s"Invalid setClock $position $clock") >>-
          reloadSriBecauseOf(sc.study, who.sri, position.chapterId)
    }

  def setTag(studyId: Study.Id, setTag: actorApi.SetTag)(who: Who) =
    sequenceStudyWithChapter(studyId, setTag.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        doSetTags(study, chapter, PgnTags(chapter.tags + setTag.tag), who)
      }
    }

  def setTags(studyId: Study.Id, chapterId: Chapter.Id, tags: Tags)(who: Who) =
    sequenceStudyWithChapter(studyId, chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        doSetTags(study, chapter, tags, who)
      }
    }

  private def doSetTags(study: Study, oldChapter: Chapter, tags: Tags, who: Who): Funit = {
    val chapter = oldChapter.copy(tags = tags)
    (chapter.tags != oldChapter.tags) ?? {
      chapterRepo.setTagsFor(chapter) >> {
        PgnTags.setRootClockFromTags(chapter) ?? { c =>
          doSetClock(Study.WithChapter(study, c), Position(c, Path.root).ref, c.root.clock)(who)
        }
      } >>-
        sendTo(study.id)(_.setTags(chapter.id, chapter.tags, who))
    } >>- indexStudy(study)
  }

  def setComment(studyId: Study.Id, position: Position.Ref, text: Comment.Text)(who: Who) =
    sequenceStudyWithChapter(studyId, position.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        lightUserApi.async(who.u) flatMap {
          _ ?? { author =>
            val comment = Comment(
              id = Comment.Id.make,
              text = text,
              by = Comment.Author.User(author.id, author.titleName)
            )
            doSetComment(study, Position(chapter, position.path), comment, who)
          }
        }
      }
    }

  private def doSetComment(study: Study, position: Position, comment: Comment, who: Who): Funit =
    position.chapter.setComment(comment, position.path) match {
      case Some(newChapter) =>
        studyRepo.updateNow(study)
        newChapter.root.nodeAt(position.path) ?? { node =>
          node.comments.findBy(comment.by) ?? { c =>
            chapterRepo.setComments(node.comments.filterEmpty)(newChapter, position.path) >>- {
              sendTo(study.id)(_.setComment(position.ref, c, who))
              indexStudy(study)
            }
          }
        }
      case None =>
        fufail(s"Invalid setComment ${study.id} $position") >>-
          reloadSriBecauseOf(study, who.sri, position.chapter.id)
    }

  def deleteComment(studyId: Study.Id, position: Position.Ref, id: Comment.Id)(who: Who) =
    sequenceStudyWithChapter(studyId, position.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        chapter.deleteComment(id, position.path) match {
          case Some(newChapter) =>
            chapterRepo.update(newChapter) >>-
              sendTo(study.id)(_.deleteComment(position, id, who)) >>-
              indexStudy(study)
          case None =>
            fufail(s"Invalid deleteComment $studyId $position $id") >>-
              reloadSriBecauseOf(study, who.sri, chapter.id)
        }
      }
    }

  def toggleGlyph(studyId: Study.Id, position: Position.Ref, glyph: Glyph)(who: Who) =
    sequenceStudyWithChapter(studyId, position.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        chapter.toggleGlyph(glyph, position.path) match {
          case Some(newChapter) =>
            studyRepo.updateNow(study)
            newChapter.root.nodeAt(position.path) ?? { node =>
              chapterRepo.setGlyphs(node.glyphs)(newChapter, position.path) >>-
                newChapter.root.nodeAt(position.path).foreach { node =>
                  sendTo(study.id)(_.setGlyphs(position, node.glyphs, who))
                }
            }
          case None =>
            fufail(s"Invalid toggleGlyph $studyId $position $glyph") >>-
              reloadSriBecauseOf(study, who.sri, chapter.id)
        }
      }
    }

  def setGamebook(studyId: Study.Id, position: Position.Ref, gamebook: Gamebook)(who: Who) =
    sequenceStudyWithChapter(studyId, position.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        chapter.setGamebook(gamebook, position.path) match {
          case Some(newChapter) =>
            studyRepo.updateNow(study)
            chapterRepo.setGamebook(gamebook)(newChapter, position.path) >>-
              indexStudy(study)
          case None =>
            fufail(s"Invalid setGamebook $studyId $position") >>-
              reloadSriBecauseOf(study, who.sri, chapter.id)
        }
      }
    }

  def explorerGame(studyId: Study.Id, data: actorApi.ExplorerGame)(who: Who) =
    sequenceStudyWithChapter(studyId, data.position.chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(who.u, study) {
        if (data.insert)
          explorerGameHandler.insert(study, Position(chapter, data.position.path), data.gameId) flatMap {
            case None =>
              fufail(s"Invalid explorerGame insert $studyId $data") >>-
                reloadSriBecauseOf(study, who.sri, chapter.id)
            case Some((chapter, path)) =>
              studyRepo.updateNow(study)
              chapter.root.nodeAt(path) ?? { parent =>
                chapterRepo.setChildren(parent.children)(chapter, path) >>-
                  sendTo(study.id)(_.reloadAll)
              }
          }
        else
          explorerGameHandler.quote(data.gameId) flatMap {
            _ ?? {
              doSetComment(study, Position(chapter, data.position.path), _, who)
            }
          }
      }
    }

  def addChapter(studyId: Study.Id, data: ChapterMaker.Data, sticky: Boolean)(who: Who): Funit =
    data.manyGames match {
      case Some(datas) =>
        lila.common.Future.applySequentially(datas) { data =>
          addChapter(studyId, data, sticky)(who)
        }
      case _ =>
        sequenceStudy(studyId) { study =>
          Contribute(who.u, study) {
            chapterRepo.countByStudyId(study.id) flatMap { count =>
              if (count >= Study.maxChapters) funit
              else
                data.initial ?? {
                  chapterRepo.firstByStudy(study.id) flatMap {
                    _.filter(_.isEmptyInitial) ?? chapterRepo.delete
                  }
                } >>
                  chapterRepo.nextOrderByStudy(study.id) flatMap { order =>
                    chapterMaker(study, data, order, who.u) flatMap { chapter =>
                      doAddChapter(study, chapter, sticky, who)
                    } addFailureEffect {
                      case ChapterMaker.ValidationException(error) =>
                        sendTo(study.id)(_.validationError(error, who.sri))
                      case u => logger.error(s"StudyApi.addChapter to $studyId", u)
                    }
                  }
            }
          }
        }
    }

  def rename(studyId: Study.Id, name: Study.Name): Funit =
    sequenceStudy(studyId) { old =>
      val study = old.copy(name = name)
      studyRepo.updateSomeFields(study) >>- indexStudy(study)
    }

  def importPgns(studyId: Study.Id, datas: List[ChapterMaker.Data], sticky: Boolean)(who: Who) =
    lila.common.Future.applySequentially(datas) { data =>
      addChapter(studyId, data, sticky)(who)
    }

  def doAddChapter(study: Study, chapter: Chapter, sticky: Boolean, who: Who) =
    chapterRepo.insert(chapter) >> {
      val newStudy = study withChapter chapter
      (sticky ?? studyRepo.updateSomeFields(newStudy)) >>-
        sendTo(study.id)(_.addChapter(newStudy.position, sticky, who))
    } >>
      studyRepo.updateNow(study) >>-
      indexStudy(study)

  def setChapter(studyId: Study.Id, chapterId: Chapter.Id)(who: Who) =
    sequenceStudy(studyId) { study =>
      study.canContribute(who.u) ?? doSetChapter(study, chapterId, who)
    }

  private def doSetChapter(study: Study, chapterId: Chapter.Id, who: Who) =
    (study.position.chapterId != chapterId) ?? {
      chapterRepo.byIdAndStudy(chapterId, study.id) flatMap {
        _ ?? { chapter =>
          val newStudy = study withChapter chapter
          studyRepo.updateSomeFields(newStudy) >>-
            sendTo(study.id)(_.changeChapter(newStudy.position, who))
        }
      }
    }

  def editChapter(studyId: Study.Id, data: ChapterMaker.EditData)(who: Who) =
    sequenceStudy(studyId) { study =>
      Contribute(who.u, study) {
        chapterRepo.byIdAndStudy(data.id, studyId) flatMap {
          _ ?? { chapter =>
            val name = Chapter fixName data.name
            val newChapter = chapter.copy(
              name = name,
              practice = data.isPractice option true,
              gamebook = data.isGamebook option true,
              conceal = (chapter.conceal, data.isConceal) match {
                case (None, true)     => Chapter.Ply(chapter.root.ply).some
                case (Some(_), false) => None
                case _                => chapter.conceal
              },
              setup = chapter.setup.copy(
                orientation = data.realOrientation match {
                  case ChapterMaker.Orientation.Fixed(color) => color
                  case _                                     => chapter.setup.orientation
                }
              ),
              description = data.hasDescription option {
                chapter.description | "-"
              }
            )
            if (chapter == newChapter) funit
            else
              chapterRepo.update(newChapter) >> {
                if (chapter.conceal != newChapter.conceal) {
                  (newChapter.conceal.isDefined && study.position.chapterId == chapter.id).?? {
                    val newPosition = study.position.withPath(Path.root)
                    studyRepo.setPosition(study.id, newPosition)
                  } >>-
                    sendTo(study.id)(_.reloadAll)
                } else
                  fuccess {
                    val shouldReload =
                      (newChapter.setup.orientation != chapter.setup.orientation) ||
                        (newChapter.practice != chapter.practice) ||
                        (newChapter.gamebook != chapter.gamebook) ||
                        (newChapter.description != chapter.description)
                    if (shouldReload) sendTo(study.id)(_.updateChapter(chapter.id, who))
                    else reloadChapters(study)
                  }
              }
          } >>- indexStudy(study)
        }
      }
    }

  def descChapter(studyId: Study.Id, data: ChapterMaker.DescData)(who: Who) =
    sequenceStudy(studyId) { study =>
      Contribute(who.u, study) {
        chapterRepo.byIdAndStudy(data.id, studyId) flatMap {
          _ ?? { chapter =>
            val newChapter = chapter.copy(
              description = data.clean.nonEmpty option data.clean
            )
            (chapter != newChapter) ?? {
              chapterRepo.update(newChapter) >>- {
                sendTo(study.id)(_.descChapter(newChapter.id, newChapter.description, who))
                indexStudy(study)
              }
            }
          }
        }
      }
    }

  def deleteChapter(studyId: Study.Id, chapterId: Chapter.Id)(who: Who) =
    sequenceStudy(studyId) { study =>
      Contribute(who.u, study) {
        chapterRepo.byIdAndStudy(chapterId, studyId) flatMap {
          _ ?? { chapter =>
            chapterRepo.orderedMetadataByStudy(studyId).flatMap { chaps =>
              // deleting the only chapter? Automatically create an empty one
              if (chaps.sizeIs < 2) {
                chapterMaker(study, ChapterMaker.Data(Chapter.Name("Chapter 1")), 1, who.u) flatMap { c =>
                  doAddChapter(study, c, sticky = true, who) >> doSetChapter(study, c.id, who)
                }
              } // deleting the current chapter? Automatically move to another one
              else
                (study.position.chapterId == chapterId).?? {
                  chaps.find(_.id != chapterId) ?? { newChap =>
                    doSetChapter(study, newChap.id, who)
                  }
                }
            } >> chapterRepo.delete(chapter.id) >>- reloadChapters(study)
          } >>- indexStudy(study)
        }
      }
    }

  def sortChapters(studyId: Study.Id, chapterIds: List[Chapter.Id])(who: Who) =
    sequenceStudy(studyId) { study =>
      Contribute(who.u, study) {
        chapterRepo.sort(study, chapterIds) >>- reloadChapters(study)
      }
    }

  def descStudy(studyId: Study.Id, desc: String)(who: Who) =
    sequenceStudy(studyId) { study =>
      Contribute(who.u, study) {
        val newStudy = study.copy(description = desc.nonEmpty option desc)
        (study != newStudy) ?? {
          studyRepo.updateSomeFields(newStudy) >>-
            sendTo(study.id)(_.descStudy(newStudy.description, who)) >>-
            indexStudy(study)
        }
      }
    }

  def setTopics(studyId: Study.Id, topicStrs: List[String])(who: Who) =
    sequenceStudy(studyId) { study =>
      Contribute(who.u, study) {
        val topics    = StudyTopics.fromStrs(topicStrs)
        val newStudy  = study.copy(topics = topics.some)
        val newTopics = study.topics.fold(topics)(topics.diff)
        (study != newStudy) ?? {
          studyRepo.updateTopics(newStudy) >>
            topicApi.userTopicsAdd(who.u, newTopics) >>- {
              sendTo(study.id)(_.setTopics(topics, who))
              indexStudy(study)
              topicApi.recompute()
            }
        }
      }
    }

  def addTopics(studyId: Study.Id, topics: List[String]) =
    sequenceStudy(studyId) { study =>
      studyRepo.updateTopics(study addTopics StudyTopics.fromStrs(topics))
    }

  def editStudy(studyId: Study.Id, data: Study.Data)(who: Who) =
    sequenceStudy(studyId) { study =>
      canActAsOwner(study, who.u) flatMap { asOwner =>
        data.settings.ifTrue(asOwner) ?? { settings =>
          val newStudy = study.copy(
            name = Study toName data.name,
            settings = settings,
            visibility = data.vis,
            description = settings.description option {
              study.description.filter(_.nonEmpty) | "-"
            }
          )
          (newStudy != study) ?? {
            studyRepo.updateSomeFields(newStudy) >>-
              sendTo(study.id)(_.reloadAll) >>-
              indexStudy(study)
          }
        }
      }
    }

  def delete(study: Study) =
    sequenceStudy(study.id) { study =>
      studyRepo.delete(study) >>
        chapterRepo.deleteByStudy(study)
    }

  def like(studyId: Study.Id, v: Boolean)(who: Who): Funit =
    studyRepo.like(studyId, who.u, v) map { likes =>
      sendTo(studyId)(_.setLiking(Study.Liking(likes, v), who))
      if (v) studyRepo byId studyId foreach {
        _.filter(_.isPublic) foreach { study =>
          timeline ! (Propagate(StudyLike(who.u, study.id.value, study.name.value)) toFollowersOf who.u)
        }
      }
    }

  def resetAllRanks = studyRepo.resetAllRanks

  def chapterIdNames(studyIds: List[Study.Id]): Fu[Map[Study.Id, Vector[Chapter.IdName]]] =
    chapterRepo.idNamesByStudyIds(studyIds, Study.maxChapters)

  def chapterMetadatas = chapterRepo.orderedMetadataByStudy _

  def withLiked(me: Option[User])(studies: Seq[Study]): Fu[Seq[Study.WithLiked]] =
    me.?? { u =>
      studyRepo.filterLiked(u, studies.map(_.id))
    } map { liked =>
      studies.map { study =>
        Study.WithLiked(study, liked(study.id))
      }
    }

  def analysisRequest(studyId: Study.Id, chapterId: Chapter.Id, userId: User.ID): Funit =
    sequenceStudyWithChapter(studyId, chapterId) { case Study.WithChapter(study, chapter) =>
      Contribute(userId, study) {
        serverEvalRequester(study, chapter, userId)
      }
    }

  def deleteAllChapters(studyId: Study.Id, by: User) =
    sequenceStudy(studyId) { study =>
      Contribute(by.id, study) {
        chapterRepo deleteByStudy study
      }
    }

  def adminInvite(studyId: Study.Id, me: Holder): Funit =
    sequenceStudy(studyId) { inviter.admin(_, me) }

  private def indexStudy(study: Study) =
    Bus.publish(actorApi.SaveStudy(study), "study")

  private def reloadSriBecauseOf(study: Study, sri: Sri, chapterId: Chapter.Id) =
    sendTo(study.id)(_.reloadSriBecauseOf(sri, chapterId))

  def reloadChapters(study: Study) =
    chapterRepo.orderedMetadataByStudy(study.id).foreach { chapters =>
      sendTo(study.id)(_ reloadChapters chapters)
    }

  private def canActAsOwner(study: Study, userId: User.ID): Fu[Boolean] =
    fuccess(study isOwner userId) >>| studyRepo.isAdminMember(study, userId)

  import ornicar.scalalib.Zero
  private def Contribute[A](userId: User.ID, study: Study)(f: => A)(implicit default: Zero[A]): A =
    if (study canContribute userId) f else default.zero

  // work around circular dependency
  private var socket: Option[StudySocket] = None
  private[study] def registerSocket(s: StudySocket) = { socket = s.some }
  private def sendTo(studyId: Study.Id)(f: StudySocket => Study.Id => Unit): Unit =
    socket foreach { s =>
      f(s)(studyId)
    }
}


text:
{% extends "disciplines/base.html" %}
{% load mptt_tags %}

{% block head_title %}Disciplines{% endblock %}

{% block breadcrumbs %}

Disciplines

{% endblock %}

{% block body %}

        Have a suggestion for adding, removing, or reorganizing our discipline
        structure? Submit Feedback by using the button on the left or by going
        to the Submit Feedback page.

    Discipline Tree:

        {% full_tree_for_model disciplines.Discipline as discipline_set %}

        {% for discipline,structure in discipline_set|tree_info %}
            {% if structure.new_level %}

            {% else %}

            {% endif %}
                {{ discipline }}
            {% for level in structure.closed_levels %}

{% endfor %}
        {% endfor %}

{% endblock body %}