text:
package br.com.autonomiccs.apacheCloudStack.client;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHeaderElement;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import br.com.autonomiccs.apacheCloudStack.client.beans.ApacheCloudStackUser;
import br.com.autonomiccs.apacheCloudStack.exceptions.ApacheCloudStackClientRequestRuntimeException;
import br.com.autonomiccs.apacheCloudStack.exceptions.ApacheCloudStackClientRuntimeException;

@RunWith(MockitoJUnitRunner.class)
public class ApacheCloudStackClientTest {

    private ApacheCloudStackClient apacheCloudStackClient;

    @Mock
    private ApacheCloudStackUser apacheCloudStackUser;

    private String cloudStackDomain = "cloud.domain.com";
    private String cloudStackUrl = "https://" + cloudStackDomain + "/client/api";

    @Before
    public void setup() {
        apacheCloudStackClient = Mockito.spy(new ApacheCloudStackClient(cloudStackUrl, apacheCloudStackUser));
    }

    @Test
    public void executeRequestTest() throws ClientProtocolException, IOException {
        configureMocksExecuteTestAndVerifyForMethodExecuteRequest(200);
    }

    @Test(expected = ApacheCloudStackClientRequestRuntimeException.class)
    public void executeRequestTestRequestStatusDifferentFromHttpStatusOk() throws ClientProtocolException, IOException {
        configureMocksExecuteTestAndVerifyForMethodExecuteRequest(500);
    }

    private void configureMocksExecuteTestAndVerifyForMethodExecuteRequest(int requestStatusCode) throws IOException, ClientProtocolException {
        Mockito.doReturn(cloudStackUrl).when(apacheCloudStackClient).createApacheCloudStackApiUrlRequest(Mockito.any(ApacheCloudStackRequest.class), Mockito.eq(true));

        CloseableHttpClient httpClientMock = Mockito.mock(CloseableHttpClient.class);
        HttpContext httpContextMock = Mockito.mock(HttpContext.class);
        CloseableHttpResponse closeableHttpResponseMock = Mockito.mock(CloseableHttpResponse.class);
        StatusLine statusLineMock = Mockito.mock(StatusLine.class);

        Mockito.when(statusLineMock.getStatusCode()).thenReturn(requestStatusCode);
        Mockito.when(closeableHttpResponseMock.getStatusLine()).thenReturn(statusLineMock);
        Mockito.when(httpClientMock.execute(Mockito.any(HttpGet.class), Mockito.eq(httpContextMock))).thenReturn(closeableHttpResponseMock);
        Mockito.when(apacheCloudStackClient.createHttpClient()).thenReturn(httpClientMock);
        Mockito.when(apacheCloudStackClient.apacheCloudStackUser.getApiKey()).thenReturn("apiKey");
        Mockito.doReturn(httpContextMock).when(apacheCloudStackClient).createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeeded(Mockito.eq(httpClientMock),
                Mockito.eq(true));
        String responseString = "responseAsString";
        Mockito.doReturn(responseString).when(apacheCloudStackClient).getResponseAsString(Mockito.eq(closeableHttpResponseMock));

        String returnOfExecuteRequest = apacheCloudStackClient.executeRequest(Mockito.mock(ApacheCloudStackRequest.class));
        Assert.assertEquals(responseString, returnOfExecuteRequest);

        InOrder inOrder = Mockito.inOrder(apacheCloudStackClient, httpClientMock, closeableHttpResponseMock, statusLineMock);
        inOrder.verify(apacheCloudStackClient).createApacheCloudStackApiUrlRequest(Mockito.any(ApacheCloudStackRequest.class), Mockito.eq(true));
        inOrder.verify(apacheCloudStackClient).createHttpClient();
        inOrder.verify(httpClientMock).execute(Mockito.any(HttpGet.class), Mockito.eq(httpContextMock));
        inOrder.verify(closeableHttpResponseMock).getStatusLine();
        inOrder.verify(statusLineMock).getStatusCode();
        inOrder.verify(httpClientMock).close();
    }

    @Test(expected = ApacheCloudStackClientRuntimeException.class)
    public void executeRequestTestExceptionWhenExecutingRequest() throws IOException, ClientProtocolException {
        Mockito.doReturn(cloudStackUrl).when(apacheCloudStackClient).createApacheCloudStackApiUrlRequest(Mockito.any(ApacheCloudStackRequest.class), Mockito.eq(true));

        CloseableHttpClient httpClientMock = Mockito.mock(CloseableHttpClient.class);

        Mockito.when(httpClientMock.execute(Mockito.any(HttpGet.class))).thenThrow(new IOException());
        Mockito.when(apacheCloudStackClient.createHttpClient()).thenReturn(httpClientMock);

        apacheCloudStackClient.executeRequest(Mockito.mock(ApacheCloudStackRequest.class));
        Mockito.verify(httpClientMock).close();
    }

    private void testRequestConfig(final RequestConfig config, final int timeout) {
        Assert.assertEquals(config.getConnectTimeout(), timeout * (int)DateUtils.MILLIS_PER_SECOND);
        Assert.assertEquals(config.getConnectionRequestTimeout(), timeout * (int)DateUtils.MILLIS_PER_SECOND);
        Assert.assertEquals(config.getSocketTimeout(), timeout * (int)DateUtils.MILLIS_PER_SECOND);
    }

    @Test
    public void createRequestConfigDefaultTest() {
        RequestConfig config = apacheCloudStackClient.createRequestConfig();
        testRequestConfig(config, 60);
    }

    @Test
    public void createRequestConfigCustomValueTest() {
        int timeout = 30;
        apacheCloudStackClient.setConnectionTimeout(timeout);
        RequestConfig config = apacheCloudStackClient.createRequestConfig();
        testRequestConfig(config, timeout);
    }

    @Test
    public void createHttpClientTestValidateServerHttpsCertificateTrueAndTotalInsecureFalse() {
        configureExecuteAndVerifyTestForCreateHttpClient(true, 0, false, 0);
    }

    @Test
    public void createHttpClientTestValidateServerHttpsCertificateTrueAndTotalInsecureTrue() {
        configureExecuteAndVerifyTestForCreateHttpClient(true, 0, true, 0);
    }

    @Test
    public void createHttpClientTestValidateServerHttpsCertificateFalseAndTotalInsecureFalse() {
        configureExecuteAndVerifyTestForCreateHttpClient(false, 1, false, 0);
    }

    @Test
    public void createHttpClientTestValidateServerHttpsCertificateFalseAndTotalInsecureTrue() {
        configureExecuteAndVerifyTestForCreateHttpClient(false, 1, true, 1);
    }

    private void configureExecuteAndVerifyTestForCreateHttpClient(boolean shouldVerifyServerCertificates, int numberOfCreateUnsecureSslFactoryCalls, boolean totalInsecure,
            int expectedCallForInsecureHostNameCheck) {
        apacheCloudStackClient.validateServerHttpsCertificate = shouldVerifyServerCertificates;
        apacheCloudStackClient.acceptAllKindsOfCertificates = totalInsecure;

        CloseableHttpClient httpClient = apacheCloudStackClient.createHttpClient();

        Assert.assertNotNull(httpClient);
        Mockito.verify(apacheCloudStackClient, Mockito.times(1)).createRequestConfig();
        Mockito.verify(apacheCloudStackClient, Mockito.times(expectedCallForInsecureHostNameCheck)).createInsecureHostNameVerifier();
        Mockito.verify(apacheCloudStackClient, Mockito.times(numberOfCreateUnsecureSslFactoryCalls)).createInsecureSslFactory();
    }

    @Test
    public void getResponseAsStringTest() throws UnsupportedOperationException, IOException {
        String responseTest = "teste response";

        CloseableHttpResponse closeableHttpResponseMock = Mockito.mock(CloseableHttpResponse.class);
        HttpEntity httpEntityMock = Mockito.mock(HttpEntity.class);

        InputStream is = new ByteArrayInputStream(responseTest.getBytes());

        Mockito.doReturn(is).when(httpEntityMock).getContent();
        Mockito.doReturn(httpEntityMock).when(closeableHttpResponseMock).getEntity();

        String responseAsString = apacheCloudStackClient.getResponseAsString(closeableHttpResponseMock);

        Assert.assertEquals(responseTest, responseAsString);
    }

    @Test
    public void createApacheCloudStackApiUrlRequestTestWithSignature() {
        ApacheCloudStackRequest apacheCloudStackRequestMock = Mockito.mock(ApacheCloudStackRequest.class);

        String queryString = "queryString";
        Mockito.doReturn(queryString).when(apacheCloudStackClient).createCommandString(Mockito.eq(apacheCloudStackRequestMock));

        String signatureValue = "signatureValue";
        Mockito.doReturn(signatureValue).when(apacheCloudStackClient).createSignature(Mockito.eq(queryString));

        String urlRequestReturned = apacheCloudStackClient.createApacheCloudStackApiUrlRequest(apacheCloudStackRequestMock, true);
        Assert.assertEquals(cloudStackUrl + "?" + queryString + "&signature=" + signatureValue, urlRequestReturned);

        InOrder inOrder = Mockito.inOrder(apacheCloudStackClient);
        inOrder.verify(apacheCloudStackClient).createCommandString(Mockito.eq(apacheCloudStackRequestMock));
        inOrder.verify(apacheCloudStackClient).createSignature(Mockito.eq(queryString));
        inOrder.verify(apacheCloudStackClient).getUrlEncodedValue(Mockito.eq(signatureValue));
    }

    @Test
    public void createApacheCloudStackApiUrlRequestTestWithoutSignature() {
        ApacheCloudStackRequest apacheCloudStackRequestMock = Mockito.mock(ApacheCloudStackRequest.class);

        String queryString = "queryString";
        Mockito.doReturn(queryString).when(apacheCloudStackClient).createCommandString(Mockito.eq(apacheCloudStackRequestMock));

        String urlRequestReturned = apacheCloudStackClient.createApacheCloudStackApiUrlRequest(apacheCloudStackRequestMock, false);
        Assert.assertEquals(cloudStackUrl + "?" + queryString, urlRequestReturned);

        InOrder inOrder = Mockito.inOrder(apacheCloudStackClient);
        inOrder.verify(apacheCloudStackClient).createCommandString(Mockito.eq(apacheCloudStackRequestMock));
        inOrder.verify(apacheCloudStackClient, Mockito.times(0)).createSignature(Mockito.eq(queryString));
        inOrder.verify(apacheCloudStackClient, Mockito.times(0)).getUrlEncodedValue(Mockito.anyString());
    }

    @Test
    public void createSignatureTest() {
        String expectedSignature = "wqtSA/cANcWnWlh/ukfnaExyM54=";
        Mockito.doReturn("secretKey").when(apacheCloudStackUser).getSecretKey();

        String signature = apacheCloudStackClient.createSignature("queryString");

        Assert.assertEquals(expectedSignature, signature);
    }

