text:
import gc
import unittest

import mock

from google.cloud import bigquery_storage

class TestConnection(unittest.TestCase):
    @staticmethod
    def _get_target_class():
        from google.cloud.bigquery.dbapi import Connection

        return Connection

    def _make_one(self, *args, **kw):
        return self._get_target_class()(*args, **kw)

    def _mock_client(self):
        from google.cloud.bigquery import client

        mock_client = mock.create_autospec(client.Client)
        return mock_client

    def _mock_bqstorage_client(self):
        mock_client = mock.create_autospec(bigquery_storage.BigQueryReadClient)
        mock_client._transport = mock.Mock(spec=["channel"])
        mock_client._transport.grpc_channel = mock.Mock(spec=["close"])
        return mock_client

    def test_ctor_wo_bqstorage_client(self):
        from google.cloud.bigquery.dbapi import Connection

        mock_client = self._mock_client()
        mock_client._ensure_bqstorage_client.return_value = None

        connection = self._make_one(client=mock_client)
        self.assertIsInstance(connection, Connection)
        self.assertIs(connection._client, mock_client)
        self.assertIs(connection._bqstorage_client, None)

    def test_ctor_w_bqstorage_client(self):
        from google.cloud.bigquery.dbapi import Connection

        mock_client = self._mock_client()
        mock_bqstorage_client = self._mock_bqstorage_client()
        mock_client._ensure_bqstorage_client.return_value = mock_bqstorage_client

        connection = self._make_one(
            client=mock_client,
            bqstorage_client=mock_bqstorage_client,
        )

        mock_client._ensure_bqstorage_client.assert_called_once_with(
            mock_bqstorage_client
        )
        self.assertIsInstance(connection, Connection)
        self.assertIs(connection._client, mock_client)
        self.assertIs(connection._bqstorage_client, mock_bqstorage_client)

    @mock.patch("google.cloud.bigquery.Client", autospec=True)
    def test_connect_wo_client(self, mock_client):
        from google.cloud.bigquery.dbapi import connect
        from google.cloud.bigquery.dbapi import Connection

        connection = connect()
        self.assertIsInstance(connection, Connection)
        self.assertIsNotNone(connection._client)
        self.assertIsNotNone(connection._bqstorage_client)

    def test_connect_w_client(self):
        from google.cloud.bigquery.dbapi import connect
        from google.cloud.bigquery.dbapi import Connection

        mock_client = self._mock_client()
        mock_bqstorage_client = self._mock_bqstorage_client()
        mock_client._ensure_bqstorage_client.return_value = mock_bqstorage_client

        connection = connect(client=mock_client)

        mock_client._ensure_bqstorage_client.assert_called_once_with()
        self.assertIsInstance(connection, Connection)
        self.assertIs(connection._client, mock_client)
        self.assertIs(connection._bqstorage_client, mock_bqstorage_client)

    def test_connect_w_both_clients(self):
        from google.cloud.bigquery.dbapi import connect
        from google.cloud.bigquery.dbapi import Connection

        mock_client = self._mock_client()
        mock_bqstorage_client = self._mock_bqstorage_client()
        mock_client._ensure_bqstorage_client.return_value = mock_bqstorage_client

        connection = connect(
            client=mock_client,
            bqstorage_client=mock_bqstorage_client,
        )

        mock_client._ensure_bqstorage_client.assert_called_once_with(
            mock_bqstorage_client
        )
        self.assertIsInstance(connection, Connection)
        self.assertIs(connection._client, mock_client)
        self.assertIs(connection._bqstorage_client, mock_bqstorage_client)

    def test_raises_error_if_closed(self):
        from google.cloud.bigquery.dbapi.exceptions import ProgrammingError

        connection = self._make_one(client=self._mock_client())

        connection.close()

        for method in ("close", "commit", "cursor"):
            with self.assertRaisesRegex(
                ProgrammingError, r"Operating on a closed connection\."
            ):
                getattr(connection, method)()

    def test_close_closes_all_created_bigquery_clients(self):
        client = self._mock_client()
        bqstorage_client = self._mock_bqstorage_client()

        client_patcher = mock.patch(
            "google.cloud.bigquery.dbapi.connection.bigquery.Client",
            return_value=client,
        )
        bqstorage_client_patcher = mock.patch.object(
            client,
            "_ensure_bqstorage_client",
            return_value=bqstorage_client,
        )

        with client_patcher, bqstorage_client_patcher:
            connection = self._make_one(client=None, bqstorage_client=None)

        connection.close()

        self.assertTrue(client.close.called)
        self.assertTrue(bqstorage_client._transport.grpc_channel.close.called)

    def test_close_does_not_close_bigquery_clients_passed_to_it(self):
        client = self._mock_client()
        bqstorage_client = self._mock_bqstorage_client()
        connection = self._make_one(client=client, bqstorage_client=bqstorage_client)

        connection.close()

        self.assertFalse(client.close.called)
        self.assertFalse(bqstorage_client._transport.grpc_channel.close.called)

    def test_close_closes_all_created_cursors(self):
        connection = self._make_one(client=self._mock_client())
        cursor_1 = connection.cursor()
        cursor_2 = connection.cursor()
        self.assertFalse(cursor_1._closed)
        self.assertFalse(cursor_2._closed)

        connection.close()

        self.assertTrue(cursor_1._closed)
        self.assertTrue(cursor_2._closed)

    def test_close_closes_only_open_created_cursors(self):
        connection = self._make_one(client=self._mock_client())
        cursor_1 = connection.cursor()
        cursor_2 = connection.cursor()
        self.assertFalse(cursor_1._closed)
        self.assertFalse(cursor_2._closed)

        cursor_1.close()
        self.assertTrue(cursor_1._closed)
        cursor_1.close = mock.MagicMock()

        connection.close()

        self.assertFalse(cursor_1.close.called)
        self.assertTrue(cursor_2._closed)

    def test_does_not_keep_cursor_instances_alive(self):
        from google.cloud.bigquery.dbapi import Cursor

        connection = self._make_one(client=self._mock_client())
        cursor_1 = connection.cursor()  # noqa
        cursor_2 = connection.cursor()
        cursor_3 = connection.cursor()  # noqa

        del cursor_2

        # Connections should not hold strong references to the Cursor instances
        # they created, unnecessarily keeping them alive.
        gc.collect()
        cursor_count = 0
        for obj in gc.get_objects():
            try:
                if isinstance(obj, Cursor):
                    cursor_count += 1
            except ReferenceError:  # pragma: NO COVER
                pass
        self.assertEqual(cursor_count, 2)

    def test_commit(self):
        connection = self._make_one(client=self._mock_client())
        # commit() is a no-op, there is nothing to test.
        connection.commit()

    def test_cursor(self):
        from google.cloud.bigquery.dbapi import Cursor

        connection = self._make_one(client=self._mock_client())
        cursor = connection.cursor()
        self.assertIsInstance(cursor, Cursor)
        self.assertIs(cursor.connection, connection)


text:
<?php

namespace App\Core\Repositories;

use App\Core\Models\Message;
use App\Core\Models\Participant;
use App\Core\Models\ProductReview;
use App\Core\Models\Thread;
use Carbon\Carbon;
use Illuminate\Container\Container as Application;
use Illuminate\Contracts\Bus\Dispatcher;
use RepositoryLab\Repository\Eloquent\BaseRepository;

/**
 * Class ProductReviewRepositoryEloquent.
 */
class ProductReviewRepositoryEloquent extends BaseRepository implements ProductReviewRepository
{
    /**
     * @var RolesRepository
     */
    protected $roleRepository;
    /**
     * @var ProductsRepository
     */
    protected $product;
    /**
     * @var Thread
     */
    protected $thread;
    /**
     * @var Message
     */
    protected $message;
    /**
     * @var
     */
    protected $productDescription;
    /**
     * @var Participant
     */
    protected $participant;

    /**
     * ProductReviewRepositoryEloquent constructor.
     *
     * @param Application        $app
     * @param Dispatcher         $dispatcher
     * @param RolesRepository    $roleRepository
     * @param ProductsRepository $product
     */
    public function __construct(Application $app,
                                Dispatcher $dispatcher,
                                RolesRepository $roleRepository,
                                ProductsRepository $product)
    {
        parent::__construct($app, $dispatcher);
        $this->roleRepository = $roleRepository;
        $this->product = $product;
        $this->thread = new Thread();
        $this->message = new Message();
        $this->participant = new Participant();
    }

    /**
     * @var array
     */
    protected $fieldSearchable = [
        'rating' => '=',
        'hidden' => '=',
    ];

    /**
     * Specify Model class name.
     *
     * @return string
     */
    public function model()
    {
        $productReview = ProductReview::class;

        return $productReview;
    }

    /**
     * Boot up the repository, pushing criteria.
     */
    public function boot()
    {
        $this->pushCriteria(app(\RepositoryLab\Repository\Criteria\RequestCriteria::class));
    }

    /**
     * @return ProductReview
     */
    public function getModel()
    {
        $model = new ProductReview();

        return $model;
    }

    /**
     * return the number of user's products.
     *
     * @return mixed
     */
    public function countUserProductReviews()
    {
        return $this->with('user')->where('user_id', '=', \Auth::id())->count();
    }

    /**
     * get all Products.
     *
     * @return mixed
     */
    public function getAll()
    {
        return $this->getModel()->latest('created_at')->paginate();
    }

    /**
     * get all current logged in user Reviews.
     *
     * @return mixed
     */
    public function getAllUsers()
    {
        return $this->getModel()->latest('created_at')->users()->paginate();
    }

    /**
     * get the specific to user id feedbacks.
     *
     * @param $id
     *
     * @return mixed
     */
    public function getAllUserById($id)
    {
        return $this->getModel()->latest('created_at')->usersById($id)->paginate();
    }

