text:
from test_main import PatternyTest
from patterny.config import Config
from patterny.db.dao import MongoDB, Bugs, Comments
from patterny.bugzilla.bug import Bug
from patterny.bugzilla.comment import Comment
from nose.tools import assert_not_equal, assert_equal
from utils import CONFIG_FILE

class MongoDBTest(PatternyTest):
    @classmethod
    def setup_class(cls):
        with open(CONFIG_FILE) as f:
            config = Config(f)
            cls.mongo = MongoDB(config)
            assert_not_equal(cls.mongo.db, None)

    def setup(self):
        pass

    @classmethod
    def teardown_class(cls):
        with open(CONFIG_FILE) as f:
            config = Config(f)
            cls.mongo = MongoDB(config)
            cls.mongo.client.drop_database(config.mongo_db)

    def test_mongodb(self):
        mongo = MongoDB(self.load_config())
        assert_not_equal(mongo.client, None, msg='Mongo client connection to MongoDB should not be None')
        assert_not_equal(mongo.db, None, msg='Mongo DB connection to MongoDB should not be None')

    def test_bugs(self):
        bugs = Bugs(self.load_config())
        assert_not_equal(bugs.client, None, msg='Mongo client connection to MongoDB should not be None')
        assert_not_equal(bugs.db, None, msg='Mongo DB connection to MongoDB should not be None')

    def test_bugs_insert(self):
        bug = Bug(dict(id=123, summary='Simple insert'))
        bugs = Bugs(self.load_config())
        result = bugs.insert(bug.to_dict())
        assert_not_equal(result, None)

    def test_comments_insert(self):
        comment = Comment(dict(id=1234, bug_id=123, text='I just wrote a new Selenium script to test custom fields'))
        comments = Comments(self.load_config())
        result = comments.insert(comment.to_dict())
        assert_not_equal(result, None)

    def test_comments_insert_many(self):
        data = [
            {
                "author": "neonimion@hotmail.com",
                "bug_id": 298692,
                "creator": "neonimion@hotmail.com",
                "id": 2535102,
                "text": "User-Agent:       Mozilla/5.0 (Windows; U; Windows NT 5.1; nl-NL; rv:1.7.8) Gecko/20050511 Firefox/1.0.4\nBuild Identifier: Mozilla/5.0 (Windows; U; Windows NT 5.1; nl-NL; rv:1.7.8) Gecko/20050511 Firefox/1.0.4\n\nWhen I scroll up or down in the bookmark menu it always scrolls back automaticly.\nI first need to go to an arrow and than when it goes up or down I can scroll\nwithout any problems.\n\nReproducible: Always\n\nSteps to Reproduce:\n1.go to the bookmark menu\n2.and start scrolling\n3.\n\nActual Results:  \nthe bookmark menu goes back up or down after the scrolling.\n\nExpected Results:  \nit should scroll up or down without scrolling back again.\n\nI have a long bookmark list"
            },
            {
                "author": "kbrosnan@gmail.com",
                "bug_id": 298692,
                "creator": "kbrosnan@gmail.com",
                "id": 2535110,
                "text": "\n\n*** This bug has been marked as a duplicate of 51004 ***"
            },
            {
                "author": "neonimion@hotmail.com",
                "bug_id": 298692,
                "creator": "neonimion@hotmail.com",
                "id": 2535117,
                "text": "the bookmark menu scrolls back when I open it and try to scroll up or down."
            }
        ]
        comments = Comments(self.load_config())
        result = comments.insert_many(data)
        assert_not_equal(result, None)

    def test_comments_find(self):
        data = [
            {
                "author": "neonimion@hotmail.com",
                "bug_id": 12345,
                "creator": "neonimion@hotmail.com",
                "id": 4321,
                "text": "User-Agent:       Mozilla/5.0 (Windows; U; Windows NT 5.1; nl-NL; rv:1.7.8) Gecko/20050511 Firefox/1.0.4\nBuild Identifier: Mozilla/5.0 (Windows; U; Windows NT 5.1; nl-NL; rv:1.7.8) Gecko/20050511 Firefox/1.0.4\n\nWhen I scroll up or down in the bookmark menu it always scrolls back automaticly.\nI first need to go to an arrow and than when it goes up or down I can scroll\nwithout any problems.\n\nReproducible: Always\n\nSteps to Reproduce:\n1.go to the bookmark menu\n2.and start scrolling\n3.\n\nActual Results:  \nthe bookmark menu goes back up or down after the scrolling.\n\nExpected Results:  \nit should scroll up or down without scrolling back again.\n\nI have a long bookmark list"
            },
            {
                "author": "kbrosnan@gmail.com",
                "bug_id": 12346,
                "creator": "kbrosnan@gmail.com",
                "id": 54321,
                "text": "\n\n*** This bug has been marked as a duplicate of 51004 ***"
            },
            {
                "author": "neonimion@hotmail.com",
                "bug_id": 12345,
                "creator": "neonimion@hotmail.com",
                "id": 654321,
                "text": "the bookmark menu scrolls back when I open it and try to scroll up or down."
            }
        ]
        comments = Comments(self.load_config())
        insert_ids = comments.insert_many(data)
        assert_not_equal(insert_ids, None)

        queried_comments = comments.find()
        assert_not_equal(queried_comments, None)

        queried_comments = comments.find(query={"bug_id": 12345})
        assert_not_equal(queried_comments, None)
        assert_equal(len(queried_comments), 2)


text:
package org.apache.sentry.tests.e2e.hive;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Random;

import com.google.common.io.Resources;
import junit.framework.Assert;

