text:
javascripting-with-dogs
===

javascript is fun and all, but javascripting with dogs is way more exciting. in this tutorial, i'll go over the basics of javascript, but add in some cute pups along the way.

###setting a variable
```
var dog = 'homer'

var puppy = 'plato'

console.log('meet ' + dog + ' and ' puppy)
```

 ==> this will print: **meet homer and plato**

![homer](/img/homer.jpg)

##arrays
```
var dogs = ['homer', 'plato]

console.log(dogs[0] + ' loves ' + dogs[1])

```

==> this will print: **homer loves plato**

![Alt text](/img/homerandplato.jpg)

##objects in arrays
```
var dogs = [{name: 'homer', age: 5}, {name: 'Plato', age: 4}]

console.log('the dogs are ' + dogs[0].age ' and ' + dogs[1].age)

```

==> this will print: **the dogs are 5 and 4**

![Alt text](/img/180831_1599740081972_7795070_n.jpg)

![Alt text](/img/plato3.jpg)

## the foreach loop
```
var dogs = [{name: 'homer', age: 5, breed: 'labradoodle'}, {name: 'Plato', age: 6, breed: 'husky'}]

dogs.forEach(function(dog) {

  console.log(dog.breed)

}
```

==> this will print: **{'labradoodle', 'husky'}**

![Alt text](/img/plato10.jpg)

![Alt text](/img/homer10.jpg)

##the push method
```
var dogs = [{name: 'homer', age: 5, food: 'hotdogs'}, {name: 'Plato', age: 6, food: 'chipotle'}, {name: 'Scooter', age: 10, food: 'greenies}]

var fav_food = []

dogs.forEach(function (dog) {
 fav_food.push(dog.food)
})

console.log(fav_food)
```
==> this will print: **['hotdogs','chipotle','greenies']**

![Alt text](/img/homerandplato2.jpg)

![Alt text](/img/scooter.jpg)

##thanks for reading!
hopefully you learned something about some javascipt basics...but if you didnt, hopefully you appreciated the cute puppies. shoutout to homer, plato, and scooter for their good looks.

        <img width="45%" src="img/downingandplato.jpg" alt="Downing" title="I love my Plato!"


text:
Namespace Ribbons.Document.Display

    Public Class CreoReferenced
        Inherits RibbonButtonBase

        Public Sub New()
            _Image = ""
            _Order = 1
            _Text = "Creo Referenced"
            _ToolTip = ""
        End Sub

        Protected Friend Overrides Sub OnClick()

        End Sub

        Protected Friend Overrides Sub OnIsEnabled()

        End Sub

    End Class

End Namespace

redpajama_set_name: RedPajamaGithub


text:
require "ofx/data/serialization/common"

module OFX
  module Data
    module Serialization
      module Banking
        module Statement
          module Transaction
            class Response
              include Common

              def default_registry_entry_args
                [:"banking.statement.transaction.response", nil]
              end

              def serialize(transaction, builder)
                builder.STMTTRNRS do |builder|
                  builder.TRNUID transaction.trnuid
                  serialize_collection(children(transaction), builder)
                end
              end

              def children(transaction)
                [transaction.status, transaction.response]
              end
            end
          end
        end
      end
    end
  end
end


text:
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Nucleo.EventArguments;
using Nucleo.EventsManagement;
using Nucleo.EventsManagement.Listeners;
using Nucleo.Orm.Entities;
using Nucleo.Presentation;
using Nucleo.Views;
using Nucleo.Web.Views;

using Nucleo.Orm.DataClasses;
using Nucleo.Code.Data.DataClasses;

namespace Nucleo.Demos.LinqToSql
{
	public class LargeResultSetModel
	{
		public IQueryable<SalesOrderDetail> SalesOrderDetails { get; set; }
	}

	public interface ILargeResultSetView : IView<LargeResultSetModel>
	{
		event DataEventHandler<bool> Refresh;
	}

	public class LargeResultSetPresenter : BasePresenter<ILargeResultSetView>
	{
		public LargeResultSetPresenter(ILargeResultSetView view)
			: base(view)
		{
			view.Refresh += View_Refresh;
			view.Starting += new EventHandler(View_Starting);
		}

		void View_Refresh(object sender, DataEventArgs<bool> e)
		{
			LoadData(e.Data);
		}

		void View_Starting(object sender, EventArgs e)
		{
			LoadData(false);
		}

		private void LoadData(bool loadAll)
		{
			var context = new AdventureWorksDataContext("AdventureWorksDbContext");
			var uow = new TableEntityUnitOfWork<SalesOrderDetail>(context.SalesOrderDetails);

			IQueryable<SalesOrderDetail> result = null;

			if (loadAll)
				result = uow.Queries().Query((os) => from s in os select s);
			else
				result = uow.Queries().Query((os) => (from s in os select s).Take(100));

			if (this.View.Model == null)
				this.View.Model = new LargeResultSetModel();
			this.View.Model.SalesOrderDetails = result;
		}
	}

	[PresenterBinding(typeof(LargeResultSetPresenter))]
	public partial class LargeResultSet : DemoViewPage<LargeResultSetModel>, ILargeResultSetView
	{
		public event DataEventHandler<bool> Refresh;

		public override string Description
		{
			get { return ""; }
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			if (this.Model == null)
				return;

			this.gvw.DataSource = this.Model.SalesOrderDetails.ToList();
			this.gvw.DataBind();
		}

		protected virtual void OnRefresh(DataEventArgs<bool> e)
		{
			if (Refresh != null)
				Refresh(this, e);
		}

		protected void btn_Click(object sender, EventArgs e)
		{
			this.gvw.PageIndex = 0;
			this.OnRefresh(new DataEventArgs<bool>(this.rbl.SelectedValue == "A"));
		}

		protected void gvw_PageIndexChanging(object sender, GridViewPageEventArgs e)
		{
			this.gvw.PageIndex = e.NewPageIndex;
			this.OnRefresh(new DataEventArgs<bool>(this.rbl.SelectedValue == "A"));
		}
	}
}


text:
'use babel'

import {React} from 'react-for-atom';
import store from '../redux/Store';
import {refreshGenerators, runGenerator} from '../redux/Actions';

export default React.createClass({
  getInitialState: function() {
    return this.getUpdatedState();
  },
  componentDidMount: function() {
    this.unsubscribe = store.subscribe(this.updateGenerators);
    store.dispatch(refreshGenerators());
  },
  componentWillUnmount: function() {
    this.unsubscribe();
  },
  updateGenerators: function() {
    this.setState(this.getUpdatedState());
  },
  getUpdatedState: function() {
    return {
      generators: store.getState().generators
    };
  },
  onGeneratorClick: function(namespace, name) {
    store.dispatch(runGenerator(namespace, name));
  },
  render: function() {
    return (
      React.cloneElement(this.props.children, {
        ...this.state,
        onGeneratorClick: this.onGeneratorClick
      })
    );
  }
});


text:
var Hub = require("./hub");

var EmailsView = {
  init: function() {
    this._bindToHub();
  },

  _bindToHub: function() {
    var _this = this;

    Hub.subscribe("active-email-change", function(data) {
      _this._onActiveEmailChange(data);
    });
  },

  _onActiveEmailChange: function(data) {
    this._activateEmailInListView(data.email);
    this._updatePreviewBody(data.email);
  },

  _activateEmailInListView: function(email) {
    var listItems = document.getElementsByClassName("list-group-item");

    for (var i = 0; i < listItems.length; i++) {
      listItems[i].className = "list-group-item";
    }

    document.getElementById("email-header-" + email.id).className = "list-group-item active";
  },

  _updatePreviewBody: function(email) {
    document.getElementById("preview-body").innerHTML = email.body;
  }
};

module.exports = EmailsView;


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>phpDocumentor Parser Errors and Warnings</title>
			<link rel="stylesheet" href="media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

						Post-parsing

Post-parsing

Warnings:

Warning - Class SchemalessBehavior parent ModelBehavior not found

Warning - Class SqlCompatibleBehavior parent ModelBehavior not found

Warning - Class MongodbSource parent DboSource not found

		Documentation generated on Tue, 26 Jul 2011 01:09:02 +0900 by phpDocumentor 1.4.3


text:
package org.springframework.boot.actuate.endpoint;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.Assert;

/**
 * {@link Endpoint} to expose a collection of {@link PublicMetrics}.
 *
 * @author Dave Syer
 */
@ConfigurationProperties(prefix = "endpoints.metrics", ignoreUnknownFields = false)
public class MetricsEndpoint extends AbstractEndpoint<Map<String, Object>> {

	private final List<PublicMetrics> publicMetrics;

	/**
	 * Create a new {@link MetricsEndpoint} instance.
	 * @param publicMetrics the metrics to expose
	 */
	public MetricsEndpoint(PublicMetrics publicMetrics) {
		this(Collections.singleton(publicMetrics));
	}

	/**
	 * Create a new {@link MetricsEndpoint} instance.
	 * @param publicMetrics the metrics to expose. The collection will be sorted using the
	 * {@link AnnotationAwareOrderComparator}.
	 */
	public MetricsEndpoint(Collection<PublicMetrics> publicMetrics) {
		super("metrics");
		Assert.notNull(publicMetrics, "PublicMetrics must not be null");
		this.publicMetrics = new ArrayList<PublicMetrics>(publicMetrics);
		AnnotationAwareOrderComparator.sort(this.publicMetrics);
	}

	public void registerPublicMetrics(PublicMetrics metrics) {
		this.publicMetrics.add(metrics);
		AnnotationAwareOrderComparator.sort(this.publicMetrics);
	}

	public void unregisterPublicMetrics(PublicMetrics metrics) {
		this.publicMetrics.remove(metrics);
	}

	@Override
	public Map<String, Object> invoke() {
		Map<String, Object> result = new LinkedHashMap<String, Object>();
		List<PublicMetrics> metrics = new ArrayList<PublicMetrics>(this.publicMetrics);
		for (PublicMetrics publicMetric : metrics) {
			try {
				for (Metric<?> metric : publicMetric.metrics()) {
					result.put(metric.getName(), metric.getValue());
				}
			}
			catch (Exception e) {
				// Could not evaluate metrics
			}
		}
		return result;
	}

}


