text:
<?php namespace Illuminate\Routing;

use ReflectionClass, ReflectionMethod;

class ControllerInspector {

	/**
	 * An array of HTTP verbs.
	 *
	 * @var array
	 */
	protected $verbs = array(
		'any', 'get', 'post', 'put', 'patch',
		'delete', 'head', 'options'
	);

	/**
	 * Get the routable methods for a controller.
	 *
	 * @param  string  $controller
	 * @param  string  $prefix
	 * @return array
	 */
	public function getRoutable($controller, $prefix)
	{
		$routable = array();

		$reflection = new ReflectionClass($controller);

		// To get the routable methods, we will simply spin through all methods on the
		// controller instance checking to see if it belongs to the given class and
		// is a publicly routable method. If so, we will add it to this listings.
		foreach ($reflection->getMethods() as $method)
		{
			if ($this->isRoutable($method, $reflection->name))
			{
				$data = $this->getMethodData($method, $prefix);

				// If the routable method is an index method, we will create a special index
				// route which is simply the prefix and the verb and does not contain any
				// the wildcard place-holders that each "typical" routes would contain.
				if ($data['plain'] == $prefix.'/index')
				{
					$routable[$method->name][] = $data;

					$routable[$method->name][] = $this->getIndexData($data, $prefix);
				}

				// If the routable method is not a special index method, we will just add in
				// the data to the returned results straight away. We do not need to make
				// any special routes for this scenario but only just add these routes.
				else
				{
					$routable[$method->name][] = $data;
				}
			}
		}

		return $routable;
	}

	/**
	 * Determine if the given controller method is routable.
	 *
	 * @param  ReflectionMethod  $method
	 * @param  string  $controller
	 * @return bool
	 */
	public function isRoutable(ReflectionMethod $method, $controller)
	{
		if ($method->class == 'Illuminate\Routing\Controller') return false;

		return $method->isPublic() && starts_with($method->name, $this->verbs);
	}

	/**
	 * Get the method data for a given method.
	 *
	 * @param  ReflectionMethod  $method
	 * @return array
	 */
	public function getMethodData(ReflectionMethod $method, $prefix)
	{
		$verb = $this->getVerb($name = $method->name);

		$uri = $this->addUriWildcards($plain = $this->getPlainUri($name, $prefix));

		return compact('verb', 'plain', 'uri');
	}

	/**
	 * Get the routable data for an index method.
	 *
	 * @param  array   $data
	 * @param  string  $prefix
	 * @return array
	 */
	protected function getIndexData($data, $prefix)
	{
		return array('verb' => $data['verb'], 'plain' => $prefix, 'uri' => $prefix);
	}

	/**
	 * Extract the verb from a controller action.
	 *
	 * @param  string  $name
	 * @return string
	 */
	public function getVerb($name)
	{
		return head(explode('_', snake_case($name)));
	}

	/**
	 * Determine the URI from the given method name.
	 *
	 * @param  string  $name
	 * @param  string  $prefix
	 * @return string
	 */
	public function getPlainUri($name, $prefix)
	{
		return $prefix.'/'.implode('-', array_slice(explode('_', snake_case($name)), 1));
	}

	/**
	 * Add wildcards to the given URI.
	 *
	 * @param  string  $uri
	 * @return string
	 */
	public function addUriWildcards($uri)
	{
		return $uri.'/{one?}/{two?}/{three?}/{four?}/{five?}';
	}

}


text:
var Nancy = Nancy || {};
Nancy.Demo = Nancy.Demo || {};
Nancy.Demo.ServiceRouting = Nancy.Demo.ServiceRouting || {};

(function (exports, $, ko, undefined) {
	exports.AsyncIndexViewModel = function() {
		this.results = ko.observableArray([]);
		this.timerIds = ko.observableArray([]);
		this.selectedTimerId = ko.observable();
	};

	var poorMansGuid = function() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	};

	var twoDecimals = function(value) {
		return ((value < 10) ? '0' : '') + value;
	};

	var threeDecimals = function(value) {
		return ((value < 10) ? '00' : (value < 100) ? '0' : '') + value;
	};

	exports.AsyncIndexViewModel.prototype.startTimer = function() {
		var vm = this;
		var timerId = poorMansGuid();
		vm.timerIds.push(timerId);

		$.ajax({
			method: 'GET',
			url: '/async/timer/' + timerId + '/start',
			timeout: 2 * 60 * 1000,
			dataType: 'json',
			error: function (xhr, status, message) {
				vm.results.push('[START ERROR] ' + message);
				vm.timerIds.remove(timerId);
			},
			success: function (data) {
				vm.results.push(
					'--> Timer ' + data.id +
					' ran for ' + twoDecimals(data.minutes) + ':' + twoDecimals(data.seconds) + '.' + threeDecimals(data.milliseconds) +
					', using threads ' + data.startedOnThread + ' and ' + data.endedOnThread);

				vm.timerIds.remove(timerId);
			}
		});
	};

	exports.AsyncIndexViewModel.prototype.stopTimer = function() {
		var vm = this;
		var timerId = vm.selectedTimerId();
		if (!timerId)
			return;

		vm.timerIds.remove(timerId);

		$.ajax({
			method: 'GET',
			url: '/async/timer/' + timerId + '/stop',
			dataType: 'json',
			error: function(xhr, status, message) {
				vm.results.push('[STOP ERROR] ' + message);
			},
			success: function() {
				vm.results.push('<-- Stopped timer ' + timerId);
			}
		});
	};
})(Nancy.Demo.ServiceRouting, jQuery, ko, undefined);

redpajama_set_name: RedPajamaGithub


text:
from __future__ import print_function
import time
import platform
import pandas as pd
from io import BytesIO
from io import StringIO
from googleapiclient.http import MediaInMemoryUpload
from googleapiclient.http import BatchHttpRequest
from googleapiclient.errors import HttpError
from .. base import ClientBase
from .. schema import Schema, convert_df2bqschema
from .. errors import BigQueryError

