text:
#include "../include/dbio.h"

namespace fisp
{
	namespace utility
	{
		/*-----------------------------------------------------------
		class DBPath
		------------------------------------------------------------*/
		DBPath::DBPath()
		{
			mstrData	= "data\\";
			mstrFile	= "";
			mstrApp		= "";
			mstrSource	= "source\\";
			mstrConfig	= "config\\";
			mstrStore	= "store\\";
			mstrUsers	= "users\\";
			mstrShader	= "shader\\";
			mstrWeb		= "web\\";
			mstrExePath = "";
			mstrDataPath = "";
		}

		DBPath::DBPath(const DBPath& other)
		{
			mstrData = other.mstrData;
			mstrFile = other.mstrFile;
			mstrApp = other.mstrApp;
			mstrSource = other.mstrSource;
			mstrConfig = other.mstrConfig;
			mstrStore = other.mstrStore;
			mstrUsers = other.mstrUsers;
			mstrShader = other.mstrShader;
			mstrWeb = other.mstrWeb;
			mstrExePath = other.mstrExePath;
			mstrDataPath = other.mstrDataPath;
		}

		void DBPath::setFileAndData(const String& file, const String& data)
		{
			fileField(file);
			dataField(data);
		}

		void DBPath::getFileAndData(String& file, String& data) const
		{
			file = fileField();
			data = dataField();
		}

		// only change data name. Default data name is "data".
		void DBPath::dataName(const String& strDataName)
		{
			if (strDataName.isEmpty())
				return;
			mstrData = "..\\";
			mstrData += strDataName;
			mstrData += "\\";
		}

		void DBPath::dataField(const String& strData)
		{
			mstrData = strData;
		}

		const String& DBPath::dataField() const
		{
			return mstrData;
		}

		void DBPath::fileField(const String& file)
		{
			mstrFile = file;
		}

		const String& DBPath::fileField() const
		{
			return mstrFile;
		}

		void DBPath::appField(const String& strApp)
		{
			if (!strApp.isEmpty())
			{
				mstrApp = strApp + "\\";
			}
			else
			{
				mstrApp = "";
			}
		}

		const String& DBPath::appField() const
		{
			return mstrApp;
		}

		void DBPath::sourceField(const String& path)
		{
			mstrSource = path;
		}

		String DBPath::source(bool absolute /*= true*/) const
		{
			if (absolute)
			{
				return mstrDataPath + mstrSource;
			}
			return mstrSource;
		}

		void DBPath::configField(const String& path)
		{
			mstrConfig = path;
		}

		String DBPath::config(bool absolute /*= true*/) const
		{
			if (absolute)
			{
				return mstrDataPath + mstrConfig;
			}
			return mstrConfig;
		}

		void DBPath::storeField(const String& path)
		{
			mstrStore = path;
		}

		String DBPath::store(bool absolute /* = true */) const
		{
			if (absolute)
			{
				return mstrDataPath + mstrStore;
			}
			return mstrStore;
		}

		void DBPath::usersField(const String& path)
		{
			mstrUsers = path;
		}

		String DBPath::users(bool absolute /* = true */) const
		{
			if (absolute)
			{
				return mstrDataPath + mstrUsers;
			}
			return mstrUsers;
		}

		void DBPath::shaderField(const String& path)
		{
			mstrShader = path;
		}

		String DBPath::shader(bool absolute /*= true*/) const
		{
			if (absolute)
			{
				return mstrDataPath + mstrShader;
			}
			return mstrShader;
		}

		void DBPath::webField(const String& path)
		{
			mstrWeb = path;
		}

		String DBPath::web(bool absolute /* = true */) const
		{
			if (absolute)
			{
				return mstrDataPath + mstrWeb;
			}
			return mstrWeb;
		}

		const String& DBPath::exePath() const
		{
			return mstrExePath;
		}

		void DBPath::exePath(const String& path)
		{
			mstrExePath = path;
		}

		const String& DBPath::dataPath() const
		{
			return mstrDataPath;
		}

		void DBPath::dataPath(int uPreDirectory)
		{
			if (uPreDirectory < 0)
			{
				mstrDataPath = mstrData;
				return;
			}
			if (uPreDirectory == 0)
			{
				mstrDataPath = mstrExePath + mstrData;
				return;
			}
			//
			String str = mstrExePath;
			ulong uIdx = 0, uFrom = str.getSize() - 1;
			while (uPreDirectory >= 0 && str.find(String("\\"), uIdx, uFrom, true))
			{
				if (uIdx <= 0)
				{
					mstrDataPath = mstrData;
					return;
				}
				uFrom = uIdx - 1;
				uPreDirectory--;
			}
			uFrom++;
			str.remove(uFrom, str.getSize() - uFrom);
			mstrDataPath = str + "\\" + mstrData;
		}

		void DBPath::fromPath(const String& strPath, int uPreDirectory)
		{
			mstrExePath = extractPath(strPath, 0);
			mstrDataPath = extractPath(strPath, uPreDirectory) + mstrData;
		}