import org.apache.sentry.provider.file.PolicyFile;
import org.apache.sentry.tests.e2e.hive.hiveserver.HiveServerFactory;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestUriPermissions extends AbstractTestWithStaticConfiguration {
  private static final Logger LOGGER = LoggerFactory.
          getLogger(TestUriPermissions.class);

  private PolicyFile policyFile;
  private File dataFile;
  private String loadData;

  @BeforeClass
  public static void setupTestStaticConfiguration () throws Exception {
    AbstractTestWithStaticConfiguration.setupTestStaticConfiguration();
  }

  @Before
  public void setup() throws Exception {
    policyFile = super.setupPolicy();
    super.setup();
  }

  // test load data into table
  @Test
  public void testLoadPrivileges() throws Exception {
    dataFile = new File(dataDir, SINGLE_TYPE_DATA_FILE_NAME);
    FileOutputStream to = new FileOutputStream(dataFile);
    Resources.copy(Resources.getResource(SINGLE_TYPE_DATA_FILE_NAME), to);
    to.close();
    loadData = "server=server1->uri=file://" + dataFile.getPath();

    String tabName = "tab1";
    Connection userConn = null;
    Statement userStmt = null;

    // create dbs
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("use default");
    adminStmt.execute("CREATE DATABASE " + DB1);
    adminStmt.execute("use " + DB1);
    adminStmt.execute("CREATE TABLE " + tabName + "(id int)");
    context.close();

    policyFile
            .addRolesToGroup(USERGROUP1, "db1_read", "db1_write", "data_read")
            .addRolesToGroup(USERGROUP2, "db1_write")
            .addPermissionsToRole("db1_write", "server=server1->db=" + DB1 + "->table=" + tabName + "->action=INSERT")
            .addPermissionsToRole("db1_read", "server=server1->db=" + DB1 + "->table=" + tabName + "->action=SELECT")
            .addPermissionsToRole("data_read", loadData);
    writePolicyFile(policyFile);

    // positive test, user1 has access to file being loaded
    userConn = context.createConnection(USER1_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    userStmt.execute("load data local inpath 'file://" + dataFile.getPath() +
        "' into table " + tabName);
    userStmt.execute("select * from " + tabName + " limit 1");
    ResultSet res = userStmt.getResultSet();
    Assert.assertTrue("Table should have data after load", res.next());
    res.close();
    context.close();

    // Negative test, user2 doesn't have access to the file being loaded
    userConn = context.createConnection(USER2_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    context.assertAuthzException(userStmt, "load data local inpath 'file://" + dataFile.getPath() +
        "' into table " + tabName);
    userStmt.close();
    userConn.close();
  }

  // Test alter partition location
  @Test
  public void testAlterPartitionLocationPrivileges() throws Exception {
    String tabName = "tab1";
    String newPartitionDir = "foo";
    String tabDir = hiveServer.getProperty(HiveServerFactory.WAREHOUSE_DIR) +
      "/" + tabName + "/" + newPartitionDir;
    Connection userConn = null;
    Statement userStmt = null;

    // create dbs
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("use default");
    adminStmt.execute("CREATE DATABASE " + DB1);
    adminStmt.execute("use " + DB1);
    adminStmt.execute("CREATE TABLE " + tabName + " (id int) PARTITIONED BY (dt string)");
    adminCon.close();

    policyFile
        .addRolesToGroup(USERGROUP1, "db1_all", "data_read")
        .addRolesToGroup(USERGROUP2, "db1_all")
        .addRolesToGroup(USERGROUP3, "db1_tab1_all", "data_read")
        .addPermissionsToRole("db1_all", "server=server1->db=" + DB1)
        .addPermissionsToRole("db1_tab1_all", "server=server1->db=" + DB1 + "->table=" + tabName)
        .addPermissionsToRole("data_read", "server=server1->uri=" + tabDir);
    writePolicyFile(policyFile);

    // positive test: user1 has privilege to alter table add partition but not set location
    userConn = context.createConnection(USER1_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    userStmt.execute("ALTER TABLE " + tabName + " ADD IF NOT EXISTS PARTITION (dt = '21-Dec-2012') " +
            " LOCATION '" + tabDir + "'");
    userStmt.execute("ALTER TABLE " + tabName + " DROP PARTITION (dt = '21-Dec-2012')");
    userStmt.execute("ALTER TABLE " + tabName + " ADD PARTITION (dt = '21-Dec-2012') " +
        " LOCATION '" + tabDir + "'");
    userStmt.execute(
        "ALTER TABLE " + tabName + " PARTITION (dt = '21-Dec-2012') " + " SET LOCATION '" + tabDir + "'");
    userConn.close();

    // negative test: user2 doesn't have privilege to alter table add partition
    userConn = context.createConnection(USER2_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    context.assertAuthzException(userStmt,
        "ALTER TABLE " + tabName + " ADD PARTITION (dt = '22-Dec-2012') " +
          " LOCATION '" + tabDir + "/foo'");
    // positive test, user2 can alter managed partitions
    userStmt.execute("ALTER TABLE " + tabName + " ADD PARTITION (dt = '22-Dec-2012')");
    userStmt.execute("ALTER TABLE " + tabName + " DROP PARTITION (dt = '22-Dec-2012')");
    userStmt.execute("ALTER TABLE " + tabName + " ADD IF NOT EXISTS PARTITION (dt = '22-Dec-2012')");
    userStmt.execute("ALTER TABLE " + tabName + " DROP PARTITION (dt = '22-Dec-2012')");
    userConn.close();

    // positive test: user3 has privilege to add/drop partitions
    userConn = context.createConnection(USER3_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    userStmt.execute(
        "ALTER TABLE " + tabName + " ADD PARTITION (dt = '22-Dec-2012') " +
          " LOCATION '" + tabDir + "/foo'");
    userStmt.execute(
        "ALTER TABLE " + tabName + " DROP PARTITION (dt = '21-Dec-2012')");

    userStmt.close();
    userConn.close();
  }

  // test alter table set location
  @Test
  public void testAlterTableLocationPrivileges() throws Exception {
    String tabName = "tab1";
    String tabDir = hiveServer.getProperty(HiveServerFactory.WAREHOUSE_DIR) + "/" + tabName;
    Connection userConn = null;
    Statement userStmt = null;

    // create dbs
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("use default");
    adminStmt.execute("CREATE DATABASE " + DB1);
    adminStmt.execute("use " + DB1);
    adminStmt.execute("CREATE TABLE " + tabName + " (id int)  PARTITIONED BY (dt string)");
    adminCon.close();

    policyFile
            .addRolesToGroup(USERGROUP1, "server1_all")
            .addRolesToGroup(USERGROUP2, "db1_all, data_read")
            .addPermissionsToRole("db1_all", "server=server1->db=" + DB1)
            .addPermissionsToRole("data_read", "server=server1->URI=" + tabDir)
            .addPermissionsToRole("server1_all", "server=server1");
    writePolicyFile(policyFile);

    // positive test: user2 has privilege to alter table set partition
    userConn = context.createConnection(USER2_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    userStmt.execute(
        "ALTER TABLE " + tabName + " SET LOCATION '" + tabDir +  "'");
    userConn.close();

    // positive test: user1 has privilege to alter table set partition
    userConn = context.createConnection(USER1_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    userStmt.execute("ALTER TABLE " + tabName + " SET LOCATION '" + tabDir + "'");
    userConn.close();
  }

  // Test external table
  @Test
  public void testExternalTablePrivileges() throws Exception {
    Connection userConn = null;
    Statement userStmt = null;

    String dataDirPath = "file://" + dataDir;
    String tableDir = dataDirPath + "/" + Math.random();

    //Hive needs write permissions on this local directory
    baseDir.setWritable(true, false);
    dataDir.setWritable(true, false);

    // create dbs
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("use default");
    adminStmt.execute("CREATE DATABASE " + DB1);
    adminStmt.close();
    adminCon.close();

    policyFile
            .addRolesToGroup(USERGROUP1, "db1_all", "data_read")
            .addRolesToGroup(USERGROUP2, "db1_all")
            .addPermissionsToRole("db1_all", "server=server1->db=" + DB1)
            .addPermissionsToRole("data_read", "server=server1->URI=" + dataDirPath);
    writePolicyFile(policyFile);

    // negative test: user2 doesn't have privilege to create external table in given path
    userConn = context.createConnection(USER2_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    context.assertAuthzException(userStmt,
        "CREATE EXTERNAL TABLE extab1(id INT) LOCATION '" + tableDir + "'");
    context.assertAuthzException(userStmt, "CREATE TABLE extab1(id INT) LOCATION '" + tableDir + "'");
    userStmt.close();
    userConn.close();

    // positive test: user1 has privilege to create external table in given path
    userConn = context.createConnection(USER1_1);
    userStmt = context.createStatement(userConn);
    userStmt.execute("use " + DB1);
    userStmt.execute("CREATE EXTERNAL TABLE extab1(id INT) LOCATION '" + tableDir + "'");
    userStmt.execute("DROP TABLE extab1");
    userStmt.execute("CREATE TABLE extab1(id INT) LOCATION '" + tableDir + "'");
    userStmt.close();
    userConn.close();
  }

}

redpajama_set_name: RedPajamaGithub


text:
import functools

import mandelbrot

def _process_chunk(chunk, function, **args):
    (x, y_range, res, ims, pitch) = chunk
    results = []
    for y in y_range:
        results.append((x,
                        y,
                        function(res[x] + ims[y], **args),
                        pitch))
    return results

def worker(max_iterations, arbitrary_precision):
    if arbitrary_precision:
        function = mandelbrot.iterations_to_escape_ap
    else:
        function = mandelbrot.iterations_to_escape
    return functools.partial(_process_chunk, function=function, max_iterations=max_iterations)


text:
import random
import unittest

from SDWLE.agents.basic_agents import DoNothingAgent, PredictableAgent
from SDWLE.cards.base import SecretCard
from SDWLE.cards.heroes import Malfurion, Jaina
from SDWLE.cards.minions.rogue import AnubarAmbusher
from SDWLE.engine import Game, Deck, card_lookup
from testsSDW.agents.testing_agents import CardTestingAgent, OneCardPlayingAgent, PlayAndAttackAgent
from testsSDW.testing_utils import generate_game_for, mock
from SDWLE.cards import StonetuskBoar, ArcaneIntellect, Naturalize, Abomination, NerubianEgg, SylvanasWindrunner
from SDWLE.game_objects import Bindable
from SDWLE.cards import SDW01, SDW02, SDW03, SDW04, SDWBasicA, SDWBasicH, SDWBasicT, SDWBasic01, SDWBasic02
from SDWLE.constants import GAMESTATE, CHARACTER_CLASS, MINION_TYPE, TROOP_TYPE, COLOR_TYPE, NATURE_TYPE

class TestGame(unittest.TestCase):
    def setUp(self):
        random.seed(1857)

    def test_state_machine(self):
        game = generate_game_for([SDW01, SDW02, SDW03],
                                 [SDW03, SDW04, SDW02],
                                 PredictableAgent, PredictableAgent, random_order=False)

        game.state_init(GAMESTATE.START)

        for i in range(20):
            game.state_step()

        self.assertEqual(game.game_ended, True)

    def test_create_game(self):
        card_set1 = []
        card_set2 = []
        test_env = self

        for cardIndex in range(0, 30):
            card_set1.append(card_lookup("Stonetusk Boar"))
            card_set2.append(card_lookup("Novice Engineer"))

        deck1 = Deck(card_set1, Malfurion())
        deck2 = Deck(card_set2, Jaina())
        checked_cards = []

        class MockAgent1:
            def do_card_check(self, cards):
                test_env.assertEqual(len(cards), 5)
                checked_cards.append(list(cards))
                return [False, True, True, True, True]

            def set_game(self, game):
                pass

        class MockAgent2:
            def do_card_check(self, cards):
                test_env.assertEqual(len(cards), 5)
                checked_cards.append(list(cards))
                return [False, True, True, False, True]

            def set_game(self, game):
                pass

        agent1 = mock.Mock(spec=MockAgent1(), wraps=MockAgent1())
        agent2 = mock.Mock(spec=MockAgent2(), wraps=MockAgent2())
        game = Game([deck1, deck2], [agent1, agent2])
        game.pre_game()

        self.assertEqual(agent1.method_calls[0][0], "do_card_check", "Agent not asked to select cards")
        self.assertEqual(agent2.method_calls[0][0], "do_card_check", "Agent not asked to select cards")

        self.assertTrue(game.players[0].deck == deck1, "Deck not assigned to player")
        self.assertTrue(game.players[1].deck == deck2, "Deck not assigned to player")

        self.assertTrue(game.players[0].agent == agent1, "Agent not stored in the hearthbreaker")
        self.assertTrue(game.players[1].agent == agent2, "Agent not stored in the hearthbreaker")

        self.assertListEqual(checked_cards[0][1:], game.players[0].hand[1:], "Cards not retained after request")
        self.assertListEqual(checked_cards[1][1:2], game.players[1].hand[1:2], "Cards not retained after request")

    def test_game_start_end(self):
        card_set1 = []
        card_set2 = []

        for cardIndex in range(0, 30):
            card_set1.append(card_lookup("Stonetusk Boar"))
            card_set2.append(card_lookup("Novice Engineer"))

        deck1 = Deck(card_set1, Malfurion())
        deck2 = Deck(card_set2, Jaina())

        agent1 = mock.Mock(spec=DoNothingAgent(), wraps=DoNothingAgent())
        agent2 = mock.Mock(spec=DoNothingAgent(), wraps=DoNothingAgent())
        game = Game([deck1, deck2], [agent1, agent2])

        game.start()

        self.assertEqual(game.game_ended, True)

    # def test_secrets(self):
    #     for secret_type in SecretCard.__subclasses__():
    #         random.seed(1857)
    #         secret = secret_type()
    #         game = generate_game_for(secret_type, StonetuskBoar, CardTestingAgent, DoNothingAgent)
    #         for turn in range(0, secret.mana * 2 - 2):
    #             game.play_single_turn()
    #
    #         def assert_different():
    #             new_events = game.events.copy()
    #             new_events.update(game.other_player.hero.events)
    #             new_events.update(game.other_player.events)
    #             new_events.update(game.current_player.hero.events)
    #             new_events.update(game.current_player.events)
    #             self.assertNotEqual(events, new_events, secret.name)
    #
    #         def assert_same():
    #             new_events = game.events.copy()
    #             new_events.update(game.current_player.hero.events)
    #             new_events.update(game.current_player.events)
    #             new_events.update(game.other_player.hero.events)
    #             new_events.update(game.other_player.events)
    #             self.assertEqual(events, new_events)
    #
    #         game.current_player.bind("turn_ended", assert_different)
    #         game.other_player.bind("turn_ended", assert_same)
    #
    #         # save the events as they are prior to the secret being played
    #         events = game.events.copy()
    #         events.update(game.other_player.hero.events)
    #         events.update(game.other_player.events)
    #         events.update(game.current_player.hero.events)
    #         events.update(game.current_player.events)
    #
    #         # The secret is played, but the events aren't updated until the secret is activated
    #         game.play_single_turn()
    #
    #         self.assertEqual(1, len(game.current_player.secrets))
    #
    #         # Now the events should be changed
    #         game.play_single_turn()
    #
    #         # Now the events should be reset
    #         game.play_single_turn()

    # def test_physical_hero_attacks(self):
    #     game = generate_game_for(Naturalize, ArcaneIntellect, PredictableAgent, PredictableAgent)
    #     for turn in range(0, 4):
    #         game.play_single_turn()
    #
    #     self.assertEqual(30, game.other_player.hero.health)
    #     self.assertEqual(0, game.other_player.hero.armor)
    #     self.assertEqual(29, game.current_player.hero.health)

    # def test_hero_weapon_sheath(self):
    #     game = generate_game_for(AnubarAmbusher, StonetuskBoar, PredictableAgent, PlayAndAttackAgent)
    #
    #     for turn in range(0, 3):
    #         game.play_single_turn()
    #
    #     self.assertEqual(0, len(game.other_player.minions))
    #     self.assertEqual(28, game.current_player.hero.health)
    #
    #     game.play_single_turn()
    #     self.assertEqual(2, len(game.current_player.minions))
    #     self.assertEqual(26, game.other_player.hero.health)

    # def test_deathrattle_ordering(self):
    #     game = generate_game_for(SylvanasWindrunner, [Abomination, NerubianEgg],
    #                              OneCardPlayingAgent, OneCardPlayingAgent)
    #
    #     for turn in range(0, 12):
    #         game.play_single_turn()
    #
    #     self.assertEqual(2, len(game.current_player.minions))
    #     self.assertEqual(1, len(game.other_player.minions))
    #     game.other_player.minions[0].health = 2
    #
    #     game.current_player.minions[1].die(None)
    #     game.check_delayed()
    #
    #     # Everything should die at once, but Sylvanas shouldn't get the Nerubian because its Deathrattle will not have
    #     # gone yet
    #
    #     self.assertEqual(1, len(game.current_player.minions))

class TestBinding(unittest.TestCase):
    def test_bind(self):
        event = mock.Mock()
        binder = Bindable()
        binder.bind("test", event)
        binder.trigger("test", 1, 5, 6)
        event.assert_called_once_with(1, 5, 6)
        binder.unbind("test", event)
        binder.trigger("test")
        event.assert_called_once_with(1, 5, 6)

    def test_bind_once(self):
        event = mock.Mock()
        event2 = mock.Mock()
        binder = Bindable()
        binder.bind_once("test", event)
        binder.bind("test", event2)
        binder.trigger("test", 1, 5, 6)
        event.assert_called_once_with(1, 5, 6)
        event2.assert_called_once_with(1, 5, 6)
        binder.trigger("test")
        event.assert_called_once_with(1, 5, 6)
        self.assertEqual(event2.call_count, 2)


text:
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18051
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PagePerformanceInsights.Handler.Views
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "1.5.4.0")]
    public partial class ResponseDistribution : RazorGenerator.Templating.RazorTemplateBase
    {
#line hidden

        #line 3 "..\..\Handler\Views\ResponseDistribution.cshtml"

	internal PagePerformanceInsights.Handler.ViewModels.ResponseDistributionViewModel ViewModel{get;set;}

        #line default
        #line hidden

        public override void Execute()
        {

WriteLiteral("\r\n\r\n");

WriteLiteral(@"

");

        }
    }
}
#pragma warning restore 1591


text:
import os
from typing import Dict, Tuple
from unittest import mock

import pandas as pd
import pytest

# noinspection PyBroadException
from great_expectations.validator.computed_metric import MetricValue

try:
    # noinspection PyUnresolvedReferences
    from azure.storage.blob import BlobServiceClient
except:
    azure = None

import great_expectations.exceptions as ge_exceptions
from great_expectations.core.batch_spec import RuntimeDataBatchSpec, S3BatchSpec
from great_expectations.core.metric_domain_types import MetricDomainTypes
from great_expectations.execution_engine.pandas_execution_engine import (
    PandasExecutionEngine,
    storage,
)
from great_expectations.util import is_library_loadable
from great_expectations.validator.metric_configuration import MetricConfiguration
from tests.expectations.test_util import get_table_columns_metric

def test_constructor_with_boto3_options():
    # default instantiation
    PandasExecutionEngine()

    # instantiation with custom parameters
    engine = PandasExecutionEngine(discard_subset_failing_expectations=True)
    assert "discard_subset_failing_expectations" in engine.config
    assert engine.config.get("discard_subset_failing_expectations") is True
    custom_boto3_options = {"region_name": "us-east-1"}
    engine = PandasExecutionEngine(boto3_options=custom_boto3_options)
    assert "boto3_options" in engine.config
    assert engine.config.get("boto3_options")["region_name"] == "us-east-1"

def test_reader_fn():
    engine = PandasExecutionEngine()

    # Testing that can recognize basic excel file
    fn = engine._get_reader_fn(path="myfile.xlsx")
    assert "<function read_excel" in str(fn)

    # Testing that can recognize basic sas7bdat file
    fn_read_sas7bdat = engine._get_reader_fn(path="myfile.sas7bdat")
    assert "<function read_sas" in str(fn_read_sas7bdat)

    # Testing that can recognize basic SAS xpt file
    fn_read_xpt = engine._get_reader_fn(path="myfile.xpt")
    assert "<function read_sas" in str(fn_read_xpt)

    # Ensuring that other way around works as well - reader_method should always override path
    fn_new = engine._get_reader_fn(reader_method="read_csv")
    assert "<function" in str(fn_new)

def test_get_domain_records_with_column_domain():
    engine = PandasExecutionEngine()
    df = pd.DataFrame(
        {"a": [1, 2, 3, 4, 5], "b": [2, 3, 4, 5, None], "c": [1, 2, 3, 4, None]}
    )
    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")

    data = engine.get_domain_records(
        domain_kwargs={
            "column": "a",
            "row_condition": "b<5",
            "condition_parser": "pandas",
        }
    )

    expected_column_df = df.iloc[:3]

    assert data.equals(
        expected_column_df
    ), "Data does not match after getting full access compute domain"

def test_get_domain_records_with_column_pair_domain():
    engine = PandasExecutionEngine()
    df = pd.DataFrame(
        {
            "a": [1, 2, 3, 4, 5, 6],
            "b": [2, 3, 4, 5, None, 6],
            "c": [1, 2, 3, 4, 5, None],
        }
    )
    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")

    data = engine.get_domain_records(
        domain_kwargs={
            "column_A": "a",
            "column_B": "b",
            "row_condition": "b>2",
            "condition_parser": "pandas",
            "ignore_row_if": "both_values_are_missing",
        }
    )

    expected_column_pair_df = pd.DataFrame(
        {
            "a": [2, 3, 4, 6],
            "b": [3.0, 4.0, 5.0, 6.0],
            "c": [2.0, 3.0, 4.0, None],
        },
        index=[1, 2, 3, 5],
    )
    assert data.equals(
        expected_column_pair_df
    ), "Data does not match after getting full access compute domain"

    data = engine.get_domain_records(
        domain_kwargs={
            "column_A": "b",
            "column_B": "c",
            "row_condition": "b>2",
            "condition_parser": "pandas",
            "ignore_row_if": "either_value_is_missing",
        }
    )
    data = data.astype(int)

    expected_column_pair_df = pd.DataFrame(
        {"a": [2, 3, 4], "b": [3, 4, 5], "c": [2, 3, 4]}, index=[1, 2, 3]
    )

    assert data.equals(
        expected_column_pair_df
    ), "Data does not match after getting full access compute domain"

    data = engine.get_domain_records(
        domain_kwargs={
            "column_A": "b",
            "column_B": "c",
            "row_condition": "a<6",
            "condition_parser": "pandas",
            "ignore_row_if": "neither",
        }
    )

    expected_column_pair_df = pd.DataFrame(
        {
            "a": [1, 2, 3, 4, 5],
            "b": [2.0, 3.0, 4.0, 5.0, None],
            "c": [1.0, 2.0, 3.0, 4.0, 5.0],
        }
    )

    assert data.equals(
        expected_column_pair_df
    ), "Data does not match after getting full access compute domain"

def test_get_domain_records_with_multicolumn_domain():
    engine = PandasExecutionEngine()
    df = pd.DataFrame(
        {
            "a": [1, 2, 3, 4, None, 5],
            "b": [2, 3, 4, 5, 6, 7],
            "c": [1, 2, 3, 4, None, 6],
        }
    )
    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")

    data = engine.get_domain_records(
        domain_kwargs={
            "column_list": ["a", "c"],
            "row_condition": "b>2",
            "condition_parser": "pandas",
            "ignore_row_if": "all_values_are_missing",
        }
    )
    data = data.astype(int)

    expected_multicolumn_df = pd.DataFrame(
        {"a": [2, 3, 4, 5], "b": [3, 4, 5, 7], "c": [2, 3, 4, 6]}, index=[1, 2, 3, 5]
    )

    assert data.equals(
        expected_multicolumn_df
    ), "Data does not match after getting full access compute domain"

    data = engine.get_domain_records(
        domain_kwargs={
            "column_list": ["b", "c"],
            "row_condition": "a<5",
            "condition_parser": "pandas",
            "ignore_row_if": "any_value_is_missing",
        }
    )
    data = data.astype(int)

    expected_multicolumn_df = pd.DataFrame(
        {"a": [1, 2, 3, 4], "b": [2, 3, 4, 5], "c": [1, 2, 3, 4]}, index=[0, 1, 2, 3]
    )

    assert data.equals(
        expected_multicolumn_df
    ), "Data does not match after getting full access compute domain"

    engine = PandasExecutionEngine()
    df = pd.DataFrame(
        {
            "a": [1, 2, 3, 4, None, 5],
            "b": [2, 3, 4, 5, 6, 7],
            "c": [1, 2, 3, 4, None, 6],
        }
    )
    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")

    data = engine.get_domain_records(
        domain_kwargs={
            "column_list": ["b", "c"],
            "ignore_row_if": "never",
        }
    )

    expected_multicolumn_df = pd.DataFrame(
        {
            "a": [1, 2, 3, 4, None, 5],
            "b": [2, 3, 4, 5, 6, 7],
            "c": [1, 2, 3, 4, None, 6],
        },
        index=[0, 1, 2, 3, 4, 5],
    )

    assert data.equals(
        expected_multicolumn_df
    ), "Data does not match after getting full access compute domain"

def test_get_compute_domain_with_no_domain_kwargs():
    engine = PandasExecutionEngine()
    df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]})

    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")
    data, compute_kwargs, accessor_kwargs = engine.get_compute_domain(
        domain_kwargs={}, domain_type="table"
    )
    assert data.equals(df), "Data does not match after getting compute domain"
    assert compute_kwargs == {}, "Compute domain kwargs should be existent"
    assert accessor_kwargs == {}, "Accessor kwargs have been modified"

    # Trying same test with enum form of table domain - should work the same way
    data, compute_kwargs, accessor_kwargs = engine.get_compute_domain(
        domain_kwargs={}, domain_type=MetricDomainTypes.TABLE
    )
    assert data.equals(df), "Data does not match after getting compute domain"
    assert compute_kwargs == {}, "Compute domain kwargs should be existent"
    assert accessor_kwargs == {}, "Accessor kwargs have been modified"

def test_get_compute_domain_with_column_pair_domain():
    engine = PandasExecutionEngine()
    df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, 5], "c": [1, 2, 3, 4]})

    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")
    data, compute_kwargs, accessor_kwargs = engine.get_compute_domain(
        domain_kwargs={"column_A": "a", "column_B": "b"}, domain_type="column_pair"
    )
    assert data.equals(df), "Data does not match after getting compute domain"
    assert compute_kwargs == {}, "Compute domain kwargs should be existent"
    assert accessor_kwargs == {
        "column_A": "a",
        "column_B": "b",
    }, "Accessor kwargs have been modified"