text:
[![Build Status](https://travis-ci.com/nikku/angular-data-depend.png?branch=master)](https://travis-ci.com/nikku/angular-data-depend)

A toolkit for implementing complex, data heavy [AngularJS](http://angularjs.org/) applications.

## Features

__dataDepend__ allows you handle complex data dependencies via _data providers_ and _data observers_.

*   It allows you to make data dependencies in explicit
*   It takes care of resolving only the required data in the correct order
*   It updates dependent data upon changes
*   It gives you feedback on the load state of the data

## Overview

Use __dataDepend__ to structure your application into _providers_ and _observers_ and let the library do all the rest.

```javascript
function MyController($scope, Article, Comment, Authentication, dataDepend) {

  var $data = dataDepend.create($scope);

  // providers ///////////

  $data.provide('articleId', 22);
  $data.provide('currentUser', Authentication.currentUser());

  $data.provide('article', ['articleId', function(id) {
    return Article.get({ id: id }).$promise;
  }]);

  $data.provide('recommendations', ['article', 'currentUser', function(article, comments, currentUser) {
    return Article.queryRecommended({ article: article, user: currentUser }).$promise;
  }]);

  // consumers ///////////

  function updateView(article, recommendations) {
    // update current scope
  }

  // $scope.view keeps track of current loading state
  // and provides access to loaded variable
  $scope.view = $data.observe(['article', 'recommendations', updateView]);
}
```

## Resources

-   [Website](http://nikku.github.io/angular-data-depend/)
-   [Issue tracker](https://github.com/Nikku/angular-data-depend/issues)

## Usage

Create a new data container:

```javascript
var $data = dataDepend.create($scope);
```

#### Providers

Providers compute, fetch or statically supply the application with a named data items.
Register a data provider via `#provide(name, definition | value)`. The simples provider is the static one, producing a primitive or object value:

```javascript
$data.provide('articleId', 22);
```

The values produced by static providers may be updated via `$data.set(name, value)`;

A dynamic provider is a function that returns either the value or a [promise](http://docs.angularjs.org/api/ng.$q#description_the-promise-api):

```
$data.provide('articleFromBackend', function() {
  return $http.get('/the-one-and-only-article').then(function(response) {
    return response.data
  });
});
```

Dynamic providers may declare dependencies on other data items (in a [$injector](http://docs.angularjs.org/api/AUTO.$injector) compatible format):

```javascript
$data.provide('article', ['articleId', function(id) {
  return $http.get('/articles/' + id).then(function(response) {
    return response.data
  });
}]);
```

#### Observers

Observers get notified whenever a set of data items change.
They track the load status of these items, trigger their evaluation and should be used as the end points to bind data items to the view scope.

Register an observer via `#observe(definition)`:

```javascript
var handle = $data.observe(['article', 'articleDetails', function(article, articleDetails) {
  $scope.article = article;
  $scope.articleDetails = articleDetails;
}]);
```

Registering an observer via `#observe()` returns a handle to the created observer. The handle can be used to query the status of the observed data:

```javascript
handle.$loaded; // false if any of the required data elements are currently loading
handle.$error;  // error if any occured during loading the observed dependencies
```

#### Notes

To re-use a data container in a child scope, a child instance bound to the specific scope should be created:

```javascript
var $childData = $data.newChild(childScope);
```

This ensures that all observer and producer bindings registered in the child scope are properly cleaned up.

## Building the Project

1.   Fork + clone [the repository](https://github.com/Nikku/angular-data-depend).
2.   Install dependencies via `npm install`.
3.   Build the library via `grunt`.

## License

Use under terms of MIT license.


text:
import { IDictionary } from "common-types";
import { SerializedQuery } from "serialized-query";
import { ISchemaHelper } from "./mocking-types";

export type RtdbQuery = import("@firebase/database-types").Query;
export type RtdbReference = import("@firebase/database-types").Reference;
export type RtdbDataSnapshot = import("@firebase/database-types").DataSnapshot;
export type RtdbThenableReference = import("@firebase/database-types").ThenableReference;
export type RtdbEventType = import("@firebase/database-types").EventType;
export type FirebaseDatabase = import("@firebase/database-types").FirebaseDatabase;

export interface ISchema {
  id: string;
  /** path to the database which is the root for given schema list */
  path: () => string;
  /** mock generator function */
  fn: () => IDictionary;
  /**
   * the name of the entity being mocked, if not set then schema name
   * is assume to equal model name
   */
  modelName?: string;
  /** a static path that preceeds this schema's placement in the database */
  prefix?: string;
}

export interface IRelationship {
  id: string;
  /** cardinality type */
  type: "hasMany" | "belongsTo";
  /** the source model */
  source: string;
  /**
   * the property on the source model which is the FK
   * (by default it will use standard naming conventions)
   */
  sourceProperty: string;
  /** the model being referred to in the source model's FK */
  target: string;
}

/** Queued up schema's ready for generation */
export interface IQueue {
  id: string;
  schema: string;
  quantity: number;
  hasMany?: IDictionary<number>;
  overrides?: IDictionary;
  prefix: string;
  /** the key refers to the property name, the value true means "fulfill" */
  belongsTo?: IDictionary<boolean>;
}

/** A Schema's mock callback generator must conform to this type signature */
export type SchemaCallback<T = any> = (helper: ISchemaHelper<T>) => () => T;

/**
 * Captures a CRUD event
 */
export interface IMockWatcherGroupEvent {
  /** the unique identifier of the listener */
  listenerId: string;
  /** the path that the listener is listening at */
  listenerPath: string;
  /** the event which is being listened to */
  listenerEvent: import(/* webpackChunkName: "firebase-db-types" */ "@firebase/database-types").EventType;
  /** the dispatch function for this listener */
  callback: IFirebaseEventHandler;
  /** the path where the event took place */
  eventPaths: string[];
  /** the "key" of the event; this applied to value AND child events */
  key: string;
  /** changes between value and priorValue */
  changes: any;
  /** the new value which has been set */
  value: any;
  /** the prior value that this property held previous to the event */
  priorValue: any;
}

/**
 * A change event which is fired from Firebase; the specific signature
 * of the event depends on the event type being fired.
 *
 * events: [API Spec](https://firebase.google.com/docs/reference/node/firebase.database.Reference#on)
 *
 * @param snap the DBRtdbDataSnapshot which provides access to the root of the `on` event;
 * in the case of a _removal_ you will get snapshot of the prior value
 * @param prevChildKey provided on `child_changed`, `child_moved`, and `child_added`; gives the
 * name of the key which directly _preceeds_ the event key in Firebase's stored order
 */
export interface IFirebaseEventHandler {
  (snap: RtdbDataSnapshot, prevChildKey?: string): void;
}

export type EventHandler =
  | HandleValueEvent
  | HandleNewEvent
  | HandleRemoveEvent;
export type GenericEventHandler = (
  snap: RtdbDataSnapshot,
  key?: string
) => void;
export type HandleValueEvent = (dataSnapShot: RtdbDataSnapshot) => void;
export type HandleNewEvent = (
  childSnapshot: RtdbDataSnapshot,
  prevChildKey: string
) => void;
export type HandleRemoveEvent = (oldChildSnapshot: RtdbDataSnapshot) => void;
export type HandleMoveEvent = (
  childSnapshot: RtdbDataSnapshot,
  prevChildKey: string
) => void;
export type HandleChangeEvent = (
  childSnapshot: RtdbDataSnapshot,
  prevChildKey: string
) => void;

export type QueryValue = number | string | boolean | null;

export interface IListener {
  /** random string */
  id: string;
  /** the _query_ the listener is based off of */
  query: SerializedQuery;

  eventType: RtdbEventType;
  callback: (a: RtdbDataSnapshot | null, b?: string) => any;
  cancelCallbackOrContext?: object | null;
  context?: object | null;
}


text:
layout: post
title: Using moving averages to improve fanduel predictions
excerpt: "Improving performance to 94%"
modified: 2015-07-16
tags: [random forest, svm, tf-idf, nlp, natural language processing, python, statistics, metis]
comments: true
image:
  feature: banner1.jpg
  credit: WeGraphics
  creditlink: http://wegraphics.net/downloads/free-ultimate-blurred-background-pack/
---
### Intro
[Project link][1]

Ok, last night was my first post around fanduel and it had me very excited!  I was able to create a model that explained 76% of the variation in the fanduel scores I was seeing on a nightly basis!  But there were so many other things I wanted to try that would improve predictive accuracy; one of them being moving averages!  This post details how I used moving averages to improve the model's explanation of variations in fanduel scores to 94%!

### What's a moving average?
A [moving average][2] is just an average that keeps updating as new data is available.  For example, a 3 day moving average takes your data from the last 3 days and computes and average.  The next day, the previous 3 days of data are used to compute and updated moving average.  Moving averages can help to identify trends.

Why do we care? Because basketball, just like any sport, is about hot and cold streaks.  Sure, Russell Westbrook is phenomenal all year long, but there's definitely periods where he is doing better and worse.  If Kevin Durant is playing, Westbrooks moving averages are going to likely be lower than when Kevin Durant was injured, and the moving average calculations are going to capture that!

In the context of this analysis, I am going to start by creating a moving average based on just the player's fanduel scores.  So in Westbrook's case, I will be saying "what were his average fanduel points for the last 3 games, 5 games, 10 games?"

### Calculating our moving average
In order to calculate a moving average, pandas makes it very easy.  There is a [rolling_mean][3] function that you can call which calculates a moving average for you.  You just need to specify the column and the number of periods.

In order to do this, you must first sort your data by player name, and then by date, so that performances are ordered properly.  The code to sort and calculate a moving average is below:

{% highlight python %}
# data must be grouped first
# sorting the data
df_sorted = df.sort(['PLAYER', 'DATE'], ascending=[True, True])

# creating the moving averages
df_sorted['past_1'] = pd.rolling_mean(df_sorted['fanduel_score'], 1)
df_sorted['past_3'] = pd.rolling_mean(df_sorted['fanduel_score'], 3)
df_sorted['past_5'] = pd.rolling_mean(df_sorted['fanduel_score'], 5)
df_sorted['past_10'] = pd.rolling_mean(df_sorted['fanduel_score'], 10)

{% endhighlight %}

So this is great, but you'll notice now that there are NaNs for some of the moving average values.  For example, on our first very data point for a player, we see that none of the moving averages compute because there isn't any previous data to compute on.  So if we are in the first 5 games of a season for a player, we aren't going to be able to compuate a 10 game moving average.  In these cases, I think imputing a season mean or the moving average from the next most recent moving average would be appropriate.

### Predicting
Ok, now assuming we have already split our data into training and test or are going to do cross validation, it's time to predict!  I'm using all the same features as yesterday, but will now add the moving averages in today.  I wasn't able to get the log transform to work on this data set, so I will be using the regular fanduel score as the dependent variable.  Another note is that I did not have time to impute the season averages or any other missing values from the moving average computation, so I have just dropped rows that contain NaN.  Not ideal, but I will fix this in the long run.  Still, there are many players and games that can still be predicted and the results are great.

As yesterday, I'm just using the [SVM regressor][4] with the RBF kernel.  Not tuning the C or Gamma parameters yet.

**Results:** 94% r-squared! Very great score for again somewhat minimal work.  I'll be pretty pleased if on average I can explain 94% of variations in fanduel scores with this model.  By the time we are two or so weeks into the season, my model should be outputting great scores!

{% highlight python %}
from sklearn.svm import SVR

model_SVR_rbf = SVR(kernel='rbf', C=.5)
model_SVR_rbf.fit(x_train, y_train)
model_SVR_rbf.score(x_test, y_test)

{% endhighlight %}

### Next steps
One input that seriously helps our prediction is the number of minutes that a player plays on a given night.  Very predictive.  But this isn't known beforehand and minutes can often be a factor of how well a player is playing that night.  Some work will need to be done to look at the distribution of minutes for players who start.  If this is fairly small, then I would like to introduce a 'Starter' variable which indicates whether a player is starting or not.

Another way to predict minutes is to look for inuries.  If a starting PG goes down with an injury, the backup PG is almost guaranteed to see his minutes jump from around 15-20 to 35-40, thus increasing fanduel production.  This is a very important strategy when crafting your lineups, and I'll be looking to automate this step in the future.

~ Trevor

[1]: https://github.com/trevor-smith/fanduel_nba
[2]: https://en.wikipedia.org/wiki/Moving_average
[3]: http://pandas.pydata.org/pandas-docs/stable/computation.html#moving-rolling-statistics-moments
[4]: http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html#sklearn.svm.SVR
[5]: https://twitter.com/bo_p
[6]: https://twitter.com/planarrowspace


text:
"""
Unit tests for the da.check.pytest module.

---
type:
    python_module

validation_level:
    v00_minimum

protection:
    k00_public

copyright:
    "Copyright 2016 High Integrity Artificial Intelligence Systems"

license:
    "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."
...
"""

# =============================================================================
class SpecifyCoro:
    """
    Specify the da.check.pytest.coro() function.

    """

    # -------------------------------------------------------------------------
    def it_returns_something(self):
        """
        The coro() function returns a value that is not None.

        """
        import da.check.pytest
        assert da.check.pytest.coro(None, None) is not None

# =============================================================================
class Specify_ReportUnitTestFailure:
    """
    Specify the da.check.pytest._report_unit_test_failure() function

    """

    # -------------------------------------------------------------------------
    def it_is_callable(self):
        """
        The _report_unit_test_failure() function is callable.

        """
        import da.check.pytest
        assert callable(da.check.pytest._report_unit_test_failure)

# =============================================================================
class Specify_CheckStaticCoverage:
    """
    Specify the da.check.pytest._check_static_coverage() function

    """

    # -------------------------------------------------------------------------
    def it_is_callable(self):
        """
        The _check_static_coverage() function is callable.

        """
        import da.check.pytest
        assert callable(da.check.pytest._check_static_coverage)


text:
An example of Named Queries is their user by the iiif.ly application to generate a manifest from a set of images.

When it registers the end user's images, iiif.ly assigns metadata to group images together, and to preserve the order.

The iiif.ly customer (API user) has configured a Named Query to return a IIIF manifest.

Template: https://dlcs.io/resource/{customer}/{query-name}/{space-name}/{string1}

The **Named Query** – in response to requests that match this template,
1. Select all the images in {space-name} with a string1 value of {string1} and order them by {number1}
2. Project the images into a manifest with one sequence where each canvas in the sequence corresponds to one image

Example:

https://dlcs.io/resource/4/iiifly/28EC11C6/a5425f9b

http://universalviewer.io/?manifest=https://dlcs.io/resource/4/iiifly/28EC11C6/a5425f9b


text:
/* ------------------------------------------------------------------------- */
/*
 *  uri.h
 *
 *  Copyright (c) 2004 - 2009, clown. All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *    - Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    - Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *    - No names of its contributors may be used to endorse or promote
 *      products derived from this software without specific prior written
 *      permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 *  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  Last-modified: Tue 03 Nov 2009 21:53:03 JST
 */
/* ------------------------------------------------------------------------- */
#ifndef CLX_URI_H
#define CLX_URI_H

#include "config.h"
#include <string>
#include <iterator>
#include "literal.h"
#include "lexical_cast.h"
#include "convert.h"
#include "uri_convert.h"

namespace clx {
	namespace uri {
		/* ----------------------------------------------------------------- */
		//  encode
		/* ----------------------------------------------------------------- */
		template <class InIter, class OutIter>
		inline OutIter encode(InIter first, InIter last, OutIter result) {
			clx::basic_uri_encoder<typename InIter::value_type> f;
			return clx::convert(first, last, result, f);
		}

		/* ----------------------------------------------------------------- */
		//  encode
		/* ----------------------------------------------------------------- */
		template <class Ch, class Tr>
		inline std::basic_string<Ch, Tr> encode(const std::basic_string<Ch, Tr>& src) {
			clx::basic_uri_encoder<Ch, Tr> f;
			return clx::convert(src, f);
		}

		/* ----------------------------------------------------------------- */
		//  encode
		/* ----------------------------------------------------------------- */
		template <class CharT>
		inline std::basic_string<CharT> encode(const CharT* src) {
			clx::basic_uri_encoder<CharT> f;
			return clx::convert(src, f);
		}

		/* ----------------------------------------------------------------- */
		//  decode
		/* ----------------------------------------------------------------- */
		template <class InIter, class OutIter>
		inline OutIter decode(InIter first, InIter last, OutIter result) {
			clx::basic_uri_decoder<typename InIter::value_type> f;
			return clx::convert(first, last, result, f);
		}

		/* ----------------------------------------------------------------- */
		//  decode
		/* ----------------------------------------------------------------- */
		template <class Ch, class Tr>
		inline std::basic_string<Ch, Tr> decode(const std::basic_string<Ch, Tr>& src) {
			clx::basic_uri_decoder<Ch, Tr> f;
			return clx::convert(src, f);
		}

		/* ----------------------------------------------------------------- */
		//  decode
		/* ----------------------------------------------------------------- */
		template <class CharT>
		inline std::basic_string<CharT> decode(const CharT* src) {
			clx::basic_uri_decoder<CharT> f;
			return clx::convert(src, f);
		}
	};
}

#endif


text:
import random

from sanic import Sanic
from sanic.response import json
from ujson import loads

def test_storage():
    app = Sanic('test_text')

    @app.middleware('request')
    def store(request):
        request['user'] = 'sanic'
        request['sidekick'] = 'tails'
        del request['sidekick']

    @app.route('/')
    def handler(request):
        return json({'user': request.get('user'), 'sidekick': request.get('sidekick')})

    request, response = app.test_client.get('/')

    response_json = loads(response.text)
    assert response_json['user'] == 'sanic'
    assert response_json.get('sidekick') is None

def test_app_injection():
    app = Sanic('test_app_injection')
    expected = random.choice(range(0, 100))

    @app.listener('after_server_start')
    async def inject_data(app, loop):
        app.injected = expected

    @app.get('/')
    async def handler(request):
        return json({'injected': request.app.injected})

    request, response = app.test_client.get('/')

    response_json = loads(response.text)
    assert response_json['injected'] == expected


text:
/* jshint plusplus: false */

exports.override = function override(obj, prop, fun) {
  function mock(fun) {
    var old = obj[prop];
    var wrapper = function() {
      wrapper.called = true;
      wrapper.calledTimes++;
      return fun.apply(this, arguments);
    };
    wrapper.called = false;
    wrapper.calledTimes = 0;
    wrapper.old = old;
    obj[prop] = wrapper;
  }
  if(fun) {
    return function() {
      mock(fun);
    };
  } else {
    return function(fun) {
      mock(fun);
    };
  }
};

exports.restore = function restore(obj, prop, full) {
  return function() {
    obj[prop] = obj[prop].old;
    while(full && obj[prop].old) {
      obj[prop] = obj[prop].old;
    }
  };
};


text:
"""Utility for changing directories and execution of commands in a subshell."""
from __future__ import print_function

import os
import shlex
import subprocess

# Store the previous working directory for the 'cd -' command.

class Holder:
    """Holds the _prev_dir_ class attribute for chdir() function."""
    _prev_dir_ = None

    @classmethod
    def prev_dir(cls):
        return cls._prev_dir_

    @classmethod
    def swap(cls, dir):
        cls._prev_dir_ = dir

def chdir(debugger, args, result, dict):
    """Change the working directory, or cd to ${HOME}.
    You can also issue 'cd -' to change to the previous working directory."""
    new_dir = args.strip()
    if not new_dir:
        new_dir = os.path.expanduser('~')
    elif new_dir == '-':
        if not Holder.prev_dir():
            # Bad directory, not changing.
            print("bad directory, not changing")
            return
        else:
            new_dir = Holder.prev_dir()

    Holder.swap(os.getcwd())
    os.chdir(new_dir)
    print("Current working directory: %s" % os.getcwd())

def system(debugger, command_line, result, dict):
    """Execute the command (a string) in a subshell."""
    args = shlex.split(command_line)
    process = subprocess.Popen(
        args,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    output, error = process.communicate()
    retcode = process.poll()
    if output and error:
        print("stdout=>\n", output)
        print("stderr=>\n", error)
    elif output:
        print(output)
    elif error:
        print(error)
    print("retcode:", retcode)


text:
import { AppPage } from './app.po';

describe('build-in-angular-aria App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to app!');
  });
});


text:
// ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
//  2008/05/14  Martin D. Flynn
//     -Initial release
// ----------------------------------------------------------------------------
package org.opengts.geocoder;

import org.opengts.util.*;

import org.opengts.dbtools.*;
import org.opengts.db.*;
import org.opengts.db.tables.Account;

public abstract class GeocodeProviderAdapter
    implements GeocodeProvider
{

    // ------------------------------------------------------------------------

    public static final String PROP_GeocodeProvider_        = "GeocodeProvider.";
    public static final String _PROP_isEnabled              = ".isEnabled";

    // ------------------------------------------------------------------------

    private String       name           = null;
    private TriState     isEnabled      = TriState.UNKNOWN;

    private String       accessKey      = null;
    private RTProperties properties     = null;

    /**
    *** Constructor
    *** @param name    The name of this GeocodeProvider
    *** @param key     The access key (may be null)
    *** @param rtProps The properties (may be null)
    **/
    public GeocodeProviderAdapter(String name, String key, RTProperties rtProps)
    {
        super();
        this.setName(name);
        this.setAuthorization(key);
        this.setProperties(rtProps);
    }

    // ------------------------------------------------------------------------

    /**
    *** Sets the name of this GeocodeProvider
    *** @param name  The name of this geocode provider
    **/
    public void setName(String name)
    {
        this.name = (name != null)? name : "";
    }

    /**
    *** Gets the name of this GeocodeProvider
    *** @return  The name of this geocode provider
    **/
    public String getName()
    {
        return (this.name != null)? this.name : "";
    }

    // ------------------------------------------------------------------------

    /**
    *** Sets the authorization key of this GeocodeProvider
    *** @param key  The key of this geocode provider
    **/
    public void setAuthorization(String key)
    {
        this.accessKey = key;
    }

    /**
    *** Gets the authorization key of this GeocodeProvider
    *** @return The access key of this geocode provider
    **/
    public String getAuthorization()
    {
        return this.accessKey;
    }

    // ------------------------------------------------------------------------

    /**
    *** Parse and return the user name and password
    *** @return The username and password (always a 2 element array)
    **/
    protected String[] _getUserPass()
    {
        String username = null;
        String password = null;
        String key = this.getAuthorization();
        if ((key != null) && !key.equals("")) {
            int p = key.indexOf(":");
            if (p >= 0) {
                username = key.substring(0,p);
                password = key.substring(p+1);
            } else {
                username = key;
                password = "";
            }
        } else {
            username = null;
            password = null;
        }
        return new String[] { username, password };
    }

    /**
    *** Return authorization username.  This assumes that the username and password are
    *** separated by a ':' character
    *** @return The username
    **/
    protected String getUsername()
    {
        return this._getUserPass()[0];
    }

    /**
    *** Return authorization password.  This assumes that the username and password are
    *** separated by a ':' character
    *** @return The password
    **/
    protected String getPassword()
    {
        return this._getUserPass()[1];
    }

    // ------------------------------------------------------------------------

    /**
    *** Sets the properties for this ReverseGeocodeProvider
    *** @param rtProps  The properties for this reverse-geocode provider
    **/
    public void setProperties(RTProperties rtProps)
    {
        this.properties = rtProps;
    }

    /**
    *** Gets the properties for this ReverseGeocodeProvider
    *** @return The properties for this reverse-geocode provider
    **/
    public RTProperties getProperties()
    {
        if (this.properties == null) {
            this.properties = new RTProperties();
        }
        return this.properties;
    }

    // ------------------------------------------------------------------------
    // ------------------------------------------------------------------------

    /**
    *** Returns true if this ReverseGeocodeProvider is enabled
    *** @return True if enabled
    **/
    public boolean isEnabled()
    {
        if (this.isEnabled.isUnknown()) {
            String key = PROP_GeocodeProvider_ + this.getName() + _PROP_isEnabled;
            if (RTConfig.getBoolean(key,true)) {
                this.isEnabled = TriState.TRUE;
            } else {
                this.isEnabled = TriState.FALSE;
                Print.logWarn("GeocodeProvider disabled: " + this.getName());
            }
        }
        //Print.logInfo("Checking RGP 'isEnabled': " + this.getName() + " ==> " + this.isEnabled.isTrue());
        return this.isEnabled.isTrue();
    }

    // ------------------------------------------------------------------------

    /* GeocodeProvider interface methods */
    public abstract boolean isFastOperation();
    public abstract GeoPoint getGeocode(String address, String country);

    // ------------------------------------------------------------------------
    // ------------------------------------------------------------------------

    private static final String ARG_ACCOUNT[]   = new String[] { "account"          , "acct"       };
    private static final String ARG_PLN[]       = new String[] { "privateLabelName" , "pln" , "pl" };
    private static final String ARG_ADDRESS[]   = new String[] { "address"          , "addr", "a"  };
    private static final String ARG_COUNTRY[]   = new String[] { "country"          , "c"          };

    private static void usage()
    {
        String n = ReverseGeocodeProviderAdapter.class.getName();
        Print.sysPrintln("");
        Print.sysPrintln("Description:");
        Print.sysPrintln("   Geocode Testing Tool ...");
        Print.sysPrintln("");
        Print.sysPrintln("Usage:");
        Print.sysPrintln("   java ... " + n + " -address=<addr> -account=<id>");
        Print.sysPrintln(" or");
        Print.sysPrintln("   java ... " + n + " -address=<addr> -pln=<name>");
        Print.sysPrintln("");
        Print.sysPrintln("Common Options:");
        Print.sysPrintln("   -address=<addr>    Address to Geocode");
        Print.sysPrintln("   -country=<country> Country to Geocode");
        Print.sysPrintln("   -account=<id>      Acount ID from which to obtain the GeocodeProvider");
        Print.sysPrintln("   -pln=<name>        PrivateLabel name/host");
        Print.sysPrintln("");
        System.exit(1);
    }

    public static void _main()
    {

        /* Address */
        String country = RTConfig.getString(ARG_COUNTRY,"").replace('_',' ');
        String addr    = RTConfig.getString(ARG_ADDRESS,"").replace('_',' ');
        if (StringTools.isBlank(addr)) {
            Print.sysPrintln("ERROR: No Address specified");
            usage();
        }
        Print.logInfo("Address = " + addr);
        Print.logInfo("Country = " + country);

        /* get PrivateLabel */
        BasicPrivateLabel privLabel = null;
        String accountID = RTConfig.getString(ARG_ACCOUNT, "");
        if (!StringTools.isBlank(accountID)) {
            Account acct = null;
            try {
                acct = Account.getAccount(accountID); // may throw DBException
                if (acct == null) {
                    Print.sysPrintln("ERROR: Account-ID does not exist: " + accountID);
                    usage();
                }
                privLabel = acct.getPrivateLabel();
            } catch (DBException dbe) {
                Print.logException("Error loading Account: " + accountID, dbe);
                //dbe.printException();
                System.exit(99);
            }
        } else {
            String pln = RTConfig.getString(ARG_PLN,"default");
            if (StringTools.isBlank(pln)) {
                Print.sysPrintln("ERROR: Must specify '-account=<Account>'");
                usage();
            } else {
                privLabel = BasicPrivateLabelLoader.getPrivateLabel(pln);
                if (privLabel == null) {
                    Print.sysPrintln("ERROR: PrivateLabel name not found: %s", pln);
                    usage();
                }
            }
        }

        /* get reverse-geocoder */
        GeocodeProvider rgp = privLabel.getGeocodeProvider();
        if (rgp == null) {
            Print.sysPrintln("ERROR: No GeocodeProvider for PrivateLabel: %s", privLabel.getName());
            System.exit(99);
        } else
        if (!rgp.isEnabled()) {
            Print.sysPrintln("WARNING: GeocodeProvider disabled: " + rgp.getName());
            System.exit(0);
        }

        /* get Geocode */
        try {
            // make sure the Domain properties are available to RTConfig
            privLabel.pushRTProperties();   // stack properties (may be redundant in servlet environment)
            GeoPoint geop = rgp.getGeocode(addr, country); // get the geocode
            if (geop != null) {
                Print.sysPrintln("");
                Print.sysPrintln("Geocode:");
                Print.sysPrintln(geop.toString());
                Print.sysPrintln("");
            } else {
                Print.sysPrintln("ERROR: Unable to obtain Geocode for specified address: " + addr);
            }
        } catch (Throwable th) {
            // ignore
        } finally {
            privLabel.popRTProperties();    // remove from stack
        }

    }

    public static void main(String args[])
    {
        DBConfig.cmdLineInit(args,true);  // main
        GeocodeProviderAdapter._main();
    }

}


text:
class Profile;

namespace base {
class DictionaryValue;
}

namespace extensions {

// A specialization of the ExternalProvider that uses
// prefs::kExtensionInstallForceList to look up which external extensions are
// registered.
class ExternalPolicyLoader
    : public ExternalLoader,
      public content::NotificationObserver {
 public:
  explicit ExternalPolicyLoader(Profile* profile);

  // content::NotificationObserver implementation
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  // Adds an extension to be updated to the pref dictionary.
  static void AddExtension(base::DictionaryValue* dict,
                           const std::string& extension_id,
                           const std::string& update_url);

 protected:
  virtual void StartLoading() OVERRIDE;

 private:
  friend class base::RefCountedThreadSafe<ExternalLoader>;

  virtual ~ExternalPolicyLoader() {}

  PrefChangeRegistrar pref_change_registrar_;
  content::NotificationRegistrar notification_registrar_;

  Profile* profile_;

  DISALLOW_COPY_AND_ASSIGN(ExternalPolicyLoader);
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_EXTERNAL_POLICY_LOADER_H_


text:
require 'spec_helper'

RSpec.describe Clusters::Cluster, :use_clean_rails_memory_store_caching do
  include ReactiveCachingHelpers
  include KubernetesHelpers

  it_behaves_like 'having unique enum values'

  subject { build(:cluster) }

  it { is_expected.to include_module(HasEnvironmentScope) }
  it { is_expected.to belong_to(:user) }
  it { is_expected.to belong_to(:management_project).class_name('::Project') }
  it { is_expected.to have_many(:cluster_projects) }
  it { is_expected.to have_many(:projects) }
  it { is_expected.to have_many(:cluster_groups) }
  it { is_expected.to have_many(:groups) }
  it { is_expected.to have_many(:groups_projects) }
  it { is_expected.to have_one(:provider_gcp) }
  it { is_expected.to have_one(:provider_aws) }
  it { is_expected.to have_one(:platform_kubernetes) }
  it { is_expected.to have_one(:application_helm) }
  it { is_expected.to have_one(:application_ingress) }
  it { is_expected.to have_one(:application_prometheus) }
  it { is_expected.to have_one(:application_runner) }
  it { is_expected.to have_many(:kubernetes_namespaces) }
  it { is_expected.to have_one(:cluster_project) }
  it { is_expected.to have_many(:deployment_clusters) }
  it { is_expected.to have_many(:metrics_dashboard_annotations) }
  it { is_expected.to have_many(:successful_deployments) }
  it { is_expected.to have_many(:environments).through(:deployments) }

  it { is_expected.to delegate_method(:status).to(:provider) }
  it { is_expected.to delegate_method(:status_reason).to(:provider) }
  it { is_expected.to delegate_method(:on_creation?).to(:provider) }
  it { is_expected.to delegate_method(:knative_pre_installed?).to(:provider) }
  it { is_expected.to delegate_method(:active?).to(:platform_kubernetes).with_prefix }
  it { is_expected.to delegate_method(:rbac?).to(:platform_kubernetes).with_prefix }
  it { is_expected.to delegate_method(:available?).to(:application_helm).with_prefix }
  it { is_expected.to delegate_method(:available?).to(:application_ingress).with_prefix }
  it { is_expected.to delegate_method(:available?).to(:application_prometheus).with_prefix }
  it { is_expected.to delegate_method(:available?).to(:application_knative).with_prefix }
  it { is_expected.to delegate_method(:external_ip).to(:application_ingress).with_prefix }
  it { is_expected.to delegate_method(:external_hostname).to(:application_ingress).with_prefix }

  it { is_expected.to respond_to :project }

  describe 'applications have inverse_of: :cluster option' do
    let(:cluster) { create(:cluster) }
    let!(:helm) { create(:clusters_applications_helm, cluster: cluster) }

    it 'does not do a third query when referencing cluster again' do
      expect { cluster.application_helm.cluster }.not_to exceed_query_limit(2)
    end
  end

  describe '.enabled' do
    subject { described_class.enabled }

    let!(:cluster) { create(:cluster, enabled: true) }

    before do
      create(:cluster, :disabled)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.disabled' do
    subject { described_class.disabled }

    let!(:cluster) { create(:cluster, :disabled) }

    before do
      create(:cluster, enabled: true)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.user_provided' do
    subject { described_class.user_provided }

    let!(:cluster) { create(:cluster_platform_kubernetes).cluster }

    before do
      create(:cluster_provider_gcp, :created)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.gcp_provided' do
    subject { described_class.gcp_provided }

    let!(:cluster) { create(:cluster_provider_gcp, :created).cluster }

    before do
      create(:cluster, :provided_by_user)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.gcp_installed' do
    subject { described_class.gcp_installed }

    let!(:cluster) { create(:cluster_provider_gcp, :created).cluster }

    before do
      create(:cluster, :providing_by_gcp)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.aws_provided' do
    subject { described_class.aws_provided }

    let!(:cluster) { create(:cluster_provider_aws, :created).cluster }

    before do
      create(:cluster, :provided_by_user)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.aws_installed' do
    subject { described_class.aws_installed }

    let!(:cluster) { create(:cluster_provider_aws, :created).cluster }

    before do
      errored_provider = create(:cluster_provider_aws)
      errored_provider.make_errored!("Error message")
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.managed' do
    subject do
      described_class.managed
    end

    context 'cluster is not managed' do
      let!(:cluster) { create(:cluster, :not_managed) }

      it { is_expected.not_to include(cluster) }
    end

    context 'cluster is managed' do
      let!(:cluster) { create(:cluster) }

      it { is_expected.to include(cluster) }
    end
  end

  describe '.with_management_project' do
    subject { described_class.with_management_project }

    context 'cluster has a management project' do
      let!(:cluster) { create(:cluster, :management_project) }

      it { is_expected.to include(cluster) }
    end

    context 'cluster does not have a management project' do
      let!(:cluster) { create(:cluster) }

      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.with_application_prometheus' do
    subject { described_class.with_application_prometheus }

    let!(:cluster) { create(:cluster) }

    context 'cluster has prometheus application' do
      let!(:application) { create(:clusters_applications_prometheus, :installed, cluster: cluster) }

      it { is_expected.to include(cluster) }
    end

    context 'cluster does not have prometheus application' do
      let(:cluster) { create(:cluster) }

      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.with_enabled_modsecurity' do
    subject { described_class.with_enabled_modsecurity }

    let_it_be(:cluster) { create(:cluster) }

    context 'cluster has ingress application with enabled modsecurity' do
      let!(:application) { create(:clusters_applications_ingress, :installed, :modsecurity_logging, cluster: cluster) }

      it { is_expected.to include(cluster) }
    end

    context 'cluster has ingress application with disabled modsecurity' do
      let!(:application) { create(:clusters_applications_ingress, :installed, :modsecurity_disabled, cluster: cluster) }

      it { is_expected.not_to include(cluster) }
    end

    context 'cluster does not have ingress application' do
      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.with_available_elasticstack' do
    subject { described_class.with_available_elasticstack }

    let_it_be(:cluster) { create(:cluster) }

    context 'cluster has ElasticStack application' do
      let!(:application) { create(:clusters_applications_elastic_stack, :installed, cluster: cluster) }

      it { is_expected.to include(cluster) }
    end

    context 'cluster does not have ElasticStack application' do
      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.distinct_with_deployed_environments' do
    subject { described_class.distinct_with_deployed_environments }

    let_it_be(:cluster) { create(:cluster) }

    context 'cluster has multiple successful deployment with environment' do
      let!(:environment) { create(:environment) }
      let!(:deployment) { create(:deployment, :success, cluster: cluster, environment: environment) }
      let!(:deployment_2) { create(:deployment, :success, cluster: cluster, environment: environment) }

      it { is_expected.to include(cluster) }

      it 'lists only distinct environments' do
        expect(subject.first.environments.count).to eq(1)
      end
    end

    context 'cluster has only failed deployment with environment' do
      let!(:environment) { create(:environment) }
      let!(:deployment) { create(:deployment, :failed, cluster: cluster, environment: environment) }

      it { is_expected.not_to include(cluster) }
    end

    context 'cluster does not have any deployment' do
      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.with_project_alert_service_data' do
    subject { described_class.with_project_alert_service_data(project_id) }

    let!(:cluster) { create(:cluster, :project) }
    let!(:project_id) { cluster.first_project.id }

    context 'project has alert service data' do
      let!(:alerts_service) { create(:alerts_service, project: cluster.clusterable) }

      it { is_expected.to include(cluster) }
    end

    context 'project has no alert service data' do
      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.for_project_namespace' do
    subject { described_class.for_project_namespace(namespace_id) }

    let!(:cluster) { create(:cluster, :project) }
    let!(:another_cluster) { create(:cluster, :project) }
    let(:namespace_id) { cluster.first_project.namespace_id }

    it { is_expected.to contain_exactly(cluster) }
  end

  describe 'validations' do
    subject { cluster.valid? }

    context 'when validates unique_environment_scope' do
      context 'for a project cluster' do
        let(:project) { create(:project) }

        before do
          create(:cluster, projects: [project], environment_scope: 'product/*')
        end

        context 'when identical environment scope exists in project' do
          let(:cluster) { build(:cluster, projects: [project], environment_scope: 'product/*') }

          it { is_expected.to be_falsey }
        end

        context 'when identical environment scope does not exist in project' do
          let(:cluster) { build(:cluster, projects: [project], environment_scope: '*') }

          it { is_expected.to be_truthy }
        end

        context 'when identical environment scope exists in different project' do
          let(:project2) { create(:project) }
          let(:cluster) { build(:cluster, projects: [project2], environment_scope: 'product/*') }

          it { is_expected.to be_truthy }
        end
      end

      context 'for a group cluster' do
        let(:group) { create(:group) }

        before do
          create(:cluster, cluster_type: :group_type, groups: [group], environment_scope: 'product/*')
        end

        context 'when identical environment scope exists in group' do
          let(:cluster) { build(:cluster, cluster_type: :group_type, groups: [group], environment_scope: 'product/*') }

          it { is_expected.to be_falsey }
        end

        context 'when identical environment scope does not exist in group' do
          let(:cluster) { build(:cluster, cluster_type: :group_type, groups: [group], environment_scope: '*') }

          it { is_expected.to be_truthy }
        end

        context 'when identical environment scope exists in different group' do
          let(:cluster) { build(:cluster, :group, environment_scope: 'product/*') }

          it { is_expected.to be_truthy }
        end
      end

      context 'for an instance cluster' do
        before do
          create(:cluster, :instance, environment_scope: 'product/*')
        end

        context 'identical environment scope exists' do
          let(:cluster) { build(:cluster, :instance, environment_scope: 'product/*') }

          it { is_expected.to be_falsey }
        end

        context 'identical environment scope does not exist' do
          let(:cluster) { build(:cluster, :instance, environment_scope: '*') }

          it { is_expected.to be_truthy }
        end
      end
    end

    context 'when validates name' do
      context 'when provided by user' do
        let!(:cluster) { build(:cluster, :provided_by_user, name: name) }

        context 'when name is empty' do
          let(:name) { '' }

          it { is_expected.to be_falsey }
        end

        context 'when name is nil' do
          let(:name) { nil }

          it { is_expected.to be_falsey }
        end

        context 'when name is present' do
          let(:name) { 'cluster-name-1' }

          it { is_expected.to be_truthy }
        end
      end

      context 'when provided by gcp' do
        let!(:cluster) { build(:cluster, :provided_by_gcp, name: name) }

        context 'when name is shorter than 1' do
          let(:name) { '' }

          it { is_expected.to be_falsey }
        end

        context 'when name is longer than 63' do
          let(:name) { 'a' * 64 }

          it { is_expected.to be_falsey }
        end

        context 'when name includes invalid character' do
          let(:name) { '!!!!!!' }

          it { is_expected.to be_falsey }
        end

        context 'when name is present' do
          let(:name) { 'cluster-name-1' }

          it { is_expected.to be_truthy }
        end

        context 'when record is persisted' do
          let(:name) { 'cluster-name-1' }

          before do
            cluster.save!
          end

          context 'when name is changed' do
            before do
              cluster.name = 'new-cluster-name'
            end

            it { is_expected.to be_falsey }
          end

          context 'when name is same' do
            before do
              cluster.name = name
            end

            it { is_expected.to be_truthy }
          end
        end
      end
    end

    context 'when validates restrict_modification' do
      context 'when creation is on going' do
        let!(:cluster) { create(:cluster, :providing_by_gcp) }

        it { expect(cluster.update(enabled: false)).to be_falsey }
      end

      context 'when creation is done' do
        let!(:cluster) { create(:cluster, :provided_by_gcp) }

        it { expect(cluster.update(enabled: false)).to be_truthy }
      end
    end

    describe 'cluster_type validations' do
      let(:instance_cluster) { create(:cluster, :instance) }
      let(:group_cluster) { create(:cluster, :group) }
      let(:project_cluster) { create(:cluster, :project) }

      it 'validates presence' do
        cluster = build(:cluster, :project, cluster_type: nil)

        expect(cluster).not_to be_valid
        expect(cluster.errors.full_messages).to include("Cluster type can't be blank")
      end

      context 'project_type cluster' do
        it 'does not allow setting group' do
          project_cluster.groups << build(:group)

          expect(project_cluster).not_to be_valid
          expect(project_cluster.errors.full_messages).to include('Cluster cannot have groups assigned')
        end
      end

      context 'group_type cluster' do
        it 'does not allow setting project' do
          group_cluster.projects << build(:project)

          expect(group_cluster).not_to be_valid
          expect(group_cluster.errors.full_messages).to include('Cluster cannot have projects assigned')
        end
      end

      context 'instance_type cluster' do
        it 'does not allow setting group' do
          instance_cluster.groups << build(:group)

          expect(instance_cluster).not_to be_valid
          expect(instance_cluster.errors.full_messages).to include('Cluster cannot have groups assigned')
        end

        it 'does not allow setting project' do
          instance_cluster.projects << build(:project)

          expect(instance_cluster).not_to be_valid
          expect(instance_cluster.errors.full_messages).to include('Cluster cannot have projects assigned')
        end
      end
    end

    describe 'domain validation' do
      let(:cluster) { build(:cluster) }

      subject { cluster }

      context 'when cluster has domain' do
        let(:cluster) { build(:cluster, :with_domain) }

        it { is_expected.to be_valid }
      end

      context 'when cluster is not a valid hostname' do
        let(:cluster) { build(:cluster, domain: 'http://not.a.valid.hostname') }

        it 'adds an error on domain' do
          expect(subject).not_to be_valid
          expect(subject.errors[:domain].first).to eq('contains invalid characters (valid characters: [a-z0-9\\-])')
        end
      end

      context 'when cluster does not have a domain' do
        it { is_expected.to be_valid }
      end
    end

    describe 'unique scope for management_project' do
      let(:project) { create(:project) }
      let!(:cluster_with_management_project) { create(:cluster, management_project: project) }

      context 'duplicate scopes for the same management project' do
        let(:cluster) { build(:cluster, management_project: project) }

        it 'adds an error on environment_scope' do
          expect(cluster).not_to be_valid
          expect(cluster.errors[:environment_scope].first).to eq('cannot add duplicated environment scope')
        end
      end
    end
  end

  describe '.ancestor_clusters_for_clusterable' do
    let(:group_cluster) { create(:cluster, :provided_by_gcp, :group) }
    let(:group) { group_cluster.group }
    let(:hierarchy_order) { :desc }
    let(:clusterable) { project }

    subject do
      described_class.ancestor_clusters_for_clusterable(clusterable, hierarchy_order: hierarchy_order)
    end

    context 'when project does not belong to this group' do
      let(:project) { create(:project, group: create(:group)) }

      it 'returns nothing' do
        is_expected.to be_empty
      end
    end

    context 'when group has a configured kubernetes cluster' do
      let(:project) { create(:project, group: group) }

      it 'returns the group cluster' do
        is_expected.to eq([group_cluster])
      end
    end

    context 'when group and instance have configured kubernetes clusters' do
      let(:project) { create(:project, group: group) }
      let!(:instance_cluster) { create(:cluster, :provided_by_gcp, :instance) }

      it 'returns clusters in order, descending the hierachy' do
        is_expected.to eq([group_cluster, instance_cluster])
      end
    end

    context 'when sub-group has configured kubernetes cluster' do
      let(:sub_group_cluster) { create(:cluster, :provided_by_gcp, :group) }
      let(:sub_group) { sub_group_cluster.group }
      let(:project) { create(:project, group: sub_group) }

      before do
        sub_group.update!(parent: group)
      end

      it 'returns clusters in order, descending the hierachy' do
        is_expected.to eq([group_cluster, sub_group_cluster])
      end

      it 'avoids N+1 queries' do
        another_project = create(:project)
        control_count = ActiveRecord::QueryRecorder.new do
          described_class.ancestor_clusters_for_clusterable(another_project, hierarchy_order: hierarchy_order)
        end.count

        cluster2 = create(:cluster, :provided_by_gcp, :group)
        child2 = cluster2.group
        child2.update!(parent: sub_group)
        project = create(:project, group: child2)

        expect do
          described_class.ancestor_clusters_for_clusterable(project, hierarchy_order: hierarchy_order)
        end.not_to exceed_query_limit(control_count)
      end

      context 'for a group' do
        let(:clusterable) { sub_group }

        it 'returns clusters in order for a group' do
          is_expected.to eq([group_cluster])
        end
      end
    end

    context 'scope chaining' do
      let(:project) { create(:project, group: group) }

      subject { described_class.none.ancestor_clusters_for_clusterable(project) }

      it 'returns nothing' do
        is_expected.to be_empty
      end
    end
  end

  describe '#provider' do
    subject { cluster.provider }

    context 'when provider is gcp' do
      let(:cluster) { create(:cluster, :provided_by_gcp) }

      it 'returns a provider' do
        is_expected.to eq(cluster.provider_gcp)
      end
    end

    context 'when provider is aws' do
      let(:cluster) { create(:cluster, :provided_by_aws) }

      it 'returns a provider' do
        is_expected.to eq(cluster.provider_aws)
      end
    end

    context 'when provider is user' do
      let(:cluster) { create(:cluster, :provided_by_user) }

      it { is_expected.to be_nil }
    end
  end

  describe '#platform' do
    subject { cluster.platform }

    context 'when platform is kubernetes' do
      let(:cluster) { create(:cluster, :provided_by_user) }

      it 'returns a platform' do
        is_expected.to eq(cluster.platform_kubernetes)
        expect(subject.class.name.deconstantize).to eq(Clusters::Platforms.to_s)
      end
    end
  end

  describe '#first_project' do
    subject { cluster.first_project }

    context 'when cluster belongs to a project' do
      let(:cluster) { create(:cluster, :project) }
      let(:project) { Clusters::Project.find_by_cluster_id(cluster.id).project }

      it { is_expected.to eq(project) }
    end

    context 'when cluster does not belong to projects' do
      let(:cluster) { create(:cluster) }

      it { is_expected.to be_nil }
    end
  end

  describe '#group' do
    subject { cluster.group }

    context 'when cluster belongs to a group' do
      let(:cluster) { create(:cluster, :group) }
      let(:group) { cluster.groups.first }

      it { is_expected.to eq(group) }
    end

    context 'when cluster does not belong to any group' do
      let(:cluster) { create(:cluster) }

      it { is_expected.to be_nil }
    end
  end

  describe '.with_persisted_applications' do
    let(:cluster) { create(:cluster) }
    let!(:helm) { create(:clusters_applications_helm, :installed, cluster: cluster) }

    it 'preloads persisted applications' do
      query_rec = ActiveRecord::QueryRecorder.new do
        described_class.with_persisted_applications.find_by_id(cluster.id).application_helm
      end

      expect(query_rec.count).to eq(1)
    end
  end

  describe '#persisted_applications' do
    let(:cluster) { create(:cluster) }

    subject { cluster.persisted_applications }

    context 'when all applications are created' do
      let!(:helm) { create(:clusters_applications_helm, cluster: cluster) }
      let!(:ingress) { create(:clusters_applications_ingress, cluster: cluster) }
      let!(:cert_manager) { create(:clusters_applications_cert_manager, cluster: cluster) }
      let!(:prometheus) { create(:clusters_applications_prometheus, cluster: cluster) }
      let!(:runner) { create(:clusters_applications_runner, cluster: cluster) }
      let!(:jupyter) { create(:clusters_applications_jupyter, cluster: cluster) }
      let!(:knative) { create(:clusters_applications_knative, cluster: cluster) }

      it 'returns a list of created applications' do
        is_expected.to contain_exactly(helm, ingress, cert_manager, prometheus, runner, jupyter, knative)
      end
    end

    context 'when not all were created' do
      let!(:helm) { create(:clusters_applications_helm, cluster: cluster) }
      let!(:ingress) { create(:clusters_applications_ingress, cluster: cluster) }

      it 'returns a list of created applications' do
        is_expected.to contain_exactly(helm, ingress)
      end
    end
  end

  describe '#applications' do
    let_it_be(:cluster, reload: true) { create(:cluster) }

    subject { cluster.applications }

    context 'when none of applications are created' do
      it 'returns a list of a new objects' do
        is_expected.not_to be_empty
      end
    end

    context 'when applications are created' do
      let(:cluster) { create(:cluster, :with_all_applications) }

      it 'returns a list of created applications', :aggregate_failures do
        is_expected.to have_attributes(size: described_class::APPLICATIONS.size)
        is_expected.to all(be_kind_of(::Clusters::Concerns::ApplicationCore))
        is_expected.to all(be_persisted)
      end
    end
  end

  describe '#find_or_build_application' do
    let_it_be(:cluster, reload: true) { create(:cluster) }

    it 'rejects classes that are not applications' do
      expect do
        cluster.find_or_build_application(Project)
      end.to raise_error(ArgumentError)
    end

    context 'when none of applications are created' do
      it 'returns the new application', :aggregate_failures do
        described_class::APPLICATIONS.values.each do |application_class|
          application = cluster.find_or_build_application(application_class)

          expect(application).to be_a(application_class)
          expect(application).not_to be_persisted
        end
      end
    end

    context 'when application is persisted' do
      let(:cluster) { create(:cluster, :with_all_applications) }

      it 'returns the persisted application', :aggregate_failures do
        described_class::APPLICATIONS.each_value do |application_class|
          application = cluster.find_or_build_application(application_class)

          expect(application).to be_kind_of(::Clusters::Concerns::ApplicationCore)
          expect(application).to be_persisted
        end
      end
    end
  end

  describe '#allow_user_defined_namespace?' do
    subject { cluster.allow_user_defined_namespace? }

    context 'project type cluster' do
      context 'gitlab managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp) }

        it { is_expected.to be_truthy }
      end

      context 'not managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, managed: false) }

        it { is_expected.to be_truthy }
      end
    end

    context 'group type cluster' do
      context 'gitlab managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, :group) }

        it { is_expected.to be_falsey }
      end

      context 'not managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, :group, managed: false) }

        it { is_expected.to be_truthy }
      end
    end

    context 'instance type cluster' do
      context 'gitlab managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, :instance) }

        it { is_expected.to be_falsey }
      end

      context 'not managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, :instance, managed: false) }

        it { is_expected.to be_truthy }
      end
    end
  end

  describe '#all_projects' do
    context 'cluster_type is project_type' do
      let(:project) { create(:project) }
      let(:cluster) { create(:cluster, :with_installed_helm, projects: [project]) }

      it 'returns projects' do
        expect(cluster.all_projects).to match_array [project]
      end
    end

    context 'cluster_type is group_type' do
      let(:group) { create(:group) }
      let!(:project) { create(:project, group: group) }
      let(:cluster) { create(:cluster_for_group, :with_installed_helm, groups: [group]) }

      it 'returns group projects' do
        expect(cluster.all_projects.ids).to match_array [project.id]
      end
    end

    context 'cluster_type is instance_type' do
      let!(:project) { create(:project) }
      let(:cluster) { create(:cluster, :instance) }

      it "returns all instance's projects" do
        expect(cluster.all_projects.ids).to match_array [project.id]
      end
    end
  end

  describe '#kube_ingress_domain' do
    let(:cluster) { build(:cluster, :provided_by_gcp) }

    subject { cluster.kube_ingress_domain }

    context 'with domain set in cluster' do
      let(:cluster) { build(:cluster, :provided_by_gcp, :with_domain) }

      it { is_expected.to eq(cluster.domain) }
    end

    context 'with no domain on cluster' do
      let(:cluster) { build(:cluster, :project, :provided_by_gcp) }
      let(:project) { cluster.project }

      context 'with domain set at instance level' do
        before do
          stub_application_setting(auto_devops_domain: 'global_domain.com')
        end

        it { is_expected.to eq('global_domain.com') }
      end
    end
  end

  describe '#kubernetes_namespace_for' do
    subject { cluster.kubernetes_namespace_for(environment, deployable: build) }

    let(:environment_name) { 'the-environment-name' }
    let(:environment) { create(:environment, name: environment_name, project: cluster.project, last_deployable: build) }
    let(:build) { create(:ci_build, environment: environment_name, project: cluster.project) }
    let(:cluster) { create(:cluster, :project, managed: managed_cluster) }
    let(:managed_cluster) { true }
    let(:default_namespace) { Gitlab::Kubernetes::DefaultNamespace.new(cluster, project: cluster.project).from_environment_slug(environment.slug) }
    let(:build_options) { {} }

    it 'validates the project id' do
      environment.project_id = build.project_id + 1
      expect { subject }.to raise_error ArgumentError, 'environment.project_id must match deployable.project_id'
    end

    context 'when environment has no last_deployable' do
      let(:build) { nil }

      it { is_expected.to eq default_namespace }
    end

    context 'when cluster is managed' do
      before do
        build.options = { environment: { kubernetes: { namespace: 'ci yaml namespace' } } }
      end

      it 'returns the cached namespace if present, ignoring CI config' do
        cached_namespace = create(:cluster_kubernetes_namespace, cluster: cluster, environment: environment, namespace: 'the name', service_account_token: 'some token')
        expect(subject).to eq cached_namespace.namespace
      end

      it 'returns the default namespace when no cached namespace, ignoring CI config' do
        expect(subject).to eq default_namespace
      end
    end

    context 'when cluster is not managed' do
      let(:managed_cluster) { false }

      it 'returns the cached namespace if present, regardless of CI config' do
        cached_namespace = create(:cluster_kubernetes_namespace, cluster: cluster, environment: environment, namespace: 'the name', service_account_token: 'some token')
        build.options = { environment: { kubernetes: { namespace: 'ci yaml namespace' } } }
        expect(subject).to eq cached_namespace.namespace
      end

      it 'returns the CI YAML namespace when configured' do
        build.options = { environment: { kubernetes: { namespace: 'ci yaml namespace' } } }
        expect(subject).to eq 'ci yaml namespace'
      end

      it 'returns the default namespace when no namespace is configured' do
        expect(subject).to eq default_namespace
      end
    end
  end

  describe '#predefined_variables' do
    subject { cluster.predefined_variables }

    context 'with an instance domain' do
      let(:cluster) { create(:cluster, :provided_by_gcp) }

      before do
        stub_application_setting(auto_devops_domain: 'global_domain.com')
      end

      it 'includes KUBE_INGRESS_BASE_DOMAIN' do
        expect(subject.to_hash).to include(KUBE_INGRESS_BASE_DOMAIN: 'global_domain.com')
      end
    end

    context 'with a cluster domain' do
      let(:cluster) { create(:cluster, :provided_by_gcp, domain: 'example.com') }

      it 'includes KUBE_INGRESS_BASE_DOMAIN' do
        expect(subject.to_hash).to include(KUBE_INGRESS_BASE_DOMAIN: 'example.com')
      end
    end

    context 'with no domain' do
      let(:cluster) { build(:cluster, :provided_by_gcp, :project) }

      it 'returns an empty array' do
        expect(subject.to_hash).to be_empty
      end
    end
  end

  describe '#provided_by_user?' do
    subject { cluster.provided_by_user? }

    context 'with a GCP provider' do
      let(:cluster) { create(:cluster, :provided_by_gcp) }

      it { is_expected.to be_falsy }
    end

    context 'with an user provider' do
      let(:cluster) { create(:cluster, :provided_by_user) }

      it { is_expected.to be_truthy }
    end
  end

  describe '#status_name' do
    subject { cluster.status_name }

    context 'the cluster has a provider' do
      let(:cluster) { build(:cluster, :provided_by_gcp) }
      let(:provider_status) { :errored }

      before do
        cluster.provider.make_errored!
      end

      it { is_expected.to eq provider_status }

      context 'when cluster cleanup is ongoing' do
        using RSpec::Parameterized::TableSyntax

        where(:status_name, :cleanup_status) do
          provider_status  | :cleanup_not_started
          :cleanup_ongoing | :cleanup_uninstalling_applications
          :cleanup_ongoing | :cleanup_removing_project_namespaces
          :cleanup_ongoing | :cleanup_removing_service_account
          :cleanup_errored | :cleanup_errored
        end

        with_them do
          it 'returns cleanup_ongoing when uninstalling applications' do
            cluster.cleanup_status = described_class
              .state_machines[:cleanup_status]
              .states[cleanup_status]
              .value

            is_expected.to eq status_name
          end
        end
      end
    end

    context 'there is a cached connection status' do
      let(:cluster) { build(:cluster, :provided_by_user) }

      before do
        allow(cluster).to receive(:connection_status).and_return(:connected)
      end

      it { is_expected.to eq :connected }
    end

    context 'there is no connection status in the cache' do
      let(:cluster) { build(:cluster, :provided_by_user) }

      before do
        allow(cluster).to receive(:connection_status).and_return(nil)
      end

      it { is_expected.to eq :created }
    end
  end

  describe 'cleanup_status state_machine' do
    shared_examples 'cleanup_status transition' do
      let(:cluster) { create(:cluster, from_state) }

      it 'transitions cleanup_status correctly' do
        expect { subject }.to change { cluster.cleanup_status_name }
          .from(from_state).to(to_state)
      end

      it 'schedules a Clusters::Cleanup::*Worker' do
        expect(expected_worker_class).to receive(:perform_async).with(cluster.id)
        subject
      end
    end

    describe '#start_cleanup!' do
      let(:expected_worker_class) { Clusters::Cleanup::AppWorker }
      let(:to_state) { :cleanup_uninstalling_applications }

      subject { cluster.start_cleanup! }

      context 'when cleanup_status is cleanup_not_started' do
        let(:from_state) { :cleanup_not_started }

        it_behaves_like 'cleanup_status transition'
      end

      context 'when cleanup_status is errored' do
        let(:from_state) { :cleanup_errored }

        it_behaves_like 'cleanup_status transition'
      end
    end

    describe '#make_cleanup_errored!' do
      non_errored_states = Clusters::Cluster.state_machines[:cleanup_status].states.keys - [:cleanup_errored]

      non_errored_states.each do |state|
        it "transitions cleanup_status from #{state} to cleanup_errored" do
          cluster = create(:cluster, state)

          expect { cluster.make_cleanup_errored! }.to change { cluster.cleanup_status_name }
            .from(state).to(:cleanup_errored)
        end

        it "sets error message" do
          cluster = create(:cluster, state)

          expect { cluster.make_cleanup_errored!("Error Message") }.to change { cluster.cleanup_status_reason }
            .from(nil).to("Error Message")
        end
      end
    end

    describe '#continue_cleanup!' do
      context 'when cleanup_status is cleanup_uninstalling_applications' do
        let(:expected_worker_class) { Clusters::Cleanup::ProjectNamespaceWorker }
        let(:from_state) { :cleanup_uninstalling_applications }
        let(:to_state) { :cleanup_removing_project_namespaces }

        subject { cluster.continue_cleanup! }

        it_behaves_like 'cleanup_status transition'
      end

      context 'when cleanup_status is cleanup_removing_project_namespaces' do
        let(:expected_worker_class) { Clusters::Cleanup::ServiceAccountWorker }
        let(:from_state) { :cleanup_removing_project_namespaces }
        let(:to_state) { :cleanup_removing_service_account }

        subject { cluster.continue_cleanup! }

        it_behaves_like 'cleanup_status transition'
      end
    end
  end

  describe '#connection_status' do
    let(:cluster) { create(:cluster) }
    let(:status) { :connected }

    subject { cluster.connection_status }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, connection_status: status)
      end

      it { is_expected.to eq(status) }
    end
  end

  describe '#connection_error' do
    let(:cluster) { create(:cluster) }
    let(:error) { :unknown_error }

    subject { cluster.connection_error }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, connection_error: error)
      end

      it { is_expected.to eq(error) }
    end
  end

  describe '#node_connection_error' do
    let(:cluster) { create(:cluster) }
    let(:error) { :unknown_error }

    subject { cluster.node_connection_error }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, node_connection_error: error)
      end

      it { is_expected.to eq(error) }
    end
  end

  describe '#metrics_connection_error' do
    let(:cluster) { create(:cluster) }
    let(:error) { :unknown_error }

    subject { cluster.metrics_connection_error }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, metrics_connection_error: error)
      end

      it { is_expected.to eq(error) }
    end
  end

  describe '#nodes' do
    let(:cluster) { create(:cluster) }

    subject { cluster.nodes }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, nodes: [kube_node])
      end

      it { is_expected.to eq([kube_node]) }
    end
  end

  describe '#calculate_reactive_cache' do
    subject { cluster.calculate_reactive_cache }

    context 'cluster is disabled' do
      let(:cluster) { create(:cluster, :disabled) }

      it 'does not populate the cache' do
        expect(cluster).not_to receive(:retrieve_connection_status)
        expect(cluster).not_to receive(:retrieve_nodes)

        is_expected.to be_nil
      end
    end

    context 'cluster is enabled' do
      let(:cluster) { create(:cluster, :provided_by_user, :group) }
      let(:gl_k8s_node_double) { double(Gitlab::Kubernetes::Node) }
      let(:expected_nodes) { {} }

      before do
        stub_kubeclient_discover(cluster.platform.api_url)
        allow(Gitlab::Kubernetes::Node).to receive(:new).with(cluster).and_return(gl_k8s_node_double)
        allow(gl_k8s_node_double).to receive(:all).and_return(expected_nodes)
      end

      context 'connection to the cluster is successful' do
        let(:expected_nodes) { { nodes: [kube_node.merge(kube_node_metrics)] } }
        let(:connection_status) { { connection_status: :connected } }

        before do
          allow(gl_k8s_node_double).to receive(:all).and_return(expected_nodes)
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }
      end

      context 'cluster cannot be reached' do
        let(:connection_status) { { connection_status: :unreachable, connection_error: :connection_error } }

        before do
          allow(cluster.kubeclient.core_client).to receive(:discover)
            .and_raise(SocketError)
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }
      end

      context 'cluster cannot be authenticated to' do
        let(:connection_status) { { connection_status: :authentication_failure, connection_error: :authentication_error } }

        before do
          allow(cluster.kubeclient.core_client).to receive(:discover)
            .and_raise(OpenSSL::X509::CertificateError.new("Certificate error"))
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }
      end

      describe 'Kubeclient::HttpError' do
        let(:connection_status) { { connection_status: :authentication_failure, connection_error: :http_error } }
        let(:error_code) { 403 }
        let(:error_message) { "Forbidden" }

        before do
          allow(cluster.kubeclient.core_client).to receive(:discover)
            .and_raise(Kubeclient::HttpError.new(error_code, error_message, nil))
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }

        context 'generic timeout' do
          let(:connection_status) { { connection_status: :unreachable, connection_error: :http_error } }
          let(:error_message) { 'Timed out connecting to server'}

          it { is_expected.to eq(**connection_status, **expected_nodes) }
        end

        context 'gateway timeout' do
          let(:connection_status) { { connection_status: :unreachable, connection_error: :http_error } }
          let(:error_message) { '504 Gateway Timeout for GET https://kubernetes.example.com/api/v1'}

          it { is_expected.to eq(**connection_status, **expected_nodes) }
        end
      end

      context 'an uncategorised error is raised' do
        let(:connection_status) { { connection_status: :unknown_failure, connection_error: :unknown_error } }

        before do
          allow(cluster.kubeclient.core_client).to receive(:discover)
            .and_raise(StandardError)
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }

        it 'notifies Sentry' do
          expect(Gitlab::ErrorTracking).to receive(:track_exception)
            .with(instance_of(StandardError), hash_including(cluster_id: cluster.id))
            .once

          subject
        end
      end
    end
  end

  describe '#delete_cached_resources!' do
    let!(:cluster) { create(:cluster, :project) }
    let!(:staging_namespace) { create(:cluster_kubernetes_namespace, cluster: cluster, namespace: 'staging') }
    let!(:production_namespace) { create(:cluster_kubernetes_namespace, cluster: cluster, namespace: 'production') }

    subject { cluster.delete_cached_resources! }

    it 'deletes associated namespace records' do
      expect(cluster.kubernetes_namespaces).to match_array([staging_namespace, production_namespace])

      subject

      expect(cluster.kubernetes_namespaces).to be_empty
    end
  end

  describe '#clusterable' do
    subject { cluster.clusterable }

    context 'project type' do
      let(:cluster) { create(:cluster, :project) }

      it { is_expected.to eq(cluster.project) }
    end

    context 'group type' do
      let(:cluster) { create(:cluster, :group) }

      it { is_expected.to eq(cluster.group) }
    end

    context 'instance type' do
      let(:cluster) { create(:cluster, :instance) }

      it { is_expected.to be_a(Clusters::Instance) }
    end

    context 'unknown type' do
      let(:cluster) { create(:cluster, :project) }

      before do
        allow(cluster).to receive(:cluster_type).and_return('unknown_type')
      end

      it 'raises NotImplementedError' do
        expect { subject }.to raise_error(NotImplementedError)
      end
    end
  end
