text:
#include "configargs.h"

#define GCCPLUGIN_VERSION_MAJOR   5
#define GCCPLUGIN_VERSION_MINOR   3
#define GCCPLUGIN_VERSION_PATCHLEVEL   0
#define GCCPLUGIN_VERSION  (GCCPLUGIN_VERSION_MAJOR*1000 + GCCPLUGIN_VERSION_MINOR)

static char basever[] = "5.3.0";
static char datestamp[] = "20151204";
static char devphase[] = "";
static char revision[] = "";

/* FIXME plugins: We should make the version information more precise.
   One way to do is to add a checksum. */

static struct plugin_gcc_version gcc_version = {basever, datestamp,
						devphase, revision,
						configuration_arguments};


text:
import useWebChatAPIContext from './internal/useWebChatAPIContext';

export default function useSetNotification() {
  return useWebChatAPIContext().setNotification;
}

redpajama_set_name: RedPajamaGithub


text:
module ApplicationHelper
  def logged_in?
    !!current_user
  end
end


text:
1. Run the Kubernetes Dashboard in minikube
2. Explore the dashboard and look for the features it supports
3. Create a deployment from the dashboard

### Run the Kubernetes Dashboard in minikube
The Kubernetes Dashboard is a simple, web user interface for Kubernetes clusters. It allows users to manage applications running in the cluster and troubleshoot them, as well as manage the cluster itself.

One of the common asks in the container world is for the need for a ui to visualize what is going on with clusters. It was one of the most requested features of Docker when it first started, and companies like StackEngine, the one I worked at, or Rancher, were the way devops engineers would use to manage clusters.

Kubernetes learned from this lesson early on, and created the Kubernetes Dashboard for this purpose, and it allows you to monitor and view clusters from an operational perspective.

We will also enable heapster, to see cluster memory and CPU usage. This is enabled on minikube with `minikube addons enable heapster`

The dashboard comes pre enabled as an addon. To start up the dashboard type `minikube dashboard` in your command prompt.

This will bring up the dashboard in your browser.

### 2. Explore the dashboard and look for the features it supports
Explore the cluster sections, available namespaces.

Visit the deployments section, and drill down into a deployment, and notice how you can scale, edit or delete a deployment. Visit the replica set for the deployment to see all the pods associated with it.

Go into the pod section to see all the pods running. Notice how you can fetch pod logs from the ui directly, or exec into a pod if it has it available.

### 3. Create a deployment from the dashboard
Create a helloworld deployment with the UI; specify an app name, and container image karthequian/helloworld:latest with 2 pods. See the deployment and pods running in the UI.

#### Handout Links

[Dashboard - Full Featured Web Interface for Kubernetes] http://blog.kubernetes.io/2016/07/dashboard-web-interface-for-kubernetes.html


text:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Salient.ReliableHttpClient.Serialization.Newtonsoft
{
    /// <summary>
    ///   Useful when serializing/deserializing json for use with the Stack Overflow API, which produces and consumes Unix Timestamp dates
    /// </summary>
    /// <remarks>
    ///   swiped from lfoust and fixed for latest json.net with some tweaks for handling out-of-range dates
    /// </remarks>
    public class UnixDateTimeConverter : DateTimeConverterBase
    {
        //public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
        //{
        //    if (reader.TokenType != JsonToken.Integer)
        //        throw new Exception("Wrong Token Type");

        //    long ticks = (long)reader.Value;
        //    return ticks.FromUnixTime();
        //}

        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param><param name="value">The value.</param><param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            long val;
            if (value is DateTime)
            {
                val = ((DateTime)value).ToUnixTime();
            }
            else
            {
                throw new Exception("Expected date object value.");
            }
            writer.WriteValue(val);
        }

        /// <summary>
        ///   Reads the JSON representation of the object.
        /// </summary>
        /// <param name = "reader">The <see cref = "JsonReader" /> to read from.</param>
        /// <param name = "objectType">Type of the object.</param>
        /// <param name = "existingValue">The existing value of object being read.</param>
        /// <param name = "serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.Integer)
                throw new Exception("Wrong Token Type");

            long ticks = (long)reader.Value;
            return UnixDateTimeHelper.FromUnixTime(ticks);
        }
    }

    /// <summary>
    ///   Useful when serializing/deserializing json for use with the Stack Overflow API, which produces and consumes Unix Timestamp dates
    /// </summary>
    /// <remarks>
    ///   swiped from lfoust and fixed for latest json.net with some tweaks for handling out-of-range dates
    /// </remarks>
    public class UnixDateTimeOffsetConverter : DateTimeConverterBase
    {
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param><param name="value">The value.</param><param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            long val;
            // TODO: perhaps a bit of leniency is in order here. Can convert a date to datetime offset
            if (value is DateTimeOffset)
            {
                val = ((DateTimeOffset)value).ToUnixTime();
            }
            else
            {
                throw new Exception("Expected date object value.");
            }
            writer.WriteValue(val);
        }

        /// <summary>
        ///   Reads the JSON representation of the object.
        /// </summary>
        /// <param name = "reader">The <see cref = "JsonReader" /> to read from.</param>
        /// <param name = "objectType">Type of the object.</param>
        /// <param name = "existingValue">The existing value of object being read.</param>
        /// <param name = "serializer">The calling serializer.</param>
        /// <exception cref="Exception"></exception>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.Integer)
            {
                throw new Exception("Wrong Token Type");
            }

            var ticks = (long)reader.Value;

            return UnixDateTimeOffsetHelper.FromUnixTime(ticks);
        }
    }

}


text:
package influxql

import (
	"flag"
	"os"
	"testing"

	u "github.com/araddon/gou"
	"github.com/araddon/qlbridge/lex"
	"github.com/stretchr/testify/assert"
)

var (
	VerboseTests *bool = flag.Bool("vv", false, "Verbose Logging?")
)

func TestMain(m *testing.M) {
	flag.Parse()
	if *VerboseTests {
		u.SetupLogging("debug")
		u.SetColorOutput()
	}
	// Now run the actual Tests
	os.Exit(m.Run())
}

func tv(t lex.TokenType, v string) lex.Token {
	return lex.Token{T: t, V: v}
}

func verifyTokens(t *testing.T, sql string, tokens []lex.Token) {
	l := lex.NewLexer(sql, InfluxQlDialect)
	for _, goodToken := range tokens {
		tok := l.NextToken()
		u.Debugf("%#v  %#v", tok, goodToken)
		assert.Equal(t, tok.V, goodToken.V, "has='%v' want='%v'", tok.V, goodToken.V)
		assert.Equal(t, tok.T, goodToken.T, "has='%v' want='%v'", tok.V, goodToken.V)
	}
}

func TestLexSimple(t *testing.T) {
	verifyTokens(t, `select * from "series with special characters!"`,
		[]lex.Token{
			tv(lex.TokenSelect, "select"),
			tv(lex.TokenStar, "*"),
			tv(lex.TokenFrom, "from"),
			tv(lex.TokenValue, "series with special characters!"),
		})
	verifyTokens(t, `select * from /.*/ limit 1"`,
		[]lex.Token{
			tv(lex.TokenSelect, "select"),
			tv(lex.TokenStar, "*"),
			tv(lex.TokenFrom, "from"),
			tv(lex.TokenRegex, "/.*/"),
			tv(lex.TokenLimit, "limit"),
			tv(lex.TokenInteger, "1"),
		})
	verifyTokens(t, `select * from /^stats\./i where time > now() - 1h;`,
		[]lex.Token{
			tv(lex.TokenSelect, "select"),
			tv(lex.TokenStar, "*"),
			tv(lex.TokenFrom, "from"),
			tv(lex.TokenRegex, "/^stats\\./i"),
			tv(lex.TokenWhere, "where"),
			tv(lex.TokenIdentity, "time"),
			tv(lex.TokenGT, ">"),
			tv(lex.TokenUdfExpr, "now"),
			tv(lex.TokenLeftParenthesis, "("),
			tv(lex.TokenRightParenthesis, ")"),
			tv(lex.TokenMinus, "-"),
		})
}

func TestLexContinuous(t *testing.T) {
	verifyTokens(t, `select percentile(value,95) from response_times group by time(5m)
						into response_times.percentiles.5m.95`,
		[]lex.Token{
			tv(lex.TokenSelect, "select"),
			tv(lex.TokenUdfExpr, "percentile"),
			tv(lex.TokenLeftParenthesis, "("),
			tv(lex.TokenIdentity, "value"),
			tv(lex.TokenComma, ","),
			tv(lex.TokenInteger, "95"),
			tv(lex.TokenRightParenthesis, ")"),
			tv(lex.TokenFrom, "from"),
			tv(lex.TokenIdentity, "response_times"),
			tv(lex.TokenGroupBy, "group by"),
			tv(lex.TokenUdfExpr, "time"),
			tv(lex.TokenLeftParenthesis, "("),
			tv(lex.TokenDuration, "5m"),
		})
}


text:
require 'spec_helper'
require 'sqs_worker/fetcher'

module SqsWorker
  describe Fetcher do

    subject(:fetcher) { described_class.new(queue_name: queue_name, manager: manager, batch_size: batch_size) }

    let(:batch_size) { 5 }
    let(:queue_name) { 'queue_name' }
    let(:manager) { double(Manager, fetch_done: nil)}
    let(:sqs) { double(Sqs, find_queue: queue) }
    let(:queue) { double('queue') }
    let(:messages) { ['message'] }

    before do
      expect(Sqs).to receive(:instance).and_return(sqs)
      expect(sqs).to receive(:find_queue).and_return(queue)
    end

    describe 'normal operation' do

      before do
        expect(queue).to receive(:receive_messages).with({ max_number_of_messages: batch_size, attribute_names: ['ApproximateReceiveCount'] }).and_return(messages)
        fetcher.fetch
      end

      it 'fetches messages from the queue and passes to manager' do
        expect(manager).to have_received(:fetch_done).with(messages)
      end

      it 'logs the successful fetching of messages' do
        expect(logger).to have_received(:debug).with(event_name: 'sqs_worker_fetched_messages', queue_name: queue_name, size: messages.size)
      end

      context 'when there is a single message returned (ie batch size is 1)' do
        let(:messages) { 'message' }

        it 'fetches messages from the queue and passes to manager, as an array' do
          expect(manager).to have_received(:fetch_done).with([messages])
        end

        it 'logs the successful fetching of messages' do
          expect(logger).to have_received(:debug).with(event_name: 'sqs_worker_fetched_messages', queue_name: queue_name, size: 1)
        end
      end
    end

    describe 'when there are errors in the client' do

      let(:exception) { 'errors ahoy!' }

      before do
        expect(queue).to receive(:receive_messages).with(anything).and_raise(exception)
        fetcher.fetch
      end

      it 'messages the manager with empty messages' do
        expect(manager).to have_received(:fetch_done).with([])
      end

      it 'logs the error' do
        expect(logger).to have_received(:error).with(error: an_instance_of(RuntimeError))
      end
    end
  end
end