    @Test
    public void createCommandStringTest() {
        List<ApacheCloudStackApiCommandParameter> params = new ArrayList<>();
        String valueParam1 = "value1";
        String valueParam2 = "value2 espaço";
        params.add(new ApacheCloudStackApiCommandParameter("param1", valueParam1));
        params.add(new ApacheCloudStackApiCommandParameter("param2", valueParam2));

        String expectedCommandSrting = "param1=value1&param2=value2 espaço";

        ApacheCloudStackRequest ApacheCloudStackRequestMock = Mockito.mock(ApacheCloudStackRequest.class);
        Mockito.doReturn(params).when(apacheCloudStackClient).createSortedCommandQueryList(Mockito.eq(ApacheCloudStackRequestMock));
        Mockito.doReturn(valueParam1).when(apacheCloudStackClient).getUrlEncodedValue(Mockito.eq(valueParam1));
        Mockito.doReturn(valueParam2).when(apacheCloudStackClient).getUrlEncodedValue(Mockito.eq(valueParam2));

        String commandStringReturned = apacheCloudStackClient.createCommandString(ApacheCloudStackRequestMock);
        Assert.assertEquals(expectedCommandSrting, commandStringReturned);

        InOrder inOrder = Mockito.inOrder(apacheCloudStackClient);
        inOrder.verify(apacheCloudStackClient).createSortedCommandQueryList(Mockito.eq(ApacheCloudStackRequestMock));
        inOrder.verify(apacheCloudStackClient).getUrlEncodedValue(Mockito.eq(valueParam1));
        inOrder.verify(apacheCloudStackClient).getUrlEncodedValue(Mockito.eq(valueParam2));

    }

    @Test
    public void getUrlEncodedValueTestNullValue() {
        String urlEncodedValueReturned = apacheCloudStackClient.getUrlEncodedValue(null);
        Assert.assertEquals("null", urlEncodedValueReturned);
    }

    @Test
    public void getUrlEncodedValueTestNonSpecialCharactersValue() {
        String urlEncodedValueReturned = apacheCloudStackClient.getUrlEncodedValue("test");
        Assert.assertEquals("test", urlEncodedValueReturned);
    }

    @Test
    public void getUrlEncodedValueTestValueWithSpaces() {
        String urlEncodedValueReturned = apacheCloudStackClient.getUrlEncodedValue("test value");
        Assert.assertEquals("test%20value", urlEncodedValueReturned);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void createSortedCommandQueryListTestWithApiKey() {
        ApacheCloudStackRequest apacheCloudStackRequestMock = Mockito.mock(ApacheCloudStackRequest.class);
        Set<ApacheCloudStackApiCommandParameter> params = new HashSet<>();

        params.add(new ApacheCloudStackApiCommandParameter("param1", "value1"));
        Mockito.doReturn(params).when(apacheCloudStackRequestMock).getParameters();
        Mockito.when(apacheCloudStackClient.apacheCloudStackUser.getApiKey()).thenReturn("apiKey");
        Mockito.doNothing().when(apacheCloudStackClient).configureRequestExpiration(Mockito.anyList());

        List<ApacheCloudStackApiCommandParameter> sortedCommandQueryList = apacheCloudStackClient.createSortedCommandQueryList(apacheCloudStackRequestMock);

        Mockito.verify(apacheCloudStackRequestMock).getParameters();
        Mockito.verify(apacheCloudStackClient).configureRequestExpiration(Mockito.anyList());

        Assert.assertEquals(3, sortedCommandQueryList.size());
        Assert.assertEquals("apiKey", sortedCommandQueryList.get(0).getName());
        Assert.assertEquals("command", sortedCommandQueryList.get(1).getName());
        Assert.assertEquals("param1", sortedCommandQueryList.get(2).getName());
    }

    @Test
    @SuppressWarnings("unchecked")
    public void createSortedCommandQueryListTestWithourApiKey() {
        ApacheCloudStackRequest apacheCloudStackRequestMock = Mockito.mock(ApacheCloudStackRequest.class);
        Set<ApacheCloudStackApiCommandParameter> params = new HashSet<>();

        params.add(new ApacheCloudStackApiCommandParameter("param1", "value1"));
        Mockito.doReturn(params).when(apacheCloudStackRequestMock).getParameters();
        Mockito.when(apacheCloudStackClient.apacheCloudStackUser.getApiKey()).thenReturn(null);
        Mockito.doNothing().when(apacheCloudStackClient).configureRequestExpiration(Mockito.anyList());

        List<ApacheCloudStackApiCommandParameter> sortedCommandQueryList = apacheCloudStackClient.createSortedCommandQueryList(apacheCloudStackRequestMock);

        Mockito.verify(apacheCloudStackRequestMock).getParameters();
        Mockito.verify(apacheCloudStackClient).configureRequestExpiration(Mockito.anyList());

        Assert.assertEquals(2, sortedCommandQueryList.size());
        Assert.assertEquals("command", sortedCommandQueryList.get(0).getName());
        Assert.assertEquals("param1", sortedCommandQueryList.get(1).getName());
    }

    @Test
    public void executeRequestAutoConvertReturnToJavaObject() {
        String jsonTest = "{attr1: 1, attr2: 'test'}";

        ApacheCloudStackRequest apacheCloudStackRequestMock = Mockito.mock(ApacheCloudStackRequest.class);
        Mockito.doReturn(jsonTest).when(apacheCloudStackClient).executeRequest(Mockito.eq(apacheCloudStackRequestMock));

        TestExecuteReturnObject returnedObject = apacheCloudStackClient.executeRequest(apacheCloudStackRequestMock, TestExecuteReturnObject.class);

        Mockito.verify(apacheCloudStackClient).executeRequest(Mockito.eq(apacheCloudStackRequestMock));

        Assert.assertNotNull(returnedObject);
        Assert.assertTrue(returnedObject instanceof TestExecuteReturnObject);

        Assert.assertEquals(1, returnedObject.attr1);
        Assert.assertEquals("test", returnedObject.attr2);

    }

    private class TestExecuteReturnObject {
        private int attr1;
        private String attr2;
    }

    @Test
    public void createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeededTestAuthenticationWithApiKeyAndSecretKey() {
        CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class);
        HttpContext basicHttpContext = apacheCloudStackClient.createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeeded(closeableHttpClientMock, true);

        Mockito.verify(apacheCloudStackClient, Mockito.times(0)).createHttpContextWithAuthenticatedSessionUsingUserCredentials(Mockito.any(closeableHttpClientMock.getClass()));
        Assert.assertNotNull(basicHttpContext);
    }

    @Test
    public void createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeededTestAuthenticationWithUsernameAndPassword() {
        CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class);
        HttpContext httpContextMock = Mockito.mock(HttpContext.class);
        Mockito.doReturn(httpContextMock).when(apacheCloudStackClient)
        .createHttpContextWithAuthenticatedSessionUsingUserCredentials(Mockito.any(closeableHttpClientMock.getClass()));
        HttpContext basicHttpContext = apacheCloudStackClient.createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeeded(closeableHttpClientMock, false);

        Mockito.verify(apacheCloudStackClient, Mockito.times(1)).createHttpContextWithAuthenticatedSessionUsingUserCredentials(Mockito.eq(closeableHttpClientMock));