		String DBPath::extractPath(const String& strPath, int uPreDirectory)
		{
			String strFinalPath;
			if (uPreDirectory < 0)
			{
				uPreDirectory = 0;
			}
			//
			String str = strPath;
			ulong uIdx = 0, uFrom = str.getSize() - 1;
			while (uPreDirectory >= 0 && str.find(String("\\"), uIdx, uFrom, true))
			{
				if (uIdx <= 0)
				{
					strFinalPath = "";
					return strFinalPath;
				}
				uFrom = uIdx - 1;
				uPreDirectory--;
			}
			uFrom++;
			str.remove(uFrom, str.getSize() - uFrom);
			strFinalPath = str + "\\";
			//
			return strFinalPath;
		}

	}
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**push_credential_id** | **int** | The push credential id |
**push_provider_id** | **int** | The push provider id |
**push_provider_name** | **string** | The push provider name. Available values: APPLE, APPLE_VOIP, GOOGLE |
**external_app_name** | **string** | The push provider's application name. |
**cert_credential** | [**\Voximplant\Model\CertCredentialType**](CertCredentialType.md) |  | [optional]
**applications** | [**\Voximplant\Model\ApplicationInfoType[]**](ApplicationInfoType.md) |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

redpajama_set_name: RedPajamaGithub


text:
@echo off
echo "Instaluji nw balicek"
npm install nw
echo "Instaluji EsruinoWebIDE"
npm install

set /p DUMMY=Hotovo! Stisknete ENTER pro pokracovani...


text:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace HWD
{

	public class splash : System.Windows.Forms.Form
	{
		private System.Windows.Forms.PictureBox pictureBox1;
		public System.Timers.Timer timer1;

		private System.ComponentModel.Container components = null;

		public splash()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(splash));
			this.pictureBox1 = new System.Windows.Forms.PictureBox();
			this.timer1 = new System.Timers.Timer();
			((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
			this.SuspendLayout();
			//
			// pictureBox1
			//
			this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
			this.pictureBox1.Location = new System.Drawing.Point(0, 0);
			this.pictureBox1.Name = "pictureBox1";
			this.pictureBox1.Size = new System.Drawing.Size(408, 320);
			this.pictureBox1.TabIndex = 0;
			this.pictureBox1.TabStop = false;
			//
			// timer1
			//
			this.timer1.Interval = 3000;
			this.timer1.SynchronizingObject = this;
			this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
			//
			// splash
			//
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(400, 317);
			this.ControlBox = false;
			this.Controls.Add(this.pictureBox1);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
			this.Name = "splash";
			this.ShowInTaskbar = false;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Loading HWD";
			this.TopMost = true;
			((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			this.Close();
		}
	}
}


text:
package org.wso2.am.integration.tests.streamingapis.serversentevents;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.admin.ApiResponse;
import org.wso2.am.integration.clients.admin.api.dto.AdvancedThrottlePolicyDTO;
import org.wso2.am.integration.clients.admin.api.dto.EventCountLimitDTO;
import org.wso2.am.integration.clients.admin.api.dto.ThrottleLimitDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIListDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.SubscriptionDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.TopicListDTO;
import org.wso2.am.integration.test.impl.DtoFactory;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APILifeCycleAction;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.am.integration.test.utils.generic.APIMTestCaseUtils;
import org.wso2.am.integration.test.utils.token.TokenUtils;
import org.wso2.am.integration.tests.streamingapis.StreamingApiTestUtils;
import org.wso2.am.integration.tests.streamingapis.serversentevents.client.SimpleSseReceiver;
import org.wso2.am.integration.tests.streamingapis.serversentevents.server.SseServlet;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.annotations.SetEnvironment;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;

import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
public class ServerSentEventsAPITestCase extends APIMIntegrationBaseTest {

    private final Log log = LogFactory.getLog(ServerSentEventsAPITestCase.class);
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    private String sseEventPublisherSource = TestConfigurationProvider.getResourceLocation() + File.separator +
            "artifacts" + File.separator + "AM" + File.separator + "configFiles" + File.separator + "streamingAPIs" +
            File.separator + "serverSentEventsTest" + File.separator;
    private String sseRequestEventPublisherSource = "SSE_Req_Logger.xml";
    private String sseThrottleOutEventPublisherSource = "SSE_Throttle_Out_Logger.xml";
    private String sseEventPublisherTarget = FrameworkPathUtil.getCarbonHome() + File.separator + "repository" +
            File.separator + "deployment" + File.separator + "server" + File.separator + "eventpublishers" +
            File.separator;

    private String apiName = "SSEAPI";
    private String applicationName = "SSEApplication";

    private ServerConfigurationManager serverConfigurationManager;
    private String provider;
    private APIRequest apiRequest;
    private int sseServerPort;
    private String sseServerHost;
    private String apiId;
    private String appId;
    private SseServlet sseServlet;
    private Server sseServer;
    private SimpleSseReceiver sseReceiver;
    private String apiEndpoint;
    private String consumerKey;
    private String consumerSecret;

    @Factory(dataProvider = "userModeDataProvider")
    public ServerSentEventsAPITestCase(TestUserMode userMode) {
        this.userMode = userMode;
    }

    @DataProvider
    public static Object[][] userModeDataProvider() {
        return new Object[][]{
                new Object[] { TestUserMode.SUPER_TENANT_ADMIN },
                new Object[] { TestUserMode.TENANT_ADMIN }
        };
    }

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init(userMode);
        serverConfigurationManager = new ServerConfigurationManager(gatewayContextWrk);
        serverConfigurationManager.applyConfigurationWithoutRestart
                (new File(sseEventPublisherSource + sseRequestEventPublisherSource),
                        new File(sseEventPublisherTarget + sseRequestEventPublisherSource), false);
        serverConfigurationManager.applyConfigurationWithoutRestart
                (new File(sseEventPublisherSource + sseThrottleOutEventPublisherSource),
                        new File(sseEventPublisherTarget + sseThrottleOutEventPublisherSource), false);
        sseServerHost = InetAddress.getLocalHost().getHostName();
        int lowerPortLimit = 8080;
        int upperPortLimit = 8090;
        sseServerPort = StreamingApiTestUtils.getAvailablePort(lowerPortLimit, upperPortLimit, sseServerHost);
        if (sseServerPort == -1) {
            throw new APIManagerIntegrationTestException("No available port in the range " + lowerPortLimit + "-" +
                    upperPortLimit + " was found");
        }
        log.info("Selected port " + sseServerPort + " to start backend server");
        initializeSseServer(sseServerPort);
    }

    @Test(description = "Publish SSE API")
    public void testPublishSseApi() throws Exception {
        provider = user.getUserName();
        String apiContext = "sse";
        String apiVersion = "1.0.0";

        URI endpointUri = new URI("http://" + sseServerHost + ":" + sseServerPort);

        //Create the api creation request object
        apiRequest = new APIRequest(apiName, apiContext, endpointUri, endpointUri);
        apiRequest.setVersion(apiVersion);
        apiRequest.setTiersCollection(APIMIntegrationConstants.API_TIER.ASYNC_UNLIMITED);
        apiRequest.setProvider(provider);
        apiRequest.setType("SSE");
        HttpResponse addAPIResponse = restAPIPublisher.addAPI(apiRequest);
        apiId = addAPIResponse.getData();
        createAPIRevisionAndDeployUsingRest(apiId, restAPIPublisher);
        restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.PUBLISH.getAction(), null);
        waitForAPIDeploymentSync(user.getUserName(), apiName, apiVersion, APIMIntegrationConstants.IS_API_EXISTS);

        APIIdentifier apiIdentifier = new APIIdentifier(provider, apiName, apiVersion);

        if (TestUserMode.SUPER_TENANT_ADMIN.equals(userMode) || TestUserMode.SUPER_TENANT_USER.equals(userMode)) {
            apiEndpoint = getSuperTenantAPIInvocationURLHttp(apiContext, apiVersion);
        } else {
            apiEndpoint = getAPIInvocationURLHttp(apiContext, apiVersion);
        }

        APIListDTO apiPublisherAllAPIs = restAPIPublisher.getAllAPIs();
        assertTrue(APIMTestCaseUtils.isAPIAvailable(apiIdentifier, apiPublisherAllAPIs),
                "Published API is visible in API Publisher.");
        org.wso2.am.integration.clients.store.api.v1.dto.APIListDTO restAPIStoreAllAPIs;
        if (TestUserMode.SUPER_TENANT_ADMIN == userMode) {
            restAPIStoreAllAPIs = restAPIStore.getAllAPIs();
        } else {
            restAPIStoreAllAPIs = restAPIStore.getAllAPIs(user.getUserDomain());
        }
        assertTrue(APIMTestCaseUtils.isAPIAvailableInStore(apiIdentifier, restAPIStoreAllAPIs),
                "Published API is visible in API Store.");
    }

    @Test(description = "Create Application and subscribe", dependsOnMethods = "testPublishSseApi")
    public void testSseApiApplicationSubscription() throws Exception {
        HttpResponse applicationResponse = restAPIStore.createApplication(applicationName,
                "", APIMIntegrationConstants.API_TIER.UNLIMITED, ApplicationDTO.TokenTypeEnum.OAUTH);
        appId = applicationResponse.getData();
        SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId, appId,
                APIMIntegrationConstants.API_TIER.ASYNC_UNLIMITED);
        // Validate Subscription of the API
        Assert.assertEquals(subscriptionDTO.getStatus(), SubscriptionDTO.StatusEnum.UNBLOCKED);
    }

    @Test(description = "check for topics of a SSE api", dependsOnMethods = "testSseApiApplicationSubscription")
    public void testTopicRetrievalofSSEApi() throws  Exception {
        HttpResponse topicResponse = restAPIStore.getTopics(apiId, user.getUserDomain());
        Gson g = new Gson();
        TopicListDTO topicListDTO = g.fromJson(topicResponse.getData(), TopicListDTO.class);
        Assert.assertEquals(topicListDTO.getCount().intValue(), 1);

    }