def test_get_compute_domain_with_multicolumn_domain():
    engine = PandasExecutionEngine()
    df = pd.DataFrame(
        {"a": [1, 2, 3, 4], "b": [2, 3, 4, None], "c": [1, 2, 2, 3], "d": [2, 7, 9, 2]}
    )

    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")
    data, compute_kwargs, accessor_kwargs = engine.get_compute_domain(
        domain_kwargs={"column_list": ["a", "b", "c"]}, domain_type="multicolumn"
    )
    assert data.equals(df), "Data does not match after getting compute domain"
    assert compute_kwargs == {}, "Compute domain kwargs should be existent"
    assert accessor_kwargs == {
        "column_list": ["a", "b", "c"]
    }, "Accessor kwargs have been modified"

def test_get_compute_domain_with_column_domain():
    engine = PandasExecutionEngine()
    df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]})

    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")
    data, compute_kwargs, accessor_kwargs = engine.get_compute_domain(
        domain_kwargs={"column": "a"}, domain_type=MetricDomainTypes.COLUMN
    )
    assert data.equals(df), "Data does not match after getting compute domain"
    assert compute_kwargs == {}, "Compute domain kwargs should be existent"
    assert accessor_kwargs == {"column": "a"}, "Accessor kwargs have been modified"

def test_get_compute_domain_with_row_condition():
    engine = PandasExecutionEngine()
    df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]})
    expected_df = df[df["b"] > 2]

    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")

    data, compute_kwargs, accessor_kwargs = engine.get_compute_domain(
        domain_kwargs={"row_condition": "b > 2", "condition_parser": "pandas"},
        domain_type="table",
    )
    # Ensuring data has been properly queried
    assert data["b"].equals(
        expected_df["b"]
    ), "Data does not match after getting compute domain"

    # Ensuring compute kwargs have not been modified
    assert (
        "row_condition" in compute_kwargs.keys()
    ), "Row condition should be located within compute kwargs"
    assert accessor_kwargs == {}, "Accessor kwargs have been modified"

