text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class Event extends Model
{

    /**
     * The attributes that are mass assignable
     *
     * @var array
     */
    protected $fillable = ['title', 'subtitle', 'description', 'start', 'end'];

    /**
     * Get all events
     *
     * @param string $orderBy Attribute to order by
     * @param string $direction OrderBy direction
     * @param integer $limit Limit results
     * @return array
     */
    public static function getEvents($orderBy = "start", $direction = "desc", $where = [], $limit = null)
    {
        return DB::table('events')
                ->where($where)
                ->orderBy($orderBy, $direction)
                ->take($limit)
                ->get();
    }
}

redpajama_set_name: RedPajamaGithub


text:
PHP Interpreter
===============

A PHP Interpreter, useful for evaluating simple PHP commands.

Warnings
--------
This utility grants access to all enabled functions in the PHP system to which it is deployed **to anyone who can access it**. For environments exposed to the internet (production and development), this could include anyone who can find or guess the link to this utility on your server. At the core of this utility is the [eval()](http://uk.php.net/eval) function, which allows the the execution of theoretically any PHP code - even code that may access and manipulate files __outside of the document root__, and execution of CLI code using backticks (i.e. `` `ls /` ``).

Because of this, we **strongly** recommend the following:-
 * __NEVER__ deploy this utility to production environments, even during development testing
 * __Do not__ deploy this utility to development environments accessible from the internet
 * It should be safe to deploy this utility to a locally-hosted web server (i.e. XAMPP), but only where you are certain the web server is not exposed to the internet

Please ensure you have read the [licence](LICENSE) corresponding to this project before deploying it - the author accepts no responsibility for misuse of the utility, including ignorance of the above warnings and the dangers of eval().

Usage
-----
Simply place phpi.php in the location where you would like to access it (obviously, this must be on the document root of a web server with PHP installed, or some localised variant (like [XAMPP](https://www.apachefriends.org/index.html)).

On load, the utility will be in single-line mode - to change between it and multi-line mode, click the red arrow to the right of the command-line.

In single-line mode, the *Enter* key will execute the entered code, and pressing the *Up* key will fill the command-line with the last command executed.

In multi-line mode, the *Enter* key will insert a new line, the *Tab* key will indent the current line (insert 4 spaces). In multi-line mode *Ctrl+Enter* will execute the entered code, and pressing *Ctrl+Up* will fill the command-line with the last command executed.

When an error is encountered, it will report the error in the output feed, and will leave the entered code in the command-line, awaiting corrections. For further information, the full error details (including trace) are reported to the console.

Author
------
php-interpreter (phpi) is written by [Richard Chaffer](http://richardchaffer.name).

Licence
-------
Copyright (c) 2014 Richard Chaffer
All Rights Reserved.
Released under the [MIT Licence](LICENSE).


text:
namespace ash {

void SetRestoreBoundsInScreen(aura::Window* window, const gfx::Rect& bounds) {
  window->SetProperty(aura::client::kRestoreBoundsKey, new gfx::Rect(bounds));
}

void SetRestoreBoundsInParent(aura::Window* window, const gfx::Rect& bounds) {
  SetRestoreBoundsInScreen(window,
      ScreenAsh::ConvertRectToScreen(window->parent(), bounds));
}

const gfx::Rect* GetRestoreBoundsInScreen(aura::Window* window) {
  return window->GetProperty(aura::client::kRestoreBoundsKey);
}

gfx::Rect GetRestoreBoundsInParent(aura::Window* window) {
  const gfx::Rect* rect = GetRestoreBoundsInScreen(window);
  if (!rect)
    return gfx::Rect();
  return ScreenAsh::ConvertRectFromScreen(window->parent(), *rect);
}

void ClearRestoreBounds(aura::Window* window) {
  window->ClearProperty(aura::client::kRestoreBoundsKey);
}

void SetTrackedByWorkspace(aura::Window* window, bool value) {
  window->SetProperty(internal::kWindowTrackedByWorkspaceKey, value);
}

bool GetTrackedByWorkspace(const aura::Window* window) {
  return window->GetProperty(internal::kWindowTrackedByWorkspaceKey);
}

void SetIgnoredByShelf(aura::Window* window, bool value) {
  window->SetProperty(internal::kIgnoredByShelfKey, value);
}

bool GetIgnoredByShelf(const aura::Window* window) {
  return window->GetProperty(internal::kIgnoredByShelfKey);
}

void SetWindowAlwaysRestoresToRestoreBounds(aura::Window* window, bool value) {
  window->SetProperty(internal::kWindowRestoresToRestoreBounds, value);
}

bool GetWindowAlwaysRestoresToRestoreBounds(const aura::Window* window) {
  return window->GetProperty(internal::kWindowRestoresToRestoreBounds);
}

internal::RootWindowController* GetRootWindowController(
    const aura::RootWindow* root_window) {
  return root_window ?
      root_window->GetProperty(internal::kRootWindowControllerKey) : NULL;
}

void SetRootWindowController(aura::RootWindow* root_window,
                             internal::RootWindowController* controller) {
  root_window->SetProperty(internal::kRootWindowControllerKey, controller);
}

}  // namespace ash


text:
<?php
namespace Gajus\Doll;

/**
 * @link https://github.com/gajus/doll for the canonical source repository
 * @license https://github.com/gajus/doll/blob/master/LICENSE BSD 3-Clause
 */
class PDOStatement extends \PDOStatement {
    private
        /**
         * @var PDO
         */
        $dbh,
        /**
         * @var string
         */
        $raw_query_string,
        /**
         * @var array
         */
        $named_parameter_markers;

    /**
     * @param PDO $dbh
     */
    final protected function __construct(PDO $dbh) {
        $this->dbh = $dbh;
    }

    /**
     * When the prepared statement is using named parameter markers, the query is overwritten with an
     * equivalent query using question mark parameter markers. The raw query is used for logging purposes.
     *
     * Names of the parameter markers are used to locate the assigned value when executing the statement.
     *
     * @param string $raw_query_string
     * @param array $named_parameter_markers
     * @return null
     */
    public function setParameterMarkerNames ($raw_query_string, array $named_parameter_markers) {
        if ($this->named_parameter_markers !== null) {
            throw new Exception\LogicException('Parameter markers can be set only at the time of building the statement.');
        }

        $this->raw_query_string = $raw_query_string;
        $this->named_parameter_markers = $named_parameter_markers;
    }

    /**
     * @return $this
     */
    public function nextRowset() {
        if (!parent::nextRowset()) {
            throw new Exception\RuntimeException('Rowset is not available.');
        }

        return $this;
    }

    /**
     * @return $this
     */
    public function execute ($parameters = []) {
        $execution_wall_time = -microtime(true);

        // Using named parameters
        if ($parameters && !array_key_exists(0, $parameters)) {
            $parameter_marker_names = array_unique(array_map(function ($pn) {
                    return $pn['name'];
            }, $this->named_parameter_markers));

            if (array_diff($parameter_marker_names, array_keys($parameters))) {
                // @todo Improve phrasing.
                throw new Exception\InvalidArgumentException('Prepared statement executed without values for all the parameter markers.');
            } else if (array_diff(array_keys($parameters), $parameter_marker_names)) {
                throw new Exception\InvalidArgumentException('Prepared statement executed with undefined parameters.');
            }

            foreach ($this->named_parameter_markers as $index => $parameter_marker) {
                $this->bindValue($index + 1, $parameters[$parameter_marker['name']], $parameter_marker['type']);
            }

            $execute = parent::execute();
        } else {
            if ($this->named_parameter_markers) {
                throw new Exception\InvalidArgumentException('Prepared statement with named parameter markers executed using list.');
            }

            $execute = parent::execute($parameters);
        }

        if ($execute === false) {
            $error = $this->errorInfo();

            if ($error[0] === 'HY093') {
                // For some odd reason PDO does no throw Exception in this case.
                // @see http://www.php.net/manual/en/pdostatement.execute.php
                throw new Exception\InvalidArgumentException('You cannot bind multiple values to a single parameter. You cannot bind more values than specified.');
            } else if ($error[0] === '00000') {
                // @see PHP PDO bug, https://gist.github.com/gajus/df145c92c19520273ffb
            } else {
                throw new Exception\RuntimeException('Oops. Something gone terribly wrong.');
            }
        }

        $this->dbh->on('execute', $this->raw_query_string, $execution_wall_time + microtime(true), $parameters);

        return $this;
    }
}


text:
        <link rel="stylesheet" href="../css/player.css" type="text/css" media="screen" />

                g
                h

Exfm

e

Now Playing

t

s

b

R

r

S

T

Tumblr

                                            View Post
                                            Like Post

Soundcloud

                                            View Song
                                            Like Song

Bandcamp

                                            Buy Song

Rhapsody

                                            Save to Playlist

Rdio

                                            Save to Playlist

Spotify

                                            Play Song

Tomahawk

                                            Queue Song

                                0:00
                                0:00

        <template id="playlist-item-template">

        </template>


text:
import os
import shutil
import tempfile

import yaml
from azure.common import AzureHttpError
from azure.storage.queue import QueueMessage
from mock import ANY, Mock, patch

from ..azure_common import BaseTest
from c7n_azure.container_host.host import Host

DEFAULT_EVENT_QUEUE_ID = "event-queue-id"
DEFAULT_EVENT_QUEUE_STORAGE_ID = "/subscriptions/11111111-2222-3333-4444-555555555555/"
"resourceGroups/storagerg/providers/Microsoft.Storage/storageAccounts/samplestorage"
DEFAULT_EVENT_QUEUE_NAME = "event-queue-name"
DEFAULT_POLICY_STORAGE = "policy-storage"

class ContainerHostTest(BaseTest):
    def test_build_options(self):
        result = Host.build_options(
            output_dir='/test/dir',
            log_group='test_log_group',
            metrics='test_metrics'
        )

        self.assertEqual('test_log_group', result['log_group'])
        self.assertEqual('/test/dir', result['output_dir'])
        self.assertEqual('test_metrics', result['metrics'])

    @patch('tempfile.mkdtemp', return_value='test_path')
    def test_build_options_empty(self, _):
        result = Host.build_options()

        self.assertEqual(None, result['log_group'])
        self.assertEqual('test_path', result['output_dir'])
        self.assertEqual(None, result['metrics'])

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('tempfile.mkdtemp', return_value='test_path')
    def test_init(self, _1, _2, _3, _4, _5):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)
        jobs = host.scheduler.get_jobs()
        update_policy_job = [j for j in jobs if j.id == 'update_policies']
        poll_queue_job = [j for j in jobs if j.id == 'poll_queue']

        self.assertEqual('test_path', host.policy_cache)
        self.assertEqual(2, len(jobs))
        self.assertIsNotNone(update_policy_job)
        self.assertIsNotNone(poll_queue_job)

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('tempfile.mkdtemp', return_value='test_path')
    def test_init_different_storage_subscription(self, _1, _2, _3, _4, _5):
        host = Host(DEFAULT_EVENT_QUEUE_STORAGE_ID,
                    DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)
        self.assertIsNot(host.storage_session, host.session)

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    def test_update_policies(self, get_blob_client_mock, _1, _2, _3, _4):
        # mock blob list call
        client_mock = Mock()
        client_mock.list_blobs.return_value = [
            ContainerHostTest.get_mock_blob("blob1.yml", "hash1"),
            ContainerHostTest.get_mock_blob("blob2.YAML", "hash2"),
            ContainerHostTest.get_mock_blob("blob3.md", "hash3")
        ]

        client_mock.get_blob_to_path = self.download_policy_blob
        get_blob_client_mock.return_value = (client_mock, None, None)

        # init
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        # cleanup
        self.addCleanup(lambda: shutil.rmtree(host.policy_cache))

        self.assertEqual({}, host.policies)

        # run
        host.update_policies()

        # both policies were loaded
        self.assertEqual(2, len(host.policies.items()))

        # jobs were created
        jobs = host.scheduler.get_jobs()
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob1.yml']))
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob2.YAML']))

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    def test_update_policies_add_remove(self, get_blob_client_mock, _1, _2, _3, _4):
        """
        Run a series of add/update/removal of policy blobs
        and verify jobs and caches are updated correctly
        """
        # mock blob list call
        client_mock = Mock()
        client_mock.list_blobs.return_value = [
            ContainerHostTest.get_mock_blob("blob1.yml", "hash1")
        ]

        client_mock.get_blob_to_path = self.download_policy_blob
        get_blob_client_mock.return_value = (client_mock, None, None)

        # init
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        # cleanup
        self.addCleanup(lambda: shutil.rmtree(host.policy_cache))

        self.assertEqual({}, host.policies)

        # Initial load
        host.update_policies()
        self.assertEqual(1, len(host.policies.items()))

        ##################
        # Add two policies
        ##################
        client_mock.list_blobs.return_value = [
            ContainerHostTest.get_mock_blob("blob1.yml", "hash1"),
            ContainerHostTest.get_mock_blob("blob2.yml", "hash2"),
            ContainerHostTest.get_mock_blob("blob3.yml", "hash3")
        ]

        host.update_policies()
        self.assertEqual(3, len(host.policies.items()))
        self.assertIsNotNone(host.policies['blob1.yml'])
        self.assertIsNotNone(host.policies['blob2.yml'])
        self.assertIsNotNone(host.policies['blob3.yml'])

        # jobs were updated
        jobs = host.scheduler.get_jobs()
        self.assertEqual(3, len([j for j in jobs if j.func == host.run_policy]))
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob1.yml']))
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob2.yml']))
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob3.yml']))

        ##############################################
        # Add one, remove one, update one
        ##############################################
        client_mock.list_blobs.return_value = [
            ContainerHostTest.get_mock_blob("blob1.yml", "hash1"),
            ContainerHostTest.get_mock_blob("blob4.yml", "hash4"),
            ContainerHostTest.get_mock_blob("blob3.yml", "hash3_new")
        ]

        host.update_policies()
        self.assertEqual(3, len(host.policies.items()))
        self.assertIsNotNone(host.policies['blob1.yml'])
        self.assertIsNotNone(host.policies['blob4.yml'])
        self.assertIsNotNone(host.policies['blob3.yml'])
        self.assertEqual('hash3_new', host.blob_cache['blob3.yml'])

        # jobs were updated
        jobs = host.scheduler.get_jobs()
        self.assertEqual(3, len([j for j in jobs if j.func == host.run_policy]))
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob1.yml']))
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob4.yml']))
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob3.yml']))

        ############
        # remove all
        ############
        client_mock.list_blobs.return_value = [
        ]

        host.update_policies()
        self.assertEqual(0, len(host.policies.items()))

        # jobs were updated
        jobs = host.scheduler.get_jobs()
        self.assertEqual(0, len([j for j in jobs if j.func == host.run_policy]))

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    def test_update_policies_create_content_hash(self, get_blob_client_mock, _1, _2, _3, _4):
        client_mock = Mock()
        client_mock.list_blobs.return_value = [
            ContainerHostTest.get_mock_blob("blob1.yml", None),  # no hash
        ]

        client_mock.get_blob_to_path = self.download_policy_blob
        get_blob_client_mock.return_value = (client_mock, None, None)

        def get_blob_properties(_, blob_name):
            return ContainerHostTest.get_mock_blob(blob_name, 'hash')  # now with hash
        client_mock.get_blob_properties = get_blob_properties

        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        # cleanup
        self.addCleanup(lambda: shutil.rmtree(host.policy_cache))

        self.assertEqual({}, host.policies)

        # run
        host.update_policies()

        # both policies were loaded
        self.assertEqual(1, len(host.policies.items()))

        # jobs were created
        jobs = host.scheduler.get_jobs()
        self.assertEqual(1, len([j for j in jobs if j.id == 'blob1.yml']))

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    def test_update_policies_ignore_policy_if_failed_to_create_content_hash(self,
            get_blob_client_mock, _1, _2, _3, _4):
        client_mock = Mock()
        client_mock.list_blobs.return_value = [
            ContainerHostTest.get_mock_blob("blob1.yml", None),  # no hash
        ]

        client_mock.get_blob_to_path = self.download_policy_blob
        get_blob_client_mock.return_value = (client_mock, None, None)

        def create_blob_from_bytes(_1, _2, _3, **kwargs):
            raise AzureHttpError("Failed to create blob", 403)
        client_mock.create_blob_from_bytes = create_blob_from_bytes

        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        # cleanup
        self.addCleanup(lambda: shutil.rmtree(host.policy_cache))

        self.assertEqual({}, host.policies)

        # run
        host.update_policies()

        # no policies were loaded
        self.assertEqual(0, len(host.policies.items()))

        # jobs were created
        jobs = host.scheduler.get_jobs()
        self.assertEqual(0, len([j for j in jobs if j.id == 'blob1.yml']))

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    def test_update_policies_list_blobs_azure_http_error(self,
            get_blob_client_mock, _2, _3, _4, _5):
        client_mock = Mock()
        client_mock.list_blobs.side_effect = AzureHttpError("failed to list blobs", 400)
        get_blob_client_mock.return_value = (client_mock, None, None)

        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)
        with self.assertRaises(AzureHttpError):
            host.update_policies()
        client_mock.list_blobs.assert_called()

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    def test_update_policies_missing_mode(self, get_blob_client_mock, _2, _3, _4, _5):
        client_mock = Mock()
        client_mock.list_blobs.return_value = [
            ContainerHostTest.get_mock_blob('no-mode-blob.yaml', 'no-mode-blob')
        ]
        client_mock.get_blob_to_path = self.download_missing_mode_policy_blob
        get_blob_client_mock.return_value = (client_mock, None, None)
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)
        self.addCleanup(lambda: shutil.rmtree(host.policy_cache))
        host.update_policies()
        self.assertEqual(1, len(host.policies.items()))

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    @patch('os.makedirs', wraps=os.makedirs)
    def test_update_policies_in_subfolders(self,
            makedirs_mock, get_blob_client_mock, _2, _3, _4, _5):
        blob_name = "path/to/blob.yml"
        client_mock = Mock()
        client_mock.list_blobs.return_value = [ContainerHostTest.get_mock_blob(blob_name, 'blob')]
        client_mock.get_blob_to_path = self.download_policy_blob
        get_blob_client_mock.return_value = (client_mock, None, None)

        self.addCleanup(lambda: shutil.rmtree(host.policy_cache))

        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)
        host.update_policies()
        self.assertEqual(1, len(host.policies.items()))
        jobs = host.scheduler.get_jobs()
        self.assertEqual(1, len([j for j in jobs if j.id == blob_name]))
        blob_dir = os.path.join(host.policy_cache, blob_name)
        makedirs_mock.assert_any_call(os.path.dirname(blob_dir))

    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Host.update_policies')
    @patch('c7n_azure.container_host.host.AzureEventSubscription')
    @patch('c7n_azure.container_host.host.EventSubscriptionFilter')
    def test_update_event_subscriptions(self, event_filter_mock, _0, _1, _2, _3, _4):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        host.event_queue_name = 'testq'

        host.policies = {
            'one': {
                'policy': ContainerHostTest.get_mock_policy({
                    'name': 'one',
                    'mode': {
                        'type': 'container-event',
                        'events': ['ResourceGroupWrite', 'VnetWrite']
                    }
                })
            },
            'two': {
                'policy': ContainerHostTest.get_mock_policy({
                    'name': 'two',
                    'mode': {
                        'type': 'container-event',
                        'events': ['ResourceGroupWrite']
                    }
                })
            },
            'three': {
                'policy': ContainerHostTest.get_mock_policy({
                    'name': 'three',
                    'mode': {
                        'type': 'container-event',
                        'events': [{
                            'resourceProvider': 'Microsoft.KeyVault/vaults',
                            'event': 'write'
                        }]
                    }
                })
            }
        }

        # Verify we get all three events with no duplicates
        host.update_event_subscription()
        event_filter_mock.assert_called_with(
            included_event_types=['Microsoft.Resources.ResourceWriteSuccess'])

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage')
    @patch('c7n_azure.container_host.host.Host.run_policies_for_event')
    def test_poll_queue(self, run_policy_mock, storage_mock, _1, _2, _3):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        host.policies = {
            'one': {
                'policy': ContainerHostTest.get_mock_policy({
                    'name': 'one',
                    'mode': {
                        'type': 'container-event',
                        'events': ['ResourceGroupWrite', 'VnetWrite']
                    }
                })
            }
        }

        q1 = QueueMessage()
        q1.id = 1
        q1.dequeue_count = 0
        q1.content = """eyAgCiAgICJzdWJqZWN0IjoiL3N1YnNjcmlwdGlvbnMvZWE5ODk3NGItNWQyYS00ZDk4LWE3
        OGEtMzgyZjM3MTVkMDdlL3Jlc291cmNlR3JvdXBzL3Rlc3RfY29udGFpbmVyX21vZGUiLAogICAiZXZlbnRUeXBlIj
        oiTWljcm9zb2Z0LlJlc291cmNlcy5SZXNvdXJjZVdyaXRlU3VjY2VzcyIsCiAgICJldmVudFRpbWUiOiIyMDE5LTA3
        LTE2VDE4OjMwOjQzLjM1OTUyNTVaIiwKICAgImlkIjoiNjE5ZDI2NzQtYjM5Ni00MzU2LTk2MTktNmM1YTUyZmU0ZT
        g4IiwKICAgImRhdGEiOnsgICAgICAgIAogICAgICAiY29ycmVsYXRpb25JZCI6IjdkZDVhNDc2LWUwNTItNDBlMi05
        OWU0LWJiOTg1MmRjMWY4NiIsCiAgICAgICJyZXNvdXJjZVByb3ZpZGVyIjoiTWljcm9zb2Z0LlJlc291cmNlcyIsCi
        AgICAgICJyZXNvdXJjZVVyaSI6Ii9zdWJzY3JpcHRpb25zL2VhOTg5NzRiLTVkMmEtNGQ5OC1hNzhhLTM4MmYzNzE1
        ZDA3ZS9yZXNvdXJjZUdyb3Vwcy90ZXN0X2NvbnRhaW5lcl9tb2RlIiwKICAgICAgIm9wZXJhdGlvbk5hbWUiOiJNaW
        Nyb3NvZnQuUmVzb3VyY2VzL3N1YnNjcmlwdGlvbnMvcmVzb3VyY2VHcm91cHMvd3JpdGUiLAogICAgICAic3RhdHVz
        IjoiU3VjY2VlZGVkIiwKICAgfSwKICAgInRvcGljIjoiL3N1YnNjcmlwdGlvbnMvYWE5ODk3NGItNWQyYS00ZDk4LW
        E3OGEtMzgyZjM3MTVkMDdlIgp9"""

        q2 = QueueMessage()
        q2.id = 2
        q2.dequeue_count = 0
        q2.content = q1.content

        # Return 2 messages on first call, then none
        storage_mock.get_queue_messages.side_effect = [[q1, q2], []]
        host.poll_queue()
        self.assertEqual(2, run_policy_mock.call_count)
        run_policy_mock.reset_mock()

        # Return 5 messages on first call, then 2, then 0
        storage_mock.get_queue_messages.side_effect = [[q1, q1, q1, q1, q1], [q1, q2], []]
        host.poll_queue()
        self.assertEqual(7, run_policy_mock.call_count)
        run_policy_mock.reset_mock()

        # High dequeue count
        q1.dequeue_count = 100
        storage_mock.get_queue_messages.side_effect = [[q1, q2], []]
        host.poll_queue()
        self.assertEqual(1, run_policy_mock.call_count)

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.BlockingScheduler.add_job')
    def test_run_policy_for_event(self, add_job_mock, _0, _1, _2, _3):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        host.policies = {
            'one': {
                'policy': ContainerHostTest.get_mock_policy({
                    'name': 'one',
                    'mode': {
                        'type': 'container-event',
                        'events': ['ResourceGroupWrite', 'VnetWrite']
                    }
                })
            }
        }

        message = QueueMessage()
        message.id = 1
        message.dequeue_count = 0
        message.content = \
            """eyAgCiAgICJzdWJqZWN0IjoiL3N1YnNjcmlwdGlvbnMvZWE5ODk3NGItNWQyYS00ZDk4LWE3OGEt
            MzgyZjM3MTVkMDdlL3Jlc291cmNlR3JvdXBzL3Rlc3RfY29udGFpbmVyX21vZGUiLAogICAiZXZl
            bnRUeXBlIjoiTWljcm9zb2Z0LlJlc291cmNlcy5SZXNvdXJjZVdyaXRlU3VjY2VzcyIsCiAgICJl
            dmVudFRpbWUiOiIyMDE5LTA3LTE2VDE4OjMwOjQzLjM1OTUyNTVaIiwKICAgImlkIjoiNjE5ZDI2
            NzQtYjM5Ni00MzU2LTk2MTktNmM1YTUyZmU0ZTg4IiwKICAgImRhdGEiOnsgICAgICAgIAogICAg
            ICAiY29ycmVsYXRpb25JZCI6IjdkZDVhNDc2LWUwNTItNDBlMi05OWU0LWJiOTg1MmRjMWY4NiIs
            CiAgICAgICJyZXNvdXJjZVByb3ZpZGVyIjoiTWljcm9zb2Z0LlJlc291cmNlcyIsCiAgICAgICJy
            ZXNvdXJjZVVyaSI6Ii9zdWJzY3JpcHRpb25zL2VhOTg5NzRiLTVkMmEtNGQ5OC1hNzhhLTM4MmYz
            NzE1ZDA3ZS9yZXNvdXJjZUdyb3Vwcy90ZXN0X2NvbnRhaW5lcl9tb2RlIiwKICAgICAgIm9wZXJh
            dGlvbk5hbWUiOiJNaWNyb3NvZnQuUmVzb3VyY2VzL3N1YnNjcmlwdGlvbnMvcmVzb3VyY2VHcm91
            cHMvd3JpdGUiLAogICAgICAic3RhdHVzIjoiU3VjY2VlZGVkIgogICB9LAogICAidG9waWMiOiIv
            c3Vic2NyaXB0aW9ucy9hYTk4OTc0Yi01ZDJhLTRkOTgtYTc4YS0zODJmMzcxNWQwN2UiCn0="""

        # run with real match
        host.run_policies_for_event(message)
        add_job_mock.assert_called_with(ANY,
                                        id='one619d2674-b396-4356-9619-6c5a52fe4e88',
                                        name='one',
                                        args=ANY,
                                        misfire_grace_time=ANY)

        add_job_mock.reset_mock()

        # run with no match
        host.policies = {}
        host.run_policies_for_event(message)
        self.assertFalse(add_job_mock.called)

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    @patch('yaml.safe_load', side_effect=yaml.YAMLError())
    @patch('os.unlink')
    def test_unload_policy_file_with_yaml_error(self,
            os_unlink, yaml_safe_load, _1, _2, _3, _4, _5):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        # Create a bad yaml file
        file_path = tempfile.mktemp(suffix=".yaml")
        with open(file_path, 'w') as f:
            f.write("bad yaml file")

        host.load_policy(file_path, host.policies)
        host.unload_policy_file(file_path, host.policies)
        os_unlink.assert_called()

        # Clean up the file
        os.remove(file_path)

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    @patch('os.unlink')
    def test_unload_policy_file_that_was_never_loaded(self,
            os_unlink, _1, _2, _3, _4, _5):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        policy_string = """
                            policies:
                              - name: foo
                                mode:
                                  type: container-periodic
                                  schedule: '* * * * *'
                                resource: azure.resourcegroup
                        """

        # Create a bad yaml file
        file_path = tempfile.mktemp(suffix=".yaml")
        with open(file_path, 'w') as f:
            f.write(policy_string)

        host.unload_policy_file(file_path, {})
        os_unlink.assert_called()

        # Clean up the file
        os.remove(file_path)

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    @patch('os.unlink')
    def test_unload_policy_file_without_name(self,
            os_unlink, yaml_safe_load, _1, _2, _3, _4):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        # Create a bad yaml file (no name field)
        file_path = tempfile.mktemp(suffix=".yaml")
        with open(file_path, 'w') as f:
            f.write("""
                        policies:
                          - mode:
                              type: container-periodic
                              schedule: '* * * * *'
                            resource: azure.resourcegroup
                        """)

        host.load_policy(file_path, host.policies)
        host.unload_policy_file(file_path, host.policies)
        os_unlink.assert_called()

        # Clean up the file
        os.remove(file_path)

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    @patch('os.unlink')
    def test_unload_policy_file_with_bad_schema(self,
            os_unlink, _1, _2, _3, _4, _5):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)

        # Schedule is invalid
        policy_string = """
                            policie:
                              - name: foo
                                mode:
                                  type: container-periodic
                                  schedule: '* * * *'
                                resource: azure.resourcegroup
                        """

        # Create a bad yaml file
        file_path = tempfile.mktemp(suffix=".yaml")
        with open(file_path, 'w') as f:
            f.write(policy_string)

        host.load_policy(file_path, host.policies)
        host.unload_policy_file(file_path, host.policies)
        os_unlink.assert_called()

        # Clean up the file
        os.remove(file_path)

    @patch('c7n_azure.container_host.host.Host.update_event_subscription')
    @patch('c7n_azure.container_host.host.BlockingScheduler.start')
    @patch('c7n_azure.container_host.host.Host.prepare_queue_storage')
    @patch('c7n_azure.container_host.host.Storage.get_queue_client_by_storage_account')
    @patch('c7n_azure.container_host.host.Storage.get_blob_client_by_uri')
    def test_run_policy_handles_exceptions(self, _1, _2, _3, _4, _5):
        host = Host(DEFAULT_EVENT_QUEUE_ID, DEFAULT_EVENT_QUEUE_NAME, DEFAULT_POLICY_STORAGE)
        mock_policy = Mock()
        mock_policy.push.side_effect = Exception()
        host.run_policy(mock_policy, None, None)

    @staticmethod
    def download_policy_blob(_, name, path):
        policy_string = """
                            policies:
                              - name: %s
                                mode:
                                  type: container-periodic
                                  schedule: '* * * * *'
                                resource: azure.resourcegroup
                        """

        with open(path, 'w') as out_file:
            out_file.write(policy_string % name)

    @staticmethod
    def download_missing_mode_policy_blob(_, name, path):
        policy_string = """
                            policies:
                              - name: %s
                                resource: azure.resourcegroup
                        """

        with open(path, 'w') as out_file:
            out_file.write(policy_string % name)

    @staticmethod
    def get_mock_blob(name, md5):
        new_blob = Mock()
        new_blob.name = name
        new_blob.content_settings.content_md5 = md5
        return new_blob

    @staticmethod
    def get_mock_policy(policy):
        new_policy = Mock()
        new_policy.data = policy
        return new_policy


