text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Egypt Election Data </title>
        <link rel="icon" href="assets/img/favicon.ico" >
          <link rel="stylesheet" href="assets/css/animate.css">
        <link href='http://api.tiles.mapbox.com/mapbox.js/v1.6.0/mapbox.css' rel='stylesheet' />
        <link rel="stylesheet" href="assets/js/vendor/jquery-morris-chart/css/morris.css" />
        <link rel="stylesheet" href="assets/css/foundation.css">
        <link rel="stylesheet" href="assets/css/surfaceui.css">
        <link rel="stylesheet" href="assets/css/eed.css">

Egypt Election data

Menu

 English

العربية


text: A Python client for CellBase

redpajama_set_name: RedPajamaGithub


text:
using namespace std;
using namespace COLIDE_RIGID;

void SinglePointSimulator::forward () {
  assert(quality_>1e-4);
  v_ += h_*join_force_/quality_;
  u_ = h_*v_;
}

void SinglePointSimulator::SetExtForce (const Eigen::Vector3d &extforce) {
  extforce_ = extforce;
  join_force_ = extforce_ + gravity_;
  //ZSW_REDUNDANT("join force:" << join_force_.transpose());
}

void SinglePointSimulator::CalSetGravity (const Eigen::Vector3d &g_normal)
{
  assert(quality_ > 1e-4);
  gravity_ = quality_ * g_normal;
  join_force_ = extforce_ + gravity_;
  ZSW_REDUNDANT("join force:" << join_force_.transpose());
}


text:
package org.locationtech.geomesa.hbase.utils

import java.util.Collections

import org.apache.hadoop.hbase.client.metrics.ScanMetrics
import org.apache.hadoop.hbase.client.{Result, ResultScanner}

object EmptyScanner extends ResultScanner {
  override def next(): Result = Iterator.empty.next()
  override def next(i: Int): Array[Result] = Iterator.empty.next()
  override def close(): Unit = {}
  override def iterator(): java.util.Iterator[Result] = Collections.emptyIterator()

  // override for methods in hbase 1.4 - can't mark them as override as it won't compile with 1.3

  // noinspection AccessorLikeMethodIsEmptyParen
  def getScanMetrics(): ScanMetrics = null
  def renewLease(): Boolean = false
}