        Assert.assertNotNull(basicHttpContext);
        Assert.assertEquals(httpContextMock, basicHttpContext);
    }

    @Test
    public void createHttpContextWithAuthenticatedSessionUsingUserCredentialsTest() throws ClientProtocolException, IOException {
        HttpPost httpPostMock = Mockito.mock(HttpPost.class);
        Mockito.doReturn(httpPostMock).when(apacheCloudStackClient).createHttpPost();

        NameValuePair nameValuePairMock = Mockito.mock(NameValuePair.class);
        ArrayList<NameValuePair> paramsMock = new ArrayList<>(1);
        paramsMock.add(nameValuePairMock);

        Mockito.doReturn(paramsMock).when(apacheCloudStackClient).getParametersForLogin();

        StatusLine statusLineMock = Mockito.mock(StatusLine.class);
        CloseableHttpResponse closeableHttpResponseMock = Mockito.mock(CloseableHttpResponse.class);
        CloseableHttpClient httpClientMock = Mockito.mock(CloseableHttpClient.class);

        Mockito.doReturn(200).when(statusLineMock).getStatusCode();
        Mockito.doReturn(statusLineMock).when(closeableHttpResponseMock).getStatusLine();
        Mockito.doReturn(closeableHttpResponseMock).when(httpClientMock).execute(Mockito.eq(httpPostMock));

        HttpContext httpContextMock = Mockito.mock(HttpContext.class);
        Mockito.doReturn(httpContextMock).when(apacheCloudStackClient).createHttpContextWithCookies(Mockito.eq(closeableHttpResponseMock));
        Mockito.doReturn("responseAsString").when(apacheCloudStackClient).getResponseAsString(Mockito.eq(closeableHttpResponseMock));

        HttpContext httpContextAuthenticatedWithUsernamePassword = apacheCloudStackClient.createHttpContextWithAuthenticatedSessionUsingUserCredentials(httpClientMock);

        Assert.assertEquals(httpContextMock, httpContextAuthenticatedWithUsernamePassword);

        InOrder inOrder = Mockito.inOrder(httpPostMock, apacheCloudStackClient, statusLineMock, closeableHttpResponseMock, httpClientMock);
        inOrder.verify(apacheCloudStackClient).createHttpPost();
        inOrder.verify(apacheCloudStackClient).getParametersForLogin();
        inOrder.verify(httpPostMock).setEntity(Mockito.any(UrlEncodedFormEntity.class));
        inOrder.verify(httpClientMock).execute(Mockito.eq(httpPostMock));
        inOrder.verify(closeableHttpResponseMock).getStatusLine();
        inOrder.verify(statusLineMock).getStatusCode();
        inOrder.verify(apacheCloudStackClient).getResponseAsString(Mockito.eq(closeableHttpResponseMock));
        inOrder.verify(apacheCloudStackClient).createHttpContextWithCookies(Mockito.eq(closeableHttpResponseMock));
    }

    @Test(expected = ApacheCloudStackClientRuntimeException.class)
    public void createHttpContextWithAuthenticatedSessionUsingUserCredentialsTestExceptionExecutingRequest() throws ClientProtocolException, IOException {
        HttpPost httpPostMock = Mockito.mock(HttpPost.class);
        Mockito.doReturn(httpPostMock).when(apacheCloudStackClient).createHttpPost();

        NameValuePair nameValuePairMock = Mockito.mock(NameValuePair.class);
        ArrayList<NameValuePair> paramsMock = new ArrayList<>(1);
        paramsMock.add(nameValuePairMock);

        Mockito.doReturn(paramsMock).when(apacheCloudStackClient).getParametersForLogin();

        CloseableHttpClient httpClientMock = Mockito.mock(CloseableHttpClient.class);

        Mockito.doThrow(IOException.class).when(httpClientMock).execute(Mockito.eq(httpPostMock));

        apacheCloudStackClient.createHttpContextWithAuthenticatedSessionUsingUserCredentials(httpClientMock);
    }

    @Test
    public void createHttpContextWithCookiesTest() {
        CloseableHttpResponse closeableHttpResponseMock = Mockito.mock(CloseableHttpResponse.class);

        Header[] headers = new Header[1];
        Mockito.doReturn(headers).when(closeableHttpResponseMock).getAllHeaders();

        Mockito.doNothing().when(apacheCloudStackClient).createAndAddCookiesOnStoreForHeaders(Mockito.any(BasicCookieStore.class), Mockito.eq(headers));
        HttpContext httpContextWithCookies = apacheCloudStackClient.createHttpContextWithCookies(closeableHttpResponseMock);

        Assert.assertNotNull(httpContextWithCookies);
        Assert.assertNotNull(httpContextWithCookies.getAttribute(HttpClientContext.COOKIE_STORE));

        Mockito.verify(apacheCloudStackClient).createAndAddCookiesOnStoreForHeaders(Mockito.any(BasicCookieStore.class), Mockito.eq(headers));

    }

    @Test
    public void createAndAddCookiesOnStoreForHeadersTest() {
        Header[] headers = new Header[2];
        headers[0] = new BasicHeader("Set-Cookie cookieName", "value1");
        headers[1] = new BasicHeader("anyOtherCookie", "value2");

        CookieStore cookieStoreMock = Mockito.mock(CookieStore.class);

        Mockito.doNothing().when(apacheCloudStackClient).createAndAddCookiesOnStoreForHeader(Mockito.eq(cookieStoreMock), Mockito.any(Header.class));
        apacheCloudStackClient.createAndAddCookiesOnStoreForHeaders(cookieStoreMock, headers);

        Mockito.verify(apacheCloudStackClient).createAndAddCookiesOnStoreForHeader(Mockito.eq(cookieStoreMock), Mockito.eq(headers[0]));
    }

    public void createAndAddCookiesOnStoreForHeaderTest() {
        CookieStore cookieStoreMock = Mockito.mock(CookieStore.class);
        Header headerMock = Mockito.mock(Header.class);

        HeaderElement headerElementMock1 = Mockito.mock(HeaderElement.class);

        List<HeaderElement> headerElements = new ArrayList<>(1);
        headerElements.add(headerElementMock1);

        Mockito.doReturn(headerElements).when(headerMock).getElements();

        Cookie cookieMock = Mockito.mock(Cookie.class);
        Mockito.doReturn(cookieMock).when(apacheCloudStackClient).createCookieForHeaderElement(Mockito.eq(headerElementMock1));

        apacheCloudStackClient.createAndAddCookiesOnStoreForHeader(cookieStoreMock, headerMock);

        Mockito.verify(headerMock).getElements();
        Mockito.verify(apacheCloudStackClient).createCookieForHeaderElement(Mockito.eq(headerElementMock1));
    }

    @Test
    public void createCookieForHeaderElementTest() {
        String cookiePath = "/client/api";

        String paramName = "paramName1";
        String paramValue = "paramVale1";
        NameValuePair[] parameters = new NameValuePair[1];
        parameters[0] = new BasicNameValuePair(paramName, paramValue);

        String headerName = "headerElementName";
        String headerValue = "headerElementValue";
        HeaderElement headerElement = new BasicHeaderElement(headerName, headerValue, parameters);

        Mockito.doNothing().when(apacheCloudStackClient).configureDomainForCookie(Mockito.any(BasicClientCookie.class));

        BasicClientCookie cookieForHeaderElement = apacheCloudStackClient.createCookieForHeaderElement(headerElement);

        Assert.assertNotNull(cookieForHeaderElement);
        Assert.assertEquals(headerName, cookieForHeaderElement.getName());
        Assert.assertEquals(headerValue, cookieForHeaderElement.getValue());
        Assert.assertEquals(paramValue, cookieForHeaderElement.getAttribute(paramName));
        Assert.assertEquals(cookiePath, cookieForHeaderElement.getPath());

        Mockito.verify(apacheCloudStackClient).configureDomainForCookie(Mockito.eq(cookieForHeaderElement));
    }

    @Test
    public void configureDomainForCookieTest() {
        BasicClientCookie basicClientCookie = new BasicClientCookie("name", "value");
        apacheCloudStackClient.configureDomainForCookie(basicClientCookie);

        Assert.assertEquals(cloudStackDomain, basicClientCookie.getDomain());
    }

    @Test
    public void createHttpPostTest() throws MalformedURLException {
        HttpPost httpPost = apacheCloudStackClient.createHttpPost();

        Assert.assertEquals(cloudStackUrl, httpPost.getURI().toURL().toString());
        Assert.assertEquals("application/x-www-form-urlencoded", httpPost.getFirstHeader("Content-Type").getValue());
    }

    public void getParametersForLoginTest() {
        Mockito.doReturn("userName").when(apacheCloudStackUser).getUsername();
        Mockito.doReturn("password").when(apacheCloudStackUser).getPassword();
        Mockito.doReturn("domain").when(apacheCloudStackUser).getDomain();

        List<NameValuePair> parametersForLogin = apacheCloudStackClient.getParametersForLogin();

        Assert.assertNotNull(parametersForLogin);
        Assert.assertEquals(4, parametersForLogin.size());

        Assert.assertEquals("command", parametersForLogin.get(0).getValue());
        Assert.assertEquals("login", parametersForLogin.get(0).getName());

        Assert.assertEquals("username", parametersForLogin.get(1).getValue());
        Assert.assertEquals("userName", parametersForLogin.get(1).getName());

        Assert.assertEquals("password", parametersForLogin.get(2).getValue());
        Assert.assertEquals("password", parametersForLogin.get(2).getName());

        Assert.assertEquals("domain", parametersForLogin.get(3).getValue());
        Assert.assertEquals("domain", parametersForLogin.get(3).getName());
    }

    @Test
    public void executeUserLogoutTest() {
        String urlRequest = "urlRequest";

        Mockito.doReturn(urlRequest).when(apacheCloudStackClient).createApacheCloudStackApiUrlRequest(Mockito.any(ApacheCloudStackRequest.class), Mockito.eq(false));
        Mockito.doReturn("response").when(apacheCloudStackClient).executeRequestGetResponseAsString(Mockito.eq(urlRequest), Mockito.any(CloseableHttpClient.class),
                Mockito.any(HttpContext.class));

        apacheCloudStackClient.executeUserLogout(Mockito.mock(CloseableHttpClient.class), Mockito.mock(HttpContext.class));

        InOrder inOrder = Mockito.inOrder(apacheCloudStackClient);
        inOrder.verify(apacheCloudStackClient).createApacheCloudStackApiUrlRequest(Mockito.any(ApacheCloudStackRequest.class), Mockito.eq(false));
        inOrder.verify(apacheCloudStackClient).executeRequestGetResponseAsString(Mockito.eq(urlRequest), Mockito.any(CloseableHttpClient.class), Mockito.any(HttpContext.class));
    }

    @Test
    public void configureRequestExpirationTestRequestsShouldNotExpire() {
        apacheCloudStackClient.setShouldRequestsExpire(false);

        ArrayList<ApacheCloudStackApiCommandParameter> arrayList = new ArrayList<>();
        apacheCloudStackClient.configureRequestExpiration(arrayList);

        Assert.assertEquals(0, arrayList.size());
    }

    @Test
    public void configureRequestExpirationTestRequestsShouldNotExpireUsingOverride() {
        apacheCloudStackClient.setShouldRequestsExpire(false);

        ArrayList<ApacheCloudStackApiCommandParameter> arrayList = new ArrayList<>();
        arrayList.add(new ApacheCloudStackApiCommandParameter("expires", "2011-10-10T12:00:00+0530"));

        apacheCloudStackClient.configureRequestExpiration(arrayList);

        Assert.assertEquals(2, arrayList.size());
        Mockito.verify(apacheCloudStackClient, Mockito.never()).createExpirationDate();
    }

    @Test
    public void configureRequestExpirationTestRequestsShouldExpireUsingOverride() {
        apacheCloudStackClient.setShouldRequestsExpire(true);

        ArrayList<ApacheCloudStackApiCommandParameter> arrayList = new ArrayList<>();
        ApacheCloudStackApiCommandParameter expirationParameter = new ApacheCloudStackApiCommandParameter("expires", "2011-10-10T12:00:00+0530");
        arrayList.add(expirationParameter);

        apacheCloudStackClient.configureRequestExpiration(arrayList);

        Assert.assertEquals(2, arrayList.size());
        Assert.assertEquals(expirationParameter, arrayList.get(0));
        Mockito.verify(apacheCloudStackClient, Mockito.never()).createExpirationDate();
    }

    @Test
    public void configureRequestExpirationTestRequestsShouldExpireWithoutOverride() {
        apacheCloudStackClient.setShouldRequestsExpire(true);

        ArrayList<ApacheCloudStackApiCommandParameter> arrayList = new ArrayList<>();

        String expirationDate = "2011-10-10T12:00:00+0530";
        Mockito.doReturn(expirationDate).when(apacheCloudStackClient).createExpirationDate();

        apacheCloudStackClient.configureRequestExpiration(arrayList);

        Assert.assertEquals(2, arrayList.size());
        Assert.assertEquals("signatureVersion", arrayList.get(0).getName());
        Assert.assertEquals(3, arrayList.get(0).getValue());
        Assert.assertEquals("expires", arrayList.get(1).getName());
        Assert.assertEquals(expirationDate, arrayList.get(1).getValue());

        Mockito.verify(apacheCloudStackClient).createExpirationDate();
    }

    @Test
    public void createExpirationDateTest() {
        Calendar someMomentInTimeSpace = Calendar.getInstance();
        someMomentInTimeSpace.set(1999, 12, 31, 23, 59, 59);
        someMomentInTimeSpace.set(Calendar.MILLISECOND, 0);
        Mockito.doReturn(someMomentInTimeSpace.getTime()).when(apacheCloudStackClient).getExpirationDate();

        String expirationDate = apacheCloudStackClient.createExpirationDate();

        String expectedExpirationDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(someMomentInTimeSpace.getTime());
        Assert.assertEquals(expectedExpirationDate, expirationDate);

        Mockito.verify(apacheCloudStackClient).getExpirationDate();
    }

    @Test
    public void createInsecureHostNameVerifierTest() {
        HostnameVerifier hostNameVerifier = apacheCloudStackClient.createInsecureHostNameVerifier();

        Assert.assertTrue(hostNameVerifier.verify("...", null));
        Assert.assertTrue(hostNameVerifier.verify("Any other thing", null));

    }

    @Test
    public void toStringTest() {
        String toStringValue = apacheCloudStackClient.toString();

        String expectedToStringValue = "Apache CloudSTackClient for site[https://cloud.domain.com/client/api], parameters: [connectionTimeout=60, acceptAllKindsOfCertificates=false, validateServerHttpsCertificate=true, requestValidity=30, shouldRequestsExpire=true]";
        Assert.assertEquals(expectedToStringValue, toStringValue);
    }
}


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

import javax.annotation.Generated;