    @Test(description = "Invoke SSE API", dependsOnMethods = "testSseApiApplicationSubscription")
    public void testInvokeSseApi() throws Exception {
        ArrayList grantTypes = new ArrayList();
        grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.PASSWORD);
        grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.REFRESH_CODE);
        grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
        ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(appId, "3600", null,
                ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
        String accessToken = applicationKeyDTO.getToken().getAccessToken();
        consumerKey = applicationKeyDTO.getConsumerKey();
        consumerSecret = applicationKeyDTO.getConsumerSecret();
        invokeSseApi(accessToken, 30000);

        int sent = sseServlet.getEventsSent();
        int received = sseReceiver.getReceivedDataEventsCount();
        Assert.assertNotEquals(sent, 0);
        Assert.assertEquals(sent, received);

        sseServlet.setEventsSent(0);
        sseReceiver.setReceivedDataEventsCount(0);
    }

    public void testSseApiThrottling() throws Exception {
        InputStream inputStream = new FileInputStream(getAMResourceLocation() + File.separator +
                "configFiles" + File.separator + "streamingAPIs" + File.separator + "serverSentEventsTest" +
                File.separator + "policy.json");

        // Extract the field values from the input stream
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonMap = mapper.readTree(inputStream);
        String policyName = jsonMap.get("policyName").textValue();
        String policyDescription = jsonMap.get("policyDescription").textValue();
        JsonNode defaultLimitJson = jsonMap.get("defaultLimit");
        JsonNode requestCountJson = defaultLimitJson.get("requestCount");
        Long requestCountLimit = Long.valueOf(String.valueOf(requestCountJson.get("requestCount")));
        String timeUnit = requestCountJson.get("timeUnit").textValue();
        Integer unitTime = Integer.valueOf(String.valueOf(requestCountJson.get("unitTime")));

        // Create the advanced throttling policy with request count quota type
        EventCountLimitDTO eventCountLimitDTO = DtoFactory.createEventCountLimitDTO(timeUnit, unitTime,
                requestCountLimit);
        ThrottleLimitDTO defaultLimit = DtoFactory.createEventCountThrottleLimitDTO(eventCountLimitDTO);
        AdvancedThrottlePolicyDTO advancedPolicyDTO = DtoFactory
                .createAdvancedThrottlePolicyDTO(policyName, "", policyDescription, false, defaultLimit,
                        new ArrayList<>());

        // Add the advanced throttling policy
        ApiResponse<AdvancedThrottlePolicyDTO> addedPolicy =
                restAPIAdmin.addAdvancedThrottlingPolicy(advancedPolicyDTO);
        // Assert the status code and policy ID
        Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
        AdvancedThrottlePolicyDTO addedAdvancedPolicyDTO = addedPolicy.getData();
        String apiPolicyId = addedAdvancedPolicyDTO.getPolicyId();
        Assert.assertNotNull(apiPolicyId, "The policy ID cannot be null or empty");

        // Update Throttling policy of the API
        HttpResponse response = restAPIPublisher.getAPI(apiId);
        Gson g = new Gson();
        APIDTO apidto = g.fromJson(response.getData(), APIDTO.class);
        apidto.setApiThrottlingPolicy("SSETestThrottlingPolicy");
        APIDTO updatedAPI = restAPIPublisher.updateAPI(apidto);
        Assert.assertEquals(updatedAPI.getApiThrottlingPolicy(), "SSETestThrottlingPolicy");
        // Get an Access Token from the user who is logged into the API Store.
        URL tokenEndpointURL = new URL(getKeyManagerURLHttps() + "/oauth2/token");
        String subsAccessTokenPayload = APIMTestCaseUtils.getPayloadForPasswordGrant(user.getUserName(),
                user.getPassword());
        JSONObject subsAccessTokenGenerationResponse = new JSONObject(
                apiStore.generateUserAccessKey(consumerKey, consumerSecret, subsAccessTokenPayload,
                        tokenEndpointURL).getData());

        String subsRefreshToken = subsAccessTokenGenerationResponse.getString("refresh_token");
        assertFalse(org.apache.commons.lang.StringUtils.isEmpty(subsRefreshToken),
                "Refresh token of access token generated by subscriber is empty");

        // Obtain user access token
        String requestBody = APIMTestCaseUtils.getPayloadForPasswordGrant(user.getUserName(), user.getPassword());
        JSONObject accessTokenGenerationResponse = new JSONObject(
                apiStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody,
                        tokenEndpointURL).getData());

        // Get Access Token and Refresh Token
        String refreshToken = accessTokenGenerationResponse.getString("refresh_token");
        String getAccessTokenFromRefreshTokenRequestBody =
                "grant_type=refresh_token&refresh_token=" + refreshToken;
        accessTokenGenerationResponse = new JSONObject(
                apiStore.generateUserAccessKey(consumerKey, consumerSecret,
                        getAccessTokenFromRefreshTokenRequestBody,
                        tokenEndpointURL).getData());
        String userAccessToken = accessTokenGenerationResponse.getString("access_token");

        Assert.assertNotNull("Access Token not found " + accessTokenGenerationResponse, userAccessToken);
        String tokenJti = TokenUtils.getJtiOfJwtToken(userAccessToken);
        testThrottling(tokenJti);
    }

    private void testThrottling(String accessToken) throws Exception {
        // Attempt to run for 3 minutes. Connection is expected to be closed within 1 minute due to throttle out.
        startAndStopSseServer(3 * 60000);
        // Prevent API requests getting dispersed into two time units
        while (LocalDateTime.now().getSecond() > 40) {
            Thread.sleep(5000L);
        }
        long startTime = System.currentTimeMillis();
        startSseReceiver(accessToken, null);
        long endTime = System.currentTimeMillis();
        Assert.assertTrue((endTime - startTime) < 60000);

        // Re-attempt to connect after throttle out. A throttled out event is expected to be received.
        AtomicBoolean isThrottled = new AtomicBoolean(false);
        startSseReceiver(accessToken, new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) {
                isThrottled.set(aBoolean);
            }
        });
        Thread.sleep(3000L);
        Assert.assertTrue(isThrottled.get());
    }

    private void initializeSseServer(int port) {
        Server server = new Server(port);
        ServletHandler servletHandler = new ServletHandler();
        server.setHandler(servletHandler);

        sseServlet = new SseServlet();
        ServletHolder servletHolder = new ServletHolder(sseServlet);
        servletHandler.addServletWithMapping(servletHolder, "/memory");

        sseServer = server;
    }

    private void invokeSseApi(String bearerToken, long runForMillis) throws Exception {
        startAndStopSseServer(runForMillis);
        Thread.sleep(5000);
        startSseReceiver(bearerToken, null);
    }

    private void startAndStopSseServer(long stopAfterMillis) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    sseServer.start();
                    log.info("SSE Server Started and will be stopped after: " + stopAfterMillis + "ms.");
                    Thread.sleep(stopAfterMillis);
                    sseServer.stop();
                    log.info("SSE Server Stopped.");
                } catch (Exception e) {
                    log.error("Failed to start/stop the SSE server.", e);
                }
            }
        });
    }

    private void startSseReceiver(String bearerToken, Consumer<Boolean> throttledResponseConsumer) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(apiEndpoint + "/memory");
        sseReceiver = new SimpleSseReceiver(target, bearerToken);
        sseReceiver.registerThrottledResponseConsumer(throttledResponseConsumer);
        try {
            sseReceiver.open();
        } finally {
            sseReceiver.close(); // This will be called when sseServer.stop() is called
        }
    }

    @AfterTest(alwaysRun = true)
    public void destroy() throws Exception {
        serverConfigurationManager.restoreToLastConfiguration(false);
        executorService.shutdownNow();
        super.cleanUp();
    }
}


text:
package org.bumishakti.shell.commands;

import java.util.ArrayList;
import java.util.List;

import org.bumishakti.shell.RedmineServerManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;

import com.taskadapter.redmineapi.bean.Group;
import com.taskadapter.redmineapi.bean.Membership;
import com.taskadapter.redmineapi.bean.Role;
import com.taskadapter.redmineapi.bean.User;

/**
 * @author dbs
 *
 */
@Component
public class RedmineUserCommands implements CommandMarker{

	@Autowired RedmineServerManager redmineManager;

	@CliAvailabilityIndicator({"usr list", "usr create", "usr update", "usr delete"})
	public boolean isIssueAvailable() {
		return redmineManager.isRedmineConnected();
	}

	@CliCommand(value = "usr list", help = "List all Redmine users")
	public String list(
			@CliOption(key = { "user" }, mandatory = false, help = "User name to search, by login, first name or last name, or id or email") final String userName){
		StringBuffer buf = new StringBuffer();
		try {
			if(!isIssueAvailable())
				throw new Exception(String.format("please connect to Redmine instance first"));
			List<User> users, usersDB = redmineManager.getUsers();
			if(null != userName){
				users = new ArrayList<>();
				for (User u : usersDB) {
					if( (u.getLogin().toLowerCase().contains(userName.toLowerCase()))
							|| (u.getMail().toLowerCase().contains(userName.toLowerCase()))
							|| (u.getFirstName().toLowerCase().contains(userName.toLowerCase()))
							|| (u.getLastName().toLowerCase().contains(userName.toLowerCase()))
							|| (u.getId().toString().equals(userName))){
						users.add(u);
					}
				}
				if(users.isEmpty())
					return String.format("%s [%s] not found", Constants.REDMINE_USER, userName);
			}else
				users = usersDB;
			buf.append(String.format("%d %s(s):", users.size(), Constants.REDMINE_USER)).append("\n");
			for (User u : users) {
				buf.append("\n").append(printUserInfo(u)).append("\n");
			}
			buf.append("\n").append("Number of ").append(Constants.REDMINE_USER).append(": ").append(users.size());
		} catch (Exception e) {
			buf.append("\n").append(e.getMessage());
		}
		return buf.toString();
	}

	private String printUserInfo(User u) {
		StringBuffer buf = new StringBuffer();
		buf.append(Constants.REDMINE_USER).append(" [").append(u.getFullName()).append("]")
		.append(", Login: [").append(u.getLogin()).append("]")
		.append(", Id: [").append(u.getId()).append("]")
		.append(", Mail: [").append(u.getMail()).append("]")
		.append(", Last Login On: [").append(u.getLastLoginOn())
		.append("\n\tGroups:\n");
		for (Group g : u.getGroups()) {
			buf.append("\tgroup: ").append(g.getName()).append("\n");
		}
		buf.append("\n\tMemberships:\n");
		for (Membership m : u.getMemberships()) {
			buf.append("\tmembership: ").append(m.getProject().getName()).append("\n");
			buf.append("\n\t\tRoles:\n");
			for (Role r : m.getRoles()) {
				buf.append("\t\trole: ").append(r.getName()).append("\n");
			}
		}
		return buf.toString();
	}
}


text:
package org.evilco.mc.protocol.common.packet.server;

import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import org.evilco.mc.protocol.common.packet.IPacket;
import org.evilco.mc.protocol.common.utility.PacketDataUtility;

/**
 * Represents the handshake packet.
 */
public class HandshakePacket implements IPacket {

	/**
	 * Stores the protocol version.
	 */
	@Getter
	@Setter
	private int protocolVersion = 4;

	/**
	 * Stores the server address (the hostname or IP address).
	 */
	@Getter
	@Setter
	@NonNull
	private String serverAddress;

	/**
	 * Stores the server port.
	 */
	@Getter
	@Setter
	private int serverPort;

	/**
	 * Stores the next requested state.
	 */
	@Getter
	@Setter
	private int nextState;

	/**
	 * Constructs a new HandshakePacket.
	 * @param serverAddress The server address.
	 * @param serverPort The server port.
	 * @param nextState The next state.
	 */
	public HandshakePacket (@NonNull String serverAddress, int serverPort, int nextState) {
		this.serverAddress = serverAddress;
		this.serverPort = serverPort;
		this.nextState = nextState;
	}

	/**
	 * Constructs a new HandshakePacket.
	 * @param protocolVersion The protocol version.
	 * @param serverAddress The server address.
	 * @param serverPort The server port.
	 * @param nextState The next state.
	 */
	public HandshakePacket (int protocolVersion, @NonNull String serverAddress, int serverPort, int nextState) {
		this (serverAddress, serverPort, nextState);
		this.protocolVersion = protocolVersion;
	}

	/**
	 * Constructs a new HandshakePacket.
	 * @param buffer The packet buffer.
	 */
	public HandshakePacket (ByteBuf buffer) {
		this.protocolVersion = PacketDataUtility.readVariableInteger (buffer);
		this.serverAddress = PacketDataUtility.readString (buffer);
		this.serverPort = buffer.readUnsignedShort ();
		this.nextState = PacketDataUtility.readVariableInteger (buffer);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void write (ByteBuf out) {
		PacketDataUtility.writeVariableInteger (out, this.protocolVersion);
		PacketDataUtility.writeString (out, this.serverAddress);
		out.writeShort (this.serverPort);
		PacketDataUtility.writeVariableInteger (out, this.nextState);
	}
}


text:
package net.vrallev.android.cat.instance;

import net.vrallev.android.cat.CatLog;

/**
 * @author rwondratschek
 */
@SuppressWarnings("UnusedDeclaration")
public class CatSimple extends CatLog {

