text:
package org.pilgrim.leetcode.easy;

import java.util.Arrays;

/**
 * In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.

At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.

What is the maximum total sum that the height of the buildings can be increased?

Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
  [2, 4, 5, 7],
  [9, 2, 6, 3],
  [0, 3, 1, 0] ]

The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]

The grid after increasing the height of buildings without affecting skylines is:

gridNew = [ [8, 4, 8, 7],
            [7, 4, 7, 7],
            [9, 4, 8, 7],
            [3, 3, 3, 3] ]

Notes:

1 < grid.length = grid[0].length <= 50.
All heights grid[i][j] are in the range [0, 100].
All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism.
 * @author segoncha
 *
 */
public class MaxIncreaseKeepCitySkyline {

	public int maxIncreaseKeepingSkyline(int[][] grid) {
		if(null == grid){
			return 0;
		}

		int sum = 0;

		int n = grid.length;
		int m = grid[0].length;
		int[] maxH = new int[n];
		int[] maxV = new int[m];

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				int height = grid[i][j];
				maxH[i] = Math.max(height, maxH[i]);
				maxV[j] = Math.max(height, maxV[j]);
			}
		}

		System.out.println(Arrays.toString(maxH));
		System.out.println(Arrays.toString(maxV));

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				int height = grid[i][j];
				int minMax =Math.min(maxH[i], maxV[j]);
				sum += minMax - height;
			}
		}

		return sum;
    }

	public static void main(String[] args) {

		int[][] grid = {{3,0,8,4},{2,4,5,7},{9,2,6,3},{0,3,1,0}};
		MaxIncreaseKeepCitySkyline citySkyline = new MaxIncreaseKeepCitySkyline();
		System.out.println(citySkyline.maxIncreaseKeepingSkyline(grid));
	}
}


text:
#import <UIKit/UIKit.h>

@interface TabBarInboxSampleAppDelegate : NSObject <UIApplicationDelegate>

- (void)loadInbox;
- (void)setInboxBadgeValue;

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end

redpajama_set_name: RedPajamaGithub


text: syntax and indent settings for CoPL proof


text:
class CreateUserTokens < ActiveRecord::Migration
  def change
    create_table :user_tokens do |t|
      t.belongs_to :user
      t.string :token, index: true
      t.timestamps null: false
    end
  end
end


text:
package core

import (
	"encoding/json"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
)

// InstanceSourceViaBootVolumeDetails The representation of InstanceSourceViaBootVolumeDetails
type InstanceSourceViaBootVolumeDetails struct {

	// The OCID of the boot volume used to boot the instance.
	BootVolumeId *string `mandatory:"true" json:"bootVolumeId"`
}

func (m InstanceSourceViaBootVolumeDetails) String() string {
	return common.PointerString(m)
}

// MarshalJSON marshals to json representation
func (m InstanceSourceViaBootVolumeDetails) MarshalJSON() (buff []byte, e error) {
	type MarshalTypeInstanceSourceViaBootVolumeDetails InstanceSourceViaBootVolumeDetails
	s := struct {
		DiscriminatorParam string `json:"sourceType"`
		MarshalTypeInstanceSourceViaBootVolumeDetails
	}{
		"bootVolume",
		(MarshalTypeInstanceSourceViaBootVolumeDetails)(m),
	}

	return json.Marshal(&s)
}


text:
package org.yaml.snakeyaml.events;

import java.util.Map;

import org.yaml.snakeyaml.DumperOptions.Version;
import org.yaml.snakeyaml.error.Mark;

/**
 * Marks the beginning of a document.
 *

 * This event followed by the document's content and a {@link DocumentEndEvent}.
 *

 */
public final class DocumentStartEvent extends Event {
    private final boolean explicit;
    private final Version version;
    private final Map<String, String> tags;

    public DocumentStartEvent(Mark startMark, Mark endMark, boolean explicit, Version version,
            Map<String, String> tags) {
        super(startMark, endMark);
        this.explicit = explicit;
        this.version = version;
        this.tags = tags;
    }

    public boolean getExplicit() {
        return explicit;
    }

    /**
     * YAML version the document conforms to.
     *
     * @return nullif the document has no explicit
     *         %YAML directive. Otherwise an array with two
     *         components, the major and minor part of the version (in this
     *         order).
     */
    public Version getVersion() {
        return version;
    }

    /**
     * Tag shorthands as defined by the %TAG directive.
     *
     * @return Mapping of 'handles' to 'prefixes' (the handles include the '!'
     *         characters).
     */
    public Map<String, String> getTags() {
        return tags;
    }

    @Override
    public Event.ID getEventId() {
        return ID.DocumentStart;
    }
}


text:
"use strict";

var selector = require('./scxml-dynamic-name-match-transition-selector'),
    ArraySet = require('./set/ArraySet'),
    m = require('./model');

module.exports = function(opts) {
    opts = opts || {};
    opts.TransitionSet = opts.TransitionSet || ArraySet;
    opts.StateSet = opts.StateSet || ArraySet;
    opts.BasicStateSet = opts.BasicStateSet || ArraySet;
    opts.transitionSelector = opts.transitionSelector || selector;
    opts.model = opts.model || m;
    return opts;
};


text:
class P {
  def foo: String = ""
}

class Z extends P {
  override def foo = foo
  val x: String = /*start*/foo/*end*/
}
//String