text:
/**
* Register globals
*/
console.log('Starting TweetMeme Extension');
var urls = new Array();
var CACHE_ERROR = 'TM_ERROR_RETURNED';
var timeout = setInterval(clearCaches, 1800000);

/**
* Set up our debugging configuration
*/
var debugEnabled = false;
var errorEnabled = false;

function enableDebug() { debugEnabled = true; return 'Debugging Enabled'; }
function disableDebug() { debugEnabled = false; return 'Debugging disabled'; }
function enableErrors() { errorEnabled = true; return 'Errors enabled'; }
function disableErrors() { errorEnabled = false; return 'Errors disabled'; }

console.log('Debugging on? ' + debugEnabled);
if (!debugEnabled) {
	console.log('Call enableDebug() to enable debugging, and disableDebug() to turn it off again');
}

console.log('Error reporting on? ' + errorEnabled);

if (!errorEnabled) {
	console.log('Call enableErrors() to enable error reporting, and disableErrors() to turn it off again');
}

var c = console;
var console = {
	log: function(str) {
		if (debugEnabled) {
			return c.log(str);
		} else {
			return false;
		}
	},
	warn: function(str) {
		if (debugEnabled) {
			return c.warn(str);
		} else {
			return false;
		}
	},
	error: function(str) {
		if (errorEnabled) {
			return c.error(str);
		} else {
			return false;
		}
	},
	debug: function(str) {
		if (debugEnabled) {
			return c.debug(str);
		} else {
			return false;
		}
	}
}