text:
module.exports = function() {
  this.Given(/^I visit Index/, function() {
    this.driver.get('http://localhost:9000/#/')
  });

  this.Then(/^I should see "([^"]*)" in the data bound field for "([^"]*)"$/, function(expected, field) {
    // express the regexp above with the code you wish you had
    return this.Widget.read({
      selector: 'div[liaison-bind="' + field + '"]'
    }).should.eventually.eql(expected);
  });

  this.When(/^I update "([^"]*)" input to "([^"]*)"$/, function(field, value) {
    // express the regexp above with the code you wish you had
    this.Widget.fill({
      selector: "input[liaison-bind='" + field + "']",
      value: [""]
    });
    new this.Widget({
      root: "input[liaison-bind='" + field + "']",
      value: ['', '\uE007']
    }).sendKeys(value, '\uE007');
  });
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall.Content.Instructions;
using System.ComponentModel;
using System.Xml.Serialization;
using Newtonsoft.Json;
using GlueCommon.Converters;

namespace FlatRedBall.Glue.SaveClasses
{

    [TypeConverter(typeof(SerializableExpandableObjectConverter))]
    public class StateSave
    {

        public string Name
        {
            get;
            set;
        }
        public List<InstructionSave> InstructionSaves { get; set; } = new List<InstructionSave>();

        [XmlIgnore]
        [JsonIgnore]
        public static Func<StateSave, string> ToStringDelegate;

        #region Methods

        public StateSave Clone()
        {
            StateSave newStateSave = this.MemberwiseClone() as StateSave;

            newStateSave.InstructionSaves = new List<InstructionSave>();

            foreach (InstructionSave instructionSave in InstructionSaves)
            {
                newStateSave.InstructionSaves.Add(instructionSave.Clone());
            }

            return newStateSave;
        }

        public bool AssignsVariable(CustomVariable variable)
        {
            foreach (InstructionSave instructionSave in this.InstructionSaves)
            {
                if (instructionSave.Value != null && instructionSave.Member == variable.Name)
                {
                    return true;
                }
            }
            return false;
        }

        public void SortInstructionSaves(List<CustomVariable> customVariables)
        {
            int insertLocation = 0;

            for (int i = InstructionSaves.Count - 1; i > -1; i--)
            {
                InstructionSave instruction = InstructionSaves[i];
                bool wasFound = false;
                for (int j = 0; j < customVariables.Count; j++)
                {
                    if (customVariables[j].Name == instruction.Member)
                    {
                        wasFound = true;
                        break;
                    }
                }

                if (!wasFound)
                {
                    InstructionSaves.RemoveAt(i);
                }
            }

            for (int i = 0; i < customVariables.Count; i++)
            {
                string name = customVariables[i].Name;

                for (int j = insertLocation; j < InstructionSaves.Count; j++)
                {
                    InstructionSave instruction = InstructionSaves[j];

                    if (instruction.Member == name)
                    {
                        InstructionSaves.Remove(instruction);
                        InstructionSaves.Insert(insertLocation, instruction);
                        insertLocation++;
                        break;
                    }

                }
            }

        }

        public override string ToString()
        {
            if (ToStringDelegate != null)
            {
                return ToStringDelegate(this);
            }
            else
            {
                return Name + " (State)";
            }
        }

        #endregion
    }
}


text:
package edu.drexel.cis.dragon.ir.index.sequence;

public abstract interface SequenceWriter
{
  public abstract void initialize();

  public abstract void close();

  public abstract boolean addSequence(int paramInt, int[] paramArrayOfInt);
}

/* Location:           C:\dragontoolikt\dragontool.jar
 * Qualified Name:     dragon.ir.index.sequence.SequenceWriter
 * JD-Core Version:    0.6.2
 */


text:
import re
import os
from os import path
import sys
import subprocess

def main():
    tests = sorted([fn for fn in os.listdir('x86-obj')
                    if re.match(r'^dmamodel_[^\.]+$', fn) is not None])
    test_files = [path.abspath(path.join('x86-obj', fn)) for fn in tests]
    test_names = [fn.split('_', 1)[1] for fn in tests]
    for name, fn in zip(test_names, test_files):
        sys.stdout.write('{0}. '.format(name))
        try:
            subprocess.check_output([fn])
        except subprocess.CalledProcessError as ex:
            print 'FAILED! (assert on line {0})'.format(ex.output.strip())
            continue
        print 'Passed.'

if __name__=='__main__':
    main()


text:
title: CodeCademy 4
layout: post
author: ben.munton
permalink: /codecademy-4/
source-id: 1BvFOWSL_3PBeO4IKkQ6_9p_-yrmzWfZI0k-mwC7EOVE
published: true
---

    Title
    CodeCademy 4
    Date
    6/2/17

    Starting point:
    23%

    Target for this lesson?
    25%

    Did I reach my target?
(add details to "Lesson Review")
    Yes, (28%)

    Lesson Review

    How did I learn? What strategies were effective?

    I carried on from last week, and I made sure that I read all of the instructions thoroughly, as that slowed me down last week.  This week I kept working, and I got to 28%, but I was further on as I was near to the end.  I got stuck on a few questions, but carried on trying new methods, and carried on.

    What limited my learning? Which habits do I need to work on?

    This week I got a bit distracted, and lost focus. This was partly to do with the fact that Mr. Keen had not spoken directly to us any instructions. He had not given us any direct work, but just said to get on with our work.

    What will I change for next time? How will I improve my learning?

    Next lesson, we will get further, and I will be on at least 30% by then by doing 1 exercise a day.  I will concentrate more, and get to at least 33% I hope.


text:
package com.andersonbco.shortener.services.exceptions;

public class CustomAliasExistsException extends RuntimeException{

	/**
	 *
	 */
	private static final long serialVersionUID = 1696068276907560715L;

	public CustomAliasExistsException(String message) {
		super(message);
	}

	public CustomAliasExistsException(String message, Throwable cause) {
		super(message, cause);
	}
}


text:
package org.jenkins.ci.plugins.jenkinslint.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Victor Martinez
 */
public class StringUtils {

    public static boolean isEmptyOrBlank (String line) {
        boolean found = false;
        Pattern p = Pattern.compile("^\\s+");
        Matcher m = p.matcher(line);
        found = m.matches();
        return found || line.isEmpty();
    }

    public static boolean isShellComment(String line) {
        boolean found = false;
        Pattern p = Pattern.compile("^\\s*#\\s*.*");
        Matcher m = p.matcher(line);
        found = m.matches();
        return found;
    }

    public static boolean isBatchComment(String line) {
        boolean found = false;
        Pattern p = Pattern.compile("^\\s*REM\\s*.*", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(line);
        found = m.matches();
        return found;
    }

    public static boolean isH (String line) {
        boolean found = false;
        Pattern p = Pattern.compile("^\\s*h.*", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(line);
        found = m.matches();
        return found;
    }

    public static boolean isAt (String line) {
        boolean found = false;
        Pattern p = Pattern.compile("^\\s*@.*");
        Matcher m = p.matcher(line);
        found = m.matches();
        return found;
    }
}


text:
@interface ViewController : NSViewController

    - (IBAction)showPanelAction:(id)sender;

@end


text:
package cmd

import (
	"fmt"
	"os"
	"path"

	"github.com/spf13/cobra"
)

const flush_all_flag string = "all"

// flushCmd represents the flush command
var flushCmd = &cobra.Command{
	Use:   "flush ID [ID...]",
	Short: "Delete files permanently",
	Long: `Delete given deletion groups permanently from the disk.
Use listing command to find deletion group IDs of files
from trash. Note that files that are flushed cannot be
recovered with this tool. Notice also that no file shredding
will be done - if you need shredding, use a specialized tool for it.`,
	Run: func(cmd *cobra.Command, args []string) {
		allFlag, _ := cmd.Flags().GetBool(flush_all_flag)

		// validate inputs
		{
			if !allFlag && len(args) < 1 { // not enough parameters
				cmd.Help()
				return
			}

			// if --all flag is passed, there should not be any other argument
			if allFlag && len(args) > 0 {
				fmt.Println("Error: --all parameter cannot be combined with other arguments")
				fmt.Println()
				cmd.Help()
				return
			}
		}

		ensureTrashDirExists(false)
		trashPath := getTrashPath()

		// handle the case when --all is passed
		if allFlag {
			os.RemoveAll(trashPath)
			createDir(trashPath)
			return
		}

		delGroups := getSelectedDeletionGroups(args, trashPath)

		// delete each of deletion groups passed as program arguments
		{
			for _, dg := range delGroups {
				deletionPath := path.Join(trashPath, dg.startingDir)
				os.RemoveAll(deletionPath)

				fmt.Printf("All files from %s were permanently deleted\n", deletionPath)
			}
			fmt.Println("flush operation successfully completed.")
		}
	},
}

func init() {
	RootCmd.AddCommand(flushCmd)
	flushCmd.Flags().Bool(flush_all_flag, false, "Permanently delete all files from trash")
}


text:
namespace OS
{
    class WaitTimerImpl
    {
    public:
        WaitTimerImpl()
            : m_timer(nullptr)
        {}

        ~WaitTimerImpl()
        {
            Terminate();
        }

        HRESULT Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback)
        {
            m_context = context;
            m_callback = callback;

            m_timer = CreateThreadpoolTimer(WaitCallback, this, nullptr);
            RETURN_LAST_ERROR_IF_NULL(m_timer);

            return S_OK;
        }

        void Terminate()
        {
            if (m_timer != nullptr)
            {
                SetThreadpoolTimer(m_timer, nullptr, 0, 0);
                WaitForThreadpoolTimerCallbacks(m_timer, TRUE);
                CloseThreadpoolTimer(m_timer);
                m_timer = nullptr;
            }
        }

        void Start(_In_ uint64_t absoluteTime)
        {
            LARGE_INTEGER li;
            FILETIME ft;
            ASSERT((absoluteTime & 0x8000000000000000) == 0);
            li.QuadPart = static_cast<LONGLONG>(absoluteTime);
            ft.dwHighDateTime = li.HighPart;
            ft.dwLowDateTime = li.LowPart;

            SetThreadpoolTimer(m_timer, &ft, 0, 0);
        }

        void Cancel()
        {
            SetThreadpoolTimer(m_timer, nullptr, 0, 0);
        }

    private:

        PTP_TIMER m_timer;
        void* m_context;
        WaitTimerCallback* m_callback;

        static VOID CALLBACK WaitCallback(
            _Inout_ PTP_CALLBACK_INSTANCE,
            _Inout_opt_ void* context,
            _Inout_ PTP_TIMER)
        {
            if (context != nullptr)
            {
                WaitTimerImpl* pthis = static_cast<WaitTimerImpl*>(context);
                pthis->m_callback(pthis->m_context);
            }
        }
    };

    WaitTimer::WaitTimer() noexcept
        : m_impl(nullptr)
    {}

    WaitTimer::~WaitTimer() noexcept
    {
        Terminate();
    }

    HRESULT WaitTimer::Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback) noexcept
    {
        if (m_impl.load() != nullptr || callback == nullptr)
        {
            ASSERT(FALSE);
            return E_UNEXPECTED;
        }

        std::unique_ptr<WaitTimerImpl> timer(new (std::nothrow) WaitTimerImpl);
        RETURN_IF_NULL_ALLOC(timer.get());
        RETURN_IF_FAILED(timer->Initialize(context, callback));

        m_impl = timer.release();

        return S_OK;
    }

    void WaitTimer::Terminate() noexcept
    {
        std::unique_ptr<WaitTimerImpl> timer(m_impl.exchange(nullptr));
        if (timer != nullptr)
        {
            timer->Terminate();
        }
    }

    void WaitTimer::Start(_In_ uint64_t absoluteTime) noexcept
    {
        m_impl.load()->Start(absoluteTime);
    }

    void WaitTimer::Cancel() noexcept
    {
        m_impl.load()->Cancel();
    }

    uint64_t WaitTimer::GetAbsoluteTime(_In_ uint32_t msFromNow) noexcept
    {
        FILETIME ft;
        ULARGE_INTEGER li;
        GetSystemTimeAsFileTime(&ft);
        ASSERT((ft.dwHighDateTime & 0x80000000) == 0);

        uint64_t hundredNanosFromNow = msFromNow;
        hundredNanosFromNow *= 10000ULL;

        li.HighPart = ft.dwHighDateTime;
        li.LowPart = ft.dwLowDateTime;
        li.QuadPart += hundredNanosFromNow;

        return li.QuadPart;
    }
} // Namespace


text:
"""
    Kubernetes

    No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)

    OpenAPI spec version: v1.7.4

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import os
import sys
import unittest

import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1_initializers import V1Initializers

class TestV1Initializers(unittest.TestCase):
    """ V1Initializers unit test stubs """

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testV1Initializers(self):
        """
        Test V1Initializers
        """
        model = kubernetes.client.models.v1_initializers.V1Initializers()

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


text:
module Ganesha
  module Repositories
    class LinksInMemory
      attr_reader :links, :next_id

      def initialize
        @links = {}
        @next_id = 1
      end

      def all
        links.values
      end

      def between(from, to)
        range = from..to

        all.select do |link|
          range.cover? link.created_at.to_date
        end
      end

      def save(link)
        link.id = next_id
        links[next_id] = link
        @next_id += 1
        link
      end

      def count
        links.length
      end
    end
  end
end


text:
package logic

import (
	"context"
	"strconv"
	"testing"
	"time"

	"golang.org/x/time/rate"

	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
	apiv1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	vpa_types "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/autoscaling.k8s.io/v1"
	target_mock "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/target/mock"
	"k8s.io/autoscaler/vertical-pod-autoscaler/pkg/updater/eviction"
	"k8s.io/autoscaler/vertical-pod-autoscaler/pkg/updater/priority"
	"k8s.io/autoscaler/vertical-pod-autoscaler/pkg/utils/status"
	"k8s.io/autoscaler/vertical-pod-autoscaler/pkg/utils/test"
)

func parseLabelSelector(selector string) labels.Selector {
	labelSelector, _ := metav1.ParseToLabelSelector(selector)
	parsedSelector, _ := metav1.LabelSelectorAsSelector(labelSelector)
	return parsedSelector
}

func TestRunOnce_Mode(t *testing.T) {
	tests := []struct {
		name                  string
		updateMode            vpa_types.UpdateMode
		expectFetchCalls      bool
		expectedEvictionCount int
	}{
		{
			name:                  "with Auto mode",
			updateMode:            vpa_types.UpdateModeAuto,
			expectFetchCalls:      true,
			expectedEvictionCount: 5,
		},
		{
			name:                  "with Initial mode",
			updateMode:            vpa_types.UpdateModeInitial,
			expectFetchCalls:      false,
			expectedEvictionCount: 0,
		},
		{
			name:                  "with Off mode",
			updateMode:            vpa_types.UpdateModeOff,
			expectFetchCalls:      false,
			expectedEvictionCount: 0,
		},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			testRunOnceBase(
				t,
				tc.updateMode,
				newFakeValidator(true),
				tc.expectFetchCalls,
				tc.expectedEvictionCount,
			)
		})
	}
}

func TestRunOnce_Status(t *testing.T) {
	tests := []struct {
		name                  string
		statusValidator       status.Validator
		expectFetchCalls      bool
		expectedEvictionCount int
	}{
		{
			name:                  "with valid status",
			statusValidator:       newFakeValidator(true),
			expectFetchCalls:      true,
			expectedEvictionCount: 5,
		},
		{
			name:                  "with invalid status",
			statusValidator:       newFakeValidator(false),
			expectFetchCalls:      false,
			expectedEvictionCount: 0,
		},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			testRunOnceBase(
				t,
				vpa_types.UpdateModeAuto,
				tc.statusValidator,
				tc.expectFetchCalls,
				tc.expectedEvictionCount,
			)
		})
	}
}

func testRunOnceBase(
	t *testing.T,
	updateMode vpa_types.UpdateMode,
	statusValidator status.Validator,
	expectFetchCalls bool,
	expectedEvictionCount int,
) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	replicas := int32(5)
	livePods := 5
	labels := map[string]string{"app": "testingApp"}
	selector := parseLabelSelector("app = testingApp")
	containerName := "container1"
	rc := apiv1.ReplicationController{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "rc",
			Namespace: "default",
		},
		Spec: apiv1.ReplicationControllerSpec{
			Replicas: &replicas,
		},
	}
	pods := make([]*apiv1.Pod, livePods)
	eviction := &test.PodsEvictionRestrictionMock{}

	for i := range pods {
		pods[i] = test.Pod().WithName("test_"+strconv.Itoa(i)).
			AddContainer(test.BuildTestContainer(containerName, "1", "100M")).
			WithCreator(&rc.ObjectMeta, &rc.TypeMeta).
			Get()

		pods[i].Labels = labels
		eviction.On("CanEvict", pods[i]).Return(true)
		eviction.On("Evict", pods[i], nil).Return(nil)
	}

	factory := &fakeEvictFactory{eviction}
	vpaLister := &test.VerticalPodAutoscalerListerMock{}

	podLister := &test.PodListerMock{}
	podLister.On("List").Return(pods, nil)

	vpaObj := test.VerticalPodAutoscaler().
		WithContainer(containerName).
		WithTarget("2", "200M").
		WithMinAllowed("1", "100M").
		WithMaxAllowed("3", "1G").
		Get()
	vpaObj.Spec.UpdatePolicy = &vpa_types.PodUpdatePolicy{UpdateMode: &updateMode}
	vpaLister.On("List").Return([]*vpa_types.VerticalPodAutoscaler{vpaObj}, nil).Once()

	mockSelectorFetcher := target_mock.NewMockVpaTargetSelectorFetcher(ctrl)

	updater := &updater{
		vpaLister:                    vpaLister,
		podLister:                    podLister,
		evictionFactory:              factory,
		evictionRateLimiter:          rate.NewLimiter(rate.Inf, 0),
		recommendationProcessor:      &test.FakeRecommendationProcessor{},
		selectorFetcher:              mockSelectorFetcher,
		useAdmissionControllerStatus: true,
		statusValidator:              statusValidator,
		priorityProcessor:            priority.NewProcessor(),
	}

	if expectFetchCalls {
		mockSelectorFetcher.EXPECT().Fetch(gomock.Eq(vpaObj)).Return(selector, nil)
	}
	updater.RunOnce(context.Background())
	eviction.AssertNumberOfCalls(t, "Evict", expectedEvictionCount)
}

func TestRunOnceNotingToProcess(t *testing.T) {
	eviction := &test.PodsEvictionRestrictionMock{}
	factory := &fakeEvictFactory{eviction}
	vpaLister := &test.VerticalPodAutoscalerListerMock{}
	podLister := &test.PodListerMock{}
	vpaLister.On("List").Return(nil, nil).Once()

	updater := &updater{
		vpaLister:                    vpaLister,
		podLister:                    podLister,
		evictionFactory:              factory,
		evictionRateLimiter:          rate.NewLimiter(rate.Inf, 0),
		recommendationProcessor:      &test.FakeRecommendationProcessor{},
		useAdmissionControllerStatus: true,
		statusValidator:              newFakeValidator(true),
	}
	updater.RunOnce(context.Background())
}

func TestGetRateLimiter(t *testing.T) {
	cases := []struct {
		rateLimit       float64
		rateLimitBurst  int
		expectedLimiter *rate.Limiter
	}{
		{0.0, 1, rate.NewLimiter(rate.Inf, 0)},
		{-1.0, 2, rate.NewLimiter(rate.Inf, 0)},
		{10.0, 3, rate.NewLimiter(rate.Limit(10), 3)},
	}
	for _, tc := range cases {
		limiter := getRateLimiter(tc.rateLimit, tc.rateLimitBurst)
		assert.Equal(t, tc.expectedLimiter.Burst(), limiter.Burst())
		assert.InDelta(t, float64(tc.expectedLimiter.Limit()), float64(limiter.Limit()), 1e-6)
	}
}

type fakeEvictFactory struct {
	evict eviction.PodsEvictionRestriction
}

func (f fakeEvictFactory) NewPodsEvictionRestriction(pods []*apiv1.Pod, vpa *vpa_types.VerticalPodAutoscaler) eviction.PodsEvictionRestriction {
	return f.evict
}

type fakeValidator struct {
	isValid bool
}

func newFakeValidator(isValid bool) status.Validator {
	return &fakeValidator{isValid}
}

func (f *fakeValidator) IsStatusValid(statusTimeout time.Duration) (bool, error) {
	return f.isValid, nil
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 18(4): 306 (1934)

#### Original name
null

### Remarks
null


text:
Noambox is designed to play music on single-board computers(like Raspberry Pi).This program is written in Python.It runs a httpserver(tornado) and offers a webui controller.

### LICENSE
PLEASE READ THE [LICENSE](https://github.com/imsuwj/noambox/blob/master/LICENSE) FILE.


text:
require('mmState');

//状态配置
avalon.state('INDEX', {
  url: '/',
  views: {
    '': {
      templateProvider: function () {
        return new Promise(function (rs) {require.ensure([], function () {rs(require('text!../modules/login/login.html'));});});
      },
      controllerProvider: function () {
        return new Promise(function (rs) {require.ensure([], function () {rs(require('../modules/login/login.js'));});});
      },
      ignoreChange: function (changeType) {
        if(changeType) return true;
      }
    }
  }
});
avalon.state('ERR404', {
  url: '/error/404',
  views: {
    '': {
      templateProvider: function () {
        return new Promise(function (rs) {require.ensure([], function () {rs(require('text!../modules/common/error/404.html'));});});
      },
      ignoreChange: function (changeType) {
        if(changeType) return true;
      }
    }
  }
});


text:
{-# LANGUAGE PackageImports #-}
import Control.Monad (unless, join, when)
import Control.Monad.Fix
import Control.Concurrent (threadDelay)
import Control.Monad.Random

import "GLFW-b" Graphics.UI.GLFW as GLFW
import qualified Graphics.UI.GLUT as GLUT
import Graphics.Gloss.Rendering
import FRP.Elerea.Simple

import Rocketfuel.Types
import Rocketfuel.Commands
import Rocketfuel.Display
import Rocketfuel.Input

defaultCommand :: Maybe Command
defaultCommand = Nothing

main :: IO()
main = do let width = 800
              height = 600
              mouseState = Click (0.0, 0.0) Released
          -- Initialize GLUT, Elerea and GlossState
          (_,_) <- GLUT.getArgsAndInitialize
          (mouse, mouseSink) <- external mouseState
          glossState <- initState
          resources <- loadResources
          baseContext <- buildContext
          let baseCommand = defaultCommand
          randomGenerator <- newStdGen
          -- Get a window and loop
          withWindow width height "Rocketfuel" $ \window -> do
            -- Prepare the FRP network
            network <- start $ do
                command <- transfer baseCommand updateCommand mouse
                newContext <- transfer (baseContext, randomGenerator) updateContext command
                return $ displayContext window (width, height) glossState resources <$> (grid . fst) `fmap` newContext
            fix $ \loop -> do
                readMouse window mouseSink
                join network
                threadDelay 20000
                quit <- keyIsPressed window Key'Escape
                unless quit loop

-- Utility function to get a window
withWindow :: Int -> Int -> String -> (GLFW.Window -> IO ()) -> IO ()
withWindow width height title f = do
    GLFW.setErrorCallback $ Just simpleErrorCallback
    r <- GLFW.init
    when r $ do
                m <- GLFW.createWindow width height title Nothing Nothing
                case m of
                    (Just win) -> do
                        GLFW.makeContextCurrent m
                        f win
                        GLFW.setErrorCallback $ Just simpleErrorCallback
                        GLFW.destroyWindow win
                    Nothing -> return ()
                GLFW.terminate
    where
        simpleErrorCallback e s = putStrLn $ unwords [show e, show s]


text:
package wookie.example

import java.io.File
import java.util.Properties
import javafx.application.Platform
import javafx.scene.control.Label
import javafx.scene.layout.VBox

import org.slf4j.LoggerFactory
import wookie.view._
import wookie.{PanelSupplier, WookiePanel, WookieSandboxApp, WookieScenario}

case class DownloadResult(file:Option[File], message: String, ok:Boolean){

}

/**
 * @author Andrey Chaschev chaschev@gmail.com
 */
object DownloadJDK {
  import scala.concurrent.ExecutionContext.Implicits.global

  var login = ""
  var password = ""

  final val logger = LoggerFactory.getLogger(DownloadJDK.getClass)

  @volatile
  var version: String = "8u11"

  @volatile
  var miniMode: Boolean = false

  // current design assumes multiple downloaders are possible
  // this closure is used to create a single download panel
  val defaultPanelSupplier = new PanelSupplier {
    override def apply(): WookiePanel = {
      val wookieView = WookieView.newBuilder
        .useFirebug(false)
        .useJQuery(true)
        .createWebView(!DownloadJDK.miniMode)
        .includeJsScript(io.Source.fromInputStream(getClass.getResourceAsStream("/wookie/downloadJDK.js")).mkString)
        .build

      WookiePanel.newBuilder(wookieView)
        .userPanel(new VBox(wookieView.progressLabel, wookieView.progressBar))
        .build
    }

  }
  def main(args: Array[String])
  {
    val app = WookieSandboxApp.start()

    val props = new Properties()

    props.load(getClass.getResourceAsStream("/auth.properties"))

    login = props.getProperty("oracle.login")
    password = props.getProperty("oracle.password")

    app.runOnStage(
      new WookieScenario(
        url = Some("http://www.google.com"),
        title = "Downloading JDK " + DownloadJDK.version,
        panel = defaultPanelSupplier,
        procedure = (wookiePanel, wookie, $) => {

          //this is login form state
          wookie.waitForLocation(wookie.defaultArg("login form")
            .timeoutNone()
            .matchByAddress(_.contains("signon.jsp"))
            .whenLoaded(new WhenPageLoaded {
            override def apply()(implicit e: PageDoneEvent): Unit = {
              logger.info(s"signon form: ${$("#sso_username")}")

              $("#sso_username").value(login)
              $("#ssopassword").value(password)

              $(".submit_btn").followLink()
            }
          }))

          // this is download detection by an url
          wookie.waitForDownloadToStart(
            new LocationMatcher(loc =>
              loc.contains("download.oracle.com") && loc.contains("?")
            )
          ).andThen({ case result =>
            logger.info(s"download done: $result")
          })

          // download logic
          // first try the latest version page, which does not require oracle login
          // then try archives page for the JDK version given
          val (latestUrl, archiveUrl) = findLinksFromVersion()

          if (latestUrl.isDefined) {
            tryFindVersionAtPage(wookie, latestUrl.get, (found:Boolean) => {
              if(!found){
                tryArchivePage(found, archiveUrl, wookie)
              }else{
                println(s"found the link at ${latestUrl.get}, download should start...")
              }
            })
          } else {
            tryArchivePage(found = false, archiveUrl, wookie)
          }
        }))
  }

  def findLinksFromVersion(): (Option[String], Option[String]) = {
    val archiveLinksMap = Map(
      5 -> "http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html",
      6 -> "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html",
      7 -> "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html",
      8 -> "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html"
    )

    val latestLinksMap = Map(
      7 -> "http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html",
      8 -> "http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html"
    )

    var archiveUrl: Option[String] = None
    var latestUrl: Option[String] = None

    val ch = DownloadJDK.version.charAt(0)

    if (List('8', '7', '6', '5').contains(ch)) {
      latestUrl = latestLinksMap.get(ch - '0')
      archiveUrl = archiveLinksMap.get(ch - '0')
    }

    (latestUrl, archiveUrl)
  }

  def setStatus(label:Label, s: String)
  {
    Platform.runLater(new Runnable {
      def run()
      {
        label.setText(s)
      }
    })
  }

  protected def tryArchivePage(found: Boolean, archiveUrl: Option[String], browser: WookieView) = {
    if (!found && archiveUrl.isDefined) {
      tryFindVersionAtPage(browser, archiveUrl.get, (found) => {
        if (found) {
          logger.info("found a link, will be redirected to the login page...")
        } else {
          //todo fixme complete download promise
//          downloadPromise.complete(Try(new DownloadResult(None, "didn't find a link", false)))
        }
      })
    } else {
      logger.info("download started...")
    }
  }

  private[wookie] def tryFindVersionAtPage(browser: WookieView, archiveUrl: String, whenDone: (Boolean) => Unit) =
  {
    browser.load(archiveUrl, new WhenPageLoaded {
      override def apply()(implicit e: PageDoneEvent): Unit = {
        try {
          val aBoolean = browser.getEngine.executeScript("downloadIfFound('" + DownloadJDK.version + "', true, 'linux');").asInstanceOf[Boolean]

          if (aBoolean) {
            whenDone.apply(true)
          }else {
            whenDone.apply(false)
          }
        } catch {
          case e: Exception => e.printStackTrace
        }
      }
    })
  }
}


text:
package net.wytrem.glmario.gl.shaders;

public class ShaderCompileException extends RuntimeException
{
    private static final long serialVersionUID = -6309728058019690755L;

    public ShaderCompileException()
    {
        super();
    }

    public ShaderCompileException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
    {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public ShaderCompileException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public ShaderCompileException(String message)
    {
        super(message);
    }

    public ShaderCompileException(Throwable cause)
    {
        super(cause);
    }
}


text:
#region References

using System;
using System.Collections.Generic;
using Scribe.Website.Models;

#endregion

namespace Scribe.Website.ViewModels
{
	public class AnalyticsHomeView
	{
		#region Properties

		public string EndDate { get; set; }

		public IEnumerable<AnalyticData<int>> MostActiveEditors { get; set; }

		public IEnumerable<AnalyticData<int>> MostActiveGroups { get; set; }

		public IEnumerable<AnalyticData<int>> MostActivePages { get; set; }

		public IEnumerable<AnalyticData<int>> MostViewPages { get; set; }

		public IEnumerable<AnalyticData<int>> NewPagesByUser { get; set; }

		public IEnumerable<AnalyticData<int>> NewPagesPerMonth { get; set; }

		public string StartDate { get; set; }

		#endregion
	}
}


text:
package gw2api

import (
	"net/url"
	"time"
)

// GuildPermission Name/Desc basically
type GuildPermission struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

// GuildPermissions Grab them all
func (gw2 *GW2Api) GuildPermissions() (res []string, err error) {
	ver := "v2"
	tag := "guild/permissions"
	err = gw2.fetchEndpoint(ver, tag, nil, &res)
	return
}

// GuildPermissionIds Names/Description of permissions
func (gw2 *GW2Api) GuildPermissionIds(ids ...string) (guild []GuildPermission, err error) {
	ver := "v2"
	tag := "guild/permissions"
	params := url.Values{}
	params.Add("ids", commaList(ids))
	err = gw2.fetchEndpoint(ver, tag, params, &guild)
	return
}

// GuildUpgradeCost specific costs of an upgrade. Type like Collection or Item
type GuildUpgradeCost struct {
	Type   string `json:"type"`
	Count  int    `json:"count"`
	Name   string `json:"name"`
	ItemID int    `json:"item_id"`
}

// GuildUpgrade All the Upgrade Information
type GuildUpgrade struct {
	ID            int                `json:"id"`
	Name          string             `json:"name"`
	Description   string             `json:"description"`
	BuildTime     int                `json:"build_time"`
	Icon          string             `json:"icon"`
	Type          string             `json:"type"`
	RequiredLevel int                `json:"required_level"`
	Experience    int                `json:"experience"`
	Prerequisites []int              `json:"prerequisites"`
	Costs         []GuildUpgradeCost `json:"costs"`
}

// GuildUpgrades Get them all
func (gw2 *GW2Api) GuildUpgrades() (res []int, err error) {
	ver := "v2"
	tag := "guild/upgrades"
	err = gw2.fetchEndpoint(ver, tag, nil, &res)
	return
}

// GuildUpgradeIds Translated information
func (gw2 *GW2Api) GuildUpgradeIds(lang string, ids ...int) (guild []GuildUpgrade, err error) {
	ver := "v2"
	tag := "guild/upgrades"
	params := url.Values{}
	if lang != "" {
		params.Add("lang", lang)
	}
	params.Add("ids", commaList(stringSlice(ids)))
	err = gw2.fetchEndpoint(ver, tag, params, &guild)
	return
}

// GuildRank Granted Permissions and Order to sorty by
type GuildRank struct {
	ID          string   `json:"id"`
	Order       int      `json:"order"`
	Permissions []string `json:"permissions"`
}

// GuildRanks Show all ranks in the guild
func (gw2 *GW2Api) GuildRanks(id string) (guild []GuildRank, err error) {
	ver := "v2"
	tag := "guild/" + id + "/ranks"
	err = gw2.fetchAuthenticatedEndpoint(ver, tag, PermGuilds, nil, &guild)
	return
}

// GuildMember Accountname, current rank and date they joined
type GuildMember struct {
	Name   string    `json:"name"`
	Rank   string    `json:"rank"`
	Joined time.Time `json:"joined"`

	// Only as part of guild team
	Role string `json:"role"`
}

// GuildMembers returns a list of all members
func (gw2 *GW2Api) GuildMembers(id string) (member []GuildMember, err error) {
	ver := "v2"
	tag := "guild/" + id + "/members"
	err = gw2.fetchAuthenticatedEndpoint(ver, tag, PermGuilds, nil, &member)
	return
}

// GuildStashItem represents a single slot in one of the bank tabs
type GuildStashItem struct {
	ID    int `json:"id"`
	Count int `json:"count"`
}

// GuildStash represents a bank tab in the guild bank
type GuildStash struct {
	UpgradeID int              `json:"upgrade_id"`
	Size      int              `json:"size"`
	Coins     int              `json:"coins"`
	Inventory []GuildStashItem `json:"inventory"`
}

// GuildStashes returns a list of all guild bank tabs and their content
func (gw2 *GW2Api) GuildStashes(id string) (stash []GuildStash, err error) {
	ver := "v2"
	tag := "guild/" + id + "/stash"
	err = gw2.fetchAuthenticatedEndpoint(ver, tag, PermGuilds, nil, &stash)
	return
}

// GuildTreasuryUpgrade represents an upgrade which requires the parent ressource
type GuildTreasuryUpgrade struct {
	UpgradeID int `json:"upgrade_id"`
	Count     int `json:"count"`
}

// GuildTreasury represents the need for an item. NeededBy show the upgrades needing it
type GuildTreasury struct {
	ID       int                    `json:"id"`
	Count    int                    `json:"count"`
	NeededBy []GuildTreasuryUpgrade `json:"needed_by"`
}

// GuildTreasuries returns a list of all currently needed items for any guild upgrade
func (gw2 *GW2Api) GuildTreasuries(id string) (treasury []GuildTreasury, err error) {
	ver := "v2"
	tag := "guild/" + id + "/treasury"
	err = gw2.fetchAuthenticatedEndpoint(ver, tag, PermGuilds, nil, &treasury)
	return
}

// GuildEmblems returns two lists for all emblem layers
func (gw2 *GW2Api) GuildEmblems() (foreground []int, background []int, err error) {
	ver := "v2"
	tag := "emblem/foregrounds"
	if err = gw2.fetchEndpoint(ver, tag, nil, &foreground); err != nil {
		return
	}
	tag = "emblem/backgrounds"
	err = gw2.fetchEndpoint(ver, tag, nil, &background)
	return
}

// EmblemLayers for the requested Fore/Background
type EmblemLayers struct {
	ID     int      `json:"id"`
	Layers []string `json:"layers"`
}

// GuildEmblemForegroundIds returns the layers for the requested foregrounds
func (gw2 *GW2Api) GuildEmblemForegroundIds(ids ...int) (layers []EmblemLayers, err error) {
	ver := "v2"
	tag := "emblem/foregrounds"
	params := url.Values{}
	params.Add("ids", commaList(stringSlice(ids)))
	err = gw2.fetchEndpoint(ver, tag, params, &layers)
	return
}

// GuildEmblemBackgroundIds returns the layers for the requested backgrounds
func (gw2 *GW2Api) GuildEmblemBackgroundIds(ids ...int) (layers []EmblemLayers, err error) {
	ver := "v2"
	tag := "emblem/backgrounds"
	params := url.Values{}
	params.Add("ids", commaList(stringSlice(ids)))
	err = gw2.fetchEndpoint(ver, tag, params, &layers)
	return
}

// GuildLogEntry returns information about certain events in a guild's log
type GuildLogEntry struct {
	ID   int       `json:"id"`
	Time time.Time `json:"time"`
	Type string    `json:"type"`
	//type = treasury
	ItemID int `json:"item_id"`
	Count  int `json:"count"`
	//type = motd
	Motd string `json:"motd"`
	//type = (motd|joined|invited)
	User string `json:"user"`
	//type = influence
	Activity          string   `json:"activity"`
	TotalParticipants int      `json:"total_participants"`
	Participants      []string `json:"participants"`
	//type = rank_change
	ChangedBy string `json:"changed_by"`
	OldRank   string `json:"old_rank"`
	NewRank   string `json:"new_rank"`
	//type = invited
	InvitedBy string `json:"invited_by"`
	//type = stash
	Operation string `json:"operation"`
	Coints    int    `json:"coins"`
	//type = upgrade
	UpgradeID int    `json:"upgrade_id"`
	Action    string `json:"action"`
}

// GuildLog returns up to a 100 of each type of log entry
func (gw2 *GW2Api) GuildLog(id string) (log []GuildLogEntry, err error) {
	ver := "v2"
	tag := "guild/" + id + "/log"
	err = gw2.fetchAuthenticatedEndpoint(ver, tag, PermGuilds, nil, &log)
	return
}

// GuildTeamStats per season stats of a guild team
type GuildTeamStats struct {
	SeasonID string `json:"id"`
	Wins     int    `json:"wins"`
	Losses   int    `json:"losses"`
	Rating   int    `json:"rating"`
}

// GuildTeam a designated team for PvP
type GuildTeam struct {
	ID        int            `json:"id"`
	Members   []GuildMember  `json:"members"`
	Name      string         `json:"name"`
	Aggregate WinLoss        `json:"aggregate"`
	Ladders   LadderStats    `json:"ladders"`
	Games     PvPGameStats   `json:"games"`
	Seasons   GuildTeamStats `json:"seasons"`
}

// GuildPvPTeams returns a list of teams for a guild
func (gw2 *GW2Api) GuildPvPTeams(id string) (teams []GuildTeam, err error) {
	ver := "v2"
	tag := "guild/" + id + "/teams"
	err = gw2.fetchAuthenticatedEndpoint(ver, tag, PermGuilds, nil, &teams)
	return
}


text:
cask "disk-drill" do
  version "4.7.382"
  sha256 :no_check

  url "https://dl.cleverfiles.com/diskdrill.dmg"
  name "Disk Drill"
  desc "Data recovery software"
  homepage "https://www.cleverfiles.com/"

  livecheck do
    url "https://www.cleverfiles.com/releases/auto-update/dd2-newestr.xml"
    strategy :sparkle
  end

  app "Disk Drill.app"

  uninstall script: {
    executable: "#{staged_path}/Disk Drill.app/Contents/Resources/uninstall",
    sudo:       true,
  }

  zap trash: [
    "~/Library/Application Support/DiskDrill",
    "~/Library/Caches/com.cleverfiles.Disk_Drill",
    "~/Library/Containers/com.cleverfiles.DiskDrill.Media/Data/cfbackd.chief",
    "~/Library/Logs/DiskDrill.log",
    "~/Library/Preferences/com.cleverfiles.Disk_Drill.plist",
    "~/Library/Preferences/com.cleverfiles.DiskDrill.plist",
    "~/Library/Preferences/com.cleverfiles.DiskDrill-setapp.plist",
  ]
end


text:
//using System;
//using System.Threading;
//using EasyNetQ.Interception;
//using EasyNetQ.Tests.Integration.Scheduling;
//using NUnit.Framework;

//namespace EasyNetQ.Tests.Integration
//{
//    [TestFixture]
//    public class PublishSubscribeWithInterceptionTest
//    {
//        [SetUp]
//        public void SetUp()
//        {
//            bus = RabbitHutch.CreateBus("host=localhost", x => x.EnableInterception(r => r.EnableGZipCompression().EnableTripleDESEncryption(Convert.FromBase64String("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), Convert.FromBase64String("aaaaaaaaaaa="))));
//        }

//        [TearDown]
//        public void TearDown()
//        {
//            if (bus != null) bus.Dispose();
//        }

//        private IBus bus;

//        [Test]
//        [Explicit("Needs an instance of RabbitMQ on localhost to work")]
//        public void Should_be_able_to_get_a_message()
//        {
//            var autoResetEvent = new AutoResetEvent(false);

//            bus.Subscribe<PartyInvitation>("Should_be_able_to_get_a_message", message =>
//                {
//                    Console.WriteLine("Got message: {0}", message.Text);
//                    autoResetEvent.Set();
//                });

//            var invitation = new PartyInvitation
//                {
//                    Text = "Please come to my party",
//                    Date = new DateTime(2011, 5, 24)
//                };

//            bus.Publish(invitation);

//            if (! autoResetEvent.WaitOne(100000))
//                Assert.Fail();
//        }
//    }
//}


text:
$script:dscModuleName = 'xWebAdministration'
$script:dscResourceFriendlyName = 'xWebConfigProperty'
$script:dscResourceName = "MSFT_$($script:dscResourceFriendlyName)"

#region HEADER
# Integration Test Template Version: 1.3.0
[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
    (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
    & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))
}

Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath (Join-Path -Path 'DSCResource.Tests' -ChildPath 'TestHelper.psm1')) -Force
# Ensure the WebAdministration module is imported into the current session!
Import-Module WebAdministration -Force
$TestEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $script:dscModuleName `
    -DSCResourceName $script:dscResourceName `
    -TestType Integration
#endregion

[string] $tempName = "$($script:dscResourceName)_" + (Get-Date).ToString('yyyyMMdd_HHmmss')

# Using try/finally to always cleanup.
try
{
    $configurationFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1"
    . $configurationFile

    $null = Backup-WebConfiguration -Name $tempName

    #region Integration Tests
    Describe "$($script:dscResourceName)_Integration" {
        # Create the website we'll use for testing purposes.
        $websiteName = New-Guid
        if (-not(Get-Website -Name $websiteName))
        {
            $websitePhysicalPath = "$($TestDrive)\$($websiteName)"
            New-Item -Path $websitePhysicalPath -ItemType Directory -Force | Out-Null
            New-Website -Name $websiteName -PhysicalPath $websitePhysicalPath | Out-Null
        }

        $ConfigurationData = @{
            AllNodes = @(
                @{
                    NodeName             = 'localhost'
                    WebsitePath          = "IIS:\Sites\$($websiteName)"
                    Filter               = 'system.webServer/directoryBrowse'
                    PropertyName         = 'enabled'
                    AddValue             = $true
                    UpdateValue          = $false
                    IntegerFilter        = '/SYSTEM.WEB/TRACE'
                    IntergerPropertyName = 'requestLimit'
                    IntegerValue         = [string](Get-Random -Minimum 11 -Maximum 1000)
                }
            )
        }

        $startDscConfigurationParameters = @{
            Path              = $TestDrive
            ComputerName      = 'localhost'
            Wait              = $true
            Verbose           = $true
            Force             = $true
        }

        $websitePath          = $ConfigurationData.AllNodes.WebsitePath
        $filter               = $ConfigurationData.AllNodes.Filter
        $propertyName         = $ConfigurationData.AllNodes.PropertyName
        $addValue             = $ConfigurationData.AllNodes.AddValue
        $updateValue          = $ConfigurationData.AllNodes.UpdateValue
        $integerFilter        = $ConfigurationData.AllNodes.IntegerFilter
        $intergerPropertyName = $ConfigurationData.AllNodes.IntergerPropertyName
        $integerValue         = $ConfigurationData.AllNodes.IntegerValue

        Context 'When Adding Property' {
            It 'Should compile and apply the MOF without throwing' {
                {
                    & "$($script:dscResourceName)_Add" -OutputPath $TestDrive -ConfigurationData $ConfigurationData
                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
            }

            It 'Should return $true for Test-DscConfiguration' {
                Test-DscConfiguration | Should Be $true
            }

            It 'Should have the correct value of the configuration property' {
                $value = (Get-WebConfigurationProperty -PSPath $websitePath -Filter $filter -Name $propertyName).Value

                $value | Should -Be $addValue
            }
        }

        Context 'When Updating a Property' {
            It 'Should compile and apply the MOF without throwing' {
                {
                    & "$($script:dscResourceName)_Update" -OutputPath $TestDrive -ConfigurationData $ConfigurationData
                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Not -Throw
            }

            It 'Should update the configuration property correctly' {
                $value = (Get-WebConfigurationProperty -PSPath $websitePath -Filter $filter -Name $propertyName).Value

                $value | Should -Be $updateValue
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
            }

            It 'Should return $true for Test-DscConfiguration' {
                Test-DscConfiguration | Should Be $true
            }
        }

        Context 'When Removing a Property' {
            It 'Should compile and apply the MOF without throwing' {
                {
                    & "$($script:dscResourceName)_Remove" -OutputPath $TestDrive -ConfigurationData $ConfigurationData
                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Not -Throw
            }

            It 'Should remove configuration property' {
                # Get the value.
                # Because configuration properties can be inherited (& I'm not aware of a reliable way to determine if the value returned is inherited or set explicitly),
                # we instead read the config file as XML directly & attempt to locate the property under test.

                $value = ([xml] ((Get-WebConfigFile -PSPath $websitePath) | Get-Content)).SelectSingleNode("//$($filter)/@$($propertyName)")
                $value | Should -Be $null
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
            }

            It 'Should return $true for Test-DscConfiguration' {
                Test-DscConfiguration | Should Be $true
            }
        }

        Context 'When Updating a Integer Property' {
            It 'Should compile and apply the MOF without throwing' {
                {
                    & "$($script:dscResourceName)_Integer" -OutputPath $TestDrive -ConfigurationData $ConfigurationData
                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
            }

            It 'Should update the configuration integer property correctly' {
                [string] $value = (Get-WebConfigurationProperty -PSPath $websitePath -Filter $integerFilter -Name $intergerPropertyName).Value

                $value | Should -Be $integerValue
            }

            It 'Should return $true for Test-DscConfiguration' {
                Test-DscConfiguration | Should Be $true
            }
        }

        # Remove the website we created for testing purposes.
        if (Get-Website -Name $websiteName)
        {
            Remove-Website -Name $websiteName
            Remove-Item -Path $websitePhysicalPath -Force -Recurse
        }
    }
    #endregion
}
finally
{
    #region FOOTER
    Restore-TestEnvironment -TestEnvironment $TestEnvironment

    # Addresses Issue #385: xWebConfigPropertyCollection: Timing issue in integration tests
    Start-Sleep -Seconds 4

    Restore-WebConfiguration -Name $tempName
    Remove-WebConfigurationBackup -Name $tempName
    #endregion
}


text:
var _            = require('lodash');
var logging      = require('./lib/logging');
var common       = require('./lib/common');

module.exports = async function do_act( instance, actmeta, prior_ctxt, origargs) {
  var args = _.clone(origargs)
  prior_ctxt = prior_ctxt || {chain:[],entry:true,depth:1}

  var act_callpoint = callpoint()

  var id_tx = ( args.id$ || args.actid$ || instance.idgen() ).split('/')

  var tx =
        id_tx[1] ||
        origargs.tx$ ||
        instance.fixedargs.tx$ ||
        instance.idgen()

  var actid    = (id_tx[0] || instance.idgen()) + '/' + tx

  var actstart = Date.now()

  if( await act_cache_check( instance, args, prior_ctxt, act_callpoint ) ) return;

  var actstats = act_stats_call( actmeta.pattern )

  // build callargs
  var callargs = args

  // remove actid so that user manipulation of args for subsequent use does
  // not cause inadvertent hit on existing action
  delete callargs.id$
  delete callargs.actid$ // legacy alias

  callargs.meta$ = {
    id:      actid,
    tx:      tx,
    start:   actstart,
    pattern: actmeta.pattern,
    action:  actmeta.id,
    entry:   prior_ctxt.entry,
    chain:   prior_ctxt.chain
  }

  if( actmeta.deprecate ) {
    instance.log.warn( 'DEPRECATED', actmeta.pattern, actmeta.deprecate,
                       act_callpoint )
  }

  logging.log_act_in( root, {actid:actid,info:origargs.transport$},
                      actmeta, callargs, prior_ctxt,
                      act_callpoint )

  instance.emit('act-in', callargs)

  var delegate = act_make_delegate( instance, tx, callargs, actmeta, prior_ctxt )

  callargs = _.extend({},callargs,delegate.fixedargs,{tx$:tx})

  var listen_origin = origargs.transport$ && origargs.transport$.origin

  var act_done = function(err) {
    try {
      var actend = Date.now()
      private$.timestats.point( actend-actstart, actmeta.argpattern )

      prior_ctxt.depth--
      prior_ctxt.entry = prior_ctxt.depth <= 0

      var result  = arr(arguments)

      var resdata = result[1]
      var info    = result[2]

      if( null == err &&
          null != resdata &&
          !(_.isPlainObject(resdata) ||
            _.isArray(resdata) ||
            !!resdata.entity$ ||
            !!resdata.force$
           ) &&
          so.strict.result)
      {

        // allow legacy patterns
        if( !( 'generate_id' === callargs.cmd ||
               true === callargs.note ||
               'native' === callargs.cmd ||
               'quickcode' === callargs.cmd
             ))
        {
          err = error(
            'result_not_objarr', {
              pattern:actmeta.pattern,
              args:util.inspect(common.clean(callargs)).replace(/\n/g,''),
              result:resdata
            })
        }
      }

      private$.actcache.set(actid,{
        result:  result,
        actmeta: actmeta,
        when:    Date.now()
      })

      if( err ) {
        private$.stats.act.fails++
        actstats.fails++

        var out = await act_error(instance,err,actmeta,result,
                            actend-actstart,callargs,prior_ctxt,act_callpoint)

        result[0] = out.err

        if( _.isFunction(delegate.on_act_err) ) {
          delegate.on_act_err(actmeta,result[0])
        }

        if( args.fatal$ ) {
          return instance.die(out.err)
        }
      }
      else {
        instance.emit('act-out',callargs,result[1])
        result[0] = null

        logging.log_act_out(
          root, {
            actid:    actid,
            duration: actend-actstart,
            info:     info,
            listen:   listen_origin
          },
          actmeta, callargs, result, prior_ctxt, act_callpoint )

        if( _.isFunction(delegate.on_act_out) ) {
          delegate.on_act_out(actmeta,result[1])
        }

        private$.stats.act.done++
        actstats.done++
      }

      // for exceptions thrown inside the callback
      catch( ex ) {
        var err = ex

        // handle throws of non-Error values
        if( !util.isError(ex) ) {
          err = ( _.isObject(ex) ?
                  new Error(jsonic.stringify(ex)) :
                  err = new Error(''+ex) )
        }

        await callback_error( instance, err, actmeta, result,
                        actend-actstart, callargs, prior_ctxt, act_callpoint )
      }
    }
    catch(ex) {
      instance.emit('error',ex)
    }
  }

  // TODO: err should instead be handled via async and try/catch!!
  try {
    await act_param_check( origargs, actmeta);

    var execspec = {
      id:      actid,
      gate:    prior_ctxt.entry && !!callargs.gate$,
      ungate:  !!callargs.ungate$,
      desc:    actmeta.argpattern

      plugin: {
        name: actmeta.plugin_name,
        tag:  actmeta.plugin_tag
      },

      fn: async function() {
        if( root.closed && !callargs.closing$ ) {
          return cb(error('instance-closed',{args:common.clean(callargs)}))
        }

        delegate.good = function(out) {
          return out;
        }

        delegate.bad = function(err) {
          throw err;
        }

        if( _.isFunction(delegate.on_act_in) ) {
          delegate.on_act_in(actmeta,callargs)
        }
        await actmeta.func.call(delegate,callargs)
      },
    }

    private$.executor.execute(execspec)

  } catch ( err ) {
      // async?
      if( err ) return act_done(err);
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Phrynium virgatum Roxb.

### Remarks
null


text:
PDF generation
==============

If you want to enable the generation of PDF you will need to install the
following requirements.

Requirements
------------

.. code-block:: shell

    sudo apt-get install libxml2-dev libxslt-dev libcairo-dev libffi-dev libpango1.0-dev

    # to include JPEG images in PDF files
    sudo apt-get install libgdk-pixbuf2.0-dev

    sudo pip3.5 install cairocffi weasyprint


text:
using System.IdentityModel.Configuration;
using System.Web;
using System.Web.Configuration;
using IFramework.Config;

namespace IFramework.SingleSignOn.IdentityProvider
{
    public class CustomSecurityTokenServiceConfiguration : SecurityTokenServiceConfiguration
    {
        private const string CustomSecurityTokenServiceConfigurationKey = "CustomSecurityTokenServiceConfigurationKey";
        private static readonly object SyncRoot = new object();

        public CustomSecurityTokenServiceConfiguration()
            : base(WebConfigurationManager.AppSettings[Common.IssuerName])
        {
            SecurityTokenService = Configuration.Instance.GetCustomSecurityTokenServiceType();
        }

        public static CustomSecurityTokenServiceConfiguration Current
        {
            get
            {
                var app = HttpContext.Current.Application;
                var config =
                    app.Get(CustomSecurityTokenServiceConfigurationKey) as CustomSecurityTokenServiceConfiguration;
                if (config != null)
                {
                    return config;
                }
                lock (SyncRoot)
                {
                    config =
                        app.Get(CustomSecurityTokenServiceConfigurationKey) as CustomSecurityTokenServiceConfiguration;
                    if (config == null)
                    {
                        config = new CustomSecurityTokenServiceConfiguration();
                        app.Add(CustomSecurityTokenServiceConfigurationKey, config);
                    }
                    return config;
                }
            }
        }
    }
}


text:
package com.amazonaws.services.guardduty.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.guardduty.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * PublicAccessMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class PublicAccessMarshaller {

    private static final MarshallingInfo<StructuredPojo> PERMISSIONCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("permissionConfiguration").build();
    private static final MarshallingInfo<String> EFFECTIVEPERMISSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("effectivePermission").build();

    private static final PublicAccessMarshaller instance = new PublicAccessMarshaller();

    public static PublicAccessMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(PublicAccess publicAccess, ProtocolMarshaller protocolMarshaller) {

        if (publicAccess == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(publicAccess.getPermissionConfiguration(), PERMISSIONCONFIGURATION_BINDING);
            protocolMarshaller.marshall(publicAccess.getEffectivePermission(), EFFECTIVEPERMISSION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
.. currentmodule:: altair

.. _user-guide-line-marks:

Line
~~~~
The ``line`` mark represents the data points stored in a field with a line connecting all of these points. Line marks are commonly used to depict trajectories or change over time. Unlike most other marks that represent one data element per mark, one line mark represents multiple data element as a single line, akin to ``area`` and ``trail``.

Note: For line segments that connect (x,y) positions to (x2,y2) positions, please use ``rule`` marks. For continuous lines with varying size, please use ``trail`` marks.

Examples
--------
Line Chart
^^^^^^^^^^
Using line with one temporal or ordinal field (typically on ``x``) and another quantitative field (typically on ``y``) produces a simple line chart with a single line.

.. altair-plot::
    import altair as alt
    from altair import datum
    from vega_datasets import data

    source = data.stocks()

    alt.Chart(source).mark_line().encode(
        x='date',
        y='price',
    ).transform_filter(
        datum.symbol == 'GOOG')

We can add create multiple lines by grouping along different attributes, such as ``color`` or ``detail``.

Multi-series Colored Line Chart
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Adding a field to a mark property channel such as ``color`` groups data points into different series, producing a multi-series colored line chart.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.stocks()

    alt.Chart(source).mark_line().encode(
        x='date',
        y='price',
        color='symbol',
    )

We can further apply selection to highlight a certain line on hover.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.stocks()

    highlight = alt.selection(type='single', on='mouseover',
                            fields=['symbol'], nearest=True)

    base = alt.Chart(source).encode(
        x='date:T',
        y='price:Q',
        color='symbol:N'
    )

    points = base.mark_circle().encode(
        opacity=alt.value(0)
    ).add_selection(
        highlight
    ).properties(
        width=600
    )

    lines = base.mark_line().encode(
        size=alt.condition(~highlight, alt.value(1), alt.value(3))
    )

    points + lines

Multi-series Line Chart with Varying Dashes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Adding a field to ``strokeDash`` also produces a multi-series line chart.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.stocks()

    alt.Chart(source).mark_line().encode(
        x='date',
        y='price',
        strokeDash='symbol',
    )

We can also use line grouping to create a line chart that has multiple parts with varying styles.

.. altair-plot::
    import altair as alt
    import pandas as pd

    source = pd.DataFrame({
        'a' : ['A', 'B', 'D', 'E', 'E', 'G', 'H'],
        'b' : [28, 55, 91, 81, 81, 19, 87],
        'predicted' : [False, False, False, False, True, True, True]
    })

    alt.Chart(source).mark_line().encode(
        x = 'a:O',
        y = 'b:Q',
        strokeDash = 'predicted:N'
    )

Multi-series Line Chart with the Detail Channel
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To group lines by a field without mapping the field to any visual properties, we can map the field to the ``detail`` channel to create a multi-series line chart with the same color.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.stocks()

    alt.Chart(source).mark_line().encode(
        x='date',
        y='price',
        detail='symbol',
    )

The same method can be used to group lines for a ranged dot plot.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.countries()

    base = alt.Chart(source).encode(
        alt.X('life_expect:Q', title= 'Life Expectancy (years)', scale=alt.Scale(zero=False)),
        alt.Y('country:N', title = 'Country', axis = alt.Axis(offset = 5, ticks = False, minExtent = 70, domain = False)),
    ).transform_filter(
        alt.FieldOneOfPredicate(field = 'country',
                                oneOf = ["China", "India", "United States", "Indonesia", "Brazil"])
    )

    line = base.mark_line().encode(
        detail = 'country',
        color = alt.value("#db646f")
    ).transform_filter(
        alt.FieldOneOfPredicate(field = 'year', oneOf = [1995, 2000])
    )

    point = base.mark_point(filled = True).encode(
        alt.Color(field = 'year',
                scale = alt.Scale(range = ["#e6959c", "#911a24"], domain = [1995, 2000])),
        size = alt.value(100),
        opacity = alt.value(1)
    )

    line + point

Line Chart with Point Markers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
By setting the ``point`` property of the mark definition to ``true`` or an object defining a property of the overlaying point marks, we can overlay point markers on top of line.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.stocks()

    alt.Chart(source).mark_line(point=True).encode(
        x='year(date)',
        y='mean(price):Q',
        color='symbol:N'
    )

This is equivalent to adding another layer of filled point marks.

Note that the overlay point marks have ``opacity`` = 1 by default (instead of semi-transparent like normal point marks).

Here we create stroked points by setting their ``\"filled\"`` to ``false`` and their fill to ``\"white\"``.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.stocks()

    alt.Chart(source).mark_line(point= alt.OverlayMarkDef(filled = False, fill = 'white')).encode(
        x='year(date)',
        y='mean(price):Q',
        color='symbol:N'
    )

Connected Scatter Plot (Line Chart with Custom Path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The line's path (order of points in the line) is determined by data values on the temporal/ordinal field by default. However, a field can be mapped to the ``order`` channel for determining a custom path.

For example, to show a pattern of data change over time between gasoline price and average miles driven per capita we use ``order`` channel to sort the points in the line by time field (year). In this example, we also use the ``point`` property to overlay point marks over the line marks to highlight each data point.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.driving()

    alt.Chart(source).mark_line(point=True).encode(
        alt.X('miles', scale=alt.Scale(zero=False)),
        alt.Y('gas', scale=alt.Scale(zero=False)),
        order='year'
    )

Line interpolation
^^^^^^^^^^^^^^^^^^
The ``interpolate`` property of a mark definition can be used to change line interpolation method. For example, we can set ``interpolate`` to ``"monotone"``.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.stocks()

    alt.Chart(source).mark_line(interpolate='monotone').encode(
        x='date',
        y='price'
    ).transform_filter(
        alt.datum.symbol == 'GOOG'
    )

We can also set ``interpolate`` to ``"step-after"`` to create a step-chart.

.. altair-plot::
    import altair as alt
    from vega_datasets import data

    source = data.stocks()

    alt.Chart(source).mark_line(interpolate='step-after').encode(
        x='date',
        y='price'
    ).transform_filter(
        alt.datum.symbol == 'GOOG'
    )

Geo Line
^^^^^^^^
By mapping geographic coordinate data to ``longitude`` and ``latitude`` channels of a corresponding projection, we can draw lines through geographic points.

.. altair-plot::
    import altair as alt
    from vega_datasets import data
    import pandas as pd

    airports = data.airports.url
    flights_airport = data.flights_airport.url

    states = alt.topo_feature(data.us_10m.url, feature="states")

    lookup_data = alt.LookupData(
        airports, key="iata", fields=["state", "latitude", "longitude"]
    )

    source = pd.DataFrame({
        'airport' : ['SEA', 'SFO', 'LAX', 'LAS', 'DFW', 'DEN', 'ORD', 'JFK'],
        'order' : [1, 2, 3, 4, 5, 6, 7, 8],
    })

    background = alt.Chart(states).mark_geoshape(
        fill="lightgray",
        stroke="white"
    ).properties(
        width=750,
        height=500
    ).project("albersUsa")

    line = alt.Chart(source).mark_line().encode(
        latitude="latitude:Q",
        longitude="longitude:Q",
        order = 'order'
    ).transform_lookup(
        lookup = 'airport',
        from_ = lookup_data
    )

    background + line

Line Config
^^^^^^^^^^^

The ``line`` property of the top-level ``config`` object sets the default properties for all line marks. If mark property encoding channels are specified for marks, these config values will be overridden.

The line config can contain any line mark properties (except ``type``, ``style``, and ``clip``).


text:
import { Link } from './Link';

describe('Link', () => {
    it('constructor initializes Link properly', () => {
        const link: Link = new Link();

        expect(link.getHealth()).toStrictEqual(6);
        expect(link.getBombCount()).toStrictEqual(99);
    });
});


text:
+++
abstract = ""
abstract_short = ""
authors = ["SM Gatesy", "KM Middleton", "BK Hall (editor)"]
date = "2007-01-02"
highlight = true
image_preview = ""
math = false
publication = "Fins Into Limbs"
publication_short = ""
publication_types = ["6"]
selected = false
title = "Skeletal Adaptations for Flight"
url_code = ""
url_dataset = ""
url_pdf = ""
url_project = "http://press.uchicago.edu/ucp/books/book/chicago/F/bo3793400.html"
url_slides = ""
url_video = ""

[header]
  caption = ""
  image = ""

+++


text:
package net.happybrackets.develop.softsynth;

import net.happybrackets.core.HBAction;
import net.happybrackets.core.HBReset;
import net.happybrackets.device.HB;

import javax.sound.midi.*;
import java.lang.invoke.MethodHandles;

// You can run this from classes folder using java -cp . net.happybrackets.develop.softsynth.RawSynth
public class RawSynth {
    // Change to the number of audio Channels on your device

    static public void runProgram() {

        try {
            Synthesizer midiSynth = MidiSystem.getSynthesizer();

            midiSynth.open();
            Instrument [] instr = midiSynth.getDefaultSoundbank().getInstruments();
            MidiChannel[] channels = midiSynth.getChannels();

            midiSynth.loadInstrument(instr[0]);
            channels[0].noteOn(60, 100);

            try {
                Thread.sleep( 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            channels[0].noteOff(60);

        } catch (MidiUnavailableException e) {
            e.printStackTrace();
        }

        /***** Type your HBAction code above this line ******/
    }

    //<editor-fold defaultstate="collapsed" desc="Debug Start">

    /**
     * This function is used when running sketch in IntelliJ IDE for debugging or testing
     *
     * @param args standard args required
     */
    public static void main(String[] args) {

        try {
            runProgram();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //</editor-fold>
}


text:
"""
Pelix interactive shell

Provides a console interface for the Pelix shell, based on readline when
available.

:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.5.8
:status: Beta

..

    Copyright 2014 isandlaTech

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

# Module version
__version_info__ = (0, 5, 8)
__version__ = ".".join(str(x) for x in __version_info__)

# Documentation strings format
__docformat__ = "restructuredtext en"

# ------------------------------------------------------------------------------

# Shell constants
from pelix.constants import BundleActivator
from . import SERVICE_SHELL
from .beans import IOHandler, ShellSession
import pelix.framework as pelix

# Standard library
import logging
import sys
import threading

# ------------------------------------------------------------------------------

_logger = logging.getLogger(__name__)

# ------------------------------------------------------------------------------

try:
    # Set up readline if available
    import readline
    readline.parse_and_bind('tab: complete')
    readline.set_completer(None)
except ImportError:
    # Readline is missing, not critical
    readline = None

# Before Python 3, input() was raw_input()
if sys.version_info[0] < 3:
    safe_input = raw_input
else:
    safe_input = input

# ------------------------------------------------------------------------------

class InteractiveShell(object):
    """
    The interactive shell handler
    """
    def __init__(self, context):
        """
        Sets up the members

        :param context: The bundle context
        """
        self._context = context
        self._shell_ref = None
        self._shell = None

        # Read line cache
        self._readline_matches = []

        # Rendez-vous events
        self._lock = threading.RLock()
        self._stop_event = threading.Event()
        self._shell_event = threading.Event()

        # Try to find a shell service
        self.search_shell()

        # Register as a service listener
        self._context.add_service_listener(self, None, SERVICE_SHELL)

    def _readline_prompt(self):
        """
        Prompt using the readline module (no pre-flush)

        :return: The command line
        """
        sys.stdout.flush()
        return safe_input(self._shell.get_ps1())

    def _normal_prompt(self):
        """
        Flushes the prompt before requesting the input

        :return: The command line
        """
        sys.stdout.write(self._shell.get_ps1())
        sys.stdout.flush()
        return safe_input()

    def loop_input(self, on_quit=None):
        """
        Reads the standard input until the shell session is stopped

        :param on_quit: A call back method, called without argument when the
                        shell session has ended
        """
        # Set the session up
        session = ShellSession(IOHandler(sys.stdin, sys.stdout), {})

        try:
            first_prompt = True

            # Set up the prompt
            prompt = self._readline_prompt if readline is not None \
                else self._normal_prompt

            while not self._stop_event.is_set():
                # Wait for the shell to be there
                # Before Python 2.7, wait() doesn't return a result
                if self._shell_event.wait(.2) or self._shell_event.is_set():
                    # Shell present
                    if first_prompt:
                        # Show the banner on first prompt
                        sys.stdout.write(self._shell.get_banner())
                        first_prompt = False

                    # Read the next line
                    line = prompt()

                    with self._lock:
                        if self._shell_event.is_set():
                            # Execute it
                            self._shell.execute(line, session)

                        elif not self._stop_event.is_set():
                            # Shell service lost while not stopping
                            sys.stdout.write('Shell service lost.')
                            sys.stdout.flush()

        except (EOFError, KeyboardInterrupt, SystemExit):
            # Input closed or keyboard interruption
            pass

        self._stop_event.set()

        sys.stdout.write('Bye !\n')
        sys.stdout.flush()
        if on_quit is not None:
            # Call a handler if needed
            on_quit()

    def readline_completer(self, text, state):
        """
        A completer for the readline library
        """
        if state == 0:
            if '.' in text:
                # A name space is given
                namespace, prefix = text.split('.', 2)
                commands = self._shell.get_commands(namespace)

                # Filter methods according to the prefix
                self._readline_matches = ['{0}.{1}'.format(namespace, command)
                                          for command in commands
                                          if command.startswith(prefix)]

            else:
                # Complete with name space names or default commands
                prefix = text

                # Default commands goes first...
                possibilities = [command
                                 for command in self._shell.get_commands(None)
                                 if command.startswith(prefix)]

                # ... then name spaces
                namespaces = self._shell.get_namespaces()
                possibilities.extend('{0}.'.format(namespace)
                                     for namespace in namespaces
                                     if namespace.startswith(prefix))

                # ... then commands in those name spaces
                possibilities.extend(
                    '{0}.{1}'.format(namespace, command)
                    for namespace in namespaces if namespace is not None
                    for command in self._shell.get_commands(namespace)
                    if command.startswith(prefix))

                # Filter methods according to the prefix
                self._readline_matches = possibilities

            if not self._readline_matches:
                return None

            # Return the first possibility
            return self._readline_matches[0]

        elif state < len(self._readline_matches):
            # Next try
            return self._readline_matches[state]

    def search_shell(self):
        """
        Looks for a shell service
        """
        with self._lock:
            if self._shell is not None:
                # A shell is already there
                return

            reference = self._context.get_service_reference(SERVICE_SHELL)
            if reference is not None:
                self.set_shell(reference)

    def service_changed(self, event):
        """
        Called by Pelix when an events changes
        """
        kind = event.get_kind()
        reference = event.get_service_reference()

        if kind in (pelix.ServiceEvent.REGISTERED,
                    pelix.ServiceEvent.MODIFIED):
            # A service matches our filter
            self.set_shell(reference)

        else:
            with self._lock:
                # Service is not matching our filter anymore
                self.clear_shell()

                # Request for a new binding
                self.search_shell()

    def set_shell(self, svc_ref):
        """
        Binds the given shell service.

        :param svc_ref: A service reference
        """
        if svc_ref is None:
            return

        with self._lock:
            # Get the service
            self._shell_ref = svc_ref
            self._shell = self._context.get_service(self._shell_ref)

            # Set the readline completer
            if readline is not None:
                readline.set_completer(self.readline_completer)

            # Set the flag
            self._shell_event.set()

    def clear_shell(self):
        """
        Unbinds the active shell service
        """
        with self._lock:
            # Clear the flag
            self._shell_event.clear()

            # Clear the readline completer
            if readline is not None:
                readline.set_completer(None)
                del self._readline_matches[:]

            if self._shell_ref is not None:
                # Release the service
                self._context.unget_service(self._shell_ref)

            self._shell_ref = None
            self._shell = None

    def stop(self):
        """
        Clears all members
        """
        # Exit the loop
        with self._lock:
            self._stop_event.set()
            self._shell_event.clear()

        if self._context is not None:
            # Unregister from events
            self._context.remove_service_listener(self)

            # Release the shell
            self.clear_shell()
            self._context = None

# ------------------------------------------------------------------------------

@BundleActivator
class Activator(object):
    """
    The bundle activator
    """
    def __init__(self):
        """
        Sets up the members
        """
        self._context = None
        self._shell = None
        self._thread = None

    def start(self, context):
        """
        Bundle started
        """
        self._context = context
        self._shell = InteractiveShell(context)

        # Run the loop thread
        self._thread = threading.Thread(target=self._shell.loop_input,
                                        args=[self._quit],
                                        name="Pelix-Shell-TextConsole")
        # Set the thread as a daemon, to let it be killed by the interpreter
        # once all other threads stopped.
        self._thread.daemon = True
        self._thread.start()

    def stop(self, context):
        """
        Bundle stopped
        """
        self._cleanup()
        self._context = None

    def _quit(self):
        """
        Called when the shell session has ended
        """
        # Clean up members
        self._cleanup()

        # Stop the framework
        if self._context is not None:
            self._context.get_bundle(0).stop()

    def _cleanup(self):
        """
        Cleans up the members
        """
        if self._shell is not None:
            # Stop the shell
            self._shell.stop()

        self._thread = None
        self._shell = None

# ------------------------------------------------------------------------------

def main():
    """
    Entry point
    """
    # Use the utility method to create, run and delete the framework
    pelix.create_framework(('pelix.ipopo.core', 'pelix.shell.core',
                            'pelix.shell.console', 'pelix.shell.ipopo'),
                           None, True, True, True)

if __name__ == '__main__':
    # Prepare the logger
    if '-v' in sys.argv or '--verbose' in sys.argv:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.WARNING)

    # Run the entry point
    main()