end


text:
@interface EventCommentsViewCell : UITableViewCell {
	IBOutlet UILabel *uiComment;
	IBOutlet UILabel *uiAuthor;

}

@property (nonatomic, retain) UILabel     *uiComment;
@property (nonatomic, retain) UILabel     *uiAuthor;

@end


text:
using System.Linq;
using Fancy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Testing.FancyMapper.Models;
using Testing.FancyMapper.Objects;

namespace Testing.FancyMapper
{
    [TestClass]
    public class EnumerableTests
    {
        [TestMethod]
        public void TestMirroringListToListOfModels()
        {
            //create test data
            var obj = new ListOfSimpleObject();
            for (var a = 0; a < 100; a++)
            {
                obj.Objects.Add(new SimpleObject
                {
                    TestString = a.ToString(),
                    TestInt = a
                });
            }

            //create a complex model with no data
            var mod = new ListModel();

            //mirror
            FancyUtil.Mirror(obj, mod);

            //verify equivalency
            for (var a = 0; a < obj.Objects.Count; a++)
            {
                var i = obj.Objects.OrderBy(x => x.TestString);
                var o = mod.Models.OrderBy(x => x.PoorlyNamedString);
                Assert.AreEqual(i.ToList()[a].TestString, o.ToList()[a].PoorlyNamedString);
            }
        }