/**
* Set default badge contents
*
* Set badge colour
*/
console.debug('Configuring badge');
setBadge("");
setBadgeColour('green');

/**
* Returns a string of spaces to pad out
* the badge for a given string to pad it out
*/
function getSpacesForString(str)
{
	rtn = "";
	i = 7;
	while (i > (str.length*2)) {
		i--;
		rtn += " ";
	}
	return rtn;
}

/**
* Resets all the caches
*
* Periodically called from when the
* plugin is first loaded
*/
function clearCaches()
{
	console.warn('Clearing caches...');
	urls = new Array();
	console.warn('... done');
}

/**
* Sets the badge colour
*
* inputs are 'red', 'grey', 'green'
* defaults to green
*/
function setBadgeColour(colour, tabid)
{
	if (colour == 'red') {
		obj = {color: [255,0,0,255]}
		if (tabid) {
			obj.tabId = tabid;
		}
	} else if (colour == 'grey') {
		obj = {color: [192,192,192,255]}
		if (tabid) {
			obj.tabId = tabid;
		}
	} else {
		// go to green
		obj = {color: [149,200,62,255]}
		if (tabid) {
			obj.tabId = tabid;
		}
	}
	chrome.browserAction.setBadgeBackgroundColor(obj);
}

/**
* Strips useless anchors from URLs
*
* A useless anchor is a URL that doesn't
* contain a slash at any point after the anchor
*/
function stripAnchors(str)
{
	if (str.indexOf('#') >= 0) {
		// URL has an anchor in it
		anchor_section = str.substring(str.indexOf('#') + 1);
		if (anchor_section.indexOf('/') < 0) {
			/**
			* anchor section doesn't contain a /
			* so remove the anchor as TM will anyway
			*/
			str = str.substring(0, str.indexOf('#'));
			console.warn('Useless anchor found, URL shortened to "' + str + '"');
		} else {
			console.debug('Anchor found in URL but deemed to be useful, contains a /');
		}
	}

	return str;
}

