text:
package com.b2msolutions.reyna;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.b2msolutions.reyna.Dispatcher.Result;
import com.b2msolutions.reyna.blackout.Time;
import com.b2msolutions.reyna.blackout.TimeRange;
import com.b2msolutions.reyna.http.HttpPost;
import com.b2msolutions.reyna.shadows.ShadowAndroidHttpClient;
import com.b2msolutions.reyna.system.Clock;
import com.b2msolutions.reyna.system.Message;
import com.b2msolutions.reyna.system.Preferences;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowConnectivityManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.zip.GZIPOutputStream;

import static junit.framework.Assert.assertFalse;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.robolectric.Shadows.shadowOf;

@Config(shadows = {ShadowAndroidHttpClient.class})
@RunWith(RobolectricTestRunner.class)
public class DispatcherTest {

    private Context context;
    private Intent batteryStatus;
    @Mock NetworkInfo networkInfo;
    @Mock Date now;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        context = RuntimeEnvironment.application.getApplicationContext();
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        ShadowConnectivityManager shadowConnectivityManager = shadowOf(connectivityManager);
        shadowConnectivityManager.setActiveNetworkInfo(networkInfo);
        when(networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI);
        when(networkInfo.isConnectedOrConnecting()).thenReturn(true);
    }

    @Test
    public void sendMessageHappyPathShouldSetExecuteCorrectHttpPostAndReturnOK() throws URISyntaxException, IOException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
        Message message = RepositoryTest.getMessageWithHeaders();

        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(200);
        HttpResponse httpResponse = mock(HttpResponse.class);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);

        HttpPost httpPost = mock(HttpPost.class);
        HttpClient httpClient = mock(HttpClient.class);
        when(httpClient.execute(httpPost)).thenReturn(httpResponse);

        Time time = mock(Time.class);

        assertEquals(Result.OK, new Dispatcher().sendMessage(message, httpPost, httpClient, this.context));

        this.verifyHttpPost(message, httpPost);

        ArgumentCaptor<StringEntity> stringEntityCaptor = ArgumentCaptor.forClass(StringEntity.class);
        verify(httpPost).setEntity(stringEntityCaptor.capture());
        StringEntity stringEntity = stringEntityCaptor.getValue();
        assertEquals(stringEntity.getContentType().getValue(), "text/plain; charset=UTF-8");
        assertEquals(EntityUtils.toString(stringEntity), "body");
    }

    @Test
    public void sendMessageHappyPathWithChineseCharactersShouldSetExecuteCorrectHttpPostAndReturnOK() throws URISyntaxException, IOException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
        Message message = RepositoryTest.getMessageWithHeaders("谷歌拼音输入法");

        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(200);
        HttpResponse httpResponse = mock(HttpResponse.class);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);

        HttpPost httpPost = mock(HttpPost.class);
        HttpClient httpClient = mock(HttpClient.class);
        when(httpClient.execute(httpPost)).thenReturn(httpResponse);

        Clock clock = mock(Clock.class);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.clock = clock;

        assertEquals(Result.OK, dispatcher.sendMessage(message, httpPost, httpClient, this.context));

        this.verifyHttpPost(message, httpPost);

        ArgumentCaptor<StringEntity> stringEntityCaptor = ArgumentCaptor.forClass(StringEntity.class);
        verify(httpPost).setEntity(stringEntityCaptor.capture());
        StringEntity stringEntity = stringEntityCaptor.getValue();
        assertEquals(stringEntity.getContentType().getValue(), "text/plain; charset=UTF-8");
        assertEquals(EntityUtils.toString(stringEntity), "谷歌拼音输入法");
    }

    @Test
    public void sendMessageHappyPathWithPortShouldSetPort() throws URISyntaxException, IOException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
        Message message = new Message(new URI("https://www.google.com:9008/a/b"), "body", null);

        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(200);
        HttpResponse httpResponse = mock(HttpResponse.class);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);

        HttpPost httpPost = mock(HttpPost.class);
        HttpClient httpClient = mock(HttpClient.class);
        when(httpClient.execute(httpPost)).thenReturn(httpResponse);

        Clock clock = mock(Clock.class);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.clock = clock;

        assertEquals(Result.OK, dispatcher.sendMessage(message, httpPost, httpClient, this.context));

        ArgumentCaptor<StringEntity> stringEntityCaptor = ArgumentCaptor.forClass(StringEntity.class);
        verify(httpPost).setEntity(stringEntityCaptor.capture());
        StringEntity stringEntity = stringEntityCaptor.getValue();
        assertEquals(stringEntity.getContentType().getValue(), "text/plain; charset=UTF-8");
        assertEquals(EntityUtils.toString(stringEntity), "body");
    }

    @Test
    public void sendMessageShouldReturnBlackoutWhenInBlackout() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);

        Calendar now = Calendar.getInstance();
        int hourOfDay = now.get(Calendar.HOUR_OF_DAY);
        TimeRange range = new TimeRange(new Time(hourOfDay - 1, 0), new Time(hourOfDay + 1, 0));
        new Preferences(this.context).saveCellularDataBlackout(range);

        Clock clock = mock(Clock.class);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.clock = clock;

        assertEquals(Result.BLACKOUT, dispatcher.sendMessage(null, null, null, this.context));
    }

    @Test
    public void sendMessageShouldReturnNotConnectedWhenNotConnected() {
        when(this.networkInfo.isConnectedOrConnecting()).thenReturn(false);

        Clock clock = mock(Clock.class);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.clock = clock;

        assertEquals(Result.NOTCONNECTED, dispatcher.sendMessage(null, null, null, this.context));
    }

    @Test
    public void whenExecuteThrowsReturnTemporaryError() throws URISyntaxException, IOException {
        Message message = RepositoryTest.getMessageWithHeaders();

        HttpPost httpPost = mock(HttpPost.class);
        HttpClient httpClient = mock(HttpClient.class);
        when(httpClient.execute(httpPost)).thenThrow(new RuntimeException(""));

        Clock clock = mock(Clock.class);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.clock = clock;

        assertEquals(Result.TEMPORARY_ERROR, dispatcher.sendMessage(message, httpPost, httpClient, this.context));

        this.verifyHttpPost(message, httpPost);
    }

    @Test
    public void getResultShouldReturnExpected() {
        assertEquals(Result.PERMANENT_ERROR, Dispatcher.getResult(100));
        assertEquals(Result.OK, Dispatcher.getResult(200));
        assertEquals(Result.PERMANENT_ERROR, Dispatcher.getResult(300));
        assertEquals(Result.PERMANENT_ERROR, Dispatcher.getResult(400));
        assertEquals(Result.TEMPORARY_ERROR, Dispatcher.getResult(500));
        assertEquals(Result.PERMANENT_ERROR, Dispatcher.getResult(600));
    }

    @Test
    public void sendMessageWithGzipAndContentIsLessThanMinGzipLengthShouldRemoveGzipHeaderAndSendMessageAsString() throws Exception {
        Message message = RepositoryTest.getMessageWithGzipHeaders("body");

        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(200);
        HttpResponse httpResponse = mock(HttpResponse.class);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);

        HttpPost httpPost = mock(HttpPost.class);
        HttpClient httpClient = mock(HttpClient.class);
        when(httpClient.execute(httpPost)).thenReturn(httpResponse);
        when(httpClient.execute(httpPost)).thenReturn(httpResponse);

        Clock clock = mock(Clock.class);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.clock = clock;

        assertEquals(Result.OK, dispatcher.sendMessage(message, httpPost, httpClient, this.context));

        this.verifyHttpPost(message, httpPost);

        ArgumentCaptor<ByteArrayEntity> byteArrayEntityCaptor = ArgumentCaptor.forClass(ByteArrayEntity.class);
        verify(httpPost).setEntity(byteArrayEntityCaptor.capture());
        ByteArrayEntity entity = byteArrayEntityCaptor.getValue();
        assertNull(entity.getContentEncoding());
        assertEquals(EntityUtils.toString(entity, "utf-8"), "body");
    }

    @Test
    public void sendMessageWithGzipHeaderShouldCompressContentAndReturnOK() throws URISyntaxException, IOException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
        Message message = RepositoryTest.getMessageWithGzipHeaders("this any message body more than 10 bytes length");
        byte[] data = "this any message body more than 10 bytes length".getBytes("utf-8");

        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(200);
        HttpResponse httpResponse = mock(HttpResponse.class);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);

        HttpPost httpPost = mock(HttpPost.class);
        HttpClient httpClient = mock(HttpClient.class);
        when(httpClient.execute(httpPost)).thenReturn(httpResponse);

        Clock clock = mock(Clock.class);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.clock = clock;

        Result actual = dispatcher.sendMessage(message, httpPost, httpClient, this.context);

        assertEquals(Result.OK, actual);

        this.verifyHttpPost(message, httpPost);

        ArgumentCaptor<ByteArrayEntity> entityCaptor = ArgumentCaptor.forClass(ByteArrayEntity.class);
        verify(httpPost).setEntity(entityCaptor.capture());
        AbstractHttpEntity byteArrayEntity = entityCaptor.getValue();
        assertEquals(byteArrayEntity.getContentEncoding().getValue(), "gzip");

        byte[] expected = gzip(data);
        assertArrayEquals(EntityUtils.toByteArray(byteArrayEntity), expected);
    }

    @Test
    public void canSendShouldReturnNOTCONNECTEDIfNoActiveNetwork() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        ShadowConnectivityManager shadowConnectivityManager = shadowOf(connectivityManager);
        shadowConnectivityManager.setActiveNetworkInfo(null);
        assertEquals(Result.NOTCONNECTED, Dispatcher.canSend(this.context));
    }

    @Test
    public void canSendShouldReturnOKIfNonCellularAndConnected() {
        canSendShouldReturnOKIfNonCellularAndConnected(7); // BLUETOOTH
        canSendShouldReturnOKIfNonCellularAndConnected(ConnectivityManager.TYPE_WIFI);
        canSendShouldReturnOKIfNonCellularAndConnected(8); // DUMMY
        canSendShouldReturnOKIfNonCellularAndConnected(9); // ETHERNET
    }

    @Test
    public void canSendShouldReturnOKIfMobileAndHasNoPreferences() {
        canSendShouldReturnOKIfCellularAndHasNoPreferences(ConnectivityManager.TYPE_MOBILE);
        canSendShouldReturnOKIfCellularAndHasNoPreferences(ConnectivityManager.TYPE_MOBILE_DUN);
        canSendShouldReturnOKIfCellularAndHasNoPreferences(ConnectivityManager.TYPE_MOBILE_HIPRI);
        canSendShouldReturnOKIfCellularAndHasNoPreferences(ConnectivityManager.TYPE_MOBILE_MMS);
        canSendShouldReturnOKIfCellularAndHasNoPreferences(ConnectivityManager.TYPE_MOBILE_SUPL);
        canSendShouldReturnOKIfCellularAndHasNoPreferences(ConnectivityManager.TYPE_WIMAX);
    }

    @Test
    public void canSendShouldReturnBlackoutIfMobileAndInBlackout() {
        canSendShouldReturnBlackoutIfCellularAndInBlackout(ConnectivityManager.TYPE_MOBILE);
        canSendShouldReturnBlackoutIfCellularAndInBlackout(ConnectivityManager.TYPE_MOBILE_DUN);
        canSendShouldReturnBlackoutIfCellularAndInBlackout(ConnectivityManager.TYPE_MOBILE_HIPRI);
        canSendShouldReturnBlackoutIfCellularAndInBlackout(ConnectivityManager.TYPE_MOBILE_MMS);
        canSendShouldReturnBlackoutIfCellularAndInBlackout(ConnectivityManager.TYPE_MOBILE_SUPL);
        canSendShouldReturnBlackoutIfCellularAndInBlackout(ConnectivityManager.TYPE_WIMAX);
    }

    @Test
    public void canSendShouldReturnOKIfMobileAndOutsideOfBlackout() {
        canSendShouldReturnOKIfMobileAndOutsideOfBlackout(ConnectivityManager.TYPE_MOBILE);
        canSendShouldReturnOKIfMobileAndOutsideOfBlackout(ConnectivityManager.TYPE_MOBILE_DUN);
        canSendShouldReturnOKIfMobileAndOutsideOfBlackout(ConnectivityManager.TYPE_MOBILE_HIPRI);
        canSendShouldReturnOKIfMobileAndOutsideOfBlackout(ConnectivityManager.TYPE_MOBILE_MMS);
        canSendShouldReturnOKIfMobileAndOutsideOfBlackout(ConnectivityManager.TYPE_MOBILE_SUPL);
        canSendShouldReturnOKIfMobileAndOutsideOfBlackout(ConnectivityManager.TYPE_WIMAX);
    }

    @Test
    public void canSendShouldReturnNoConnectionIfActiveConnectionIsNotConnectedOrConnecting() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        ShadowConnectivityManager shadowConnectivityManager = shadowOf(connectivityManager);
        when(this.networkInfo.isConnectedOrConnecting()).thenReturn(false);
        shadowConnectivityManager.setActiveNetworkInfo(this.networkInfo);

        assertEquals(Result.NOTCONNECTED, Dispatcher.canSend(this.context));

    }

    private void canSendShouldReturnOKIfMobileAndOutsideOfBlackout(int type) {
        when(this.networkInfo.getType()).thenReturn(type);

        Calendar now = Calendar.getInstance();
        int hourOfDay = now.get(Calendar.HOUR_OF_DAY);

        TimeRange range = new TimeRange(new Time(hourOfDay - 2, 0), new Time(hourOfDay - 1, 0));
        new Preferences(this.context).saveCellularDataBlackout(range);

        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    private void canSendShouldReturnOKIfCellularAndHasNoPreferences(int type) {
        when(this.networkInfo.getType()).thenReturn(type);
        SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    private void canSendShouldReturnBlackoutIfCellularAndInBlackout(int type) {
        when(this.networkInfo.getType()).thenReturn(type);

        Calendar now = Calendar.getInstance();
        int hourOfDay = now.get(Calendar.HOUR_OF_DAY);

        TimeRange range = new TimeRange(new Time(hourOfDay - 1, 0), new Time(hourOfDay + 1, 0));
        new Preferences(this.context).saveCellularDataBlackout(range);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));
    }

    private void canSendShouldReturnOKIfNonCellularAndConnected(int type) {
        when(this.networkInfo.getType()).thenReturn(type);

        Calendar now = Calendar.getInstance();
        int hourOfDay = now.get(Calendar.HOUR_OF_DAY);
        TimeRange range = new TimeRange(new Time(hourOfDay - 1, 0), new Time(hourOfDay + 1, 0));
        new Preferences(this.context).saveCellularDataBlackout(range);

        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    private void verifyHttpPost(Message message, HttpPost httpPost) {
        ArgumentCaptor<URI> argument = ArgumentCaptor.forClass(URI.class);
        verify(httpPost).setURI(argument.capture());
        assertEquals(message.getUrl(), argument.getValue().toString());

        verify(httpPost).setHeader(message.getHeaders()[0].getKey(), message.getHeaders()[0].getValue());
        verify(httpPost).setHeader(message.getHeaders()[1].getKey(), message.getHeaders()[1].getValue());
        verify(httpPost, times(2)).setHeader(anyString(), anyString());
    }

    private byte[] gzip(byte[] data) throws IOException {
        ByteArrayOutputStream arr = new ByteArrayOutputStream();
        OutputStream zipper = new GZIPOutputStream(arr);
        zipper.write(data);
        zipper.close();
        return arr.toByteArray();
    }

    @Test
    // device wlan oncharge
    // configuration
    //   wlan true
    public void shouldSendBlackoutTimeScenarioA() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI);
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, android.os.BatteryManager.BATTERY_PLUGGED_AC);

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveWlanBlackout("02:00-02:01");
        preferences.saveOnChargeBlackout(true);
        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOnChargeBlackout(false);
        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    @Test
    // device wlan oncharge
    // configuration
    //   wlan false
    public void shouldNotSendBlackoutTimeScenarioB() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI);
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, android.os.BatteryManager.BATTERY_PLUGGED_AC);

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveWlanBlackout("00:00-23:59");
        preferences.saveOnChargeBlackout(true);
        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOnChargeBlackout(false);
        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));
    }

    @Test
    // device wlan offcharge
    // configuration
    //   wlan true
    public void blackoutTimeScenarioC() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI);
        initBatteryChanged();

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveWlanBlackout("02:00-02:01");
        preferences.saveOffChargeBlackout(true);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOffChargeBlackout(false);
        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    @Test
    // device wlan offcharge
    // configuration
    //   wlan false
    public void blackoutTimeScenarioD() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI);
        initBatteryChanged();

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveWlanBlackout("00:00-23:59");
        preferences.saveOffChargeBlackout(true);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOffChargeBlackout(false);
        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));
    }

    private void testBlackoutMobileScenario(int type) {
        when(this.networkInfo.getType()).thenReturn(type);
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, android.os.BatteryManager.BATTERY_PLUGGED_AC);

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveWwanBlackout("02:00-02:01");
        preferences.saveOnChargeBlackout(true);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOnChargeBlackout(false);
        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    @Test
    // device wwan oncharge
    // configuration
    //   wwan true
    public void blackoutTimeScenarioE() {
        testBlackoutMobileScenario(ConnectivityManager.TYPE_MOBILE);
        testBlackoutMobileScenario(ConnectivityManager.TYPE_MOBILE_DUN);
        testBlackoutMobileScenario(ConnectivityManager.TYPE_MOBILE_HIPRI);
        testBlackoutMobileScenario(ConnectivityManager.TYPE_MOBILE_MMS);
        testBlackoutMobileScenario(ConnectivityManager.TYPE_MOBILE_SUPL);
        testBlackoutMobileScenario(ConnectivityManager.TYPE_WIMAX);
    }

    @Test
    // device wwan oncharge
    // configuration
    //   wwan false
    public void blackoutTimeScenarioF() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, android.os.BatteryManager.BATTERY_PLUGGED_AC);

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveWwanBlackout("00:00-23:59");
        preferences.saveOnChargeBlackout(true);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOnChargeBlackout(false);
        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));
    }

    @Test
    // device wwan offcharge
    // configuration
    //   wwan true
    public void blackoutTimeScenarioG() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        initBatteryChanged();

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveWwanBlackout("02:00-02:01");
        preferences.saveOffChargeBlackout(true);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOffChargeBlackout(false);
        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    @Test
    // device wwan offcharge
    // configuration
    //   wwan false
    public void blackoutTimeScenarioH() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        initBatteryChanged();

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveWwanBlackout("00:00-23:59");
        preferences.saveOffChargeBlackout(true);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOffChargeBlackout(false);
        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));
    }

    @SuppressLint("NewApi")
    @Test
    // device roaming oncharge
    // configuration
    //   roaming false
    public void blackoutTimeScenarioI() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        when(this.networkInfo.isRoaming()).thenReturn(true);
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, android.os.BatteryManager.BATTERY_PLUGGED_AC);

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveOnChargeBlackout(true);
        preferences.saveWwanRoamingBlackout(false);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOnChargeBlackout(false);
        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    @SuppressLint("NewApi")
    @Test
    // device roaming oncharge
    // configuration
    //   roaming true
    public void blackoutTimeScenarioJ() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        when(this.networkInfo.isRoaming()).thenReturn(true);
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, android.os.BatteryManager.BATTERY_PLUGGED_AC);

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveOnChargeBlackout(true);
        preferences.saveWwanRoamingBlackout(true);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOnChargeBlackout(false);
        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));
    }

    @SuppressLint("NewApi")
    @Test
    // device roaming offcharge
    // configuration
    //   roaming true
    public void blackoutTimeScenarioK() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        when(this.networkInfo.isRoaming()).thenReturn(true);
        initBatteryChanged();

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveOffChargeBlackout(true);
        preferences.saveWwanRoamingBlackout(true);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOffChargeBlackout(false);
        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));
    }

    @SuppressLint("NewApi")
    @Test
    // device roaming offcharge
    // configuration
    //   roaming false
    public void blackoutTimeScenarioL() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        when(this.networkInfo.isRoaming()).thenReturn(true);
        initBatteryChanged();

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveOffChargeBlackout(true);
        preferences.saveWwanRoamingBlackout(false);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOffChargeBlackout(false);
        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    @SuppressLint("NewApi")
    @Test
    // device wwan and wlan oncharge
    // configuration
    //   wwan true
    public void blackoutTimeScenarioM() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        when(this.networkInfo.isRoaming()).thenReturn(true);
        initBatteryChanged();

        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveOffChargeBlackout(true);
        preferences.saveWwanRoamingBlackout(false);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(this.context));

        preferences.saveOffChargeBlackout(false);
        assertEquals(Result.OK, Dispatcher.canSend(this.context));
    }

    @Test
    public void whenCallingIsChargingAndCouldNotGetBatteryStatusShouldReturnFalse() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        RuntimeEnvironment.application.sendStickyBroadcast(intent);
        assertFalse(Dispatcher.isBatteryCharging(context));
    }

    private void initBatteryChanged() {
        batteryStatus = new Intent();
        batteryStatus.setAction(Intent.ACTION_BATTERY_CHANGED);
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_LEVEL, 3);
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_SCALE, 7);
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_STATUS, 4);
        RuntimeEnvironment.application.sendStickyBroadcast(batteryStatus);
    }

    @Test
    public void whenCallingIsChargingShouldReturnExpected() {
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, android.os.BatteryManager.BATTERY_PLUGGED_AC);
        assertTrue(Dispatcher.isBatteryCharging(context));
    }

    @Test
    public void whenCallingIsChargingUsbShouldReturnExpected() {
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, android.os.BatteryManager.BATTERY_PLUGGED_USB);
        assertTrue(Dispatcher.isBatteryCharging(context));
    }

    @Test
    public void whenCallingIsChargingWirelessShouldReturnExpected() {
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, 4);
        assertTrue(Dispatcher.isBatteryCharging(context));
    }

    @Test
    public void whenCallingIsChargingUnknownShouldReturnExpected() {
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, 3);
        assertTrue(Dispatcher.isBatteryCharging(context));
    }

    @Test
    public void whenCallingGetBatteryChargingOnAndNotChargingShouldReturnExpected() {
        initBatteryChanged();
        batteryStatus.putExtra(android.os.BatteryManager.EXTRA_PLUGGED, -1);
        assertFalse(Dispatcher.isBatteryCharging(context));
    }

    @Test
    public void whenOldAndNewConfigurationPresentPreferNewConfiguration() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        Calendar now = new GregorianCalendar();
        Time oldTo = new Time(now.get(Calendar.HOUR_OF_DAY) + 1, now.get(Calendar.MINUTE));
        preferences.saveCellularDataBlackout(new TimeRange(new Time(0,0), oldTo));

        String newTo = (String.format("%02d", now.get(Calendar.HOUR_OF_DAY) - 1)) + ":" + String.format("%02d", now.get(Calendar.MINUTE));
        preferences.saveWwanBlackout("00:00-" + newTo);

        assertEquals(Result.OK, Dispatcher.canSend(context));
    }

    @Test
    public void whenOldConfigurationPresentAndNewNotPresentDontUseNewConfDefaultValue() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        Calendar now = new GregorianCalendar();
        Time oldTo = new Time(now.get(Calendar.HOUR_OF_DAY) + 1, now.get(Calendar.MINUTE));
        preferences.saveCellularDataBlackout(new TimeRange(new Time(0,0), oldTo));

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(context));
    }

    @Test
    public void whenOldConfigurationIsFromZeroAndToZeroAllowSending() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveCellularDataBlackout(new TimeRange(new Time(0, 0), new Time(0, 0)));

        assertEquals(Result.OK, Dispatcher.canSend(context));
    }

    @Test
    public void whenCallingCanSendAndCurrentTimeIsBetweenNonRecurringWwanBlackoutStartTimeAndEndTimeShouldBlackout() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveNonRecurringWwanBlackoutStartTime(42L);
        preferences.saveNonRecurringWwanBlackoutEndTime(84L);

        GregorianCalendar now = mock(GregorianCalendar.class);
        when(now.getTimeInMillis()).thenReturn(63L);

        assertEquals(Result.BLACKOUT, Dispatcher.canSend(context, now));
    }

    @Test
    public void whenCallingCanSendAndCurrentTimeIsBeforeNonRecurringWwanBlackoutStartTimeAndEndTimeShouldBeOk() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveNonRecurringWwanBlackoutStartTime(70L);
        preferences.saveNonRecurringWwanBlackoutEndTime(84L);

        GregorianCalendar now = mock(GregorianCalendar.class);
        when(now.getTimeInMillis()).thenReturn(63L);

        assertEquals(Result.OK, Dispatcher.canSend(context, now));
    }

    @Test
    public void whenCallingCanSendAndCurrentTimeIsAfterNonRecurringWwanBlackoutStartTimeAndEndTimeShouldBeOk() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.saveNonRecurringWwanBlackoutStartTime(70L);
        preferences.saveNonRecurringWwanBlackoutEndTime(84L);

        GregorianCalendar now = mock(GregorianCalendar.class);
        when(now.getTimeInMillis()).thenReturn(90L);

        assertEquals(Result.OK, Dispatcher.canSend(context, now));
    }

    @Test
    public void whenCallingCanSendAndNonRecurringWwanBlackoutStartTimeOrEndTimeIsNotSetShouldBeOk() {
        when(this.networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
        Preferences preferences = new Preferences(RuntimeEnvironment.application.getApplicationContext());
        preferences.resetNonRecurringWwanBlackout();

        GregorianCalendar now = mock(GregorianCalendar.class);
        when(now.getTimeInMillis()).thenReturn(90L);

        assertEquals(Result.OK, Dispatcher.canSend(context, now));
    }

    @Test
    public void whenCallingSendMessageShouldAddSubmittedTimestamp() throws IOException, URISyntaxException {
        Message message = RepositoryTest.getMessageWithHeaders();

        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(200);
        HttpResponse httpResponse = mock(HttpResponse.class);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);

        HttpPost httpPost = mock(HttpPost.class);
        HttpClient httpClient = mock(HttpClient.class);
        when(httpClient.execute(httpPost)).thenReturn(httpResponse);

        Clock clock = mock(Clock.class);
        Dispatcher dispatcher = new Dispatcher();
        when(clock.getCurrentTimeMillis()).thenReturn(42L);
        dispatcher.clock = clock;

        assertEquals(Result.OK, dispatcher.sendMessage(message, httpPost, httpClient, this.context));

        verify(httpPost).addHeader("submitted", "42");
    }
}