text:
(function(module) {
  jashboard.plugin.build = _.extend(module, {
    JenkinsMonitorFormValidationRules: function(scope) {
      this.jenkinsBuildId = function() {
        if (scope.monitorConfigurationFormModel.build.type === "jenkins") {
          return jashboard.commonValidationRules.required(scope.monitorConfigurationFormModel.build.buildId);
        }
      };
    }
  });
}(jashboard.plugin.build || {}));


text:
package ru.ydn.wicket.wicketorientdb.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.wicket.request.Request;

import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.metadata.security.OSecurityRole;
import com.orientechnologies.orient.core.metadata.security.OSecurityUser;
import com.orientechnologies.orient.core.record.impl.ODocument;

import lombok.experimental.ExtensionMethod;
import lombok.experimental.UtilityClass;

/**
 * Lombok extention class to simplify work with source code.
 * Should be added as {@link ExtensionMethod}
 */
@UtilityClass
public final class LombokExtensions {

	/**
	 * Extract ODocument from {@link OSecurityUser}
	 * @param user object to extract from
	 * @return {@link ODocument}
	 */
	public ODocument getDocument(OSecurityUser user) {
		return user!=null?getDocument(user.getIdentity().getIdentity()):null;
	}

	/**
	 * Extract ODocument from {@link OSecurityRole}
	 * @param role object to extract from
	 * @return {@link ODocument}
	 */
	public ODocument getDocument(OSecurityRole role) {
		return role!=null?getDocument(role.getIdentity().getIdentity()):null;
	}