/**
* Utility to set a badge string and
* automatically pad it correctly
*/
function setBadge(str, tabid)
{
	console.debug('Setting badge to contain "' + str + '"');
	obj = {text: getSpacesForString(str + "") + str};
	if (tabid) {
		obj.tabId = tabid;
	}
	chrome.browserAction.setBadgeText(obj);
}

/**
* Function to manage inserts into the
* cache, and displaying of the counts on to the
* button
*/
function cacheAndDisplay(url, count, windowid)
{
	console.debug('Caching count of "' + count + '" for url "' + url + '"');
	urls[url] = count;
	display(url, count, windowid);
}

/**
* Displays the count on the badge
* if it is for the correct url
*/
function display(url, count, windowid)
{
	chrome.windows.get(windowid, function(window) {
		chrome.tabs.getSelected(window.id, function(tab) {
			if (stripAnchors(tab.url) == url) {
				/**
				* If it is a cached error, then
				* don't display that - just return blank
				*/
				if (count == CACHE_ERROR) {
					count = '';
				}
				console.debug('URL "' + url + '" matches the current tab URL "' + tab.url + '" so updating badge to read "' + count + '"');
				newcount = parseInt(count);
				if (newcount) {
					if (newcount >= 1000000) {
						count = Math.round(newcount / 1000000) + 'M';
						console.log('Count of "' + newcount + '" modified to "' + count + '"');
					} else if (newcount >= 10000) {
						count = Math.round(newcount / 10000) + 'k';
						console.log('Count of "' + newcount + '" modified to "' + count + '"');
					}
				}
				setBadge(count, tab.id);
			} else {
				console.warn('URL "' + url + '" does not match the current tab URL "' + tab.url + '" so not updating the badge');
			}
		});
	});
}