text:
/*
 * This file is generated by jOOQ.
*/
package org.killbill.billing.plugin.notification.dao.gen.tables;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.Identity;
import org.jooq.Index;
import org.jooq.Name;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.jooq.types.ULong;
import org.killbill.billing.plugin.notification.dao.gen.Indexes;
import org.killbill.billing.plugin.notification.dao.gen.Keys;
import org.killbill.billing.plugin.notification.dao.gen.Killbill;
import org.killbill.billing.plugin.notification.dao.gen.tables.records.EmailNotificationsConfigurationRecord;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.10.1"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class EmailNotificationsConfiguration extends TableImpl<EmailNotificationsConfigurationRecord> {

    private static final long serialVersionUID = 1597491816;

    /**
     * The reference instance of killbill.email_notifications_configuration
     */
    public static final EmailNotificationsConfiguration EMAIL_NOTIFICATIONS_CONFIGURATION = new EmailNotificationsConfiguration();

    /**
     * The class holding records for this type
     */
    @Override
    public Class<EmailNotificationsConfigurationRecord> getRecordType() {
        return EmailNotificationsConfigurationRecord.class;
    }

    /**
     * The column killbill.email_notifications_configuration.record_id.
     */
    public final TableField<EmailNotificationsConfigurationRecord, ULong> RECORD_ID = createField("record_id", org.jooq.impl.SQLDataType.BIGINTUNSIGNED.nullable(false).identity(true), this, "");

    /**
     * The column killbill.email_notifications_configuration.kb_account_id.
     */
    public final TableField<EmailNotificationsConfigurationRecord, String> KB_ACCOUNT_ID = createField("kb_account_id", org.jooq.impl.SQLDataType.VARCHAR(255).defaultValue(org.jooq.impl.DSL.inline("NULL", org.jooq.impl.SQLDataType.VARCHAR)), this, "");

    /**
     * The column killbill.email_notifications_configuration.kb_tenant_id.
     */
    public final TableField<EmailNotificationsConfigurationRecord, String> KB_TENANT_ID = createField("kb_tenant_id", org.jooq.impl.SQLDataType.VARCHAR(255).nullable(false), this, "");

    /**
     * The column killbill.email_notifications_configuration.event_type.
     */
    public final TableField<EmailNotificationsConfigurationRecord, String> EVENT_TYPE = createField("event_type", org.jooq.impl.SQLDataType.VARCHAR(255).defaultValue(org.jooq.impl.DSL.inline("NULL", org.jooq.impl.SQLDataType.VARCHAR)), this, "");

    /**
     * The column killbill.email_notifications_configuration.created_at.
     */
    public final TableField<EmailNotificationsConfigurationRecord, Timestamp> CREATED_AT = createField("created_at", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");

    /**
     * Create a killbill.email_notifications_configuration table reference
     */
    public EmailNotificationsConfiguration() {
        this(DSL.name("email_notifications_configuration"), null);
    }

    /**
     * Create an aliased killbill.email_notifications_configuration table reference
     */
    public EmailNotificationsConfiguration(String alias) {
        this(DSL.name(alias), EMAIL_NOTIFICATIONS_CONFIGURATION);
    }

    /**
     * Create an aliased killbill.email_notifications_configuration table reference
     */
    public EmailNotificationsConfiguration(Name alias) {
        this(alias, EMAIL_NOTIFICATIONS_CONFIGURATION);
    }

    private EmailNotificationsConfiguration(Name alias, Table<EmailNotificationsConfigurationRecord> aliased) {
        this(alias, aliased, null);
    }

    private EmailNotificationsConfiguration(Name alias, Table<EmailNotificationsConfigurationRecord> aliased, Field<?>[] parameters) {
        super(alias, null, aliased, parameters, "");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Schema getSchema() {
        return Killbill.KILLBILL;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Index> getIndexes() {
        return Arrays.<Index>asList(Indexes.EMAIL_NOTIFICATIONS_CONFIGURATION_KENUI_CONFIGURATION_EVENT_TYPE_KB_ACCOUNT_ID, Indexes.EMAIL_NOTIFICATIONS_CONFIGURATION_KENUI_CONFIGURATION_EVENT_TYPE_KB_TENANT_ID, Indexes.EMAIL_NOTIFICATIONS_CONFIGURATION_KENUI_CONFIGURATION_KB_ACCOUNT_ID, Indexes.EMAIL_NOTIFICATIONS_CONFIGURATION_KENUI_CONFIGURATION_KB_TENANT_ID, Indexes.EMAIL_NOTIFICATIONS_CONFIGURATION_PRIMARY, Indexes.EMAIL_NOTIFICATIONS_CONFIGURATION_RECORD_ID);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Identity<EmailNotificationsConfigurationRecord, ULong> getIdentity() {
        return Keys.IDENTITY_EMAIL_NOTIFICATIONS_CONFIGURATION;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UniqueKey<EmailNotificationsConfigurationRecord> getPrimaryKey() {
        return Keys.KEY_EMAIL_NOTIFICATIONS_CONFIGURATION_PRIMARY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<UniqueKey<EmailNotificationsConfigurationRecord>> getKeys() {
        return Arrays.<UniqueKey<EmailNotificationsConfigurationRecord>>asList(Keys.KEY_EMAIL_NOTIFICATIONS_CONFIGURATION_PRIMARY, Keys.KEY_EMAIL_NOTIFICATIONS_CONFIGURATION_RECORD_ID, Keys.KEY_EMAIL_NOTIFICATIONS_CONFIGURATION_KENUI_CONFIGURATION_EVENT_TYPE_KB_ACCOUNT_ID);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public EmailNotificationsConfiguration as(String alias) {
        return new EmailNotificationsConfiguration(DSL.name(alias), this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public EmailNotificationsConfiguration as(Name alias) {
        return new EmailNotificationsConfiguration(alias, this);
    }

    /**
     * Rename this table
     */
    @Override
    public EmailNotificationsConfiguration rename(String name) {
        return new EmailNotificationsConfiguration(DSL.name(name), null);
    }

    /**
     * Rename this table
     */
    @Override
    public EmailNotificationsConfiguration rename(Name name) {
        return new EmailNotificationsConfiguration(name, null);
    }
}


text:
using System;

namespace WebApiDavExtension.CalDav
{
	public class TimeRange
	{
		public DateTime Start { get; set; }
		public DateTime End { get; set; }
	}
}


text: export { default } from 'ember-forge-ui/components/ef-list-group-header';


text:
'use strict';

angular.module('core')
    .controller('NotificationController', ['$scope','$location','Authentication',
	function($scope, Authentication,$location,Socket) {
	    $scope.authentication = Authentication;

	}
]);


text:
<?php

// FrontendBundle:Area:etapa.html.twig
return array (
);


text:
class IFilesystemDriver;

class Filesystem
{
public:
	static Path pwd();

public:
	class Exception : public std::runtime_error
	{
	public:
		Exception(const std::string& message);
	};

protected:
	friend class IFilesystemDriver;
	static void install(IFilesystemDriver& driver);
	static void uninstall();

protected:
	static IFilesystemDriver* _driver;
};


text:
package org.dol.biz.nogenerator;

import org.dol.redis.Redis;
import org.springframework.data.redis.core.BoundHashOperations;

public class RedisNoGenerator implements NoGenerator {

    private final String                                      key;
    private final Redis                                       redis;
    private       BoundHashOperations<String, String, String> ops;

    public RedisNoGenerator(Redis redis, String key) {
        this.key = key;
        this.redis = redis;
        this.ops = redis.boundHashOps(key);
    }

    @Override
    public String getName() {
        return GeneratorDefine.REDIS_GENERATOR;
    }

    @Override
    public String generateNO(String key, GeneratorDefine generatorDefine) {
        Long val = ops.increment(key, 1);
        while (val < generatorDefine.getMinValue()) {
            if (redis.hashCompareAndSwap(this.key, key, String.valueOf(generatorDefine.getMinValue()), String.valueOf(val))) {
                val = generatorDefine.getMinValue();
            } else {
                val = redis.boundHashOps(this.key).increment(key, 1);
            }
        }
        return padIfNeed(generatorDefine, String.valueOf(val));
    }
}


text:
namespace Zu.ChromeDevTools.Network
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Represents an adapter for the Network domain to simplify the command interface.
    /// </summary>
    public class NetworkAdapter
    {
        private readonly ChromeSession m_session;

        public NetworkAdapter(ChromeSession session)
        {
            m_session = session ?? throw new ArgumentNullException(nameof(session));
        }

        /// <summary>
        /// Gets the ChromeSession associated with the adapter.
        /// </summary>
        public ChromeSession Session
        {
            get { return m_session; }
        }

        /// <summary>
        /// Sets a list of content encodings that will be accepted. Empty list means no encoding is accepted.
        /// </summary>
        public async Task<SetAcceptedEncodingsCommandResponse> SetAcceptedEncodings(SetAcceptedEncodingsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetAcceptedEncodingsCommand, SetAcceptedEncodingsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Clears accepted encodings set by setAcceptedEncodings
        /// </summary>
        public async Task<ClearAcceptedEncodingsOverrideCommandResponse> ClearAcceptedEncodingsOverride(ClearAcceptedEncodingsOverrideCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<ClearAcceptedEncodingsOverrideCommand, ClearAcceptedEncodingsOverrideCommandResponse>(command ?? new ClearAcceptedEncodingsOverrideCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Tells whether clearing browser cache is supported.
        /// </summary>
        public async Task<CanClearBrowserCacheCommandResponse> CanClearBrowserCache(CanClearBrowserCacheCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<CanClearBrowserCacheCommand, CanClearBrowserCacheCommandResponse>(command ?? new CanClearBrowserCacheCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Tells whether clearing browser cookies is supported.
        /// </summary>
        public async Task<CanClearBrowserCookiesCommandResponse> CanClearBrowserCookies(CanClearBrowserCookiesCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<CanClearBrowserCookiesCommand, CanClearBrowserCookiesCommandResponse>(command ?? new CanClearBrowserCookiesCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Tells whether emulation of network conditions is supported.
        /// </summary>
        public async Task<CanEmulateNetworkConditionsCommandResponse> CanEmulateNetworkConditions(CanEmulateNetworkConditionsCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<CanEmulateNetworkConditionsCommand, CanEmulateNetworkConditionsCommandResponse>(command ?? new CanEmulateNetworkConditionsCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Clears browser cache.
        /// </summary>
        public async Task<ClearBrowserCacheCommandResponse> ClearBrowserCache(ClearBrowserCacheCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<ClearBrowserCacheCommand, ClearBrowserCacheCommandResponse>(command ?? new ClearBrowserCacheCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Clears browser cookies.
        /// </summary>
        public async Task<ClearBrowserCookiesCommandResponse> ClearBrowserCookies(ClearBrowserCookiesCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<ClearBrowserCookiesCommand, ClearBrowserCookiesCommandResponse>(command ?? new ClearBrowserCookiesCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Response to Network.requestIntercepted which either modifies the request to continue with any
        /// modifications, or blocks it, or completes it with the provided response bytes. If a network
        /// fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted
        /// event will be sent with the same InterceptionId.
        /// Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.
        /// </summary>
        public async Task<ContinueInterceptedRequestCommandResponse> ContinueInterceptedRequest(ContinueInterceptedRequestCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<ContinueInterceptedRequestCommand, ContinueInterceptedRequestCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Deletes browser cookies with matching name and url or domain/path pair.
        /// </summary>
        public async Task<DeleteCookiesCommandResponse> DeleteCookies(DeleteCookiesCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<DeleteCookiesCommand, DeleteCookiesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Disables network tracking, prevents network events from being sent to the client.
        /// </summary>
        public async Task<DisableCommandResponse> Disable(DisableCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<DisableCommand, DisableCommandResponse>(command ?? new DisableCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Activates emulation of network conditions.
        /// </summary>
        public async Task<EmulateNetworkConditionsCommandResponse> EmulateNetworkConditions(EmulateNetworkConditionsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<EmulateNetworkConditionsCommand, EmulateNetworkConditionsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Enables network tracking, network events will now be delivered to the client.
        /// </summary>
        public async Task<EnableCommandResponse> Enable(EnableCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<EnableCommand, EnableCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Returns all browser cookies. Depending on the backend support, will return detailed cookie
        /// information in the `cookies` field.
        /// </summary>
        public async Task<GetAllCookiesCommandResponse> GetAllCookies(GetAllCookiesCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<GetAllCookiesCommand, GetAllCookiesCommandResponse>(command ?? new GetAllCookiesCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Returns the DER-encoded certificate.
        /// </summary>
        public async Task<GetCertificateCommandResponse> GetCertificate(GetCertificateCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<GetCertificateCommand, GetCertificateCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Returns all browser cookies for the current URL. Depending on the backend support, will return
        /// detailed cookie information in the `cookies` field.
        /// </summary>
        public async Task<GetCookiesCommandResponse> GetCookies(GetCookiesCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<GetCookiesCommand, GetCookiesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Returns content served for the given request.
        /// </summary>
        public async Task<GetResponseBodyCommandResponse> GetResponseBody(GetResponseBodyCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<GetResponseBodyCommand, GetResponseBodyCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Returns post data sent with the request. Returns an error when no data was sent with the request.
        /// </summary>
        public async Task<GetRequestPostDataCommandResponse> GetRequestPostData(GetRequestPostDataCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<GetRequestPostDataCommand, GetRequestPostDataCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Returns content served for the given currently intercepted request.
        /// </summary>
        public async Task<GetResponseBodyForInterceptionCommandResponse> GetResponseBodyForInterception(GetResponseBodyForInterceptionCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<GetResponseBodyForInterceptionCommand, GetResponseBodyForInterceptionCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Returns a handle to the stream representing the response body. Note that after this command,
        /// the intercepted request can't be continued as is -- you either need to cancel it or to provide
        /// the response body. The stream only supports sequential read, IO.read will fail if the position
        /// is specified.
        /// </summary>
        public async Task<TakeResponseBodyForInterceptionAsStreamCommandResponse> TakeResponseBodyForInterceptionAsStream(TakeResponseBodyForInterceptionAsStreamCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<TakeResponseBodyForInterceptionAsStreamCommand, TakeResponseBodyForInterceptionAsStreamCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// This method sends a new XMLHttpRequest which is identical to the original one. The following
        /// parameters should be identical: method, url, async, request body, extra headers, withCredentials
        /// attribute, user, password.
        /// </summary>
        public async Task<ReplayXHRCommandResponse> ReplayXHR(ReplayXHRCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<ReplayXHRCommand, ReplayXHRCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Searches for given string in response content.
        /// </summary>
        public async Task<SearchInResponseBodyCommandResponse> SearchInResponseBody(SearchInResponseBodyCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SearchInResponseBodyCommand, SearchInResponseBodyCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Blocks URLs from loading.
        /// </summary>
        public async Task<SetBlockedURLsCommandResponse> SetBlockedURLs(SetBlockedURLsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetBlockedURLsCommand, SetBlockedURLsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Toggles ignoring of service worker for each request.
        /// </summary>
        public async Task<SetBypassServiceWorkerCommandResponse> SetBypassServiceWorker(SetBypassServiceWorkerCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetBypassServiceWorkerCommand, SetBypassServiceWorkerCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Toggles ignoring cache for each request. If `true`, cache will not be used.
        /// </summary>
        public async Task<SetCacheDisabledCommandResponse> SetCacheDisabled(SetCacheDisabledCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetCacheDisabledCommand, SetCacheDisabledCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
        /// </summary>
        public async Task<SetCookieCommandResponse> SetCookie(SetCookieCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetCookieCommand, SetCookieCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Sets given cookies.
        /// </summary>
        public async Task<SetCookiesCommandResponse> SetCookies(SetCookiesCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetCookiesCommand, SetCookiesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Specifies whether to always send extra HTTP headers with the requests from this page.
        /// </summary>
        public async Task<SetExtraHTTPHeadersCommandResponse> SetExtraHTTPHeaders(SetExtraHTTPHeadersCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetExtraHTTPHeadersCommand, SetExtraHTTPHeadersCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Specifies whether to attach a page script stack id in requests
        /// </summary>
        public async Task<SetAttachDebugStackCommandResponse> SetAttachDebugStack(SetAttachDebugStackCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetAttachDebugStackCommand, SetAttachDebugStackCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Sets the requests to intercept that match the provided patterns and optionally resource types.
        /// Deprecated, please use Fetch.enable instead.
        /// </summary>
        public async Task<SetRequestInterceptionCommandResponse> SetRequestInterception(SetRequestInterceptionCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetRequestInterceptionCommand, SetRequestInterceptionCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Allows overriding user agent with the given string.
        /// </summary>
        public async Task<SetUserAgentOverrideCommandResponse> SetUserAgentOverride(SetUserAgentOverrideCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetUserAgentOverrideCommand, SetUserAgentOverrideCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Returns information about the COEP/COOP isolation status.
        /// </summary>
        public async Task<GetSecurityIsolationStatusCommandResponse> GetSecurityIsolationStatus(GetSecurityIsolationStatusCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<GetSecurityIsolationStatusCommand, GetSecurityIsolationStatusCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Enables tracking for the Reporting API, events generated by the Reporting API will now be delivered to the client.
        /// Enabling triggers 'reportingApiReportAdded' for all existing reports.
        /// </summary>
        public async Task<EnableReportingApiCommandResponse> EnableReportingApi(EnableReportingApiCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<EnableReportingApiCommand, EnableReportingApiCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Fetches the resource and returns the content.
        /// </summary>
        public async Task<LoadNetworkResourceCommandResponse> LoadNetworkResource(LoadNetworkResourceCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<LoadNetworkResourceCommand, LoadNetworkResourceCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }

        /// <summary>
        /// Fired when data chunk was received over the network.
        /// </summary>
        public void SubscribeToDataReceivedEvent(Action<DataReceivedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when EventSource message is received.
        /// </summary>
        public void SubscribeToEventSourceMessageReceivedEvent(Action<EventSourceMessageReceivedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when HTTP request has failed to load.
        /// </summary>
        public void SubscribeToLoadingFailedEvent(Action<LoadingFailedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when HTTP request has finished loading.
        /// </summary>
        public void SubscribeToLoadingFinishedEvent(Action<LoadingFinishedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Details of an intercepted HTTP request, which must be either allowed, blocked, modified or
        /// mocked.
        /// Deprecated, use Fetch.requestPaused instead.
        /// </summary>
        public void SubscribeToRequestInterceptedEvent(Action<RequestInterceptedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired if request ended up loading from cache.
        /// </summary>
        public void SubscribeToRequestServedFromCacheEvent(Action<RequestServedFromCacheEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when page is about to send HTTP request.
        /// </summary>
        public void SubscribeToRequestWillBeSentEvent(Action<RequestWillBeSentEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when resource loading priority is changed
        /// </summary>
        public void SubscribeToResourceChangedPriorityEvent(Action<ResourceChangedPriorityEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when a signed exchange was received over the network
        /// </summary>
        public void SubscribeToSignedExchangeReceivedEvent(Action<SignedExchangeReceivedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when HTTP response is available.
        /// </summary>
        public void SubscribeToResponseReceivedEvent(Action<ResponseReceivedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when WebSocket is closed.
        /// </summary>
        public void SubscribeToWebSocketClosedEvent(Action<WebSocketClosedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired upon WebSocket creation.
        /// </summary>
        public void SubscribeToWebSocketCreatedEvent(Action<WebSocketCreatedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when WebSocket message error occurs.
        /// </summary>
        public void SubscribeToWebSocketFrameErrorEvent(Action<WebSocketFrameErrorEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when WebSocket message is received.
        /// </summary>
        public void SubscribeToWebSocketFrameReceivedEvent(Action<WebSocketFrameReceivedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when WebSocket message is sent.
        /// </summary>
        public void SubscribeToWebSocketFrameSentEvent(Action<WebSocketFrameSentEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when WebSocket handshake response becomes available.
        /// </summary>
        public void SubscribeToWebSocketHandshakeResponseReceivedEvent(Action<WebSocketHandshakeResponseReceivedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when WebSocket is about to initiate handshake.
        /// </summary>
        public void SubscribeToWebSocketWillSendHandshakeRequestEvent(Action<WebSocketWillSendHandshakeRequestEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired upon WebTransport creation.
        /// </summary>
        public void SubscribeToWebTransportCreatedEvent(Action<WebTransportCreatedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when WebTransport handshake is finished.
        /// </summary>
        public void SubscribeToWebTransportConnectionEstablishedEvent(Action<WebTransportConnectionEstablishedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when WebTransport is disposed.
        /// </summary>
        public void SubscribeToWebTransportClosedEvent(Action<WebTransportClosedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when additional information about a requestWillBeSent event is available from the
        /// network stack. Not every requestWillBeSent event will have an additional
        /// requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent
        /// or requestWillBeSentExtraInfo will be fired first for the same request.
        /// </summary>
        public void SubscribeToRequestWillBeSentExtraInfoEvent(Action<RequestWillBeSentExtraInfoEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when additional information about a responseReceived event is available from the network
        /// stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for
        /// it, and responseReceivedExtraInfo may be fired before or after responseReceived.
        /// </summary>
        public void SubscribeToResponseReceivedExtraInfoEvent(Action<ResponseReceivedExtraInfoEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired exactly once for each Trust Token operation. Depending on
        /// the type of the operation and whether the operation succeeded or
        /// failed, the event is fired before the corresponding request was sent
        /// or after the response was received.
        /// </summary>
        public void SubscribeToTrustTokenOperationDoneEvent(Action<TrustTokenOperationDoneEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired once when parsing the .wbn file has succeeded.
        /// The event contains the information about the web bundle contents.
        /// </summary>
        public void SubscribeToSubresourceWebBundleMetadataReceivedEvent(Action<SubresourceWebBundleMetadataReceivedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired once when parsing the .wbn file has failed.
        /// </summary>
        public void SubscribeToSubresourceWebBundleMetadataErrorEvent(Action<SubresourceWebBundleMetadataErrorEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when handling requests for resources within a .wbn file.
        /// Note: this will only be fired for resources that are requested by the webpage.
        /// </summary>
        public void SubscribeToSubresourceWebBundleInnerResponseParsedEvent(Action<SubresourceWebBundleInnerResponseParsedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Fired when request for resources within a .wbn file failed.
        /// </summary>
        public void SubscribeToSubresourceWebBundleInnerResponseErrorEvent(Action<SubresourceWebBundleInnerResponseErrorEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        /// Is sent whenever a new report is added.
        /// And after 'enableReportingApi' for all existing reports.
        /// </summary>
        public void SubscribeToReportingApiReportAddedEvent(Action<ReportingApiReportAddedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        ///
        /// </summary>
        public void SubscribeToReportingApiReportUpdatedEvent(Action<ReportingApiReportUpdatedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        ///
        /// </summary>
        public void SubscribeToReportingApiEndpointsChangedForOriginEvent(Action<ReportingApiEndpointsChangedForOriginEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
    }
}


text:
<?php

namespace Github\Tests\Api\Repository\Actions;

use Github\Api\Repository\Actions\WorkflowJobs;
use Github\Tests\Api\TestCase;
use PHPUnit\Framework\MockObject\MockObject;

class WorkflowJobsTest extends TestCase
{
    /**
     * @test
     */
    public function shouldGetWorkflowJobs()
    {
        $expectedArray = [
            ['id' => 'id', 'run_id' => 'run_id', 'status' => 'completed', 'conclusion' => 'success'],
        ];

        /** @var WorkflowJobs|MockObject $api */
        $api = $this->getApiMock();

        $api
            ->expects($this->once())
            ->method('get')
            ->with('/repos/KnpLabs/php-github-api/actions/runs/1/jobs')
            ->will($this->returnValue($expectedArray));

        $this->assertEquals($expectedArray, $api->all('KnpLabs', 'php-github-api', 1));
    }

    /**
     * @test
     */
    public function shouldShowWorkflowJob()
    {
        $expectedArray = [
            'id' => 'id', 'run_id' => 'run_id', 'status' => 'completed', 'conclusion' => 'success',
        ];

        /** @var WorkflowJobs|MockObject $api */
        $api = $this->getApiMock();

        $api
            ->expects($this->once())
            ->method('get')
            ->with('/repos/KnpLabs/php-github-api/actions/jobs/1')
            ->will($this->returnValue($expectedArray));

        $this->assertEquals($expectedArray, $api->show('KnpLabs', 'php-github-api', 1));
    }

    protected function getApiClass()
    {
        return WorkflowJobs::class;
    }
}


text:
@implementation NSDictionary (ZLClearFromNulls)

-(NSDictionary *) ZL_clearFromNulls
{
    NSMutableDictionary *mutableDictionary = [self mutableCopy];
    for (id key in mutableDictionary.allKeys) {
        id object = [mutableDictionary objectForKey:key];
        if ([object isKindOfClass:[NSNull class]]) {
            [mutableDictionary removeObjectForKey:key];
        }
    }

    return [NSDictionary dictionaryWithDictionary:mutableDictionary];
}

@end

/////////////////////////////////////////////////////


text:
'use strict';

// Setting up route
angular.module('users').config(['$stateProvider',
	function($stateProvider) {
		// Users state routing
		$stateProvider.
		state('profile', {
			url: '/settings/profile',
			templateUrl: 'modules/users/views/settings/edit-profile.client.view.html'
		}).
		state('password', {
			url: '/settings/password',
			templateUrl: 'modules/users/views/settings/change-password.client.view.html'
		}).
		state('accounts', {
			url: '/settings/accounts',
			templateUrl: 'modules/users/views/settings/social-accounts.client.view.html'
		}).
		state('signup', {
			url: '/signup',
			templateUrl: 'modules/users/views/authentication/signup.client.view.html'
		}).
		state('addUser', {
			url: '/users/add',
			templateUrl: 'modules/users/views/authentication/create-user.client.view.html'
		}).
		state('signin', {
			url: '/signin',
			templateUrl: 'modules/users/views/authentication/signin.client.view.html'
		}).
		state('forgot', {
			url: '/password/forgot',
			templateUrl: 'modules/users/views/password/forgot-password.client.view.html'
		}).
		state('reset-invlaid', {
			url: '/password/reset/invalid',
			templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html'
		}).
		state('reset-success', {
			url: '/password/reset/success',
			templateUrl: 'modules/users/views/password/reset-password-success.client.view.html'
		}).
		state('reset', {
			url: '/password/reset/:token',
			templateUrl: 'modules/users/views/password/reset-password.client.view.html'
		})

		.state('manageOrgs', {
			url: '/orgs',
			templateUrl: 'modules/users/views/orgs/manage-orgs.client.view.html'
		})
		.state('listUsers', {
			url: '/users',
			templateUrl: 'modules/users/views/settings/list-users.client.view.html'
		});
	}
]);


text:
Rails.application.config.assets.version = '1.0'

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
Rails.application.config.assets.precompile += %w( jquery.js )

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'adresse', 'adresses'
end


text:
<#
.Synopsis
    Install PowerShell Core on Windows, Linux or macOS.
.DESCRIPTION
    By default, the latest PowerShell Core release package will be installed.
    If '-Daily' is specified, then the latest PowerShell Core daily package will be installed.
.Parameter Destination
    The destination path to install PowerShell Core to.
.Parameter Daily
    Install PowerShell Core from the daily build.
    Note that the 'PackageManagement' module is required to install a daily package.
.Parameter DoNotOverwrite
    Do not overwrite the destination folder if it already exists.
.Parameter AddToPath
    On Windows, add the absolute destination path to the 'User' scope environment variable 'Path';
    On Linux, make the symlink '/usr/bin/pwsh' points to "$Destination/pwsh";
    On MacOS, make the symlink '/usr/local/bin/pwsh' points to "$Destination/pwsh".
#>
[CmdletBinding(DefaultParameterSetName = "Daily")]
param(
    [Parameter(ParameterSetName = "Daily")]
    [string] $Destination,

    [Parameter(ParameterSetName = "Daily")]
    [switch] $Daily,

    [Parameter(ParameterSetName = "Daily")]
    [switch] $DoNotOverwrite,

    [Parameter(ParameterSetName = "Daily")]
    [switch] $AddToPath,

    [Parameter(ParameterSetName = "MSI")]
    [switch] $UseMSI,

    [Parameter(ParameterSetName = "MSI")]
    [switch] $Quiet,

    [Parameter()]
    [switch] $Preview
)

Set-StrictMode -Version latest
$ErrorActionPreference = "Stop"

$IsLinuxEnv = (Get-Variable -Name "IsLinux" -ErrorAction Ignore) -and $IsLinux
$IsMacOSEnv = (Get-Variable -Name "IsMacOS" -ErrorAction Ignore) -and $IsMacOS
$IsWinEnv = !$IsLinuxEnv -and !$IsMacOSEnv

if (-not $Destination) {
    if ($IsWinEnv) {
        $Destination = "$env:LOCALAPPDATA\Microsoft\powershell"
    } else {
        $Destination = "~/.powershell"
    }

    if ($Daily) {
        $Destination = "${Destination}-daily"
    }
}

$Destination = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Destination)

if (-not $UseMSI) {
    Write-Verbose "Destination: $Destination" -Verbose
} else {
    if (-not $IsWinEnv) {
        throw "-UseMSI is only supported on Windows"
    }
}

Function Remove-Destination([string] $Destination) {
    if (Test-Path -Path $Destination) {
        if ($DoNotOverwrite) {
            throw "Destination folder '$Destination' already exist. Use a different path or omit '-DoNotOverwrite' to overwrite."
        }
        Write-Verbose "Removing old installation: $Destination" -Verbose
        if (Test-Path -Path "$Destination.old") {
            Remove-Item "$Destination.old" -Recurse -Force
        }
        if ($IsWinEnv -and ($Destination -eq $PSHome)) {
            # handle the case where the updated folder is currently in use
            Get-ChildItem -Recurse -File -Path $PSHome | ForEach-Object {
                if ($_.extension -eq "old") {
                    Remove-Item $_
                } else {
                    Move-Item $_.fullname "$($_.fullname).old"
                }
            }
        } else {
            # Unix systems don't keep open file handles so you can just move files/folders even if in use
            Move-Item "$Destination" "$Destination.old"
        }
    }
}

<#
.Synopsis
    Parameter validation for Add-PathTToSettingsToSettings.
.DESCRIPTION
    Validates that the parameter being validated:
    - is not null
    - is a folder and exists
    - and that it does not exist in settings where settings is:
        = the process PATH for Linux/OSX
        - the registry PATHs for Windows
#>
class ValidatePathNotInSettingsAttribute : System.Management.Automation.ValidateArgumentsAttribute {
    [void] Validate([object] $Arguments, [System.Management.Automation.EngineIntrinsics] $engineIntrinsics) {
        $Path = $Arguments
        if ([string]::IsNullOrWhiteSpace($Path)) {
            Throw [System.ArgumentNullException]::new()
        }

        # Remove ending DirectorySeparatorChar for comparison purposes
        $Path = [System.Environment]::ExpandEnvironmentVariables($Path.TrimEnd([System.IO.Path]::DirectorySeparatorChar));

        if (-not [System.IO.Directory]::Exists($Path)) {
            Throw [System.IO.DirectoryNotFoundException]::new()
        }

        # [System.Environment]::GetEnvironmentVariable automatically expands all variables
        [System.Array] $InstalledPaths = @()
        if ([System.Environment]::OSVersion.Platform -eq "Win32NT") {
            $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH', [System.EnvironmentVariableTarget]::User)).Split([System.IO.Path]::PathSeparator))
            $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH', [System.EnvironmentVariableTarget]::Machine)).Split([System.IO.Path]::PathSeparator))
        } else {
            $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH'), [System.EnvironmentVariableTarget]::Process).Split([System.IO.Path]::PathSeparator))
        }

        # Remove ending DirectorySeparatorChar in all items of array for comparison purposes
        $InstalledPaths = $InstalledPaths.ForEach( { $_.TrimEnd([System.IO.Path]::DirectorySeparatorChar) } )

        # Throw if $InstalledPaths is in setting
        if ($InstalledPaths -icontains $Path) {
            Throw [System.ArgumentException]::new("Path already exists.")
        }
    }
}

<#
.Synopsis
    Adds a Path to settings (Supports Windows Only)
.DESCRIPTION
    Adds the target path to the target registry.
.Parameter Path
    The path to add to the registry. It is validated with ValidatePathNotInSettings which ensures that:
    -The path exists
    -Is a directory
    -Is not in the registry (HKCU or HKLM)
.Parameter Target
    The target hive to install the Path to.
    Must be either User or Machine
    Defaults to User
#>
Function Add-PathTToSettings {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [ValidatePathNotInSettings()]
        [string] $Path,

        [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet([System.EnvironmentVariableTarget]::User, [System.EnvironmentVariableTarget]::Machine)]
        [System.EnvironmentVariableTarget] $Target = ([System.EnvironmentVariableTarget]::User)
    )

    if (-not $IsWinEnv) {
        return
    }

    if ($Target -eq [System.EnvironmentVariableTarget]::User) {
        [string] $Environment = 'Environment'
        [Microsoft.Win32.RegistryKey] $Key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($Environment, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree)
    } else {
        [string] $Environment = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
        [Microsoft.Win32.RegistryKey] $Key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($Environment, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree)
    }

    # $key is null here if it the user was unable to get ReadWriteSubTree access.
    if ($null -eq $Key) {
        throw [System.Security.SecurityException]::new("Unable to access the target registry")
    }

    # Get current unexpanded value
    [string] $CurrentUnexpandedValue = $Key.GetValue('PATH', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)

    # Keep current PathValueKind if possible/appropriate
    try {
        [Microsoft.Win32.RegistryValueKind] $PathValueKind = $Key.GetValueKind('PATH')
    } catch {
        [Microsoft.Win32.RegistryValueKind] $PathValueKind = [Microsoft.Win32.RegistryValueKind]::ExpandString
    }

    # Evaluate new path
    $NewPathValue = [string]::Concat($CurrentUnexpandedValue.TrimEnd([System.IO.Path]::PathSeparator), [System.IO.Path]::PathSeparator, $Path)

    # Upgrade PathValueKind to [Microsoft.Win32.RegistryValueKind]::ExpandString if appropriate
    if ($NewPathValue.Contains('%')) { $PathValueKind = [Microsoft.Win32.RegistryValueKind]::ExpandString }

    $Key.SetValue("PATH", $NewPathValue, $PathValueKind)
}

if (-not $IsWinEnv) {
    $architecture = "x64"
} else {
    switch ($env:PROCESSOR_ARCHITECTURE) {
        "AMD64" { $architecture = "x64" }
        "x86" { $architecture = "x86" }
        default { throw "PowerShell package for OS architecture '$_' is not supported." }
    }
}
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName())
New-Item -ItemType Directory -Path $tempDir -Force -ErrorAction SilentlyContinue
try {
    # Setting Tls to 12 to prevent the Invoke-WebRequest : The request was
    # aborted: Could not create SSL/TLS secure channel. error.
    $originalValue = [Net.ServicePointManager]::SecurityProtocol
    [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12

    if ($Daily) {
        if (-not (Get-Module -Name PackageManagement -ListAvailable)) {
            throw "PackageManagement module is required to install daily PowerShell Core."
        }

        if ($architecture -ne "x64") {
            throw "The OS architecture is '$architecture'. However, we currently only support daily package for x64."
        }

        ## Register source if not yet
        if (-not (Get-PackageSource -Name powershell-core-daily -ErrorAction SilentlyContinue)) {
            $packageSource = "https://powershell.myget.org/F/powershell-core-daily"
            Write-Verbose "Register powershell-core-daily package source '$packageSource' with PackageManagement" -Verbose
            Register-PackageSource -Name powershell-core-daily -Location $packageSource -ProviderName nuget -Trusted -ErrorAction SilentlyContinue
        }

        if ($IsWinEnv) {
            $packageName = "powershell-win-x64-win7-x64"
        } elseif ($IsLinuxEnv) {
            $packageName = "powershell-linux-x64"
        } elseif ($IsMacOSEnv) {
            $packageName = "powershell-osx-x64"
        }

        $package = Find-Package -Source powershell-core-daily -AllowPrereleaseVersions -Name $packageName
        Write-Verbose "Daily package found. Name: $packageName; Version: $($package.Version)" -Verbose

        Install-Package -InputObject $package -Destination $tempDir -ExcludeVersion -ErrorAction SilentlyContinue
        $contentPath = [System.IO.Path]::Combine($tempDir, $packageName, "content")
    } else {
        $metadata = Invoke-RestMethod https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/metadata.json
        if ($Preview) {
            $release = $metadata.PreviewReleaseTag -replace '^v'
        } else {
            $release = $metadata.ReleaseTag -replace '^v'
        }

        if ($IsWinEnv) {
            if ($UseMSI) {
                $packageName = "PowerShell-${release}-win-${architecture}.msi"
            } else {
                $packageName = "PowerShell-${release}-win-${architecture}.zip"
            }
        } elseif ($IsLinuxEnv) {
            $packageName = "powershell-${release}-linux-${architecture}.tar.gz"
        } elseif ($IsMacOSEnv) {
            $packageName = "powershell-${release}-osx-${architecture}.tar.gz"
        }

        $downloadURL = "https://github.com/PowerShell/PowerShell/releases/download/v${release}/${packageName}"
        Write-Verbose "About to download package from '$downloadURL'" -Verbose

        $packagePath = Join-Path -Path $tempDir -ChildPath $packageName
        if ($PSVersionTable.PSEdition -eq "Desktop") {
            # On Windows PowerShell, progress can make the download significantly slower
            $oldProgressPreference = $ProgressPreference
            $ProgressPreference = "SilentlyContinue"
        }

        try {
            Invoke-WebRequest -Uri $downloadURL -OutFile $packagePath
        } finally {
            if ($PSVersionTable.PSEdition -eq "Desktop") {
                $ProgressPreference = $oldProgressPreference
            }
        }

        $contentPath = Join-Path -Path $tempDir -ChildPath "new"

        New-Item -ItemType Directory -Path $contentPath -ErrorAction SilentlyContinue
        if ($IsWinEnv) {
            if ($UseMSI -and $Quiet) {
                Write-Verbose "Performing quiet install"
                $process = Start-Process msiexec -ArgumentList "/i", $packagePath, "/quiet" -Wait -PassThru
                if ($process.exitcode -ne 0) {
                    throw "Quiet install failed, please rerun install without -Quiet switch or ensure you have administrator rights"
                }
            } elseif ($UseMSI) {
                Start-Process $packagePath -Wait
            } else {
                Expand-Archive -Path $packagePath -DestinationPath $contentPath
            }
        } else {
            tar zxf $packagePath -C $contentPath
        }
    }

    if (-not $UseMSI) {
        Remove-Destination $Destination
        if (Test-Path $Destination) {
            Write-Verbose "Copying files" -Verbose
            # only copy files as folders will already exist at $Destination
            Get-ChildItem -Recurse -Path "$contentPath" -File | ForEach-Object {
                $DestinationFilePath = Join-Path $Destination $_.fullname.replace($contentPath, "")
                Copy-Item $_.fullname -Destination $DestinationFilePath
            }
        } else {
            $null = New-Item -Path (Split-Path -Path $Destination -Parent) -ItemType Directory -ErrorAction SilentlyContinue
            Move-Item -Path $contentPath -Destination $Destination
        }
    }

    # Edit icon to disambiguate daily builds.
    if ($IsWinEnv -and $Daily.IsPresent) {
        if (-not (Test-Path "~/.rcedit/rcedit-x64.exe")) {
            Write-Verbose "Install RCEdit for modifying exe resources" -Verbose
            $rceditUrl = "https://github.com/electron/rcedit/releases/download/v1.0.0/rcedit-x64.exe"
            New-Item -Path "~/.rcedit" -Type Directory -Force -ErrorAction SilentlyContinue
            Invoke-WebRequest -OutFile "~/.rcedit/rcedit-x64.exe" -Uri $rceditUrl
        }

        Write-Verbose "Change icon to disambiguate it from a released installation" -Verbose
        & "~/.rcedit/rcedit-x64.exe" "$Destination\pwsh.exe" --set-icon "$Destination\assets\Powershell_avatar.ico"
    }

    ## Change the mode of 'pwsh' to 'rwxr-xr-x' to allow execution
    if (-not $IsWinEnv) { chmod 755 $Destination/pwsh }

    if ($AddToPath -and -not $UseMSI) {
        if ($IsWinEnv) {
            if ((-not ($Destination.StartsWith($ENV:USERPROFILE))) -and
                (-not ($Destination.StartsWith($ENV:APPDATA))) -and
                (-not ($Destination.StartsWith($env:LOCALAPPDATA)))) {
                $TargetRegistry = [System.EnvironmentVariableTarget]::Machine
                try {
                    Add-PathTToSettings -Path $Destination -Target $TargetRegistry
                } catch {
                    Write-Verbose -Message "Unable to save the new path in the machine wide registry."
                    $TargetRegistry = [System.EnvironmentVariableTarget]::User
                }
            } else {
                $TargetRegistry = [System.EnvironmentVariableTarget]::User
            }

            # If failed to install to machine wide path or path was not appropriate for machine wide path
            if ($TargetRegistry -eq [System.EnvironmentVariableTarget]::User) {
                try {
                    Add-PathTToSettings -Path $Destination -Target $TargetRegistry
                } catch {
                    Write-Verbose -Message "Unable to save the new path in the registry for the current user"
                }
            }
        } else {
            $targetPath = Join-Path -Path $Destination -ChildPath "pwsh"
            if ($IsLinuxEnv) { $symlink = "/usr/bin/pwsh" } elseif ($IsMacOSEnv) { $symlink = "/usr/local/bin/pwsh" }
            $needNewSymlink = $true

            if (Test-Path -Path $symlink) {
                $linkItem = Get-Item -Path $symlink
                if ($linkItem.LinkType -ne "SymbolicLink") {
                    Write-Warning "'$symlink' already exists but it's not a symbolic link. Abort adding to PATH."
                    $needNewSymlink = $false
                } elseif ($linkItem.Target -contains $targetPath) {
                    ## The link already points to the target
                    Write-Verbose "'$symlink' already points to '$targetPath'" -Verbose
                    $needNewSymlink = $false
                }
            }

            if ($needNewSymlink) {
                $uid = id -u
                if ($uid -ne "0") { $SUDO = "sudo" } else { $SUDO = "" }

                Write-Verbose "Make symbolic link '$symlink' point to '$targetPath'..." -Verbose
                & $SUDO ln -fs $targetPath $symlink

                if ($LASTEXITCODE -ne 0) {
                    Write-Error "Could not add to PATH: failed to make '$symlink' point to '$targetPath'."
                }
            }
        }

        ## Add to the current process 'Path' if the process is not 'pwsh'
        $runningProcessName = (Get-Process -Id $PID).ProcessName
        if ($runningProcessName -ne 'pwsh') {
            $env:Path = $Destination + [System.IO.Path]::PathSeparator + $env:Path
        }
    }

    if (-not $UseMSI) {
        Write-Host "PowerShell Core has been installed at $Destination" -ForegroundColor Green
        if ($Destination -eq $PSHome) {
            Write-Host "Please restart pwsh" -ForegroundColor Magenta
        }
    }
} finally {
    # Restore original value
    [Net.ServicePointManager]::SecurityProtocol = $originalValue

    Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}


text:
package net.lucianolattes.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.lucianolattes.dao.UserDao;
import net.lucianolattes.exception.FollowException;
import net.lucianolattes.exception.UserNotFoundException;
import net.lucianolattes.model.UserProfile;

/**
 * This service acts as a middleware between <tt>UserController</tt> and DAO
 * layer. Gathers data from controller, performs validation and business logic
 * and calls repositories for data manipulation.
 *
 * @author lucianolattes
 */
@Service
public class UserService {

  @Autowired
  private UserDao userDao;

  public List<UserProfile> getFollowing(String username) {
    List<UserProfile> following = userDao.getFollowing(username);
    return following;
  }

  public List<UserProfile> getFollowingByGivenUser(String username) throws UserNotFoundException {
    if (userDao.checkUser(username)) {
      return getFollowing(username);
    } else {
      throw new UserNotFoundException("The user '" + username + "' does not exist");
    }
  }

  public List<UserProfile> getFollowers(String username) {
    List<UserProfile> followers = userDao.getFollowers(username);
    return followers;
  }

  public List<UserProfile> getFollowersByGivenUser(String username) throws UserNotFoundException {
    if (userDao.checkUser(username)) {
      return getFollowers(username);
    } else {
      throw new UserNotFoundException("The user '" + username + "' does not exist");
    }
  }

  public List<UserProfile> follow(String follower, String followee) throws UserNotFoundException {
    if (userDao.checkUser(followee)) {
      userDao.insertFollow(follower, followee);
      return getFollowing(follower);
    } else {
      throw new UserNotFoundException("The user '" + followee + "' does not exist");
    }
  }

  public List<UserProfile> unfollow(String follower, String followee) throws UserNotFoundException, FollowException {
    if (userDao.checkUser(followee)) {
      if (userDao.checkFollow(follower, followee)) {
        userDao.deleteFollow(follower, followee);
        return getFollowing(follower);
      } else {
        throw new FollowException("The user '" + follower + "' does not follow '" + followee + "'");
      }
    } else {
      throw new UserNotFoundException("The user '" + followee + "' does not exist");
    }
  }
}


text:
from datetime import datetime
import time

from testrail.base import TestRailBase
from testrail import api
from testrail.project import Project
from testrail.helper import TestRailError

class Milestone(TestRailBase):
    def __init__(self, content=None):
        self._content = content or dict()
        self.api = api.API()

    def __str__(self):
        return self.name

    @property
    def completed_on(self):
        try:
            return datetime.fromtimestamp(
                int(self._content.get('completed_on')))
        except TypeError:
            return None

    @property
    def description(self):
        return self._content.get('description')

    @description.setter
    def description(self, value):
        if value is not None:
            if not isinstance(value, str):
                raise TestRailError('input must be string or None')
        self._content['description'] = value

    @property
    def due_on(self):
        try:
            return datetime.fromtimestamp(int(self._content.get('due_on')))
        except TypeError:
            return None

    @due_on.setter
    def due_on(self, value):
        if value is None:
            due = None
        else:
            if not isinstance(value, datetime):
                raise TestRailError('input must be a datetime or None')
            due = int(time.mktime(value.timetuple()))
        self._content['due_on'] = due

    @property
    def id(self):
        return self._content.get('id')

    @property
    def is_completed(self):
        return bool(self._content.get('is_completed'))

    @is_completed.setter
    def is_completed(self, value):
        if not isinstance(value, bool):
            raise TestRailError('input must be a boolean')
        self._content['is_completed'] = value

    @property
    def name(self):
        return self._content.get('name')

    @name.setter
    def name(self, value):
        if not isinstance(value, str):
            raise TestRailError('input must be a string')
        self._content['name'] = value

    @property
    def project(self):
        return Project(
            self.api.project_with_id(self._content.get('project_id')))

    @project.setter
    def project(self, value):
        if not isinstance(value, Project):
            raise TestRailError('input must be a Project')
        self.api.project_with_id(value.id)  # verify project is valid
        self._content['project_id'] = value.id

    @property
    def url(self):
        return self._content.get('url')

    def raw_data(self):
        return self._content


text:
package anabalica.github.io.meowletters;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.github.amlcurran.showcaseview.OnShowcaseEventListener;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.ViewTarget;

import anabalica.github.io.meowletters.customviews.SquareButton;
import anabalica.github.io.meowletters.letters.Letter;
import anabalica.github.io.meowletters.letters.LetterChain;
import anabalica.github.io.meowletters.letters.LetterGrid;
import anabalica.github.io.meowletters.metrics.Level;
import anabalica.github.io.meowletters.metrics.Score;
import anabalica.github.io.meowletters.utils.SoundManager;
import anabalica.github.io.meowletters.utils.Status;
import anabalica.github.io.meowletters.utils.State;

/**
 * This is the activity that starts or continues the game. It is an educational
 * game for children to practice the knowledge of an alphabet.
 *
 * @author Ana Balica
 */
public class GameActivity extends Activity implements OnShowcaseEventListener, AdapterView.OnItemClickListener {
    public static final int gridRows = 5;
    public static final int gridColumns = 5;
    private ProgressBar timerBar;
    private GameCountDownTimer timer;
    private State state;

    private int millisTotal = 5000;
    private int millisInterval = 5;
    private int millisReset = 0;
    private long millisPenalty = 1000;
    private long timerMillisUntilFinished;

    public final static String LEVEL = "anabalica.github.io.meowletters.level";
    public final static String SCORE = "anabalica.github.io.meowletters.score";
    public final static String FIRST_LAUNCH = "first_launch";

    private LetterGrid letterGrid;
    private LetterChain selectedLetterChain = new LetterChain();
    private LetterChain firstLetterChain;

    private Score score = new Score();
    private Level level = new Level();

    private boolean penalty = false;
    private boolean createNewTimer = false;

    private final Integer[][] letterButtons = {
            {R.id.letter_button_00, R.id.letter_button_01, R.id.letter_button_02, R.id.letter_button_03, R.id.letter_button_04},
            {R.id.letter_button_10, R.id.letter_button_11, R.id.letter_button_12, R.id.letter_button_13, R.id.letter_button_14},
            {R.id.letter_button_20, R.id.letter_button_21, R.id.letter_button_22, R.id.letter_button_23, R.id.letter_button_24},
            {R.id.letter_button_30, R.id.letter_button_31, R.id.letter_button_32, R.id.letter_button_33, R.id.letter_button_34},
            {R.id.letter_button_40, R.id.letter_button_41, R.id.letter_button_42, R.id.letter_button_43, R.id.letter_button_44}};

    public static Status status = Status.RUN;
    private Boolean firstLaunch;
    private ShowcaseView nextShowcaseView;
    private static int showcaseViewCounter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
    }

    public Level getLevel() {
        return level;
    }

    public Score getScore() {
        return score;
    }

    public boolean hasPenalty() {
        return penalty;
    }

    public boolean isCreateNewTimer() {
        return createNewTimer;
    }

    public LetterChain getSelectedLetterChain() {
        return selectedLetterChain;
    }

    public LetterGrid getLetterGrid() {
        return letterGrid;
    }

    public long getTimerMillisUntilFinished() {
        return timerMillisUntilFinished;
    }

    private void startGame() {
        timerBar = (ProgressBar) findViewById(R.id.timerBar);
        timerBar.setMax(millisTotal);
        timerBar.setProgress(millisTotal);

        // Initialize the letter grid and initial letter chain
        letterGrid = new LetterGrid(gridRows, gridColumns);
        firstLetterChain  = LetterChain.generateChain(2, 1);
        letterGrid.addLetterChain(firstLetterChain);
        drawLetterButtons();

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        firstLaunch = sharedPrefs.getBoolean(FIRST_LAUNCH, true);
        if (firstLaunch) {
            new ShowcaseView.Builder(this, true)
                    .setContentText(R.string.step_1)
                    .setStyle(R.style.CustomShowcaseTheme)
                    .setShowcaseEventListener(this)
                    .build();
        } else {
            timer = new GameCountDownTimer(millisTotal, millisInterval);
            timer.start();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        System.out.println("OnItemClick");
    }

    @Override
    public void onShowcaseViewHide(ShowcaseView showcaseView) {
        System.out.println("OnShowcaseViewHide");
        System.out.println(showcaseView);
        showcaseViewCounter++;
        int row;
        int column;
        ViewTarget target;
        Letter secondLetter = firstLetterChain.get(1);
        switch (showcaseViewCounter) {
            case 1:
                Letter firstLetter = firstLetterChain.get(0);
                row = firstLetter.getPosition().getRow();
                column = firstLetter.getPosition().getColumn();
                target = new ViewTarget(letterButtons[row][column], this);
                nextShowcaseView = new ShowcaseView.Builder(this, true)
                        .setContentText(R.string.step_2)
                        .setStyle(R.style.CustomShowcaseTheme)
                        .setTarget(target)
                        .setShowcaseEventListener(this)
                        .build();
                nextShowcaseView.hideButton();
                break;
            case 2:
                row = secondLetter.getPosition().getRow();
                column = secondLetter.getPosition().getColumn();
                target = new ViewTarget(letterButtons[row][column], this);
                nextShowcaseView = new ShowcaseView.Builder(this, true)
                        .setContentText(R.string.step_3)
                        .setStyle(R.style.CustomShowcaseTheme)
                        .setTarget(target)
                        .setShowcaseEventListener(this)
                        .build();
                nextShowcaseView.hideButton();
                break;
            case 3:
                row = secondLetter.getPosition().getRow();
                column = secondLetter.getPosition().getColumn();
                target = new ViewTarget(letterButtons[row][column], this);
                nextShowcaseView = new ShowcaseView.Builder(this, true)
                        .setContentText(R.string.step_4)
                        .setStyle(R.style.CustomShowcaseTheme)
                        .setTarget(target)
                        .setShowcaseEventListener(this)
                        .build();
                nextShowcaseView.hideButton();
                break;
            case 4:
                nextShowcaseView = new ShowcaseView.Builder(this, true)
                        .setContentText(R.string.step_5)
                        .setStyle(R.style.CustomShowcaseTheme)
                        .setShowcaseEventListener(this)
                        .build();
                break;

            case 5:
                target = new ViewTarget(R.id.timerBar, this);
                nextShowcaseView = new ShowcaseView.Builder(this, true)
                        .setContentText(R.string.step_6)
                        .setStyle(R.style.CustomShowcaseTheme)
                        .setTarget(target)
                        .setShowcaseEventListener(this)
                        .build();
                break;
            case 6:
                nextShowcaseView = new ShowcaseView.Builder(this, true)
                        .setContentText(R.string.step_7)
                        .setStyle(R.style.CustomShowcaseTheme)
                        .setShowcaseEventListener(this)
                        .build();
                break;
            case 7:
                nextShowcaseView = new ShowcaseView.Builder(this, true)
                        .setContentText(R.string.step_8)
                        .setStyle(R.style.CustomShowcaseTheme)
                        .setShowcaseEventListener(this)
                        .build();
                break;
            case 8:
                nextShowcaseView = new ShowcaseView.Builder(this, true)
                        .setContentText(R.string.step_9)
                        .setStyle(R.style.FinalCustomShowcaseTheme)
                        .setShowcaseEventListener(this)
                        .build();
                break;
            case 9:
                SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = sharedPrefs.edit();
                editor.putBoolean(FIRST_LAUNCH, false);
                editor.apply();

                timer = new GameCountDownTimer(millisTotal, millisInterval);
                timer.start();
                break;
        }
    }

    @Override
    public void onShowcaseViewShow(ShowcaseView showcaseView) {
        // do nothing
    }

    @Override
    public void onShowcaseViewDidHide(ShowcaseView showcaseView) {
        // do nothing
    }

    private void resumeGame() {
        status = Status.RESUME;
        setScoreText();
        setLevelText();
        drawLetterButtons();

        timerBar = (ProgressBar) findViewById(R.id.timerBar);
        timerBar.setMax(millisTotal);
        timerBar.setProgress((int) timerMillisUntilFinished);

        // Start the countdown timer
        timer = new GameCountDownTimer(millisTotal, millisInterval);
        timer.start();
    }

    private void loadState() {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        state = new State(sharedPreferences);
        level = state.getLevel();
        score = state.getScore();
        letterGrid = state.getLetterGrid();
        selectedLetterChain = state.getSelectedLetterChain();
        penalty = state.getPenalty();
        createNewTimer = state.getCreateNewTimer();
        timerMillisUntilFinished = state.getTimerMillisUntilFinished();
    }

    @Override
    public void onPause() {
        timer.cancel();
        status = Status.PAUSE;
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        state = new State(sharedPreferences);
        state.save(this);
        super.onPause();
    }

    @Override
    public void onResume() {
        if (status == Status.RUN) {
            startGame();
        } else if (status == Status.RESUME) {
            loadState();
            resumeGame();
        } else if (status == Status.PAUSE) {
            onBackPressed();
        }
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.pull_in_left, R.anim.push_out_right);
    }

    /**
     * Select a letter from the grid add it to the letter chain and
     * display it on the grid.
     */
    public void selectLetter(View view) {
        SquareButton button = (SquareButton) view;
        int row = button.getRow();
        int column = button.getColumn();
        Letter letter = letterGrid.getLetter(row, column);

        // select/deselect letter(s)
        if (letter != null) {
            SplashActivity.bus.post(SoundManager.LETTER_SOUND);
            if (letter.isSelected()) {
                LetterChain removedLetters = selectedLetterChain.remove(letter);
                deselectLetterButtons(removedLetters);
            } else {
                letter.select();
                selectedLetterChain.add(letter);
                selectLetterButton(button);
            }
        }

        if (showcaseViewCounter == 1 || showcaseViewCounter == 2 || showcaseViewCounter == 3) {
            nextShowcaseView.hide();
            return;
        }

        // check if valid and if final
        if (selectedLetterChain.size() > 1) {
            if (selectedLetterChain.isValid()) {
                if (selectedLetterChain.isFinal(letterGrid)) {
                    timer.onFinish();
                }
            } else {
                deselectLetterButtons(selectedLetterChain);
                shakeLetterButtons(selectedLetterChain);
                penalty = true;
            }
        }
    }

    /**
     * Create shake/wobble animation for letters on the grid.
     *
     * @param letterChain LetterChain object
     */
    private void shakeLetterButtons(LetterChain letterChain) {
        for (Letter letter: letterChain) {
            int row = letter.getPosition().getRow();
            int column = letter.getPosition().getColumn();
            Button button = (Button) findViewById(letterButtons[row][column]);
            Animation shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.shake);
            button.startAnimation(shakeAnimation);
        }
    }

    /**
     * Selecte in the UI a letter button.
     *
     * @param button
     */
    private void selectLetterButton(Button button) {
        button.setTextColor(getResources().getColor(R.color.beige));
        button.setBackground(getResources().getDrawable(R.drawable.letter_button_selected));
    }

    /**
     * Deselect in the UI a chain of letters.
     *
     * @param chain LetterChain object of letters to be unselected
     */
    private void deselectLetterButtons(LetterChain chain) {
        for (Letter letter : chain) {
            int row = letter.getPosition().getRow();
            int column = letter.getPosition().getColumn();
            letter.deselect();
            letterGrid.getLetter(row, column).deselect();

            Button button = (Button) findViewById(letterButtons[row][column]);
            button.setTextColor(getResources().getColor(R.color.red));
            button.setBackground(getResources().getDrawable(R.drawable.letter_button_unselected));
        }
    }

    /**
     * Translate the LetterGrid to the actual UI grid by drawing the buttons,
     * their letter and their correct position.
     */
    private void drawLetterButtons() {
        for (int row = 0; row < gridRows; row++) {
            for (int column = 0; column < gridColumns; column++) {
                if (letterGrid.getGrid()[row][column] != null) {
                    drawLetterButton(letterGrid.getGrid()[row][column], row, column);
                }
            }
        }
    }

    /**
     * Draw a LetterButton on the UI grid in the provided position
     *
     * @param letter Letter object
     * @param row int the row position
     * @param column int the column position
     */
    private void drawLetterButton(Letter letter, int row, int column) {
        Button button = (Button) findViewById(letterButtons[row][column]);
        button.setText(letter.getLetter());
        if (letter.isSelected()) {
            button.setBackground(getResources().getDrawable(R.drawable.letter_button_selected));
            button.setTextColor(getResources().getColor(R.color.beige));
        } else {
            button.setBackground(getResources().getDrawable(R.drawable.letter_button_unselected));
            button.setTextColor(getResources().getColor(R.color.red));
        }
    }

    /**
     * Hide from the UI grid all letters of a letter chain.
     *
     * @param letterChain LetterChain object
     */
    private void hideLetterButtons(LetterChain letterChain) {
        for (Letter letter : letterChain) {
            int row = letter.getPosition().getRow();
            int column = letter.getPosition().getColumn();
            hideLetterButton(row, column);
        }
    }

    /**
     * Hide a LetterButton from the UI grid
     *
     * @param row int the row position
     * @param column int the column position
     */
    private void hideLetterButton(int row, int column) {
        Button button = (Button) findViewById(letterButtons[row][column]);
        button.setBackground(getResources().getDrawable(R.drawable.letter_button_unselected));
        button.setText("");
    }

    /**
     * Update the game score.
     *
     * @param letterChainSize int size of the letter chain
     */
    private void updateScore(int letterChainSize) {
        score.update(letterChainSize);
        setScoreText();
    }

    /**
     * Set the game score in the UI
     */
    private void setScoreText() {
        TextView scoreView = (TextView) findViewById(R.id.score);
        String points = Integer.toString(score.getPoints());
        scoreView.setText(points);
    }

    /**
     * Update the game level.
     *
     * @param points int amount of score points
     */
    private void updateLevel(int points) {
        level.updateLevel(points);
        setLevelText();
    }

    /**
     * Set the game level in the UI
     */
    private void setLevelText() {
        TextView levelView = (TextView) findViewById(R.id.level);
        String currentLevel = Integer.toString(level.getLevel());
        levelView.setText(currentLevel);
    }

    /**
     * Add a letter chain to the grid.
     */
    private void addLetterChain() {
        LetterChain letterChain = LetterChain.generateChain(level.getLevel(), letterGrid);
        letterGrid.addLetterChain(letterChain);
        drawLetterButtons();
    }

    /**
     * Custom countdown timer that runs infinitely and updates it's state to
     * the progress bar.
     */
    public class GameCountDownTimer extends CountDownTimer {

        public GameCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            if (selectedLetterChain.isValid()) {
                updateScore(selectedLetterChain.size());
                updateLevel(score.getPoints());
                hideLetterButtons(selectedLetterChain);
                letterGrid.removeLetterChain(selectedLetterChain);
            } else {
                deselectLetterButtons(selectedLetterChain);
            }

            if (createNewTimer) {
                timer.cancel();
                timer = new GameCountDownTimer(millisTotal, millisInterval);
                timer.start();
                createNewTimer = false;
            }

            // check if game over
            if (letterGrid.getEmptyCellsCount() == 0) {
                SplashActivity.bus.post(SoundManager.GAME_OVER_SOUND);
                Intent intent = new Intent(GameActivity.this, GameOverActivity.class);
                String points = String.valueOf(score.getPoints());
                intent.putExtra(SCORE, points);
                intent.putExtra(LEVEL, String.valueOf(level.getLevel()));
                GameActivity.this.startActivity(intent);
                overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
                return;
            }

            selectedLetterChain.clear();
            addLetterChain();
            SplashActivity.bus.post(SoundManager.TIMER_OUT_SOUND);

            // reset the timer
            timerBar.setProgress(millisReset);
            timerBar.setProgress(millisTotal);
            timer.start();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (penalty) {
                addPenalty(millisUntilFinished);
                penalty = false;
            }
            if (status == Status.RESUME) {
                startFrom(timerMillisUntilFinished);
                status = Status.RUN;
            }
            timerBar.setProgress((int) millisUntilFinished);
            timerMillisUntilFinished = millisUntilFinished;
        }

        public void startFrom(long millisUntilFinished) {
            timer.cancel();
            timer = new GameCountDownTimer(millisUntilFinished, millisInterval);
            timer.start();
            createNewTimer = true;
        }

        /**
         * Add a timer penalty, i.e. decrement some amount of time from the countdown timer.
         *
         * @param millisUntilFinished long amount of milliseconds until timer finishes
         */
        private void addPenalty(long millisUntilFinished) {
            SplashActivity.bus.post(SoundManager.PENALTY_SOUND);
            millisUntilFinished -= millisPenalty;
            if (millisUntilFinished < 0) {
                timer.onFinish();
                return;
            }
            timer.cancel();
            timer = new GameCountDownTimer(millisUntilFinished, millisInterval);
            timer.start();
            createNewTimer = true;
            deselectLetterButtons(selectedLetterChain);
            selectedLetterChain.clear();
        }
    }
}