	public HttpServletRequest asHttpServletRequest(Request request) {
		if(request==null) return null;
		else return (HttpServletRequest) request.getContainerRequest();
	}

	private ODocument getDocument(OIdentifiable identifiable) {
		if(identifiable==null || identifiable instanceof ODocument) return (ODocument) identifiable;
		ODocument ret = identifiable.getRecord();
		if(ret == null) ret = DBClosure.sudoLoad(identifiable.getIdentity());
		return ret;
	}
}


text:
#!/usr/bin/env python
import npyscreen, curses, os
from tools import utils

class MyTestApp(npyscreen.NPSAppManaged):

    def onStart(self):
        # When Application starts, set up the Forms that will be used.
        # These two forms are persistent between each edit.
        self.addForm("MAIN",       MainForm, name="Calculus Toolbox v0.2", color="IMPORTANT",)
        self.addForm("Build Calculus",     BuildForm, name="Build Calculus", color="IMPORTANT",  )
        self.addForm("Debug Tools",     DebugForm, name="Debug Tools", color="WARNING",  )
        # This one will be re-created each time it is edited.
        #self.addFormClass("THIRD", MainForm, name="Screen 3", color="CRITICAL",)

    def change_form(self, name):
        # Switch forms.  NB. Do *not* call the .edit() method directly (which
        # would lead to a memory leak and ultimately a recursion error).
        # Instead, use the method .switchForm to change forms.
        self.switchForm(name)

        # By default the application keeps track of every form visited.
        # There's no harm in this, but we don't need it so:
        self.resetHistory()