/**
 * <p/>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidParameterGroupStateException extends com.amazonaws.services.memorydb.model.AmazonMemoryDBException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InvalidParameterGroupStateException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InvalidParameterGroupStateException(String message) {
        super(message);
    }

}

redpajama_set_name: RedPajamaGithub


text:
define(["require", "exports", "./RGBA"], function (require, exports, RGBA_1) {
    var StageOption = (function () {
        function StageOption(option) {
            this.autoResize = false;
            this.pixelRatio = 1;
            this.autoClear = true;
            this.autoClearColor = new RGBA_1.default();
            for (var name in option) {
                if (this.hasOwnProperty(name)) {
                    var value;
                    switch (name) {
                        case 'pixelRatio': {
                            value = option[name] | 0;
                            break;
                        }
                        default: {
                            value = option[name];
                            break;
                        }
                    }
                    this[name] = value;
                }
            }
        }
        return StageOption;
    })();
    exports.StageOption = StageOption;
});


text:
INSTALL_ARGS := $(if $(PREFIX),--prefix $(PREFIX),)
BIN := ./_build/default/bin/main.exe

-include Makefile.dev

default: boot.exe
	./boot.exe --dev

release: boot.exe
	./boot.exe

boot.exe: bootstrap.ml
	ocaml bootstrap.ml

install:
	$(BIN) install $(INSTALL_ARGS)

uninstall:
	$(BIN) uninstall $(INSTALL_ARGS)

reinstall: uninstall reinstall

test:
	$(BIN) runtest --dev

test-js:
	$(BIN) build @runtest-js --dev

test-all:
	$(BIN) build @runtest @runtest-js --dev

promote:
	$(BIN) promote

accept-corrections: promote

all-supported-ocaml-versions:
	$(BIN) build --dev @install @runtest --workspace jbuild-workspace.dev --root .

clean:
	$(BIN) clean
	rm -f ./boot.exe $(wildcard ./bootstrap.cmi ./bootstrap.cmo ./bootstrap.exe)

distclean: clean
	rm -f src/setup.ml

doc:
	cd doc && sphinx-build . _build

livedoc:
	cd doc && sphinx-autobuild . _build \
	  -p 8888 -q  --host $(shell hostname) -r '\.#.*'

update-jbuilds: $(BIN)
	$(BIN) build --dev @doc/runtest --auto-promote

.PHONY: default install uninstall reinstall clean test doc
.PHONY: promote accept-corrections


text:
class Explosion < GameObject
  attr_accessor :x, :y

  def initialize(object_pool, x, y)
    super(object_pool)
    @x, @y = x, y
    ExplosionGraphics.new(self)
    ExplosionSounds.play
    inflict_damage
  end

  private

  def inflict_damage
    object_pool.nearby(self, 100).each do |obj|
      if obj.class == Tank
        obj.health.inflict_damage(
          Math.sqrt(3 * 100 - Utils.distance_between(
              obj.x, obj.y, x, y)))
      end
    end
  end
end


text:
<?php

require_once __DIR__.'/../app/bootstrap_cache.php';
require_once __DIR__.'/../app/AppKernel.php';
require_once __DIR__.'/../app/AppCache.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppCache(new AppKernel('prod', false));
//$kernel = new AppKernel('prod', false);
$kernel->handle(Request::createFromGlobals())->send();


text:
from google.appengine.ext import db
import webapp2
from webapp2_extras import sessions
import os
import sessions_module
from model.User import User,Session
from model.Jirga import Jirga
from model.Question import Question
from model.Vote import Vote
import json

class MainHandler(sessions_module.BaseSessionHandler):

    def get(self):
        user = self.getuser()
        if(user is not None):
            jirgas = Jirga.get(user.jirgas)
            result = {}
            self.response.headers['Content-Type'] = 'application/json'
            for jirga in jirgas:
                obj2 = {
                    'name': jirga.title,
                    'key': jirga.jirgaId,
                }
                questions = Question.get(jirga.questions)
                for question in questions:
                    if user.key not in question.voted:
                        obj3 = {
                            'key':question.key(),
                            'title':question.questionString,
                            'author':question.author
                        }
                        votes = Vote.get(question.votes)
                        for vote in votes:
                            if vote is not None:
                                obj4 = {
                                    'vote':vote.number,
                                    'answer':vote.answer,
                                    'count':vote.count
                                }
                                obj3.update(obj4)
                        obj2.update(obj3)
                        result.update(obj2)
                    #else:
                    #user has already voted skip this question

            self.response.out.write(json.dumps(result))
        else:
            self.response.write("FAIL - not logged in")

app = webapp2.WSGIApplication([('/getMyQuestions', MainHandler)], config=sessions_module.myconfig_dict, debug=True)


text:
//
//  GifAnimationLayer.m
//  GifAnimationLayer
//
//  Created by Zhang Yi <zhangyi.cn@gmail.com> on 2012-5-24.
//  Copyright (c) 2012年 iDeer inc.
//
//  Permission is hereby granted, free of charge, to any person obtaining
//  a copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
//  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#import "GifAnimationLayer.h"
#import <ImageIO/ImageIO.h>

static NSString * const kGifAnimationKey = @"GifAnimation";

inline static double CGImageSourceGetGifFrameDelay(CGImageSourceRef imageSource, NSUInteger index)
{
    double frameDuration = 0.0f;

    CFDictionaryRef theImageProperties;
    if ((theImageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, NULL))) {
        CFDictionaryRef gifProperties;
        if (CFDictionaryGetValueIfPresent(theImageProperties, kCGImagePropertyGIFDictionary, (const void **)&gifProperties)) {
            const void *frameDurationValue;
            if (CFDictionaryGetValueIfPresent(gifProperties, kCGImagePropertyGIFUnclampedDelayTime, &frameDurationValue)) {
                frameDuration = [(__bridge NSNumber *)frameDurationValue floatValue];
                if (frameDuration <= 0) {
                    if (CFDictionaryGetValueIfPresent(gifProperties, kCGImagePropertyGIFDelayTime, &frameDurationValue)) {
                        frameDuration = [(__bridge NSNumber *)frameDurationValue floatValue];
                    }
                }
            }
        }
        CFRelease(theImageProperties);
    }

    return frameDuration;
}

inline static NSUInteger CGImageSourceGetGifLoopCount(CGImageSourceRef imageSource)
{
    NSUInteger loopCount = 0;
    CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
    if (properties) {
        NSNumber *loopCountValue =  (__bridge NSNumber *)CFDictionaryGetValue(properties, kCGImagePropertyGIFLoopCount);
        loopCount = [loopCountValue unsignedIntegerValue];
        CFRelease(properties);
    }
    return loopCount;
}

inline static BOOL CGImageSourceHasAlpha(CGImageSourceRef imageSource)
{
    const void * result = NULL;

    CFDictionaryRef theImageProperties;
    if ((theImageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL))) {
        result = CFDictionaryGetValue(theImageProperties, kCGImagePropertyHasAlpha);
        CFRelease(theImageProperties);
    }
    return result == kCFBooleanTrue;
}

@interface GifAnimationLayer () {
    NSTimeInterval *_frameDurationArray;
    NSTimeInterval _totalDuration;
    BOOL _paused;
}

- (CGImageRef)copyImageAtFrameIndex:(NSUInteger)index;

@property (nonatomic,assign) NSUInteger currentGifFrameIndex;
@property (nonatomic,readonly) NSUInteger numberOfFrames;
@property (nonatomic,readonly) NSUInteger loopCount;

@end

@implementation GifAnimationLayer {
    CGImageSourceRef _imageSource;
}

@synthesize gifFilePath=_gifFilePath;
@synthesize currentGifFrameIndex=_currentGifFrameIndex;
@synthesize numberOfFrames=_numberOfFrames;
@synthesize loopCount=_loopCount;

- (id)init
{
    if ((self = [super init])) {
        _currentGifFrameIndex = NSNotFound;
    }
    return self;
}

+ (id)layerWithGifFilePath:(NSString *)filePath
{
    GifAnimationLayer *layer = [self layer];
    layer.gifFilePath = filePath;
    return layer;
}

+ (BOOL)needsDisplayForKey:(NSString *)key
{
    return [key isEqualToString:@"currentGifFrameIndex"];
}

- (void)display
{
    NSUInteger index = [(GifAnimationLayer *)[self presentationLayer] currentGifFrameIndex];
    if (index == NSNotFound) {
        return;
    }
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    self.contents = (__bridge_transfer id)[self copyImageAtFrameIndex:index];
    [CATransaction commit];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    if (_numberOfFrames > 0) {
        free(_frameDurationArray);
        _numberOfFrames = 0;
        _totalDuration  = 0;
    }

    if (_imageSource) {
        CFRelease(_imageSource);
    }
}

- (void)startAnimating
{
    [self stopAnimating];

    if (!_imageSource || self.numberOfFrames <= 0) {
        return;
    }

    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"currentGifFrameIndex"];
    animation.calculationMode = kCAAnimationDiscrete;
    animation.autoreverses    = NO;
    if (self.loopCount > 0) {
        animation.repeatCount = self.loopCount;
    } else {
        animation.repeatCount = HUGE_VALF;
    }

    /**
      * keyTimes
      *
      * http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CAKeyframeAnimation_class/Introduction/Introduction.html#//apple_ref/occ/cl/CAKeyframeAnimation
      *
      * Each value in the array is a floating point number between 0.0 and 1.0 and corresponds to one element in the values array.
      * Each element in the keyTimes array defines the duration of the corresponding keyframe value as a fraction of the total duration of the animation.
      * Each element value must be greater than, or equal to, the previous value.
      */
    NSMutableArray *values   = [NSMutableArray arrayWithCapacity:self.numberOfFrames];
    NSMutableArray *keyTimes = [NSMutableArray arrayWithCapacity:self.numberOfFrames];
    NSTimeInterval lastDurationFraction = 0;
    for (NSUInteger i=0; i<self.numberOfFrames; ++i) {
        [values addObject:[NSNumber numberWithUnsignedInteger:i]];

        NSTimeInterval currentDurationFraction;
        if (i == 0) {
            currentDurationFraction = 0;
        } else {
            currentDurationFraction = lastDurationFraction + _frameDurationArray[i]/_totalDuration;
        }
        lastDurationFraction = currentDurationFraction;
        [keyTimes addObject:[NSNumber numberWithDouble:currentDurationFraction]];
    }

    //add final destination value
    [values addObject:[NSNumber numberWithUnsignedInteger:self.numberOfFrames]];
    [keyTimes addObject:[NSNumber numberWithDouble:1.0]];

    animation.values   = values;
    animation.keyTimes = keyTimes;
    animation.duration = _totalDuration;

    [self addAnimation:animation forKey:kGifAnimationKey];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)stopAnimating
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [self removeAnimationForKey:kGifAnimationKey];
}

- (void)applicationDidEnterBackground
{
    self.speed = 0.0;
}

- (void)applicationWillEnterForeground
{
    self.speed = 1.0;
    if (!_paused) {
        [self startAnimating];
    }
}

- (void)pauseAnimating
{
    self.speed = 0.0;
    _paused    = YES;
}

- (void)resumeAnimating
{
    self.speed = 1.0;
    _paused    = NO;
    if (![self animationForKey:kGifAnimationKey]) {
        [self startAnimating];
    }
}