    private final String mTag;

    public CatSimple(Class<?> clazz) {
        this(clazz.getSimpleName());
    }

    public CatSimple(String tag) {
        mTag = tag == null ? "" : tag;
    }

    @Override
    protected String getTag() {
        return mTag;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Spect.Net.VsPackage.SolutionItems;

#pragma warning disable VSTHRD010 // Invoke single-threaded types on Main thread

namespace Spect.Net.VsPackage.VsxLibrary.Command
{
    /// <summary>
    /// This class represents a command that can be associated with a .z80asm file.
    /// </summary>
    public abstract class SingleProjectItemCommandBase : SpectNetCommandBase
    {
        /// <summary>
        /// Gets the file item extensions accepted by this command
        /// </summary>
        public abstract IEnumerable<string> ItemExtensionsAccepted { get; }

        /// <summary>
        /// Override this method to define the status query action
        /// </summary>
        /// <param name="mc"></param>
        protected override void OnQueryStatus(OleMenuCommand mc)
        {
            mc.Visible = SpectNetPackage.Default.ActiveProject != null
                && ItemPath != null;
        }

        /// <summary>
        /// Gets the currently selected Z80 program item
        /// </summary>
        /// <param name="hierarchy"></param>
        /// <param name="itemId"></param>
        public void GetItem(out IVsHierarchy hierarchy, out uint itemId) =>
            IsSingleItemSelection(out hierarchy, out itemId);

        /// <summary>
        /// Gets the full path of the item; or null, if there is no .z80asm item selected.
        /// </summary>
        public string ItemPath
        {
            get
            {
                var singleItem = IsSingleItemSelection(out var hierarchy, out var itemId);
                if (!singleItem) return null;

                // ReSharper disable once SuspiciousTypeConversion.Global
                if (hierarchy is IVsProject project)
                {
                    project.GetMkDocument(itemId, out var itemFullPath);
                    var ext = Path.GetExtension(itemFullPath);
                    return ItemExtensionsAccepted.Any(e => string.Compare(e, ext, StringComparison.OrdinalIgnoreCase) == 0)
                        ? itemFullPath
                        : null;
                }
                return null;
            }
        }

        /// <summary>
        /// Gets the extension of the item
        /// </summary>
        public string ItemExtension => Path.GetExtension(ItemPath);

        /// <summary>
        /// Gets the identity of the project item.
        /// </summary>
        public string Identity
        {
            get
            {
                var singleItem = IsSingleItemSelection(out var hierarchy, out var itemId);
                if (!singleItem) return null;

                hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out var objProj);
                if (objProj is ProjectItem projItem)
                {
                    var identity = projItem.Properties.Item("Identity");
                    return identity?.Value?.ToString();
                }
                return null;
            }
        }

        /// <summary>
        /// Tests if the file behind the command is in the active project
        /// </summary>
        public bool IsInActiveProject
            => SpectNetPackage.Default.Solution.IsFileInActiveProject(ItemPath);

        /// <summary>
        /// Gets the ZX Spectrum project of this item
        /// </summary>
        public SpectrumProject SpectrumProject =>
            SpectNetPackage.Default.Solution.Projects
                .FirstOrDefault(project => project.ContainsFile(ItemPath));

        /// <summary>
        /// This method checks if there is only a single item selected in Solution Explorer.
        /// </summary>
        /// <param name="hierarchy">The selected hierarchy</param>
        /// <param name="itemid">The selected item in the hierarchy</param>
        /// <returns>
        /// True, if only a single item is selected; otherwise, false
        /// </returns>
        public static bool IsSingleItemSelection(out IVsHierarchy hierarchy, out uint itemid)
        {
            hierarchy = null;
            itemid = VSConstants.VSITEMID_NIL;

            if (!(Package.GetGlobalService(typeof(SVsShellMonitorSelection)) is IVsMonitorSelection monitorSelection)
                || !(Package.GetGlobalService(typeof(SVsSolution)) is IVsSolution solution))
            {
                return false;
            }

            var hierarchyPtr = IntPtr.Zero;
            var selectionContainerPtr = IntPtr.Zero;

            try
            {
                // --- Obtain the current selection
                var hr = monitorSelection.GetCurrentSelection(out hierarchyPtr,
                    out itemid,
                    out var multiItemSelect,
                    out selectionContainerPtr);

                if (ErrorHandler.Failed(hr) || hierarchyPtr == IntPtr.Zero || itemid == VSConstants.VSITEMID_NIL)
                {
                    // --- There is no selection
                    return false;
                }

                // --- Multiple items are selected
                if (multiItemSelect != null) return false;

                // --- No hierarchy, no selection
                hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy;
                if (hierarchy == null) return false;

                // --- Return true only when the hierarchy is a project inside the Solution
                // --- and it has a ProjectID Guid
                return !ErrorHandler.Failed(solution.GetGuidOfProject(hierarchy, out _));
            }
            finally
            {
                // --- Release unmanaged resources
                if (selectionContainerPtr != IntPtr.Zero)
                {
                    Marshal.Release(selectionContainerPtr);
                }
                if (hierarchyPtr != IntPtr.Zero)
                {
                    Marshal.Release(hierarchyPtr);
                }
            }
        }
    }

}

#pragma warning restore VSTHRD010 // Invoke single-threaded types on Main thread


text:
import * as React from 'react';
import { storiesOf } from '@storybook/react';
import styled from 'styled-components';
import Translate from '../Translate';
import { Toggler } from '@element-motion/dev';
import { Motion } from '@element-motion/utils';
import Scale from './index';
import InverseScale from './InverseScale';

/**
 * Very important
 * Do not put padding or margin in this else it will be scaled down.
 * It won't look correct at all.
 */
const Menu = styled.div<any>`
  display: inline-block;
  flex-direction: column;
  background-color: #393939;
  border-radius: ${props => (props.isExpanded ? 3 : 1)}px;
  color: #fff;
  box-shadow: 0 1px 5px rgba(32, 33, 36, 0.5);
  position: relative;
  overflow: ${props => props.overflow};
`;

const MenuItems = styled.ul`
  margin: 0;
  padding: 0;
  list-style: none;
`;

const MenuButton = styled.div`
  padding: 8px;
  cursor: pointer;

  :hover {
    text-decoration: underline;
  }
`;

const MenuItem = styled.li`
  border-top: 1px solid rgba(255, 255, 255, 0.4);
  display: block;
  padding: 8px;
  white-space: nowrap;
`;

const origin = {
  topLeft: 'top:0;left: 0;',
  topRight: 'top:0;right:0;',
  bottomRight: 'bottom:0;right:0;',
  bottomLeft: 'bottom:0;left:0;',
  midLeft: 'top:0;left:50%;',
};

const Block = styled.div<any>`
  position: absolute;
  width: ${props => props.size || 100}px;
  height: ${props => props.size || 100}px;
  background-color: red;
  ${props => origin[props.origin]};
`;

storiesOf('@element-motion/motions/Scale', module)
  .add('Multiple', () => (
    <Toggler>
      {toggler => (
        <>
          <Motion triggerSelfKey={toggler.shown}>
            <Scale>
              {motion => (
                <Block
                  origin="topLeft"
                  {...motion}
                  onClick={() => toggler.toggle()}
                  size={toggler.shown ? 200 : 100}
                />
              )}
            </Scale>
          </Motion>

          <Motion triggerSelfKey={toggler.shown}>
            <Scale>
              {motion => (
                <Block
                  origin="midLeft"
                  {...motion}
                  onClick={() => toggler.toggle()}
                  size={toggler.shown ? 300 : 100}
                />
              )}
            </Scale>
          </Motion>
        </>
      )}
    </Toggler>
  ))