class MainForm(npyscreen.ActionFormMinimal):
    def create(self):
        self.add(npyscreen.FixedText, value = "Select operation:")
        # self.add(MyButton, name = 'Build Calculus', relx = 2,rely= 5)
        self.add(MyButton, name = 'Debug Tools', relx = 2,rely= 5)

    def on_ok(self):
        # Exit the application if the OK button is pressed.
        self.parentApp.switchForm(None)

class MyButton(npyscreen.MiniButtonPress):
    def whenPressed(self):
        self.parent.parentApp.switchForm(self.name)

class BuildForm(npyscreen.ActionFormMinimal):
    def create(self):
        self.fn = self.add(npyscreen.TitleFilenameCombo, name = "Calculus file:",)
        self.fn.value = os.getcwd() + "/default.json"
        self.out = self.add(npyscreen.TitleFilenameCombo, name = "Output folder:",  select_dir=True,)

    def on_ok(self):
        # Exit the application if the OK button is pressed.
        self.parentApp.switchForm("MAIN")

    def change_forms(self, *args, **keywords):
        self.text.value = args

class DebugForm(npyscreen.ActionFormMinimal):
    def create(self):
        self.add(npyscreen.FixedText, value = "Test build on single file...")

        self.fn = self.add(npyscreen.TitleFilenameCombo, name = "Calc file:", rely=4)
        self.fn.value = os.getcwd() + "/default.json"
        self.out = self.add(npyscreen.TitleFilenameCombo, name = "Out folder:",  select_dir=True,)
        self.out.value = os.getcwd() + "/export/"
        self.input = self.add(npyscreen.TitleFilenameCombo, name = "Input file:",  )
        self.input.value = os.getcwd() + "/template/"

        self.build = self.add(npyscreen.ButtonPress, name = 'Build' ,rely= 8)
        self.build.whenPressed = self.doBuild

        self.reload = self.add(npyscreen.ButtonPress, name = 'Reload Builder' , rely=8, relx= 10)
        self.reload.whenPressed = self.doReload

        self.add(npyscreen.FixedText, value = "Test unbuild on single file..." , rely=10)

        self.out2 = self.add(npyscreen.TitleFilenameCombo, name = "Out folder:",  select_dir=True , rely=12)
        self.out2.value = os.getcwd() + "/clean/"
        self.input2 = self.add(npyscreen.TitleFilenameCombo, name = "Input file:",  )
        self.input2.value = os.getcwd() + "/export/"

        self.unbuild = self.add(npyscreen.ButtonPress, name = 'Un-Build' , rely= 15)
        self.unbuild.whenPressed = self.doUnbuild

    def on_ok(self):
        # Exit the application if the OK button is pressed.
        self.parentApp.switchForm("MAIN")

    def doReload(self, *args):
        from tools import isabuilder, scalabuilder
        try:
            isabuilder = reload(isabuilder)
            scalabuilder = reload(scalabuilder)
        except Exception, e:
            npyscreen.notify_confirm(str(e))

    def doBuild(self, *args):
        try:
            if os.path.isfile(self.input.value):
                out_path = self.input.value.split("/")[-1]
                file_type = self.input.value.split(".")[-1]
                from tools import isabuilder, scalabuilder

                if file_type == "thy":
                    isaBuild = isabuilder.IsabelleBuilder(self.fn.value)
                    if "_" in out_path: out_path = isaBuild.get("calc_name") + "_" + out_path.split("_")[-1]
                    else: out_path = isaBuild.get("calc_name") + "." + file_type
                    utils.writeFile(self.out.value+"/"+out_path, utils.processFile(utils.readFile(self.input.value), isaBuild, "(*", "*)"))
                elif file_type == "scala":
                    scalaBuild = scalabuilder.ScalaBuilder(self.fn.value)
                    scalaBuild.add("core_compiled", "")

                    utils.writeFile(self.out.value+"/"+out_path, utils.processFile(utils.readFile(self.input.value), scalaBuild, "/*", "*/"))
                else:
                    npyscreen.notify_confirm("Error input file not supported!")

            else:
                npyscreen.notify_confirm("Error no input file selected!")
        except Exception, e: # catch *all* exceptions
            npyscreen.notify_confirm(str(e))

    def doUnbuild(self, *args):
        if os.path.isfile(self.input2.value):
            out_path = self.input2.value.split("/")[-1]
            file_type = self.input2.value.split(".")[-1]
            if file_type == "thy":
                utils.writeFile( self.out2.value+"/"+out_path, utils.revert( utils.readFile(self.input2.value), "(*", "*)" ) )
            elif file_type == "scala":
                utils.writeFile( self.out2.value+"/"+out_path, utils.revert( utils.readFile(self.input2.value), "/*", "*/" ) )
            else:
                npyscreen.notify_confirm("Error input file not supported!")

        else:
            npyscreen.notify_confirm("Error no input file selected!")