- (void)setGifFilePath:(NSString *)gifFilePath
{
    if (_numberOfFrames > 0) {
        free(_frameDurationArray);
        _numberOfFrames = 0;
    }

    if (_imageSource) {
        CFRelease(_imageSource);
    }

    _totalDuration  = 0;
    _gifFilePath = gifFilePath;

    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    self.opaque = YES;
    [CATransaction commit];

    // update numberOfFrames and frameDurationArray
    const CFStringRef optionKeys[1]   = {kCGImageSourceShouldCache};
    const CFStringRef optionValues[1] = {(CFTypeRef)kCFBooleanFalse};
    CFDictionaryRef options = CFDictionaryCreate(NULL, (const void **)optionKeys, (const void **)optionValues, 1, &kCFTypeDictionaryKeyCallBacks, & kCFTypeDictionaryValueCallBacks);
    _imageSource = CGImageSourceCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:self.gifFilePath], options);
    CFRelease(options);

    if (_imageSource) {
        _numberOfFrames = CGImageSourceGetCount(_imageSource);
        _loopCount = CGImageSourceGetGifLoopCount(_imageSource);

        _frameDurationArray = (NSTimeInterval *) malloc(_numberOfFrames * sizeof(NSTimeInterval));
        for (NSUInteger i=0; i<_numberOfFrames; ++i) {
            _frameDurationArray[i] = CGImageSourceGetGifFrameDelay(_imageSource, i);
            _totalDuration += _frameDurationArray[i];
        }

        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        self.opaque = !CGImageSourceHasAlpha(_imageSource);
        [CATransaction commit];
    }

    [self setCurrentGifFrameIndex:0];
    [self display];
}

- (CGImageRef)copyImageAtFrameIndex:(NSUInteger)index
{
    if (!_imageSource || index > _numberOfFrames) {
        return nil;
    }

    CGImageRef theImage = CGImageSourceCreateImageAtIndex(_imageSource, index, NULL);

    return theImage;
}

@end


text: A major plugin aiming to make it possible to create entire civilizations.


text:
package group.idealworld.dew.core.web.interceptor;

import group.idealworld.dew.Dew;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;

/**
 * Interceptor web auto configuration.
 *
 * @author gudaoxuri
 */
@Configuration
@ConditionalOnWebApplication
@Order(20000)
public class InterceptorWebAutoConfiguration implements WebMvcConfigurer {

    @Value(("${springdoc.api-docs.path:/v3/api-docs}"))
    private String openApiDocPath;

    @Value(("${springdoc.swagger-ui.path:/swagger-ui}"))
    private String openApiUiPath;

    @Value(("${management.endpoints.web.base-path:/management}"))
    private String managementPath;

    private static final Logger LOGGER = LoggerFactory.getLogger(InterceptorWebAutoConfiguration.class);

    /**
     * Init.
     */
    @PostConstruct
    public void init() {
        LOGGER.info("Load Auto Configuration : {}", this.getClass().getName());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (Dew.dewConfig == null) {
            // 未启用web的情况下,Dew加载滞后,忽略
            return;
        }
        if (!Dew.dewConfig.getSecurity().isAuthEnabled()) {
            return;
        }
        if (Dew.dewConfig.getSecurity().isIdentInfoEnabled()) {
            registry.addInterceptor(new IdentInfoHandlerInterceptor())
                    .excludePathPatterns("/error/**")
                    .excludePathPatterns(openApiUiPath + "/**")
                    .excludePathPatterns(openApiDocPath + "/**")
                    .excludePathPatterns(managementPath + "/**");
        } else {
            registry.addInterceptor(new TokenHandlerInterceptor())
                    .excludePathPatterns("/error/**")
                    .excludePathPatterns(openApiUiPath + "/**")
                    .excludePathPatterns(openApiDocPath + "/**")
                    .excludePathPatterns(managementPath + "/**");
        }
        if (Dew.dewConfig.getSecurity().getRouter().isEnabled()) {
            registry.addInterceptor(new RouterHandlerInterceptor())
                    .excludePathPatterns("/error/**")
                    .excludePathPatterns(openApiUiPath + "/**")
                    .excludePathPatterns(openApiDocPath + "/**")
                    .excludePathPatterns(managementPath + "/**");
        }
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseTrailingSlashMatch(true);
    }
}


text:
Ensure that ``angle.to_string()`` continues to work after pickling,
and that units passed on to ``to_string()`` or the ``Angle``
initializer can be composite units (like ``u.hour**1``), which might
result from preceding calculations.


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2015. Kyoungjun Park. All Rights Reserved.
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/white">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/toolbar_main"
        >
    </include>

    <com.example.kjpark.smartclass.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp"
        android:background="@color/colorPrimary"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
    </android.support.v4.view.ViewPager>

</LinearLayout>


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class ShrinkDiskFault extends VimFault {
  public Integer diskId;

  public Integer getDiskId() {
    return this.diskId;
  }

  public void setDiskId(Integer diskId) {
    this.diskId=diskId;
  }
}


text:
# All routing related to repositoty browsing

resource :repository, only: [:create] do
  member do
    get 'archive', constraints: { format: Gitlab::Regex.archive_formats_regex }
  end
end

resources :refs, only: [] do
  collection do
    get 'switch'
  end

  member do
    # tree viewer logs
    get 'logs_tree', constraints: { id: Gitlab::Regex.git_reference_regex }
    # Directories with leading dots erroneously get rejected if git
    # ref regex used in constraints. Regex verification now done in controller.
    get 'logs_tree/*path' => 'refs#logs_tree', as: :logs_file, constraints: {
      id: /.*/,
      path: /.*/
    }
  end
end

get '/new/*id', to: 'blob#new', constraints: { id: /.+/ }, as: 'new_blob'
post '/create/*id', to: 'blob#create', constraints: { id: /.+/ }, as: 'create_blob'
get '/edit/*id', to: 'blob#edit', constraints: { id: /.+/ }, as: 'edit_blob'
put '/update/*id', to: 'blob#update', constraints: { id: /.+/ }, as: 'update_blob'
post '/preview/*id', to: 'blob#preview', constraints: { id: /.+/ }, as: 'preview_blob'

scope('/blob/*id', as: :blob, controller: :blob, constraints: { id: /.+/, format: false }) do
  get :diff
  get '/', action: :show
  delete '/', action: :destroy
  post '/', action: :create
  put '/', action: :update
end

get(
  '/raw/*id',
  to: 'raw#show',
  constraints: { id: /.+/, format: /(html|js)/ },
  as: :raw
)

get(
  '/tree/*id',
  to: 'tree#show',
  constraints: { id: /.+/, format: /(html|js)/ },
  as: :tree
)

get(
  '/find_file/*id',
  to: 'find_file#show',
  constraints: { id: /.+/, format: /html/ },
  as: :find_file
)

get(
  '/files/*id',
  to: 'find_file#list',
  constraints: { id: /(?:[^.]|\.(?!json$))+/, format: /json/ },
  as: :files
)

post(
  '/create_dir/*id',
    to: 'tree#create_dir',
    constraints: { id: /.+/ },
    as: 'create_dir'
)

get(
  '/blame/*id',
  to: 'blame#show',
  constraints: { id: /.+/, format: /(html|js)/ },
  as: :blame
)

# File/dir history
get(
  '/commits/*id',
  to: 'commits#show',
  constraints: { id: /.+/, format: false },
  as: :commits
)


text:
let Handler = Model.createComponent("Handler");

Handler.defineMethod("init", function init(content) {
  // Init content
  this._content = content;
  this.initContent();
});

Handler.defineMethod("uninit", function () {
  // Uninit content
  this.uninitContent();
  delete this._content;
});

// Content

Object.defineProperty(Handler.prototype, "content", {
  get: function () {
    return this._content;
  },
  set: function (value) {
    if (this._content === value) return;
    this.uninitContent();
    this._content = value;
    this.initContent();
  }
});

Handler.defineMethod("initContent", function () {
  if (!this.content) return;
  this.content.handler = this;
});

Handler.defineMethod("contentDidUpdate", function () {
  this.didUpdate();
});

Handler.defineMethod("uninitContent", function () {
  if (!this.content) return;
  delete this.content.handler;
});


text:
namespace hornet {

constant_pool::constant_pool(uint16_t size)
    : _entries(size)
{
}

constant_pool::~constant_pool()
{
}

void constant_pool::set(uint16_t idx, std::shared_ptr<cp_info> entry)
{
    assert(idx < _entries.size());

    _entries[idx] = entry;
}

const cp_info& constant_pool::get(uint16_t idx) const
{
    assert(idx < _entries.size());

    auto entry = _entries[idx - 1];

    return *entry.get();
}

const cp_info& constant_pool::get_class(uint16_t idx) const
{
    return get_ty<cp_info, cp_tag::const_class>(idx);
}

const cp_info& constant_pool::get_fieldref(uint16_t idx) const
{
    return get_ty<cp_info, cp_tag::const_fieldref>(idx);
}

const cp_info& constant_pool::get_methodref(uint16_t idx) const
{
    return get_ty<cp_info, cp_tag::const_methodref>(idx);
}

const cp_info& constant_pool::get_interface_methodref(uint16_t idx) const
{
    return get_ty<cp_info, cp_tag::const_interface_methodref>(idx);
}

jint constant_pool::get_integer(uint16_t idx) const
{
    auto& value = get_ty<cp_info, cp_tag::const_integer>(idx);

    return value.int_value;
}

jlong constant_pool::get_long(uint16_t idx) const
{
    auto& value = get_ty<cp_info, cp_tag::const_long>(idx);

    return value.long_value;
}

jfloat constant_pool::get_float(uint16_t idx) const
{
    auto& value = get_ty<cp_info, cp_tag::const_float>(idx);

    return value.float_value;
}

jdouble constant_pool::get_double(uint16_t idx) const
{
    auto& value = get_ty<cp_info, cp_tag::const_double>(idx);

    return value.double_value;
}

const cp_info& constant_pool::get_name_and_type(uint16_t idx) const
{
    return get_ty<cp_info, cp_tag::const_name_and_type>(idx);
}

const cp_info& constant_pool::get_utf8(uint16_t idx) const
{
    return get_ty<cp_info, cp_tag::const_utf8>(idx);
}

string *constant_pool::get_string(uint16_t idx) const
{
    auto& entry = get_ty<cp_info, cp_tag::const_string>(idx);

    auto& utf8 = get_utf8(entry.string_index);

    return hornet::_jvm->intern_string(std::string(utf8.bytes));
}

template<typename Type, cp_tag Tag>
const Type& constant_pool::get_ty(uint16_t idx) const
{
    assert(idx < _entries.size());

    auto entry = _entries[idx - 1];

    assert(entry->tag == Tag);

    return *reinterpret_cast<Type*>(entry.get());
}

}


text:
<?php

namespace Ems\View\Illuminate;

use Ems\Contracts\Core\Renderable;
use Ems\Contracts\Core\Renderer as RendererContract;
use Ems\Contracts\View\View;
use Illuminate\Contracts\View\Factory as ViewFactory;

/**
 * e.g. for usage with HighlightProviders
 */
class Renderer implements RendererContract
{
    /**
     * @var ViewFactory
     **/
    protected $view;

    /**
     * @param ViewFactory
     **/
    public function __construct(ViewFactory $view)
    {
        $this->view = $view;
    }