# What happens when we filter such that no value meets the condition?
def test_get_compute_domain_with_unmeetable_row_condition():
    engine = PandasExecutionEngine()
    df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]})
    expected_df = df[df["b"] > 24]

    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")

    data, compute_kwargs, accessor_kwargs = engine.get_compute_domain(
        domain_kwargs={
            "column": "a",
            "row_condition": "b > 24",
            "condition_parser": "pandas",
        },
        domain_type="column",
    )
    # Ensuring data has been properly queried
    assert data["b"].equals(
        expected_df["b"]
    ), "Data does not match after getting compute domain"

    # Ensuring compute kwargs have not been modified
    assert (
        "row_condition" in compute_kwargs.keys()
    ), "Row condition should be located within compute kwargs"
    assert accessor_kwargs == {"column": "a"}, "Accessor kwargs have been modified"

# Just checking that the Pandas Execution Engine can perform these in sequence
def test_resolve_metric_bundle():
    df = pd.DataFrame({"a": [1, 2, 3, None]})

    # Building engine and configurations in attempt to resolve metrics
    engine = PandasExecutionEngine(batch_data_dict={"made-up-id": df})

    metrics: Dict[Tuple[str, str, str], MetricValue] = {}

    table_columns_metric: MetricConfiguration
    results: Dict[Tuple[str, str, str], MetricValue]

    table_columns_metric, results = get_table_columns_metric(engine=engine)
    metrics.update(results)

    mean = MetricConfiguration(
        metric_name="column.mean",
        metric_domain_kwargs={"column": "a"},
        metric_value_kwargs=None,
    )
    mean.metric_dependencies = {
        "table.columns": table_columns_metric,
    }
    stdev = MetricConfiguration(
        metric_name="column.standard_deviation",
        metric_domain_kwargs={"column": "a"},
        metric_value_kwargs=None,
    )
    stdev.metric_dependencies = {
        "table.columns": table_columns_metric,
    }
    desired_metrics = (mean, stdev)
    results = engine.resolve_metrics(
        metrics_to_resolve=desired_metrics, metrics=metrics
    )
    metrics.update(results)

    # Ensuring metrics have been properly resolved
    assert (
        metrics[("column.mean", "column=a", ())] == 2.0
    ), "mean metric not properly computed"
    assert metrics[("column.standard_deviation", "column=a", ())] == 1.0, (
        "standard deviation " "metric not properly computed"
    )

# Ensuring that we can properly inform user when metric doesn't exist - should get a metric provider error
def test_resolve_metric_bundle_with_nonexistent_metric():
    df = pd.DataFrame({"a": [1, 2, 3, None]})

    # Building engine and configurations in attempt to resolve metrics
    engine = PandasExecutionEngine(batch_data_dict={"made_up_id": df})
    mean = MetricConfiguration(
        metric_name="column.i_don't_exist",
        metric_domain_kwargs={"column": "a"},
        metric_value_kwargs=None,
    )
    stdev = MetricConfiguration(
        metric_name="column.nonexistent",
        metric_domain_kwargs={"column": "a"},
        metric_value_kwargs=None,
    )
    desired_metrics = (mean, stdev)

    # noinspection PyUnusedLocal
    with pytest.raises(ge_exceptions.MetricProviderError) as e:
        # noinspection PyUnusedLocal
        metrics = engine.resolve_metrics(metrics_to_resolve=desired_metrics)

# Making sure dataframe property is functional
def test_dataframe_property_given_loaded_batch():
    engine = PandasExecutionEngine()
    df = pd.DataFrame({"a": [1, 2, 3, 4]})

    # Loading batch data
    engine.load_batch_data(batch_data=df, batch_id="1234")

    # Ensuring Data not distorted
    assert engine.dataframe.equals(df)

def test_get_batch_data(test_df):
    split_df = PandasExecutionEngine().get_batch_data(
        RuntimeDataBatchSpec(
            batch_data=test_df,
        )
    )
    assert split_df.dataframe.shape == (120, 10)

    # No dataset passed to RuntimeDataBatchSpec
    with pytest.raises(ge_exceptions.InvalidBatchSpecError):
        PandasExecutionEngine().get_batch_data(RuntimeDataBatchSpec())

def test_get_batch_s3_compressed_files(test_s3_files_compressed, test_df_small):
    bucket, keys = test_s3_files_compressed
    path = keys[0]
    full_path = f"s3a://{os.path.join(bucket, path)}"

    batch_spec = S3BatchSpec(path=full_path, reader_method="read_csv")
    df = PandasExecutionEngine().get_batch_data(batch_spec=batch_spec)
    assert df.dataframe.shape == test_df_small.shape

@pytest.mark.skipif(
    not is_library_loadable(library_name="pyarrow")
    and not is_library_loadable(library_name="fastparquet"),
    reason="pyarrow and fastparquet are not installed",
)
def test_get_batch_s3_parquet(test_s3_files_parquet, test_df_small):
    bucket, keys = test_s3_files_parquet
    path = [key for key in keys if key.endswith(".parquet")][0]
    full_path = f"s3a://{os.path.join(bucket, path)}"

    batch_spec = S3BatchSpec(path=full_path, reader_method="read_parquet")
    df = PandasExecutionEngine().get_batch_data(batch_spec=batch_spec)
    assert df.dataframe.shape == test_df_small.shape

def test_get_batch_with_no_s3_configured():
    batch_spec = S3BatchSpec(
        path="s3a://i_dont_exist",
        reader_method="read_csv",
        splitter_method="_split_on_whole_table",
    )
    # if S3 was not configured
    execution_engine_no_s3 = PandasExecutionEngine()

    with pytest.raises(ge_exceptions.ExecutionEngineError):
        execution_engine_no_s3.get_batch_data(batch_spec=batch_spec)

def test_get_batch_with_split_on_divided_integer_and_sample_on_list(test_df):
    split_df = PandasExecutionEngine().get_batch_data(
        RuntimeDataBatchSpec(
            batch_data=test_df,
            splitter_method="_split_on_divided_integer",
            splitter_kwargs={
                "column_name": "id",
                "divisor": 10,
                "batch_identifiers": {"id": 5},
            },
            sampling_method="_sample_using_mod",
            sampling_kwargs={
                "column_name": "id",
                "mod": 5,
                "value": 4,
            },
        )
    )
    assert split_df.dataframe.shape == (2, 10)
    assert split_df.dataframe.id.min() == 54
    assert split_df.dataframe.id.max() == 59

# noinspection PyUnusedLocal
@mock.patch(
    "great_expectations.execution_engine.pandas_execution_engine.BlobServiceClient",
)
def test_constructor_with_azure_options(mock_azure_conn):
    # default instantiation
    PandasExecutionEngine()

    # instantiation with custom parameters
    engine = PandasExecutionEngine(discard_subset_failing_expectations=True)
    assert "discard_subset_failing_expectations" in engine.config
    assert engine.config.get("discard_subset_failing_expectations") is True
    custom_azure_options = {"account_url": "my_account_url"}
    engine = PandasExecutionEngine(azure_options=custom_azure_options)
    assert "azure_options" in engine.config
    assert engine.config.get("azure_options")["account_url"] == "my_account_url"

@mock.patch(
    "great_expectations.execution_engine.pandas_execution_engine.BlobServiceClient",
)
def test_get_batch_data_with_azure_batch_spec(
    mock_azure_conn,
    azure_batch_spec,
):
    mock_blob_client = mock_azure_conn().get_blob_client()
    mock_azure_obj = mock_blob_client.download_blob()
    mock_azure_obj.readall.return_value = (
        b"colA,colB,colC\n1,2,3\n4,5,6\n7,8,9"  # (3,3) CSV for testing
    )

    df = PandasExecutionEngine().get_batch_data(batch_spec=azure_batch_spec)

    mock_azure_conn().get_blob_client.assert_called_with(
        container="test_container", blob="path/A-100.csv"
    )
    mock_azure_obj.readall.assert_called_once()

    assert df.dataframe.shape == (3, 3)

def test_get_batch_with_no_azure_configured(azure_batch_spec):
    # if Azure BlobServiceClient was not configured
    execution_engine_no_azure = PandasExecutionEngine()
    execution_engine_no_azure._azure = None

    # Raises error due the connection object not being set
    with pytest.raises(ge_exceptions.ExecutionEngineError):
        execution_engine_no_azure.get_batch_data(batch_spec=azure_batch_spec)