def main():
    TA = MyTestApp()
    TA.run()

if __name__ == '__main__':
    main()


text:
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example - example-error-$rootScope-inprog-debug</title>

    <script src="../../../angular.js"></script>
    <script src="app.js"></script>

</head>
<body ng-app="app">
<button ng-click="focusInput = true">Focus</button>
<input ng-focus="count = count + 1" set-focus-if="focusInput"/>
</body>
</html>


text:
<?xml version="1.0" ?>
<tei type="technical-report">
	<teiHeader>
		<fileDesc xml:id="55115186"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>
	<note type="page">1<lb/></note>

	<docTitle>
	<titlePart>Database of electron inelastic mean free path for<lb/> elemental solids<lb/></titlePart>
	</docTitle>

1. Electron inelastic mean free path (IMFP)<lb/> 2. Calculation method of electron inelastic mean free path<lb/> 3. Figures for electron inelastic mean free paths for 41 elemental solids over 10 eV<lb/> to 30,000 eV<lb/> Fig1. Li, Be, glassy carbon, graphite, diamond, and Na.<lb/>

	<byline>
	<note type="other">Fig2. Mg ,Al, Si, K, Sc, and Ti.<lb/> Fig.3 V, Cr, Fe, Co, Ni, and Cu<lb/> Fig.4 Ge, Y, Nb, Mo, Ru, and Rh.<lb/>
	</note>
	</byline>

	<note type="other">Fig. 5 Pd, Ag, In, Sn, Cs, and Gd<lb/> Fig. 6 Tb, Dy, Hf, Ta, W, and Re.<lb/> Fig. 7 Os, Ir, Pt, Au, and Bi<lb/> 4. Numerical data of electron IMFPs for 41 elemental solids over 50 eV to 30,000<lb/> eV<lb/> 4.1 Table for IMFPs of Li, Be, graphite, diamond, glassy carbon, Na, Mg, Al, Si,<lb/> and K as a function of non-relativistic electron kinetic energy.<lb/> 4.2 Table for IMFPs of Sc, Ti, V, Cr, Fe, Co, Ni, Cu, Ge, and Y as a function of<lb/> electron kinetic energy.<lb/> 4.3 Table for IMFPs of Nb, Mo, Ru, Rh, Pd, Ag, In, Sn, Cs, and Gd as a function<lb/> of non-relativistic electron kinetic energy.<lb/> 4.4 Table for IMFPs of Tb, Dy, Hf, Ta, W, Re. Os. Ir, Pt, Au and Bi as a<lb/> function of non-relativistic electron kinetic energy.<lb/> 5. References</note>

		</front>
	</text>