        [TestMethod]
        public void TestReflectingListOfModelsToList()
        {
            //create test data
            var mod = new ListModel();
            for (var a = 0; a < 100; a++)
            {
                mod.Models.Add(new SimpleModel
                {
                    PoorlyNamedString = a.ToString(),
                    PoorlyNamedInt = a
                });
            }

            //create a complex object with no data
            var obj = new ListOfSimpleObject();

            //mirror
            FancyUtil.Reflect(mod, obj);

            //verify equivalency
            for (var a = 0; a < mod.Models.Count; a++)
            {
                var i = mod.Models.OrderBy(x => x.PoorlyNamedString);
                var o = obj.Objects.OrderBy(x => x.TestString);
                Assert.AreEqual(i.ToList()[a].PoorlyNamedString, o.ToList()[a].TestString);
            }
        }
    }
}


text:
package org.apache.ignite.internal.managers.communication;

import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIO;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;

/**
 * Class represents the data receiver which is pulling data from channel using
 * {@link FileChannel#transferFrom(ReadableByteChannel, long, long)} until the
 * whole file will be completely received.
 */
class FileReceiver extends TransmissionReceiver {
    /** Handler to notify when a file has been received. */
    private final Consumer<File> hnd;

    /** File to receive data into. */
    private File file;