text:
download_page=`wget "http://www.sublimetext.com/3" -O - `
download_subl_to="$HOME/Downloads/sublime-text.deb"
download_url=$(echo $download_page | sed -nr 's;.*Ubuntu 32 bit.*;\1;p')
echo "Downloading Sublime Text 3 from '$download_url' to '\$HOME/Downloads/'..."
wget "$download_url" -O "$download_subl_to"
sudo dpkg -i "$download_subl_to"

# Download Package Control
mkdir -p "$HOME/.config/sublime-text-3/Installed Packages"
wget "https://sublime.wbond.net/Package%20Control.sublime-package" -O "$HOME/.config/sublime-text-3/Installed Packages/Package Control.sublime-package"

# Write up packages to be installed
#  - http://stackoverflow.com/questions/19529999/add-package-control-in-sublime-text-3-through-the-command-line
mkdir -p "$HOME/.config/sublime-text-3/Packages/User"
cat > "$HOME/.config/sublime-text-3/Packages/User/Package Control.sublime-settings" << EOF
{
        "bootstrapped": true,
        "in_process_packages":
        [
        ],
        "installed_packages":
        [
                "EditorConfig",
                "Markdown Extended",
                "Monokai Extended",
                "MoveTab"
        ]
}
EOF

# Download Portuguese Dictionaries
# Read:
#  - https://packagecontrol.io/packages/Dictionaries
#  - http://www.sublimetext.com/docs/3/spell_checking.html
dict_path="$HOME/.config/sublime-text-3/Packages/User/Portuguese (Brazilian)"
mkdir -p "$dict_path"
wget "https://raw.githubusercontent.com/titoBouzout/Dictionaries/master/Portuguese%20(Brazilian).aff" -O "$dict_path/Portuguese (Brazilian).aff"
wget "https://raw.githubusercontent.com/titoBouzout/Dictionaries/master/Portuguese%20(Brazilian).dic" -O "$dict_path/Portuguese (Brazilian).dic"
wget "https://raw.githubusercontent.com/titoBouzout/Dictionaries/master/Portuguese%20(Brazilian).txt" -O "$dict_path/Portuguese (Brazilian).txt"

# NOTE: All packages should install normally when sublime restarts.


text:
class Qlimagesize < Cask
  url 'http://repo.whine.fr/qlImageSize.qlgenerator-10.8.zip'
  homepage 'https://github.com/Nyx0uf/qlImageSize'
  version 'latest'
  sha256 :no_check
  qlplugin 'qlImageSize.qlgenerator'
end


text: export { TextLineSpacing24 as default } from "../../";


text:
---
layout: page
title: "Tutorial"
description: "Tutorial is valid for Spark 1.3 and higher"
group: quickstart
---

## Zeppelin Tutorial

This tutorial walks you through some of the fundamental Zeppelin concepts. We will assume you have already installed Zeppelin. If not, please see [here](../install/install.html) first.