class Client(ClientBase):

    __ENDPOINT_GBQ = "https://www.googleapis.com/auth/bigquery"
    __API_NAME = "bigquery"
    __API_VERSION = "v2"

    def __init__(self, project_id, keyfile_path=None, account_email=None):

        super(Client, self).__init__(project_id, keyfile_path, account_email)
        self._bqcredentials, self._bqservice = super(Client, self)._build_service(Client.__API_NAME,
                                                                                Client.__API_VERSION,
                                                                                Client.__ENDPOINT_GBQ)
    def get_bqservice(self):

        return self._bqservice

    def _parse_table_name(self, table_name):

        if not "." in table_name:
            error_message = """
                table name({0}) must have dataset and table (dataset.table)
            """.format(table_name)
            raise Exception(error_message)

        dataset_id, table_id = table_name.split(".", 1)
        return dataset_id, table_id

    def _check_joberror(self, job):

        if "status" in job and "errorResult" in job["status"]:
            ereasons  = [error["reason"] for error in job["status"]["errors"]]
            emessages = [error["message"] for error in job["status"]["errors"]]
            reasons  = [job["status"]["errorResult"]["reason"]]
            messages = [job["status"]["errorResult"]["message"] + ", ".join([r + ": " + m for r, m in zip(ereasons, emessages)])]
            raise BigQueryError(reasons, messages)

    def _wait_job(self, job, jobname="JOB"):

        jobs = self._bqservice.jobs()
        job_id = job["jobReference"]["jobId"]
        state = job["status"]["state"]
        wait_second = 0
        while "DONE" != state:
            print("\r[{0}] {1} (waiting {2}s)".format(jobname, state, wait_second), end="")
            time.sleep(1)
            wait_second += 1
            req = jobs.get(projectId=self._project_id, jobId=job_id)
            resp = self._try_execute(req)
            state = resp["status"]["state"]
        print("\r[{0}] {1} (waited {2}s)\n".format(jobname, state, wait_second))
        self._check_joberror(job)

        return job

    def _try_execute_and_wait(self, req, jobname="BQ JOB", retry=3):

        while True:
            try:
                resp = self._try_execute(req)
                resp = self._wait_job(resp, jobname)
                return resp
            except BigQueryError as e:
                if 503 in e.codes:
                    print("BackendError. Trying again.")
                    retry -= 1
                    if retry <= 0:
                        raise
                    continue
                raise

    def _job2series(self, json_job):

        jtime = 9*60*60*1000

        jobid = json_job["jobReference"]["jobId"]
        state = json_job["status"]["state"]
        ctime = int(json_job["statistics"]["creationTime"]) + jtime
        stime = int(json_job["statistics"]["startTime"]) + jtime
        etime = int(json_job["statistics"].get("endTime", 0)) + jtime
        bsize = json_job["statistics"].get("query", {"query":{}}).get("totalBytesProcessed", 0)

        ctimes = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(ctime/1000.0))
        stimes = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(stime/1000.0))
        etimes = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(etime/1000.0)) if etime != jtime else "-"
        #stimes = datetime.datetime.fromtimestamp(stime/1000.0)

        return pd.Series([jobid,state,ctimes,stimes,etimes,bsize],
                         index=["jobid","state","creationTime",
                                "startTime","endTime","bsize"])

    def query(self, query, table_name=None, append=True,
              write_disposition=None, allow_large_results=True,
              use_legacy=True, max_tier=None, block=True):

        if table_name is None:
            return self._query_and_get(query, use_legacy)

        return self._query_and_insert(query=query, table_name=table_name,append=append,
                                      write_disposition=write_disposition, allow_large_results=allow_large_results,
                                      use_legacy=use_legacy, max_tier=max_tier, block=block)

    def _query_and_get(self, query, use_legacy=True):

        jobs = self._bqservice.jobs()
        body={'query': query, 'timeoutMs': 200000, 'useLegacySql': use_legacy}
        req = jobs.query(projectId=self._project_id,body=body)
        resp = self._try_execute(req)

        def _check_resperror(rsp):
            if "errors" in rsp:
                raise Exception(":".join([error["reason"] + error["message"] for error in rsp["errors"]]))

        start_sec = time.time()
        job_id = resp["jobReference"]["jobId"]
        retry_count = 100
        while retry_count > 0 and not resp["jobComplete"]:
            retry_count -= 1
            time.sleep(3)
            req = jobs.getQueryResults(projectId=self._project_id,
                                       jobId=job_id,
                                       timeoutMs=200000)
            resp = self._try_execute(req)
            _check_resperror(resp)

        schema = Schema(resp["schema"])

        df_list = []
        df = schema.to_dataframe(resp["rows"])
        df_list.append(df)

        current_row_size = len(df)
        while current_row_size < int(resp["totalRows"]):
            page_token = resp.get('pageToken', None)
            req = jobs.getQueryResults(projectId=self._project_id,
                                       jobId=job_id,
                                       pageToken=page_token,
                                       timeoutMs=100000)
            resp = self._try_execute(req)
            _check_resperror(resp)
            df = schema.to_dataframe(resp["rows"])
            df_list.append(df)
            current_row_size += len(df)
            current_sec = int(time.time() - start_sec)
            row_rate = int(100 * current_row_size / float(resp["totalRows"]))
            print("\r rows: read {0} / total {1} ({2}%), time: {3}s".format(current_row_size, resp["totalRows"], row_rate, current_sec), end="")

        dfs = pd.concat(df_list)
        return dfs

    def _query_and_insert(self, query, table_name=None, append=True, block=True,
               write_disposition=None, allow_large_results=True,
               use_legacy=True, max_tier=None):

        dataset_id, table_id = self._parse_table_name(table_name)
        if write_disposition is None: #WRITE_TRUNCATE, WRITE_APPEND, WRITE_EMPTY
            write_disposition = "WRITE_APPEND" if append else "WRITE_TRUNCATE"

        body = {"configuration": {
                  "query": {
                    "query": query,
                    "writeDisposition": write_disposition,
                    "allowLargeResults": allow_large_results,
                    "destinationTable": {
                      "projectId": self._project_id,
                      "datasetId": dataset_id,
                      "tableId": table_id
                    },
                    "useLegacySql": use_legacy
                  }
               }}
        if max_tier:
            body["configuration"]["query"]["maximumBillingTier"] = max_tier

        jobs = self._bqservice.jobs()
        req = jobs.insert(projectId=self._project_id, body=body)

        if not block:
            resp = self._try_execute(req)
            self._check_joberror(resp)
            return resp["jobReference"]["jobId"]

        resp = self._try_execute_and_wait(req, "BQ INSERT")

        return resp

    def insert(self, df, table_name):

        dataset_id, table_id = self._parse_table_name(table_name)
        tabledata = self._bqservice.tabledata()

        for i in range(0, len(df), 5000):

            rows = [{"json": dict(record)} for ix, record in df[i:i+5000].iterrows()]
            req = tabledata.insertAll(projectId=self._project_id,
                                      datasetId=dataset_id,
                                      tableId=table_id,
                                      body={'rows': rows}).execute()
            resp = self._try_execute(req)
            time.sleep(0.05)

    def load(self, df, table_name, append=True, block=True, job_id=None,
             write_disposition=None, create_disposition="CREATE_IF_NEEDED"):
        """
        Upload local pandas.DataFrame to BigQuery table.

        Parameters
        ----------
        table_name : str
            dataset.table
        append : boolean
            if True, append records to existing table (if not exist, create new table).
            if False, if table exist, delete it and create new table. And append records.
        write_disposition : str
            WRITE_TRUNCATE, WRITE_APPEND, WRITE_EMPTY.
        create_disposition : str
            CREATE_NEVER, CREATE_IF_NEEDED

        Returns
        -------
        JSON job
            load job as JSON format.
        """

        dataset_id, table_id = self._parse_table_name(table_name)
        table = self.get_table(table_name)

        if write_disposition is None:
            write_disposition  = "WRITE_APPEND" if append else "WRITE_TRUNCATE"

        body = {"configuration": {
                  "load": {
                    "sourceFormat": "CSV",
                    "skipLeadingRows": 1,
                    "createDisposition": create_disposition,
                    "writeDisposition": write_disposition,
                    "destinationTable": {
                      "projectId": self._project_id,
                      "datasetId": dataset_id,
                      "tableId": table_id
                    }
                  }
               }}

        if job_id is not None:
            body["jobReference"] = {"jobId": job_id, "projectId": self._project_id}

        if isinstance(df, str):
            df = pd.read_csv(df)

        if table is None or (not append and "$" not in table.get("tableReference",{"tableId": ""})["tableId"]):
            schema = convert_df2bqschema(df)
            body["configuration"]["load"]["schema"] = schema

        if platform.python_version_tuple()[0] == "3":
            buf = StringIO()
            df.to_csv(buf, index=False)
            value = str.encode(buf.getvalue())
        else:
            buf = BytesIO()
            df.to_csv(buf, index=False)
            value = buf.getvalue()
        jobs = self._bqservice.jobs()
        req = jobs.insert(projectId=self._project_id,
                          body=body,
                          media_body=MediaInMemoryUpload(value,
                                                         mimetype='application/octet-stream',
                                                         resumable=True))

        if not block:
            resp = self._try_execute(req)
            self._check_joberror(resp)
            return resp["jobReference"]["jobId"]

        resp = self._try_execute_and_wait(req, "BQ LOAD")

        return resp

    def extract(self, table_name, uri, block=True):

        dataset_id, table_id = self._parse_table_name(table_name)
        body = {"configuration": {
                    "extract": {
                        "sourceTable": {
                            "projectId": self._project_id,
                            "datasetId": dataset_id,
                            "tableId": table_id
                        },
                        "destinationUri": uri,
                        #"destinationUris": [string],
                        "printHeader": True
                        #"fieldDelimiter": string,
                        #"destinationFormat": string,
                        #"compression": string
                    }
               }}
        jobs = self._bqservice.jobs()
        req = jobs.insert(projectId=self._project_id, body=body)

        if not block:
            resp = self._try_execute(req)
            self._check_joberror(resp)
            return resp["jobReference"]["jobId"]

        resp = self._try_execute_and_wait(req, "BQ EXTRACT")

        table = self.get_table(table_name)
        return table

    def cancel(self, job_id):

        jobs = self._bqservice.jobs()
        req = jobs.cancel(projectId=self._project_id, jobId=job_id)
        resp = self._try_execute(req)
        return resp

    def get_dataset(self, dataset_id):

        datasets = self._bqservice.datasets()
        try:
            req = datasets.get(projectId=self._project_id, datasetId=dataset_id)
            resp = self._try_execute(req)
        except HttpError as e:
            if e.resp.status == 404:
                return None
            raise

        return resp

    def list_dataset(self, all=None, page_token=None, max_results=None):

        datasets = self._bqservice.datasets()
        try:
            req = datasets.list(projectId=self._project_id,
                                all=all,
                                pageToken=page_token,
                                maxResults=max_results)
            resp = self._try_execute(req)
        except HttpError as e:
            if e.resp.status == 404:
                return []
            raise

        return resp

    def create_dataset(self, dataset_id, location=None, expiration_ms=None):

        body = {
            "datasetReference": {
                "projectId": self._project_id,
                "datasetId": dataset_id
            }
        }

        if location is not None:
            body["location"] = location
        if expiration_ms is not None:
            body["defaultTableExpirationMs"] = expiration_ms

        datasets = self._bqservice.datasets()
        req = datasets.insert(projectId=self._project_id,
                              body=body)
        resp = self._try_execute(req)
        return resp

    def delete_dataset(self, dataset_id, delete_contents=False):

        datasets = self._bqservice.datasets()
        req = datasets.delete(projectId=self._project_id,
                              datasetId=dataset_id,
                              deleteContents=delete_contents)
        resp = self._try_execute(req)

    def get_table(self, table_name):

        dataset_id, table_id = self._parse_table_name(table_name)
        tables = self._bqservice.tables()
        try:
            req = tables.get(projectId=self._project_id,
                             datasetId=dataset_id,
                             tableId=table_id)
            resp = self._try_execute(req)
        except HttpError as e:
            if e.resp.status == 404:
                return None
            raise

        return resp

    def list_table(self, dataset_id, page_token=None, max_results=None):

        tables = self._bqservice.tables()
        req = tables.list(projectId=self._project_id,
                          datasetId=dataset_id,
                          pageToken=page_token,
                          maxResults=max_results)
        resp = self._try_execute(req)
        return resp

    def create_table(self, table_name, body):
        """
        Create table.

        Parameters
        ----------
        table_name : str
            dataset.table.
        body : str
            JSON format.

        Returns
        -------
        JSON table
            inserted table as JSON format.
        """

        dataset_id, table_id = self._parse_table_name(table_name)
        tables = self._bqservice.tables()
        req = tables.insert(projectId=self._project_id,
                            datasetId=dataset_id,
                            tableId=table_id,
                            body=body)
        resp = self._try_execute(req)
        return resp

    def create_table_from(self, table_name, source, timePartitioning=None):
        table = self.get_table(source)
        dataset_id, table_id = self._parse_table_name(table_name)
        tables = self._bqservice.tables()
        body = {

        }
        req = tables.insert(projectId=self._project_id,
                            datasetId=dataset_id,
                            tableId=table_id,
                            body=body)
        resp = self._try_execute(req)
        return resp

    def delete_table(self, table_name):

        dataset_id, table_id = self._parse_table_name(table_name)
        tables = self._bqservice.tables()
        req = tables.delete(projectId=self._project_id,
                            datasetId=dataset_id,
                            tableId=table_id)
        resp = self._try_execute(req)

    def patch_table(self, table_name, body):

        dataset_id, table_id = self._parse_table_name(table_name)
        tables = self._bqservice.tables()
        req = tables.patch(projectId=self._project_id,
                           datasetId=dataset_id,
                           tableId=table_id,
                           body=body)
        resp = self._try_execute(req)
        return resp

    def show_jobs(self):

        jobs = self._bqservice.jobs()
        req = jobs.list(projectId=self._project_id)
        resp = self._try_execute(req)
        job_list = []
        for json_job in resp["jobs"]:
            job = self._job2series(json_job)
            job_list.append(job)
        print(pd.DataFrame(job_list))

    def show_job(self, job_id):

        jobs = self._bqservice.jobs()
        req = jobs.get(projectId=self._project_id, jobId=job_id)
        resp = self._try_execute(req)
        job = self._job2series(resp)
        print(resp)
        print(job)

    def _streaming_insert(self, df, dataset_id, table_id):

        tabledata = self._bqservice.tabledata()

        def insert():
            resp = tabledata.insertAll(projectId=self._project_id,
                                       datasetId=dataset_id,
                                       tableId=table_id,
                                       body=insert_data).execute()
            return resp

        for i in range(0, len(df), 5000):
            rows = []
            for ix, record in df[i:i+5000].iterrows():
                rows.append({"json": dict(record)})

            insert_data={'rows': rows}
            resp = insert()
            time.sleep(0.05)