    /** The corresponding file channel to work with. */
    @GridToStringExclude
    private FileIO fileIo;

    /**
     * @param meta Initial file meta info.
     * @param stopChecker Node stop or prcoess interrupt checker.
     * @param factory Factory to produce IO interface on files.
     * @param hnd Transmission handler provider to process download result.
     * @param path File path to destination receiver source.
     * @param log Ignite logger.
     */
    public FileReceiver(
        TransmissionMeta meta,
        int chunkSize,
        BooleanSupplier stopChecker,
        FileIOFactory factory,
        Consumer<File> hnd,
        String path,
        IgniteLogger log
    ) {
        super(meta, stopChecker, log, chunkSize);

        A.notNull(hnd, "FileHandler must be provided by transmission handler");
        A.notNull(path, "File absolute path cannot be null");
        A.ensure(!path.trim().isEmpty(), "File absolute path cannot be empty ");

        this.hnd = hnd;

        file = new File(path);

        try {
            fileIo = factory.create(file);

            fileIo.position(meta.offset());
        }
        catch (IOException e) {
            throw new IgniteException("Unable to open destination file. Receiver will be stopped: " +
                file.getAbsolutePath(), e);
        }
    }

    /** {@inheritDoc} */
    @Override public void receive(ReadableByteChannel ch) throws IOException, InterruptedException {
        super.receive(ch);

        if (transferred == meta.count())
            hnd.accept(file);
    }

    /** {@inheritDoc} */
    @Override protected void readChunk(ReadableByteChannel ch) throws IOException {
        assert fileIo != null;

        long batchSize = Math.min(chunkSize, meta.count() - transferred);

        long read = fileIo.transferFrom(ch, meta.offset() + transferred, batchSize);

        if (read == 0)
            throw new IOException("Channel is reached the end of stream. Probably, channel is closed on the remote node");

        if (read > 0)
            transferred += read;
    }

    /** {@inheritDoc} */
    @Override public void close() {
        U.closeQuiet(fileIo);

        try {
            if (transferred != meta.count())
                Files.delete(file.toPath());
        }
        catch (IOException e) {
            U.error(log, "Error deleting not fully loaded file: " + file, e);
        }
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(FileReceiver.class, this, "super", super.toString());
    }
}