  .add('OriginTopLeft', () => (
    <Toggler>
      {toggler => (
        <Motion triggerSelfKey={toggler.shown}>
          <Scale>
            {motion => (
              <Block
                origin="topLeft"
                {...motion}
                onClick={() => toggler.toggle()}
                size={toggler.shown ? 300 : 100}
              />
            )}
          </Scale>
        </Motion>
      )}
    </Toggler>
  ))
  .add('ComposedWithTranslate', () => (
    <Toggler>
      {toggler => (
        <Motion triggerSelfKey={toggler.shown}>
          <Translate>
            <Scale>
              {motion => (
                <Block
                  origin={toggler.shown ? 'topRight' : 'topLeft'}
                  {...motion}
                  onClick={() => toggler.toggle()}
                  size={toggler.shown ? 300 : 100}
                />
              )}
            </Scale>
          </Translate>
        </Motion>
      )}
    </Toggler>
  ))
  .add('OriginTopRight', () => (
    <Toggler>
      {toggler => (
        <Motion triggerSelfKey={toggler.shown}>
          <Scale transformOrigin="top right">
            {motion => (
              <Block
                origin="topRight"
                {...motion}
                onClick={() => toggler.toggle()}
                size={toggler.shown ? 300 : 100}
              />
            )}
          </Scale>
        </Motion>
      )}
    </Toggler>
  ))
  .add('OriginBottomRight', () => (
    <Toggler>
      {toggler => (
        <Motion triggerSelfKey={toggler.shown}>
          <Scale transformOrigin="bottom right">
            {motion => (
              <Block
                origin="bottomRight"
                {...motion}
                onClick={() => toggler.toggle()}
                size={toggler.shown ? 300 : 100}
              />
            )}
          </Scale>
        </Motion>
      )}
    </Toggler>
  ))
  .add('OriginBottomLeft', () => (
    <Toggler>
      {toggler => (
        <Motion triggerSelfKey={toggler.shown}>
          <Scale transformOrigin="bottom left">
            {motion => (
              <Block
                origin="bottomLeft"
                {...motion}
                onClick={() => toggler.toggle()}
                size={toggler.shown ? 300 : 100}
              />
            )}
          </Scale>
        </Motion>
      )}
    </Toggler>
  ))
  .add('WithInverse', () => (
    <Toggler>
      {toggler => (
        <Motion triggerSelfKey={toggler.shown}>
          <Scale duration={200}>
            {motion => (
              <Menu {...motion} isExpanded={toggler.shown} overflow="hidden">
                <InverseScale>
                  {inverse => (
                    <div {...inverse}>
                      <MenuButton onClick={toggler.toggle}>Menu</MenuButton>
                      <MenuItems
                        className="target"
                        style={{ position: toggler.shown ? 'static' : 'absolute' }}
                      >
                        <MenuItem>Menu item 1</MenuItem>
                        <MenuItem>Menu item 2</MenuItem>
                        <MenuItem>Menu item 3</MenuItem>
                        <MenuItem>Menu item 4</MenuItem>
                      </MenuItems>
                    </div>
                  )}
                </InverseScale>
              </Menu>
            )}
          </Scale>
        </Motion>
      )}
    </Toggler>
  ));


text:
(function(angular, $, _) {
  angular.module('crmMailing').directive('crmMailingBlockRecipients', function(crmMailingSimpleDirective) {
    return crmMailingSimpleDirective('crmMailingBlockRecipients', '~/crmMailing/BlockRecipients.html');
  });
})(angular, CRM.$, CRM._);


text:
app.filter('partition', function() {
  var cache = {};
  var filter = function(arr, size) {
    if (!arr) { return; }
    var newArr = [];
    for (var i=0; i<arr.length; i+=size) {
      newArr.push(arr.slice(i, i+size));
    }
    var arrString = JSON.stringify(arr);
    var fromCache = cache[arrString+size];
    if (JSON.stringify(fromCache) === JSON.stringify(newArr)) {
      return fromCache;
    }
    cache[arrString+size] = newArr;
    return newArr;
  };
  return filter;
});


text:
<?php

/**
 * Client for an @{class:ArcanistHgProxyServer}. This client talks to a PHP
 * process which serves as a proxy in front of a Mercurial server process.
 * The PHP proxy allows multiple clients to use the same Mercurial server.
 *
 * This class presents an API which is similar to the hg command-line API.
 *
 * Each client is bound to a specific working copy:
 *
 *   $working_copy = '/path/to/some/hg/working/copy/';
 *   $client = new ArcanistHgProxyClient($working_copy);
 *
 * For example, to run `hg log -l 5` via a client:
 *
 *   $command = array('log', '-l', '5');
 *   list($err, $stdout, $stderr) = $client->executeCommand($command);
 *
 * The advantage of using this complex mechanism is that commands run in this
 * way do not need to pay the startup overhead for hg and the Python runtime,
 * which is often on the order of 100ms or more per command.
 *
 * @task construct  Construction
 * @task config     Configuration
 * @task exec       Executing Mercurial Commands
 * @task internal   Internals
 */
final class ArcanistHgProxyClient {

  private $workingCopy;
  private $server;

  private $skipHello;

/* -(  Construction  )------------------------------------------------------- */

  /**
   * Build a new client. This client is bound to a working copy. A server
   * must already be running on this working copy for the client to work.
   *
   * @param string Path to a Mercurial working copy.
   *
   * @task construct
   */
  public function __construct($working_copy) {
    $this->workingCopy = Filesystem::resolvePath($working_copy);
  }

/* -(  Configuration  )------------------------------------------------------ */

  /**
   * When connecting, do not expect the "capabilities" message.
   *
   * @param bool True to skip the "capabilities" message.
   * @return this
   *
   * @task config
   */
  public function setSkipHello($skip) {
    $this->skipHello = $skip;
    return $this;
  }

/* -(  Executing Merucurial Commands  )-------------------------------------- */

  /**
   * Execute a command (given as a list of arguments) via the command server.
   *
   * @param list<string> A list of command arguments, like "log", "-l", "5".
   * @return tuple<int, string, string> Return code, stdout and stderr.
   *
   * @task exec
   */
  public function executeCommand(array $argv) {
    if (!$this->server) {

      try {
        $server = $this->connectToDaemon();
      } catch (Exception $ex) {
        $this->launchDaemon();
        $server = $this->connectToDaemon();
      }

      $this->server = $server;
    }
    $server = $this->server;

    // Note that we're adding "runcommand" to make the server run the command.
    // Theoretically the server supports other capabilities, but in practice
    // we are only concerend with "runcommand".

    $server->write(array_merge(array('runcommand'), $argv));

    // We'll get back one or more blocks of response data, ending with an 'r'
    // block which indicates the return code. Reconstitute these into stdout,
    // stderr and a return code.

    $stdout = '';
    $stderr = '';
    $err    = 0;

    $done = false;
    while ($message = $server->waitForMessage()) {

      // The $server channel handles decoding of the wire format and gives us
      // messages which look like this:
      //
      //   array('o', '<data...>');

      list($channel, $data) = $message;
      switch ($channel) {
        case 'o':
          $stdout .= $data;
          break;
        case 'e':
          $stderr .= $data;
          break;
        case 'd':
          // TODO: Do something with this? This is the 'debug' channel.
          break;
        case 'r':
          // NOTE: This little dance is because the value is emitted as a
          // big-endian signed 32-bit long. PHP has no flag to unpack() that
          // can unpack these, so we unpack a big-endian unsigned long, then
          // repack it as a machine-order unsigned long, then unpack it as
          // a machine-order signed long. This appears to produce the desired
          // result.
          $err = head(unpack('N', $data));
          $err = pack('L', $err);
          $err = head(unpack('l', $err));
          $done = true;
          break;
      }

      if ($done) {
        break;
      }
    }

    return array($err, $stdout, $stderr);
  }

/* -(  Internals  )---------------------------------------------------------- */

  /**
   * @task internal
   */
  private function connectToDaemon() {
    $errno = null;
    $errstr = null;

    $socket_path = ArcanistHgProxyServer::getPathToSocket($this->workingCopy);
    $socket = @stream_socket_client('unix://'.$socket_path, $errno, $errstr);

    if ($errno || !$socket) {
      throw new Exception(
        "Unable to connect socket! Error #{$errno}: {$errstr}");
    }

    $channel = new PhutilSocketChannel($socket);
    $server = new ArcanistHgServerChannel($channel);

    if (!$this->skipHello) {
      // The protocol includes a "hello" message with capability and encoding
      // information. Read and discard it, we use only the "runcommand"
      // capability which is guaranteed to be available.
      $hello = $server->waitForMessage();
    }

    return $server;
  }

  /**
   * @task internal
   */
  private function launchDaemon() {
    $root = dirname(phutil_get_library_root('arcanist'));
    $bin = $root.'/scripts/hgdaemon/hgdaemon_server.php';
    $proxy = new ExecFuture(
      '%s %s --idle-limit 15 --quiet %C',
      $bin,
      $this->workingCopy,
      $this->skipHello ? '--skip-hello' : null);
    $proxy->resolvex();
  }

}


text:
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIFont : NSObject <NSCopying>

// Returns an instance of the font associated with the text style and scaled appropriately for the user's selected content size category. See UIFontDescriptor.h for the complete list.
+ (UIFont *)preferredFontForTextStyle:(NSString *)style NS_AVAILABLE_IOS(7_0);

// Returns a font using CSS name matching semantics.
+ (UIFont *)fontWithName:(NSString *)fontName size:(CGFloat)fontSize;

// Returns an array of font family names for all installed fonts
+ (NSArray *)familyNames;

// Returns an array of font names for the specified family name
+ (NSArray *)fontNamesForFamilyName:(NSString *)familyName;

// Some convenience methods to create system fonts
// Think carefully before using these methods. In most cases, a font returned by +preferredFontForTextStyle: will be more appropriate, and will respect the user's selected content size category.
+ (UIFont *)systemFontOfSize:(CGFloat)fontSize;
+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize;
+ (UIFont *)italicSystemFontOfSize:(CGFloat)fontSize;

// Weights used here are analogous to those used with UIFontDescriptor's UIFontWeightTrait.
// See the UIFontWeight... constants in UIFontDescriptor.h for suggested values.
// The caveat above about the use of ...systemFont... methods applies to this method too.
+ (UIFont *)systemFontOfSize:(CGFloat)fontSize weight:(CGFloat)weight NS_AVAILABLE_IOS(8_2);

// Font attributes
@property(nonatomic,readonly,retain) NSString *familyName;
@property(nonatomic,readonly,retain) NSString *fontName;
@property(nonatomic,readonly)        CGFloat   pointSize;
@property(nonatomic,readonly)        CGFloat   ascender;
@property(nonatomic,readonly)        CGFloat   descender;
@property(nonatomic,readonly)        CGFloat   capHeight;
@property(nonatomic,readonly)        CGFloat   xHeight;
@property(nonatomic,readonly)        CGFloat   lineHeight NS_AVAILABLE_IOS(4_0);
@property(nonatomic,readonly)        CGFloat   leading;

// Create a new font that is identical to the current font except the specified size
- (UIFont *)fontWithSize:(CGFloat)fontSize;

// Returns a font matching the font descriptor. If fontSize is greater than 0.0, it has precedence over UIFontDescriptorSizeAttribute in fontDescriptor.
+ (UIFont *)fontWithDescriptor:(UIFontDescriptor *)descriptor size:(CGFloat)pointSize NS_AVAILABLE_IOS(7_0);

// Returns a font descriptor which describes the font.
- (UIFontDescriptor *)fontDescriptor NS_AVAILABLE_IOS(7_0);

@end


text:
<?php

namespace Osiset\ShopifyApp\Test\Traits;

use Osiset\ShopifyApp\Test\TestCase;
use Osiset\ShopifyApp\Traits\ShopAccessible;

class ShopAccessibleTest extends TestCase
{
    public function testSuccess(): void
    {
        $class = new TestShopAccessible();
        $class->setShop(
            factory($this->model)->create()
        );

        $this->assertTrue($class->hasShop());
    }
}

/**
 * Stub.
 */
class TestShopAccessible
{
    use ShopAccessible;