    /**
     * {@inheritdoc}
     *
     * @param Renderable $item
     *
     * @return bool
     **/
    public function canRender(Renderable $item)
    {
        return ($item instanceof View);
    }

    /**
     * {@inheritdoc}
     *
     * @param Renderable $item
     *
     * @return string
     **/
    public function render(Renderable $item)
    {
        return $this->view->make($item->name(), $item->assignments())->render();
    }
}


text:
.. currentmodule:: numpy

==========================
NumPy 1.21.4 Release Notes
==========================

The NumPy 1.21.4 is a maintenance release that fixes a few bugs discovered
after 1.21.3. The most important fix here is a fix for the NumPy header files
to make them work for both x86_64 and M1 hardware when included in the Mac
universal2 wheels. Previously, the header files only worked for M1 and this
caused problems for folks building x86_64 extensions. This problem was not seen
before Python 3.10 because there were thin wheels for x86_64 that had
precedence. This release also provides thin x86_64 Mac wheels for Python 3.10.

The Python versions supported in this release are 3.7-3.10. If you want to
compile your own version using gcc-11, you will need to use gcc-11.2+ to avoid
problems.

Contributors
============

A total of 7 people contributed to this release.  People with a "+" by their
names contributed a patch for the first time.

* Bas van Beek
* Charles Harris
* Isuru Fernando
* Matthew Brett
* Sayed Adel
* Sebastian Berg
* 傅立业(Chris Fu) +

Pull requests merged
====================

A total of 9 pull requests were merged for this release.

* `#20278 <https://github.com/numpy/numpy/pull/20278>`__: BUG: Fix shadowed reference of ``dtype`` in type stub
* `#20293 <https://github.com/numpy/numpy/pull/20293>`__: BUG: Fix headers for universal2 builds
* `#20294 <https://github.com/numpy/numpy/pull/20294>`__: BUG: ``VOID_nonzero`` could sometimes mutate alignment flag
* `#20295 <https://github.com/numpy/numpy/pull/20295>`__: BUG: Do not use nonzero fastpath on unaligned arrays
* `#20296 <https://github.com/numpy/numpy/pull/20296>`__: BUG: Distutils patch to allow for 2 as a minor version (!)
* `#20297 <https://github.com/numpy/numpy/pull/20297>`__: BUG, SIMD: Fix 64-bit/8-bit integer division by a scalar
* `#20298 <https://github.com/numpy/numpy/pull/20298>`__: BUG, SIMD: Workaround broadcasting SIMD 64-bit integers on MSVC...
* `#20300 <https://github.com/numpy/numpy/pull/20300>`__: REL: Prepare for the NumPy 1.21.4 release.
* `#20302 <https://github.com/numpy/numpy/pull/20302>`__: TST: Fix a ``Arrayterator`` typing test failure


text:
<?php
/**
 *
 * @package ymkm-sql
 * @author Yoann Mikami <yoann@ymkm.org>
 */

require_once(__DIR__.'/Abstract.php');
require_once(__DIR__.'/../Domain.php');
require_once(__DIR__.'/../ParseException.php');
require_once(__DIR__.'/../Iface/WhereAware.php');

/**
 * Abstract class which defines an SQL expression to be evaluated inside WHERE/JOIN conditions
 *
 * A WhereExpression is a container for sub-expressions which can be of any type
 * including other WhereExpression.
 *
 * WhereExpression can be used as WHERE or JOIN conditions.
 *
 * @package ymkm-sql
 */
abstract class YMKM_SQL_Expression_AbstractWhere extends YMKM_SQL_Expression_Abstract
                                              implements YMKM_SQL_Iface_WhereAware
{
    /**
     * Constructor
     *
     * Initialize this expression with the given list of sub-expressions
     *
     * @param array $exprs the list of sub-expressions
     */
    public function __construct(array $exprs=array())
    {
        $this->addSubExpressions($exprs);
    }

    /**
     * Add specified list of expressions as sub-expressions of current instance
     *
     * @param array $subs list of s-expressions
     */
    final public function addSubExpressions(array $subs)
    {
        $this->doAddSubExpressions($subs);
    }

    /**
     * Returns sub-expressions assigned to current instance
     *
     * @return array s-expressions
     */
    final public function subExpressions()
    {
        return $this->doSubExpressions();
    }

    /**
     * @see YMKM_SQL_Expression_Abstract
     *
     * Map/reduce all s-exprs using subclass provided lambda functions.
     */
    final protected function doParse(YMKM_SQL_Domain $domain)
    {
        $out = '';
        // For use as a closure variable
        $self = $this;
        // Calls _doParse with lambda function as first parameter :
        // It map/reds the stored sub-expressions in this expression
        // Using subclass provided map/reduce functions and initial value.
        $out .= $this->_doParse(
                  function($m, $r, $i=null) use ($self) {
                    return array_reduce(
                           array_map($m, $self->subExpressions()),
                           $r, $i);
                  }, $domain);
        return $out;
    }

    /// Abstract method to be implemented by subclasses. ///

    abstract protected function doAddSubExpressions(array $subs);
    abstract protected function doSubExpressions();

    /**
     * Parses SQL part using the lambda function supplied as first parameter
     *
     * The supplied $exprsFn should be called within the subclass _doParse
     * and takes 3 parameters :
     * - Closure $m : map function : called on each s-expr of the expression instance
     * - Closure $r : reduce function : called on generated pairs from previous map function
     * - mixed $i : initial value to apply to reduce function when needed.
     *
     * Note : calling the $exprsFn is not required, and only the return value
     * of _doParse becomes the result of this expression's parsing.
     * It just offers a structure that should be useable for most where expressions
     * constructs.
     *
     * @param Closure $entitiesFn the lambda function performing map/reduce on expressions.
     * @param YMKM_SQL_Domain $domain the column and table definitions set on this query
     * @return string the parsed SQL expression
     * @throw YMKM_SQL_ParseException if parsing fails
     */
    abstract protected function _doParse($exprsFn, YMKM_SQL_Domain $domain);
}


text:
This sample Android app demonstrates
the client side of a pair of apps that communicate using remote services and AIDL, where the client provides a callback object (also implemented in AIDL) to the service to get results asynchronously.