</tei>


text:
// * ———————————————————————————————————————————————————————— * //
// * 	Global Data
// *	Loads global data - data to be used on all templates
// *	Good for shared resources - news, products...
// *	Loads .js files from /cms/global folder
// * ———————————————————————————————————————————————————————— * //
var global_data = function () {}

// Vendor dependencies
var Promise = require('bluebird')
var async = require('async')
var extend = require('extend')
var glob = require('multi-glob').glob

// Local dependencies
var logger = require(ENDURO_FOLDER + '/libs/logger')
var flat_helpers = require(ENDURO_FOLDER + '/libs/flat_db/flat_helpers')
var flat = require(ENDURO_FOLDER + '/libs/flat_db/flat')

global_data.prototype.get_global_data = function () {

	// Constants
	var data_path = [CMD_FOLDER + '/cms/global/**/*.js', CMD_FOLDER + '/cms/.settings.js']

	this.clear()

	return new Promise(function (resolve, reject) {

		// Fetches the files
		glob(data_path, function (err, files) {
			if (err) {
				logger.block(err, 'enduro_render_events')
				reject()
			}

			// Async goes through the files
			async.each(files, function (file, callback) {

				// Stores filename
				var filename = file.match(/([^\\/]+)\.([^\\/]+)$/)[1]

				// path relative to cms folder
				var fileInCms = file.match(/cms\/(.*)\.([^\\/]+)$/)[1]

				// Loads the file
				if (flat_helpers.file_exists_sync(file)) {
					flat.load(fileInCms)
						.then((data) => {
							// Extends global data with currently loaded data
							extend(true, __data.global, data)

							logger.twolog('global ' + filename, 'loaded', 'enduro_render_events')
							callback()
						}, () => {
							callback()
						})
				}

			}, () => {
				// After all global files are loaded
				logger.line('', 'enduro_render_events')
				resolve()
			})
		})
	})
}

// clears the global data
global_data.prototype.clear = function () {
	__data = {}
	__data.global = {}
}

module.exports = new global_data()