/**
* Utility to help distinguish between which type
* of listener fired the update command
*
* In this case, it was onUpdated()
*/
function updateUpdated(tabID)
{
	console.debug('onUpdate listener activated with tab ID ' + tabID);
	update(tabID);
}

/**
* Utility to help distinguish between which type
* of listener fired the update command
*
* In this case, it was onSelectionChanged()
*/
function updateSelectionChanged(tabID)
{
	console.debug('onSelectionChanged listener activated with tab ID ' + tabID);
	update(tabID);
}

/**
* Main update function
*
* If the URL of the tab specified by tabID
* is valid and not already cached, it goes
* and retrieves the count from TM then passes
* it off for caching
*/
function update(tabID)
{
	console.debug('Updating count for tab "' + tabID + '"');

	chrome.tabs.get(tabID, function(tab) {
		/**
		* Get the URL of the tab
		*/
		var theurl = false;
		theurl = stripAnchors(tab.url);

		console.debug('Tab "' + tabID + '" has URL "' + theurl + '"');

		/**
		* First check the URL is valid (starts with "http://"),
		* then see if it is cached. If so, then just use that,
		* otherwise go to TweetMeme to get the data
		*/
		if (theurl.substring(0, 7) != "http://") {
			console.warn('URL doesn\'t start with "http://"');
			display(theurl, '', tab.windowId);
			setBadgeColour('grey', tabID);
		} else if (isBlacklisted(theurl.substring(7, theurl.substring(7).indexOf('/') + 7))) {
			// the domain has been blacklisted by the user
			console.warn(theurl.substring(7, theurl.substring(7).indexOf('/')) + ' is blacklisted by user');
			display(theurl, '', tab.windowId);
			setBadgeColour('red', tabID);
		} else if (urls[theurl]) {
			/**
			* The URL's count is stored in our local cache,
			* so use that value instead of hitting TweetMeme
			* again
			*/
			setBadgeColour('green', tabID);
			if (urls[theurl] == CACHE_ERROR) {
				console.warn('Cached error found');
				display(theurl, CACHE_ERROR, tab.windowId);
			} else {
				console.debug('Count of ' + urls[theurl] + ' found in cache, using that');
				display(theurl, urls[theurl], tab.windowId);
			}
		} else {
			/**
			* The URL is valid and not in our cache,
			* so hit TweetMeme to get the value
			*/
			setBadgeColour('green', tabID);
			console.debug('Valid URL and not in cache, so hitting TweetMeme for data on ' + theurl);

			/**
			* Blank it out while we make the request
			*/
			display(theurl, '', tab.windowId);

			var x = new XMLHttpRequest();

			/**
			* We build the response function here while
			* all the variables we need are in scope
			*/
			var response = function(e) {
				if (x.readyState == 4) {
					console.debug('State: LOADED for HTTP request for "' + theurl + '"');
					data = eval('(' + x.responseText + ')');
					setBadgeColour('green', tabID);
					if (data.status == "success") {
						/**
						* Data returned was ok, so cache it and then display
						*/
						cacheAndDisplay(theurl, data.url_count, tab.windowId);
					} else {
						/**
						* Error returned, so cache that as well so we don't
						* cause massive load
						*/
						cacheAndDisplay(theurl, CACHE_ERROR, tab.windowId);
					}
				} else if (x.readyState == 3) {
					console.debug('State: RECEIVING for HTTP request for "' + theurl + '"');
				} else if (x.readyState == 2) {
					console.debug('State: SENT for HTTP request for "' + theurl + '"');
				} else if (x.readyState == 1) {
					console.debug('State: OPEN for HTTP request for "' + theurl + '"');
				} else if (x.readyState == 0) {
					console.debug('State: UNITIALISED for HTTP request for "' + theurl + '"');
				}
			}

			/**
			* Register the callback and dispatch the request
			*/
			x.onreadystatechange = response;
			x.open('GET', 'http://api.tweetmeme.com/v2/addons/bar.json?url=' + encodeURI(theurl), true);
			x.send(null);
		}
	});
}

/**
* Sets up the listeners for when a tab is changed
* or updated - we need to see if we have a new URL
*/
chrome.tabs.onUpdated.addListener(updateUpdated);
chrome.tabs.onSelectionChanged.addListener(updateSelectionChanged);
console.debug('Listeners attached');


text:
{% from "culture_macros.html" import render_feedback_form %}

{% extends "culture_activity_base.html" %}

{% block title %}{{ _("Sketch a Story")}}{% endblock %}

{% block culture_body %}

{{ _("Sketch a Story")}}