    public function hasShop(): bool
    {
        return $this->shop !== null;
    }
}


text:
package com.vladsch.MissingInActions.manager;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.vladsch.MissingInActions.util.CaretSnapshot;
import com.vladsch.MissingInActions.util.EditorCaretSnapshot;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import static com.intellij.openapi.diagnostic.Logger.getInstance;

/**
 * Represents a caret in the editor with line selection type and anchor position
 *

 * The stored selection is always in its character variant, when in line mode the original
 * anchored (leadOffset) is stored as offset.
 */
@SuppressWarnings("WeakerAccess")
public class EditorCaret implements EditorCaretSnapshot {
    private static final Logger logger = getInstance("com.vladsch.MissingInActions.manager");

    final private @NotNull EditorPositionFactory myFactory;
    final private @NotNull Caret myCaret;
    private @NotNull EditorPosition myCaretPosition;
    private @NotNull EditorPosition mySelectionStart;
    private @NotNull EditorPosition mySelectionEnd;
    private int myAnchorColumn;
    private boolean myIsStartAnchor;
    private boolean myIsLine;

    // *
    // * EditorCaretSnapshot
    // *

    /**
     * @return true if caret.getLeadSelectionOffset() == caret.getSelectionStart()
     */
    @Override
    public boolean isStartAnchor() { return myIsStartAnchor; }

    @Override
    @NotNull
    public EditorPosition getCaretPosition() { return myCaretPosition; }

    @Override
    public boolean isLine() { return myIsLine; }

    @Override
    public boolean hasSelection() {
        return mySelectionStart.line != mySelectionEnd.line
                || mySelectionStart.getOffset() != mySelectionEnd.getOffset();
    }

    @Override
    public boolean hasLines() {
        return getSelectionLineCount() > 0;
    }

    @Override
    @NotNull
    public EditorPosition getSelectionStart() {
        return mySelectionStart;
    }

    @Override
    @NotNull
    public EditorPosition getSelectionEnd() {
        return mySelectionEnd;
    }

    @Override
    public int getSelectionLineCount() {
        int lineCount = mySelectionEnd.line - mySelectionStart.line;

        if (!myIsLine && lineCount > 0 && hasSelection() && mySelectionEnd.column > 0) {
            lineCount++;
        }
        return lineCount;
    }

    @Override
    @NotNull
    public EditorPosition getLineSelectionStart() {
        return mySelectionStart.atStartOfLine();
    }

    @Override
    @NotNull
    public EditorPosition getLineSelectionEnd() {
        return mySelectionEnd.atEndOfLineSelection();
    }

    @Override
    @NotNull
    public EditorPosition getAnchorPosition() {
        return myIsStartAnchor ? mySelectionStart : mySelectionEnd;
    }

    @Override
    @NotNull
    public EditorPosition getAntiAnchorPosition() {
        return !myIsStartAnchor ? mySelectionStart : mySelectionEnd;
    }

    @Override
    public int getColumn() {
        return myCaretPosition.column;
    }

    @Override
    public int getIndent() {
        return myCaretPosition.getIndentColumn();
    }

    @NotNull
    public Caret getCaret() {
        return myCaret;
    }

    public boolean isValid() {
        return myCaret.isValid();
    }

    public boolean isPrimary() {
        return myCaret.isValid() && myCaret == myCaret.getEditor().getCaretModel().getPrimaryCaret();
    }

    /**
     * @param factory editor caret factory
     * @param caret   caret
     */
    EditorCaret(@NotNull EditorPositionFactory factory, @NotNull Caret caret, @NotNull LineSelectionState state) {
        myFactory = factory;
        myCaret = caret;

        // first, get caret's view of the world
        myCaretPosition = myFactory.fromPosition(myCaret.getLogicalPosition());
        mySelectionStart = myFactory.fromOffset(myCaret.getSelectionStart());
        mySelectionEnd = myFactory.fromOffset(myCaret.getSelectionEnd());

        // restore anchor offset
        boolean hasSelection = hasSelection();

        if (state.anchorColumn != -1 && hasSelection && mySelectionStart.line != mySelectionEnd.line) {
            myAnchorColumn = state.anchorColumn;
            myIsStartAnchor = state.isStartAnchor;
        } else {
            myIsStartAnchor = myCaret.getLeadSelectionOffset() == myCaret.getSelectionStart();
            myAnchorColumn = myCaretPosition.atOffset(caret.getLeadSelectionOffset()).column;
        }

        myIsLine = hasSelection && mySelectionStart.column == 0 && mySelectionEnd.column == 0;

        if (myCaretPosition.atStartOfLine().getOffset() + 1 == myCaretPosition.atStartOfNextLine().getOffset()) {
            if (!myIsLine) {
                if (myIsStartAnchor || !hasSelection) {
                    if (myCaretPosition.getOffset() == mySelectionEnd.getOffset()) {
                        if (myCaretPosition.column != mySelectionEnd.column) {
                            // on an empty line the selection end offset will always convert to 0 column regardless of the caret column
                            // this makes it look like the selection ends on previous line, when it ends on this one
                            // need to adjust the end to compensate for the blank line behavior
                            mySelectionEnd = myCaretPosition;
                        }
                    }
                } else {
                    if (mySelectionStart.line + 1 == mySelectionEnd.line && mySelectionEnd.atEndColumn().column == 0) {
                        // on an empty line the selection end offset will always convert to 0 column regardless of the caret column
                        // this makes it look like the selection ends on previous line, when it ends on this one
                        // need to adjust the end to compensate for the blank line behavior
                        mySelectionEnd = mySelectionEnd.atStartOfNextLine().atColumn(myAnchorColumn);
                    }
                }
            }
        }
    }

    private EditorCaret(@NotNull EditorCaret other) {
        myFactory = other.myFactory;
        myCaret = other.myCaret;
        myCaretPosition = other.myCaretPosition.copy();
        mySelectionStart = other.mySelectionStart.copy();
        mySelectionEnd = other.mySelectionEnd.copy();
        myAnchorColumn = other.myAnchorColumn;
        myIsStartAnchor = other.myIsStartAnchor;
        myIsLine = other.myIsLine;
    }

    public EditorCaret copy() {
        return new EditorCaret(this);
    }

    @NotNull
    public EditorCaret restoreColumn(int preservedColumn) {
        return restoreColumn(preservedColumn, -1);
    }

    @NotNull
    public EditorCaret restoreColumn(@Nullable CaretSnapshot snapshot) {
        return snapshot == null ? this : restoreColumn(snapshot.getColumn(), -1);
    }

    @NotNull
    public EditorCaret restoreColumn(@NotNull CaretSnapshot snapshot, boolean indentRelative) {
        return restoreColumn(snapshot.getColumn(), indentRelative ? snapshot.getIndent() : -1);
    }

    @NotNull
    public EditorCaret restoreColumn(int preservedColumn, int preservedIndent) {
        if (isUseSoftWraps()) return this;

        if (preservedColumn != -1) {
            if (preservedIndent != -1) {
                // restore indent relative
                if (hasSelection()) {
                    int indentColumn = getAntiAnchorSelectedLineCaretPosition().getIndentColumn();
                    myCaretPosition = myCaretPosition.atColumn(indentColumn + (preservedColumn - preservedIndent));
                } else {
                    int indentColumn = myCaretPosition.getIndentColumn();
                    myCaretPosition = myCaretPosition.atColumn(indentColumn + (preservedColumn - preservedIndent));
                }
            } else {
                myCaretPosition = myCaretPosition.atColumn(preservedColumn);
            }
        }
        return this;
    }

    @NotNull
    public EditorCaret resetAnchorState() {
        myAnchorColumn = -1;
        return this;
    }

    @NotNull
    public EditorCaret setAnchorColumn(@Nullable EditorPosition position) {
        return position == null ? this : setAnchorColumn(position.column);
    }

    @NotNull
    public EditorCaret setAnchorColumn(int column) {
        myAnchorColumn = column;
        return this;
    }