text:
package ru.appliedtech.storage;

public interface IStorageSession {

	void close() throws StorageException;
}


text:
title: Winslade
is_name: false

---

Winslade


text:
# Bottom Sheets

[Bottom sheets](https://material.io/components/sheets-bottom) are surfaces
containing supplementary content that are anchored to the bottom of the screen.

![Example bottom sheet: modal bottom sheet](assets/bottomsheet/bottomsheet_hero.png)

**Contents**

*   [Using bottom sheets](#using-bottom-sheets)
*   [Standard bottom sheet](#standard-bottom-sheet)
*   [Modal bottom sheet](#modal-bottom-sheet)
*   [Anatomy and key properties](#anatomy-and-key-properties)
*   [Theming](#theming-bottom-sheets)

## Using bottom sheets

Before you can use Material bottom sheets, you need to add a dependency to the
Material Components for Android library. For more information, go to the
[Getting started](https://github.com/material-components/material-components-android/tree/master/docs/getting-started.md)
page.

Standard bottom sheet basic usage:

```xml
<androidx.coordinatorlayout.widget.CoordinatorLayout
  ...>

  <FrameLayout
    ...
    android:id="@+id/standard_bottom_sheet"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

    <!-- Bottom sheet contents. -->

  </FrameLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```

Modal bottom sheet basic usage:

```kt
class ModalBottomSheet : BottomSheetDialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.modal_bottom_sheet_content, container, false)

    companion object {
        const val TAG = "ModalBottomSheet"
    }
}

class MainActivity : AppCompatActivity() {
    ...
    val modalBottomSheet = ModalBottomSheet()
    modalBottomSheet.show(supportFragmentManager, ModalBottomSheet.TAG)
    ...
}
```

More information on each individual section, below.

### Setting behavior

There are several attributes that can be used to adjust the behavior of both
standard and modal bottom sheets.

Behavior attributes can be applied to standard bottom sheets in xml by setting
them on a child `View` set to `app:layout_behavior`, or programmatically:

```kt
val standardBottomSheetBehavior = BottomSheetBehavior.from(standardBottomSheet)
// Use this to programmatically apply behavior attributes
```

Behavior attributes can be applied to modal bottom sheets using app-level theme
attributes and styles:

```xml
<style name="ModalBottomSheet" parent="Widget.Material3.BottomSheet.Modal">
  <!-- Apply attributes here -->
</style>

<style name="ModalBottomSheetDialog" parent="ThemeOverlay.Material3.BottomSheetDialog">
  <item name="bottomSheetStyle">@style/ModalBottomSheet</item>
</style>

<style name="AppTheme" parent="Theme.Material3.*">
  <item name="bottomSheetDialogTheme">@style/ModalBottomSheetDialog</item>
</style>
```

Or programmatically:

```kt
val modalBottomSheetBehavior = (modalBottomSheet.dialog as BottomSheetDialog).behavior
// Use this to programmatically apply behavior attributes
```

More information about these attributes and their default values is available in
the [behavior attributes](#behavior-attributes) section.

### Retaining behavior on configuration change

In order to save and restore specific behaviors of the bottom sheet on
configuration change, the following flags can be set (or combined with bitwise
OR operations):

*   `SAVE_PEEK_HEIGHT`: `app:behavior_peekHeight` is preserved.
*   `SAVE_HIDEABLE`: `app:behavior_hideable` is preserved.
*   `SAVE_SKIP_COLLAPSED`: `app:behavior_skipCollapsed` is preserved.
*   `SAVE_FIT_TO_CONTENTS`: `app:behavior_fitToContents` is preserved.
*   `SAVE_ALL`: All aforementioned attributes are preserved.
*   `SAVE_NONE`: No attribute is preserved. This is the default value.

Behaviors can also be set in code:

```kt
bottomSheetBehavior.saveFlags = BottomSheetBehavior.SAVE_ALL
```

Or in xml using the `app:behavior_saveFlags` attribute.

### Setting state

Standard and modal bottom sheets have the following states:

*   `STATE_COLLAPSED`: The bottom sheet is visible but only showing its peek
    height. This state is usually the 'resting position' of a bottom sheet, and
    should have enough height to indicate there is extra content for the user to
    interact with.
*   `STATE_EXPANDED`: The bottom sheet is visible at its maximum height and it
    is neither dragging nor settling (see below).
*   `STATE_HALF_EXPANDED`: The bottom sheet is half-expanded (only applicable if
    `behavior_fitToContents` has been set to false), and is neither dragging nor
    settling (see below).
*   `STATE_HIDDEN`: The bottom sheet is no longer visible and can only be
    re-shown programmatically.
*   `STATE_DRAGGING`: The user is actively dragging the bottom sheet up or down.
*   `STATE_SETTLING`: The bottom sheet is settling to a specific height after a
    drag/swipe gesture. This will be the peek height, expanded height, or 0, in
    case the user action caused the bottom sheet to hide.

You can set a state on the bottom sheet:

```kt
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
```

**Note:** `STATE_SETTLING` and `STATE_DRAGGING` should not be set programmatically.

### Listening to state and slide changes

A `BottomSheetCallback` can be added to a `BottomSheetBehavior`:

```kt
val bottomSheetCallback = object : BottomSheetBehavior.BottomSheetCallback() {

    override fun onStateChanged(bottomSheet: View, newState: Int) {
        // Do something for new state.
    }

    override fun onSlide(bottomSheet: View, slideOffset: Float) {
        // Do something for slide offset.
    }
}

// To add the callback:
bottomSheetBehavior.addBottomSheetCallback(bottomSheetCallback)

// To remove the callback:
bottomSheetBehavior.removeBottomSheetCallback(bottomSheetCallback)
```

### Handling insets and fullscreen

`BottomSheetBehavior` can automatically handle insets (such as for
[edge to edge](https://developer.android.com/training/gestures/edge-to-edge)) by
specifying any of these to true on the view:

*   `app:paddingBottomSystemWindowInsets`
*   `app:paddingLeftSystemWindowInsets`
*   `app:paddingRightSystemWindowInsets`
*   `app:paddingTopSystemWindowInsets`

On API 21 and above the modal bottom sheet will be rendered fullscreen (edge to
edge) if the navigation bar is transparent and `app:enableEdgeToEdge` is true.
To enable edge-to-edge by default for modal bottom sheets, you can override
`?attr/bottomSheetDialogTheme` like the below example:

```
<style name="AppTheme" parent="Theme.Material3.*">
  ...
  <item name="bottomSheetDialogTheme">@style/ThemeOverlay.App.BottomSheetDialog</item>
</style>

<style name="ThemeOverlay.App.BottomSheetDialog" parent="ThemeOverlay.Material3.BottomSheetDialog">
    <item name="android:navigationBarColor" tools:ignore="NewApi">@android:color/transparent</item>
</style>
```

Insets can be added automatically if any of the padding attributes above are set
to true in the style, either by updating the style passed to the constructor, or
by updating the default style specified by the `?attr/bottomSheetDialogTheme`
attribute in your theme.

`BottomSheetDialog` will also add padding to the top when the bottom sheet
slides under the status bar, to prevent content from being drawn underneath it.

### Making bottom sheets accessible

The contents within a bottom sheet should follow their own accessibility
guidelines, such as setting content descriptions for images.

To support dragging bottom sheets with accessibility services such as TalkBack,
Voice Access, Switch Access, etc., we provide a convenient widget
`BottomSheetDragHandleView` which will automatically receive and handle
accessibility commands to expand and collapse the attached bottom sheet when
the accessibility mode is enabled. To use `BottomSheetDragHandleView`, you can
add it to the top of your bottom sheet content. It will show a customizable
visual indicator for all users. See the example in the below section for how to
add a drag handle to your bottom sheet.

**Note:** `BottomSheetDragHandleView` has a default min width and height of 48dp
to conform to the minimum touch target requirement. So you will need to preserve
at least 48dp at the top to place a drag handle.

## Standard bottom sheet

Standard bottom sheets co-exist with the screen's main UI region and allow for
simultaneously viewing and interacting with both regions. They are commonly used
to keep a feature or secondary content visible on screen when content in the
main UI region is frequently scrolled or panned.

`BottomSheetBehavior` is applied to a child of
[CoordinatorLayout](https://developer.android.com/reference/androidx/coordinatorlayout/widget/CoordinatorLayout)
to make that child a **persistent bottom sheet**, which is a view that comes up
from the bottom of the screen, elevated over the main content. It can be dragged
vertically to expose more or less content.

API and source code:

*   `BottomSheetBehavior`
    *   [Class definition](https://developer.android.com/reference/com/google/android/material/bottomsheet/BottomSheetBehavior)
    *   [Class source](https://github.com/material-components/material-components-android/tree/master/lib/java/com/google/android/material/bottomsheet/BottomSheetBehavior.java)

### Standard bottom sheet example

The following example shows a standard bottom sheet in its collapsed and
expanded states:

![Standard bottom sheet example. Collapsed on the left and expanded on the
right.](assets/bottomsheet/bottomsheet_standard.png)

`BottomSheetBehavior` works in tandem with `CoordinatorLayout` to let you
display content on a bottom sheet, perform enter/exit animations, respond to
dragging/swiping gestures, etc.

Apply the `BottomSheetBehavior` to a direct child `View` of `CoordinatorLayout`:

```xml
<androidx.coordinatorlayout.widget.CoordinatorLayout
  ...>

  <FrameLayout
    android:id="@+id/standard_bottom_sheet"
    style="@style/Widget.Material3.BottomSheet"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

    <!-- Drag handle for accessibility -->
    <com.google.android.material.bottomsheet.BottomSheetDragHandleView
    android:id="@+id/drag_handle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

    <!-- Bottom sheet contents. -->
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/title"
    .../>

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/supporting_text"
    .../>

    <Button
    android:id="@+id/bottomsheet_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/action"
    .../>

    <com.google.android.material.switchmaterial.SwitchMaterial
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/switch_label"/>

  </FrameLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```

In this example, the bottom sheet is the `FrameLayout`.

## Modal bottom sheet

Modal bottom sheets present a set of choices while blocking interaction with the
rest of the screen. They are an alternative to inline menus and simple dialogs
on mobile devices, providing additional room for content, iconography, and
actions.

`BottomSheetDialogFragment` is a thin layer on top of the regular support
library Fragment that renders your fragment as a **modal bottom sheet**,
fundamentally acting as a dialog.

Modal bottom sheets render a shadow on the content below them, to indicate that
they are modal. If the content outside of the dialog is tapped, the bottom sheet
is dismissed. Modal bottom sheets can be dragged vertically and dismissed by
sliding them down completely.

API and source code:

*   `BottomSheetDialogFragment`
    *   [Class definition](https://developer.android.com/reference/com/google/android/material/bottomsheet/BottomSheetDialogFragment)
    *   [Class source](https://github.com/material-components/material-components-android/tree/master/lib/java/com/google/android/material/bottomsheet/BottomSheetDialogFragment.java)

### Modal bottom sheet example

The following example shows a modal bottom sheet in its collapsed and expanded
states:

![Modal bottom sheet example. Collapsed on the left and expanded on the right.](assets/bottomsheet/bottomsheet_modal.png)

First, subclass `BottomSheetDialogFragment` and overwrite `onCreateView` to
provide a layout for the contents of the sheet (in this example, it's
`modal_bottom_sheet_content.xml`):

```kt
class ModalBottomSheet : BottomSheetDialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.modal_bottom_sheet_content, container, false)

    companion object {
        const val TAG = "ModalBottomSheet"
    }
}
```

Then, inside an `AppCompatActivity`, to show the bottom sheet:

```kt
val modalBottomSheet = ModalBottomSheet()
modalBottomSheet.show(supportFragmentManager, ModalBottomSheet.TAG)
```

`BottomSheetDialogFragment` is a subclass of `AppCompatFragment`, which means
you need to use `Activity.getSupportFragmentManager()`.

**Note:** Don't call `setOnCancelListener` or `setOnDismissListener` on a
`BottomSheetDialogFragment`. You can override
`onCancel(DialogInterface)` or `onDismiss(DialogInterface)` if necessary.

## Anatomy and key properties

Bottom sheets have a sheet, content, and, if modal, a scrim.

![Bottom sheet anatomy](assets/bottomsheet/bottomsheet_anatomy.png)

1.  Sheet
2.  Content
3.  Scrim (in modal bottom sheets)

### Sheet attributes

Element        | Attribute             | Related method(s)                 | Default value
-------------- | --------------------- | --------------------------------- | -------------
**Color**      | `app:backgroundTint`  | N/A                               | `?attr/colorSurface`
**Shape**      | `app:shapeAppearance` | N/A                               | `?attr/shapeAppearanceLargeComponent`
**Elevation**  | `android:elevation`   | N/A                               | `1dp`
**Max width**  | `android:maxWidth`    | `setMaxWidth`
`getMaxWidth`   | `640dp`
**Max height** | `android:maxHeight`   | `setMaxHeight`
`getMaxHeight` | N/A

### Behavior attributes

More info about these attributes and how to use them in the
[setting behavior](#setting-behavior) section.

Behavior                                    | Related method(s)                                                         | Default value
------------------------------------------- | ------------------------------------------------------------------------- | -------------
`app:behavior_peekHeight`                   | `setPeekHeight`
`getPeekHeight`                                       | `auto`
`app:behavior_hideable`                     | `setHideable`
`isHideable`                                            | `false` for standard
`true` for modal
`app:behavior_skipCollapsed`                | `setSkipCollapsed`
`getSkipCollapsed`                                 | `false`
`app:behavior_fitToContents`                | `setFitToContents`
`isFitToContents`                                  | `true`
`app:behavior_draggable`                    | `setDraggable`
`isDraggable`                                          | `true`
`app:behavior_halfExpandedRatio`            | `setHalfExpandedRatio`
`getHalfExpandedRatio`                         | `0.5`
`app:behavior_expandedOffset`               | `setExpandedOffset`
`getExpandedOffset`                               | `0dp`
`app:behavior_significantVelocityThreshold` | `setSignificantVelocityThreshold`
 `getSignificantVelocityThreshold` | `500 pixels/s`

To save behavior on configuration change:

Attribute                | Related method(s)                 | Default value
------------------------ | --------------------------------- | -------------
`app:behavior_saveFlags` | `setSaveFlags`
`getSaveFlags` | `SAVE_NONE`

### Styles

**Element**               | **Default value**
------------------------- | -------------------------------------------
**Default style (modal)** | `@style/Widget.Material3.BottomSheet.Modal`

Default style theme attribute:`?attr/bottomSheetStyle`

Note: The `?attr/bottomSheetStyle` default style theme attribute is for modal
bottom sheets only. There is no default style theme attribute for standard
bottom sheets, because `BottomSheetBehavior`s don't have a designated associated
`View`.

### Theme overlays

**Element**               | **Theme overlay**
------------------------- | ------------------------------------------
**Default theme overlay** | `ThemeOverlay.Material3.BottomSheetDialog`

Default theme overlay attribute: `?attr/bottomSheetDialogTheme`

See the full list of
[styles](https://github.com/material-components/material-components-android/tree/master/lib/java/com/google/android/material/bottomsheet/res/values/styles.xml),
[attrs](https://github.com/material-components/material-components-android/tree/master/lib/java/com/google/android/material/bottomsheet/res/values/attrs.xml),
and
[themes and theme overlays](https://github.com/material-components/material-components-android/tree/master/lib/java/com/google/android/material/bottomsheet/res/values/themes.xml).

## Theming bottom sheets

Bottom sheets support
[Material Theming](https://material.io/components/sheets-bottom#theming), which
can customize color and shape.

### Bottom sheet theming example

API and source code:

*   `BottomSheetBehavior`
    *   [Class definition](https://developer.android.com/reference/com/google/android/material/bottomsheet/BottomSheetBehavior)
    *   [Class source](https://github.com/material-components/material-components-android/tree/master/lib/java/com/google/android/material/bottomsheet/BottomSheetBehavior.java)
*   `BottomSheetDialogFragment`
    *   [Class definition](https://developer.android.com/reference/com/google/android/material/bottomsheet/BottomSheetDialogFragment)
    *   [Class source](https://github.com/material-components/material-components-android/tree/master/lib/java/com/google/android/material/bottomsheet/BottomSheetDialogFragment.java)

The following example shows a bottom sheet with Material Theming, in its
collapsed and expanded states.

![Bottom sheet with pink background color. Collapsed on the left and expanded on
the right.](assets/bottomsheet/bottomsheet_theming.png)

#### Implementing bottom sheet theming

Setting the theme attribute `bottomSheetDialogTheme` to your custom
`ThemeOverlay` will affect all bottom sheets.

In `res/values/themes.xml`:

```xml
<style name="Theme.App" parent="Theme.Material3.*">
  ...
  <item name="bottomSheetDialogTheme">@style/ThemeOverlay.App.BottomSheetDialog</item>
</style>

<style name="ThemeOverlay.App.BottomSheetDialog" parent="ThemeOverlay.Material3.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/ModalBottomSheetDialog</item>
</style>
```

In `res/values/styles.xml`:

```xml
<style name="ModalBottomSheetDialog" parent="Widget.Material3.BottomSheet.Modal">
    <item name="backgroundTint">@color/shrine_pink_light</item>
    <item name="shapeAppearance">@style/ShapeAppearance.App.LargeComponent</item>
</style>

<style name="ShapeAppearance.App.LargeComponent" parent="ShapeAppearance.Material3.LargeComponent">
    <item name="cornerFamily">cut</item>
    <item name="cornerSize">24dp</item>
</style>
```

**Note:** The benefit of using a custom `ThemeOverlay` is that any changes to
your main theme, such as updated colors, will be reflected in the bottom sheet,
as long as they're not overridden in your custom theme overlay. If you use a
custom `Theme` instead, by extending from one of the
`Theme.Material3.*.BottomSheetDialog` variants, you will have more control over
exactly what attributes are included in each, but it also means you'll have to
duplicate any changes that you've made in your main theme into your custom
theme.


text:
package com.annimon.stream.function;

import com.annimon.stream.Objects;
import org.jetbrains.annotations.NotNull;

/**
 * Represents a supplier of {@code double}-valued results.
 *
 * @since 1.1.4
 * @see Supplier
 */
public interface DoubleSupplier {

    /**
     * Gets a result.
     *
     * @return a result
     */
    double getAsDouble();

    class Util {

        private Util() { }

        /**
         * Creates a safe {@code DoubleSupplier}.
         *
         * @param throwableSupplier  the supplier that may throw an exception
         * @return a {@code DoubleSupplier}
         * @throws NullPointerException if {@code throwableSupplier} is null
         * @since 1.1.7
         * @see #safe(com.annimon.stream.function.ThrowableDoubleSupplier, double)
         */
        public static DoubleSupplier safe(
                @NotNull ThrowableDoubleSupplier<Throwable> throwableSupplier) {
            return safe(throwableSupplier, 0.0);
        }

        /**
         * Creates a safe {@code DoubleSupplier}.
         *
         * @param throwableSupplier  the supplier that may throw an exception
         * @param resultIfFailed  the result which returned if exception was thrown
         * @return a {@code DoubleSupplier}
         * @throws NullPointerException if {@code throwableSupplier} is null
         * @since 1.1.7
         */
        public static DoubleSupplier safe(
                @NotNull final ThrowableDoubleSupplier<Throwable> throwableSupplier,
                final double resultIfFailed) {
            Objects.requireNonNull(throwableSupplier);
            return new DoubleSupplier() {

                @Override
                public double getAsDouble() {
                    try {
                        return throwableSupplier.getAsDouble();
                    } catch (Throwable ex) {
                        return resultIfFailed;
                    }
                }
            };
        }

    }
}


text:
#ifndef GRAPHICSSCENETEST_H
#define GRAPHICSSCENETEST_H

#include <QtTest/QtTest>

class GraphicsSceneTest : public QObject
{
    Q_OBJECT

    private slots:
        void initTestCase();
        void cleanupTestCase();

        void addTableItemTest();
        void adjustTablesTest();
        void cleanTableSchemeSceneTest();
        void colorizeAccordingSchemasTest();
        void contextMenuEventTest();
        void createItemGroupTest();
        void createRelationsTest();
        void deleteTableItemTest();
        void divideOnPagesTest();
        void drawBackgroundTest();
        void drawGridTest();
        void findTableItemTest();
        void groupItemsTest();
        void mouseMoveEventTest();
        void mousePressEventTest();
        void mouseReleaseEventTest();
        void moveDownTest();
        void moveLeftTest();
        void moveLegendTest();
        void moveModeTest();
        void moveRightTest();
        void moveUpTest();
        void movedDownTest();
        void movedLeftTest();
        void movedRightTest();
        void movedUpTest();
        void refreshLegendTest();
        void resizeTest();
        void selectAllTablesInSchemaTest();
        void selectAllTablesTest();
        void setAcceptsHoverEventsTest();
        void setFieldsTypesInvisibleTest();
        void setFieldsTypesVisibleTest();
        void setIndicesVisibleTest();
        void setMoveModeTest();
        void setSchemeMenuTest();
        void setTableColorTest();
        void setTableMenuTest();
        void settedMoveModeTest();
        void showGridTest();
        void showLegendTest();
        void showOnSceneTest();
        void ungroupItemsTest();
        void updateLegendTest();
};
#endif // GRAPHICSSCENETEST_H


text:
import scipy.linalg as la
import numpy as np
import time
import sys

from fasttsne import _TSNE as TSNE

def timed_reducer(f):
    def f2(data, d, mode, **kwargs):
        t = time.time()
        print >> sys.stderr, "Reducing to %dd using %s..." % (d, f.__name__)
        if mode == 1:
            from sklearn.preprocessing import Normalizer
            data = Normalizer(copy=False).fit_transform(data)
        X = f(data, d, mode, **kwargs)
        print >> sys.stderr, "%s -> %s. Took %.1fs" % (data.shape, X.shape, time.time() - t)
        return X
    return f2

@timed_reducer
def pca_reduce(data, pca_d, mode,
               algorithm='RandomizedPCA',
               whiten=False
           ):
    import sklearn.decomposition as deco
    alg = getattr(deco, algorithm)
    print >> sys.stderr, "pca..."
    try:
        pca = alg(n_components=pca_d, whiten=whiten)
    except TypeError, e:
        #some don't take whiten argument. If whiten is false, carry on.
        if whiten:
            raise
        pca = alg(n_components=pca_d)
    X = pca.fit_transform(data)
    return X

def fast_tsne(data, pca_d=None, d=2, perplexity=30., theta=0.5, mode=0, normalise_mean=0,
              whiten=0, pca_algo='RandomizedPCA'):
    """
    Run Barnes-Hut T-SNE on _data_.

    @param data         The data.

    @param pca_d        The dimensionality of data is reduced via PCA
                        to this dimensionality.

    @param d            The embedding dimensionality. Must be fixed to
                        2.

    @param perplexity   The perplexity controls the effective number of
                        neighbors.

    @param theta        Degree of BH optimisation (0-1; higher -> faster, worse).

    @param mode         0: Euclidean; 1: normalised Euclidean.

    @param normalise_mean Normalise mean around zero.

    @param whiten       Whiten when doing PCA.

    @param pca_algo     Which scikit-learn PCA implementation to use.
    """

    # inplace!!
    if normalise_mean:
        print >> sys.stderr, "normalising..."
        data = data - data.mean(axis=0)

    if not pca_d or pca_d > data.shape[1]:
        X = data
    else:
        X = pca_reduce(data, pca_d, mode, algorithm=pca_algo, whiten=whiten)
        del data

    N, vlen = X.shape
    print >> sys.stderr, X.shape

    tsne = TSNE()
    Y = tsne.run(X, N, vlen, d, perplexity, theta, mode)
    return Y


text:
package com.amazonaws.services.codepipeline.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Represents the output of a get pipeline state action.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetPipelineStateResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The name of the pipeline for which you want to get the state.
     *

     */
    private String pipelineName;
    /**
     *

     * The version number of the pipeline.
     *

     * <note>
     *

     * A newly-created pipeline is always assigned a version number of 1.
     *

     * </note>
     */
    private Integer pipelineVersion;
    /**
     *

     * A list of the pipeline stage output information, including stage name, state, most recent run details, whether
     * the stage is disabled, and other data.
     *

     */
    private java.util.List<StageState> stageStates;
    /**
     *

     * The date and time the pipeline was created, in timestamp format.
     *

     */
    private java.util.Date created;
    /**
     *

     * The date and time the pipeline was last updated, in timestamp format.
     *

     */
    private java.util.Date updated;

    /**
     *

     * The name of the pipeline for which you want to get the state.
     *

     *
     * @param pipelineName
     *        The name of the pipeline for which you want to get the state.
     */

    public void setPipelineName(String pipelineName) {
        this.pipelineName = pipelineName;
    }

    /**
     *

     * The name of the pipeline for which you want to get the state.
     *

     *
     * @return The name of the pipeline for which you want to get the state.
     */

    public String getPipelineName() {
        return this.pipelineName;
    }

    /**
     *

     * The name of the pipeline for which you want to get the state.
     *

     *
     * @param pipelineName
     *        The name of the pipeline for which you want to get the state.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPipelineStateResult withPipelineName(String pipelineName) {
        setPipelineName(pipelineName);
        return this;
    }

    /**
     *

     * The version number of the pipeline.
     *

     * <note>
     *

     * A newly-created pipeline is always assigned a version number of 1.
     *

     * </note>
     *
     * @param pipelineVersion
     *        The version number of the pipeline.
 <note>
     *

     *        A newly-created pipeline is always assigned a version number of 1.
     *

     */

    public void setPipelineVersion(Integer pipelineVersion) {
        this.pipelineVersion = pipelineVersion;
    }

    /**
     *

     * The version number of the pipeline.
     *

     * <note>
     *

     * A newly-created pipeline is always assigned a version number of 1.
     *

     * </note>
     *
     * @return The version number of the pipeline.
 <note>
     *

     *         A newly-created pipeline is always assigned a version number of 1.
     *

     */

    public Integer getPipelineVersion() {
        return this.pipelineVersion;
    }

    /**
     *

     * The version number of the pipeline.
     *

     * <note>
     *

     * A newly-created pipeline is always assigned a version number of 1.
     *

     * </note>
     *
     * @param pipelineVersion
     *        The version number of the pipeline.
 <note>
     *

     *        A newly-created pipeline is always assigned a version number of 1.
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPipelineStateResult withPipelineVersion(Integer pipelineVersion) {
        setPipelineVersion(pipelineVersion);
        return this;
    }

    /**
     *

     * A list of the pipeline stage output information, including stage name, state, most recent run details, whether
     * the stage is disabled, and other data.
     *

     *
     * @return A list of the pipeline stage output information, including stage name, state, most recent run details,
     *         whether the stage is disabled, and other data.
     */

    public java.util.List<StageState> getStageStates() {
        return stageStates;
    }

    /**
     *

     * A list of the pipeline stage output information, including stage name, state, most recent run details, whether
     * the stage is disabled, and other data.
     *

     *
     * @param stageStates
     *        A list of the pipeline stage output information, including stage name, state, most recent run details,
     *        whether the stage is disabled, and other data.
     */

    public void setStageStates(java.util.Collection<StageState> stageStates) {
        if (stageStates == null) {
            this.stageStates = null;
            return;
        }

        this.stageStates = new java.util.ArrayList<StageState>(stageStates);
    }

    /**
     *

     * A list of the pipeline stage output information, including stage name, state, most recent run details, whether
     * the stage is disabled, and other data.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setStageStates(java.util.Collection)} or {@link #withStageStates(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param stageStates
     *        A list of the pipeline stage output information, including stage name, state, most recent run details,
     *        whether the stage is disabled, and other data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPipelineStateResult withStageStates(StageState... stageStates) {
        if (this.stageStates == null) {
            setStageStates(new java.util.ArrayList<StageState>(stageStates.length));
        }
        for (StageState ele : stageStates) {
            this.stageStates.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of the pipeline stage output information, including stage name, state, most recent run details, whether
     * the stage is disabled, and other data.
     *

     *
     * @param stageStates
     *        A list of the pipeline stage output information, including stage name, state, most recent run details,
     *        whether the stage is disabled, and other data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPipelineStateResult withStageStates(java.util.Collection<StageState> stageStates) {
        setStageStates(stageStates);
        return this;
    }

    /**
     *

     * The date and time the pipeline was created, in timestamp format.
     *

     *
     * @param created
     *        The date and time the pipeline was created, in timestamp format.
     */

    public void setCreated(java.util.Date created) {
        this.created = created;
    }

    /**
     *

     * The date and time the pipeline was created, in timestamp format.
     *

     *
     * @return The date and time the pipeline was created, in timestamp format.
     */

    public java.util.Date getCreated() {
        return this.created;
    }

    /**
     *

     * The date and time the pipeline was created, in timestamp format.
     *

     *
     * @param created
     *        The date and time the pipeline was created, in timestamp format.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPipelineStateResult withCreated(java.util.Date created) {
        setCreated(created);
        return this;
    }

    /**
     *

     * The date and time the pipeline was last updated, in timestamp format.
     *

     *
     * @param updated
     *        The date and time the pipeline was last updated, in timestamp format.
     */

    public void setUpdated(java.util.Date updated) {
        this.updated = updated;
    }

    /**
     *

     * The date and time the pipeline was last updated, in timestamp format.
     *

     *
     * @return The date and time the pipeline was last updated, in timestamp format.
     */

    public java.util.Date getUpdated() {
        return this.updated;
    }

    /**
     *

     * The date and time the pipeline was last updated, in timestamp format.
     *

     *
     * @param updated
     *        The date and time the pipeline was last updated, in timestamp format.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetPipelineStateResult withUpdated(java.util.Date updated) {
        setUpdated(updated);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getPipelineName() != null)
            sb.append("PipelineName: ").append(getPipelineName()).append(",");
        if (getPipelineVersion() != null)
            sb.append("PipelineVersion: ").append(getPipelineVersion()).append(",");
        if (getStageStates() != null)
            sb.append("StageStates: ").append(getStageStates()).append(",");
        if (getCreated() != null)
            sb.append("Created: ").append(getCreated()).append(",");
        if (getUpdated() != null)
            sb.append("Updated: ").append(getUpdated());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetPipelineStateResult == false)
            return false;
        GetPipelineStateResult other = (GetPipelineStateResult) obj;
        if (other.getPipelineName() == null ^ this.getPipelineName() == null)
            return false;
        if (other.getPipelineName() != null && other.getPipelineName().equals(this.getPipelineName()) == false)
            return false;
        if (other.getPipelineVersion() == null ^ this.getPipelineVersion() == null)
            return false;
        if (other.getPipelineVersion() != null && other.getPipelineVersion().equals(this.getPipelineVersion()) == false)
            return false;
        if (other.getStageStates() == null ^ this.getStageStates() == null)
            return false;
        if (other.getStageStates() != null && other.getStageStates().equals(this.getStageStates()) == false)
            return false;
        if (other.getCreated() == null ^ this.getCreated() == null)
            return false;
        if (other.getCreated() != null && other.getCreated().equals(this.getCreated()) == false)
            return false;
        if (other.getUpdated() == null ^ this.getUpdated() == null)
            return false;
        if (other.getUpdated() != null && other.getUpdated().equals(this.getUpdated()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getPipelineName() == null) ? 0 : getPipelineName().hashCode());
        hashCode = prime * hashCode + ((getPipelineVersion() == null) ? 0 : getPipelineVersion().hashCode());
        hashCode = prime * hashCode + ((getStageStates() == null) ? 0 : getStageStates().hashCode());
        hashCode = prime * hashCode + ((getCreated() == null) ? 0 : getCreated().hashCode());
        hashCode = prime * hashCode + ((getUpdated() == null) ? 0 : getUpdated().hashCode());
        return hashCode;
    }

    @Override
    public GetPipelineStateResult clone() {
        try {
            return (GetPipelineStateResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package com.lothrazar.samsprojectiles.entity.projectile;

import com.lothrazar.samsprojectiles.ItemRegistry;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;

public class EntityShearingBolt extends EntityThrowable{

	public static boolean doesShearChild;
	public static boolean doesKnockback;

	public EntityShearingBolt(World worldIn){

		super(worldIn);
	}

	public EntityShearingBolt(World worldIn, EntityLivingBase ent){

		super(worldIn, ent);
	}

	public EntityShearingBolt(World worldIn, double x, double y, double z){

		super(worldIn, x, y, z);
	}

	@Override
	protected void onImpact(RayTraceResult mop){

		if(mop.entityHit != null && mop.entityHit instanceof EntitySheep){
			EntitySheep sheep = (EntitySheep) mop.entityHit;

			// imported from MY unreleased/abandoned BlockShearWool.java in ./FarmingBlocks/
			if(sheep.getSheared() == false && sheep.worldObj.isRemote == false){
				// this part is the same as how EntitySheep goes, use a random number
				if(sheep.isChild() == false || // either an adult, or child that passes config
				(EntityShearingBolt.doesShearChild == true && sheep.isChild() == true)){
					sheep.setSheared(true);
					int i = 1 + sheep.worldObj.rand.nextInt(3);

					for(int j = 0; j < i; ++j){
						EntityItem entityitem = sheep.entityDropItem(new ItemStack(Item.getItemFromBlock(Blocks.wool), 1, sheep.getFleeceColor().getMetadata()), 1.0F);
						entityitem.motionY += (double) (sheep.worldObj.rand.nextFloat() * 0.05F);
						entityitem.motionX += (double) ((sheep.worldObj.rand.nextFloat() - sheep.worldObj.rand.nextFloat()) * 0.1F);
						entityitem.motionZ += (double) ((sheep.worldObj.rand.nextFloat() - sheep.worldObj.rand.nextFloat()) * 0.1F);
					}

					if(doesKnockback){
						sheep.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0);
					}

					BlockPos pos = sheep.getPosition();
					worldObj.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.entity_sheep_shear, SoundCategory.PLAYERS, 1.0F, 1.0F, false);

				}
				// else we hit a child sheep and config disables that

				this.setDead();
			}
		}
		else{
			BlockPos pos = mop.getBlockPos();

			if(pos != null && worldObj.isRemote == false){
				worldObj.spawnEntityInWorld(new EntityItem(worldObj, pos.getX(), pos.getY(), pos.getZ(), new ItemStack(ItemRegistry.ender_wool)));
				this.setDead();
			}
		}
	}
}


text:
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    Calculator calculator;
    calculator.show();

    return app.exec();
}


text:
@class Library;

NS_ASSUME_NONNULL_BEGIN

@interface RootCollection : NSManagedObject

// Insert code here to declare functionality of your managed object subclass
+(NSString *)entityName;
+(instancetype)insertNewObjectIntoContext:(NSManagedObjectContext *)context;

-(Library*)firstLibrary;

@end

NS_ASSUME_NONNULL_END

#import "RootCollection+CoreDataProperties.h"


text:
var app = {
  initialize: function() {
    $("#account-pass").hide();
    // $(".grade-breakdown").hide();

    $(".next-button").on("click", function() {
      $("#account-id").hide();
      $("#account-pass").show();
    });

    $("#section-dashboard").hide();

    $("#logout-button").on("click", function() {
      location.reload();
    });

    //scroll effect

    $("a[href*='#to-components']").on("click",function () {
      $(".mdl-layout__content").animate({
          scrollTop: $(".page-content").height() - $("#to-components").height()*2.5
      }, "slow");
    });

    $("a[href*='#to-guides']").on("click",function () {
      $(".mdl-layout__content").animate({
          scrollTop: $(".page-content").height() - 1100
      }, "slow");
    });

    $("a[href*='attachments']").on("click",function () {
      $(".mdl-layout__content").animate({
          scrollTop: $(".page-content").height() - $(".mygrade-card").height() - 300
      }, "slow");
    });

    $("a[href*='mygrade']").on("click",function () {
      $(".mdl-layout__content").animate({
          scrollTop: $(".page-content").height()
      }, "slow");
    });

  },
  hideLogin: function() {
    $("#section-login").hide();
  },
  displayGrade: function() {
    $("#section-dashboard").show();
  },
  errorLogin: function() {
    $("#account-pass").hide();
    $("#account-id").show();
    this.showSnackBar({
      message: "Something wicked happend. Please try again."
    })
  },
  showSnackBar: function(data) {
    var snackbar = document.querySelector('#toast');
    snackbar.MaterialSnackbar.showSnackbar(data)
  },
  showLoginDialog: function() {
    var dialog = document.querySelector('#login-help-dialog');
    if (!dialog.showModal) {
      dialogPolyfill.registerDialog(dialog);
    };
    dialog.showModal();

    dialog.querySelector('.ok').addEventListener('click', function() {
      dialog.close();
    });
  },
  showGenHelpDialog: function() {
    var dialog = document.querySelector('#gen-help-dialog');
    if (!dialog.showModal) {
      dialogPolyfill.registerDialog(dialog);
    };
    dialog.showModal();

    dialog.querySelector('.ok').addEventListener('click', function() {
      dialog.close();
    });
  },
  showProgressDialog: function(){
    var dialog = document.querySelector('#wait');
    if (!dialog.showModal) {
      dialogPolyfill.registerDialog(dialog);
    };
    dialog.showModal();

    setTimeout(function(){
      dialog.close();
      $("#dashboard-contents").removeClass("wait");
    }, 3000);
  },
  setProfile: function(fbid, full_name) {
    var fbpp_src = 'https://graph.facebook.com/' + fbid + '/picture?width=100&height=100';
    $('.profile-picture').attr('src', fbpp_src);
    var firstName = full_name.split(" ")[1];
    $('.profile-name').html(firstName);
  },
  setDashboard: function(components) {
    google.charts.load('current', {
      'packages': ['corechart', 'bar']
    });
    google.charts.setOnLoadCallback(drawCharts);

    // Slice user account id to determine the course
    var accountID = $('#acct_id').val();

    // Build Components
    var dataSetMidtermComponents = [];
    var dataSetFinaltermComponents = [];

    var header = ['Component', 'Score'];
    dataSetMidtermComponents.push(header);
    dataSetFinaltermComponents.push(header);

    components.forEach(function(item) {
      //determine item type
      if (item.type == "m") {
        var avg = getAverage(item.value, item.total);
        if (item.calc == "post") {
          dataSetMidtermComponents.push([item.name, parseFloat(avg)]);
        } else {
          dataSetMidtermComponents.push([item.name, item.value]);
        }
      } else {
        var avg = getAverage(item.value, item.total);
        if (item.calc == "post") {
          dataSetFinaltermComponents.push([item.name, parseFloat(avg)]);
        } else {
          dataSetFinaltermComponents.push([item.name, item.value]);
        }
      }
    });

    //Build Guide

    // Call the guide
    var guideStr = "fx." + accountID.slice(10, accountID.length) + "_guide()",
    guideObj = eval(guideStr);

    console.log(JSON.stringify(guideObj));

    var dataSetMidtermGuide = [],
    dataSetFinaltermGuide = [],
    header = ['Guide', '%'];
    dataSetMidtermGuide.push(header);
    dataSetFinaltermGuide.push(header);

    $.each(guideObj, function(key, item) {
      if (item.type == "m") {
        dataSetMidtermGuide.push([item.name, item.value]);
      }else{
        dataSetFinaltermGuide.push([item.name, item.value]);
      }
    });

    // Build Charts
    function drawCharts() {
      if (dataSetMidtermComponents.length > 1) {
        drawChartMidtermComponents();
        drawChartMidtermGuide();
      }
      if (dataSetFinaltermComponents.length > 1) {
        $(".coming-soon").hide();
        drawChartFinaltermComponents();
        drawChartFinaltermGuide();
      }

      drawGeneralGradeChart();
    }

    function drawChartMidtermComponents() {
      var data = google.visualization.arrayToDataTable(dataSetMidtermComponents),
      options = {
        hAxis: {
          minValue: 0,
        },
        vAxis: {
          minValue: 0,
          maxValue: 100
        },
        bars: 'horizontal',
        axes: {
          y: {
            0: {
              side: 'right'
            }
          }
        },
        width: 900,
        height: 450
      },
      formatter = new google.visualization.NumberFormat({
        decimalSymbol: '.',
        groupingSymbol: '.'
      });
      formatter.format(data, 1);

      var material = new google.charts.Bar(document.getElementById('chart-midterm-components'));
      material.draw(data, options);
    };

    function drawChartFinaltermComponents() {
      var data = google.visualization.arrayToDataTable(dataSetFinaltermComponents),
      options = {
        hAxis: {
          minValue: 0,
        },
        vAxis: {
          minValue: 0,
          maxValue: 100
        },
        bars: 'horizontal',
        axes: {
          y: {
            0: {
              side: 'right'
            }
          }
        },
        width: 900,
        height: 300
      };

      var formatter = new google.visualization.NumberFormat({
        decimalSymbol: '.',
        groupingSymbol: '.'
      });
      formatter.format(data, 1);

      var material = new google.charts.Bar(document.getElementById('chart-finalterm-components'));
      material.draw(data, options);
    };

    function drawChartMidtermGuide(){
        var data = google.visualization.arrayToDataTable(dataSetMidtermGuide),
        colorStyle = randomColorStyle().slice(0,dataSetMidtermGuide.length),
        options = {
          pieHole: 0.4,
          width: 460,
          height: 300,
          colors: colorStyle
        },
        chart = new google.visualization.PieChart(document.getElementById('chart-midterm-guide'));
        chart.draw(data, options);
    };

    function drawChartFinaltermGuide(){
        var data = google.visualization.arrayToDataTable(dataSetFinaltermGuide),
        colorStyle = randomColorStyle().slice(0,dataSetFinaltermGuide.length),
        options = {
          pieHole: 0.4,
          width: 460,
          height: 300,
          colors: colorStyle
        },
        chart = new google.visualization.PieChart(document.getElementById('chart-finalterm-guide'));
        chart.draw(data, options);
    };

    //final grade

    var generalGradeComponents = [],
    header = ['Component', 'Grade'];
    generalGradeComponents.push(header);

    // Call the formula and get the results
    var courseFormulaObj = "fx." + accountID.slice(10, accountID.length) + "(components)",
    result = eval(courseFormulaObj);

    $("#ggEquiv").html(ggEquiv(result.general));
    $("#ggDesc").html(ggDesc(result.general));

    if(Object.keys(result).length>1){
      generalGradeComponents.push(['Midterm',result.midterm]);
      generalGradeComponents.push(['Finals',result.finalterm]);
      generalGradeComponents.push(['General',result.general]);
    }else{
      generalGradeComponents.push(['General',result.general]);
    };

    function drawGeneralGradeChart(){
      {
        var data = google.visualization.arrayToDataTable(generalGradeComponents),
        options = {
          hAxis: {
            minValue: 0,
          },
          vAxis: {
            minValue: 0,
            maxValue: 100
          },
          bars: 'horizontal',
          axes: {
            y: {
              0: {
                side: 'right'
              }
            }
          },
          width: 900,
          height: 250,
          colors:['#ff9800']
        },
        formatter = new google.visualization.NumberFormat({
          decimalSymbol: '.',
          groupingSymbol: '.'
        });
        formatter.format(data, 1);

        var material = new google.charts.Bar(document.getElementById('chart-final-grade'));
        material.draw(data, options);
      };
    };

  },
  getAttachments: function(attachments) {
    if (attachments == null) {} else {
      console.log("Attachments received: " + attachments);
      this.setAttachments(attachments);
    }
  },
  setAttachments: function(attachments) {
    $("#attachments").html("");
    attachments.forEach(function(item) {
      $trElement = $('

');
      var tdElementStr = "";
      tdElementStr += '' + item.desc + '	';
      tdElementStr += 'Download	';
      $tdElement = $(tdElementStr);
      $tdElement.appendTo($trElement);
      $trElement.appendTo($("#attachments"));
    });
  }
};


text:
/// <reference path="Interfaces.ts"/>

import Request = require("Request");
import Utility = require("Utility");
import CurrentGame = require("CurrentGame");

class Summoner {

    Id: number;
    Name: KnockoutObservable<string>;
    Region: string;
    CurrGame: CurrentGame;

    LastModifiedAgo: KnockoutComputed<string>;
    LastModifiedDate: KnockoutComputed<string>;
    ProfileIcon: KnockoutObservable<number>;
    CurrentGameMessage: KnockoutComputed<string>;
    RefreshEnabled: KnockoutObservable<boolean>;

    private _revisionDate: KnockoutObservable<number>;
    private _updateLastModifiedAgoTimeout: number;
    private _currentGameLastCheckedTime: KnockoutObservable<number>;
    private _updateCurrentGameLastCheckedTimeTimeout: number;
    private _updateRefreshRequests: KnockoutComputed<void>;

    private _currentGameRequest: Request.Info;
    private _dataRequest: Request.Info;

    constructor(
        tempName: string,
        region: string
    ) {
        var self = this;

        // init public non-computables
        self.Name = ko.observable(tempName);
        self.Region = region.toLowerCase();
        self.ProfileIcon = ko.observable(-1);
        self.CurrGame = new CurrentGame();
        self.RefreshEnabled = ko.observable(false);

        // init private non-computables
        self._revisionDate = ko.observable(-1);
        self._currentGameLastCheckedTime = ko.observable(-1);

        // init public computables
        this.LastModifiedAgo = ko.computed(function summonerLastModifiedAgo() {
            if (self._revisionDate() === -1)
                return "?";
            var toReturn = Utility.TimeSinceAgo(self._revisionDate());

            // either come back and update it in 1s, or 1m
            clearTimeout(self._updateLastModifiedAgoTimeout);
            if (toReturn.indexOf("sec") !== -1)
                self._updateLastModifiedAgoTimeout = setTimeout(self._revisionDate.valueHasMutated, Math.random() * 20000 + 10000); // 10-30s
            else
                self._updateLastModifiedAgoTimeout = setTimeout(self._revisionDate.valueHasMutated, Math.random() * 2000 * 60); // 0-2m

            return toReturn;
        });

        this.LastModifiedDate = ko.computed(function summonerLastModifiedAgo() {
            if (self._revisionDate() === -1) return "?";

            return Utility.GetFriendlyDate(new Date(self._revisionDate()));
        });

        self.CurrentGameMessage = ko.computed(function SummonerCurrentGameMessage() {
            var currGameType = self.CurrGame.GameType();
            var currGameElapsed = self.CurrGame.ElapsedTime();
            var currGameLastChecked = self._currentGameLastCheckedTime();

            if (currGameLastChecked < 0) return "";

            if (!currGameType) {
                clearTimeout(self._updateCurrentGameLastCheckedTimeTimeout);
                var timeAgo = Utility.TimeSinceAgo(currGameLastChecked);
                if (timeAgo.indexOf("sec") > -1)
                    self._updateCurrentGameLastCheckedTimeTimeout =
                        setTimeout(function() { self._currentGameLastCheckedTime.valueHasMutated(); }, Math.random() * 20000 + 10000); // 10-30s
                else
                    self._updateCurrentGameLastCheckedTimeTimeout =
                    setTimeout(function() { self._currentGameLastCheckedTime.valueHasMutated(); }, Math.random() * 2000 * 60); // 0-2m
                return "No active game: " + Utility.TimeSinceAgo(currGameLastChecked);
            }

            return currGameType + " - " + currGameElapsed;
        });

        // init private computables
        self._updateRefreshRequests = ko.computed(function SummonerUpdateRefreshRequests() {
            if (!self.RefreshEnabled())
                self.CancelCurrentGameRequest();
            else
                self.GetCurrentGame();
        });
    } // ctor

    Hydrate(summonerObject: ISummoner) {
        var self = this;
        self.Id = summonerObject.id;
        self.Name(summonerObject.name);
        self.ProfileIcon = ko.observable(summonerObject.profileIconId);
        if (summonerObject.revisionDate > self._revisionDate())
            self._revisionDate(summonerObject.revisionDate);
        if (self.RefreshEnabled()) self.GetCurrentGame();
    }

    // once only
    GetData(
        successCallback: () => void,
        errorCallback: (number) => void
    ) {
        var self = this;
        Request.Manager.GetSummonerByName(
            self.Name(),
            self.Region,
            function SummonerGetDataSuccess(responseText: string) {
                self.Hydrate(JSON.parse(responseText)[self.Name().toLowerCase().replace(/\s/g, "")]);
                successCallback();
            },
            function SummonerGetDataError(status: number) {
                alert("Summoner.GetData() error: " + status); // todo: handle 404
                errorCallback(status);
            },
            false,
            null
        );
    }

    // refreshes
    GetCurrentGame() {
        var self = this;

        if (!self.Id) return;
        if (self._currentGameRequest) return; // there's already a request in flight

        self._currentGameRequest = Request.Manager.GetCurrentGameBySummonerId(
            self.Id,
            self.Region,
            function SummonerGetCurrentGameSuccess(responseText: string) {
                self._currentGameLastCheckedTime(Date.now());
                var game: ICurrentGame = JSON.parse(responseText);
                self.CurrGame.Hydrate(responseText);
                self._revisionDate(Date.now());
            },
            function SummonerGetCurrentGameError(status: number) {
                self._currentGameLastCheckedTime(Date.now());
                if (status === 404) self.CurrGame.Blank();
            },
            true,
            self._currentGameRequest);
    }

    CancelCurrentGameRequest() {
        var self = this;
        if (!!self._currentGameRequest)
            Request.Manager.CancelRequest(self._currentGameRequest);
        self._currentGameRequest = null;
    }
}

export = Summoner;


text:
//-----------------------------------------------------
// Include Files
//-----------------------------------------------------
#include "GameEngine.h"
#include "Enemy.h"
#include "SmallExplosion.h"

//-----------------------------------------------------
// Devil Class
//-----------------------------------------------------
class Devil : public Enemy
{
public:
	Devil(HitRegion * HitLevel, bool direction);				// Constructor
	virtual ~Devil();		// Destructor

	//-------------------------------------------------
	// Own methods
	//-------------------------------------------------
	void Tick(double deltaTime, DOUBLE2 posHero);
	void Paint(MATRIX3X2 matview);
	void Spawn(int posX,int posY);
	void Hit(int amountOfDamage);

	void Destroy(bool brutally);
	void CollisionDetection();
	void AgressiveAI(DOUBLE2 posHero);

	HitRegion * GetBoltHitRegion();
	void DestroyBolt();

private:
	//-------------------------------------------------
	// Own methods
	//-------------------------------------------------
	void TickBolt(double deltaTime);
	void PaintBolt(MATRIX3X2 matView);
	void FireBolt();

	//-------------------------------------------------
	// Datamembers
	//-------------------------------------------------
	static Bitmap * m_BmpEnemyPtr;
	bool m_Agressive;
	bool m_Backward;
	HitRegion * m_HitBoltPtr;
	DOUBLE2 m_PosBolt;
	bool m_Firing;
	bool m_FireDirection;

	Explosion * m_ExplosionPtr;

	// -------------------------
	// Disabling default copy constructor and default
	// assignment operator.
	// -------------------------
	Devil(const Devil& yRef);
	Devil& operator=(const Devil& yRef);
};


text:
#ifndef RMLUI_CORE_FONTENGINEDEFAULT_FONTFACEHANDLE_H
#define RMLUI_CORE_FONTENGINEDEFAULT_FONTFACEHANDLE_H

#include "../../../Include/RmlUi/Core/Traits.h"
#include "../../../Include/RmlUi/Core/FontEffect.h"
#include "../../../Include/RmlUi/Core/FontGlyph.h"
#include "../../../Include/RmlUi/Core/Geometry.h"
#include "../../../Include/RmlUi/Core/Texture.h"
#include "FontTypes.h"

namespace Rml {

class FontFaceLayer;

/**
	@author Peter Curry
 */

class FontFaceHandleDefault final : public NonCopyMoveable
{
public:
	FontFaceHandleDefault();
	~FontFaceHandleDefault();

	bool Initialize(FontFaceHandleFreetype face, int font_size);

	/// Returns the point size of this font face.
	int GetSize() const;
	/// Returns the pixel height of a lower-case x in this font face.
	int GetXHeight() const;
	/// Returns the default height between this font face's baselines.
	int GetLineHeight() const;

	/// Returns the font's baseline, as a pixel offset from the bottom of the font.
	int GetBaseline() const;

	/// Returns the font's underline, as a pixel offset from the bottom of the font.
	float GetUnderline(float& thickness) const;

	/// Returns the font's glyphs.
	const FontGlyphMap& GetGlyphs() const;

	/// Returns the width a string will take up if rendered with this handle.
	/// @param[in] string The string to measure.
	/// @param[in] prior_character The optionally-specified character that immediately precedes the string. This may have an impact on the string width due to kerning.
	/// @return The width, in pixels, this string will occupy if rendered with this handle.
	int GetStringWidth(const String& string, Character prior_character = Character::Null);

	/// Generates, if required, the layer configuration for a given list of font effects.
	/// @param[in] font_effects The list of font effects to generate the configuration for.
	/// @return The index to use when generating geometry using this configuration.
	int GenerateLayerConfiguration(const FontEffectList& font_effects);
	/// Generates the texture data for a layer (for the texture database).
	/// @param[out] texture_data The pointer to be set to the generated texture data.
	/// @param[out] texture_dimensions The dimensions of the texture.
	/// @param[in] font_effect The font effect used for the layer.
	/// @param[in] texture_id The index of the texture within the layer to generate.
	/// @param[in] handle_version The version of the handle data. Function returns false if out of date.
	bool GenerateLayerTexture(UniquePtr<const byte[]>& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect, int texture_id, int handle_version) const;

	/// Generates the geometry required to render a single line of text.
	/// @param[out] geometry An array of geometries to generate the geometry into.
	/// @param[in] string The string to render.
	/// @param[in] position The position of the baseline of the first character to render.
	/// @param[in] colour The colour to render the text.
	/// @return The width, in pixels, of the string geometry.
	int GenerateString(GeometryList& geometry, const String& string, Vector2f position, Colourb colour, int layer_configuration = 0);

	/// Version is changed whenever the layers are dirtied, requiring regeneration of string geometry.
	int GetVersion() const;

private:
	// Build and append glyph to 'glyphs'
	bool AppendGlyph(Character character);

	// Build a kerning cache for common characters.
	void FillKerningPairCache();

	// Return the kerning for a character pair.
	int GetKerning(Character lhs, Character rhs) const;

	/// Retrieve a glyph from the given code point, building and appending a new glyph if not already built.
	/// @param[in-out] character  The character, can be changed e.g. to the replacement character if no glyph is found.
	/// @param[in] look_in_fallback_fonts  Look for the glyph in fallback fonts if not found locally, adding it to our glyphs.
	/// @return The font glyph for the returned code point.
	const FontGlyph* GetOrAppendGlyph(Character& character, bool look_in_fallback_fonts = true);

	// Regenerate layers if dirty, such as after adding new glyphs.
	bool UpdateLayersOnDirty();

	// Create a new layer from the given font effect if it does not already exist.
	FontFaceLayer* GetOrCreateLayer(const SharedPtr<const FontEffect>& font_effect);

	// (Re-)generate a layer in this font face handle.
	bool GenerateLayer(FontFaceLayer* layer);

	FontGlyphMap glyphs;

	struct EffectLayerPair {
		const FontEffect* font_effect;
		UniquePtr<FontFaceLayer> layer;
	};
	using FontLayerMap = Vector< EffectLayerPair >;
	using FontLayerCache = SmallUnorderedMap< size_t, FontFaceLayer* >;
	using LayerConfiguration = Vector< FontFaceLayer* >;
	using LayerConfigurationList = Vector< LayerConfiguration >;

	// The list of all font layers, index by the effect that instanced them.
	FontFaceLayer* base_layer;
	FontLayerMap layers;
	// Each font layer that generated geometry or textures, indexed by the font-effect's fingerprint key.
	FontLayerCache layer_cache;

	// Pre-cache kerning pairs for some ascii subset of all characters.
	using AsciiPair = std::uint16_t;
	using KerningIntType = std::int16_t;
	using KerningPairs = UnorderedMap< AsciiPair, KerningIntType >;
	KerningPairs kerning_pair_cache;

	bool has_kerning = false;
	bool is_layers_dirty = false;
	int version = 0;

	// All configurations currently in use on this handle. New configurations will be generated as required.
	LayerConfigurationList layer_configurations;

	FontMetrics metrics;

	FontFaceHandleFreetype ft_face;
};

} // namespace Rml
#endif


text:
import Vue from 'vue';
import VueResource from 'vue-resource';
import VueRouter from 'vue-router';
import Navigation from 'components/Navigation/navigation';
import Loader from 'components/Loader/Loader';

Vue.use(VueRouter);
Vue.use(VueResource);

import routes from 'src/routes';
import 'src/style.scss';

export const LoadingState = new Vue();

export const router = new VueRouter({
  routes,
  mode: 'history',
  linkActiveClass: 'active'
});

export const App = new Vue({
  router,
  components: {
    Navigation,
    Loader
  },

  data(){
    return {
      isLoading: false
    };
  },

  created(){
    LoadingState.$on('toggle', (isLoading) => {
      this.isLoading = isLoading;
    });
  }
}).$mount('#app');