{{ _("Use WordCounter to analyze a musician's lyrics and sketch a story with their words") }}

      {# Set Up #}

{{ _("Set Up") }}

{{ _("This activity will take 30 to 45 minutes. You should have these materials on hand:") }}

{{ _("A projector to show these videos")}}

{{ _("Large pieces of paper to draw on (2 feet by 3 feet is best)")}}

{{ _("Thick crayons or markers of different colors")}}

{{ _("A phone, tablet, or computer connected to the internet for each small
            group of 3 people")}}

{{ _("Planning to show the videos offline? Click here to download them in advance.")}}

{{ _("Download and print the activity guide") }}

      {# Asking Questions #}

1

{{ _("Kick-Off The Activity") }}

{{ _("It is hard to go from data to story.  This activity lets you quickly do that by analyzing datasets to find patterns in text, and then sketching out some story you find.  It introduces basic terminology for quantitative text analysis, helps you get acquainted with Databasic.io's WordCounter tool, and prompts you to consider places in your organization where you work with text as data.  Participants will pair up with colleagues to search for stories in some fun sample data and then draw a sketch to share that story. Start the activity by playing the kickoff video below for your group.") }}

{{ _("Introduce the activity and then give folks about 15 minutes to sketch.  With 10 minutes left let them know that they should have chosen a dataset to work with. When they have 5 minutes left make sure they have a story and are sketching on paper, otherwise they'll be scrambling to get a drawing done.") }}

      {# Gathering Data #}

2

{{ _("Have Everyone Share Back") }}

{{ _("Play this video after each small group has sketched their story on a large sheet of paper. Here we outline some questions to discuss as each group describes the story that they found. For example, you'll want to take note of stories based on comparing two things versus those those based on a single, interesting data point. And you can start a conversation about how groups used visual parameters – like color, size and position – to communicate their story.") }}

      {# Analyzing Data #}

3

{{ _("Wrap-Up and Talk Next Steps") }}

{{ _("Now that everyone has analyzed text and sketched a story, this video will help people think about where to go from here. For example, what are some text datasets that your organization already has on hand?  We discuss some more sophisticated methods of quantitative text analysis as well as point out some common pitfalls to try to avoid.") }}

      {{ render_feedback_form("word-counter") }}

{% endblock %}


text:
static NSString * const CONTEXT_NAME = @"foo";

@implementation Context

@synthesize elementStore = elementStore_;
@synthesize sessionId = sessionId_;

// The WebViewController has most of the actual functionality this vdir exposes.
// We'll just forward most messages there.
- (void)setResourceToViewMethodGET:(SEL)getMethod
                              POST:(SEL)postMethod
                          withName:(NSString *)name {
  [self setResource:[WebDriverResource resourceWithTarget:[self viewController]
                                                GETAction:getMethod
                                               POSTAction:postMethod]
           withName:name];
}

- (id)initWithSessionId:(int)theSessionId {
  if (![super init])
    return nil;

  sessionId_ = theSessionId;

  // The index returns the capabilities and OS of the browser
  [self setIndex:[WebDriverResource resourceWithTarget:self
                                             GETAction:@selector(capabilities)
                                            POSTAction:@selector(capabilities)
                                             PUTAction:NULL
                                          DELETEAction:@selector(deleteContext)
   ]];

  // Set the view to be visible. This is ignored.
  [self setResourceToViewMethodGET:@selector(visible)
                              POST:@selector(setVisible:)
                          withName:@"visible"];

  // Browse to given URL / get current URL.
  [self setResourceToViewMethodGET:@selector(URL)
                              POST:@selector(setURL:)
                          withName:@"url"];

  // Evaluate the given javascript string. If the request causes a new page to
  // load, block until that loading is complete.
  // Note that this is 'raw' jsEval - as opposed to /execute below.
  [self setResourceToViewMethodGET:NULL
                              POST:@selector(jsEvalAndBlock:)
                          withName:@"eval"];

  // The current title of the web pane.
  [self setResourceToViewMethodGET:@selector(currentTitle)
                              POST:NULL
                          withName:@"title"];

  // Go back.
  [self setResourceToViewMethodGET:NULL
                              POST:@selector(back)
                          withName:@"back"];

  // Go forward.
  [self setResourceToViewMethodGET:NULL
                              POST:@selector(forward)
                          withName:@"forward"];

  // Refresh the page.
  [self setResourceToViewMethodGET:NULL
                              POST:@selector(refresh)
                          withName:@"refresh"];

  // Get the loaded HTML
  [self setResourceToViewMethodGET:@selector(source)
                              POST:NULL
                          withName:@"source"];

  // Get a screenshot
  [self setResourceToViewMethodGET:@selector(screenshot)
                              POST:NULL
                          withName:@"screenshot"];

  // Load firebug into the webview. This doesn't currently work.
  // TODO(josephg): find out why firebug doesn't load and fix it.
  [self setResourceToViewMethodGET:NULL
                              POST:@selector(addFirebug)
                          withName:@"firebug"];

  // Execute JS function with the given body. This takes an optional second
  // argument which is a list of arguments to the function.
  // Executes (function() { $1 }).apply(null, $2);
  WebDriverResource *executeScript
        = [WebDriverResource resourceWithTarget:self
                                      GETAction:NULL
                                     POSTAction:@selector(executeScript:withArguments:)];
  [executeScript setAllowOptionalArguments:YES];
  [self setResource:executeScript withName:@"execute"];

  // /element will be an ElementStore virtual directory. We also forward
  // /elements to the element store - getting from there returns multiple
  // element results.
  elementStore_ = [[ElementStore alloc] init];
  [self setResource:elementStore_ withName:@"element"];
  [self setResource:[WebDriverResource resourceWithTarget:elementStore_
                                                GETAction:NULL
                                               POSTAction:@selector(findElementsByMethod:query:)]
           withName:@"elements"];

  [self setResource:[Cookie cookieWithSessionId:sessionId_]
           withName:@"cookie"];

  return self;
}

- (id)init {
  NSLog(@"context created with unknown session id");
  return [self initWithSessionId:0];
}

- (void)dealloc {
  [super dealloc];
}

+ (NSString *)contextName {
  return CONTEXT_NAME;
}

- (id)capabilities {
  NSMutableDictionary *caps = [NSMutableDictionary dictionary];
  [caps setObject:@"mobile safari" forKey:@"browserName"];
  [caps setObject:@"MAC" forKey:@"platform"];
  [caps setValue:[NSNumber numberWithBool:YES]
          forKey:@"javascriptEnabled"];
  [caps setObject:@"1.0" forKey:@"version"];
  return caps;
}

// This is called from session when the client sends DELETE to session.
- (void)deleteContext {
  NSLog( @"Delete session: %d", sessionId_ );
  [contents removeAllObjects];
  [elementStore_ release];
}

#pragma mark Webdriver Resource configuration

- (void)configureResource:(id<HTTPResource>)resource {
  if ([resource respondsToSelector:@selector(setContext:)]) {
    [(id)resource setContext:CONTEXT_NAME];
  }
  if ([resource respondsToSelector:@selector(setSession:)]) {
    [(id)resource setSession:[NSString stringWithFormat:@"%d", sessionId_]];
  }
}

- (id<HTTPResource>)elementWithQuery:(NSString *)query {
  id<HTTPResource> resource = [super elementWithQuery:query];
  [self configureResource:resource];
  return resource;
}

@end


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	function count_visit(){
		$CI=&get_instance();

		if(empty($CI->input->cookie('skill_user'))||empty($CI->input->cookie('skill_token'))){
			return false;
		}
		$user_id=$CI->input->cookie('skill_user');
		$login_key=$CI->input->cookie('skill_token');

		$credentials=array('user_id'=>$user_id,'token'=>$login_key,'valid'=>1);
		$CI->db->select('valid');
		$CI->db->where($credentials);
		$loginCheck=$CI->db->count_all_results('login');
		if($loginCheck==1){
			return true;
		}
		return false;
	}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OTFN.Core.Market
{
    public class ForexSymbolNames
    {
        public const string EURUSD = "EURUSD";
        public const string EURGBP = "EURGBP";
        public const string GBPUSD = "GBPUSD";
        public const string USDCAD = "USDCAD";
        public const string EURCAD = "EURCAD";
        public const string EURJPY = "EURJPY";
        public const string USDJPY = "USDJPY";
        public const string GBPJPY = "GBPJPY";
        public const string GBPCAD = "GBPCAD";
        public const string EURAUD = "EURAUD";
        public const string AUDCAD = "AUDCAD";
        public const string AUDUSD = "AUDUSD";
        public const string CADJPY = "CADJPY";
        public const string XAUUSD = "XAUUSD";
        public const string XAGUSD = "XAGUSD";
        public const string AUDNZD = "AUDNZD";
//        public const string  = "";
    }
}


text:
<?php

class Sub_category_m extends MY_Model
{
    protected $_table_name = 'sub_categorys';
    protected $_primary_key = 'id';

    function __construct()
    {
        parent::__construct();
    }

    public function add_sub_category()
    {
        $this->data = [
            'category_id' => $this->input->post('category'),
            'sub_category_title' => $this->input->post('sub_category_title')
        ];

        if ($this->save($this->data)) {
            return true;
        }else{
            return false;
        }
    }

    public function get_sub_category() {
        $this->db->select('sub_categorys.id,sub_categorys.sub_category_title,categorys.category_title');
        $this->db->join('categorys', 'sub_categorys.category_id=categorys.id');
        $this->db->order_by("sub_category_title", "asc");
        $sub_categorys = $this->get();
        if(count($sub_categorys)){
            return $sub_categorys;
        }else {
            return FALSE;
        }
    }

    public function update_sub_category($sub_category_id = null)
    {
        $this->data = [
            'sub_category_title' => $this->input->post('sub_category_title')
        ];

        if ($this->save($this->data,$sub_category_id)) {
            return true;
        }else{
            return false;
        }
    }

    public function get_sub_category_by_cat_id($category_id) {

        $this->db->where('category_id', $category_id);
        $this->db->order_by("sub_category_title", "asc");

        $sub_categorys = $this->get();
        if(count($sub_categorys)){
            return $sub_categorys;
        }else {
            return FALSE;
        }
    }

}

?>


text:
require 'spec_helper'
require 'vk/api/photos/methods/restore'

RSpec.describe Vk::API::Photos::Methods::Restore do
  subject(:model) { described_class }
  it { is_expected.to be < Dry::Struct }
  it { is_expected.to be < Vk::Schema::Method }

  describe 'attributes' do
    subject(:attributes) { model.instance_methods(false) }

    it { is_expected.to include :owner_id }
    it { is_expected.to include :photo_id }
  end
end


text:
Danilo Correa <danilosilva87@gmail.com>
Emmerson Siqueira <emmersonsiqueira@gmail.com>
--TEST--
PhpLabel rule exception should not be thrown for valid inputs
--FILE--
<?php

declare(strict_types=1);

require 'vendor/autoload.php';

use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Exceptions\PhpLabelException;
use Respect\Validation\Validator as v;

try {
    v::phpLabel()->check('f o o');
} catch (PhpLabelException $exception) {
    echo $exception->getMessage() . PHP_EOL;
}

try {
    v::not(v::phpLabel())->check('correctOne');
} catch (PhpLabelException $exception) {
    echo $exception->getMessage() . PHP_EOL;
}

try {
    v::phpLabel()->assert('0wner');
} catch (NestedValidationException $exception) {
    echo $exception->getFullMessage() . PHP_EOL;
}

try {
    v::not(v::phpLabel())->assert('Respect');
} catch (NestedValidationException $exception) {
    echo $exception->getFullMessage() . PHP_EOL;
}
?>
--EXPECT--
"f o o" must be a valid PHP label
"correctOne" must not be a valid PHP label
- "0wner" must be a valid PHP label
- "Respect" must not be a valid PHP label


text:
layout: post
title: 'Starck: hasta en la birra'
tags:
- micrographic
- product design
---
Primero fue un ratón, luego un sofá, y después un despertador. La semana pasada nos descubrió su colección de relojes de pulsera y ayer su propia cerveza.

Philippe Starck amenaza con convertirse en algo así como el "Jordi Labanda" o la "Agatha Ruiz de la Prada" del diseño industrial. Claro que todo esto ya lo pusieron en práctica otros mucho antes… La mercadotecnia por encima de todo. Sign of the times!

Vía MoCo Loco


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('lotes', '0006_remove_modelotermica_modelo'),
    ]

    operations = [
        migrations.AlterField(
            model_name='modelotermica',
            name='receita',
            field=models.CharField(blank=True, max_length=8192, null=True, verbose_name='receita'),
        ),
    ]


text:
module RuboCop
  module Cop
    # Common code for ordinary arrays with [] that can be written with %
    # syntax.
    module ArraySyntax
      private

      def bracketed_array_of?(element_type, node)
        return false unless node.square_brackets? && node.values.size > 1

        node.values.all? { |value| value.type == element_type }
      end
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Affordable Web and Graphic design for SMEs and individuals in Ireland. The quality of our services will surpass your expectations.">
    <meta name="author" content="Verta">

    <title>Verta</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Libre+Franklin:300i,400,400i" rel="stylesheet">

    <link href="css/agency.css" rel="stylesheet">
    <link href="css/contact.css" rel="stylesheet">

    <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
    <link rel="manifest" href="/manifest.json">
    <meta name="theme-color" content="#ffffff">
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                VERTA

                        Services

                        What is Verta

                        About

                        Contact

                        Offers

                        Portfolio

Do you want to grow your business?

With Verta, you can!

                Tell Me More

Our services are outstanding

let us tell you why

We can create your website, hassle free!

                        Don't worry! We will handle everything and you don't have to worry about a thing. Simply sit back while we create a website to take your business to the next level.

We'll give you access to real time analytics with every website from us!

                        You get real time insights into how your business is performing online, all displayed neatly in charts & graphs. This will help you know what'll make your website more popular.

We'll have your website ready in no time at all!

                        We'll make your website in just a few short weeks, even less in most cases. We put your business online quickly so you don't miss a thing.

 We'll even handle your advertising!

                        We will take care of all your advertising needs. We'll also perform Search Engine Optimisation, making your site appear close to the top of people's searches online.

We'll take your idea and turn it into a design you'll be proud of!

                        After a quick consultation with you, we will have enough information to tailor a design perfectly to your needs. We'll handle all the design, leaving you to focus on the important stuff.

We keep our prices affordable to enable anyone to get online!

                        It's simple! We use modern web technologies to make your website more affordable. Our packages won't sacrifice on anything.

        Check out our offers

What is Verta?

Verta is...

Tailored

Designed for you

Accessible

A website for everyone

Mobile

Your website on any device

Beautiful

Beauty never ceases to amaze

Adaptable

Your logo will look great anywhere

Precise

Designed with care for details

         Check out our portfolio

About

A little bit about our company.

Verta Web & Graphic Design was founded to provide SMEs and Individuals with web and graphic design at an unbeatable price and quality. Our designs are modern and will surpass your expectations.

Contact Us

                    <form action="https://formspree.io/info@verta.ie" method="POST">

                                    <input type="text" class="form-control" placeholder="Your Name *" name="name">

                                    <input type="email" class="form-control" placeholder="Your Email *" name="email">

                                    <textarea class="form-control" placeholder="Your Message *" name="message"></textarea>

                                <button type="submit" value="Send" class="btn btn-xl">Send Message</button>

                    </form>

 Info@verta.ie

 @verta.ie

 0858181139

                    Copyright © Verta 2017

Privacy Policy and Terms of Use

Tailored

A design that suits your needs

We can make logos and graphic design for a wide variety of applications. Is it a cup, a bag, a shirt, a flyer? Chat to us and we will help you!

                                        <button type="button" class="btn btn-primary" data-dismiss="modal"> Close </button>

Accessible

                                    A website for everyone

                                 Some websites are hard to navigate but not ours. Rest assured all your content will look neat and organised.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close </button>

Mobile

Your website on any device

                                 Nearly 60% of web searches from mobile devices, so it's important that your website presents well on mobile devices.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close </button>

Beautiful

Beauty never ceases to amaze

A picture speaks a thousand words? well, our websites speak a million with their beautiful modern design. So why not find out for yourself?

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close </button>

Adaptable

Your logo will look great anywhere.

We will supply you with numerous sizes, shapes and layouts of your logo so that it can be used for numerous applications, and if you still need help you can always chat with us.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close </button>

Precision

Designed with care

We design the graphics with precison and extra care, we design them as if they were for ourselves. Worry not, your are in good hands!

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close </button>


text:
.sf-toolbarreset div,.sf-toolbarreset dl,.sf-toolbarreset dt,.sf-toolbarreset dd,.sf-toolbarreset ul,.sf-toolbarreset ol,.sf-toolbarreset li,.sf-toolbarreset h1,.sf-toolbarreset h2,.sf-toolbarreset h3,.sf-toolbarreset h4,.sf-toolbarreset h5,.sf-toolbarreset h6,.sf-toolbarreset pre,.sf-toolbarreset code,.sf-toolbarreset form,.sf-toolbarreset fieldset,.sf-toolbarreset legend,.sf-toolbarreset input,.sf-toolbarreset textarea,.sf-toolbarreset p,.sf-toolbarreset blockquote,.sf-toolbarreset th,.sf-toolbarreset td
	{
	margin: 0;
	padding: 0;
}

.sf-toolbarreset table {
	border-collapse: collapse;
	border-spacing: 0;
}

.sf-toolbarreset fieldset,.sf-toolbarreset img {
	border: 0;
}

.sf-toolbarreset address,.sf-toolbarreset caption,.sf-toolbarreset cite,.sf-toolbarreset code,.sf-toolbarreset dfn,.sf-toolbarreset em,.sf-toolbarreset strong,.sf-toolbarreset th,.sf-toolbarreset var
	{
	font-style: normal;
	font-weight: normal;
}

.sf-toolbarreset li {
	list-style: none;
}

.sf-toolbarreset caption,.sf-toolbarreset th {
	text-align: left;
}

.sf-toolbarreset h1,.sf-toolbarreset h2,.sf-toolbarreset h3,.sf-toolbarreset h4,.sf-toolbarreset h5,.sf-toolbarreset h6
	{
	font-size: 100%;
	font-weight: normal;
}

.sf-toolbarreset q:before,.sf-toolbarreset q:after {
	content: '';
}

.sf-toolbarreset abbr,.sf-toolbarreset acronym {
	border: 0;
	font-variant: normal;
}

.sf-toolbarreset sup {
	vertical-align: text-top;
}

.sf-toolbarreset sub {
	vertical-align: text-bottom;
}

.sf-toolbarreset input,.sf-toolbarreset textarea,.sf-toolbarreset select
	{
	font-family: inherit;
	font-size: inherit;
	font-weight: inherit;
}

.sf-toolbarreset input,.sf-toolbarreset textarea,.sf-toolbarreset select
	{
	*font-size: 100%;
}

.sf-toolbarreset legend {
	color: #000;
}

.sf-toolbarreset {
	background: #cbcbcb;
	background-image: -moz-linear-gradient(-90deg, #e8e8e8, #cbcbcb);
	background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#e8e8e8),
		to(#cbcbcb));
	bottom: 0;
	left: 0;
	z-index: 6000000;
	width: 100%;
	border-top: 1px solid #bbb;
	padding: 5px 0;
	margin: 0;
	font: 11px Verdana, Arial, sans-serif;
	color: #000;
}

.sf-toolbarreset abbr {
	border-bottom: 1px dotted #000000;
	cursor: help;
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Microsoft.Rest.Azure
{
    using System.Globalization;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using Microsoft.Rest.ClientRuntime.Azure.Properties;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    /// <summary>
    /// Defines long running operation polling state.
    /// </summary>
    /// <typeparam name="TBody">Type of resource body.</typeparam>
    /// <typeparam name="THeader">Type of resource header.</typeparam>
    internal class PollingState<TBody, THeader> where TBody : class where THeader : class
    {
#if DEBUG
        const int TEST_MIN_DELAY_SECONDS = 0;
        const int DEFAULT_MIN_DELAY_SECONDS = 0;
        const int DEFAULT_MAX_DELAY_SECONDS = 40;
#else
        // Delay values are in seconds
        const int TEST_MIN_DELAY_SECONDS = 0;
        const int DEFAULT_MIN_DELAY_SECONDS = 10;
        const int DEFAULT_MAX_DELAY_SECONDS = 600;
#endif

        private int _retryAfterInSeconds;
        private int _clientLongRunningOperationRetryTimeout;
        private bool _isRunningUnderPlaybackMode;

        /// <summary>
        /// Initializes an instance of PollingState.
        /// </summary>
        /// <param name="response">First operation response.</param>
        /// <param name="retryTimeout">Default timeout.</param>
        public PollingState(HttpOperationResponse<TBody, THeader> response, int? retryTimeout)
        {
            // Due to test/playback scenario, we prioritze retryTimeout set by Client (client.LongRunningOperationRetryTimeout property)
            // So LROTimeoutsetbyClient needs to be set first before we set the generic RetryAfterInSeconds value
            LROTimeoutSetByClient = retryTimeout.HasValue ? retryTimeout.Value : AzureAsyncOperation.DefaultDelay;
            RetryAfterInSeconds = retryTimeout.HasValue ? retryTimeout.Value : AzureAsyncOperation.DefaultDelay;
            Response = response.Response;
            Request = response.Request;
            Resource = response.Body;
            ResourceHeaders = response.Headers;
            _isRunningUnderPlaybackMode = false;

            string raw = response.Response.Content == null ? null : response.Response.Content.AsString();

            JObject resource = null;
            if (!string.IsNullOrEmpty(raw))
            {
                try
                {
                    resource = JObject.Parse(raw);
                }
                catch (JsonException)
                {
                    // failed to deserialize, return empty body
                }
            }

            switch (Response.StatusCode)
            {
                case HttpStatusCode.Accepted:
                    Status = AzureAsyncOperation.InProgressStatus;
                    break;
                case HttpStatusCode.OK:
                    if (resource != null && resource["properties"] != null &&
                        resource["properties"]["provisioningState"] != null)
                    {
                        Status = (string)resource["properties"]["provisioningState"];
                    }
                    else
                    {
                        Status = AzureAsyncOperation.SuccessStatus;
                    }
                    break;
                case HttpStatusCode.Created:
                    if (resource != null && resource["properties"] != null &&
                        resource["properties"]["provisioningState"] != null)
                    {
                        Status = (string) resource["properties"]["provisioningState"];
                    }
                    else
                    {
                        Status = AzureAsyncOperation.InProgressStatus;
                    }
                    break;
                case HttpStatusCode.NoContent:
                    Status = AzureAsyncOperation.SuccessStatus;
                    break;
                default:
                    Status = AzureAsyncOperation.FailedStatus;
                    break;
            }
        }

        private string _status;

        private CloudException _cloudException;

        /// <summary>
        /// Gets or sets polling status.
        /// </summary>
        public string Status {
            get
            {
                return _status;
            }
            set
            {
                if (value == null)
                {
                    throw new CloudException(Resources.NoProvisioningState);
                }
                _status = value;
            }
        }

        /// <summary>
        /// Gets or sets the latest value captured from Azure-AsyncOperation header.
        /// </summary>
        public string AzureAsyncOperationHeaderLink { get; set; }

        /// <summary>
        /// Gets or sets the latest value captured from Location header.
        /// </summary>
        public string LocationHeaderLink { get; set; }

        private HttpResponseMessage _response;

        /// <summary>
        /// Gets or sets last operation response.
        /// </summary>
        public HttpResponseMessage Response
        {
            get { return _response; }
            set
            {
                _response = value;
                if (_response != null)
                {
                    if (_response.Headers.Contains("azSdkTestPlayBackMode"))
                    {
                        _isRunningUnderPlaybackMode = bool.Parse(_response.Headers.GetValues("azSdkTestPlayBackMode").FirstOrDefault());
                    }
                    if (_response.Headers.Contains("Azure-AsyncOperation"))
                    {
                        AzureAsyncOperationHeaderLink = _response.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
                    }
                    if (_response.Headers.Contains("Location"))
                    {
                        LocationHeaderLink = _response.Headers.GetValues("Location").FirstOrDefault();
                    }
                    if (_response.Headers.Contains("Retry-After"))
                    {
                        string retryValue = _response.Headers.GetValues("Retry-After").FirstOrDefault();
                        RetryAfterInSeconds = int.Parse(retryValue, CultureInfo.InvariantCulture);
                    }
                }
            }
        }

        /// <summary>
        /// Gets or sets last operation request.
        /// </summary>
        public HttpRequestMessage Request { get; set; }

        /// <summary>
        /// Gets or sets cloud error.
        /// </summary>
        public CloudError Error { get; set; }

        /// <summary>
        /// Gets or sets resource.
        /// </summary>
        public TBody Resource { get; set; }

        /// <summary>
        /// Gets or sets resource header.
        /// </summary>
        public THeader ResourceHeaders { get; set; }

        /// <summary>
        /// This timeout is set by client during client construction
        /// This is useful to detect if we are running in test/playback mode
        /// </summary>
        private int LROTimeoutSetByClient
        {
            get
            {
                return _clientLongRunningOperationRetryTimeout;
            }
            set
            {
                _clientLongRunningOperationRetryTimeout = value;
            }
        }

        /// <summary>
        /// Gets long running operation delay in milliseconds.
        /// </summary>
        [Obsolete("DelayInMilliseconds property will be deprecated in future releases. You should start using DelayBetweenPolling")]
        public int DelayInMilliseconds
        {
            get
            {
                return RetryAfterInSeconds * 1000;
            }
        }

        /// <summary>
        /// Long running operation polling delay
        /// </summary>
        public TimeSpan DelayBetweenPolling
        {
            get
            {
                return TimeSpan.FromSeconds(RetryAfterInSeconds);
            }
        }

        /// <summary>
        /// Initially this is initialized with LongRunningOperationRetryTimeout value
        /// Verify min/max allowed value according to ARM spec (especially minimum value for throttling at ARM level)
        /// We want this to be int value and not int? because this value will always have a default non-zero/non-null value
        /// </summary>
        internal int RetryAfterInSeconds
        {
            get
            {
                return _retryAfterInSeconds;
            }

            set
            {
                _retryAfterInSeconds = ValidateRetryAfterValue(value);
            }
        }

        /// <summary>
        /// Test hook to determine if running under Playback mode (test mode)
        /// </summary>
        internal bool IsRunningUnderPlaybackMode
        {
            get
            {
                if (Response != null)
                {
                    if (Response.Headers.Contains("azSdkTestPlayBackMode"))
                    {
                        _isRunningUnderPlaybackMode = bool.Parse(Response.Headers.GetValues("azSdkTestPlayBackMode").FirstOrDefault());
                    }
                }

                return _isRunningUnderPlaybackMode;
            }
        }

        private int ValidateRetryAfterValue(int? currentValue)
        {
            if (currentValue.HasValue)
            {
                if (currentValue <= TEST_MIN_DELAY_SECONDS)
                    currentValue = TEST_MIN_DELAY_SECONDS;
                else if (currentValue < DEFAULT_MIN_DELAY_SECONDS)
                    currentValue = DEFAULT_MIN_DELAY_SECONDS;
                else if (currentValue > DEFAULT_MAX_DELAY_SECONDS)
                    currentValue = DEFAULT_MAX_DELAY_SECONDS;

                if (IsRunningUnderPlaybackMode)
                {
                    currentValue = TEST_MIN_DELAY_SECONDS;
                }
                else
                {
                    if (LROTimeoutSetByClient == TEST_MIN_DELAY_SECONDS)    // we assume playback mode (test mode)
                    {
                        if (currentValue != LROTimeoutSetByClient)  //Case where Retry-After is set to non zero, we set it to 0 in playback mode
                        {
                            currentValue = TEST_MIN_DELAY_SECONDS;
                        }
                    }
                }
            }
            else
            {
                currentValue = AzureAsyncOperation.DefaultDelay;
            }

            return currentValue.Value;
        }

        /// <summary>
        /// Gets CloudException from current instance.
        /// </summary>
        public CloudException CloudException
        {
            get
            {
                if(_cloudException == null)
                {
                    _cloudException = new CloudException(string.Format(CultureInfo.InvariantCulture,
                                            Resources.LongRunningOperationFailed, Status))
                    {
                        Body = Error,
                        Request = new HttpRequestMessageWrapper(Request, Request.Content.AsString()),
                        Response = new HttpResponseMessageWrapper(Response, Response.Content.AsString())
                    };
                }

                return _cloudException;
            }

            internal set
            {
                _cloudException = value;
            }
        }

        /// <summary>
        /// Gets AzureOperationResponse from current instance.
        /// </summary>
        public AzureOperationResponse<TBody, THeader> AzureOperationResponse
        {
            get
            {
                return new AzureOperationResponse<TBody, THeader>
                {
                    Body = Resource,
                    Headers = ResourceHeaders,
                    Request = Request,
                    Response = Response
                };
            }
        }
    }
}


text:
/**
 * Package contains ajax-enabled navigation components
 */
package org.orienteer.core.component.table.navigation;


text:
<?php

namespace Symfony\Component\Debug;

function headers_sent()
{
    return false;
}

function header($str, $replace = true, $status = null)
{
    Tests\testHeader($str, $replace, $status);
}

namespace Symfony\Component\Debug\Tests;

function testHeader()
{
    static $headers = array();

    if (!$h = func_get_args()) {
        $h = $headers;
        $headers = array();

        return $h;
    }

    $headers[] = func_get_args();
}


text: graphs on Irelands soccer rankings from 2006 to 2015