    @Override
    public int getAnchorColumn() {
        return myAnchorColumn;
    }

    @NotNull
    public EditorCaret setIsStartAnchorUpdateAnchorColumn(boolean isStartAnchor) {
        if (myIsStartAnchor != isStartAnchor) {
            if (myIsLine) {
                toCharSelection();
                normalizeCaretPosition();

                setAnchorColumn(getCaretPosition());
                setIsStartAnchor(isStartAnchor);
                normalizeCaretPosition();

                toLineSelection();
            } else {
                setAnchorColumn(getCaretPosition());
                setIsStartAnchor(isStartAnchor);
            }

            normalizeCaretPosition();
        }
        return this;
    }

    /**
     * Save the caret line selection information for later
     */
    public void commitState() {
        myFactory.getManager().setLineSelectionState(myCaret
                , myAnchorColumn
                , myIsStartAnchor
        );
    }

    /**
     * Apply caret information to actual caret and scroll to caret position
     */
    public void commit() {
        commit(true);
    }

    /**
     * Apply caret information to actual caret and scroll to caret position
     *

     * if selection is marked as line type then selection start and end will be extended to full lines and
     * caret position will be changed to its normalized caret position for selection extension
     * options.
     *
     * @param scrollToCaret if true then scroll to caret position of actual caret differs
     */
    @SuppressWarnings("SameParameterValue")
    public void commit(boolean scrollToCaret) {
        if (myCaret.isValid()) {
            myFactory.getManager().guard(() -> {
                // validate caret first
                if (myCaret.isValid()) {
                    if (!myCaretPosition.equals(myCaret.getLogicalPosition())) {
                        myCaret.moveToLogicalPosition(myCaretPosition);
                        if (scrollToCaret) scrollToCaret();
                    }

                    if (myIsLine && (mySelectionStart.column != 0 || mySelectionEnd.column != 0)) {
                        mySelectionStart = getLineSelectionStart();
                        mySelectionEnd = getLineSelectionEnd();
                        normalizeCaretPosition();
                    }

                    int startOffset = mySelectionStart.getOffset();
                    int endOffset = mySelectionEnd.getOffset();
                    if (startOffset != myCaret.getSelectionStart() || endOffset != myCaret.getSelectionEnd()) {
                        myCaret.setSelection(startOffset, endOffset);
                    }

                    commitState();
                }
            });
        }
    }

    /**
     * Scroll to caret position if it is the primary caret
     */
    public void scrollToCaret() {
        if (myCaret.isValid()) {
            Editor editor = myFactory.getEditor();
            if (myCaret == editor.getCaretModel().getPrimaryCaret()) {
                editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
            }
        }
    }

    /**
     * Remove selection from this caret and reset its state to not line type
     *
     * @return this
     */
    @Override
    @NotNull
    public EditorCaret removeSelection() {
        mySelectionStart = myCaretPosition;
        mySelectionEnd = myCaretPosition;
        myIsLine = false;
        myIsStartAnchor = true;
        return this;
    }

    /**
     * Convert to line selection if it is not one already and if it spans more than one line
     *
     * @return this
     */
    @NotNull
    public EditorCaret toLineSelectionIfHasLines() {
        if (!myIsLine && mySelectionStart.line != mySelectionEnd.line) {
            toLineSelection();
        }
        return this;
    }

    /**
     * This restores the original character selection from this line selection
     * can be obtained by extending it to full lines
     *
     * @return this
     */
    @NotNull
    public EditorCaret toCharSelection() {
        if (myIsLine) {
            mySelectionStart = getCharSelectionStart();
            mySelectionEnd = getCharSelectionEnd();
            myIsLine = false;
        }
        return this;
    }

    /**
     * inverse of getLineSelectionStart
     *
     * @return char selection start
     */
    @NotNull
    private EditorPosition getCharSelectionStart() {
        if (myIsLine) {
            if (!myIsStartAnchor) {
                return mySelectionStart.atColumn(myCaretPosition);
            } else {
                return mySelectionStart.atColumn(myAnchorColumn);
            }
        } else {
            return mySelectionStart;
        }
    }

    @NotNull
    private EditorPosition getCharSelectionEnd() {
        if (myIsLine) {
            if (myIsStartAnchor) {
                return myCaretPosition.column == 0 ? mySelectionEnd.atStartOfLine() : mySelectionEnd.addLine(-1).atColumn(myCaretPosition);
            } else {
                return myAnchorColumn == 0 ? mySelectionEnd.atStartOfLine() : mySelectionEnd.addLine(-1).atColumn(myAnchorColumn);
            }
        } else {
            return mySelectionEnd;
        }
    }

    /**
     * This converts the line selection to its equivalent char selection and looses
     * the character selection from which it was obtained
     *
     * @return this
     */
    @NotNull
    public EditorCaret toLineEquivalentCharSelection() {
        if (myIsLine) {
            mySelectionStart = getLineSelectionStart();
            mySelectionEnd = getLineSelectionEnd();
            myAnchorColumn = 0;
            myIsLine = false;
        }
        return this;
    }

    /**
     * Convert the current selection to line selection,
     * if it is not a line selection will extend start and end to result in a line selection.
     *
     * @return this
     */
    @NotNull
    public EditorCaret toLineSelection() {
        if (!myIsLine && hasSelection()) {
            expandToFullLines();
            myIsLine = true;
        }
        return this;
    }

    /**
     * Convert the current selection to line selection using selection extension rules
     * to expand/trim start/end based on isStartAnchor
     *
     * @return this
     */
    @NotNull
    public EditorCaret toCaretPositionBasedLineSelection() {
        return toCaretPositionBasedLineSelection(null, null);
    }

    @NotNull
    public EditorCaret toCaretPositionBasedLineSelection(@Nullable Boolean isSelectionStartExtended, @Nullable Boolean isSelectionEndExtended) {
        if (myIsStartAnchor) {
            // adjust end
            boolean isEndExtended = isSelectionEndExtended != null ? isSelectionEndExtended : myFactory.getManager().isSelectionEndExtended();
            if (!isEndExtended || myCaretPosition.column == 0) {
                mySelectionEnd = mySelectionEnd.atStartOfLine();
            } else {
                mySelectionEnd = mySelectionEnd.atEndOfLineSelection();
            }
        } else {
            // adjust start
            boolean isStartExtended = isSelectionStartExtended != null ? isSelectionStartExtended : myFactory.getManager().isSelectionStartExtended();
            if (!isStartExtended && myCaretPosition.column != 0) {
                mySelectionStart = mySelectionStart.atStartOfNextLine();
            } else {
                mySelectionStart = mySelectionStart.atStartOfLine();
            }
        }

        myIsLine = true;
        return this;
    }

    /**
     * This restores the character selection for use in line selection extending actions
     *
     * @return this
     */
    @NotNull
    public EditorCaret toCharSelectionForCaretPositionBasedLineSelection() {
        return toCharSelectionForCaretPositionBasedLineSelection(null, null);
    }

    @SuppressWarnings("SameParameterValue")
    @NotNull
    public EditorCaret toCharSelectionForCaretPositionBasedLineSelection(@Nullable Boolean isSelectionStartExtended, @Nullable Boolean isSelectionEndExtended) {
        if (myIsLine) {
            if (myIsStartAnchor) {
                boolean isEndExtended = isSelectionEndExtended != null ? isSelectionEndExtended : myFactory.getManager().isSelectionEndExtended();
                if (isEndExtended && myCaretPosition.column != 0) {
                    mySelectionEnd = mySelectionEnd.addLine(-1).atColumn(myCaretPosition);
                } else {
                    mySelectionEnd = mySelectionEnd.atColumn(myCaretPosition);
                }
                mySelectionStart = getCharSelectionStart();
            } else {
                boolean isStartExtended = isSelectionStartExtended != null ? isSelectionStartExtended : myFactory.getManager().isSelectionStartExtended();
                if (!isStartExtended && myCaretPosition.column != 0) {
                    mySelectionStart = mySelectionStart.atColumn(myCaretPosition).addLine(-1, EditorPosition::atStartOfLine);
                } else {
                    mySelectionStart = mySelectionStart.atColumn(myCaretPosition);
                }
                mySelectionEnd = getCharSelectionEnd();
            }

            if (mySelectionStart.line > mySelectionEnd.line || (mySelectionStart.line == mySelectionEnd.line && mySelectionStart.column > mySelectionEnd.column)) {
                EditorPosition pos = mySelectionStart;
                mySelectionStart = mySelectionEnd;
                mySelectionEnd = pos;
                myIsStartAnchor = !myIsStartAnchor;
                myAnchorColumn = getAnchorPosition().column;
            }
            myIsLine = false;
        }
        return this;
    }

    /**
     * Trim or expand to full lines before forcing to line selection
     *
     * @return this
     */
    @NotNull
    public EditorCaret trimOrExpandToLineSelection() {
        return trimOrExpandToFullLines().toLineSelection();
    }