@pytest.mark.skipif(
    storage is None,
    reason="Could not import 'storage' from google.cloud in pandas_execution_engine.py",
)
@mock.patch(
    "great_expectations.execution_engine.pandas_execution_engine.service_account",
)
@mock.patch(
    "great_expectations.execution_engine.pandas_execution_engine.storage.Client",
)
def test_constructor_with_gcs_options(mock_gcs_conn, mock_auth_method):
    # default instantiation
    PandasExecutionEngine()

    # instantiation with custom parameters
    engine = PandasExecutionEngine(discard_subset_failing_expectations=True)
    assert "discard_subset_failing_expectations" in engine.config
    assert engine.config.get("discard_subset_failing_expectations") is True
    custom_gcs_options = {"filename": "a/b/c/my_gcs_credentials.json"}
    engine = PandasExecutionEngine(gcs_options=custom_gcs_options)
    assert "gcs_options" in engine.config
    assert "filename" in engine.config.get("gcs_options")

@pytest.mark.skipif(
    storage is None,
    reason="Could not import 'storage' from google.cloud in pandas_execution_engine.py",
)
@mock.patch(
    "great_expectations.execution_engine.pandas_execution_engine.storage.Client",
)
def test_get_batch_data_with_gcs_batch_spec(
    mock_gcs_conn,
    gcs_batch_spec,
):
    mock_gcs_bucket = mock_gcs_conn().get_bucket()
    mock_gcs_blob = mock_gcs_bucket.blob()
    mock_gcs_blob.download_as_bytes.return_value = (
        b"colA,colB,colC\n1,2,3\n4,5,6\n7,8,9"  # (3,3) CSV for testing
    )

    # Necessary to pass kwargs to bypass "os.getenv | gcs_options == {}" check
    kwargs = {"gcs_options": {"my_option": "my_value"}}
    df = PandasExecutionEngine(**kwargs).get_batch_data(batch_spec=gcs_batch_spec)

    mock_gcs_conn().get_bucket.assert_called_with("test_bucket")
    mock_gcs_bucket.blob.assert_called_with("path/A-100.csv")
    mock_gcs_blob.download_as_bytes.assert_called_once()

    assert df.dataframe.shape == (3, 3)

def test_get_batch_data_with_gcs_batch_spec_no_credentials(gcs_batch_spec, monkeypatch):
    # If PandasExecutionEngine contains no credentials for GCS, we will still instantiate _gcs engine,
    # but will raise Exception when trying get_batch_data(). The only situation where it would work is if we are running in a Google Cloud container.
    # TODO : Determine how we can test the scenario where we are running PandasExecutionEngine from within Google Cloud env.

    monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False)
    with pytest.raises(Exception):
        PandasExecutionEngine().get_batch_data(batch_spec=gcs_batch_spec)

@pytest.mark.skipif(
    storage is None,
    reason="Could not import 'storage' from google.cloud in pandas_execution_engine.py",
)
def test_get_batch_with_gcs_misconfigured(gcs_batch_spec):
    # gcs_batchspec point to data that the ExecutionEngine does not have access to
    execution_engine_no_gcs = PandasExecutionEngine()
    # Raises error if batch_spec causes ExecutionEngine error
    with pytest.raises(ge_exceptions.ExecutionEngineError):
        execution_engine_no_gcs.get_batch_data(batch_spec=gcs_batch_spec)


text:
var _ = require('underscore');
var path = require('path');
var utils = require('./utils');
var isAbsolute = require('express/lib/utils').isAbsolute;
var assert = require('assert');

function normalizePath(templatepath) {
  var ext = path.extname(templatepath);
  if (ext.length)
    templatepath = templatepath.slice(0, -1*ext.length);
  return path.normalize(templatepath);
}

function addToClientModel(_ctx, domid, filename, model) {
  if (!_ctx.clientTemplates)
    _ctx.clientTemplates = {}
  _ctx.clientTemplates[domid] = {
    template: normalizePath(filename) //needs to match path name in routes/jswig.js
  }
  if (model) {
    _ctx.clientTemplates[domid].model = model;
  }
}

/*
If an object looks like a database obj, add it to clientData and serialize it out
as a string that would eval on the client as reference an object in the dbCache.
*/
function serializeRefs(k,v, clientData) {
  if (k == 'clientTemplates') {  //avoid circular refs but doesn't seem to work??
    return undefined;
  }
  if (v && typeof v === 'object') {
    //we have to do it like this to avoid toString being call internally
    var copy = new v.constructor();
    for (var prop in v) {
      if (!v.hasOwnProperty(prop)) continue;
      var val = v[prop]
      if (val && val._id) {
        var obj = val;
        clientData[obj._id] = _.extend(clientData[obj._id] || {}, obj);
        val = "@@@" + obj._id+ "@@@";
      }
      copy[prop] = val;
    }
    return copy;
  }
  return v;
}

//dictionary of persistent objects
//model objects have references to the values in that dictionary
//dom elements are associated with the template and model via jquery's data()
function renderClientside(_ctx, opt) {
  var out = '<script>if (window.$ && !$.templates) $.templates = {}</script>';
  if (_ctx.clientTemplates) {
    var templates = {};
    ///jscript/templatename.html => $.templates['templatename'] = function() {}
    _.each(_ctx.clientTemplates, function(value) {
      if (!templates[value.template]) {
        var scriptpath = value.template;
        var ext = path.extname(scriptpath);
        if (ext.length)
          scriptpath = scriptpath.slice(0, -1*ext.length);
        out += "<script async defer src='/jswig/" + normalizePath(scriptpath) +".js'></script>\n";
        templates[value.template] = true;
      }
    });
    out += '<script src="' + path.join( (opt && opt.jsbase) || "/js/", "swig.min.js") + '"></script>\n';

    var clientData = {};
    var modelJson = JSON.stringify(_ctx.clientTemplates,
      function(k,v) {return serializeRefs(k,v,clientData)}).replace(/"@@@(.+?)@@@"/g, "\$.dbCache['$1']");
    out += "\n<script>$.dbCache=" + JSON.stringify(clientData) + ';\n';
    out += "$(document).ready(function() {$.each(" + modelJson
    +", function(domid, model) {\n"
    +"     $('#'+domid).data('_template', model.template);\n"
    +"     $('#'+domid).data('_model', model.model);});\n"
    +"});</script>\n";
    //XXX should be a generic way to introspect _ctx for variables intended for client and to render them
    if (_ctx.routes && _ctx.routes.getUrlMapSource) { //XXX dbRender() needs to add routes to template locals
      out += "\n<script>$.routes=" + _ctx.routes.getUrlMapSource() + '</script>\n';
    }
 }
  return out;
}

/*
top level invocation:

from: empty || any
to: absolute
absolute

from: empty
to: relative
search [derived, derived/base, base]

(enable access to files with same name)

from: empty
to:   "base/"
search [derived/base, base]

happens when including a file:

from: derived | derived/base
to:   relative
search [derived, derived/base, base]

(enable overrides)
from: base
to:  any relative
search [derived/base, base]

(enable access to files with same name)

from: derived
to:   "base/"
search [derived/base, base]

(enable equivalent of "super()")

from: derived/base | base
to:   "base/"
search [base]

*/
function getPathLoader(swig, viewpaths) {
  var loader = swig.loaders.fs();

  loader.resolve = function (to, from) {
    // console.log('start resolve', to, from, to && isAbsolute(to));
    if (!to) return '';
    if (isAbsolute(to)) {
      //XXX if starts with /base, strip it and skip normalize(join()) below
      return to;
    }

    var basepath = viewpaths.slice(-1)[0];
    var derivedpaths = viewpaths.slice(0, -1);
    var derivedbasepaths = derivedpaths.map(function(p) { return path.join(p, 'base')});

    var tobase = to.match("^base"+path.sep);
    if (tobase)
      to = to.slice(5);

    if (!from) {
      // top level invocation (not an include)
      if (tobase) {
        //search [derived/base, base]
        return utils.searchPath(derivedbasepaths.concat(basepath), to);
      } else {
        //search [derived, derived/base, base]
        return utils.searchPath(derivedpaths.concat(derivedbasepaths).concat(basepath), to);
      }

    } else {
      var pathindex = _.findIndex(viewpaths, function(p) {return from.indexOf(p) === 0});
      var fromderived = pathindex != viewpaths.length - 1;
      var matchingPath = viewpaths[pathindex];
      var rootlen = matchingPath.length;
      var fromderivedbase = from.substr(rootlen, 5) == "base"+path.sep;
      if (fromderivedbase) {
        rootlen += 5;
      }

      var fromroot = path.dirname(from).slice(rootlen);
      to = path.normalize(path.join(fromroot, to));
      if (tobase) {
        if (fromderived && !fromderivedbase)  {
          //search [derived/base, base]
          return utils.searchPath(derivedbasepaths.concat(basepath), to);
        } else {
          assert(!fromderived || fromderivedbase);
          //search [base]
          return utils.searchPath([basepath], to);
        }
      } else {
        if (fromderived) {
          //search [derived, derived/base, base]
          return utils.searchPath(derivedpaths.concat(derivedbasepaths).concat(basepath), to);
        } else {
          // search [derived/base, base]
          return utils.searchPath(derivedbasepaths.concat(basepath), to);
        }
      }
    }
  }

  var superload = loader.load;
  loader.load = function (identifier, cb) {
    //path resolve
    if (!identifier)
      throw new Error('can not load empty identifier');
    return superload(identifier, cb);
  }
  return loader;
}

module.exports = function(swig, opt) {
  var clientinclude = require('../lib/swigtags/clientinclude');
  swig.setTag('clienttemplate', clientinclude.parse, function(compiler, args) {return clientinclude.compile(compiler, args, false)});
  swig.setTag('clientmodel', clientinclude.parse, function(compiler, args) {return clientinclude.compile(compiler, args, true)});
  var clientrender = require('../lib/swigtags/clientrender');
  swig.setTag('clientrender', clientrender.parse, clientrender.compile);
  swig.setExtension('addToClientModel', addToClientModel);
  swig.setExtension('renderClientside', renderClientside);
  if (opt) {
    swig.setDefaults(
      _.defaults(opt, {
        loader: getPathLoader(swig, opt.loaderPath || [])
      })
    );
  }

  return {
    addToClientModel: addToClientModel,
    renderClientside: function(_ctx) {return renderClientside(_ctx,opt)}
  }
}


text:
package net.caoticode.buhtig

import dispatch._
import dispatch.Defaults._

/**
 * @author Daniel Camarda <maniacal.dread@gmail.com>
 */

class Buhtig(token: String) {

  val authHeader = Map("Authorization" -> s"token $token")
  val github: Req = host("api.github.com").secure <:< authHeader

  def syncClient = new SyncClient(github)
  def asyncClient = new AsyncClient(github)

  def close() = Http.shutdown()
}


text:
var pathsComplementFromTree = require('./../lib').pathsComplementFromTree;
var pathsComplementFromLengthTree = require('./../lib').pathsComplementFromLengthTree;
var expect = require('chai').expect;