This app is covered in
[the chapter on remote services](https://commonsware.com/Android/previews/remote-services-and-the-binding-pattern)
in [*The Busy Coder's Guide to Android Development*](https://commonsware.com/Android/).


text:
require 'pry-debugger'
require "./lib/pig_latin.rb"


text:
using glm::vec2;
using glm::vec3;
using glm::vec4;
using glm::mat4;

class Camera
{
public:
	Camera(vec3 a_pos, vec3 a_lookAt, float a_fFov, float a_fAspect, float a_fNear, float a_fFar);
	Camera(){};
	~Camera();
	virtual	bool	update(float dT) = 0;
	void	SetPerspective(float a_fFov, float a_fAspect, float a_fNear, float a_fFar);
	void	SetLookAt(vec3 a_pos, vec3 a_lookAt, vec3 a_up);
	void	SetPosition(vec3 a_pos);
	mat4	GetProjection();
	mat4	GetProjectionView();
	void	UpdateProjectionViewTransform();
	vec3	GetForwardDirection();
	vec3	GetUpDirection();
	vec3	GetRightDirection();
	vec3	GetPosition();

	mat4	m_worldTransform;
	mat4	m_viewTransform;
	mat4	m_projectionTransform;
	mat4	m_projectionViewTransform;
private:
};

class FlyCamera : public Camera
{
public:
	FlyCamera(vec3 a_pos, vec3 a_lookAt, float a_fFov, float a_fAspect, float a_fNear, float a_fFar);
	FlyCamera(){};
	~FlyCamera();
	bool	update(float dT);
	void	SetSpeed(float a_fSpeed);

	float	m_fSpeed;	//	need to put this back into private and handle speed changes from AntTweakBar properly
	mat4	m_LastRotation;
	bool	m_bRotatedThisFrame;
private:
};
#endif


text:
!SLIDE

# modules

## how to make `BC.util`?

### _not_ the same as inheritance

!SLIDE

	@@@ javascript
	BC.util = (function (BC) {
		var util = {},
			foo; // private variable

		// public
		util.someFunction = function () {};

		// private
		function someOther() {}

		return util;
	}(BC));
---
## this a fast, reusable pattern


text:
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, PackageImports #-}
module DBusBrowser.DBus
       ( module DBus
       , module DBus.Introspection
       , Client
       , getBusses
       , getNames
       , getObjects
       , getInterfaces
       , Iface(..)
       , Prop(..)
       , getMembers
       ) where

import Prelude hiding (catch)

import DBus.Client hiding (Method)
import DBus hiding (getSessionAddress,Signal)
import DBus.Introspection hiding (signal)

import qualified Data.Set as S
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Map as M
import Data.List (sort,find)
import System.Environment
import qualified Data.Text.IO as TIO
import Control.Exception
import Control.Applicative
import Control.Monad.Trans.Maybe
import Control.Monad

type MaybeIO = MaybeT IO

maybeExt :: IO a -> MaybeIO a
maybeExt f = MaybeT $ Just `fmap` f `catch` \(_ :: SomeException) -> return Nothing

wrap :: Maybe a -> MaybeIO a
wrap = MaybeT . return

getMachineId :: MaybeIO T.Text
getMachineId = do
  (content :: T.Text) <- maybeExt $ TIO.readFile "/etc/machine-id"
  wrap $ safeHead (T.lines content)
  where safeHead (x:_) = Just x
        safeHead _ = Nothing

getDisplay :: MaybeIO T.Text
getDisplay = do
  disp <- T.pack <$> (maybeExt $ getEnv "DISPLAY")
  MaybeT $ return $ stripPrefices $ stripScreen disp

  where stripPrefices d =  T.stripPrefix ":" d
                       <|> T.stripPrefix "localhost:" d
                       <|> T.stripPrefix "localhost.localdomain:" d
        stripScreen     =  T.takeWhile (/= '.')

getSessionID :: MaybeIO T.Text
getSessionID = do
  machid <- getMachineId
  disp   <- getDisplay
  return $ machid `T.append` "-" `T.append` disp

getSessionAddress :: MaybeIO T.Text
getSessionAddress = do
  sessId <- getSessionID
  home <- maybeExt $ getEnv "HOME"
  let filename = home ++ "/.dbus/session-bus/" ++ (T.unpack sessId)
      prefix = "DBUS_SESSION_BUS_ADDRESS="
  file <- maybeExt $ TIO.readFile filename
  let line = find (T.isPrefixOf prefix) (T.lines file)
  MaybeT $ return $ T.stripPrefix prefix =<< line

connectSessionFancy :: MaybeIO Client
connectSessionFancy = do
  addr <- getSessionAddress >>= (wrap . parseAddress . T.unpack)
  maybeExt $ connect addr

getSessionBus :: MaybeIO Client
getSessionBus = (maybeExt connectSession) `mplus` connectSessionFancy

getBusses :: IO (Maybe Client, Maybe Client)
getBusses = do
  system <- fmap Just connectSystem `catch` \(_ :: ClientError) -> return Nothing
  session <- runMaybeT getSessionBus
  return (system, session)

getNames :: Client -> IO [BusName]
getNames client = do
  res <- call_ client $
         (methodCall "/org/freedesktop/DBus" "org.freedesktop.DBus"
         (memberName_ "ListNames") )
         { methodCallDestination = Just "org.freedesktop.DBus" }

  let names = fromMaybe [] $ fromVariant (methodReturnBody res !! 0)

  return $ sort $ map busName_ names

getObjects :: Client -> BusName -> IO [ObjectPath]
getObjects client service = collectObjects client service "/"

introspect :: Client -> BusName -> ObjectPath -> IO (Maybe Object)
introspect client service path = do
  res <- call_ client $
         (methodCall path "org.freedesktop.DBus.Introspectable" "Introspect") {
           methodCallDestination = Just service }

  let xml = fromVariant $ methodReturnBody res !! 0
      object = parseXML path =<< xml

  return object

collectObjects :: Client -> BusName -> ObjectPath -> IO [ObjectPath]
collectObjects client service path = do
  res <- introspect client service path
  case res of
    Nothing -> return []
    Just o  -> if null (objectInterfaces o)
               then subObjects (objectChildren o)
               else fmap (path:) $ subObjects (objectChildren o)

  where subObjects objs = fmap concat $ mapM (collectObjects client service . objectPath) objs

getInterfaces :: Client -> BusName -> ObjectPath -> IO [InterfaceName]
getInterfaces client service path = do
  res <- introspect client service path
  case res of
    Nothing -> return []
    Just o  -> return $ map interfaceName $ objectInterfaces o

data Iface = Iface [Method] [Signal] [Prop]

type PropRead = Bool
type PropWrite = Bool
data Prop = Prop {
  propName :: T.Text,
  propType :: Type,
  propRead :: PropRead,
  propWrite :: PropWrite,
  propValue :: Maybe Variant
}

mkIface :: Client -> BusName -> ObjectPath -> InterfaceName -> Interface -> IO Iface
mkIface client service path iface i = fmap (Iface ms ss) ps'
  where ps' = mapM getProp (interfaceProperties i)
        getProp p = fmap (prop2prop p) (getProperty client service path iface
                                         (T.pack $ propertyName p))
        prop2prop p = Prop (T.pack $ propertyName p) (propertyType p)
                      (propertyRead p) (propertyWrite p)
        ms = interfaceMethods i
        ss = interfaceSignals i

getMembers :: Client -> BusName -> ObjectPath -> InterfaceName -> IO (Maybe Iface)
getMembers client service path iface = do
  res <- introspect client service path
  case res of
    Nothing -> return Nothing
    Just o -> do
      let found = find (\i -> interfaceName i == iface) (objectInterfaces o)
      maybe (return Nothing) (fmap Just . mkIface client service path iface) found

getProperty :: Client -> BusName -> ObjectPath -> InterfaceName -> T.Text -> IO (Maybe Variant)
getProperty client service path iface prop = do
  res <- call_ client $ (methodCall path  "org.freedesktop.DBus.Properties" "Get") {
    methodCallDestination = Just service,
    methodCallBody = [toVariant iface, toVariant prop] }

  let (list :: Maybe Variant) = fromVariant (methodReturnBody res !! 0)

  return $ list


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="unit" parallel="false">
  <test name="ucf-api" preserve-order="false" enabled="false">
  </test>
</suite>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />

    <form action="/Home/UploadA" method="post" enctype="multipart/form-data">
        <input id="file1" name="file" type="file" /><input type="submit" id="btn1" value="第1种方法" />

    </form>
    <form action="/Home/UploadB" method="post" enctype="multipart/form-data">
        <input id="file2" name="file" type="file" /><input type="submit" id="btn2" value="第2种方法" />

    </form>
    <form action="/Home/UploadC" method="post" enctype="multipart/form-data">
        <input id="file3" name="file" type="file" /><input type="submit" id="btn3" value="第3种方法" />

    </form>


text:
import universal from 'react-universal-component';
import options from '../../async';

export default universal(import('./NotFound'), options);


text:
package org.mybatis.guice.jta.simple;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface Schema1Mapper {

  @Update({ "drop schema schema1 if exists cascade;" })
  int createSchema1Step1();

  @Update({ "create schema schema1;" })
  int createSchema1Step2();

  @Update({ "create table schema1.name (id int not null, name varchar(50) not null);" })
  int createSchema1Step3();

  @Select({ "select id, name from schema1.name order by id" })
  List<Name> getAllNames();

  @Insert({ "insert into schema1.name (id, name) values (#{id}, #{name})" })
  int insertName(Name name);
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="@color/bluelight_500"
        android:pathData="M22,12l-4,-4v3H3v2h15v3z"/>
</vector>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">HelloCharts</string>
    <string name="action_about">About</string>
    <string name="title_activity_line_chart">LineChartActivity</string>
    <string name="title_activity_column_chart">ColumnChartActivity</string>
    <string name="title_activity_pie_chart">PieChartActivity</string>
    <string name="title_activity_bubble_chart">BubbleChartActivity</string>
    <string name="title_activity_preview_line_chart">PreviewLineChartActivity</string>
    <string name="title_activity_preview_column_chart">PreviewColumnChartActivity</string>
    <string name="title_activity_combo_line_column_chart">ComboLineColumnChartActivity</string>
    <string name="title_activity_line_column_dependency">温度变传感器</string>
    <string name="title_activity_good_bad">GoodBadActivity</string>
    <string name="title_activity_tempo_chart">TempoChartActivity</string>
    <string name="title_activity_speed_chart">SpeedChartActivity</string>
    <string name="title_activity_view_pager_charts">ViewPagerChartsActivity</string>
    <string name="title_section1">Section 1</string>
    <string name="title_section2">Section 2</string>
    <string name="title_section3">Section 3</string>
    <string name="title_activity_about">你好世界</string>
    <string name="about_version_label">"Library version "</string>
    <string name="about_author">Leszek Wach 2014</string>
    <string name="about_app_icon_content_description">App icon</string>
    <string name="about_go_to_github">Go to GitHub</string>
    <string name="title_activity_main2">Main2Activity</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">查看记录</string>
    <string name="title_activity_main22">Main22Activity</string>

    <string name="read">读取</string>
    <string name="record">纪录</string>
    <string name="setting">设置</string>
    <string name="clear">清空</string>
    <string name="scan">查看</string>
    <string name="minimun_temp">最低温度</string>
    <string name="maxmun_temp">最高温度</string>
    <string name="back">返回</string>

</resources>


text:
#include "pthread.h"
#include "implement.h"

int
ptw32_processInitialize (void)
     /*
      * ------------------------------------------------------
      * DOCPRIVATE
      *      This function performs process wide initialization for
      *      the pthread library.
      *
      * PARAMETERS
      *      N/A
      *
      * DESCRIPTION
      *      This function performs process wide initialization for
      *      the pthread library.
      *      If successful, this routine sets the global variable
      *      ptw32_processInitialized to TRUE.
      *
      * RESULTS
      *              TRUE    if successful,
      *              FALSE   otherwise
      *
      * ------------------------------------------------------
      */
{
  if (ptw32_processInitialized)
    {
      /*
       * Ignore if already initialized. this is useful for
       * programs that uses a non-dll pthread
       * library. Such programs must call ptw32_processInitialize() explicitly,
       * since this initialization routine is automatically called only when
       * the dll is loaded.
       */
      return PTW32_TRUE;
    }

  ptw32_processInitialized = PTW32_TRUE;

  /*
   * Initialize Keys
   */
  if ((pthread_key_create (&ptw32_selfThreadKey, NULL) != 0) ||
      (pthread_key_create (&ptw32_cleanupKey, NULL) != 0))
    {

      ptw32_processTerminate ();
    }

  /*
   * Set up the global locks.
   */
  InitializeCriticalSection (&ptw32_thread_reuse_lock);
  InitializeCriticalSection (&ptw32_mutex_test_init_lock);
  InitializeCriticalSection (&ptw32_cond_list_lock);
  InitializeCriticalSection (&ptw32_cond_test_init_lock);
  InitializeCriticalSection (&ptw32_rwlock_test_init_lock);
  InitializeCriticalSection (&ptw32_spinlock_test_init_lock);

  return (ptw32_processInitialized);

}				/* processInitialize */


text:
package com.blazemeter.jmeter.xmpp;

import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Packet;

public class Loggers {
    private static final Logger log = LoggingManager.getLoggerForClass();

    public static class LogRecv implements PacketListener {
        private final XMPPConnection conn;

        public LogRecv(XMPPConnection conn) {
            this.conn = conn;
        }

        @Override
        public void processPacket(Packet packet) throws SmackException.NotConnectedException {
            try {
                log.debug("Packet recv [" + conn.getConnectionID() + "]: " + packet.toXML());
            } catch (IllegalArgumentException e) {
                log.debug("Failed to log packet", e);
                log.debug("Packet recv [" + conn.getConnectionID() + "]: " + packet.getError());
            }
        }
    }

    public static class LogSent implements PacketListener {
        private final XMPPConnection conn;

        public LogSent(XMPPConnection conn) {
            this.conn = conn;
        }

        @Override
        public void processPacket(Packet packet) throws SmackException.NotConnectedException {
            log.debug("Packet sent [" + conn.getConnectionID() + "]: " + packet.toXML());
        }
    }

    public static class LogConn implements ConnectionListener {
        private final XMPPConnection conn;

        public LogConn(XMPPConnection conn) {
            this.conn = conn;
        }

        @Override
        public void connected(XMPPConnection connection) {
            log.debug("Connected: " + connection.getConnectionID());
        }

        @Override
        public void authenticated(XMPPConnection connection) {
            log.debug("Authenticated: " + connection.getConnectionID());
        }

        @Override
        public void connectionClosed() {
            log.debug("Connection closed: " + conn.getConnectionID());
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            log.error("Connection closed with error: " + conn.getConnectionID(), e);
        }

        @Override
        public void reconnectingIn(int seconds) {
            log.debug("Reconnecting in: " + seconds);
        }

        @Override
        public void reconnectionSuccessful() {
            log.debug("Reconnection successfull");
        }

        @Override
        public void reconnectionFailed(Exception e) {
            log.error("Reconnection failed: ", e);

        }
    }
}


text:
<?php

namespace Bdmpubs\Modules\Commands;

use Illuminate\Console\Command;
use Bdmpubs\Modules\Publishing\MigrationPublisher;
use Symfony\Component\Console\Input\InputArgument;

class PublishMigrationCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:publish-migration';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Publish a module's migrations to the application";

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        if ($name = $this->argument('module')) {
            $module = $this->laravel['modules']->findOrFail($name);

            $this->publish($module);

            return;
        }

        foreach ($this->laravel['modules']->enabled() as $module) {
            $this->publish($module);
        }
    }

    /**
     * Publish migration for the specified module.
     *
     * @param \Bdmpubs\Modules\Module $module
     */
    public function publish($module)
    {
        with(new MigrationPublisher($module))
            ->setRepository($this->laravel['modules'])
            ->setConsole($this)
            ->publish();
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('module', InputArgument::OPTIONAL, 'The name of module being used.'),
        );
    }
}