    public boolean canSafelyTrimOrExpandToFullLineSelection() {
        if (!myIsLine && mySelectionStart.line != mySelectionEnd.line) {
            if (mySelectionStart.column != 0 || mySelectionEnd.column != 0) {
                EditorPosition selectionStart = mySelectionStart.toTrimmedOrExpandedFullLine();
                EditorPosition selectionEnd = mySelectionEnd.toTrimmedOrExpandedFullLine();
                return selectionStart.column == 0 && selectionEnd.column == 0;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * Trim or expand to full lines without changing selection type to line
     *
     * @return this
     */
    @NotNull
    public EditorCaret trimOrExpandToFullLines() {
        if ((mySelectionStart.column != 0 || mySelectionEnd.column != 0) && hasSelection()) {
            mySelectionStart = mySelectionStart.toTrimmedOrExpandedFullLine();
            mySelectionEnd = mySelectionEnd.toTrimmedOrExpandedFullLine();
        }
        return this;
    }

    @SuppressWarnings("UnusedReturnValue")
    @NotNull
    public EditorCaret expandToFullLines() {
        if (!myIsLine && hasSelection()) {
            mySelectionStart = getLineSelectionStart();
            mySelectionEnd = getLineSelectionEnd();
        }
        return this;
    }

    //*
    //*  Selection Start/End Expanded Handling
    //*

    /**
     * Set selection anchor to start/end of selection
     * underlying caret not changed until commit()
     *
     * @param isStartAnchor    true if startSelection to be the lead offset, false for endSelection to be lead offset
     */
    public EditorCaret setStartAnchor(boolean isStartAnchor) {
        if (hasSelection()) {
            if (getSelectionLineCount() > 1) {
                int column = getCaretPosition().column;

                setIsStartAnchorUpdateAnchorColumn(isStartAnchor);
                if (column != getCaretPosition().column) {
                    restoreColumn(column);
                }
            } else {
                if (!isStartAnchor && isStartAnchor()) {
                    setCaretPosition(getSelectionStart());
                } else if (!isStartAnchor()) {
                    setCaretPosition(getSelectionEnd());
                }

                setIsStartAnchor(isStartAnchor);
            }
        }
        return this;
    }

    /**
     * Set the caret position to reflect the current selection and selection extension options if it is a line selection
     *
     * @return this
     */
    @SuppressWarnings({ "SameParameterValue" })
    @NotNull
    public EditorCaret normalizeCaretPosition() {
        if (myIsLine) {
            if (myIsStartAnchor) {
                // caret on end of selection
                if (myFactory.getManager().isSelectionEndExtended()) {
                    myCaretPosition = myCaretPosition.column == 0 ? myCaretPosition.onLine(mySelectionEnd) : myCaretPosition.onLine(mySelectionEnd.line - 1);
                } else {
                    myCaretPosition = myCaretPosition.onLine(mySelectionEnd);
                }
            } else {
                // caret at top of selection
                if (myFactory.getManager().isSelectionStartExtended()) {
                    myCaretPosition = myCaretPosition.onLine(mySelectionStart);
                } else {
                    if (myCaretPosition.line == 0 && myCaretPosition.column != 0) {
                        myCaretPosition = myCaretPosition.atColumn(0);
                    } else {
                        myCaretPosition = myCaretPosition.column == 0 ? myCaretPosition.onLine(mySelectionStart) : myCaretPosition.onLine(mySelectionStart.line - 1);
                    }
                }
            }
        } else {
            myCaretPosition = !myIsStartAnchor ? mySelectionStart : mySelectionEnd;
        }
        return this;
    }

    /**
     * Get the position for the selected line given by the anti anchor position
     *
     * @return caret position with line adjusted to the selected anti anchor line, column is preserved
     */
    @NotNull
    public EditorPosition getAntiAnchorSelectedLineCaretPosition() {
        if (myIsStartAnchor) {
            // caret on end of selection
            if (myFactory.getManager().isSelectionEndExtended()) {
                return myCaretPosition.column == 0 ? mySelectionEnd.addLine(-1) : mySelectionEnd.atColumn(myCaretPosition);
            } else {
                return mySelectionEnd.addLine(-1).atColumn(myCaretPosition);
            }
        } else {
            // caret at top of selection
            return mySelectionStart.atColumn(myCaretPosition);
            //if (myFactory.getManager().isSelectionStartExtended()) {
            //} else {
            //    return myCaretPosition.column != 0 ? mySelectionStart.addLine(1).atColumn(myCaretPosition) : mySelectionStart.atColumn(myCaretPosition);
            //}
        }
    }

    //*
    //*  Selection/Anchor/AntiAnchor Related Functions
    //*

    @NotNull
    public EditorCaret setAnchorPosition(@Nullable EditorPosition other) {
        if (other != null) {
            if (myIsStartAnchor) {
                mySelectionStart = other;
            } else {
                mySelectionEnd = other;
            }
        }
        return this;
    }

    @NotNull
    public EditorCaret setAntiAnchorPosition(@Nullable EditorPosition other) {
        if (other != null) {
            if (myIsStartAnchor) {
                mySelectionEnd = other;
            } else {
                mySelectionStart = other;
            }
        }
        return this;
    }

    @NotNull
    public EditorCaret setSelectionStart(@Nullable EditorPosition position) {
        if (position != null) {
            mySelectionStart = position;
        }
        return this;
    }

    @NotNull
    public EditorCaret setSelectionEnd(@Nullable EditorPosition position) {
        if (position != null) {
            mySelectionEnd = position;
        }
        return this;
    }

    //*
    //*  Helper functions for getting/setting: line/column/offset
    //*

    @NotNull
    public EditorCaret setCaretPosition(int line, int column) {
        myCaretPosition = myCaretPosition.atPosition(line, column);
        return this;
    }

    @NotNull
    public EditorCaret setCaretPosition(int offset) {
        myCaretPosition = myCaretPosition.atOffset(offset);
        return this;
    }

    @NotNull
    public EditorCaret setCaretPosition(@Nullable EditorPosition position) {
        if (position != null) {
            myCaretPosition = position;
        }
        return this;
    }

    @NotNull
    public EditorCaret setSelectionStart(int line, int column) {
        mySelectionStart = myCaretPosition.atPosition(line, column);
        return this;
    }

    @NotNull
    public EditorCaret setSelectionStart(int offset) {
        mySelectionStart = myCaretPosition.atOffset(offset);
        return this;
    }

    @NotNull
    public EditorCaret setSelectionEnd(int line, int column) {
        mySelectionEnd = myCaretPosition.atPosition(line, column);
        return this;
    }

    @NotNull
    public EditorCaret setSelectionEnd(int offset) {
        mySelectionEnd = myCaretPosition.atOffset(offset);
        return this;
    }

    @NotNull
    public EditorCaret setSelection(int startOffset, int endOffset) {
        mySelectionStart = myCaretPosition.atOffset(startOffset);
        mySelectionEnd = myCaretPosition.atOffset(endOffset);
        return this;
    }

    @NotNull
    public EditorCaret setSelection(EditorPosition startOffset, EditorPosition endOffset) {
        mySelectionStart = startOffset;
        mySelectionEnd = endOffset;
        return this;
    }

    @NotNull
    public EditorCaret atColumn(@Nullable LogicalPosition other) {
        if (other != null) {
            myCaretPosition = myCaretPosition.atColumn(other.column);
        }
        return this;
    }

    @NotNull
    @SuppressWarnings("UnusedReturnValue")
    public EditorCaret atColumn(int other) {
        myCaretPosition = myCaretPosition.atColumn(other);
        return this;
    }

    @NotNull
    public EditorCaret onLine(@Nullable LogicalPosition other) {
        if (other != null) {
            myCaretPosition = myCaretPosition.onLine(other.line);
        }
        return this;
    }

    @NotNull
    public EditorCaret onLine(int other) {
        myCaretPosition = myCaretPosition.onLine(other);
        return this;
    }

    //*
    //*  Simple Getters/Setters
    //*

    @NotNull
    public EditorCaret setIsStartAnchor(boolean isStartAnchor) {
        myIsStartAnchor = isStartAnchor;
        return this;
    }

    public boolean isUseSoftWraps() {
        return myFactory.getEditor().getSettings().isUseSoftWraps();
    }

    @NotNull
    public EditorPositionFactory getFactory() { return myFactory; }

    @NotNull
    public LineSelectionManager getManager() { return myFactory.getManager(); }

    public int getDocumentTextLength() { return myFactory.getDocumentTextLength(); }

    public int getDocumentLineCount() { return myFactory.getDocumentLineCount(); }

    @NotNull
    public BasedSequence getDocumentChars() { return myFactory.getDocumentChars(); }

    @NotNull
    public Editor getEditor() { return myFactory.getEditor(); }

    @NotNull
    public Document getDocument() { return myFactory.getDocument(); }

    @NotNull
    public Project getProject() {
        Project project = getEditor().getProject();
        assert project != null;
        return project;
    }

    @NotNull
    public static EditorPosition adjustIndentRelative(EditorPosition position, int preservedColumn, int preservedIndent) {
        return adjustIndentRelative(position, position.getIndentColumn(), preservedColumn, preservedIndent);
    }

    public static EditorPosition adjustIndentRelative(EditorPosition position, int ourIndent, int preservedColumn, int preservedIndent) {
        return position.atColumn(ourIndent + (preservedColumn - preservedIndent));
    }

    public String toString() {
        return "EditorCaret{" +
                ", anchorPosition=" + myAnchorColumn +
                ", isLine=" + myIsLine +
                ", caretPosition=" + myCaretPosition +
                ", selectionStart=" + mySelectionStart +
                ", selectionEnd=" + mySelectionEnd +
                ", isStartAnchor=" + myIsStartAnchor +
                '}';
    }
}