describe('pathsComplementFromTree and LengthTree', function() {
    it('should strip the single path from tree.', function() {
        var paths = [['one', 'two']];
        var tree = {one: {two: null}};
        var out = pathsComplementFromTree(paths, tree);
        expect(out).to.deep.equals([]);
    });

    it('should not strip the single path from tree.', function() {
        var paths = [['one', 'two']];
        var tree = {one: {too: null}};
        var out = pathsComplementFromTree(paths, tree);
        expect(out).to.deep.equals([['one', 'two']]);
    });

    it('should strip out one of the two paths, has complex paths.', function() {
        var paths = [
            ['one', {from: 0, to: 1}, 'two'],
            ['one', {from: 0, to: 2}, 'two']
        ];
        var tree = {
            one: {
                0: {
                    two: null
                },
                1: {
                    two: null
                }
            }
        };
        var out = pathsComplementFromTree(paths, tree);
        expect(out).to.deep.equals([['one', {from: 0, to: 2}, 'two']]);
    });

    it('should strip the single path from length tree.', function() {
        var paths = [['one', 'two']];
        var tree = {2: {one: {two: null}}};
        var out = pathsComplementFromLengthTree(paths, tree);
        expect(out).to.deep.equals([]);
    });

    it('should not strip the single path from length tree.', function() {
        var paths = [['one', 'two']];
        var tree = {2: {one: {too: null}}};
        var out = pathsComplementFromLengthTree(paths, tree);
        expect(out).to.deep.equals([['one', 'two']]);
    });

    it('should strip out one of the two paths, has complex paths from length tree.', function() {
        var paths = [
            ['one', {from: 0, to: 1}, 'two'],
            ['one', {from: 0, to: 2}, 'two']
        ];
        var tree = {
            3: {
                one: {
                    0: {
                        two: null
                    },
                    1: {
                        two: null
                    }
                }
            }
        };
        var out = pathsComplementFromLengthTree(paths, tree);
        expect(out).to.deep.equals([['one', {from: 0, to: 2}, 'two']]);
    });
});


text:
<!DOCTYPE HTML>

<title>Uses of Class org.opensextant.extractors.xcoord.DMSOrdinate (Xponents Core API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

copyright             OpenSextant.org, 2013-2021

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Uses of Class
org.opensextant.extractors.xcoord.DMSOrdinate

Packages that use DMSOrdinate

Package
Description

org.opensextant.extractors.xcoord

 XCoord: Geographic Coordinate Extraction

Uses of DMSOrdinate in org.opensextant.extractors.xcoord

Methods in org.opensextant.extractors.xcoord with parameters of type DMSOrdinate

Modifier and Type
Method
Description

static boolean
GeocoordNormalization.evaluateSpecificity(DMSOrdinate lat,
                   DMSOrdinate lon)

Hueuristic for what style of fields are allowed in valid DD or DM/DMS
 coordinates.

void
GeocoordMatch.setCoordinate(DMSOrdinate _lat,
             DMSOrdinate _lon)

Set the ordinates back on the match; general filters are assessed.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

copyright             OpenSextant.org, 2013-2021

Copyright © 2013–2022. All rights reserved.


text:
package tplimpl

import (
	"bytes"
	"fmt"
	"path/filepath"
	"reflect"
	"testing"

	"io/ioutil"
	"log"
	"os"

	"github.com/gohugoio/hugo/config"
	"github.com/gohugoio/hugo/deps"
	"github.com/gohugoio/hugo/helpers"
	"github.com/gohugoio/hugo/hugofs"
	"github.com/gohugoio/hugo/i18n"
	"github.com/gohugoio/hugo/tpl"
	"github.com/gohugoio/hugo/tpl/internal"
	"github.com/spf13/afero"
	jww "github.com/spf13/jwalterweatherman"
	"github.com/spf13/viper"
	"github.com/stretchr/testify/require"
)

var (
	logger = jww.NewNotepad(jww.LevelFatal, jww.LevelFatal, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
)

func newDepsConfig(cfg config.Provider) deps.DepsCfg {
	l := helpers.NewLanguage("en", cfg)
	l.Set("i18nDir", "i18n")
	return deps.DepsCfg{
		Language:            l,
		Cfg:                 cfg,
		Fs:                  hugofs.NewMem(l),
		Logger:              logger,
		TemplateProvider:    DefaultTemplateProvider,
		TranslationProvider: i18n.NewTranslationProvider(),
	}
}

func TestTemplateFuncsExamples(t *testing.T) {
	t.Parallel()

	workingDir := "/home/hugo"

	v := viper.New()

	v.Set("workingDir", workingDir)
	v.Set("multilingual", true)
	v.Set("baseURL", "http://mysite.com/hugo/")
	v.Set("CurrentContentLanguage", helpers.NewLanguage("en", v))

	fs := hugofs.NewMem(v)

	afero.WriteFile(fs.Source, filepath.Join(workingDir, "README.txt"), []byte("Hugo Rocks!"), 0755)

	depsCfg := newDepsConfig(v)
	depsCfg.Fs = fs
	d, err := deps.New(depsCfg)
	require.NoError(t, err)

	var data struct {
		Title   string
		Section string
		Params  map[string]interface{}
	}

	data.Title = "**BatMan**"
	data.Section = "blog"
	data.Params = map[string]interface{}{"langCode": "en"}

	for _, nsf := range internal.TemplateFuncsNamespaceRegistry {
		ns := nsf(d)
		for _, mm := range ns.MethodMappings {
			for i, example := range mm.Examples {
				in, expected := example[0], example[1]
				d.WithTemplate = func(templ tpl.TemplateHandler) error {
					require.NoError(t, templ.AddTemplate("test", in))
					require.NoError(t, templ.AddTemplate("partials/header.html", "<title>Hugo Rocks!</title>"))
					return nil
				}
				require.NoError(t, d.LoadResources())

				var b bytes.Buffer
				require.NoError(t, d.Tmpl.Lookup("test").Execute(&b, &data))
				if b.String() != expected {
					t.Fatalf("%s[%d]: got %q expected %q", ns.Name, i, b.String(), expected)
				}
			}
		}
	}

}

// TODO(bep) it would be dandy to put this one into the partials package, but
// we have some package cycle issues to solve first.
func TestPartialCached(t *testing.T) {
	t.Parallel()
	testCases := []struct {
		name    string
		partial string
		tmpl    string
		variant string
	}{
		// name and partial should match between test cases.
		{"test1", "{{ .Title }} seq: {{ shuffle (seq 1 20) }}", `{{ partialCached "test1" . }}`, ""},
		{"test1", "{{ .Title }} seq: {{ shuffle (seq 1 20) }}", `{{ partialCached "test1" . "%s" }}`, "header"},
		{"test1", "{{ .Title }} seq: {{ shuffle (seq 1 20) }}", `{{ partialCached "test1" . "%s" }}`, "footer"},
		{"test1", "{{ .Title }} seq: {{ shuffle (seq 1 20) }}", `{{ partialCached "test1" . "%s" }}`, "header"},
	}

	var data struct {
		Title   string
		Section string
		Params  map[string]interface{}
	}

	data.Title = "**BatMan**"
	data.Section = "blog"
	data.Params = map[string]interface{}{"langCode": "en"}

	for i, tc := range testCases {
		var tmp string
		if tc.variant != "" {
			tmp = fmt.Sprintf(tc.tmpl, tc.variant)
		} else {
			tmp = tc.tmpl
		}

		config := newDepsConfig(viper.New())

		config.WithTemplate = func(templ tpl.TemplateHandler) error {
			err := templ.AddTemplate("testroot", tmp)
			if err != nil {
				return err
			}
			err = templ.AddTemplate("partials/"+tc.name, tc.partial)
			if err != nil {
				return err
			}

			return nil
		}

		de, err := deps.New(config)
		require.NoError(t, err)
		require.NoError(t, de.LoadResources())

		buf := new(bytes.Buffer)
		templ := de.Tmpl.Lookup("testroot")
		err = templ.Execute(buf, &data)
		if err != nil {
			t.Fatalf("[%d] error executing template: %s", i, err)
		}

		for j := 0; j < 10; j++ {
			buf2 := new(bytes.Buffer)
			err := templ.Execute(buf2, nil)
			if err != nil {
				t.Fatalf("[%d] error executing template 2nd time: %s", i, err)
			}

			if !reflect.DeepEqual(buf, buf2) {
				t.Fatalf("[%d] cached results do not match:\nResult 1:\n%q\nResult 2:\n%q", i, buf, buf2)
			}
		}
	}
}

func BenchmarkPartial(b *testing.B) {
	config := newDepsConfig(viper.New())
	config.WithTemplate = func(templ tpl.TemplateHandler) error {
		err := templ.AddTemplate("testroot", `{{ partial "bench1" . }}`)
		if err != nil {
			return err
		}
		err = templ.AddTemplate("partials/bench1", `{{ shuffle (seq 1 10) }}`)
		if err != nil {
			return err
		}

		return nil
	}

	de, err := deps.New(config)
	require.NoError(b, err)
	require.NoError(b, de.LoadResources())

	buf := new(bytes.Buffer)
	tmpl := de.Tmpl.Lookup("testroot")

	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if err := tmpl.Execute(buf, nil); err != nil {
			b.Fatalf("error executing template: %s", err)
		}
		buf.Reset()
	}
}

func BenchmarkPartialCached(b *testing.B) {
	config := newDepsConfig(viper.New())
	config.WithTemplate = func(templ tpl.TemplateHandler) error {
		err := templ.AddTemplate("testroot", `{{ partialCached "bench1" . }}`)
		if err != nil {
			return err
		}
		err = templ.AddTemplate("partials/bench1", `{{ shuffle (seq 1 10) }}`)
		if err != nil {
			return err
		}

		return nil
	}

	de, err := deps.New(config)
	require.NoError(b, err)
	require.NoError(b, de.LoadResources())

	buf := new(bytes.Buffer)
	tmpl := de.Tmpl.Lookup("testroot")

	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if err := tmpl.Execute(buf, nil); err != nil {
			b.Fatalf("error executing template: %s", err)
		}
		buf.Reset()
	}
}

func newTestFuncster() *templateFuncster {
	return newTestFuncsterWithViper(viper.New())
}

func newTestFuncsterWithViper(v *viper.Viper) *templateFuncster {
	config := newDepsConfig(v)
	d, err := deps.New(config)
	if err != nil {
		panic(err)
	}

	if err := d.LoadResources(); err != nil {
		panic(err)
	}

	return d.Tmpl.(*templateHandler).html.funcster
}


text:
/**
 * \file
 *         AVR specific implementation of multithreading architecture
 * \author
 *         Adam Dunkels <adam@sics.se>
 * \author
 *         Simon Barner <barner@in.tum.de>
 *
 */

#ifndef __MTARCH_H__
#define __MTARCH_H__

#include "contiki-conf.h"