text:
package arraysandstrings;

public class PalindromePermutation {
    private static boolean isPalindromePermutation(String str){
        int[] table = buildCharFreqTable(str);
        return maxOneOddCount(table);
    }

    private static int[] buildCharFreqTable(String str) {
        int[] table = new int[Character.getNumericValue('z')-Character.getNumericValue('a')+1];
        for(char ch : str.toCharArray()){
            int val = getNumericValue(ch);
            if(val != -1) {
                table[val]++;
            }
        }
        return table;
    }

    private static boolean maxOneOddCount(int[] table){
        boolean oddCount = false;
        for(int i : table){
            if(i%2 == 1){
                if(oddCount) {
                    return false;
                }
                oddCount = true;
            }
        }
        return true;
    }

    private static int getNumericValue(char ch){
        int a = Character.getNumericValue('a');
        int z = Character.getNumericValue('z');
        int val = Character.getNumericValue(ch);
        if(val >= a && val <= z){
            return val - a;
        }
        return -1;
    }

    private static boolean isPalindromePermutationBitVector(String str){
        int bitvector = generateBitVector(str);
        return bitvector == 0 || exactlyOneBitSet(bitvector);
    }

    private static boolean exactlyOneBitSet(int bitvector) {
        return (bitvector & (bitvector - 1)) == 0;
    }