    /**
     * @param $id
     * @param $message
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed
     */
    public function replyProductReview($id, $message)
    {
        $productReview = $this->with('comments')->find($id);
        $thread = $productReview->comments->first();
        $thread->activateAllParticipants();
        $user_id = \Auth::user()->id;
        // Message
        $this->message->create(
            [
                'thread_id' => $thread->id,
                'user_id'   => $user_id,
                'body'      => $message,
            ]
        );

        // Add replier as a participant
        $participant = $this->participant->firstOrCreate(
            [
                'thread_id' => $thread->id,
                'user_id'   => $user_id,
            ]
        );
        $participant->last_read = new Carbon();
        $participant->save();

        return $productReview;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import type { RequestConfig } from '../../common/types';
import type { NetworkInfoResponse } from '../types';
import { request } from '../../utils/request';

export const getNetworkInfo = (
  config: RequestConfig
): Promise<NetworkInfoResponse> =>
  request({
    method: 'GET',
    path: '/v2/network/information',
    ...config,
  });


text:
package de.mineformers.core.impl.asm

import de.mineformers.core.asm.transformer.CachedClassTransformer

/**
 * CoreClassTransformer
 *
 * @author PaleoCrafter
 */
class CoreClassTransformer extends CachedClassTransformer {
  /**
   * Registers every transformer
   */
  override def init(): Unit = {
    register(new MessageTransformer)
  }
}


text:
import argparse
import io
import json
import os
import shlex
import subprocess
import urllib.request
import re
import tarfile
from tempfile import NamedTemporaryFile

from lib import dateutil

# GitHub OAuth token issuer
TOKENIZER = None

# Map GHTorrent's projects.language to ACK compatible language (if necessary).
ACK_LANGUAGE_MAP = {
    'c': 'cc',
    'c++': 'cpp',
    'c#': 'csharp',
    'objective-c': 'objc',
    'ojective-c++': 'objcpp',
}

_loc_cache = dict()
_cache_hits = 0

def get_cache_hits():
    return _cache_hits

def get_loc(path, files=None):
    """Return the lines-of-code for each language.

    cloc (http://cloc.sourceforge.net/) is used to compute the metrics. The
    method merely parses the output from cloc to return a Python-friendly
    data structure.

    Parameters
    ----------
    path : string
        An absolute path to the source code.
    files : list, optional
        The relative path of file(s) that must used when counting the
        lines-of-code.

    Returns
    -------
    sloc : dictionary
        Dictionary keyed by language with a dictionary containing the metrics
        as the value. The metric dictionary is keyed by 'cloc' for
        comment-lines-of-code and 'sloc' for source-lines-of-code.
    """
    global _loc_cache
    global _cache_hits

    if files is None and path in _loc_cache.keys():
        _cache_hits += 1
        cached = _loc_cache[path]
        if isinstance(cached, Exception):
            raise cached
        else:
            return cached

    if not (os.path.exists(path) or os.path.isdir(path)):
        exception = Exception('%s is an invalid path.' % path)
        if files is None:
            _loc_cache[path] = exception
        raise exception

    sloc = dict()

    tempfile = None
    try:
        command = 'cloc --csv '

        if files:
            # Using temporary file to overcome the character limit in bash
            #   command line.
            tempfile = NamedTemporaryFile()
            with open(tempfile.name, 'w') as _tempfile:
                for _file in files:
                    _tempfile.write('{0}\n'.format(_file))

            command += '--list-file={0}'.format(tempfile.name)
        else:
            command += '.'

        if 'DEBUG' in os.environ:
            print(command)

        process = subprocess.Popen(
            command, cwd=path, shell=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )

        (out, err) = [x.decode() for x in process.communicate()]

        lines = [
            line for line in out.split('\n') if len(line.strip('\n')) != 0
        ]

        index = -1
        for _index, _line in enumerate(lines):
            if 'files,' in _line:
                index = _index
                break

        if index != -1:
            for _index in range(index + 1, len(lines)):
                components = lines[_index].split(',')
                sloc[components[1]] = {
                    'cloc': int(components[3]),
                    'sloc': int(components[4])
                }

        if files is None:
            _loc_cache[path] = sloc
    except:
        raise
    finally:
        if tempfile is not None and not tempfile.closed:
            tempfile.close()

    return sloc

def search(
    pattern, path, recursive=True, whole=False, ignorecase=False, include=None,
    exclude=None
):
    """Search for the presence of a pattern.

    grep (http://www.gnu.org/software/grep/manual/grep.html) is used to
    recursively search for the pattern in all files within a specified path.

    Parameters
    ----------
    pattern : string
        A non-empty PERL style regular expression to match.
    path : string
        An absolute path to the location to root the search at.
    recursive : bool, optional
        Indicates if the search should be recursively across the entire
        directory tree rooted at path. Default is True.
    whole : bool, optional
        Indicates if the search should use whole word matching. Default is
        False.
    ignorecase : bool, optional
        Indicates if the serach should be insensitive to case.
    include : list, optional
        A list of patterns that specify the files to include in the search.
        Default is None.
    exclude : list, optional
        A list of patterns that specify the files to exclude in the search.
        Default is None.

    Returns
    -------
    files : list
        A list of relative paths to files that contain the matching string. If
        no files were found containing the matching string then None is
        returned.
    """
    if not (os.path.exists(path) or os.path.isdir(path)):
        raise Exception('%s is an invalid path.' % path)

    if not pattern:
        raise Exception('Parameter pattern cannot be emtpy.')

    files = None

    command = 'grep -Plc'
    if recursive:
        command += ' -r'
    if whole:
        command += ' -w'
    if ignorecase:
        command += ' -i'
    if include:
        command += ' --include '
        command += ' --include '.join(shlex.quote(i) for i in include)
    if exclude:
        command += ' --exclude '
        command += ' --exclude '.join(shlex.quote(i) for i in exclude)

    command += ' '
    command += shlex.quote(pattern)

    if 'DEBUG' in os.environ:
        print(command)

    process = subprocess.Popen(
        command, cwd=path, shell=True,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    (out, err) = [x.decode() for x in process.communicate()]

    lines = [
        line.strip('\n')
        for line in out.split('\n') if len(line.strip('\n')) != 0
    ]

    if lines:
        files = lines

    return files

def url_to_json(url, headers={}):
    """Returns the JSON response from the url.

    Args:
        url (string): URL from which to GET the JSON resource.

    Returns:
        dict: JSON of the response or empty dict on error.
    """
    request = urllib.request.Request(
        url,
        headers=headers
    )

    try:
        response = urllib.request.urlopen(request)

        raw_data = response.readall().decode('utf-8')
        result = json.loads(raw_data)
    except Exception as e:
        # TODO: Properly handle error. For now, just return empty dictionary.
        result = {}

    return result

def get_repo_path(repo_id, repositories_dir):
    # Repository path is the subdir within the id folder whose name is
    # NOT metadata.json. That is, the path we're interested in is the
    # downloaded git source. If no such path exists, the repository path
    # is simply the path to the id folder.
    base_path = repositories_dir + str(repo_id) + "/"
    repo_path = base_path  # Default to this if we can't find the git repo
    for entry in os.listdir(base_path):
        if entry != 'metadata.json':
            repo_path += entry
            break
    return repo_path

def clone(owner, name, directory, date=None):
    """Clone a GitHub repository and reset its state to a specific commit.

    Parameters
    ----------
    owner : string
        User name of the owner of the repository.
    name : string
        Name of the repository to clone.
    date : string
        A date used to identify the commit to which the state of the repository
        will be reset to.
    directory : string
        Absolute path of a directory to clone the repository to.

    Returns
    -------
    path : string
        Absolute path of the directory containing the repository just cloned.
    """
    (cloneable, reason) = is_cloneable(owner, name)
    if not cloneable:
        raise Exception(reason)

    path = directory
    url = 'https://github.com/{0}/{1}'.format(owner, name)

    # Clone
    command = 'git clone {0}'.format(url)
    if 'DEBUG' in os.environ:
        print(command)

    process = subprocess.Popen(
        command, cwd=path, shell=True,
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
    )
    process.wait()
    if process.returncode != 0:
        raise Exception('Failed to execute {0}'.format(command))

    if date is not None:
        # Reset
        path = os.path.join(path, name)
        command = (
            'git log -1 --before="{0} 23:59:59" --pretty="format:%H"'.format(
                date
            )
        )
        if 'DEBUG' in os.environ:
            print(command)

        process = subprocess.Popen(
            command, cwd=path, shell=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        (out, err) = [i.decode() for i in process.communicate()]

        if process.returncode != 0:
            raise Exception('Failed to execute {0}'.format(command))

        sha = out
        command = 'git reset --hard {0}'.format(sha)
        if 'DEBUG' in os.environ:
            print(command)

        process = subprocess.Popen(
            command, cwd=path, shell=True,
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
        process.wait()
        if process.returncode != 0:
            raise Exception('Failed to execute {0}'.format(command))

    return path

def read(jsonfile):
    """Read a JSON file.

    Parameters
    ----------
    jsonfile : file object
        An open file handle to a JSON file.

    Return
    ------
    jsondata : dict
        A dictionary returned by the json.load()
    """
    jsondata = dict()
    try:
        if jsonfile:
            jsondata = json.load(jsonfile)
        return jsondata
    except:
        raise Exception('Failure in loading JSON data {0}'.format(
            jsonfile.name
        ))
    finally:
        jsonfile.close()

def parse_datetime_delta(datetime_delta):
    """Parse specification of datetime delta of the form nynmndnHnMnS

    Parameters
    ----------
    datetime_delta : str
        A string of the form nynmndnHnMnS. All components of the
        specification are optional. Note that the component specifiers are
        case-sensitive.

    Returns
    -------
    relativedelta : lib.dateutil.relativedelta
        An instance of lib.dateutil.relativedelta representing the datetime
        delta specified in the argument to this function. A value of zero is
        set for each component that is not specfied in the argument.
    """
    delta = dateutil.relativedelta()

    match = re.search('(\d+)y', datetime_delta)
    if match:
        delta.years = int(match.group(1))

    match = re.search('(\d+)m', datetime_delta)
    if match:
        delta.months = int(match.group(1))

    match = re.search('(\d+)d', datetime_delta)
    if match:
        delta.days = int(match.group(1))

    match = re.search('(\d+)H', datetime_delta)
    if match:
        delta.hours = int(match.group(1))

    match = re.search('(\d+)M', datetime_delta)
    if match:
        delta.minutes = int(match.group(1))

    match = re.search('(\d+)S', datetime_delta)
    if match:
        delta.seconds = int(match.group(1))

    return delta

def is_cloneable(owner, name):
    """Verify if a repository is clone-able.

    Parameters
    ----------
    owner : string
        User name of the owner of the repository.
    name : string
        Name of the repository to clone.

    Returns
    -------
    cloneablility : 2-tuple
        A 2-tuple indicating the cloneablility of the repository. First element
        is True if the repository is clone-able, False otherwise. Second
        element is a string that describes the reason for a repository for not
        being clone-able.
    """
    is_cloneable = True
    reason = None

    uri = '{0}/{1}'.format(owner, name)
    url = 'https://api.github.com/repos/{0}'.format(uri)
    if TOKENIZER is not None:
        url = TOKENIZER.tokenize(url)
    request = urllib.request.Request(url, method='HEAD')

    try:
        urllib.request.urlopen(request)
    except urllib.error.HTTPError as error:
        is_cloneable = False
        if error.code == 404:
            reason = '{0} is no longer active.'.format(uri)
        elif error.code == 403:
            reason = '{0} may have been deactivated.'.format(uri)
        else:
            reason = '{0} is not clone-able for reasons unknown.'.format(uri)

    return (is_cloneable, reason)

def get_files(path, language):
    """Return list of absolute paths to files in a specified language.

    Parameters
    ----------
    path : str
        Absolute path of the directory to search for files in.
    language : str
        Programming language as stored in GHTorrent's database.

    Returns
    -------
    files : list
        A list of absolute paths to files in a specified programming language
        (if any), None otherwise.
    """
    files = None

    language = language.lower()
    if language in ACK_LANGUAGE_MAP:
        language = ACK_LANGUAGE_MAP[language]

    command = ['ack', '-f', "--{0}".format(language), path]
    process = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )

    if 'DEBUG' in os.environ:
        print(' '.join(command))

    out, _ = [x.decode(errors='ignore') for x in process.communicate()]
    files = [line for line in out.split('\n') if line.strip()]

    return files


text:
;(function (cxt, CONFIG, common, $) {
  var background = chrome.extension.getBackgroundPage();
  cxt.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
    background.console.log(errorMsg, url, lineNumber);
  }

  angular.module('App', [])
  .filter('translate', function () {
    return common.translate;
  })
  .directive('translate', function () {
    return function (scope, el, attr) {
      el.text(common.translate(el.text()));
    };
  })
  .directive('ngAnimateOnChange', function ($timeout) {
    return function (scope, el, attr) {
      scope.$on('$destroy', scope.$watch(attr.ngAnimateOnChange, function (nv, ov) {
        if (nv == ov) {
          return undefined;
        }
        el.addClass('ng-change');
        $timeout(function () {
          el.removeClass('ng-change');
        }, CONFIG.HIGHLIGHTTIMEOUT);
      }));
    };
  })
  .directive('ngOnlynumbers', function () {
    function onkeypress (evt) {
      if (evt.keyCode === 46) {
        if (String(evt.target.value).indexOf('.') !== -1) {
          evt.preventDefault();
        }
        return undefined;
      }
      if (evt.keyCode < 48 || evt.keyCode > 57) {
        evt.preventDefault();
      }
    }

    return function (scope, el, attr) {
      el.on('keypress', onkeypress);
      scope.$on('$destroy', function () {
        el.off('keypress', onkeypress);
      });
    };
  })
  .controller('AppCtrl', function ($scope, $interval, $timeout) {
    console.log('popup', new Date().getTime(), $scope);

    angular.extend($scope, {
      bg: {
        value: 0,
        interval: 0
      },
      forms: {},
      appendForm: undefined,
      observTimeouts: CONFIG.OBSERVTIMEOUTS
    });

    function saveStorage () {
      common.saveStorage($scope.storage);
    }

    function appendSteamListing (rsp) {
      var url = this.url,
          $page = $(rsp),
          $o = $page.find('.market_listing_row');
      if (!$o.length) {
        return undefined;
      }
      $timeout(function () {
        $scope.storage.listings.push(angular.extend({
          $id: new Date().getTime(),
          $timestamp: new Date().getTime(),
          url: url,
          thumbnail: $page.find('div.market_listing_largeimage:first img').attr('src') || undefined,
          title: $o.filter(':first').find('.market_listing_item_name:first').text() || url,
          price: undefined,
          price_label: ''
        }, common.getPrice($o[0], $o[1], $o[2])));
        saveStorage();
      });
    }

    $scope.appendSteamListing = function (form) {
      if (form.$$buzy === true) {
        return undefined;
      }
      for (var i = $scope.storage.listings.length; i-- > 0;) {
        if ($scope.storage.listings[i].url === $scope.appendForm.url) {
          return undefined;
        }
      }
      form.$$buzy = true;
      $.ajax({url: $scope.appendForm.url, dataType: 'html'})
        .done(appendSteamListing)
        .fail(function () {
          console.log('ajax error');
        })
        .always(function () {
          form.$$buzy = false;
        })
      ;
    };

    $scope.updateSettings = function () {
      saveStorage();
    };

    $scope.changeItemMaxPrice = (function () {
      var timeout;
      return function (item) {
        if (!parseFloat(item.max_price)) {
          item.max_price = '';
        }
        clearTimeout(timeout);
        timeout = setTimeout(saveStorage, 1000);
      };
    })();

    $scope.remove = function (item) {
      var hasChanges = false;
      for (var i = $scope.storage.listings.length; i-- > 0;) {
        if ($scope.storage.listings[i].$id === item.$id) {
          hasChanges = true;
          $scope.storage.listings.splice(i, 1);
        }
      }
      if (hasChanges) {
        saveStorage();
      }
    };

    $scope.buy = function (item) {
      //
    };

    $scope.clear = function () {
      chrome.storage.sync.clear();
    };

    $scope.onUpdateConfig = function (evt, o) {
      $timeout(function () {
        common.extendStorage($scope.storage, o);
      });
    };

    $scope.onDevUpdate = function () {
      $scope.bg.value = background.$timestamp;
    };

    chrome.tabs.getSelected(null, function (tab) {
      $timeout(function () {
        $scope.tab = tab;
        $scope.appendForm = {
          url: undefined
        };
        var res = CONFIG.reML.exec(tab.url);
        if (res && res[1] && res[2]) {
          $scope.appendForm.url = 'http://steamcommunity.com/market/listings/' + res[1] + '/' + res[2];
        }
      });
    });

    chrome.storage.sync.get(CONFIG.STORAGEKEY, function (o) {
      $timeout(function () {
        $scope.storage = common.getStorage(o);
      });
    });

    $(cxt).on('storage.' + CONFIG.STORAGEKEY, $scope.onUpdateConfig);

    if (CONFIG.ISDEVMODE) {
      $scope.onDevUpdate();
      $scope.bg.interval = $interval($scope.onDevUpdate, 3000);
    }

    $scope.$on('$destroy', function () {
      $interval.cancel($scope.bg.interval);
      $(cxt).off('storage.' + CONFIG.STORAGEKEY, $scope.onUpdateConfig);
    });
  });
})(this, this['CONFIG'], this['common'], jQuery);


text: Fun with AngularJS


text:
package autoscaling_test

import (
	"bytes"
	"fmt"
	"time"

	"github.com/dragonfax/aws-sdk-go/aws"
	"github.com/dragonfax/aws-sdk-go/service/autoscaling"
)

var _ time.Duration
var _ bytes.Buffer

func ExampleAutoScaling_AttachInstances() {
	svc := autoscaling.New(nil)

	params := &autoscaling.AttachInstancesInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		InstanceIds: []*string{
			aws.String("XmlStringMaxLen16"), // Required
			// More values...
		},
	}
	resp, err := svc.AttachInstances(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_AttachLoadBalancers() {
	svc := autoscaling.New(nil)

	params := &autoscaling.AttachLoadBalancersInput{
		AutoScalingGroupName: aws.String("ResourceName"),
		LoadBalancerNames: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
	}
	resp, err := svc.AttachLoadBalancers(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_CompleteLifecycleAction() {
	svc := autoscaling.New(nil)

	params := &autoscaling.CompleteLifecycleActionInput{
		AutoScalingGroupName:  aws.String("ResourceName"),          // Required
		LifecycleActionResult: aws.String("LifecycleActionResult"), // Required
		LifecycleActionToken:  aws.String("LifecycleActionToken"),  // Required
		LifecycleHookName:     aws.String("AsciiStringMaxLen255"),  // Required
	}
	resp, err := svc.CompleteLifecycleAction(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_CreateAutoScalingGroup() {
	svc := autoscaling.New(nil)

	params := &autoscaling.CreateAutoScalingGroupInput{
		AutoScalingGroupName: aws.String("XmlStringMaxLen255"), // Required
		MaxSize:              aws.Int64(1),                     // Required
		MinSize:              aws.Int64(1),                     // Required
		AvailabilityZones: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
		DefaultCooldown:         aws.Int64(1),
		DesiredCapacity:         aws.Int64(1),
		HealthCheckGracePeriod:  aws.Int64(1),
		HealthCheckType:         aws.String("XmlStringMaxLen32"),
		InstanceId:              aws.String("XmlStringMaxLen16"),
		LaunchConfigurationName: aws.String("ResourceName"),
		LoadBalancerNames: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
		PlacementGroup: aws.String("XmlStringMaxLen255"),
		Tags: []*autoscaling.Tag{
			{ // Required
				Key:               aws.String("TagKey"), // Required
				PropagateAtLaunch: aws.Bool(true),
				ResourceId:        aws.String("XmlString"),
				ResourceType:      aws.String("XmlString"),
				Value:             aws.String("TagValue"),
			},
			// More values...
		},
		TerminationPolicies: []*string{
			aws.String("XmlStringMaxLen1600"), // Required
			// More values...
		},
		VPCZoneIdentifier: aws.String("XmlStringMaxLen255"),
	}
	resp, err := svc.CreateAutoScalingGroup(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_CreateLaunchConfiguration() {
	svc := autoscaling.New(nil)

	params := &autoscaling.CreateLaunchConfigurationInput{
		LaunchConfigurationName:  aws.String("XmlStringMaxLen255"), // Required
		AssociatePublicIpAddress: aws.Bool(true),
		BlockDeviceMappings: []*autoscaling.BlockDeviceMapping{
			{ // Required
				DeviceName: aws.String("XmlStringMaxLen255"), // Required
				Ebs: &autoscaling.Ebs{
					DeleteOnTermination: aws.Bool(true),
					Iops:                aws.Int64(1),
					SnapshotId:          aws.String("XmlStringMaxLen255"),
					VolumeSize:          aws.Int64(1),
					VolumeType:          aws.String("BlockDeviceEbsVolumeType"),
				},
				NoDevice:    aws.Bool(true),
				VirtualName: aws.String("XmlStringMaxLen255"),
			},
			// More values...
		},
		ClassicLinkVPCId: aws.String("XmlStringMaxLen255"),
		ClassicLinkVPCSecurityGroups: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
		EbsOptimized:       aws.Bool(true),
		IamInstanceProfile: aws.String("XmlStringMaxLen1600"),
		ImageId:            aws.String("XmlStringMaxLen255"),
		InstanceId:         aws.String("XmlStringMaxLen16"),
		InstanceMonitoring: &autoscaling.InstanceMonitoring{
			Enabled: aws.Bool(true),
		},
		InstanceType:     aws.String("XmlStringMaxLen255"),
		KernelId:         aws.String("XmlStringMaxLen255"),
		KeyName:          aws.String("XmlStringMaxLen255"),
		PlacementTenancy: aws.String("XmlStringMaxLen64"),
		RamdiskId:        aws.String("XmlStringMaxLen255"),
		SecurityGroups: []*string{
			aws.String("XmlString"), // Required
			// More values...
		},
		SpotPrice: aws.String("SpotPrice"),
		UserData:  aws.String("XmlStringUserData"),
	}
	resp, err := svc.CreateLaunchConfiguration(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_CreateOrUpdateTags() {
	svc := autoscaling.New(nil)

	params := &autoscaling.CreateOrUpdateTagsInput{
		Tags: []*autoscaling.Tag{ // Required
			{ // Required
				Key:               aws.String("TagKey"), // Required
				PropagateAtLaunch: aws.Bool(true),
				ResourceId:        aws.String("XmlString"),
				ResourceType:      aws.String("XmlString"),
				Value:             aws.String("TagValue"),
			},
			// More values...
		},
	}
	resp, err := svc.CreateOrUpdateTags(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DeleteAutoScalingGroup() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DeleteAutoScalingGroupInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		ForceDelete:          aws.Bool(true),
	}
	resp, err := svc.DeleteAutoScalingGroup(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DeleteLaunchConfiguration() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DeleteLaunchConfigurationInput{
		LaunchConfigurationName: aws.String("ResourceName"), // Required
	}
	resp, err := svc.DeleteLaunchConfiguration(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DeleteLifecycleHook() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DeleteLifecycleHookInput{
		AutoScalingGroupName: aws.String("ResourceName"),         // Required
		LifecycleHookName:    aws.String("AsciiStringMaxLen255"), // Required
	}
	resp, err := svc.DeleteLifecycleHook(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DeleteNotificationConfiguration() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DeleteNotificationConfigurationInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		TopicARN:             aws.String("ResourceName"), // Required
	}
	resp, err := svc.DeleteNotificationConfiguration(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DeletePolicy() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DeletePolicyInput{
		PolicyName:           aws.String("ResourceName"), // Required
		AutoScalingGroupName: aws.String("ResourceName"),
	}
	resp, err := svc.DeletePolicy(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DeleteScheduledAction() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DeleteScheduledActionInput{
		ScheduledActionName:  aws.String("ResourceName"), // Required
		AutoScalingGroupName: aws.String("ResourceName"),
	}
	resp, err := svc.DeleteScheduledAction(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DeleteTags() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DeleteTagsInput{
		Tags: []*autoscaling.Tag{ // Required
			{ // Required
				Key:               aws.String("TagKey"), // Required
				PropagateAtLaunch: aws.Bool(true),
				ResourceId:        aws.String("XmlString"),
				ResourceType:      aws.String("XmlString"),
				Value:             aws.String("TagValue"),
			},
			// More values...
		},
	}
	resp, err := svc.DeleteTags(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeAccountLimits() {
	svc := autoscaling.New(nil)

	var params *autoscaling.DescribeAccountLimitsInput
	resp, err := svc.DescribeAccountLimits(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeAdjustmentTypes() {
	svc := autoscaling.New(nil)

	var params *autoscaling.DescribeAdjustmentTypesInput
	resp, err := svc.DescribeAdjustmentTypes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeAutoScalingGroups() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeAutoScalingGroupsInput{
		AutoScalingGroupNames: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		MaxRecords: aws.Int64(1),
		NextToken:  aws.String("XmlString"),
	}
	resp, err := svc.DescribeAutoScalingGroups(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeAutoScalingInstances() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeAutoScalingInstancesInput{
		InstanceIds: []*string{
			aws.String("XmlStringMaxLen16"), // Required
			// More values...
		},
		MaxRecords: aws.Int64(1),
		NextToken:  aws.String("XmlString"),
	}
	resp, err := svc.DescribeAutoScalingInstances(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeAutoScalingNotificationTypes() {
	svc := autoscaling.New(nil)

	var params *autoscaling.DescribeAutoScalingNotificationTypesInput
	resp, err := svc.DescribeAutoScalingNotificationTypes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeLaunchConfigurations() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeLaunchConfigurationsInput{
		LaunchConfigurationNames: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		MaxRecords: aws.Int64(1),
		NextToken:  aws.String("XmlString"),
	}
	resp, err := svc.DescribeLaunchConfigurations(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeLifecycleHookTypes() {
	svc := autoscaling.New(nil)

	var params *autoscaling.DescribeLifecycleHookTypesInput
	resp, err := svc.DescribeLifecycleHookTypes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeLifecycleHooks() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeLifecycleHooksInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		LifecycleHookNames: []*string{
			aws.String("AsciiStringMaxLen255"), // Required
			// More values...
		},
	}
	resp, err := svc.DescribeLifecycleHooks(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeLoadBalancers() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeLoadBalancersInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		MaxRecords:           aws.Int64(1),
		NextToken:            aws.String("XmlString"),
	}
	resp, err := svc.DescribeLoadBalancers(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeMetricCollectionTypes() {
	svc := autoscaling.New(nil)

	var params *autoscaling.DescribeMetricCollectionTypesInput
	resp, err := svc.DescribeMetricCollectionTypes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeNotificationConfigurations() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeNotificationConfigurationsInput{
		AutoScalingGroupNames: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		MaxRecords: aws.Int64(1),
		NextToken:  aws.String("XmlString"),
	}
	resp, err := svc.DescribeNotificationConfigurations(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribePolicies() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribePoliciesInput{
		AutoScalingGroupName: aws.String("ResourceName"),
		MaxRecords:           aws.Int64(1),
		NextToken:            aws.String("XmlString"),
		PolicyNames: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		PolicyTypes: []*string{
			aws.String("XmlStringMaxLen64"), // Required
			// More values...
		},
	}
	resp, err := svc.DescribePolicies(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeScalingActivities() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeScalingActivitiesInput{
		ActivityIds: []*string{
			aws.String("XmlString"), // Required
			// More values...
		},
		AutoScalingGroupName: aws.String("ResourceName"),
		MaxRecords:           aws.Int64(1),
		NextToken:            aws.String("XmlString"),
	}
	resp, err := svc.DescribeScalingActivities(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeScalingProcessTypes() {
	svc := autoscaling.New(nil)

	var params *autoscaling.DescribeScalingProcessTypesInput
	resp, err := svc.DescribeScalingProcessTypes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeScheduledActions() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeScheduledActionsInput{
		AutoScalingGroupName: aws.String("ResourceName"),
		EndTime:              aws.Time(time.Now()),
		MaxRecords:           aws.Int64(1),
		NextToken:            aws.String("XmlString"),
		ScheduledActionNames: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		StartTime: aws.Time(time.Now()),
	}
	resp, err := svc.DescribeScheduledActions(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeTags() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeTagsInput{
		Filters: []*autoscaling.Filter{
			{ // Required
				Name: aws.String("XmlString"),
				Values: []*string{
					aws.String("XmlString"), // Required
					// More values...
				},
			},
			// More values...
		},
		MaxRecords: aws.Int64(1),
		NextToken:  aws.String("XmlString"),
	}
	resp, err := svc.DescribeTags(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DescribeTerminationPolicyTypes() {
	svc := autoscaling.New(nil)

	var params *autoscaling.DescribeTerminationPolicyTypesInput
	resp, err := svc.DescribeTerminationPolicyTypes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DetachInstances() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DetachInstancesInput{
		AutoScalingGroupName:           aws.String("ResourceName"), // Required
		ShouldDecrementDesiredCapacity: aws.Bool(true),             // Required
		InstanceIds: []*string{
			aws.String("XmlStringMaxLen16"), // Required
			// More values...
		},
	}
	resp, err := svc.DetachInstances(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DetachLoadBalancers() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DetachLoadBalancersInput{
		AutoScalingGroupName: aws.String("ResourceName"),
		LoadBalancerNames: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
	}
	resp, err := svc.DetachLoadBalancers(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_DisableMetricsCollection() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DisableMetricsCollectionInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		Metrics: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
	}
	resp, err := svc.DisableMetricsCollection(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_EnableMetricsCollection() {
	svc := autoscaling.New(nil)

	params := &autoscaling.EnableMetricsCollectionInput{
		AutoScalingGroupName: aws.String("ResourceName"),       // Required
		Granularity:          aws.String("XmlStringMaxLen255"), // Required
		Metrics: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
	}
	resp, err := svc.EnableMetricsCollection(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_EnterStandby() {
	svc := autoscaling.New(nil)

	params := &autoscaling.EnterStandbyInput{
		AutoScalingGroupName:           aws.String("ResourceName"), // Required
		ShouldDecrementDesiredCapacity: aws.Bool(true),             // Required
		InstanceIds: []*string{
			aws.String("XmlStringMaxLen16"), // Required
			// More values...
		},
	}
	resp, err := svc.EnterStandby(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_ExecutePolicy() {
	svc := autoscaling.New(nil)

	params := &autoscaling.ExecutePolicyInput{
		PolicyName:           aws.String("ResourceName"), // Required
		AutoScalingGroupName: aws.String("ResourceName"),
		BreachThreshold:      aws.Float64(1.0),
		HonorCooldown:        aws.Bool(true),
		MetricValue:          aws.Float64(1.0),
	}
	resp, err := svc.ExecutePolicy(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_ExitStandby() {
	svc := autoscaling.New(nil)

	params := &autoscaling.ExitStandbyInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		InstanceIds: []*string{
			aws.String("XmlStringMaxLen16"), // Required
			// More values...
		},
	}
	resp, err := svc.ExitStandby(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_PutLifecycleHook() {
	svc := autoscaling.New(nil)

	params := &autoscaling.PutLifecycleHookInput{
		AutoScalingGroupName:  aws.String("ResourceName"),         // Required
		LifecycleHookName:     aws.String("AsciiStringMaxLen255"), // Required
		DefaultResult:         aws.String("LifecycleActionResult"),
		HeartbeatTimeout:      aws.Int64(1),
		LifecycleTransition:   aws.String("LifecycleTransition"),
		NotificationMetadata:  aws.String("XmlStringMaxLen1023"),
		NotificationTargetARN: aws.String("ResourceName"),
		RoleARN:               aws.String("ResourceName"),
	}
	resp, err := svc.PutLifecycleHook(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_PutNotificationConfiguration() {
	svc := autoscaling.New(nil)

	params := &autoscaling.PutNotificationConfigurationInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		NotificationTypes: []*string{ // Required
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
		TopicARN: aws.String("ResourceName"), // Required
	}
	resp, err := svc.PutNotificationConfiguration(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_PutScalingPolicy() {
	svc := autoscaling.New(nil)

	params := &autoscaling.PutScalingPolicyInput{
		AdjustmentType:          aws.String("XmlStringMaxLen255"), // Required
		AutoScalingGroupName:    aws.String("ResourceName"),       // Required
		PolicyName:              aws.String("XmlStringMaxLen255"), // Required
		Cooldown:                aws.Int64(1),
		EstimatedInstanceWarmup: aws.Int64(1),
		MetricAggregationType:   aws.String("XmlStringMaxLen32"),
		MinAdjustmentMagnitude:  aws.Int64(1),
		MinAdjustmentStep:       aws.Int64(1),
		PolicyType:              aws.String("XmlStringMaxLen64"),
		ScalingAdjustment:       aws.Int64(1),
		StepAdjustments: []*autoscaling.StepAdjustment{
			{ // Required
				ScalingAdjustment:        aws.Int64(1), // Required
				MetricIntervalLowerBound: aws.Float64(1.0),
				MetricIntervalUpperBound: aws.Float64(1.0),
			},
			// More values...
		},
	}
	resp, err := svc.PutScalingPolicy(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_PutScheduledUpdateGroupAction() {
	svc := autoscaling.New(nil)

	params := &autoscaling.PutScheduledUpdateGroupActionInput{
		AutoScalingGroupName: aws.String("ResourceName"),       // Required
		ScheduledActionName:  aws.String("XmlStringMaxLen255"), // Required
		DesiredCapacity:      aws.Int64(1),
		EndTime:              aws.Time(time.Now()),
		MaxSize:              aws.Int64(1),
		MinSize:              aws.Int64(1),
		Recurrence:           aws.String("XmlStringMaxLen255"),
		StartTime:            aws.Time(time.Now()),
		Time:                 aws.Time(time.Now()),
	}
	resp, err := svc.PutScheduledUpdateGroupAction(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_RecordLifecycleActionHeartbeat() {
	svc := autoscaling.New(nil)

	params := &autoscaling.RecordLifecycleActionHeartbeatInput{
		AutoScalingGroupName: aws.String("ResourceName"),         // Required
		LifecycleActionToken: aws.String("LifecycleActionToken"), // Required
		LifecycleHookName:    aws.String("AsciiStringMaxLen255"), // Required
	}
	resp, err := svc.RecordLifecycleActionHeartbeat(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_ResumeProcesses() {
	svc := autoscaling.New(nil)

	params := &autoscaling.ScalingProcessQuery{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		ScalingProcesses: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
	}
	resp, err := svc.ResumeProcesses(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_SetDesiredCapacity() {
	svc := autoscaling.New(nil)

	params := &autoscaling.SetDesiredCapacityInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		DesiredCapacity:      aws.Int64(1),               // Required
		HonorCooldown:        aws.Bool(true),
	}
	resp, err := svc.SetDesiredCapacity(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_SetInstanceHealth() {
	svc := autoscaling.New(nil)

	params := &autoscaling.SetInstanceHealthInput{
		HealthStatus:             aws.String("XmlStringMaxLen32"), // Required
		InstanceId:               aws.String("XmlStringMaxLen16"), // Required
		ShouldRespectGracePeriod: aws.Bool(true),
	}
	resp, err := svc.SetInstanceHealth(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_SuspendProcesses() {
	svc := autoscaling.New(nil)

	params := &autoscaling.ScalingProcessQuery{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		ScalingProcesses: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
	}
	resp, err := svc.SuspendProcesses(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_TerminateInstanceInAutoScalingGroup() {
	svc := autoscaling.New(nil)

	params := &autoscaling.TerminateInstanceInAutoScalingGroupInput{
		InstanceId:                     aws.String("XmlStringMaxLen16"), // Required
		ShouldDecrementDesiredCapacity: aws.Bool(true),                  // Required
	}
	resp, err := svc.TerminateInstanceInAutoScalingGroup(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

func ExampleAutoScaling_UpdateAutoScalingGroup() {
	svc := autoscaling.New(nil)

	params := &autoscaling.UpdateAutoScalingGroupInput{
		AutoScalingGroupName: aws.String("ResourceName"), // Required
		AvailabilityZones: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
		DefaultCooldown:         aws.Int64(1),
		DesiredCapacity:         aws.Int64(1),
		HealthCheckGracePeriod:  aws.Int64(1),
		HealthCheckType:         aws.String("XmlStringMaxLen32"),
		LaunchConfigurationName: aws.String("ResourceName"),
		MaxSize:                 aws.Int64(1),
		MinSize:                 aws.Int64(1),
		PlacementGroup:          aws.String("XmlStringMaxLen255"),
		TerminationPolicies: []*string{
			aws.String("XmlStringMaxLen1600"), // Required
			// More values...
		},
		VPCZoneIdentifier: aws.String("XmlStringMaxLen255"),
	}
	resp, err := svc.UpdateAutoScalingGroup(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}


text:
require "bigdecimal"
require "date"

module SmartAnswer::Calculators
  class HolidayEntitlement
    # created for the holiday entitlement calculator
    STATUTORY_HOLIDAY_ENTITLEMENT_IN_WEEKS = BigDecimal(5.6, 10)
    MAXIMUM_STATUTORY_DAYS_PER_WEEK = 5.to_d
    MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT_IN_DAYS = 28.to_d
    MONTHS_PER_YEAR = 12.to_d
    DAYS_PER_YEAR = 365.to_d
    DAYS_PER_WEEK = 7.to_d
    DAYS_PER_LEAP_YEAR = 366.to_d
    STANDARD_WORKING_DAYS_PER_WEEK = 5.to_d

    attr_accessor :calculation_basis,
                  :holiday_period,
                  :leave_year_start_date,
                  :hours_per_shift

    attr_reader :hours_per_week,
                :start_date,
                :leaving_date,
                :working_days_per_week,
                :shifts_per_shift_pattern,
                :days_per_shift_pattern

    def initialize
      @leave_year_start_date = calculate_leave_year_start_date
    end

    def start_date=(date)
      @start_date = date
      @leave_year_start_date = calculate_leave_year_start_date
    end

    def leaving_date=(date)
      @leaving_date = date
      @leave_year_start_date = calculate_leave_year_start_date
    end

    def hours_per_week=(hours)
      @hours_per_week = BigDecimal(hours, 10)
    end

    def working_days_per_week=(days)
      @working_days_per_week = BigDecimal(days, 10)
    end

    def shifts_per_shift_pattern=(shifts)
      @shifts_per_shift_pattern = BigDecimal(shifts, 10)
    end

    def days_per_shift_pattern=(days)
      @days_per_shift_pattern = BigDecimal(days, 10)
    end

    def holiday_entitlement_hours
      full_time_part_time_hours_and_minutes.first
    end

    def holiday_entitlement_minutes
      full_time_part_time_hours_and_minutes.last
    end

    def hours_daily
      compressed_hours_daily_average.first
    end

    def minutes_daily
      compressed_hours_daily_average.last
    end

    def compressed_hours_daily_average
      minutes = hours_per_week.to_f / working_days_per_week * 60
      minutes.ceil.divmod(60).map(&:ceil)
    end

    def full_time_part_time_days
      days = STATUTORY_HOLIDAY_ENTITLEMENT_IN_WEEKS * working_days_per_week
      actual_days = if working_days_per_week > STANDARD_WORKING_DAYS_PER_WEEK
                      MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT_IN_DAYS
                    else
                      [MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT_IN_DAYS, days].min
                    end
      (actual_days * fraction_of_year).round(10)
    end

    def rounded_full_time_part_time_days
      if started_after_year_began?
        (full_time_part_time_days * 2).ceil / 2.0
      else
        full_time_part_time_days
      end
    end

    def formatted_full_time_part_time_days
      format_number(rounded_full_time_part_time_days)
    end

    def full_time_part_time_hours
      minimum_days_per_week = [working_days_per_week, MAXIMUM_STATUTORY_DAYS_PER_WEEK].min

      STATUTORY_HOLIDAY_ENTITLEMENT_IN_WEEKS * minimum_days_per_week * (hours_per_week / working_days_per_week)
    end

    def rounded_full_time_part_time_hours
      if started_after_year_began? || worked_full_year?
        (rounded_full_time_part_time_days * hours_per_week) / working_days_per_week
      else
        full_time_part_time_hours
      end
    end

    def formatted_full_time_part_time_compressed_hours
      if left_before_year_end? || worked_partial_year?
        format_number(pro_rated_hours, 1)
      else
        format_number(rounded_full_time_part_time_hours, 1)
      end
    end

    def full_time_part_time_hours_and_minutes
      time_in_seconds = (BigDecimal(formatted_full_time_part_time_compressed_hours, 10) * 3600).to_i
      seconds = time_in_seconds % 60
      minutes = (time_in_seconds / 60) % 60
      hours = time_in_seconds / 3600
      [hours, seconds < 30 ? minutes : minutes + 1]
    end

    def pro_rated_hours
      fraction_of_year * rounded_full_time_part_time_hours
    end

    def full_time_part_time_weeks
      if worked_full_year?
        STATUTORY_HOLIDAY_ENTITLEMENT_IN_WEEKS
      else
        STATUTORY_HOLIDAY_ENTITLEMENT_IN_WEEKS * fraction_of_year
      end
    end

    def formatted_full_time_part_time_weeks
      if worked_full_year?
        format_number(full_time_part_time_weeks)
      else
        format_number(full_time_part_time_weeks, 2)
      end
    end

    def fraction_of_year
      days_in_year = leave_year_range.leap? ? DAYS_PER_LEAP_YEAR : DAYS_PER_YEAR

      if started_after_year_began?
        months_worked / MONTHS_PER_YEAR
      elsif worked_partial_year?
        BigDecimal(leaving_date - start_date + 1.0, 10) / days_in_year
      elsif left_before_year_end?
        BigDecimal(leaving_date - leave_year_range.begins_on + 1, 10) / days_in_year
      else
        1
      end
    end

    def shift_entitlement
      if left_before_year_end? || worked_partial_year?
        format_number(rounded_shift_entitlement, 2)
      elsif started_after_year_began? || worked_full_year?
        format_number(rounded_shift_entitlement)
      end
    end

    def rounded_shift_entitlement
      minimum_days_per_week = [shifts_per_week, MAXIMUM_STATUTORY_DAYS_PER_WEEK].min
      pro_rated_shifts = STATUTORY_HOLIDAY_ENTITLEMENT_IN_WEEKS * fraction_of_year * minimum_days_per_week

      started_after_year_began? ? (pro_rated_shifts * 2).ceil / 2.0 : pro_rated_shifts
    end

    def shifts_per_week
      (shifts_per_shift_pattern / days_per_shift_pattern * DAYS_PER_WEEK).round(10)
    end

  private

    def calculate_leave_year_start_date
      worked_partial_year? ? start_date : Time.zone.today
    end

    def worked_full_year?
      start_date.nil? && leaving_date.nil?
    end

    def started_after_year_began?
      start_date.present? && leaving_date.nil?
    end

    def left_before_year_end?
      start_date.nil? && leaving_date.present?
    end

    def worked_partial_year?
      start_date.present? && leaving_date.present?
    end

    def months_worked
      year_difference = BigDecimal(leave_year_range.ends_on.year - start_date.year, 10)
      month_difference = MONTHS_PER_YEAR * year_difference + leave_year_range.ends_on.month - start_date.month
      leave_year_range.ends_on.day >= start_date.day ? month_difference + 1 : month_difference
    end

    def leave_year_range
      SmartAnswer::YearRange.resetting_on(leave_year_start_date).including(date_calc)
    end

    def date_calc
      return leave_year_start_date if worked_full_year?

      return leaving_date if leaving_date

      start_date
    end

    def strip_zeros(number)
      number.to_s.sub(/\.0+$/, "")
    end

    def format_number(number, decimal_places = 1)
      rounded = (number * 10**decimal_places).ceil.to_f / 10**decimal_places
      str = sprintf("%.#{decimal_places}f", rounded)
      strip_zeros(str)
    end
  end
end


text:
package com.longcoding.moon.controllers.internal;

import com.longcoding.moon.models.ehcache.ApiInfo;
import com.longcoding.moon.models.ehcache.ApiMetaInfo;
import com.longcoding.moon.models.enumeration.SyncType;
import com.longcoding.moon.models.internal.EnrollApi;
import com.longcoding.moon.services.internal.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Internal API for managing API specifications
 * Any node in the cluster can receive these requests.
 * When it receives the request, it sends the event to other nodes.
 *
 * The model object for the client request differs from the model object for the service layer.
 *
 * @author longcoding
 */

@Slf4j
@RestController
@RequestMapping(value = "/internal/apis")
public class ApiController {

    @Autowired
    ApiService apiService;

    /**
     * Register a new API specification. This job does not load into the cache.
     * When a new API specification request is received, it serves to issue events to other nodes, including itself.
     *
     * @param enrollApi API specification model for client requests.
     * @return API specification model for internal processing.
     */
    @RequestMapping(method = RequestMethod.POST)
    public ApiInfo createApi(@RequestBody EnrollApi enrollApi) { return apiService.createOrModifyApi(SyncType.CREATE,  enrollApi); }

    /**
     * Delete the existing api specification. This action does not directly apply to the cache.
     * When a new api specification update request is received, it is responsible for issuing an event to other nodes including itself.
     *
     * @param apiId Application Id.
     * @return Returns success or failure.
     */
    @RequestMapping(value = "{apiId}", method = RequestMethod.DELETE)
    public boolean deleteApi(@PathVariable int apiId) { return apiService.deleteApi(apiId); }

    /**
     * Update existing api specifications. This action does not directly apply to the cache.
     * When a new api specification update request is received, it is responsible for issuing an event to other nodes including itself.
     *
     * @param apiId Application Id.
     * @param enrollApi API specification model for client requests.
     * @return API specification model for internal processing.
     */
    @RequestMapping(value = "{apiId}", method = RequestMethod.PUT)
    public ApiInfo updateApi(@PathVariable int apiId, @RequestBody EnrollApi enrollApi) { return apiService.createOrModifyApi(SyncType.UPDATE, enrollApi); }

       /**
     * Query the corresponding api specification.
     *
     * @param apiId Application Id.
     * @return API specification model for internal processing.
     */
    @RequestMapping(value = "{apiId}", method = RequestMethod.GET)
    public ApiInfo getApi(@PathVariable int apiId) { return apiService.selectApi(apiId); }

    /**
     * Query the all apis specification.
     *
     * @return API specification model list for internal processing.
     */
    @RequestMapping(method = RequestMethod.GET)
    public List<ApiMetaInfo> getAllApiInfo() { return apiService.getAllApiInfo(); }

}


text:
package com.cloudera.oryx.app.als;

import java.util.List;

/**
 * Abstract implementation of {@link RescorerProvider} which implements all methods to
 * return {@code null}.
 */
public abstract class AbstractRescorerProvider implements RescorerProvider {

  /**
   * @return {@code null}
   */
  @Override
  public Rescorer getRecommendRescorer(List<String> userIDs, List<String> args) {
    return null;
  }

  /**
   * @return {@code null}
   */
  @Override
  public Rescorer getRecommendToAnonymousRescorer(List<String> itemIDs, List<String> args) {
    return null;
  }

  /**
   * @return {@code null}
   */
  @Override
  public Rescorer getMostPopularItemsRescorer(List<String> args) {
    return null;
  }

  /**
   * @return {@code null}
   */
  @Override
  public Rescorer getMostActiveUsersRescorer(List<String> args) {
    return null;
  }

  /**
   * @return {@code null}
   */
  @Override
  public Rescorer getMostSimilarItemsRescorer(List<String> args) {
    return null;
  }

}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>ThingsBoard</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="thingsboard.ico">
  <link rel="preload" href="assets/fonts/MaterialIcons-Regular.ttf" as="font" type="font/ttf" crossorigin="anonymous" />
  <link rel="stylesheet" href="assets/fonts/material-icons.css" />

  <tb-root></tb-root>


text:
require "Window"
require "GameLib"
require "Apollo"

local ForgeUI
local ForgeUI_InterfaceMenuList = {}

function ForgeUI_InterfaceMenuList:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self

	-- mandatory
    self.api_version = 1
	self.version = "0.1.0"
	self.author = "WintyBadass"
	self.strAddonName = "ForgeUI_InterfaceMenuList"
	self.strDisplayName = "Interface menu list"

	self.wndContainers = {}

	-- optional
	self.tSettings = {
		tPinnedAddons = {}
	}

    return o
end

function ForgeUI_InterfaceMenuList:Init()
	local bHasConfigureFunction = false
	local strConfigureButtonText = ""
	local tDependencies = {
		"ForgeUI"
	}
    Apollo.RegisterAddon(self, bHasConfigureFunction, strConfigureButtonText, tDependencies)
end

function ForgeUI_InterfaceMenuList:OnLoad()
	self.xmlDoc = XmlDoc.CreateFromFile("ForgeUI_InterfaceMenuList.xml")
	self.xmlDoc:RegisterCallback("OnDocumentReady", self)
end

function ForgeUI_InterfaceMenuList:OnDocumentReady()
	if self.xmlDoc == nil and not self.xmlDoc:IsLoaded() then return end

	if ForgeUI == nil then -- forgeui loaded
		ForgeUI = Apollo.GetAddon("ForgeUI")
	end

	ForgeUI.RegisterAddon(self)

end

function ForgeUI_InterfaceMenuList:ForgeAPI_AfterRegistration()
	Apollo.RegisterEventHandler("VarChange_FrameCount", "OnNextFrame", self)

	Apollo.RegisterEventHandler("InterfaceMenuList_NewAddOn", 			"OnNewAddonListed", self)
	Apollo.RegisterEventHandler("InterfaceMenuList_AlertAddOn", 		"OnDrawAlert", self)
	Apollo.RegisterEventHandler("CharacterCreated", 					"OnCharacterCreated", self)
	Apollo.RegisterEventHandler("Tutorial_RequestUIAnchor", 			"OnTutorial_RequestUIAnchor", self)
	Apollo.RegisterTimerHandler("TimeUpdateTimer", 						"OnUpdateTimer", self)
	Apollo.RegisterTimerHandler("QueueRedrawTimer", 					"OnQueuedRedraw", self)
	Apollo.RegisterEventHandler("ApplicationWindowSizeChanged", 		"ButtonListRedraw", self)
	Apollo.RegisterEventHandler("OptionsUpdated_HUDPreferences", 		"OnUpdateTimer", self)

    self.wndMain = Apollo.LoadForm(self.xmlDoc , "ForgeUI_InterfaceMenuListForm", "FixedHudStratumHigh", self)
	self.wndList = Apollo.LoadForm(self.xmlDoc , "FullListFrame", nil, self)

	self.wndMain:FindChild("OpenFullListBtn"):AttachWindow(self.wndList)
	self.wndMain:FindChild("OpenFullListBtn"):Enable(false)

	Apollo.CreateTimer("QueueRedrawTimer", 0.3, false)

	self.tMenuData = {
		[Apollo.GetString("InterfaceMenu_SystemMenu")] = { "", "Escape", "Icon_Windows32_UI_CRB_InterfaceMenu_EscMenu" }, --
	}

	self.tMenuTooltips = {}
	self.tMenuAlerts = {}

	if GameLib.GetPlayerUnit() then
		self:OnCharacterCreated()
	end

end

function ForgeUI_InterfaceMenuList:ForgeAPI_AfterRestore()
	if #self.tSettings.tPinnedAddons == 0 then
		self.tSettings.tPinnedAddons = {
			Apollo.GetString("InterfaceMenu_AccountInventory"),
			Apollo.GetString("InterfaceMenu_Character"),
			Apollo.GetString("InterfaceMenu_AbilityBuilder"),
			Apollo.GetString("InterfaceMenu_QuestLog"),
			Apollo.GetString("InterfaceMenu_GroupFinder"),
			Apollo.GetString("InterfaceMenu_Social"),
			Apollo.GetString("InterfaceMenu_Mail"),
			Apollo.GetString("InterfaceMenu_Lore")
		}
	end

	self:ButtonListRedraw()
end

function ForgeUI_InterfaceMenuList:OnListShow()
	self.wndList:ToFront()
end

function ForgeUI_InterfaceMenuList:OnCharacterCreated()
	Apollo.CreateTimer("TimeUpdateTimer", 1.0, true)
end

function ForgeUI_InterfaceMenuList:OnUpdateTimer()
	if not self.bHasLoaded then
		Event_FireGenericEvent("InterfaceMenuListHasLoaded")
		self.wndMain:FindChild("OpenFullListBtn"):Enable(true)
		self.bHasLoaded = true
	end

	--Toggle Visibility based on ui preference
	local nVisibility = Apollo.GetConsoleVariable("hud.TimeDisplay")

	local tLocalTime = GameLib.GetLocalTime()
	local tServerTime = GameLib.GetServerTime()
	local b24Hour = true
	local nLocalHour = tLocalTime.nHour > 12 and tLocalTime.nHour - 12 or tLocalTime.nHour == 0 and 12 or tLocalTime.nHour
	local nServerHour = tServerTime.nHour > 12 and tServerTime.nHour - 12 or tServerTime.nHour == 0 and 12 or tServerTime.nHour

	self.wndMain:FindChild("Time"):SetText(string.format("%02d:%02d", tostring(tLocalTime.nHour), tostring(tLocalTime.nMinute)))

	if nVisibility == 2 then --Local 12hr am/pm
		self.wndMain:FindChild("Time"):SetText(string.format("%02d:%02d", tostring(nLocalHour), tostring(tLocalTime.nMinute)))

		b24Hour = false
	elseif nVisibility == 3 then --Server 24hr
		self.wndMain:FindChild("Time"):SetText(string.format("%02d:%02d", tostring(tServerTime.nHour), tostring(tServerTime.nMinute)))
	elseif nVisibility == 4 then --Server 12hr am/pm
		self.wndMain:FindChild("Time"):SetText(string.format("%02d:%02d", tostring(nServerHour), tostring(tServerTime.nMinute)))

		b24Hour = false
	end

	nLocalHour = b24Hour and tLocalTime.nHour or nLocalHour
	nServerHour = b24Hour and tServerTime.nHour or nServerHour

	self.wndMain:FindChild("Time"):SetTooltip(
		string.format("%s%02d:%02d\n%s%02d:%02d",
			Apollo.GetString("OptionsHUD_Local"), tostring(nLocalHour), tostring(tLocalTime.nMinute),
			Apollo.GetString("OptionsHUD_Server"), tostring(nServerHour), tostring(tServerTime.nMinute)
		)
	)
end

function ForgeUI_InterfaceMenuList:OnNewAddonListed(strKey, tParams)
	strKey = string.gsub(strKey, ":", "|") -- ":'s don't work for window names, sorry!"

	self.tMenuData[strKey] = tParams

	self:FullListRedraw()
	self:ButtonListRedraw()
end

function ForgeUI_InterfaceMenuList:IsPinned(strText)
	for idx, strWindowText in pairs(self.tSettings.tPinnedAddons) do
		if (strText == strWindowText) then
			return true
		end
	end

	return false
end

function ForgeUI_InterfaceMenuList:FullListRedraw()
	local strUnbound = Apollo.GetString("Keybinding_Unbound")
	local wndParent = self.wndList:FindChild("FullListScroll")

	local strQuery = Apollo.StringToLower(tostring(self.wndList:FindChild("SearchEditBox"):GetText()) or "")
	if strQuery == nil or strQuery == "" or not strQuery:match("[%w%s]+") then
		strQuery = ""
	end

	for strWindowText, tData in pairs(self.tMenuData) do
		local bSearchResultMatch = string.find(Apollo.StringToLower(strWindowText), strQuery) ~= nil

		if strQuery == "" or bSearchResultMatch then
			local wndMenuItem = self:LoadByName("MenuListItem", wndParent, strWindowText)
			local wndMenuButton = self:LoadByName("InterfaceMenuButton", wndMenuItem:FindChild("Icon"), strWindowText)
			local strTooltip = strWindowText

			if string.len(tData[2]) > 0 then
				local strKeyBindLetter = GameLib.GetKeyBinding(tData[2])
				strKeyBindLetter = strKeyBindLetter == strUnbound and "" or string.format(" (%s)", strKeyBindLetter)  -- LOCALIZE

				strTooltip = strKeyBindLetter ~= "" and strTooltip .. strKeyBindLetter or strTooltip
			end

			if tData[3] ~= "" then
				wndMenuButton:FindChild("Icon"):SetSprite(tData[3])
			else
				wndMenuButton:FindChild("Icon"):SetText(string.sub(strTooltip, 1, 1))
			end

			wndMenuButton:FindChild("ShortcutBtn"):SetData(strWindowText)
			wndMenuButton:FindChild("Icon"):SetTooltip(strTooltip)
			self.tMenuTooltips[strWindowText] = strTooltip

			wndMenuItem:FindChild("MenuListItemBtn"):SetText(strWindowText)
			wndMenuItem:FindChild("MenuListItemBtn"):SetData(tData[1])

			wndMenuItem:FindChild("PinBtn"):SetCheck(self:IsPinned(strWindowText))
			wndMenuItem:FindChild("PinBtn"):SetData(strWindowText)

			if string.len(tData[2]) > 0 then
				local strKeyBindLetter = GameLib.GetKeyBinding(tData[2])
				wndMenuItem:FindChild("MenuListItemBtn"):FindChild("MenuListItemKeybind"):SetText(strKeyBindLetter == strUnbound and "" or string.format("(%s)", strKeyBindLetter))  -- LOCALIZE
			end
		elseif not bSearchResultMatch and wndParent:FindChild(strWindowText) then
			wndParent:FindChild(strWindowText):Destroy()
		end
	end

	wndParent:ArrangeChildrenVert(0, function (a,b) return a:GetName() < b:GetName() end)
end

function ForgeUI_InterfaceMenuList:ButtonListRedraw()
	Apollo.StopTimer("QueueRedrawTimer")
	Apollo.StartTimer("QueueRedrawTimer")
end

function ForgeUI_InterfaceMenuList:OnQueuedRedraw()
	local strUnbound = Apollo.GetString("Keybinding_Unbound")
	local wndParent = self.wndMain:FindChild("ButtonList")
	wndParent:DestroyChildren()
	local nParentWidth = wndParent:GetWidth()

	local nLastButtonWidth = 0
	local nTotalWidth = 0

	for idx, strWindowText in pairs(self.tSettings.tPinnedAddons) do
		tData = self.tMenuData[strWindowText]

		--Magic number below is allowing the 1 pixel gutter on the right
		if tData and nTotalWidth + nLastButtonWidth <= nParentWidth + 1 then
			local wndMenuItem = self:LoadByName("InterfaceMenuButton", wndParent, strWindowText)
			local strTooltip = strWindowText
			nLastButtonWidth = wndMenuItem:GetWidth()
			nTotalWidth = nTotalWidth + nLastButtonWidth

			if string.len(tData[2]) > 0 then
				local strKeyBindLetter = GameLib.GetKeyBinding(tData[2])
				strKeyBindLetter = strKeyBindLetter == strUnbound and "" or string.format(" (%s)", strKeyBindLetter)  -- LOCALIZE
				strTooltip = strKeyBindLetter ~= "" and strTooltip .. strKeyBindLetter or strTooltip
			end

			if tData[3] ~= "" then
				wndMenuItem:FindChild("Icon"):SetSprite(tData[3])
			else
				wndMenuItem:FindChild("Icon"):SetText(string.sub(strTooltip, 1, 1))
			end

			wndMenuItem:FindChild("ShortcutBtn"):SetData(strWindowText)
			wndMenuItem:FindChild("Icon"):SetTooltip(strTooltip)
		end

		if self.tMenuAlerts[strWindowText] then
			self:OnDrawAlert(strWindowText, self.tMenuAlerts[strWindowText])
		end
	end

	wndParent:ArrangeChildrenHorz(0)
end

-----------------------------------------------------------------------------------------------
-- Search
-----------------------------------------------------------------------------------------------

function ForgeUI_InterfaceMenuList:OnSearchEditBoxChanged(wndHandler, wndControl)
	self.wndList:FindChild("SearchClearBtn"):Show(string.len(wndHandler:GetText() or "") > 0)
	self:FullListRedraw()
end

function ForgeUI_InterfaceMenuList:OnSearchClearBtn(wndHandler, wndControl)
	self.wndList:FindChild("SearchFlash"):SetSprite("CRB_WindowAnimationSprites:sprWinAnim_BirthSmallTemp")
	self.wndList:FindChild("SearchFlash"):SetFocus()
	self.wndList:FindChild("SearchClearBtn"):Show(false)
	self.wndList:FindChild("SearchEditBox"):SetText("")
	self:FullListRedraw()
end

function ForgeUI_InterfaceMenuList:OnSearchCommitBtn(wndHandler, wndControl)
	self.wndList:FindChild("SearchFlash"):SetSprite("CRB_WindowAnimationSprites:sprWinAnim_BirthSmallTemp")
	self.wndList:FindChild("SearchFlash"):SetFocus()
	self:FullListRedraw()
end

-----------------------------------------------------------------------------------------------
-- Alerts
-----------------------------------------------------------------------------------------------

function ForgeUI_InterfaceMenuList:OnDrawAlert(strWindowName, tParams)
	self.tMenuAlerts[strWindowName] = tParams
	for idx, wndTarget in pairs(self.wndMain:FindChild("ButtonList"):GetChildren()) do
		if wndTarget and tParams then
			local wndButton = wndTarget:FindChild("ShortcutBtn")
			if wndButton then
				local wndIcon = wndButton:FindChild("Icon")

				if wndButton:GetData() == strWindowName then
					if tParams[1] then
						local wndIndicator = self:LoadByName("AlertIndicator", wndButton:FindChild("Alert"), "AlertIndicator")

					elseif wndButton:FindChild("AlertIndicator") ~= nil then
						wndButton:FindChild("AlertIndicator"):Destroy()
					end

					if tParams[2] then
						wndIcon:SetTooltip(string.format("%s\n\n%s", self.tMenuTooltips[strWindowName], tParams[2]))
					end

					if tParams[3] and tParams[3] > 0 then
						local strColor = tParams[1] and "UI_WindowTextOrange" or "UI_TextHoloTitle"

						wndButton:FindChild("Number"):Show(true)
						wndButton:FindChild("Number"):SetText(tParams[3])
						wndButton:FindChild("Number"):SetTextColor(ApolloColor.new(strColor))
					else
						wndButton:FindChild("Number"):Show(false)
						wndButton:FindChild("Number"):SetText("")
						wndButton:FindChild("Number"):SetTextColor(ApolloColor.new("UI_TextHoloTitle"))
					end
				end
			end
		end
	end

	local wndParent = self.wndList:FindChild("FullListScroll")
	for idx, wndTarget in pairs(wndParent:GetChildren()) do
		local wndButton = wndTarget:FindChild("ShortcutBtn")
		local wndIcon = wndButton:FindChild("Icon")

		if wndButton:GetData() == strWindowName then
			if tParams[1] then
				local wndIndicator = self:LoadByName("AlertIndicator", wndButton:FindChild("Alert"), "AlertIndicator")
			elseif wndButton:FindChild("AlertIndicator") ~= nil then
				wndButton:FindChild("AlertIndicator"):Destroy()
			end

			if tParams[2] then
				wndIcon:SetTooltip(string.format("%s\n\n%s", self.tMenuTooltips[strWindowName], tParams[2]))
			end

			if tParams[3] and tParams[3] > 0 then
				local strColor = tParams[1] and "UI_WindowTextOrange" or "UI_TextHoloTitle"

				wndButton:FindChild("Number"):Show(true)
				wndButton:FindChild("Number"):SetText(tParams[3])
				wndButton:FindChild("Number"):SetTextColor(ApolloColor.new(strColor))
			else
				wndButton:FindChild("Number"):Show(false)
			end
		end
	end
end

-----------------------------------------------------------------------------------------------
-- Helpers and Errata
-----------------------------------------------------------------------------------------------

function ForgeUI_InterfaceMenuList:OnMenuListItemClick(wndHandler, wndControl)
	if wndHandler ~= wndControl then return end

	if string.len(wndControl:GetData()) > 0 then
		Event_FireGenericEvent(wndControl:GetData())
	else
		InvokeOptionsScreen()
	end
	self.wndList:Show(false)
end

function ForgeUI_InterfaceMenuList:OnPinBtnChecked(wndHandler, wndControl)
	if wndHandler ~= wndControl then return end

	local wndParent = wndControl:GetParent():GetParent()

	self.tSettings.tPinnedAddons = {}

	for idx, wndMenuItem in pairs(wndParent:GetChildren()) do
		if wndMenuItem:FindChild("PinBtn"):IsChecked() then

			table.insert(self.tSettings.tPinnedAddons, wndMenuItem:FindChild("PinBtn"):GetData())
		end
	end

	self:ButtonListRedraw()
end

function ForgeUI_InterfaceMenuList:OnListBtnClick(wndHandler, wndControl) -- These are the five always on icons on the top
	if wndHandler ~= wndControl then return end
	local strMappingResult = self.tMenuData[wndHandler:GetData()][1] or ""

	if string.len(strMappingResult) > 0 then
		Event_FireGenericEvent(strMappingResult)
	else
		InvokeOptionsScreen()
	end
end

function ForgeUI_InterfaceMenuList:OnListBtnMouseEnter(wndHandler, wndControl)
	wndHandler:SetBGColor("ffffffff")
	if wndHandler ~= wndControl or self.wndList:IsVisible() then
		return
	end
end

function ForgeUI_InterfaceMenuList:OnListBtnMouseExit(wndHandler, wndControl) -- Also self.wndMain MouseExit and ButtonList MouseExit
	wndHandler:SetBGColor("9dffffff")
end

function ForgeUI_InterfaceMenuList:OnOpenFullListCheck(wndHandler, wndControl)
	self.wndList:FindChild("SearchEditBox"):SetFocus()
	self:FullListRedraw()
end

function ForgeUI_InterfaceMenuList:LoadByName(strForm, wndParent, strCustomName)
	local wndNew = wndParent:FindChild(strCustomName)
	if not wndNew then
		wndNew = Apollo.LoadForm(self.xmlDoc , strForm, wndParent, self)
		wndNew:SetName(strCustomName)
	end
	return wndNew
end

function ForgeUI_InterfaceMenuList:OnTutorial_RequestUIAnchor(eAnchor, idTutorial, strPopupText)
	local arTutorialAnchorMapping =
	{
		--[GameLib.CodeEnumTutorialAnchor.Abilities] 			= "LASBtn",
		--[GameLib.CodeEnumTutorialAnchor.Character] 		= "CharacterBtn",
		--[GameLib.CodeEnumTutorialAnchor.Mail] 				= "MailBtn",
		--[GameLib.CodeEnumTutorialAnchor.GalacticArchive] = "LoreBtn",
		--[GameLib.CodeEnumTutorialAnchor.Social] 			= "SocialBtn",
		--[GameLib.CodeEnumTutorialAnchor.GroupFinder] 		= "GroupFinderBtn",
	}

	local strWindowName = "ButtonList" or false
	if not strWindowName then
		return
	end

	local tRect = {}
	tRect.l, tRect.t, tRect.r, tRect.b = self.wndMain:FindChild(strWindowName):GetRect()
	tRect.r = tRect.r - 26

	if arTutorialAnchorMapping[eAnchor] then
		Event_FireGenericEvent("Tutorial_RequestUIAnchorResponse", eAnchor, idTutorial, strPopupText, tRect)
	end
end

local ForgeUI_InterfaceMenuListInst = ForgeUI_InterfaceMenuList:new()
ForgeUI_InterfaceMenuListInst:Init()