#ifdef MTARCH_CONF_STACKSIZE
#define MTARCH_STACKSIZE MTARCH_CONF_STACKSIZE
#else
#define MTARCH_STACKSIZE 128
#endif

struct mtarch_thread {
  unsigned char stack[MTARCH_STACKSIZE];
  unsigned char *sp;
};

#endif /* __MTARCH_H__ */


text:
<?php

namespace FivePercent\Component\VarTagValidator\Constraint\Factory;

use FivePercent\Component\VarTagValidator\Constraint\ConstraintFactoryInterface;
use FivePercent\Component\VarTagValidator\Constraint\VarTagConstraint;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * String constraint factory
 *
 * @author Vitaliy Zhuk <zhuk2205@gmail.com>
 */
class StringConstraintFactory implements ConstraintFactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function getVarTagConstraint()
    {
        return new VarTagConstraint([
            new Assert\Type('string')
        ]);
    }
}


text:
using DriverSolutions.BOL.Models.ModuleMedical;
using DriverSolutions.DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DriverSolutions.BOL.Managers.ModuleMedical
{
    public interface IDriverMedicalCatalogManager
    {
        DriverMedicalFilterModel Filter { get; set; }
        BindingList<DriverMedicalCatalogModel> ActiveMedicals { get; set; }
        BindingList<DriverMedicalReminderCatalogModel> ActiveReminders { get; set; }

        void RefreshMedicals();
        void RefreshReminders();

        List<UtilityModel<uint>> GetDrivers();
        List<UtilityModel<uint>> GetMedicalTypes();
    }
}


text:
module TaGenerator.AstParser where

import TaGenerator.DocumentParser
import Control.Applicative
import qualified Data.Text as T
import qualified Data.Map as M

class FromAst a where
    fromAst :: Ast -> Maybe a

-- Basic instances

instance FromAst Bool where
    fromAst = boolConst

instance FromAst T.Text where
    fromAst = stringLiteral

instance FromAst a => FromAst [a] where
    fromAst = listFromAst

-- Parsers

boolConst :: Ast -> Maybe Bool
boolConst (Variable v) = strToBool v
boolConst _ = Nothing

strToBool :: String -> Maybe Bool
strToBool "yes" = Just True
strToBool "no" = Just False

stringLiteral :: Ast -> Maybe T.Text
stringLiteral (StringLiteral s) = Just $ T.pack s
stringLiteral _ = Nothing

variable :: Ast -> Maybe String
variable (Variable s) = Just s
variable _ = Nothing

listFromAst :: FromAst a => Ast -> Maybe [a]
listFromAst (List l) = mapM fromAst l

mapFromValueMap :: FromAst v => ValueMap -> Maybe (M.Map String v)
mapFromValueMap vm = M.fromList <$> mapM pairFromAst (M.toList vm)
  where pairFromAst (k,v) = (,) <$> Just k <*> fromAst v

valueMap :: FromAst v => ValueMap -> M.Map String v
valueMap = M.mapMaybe fromAst

key :: FromAst a => String -> ValueMap -> Maybe a
key k vm = M.lookup k vm >>= fromAst


text:
package com.squareup.okhttp;

import com.squareup.okhttp.internal.RecordingHostnameVerifier;
import com.squareup.okhttp.internal.SslContextBuilder;
import com.squareup.okhttp.mockwebserver.Dispatcher;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import com.squareup.okhttp.mockwebserver.SocketPolicy;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.SSLContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public final class AsyncApiTest {
  private MockWebServer server = new MockWebServer();
  private OkHttpClient client = new OkHttpClient();
  private RecordingReceiver receiver = new RecordingReceiver();

  private static final SSLContext sslContext = SslContextBuilder.localhost();
  private HttpResponseCache cache;

  @Before public void setUp() throws Exception {
    String tmp = System.getProperty("java.io.tmpdir");
    File cacheDir = new File(tmp, "HttpCache-" + UUID.randomUUID());
    cache = new HttpResponseCache(cacheDir, Integer.MAX_VALUE);
  }

  @After public void tearDown() throws Exception {
    server.shutdown();
    cache.delete();
  }

  @Test public void get() throws Exception {
    server.enqueue(new MockResponse()
        .setBody("abc")
        .addHeader("Content-Type: text/plain"));
    server.play();

    Request request = new Request.Builder()
        .url(server.getUrl("/"))
        .header("User-Agent", "AsyncApiTest")
        .build();
    client.enqueue(request, receiver);

    receiver.await(request.url())
        .assertCode(200)
        .assertContainsHeaders("Content-Type: text/plain")
        .assertBody("abc");

    assertTrue(server.takeRequest().getHeaders().contains("User-Agent: AsyncApiTest"));
  }

  @Test public void connectionPooling() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));
    server.enqueue(new MockResponse().setBody("ghi"));
    server.play();

    client.enqueue(new Request.Builder().url(server.getUrl("/a")).build(), receiver);
    receiver.await(server.getUrl("/a")).assertBody("abc");

    client.enqueue(new Request.Builder().url(server.getUrl("/b")).build(), receiver);
    receiver.await(server.getUrl("/b")).assertBody("def");

    client.enqueue(new Request.Builder().url(server.getUrl("/c")).build(), receiver);
    receiver.await(server.getUrl("/c")).assertBody("ghi");

    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(1, server.takeRequest().getSequenceNumber());
    assertEquals(2, server.takeRequest().getSequenceNumber());
  }

  @Test public void tls() throws Exception {
    server.useHttps(sslContext.getSocketFactory(), false);
    server.enqueue(new MockResponse()
        .setBody("abc")
        .addHeader("Content-Type: text/plain"));
    server.play();

    client.setSslSocketFactory(sslContext.getSocketFactory());
    client.setHostnameVerifier(new RecordingHostnameVerifier());

    Request request = new Request.Builder()
        .url(server.getUrl("/"))
        .build();
    client.enqueue(request, receiver);

    receiver.await(request.url()).assertHandshake();
  }

  @Test public void recoverFromTlsHandshakeFailure() throws Exception {
    server.useHttps(sslContext.getSocketFactory(), false);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
    server.enqueue(new MockResponse().setBody("abc"));
    server.play();

    client.setSslSocketFactory(sslContext.getSocketFactory());
    client.setHostnameVerifier(new RecordingHostnameVerifier());

    Request request = new Request.Builder()
        .url(server.getUrl("/"))
        .build();
    client.enqueue(request, receiver);

    receiver.await(request.url()).assertBody("abc");
  }

  @Test public void post() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.play();

    Request request = new Request.Builder()
        .url(server.getUrl("/"))
        .post(Request.Body.create(MediaType.parse("text/plain"), "def"))
        .build();
    client.enqueue(request, receiver);

    receiver.await(request.url())
        .assertCode(200)
        .assertBody("abc");

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("def", recordedRequest.getUtf8Body());
    assertEquals("3", recordedRequest.getHeader("Content-Length"));
    assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
  }

  @Test public void conditionalCacheHit() throws Exception {
    server.enqueue(new MockResponse().setBody("A").addHeader("ETag: v1"));
    server.enqueue(new MockResponse()
        .clearHeaders()
        .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
    server.play();

    client.setOkResponseCache(cache);

    Request request1 = new Request.Builder()
        .url(server.getUrl("/"))
        .build();
    client.enqueue(request1, receiver);
    receiver.await(request1.url()).assertCode(200).assertBody("A");
    assertNull(server.takeRequest().getHeader("If-None-Match"));

    Request request2 = new Request.Builder()
        .url(server.getUrl("/"))
        .build();
    client.enqueue(request2, receiver);
    receiver.await(request2.url()).assertCode(200).assertBody("A");
    assertEquals("v1", server.takeRequest().getHeader("If-None-Match"));
  }

  @Test public void conditionalCacheMiss() throws Exception {
    server.enqueue(new MockResponse().setBody("A").addHeader("ETag: v1"));
    server.enqueue(new MockResponse().setBody("B"));
    server.play();

    client.setOkResponseCache(cache);

    Request request1 = new Request.Builder()
        .url(server.getUrl("/"))
        .build();
    client.enqueue(request1, receiver);
    receiver.await(request1.url()).assertCode(200).assertBody("A");
    assertNull(server.takeRequest().getHeader("If-None-Match"));

    Request request2 = new Request.Builder()
        .url(server.getUrl("/"))
        .build();
    client.enqueue(request2, receiver);
    receiver.await(request2.url()).assertCode(200).assertBody("B");
    assertEquals("v1", server.takeRequest().getHeader("If-None-Match"));
  }

  @Test public void redirect() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(301)
        .addHeader("Location: /b")
        .addHeader("Test", "Redirect from /a to /b")
        .setBody("/a has moved!"));
    server.enqueue(new MockResponse()
        .setResponseCode(302)
        .addHeader("Location: /c")
        .addHeader("Test", "Redirect from /b to /c")
        .setBody("/b has moved!"));
    server.enqueue(new MockResponse().setBody("C"));
    server.play();

    Request request = new Request.Builder().url(server.getUrl("/a")).build();
    client.enqueue(request, receiver);

    receiver.await(server.getUrl("/c"))
        .assertCode(200)
        .assertBody("C")
        .redirectedBy()
        .assertCode(302)
        .assertContainsHeaders("Test: Redirect from /b to /c")
        .redirectedBy()
        .assertCode(301)
        .assertContainsHeaders("Test: Redirect from /a to /b");

    assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
    assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reused.
    assertEquals(2, server.takeRequest().getSequenceNumber()); // Connection reused again!
  }

  @Test public void redirectWithRedirectsDisabled() throws Exception {
    client.setFollowProtocolRedirects(false);
    server.enqueue(new MockResponse()
        .setResponseCode(301)
        .addHeader("Location: /b")
        .addHeader("Test", "Redirect from /a to /b")
        .setBody("/a has moved!"));
    server.play();

    Request request = new Request.Builder().url(server.getUrl("/a")).build();
    client.enqueue(request, receiver);

    receiver.await(server.getUrl("/a"))
        .assertCode(301)
        .assertBody("/a has moved!")
        .assertContainsHeaders("Location: /b");
  }

  @Test public void follow20Redirects() throws Exception {
    for (int i = 0; i < 20; i++) {
      server.enqueue(new MockResponse()
          .setResponseCode(301)
          .addHeader("Location: /" + (i + 1))
          .setBody("Redirecting to /" + (i + 1)));
    }
    server.enqueue(new MockResponse().setBody("Success!"));
    server.play();

    Request request = new Request.Builder().url(server.getUrl("/0")).build();
    client.enqueue(request, receiver);
    receiver.await(server.getUrl("/20"))
        .assertCode(200)
        .assertBody("Success!");
  }

  @Test public void doesNotFollow21Redirects() throws Exception {
    for (int i = 0; i < 21; i++) {
      server.enqueue(new MockResponse()
          .setResponseCode(301)
          .addHeader("Location: /" + (i + 1))
          .setBody("Redirecting to /" + (i + 1)));
    }
    server.play();

    Request request = new Request.Builder().url(server.getUrl("/0")).build();
    client.enqueue(request, receiver);
    receiver.await(server.getUrl("/20")).assertFailure("Too many redirects: 21");
  }

  @Test public void canceledBeforeResponseReadIsNeverDelivered() throws Exception {
    client.getDispatcher().setMaxRequests(1); // Force requests to be executed serially.
    server.setDispatcher(new Dispatcher() {
      char nextResponse = 'A';
      @Override public MockResponse dispatch(RecordedRequest request) {
        client.cancel("request A");
        return new MockResponse().setBody(Character.toString(nextResponse++));
      }
    });
    server.play();

    // Canceling a request after the server has received a request but before
    // it has delivered the response. That request will never be received to the
    // client.
    Request requestA = new Request.Builder().url(server.getUrl("/a")).tag("request A").build();
    client.enqueue(requestA, receiver);
    assertEquals("/a", server.takeRequest().getPath());

    // We then make a second request (not canceled) to make sure the receiver
    // has nothing left to wait for.
    Request requestB = new Request.Builder().url(server.getUrl("/b")).tag("request B").build();
    client.enqueue(requestB, receiver);
    assertEquals("/b", server.takeRequest().getPath());
    receiver.await(requestB.url()).assertBody("B");

    // At this point we know the receiver is ready: if it hasn't received 'A'
    // yet it never will.
    receiver.assertNoResponse(requestA.url());
  }

  @Test public void canceledAfterResponseIsDeliveredDoesNothing() throws Exception {
    server.enqueue(new MockResponse().setBody("A"));
    server.play();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> bodyRef = new AtomicReference<String>();

    Request request = new Request.Builder().url(server.getUrl("/a")).tag("request A").build();
    client.enqueue(request, new Response.Receiver() {
      @Override public void onFailure(Failure failure) {
        throw new AssertionError();
      }

      @Override public boolean onResponse(Response response) throws IOException {
        client.cancel("request A");
        bodyRef.set(response.body().string());
        latch.countDown();
        return true;
      }
    });

    latch.await();
    assertEquals("A", bodyRef.get());
  }

  @Test public void connectionReuseWhenResponseBodyConsumed() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));
    server.play();

    Request request = new Request.Builder().url(server.getUrl("/a")).build();
    client.enqueue(request, new Response.Receiver() {
      @Override public void onFailure(Failure failure) {
        throw new AssertionError();
      }
      @Override public boolean onResponse(Response response) throws IOException {
        InputStream bytes = response.body().byteStream();
        assertEquals('a', bytes.read());
        assertEquals('b', bytes.read());
        assertEquals('c', bytes.read());

        // This request will share a connection with 'A' cause it's all done.
        client.enqueue(new Request.Builder().url(server.getUrl("/b")).build(), receiver);
        return true;
      }
    });

    receiver.await(server.getUrl("/b")).assertCode(200).assertBody("def");
    assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
    assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reuse!
  }

  @Test public void postBodyRetransmittedOnRedirect() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(302)
        .addHeader("Location: /b")
        .setBody("Moved to /b !"));
    server.enqueue(new MockResponse()
        .setBody("This is b."));
    server.play();

    Request request = new Request.Builder()
        .url(server.getUrl("/"))
        .post(Request.Body.create(MediaType.parse("text/plain"), "body!"))
        .build();
    client.enqueue(request, receiver);

    receiver.await(server.getUrl("/b"))
        .assertCode(200)
        .assertBody("This is b.");

    RecordedRequest request1 = server.takeRequest();
    assertEquals("body!", request1.getUtf8Body());
    assertEquals("5", request1.getHeader("Content-Length"));
    assertEquals("text/plain; charset=utf-8", request1.getHeader("Content-Type"));
    assertEquals(0, request1.getSequenceNumber());

    RecordedRequest request2 = server.takeRequest();
    assertEquals("body!", request2.getUtf8Body());
    assertEquals("5", request2.getHeader("Content-Length"));
    assertEquals("text/plain; charset=utf-8", request2.getHeader("Content-Type"));
    assertEquals(1, request2.getSequenceNumber());
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Imml.ComponentModel;