    private static int generateBitVector(String str) {
        int bitvector = 0;
        for(char ch : str.toCharArray()){
            int val = getNumericValue(ch);
            bitvector = toggle(bitvector,val);
        }
        return bitvector;
    }

    private static int toggle(int bitvector, int val) {
        if(val < 0) return bitvector;

        int mask = (1 << val);
        if((bitvector & mask) == 0){
            bitvector |= mask;
        }
        else{
            bitvector &= ~mask;
        }

        return bitvector;
    }

    public static void main(String args[]){
        System.out.println(isPalindromePermutation("taco cat"));
        System.out.println(isPalindromePermutation("taco bat"));
        System.out.println(isPalindromePermutationBitVector("taco cat"));
        System.out.println(isPalindromePermutationBitVector("taco bat"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Microthyrites disodilis Pampal.

### Remarks
null


text:
layout: post
status: publish
published: true
title: New MC++ Winforms Article
author:
  display_name: Tomas Restrepo
  login: tomasr
  email: tomas@winterdom.com
  url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 894
wordpress_url: http://winterdom.com/2003/04/newmcwinformsarticle
date: '2003-04-21 20:24:48 +0000'
date_gmt: '2003-04-21 20:24:48 +0000'
categories:
- ".NET"
tags: []
comments: []
---

My friend Sam just got his first article published on MSDN online together with Chris (whom I've already congratulated via email!).

This one covers WinForms programming with Managed C++ on Everett. Be sure to check it out!


text:
layout: page
title: About me
tags: [about, Jekyll, theme, responsive]
modified: 2014-08-08T20:53:07.573882-04:00
comments: true
image:
  feature: sample-image-2.jpg
---

Hello people!<br>
I'm Steven Motta, also known as Stemo688. I'm from Milan, Italy. I create principally mods for Minecraft Pocket Edition. In this website you can view all my creations

## My devices

{% highlight text %}
iMac with OS X 10.9.5 (Mavericks)

Motorola Moto g with Android 5.0 (Lollipop)
{% endhighlight %}

## How I use to make mods

To create scripts I use Sublime Text 3. To create textures I use Adobe Photoshop CC 2015.


text:
#include "pocl_cl.h"
#include "pocl_image_util.h"

extern CL_API_ENTRY cl_int CL_API_CALL
POname(clEnqueueCopyBufferToImage)(cl_command_queue  command_queue,
                           cl_mem            buffer,
                           cl_mem            image,
                           size_t            src_offset,
                           const size_t *    dst_origin, /*[3]*/
                           const size_t *    region,  /*[3]*/
                           cl_uint           num_events_in_wait_list,
                           const cl_event *  event_wait_list,
                           cl_event *        event ) CL_API_SUFFIX__VERSION_1_0
  {
    if (region == NULL)
      return CL_INVALID_VALUE;

    if (region[2] != 1) //3D image
      POCL_ABORT_UNIMPLEMENTED();

    int dev_elem_size = sizeof(cl_float);
    int dev_channels = 4;

    int host_elem_size;
    int host_channels;
    pocl_get_image_information (image, &host_channels, &host_elem_size);

    void* temp = malloc (image->size);

    cl_device_id device_id = command_queue->device;

    device_id->read
      (device_id->data,
        temp,
        image->device_ptrs[device_id->dev_id],
        image->size);

    cl_int ret_code = pocl_write_image
      (image,
        command_queue->device,
        dst_origin,
        region,
        0,
        0,
        temp+src_offset);

    free(temp);

    return ret_code;
  }
POsym(clEnqueueCopyBufferToImage)


text:
package com.github.jaiimageio.jpeg2000.impl;

import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadataNode;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/** This class is defined to represent a Resolution Box of JPEG JP2
 *  file format.  A Data Entry URL Box has a length, and a fixed type
 *  of "resc" (capture resolution) or "resd" (default display resolution).
 *
 * Its contens includes the resolution numerators, denominator, and the
 * exponents for both horizontal and vertical directions.
 */
public class ResolutionBox extends Box {
    /** The data elements in this box. */
    private short numV;
    private short numH;
    private short denomV;
    private short denomH;
    private byte expV;
    private byte expH;

    /** The cached horizontal/vertical resolutions. */
    private float hRes;
    private float vRes;

    /** Constructs a ResolutionBox from the provided type and
     *  content data array.
     */
    public ResolutionBox(int type, byte[] data) {
        super(18, type, data);
    }

    /** Constructs a ResolutionBox from the provided type and
     *  horizontal/vertical resolutions.
     */
    public ResolutionBox(int type, float hRes, float vRes) {
        super(18, type, null);
        this.hRes = hRes;
        this.vRes = vRes;
        denomH = denomV = 1;

        expV = 0;
        if (vRes >= 32768) {
            int temp = (int)vRes;
            while (temp >= 32768) {
                expV++;
                temp /= 10;
            }
            numV = (short)(temp & 0xFFFF);
        } else {
            numV = (short)vRes;
        }

        expH = 0;
        if (hRes >= 32768) {
            int temp = (int)hRes;
            while (temp >= 32768) {
                expH++;
                temp /= 10;
            }
            numH = (short)(temp & 0xFFFF);
        } else {
            numH = (short)hRes;
        }
    }

    /** Constructs a ResolutionBox based on the provided
     *  org.w3c.dom.Node.
     */
    public ResolutionBox(Node node) throws IIOInvalidTreeException {
        super(node);
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            String name = child.getNodeName();

            if ("VerticalResolutionNumerator".equals(name)) {
                numV = Box.getShortElementValue(child);
            }

            if ("VerticalResolutionDenominator".equals(name)) {
                denomV = Box.getShortElementValue(child);
            }

            if ("HorizontalResolutionNumerator".equals(name)) {
                numH = Box.getShortElementValue(child);
            }

            if ("HorizontalResolutionDenominator".equals(name)) {
                denomH = Box.getShortElementValue(child);
            }

            if ("VerticalResolutionExponent".equals(name)) {
                expV = Box.getByteElementValue(child);
            }

            if ("HorizontalResolutionExponent".equals(name)) {
                expH = Box.getByteElementValue(child);
            }
        }
    }

    /** Return the horizontal resolution. */
    public float getHorizontalResolution() {
        return hRes;
    }

    /** Return the vertical resolution. */
    public float getVerticalResolution() {
        return vRes;
    }

    /** Parse the data elements from the provided content data array. */
    protected void parse(byte[] data) {
        numV = (short)(((data[0] & 0xFF) << 8) | (data[1] & 0xFF));
        denomV = (short)(((data[2] & 0xFF) << 8) | (data[3] & 0xFF));
        numH = (short)(((data[4] & 0xFF) << 8) | (data[5] & 0xFF));
        denomH = (short)(((data[6] & 0xFF) << 8) | (data[7] & 0xFF));
        expV = data[8];
        expH = data[9];
        vRes = (float)((numV & 0xFFFF) * Math.pow(10, expV) / (denomV & 0xFFFF));
        hRes = (float)((numH & 0xFFFF)* Math.pow(10, expH) / (denomH & 0xFFFF));
    }

    /** Creates an IIOMetadataNode from this resolution
     *  box.  The format of this node is defined in the XML dtd and xsd
     *  for the JP2 image file.
     */
    public IIOMetadataNode getNativeNode() {
        IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
        setDefaultAttributes(node);

        IIOMetadataNode child = new IIOMetadataNode("VerticalResolutionNumerator");
        child.setUserObject(new Short(numV));
	child.setNodeValue("" + numV);
        node.appendChild(child);

        child = new IIOMetadataNode("VerticalResolutionDenominator");
        child.setUserObject(new Short(denomV));
	child.setNodeValue("" + denomV);
        node.appendChild(child);

        child = new IIOMetadataNode("HorizontalResolutionNumerator");
        child.setUserObject(new Short(numH));
	child.setNodeValue("" + numH);
        node.appendChild(child);

        child = new IIOMetadataNode("HorizontalResolutionDenominator");
        child.setUserObject(new Short(denomH));
	child.setNodeValue("" + denomH);
        node.appendChild(child);

        child = new IIOMetadataNode("VerticalResolutionExponent");
        child.setUserObject(new Byte(expV));
	child.setNodeValue("" + expV);
        node.appendChild(child);

        child = new IIOMetadataNode("HorizontalResolutionExponent");
        child.setUserObject(new Byte(expH));
	child.setNodeValue("" + expH);
        node.appendChild(child);

        return node;
    }

    protected void compose() {
        if (data != null)
            return;
        data = new byte[10];
        data[0] = (byte)(numV >> 8);
        data[1] = (byte)(numV & 0xFF);
        data[2] = (byte)(denomV >> 8);
        data[3] = (byte)(denomV & 0xFF);

        data[4] = (byte)(numH >> 8);
        data[5] = (byte)(numH & 0xFF);
        data[6] = (byte)(denomH >> 8);
        data[7] = (byte)(denomH & 0xFF);

        data[8] = expV;
        data[9] = expH;
    }
}


text:
This file contains miscellaneous notes about data processing.

Identifying missing output files
--------------------------------

```
from glob import glob
from os.path import join, exists

dirs = glob('2014.09.03-tax-parameter-sweep/mock-community/*/*/*/*/')

for e in dirs:
    fp = join(e,'rep_set_tax_assignments.txt')
    if not exists(fp):
        print e
```


text:
package com.google.cloud.vision.v1p1beta1;

import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

@javax.annotation.Generated("by GAPIC")
public class ImageAnnotatorClientTest {
  private static MockImageAnnotator mockImageAnnotator;
  private static MockServiceHelper serviceHelper;
  private ImageAnnotatorClient client;
  private LocalChannelProvider channelProvider;

  @BeforeClass
  public static void startStaticServer() {
    mockImageAnnotator = new MockImageAnnotator();
    serviceHelper =
        new MockServiceHelper("in-process-1", Arrays.<MockGrpcService>asList(mockImageAnnotator));
    serviceHelper.start();
  }

  @AfterClass
  public static void stopServer() {
    serviceHelper.stop();
  }

  @Before
  public void setUp() throws IOException {
    serviceHelper.reset();
    channelProvider = serviceHelper.createChannelProvider();
    ImageAnnotatorSettings settings =
        ImageAnnotatorSettings.newBuilder()
            .setTransportChannelProvider(channelProvider)
            .setCredentialsProvider(NoCredentialsProvider.create())
            .build();
    client = ImageAnnotatorClient.create(settings);
  }

  @After
  public void tearDown() throws Exception {
    client.close();
  }

  @Test
  @SuppressWarnings("all")
  public void batchAnnotateImagesTest() {
    BatchAnnotateImagesResponse expectedResponse = BatchAnnotateImagesResponse.newBuilder().build();
    mockImageAnnotator.addResponse(expectedResponse);

    List<AnnotateImageRequest> requests = new ArrayList<>();

    BatchAnnotateImagesResponse actualResponse = client.batchAnnotateImages(requests);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<GeneratedMessageV3> actualRequests = mockImageAnnotator.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    BatchAnnotateImagesRequest actualRequest = (BatchAnnotateImagesRequest) actualRequests.get(0);

    Assert.assertEquals(requests, actualRequest.getRequestsList());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  @SuppressWarnings("all")
  public void batchAnnotateImagesExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockImageAnnotator.addException(exception);

    try {
      List<AnnotateImageRequest> requests = new ArrayList<>();

      client.batchAnnotateImages(requests);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception
    }
  }
}


text:
namespace blink {
#if defined(ENABLE_PEPPER_CDMS)
class WebLocalFrame;
#endif
class WebSecurityOrigin;
}

namespace media {
class Decryptor;
class MediaKeys;
}

namespace content {

class CdmSessionAdapter;
#if defined(ENABLE_BROWSER_CDMS)
class RendererCdmManager;
#endif
class WebContentDecryptionModuleSessionImpl;

class WebContentDecryptionModuleImpl
    : public blink::WebContentDecryptionModule {
 public:
  static WebContentDecryptionModuleImpl* Create(
#if defined(ENABLE_PEPPER_CDMS)
      blink::WebLocalFrame* frame,
#elif defined(ENABLE_BROWSER_CDMS)
      RendererCdmManager* manager,
#endif
      const blink::WebSecurityOrigin& security_origin,
      const base::string16& key_system);

  virtual ~WebContentDecryptionModuleImpl();

  // Returns the Decryptor associated with this CDM. May be NULL if no
  // Decryptor associated with the MediaKeys object.
  // TODO(jrummell): Figure out lifetimes, as WMPI may still use the decryptor
  // after WebContentDecryptionModule is freed. http://crbug.com/330324
  media::Decryptor* GetDecryptor();

#if defined(ENABLE_BROWSER_CDMS)
  // Returns the CDM ID associated with this object. May be kInvalidCdmId if no
  // CDM ID is associated, such as when Clear Key is used.
  int GetCdmId() const;
#endif  // defined(ENABLE_BROWSER_CDMS)

  // blink::WebContentDecryptionModule implementation.
  virtual blink::WebContentDecryptionModuleSession* createSession();
  // TODO(jrummell): Remove this method once blink updated.
  virtual blink::WebContentDecryptionModuleSession* createSession(
      blink::WebContentDecryptionModuleSession::Client* client);

 private:
  // Takes reference to |adapter|.
  WebContentDecryptionModuleImpl(scoped_refptr<CdmSessionAdapter> adapter);

  scoped_refptr<CdmSessionAdapter> adapter_;

  DISALLOW_COPY_AND_ASSIGN(WebContentDecryptionModuleImpl);
};

// Allow typecasting from blink type as this is the only implementation.
inline WebContentDecryptionModuleImpl* ToWebContentDecryptionModuleImpl(
    blink::WebContentDecryptionModule* cdm) {
  return static_cast<WebContentDecryptionModuleImpl*>(cdm);
}

}  // namespace content

#endif  // CONTENT_RENDERER_MEDIA_WEBCONTENTDECRYPTIONMODULE_IMPL_H_


text:
@implementation HLBrokerMessage

+(HLBrokerMessage*)buildRequestWithServiceName:(NSString*)serviceName methodName:(NSString*)methodName {

    HLBrokerMessage* answer = [[HLBrokerMessage alloc] init];

    [answer setMessageType:[HLBrokerMessageType request]];

    // metaInformation is setup in the init
    [answer setServiceName:serviceName];
    [answer setMethodName:methodName];

    return answer;

}

+(HLBrokerMessage*)buildMetaRequestWithServiceName:(NSString*)serviceName methodName:(NSString*)methodName {

    HLBrokerMessage* answer = [[HLBrokerMessage alloc] init];

    [answer setMessageType:[HLBrokerMessageType metaRequest]];

    // metaInformation is setup in the init
    [answer setServiceName:serviceName];
    [answer setMethodName:methodName];

    return answer;

}

+(HLBrokerMessage*)buildFault:(HLBrokerMessage*)request exception:(NSException*)exception {

    HLBrokerMessage* answer = [[HLBrokerMessage alloc] init];

    [answer setMessageType:[HLBrokerMessageType fault]];
    [answer setMetaData:[request metaData]];

    // metaInformation is setup in the init
    [answer setServiceName:[request serviceName]];
    [answer setMethodName:[request methodName]];
    [answer setAssociativeParamaters:[HLFaultSerializer toJSONObject:exception]];
    // parameters are set in the init

    return answer;

}

+(HLBrokerMessage*)buildMetaResponse:(HLBrokerMessage*)request {

	HLBrokerMessage* answer = [[HLBrokerMessage alloc] init];

	[answer setMessageType:[HLBrokerMessageType metaResponse]];
    [answer setMetaData:[request metaData]];
	[answer setServiceName:[request serviceName]];
	[answer setMethodName:[request methodName]];

	return answer;

}

+(HLBrokerMessage*)buildResponse:(HLBrokerMessage*)request {

	HLBrokerMessage* answer = [[HLBrokerMessage alloc] init];

	[answer setMessageType:[HLBrokerMessageType response]];
    [answer setMetaData:[request metaData]];
	[answer setServiceName:[request serviceName]];
	[answer setMethodName:[request methodName]];

	return answer;

}

-(bool)hasOrderedParamaters {
    if( nil != _orderedParamaters ) {
        return false;
    }
    return true;

}

-(CAJsonArray*)orderedParamaters {
    if( nil != _orderedParamaters ) {
        return _orderedParamaters;
    }

    _orderedParamaters = [[CAJsonArray alloc] init];
    return _orderedParamaters;

}

-(NSString*)toString {

    NSString* answer;

    CAJsonStringOutput* writer = [[CAJsonStringOutput alloc] init];
    {
        CAJsonArray* messageComponents = [self toJsonArray];

        CAJsonArrayHandler* jsonArrayHandler = [CAJsonArrayHandler getInstance];
        [jsonArrayHandler writeValue:messageComponents writer:writer];

        answer = [writer toString];

    }

    return answer;

}

-(NSData*)toData;
{

    CAJsonArray* jsonArray = [self toJsonArray];

    NSJSONWritingOptions options = 0;
    NSError *error = nil;

    NSData* answer = [NSJSONSerialization dataWithJSONObject:[jsonArray values] options:options error:&error];
    if( nil != error ) {

        @throw exceptionWithMethodNameAndError(@"[NSJSONSerialization JSONObjectWithData:options:error:]", error);
    }

    return answer;
}

-(CAJsonArray*)toJsonArray {

    CAJsonArray* answer = [[CAJsonArray alloc] initWithCapacity:8];

    [answer add:[_messageType identifier]];
    [answer add:_metaData];
    [answer add:_serviceName];
    [answer addInteger:1]; // majorVersion
    [answer addInteger:0]; // minorVersion
    [answer add:_methodName];
    [answer add:_associativeParamaters];

    if( nil != _orderedParamaters ) {

        [answer add:_orderedParamaters];
    }

    return answer;
}

#pragma mark -
#pragma mark instance lifecycle

-(id)init {

	HLBrokerMessage* answer = [super init];

	answer->_metaData = [[CAJsonObject alloc] init];
	answer->_associativeParamaters = [[CAJsonObject alloc] init];
	answer->_orderedParamaters = nil;

	return answer;

}

-(id)initWithValues:(CAJsonArray*)values {

	HLBrokerMessage* answer = [self init];

	NSString* messageTypeIdentifer = [values getString:0];

	[answer setMessageType:[HLBrokerMessageType lookup:messageTypeIdentifer]];
	[answer setMetaData:[values jsonObjectAtIndex:1]];
	[answer setServiceName:[values getString:2]];

	[answer setMethodName:[values getString:5]];

    [answer setAssociativeParamaters:[values objectAtIndex:6]];

    if( 8 == [values count] ) {

        [answer setOrderedParamaters:[values jsonArrayAtIndex:7]];
    }

	return answer;
}

-(void)dealloc {

	[self setMessageType:nil];
	[self setMetaData:nil];
	[self setServiceName:nil];
	[self setMethodName:nil];
	[self setAssociativeParamaters:nil];
	[self setOrderedParamaters:nil];

}

#pragma mark -
#pragma mark fields

//BrokerMessageType* _messageType;
//@property (nonatomic, retain) BrokerMessageType* messageType;
@synthesize messageType = _messageType;

//JsonObject* _metaData;
//@property (nonatomic, retain) JsonObject* metaData;
@synthesize metaData = _metaData;

//NSString* _serviceName;
//@property (nonatomic, retain) NSString* serviceName;
@synthesize serviceName = _serviceName;

//NSString* _methodName;
//@property (nonatomic, retain) NSString* methodName;
@synthesize methodName = _methodName;

//JSONObject* _associativeParamaters;
//@property (nonatomic, retain) JSONObject* associativeParamaters;
@synthesize associativeParamaters = _associativeParamaters;

// orderedParamaters
//CAJsonArray* _orderedParamaters;
//@property (nonatomic, retain, getter=orderedParamaters) CAJsonArray* orderedParamaters;
@synthesize orderedParamaters = _orderedParamaters;

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Linn. Soc. , Bot. 14(2): 72 (1875)

#### Original name
Corticium ambiens Berk. & Broome

### Remarks
null


text:
package atccmd

import (
	"net"
	"time"
)

func keepaliveDialer(network string, address string) (net.Conn, error) {
	return net.DialTimeout(network, address, 5*time.Second)
}


text:
package org.apache.droids.protocol.http;

import java.util.Collections;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.client.AuthenticationHandler;
import org.apache.http.protocol.HttpContext;

class NoAuthHandler implements AuthenticationHandler
{

  @Override
  public Map<String, Header> getChallenges(HttpResponse response, HttpContext context)
      throws MalformedChallengeException
  {
    return Collections.emptyMap();
  }

  @Override
  public boolean isAuthenticationRequested(HttpResponse response, HttpContext context)
  {
    return false;
  }

  @Override
  public AuthScheme selectScheme(Map<String, Header> challenges, HttpResponse response, HttpContext context)
      throws AuthenticationException
  {
    throw new AuthenticationException(
        "Unable to respond to any of these challenges: " + challenges);
  }

}


text:
package com.zhbit.dao.stuentstatus.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.zhbit.dao.BaseDaoImpl;
import com.zhbit.dao.stuentstatus.StuStatusDao;
import com.zhbit.entity.StuStatus;

/**
 * 项目名称:ElecRecord
 * 类名称: StuStatusDaoImpl
 * 类描述:用于处理学籍异动信息的Dao层实现类
 * 创建人:罗建鑫
 * 创建时间:2016年5月26日 上午10:43:11
 * 修改人:罗建鑫
 * 修改时间:2016年5月26日 上午10:43:11
 * 修改备注:
 * @version
 */
@Repository(value=StuStatusDao.DAO_NAME)
public class StuStatusDaoImpl extends BaseDaoImpl<StuStatus> implements StuStatusDao{

	@Override
	public void saveStuStatuss(List<StuStatus> statuss) {
		// TODO Auto-generated method stub
		getHibernateTemplate().saveOrUpdateAll(statuss);
	}

}


text:
import six

import sahara.plugins.mapr.domain.configuration_file as bcf
import sahara.plugins.mapr.domain.node_process as np
import sahara.plugins.mapr.domain.service as s
import sahara.plugins.mapr.services.hive.hive as hive
import sahara.plugins.mapr.util.commands as cmd
import sahara.plugins.mapr.util.validation_utils as vu
import sahara.utils.files as files

IMPALA_SERVER = np.NodeProcess(
    name='impalaserver',
    ui_name='Impala-Server',
    package='mapr-impala-server',
    open_ports=[21000, 21050, 25000]
)
IMPALA_STATE_STORE = np.NodeProcess(
    name='impalastore',
    ui_name='Impala-Statestore',
    package='mapr-impala-statestore',
    open_ports=[25010]
)
IMPALA_CATALOG = np.NodeProcess(
    name='impalacatalog',
    ui_name='Impala-Catalog',
    package='mapr-impala-catalog',
    open_ports=[25020]
)

class Impala(s.Service):
    def __init__(self):
        super(Impala, self).__init__()
        self._name = 'impala'
        self._ui_name = 'Impala'
        self._node_processes = [
            IMPALA_CATALOG,
            IMPALA_SERVER,
            IMPALA_STATE_STORE,
        ]

    def _get_impala_env_props(self, context):
        return {}

    def get_config_files(self, cluster_context, configs, instance=None):
        defaults = 'plugins/mapr/services/impala/resources/impala-env.sh'

        impala_env = bcf.TemplateFile("env.sh")
        impala_env.remote_path = self.conf_dir(cluster_context)
        if instance:
            impala_env.fetch(instance)
        impala_env.parse(files.get_file_text(defaults))
        impala_env.add_properties(self._get_impala_env_props(cluster_context))

        return [impala_env]

    def post_install(self, cluster_context, instances):
        impalas = cluster_context.filter_instances(instances, IMPALA_SERVER)
        for instance in impalas:
            cmd.chown(instance, 'mapr:mapr', self.service_dir(cluster_context))

@six.add_metaclass(s.Single)
class ImpalaV123(Impala):
    def __init__(self):
        super(ImpalaV123, self).__init__()
        self._version = '1.2.3'
        self._dependencies = [
            ('mapr-hive', hive.HiveV012().version),
            ('mapr-impala', self.version),
        ]
        self._validation_rules = [
            vu.depends_on(hive.HiveV012(), self),
            vu.on_same_node(IMPALA_CATALOG, hive.HIVE_SERVER_2),
            vu.exactly(1, IMPALA_STATE_STORE),
            vu.exactly(1, IMPALA_CATALOG),
            vu.at_least(1, IMPALA_SERVER),
        ]

    def _get_impala_env_props(self, context):
        return {
            'impala_version': self.version,
            'statestore_host': context.get_instance_ip(IMPALA_STATE_STORE),
            'catalog_host': context.get_instance_ip(IMPALA_CATALOG),
        }

@six.add_metaclass(s.Single)
class ImpalaV141(Impala):
    def __init__(self):
        super(ImpalaV141, self).__init__()
        self._version = '1.4.1'
        self._dependencies = [
            ('mapr-hive', hive.HiveV013().version),
            ('mapr-impala', self.version),
        ]
        self._validation_rules = [
            vu.depends_on(hive.HiveV013(), self),
            vu.on_same_node(IMPALA_CATALOG, hive.HIVE_SERVER_2),
            vu.exactly(1, IMPALA_STATE_STORE),
            vu.exactly(1, IMPALA_CATALOG),
            vu.at_least(1, IMPALA_SERVER),
        ]

    def _get_impala_env_props(self, context):
        return {
            'impala_version': self.version,
            'statestore_host': context.get_instance_ip(IMPALA_STATE_STORE),
            'catalog_host': context.get_instance_ip(IMPALA_CATALOG),
        }


text:
package org.jetbrains.plugins.scala
package lang
package parser
package parsing
package expressions

import lexer.ScalaTokenTypes
import builder.ScalaPsiBuilder

/**
* @author Alexander Podkhalyuzin
* Date: 06.03.2008
*/

/*
 * Bindings ::= '(' Binding {',' Binding } ')'
 */

object Bindings {
  def parse(builder: ScalaPsiBuilder): Boolean = {
    val bindingsMarker = builder.mark
    builder.getTokenType match {
      case ScalaTokenTypes.tLPARENTHESIS => {
        builder.advanceLexer() //Ate (
        builder.disableNewlines
      }
      case _ => {
        bindingsMarker.drop()
        return false
      }
    }
    Binding parse builder
    while (builder.getTokenType == ScalaTokenTypes.tCOMMA) {
      builder.advanceLexer() //Ate ,
      if (!Binding.parse(builder)) {
        builder error ErrMsg("wrong.binding")
      }
    }
    builder.getTokenType match {
      case ScalaTokenTypes.tRPARENTHESIS => {
        builder.advanceLexer() //Ate )
        builder.restoreNewlinesState
      }
      case _ => {
        builder.restoreNewlinesState
        bindingsMarker.rollbackTo()
        return false
      }
    }
    val pm = bindingsMarker.precede
    bindingsMarker.done(ScalaElementTypes.PARAM_CLAUSE)
    pm.done(ScalaElementTypes.PARAM_CLAUSES)
    true
  }
}


text:
<?php

    include_once 'headOpen.php';
    include_once 'headExtIncl.php';
    include_once 'headHamBurEnd.php';
    include 'headerNav.php';

echo "

        <content>";

    include 'addTop.php'
?>

An Introduction To Programming With Processing

Editing the smile

                         Our smile drawn with the arc() function looks fine but needs a bit of work.  Although you cannot see it the arc actually has a fill. In order to see the fill we will first have to remove or hide the ellipse, but we're happy with the way the ellipse looks so instead of deleting the statement or cutting it to the clipboard we'll comment it out. Commenting out a statement or a group of statements is the process of adding comment tokens to the statement/s that cause the statement/s to be ignored by the compiler. Comment tokens in Processing are two forward slashes "//" as mentioned previously. The easiest way to comment out the ellipse statement is simply to place the comment tokens at the start of the statement so it looks like this:

//ellipse(width/2, height/2, 100, 100);

                            You might have also noticed that when you comment out a statement, syntax highlighting causes the statement to turn grey. This means we can now run the program and Processing will no longer draw our ellipse, until we uncomment the statement by deleting the comment tokens. To comment out a block of code  select the lines of code you wish to comment out and in the PDE click:

Edit → Comment/Uncomment

    This will toggle your selection between a commented state and a standard block of non-commented code. Commenting and uncommenting is just simply a convenient and easy way of testing or debugging a program by including and excluding statements easily without having to retype out a statement that has been deleted or using an operating system's clipboard.

                            Commenting out the ellipse statement reveals that the arc is drawn with a fill.

To remove the fill we will use the noFill() function. So between the ellipse commented statement and before the arc statement add the following code:

noFill();

                            The order in which commands are issued to Processing is very important. Functions such as rectMode() and noFill() not only effect the command that directly follows them (such as the arc statement being effected by the noFill() function) but they also effect all statements that follow there after that rely on these special functions. So what that means is that if we were to place the noFill() function before an uncommented ellipse statement followed by the arc statement both the ellipse and the arc would have no fill. This is obviously not what we want, we only want the arc to be without a fill and subsequently run the ellipse() function before noFill().

If you were to run the sketch at this point it might look as though the noFill() command has removed the arc completely from the Display Window, but this is not the case. In Processing 2D primitives such as triangles, arcs, quads, ellipses and rectangles are actually made up of both a fill and a stroke. We've already seen that the fill can be controlled with the noFill() function, the fill() function and that  Processing's default setting is to draw all 2D primitives with a fill.

                            The stroke is the outline that surrounds all 2D primitives and looks like a line of various inclinations, dimensions and weights. The stroke can also be turned off with a function similar to the noFill() function, as you might have guessed it's noStroke().

                            To turn the stroke or fill back on or to simply edit an existing stroke or fill we use the stroke() or fill() functions. Both of these functions accept parameters in the form of a grayscale color, an RGB value or a RGBA value by default. You can also control how Processing accepts parameters for these two functions with the colorMode() function. We'll be changing our black stroke (which seems to have disappeared, because it's camouflaged into the black background) to a red smile. Add the following statement after the noFill statement:

stroke(255,0,0);

This statement simply informs Processing that any strokes that are drawn after this statement is run will consist of a color that is fully red, with no green and no blue in other words (255, 0, 0). Now we have a smile floating above our text, so we're going to uncomment the ellipse statement and when we run the sketch our smile is restored to it's elliptical face.
The smile is looking a little too high up on the face so we're going to move it down, this is easy because we already have the style of the smile so we just need to offset it's y position. To do this we are going to edit the arc() function once more to the following state:

arc(width/2, height/2 + 10, 50, 50, 0, PI);

                            Notice that because we are using an inverted Cartesian graph adding 10 to the arc's current y value actually moves the arc down, inversely if we subtracted 10 we would move the smile up. At first getting used to this system might be a little tricky, but it's certainly worth noting because this type of graph system is used in many graphics based software packages.

Adding Eyes

What's a smiley face without eyes? Add the following code to your sketch after the previous arc statement:

stroke(0,0,0);
fill(0,255,0);
ellipse(width/2-15, height/2-15, 20, 30);
ellipse(width/2+15, height/2-15, 20, 30);

                        As we changed the stroke to red in our previous statement to draw the smile, we need to change it back to black in order to draw the strokes encompassing the eyes so we add the second stroke statement to our program to change the stroke color back to black. Having also turned the fill off for the arc statement we need to turn it back on for the eyes and set it to green, we can conveniently achieve both of these tasks with stroke() and fill() function calls.

Let's take a look at the X and Y parameters of the ellipse functions that actually draw the eyes and how the expressions used in these statements have been modified. For the eye on the left's X parameter 15 has been subtracted, and for the eye on the right's X parameter 15 has been added.

When working with expressions like this it's important to remember that certain mathematical operators have precedence over others. For example * and / have precedence over + and -, this means that the expression width/2-15 is actually being evaluated like so (width/2)-15. This effect is known as operator precedence. Finally the Y positions of the ellipses have been offset by subtracting 15 and rendered less circular in form and more oval-shaped by making their height's greater than their widths.

<?php
    include 'addBottom.php';
    include 'processingBNav01.php';

echo "";
    include 'processingBNav02.php';
echo "Alaising";

    include 'processingBNav03.php';

echo "";
     include 'processingBNav04.php';
echo "Drawing Irregular Shapes";

    include 'processingBNav05.php';

echo "

			</content>";

    include 'sideBarOpen.php';
    include 'processingNavMain.php';
    include 'sideBarClose.php';

echo "

";

    include 'footer.php';
    include 'analytics.php';
    include 'mainHTMLClose.php'
?>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.ExtensionPoints
{
    public interface IUserControlExtensionPoint : IExtensionPoint
    {
        string UserControlSrc { get; }

        bool Visible { get; }
    }
}


text:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".LocaMainActivity$PlaceholderFragment"
    android:background="@color/loca_app_background">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/layoutTitle"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerHorizontal="true"
        android:background="@color/loca_title_bar">

        <TextView android:text="     "
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView1" />

        <TextView android:text="Loca Alarm"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            android:layout_gravity="center"
            android:gravity="center"
            android:textColor="@color/loca_text_white"
            android:textSize="24dp"
            android:textStyle="bold" />

        <TextView android:text="     "
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView2" />
    </LinearLayout>

    <fragment 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:id="@+id/map"
        tools:context="com.app.tris.loca.MapActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_below="@+id/layoutTitle"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="20dp"
        android:id="@+id/textStatus"
        android:background="@color/loca_app_background"
        android:autoText="false"
        android:elegantTextHeight="true"
        android:gravity="center"
        android:textColor="@color/loca_text"

        android:layout_above="@+id/linearLayoutBottom"
        android:text="@string/map_instruction" />

    <LinearLayout
        android:id="@+id/linearLayoutBottom"
        android:gravity="bottom"
        android:layout_width="fill_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_alignParentBottom="true"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:background="@color/loca_app_background">
        <Button
            android:id="@+id/buttonBack"
            android:text="Back"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_weight="1" />
        <Button
            android:id="@+id/buttonUpdate"
            android:text="Update"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

</RelativeLayout>


text:
package com.reactnativenavigation.params.parsers;

import android.os.Bundle;
import android.support.annotation.NonNull;

import com.reactnativenavigation.params.NavigationParams;
import com.reactnativenavigation.params.PageParams;

import java.util.List;

public class TopTabParamsParser extends Parser {
    private static final String KEY_SCREEN_ID = "screenId";
    private static final String KEY_TITLE = "title";
    private static final String NAVIGATION_PARAMS = "navigationParams";

    @SuppressWarnings("ConstantConditions")
    public List<PageParams> parse(Bundle params) {
        return parseBundle(params, new ParseStrategy<PageParams>() {
            @Override
            public PageParams parse(Bundle topTabs) {
                return parseItem(topTabs);
            }
        });
    }

    @NonNull
    private static PageParams parseItem(Bundle params) {
        PageParams result = new PageParams();
        result.screenId = params.getString(KEY_SCREEN_ID);
        result.title = params.getString(KEY_TITLE);
        result.navigationParams = new NavigationParams(params.getBundle(NAVIGATION_PARAMS));
        result.leftButton = ButtonParser.parseLeftButton(params);
        result.rightButtons = ButtonParser.parseRightButton(params);
        result.fabParams = ButtonParser.parseFab(params, result.navigationParams.navigatorEventId);
        return result;
    }
}


text:
#include "xenia/cpu/backend/x64/x64_code_cache.h"

#include <cstdlib>
#include <cstring>

#include "xenia/base/assert.h"
#include "xenia/base/clock.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/base/memory.h"
#include "xenia/base/platform_win.h"
#include "xenia/cpu/function.h"

// Function pointer definitions
using FnRtlAddGrowableFunctionTable = decltype(&RtlAddGrowableFunctionTable);
using FnRtlGrowFunctionTable = decltype(&RtlGrowFunctionTable);
using FnRtlDeleteGrowableFunctionTable =
    decltype(&RtlDeleteGrowableFunctionTable);

namespace xe {
namespace cpu {
namespace backend {
namespace x64 {

// https://msdn.microsoft.com/en-us/library/ssa62fwe.aspx
typedef enum _UNWIND_OP_CODES {
  UWOP_PUSH_NONVOL = 0, /* info == register number */
  UWOP_ALLOC_LARGE,     /* no info, alloc size in next 2 slots */
  UWOP_ALLOC_SMALL,     /* info == size of allocation / 8 - 1 */
  UWOP_SET_FPREG,       /* no info, FP = RSP + UNWIND_INFO.FPRegOffset*16 */
  UWOP_SAVE_NONVOL,     /* info == register number, offset in next slot */
  UWOP_SAVE_NONVOL_FAR, /* info == register number, offset in next 2 slots */
  UWOP_SAVE_XMM128,     /* info == XMM reg number, offset in next slot */
  UWOP_SAVE_XMM128_FAR, /* info == XMM reg number, offset in next 2 slots */
  UWOP_PUSH_MACHFRAME   /* info == 0: no error-code, 1: error-code */
} UNWIND_CODE_OPS;
class UNWIND_REGISTER {
 public:
  enum _ {
    RAX = 0,
    RCX = 1,
    RDX = 2,
    RBX = 3,
    RSP = 4,
    RBP = 5,
    RSI = 6,
    RDI = 7,
    R8 = 8,
    R9 = 9,
    R10 = 10,
    R11 = 11,
    R12 = 12,
    R13 = 13,
    R14 = 14,
    R15 = 15,
  };
};

typedef union _UNWIND_CODE {
  struct {
    uint8_t CodeOffset;
    uint8_t UnwindOp : 4;
    uint8_t OpInfo : 4;
  };
  USHORT FrameOffset;
} UNWIND_CODE, *PUNWIND_CODE;

typedef struct _UNWIND_INFO {
  uint8_t Version : 3;
  uint8_t Flags : 5;
  uint8_t SizeOfProlog;
  uint8_t CountOfCodes;
  uint8_t FrameRegister : 4;
  uint8_t FrameOffset : 4;
  UNWIND_CODE UnwindCode[1];
  /*  UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];
   *   union {
   *       OPTIONAL ULONG ExceptionHandler;
   *       OPTIONAL ULONG FunctionEntry;
   *   };
   *   OPTIONAL ULONG ExceptionData[]; */
} UNWIND_INFO, *PUNWIND_INFO;

// Size of unwind info per function.
// TODO(benvanik): move this to emitter.
static const uint32_t kUnwindInfoSize =
    sizeof(UNWIND_INFO) + (sizeof(UNWIND_CODE) * (6 - 1));

class Win32X64CodeCache : public X64CodeCache {
 public:
  Win32X64CodeCache();
  ~Win32X64CodeCache() override;

  bool Initialize() override;

  void* LookupUnwindInfo(uint64_t host_pc) override;

 private:
  UnwindReservation RequestUnwindReservation(uint8_t* entry_address) override;
  void PlaceCode(uint32_t guest_address, void* machine_code,
                 const EmitFunctionInfo& func_info, void* code_execute_address,
                 UnwindReservation unwind_reservation) override;

  void InitializeUnwindEntry(uint8_t* unwind_entry_address,
                             size_t unwind_table_slot,
                             void* code_execute_address,
                             const EmitFunctionInfo& func_info);

  // Growable function table system handle.
  void* unwind_table_handle_ = nullptr;
  // Actual unwind table entries.
  std::vector<RUNTIME_FUNCTION> unwind_table_;
  // Current number of entries in the table.
  std::atomic<uint32_t> unwind_table_count_ = {0};
  // Does this version of Windows support growable funciton tables?
  bool supports_growable_table_ = false;

  FnRtlAddGrowableFunctionTable add_growable_table_ = nullptr;
  FnRtlDeleteGrowableFunctionTable delete_growable_table_ = nullptr;
  FnRtlGrowFunctionTable grow_table_ = nullptr;
};

std::unique_ptr<X64CodeCache> X64CodeCache::Create() {
  return std::make_unique<Win32X64CodeCache>();
}

Win32X64CodeCache::Win32X64CodeCache() = default;

Win32X64CodeCache::~Win32X64CodeCache() {
  if (supports_growable_table_) {
    if (unwind_table_handle_) {
      delete_growable_table_(unwind_table_handle_);
    }
  } else {
    if (generated_code_execute_base_) {
      RtlDeleteFunctionTable(reinterpret_cast<PRUNTIME_FUNCTION>(
          reinterpret_cast<DWORD64>(generated_code_execute_base_) | 0x3));
    }
  }
}

bool Win32X64CodeCache::Initialize() {
  if (!X64CodeCache::Initialize()) {
    return false;
  }

  // Compute total number of unwind entries we should allocate.
  // We don't support reallocing right now, so this should be high.
  unwind_table_.resize(kMaximumFunctionCount);

  // Check if this version of Windows supports growable function tables.
  auto ntdll_handle = GetModuleHandleW(L"ntdll.dll");
  if (!ntdll_handle) {
    add_growable_table_ = nullptr;
    delete_growable_table_ = nullptr;
    grow_table_ = nullptr;
  } else {
    add_growable_table_ = (FnRtlAddGrowableFunctionTable)GetProcAddress(
        ntdll_handle, "RtlAddGrowableFunctionTable");
    delete_growable_table_ = (FnRtlDeleteGrowableFunctionTable)GetProcAddress(
        ntdll_handle, "RtlDeleteGrowableFunctionTable");
    grow_table_ = (FnRtlGrowFunctionTable)GetProcAddress(
        ntdll_handle, "RtlGrowFunctionTable");
  }
  supports_growable_table_ =
      add_growable_table_ && delete_growable_table_ && grow_table_;

  // Create table and register with the system. It's empty now, but we'll grow
  // it as functions are added.
  if (supports_growable_table_) {
    if (add_growable_table_(
            &unwind_table_handle_, unwind_table_.data(), unwind_table_count_,
            DWORD(unwind_table_.size()),
            reinterpret_cast<ULONG_PTR>(generated_code_execute_base_),
            reinterpret_cast<ULONG_PTR>(generated_code_execute_base_ +
                                        kGeneratedCodeSize))) {
      XELOGE("Unable to create unwind function table");
      return false;
    }
  } else {
    // Install a callback that the debugger will use to lookup unwind info on
    // demand.
    if (!RtlInstallFunctionTableCallback(
            reinterpret_cast<DWORD64>(generated_code_execute_base_) | 0x3,
            reinterpret_cast<DWORD64>(generated_code_execute_base_),
            kGeneratedCodeSize,
            [](DWORD64 control_pc, PVOID context) {
              auto code_cache = reinterpret_cast<Win32X64CodeCache*>(context);
              return reinterpret_cast<PRUNTIME_FUNCTION>(
                  code_cache->LookupUnwindInfo(control_pc));
            },
            this, nullptr)) {
      XELOGE("Unable to install function table callback");
      return false;
    }
  }

  return true;
}

Win32X64CodeCache::UnwindReservation
Win32X64CodeCache::RequestUnwindReservation(uint8_t* entry_address) {
  assert_false(unwind_table_count_ >= kMaximumFunctionCount);
  UnwindReservation unwind_reservation;
  unwind_reservation.data_size = xe::round_up(kUnwindInfoSize, 16);
  unwind_reservation.table_slot = unwind_table_count_++;
  unwind_reservation.entry_address = entry_address;
  return unwind_reservation;
}

void Win32X64CodeCache::PlaceCode(uint32_t guest_address, void* machine_code,
                                  const EmitFunctionInfo& func_info,
                                  void* code_execute_address,
                                  UnwindReservation unwind_reservation) {
  // Add unwind info.
  InitializeUnwindEntry(unwind_reservation.entry_address,
                        unwind_reservation.table_slot, code_execute_address,
                        func_info);

  if (supports_growable_table_) {
    // Notify that the unwind table has grown.
    // We do this outside of the lock, but with the latest total count.
    grow_table_(unwind_table_handle_, unwind_table_count_);
  }

  // This isn't needed on x64 (probably), but is convention.
  // On UWP, FlushInstructionCache available starting from 10.0.16299.0.
  // https://docs.microsoft.com/en-us/uwp/win32-and-com/win32-apis
  FlushInstructionCache(GetCurrentProcess(), code_execute_address,
                        func_info.code_size.total);
}

void Win32X64CodeCache::InitializeUnwindEntry(
    uint8_t* unwind_entry_address, size_t unwind_table_slot,
    void* code_execute_address, const EmitFunctionInfo& func_info) {
  auto unwind_info = reinterpret_cast<UNWIND_INFO*>(unwind_entry_address);
  UNWIND_CODE* unwind_code = nullptr;

  assert_true(func_info.code_size.prolog < 256);  // needs to fit into a uint8_t
  auto prolog_size = static_cast<uint8_t>(func_info.code_size.prolog);
  assert_true(func_info.prolog_stack_alloc_offset <
              256);  // needs to fit into a uint8_t
  auto prolog_stack_alloc_offset =
      static_cast<uint8_t>(func_info.prolog_stack_alloc_offset);

  if (!func_info.stack_size) {
    // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info
    unwind_info->Version = 1;
    unwind_info->Flags = 0;
    unwind_info->SizeOfProlog = prolog_size;
    unwind_info->CountOfCodes = 0;
    unwind_info->FrameRegister = 0;
    unwind_info->FrameOffset = 0;
  } else if (func_info.stack_size <= 128) {
    // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info
    unwind_info->Version = 1;
    unwind_info->Flags = 0;
    unwind_info->SizeOfProlog = prolog_size;
    unwind_info->CountOfCodes = 0;
    unwind_info->FrameRegister = 0;
    unwind_info->FrameOffset = 0;

    // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_code
    unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++];
    unwind_code->CodeOffset = prolog_stack_alloc_offset;
    unwind_code->UnwindOp = UWOP_ALLOC_SMALL;
    unwind_code->OpInfo = (func_info.stack_size / 8) - 1;
  } else {
    // TODO(benvanik): take as parameters?

    // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info
    unwind_info->Version = 1;
    unwind_info->Flags = 0;
    unwind_info->SizeOfProlog = prolog_size;
    unwind_info->CountOfCodes = 0;
    unwind_info->FrameRegister = 0;
    unwind_info->FrameOffset = 0;

    // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_code
    unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++];
    unwind_code->CodeOffset = prolog_stack_alloc_offset;
    unwind_code->UnwindOp = UWOP_ALLOC_LARGE;
    unwind_code->OpInfo = 0;  // One slot for size

    assert_true((func_info.stack_size / 8) < 65536u);
    unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++];
    unwind_code->FrameOffset = (USHORT)(func_info.stack_size) / 8;
  }

  if (unwind_info->CountOfCodes % 1) {
    // Count of unwind codes must always be even.
    std::memset(&unwind_info->UnwindCode[unwind_info->CountOfCodes + 1], 0,
                sizeof(UNWIND_CODE));
  }

  // Add entry.
  auto& fn_entry = unwind_table_[unwind_table_slot];
  fn_entry.BeginAddress =
      DWORD(reinterpret_cast<uint8_t*>(code_execute_address) -
            generated_code_execute_base_);
  fn_entry.EndAddress =
      DWORD(fn_entry.BeginAddress + func_info.code_size.total);
  fn_entry.UnwindData =
      DWORD(unwind_entry_address - generated_code_execute_base_);
}

void* Win32X64CodeCache::LookupUnwindInfo(uint64_t host_pc) {
  return std::bsearch(
      &host_pc, unwind_table_.data(), unwind_table_count_,
      sizeof(RUNTIME_FUNCTION),
      [](const void* key_ptr, const void* element_ptr) {
        auto key = *reinterpret_cast<const uintptr_t*>(key_ptr) -
                   kGeneratedCodeExecuteBase;
        auto element = reinterpret_cast<const RUNTIME_FUNCTION*>(element_ptr);
        if (key < element->BeginAddress) {
          return -1;
        } else if (key > element->EndAddress) {
          return 1;
        } else {
          return 0;
        }
      });
}

}  // namespace x64
}  // namespace backend
}  // namespace cpu
}  // namespace xe