Current main backend processing engine of Zeppelin is [Apache Spark](https://spark.apache.org). If you're new to this system, you might want to start by getting an idea of how it processes data to get the most out of Zeppelin.

## Tutorial with Local File

### 1. Data Refine

Before you start Zeppelin tutorial, you will need to download [bank.zip](http://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank.zip).

First, to transform csv format data into RDD of `Bank` objects, run following script. This will also remove header using `filter` function.

```scala

val bankText = sc.textFile("yourPath/bank/bank-full.csv")

case class Bank(age:Integer, job:String, marital : String, education : String, balance : Integer)

// split each line, filter out header (starts with "age"), and map it into Bank case class
val bank = bankText.map(s=>s.split(";")).filter(s=>s(0)!="\"age\"").map(
    s=>Bank(s(0).toInt,
            s(1).replaceAll("\"", ""),
            s(2).replaceAll("\"", ""),
            s(3).replaceAll("\"", ""),
            s(5).replaceAll("\"", "").toInt
        )
)

// convert to DataFrame and create temporal table
bank.toDF().registerTempTable("bank")
```

### 2. Data Retrieval

Suppose we want to see age distribution from `bank`. To do this, run:

```sql
%sql select age, count(1) from bank where age < 30 group by age order by age
```

You can make input box for setting age condition by replacing `30` with `${maxAge=30}`.

```sql
%sql select age, count(1) from bank where age < ${maxAge=30} group by age order by age
```

Now we want to see age distribution with certain marital status and add combo box to select marital status. Run:

```sql
%sql select age, count(1) from bank where marital="${marital=single,single|divorced|married}" group by age order by age
```

## Tutorial with Streaming Data

### 1. Data Refine

Since this tutorial is based on Twitter's sample tweet stream, you must configure authentication with a Twitter account. To do this, take a look at [Twitter Credential Setup](https://databricks-training.s3.amazonaws.com/realtime-processing-with-spark-streaming.html#twitter-credential-setup). After you get API keys, you should fill out credential related values(`apiKey`, `apiSecret`, `accessToken`, `accessTokenSecret`) with your API keys on following script.

This will create a RDD of `Tweet` objects and register these stream data as a table:

```scala
import org.apache.spark.streaming._
import org.apache.spark.streaming.twitter._
import org.apache.spark.storage.StorageLevel
import scala.io.Source
import scala.collection.mutable.HashMap
import java.io.File
import org.apache.log4j.Logger
import org.apache.log4j.Level
import sys.process.stringSeqToProcess

/** Configures the Oauth Credentials for accessing Twitter */
def configureTwitterCredentials(apiKey: String, apiSecret: String, accessToken: String, accessTokenSecret: String) {
  val configs = new HashMap[String, String] ++= Seq(
    "apiKey" -> apiKey, "apiSecret" -> apiSecret, "accessToken" -> accessToken, "accessTokenSecret" -> accessTokenSecret)
  println("Configuring Twitter OAuth")
  configs.foreach{ case(key, value) =>
    if (value.trim.isEmpty) {
      throw new Exception("Error setting authentication - value for " + key + " not set")
    }
    val fullKey = "twitter4j.oauth." + key.replace("api", "consumer")
    System.setProperty(fullKey, value.trim)
    println("\tProperty " + fullKey + " set as [" + value.trim + "]")
  }
  println()
}

// Configure Twitter credentials
val apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxx"
val apiSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
val accessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
val accessTokenSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
configureTwitterCredentials(apiKey, apiSecret, accessToken, accessTokenSecret)

import org.apache.spark.streaming.twitter._
val ssc = new StreamingContext(sc, Seconds(2))
val tweets = TwitterUtils.createStream(ssc, None)
val twt = tweets.window(Seconds(60))

case class Tweet(createdAt:Long, text:String)
twt.map(status=>
  Tweet(status.getCreatedAt().getTime()/1000, status.getText())
).foreachRDD(rdd=>
  // Below line works only in spark 1.3.0.
  // For spark 1.1.x and spark 1.2.x,
  // use rdd.registerTempTable("tweets") instead.
  rdd.toDF().registerAsTable("tweets")
)

twt.print

ssc.start()
```

### 2. Data Retrieval

For each following script, every time you click run button you will see different result since it is based on real-time data.

Let's begin by extracting maximum 10 tweets which contain the word **girl**.

```sql
%sql select * from tweets where text like '%girl%' limit 10
```

This time suppose we want to see how many tweets have been created per sec during last 60 sec. To do this, run:

```sql
%sql select createdAt, count(1) from tweets group by createdAt order by createdAt
```

You can make user-defined function and use it in Spark SQL. Let's try it by making function named `sentiment`. This function will return one of the three attitudes( positive, negative, neutral ) towards the parameter.

```scala
def sentiment(s:String) : String = {
    val positive = Array("like", "love", "good", "great", "happy", "cool", "the", "one", "that")
    val negative = Array("hate", "bad", "stupid", "is")

    var st = 0;

    val words = s.split(" ")
    positive.foreach(p =>
        words.foreach(w =>
            if(p==w) st = st+1
        )
    )

    negative.foreach(p=>
        words.foreach(w=>
            if(p==w) st = st-1
        )
    )
    if(st>0)
        "positivie"
    else if(st<0)
        "negative"
    else
        "neutral"
}

// Below line works only in spark 1.3.0.
// For spark 1.1.x and spark 1.2.x,
// use sqlc.registerFunction("sentiment", sentiment _) instead.
sqlc.udf.register("sentiment", sentiment _)

```

To check how people think about girls using `sentiment` function we've made above, run this:

```sql
%sql select sentiment(text), count(1) from tweets where text like '%girl%' group by sentiment(text)
```


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/html/Album/vendor/zendframework/zendframework/library/Zend/Validator/ValidatorChain.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/var/www/html/Album /

vendor /

zendframework /

zendframework /

library /

Zend /

Validator /

ValidatorChain.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

50.00%

8 / 16

      CRAP

68.75%

33 / 48

      ValidatorChain

0.00%

0 / 1

50.00%

8 / 16

      34.46

68.75%

33 / 48

       count()

0.00%

0 / 1

      2

0.00%

0 / 1

       getPluginManager()

100.00%

1 / 1

      2

100.00%

4 / 4

       setPluginManager(ValidatorPluginManager $plugins)

100.00%

1 / 1

      1

100.00%

2 / 2

       plugin($name, array $options = null)

100.00%

1 / 1

      1

100.00%

2 / 2

       attach(ValidatorInterface $validator, $breakChainOnFailure = false)

100.00%

1 / 1

      1

100.00%

4 / 4

       addValidator(ValidatorInterface $validator, $breakChainOnFailure = false)

0.00%

0 / 1

      2

0.00%

0 / 1

       prependValidator(ValidatorInterface $validator, $breakChainOnFailure = false)

100.00%

1 / 1

      1

100.00%

6 / 6

       attachByName($name, $options = array()

100.00%

1 / 1

      1

100.00%

3 / 3

       addByName($name, $options = array()

0.00%

0 / 1

      2

0.00%

0 / 1

       prependByName($name, $options = array()

100.00%

1 / 1

      1

100.00%

3 / 3

       isValid($value, $context = null)

0.00%

0 / 1

      4.91

61.54%

8 / 13

       merge(ValidatorChain $validatorChain)

0.00%

0 / 1

      6

0.00%

0 / 4

       getMessages()

0.00%

0 / 1

      2

0.00%

0 / 1

       getValidators()

100.00%

1 / 1

      1

100.00%

1 / 1

       __invoke($value)

0.00%

0 / 1

      2

0.00%

0 / 1

       __sleep()

0.00%

0 / 1

      2

0.00%

0 / 1

1
	<?php

2

9

10
	namespace Zend\Validator;

11

12
	use Countable;

13

14
	class ValidatorChain implements

15
	    Countable,

16
	    ValidatorInterface

17
	{

18
	    /**

19
	     * @var ValidatorPluginManager

20
	     */

21
	    protected $plugins;

22

23
	    /**

24
	     * Validator chain

25
	     *

26
	     * @var array

27
	     */

28
	    protected $validators = array();

29

30
	    /**

31
	     * Array of validation failure messages

32
	     *

33
	     * @var array

34
	     */

35
	    protected $messages = array();

36

37
	    /**

38
	     * Return the count of attached validators

39
	     *

40
	     * @return int

41
	     */

42
	    public function count()

43
	    {

44
	        return count($this->validators);

45
	    }

46

47
	    /**

48
	     * Get plugin manager instance

49
	     *

50
	     * @return ValidatorPluginManager

51
	     */

52
	    public function getPluginManager()

53
	    {

54
	        if (!$this->plugins) {

55
	            $this->setPluginManager(new ValidatorPluginManager());

56
	        }

57
	        return $this->plugins;

58
	    }

59

60
	    /**

61
	     * Set plugin manager instance

62
	     *

63
	     * @param  ValidatorPluginManager $plugins Plugin manager

64
	     * @return ValidatorChain

65
	     */

66
	    public function setPluginManager(ValidatorPluginManager $plugins)

67
	    {

68
	        $this->plugins = $plugins;

69
	        return $this;

70
	    }

71

72
	    /**

73
	     * Retrieve a validator by name

74
	     *

75
	     * @param  string     $name    Name of validator to return

76
	     * @param  null|array $options Options to pass to validator constructor (if not already instantiated)

77
	     * @return ValidatorInterface

78
	     */

79
	    public function plugin($name, array $options = null)

80
	    {

81
	        $plugins = $this->getPluginManager();

82
	        return $plugins->get($name, $options);

83
	    }

84

85
	    /**

86
	     * Attach a validator to the end of the chain

87
	     *

88
	     * If $breakChainOnFailure is true, then if the validator fails, the next validator in the chain,

89
	     * if one exists, will not be executed.

90
	     *

91
	     * @param  ValidatorInterface      $validator

92
	     * @param  bool                 $breakChainOnFailure

93
	     * @return ValidatorChain Provides a fluent interface

94
	     */

95
	    public function attach(ValidatorInterface $validator, $breakChainOnFailure = false)

96
	    {

97
	        $this->validators[] = array(

98
	            'instance'            => $validator,

99
	            'breakChainOnFailure' => (bool) $breakChainOnFailure,

100
	        );

101
	        return $this;

102
	    }

103

104
	    /**

105
	     * Proxy to attach() to keep BC

106
	     *

107
	     * @deprecated Please use attach()

108
	     * @param  ValidatorInterface      $validator

109
	     * @param  bool                 $breakChainOnFailure

110
	     * @return ValidatorChain Provides a fluent interface

111
	     */

112
	    public function addValidator(ValidatorInterface $validator, $breakChainOnFailure = false)

113
	    {

114
	        return $this->attach($validator, $breakChainOnFailure);

115
	    }

116

117
	    /**

118
	     * Adds a validator to the beginning of the chain

119
	     *

120
	     * If $breakChainOnFailure is true, then if the validator fails, the next validator in the chain,

121
	     * if one exists, will not be executed.

122
	     *

123
	     * @param  ValidatorInterface      $validator

124
	     * @param  bool                 $breakChainOnFailure

125
	     * @return ValidatorChain Provides a fluent interface

126
	     */

127
	    public function prependValidator(ValidatorInterface $validator, $breakChainOnFailure = false)

128
	    {

129
	        array_unshift(

130
	            $this->validators,

131
	            array(

132
	               'instance'            => $validator,

133
	               'breakChainOnFailure' => (bool) $breakChainOnFailure,

134
	            )

135
	        );

136
	        return $this;

137
	    }

138

139
	    /**

140
	     * Use the plugin manager to add a validator by name

141
	     *

142
	     * @param  string $name

143
	     * @param  array  $options

144
	     * @param  bool   $breakChainOnFailure

145
	     * @return ValidatorChain

146
	     */

147
	    public function attachByName($name, $options = array(), $breakChainOnFailure = false)

148
	    {

149
	        $validator = $this->plugin($name, $options);

150
	        $this->attach($validator, $breakChainOnFailure);

151
	        return $this;

152
	    }

153

154
	    /**

155
	     * Proxy to attachByName() to keep BC

156
	     *

157
	     * @deprecated Please use attachByName()

158
	     * @param  string $name

159
	     * @param  array  $options

160
	     * @param  bool   $breakChainOnFailure

161
	     * @return ValidatorChain

162
	     */

163
	    public function addByName($name, $options = array(), $breakChainOnFailure = false)

164
	    {

165
	        return $this->attachByName($name, $options, $breakChainOnFailure);

166
	    }

167

168
	    /**

169
	     * Use the plugin manager to prepend a validator by name

170
	     *

171
	     * @param  string $name

172
	     * @param  array  $options

173
	     * @param  bool   $breakChainOnFailure

174
	     * @return ValidatorChain

175
	     */

176
	    public function prependByName($name, $options = array(), $breakChainOnFailure = false)

177
	    {

178
	        $validator = $this->plugin($name, $options);

179
	        $this->prependValidator($validator, $breakChainOnFailure);

180
	        return $this;

181
	    }

182

183
	    /**

184
	     * Returns true if and only if $value passes all validations in the chain

185
	     *

186
	     * Validators are run in the order in which they were added to the chain (FIFO).

187
	     *

188
	     * @param  mixed $value

189
	     * @param  mixed $context Extra "context" to provide the validator

190
	     * @return bool

191
	     */

192
	    public function isValid($value, $context = null)

193
	    {

194
	        $this->messages = array();

195
	        $result         = true;

196
	        foreach ($this->validators as $element) {

197
	            $validator = $element['instance'];

198
	            if ($validator->isValid($value, $context)) {

199
	                continue;

200
	            }

201
	            $result         = false;

202
	            $messages       = $validator->getMessages();

203
	            $this->messages = array_replace_recursive($this->messages, $messages);

204
	            if ($element['breakChainOnFailure']) {

205
	                break;

206
	            }

207
	        }

208
	        return $result;

209
	    }

210

211
	    /**

212
	     * Merge the validator chain with the one given in parameter

213
	     *

214
	     * @param ValidatorChain $validatorChain

215
	     * @return ValidatorChain

216
	     */

217
	    public function merge(ValidatorChain $validatorChain)

218
	    {

219
	        foreach ($validatorChain->validators as $validator) {

220
	            $this->validators[] = $validator;

221
	        }

222

223
	        return $this;

224
	    }

225

226
	    /**

227
	     * Returns array of validation failure messages

228
	     *

229
	     * @return array

230
	     */

231
	    public function getMessages()

232
	    {

233
	        return $this->messages;

234
	    }

235

236
	    /**

237
	     * Get all the validators

238
	     *

239
	     * @return array

240
	     */

241
	    public function getValidators()

242
	    {

243
	        return $this->validators;

244
	    }

245

246
	    /**

247
	     * Invoke chain as command

248
	     *

249
	     * @param  mixed $value

250
	     * @return bool

251
	     */

252
	    public function __invoke($value)

253
	    {

254
	        return $this->isValid($value);

255
	    }

256

257
	    /**

258
	     * Prepare validator chain for serialization

259
	     *

260
	     * Plugin manager (property 'plugins') cannot

261
	     * be serialized. On wakeup the property remains unset

262
	     * and next invokation to getPluginManager() sets

263
	     * the default plugin manager instance (ValidatorPluginManager).

264
	     *

265
	     * @return array

266
	     */

267
	    public function __sleep()

268
	    {

269
	        return array('validators', 'messages');

270
	    }

271
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.13 using PHP 5.6.0-1+deb.sury.org~trusty+1 and PHPUnit 3.7.28 at Tue Oct 7 22:36:47 AMT 2014.


text:
<?php
/**
 * Configuration file
 */

define( 'BOOTSTRAP_VERSION', '4.0.0-alpha.6' );  // Bootstrap Version - @see http://v4-alpha.getbootstrap.com/
define( 'JQUERY_VERSION', '3.2.1' );  // JQuery Version - @see http://jquery.com
define( 'POPPER_VERSION', '1.9.9' );  // Popper Version - @see http://popper.js.org
define( 'EASING_VERSION', '1.3' );  // Easing Version - @see http://gsgd.co.uk/sandbox/jquery/easing
define( 'FONTAWESOME_VERSION', '4.7.0' );  // Fontawesome version - @see http://fontawesome.io
define( 'BOOTSTRAP_PR_VERSION', '0.0.1' );

define( 'AVATAR_CLASS', 'rounded-circle' );

define( 'POST_THUMBNAIL_X', 96 );
define( 'POST_THUMBNAIL_Y', 96 );
define( 'POST_THUMBNAIL_CLASS', 'img-thumbnail' );

define( 'FEATURED_IMAGE_X', 1156 );
define( 'FEATURED_IMAGE_Y', 289 );
define( 'FEATURED_IMAGE_CLASS', 'rounded' );

define( 'USE_WP45_LOGO', function_exists('get_custom_logo') );

define( 'USE_ONEPAGE', true );
define( 'USE_WOOCOMMERCE', file_exists(trailingslashit(dirname(__FILE__)).'woocommerce/wc-functions.php') );


text:
Copy the questions below into a file `part-4/quiz.md`. Then, write your answer to each question directly below it.

The quiz is worth __50 points__ in total.

_Reminder: you can use the internet to help you answer these questions :)_

- When you run a command in the terminal, where does BASH look for that command?

  * Bash looks for the command in the /bin directory ---
```bash
/
ls
bin
ls
```

- On a UNIX computer, how do you stop a running process?

  * `control + c`

- What packages do you have installed via homebrew?

  ```bash
brew list
dash            openssl         readline
git             openssl@1.1     tree
hub             postgresql      wget
```

- On a UNIX computer, how do you find the process id of a running process?

  * The easiest way to find out if process is running is run `ps aux` command and grep process name. If you got output along with process name/pid, your process is running.
  * `a` = show processes for all users
`u` = display the process's user/owner
`x` = also show processes not attached to a terminal
  * or use the command `ps`

- In a terminal, what does control-c do?

  * Interrupt/Kill whatever you are running

- What would be the result of typing the following commands?
```sh
$ cd /Users/steve
$ mkdir foo
$ touch bar
$ cd foo
$ touch bar
$ pwd
```

  * The result would be `cd: no such file or directory: /Users/steve`
  * However if I change it to `$ cd /Users/latoyawilliams` the following happens --
  1. The directory changes to `latoyawilliams`
  2. We make a new directory (folder) within `latoyawilliams` directory called `foo`
  3. We create a new file within the same directory of `foo` called `bar`
  4. We change directories to `foo`
  5. We create a new file called `bar` within the `foo` directory
  6. We print our working directory and see -- `/users/latoyawilliams/foo`

- How do you set an environment variable in your shell?

  * We can set environmental variables in a single step like this: `export NEW_VAR="Testing export"`

- What keyboard shortcut do you use to split the screen in your editor?

  * Open the command palette with cmd + shift + p (OSX) or ctrl + shift + p (Linux/Windows) and type "split". You'll see options for Up, Down, Left, and Right split.

- How do you create an alias in your shell?

  1. Open your .bashrc -- `$ vim ~/.bashrc`
  2. Go to the end of the file -- In vim, you can accomplish this just by hitting "G" (please note that it is capital).
  3. Add to the alias -- `alias aliasname='commands'`
  4. Write and close the file -- `:wq`
  5. Install the .bashrc -- `$ source ~/.bashrc` or wait for it to update once you restart your system.

- When a terminal command completes, how can you tell if it was successful or not?

  * After the command completes, type the command, `echo $?` -- any number other than 0 is unsuccessful

- What does your `~/.gitconfig` have in it? (paste the whole file here)

  * `ls -a` -- home directory to see that the .gitconfig file is there
  * `atom . .gitconfig` -- opens file in editor
  * `This is Git's per-user configuration file.
[user]
Please adapt and uncomment the following lines:
name = LaToya Williams
email = platinumtoii@yahoo.com
[core]
	excludesfile = /Users/latoyawilliams/.gitignore_global`

- What is the difference between a relative and absolute path?

  * A relative path is a way to specify the location of a directory relative to another directory.
  * An absolute or full path points to the same location in a file system, regardless of the current working directory. To do that, it must include the root directory.
  * By contrast, a relative path starts from some given working directory, avoiding the need to provide the full absolute path.

- Lets say you have the following file structure

  ```
  ~
  └── Projects
      ├── pinterest-for-dogs
      │   └── package.json
      └── linkedin-for-dancers
          ├── README.md
          └── package.json
  ```

  And you were in the `linkedin-for-dancers` folder. What command would you use to copy the `README.md` file to the `pinterest-for-dogs` folder?

 * ```bash
cp linkedin-for-dancers/README.md pinterest-for-dogs
 ```

- What keyboard shortcut do you use, in your editor, to go to a file in the project you have open?

  * command + o

- What files or folders do you want all git repositories to ignore?

  * .gitignore tells git which files (or patterns) it should ignore. It's usually used to avoid committing transient files from your working directory that aren't useful to other collaborators, such as compilation products, temporary files IDEs create, etc.
    * i.e. .DS_Store and node_modules folder

- What is the main difference between `Array.map` and `Array.forEach` in JavaScript?

  * Both the `forEach()` and `map()` method calls a provided function once for each element in an array, in order. Neither method executes the function for array elements without values. However, the `map()` method creates a new array with the results of calling a function for every array element and does not change the original array.


text:
 .. Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

Changelog
---------

1.4.0
.....

Features
~~~~~~~~

* ``S3Hook.load_file should accept Path object in addition to str (#15232)``
* ``Add Connection Documentation for Providers (#15499)``

Bug fixes
~~~~~~~~~

* ``Fix 'logging.exception' redundancy (#14823)``
* ``Fix AthenaSensor calling AthenaHook incorrectly (#15427)``
* ``Update Docstrings of Modules with Missing Params (#15391)``
* ``Add links to new modules for deprecated modules (#15316)``
* ``Fixes doc for SQSSensor (#15323)``

1.3.0
.....

Features
~~~~~~~~

* ``A bunch of template_fields_renderers additions (#15130)``
* ``Send region_name into parent class of AwsGlueJobHook (#14251)``
* ``Added retry to ECS Operator (#14263)``
* ``Make script_args templated in AwsGlueJobOperator (#14925)``
* ``Add FTPToS3Operator (#13707)``
* ``Implemented S3 Bucket Tagging (#14402)``
* ``S3DataSource is not required (#14220)``

Bug fixes
~~~~~~~~~

* ``AWS: Do not log info when SSM & SecretsManager secret not found (#15120)``
* ``Cache Hook when initializing 'CloudFormationCreateStackSensor' (#14638)``

1.2.0
.....

Features
~~~~~~~~

* ``Avoid using threads in S3 remote logging upload (#14414)``
* ``Allow AWS Operator RedshiftToS3Transfer To Run a Custom Query (#14177)``
* ``includes the STS token if STS credentials are used (#11227)``

1.1.0
.....

Features
~~~~~~~~

* ``Adding support to put extra arguments for Glue Job. (#14027)``
* ``Add aws ses email backend for use with EmailOperator. (#13986)``
* ``Add bucket_name to template fileds in S3 operators (#13973)``
* ``Add ExasolToS3Operator (#13847)``
* ``AWS Glue Crawler Integration (#13072)``
* ``Add acl_policy to S3CopyObjectOperator (#13773)``
* ``AllowDiskUse parameter and docs in MongotoS3Operator (#12033)``
* ``Add S3ToFTPOperator (#11747)``
* ``add xcom push for ECSOperator (#12096)``
* ``[AIRFLOW-3723] Add Gzip capability to mongo_to_S3 operator (#13187)``
* ``Add S3KeySizeSensor (#13049)``
* ``Add 'mongo_collection' to template_fields in MongoToS3Operator (#13361)``
* ``Allow Tags on AWS Batch Job Submission (#13396)``

Bug fixes
~~~~~~~~~

* ``Fix bug in GCSToS3Operator (#13718)``
* ``Fix S3KeysUnchangedSensor so that template_fields work (#13490)``

1.0.0
.....

Initial version of the provider.


text:
/**
 * @flow
 */

'use strict';

import StatusBar from 'StatusBar';
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Animated,
  Image,
  Text,
  Dimensions
} from 'react-native';

import { connect } from 'react-redux';
import Swiper from '../dependencies/swiper';

import Header from './header';
import Footer from './footer';
import Forecast from './forecast';
import Loading from './loading';

import type { WeatherModel } from '../models/view'

const SCREEN_WIDTH = Dimensions.get('window').width;

type Props = {
  dispatch: any;
  isLoading: bool;
  weather: Array<WeatherModel>;
  count: number;
  navigator: any;
};

type State = {
  shift: Animated.Value;
  current: number;
};

class Weather extends Component {
  props: Props;
  state: State;

  constructor(props: Props) {
    super(props);

    this.state = {
      shift: new Animated.Value(0),
      current: 0
    };

    (this: any).onScroll = this.onScroll.bind(this);
    (this: any).onSelectedIndexChange = this.onSelectedIndexChange.bind(this);
  }

  render() {
    if (this.props.isLoading === true) {
      return (
        <Loading />
      );
    }

    var forecastItems = this.props.weather.map((item, index) => {
      return (
        <Forecast key={`forecast-${index}`} forecast={item.forecast} />
      );
    });

    var swiper = (
      <Swiper
        showsPagination={false}
        loop={false}
        onScroll={this.onScroll}
        onSelectedIndexChange={this.onSelectedIndexChange}
        scrollEventThrottle={8}>
        { forecastItems }
      </Swiper>
    );

    return (
      <View style={styles.container}>
        <Header offset={this.state.shift} current={this.state.current}>
          { swiper }
        </Header>
        <Footer
          current={this.state.current}
          count={this.props.count}
          navigator={this.props.navigator} />
      </View>
    );
  }

  onSelectedIndexChange(index, offset) {
    this.setState({current: index});
  }

  onScroll(e) {
    this.state.shift.setValue(e.nativeEvent.contentOffset.x);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F9F9F9'
  }
});

function select(store: any, props: Props) {
  return {
    isLoading: store.weather.isLoading,
    weather: store.weather.data,
    count: store.weather.data.length,
    ...props
  };
}

module.exports = connect(select)(Weather);


text:
import React from 'react';
import renderer from 'react-test-renderer';

import Estonia from './Estonia';

it('renders correctly', () => {
  const tree = renderer.create(<Estonia />).toJSON();

  expect(tree).toMatchSnapshot();
});


text:
function doSomeStuff() {
  return "This script doesn't contain any update processor functions";
}


text:
FROM centos:7.9.2009

LABEL org.opencontainers.image.source="https://github.com/giovtorres/docker-centos7-slurm" \
      org.opencontainers.image.title="docker-centos7-slurm" \
      org.opencontainers.image.description="Slurm All-in-one Docker container on CentOS 7" \
      org.label-schema.docker.cmd="docker run -it -h slurmctl giovtorres/docker-centos7-slurm:latest" \
      maintainer="Giovanni Torres"

ENV PATH "/root/.pyenv/shims:/root/.pyenv/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/bin"

EXPOSE 6817 6818 6819 6820 3306

# Install common YUM dependency packages
# The IUS repo install epel-release as a dependency while also providing a newer version of Git
RUN set -ex \
    && yum makecache fast \
    && yum -y update \
    && yum -y install https://repo.ius.io/ius-release-el7.rpm \
    && yum -y install \
        autoconf \
        bash-completion \
        bzip2 \
        bzip2-devel \
        file \
        iproute \
        gcc \
        gcc-c++ \
        gdbm-devel \
        git236 \
        glibc-devel \
        gmp-devel \
        libffi-devel \
        libGL-devel \
        libX11-devel \
        make \
        mariadb-server \
        mariadb-devel \
        munge \
        munge-devel \
        ncurses-devel \
        patch \
        perl-core \
        pkgconfig \
        psmisc \
        readline-devel \
        sqlite-devel \
        tcl-devel \
        tix-devel \
        tk \
        tk-devel \
        supervisor \
        wget \
        which \
        vim-enhanced \
        xz-devel \
        zlib-devel http-parser-devel json-c-devel libjwt-devel libyaml-devel \
    && yum clean all \
    && rm -rf /var/cache/yum

# Set Vim and Git defaults
RUN set -ex \
    && echo "syntax on"           >> "$HOME/.vimrc" \
    && echo "set tabstop=4"       >> "$HOME/.vimrc" \
    && echo "set softtabstop=4"   >> "$HOME/.vimrc" \
    && echo "set shiftwidth=4"    >> "$HOME/.vimrc" \
    && echo "set expandtab"       >> "$HOME/.vimrc" \
    && echo "set autoindent"      >> "$HOME/.vimrc" \
    && echo "set fileformat=unix" >> "$HOME/.vimrc" \
    && echo "set encoding=utf-8"  >> "$HOME/.vimrc" \
    && git config --global color.ui auto \
    && git config --global push.default simple

# Add Tini
ENV TINI_VERSION v0.18.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini
RUN chmod +x /tini

# Install OpenSSL1.1.1
# See PEP 644: https://www.python.org/dev/peps/pep-0644/
ARG OPENSSL_VERSION="1.1.1l"
RUN set -ex \
    && wget --quiet https://www.openssl.org/source/openssl-${OPENSSL_VERSION}.tar.gz \
    && tar xzf openssl-${OPENSSL_VERSION}.tar.gz \
    && pushd openssl-${OPENSSL_VERSION} \
    && ./config --prefix=/opt/openssl --openssldir=/etc/ssl \
    && make \
    && make test \
    && make install \
    && echo "/opt/openssl/lib" >> /etc/ld.so.conf.d/openssl.conf \
    && ldconfig \
    && popd \
    && rm -rf openssl-${OPENSSL_VERSION}.tar.gz

# Install supported Python versions and install dependencies.
# Set the default global to the latest supported version.
# Use pyenv inside the container to switch between Python versions.
ARG PYTHON_VERSIONS="3.6.15 3.7.12 3.8.12 3.9.9 3.10.0"
ARG CONFIGURE_OPTS="--with-openssl=/opt/openssl"
RUN set -ex \
    && curl https://pyenv.run | bash \
    && echo "eval \"\$(pyenv init --path)\"" >> "${HOME}/.bashrc" \
    && echo "eval \"\$(pyenv init -)\"" >> "${HOME}/.bashrc" \
    && source "${HOME}/.bashrc" \
    && pyenv update \
    && for python_version in ${PYTHON_VERSIONS}; \
        do \
            pyenv install $python_version; \
            pyenv global $python_version; \
            pip install Cython pytest; \
        done

# Compile, build and install Slurm from Git source
ARG SLURM_TAG=slurm-21-08-6-1
ARG JOBS=4
RUN set -ex \
    && git clone -b ${SLURM_TAG} --single-branch --depth=1 https://github.com/SchedMD/slurm.git \
    && pushd slurm \
    && ./configure --prefix=/usr --sysconfdir=/etc/slurm --enable-slurmrestd \
        --with-mysql_config=/usr/bin --libdir=/usr/lib64 \
    && sed -e 's|#!/usr/bin/env python3|#!/usr/bin/python|' -i doc/html/shtml2html.py \
    && make -j ${JOBS} install \
    && install -D -m644 etc/cgroup.conf.example /etc/slurm/cgroup.conf.example \
    && install -D -m644 etc/slurm.conf.example /etc/slurm/slurm.conf.example \
    && install -D -m600 etc/slurmdbd.conf.example /etc/slurm/slurmdbd.conf.example \
    && install -D -m644 contribs/slurm_completion_help/slurm_completion.sh /etc/profile.d/slurm_completion.sh \
    && popd \
    && rm -rf slurm \
    && groupadd -r slurm  \
    && useradd -r -g slurm slurm \
    && mkdir -p /etc/sysconfig/slurm \
        /var/spool/slurmd \
        /var/spool/slurmctld \
        /var/log/slurm \
        /var/run/slurm \
    && chown -R slurm:slurm /var/spool/slurmd \
        /var/spool/slurmctld \
        /var/log/slurm \
        /var/run/slurm \
    && /sbin/create-munge-key

RUN dd if=/dev/random of=/etc/slurm/jwt_hs256.key bs=32 count=1 \
    && chmod 600 /etc/slurm/jwt_hs256.key && chown slurm.slurm /etc/slurm/jwt_hs256.key

COPY --chown=slurm files/slurm/slurm.conf files/slurm/gres.conf files/slurm/slurmdbd.conf /etc/slurm/
COPY files/supervisord.conf /etc/

RUN chmod 0600 /etc/slurm/slurmdbd.conf

# Mark externally mounted volumes
VOLUME ["/var/lib/mysql", "/var/lib/slurmd", "/var/spool/slurm", "/var/log/slurm"]

COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh

ENTRYPOINT ["/tini", "--", "/usr/local/bin/docker-entrypoint.sh"]
CMD ["/bin/bash"]


text:
<?php
namespace falkirks\disguiseme\disguise;

use falkirks\disguiseme\exception\InvalidDisguiseException;
use pocketmine\network\mcpe\protocol\AddEntityPacket;
use pocketmine\network\mcpe\protocol\MoveEntityPacket;
use pocketmine\network\mcpe\protocol\MovePlayerPacket;
use pocketmine\network\mcpe\protocol\RemoveEntityPacket;
use pocketmine\network\mcpe\protocol\SetEntityMotionPacket;
use pocketmine\Player;

class GenericEntityDisguise extends AbstractDisguise {
    /** @var  int */
    protected $type;

    /**
     * GenericEntityDisguise constructor.
     * @param Player $subject
     * @param int $type
     * @throws InvalidDisguiseException
     */
    public function __construct(Player $subject, $type){
        parent::__construct($subject);

        if(!is_numeric($type) || $type < 0){
            throw new InvalidDisguiseException("That entity ID is invalid.");
        }

        $this->type = $type;
    }

    public function showTo(Player $player){
        if(!$this->isShownTo($player)) {
            $pk = new RemoveEntityPacket();
            $pk->eid = $this->getSubject()->getID();

            $pk2 = new AddEntityPacket();
            $pk2->eid = $this->getSubject()->getID();
            $pk2->type = $this->type;
            $pk2->x = $this->getSubject()->getX();
            $pk2->y = $this->getSubject()->getY();
            $pk2->z = $this->getSubject()->getZ();
            $pk2->pitch = $this->getSubject()->pitch;
            $pk2->yaw = $this->getSubject()->yaw;
            $pk2->metadata = [];

            $pk3 = new SetEntityMotionPacket();
            $pk3->entities = [
                [
                    $this->getSubject()->getID(),
                    $this->getSubject()->motionX,
                    $this->getSubject()->motionY,
                    $this->getSubject()->motionZ
                ]
            ];

            $player->dataPacket($pk);
            $player->dataPacket($pk2);
            $player->dataPacket($pk3);

            parent::showTo($player);
            return true;
        }
        return false;
    }

    public function hideFrom(Player $player){
        if($this->isShownTo($player)) {
            $this->getSubject()->despawnFrom($player);
            $this->getSubject()->spawnTo($player);
            parent::hideFrom($player);
            return true;
        }
        return false;
    }

    public function updatePositionFor(Player $target, MovePlayerPacket $movePlayerPacket){
        if($this->isShownTo($target)) {
            $pk = new MoveEntityPacket();
            $pk->x = $movePlayerPacket->x;
            $pk->y = $movePlayerPacket->y;
            $pk->z = $movePlayerPacket->z;
            $target->dataPacket($pk);
            return true;
        }
        return false;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Vincent Elfving </title>

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

    <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">

	<link href="assets/lightbox/css/lightbox.css" rel="stylesheet">

	<link href="assets/textrotator/simpletextrotator.css" rel="stylesheet">

    <link href="assets/flexslider/flexslider.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">

    <link href="css/animate.css" rel="stylesheet">

	<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />

						Home
						About
						Projects

						Contact

			    <button class="menu-button" id="open-button"></button>

                    Vincent

                    Elfving

Quantum Magician,Physics PhD,Videographer

SEE MORE

A little about me

I am fanatic about quantum computing, machine learning and videography.

Projects

Multi-Emitter Scattering GUI

Web App  implementing scattering theory I worked on and published with Sumanta Das, Florentin Reiter, and Anders Sorensen. Publication can be found at here..

Drop me a line

Address

 Santa Barbara, CA, USA

Phone

+45 31 73 79 94

Email

vincentelfving@gmail.com

			     <form role="form">

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

                                        <input type="email" class="form-control" placeholder="Email address">

                                <textarea class="form-control" placeholder="Write you message here..." style="height:232px;"></textarea>

                            <button type="submit" class="btn btn-send">
                                Send message
                            </button>
                        </form>

All Rights Reserved. © 2015. Web design by ThemeWagon


text:
namespace ash {

// An indicator shown in UnifiedSystemTray when a VM is accessing the camera or
// mic. We might want to extend this feature to the browser in the future.
class ASH_EXPORT CameraMicTrayItemView : public TrayItemView,
                                         public SessionObserver,
                                         public MediaCaptureObserver {
 public:
  enum class Type {
    kCamera,
    kMic,
  };

  CameraMicTrayItemView(Shelf* shelf, Type type);
  ~CameraMicTrayItemView() override;

  CameraMicTrayItemView(const CameraMicTrayItemView&) = delete;
  CameraMicTrayItemView& operator=(const CameraMicTrayItemView&) = delete;

  std::u16string GetAccessibleNameString() const;

  // views::View:
  const char* GetClassName() const override;
  views::View* GetTooltipHandlerForPoint(const gfx::Point& point) override;
  std::u16string GetTooltipText(const gfx::Point& p) const override;

  // SessionObserver:
  void OnActiveUserSessionChanged(const AccountId& account_id) override;

  // TrayItemView:
  void HandleLocaleChange() override;

  // MediaCaptureObserver:
  void OnVmMediaNotificationChanged(bool camera,
                                    bool mic,
                                    bool camera_and_mic) override;

 private:
  void Update();
  void FetchMessage();

  const Type type_;
  bool active_ = false;
  bool with_mic_ = false;  // Only for `type_ == kCamera`.
  bool is_primary_session_ = false;
  std::u16string message_;
};

}  // namespace ash

#endif  // ASH_SYSTEM_UNIFIED_CAMERA_MIC_TRAY_ITEM_VIEW_H_


text:
File:      test/a-active-test.scss.md
License:   MIT — http://opensource.org/licenses/MIT
Copyright: ( C ) 2014 Stefano F. Rausch < stefano@rausch-e.net >

> **A Active** : Single Selector Test
> <small> see [normalizer.scss](../_normalizer.scss.md) </smalll>

    @import "../normalizer";

    a:active {
        @extend %a:active;

        content : "@extend %a:active;";
    }

Only `a:active` selector definitions should be stated.


text:
  An ideal iOS library using swift programming language. Draw a smooth curve through several points you designated. The curve's bend level is adjustable.
Installation
------------
  You only need drag UIBezierPath+LxThroughPointsBezier.swift to your project.
Support
------------
  Minimum support iOS version: iOS 5.0
Usage
-----------
###
```swift
        var _points = [CGPoint]()

        let point1 = CGPoint(x: 30, y: 210)
        let point2 = CGPoint(x: 90, y: 120)
        let point3 = CGPoint(x: 120, y: 200)
        let point4 = CGPoint(x: 160, y: 240)
        let point5 = CGPoint(x: 210, y: 160)
        let point6 = CGPoint(x: 240, y: 300)
        let point7 = CGPoint(x: 290, y: 140)

        _points.append(point1)
        _points.append(point2)
        _points.append(point3)
        _points.append(point4)
        _points.append(point5)
        _points.append(point6)
        _points.append(point7)

        let _curve = UIBezierPath()

        _curve.contractionFactor = CGFloat(0.7)
        _curve.moveToPoint(point1)
        _curve.addBezierThrough(points: _points)

        let _shapeLayer = CAShapeLayer()

        _shapeLayer.strokeColor = UIColor.blueColor().CGColor
        _shapeLayer.fillColor = nil
        _shapeLayer.lineWidth = 3
        _shapeLayer.path = _curve.CGPath
        _shapeLayer.lineCap = kCALineCapRound
        view.layer.addSublayer(_shapeLayer)
```
Be careful
-----------
    The good bend level is about 0.6 ~ 0.8. The default and recommended value is 0.7.
    You must give at least 1 point for drawing the curve.
Effect
-----------
*	![demo](demo.gif)

License
-----------
LxThroughPointsBezier-Swift is available under the Apache License 2.0. See the LICENSE file for more info.


text:
<!DOCTYPE html>

		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<title>Bootstrap Login Form</title>
		<meta name="generator" content="Bootply" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
		<link rel="stylesheet" href="login.css">

		<link href="css/styles.css" rel="stylesheet">

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Login

          <form class="form col-md-12 center-block">

              <input type="text" class="form-control input-lg" placeholder="Email">

              <input type="password" class="form-control input-lg" placeholder="Password">

              <button class="btn btn-primary btn-lg btn-block">Sign In</button>
              RegisterNeed help?

          </form>

          <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>


text:
import Component from 'react-pure-render/component'
import React, {PropTypes} from 'react'

export default class Place extends Component {
  static propTypes = {
    place: PropTypes.string.isRequired
  };

  constructor(props) {
    super(props)
  }

  render() {
    const {place} = this.props

    return (

{place}

    )
  }
}


text:
To combine two tasks in sequence, the `andThen` function can be used, which works roughly the same as `then` in Promise land. It takes a task and chains a function after it, so that it will get called with the result of the computation. The function in turn returns a new task. To understand things in detail, we need to take a look at the type signature:

```
class Task<T> {
    public andThen<U>(f: (x: T) => Task<U>): Task<U>;
}
```

This might seem complicated at first, but let's break it down a bit. `Task<T>` describes a task that results in a value of type `T`. We can combine it with a function that takes that resulting `T`, and returns a new task `Task<U>`. The result of that combination is another task `Task<U>`, which performs effects from both input tasks and results in a value of type `U`.

# In Parallel

To combine two tasks in parallel, the `parallel` function can be used:

```
class Task<T> {
    public parallel<U>(task: Task<U>): Task<[T, U]>;
}
```


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

using Xunit;

namespace Moq.Tests
{
	public class SequenceExtensionsFixture
	{
		[Fact]
		public void PerformSequence()
		{
			var mock = new Mock<IFoo>();

			mock.SetupSequence(x => x.Do())
				.Returns(2)
				.Returns(3)
				.Returns(() => 4)
				.Throws<InvalidOperationException>();

			Assert.Equal(2, mock.Object.Do());
			Assert.Equal(3, mock.Object.Do());
			Assert.Equal(4, mock.Object.Do());
			Assert.Throws<InvalidOperationException>(() => mock.Object.Do());
		}

		[Fact]
		public void PerformSequenceAsync()
		{
			var mock = new Mock<IFoo>();

			mock.SetupSequence(x => x.DoAsync())
				.ReturnsAsync(2)
				.ReturnsAsync(3)
				.ThrowsAsync(new InvalidOperationException());

			Assert.Equal(2, mock.Object.DoAsync().Result);
			Assert.Equal(3, mock.Object.DoAsync().Result);

			try
			{
				var x = mock.Object.DoAsync().Result;
			}
			catch (AggregateException ex)
			{
				Assert.IsType<InvalidOperationException>(ex.GetBaseException());
			}
		}

		[Fact]
		public async Task PerformSequenceAsync_ReturnsAsync_for_Task_with_value_function()
		{
			var mock = new Mock<IFoo>();
			mock.SetupSequence(m => m.DoAsync())
				.ReturnsAsync(() => 1)
				.ReturnsAsync(() => 2);

			Assert.Equal(1, await mock.Object.DoAsync());
			Assert.Equal(2, await mock.Object.DoAsync());
		}

		[Fact]
		public async Task PerformSequenceAsync_ReturnsAsync_for_ValueTask_with_value_function()
		{
			var mock = new Mock<IFoo>();
			mock.SetupSequence(m => m.DoValueAsync())
				.ReturnsAsync(() => 1)
				.ReturnsAsync(() => 2);

			Assert.Equal(1, await mock.Object.DoValueAsync());
			Assert.Equal(2, await mock.Object.DoValueAsync());
		}

		[Fact]
		public void PerformSequenceOnProperty()
		{
			var mock = new Mock<IFoo>();

			mock.SetupSequence(x => x.Value)
				.Returns("foo")
				.Returns("bar")
				.Throws<InvalidOperationException>();

			string temp;
			Assert.Equal("foo", mock.Object.Value);
			Assert.Equal("bar", mock.Object.Value);
			Assert.Throws<InvalidOperationException>(() => temp = mock.Object.Value);
		}

		[Fact]
		public void PerformSequenceWithThrowsFirst()
		{
			var mock = new Mock<IFoo>();

			mock.SetupSequence(x => x.Do())
				.Throws<Exception>()
				.Returns(1);

			Assert.Throws<Exception>(() => mock.Object.Do());
			Assert.Equal(1, mock.Object.Do());
		}

		[Fact]
		public void PerformSequenceWithCallBase()
		{
			var mock = new Mock<Foo>();

			mock.SetupSequence(x => x.Do())
				.Returns("Good")
				.CallBase()
				.Throws<InvalidOperationException>();

			Assert.Equal("Good", mock.Object.Do());
			Assert.Equal("Ok", mock.Object.Do());
			Assert.Throws<InvalidOperationException>(() => mock.Object.Do());
		}

		[Fact]
		public void Setting_up_a_sequence_overrides_any_preexisting_setup()
		{
			const string valueFromPreviousSetup = "value from previous setup";

			// Arrange: set up a sequence as the second setup and consume it
			var mock = new Mock<IFoo>();
			mock.Setup(m => m.Value).Returns(valueFromPreviousSetup);
			mock.SetupSequence(m => m.Value).Returns("1");
			var _ = mock.Object.Value;

			// Act: ask sequence for value when it is exhausted
			var actual = mock.Object.Value;

			// Assert: should have got the default value, not the one configured by the overridden setup
			Assert.Equal(default(string), actual);
			Assert.NotEqual(valueFromPreviousSetup, actual);
		}

		[Fact]
		public void When_sequence_exhausted_and_there_was_no_previous_setup_return_value_is_default()
		{
			// Arrange: set up a sequence as the only setup and consume it
			var mock = new Mock<IFoo>();
			mock.SetupSequence(m => m.Value)
				.Returns("1");
			var _ = mock.Object.Value;

			// Act: ask sequence for value when it is exhausted
			string actual = mock.Object.Value;

			// Assert: should have got the default value
			Assert.Equal(default(string), actual);
		}

		[Fact]
		public void When_sequence_overexhausted_and_new_responses_are_configured_those_are_used_on_next_invocation()
		{
			// Arrange: set up a sequence and overexhaust it, then set up more responses
			var mock = new Mock<IFoo>();
			var sequenceSetup = mock.SetupSequence(m => m.Value).Returns("1"); // configure 1st response
			var _ = mock.Object.Value; // 1st invocation
			_ = mock.Object.Value; // 2nd invocation
			sequenceSetup.Returns("2"); // configure 2nd response
			sequenceSetup.Returns("3"); // configure 3nd response

			// Act: 3rd invocation. will we get back the 2nd configured response, or the 3rd (since we're on the 3rd invocation)?
			string actual = mock.Object.Value;

			// Assert: no configured response should be skipped, therefore we should get the 2nd one
			Assert.Equal("2", actual);
		}

		[Fact]
		public void Verify_can_verify_invocation_count_for_sequences()
		{
			var mock = new Mock<IFoo>();
			mock.SetupSequence(m => m.Do());

			mock.Object.Do();
			mock.Object.Do();

			mock.Verify(m => m.Do(), Times.Exactly(2));
		}

		[Fact]
		public void Func_are_invoked_deferred()
		{
			var mock = new Mock<IFoo>();
			var i = 0;
			mock.SetupSequence(m => m.Do())
				.Returns(() => i);

			i++;

			Assert.Equal(i, mock.Object.Do());
		}

		[Fact]
		public async Task Func_are_invoked_deferred_for_Task()
		{
			var mock = new Mock<IFoo>();
			var i = 0;
			mock.SetupSequence(m => m.DoAsync())
				.ReturnsAsync(() => i);

			i++;

			Assert.Equal(i, await mock.Object.DoAsync());
		}

		[Fact]
		public async Task Func_are_invoked_deferred_for_ValueTask()
		{
			var mock = new Mock<IFoo>();
			var i = 0;
			mock.SetupSequence(m => m.DoValueAsync())
				.ReturnsAsync(() => i);

			i++;

			Assert.Equal(i, await mock.Object.DoValueAsync());
		}

		[Fact]
		public void Func_can_be_treated_as_return_value()
		{
			var mock = new Mock<IFoo>();
			Func<int> func = () => 1;
			mock.SetupSequence(m => m.GetFunc())
				.Returns(func);

			Assert.Equal(func, mock.Object.GetFunc());
		}

		[Fact]
		public void Keep_Func_as_return_value_when_setup_method_returns_implicitly_casted_type()
		{
			var mock = new Mock<IFoo>();
			Func<object> funcObj = () => 1;
			Func<Delegate> funcDel = () => new Action(() => { });
			Func<MulticastDelegate> funcMulticastDel = () => new Action(() => { });
			mock.SetupSequence(m => m.GetObj()).Returns(funcObj);
			mock.SetupSequence(m => m.GetDel()).Returns(funcDel);
			mock.SetupSequence(m => m.GetMulticastDel()).Returns(funcMulticastDel);

			Assert.Equal(funcObj, mock.Object.GetObj());
			Assert.Equal(funcDel, mock.Object.GetDel());
			Assert.Equal(funcMulticastDel, mock.Object.GetMulticastDel());
		}

		public interface IFoo
		{
			string Value { get; set; }

			int Do();

			Task<int> DoAsync();

			ValueTask<int> DoValueAsync();

			Func<int> GetFunc();

			object GetObj();

			Delegate GetDel();

			MulticastDelegate GetMulticastDel();
		}

		public class Foo
		{
			public virtual string Do()
			{
				return "Ok";
			}

			public virtual Task<string> DoAsync()
			{
				var tcs = new TaskCompletionSource<string>();
				tcs.SetResult("Ok");
				return tcs.Task;
			}
		}
	}
}


text: Practice repository for Github for Developer part 2 (June 2015)


text:
package internal.org.springframework.content.mongo.config;

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.content.commons.mappingcontext.MappingContext;
import org.springframework.content.commons.repository.factory.AbstractStoreFactoryBean;
import org.springframework.content.commons.utils.PlacementService;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.versions.LockingAndVersioningProxyFactory;

import internal.org.springframework.content.mongo.store.DefaultMongoStoreImpl;

public class MongoStoreFactoryBean extends AbstractStoreFactoryBean {

	@Autowired
	private GridFsTemplate gridFs;

	@Autowired
	private PlacementService mongoStorePlacementService;

    @Autowired(required=false)
    private MappingContext mappingContext;

	@Autowired(required=false)
    private LockingAndVersioningProxyFactory versioning;

    @Override
    protected void addProxyAdvice(ProxyFactory result, BeanFactory beanFactory) {
        if (versioning != null) {
            versioning.apply(result);
        }
    }

	@Override
	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
	}

	@Override
	protected Object getContentStoreImpl() {
		return new DefaultMongoStoreImpl(gridFs, mappingContext, mongoStorePlacementService);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

public class BoundedNumbers
{
    public static void Main()
    {
        List<int> bounds = Console.ReadLine()
            .Split()
            .Select(int.Parse)
            .ToList();

        List<int> numbers = Console.ReadLine()
            .Split()
            .Select(int.Parse)
            .Where(n => bounds.Min() <= n && n <= bounds.Max())
            .ToList();

        Console.WriteLine(string.Join(" ", numbers));
    }
}


text:
////////////////////////////////////////////////////////////////////////////////
// This source code is part of RokLegend project.
//         (Ragnarök Online Client)
//     Copyright (c) RokLegend Team, 2013
////////////////////////////////////////////////////////////////////////////////

#pragma once
#ifndef ROGRF_GRF_VERSION1_H
#define ROGRF_GRF_VERSION1_H

#include <Core/RoPrerequisites.h>

#include <Archive/RoGrf.h>
#include <Archive/RoGrfHeader.h>

/**
  * Brief description about RoGrfVersion1.
 **/
class RoGrfVersion1 : public RoGrf
{
public:
    RoGrfVersion1(size_t grfId, const RoGrfStorageBackendPtr& store, const RoGrfHeader& header, const RoString& fileName);
    virtual ~RoGrfVersion1();

private:
    void populateFileList();
    void validateRemainingFileSize();
    void populateFileListFromFileStream();
    bool isDesEncryptedFile(const RoString& fileName);
};

#endif // ROGRF_GRF_VERSION1_H


text:
using namespace BloombergLP;
using namespace bslma;

void f(bslma::Allocator *pa)
{
    bslma::Allocator     *da = bslma::Default::allocator();
    bslma::Allocator     *ba = Default::allocator();
    bslma::Allocator     *aa;
    bslma::Allocator     *za;
    bslma::TestAllocator  ta;

    aa = bslma::Default::allocator();
    za = Default::allocator();

    bsl::shared_ptr<char> sp01(new char);
    bsl::shared_ptr<char> sp02(new (*pa) char);
    bsl::shared_ptr<char> sp03(new (*pa) char, pa);
    bsl::shared_ptr<char> sp04(new (*da) char);
    bsl::shared_ptr<char> sp05(new (*da) char, da);
    bsl::shared_ptr<char> sp06(new (*ba) char);
    bsl::shared_ptr<char> sp07(new (*ba) char, ba);
    bsl::shared_ptr<char> sp08(new (ta) char);
    bsl::shared_ptr<char> sp09(new (ta) char, &ta);
    bsl::shared_ptr<char> sp10(new (*bslma::Default::allocator()) char);
    bsl::shared_ptr<char> sp11(new (*bslma::Default::allocator()) char,
                          bslma::Default::allocator());
    bsl::shared_ptr<char> sp12(new (*Default::allocator()) char);
    bsl::shared_ptr<char> sp13(new (*Default::allocator()) char,
                          Default::allocator());
    bsl::shared_ptr<char> sp14(new (*aa) char);
    bsl::shared_ptr<char> sp15(new (*aa) char, aa);
    bsl::shared_ptr<char> sp16(new (*ba) char);
    bsl::shared_ptr<char> sp17(new (*ba) char, ba);
    bsl::shared_ptr<char> sp18(new (*za) char);
    bsl::shared_ptr<char> sp19(new (*za) char, za);

    bsl::shared_ptr<char>(new char);
    bsl::shared_ptr<char>(new (*pa) char);
    bsl::shared_ptr<char>(new (*pa) char, pa);
    bsl::shared_ptr<char>(new (*da) char);
    bsl::shared_ptr<char>(new (*da) char, da);
    bsl::shared_ptr<char>(new (*ba) char);
    bsl::shared_ptr<char>(new (*ba) char, ba);
    bsl::shared_ptr<char>(new (ta) char);
    bsl::shared_ptr<char>(new (ta) char, &ta);
    bsl::shared_ptr<char>(new (*bslma::Default::allocator()) char);
    bsl::shared_ptr<char>(new (*bslma::Default::allocator()) char,
                     bslma::Default::allocator());
    bsl::shared_ptr<char>(new (*Default::allocator()) char);
    bsl::shared_ptr<char>(new (*Default::allocator()) char, Default::allocator());
    bsl::shared_ptr<char>(new (*aa) char);
    bsl::shared_ptr<char>(new (*aa) char, aa);
    bsl::shared_ptr<char>(new (*ba) char);
    bsl::shared_ptr<char>(new (*ba) char, ba);
    bsl::shared_ptr<char>(new (*za) char);
    bsl::shared_ptr<char>(new (*za) char, za);

    bsl::shared_ptr<char> ep01(new char, da);
    bsl::shared_ptr<char> ep02(new (*ba) char, da);
    bsl::shared_ptr<char> ep03(new (ta) char, ba);
    bsl::shared_ptr<char> ep04(new (*da) char, &ta);
    bsl::shared_ptr<char> ep05(new (*bslma::Default::allocator()) char, da);
    bsl::shared_ptr<char> ep06(new (*Default::allocator()) char, da);
    bsl::shared_ptr<char> ep07(new (*da) char, Default::allocator());
    bsl::shared_ptr<char> ep08(new (*da) char, bslma::Default::allocator());
}

struct X {
    bslma::Allocator *da, *ba;
    bslma::TestAllocator ta;

    bsl::shared_ptr<char> d_sp01, d_sp02, d_sp03, d_sp04, d_sp05, d_sp06, d_sp07;
    bsl::shared_ptr<char> d_sp08, d_sp09, d_sp10, d_sp11, d_sp12, d_sp13, d_sp14;
    bsl::shared_ptr<char> d_sp15, d_sp16, d_sp17, d_sp18, d_sp19;
    bsl::shared_ptr<char> d_ep01, d_ep02, d_ep03, d_ep04, d_ep05, d_ep06;
    bsl::shared_ptr<char> d_ep07, d_ep08;
    X(bslma::Allocator *pa)
    : da(bslma::Default::allocator())
    , ba(Default::allocator())
    , d_sp01(new char)
    , d_sp02(new (*pa) char)
    , d_sp03(new (*pa) char, pa)
    , d_sp04(new (*da) char)
    , d_sp05(new (*da) char, da)
    , d_sp06(new (*ba) char)
    , d_sp07(new (*ba) char, ba)
    , d_sp08(new (ta) char)
    , d_sp09(new (ta) char, &ta)
    , d_sp10(new (*bslma::Default::allocator()) char)
    , d_sp11(new (*bslma::Default::allocator()) char,
                          bslma::Default::allocator())
    , d_sp12(new (*Default::allocator()) char)
    , d_sp13(new (*Default::allocator()) char, Default::allocator())
    , d_sp16(new (*ba) char)
    , d_sp17(new (*ba) char, ba)
    , d_ep01(new char, da)
    , d_ep02(new (*ba) char, da)
    , d_ep03(new (ta) char, ba)
    , d_ep04(new (*da) char, &ta)
    , d_ep05(new (*bslma::Default::allocator()) char, da)
    , d_ep06(new (*Default::allocator()) char, da)
    , d_ep07(new (*da) char, Default::allocator())
    , d_ep08(new (*da) char, bslma::Default::allocator())
    {
    }
};

void g(bsl::shared_ptr<char> &sp, bslma::Allocator *pa)
{
    bslma::Allocator     *da = bslma::Default::allocator();
    bslma::Allocator     *ba = Default::allocator();
    bslma::Allocator     *aa;
    bslma::Allocator     *za;
    bslma::TestAllocator  ta;

    aa = bslma::Default::allocator();
    za = Default::allocator();

    sp.reset(new char);
    sp.reset(new (*pa) char);
    sp.reset(new (*pa) char, pa);
    sp.reset(new (*da) char);
    sp.reset(new (*da) char, da);
    sp.reset(new (*ba) char);
    sp.reset(new (*ba) char, ba);
    sp.reset(new (ta) char);
    sp.reset(new (ta) char, &ta);
    sp.reset(new (*bslma::Default::allocator()) char);
    sp.reset(new (*bslma::Default::allocator()) char,
                          bslma::Default::allocator());
    sp.reset(new (*Default::allocator()) char);
    sp.reset(new (*Default::allocator()) char,
                          Default::allocator());
    sp.reset(new (*aa) char);
    sp.reset(new (*aa) char, aa);
    sp.reset(new (*ba) char);
    sp.reset(new (*ba) char, ba);
    sp.reset(new (*za) char);
    sp.reset(new (*za) char, za);

    sp.reset(new char);
    sp.reset(new (*pa) char);
    sp.reset(new (*pa) char, pa);
    sp.reset(new (*da) char);
    sp.reset(new (*da) char, da);
    sp.reset(new (*ba) char);
    sp.reset(new (*ba) char, ba);
    sp.reset(new (ta) char);
    sp.reset(new (ta) char, &ta);
    sp.reset(new (*bslma::Default::allocator()) char);
    sp.reset(new (*bslma::Default::allocator()) char,
                     bslma::Default::allocator());
    sp.reset(new (*Default::allocator()) char);
    sp.reset(new (*Default::allocator()) char, Default::allocator());
    sp.reset(new (*aa) char);
    sp.reset(new (*aa) char, aa);
    sp.reset(new (*ba) char);
    sp.reset(new (*ba) char, ba);
    sp.reset(new (*za) char);
    sp.reset(new (*za) char, za);

    sp.reset(new char, da);
    sp.reset(new (*ba) char, da);
    sp.reset(new (ta) char, ba);
    sp.reset(new (*da) char, &ta);
    sp.reset(new (*bslma::Default::allocator()) char, da);
    sp.reset(new (*Default::allocator()) char, da);
    sp.reset(new (*da) char, Default::allocator());
    sp.reset(new (*da) char, bslma::Default::allocator());
}

// ----------------------------------------------------------------------------
// Copyright (C) 2019 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in co   iance 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 i   ied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
package org.lwjgl.opengl;

import org.lwjgl.system.*;

/**
 * Native bindings to the EXT_blend_minmax extension.
 *
 *
Blending capability is extended by respecifying the entire blend equation. While this document defines only two new equations, the {@link #glBlendEquationEXT BlendEquationEXT}
 * procedure that it defines will be used by subsequent extensions to define additional blending equations.

 *
 *
The two new equations defined by this extension produce the minimum (or maximum) color components of the source and destination colors. Taking the
 * maximum is useful for applications such as maximum projection in medical imaging.

 *
 *
Promoted to core in {@link GL14 OpenGL 1.4}.

 */
public class EXTBlendMinmax {

    static { GL.initialize(); }

    /** Accepted by the {@code mode} parameter of BlendEquationEXT. */
    public static final int
        GL_FUNC_ADD_EXT = 0x8006,
        GL_MIN_EXT      = 0x8007,
        GL_MAX_EXT      = 0x8008;

    /** Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev. */
    public static final int GL_BLEND_EQUATION_EXT = 0x8009;

    protected EXTBlendMinmax() {
        throw new UnsupportedOperationException();
    }

    // --- [ glBlendEquationEXT ] ---

    public static native void glBlendEquationEXT(@NativeType("GLenum") int mode);

}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CanvasComponent } from './canvas.component';
import { CanvasService } from './services/canvas.service';
import { CanvasItemService } from './services/canvas-item.service';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    CanvasComponent
  ],
  providers: [
    CanvasService,
    CanvasItemService
  ]
})
export class CanvasModule { }


text:
define(["js/data/Entity", "sprd/model/Product", "sprd/model/Article", "sprd/entity/Appearance"], function (Entity, Product, Article, Appearance) {
    var TYPE_PRODUCT = "sprd:product";
    var TYPE_ARTICLE = "sprd:article";

    return Entity.inherit("sprd.entity.ConcreteElement", {
        schema: {
            appearance: Appearance,
            size: Entity,
            productTypeName: {
                required: false,
                type: String
            },
            productTypeId: {
                required: false,
                type: String
            }
        },

        defaults: {
            /***
             * the appearance of the basket item
             * @type sprd.entity.Appearance
             */
            appearance: null,
            /***
             * the size of the basket item
             * @type sprd.entity.ProductTypeSize
             */
            size: null,

            /***
             * the basket item
             * @type {sprd.model.Product|sprd.model.Article}
             */
            item: null,

            /***
             * continueShopping link is used in checkout as link for continue shopping button.
             * @type String
             */
            continueShoppingLink: null,

            /***
             * edit link is the link displayed in checkout for editing the basket item
             * @type String
             */
            editLink: null,

            /***
             * the base article
             * @type sprd.model.Article
             */
            article: null,

            /**
             *
             */
            originalProduct: null,
            originalArticleId: null
        },

        isEqual: function (concreteElement) {
            return this.get('appearance.id') === concreteElement.get('appearance.id') &&
                this.get('size.id') === concreteElement.get('size.id') &&
                this.get('item.id') === concreteElement.get('item.id');
        },

        init: function (callback) {
            this.$.item.fetch(null, callback);
        },

        getProduct: function () {
            if (this.$.item instanceof Product) {
                return this.$.item;
            } else if (this.$.item instanceof Article) {
                return this.$.item.$.product;
            }
            return null;
        }.on(['item', 'change:product']).onChange('item'),

        getArticle: function () {
            if (this.$.item instanceof Article) {
                return this.$.item;
            }
            return null;
        },

        getSize: function(){
            if(this.$.size){
                return this.getProduct().$.productType.getSizeById(this.$.size.$.id);
            }
            return null;
        },

        getAppearance: function(){
            if(this.$.appearance){
                return this.getProduct().$.productType.getAppearanceById(this.$.appearance.$.id);
            }
            return null;
        },

        getType: function () {
            if (this.$.item instanceof Product) {
                return TYPE_PRODUCT;
            } else if (this.$.item instanceof Article) {
                return TYPE_ARTICLE;
            }
            return null;
        },

        uniqueId: function () {
            return (this.getType() === TYPE_PRODUCT ? 'P' : 'A') + this.get('item.id');
        },

        sku: function () {
            return [ this.get('getProduct().productType.id'),
                this.get('appearance.id'),
                this.get('size.id')].join(' - ');
        },

        getBaseArticleId: function () {
            var baseArticleId = this.get("article.id");

            function productContainsDesign(product, design) {
                if (design) {
                    return !!product.$.configurations.find(function (configuration) {
                        return configuration.get('design.id') == design.$.id ||
                            configuration.get('design.wtfMbsId') == design.$.id;
                    });
                } else {
                    return false;
                }
            }

            function findDesign(product) {
                var config = product.$.configurations.find(function (configuration) {
                    return !!configuration.$.design;
                });

                return config ? config.$.design : null;
            }

            var originalProduct = this.get('originalProduct');
            if (!baseArticleId && originalProduct) {
                var design = findDesign(originalProduct);
                if (design) {
                    var product = this.getProduct();
                    if (product && productContainsDesign(product, design)) {
                        baseArticleId = this.$.originalArticleId;
                    }
                }
            }

            return baseArticleId;
        }

    });
});


text:
<?php

namespace App\Lib\DsManager\Models;

/**
 * Class League
 * @package App\Lib\DsManager\Models
 */
class League
{

}


text:
#
# Copyright 2022 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

package database::mysql::mode::opentables;

use base qw(centreon::plugins::mode);

use strict;
use warnings;

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $options{options}->add_options(arguments =>
                                {
                                  "warning:s"               => { name => 'warning', },
                                  "critical:s"              => { name => 'critical', },
                                });

    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::init(%options);

    if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) {
        $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'.");
        $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) {
        $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'.");
        $self->{output}->option_exit();
    }
}

sub run {
    my ($self, %options) = @_;
    # $options{sql} = sqlmode object
    $self->{sql} = $options{sql};

    $self->{sql}->connect();

    if (!($self->{sql}->is_version_minimum(version => '5'))) {
        $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x').");
        $self->{output}->option_exit();
    }

    $self->{sql}->query(query => q{SHOW VARIABLES LIKE 'table_open_cache'});
    my ($dummy, $open_tables_limit) = $self->{sql}->fetchrow_array();
    if (!defined($open_tables_limit)) {
        $self->{output}->add_option_msg(short_msg => "Cannot get open table limit.");
        $self->{output}->option_exit();
    }
    $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS LIKE 'Open_tables'});
    ($dummy, my $open_tables) = $self->{sql}->fetchrow_array();
    if (!defined($open_tables)) {
        $self->{output}->add_option_msg(short_msg => "Cannot get open tables.");
        $self->{output}->option_exit();
    }

    my $prct_open = int(100 * $open_tables / $open_tables_limit);
    my $exit_code = $self->{perfdata}->threshold_check(value => $prct_open, threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]);

    $self->{output}->output_add(severity => $exit_code,
                                short_msg => sprintf("%.2f%% of the open files limit reached (%d of max. %d)",
                                $prct_open, $open_tables, $open_tables_limit));
    $self->{output}->perfdata_add(label => 'open_tables',
                                  nlabel => 'database.open.tables.count',
                                  value => $open_tables,
                                  warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $open_tables_limit, cast_int => 1),
                                  critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $open_tables_limit, cast_int => 1),
                                  min => 0);

    $self->{output}->display();
    $self->{output}->exit();
}

1;

__END__

=head1 MODE

Check number of open tables.

=over 8

=item B<--warning>

Threshold warning in percent.

=item B<--critical>

Threshold critical in percent.

=back

=cut


text:
 .. Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

Checking Airflow Health Status
==============================

To check the health status of your Airflow instance, you can simply access the endpoint
``/health``. It will return a JSON object in which a high-level glance is provided.

.. code-block:: JSON

  {
    "metadatabase":{
      "status":"healthy"
    },
    "scheduler":{
      "status":"healthy",
      "latest_scheduler_heartbeat":"2018-12-26 17:15:11+00:00"
    }
  }

* The ``status`` of each component can be either "healthy" or "unhealthy"

  * The status of ``metadatabase`` depends on whether a valid connection can be initiated with the database

  * The status of ``scheduler`` depends on when the latest scheduler heartbeat was received

    * If the last heartbeat was received more than 30 seconds (default value) earlier than the current time, the scheduler is
      considered unhealthy
    * This threshold value can be specified using the option ``scheduler_health_check_threshold`` within the
      ``scheduler`` section in ``airflow.cfg``

Please keep in mind that the HTTP response code of ``/health`` endpoint **should not** be used to determine the health
status of the application. The return code is only indicative of the state of the rest call (200 for success).


text:
<?xml version="1.0" encoding="utf-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
    <rewriteSystem systemIdStartString="http://www.oasis-open.org/" rewritePrefix="file:///c:/develop/" />
	<rewriteURI uriStartString="http://www.oasis-open.org/" rewritePrefix="file:///c:/develop/" />
	<rewriteURI uriStartString="http://docbook.sourceforge.net/release/xsl/current/" rewritePrefix="file:///c:/develop/docbook-xsl-1.71.1/" />
	<rewriteSystem systemIdStartString="http://docbook.sourceforge.net/release/xsl/current/" rewritePrefix="file:///c:/develop/docbook-xsl-1.71.1/" />
	<rewriteURI uriStartString="http://docbook.sourceforge.net/release/" rewritePrefix="file:///c:/develop/docbook-xsl-1.71.1/" />
	<rewriteSystem systemIdStartString="http://docbook.sourceforge.net/release/" rewritePrefix="file:///c:/develop/docbook-xsl-1.71.1/" />
</catalog>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=utf8" />
		<meta name="generator" content="JsDoc Toolkit" />

		<title>JsDoc Reference - GLGE.DocumentPreloader</title>

Class Index
| File Index

Classes

_global_

GLGE

GLGE.Action

GLGE.ActionChannel

GLGE.Animatable

GLGE.AnimationCurve

GLGE.AnimationVector

GLGE.Assets

GLGE.BezTriple

GLGE.Camera

GLGE.Collada

GLGE.Document

GLGE.DocumentPreloader

GLGE.Events

GLGE.FilePreloader

GLGE.FilterAO

GLGE.FilterGlow

GLGE.Group

GLGE.GUI

GLGE.HeightMap

GLGE.JSONLoader

GLGE.KeyInput

GLGE.Light

GLGE.LinearPoint

GLGE.Material

GLGE.MaterialLayer

GLGE.MD2

GLGE.MD3

GLGE.Mesh

GLGE.Message

GLGE.MouseInput

GLGE.MultiMaterial

GLGE.Object

GLGE.ObjectLod

GLGE.OpenCTM

GLGE.ParticleSystem

GLGE.PhysicsAbstract

GLGE.PhysicsBox

GLGE.PhysicsCar

GLGE.PhysicsConstraintPoint

GLGE.PhysicsMesh

GLGE.PhysicsPlane

GLGE.PhysicsSphere

GLGE.PhysicsWheel

GLGE.Placeable

GLGE.QuickNotation

GLGE.Renderer

GLGE.Scene

GLGE.Sphere

GLGE.StepPoint

GLGE.Text

GLGE.Texture

GLGE.TextureCamera

GLGE.TextureCameraCube

GLGE.TextureCanvas

GLGE.TextureCube

GLGE.TextureVideo

GLGE.Wavefront

GUI.Gadget

GUI.Preloader

GUI.Progressbar

GUI.Widget

				Class GLGE.DocumentPreloader

Extends
					GLGE.Events.

				Document preloader class

Defined in:  glge_documentpreloader.js.

Class Summary

						Constructor Attributes
						Constructor Name and Description

								GLGE.DocumentPreloader(doc, args)

Method Summary

							Method Attributes
							Method Name and Description

addImage(url)

Add an image, which should be loaded by the preloader.

changeState(newState)

Sets the state of the document preloader.

finish(event)

Called when the document preloader loaded all files.

loadImages()

Start loading all images in all xml files.

loadXMLFile(url)

This function loads a XML-file.

updateProgress(args)

Update preloader progress.

Methods borrowed from class GLGE.Events:

addEventListener, fireEvent, removeEventListener

					Class Detail

						GLGE.DocumentPreloader(doc, args)

Parameters:

								 doc

								 args

					Method Detail

					addImage(url)

						Add an image, which should be loaded by the preloader.

Parameters:

									{string} url

Url of the image.

					changeState(newState)

						Sets the state of the document preloader.

Parameters:

									{number} newState

New state

					finish(event)

						Called when the document preloader loaded all files.

Parameters:

									{object} event

Event parameter. Not used at all.

					loadImages()

						Start loading all images in all xml files. Assumes that XML-files have finished loading.

					loadXMLFile(url)

						This function loads a XML-file. Assumes that loading images hasn't yet begun.

Parameters:

									{string} url

Url of the XML-file.

					updateProgress(args)

						Update preloader progress.

Parameters:

									{object} args

Progress information.

args.stepBytes describes how many bytes have been loaded since the last update.

			Documentation generated by JsDoc Toolkit 2.4.0 on Sat Jul 21 2012 10:32:24 GMT+0100 (BST)