text:
namespace TQL.CronExpression.Visitors
{
    public enum SemanticErrorKind
    {
        SwappedValue,
        UnsupportedValue,
        ValueOutOfRange,
        CountMismatched
    }
}


text:
(function() {
    'use strict';

    angular
        .module('gdCart', [])
        .run(['$rootScope', 'Auth', 'gdShoppingLists', function($rootScope, Auth, gdShoppingLists) {

        }])

})();


text:
+++
title = "Top 10 linguagens de programação"
date = "2016-06-13"
categories = ["NMEC"]
original_url = "http://pedrocostaferreira.github.io/blog/2016/06/13/top-10-linguagens-de-programacao"
+++

Recentemente foi publicado no IEEE Spectrum, uma revista da área de
engenharia, um ranking com as 10 linguagens de programação mais
populares. Tal publicação chamou atenção pelo fato da ascensão da
linguagem R neste ranking. O site apresentou também, como comparação, o
ranking do ano de 2014.

Como podemos ver na imagem acima, vemos uma grande ascensão do R,
subindo da 9ª posição, em 2014, para a 6ª posição, em 2015. De acordo
com a revista, essa subida do R no ranking mostra a crescente
importância da "big data" em área de informática.


text:
<?php

namespace Drupal\rp_stream_provider_info\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\RevisionableContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\user\UserInterface;

/**
 * Defines the Stream Provider Info entity.
 *
 * @ingroup rp_stream_provider_info
 *
 * @ContentEntityType(
 *   id = "stream_provider_info",
 *   label = @Translation("Stream Provider Info"),
 *   handlers = {
 *     "storage" = "Drupal\rp_stream_provider_info\StreamProviderInfoStorage",
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\rp_stream_provider_info\StreamProviderInfoListBuilder",
 *     "views_data" = "Drupal\rp_stream_provider_info\Entity\StreamProviderInfoViewsData",
 *     "translation" = "Drupal\rp_stream_provider_info\StreamProviderInfoTranslationHandler",
 *
 *     "form" = {
 *       "default" = "Drupal\rp_stream_provider_info\Form\StreamProviderInfoForm",
 *       "add" = "Drupal\rp_stream_provider_info\Form\StreamProviderInfoForm",
 *       "edit" = "Drupal\rp_stream_provider_info\Form\StreamProviderInfoForm",
 *       "delete" = "Drupal\rp_stream_provider_info\Form\StreamProviderInfoDeleteForm",
 *     },
 *     "access" = "Drupal\rp_stream_provider_info\StreamProviderInfoAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\rp_stream_provider_info\StreamProviderInfoHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "stream_provider_info",
 *   data_table = "stream_provider_info_field_data",
 *   revision_table = "stream_provider_info_revision",
 *   revision_data_table = "stream_provider_info_field_revision",
 *   translatable = TRUE,
 *   admin_permission = "administer stream provider info entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "revision" = "vid",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/rp/entity-content/stream_provider_info/{stream_provider_info}",
 *     "add-form" = "/admin/rp/entity-content/stream_provider_info/add",
 *     "edit-form" = "/admin/rp/entity-content/stream_provider_info/{stream_provider_info}/edit",
 *     "delete-form" = "/admin/rp/entity-content/stream_provider_info/{stream_provider_info}/delete",
 *     "version-history" = "/admin/rp/entity-content/stream_provider_info/{stream_provider_info}/revisions",
 *     "revision" = "/admin/rp/entity-content/stream_provider_info/{stream_provider_info}/revisions/{stream_provider_info_revision}/view",
 *     "revision_revert" = "/admin/rp/entity-content/stream_provider_info/{stream_provider_info}/revisions/{stream_provider_info_revision}/revert",
 *     "translation_revert" = "/admin/rp/entity-content/stream_provider_info/{stream_provider_info}/revisions/{stream_provider_info_revision}/revert/{langcode}",
 *     "revision_delete" = "/admin/rp/entity-content/stream_provider_info/{stream_provider_info}/revisions/{stream_provider_info_revision}/delete",
 *     "collection" = "/admin/rp/entity-content/stream_provider_info",
 *   },
 *   field_ui_base_route = "stream_provider_info.settings"
 * )
 */
class StreamProviderInfo extends RevisionableContentEntityBase implements StreamProviderInfoInterface {

  use EntityChangedTrait;

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'user_id' => \Drupal::currentUser()->id(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

    foreach (array_keys($this->getTranslationLanguages()) as $langcode) {
      $translation = $this->getTranslation($langcode);

      // If no owner has been set explicitly, make the anonymous user the owner.
      if (!$translation->getOwner()) {
        $translation->setOwnerId(0);
      }
    }

    // If no revision author has been set explicitly, make the stream_provider_info owner the
    // revision author.
    if (!$this->getRevisionUser()) {
      $this->setRevisionUserId($this->getOwnerId());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('user_id', $account->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isPublished() {
    return (bool) $this->getEntityKey('status');
  }

  /**
   * {@inheritdoc}
   */
  public function setPublished($published) {
    $this->set('status', $published ? TRUE : FALSE);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Stream Provider Info entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of the Stream Provider Info entity.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'max_length' => 50,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Publishing status'))
      ->setDescription(t('A boolean indicating whether the Stream Provider Info is published.'))
      ->setRevisionable(TRUE)
      ->setDefaultValue(TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));

    $fields['revision_translation_affected'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Revision translation affected'))
      ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
      ->setReadOnly(TRUE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

    return $fields;
  }

  protected function urlRouteParameters($rel) {
    $uri_route_parameters = parent::urlRouteParameters($rel);
    if ($rel === 'revision_revert' && $this instanceof RevisionableContentEntityBase) {
      $uri_route_parameters[$this->getEntityTypeId() . '_revision'] = $this->getRevisionId();
    }
    elseif ($rel === 'revision_delete' && $this instanceof RevisionableContentEntityBase) {
      $uri_route_parameters[$this->getEntityTypeId() . '_revision'] = $this->getRevisionId();
    }
    return $uri_route_parameters;
  }

}


text:
A simple demo using [pomelo](https://github.com/NetEase/pomelo) and mqttconnector

## Test

In order to test this demo, you should install mqtt globally using following command

```sh
npm install -g mqtt
```

after start pomelo, on one terminal, run following command to subscribe

```
mqtt sub -t "AnyTopic" -h "localhost" -p 3010
```

on another, run following command to publish a message

```
mqtt pub -t "AnyTopic" -h "localhost" -p 3010 -m "Hello World"
```


text:
By [BD Network][thisisbd].

Social Sharer is a [Ruby on Rails][rails] [Gem][rubygems], allowing you to easily create Twitter and Facebook share dialogues.

[![Build status][shield-build]][info-build]
[![Gem Version][shield-gem]][info-gem]
[![Code Coverage][shield-coverage]][info-coverage]
[![License][shield-license]][info-license]

## Key Features
- Easy to configure
- Easy to style
- Kept up to date with changes share systems.

## Getting Started
### Installation
Add this to your gemfile within your Rails project:

```bash
gem 'social_sharer', '0.1.4'
```

### Options
#### Single share URL
If you require a single URL to be shared across both social networks but require simple tracking, e.g. for Google
Analytics you can use the options listed below:

```ruby
{
  url: 'http://thisisbd.com/',
  twitter_message: 'This%20is%20BD'
}
```

This would have Facebook link to: `http://thisisbd.com/?src=fb`
and your tweet contents would be: `This is BD http://thisisbd.com/?src=tw`

You may also add an (optional) Twitter handle to be included into the message:

```ruby
{
  url: 'http://thisisbd.com/',
  twitter_handle: '@thisisbd',
  twitter_message: 'This%20is%20BD'
}
```

Your tweet contents would be: `This is BD via @thisisbd http://thisisbd.com/?src=tw`

#### Multiple share URLs
If you provide different URLs for each social network, or want more flexible control over the URLs users are sharing,
these options are for you:

```ruby
{
  individual_settings: true,

  twitter: {
    url: 'http://thisisbd.com/twitter_url',
    message: 'This%20is%20BD'
  },

  facebook: {
    url: 'http://thisisbd.com/facebook_url'
  }
}
```

This would have Facebook link to: `http://thisisbd.com/facebook_url`
and your tweet contents would be: `This is BD http://thisisbd.com/twitter_url`

You may also add an (optional) Twitter handle to be included into the message:

```ruby
{
  individual_settings: true,

  twitter: {
    url: 'http://thisisbd.com/twitter_url',
    handle: '@thisisbd',
    message: 'This%20is%20BD'
  },

  facebook: {
    url: 'http://thisisbd.com/facebook_url'
  }
}
```

This would have Facebook link to: `http://thisisbd.com/facebook_url`
and your tweet contents would be: `This is BD via @thisisbd http://thisisbd.com/twitter_url`

### View Helper
Within your view:

```ruby
<%= social_share_tags( @social_sharer_options ) %>
```

## Requirements
Social Sharer requires [Ruby on Rails][rails] and has been tested on 4.x.

## Contributing
If you wish to submit a bug fix or feature, you can create a pull request and it will be merged pending a code review.

1. Clone it
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## License
Social Sharer is licensed under the [MIT License][info-license].

[logo]: https://raw.github.com/thisisbd/social_sharer/master/social_sharer_logo.png

[thisisbd]: http://thisisbd.com/
[rails]: http://rubyonrails.org/
[rubygems]: https://rubygems.org/

[info-coverage]: https://coveralls.io/github/thisisbd/social_sharer
[info-license]: LICENSE
[info-gem]: https://rubygems.org/gems/social_sharer
[info-build]: https://travis-ci.org/thisisbd/social_sharer
[shield-coverage]: https://img.shields.io/coveralls/thisisbd/social_sharer.svg
[shield-license]: https://img.shields.io/badge/license-MIT-blue.svg
[shield-gem]: https://img.shields.io/gem/v/social_sharer.svg
[shield-build]: https://img.shields.io/travis/thisisbd/social_sharer/master.svg


text:
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "wifi_tests.h"

using namespace utest::v1;

#if defined(MBED_CONF_APP_WIFI_SECURE_SSID)

void wifi_connect_params_valid_secure(void)
{
    WiFiInterface *wifi = get_interface();
    TEST_ASSERT(wifi);
    if (wifi == NULL) {
        return;
    }

    if (wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security()) == NSAPI_ERROR_OK) {
        if (wifi->disconnect() == NSAPI_ERROR_OK) {
            return;
        }
    }

    TEST_FAIL();
}

#endif // defined(MBED_CONF_APP_WIFI_SECURE_SSID)


text:
package psn.lotus.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xjl
 * @project lotus
 * @time 2016/10/8 16:33
 */
@Controller
public class HomeController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request, Model model) {
        //当前用户
        Subject subject = SecurityUtils.getSubject();

        //当前用户令牌
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername("admin");
        token.setPassword("password".toCharArray());

        //当前用户携令牌登陆
        subject.login(token);

        model.addAttribute("data", "testing data...");

        return subject.isAuthenticated() ? "hello" : "fail";
    }

}