text:
package com.proofpoint.reporting;

import com.google.auto.value.AutoValue;

import java.util.Collection;
import java.util.List;

@AutoValue
abstract class ReportedMethodInfo
{
    static ReportedMethodInfo reportedMethodInfo(Collection<ReportedBeanAttribute> attributes, Collection<PrometheusBeanAttribute> prometheusAttributes)
    {
        return new AutoValue_ReportedMethodInfo(List.copyOf(attributes), List.copyOf(prometheusAttributes));
    }

    abstract Collection<ReportedBeanAttribute> getAttributes();

    abstract Collection<PrometheusBeanAttribute> getPrometheusAttributes();
}


text:
name             'chef-vault-util'
maintainer       'Francois Le Droff'
maintainer_email 'francois.le.droff@gmail.com'
license          'Apache 2.0'
description      'A chef-vault utility cookbook installing chef-vault and enabling easy testing with a chef_vault_item recipe helper'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '1.0.1'


text:
using namespace std;
int main(){

  double millas,kilometros;

  cout<< " Introduzca la longitud en millas a convertir en kilometros: "<< endl;
  cin>> millas;

  kilometros =  millas * 1.609;

  cout<< "La distancia en kilometros es de: "<< kilometros << endl;
}


text:
var Common = (function($) {
    return {
        handleDatepicker: function() {
            $('.datepicker').attr('type', 'text').datepicker();
        }
    }
}(jQuery));

$(function(){
    Common.handleDatepicker();
});