namespace Imml.Scene.Controls
{
    /// <summary>
    /// Provides support for shader based manipulation of elements.
    /// </summary>
    public class Shader : ImmlElement, IParameterHost, ISourcedElement
    {
        private bool _Enabled;

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="Shader"/> is enabled.
        /// </summary>
        /// <value>
        ///   <c>true</c> if enabled; otherwise, <c>false</c>.
        /// </value>
        public virtual bool Enabled
        {
            get { return _Enabled; }
            set
            {
                if (_Enabled == value)
                    return;

                _Enabled = value;
                base.RaisePropertyChanged("Enabled", !_Enabled, _Enabled, "Shader.Enabled");
            }
        }

        /// <summary>
        /// Gets or sets the source.
        /// </summary>
        /// <value>
        /// The source.
        /// </value>
        public virtual string Source { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="Shader"/> class.
        /// </summary>
        public Shader()
        {
            this.Enabled = true;
        }
    }
}


text:
namespace holo
{
	// Endianness modes.
	namespace endianness
	{
		enum
		{
			// Little-endian byte order (LSB first, MSB last).
			little,

			// Big-endian byte order (MSB first, LSB last).
			big,
		};
	}
}

#endif


text:
.action-icon:before {
  width: 3rem;
  height: 3rem;
  position: absolute;
  content: "";
  background: url(action_icons.png) no-repeat;
  background-size: 3rem 192rem;
}

button.action-icon,
a[role="button"].action-icon {
  padding: 0 2rem 0 4rem;
  text-align: left;
  position: relative;
  color: #717171;
}

button.action-icon:before,
a[role="button"].action-icon:before {
  left: 0.5rem;
  top: 0.3rem;
}

section[role="region"] > header:first-child .icon.action-icon:before {
  top: 1rem;
  left: 0;
}

section[role="region"] > header:first-child menu[type="toolbar"] a:last-child .icon.action-icon:before,
section[role="region"] > header:first-child menu[type="toolbar"] button:last-child .icon.action-icon:before {
  top: 1rem;
  left: 0;
}

section[role="region"] > header:first-child > button .icon.action-icon:before,
section[role="region"] > header:first-child > a .icon.action-icon:before {
  left: -0.5rem;
}

[role="toolbar"] button {
  position: relative;
}

[role="toolbar"] .action-icon:before {
  left: 1.25rem;
  top: 0.5rem;
}

[data-type="list"] aside.icon {
  top: 1.5rem;
  height: 4.5rem;
}

[role="tablist"].bottom > [role="tab"] > a.action-icon:before {
  top: 0.5rem;
}

[aria-disabled="true"] .action-icon:before,
[disabled].action-icon:before {
  opacity: 0.3;
}

.alarm-stop:before { background-position:  -0px -0px; }
.back:before { background-position:  -0px -30px; }
.bluetooth:before { background-position:  -0px -60px; }
.bluetooth-transfer:before { background-position:  -0px -90px; }
.bookmark:before { background-position:  -0px -120px; }
.bookmarked:before { background-position:  -0px -150px; }
.browser-back:before { background-position:  -0px -180px; }
.browser-forward:before { background-position:  -0px -210px; }
.calendar-agendaview:before { background-position:  -0px -240px; }
.calendar-dayview:before { background-position:  -0px -270px; }
.calendar-monthview:before { background-position:  -0px -300px; }
.calendar-today:before { background-position:  -0px -330px; }
.calendar-weekview:before { background-position:  -0px -360px; }
.cancel:before { background-position:  -0px -390px; }
.clock-addalarm:before { background-position:  -0px -420px; }
.compose:before { background-position:  -0px -450px; }
.contacts:before { background-position:  -0px -480px; }
.copy:before { background-position:  -0px -510px; }
.cut:before { background-position:  -0px -540px; }
.delete:before { background-position:  -0px -570px; }
.dismisskeyboard:before { background-position:  -0px -600px; }
.download:before { background-position:  -0px -630px; }
.downloaddark:before { background-position:  -0px -660px; }
.editcontact:before { background-position:  -0px -690px; }
.email-editlist:before { background-position:  -0px -720px; }
.email-flag:before { background-position:  -0px -750px; }
.email-forward:before { background-position:  -0px -780px; }
.email-markread:before { background-position:  -0px -810px; }
.email-markunread:before { background-position:  -0px -840px; }
.email-reload:before { background-position:  -0px -870px; }
.email-reply:before { background-position:  -0px -900px; }
.email-replyall:before { background-position:  -0px -930px; }
.email-send:before { background-position:  -0px -960px; }
.email-share:before { background-position:  -0px -990px; }
.email-sync:before { background-position:  -0px -1020px; }
.forward:before { background-position:  -0px -1050px; }
.lock:before { background-position:  -0px -1080px; }
.menu:before { background-position:  -0px -1110px; }
.move:before { background-position:  -0px -1140px; }
.new:before { background-position:  -0px -1170px; }
.paste:before { background-position:  -0px -1200px; }
.search:before { background-position:  -0px -1230px; }
.selectall:before { background-position:  -0px -1260px; }
.settings:before { background-position:  -0px -1290px; }
.sms:before { background-position:  -0px -1320px; }
.snooze:before { background-position:  -0px -1350px; }
.unlock:before { background-position:  -0px -1380px; }
.user:before { background-position:  -0px -1410px; }
.ut-airplanemode:before { background-position:  -0px -1440px; }
.ut-airplanemode:hover:before,
.ut-airplanemode:active:before { background-position:  -0px -1470px; }
.ut-bluetooth:before { background-position:  -0px -1500px; }
.ut-bluetooth:hover:before,
.ut-bluetooth:active:before { background-position:  -0px -1530px; }
.ut-settings:before { background-position:  -0px -1560px; }
.ut-settings:hover:before,
.ut-settings:active:before { background-position:  -0px -1830px; }
.ut-settings:active:before { background-position:  -0px -1560px; }
.ut-settings-data:before { background-position:  -0px -1590px; }
.ut-settings-data-2g:before { background-position:  -0px -1620px; }
.ut-settings-data-3g:before { background-position:  -0px -1650px; }
.ut-settings-data-4g:before { background-position:  -0px -1680px; }
.ut-settings-data-e:before { background-position:  -0px -1710px; }
.ut-settings-data-hp:before { background-position:  -0px -1740px; }
.ut-settings-data-h:before { background-position:  -0px -1770px; }
.ut-settings-data-o:before { background-position:  -0px -1800px; }
.ut-wifi:before { background-position:  -0px -1860px; }
.ut-wifi:hover:before,
.ut-wifi:active:before { background-position:  -0px -1890px; }