text:
package com.mopub.mobileads;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;
import android.widget.FrameLayout;
import com.mopub.common.GpsHelper;
import com.mopub.common.GpsHelperTest;
import com.mopub.common.MoPub;
import com.mopub.common.SharedPreferencesHelper;
import com.mopub.common.util.test.support.TestMethodBuilderFactory;
import com.mopub.mobileads.factories.HttpClientFactory;
import com.mopub.mobileads.test.support.SdkTestRunner;
import com.mopub.mobileads.test.support.TestAdFetcherFactory;
import com.mopub.mobileads.test.support.TestHttpResponseWithHeaders;
import com.mopub.mobileads.test.support.ThreadUtils;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.Robolectric;
import org.robolectric.tester.org.apache.http.FakeHttpLayer;

import java.lang.reflect.InvocationTargetException;

import static android.Manifest.permission.ACCESS_NETWORK_STATE;
import static com.mopub.common.util.Reflection.MethodBuilder;
import static com.mopub.mobileads.AdViewController.DEFAULT_REFRESH_TIME_MILLISECONDS;
import static com.mopub.mobileads.MoPubErrorCode.INTERNAL_ERROR;
import static com.mopub.mobileads.MoPubErrorCode.NO_FILL;
import static com.mopub.mobileads.test.support.ThreadUtils.NETWORK_DELAY;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Fail.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.stub;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.application;
import static org.robolectric.Robolectric.shadowOf;

@RunWith(SdkTestRunner.class)
public class AdViewControllerTest {
    private AdViewController subject;
    private MoPubView moPubView;
    private HttpResponse response;
    private HttpClient httpClient;
    private AdFetcher adFetcher;
    private Activity context;
    private MethodBuilder methodBuilder;

    @Before
    public void setup() {
        moPubView = mock(MoPubView.class);
        stub(moPubView.getContext()).toReturn(new Activity());
        httpClient = HttpClientFactory.create();
        context = new Activity();
        shadowOf(context).grantPermissions(ACCESS_NETWORK_STATE);
        subject = new AdViewController(context, moPubView);
        response = new TestHttpResponseWithHeaders(200, "I ain't got no-body");
        adFetcher = TestAdFetcherFactory.getSingletonMock();
        methodBuilder = TestMethodBuilderFactory.getSingletonMock();
        reset(methodBuilder);
    }

    @After
    public void tearDown() throws Exception {
        reset(methodBuilder);
    }

    @Test
    public void scheduleRefreshTimerIfEnabled_shouldCancelOldRefreshAndScheduleANewOne() throws Exception {
        response.addHeader("X-Refreshtime", "30");
        subject.configureUsingHttpResponse(response);
        Robolectric.pauseMainLooper();
        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);

        subject.scheduleRefreshTimerIfEnabled();

        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(1);

        subject.scheduleRefreshTimerIfEnabled();

        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(1);
    }

    @Test
    public void scheduleRefreshTimer_shouldNotScheduleRefreshIfAutorefreshIsOff() throws Exception {
        response.addHeader("X-Refreshtime", "30");
        subject.configureUsingHttpResponse(response);

        Robolectric.pauseMainLooper();
        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);

        subject.setAutorefreshEnabled(false);

        subject.scheduleRefreshTimerIfEnabled();

        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);
    }

    @Test
    public void scheduleRefreshTimer_whenAdViewControllerNotConfiguredByResponse_shouldHaveDefaultRefreshTime() throws Exception {
        Robolectric.pauseMainLooper();
        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);

        subject.scheduleRefreshTimerIfEnabled();
        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(1);

        Robolectric.idleMainLooper(DEFAULT_REFRESH_TIME_MILLISECONDS - 1);
        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(1);

        Robolectric.idleMainLooper(1);
        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);
    }

    @Test
    public void scheduleRefreshTimer_shouldNotScheduleRefreshIfRefreshTimeIsZero() throws Exception {
//        response.addHeader("X-Refreshtime", "0");
        subject.configureUsingHttpResponse(response);
        Robolectric.pauseMainLooper();

        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);

        subject.scheduleRefreshTimerIfEnabled();

        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);
    }

    @Test
    public void trackImpression_shouldHttpGetTheImpressionUrl() throws Exception {
        response.addHeader("X-Imptracker", "http://trackingUrl");
        subject.configureUsingHttpResponse(response);
        String expectedUserAgent = new WebView(context).getSettings().getUserAgentString();
        FakeHttpLayer fakeHttpLayer = Robolectric.getFakeHttpLayer();
        fakeHttpLayer.addPendingHttpResponse(200, "");

        assertThat(expectedUserAgent).isNotNull();

        subject.trackImpression();
        ThreadUtils.pause(NETWORK_DELAY); // does this make the test flaky?

        HttpRequest request = fakeHttpLayer.getLastSentHttpRequestInfo().getHttpRequest();
        assertThat(request.getFirstHeader("User-Agent").getValue()).isEqualTo(expectedUserAgent);
        assertThat(request.getRequestLine().getUri()).isEqualTo("http://trackingUrl");

        ClientConnectionManager connectionManager = httpClient.getConnectionManager();
        try {
            new MethodBuilder(connectionManager, "assertStillUp").setAccessible().execute();
            fail("should have thrown an exception");
        } catch (InvocationTargetException expected) {
            assertThat(expected.getCause()).isInstanceOf(IllegalStateException.class);
        }
    }

    @Test
    public void trackImpression_shouldDoNothingIfImpressionUrlNotSpecified() throws Exception {
        subject.configureUsingHttpResponse(response);
        FakeHttpLayer fakeHttpLayer = Robolectric.getFakeHttpLayer();
        fakeHttpLayer.addPendingHttpResponse(200, "");

        subject.trackImpression();
        Thread.sleep(300); // does this make the test flaky?

        assertThat(fakeHttpLayer.getLastSentHttpRequestInfo()).isNull();
    }

    @Test
    public void registerClick_shouldHttpGetTheClickthroughUrl() throws Exception {
        response.addHeader("X-Clickthrough", "http://clickUrl");
        subject.configureUsingHttpResponse(response);
        String expectedUserAgent = new WebView(context).getSettings().getUserAgentString();
        FakeHttpLayer fakeHttpLayer = Robolectric.getFakeHttpLayer();
        fakeHttpLayer.addPendingHttpResponse(200, "");

        assertThat(expectedUserAgent).isNotNull();

        subject.registerClick();
        Thread.sleep(200); // does this make the test flaky?

        HttpRequest request = fakeHttpLayer.getLastSentHttpRequestInfo().getHttpRequest();
        assertThat(request.getFirstHeader("User-Agent").getValue()).isEqualTo(expectedUserAgent);
        assertThat(request.getRequestLine().getUri()).isEqualTo("http://clickUrl");

        ClientConnectionManager connectionManager = httpClient.getConnectionManager();
        try {
            new MethodBuilder(connectionManager, "assertStillUp").setAccessible().execute();
            fail("should have thrown an exception");
        } catch (InvocationTargetException expected) {
            assertThat(expected.getCause()).isInstanceOf(IllegalStateException.class);
        }
    }

    @Test
    public void trackImpression_shouldDoNothingIfClickthroughUrlNotSpecified() throws Exception {
        subject.configureUsingHttpResponse(response);
        FakeHttpLayer fakeHttpLayer = Robolectric.getFakeHttpLayer();
        fakeHttpLayer.addPendingHttpResponse(200, "");

        subject.registerClick();
        Thread.sleep(50); // does this make the test flaky?

        assertThat(fakeHttpLayer.getLastSentHttpRequestInfo()).isNull();
    }

    @Test
    public void generateAdUrl_shouldIncludeMinFields() throws Exception {
        String expectedAdUrl = "http://ads.mopub.com/m/ad" +
                "?v=6" +
                "&nv=" + MoPub.SDK_VERSION +
                "&dn=" + Build.MANUFACTURER +
                "%2C" + Build.MODEL +
                "%2C" + Build.PRODUCT +
                "&udid=sha%3A" +
                "&z=-0700" +
                "&o=u" +
                "&sc_a=1.0" +
                "&mr=1" +
                "&ct=3" +
                "&av=1.0" +
                "&android_perms_ext_storage=0";

        String adUrl = subject.generateAdUrl();

        assertThat(adUrl).isEqualTo(expectedAdUrl);
    }

    @Test
    public void loadAd_shouldNotLoadUrlIfAdUnitIdIsNull() throws Exception {
        FakeHttpLayer fakeHttpLayer = Robolectric.getFakeHttpLayer();

        subject.loadAd();

        assertThat(fakeHttpLayer.getLastSentHttpRequestInfo()).isNull();
    }

    @Test
    public void loadAd_shouldScheduleRefreshIfNoNetworkConnectivity() throws Exception {
        FakeHttpLayer fakeHttpLayer = Robolectric.getFakeHttpLayer();
        Robolectric.pauseMainLooper();
        ConnectivityManager connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
        shadowOf(connectivityManager.getActiveNetworkInfo()).setConnectionStatus(false);
        response.addHeader("X-Refreshtime", "30");
        subject.configureUsingHttpResponse(response);
        subject.setAdUnitId("adUnitId");

        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);

        subject.loadAd();

        assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(1);
        assertThat(fakeHttpLayer.getLastSentHttpRequestInfo()).isNull();
    }

    @Test
    public void loadAd_whenGooglePlayServicesIsLinkedAndAdInfoIsNotCached_shouldCacheAdInfoBeforeFetchingAd() throws Exception {
        SharedPreferencesHelper.getSharedPreferences(context).edit().clear().commit();
        GpsHelperTest.verifyCleanSharedPreferences(context);

        GpsHelper.setClassNamesForTesting();
        GpsHelperTest.TestAdInfo adInfo = new GpsHelperTest.TestAdInfo();

        when(methodBuilder.setStatic(any(Class.class))).thenReturn(methodBuilder);
        when(methodBuilder.addParam(any(Class.class), any())).thenReturn(methodBuilder);
        when(methodBuilder.execute()).thenReturn(
                GpsHelper.GOOGLE_PLAY_SUCCESS_CODE,
                adInfo,
                adInfo.ADVERTISING_ID,
                adInfo.LIMIT_AD_TRACKING_ENABLED
        );

        final AdViewController.AdViewControllerGpsHelperListener mockAdViewControllerGpsHelperListener
                = mock(AdViewController.AdViewControllerGpsHelperListener.class);
        subject.setGpsHelperListener(mockAdViewControllerGpsHelperListener);
        subject.setAdUnitId("adUnitId");
        subject.setLocation(new Location(""));
        subject.loadAd();
        Thread.sleep(500);

        verify(mockAdViewControllerGpsHelperListener).onFetchAdInfoCompleted();
        GpsHelperTest.verifySharedPreferences(context, adInfo);
    }

    @Test
    public void loadAd_whenGooglePlayServicesIsNotLinked_shouldFetchAdFast() throws Exception {
        SharedPreferencesHelper.getSharedPreferences(context).edit().clear().commit();
        GpsHelperTest.verifyCleanSharedPreferences(context);

        GpsHelper.setClassNamesForTesting();
        when(methodBuilder.setStatic(any(Class.class))).thenReturn(methodBuilder);
        when(methodBuilder.addParam(any(Class.class), any())).thenReturn(methodBuilder);
        // return error code so it fails
        when(methodBuilder.execute()).thenReturn(GpsHelper.GOOGLE_PLAY_SUCCESS_CODE + 1);

        final AdViewController.AdViewControllerGpsHelperListener mockAdViewControllerGpsHelperListener
                = mock(AdViewController.AdViewControllerGpsHelperListener.class);
        subject.setGpsHelperListener(mockAdViewControllerGpsHelperListener);
        subject.setAdUnitId("adUnitId");
        subject.setLocation(new Location(""));
        subject.loadAd();
        // no need to sleep since it run the callback without an async task

        verify(mockAdViewControllerGpsHelperListener).onFetchAdInfoCompleted();
        GpsHelperTest.verifyCleanSharedPreferences(context);
    }

    @Test
    public void loadAd_whenGooglePlayServicesIsLinkedAndAdInfoIsCached_shouldFetchAdFast() throws Exception {
        GpsHelperTest.TestAdInfo adInfo = new GpsHelperTest.TestAdInfo();
        GpsHelperTest.populateAndVerifySharedPreferences(context, adInfo);
        GpsHelper.setClassNamesForTesting();

        when(methodBuilder.setStatic(any(Class.class))).thenReturn(methodBuilder);
        when(methodBuilder.addParam(any(Class.class), any())).thenReturn(methodBuilder);
        when(methodBuilder.execute()).thenReturn(
                GpsHelper.GOOGLE_PLAY_SUCCESS_CODE
        );

        final AdViewController.AdViewControllerGpsHelperListener mockAdViewControllerGpsHelperListener
                = mock(AdViewController.AdViewControllerGpsHelperListener.class);
        subject.setGpsHelperListener(mockAdViewControllerGpsHelperListener);
        subject.setAdUnitId("adUnitId");
        subject.setLocation(new Location(""));
        subject.loadAd();
        // no need to sleep since it run the callback without an async task

        verify(mockAdViewControllerGpsHelperListener).onFetchAdInfoCompleted();
        GpsHelperTest.verifySharedPreferences(context, adInfo);
    }

    @Test
    public void loadNonJavascript_shouldFetchAd() throws Exception {
        String url = "http://www.guy.com";
        subject.loadNonJavascript(url);

        verify(adFetcher).fetchAdForUrl(eq(url));
    }

    @Test
    public void loadNonJavascript_whenAlreadyLoading_shouldNotFetchAd() throws Exception {
        String url = "http://www.guy.com";
        subject.loadNonJavascript(url);
        reset(adFetcher);
        subject.loadNonJavascript(url);

        verify(adFetcher, never()).fetchAdForUrl(anyString());
    }

    @Test
    public void loadNonJavascript_shouldClearTheFailUrl() throws Exception {
        subject.setFailUrl("blarg:");
        subject.loadNonJavascript("http://www.goodness.com");
        reset(adFetcher);
        subject.loadFailUrl(null);

        verify(adFetcher, never()).fetchAdForUrl(anyString());
        verify(moPubView).adFailed(eq(NO_FILL));
    }

    @Test
    public void loadNonJavascript_shouldAcceptNullParameter() throws Exception {
        subject.loadNonJavascript(null);
        // pass
    }

    @Test
    public void reload_shouldReuseOldUrl() throws Exception {
        String url = "http://www.guy.com";
        subject.loadNonJavascript(url);
        subject.setNotLoading();
        reset(adFetcher);
        subject.reload();

        verify(adFetcher).fetchAdForUrl(eq(url));
    }

    @Test
    public void loadFailUrl_shouldLoadFailUrl() throws Exception {
        String failUrl = "http://www.bad.man";
        subject.setFailUrl(failUrl);
        subject.loadFailUrl(INTERNAL_ERROR);

        verify(adFetcher).fetchAdForUrl(eq(failUrl));
        verify(moPubView, never()).adFailed(any(MoPubErrorCode.class));
    }

    @Test
    public void loadFailUrl_shouldAcceptNullErrorCode() throws Exception {
        subject.loadFailUrl(null);
        // pass
    }

    @Test
    public void loadFailUrl_whenFailUrlIsNull_shouldCallAdDidFail() throws Exception {
        subject.setFailUrl(null);
        subject.loadFailUrl(INTERNAL_ERROR);

        verify(moPubView).adFailed(eq(NO_FILL));
        verify(adFetcher, never()).fetchAdForUrl(anyString());
    }

    @Test
    public void setAdContentView_whenCalledFromWrongUiThread_shouldStillSetContentView() throws Exception {
        response.addHeader("X-Width", "320");
        response.addHeader("X-Height", "50");
        final View view = mock(View.class);
        AdViewController.setShouldHonorServerDimensions(view);
        subject.configureUsingHttpResponse(response);

        new Thread(new Runnable() {
            @Override
            public void run() {
                subject.setAdContentView(view);
            }
        }).start();
        ThreadUtils.pause(10);
        Robolectric.runUiThreadTasks();

        verify(moPubView).removeAllViews();
        ArgumentCaptor<FrameLayout.LayoutParams> layoutParamsCaptor = ArgumentCaptor.forClass(FrameLayout.LayoutParams.class);
        verify(moPubView).addView(eq(view), layoutParamsCaptor.capture());
        FrameLayout.LayoutParams layoutParams = layoutParamsCaptor.getValue();

        assertThat(layoutParams.width).isEqualTo(320);
        assertThat(layoutParams.height).isEqualTo(50);
        assertThat(layoutParams.gravity).isEqualTo(Gravity.CENTER);
    }

    @Test
    public void setAdContentView_whenCalledAfterCleanUp_shouldNotRemoveViewsAndAddView() throws Exception {
        response.addHeader("X-Width", "320");
        response.addHeader("X-Height", "50");
        final View view = mock(View.class);
        AdViewController.setShouldHonorServerDimensions(view);
        subject.configureUsingHttpResponse(response);

        subject.cleanup();
        new Thread(new Runnable() {
            @Override
            public void run() {
                subject.setAdContentView(view);
            }
        }).start();
        ThreadUtils.pause(10);
        Robolectric.runUiThreadTasks();

        verify(moPubView, never()).removeAllViews();
        verify(moPubView, never()).addView(any(View.class), any(FrameLayout.LayoutParams.class));
    }

    @Test
    public void setAdContentView_whenHonorServerDimensionsAndHasDimensions_shouldSizeAndCenterView() throws Exception {
        response.addHeader("X-Width", "320");
        response.addHeader("X-Height", "50");
        View view = mock(View.class);
        AdViewController.setShouldHonorServerDimensions(view);
        subject.configureUsingHttpResponse(response);

        subject.setAdContentView(view);

        verify(moPubView).removeAllViews();
        ArgumentCaptor<FrameLayout.LayoutParams> layoutParamsCaptor = ArgumentCaptor.forClass(FrameLayout.LayoutParams.class);
        verify(moPubView).addView(eq(view), layoutParamsCaptor.capture());
        FrameLayout.LayoutParams layoutParams = layoutParamsCaptor.getValue();

        assertThat(layoutParams.width).isEqualTo(320);
        assertThat(layoutParams.height).isEqualTo(50);
        assertThat(layoutParams.gravity).isEqualTo(Gravity.CENTER);
    }

    @Test
    public void setAdContentView_whenHonorServerDimensionsAndDoesntHaveDimensions_shouldWrapAndCenterView() throws Exception {
        View view = mock(View.class);
        AdViewController.setShouldHonorServerDimensions(view);
        subject.configureUsingHttpResponse(response);

        subject.setAdContentView(view);

        verify(moPubView).removeAllViews();
        ArgumentCaptor<FrameLayout.LayoutParams> layoutParamsCaptor = ArgumentCaptor.forClass(FrameLayout.LayoutParams.class);
        verify(moPubView).addView(eq(view), layoutParamsCaptor.capture());
        FrameLayout.LayoutParams layoutParams = layoutParamsCaptor.getValue();

        assertThat(layoutParams.width).isEqualTo(FrameLayout.LayoutParams.WRAP_CONTENT);
        assertThat(layoutParams.height).isEqualTo(FrameLayout.LayoutParams.WRAP_CONTENT);
        assertThat(layoutParams.gravity).isEqualTo(Gravity.CENTER);
    }

    @Test
    public void setAdContentView_whenNotServerDimensions_shouldWrapAndCenterView() throws Exception {
        response.addHeader("X-Width", "320");
        response.addHeader("X-Height", "50");
        subject.configureUsingHttpResponse(response);
        View view = mock(View.class);

        subject.setAdContentView(view);

        verify(moPubView).removeAllViews();
        ArgumentCaptor<FrameLayout.LayoutParams> layoutParamsCaptor = ArgumentCaptor.forClass(FrameLayout.LayoutParams.class);
        verify(moPubView).addView(eq(view), layoutParamsCaptor.capture());
        FrameLayout.LayoutParams layoutParams = layoutParamsCaptor.getValue();

        assertThat(layoutParams.width).isEqualTo(FrameLayout.LayoutParams.WRAP_CONTENT);
        assertThat(layoutParams.height).isEqualTo(FrameLayout.LayoutParams.WRAP_CONTENT);
        assertThat(layoutParams.gravity).isEqualTo(Gravity.CENTER);
    }
}


text:
set -ev

CMAKE_FLAGS=$*
MAKEPROG=make

if ninja --version  >/dev/null 2>&1; then
  MAKEPROG=ninja
  CMAKE_FLAGS="-GNinja $CMAKE_FLAGS"
fi

mkdir -p cmake_build && cd cmake_build
cmake $CMAKE_FLAGS ..
for LIB in $BUILD_LIBS; do
  if ! grep "^BUILD_${LIB}:BOOL=ON$" CMakeCache.txt ; then
    echo "failed to configure $LIB"
    exit 1
  fi
done
$MAKEPROG -j3
cpack
ctest -VV -E "(concurrency_test|processor_test)"

redpajama_set_name: RedPajamaGithub


text:
package org.terasology.input.binds.inventory;

import org.terasology.input.DefaultBinding;
import org.terasology.input.InputType;
import org.terasology.input.Keyboard;
import org.terasology.input.RegisterBindButton;

/**
 * @author Immortius
 */
@RegisterBindButton(id = "toolbarSlot9", description = "Toolbar Slot 10")
@DefaultBinding(type = InputType.KEY, id = Keyboard.KeyId.KEY_0)
public class ToolbarSlot9Button extends ToolbarSlotButton {
    public ToolbarSlot9Button() {
        super(9);
    }
}


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>PICO-8 Cartridge</title>
    <meta name="description" content="">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

        {{key}}

    <button @click="loadModule()">Load from Local Storage</button>
    <button @click="saveModule()">Save to Local Stroage</button>

    <button id="saveLSToFile">Save LocalStorage to File</button>
    <button id="saveEditorToFile">Save Editor to File</button>

    <button id="filebutton" onclick="uploadReroute()">Upload a JSON File</button>

    <input type="file" id="files" name="files[]" style="display:none"/>

        <canvas id="dummy4itchapp" style="position:absolute;visibility:hidden;width:0;height:0;"></canvas>

            <canvas class="emscripten pixels" id="canvas" oncontextmenu="event.preventDefault()" tabindex="1"></canvas>


text:
% function matlabfrag(FileName,OPTIONS)
%  Exports a matlab figure to an .eps file and a .tex file for use with
%  psfrag in LaTeX.  It provides similar functionality to Laprint, but
%  with an emphasis on making it more WYSIWYG, and respecting the handle
%  options for any given text, such as fontsize, fontweight, fontangle,
%  etc.
%
%  .tex file entries can be overridden by placing a string in the
%  'UserData' field of the text handle, prefixed by 'matlabfrag:'.
%
%  For use in pdflatex, I recommend the pstool package.
%
% INPUTS
%  FileName (Required) - A string containting the name of the output files.
%  OPTIONS (Optional) - additional options are added in 'key' and 'value'
%                       pairs
%    Key           |   Value
%    ----------------------------------------------------------------------
%    'handle'      | Figure to create the .eps and .tex files from.
%                  |  default is gcf (current figure handle)
%    'epspad'      | [Left,Bottom,Right,Top] - Pad the eps figure by
%                  |  the number of points in the input vector. Default
%                  |  is [0,0,0,0].
%    'renderer'    | ['painters','opengl','zbuffer'] - The renderer used
%                  |  to generate the figure. The default is 'painters'.
%                  |  If you have manually specified the renderer,
%                  |  matlabfrag will use this value.
%    'dpi'         | DPI to print the images at. Default is 300 for OpenGL
%                  |  or Z-Buffer images, and 3200 for painters images.
%
% EXAMPLE
% plot(1:10,rand(1,10));
% set(gca,'FontSize',8);
% title('badness $\phi$','interpreter','latex','fontweight','bold');
% xlabel('1 to 10','userdata','matlabfrag:\macro');
% ylabel('random','fontsize',14);
% matlabfrag('RandPlot','epspad',[5,0,0,0]);
%
% v0.6.16 04-Apr-2010
%
% Please report bugs to zebb.prime+matlabfrag@gmail.com
%
% Available on the Matlab File Exchange

function matlabfrag(FileName,varargin)

% Matlab version check
v = version;
v = regexp(v,'(\d+)\.(\d+)\.\d+\.\d+','tokens');
v = str2double(v{1});
if v(1) < 7
  error('matlabfrag:oldMatlab','Matlabfrag requires Matlab r2007a or newer to run');
elseif v(1) == 7
  if v(2) < 4
    error('matlabfrag:oldMatlab','Matlabfrag requires Matlab r2007a or newer to run');
  end
end

% Version information is taken from the above help information
HelpText = help('matlabfrag');
LatestVersion = regexp(HelpText,'(v[\d\.]+\w*?) ([\d]+\-[\w]+\-[\d]+)','tokens');
LatestVersion = LatestVersion{1};
Version = LatestVersion{1};
VersionDate = LatestVersion{2};
TEXHDR = sprintf('%% Generated using matlabfrag\n%% Version: %s\n%% Version Date: %s\n%% Author: Zebb Prime',...
  Version,VersionDate);

% Global macros
REPLACEMENT_FORMAT = '%03d';
USERDATA_PREFIX = 'matlabfrag:';
NEGXTICK_COMMAND = 'matlabfragNegXTick';
ACTION_FUNC_NAME = @(x) sprintf('f%i',x);
ACTION_DESC_NAME = @(x) sprintf('d%i',x);

% Debug macro levels
KEEP_TEMPFILE = 1;
SHOW_OPTIONS = 1;
PAUSE_BEFORE_PRINT = 2;
PAUSE_AFTER_PRINT = 2;
STEP_THROUGH_ACTIONS = 3;

p = inputParser;
p.FunctionName = 'matlabfrag';

p.addRequired('FileName', @(x) ischar(x) );
p.addParamValue('handle', gcf, @(x) ishandle(x) && strcmpi(get(x,'Type'),'figure') );
p.addParamValue('epspad', [0,0,0,0], @(x) isnumeric(x) && (all(size(x) == [1 4])) );
p.addParamValue('renderer', 'painters', ...
  @(x) any( strcmpi(x,{'painters','opengl','zbuffer'}) ) );
p.addParamValue('dpi', 300, @(x) isnumeric(x) );
p.addParamValue('debuglvl',0, @(x) isnumeric(x) && x>=0);
p.parse(FileName,varargin{:});

if p.Results.debuglvl >= SHOW_OPTIONS
  fprintf(1,'OPTION: FileName = %s\n',p.Results.FileName);
  fprintf(1,'OPTION: handle = %f\n',p.Results.handle);
  fprintf(1,'OPTION: epspad = [%i %i %i %i]\n',p.Results.epspad);
  fprintf(1,'OPTION: renderer = %s\n',p.Results.renderer);
  fprintf(1,'OPTION: dpi = %i\n',p.Results.dpi);
  fprintf(1,'OPTION: debuglvl = %i\n',p.Results.debuglvl);
  fprintf(1,'OPTION: Parameters using their defaults:');
  fprintf(1,' %s',p.UsingDefaults{:});
  fprintf(1,'\n');
end

if FigureHasNoText(p)
  return;
end

% Create Action and UndoAction structures, and initialise the length field
% to 0.
Actions.length = 0;
UndoActions.length = 0;
StringCounter = 0;

% PsfragCmds are currently in the order:
% {LatexString, ReplacementString, Alignment, TextSize, Colour,
%   FontAngle (1-italic,0-normal), FontWeight (1-bold,0-normal),
%   FixedWidth (1-true,0-false), LabelType }
PsfragCmds = {};

% Before doing anthing to the figure, make sure it is fully drawn
drawnow;

% Set up the page size to be printed
Units = get(p.Results.handle,'Units');
set(p.Results.handle,'Units','centimeters');
Pos = get(p.Results.handle,'Position');
set(p.Results.handle,'Units',Units);
SetUnsetProperties('PaperUnits to cm, PaperPos to Pos',p.Results.handle,...
  'PaperUnits','centimeters','PaperPosition',Pos);

% Process the picture
ProcessFigure(p.Results.handle);

% Apply the actions resulting from the processing
if p.Results.debuglvl >= STEP_THROUGH_ACTIONS
  disp('STEPPING: Starting to apply actions');
  for ii=1:Actions.length
    fprintf(1,'STEPPING: Press space to apply: %s\n',Actions.( ACTION_DESC_NAME(ii) ));
    pause;
    Actions.( ACTION_FUNC_NAME(ii) )();
  end
  disp('STEPPING: Finished applying actions');
else
  for ii=1:Actions.length
    Actions.( ACTION_FUNC_NAME(ii) )();
  end
end

if p.Results.debuglvl >= PAUSE_BEFORE_PRINT
  disp('PAUSING: Paused before printing');
  pause;
end

% Test to see if the directory (if specified) exists
[pathstr,namestr] = fileparts(FileName);
if ~isempty(pathstr)
  if ~exist(['./',pathstr],'dir')
    mkdir(pathstr);
  end
  % Tidy up the FileName
  FileName = [pathstr,filesep,namestr];
else
  FileName = namestr;
end

dpiswitch = ['-r',num2str( round( p.Results.dpi ) )];
% Unless over-ridden, check to see if 'renderermode' is 'manual'
renderer = lower( p.Results.renderer );
if any( strcmpi(p.UsingDefaults,'renderer') )
  if strcmpi(get(p.Results.handle,'renderermode'),'manual')
    renderer = lower( get(p.Results.handle,'renderer') );
    if p.Results.debuglvl >= SHOW_OPTIONS
      fprintf(1,['OPTION: Renderer being overridden by manual renderermode.\n',...
        '        It is now %s.\n'],renderer);
    end
  end
end

if strcmpi(renderer,'painters')
  % If using default dpi
  if any( strcmpi(p.UsingDefaults,'dpi') )
    current_dpi = 3200;
  else
    current_dpi = p.Results.dpi;
  end

  % Test to see whether the DPI is too high or not.
  temp_units = get(p.Results.handle,'units');
  set(p.Results.handle,'units','inches');
  temp_pos = get(p.Results.handle,'position');
  set(p.Results.handle,'units',temp_units);

  if temp_pos(3) * current_dpi > 32000
    old_dpi = current_dpi;
    current_dpi = 100*floor((30000 / temp_pos(3))/100);
    warning('matlabfrag:ImageTooWide',...
      ['Figure width is too large for %i DPI. Reducing\n',...
      'it to %i DPI.'],old_dpi,current_dpi);
  end

  if temp_pos(4) * current_dpi > 32000
    old_dpi = current_dpi;
    current_dpi = 100*floor((30000 / temp_pos(4))/100);
    warning('matlabfrag:defaultDPI:ImageTooHigh',...
      ['Figure height is too large for %i DPI. Reducing\n',...
      'it to %i DPI.'],old_dpi,current_dpi);
  end

  dpiswitch = sprintf('-r%i',current_dpi);
  clear temp_units temp_pos current_dpi old_dpi

  % Export the image to an eps file
  drawnow;
  %export_fig(FileName, '-eps','-transparent',p.Results.handle) %-buuh does not work correct
  print(p.Results.handle,'-depsc2','-loose',dpiswitch,'-painters',FileName);
  FileWait( [FileName,'.eps'] );
else
  % If using the opengl or zbuffer renderer
  EpsCombine(p.Results.handle,renderer,FileName,dpiswitch,...
    p.Results.debuglvl>=KEEP_TEMPFILE)
end

if p.Results.debuglvl >= PAUSE_AFTER_PRINT
  disp('PAUSING: Paused after printing');
  pause;
end

% Pad the eps if requested
if any( p.Results.epspad )
  fh = fopen([FileName,'.eps'],'r');
  epsfile = fread(fh,inf,'uint8=>char').';
  fclose(fh);
  bb = regexpi(epsfile,'\%\%BoundingBox:\s+(-*\d+)\s+(-*\d+)\s+(-*\d+)\s+(-*\d+)','tokens');
  bb = str2double(bb{1});
  epsfile = regexprep(epsfile,sprintf('%i(\\s+)%i(\\s+)%i(\\s+)%i',bb),...
    sprintf('%i$1%i$2%i$3%i',bb+round(p.Results.epspad.*[-1,-1,1,1])));
  fh = fopen([FileName,'.eps'],'w');
  fwrite(fh,epsfile);
  fclose(fh);
end

% Apply the undo action to restore the image to how
%  was originally
if p.Results.debuglvl >= STEP_THROUGH_ACTIONS
  disp('Starting to apply undo actions');
  for ii=UndoActions.length:-1:1
    fprintf(1,'Press space to unapply: %s\n',UndoActions.( ACTION_DESC_NAME(ii) ));
    pause;
    UndoActions.( ACTION_FUNC_NAME(ii) )();
  end
  disp('Finished applying undo actions');
else
  for ii=UndoActions.length:-1:1
    UndoActions.( ACTION_FUNC_NAME(ii) )();
  end
end

% Flush all drawing operations
drawnow;

% Sort by text size first
[Y,I] = sortrows( cell2mat( PsfragCmds(:,4) ) ); %#ok<*ASGLU> Required for backward compatibility
PsfragCmds = PsfragCmds(I,:);
% Now sort by colour
[Y,I] = sortrows( cell2mat( PsfragCmds(:,5) ), [3 2 1] );
PsfragCmds = PsfragCmds(I,:);
% Now sort by font angle
[Y,I] = sortrows( cell2mat( PsfragCmds(:,6) ) );
PsfragCmds = PsfragCmds(I,:);
% Now sort by font weight
[Y,I] = sortrows( cell2mat( PsfragCmds(:,7) ) );
PsfragCmds = PsfragCmds(I,:);
% Now sort by whether it is 'fixed width'
[Y,I] = sortrows( cell2mat( PsfragCmds(:,8) ) );
PsfragCmds = PsfragCmds(I,:);
% Now sort by label type
[Y,I] = sortrows( PsfragCmds(:,9) );
PsfragCmds = PsfragCmds(I,:);
clear Y

% Finally write the latex-file
try
  fid = fopen([FileName,'.tex'],'w');
  fwrite(fid,TEXHDR);

  writeOutNegXTick = @() fprintf(fid,'\n%%\n\\def\\%s{\\mathord{\\makebox[0pt][r]{$-$}}}',NEGXTICK_COMMAND);

  FontStylePrefix = 'matlabtext';
  FontStyleId = double('A')-1;
  NewFontStyle = 1;
  CurrentColour = [0 0 0];
  CurrentFontSize = 0;
  CurrentWeight = 0;
  CurrentAngle = 0;
  CurrentlyFixedWidth = 0;
  CurrentType = PsfragCmds{1,9};

  fprintf(fid,'\n%%\n%%%% <%s>',CurrentType);
  if strcmpi(CurrentType,'xtick')
    writeOutNegXTick();
  end
  for ii=1:size(PsfragCmds,1)
    % Test to see if the font size has changed
    if ~(CurrentFontSize == PsfragCmds{ii,4})
      CurrentFontSize = PsfragCmds{ii,4};
      NewFontStyle = 1;
    end
    % Test to see if the colour has changed
    if ~all(CurrentColour == PsfragCmds{ii,5})
      CurrentColour = PsfragCmds{ii,5};
      NewFontStyle = 1;
    end
    % Test to see fi the font angle has changed
    if ~(CurrentAngle == PsfragCmds{ii,6})
      CurrentAngle = PsfragCmds{ii,6};
      NewFontStyle = 1;
    end
    % Test to see if the font weight has changed
    if ~(CurrentWeight == PsfragCmds{ii,7})
      CurrentWeight = PsfragCmds{ii,7};
      NewFontStyle = 1;
    end
    % Test to see if 'fixedwidth' has changed
    if ~(CurrentlyFixedWidth == PsfragCmds{ii,8})
      CurrentlyFixedWidth = PsfragCmds{ii,8};
      NewFontStyle = 1;
    end
    % Test to see if 'type' has changed
    if ~strcmpi(CurrentType,PsfragCmds{ii,9})
      fprintf(fid,'\n%%\n%%%% </%s>',CurrentType);
      CurrentType = PsfragCmds{ii,9};
      fprintf(fid,'\n%%\n%%%% <%s>',CurrentType);
      if strcmpi(CurrentType,'xtick')
        writeOutNegXTick();
      end
      if ~NewFontStyle
        fprintf(fid,'\n%%');
      end
    end
    if NewFontStyle
      FontStyleId = FontStyleId + 1;
      if CurrentAngle; Angle = '\itshape';
      else Angle = ''; end;
      if CurrentWeight; Weight = '\bfseries\boldmath';
      else Weight = ''; end;
      if CurrentlyFixedWidth; Fixed = '\ttfamily';
      else Fixed = ''; end;
      fprintf(fid,['\n%%\n\\providecommand\\%s%s{\\color[rgb]{%.3f,%.3f,'...
        '%.3f}\\fontsize{%d}{%d}%s%s%s\\selectfont\\strut}%%'],FontStylePrefix,...
        char(FontStyleId),CurrentColour(1),CurrentColour(2),...
        CurrentColour(3),CurrentFontSize,CurrentFontSize,Angle,Weight,Fixed);
      NewFontStyle = 0;
    end
    fprintf(fid,'\n\\psfrag{%s}',PsfragCmds{ii,2});
    % Only put in positioning information if it is not [bl] aligned
    if ~strcmp(PsfragCmds{ii,3},'bl') || ~strcmp(PsfragCmds{ii,3},'lb')
      fprintf(fid,'[%s][%s]',PsfragCmds{ii,3},PsfragCmds{ii,3});
    end
    fprintf(fid,'{\\%s%s %s}%%',FontStylePrefix,...
      char(FontStyleId),RemoveSpaces(PsfragCmds{ii,1}));
  end
  fprintf(fid,'\n%%\n%%%% </%s>',CurrentType);

  fclose(fid);

catch                %#ok -- needed for r2007a support
  err = lasterror;   %#ok
  if fid > 0
    fclose(fid);
  end
  err.stack.line
  rethrow( err );
end
% All done! Below are the sub-functions

% Find all of the 'text' and 'axes' objects in the
% figure and dispatch the processing of them
  function ProcessFigure(parent)

    % Show all of the hidden handles
    hidden = get(0,'showhiddenhandles');
    set(0,'showhiddenhandles','on');

    % Get all text and axes handles
    axeshandles = findobj(parent,'Type','axes');
    texthandles = findobj(parent,'Type','text');

    % Hide all of the hidden handles again
    set(0,'showhiddenhandles',hidden);

    % Get the position of all the text objects
    textpos = GetTextPos(texthandles);

    % Freeze all axes, and process ticks.
    for jj=1:length(axeshandles)
      ProcessTicks(axeshandles(jj));
    end

    % Process all text.
    for jj=1:length(texthandles)
      ProcessText(texthandles(jj),textpos{jj});
    end
  end

% Get all fo the text object's positions.
  function TextPos = GetTextPos(texthandles)
    TextPos = cell(1,length(texthandles));
    for jj=1:length(texthandles)
      TextPos{jj} = get(texthandles(jj),'position');
      AddUndoAction('Reset text posision', @() set(texthandles(jj),'position', TextPos{jj} ));
    end
  end

% Process a text handle, extracting the appropriate data
%  and creating 'action' functions
  function ProcessText(handle,Pos)
    % Get some of the text properties.
    String = get(handle,'string');
    UserData = get(handle,'UserData');
    UserString = {};
    % Test to see if the text is visible. If not, return.
    if strcmpi(get(handle,'visible'),'off'); return; end;
    % Process the strings alignment options
    [halign,valign] = GetAlignment(handle);
    % Test to see if UserData is valid.
    if ischar(UserData)
      if ~isempty(sscanf(UserData,'%s'))
        UserString = regexp(UserData,[USERDATA_PREFIX,'(.*)'],'tokens');
      end
    end
    % Test for multiline strings (using cells).
    if iscell(String)
      % Error checking. Luckily Matlab is fairly nice with the way it
      % treats its strings in figures.
      assert( size(String,2) == 1 && iscellstr(String),...
        'matlabfrag:WeirdError',['Weird ''String'' formatting.\n',...
        'Please email the author, as this error should not occur.']);
      % If the cell only has 1 element, then do nothing.
      if size(String,1)==1
        String = String{:};
      else
        temp = sprintf('\\begin{tabular}{@{}%c@{}}%s',halign,String{1});
        for jj=2:length(String)
          temp = sprintf('%s\\\\%s',temp,String{jj});
        end
        String = sprintf('%s\\end{tabular}',temp);
      end
    end
    % Test for multiline strings using matrices
    if size(String,1) > 1
      temp = sprintf('\\begin{tabular}{@{}%c@{}}%s',halign,...
        regexprep(String(1,:),' ','~'));
      for jj=2:size(String,1)
        temp = sprintf('%s\\\\%s',temp,...
          regexprep(String(jj,:),' ','~'));
      end
      String = sprintf('%s\\end{tabular}',temp);
    end
    % If there is no text, return.
    if isempty(sscanf(String,'%s')) && isempty(UserString); return; end;
    % Retrieve the common options
    [FontSize,FontAngle,FontWeight,FixedWidth] = CommonOptions(handle);
    % Assign a replacement action for the string
    CurrentReplacement = ReplacementString();
    SetUnsetProperties('Replacing text string',handle,'String',CurrentReplacement);
    % Check for a 'UserData' property, which replaces the string with latex
    if ~isempty(UserString)
      String = cell2mat(UserString{:});
    end
    % Replacement action for the interpreter
    if ~strcmpi(get(handle,'interpreter'),'none')
      SetUnsetProperties('Text Interpreter to none',handle,'interpreter','none');
    end
    % Make sure the final position is the same as the original one
    AddAction('Reset text Pos', @() set(handle,'position',Pos) );

    % Get the text colour
    Colour = get(handle,'color');
    % Finally create the replacement command
    AddPsfragCommand(String,CurrentReplacement,[valign,halign],...
      FontSize,Colour,FontAngle,FontWeight,FixedWidth,'text');
  end

% Processes the position, position mode and 'ticks' of an axis, then returns.
%  Don't do anything if it is a legend
  function ProcessTicks(handle)
    % Return if nothing to do.
    if strcmpi(get(handle,'visible'),'off'); return; end;
    % If legend, freeze the axes and return.
    if strcmpi(get(handle,'tag'),'legend');
      SetUnsetProperties('Legend Pos to current Pos',...
        handle,'Position', get(handle,'Position') );
      return;
    end;
    % Make sure figure doesn't resize itself while we are messing with it.
    for jj=['x' 'y' 'z']
      AutoTickLabel.(jj) = strcmpi(get(handle,[jj,'ticklabelmode']),'auto');
    end
    SetUnsetProperties('TickModes to manual',handle,...
      'xlimmode','manual','ylimmode','manual','zlimmode','manual',...
      'xtickmode','manual','ytickmode','manual','ztickmode','manual',...
      'xticklabelmode','manual','yticklabelmode','manual','zticklabelmode','manual');
    SetUnsetProperties('Fix Axes Pos',handle,'position', get(handle,'position') );
    try
      hlist = get(handle,'ScribeLegendListeners');
      SetUnsetProperties('Disable legend fontname listener',hlist.fontname,'enabled','off');
    catch                 %#ok -- required for r2007a support
      err = lasterror;    %#ok
      if ~isempty(regexpi(err.message,'''enabled'''))
        error('matlabfrag:legendlistener',...
          ['Oops, it looks like Matlab has changed the way it does legend\n',...
          'callbacks. Please let me know if you see this via ',...
          'email']);
      end
    end
    % Extract common options.
    [FontSize,FontAngle,FontWeight,FixedWidth] = CommonOptions(handle);
    SetUnsetProperties('Axes font to fixed-width',handle,'FontName','fixedwidth');
    FontName = 'fixedwidth';
    % Loop through all axes
    for jj = ['x' 'y' 'z']
      ticklabels = get(handle,[jj,'ticklabel']);
      ticks = get(handle,[jj,'tick']);
      lims = get(handle,[jj,'lim']);
      % If there are no ticks, skip to the next axis
      if isempty(ticks)
        continue;
      end
      % Trim the ticks (if they lay outside lims)
      if AutoTickLabel.(jj)
        ticks = ticks( ticks >= lims(1) );
        ticks = ticks( ticks <= lims(2) );
        SetUnsetProperties('Trimming tick labels',handle,[jj,'tick'],ticks);
      end
      set(handle,[jj,'tickmode'],'manual',[jj,'ticklabelmode'],'manual');
      if ~isempty(ticklabels)
        tickcolour = get(handle,[jj,'color']);

        % Test to see if it is on a logarithmic scale
        if strcmpi(get(handle,[jj,'scale']),'log') && AutoTickLabel.(jj)
          % And all of the values are integers
          ticklabelcell = mat2cell(ticklabels,ones(1,size(ticklabels,1)),size(ticklabels,2));
          if all(~isnan(str2double(ticklabelcell)))
            % If so, make the labels read 10^<TickLabel>
            ticklabels = cellfun(@(x) ['$10^{',RemoveSpaces(x),'}$'],...
              ticklabelcell,'uniformoutput',0);
          end

          % Test to see if there is a common factor
        elseif strcmpi(get(handle,[jj,'scale']),'linear') && AutoTickLabel.(jj)
          for kk=1:size(ticklabels,1)
            % Find the first non-NaN ratio between tick labels and tick
            % values
            scale = ticks(kk)/str2double(ticklabels(kk,:));
            if ~isnan(scale); break; end;
          end

          % If the scale is not 1, then we need to place a marker near the
          % axis
          if abs(scale-1) > 1e-3
            scale = log10(scale);
            % Make sure it is an integer.
            assert( abs(scale-round(scale))<1e-2, 'matlabfrag:AxesScaling:NonInteger',...
              ['Non integer axes scaling.  This is most likely a bug in matlabfrag.\n',...
              'Please let me know the ytick and yticklabel values for this plot.']);
            LatexScale = ['$\times10^{',num2str(round(scale)),'}$'];
            % Test to see if this is a 3D or 2D plot
            if isempty(get(handle,'zticklabel')) &&...
                all( get(handle,'view') == [0 90] )

              %2D Plot... fairly easy.
              % Common required data...
              Xlims = get(handle,'xlim');
              Ylims = get(handle,'ylim');
              XAlignment = get(handle,'XAxisLocation');
              YAlignment = get(handle,'YAxisLocation');
              % 2D plot, so only x and y...
              CurrentReplacement = ReplacementString();

              % X axis scale
              if strcmpi(jj,'x')
                if strcmpi(XAlignment,'bottom');
                  ht = text(Xlims(2),Ylims(1),CurrentReplacement,...
                    'fontsize',FontSize,'fontname',FontName,...
                    'HorizontalAlignment','center','VerticalAlignment','top',...
                    'parent',handle);
                  extent = get(ht,'extent');
                  position = get(ht,'position');
                  set(ht,'position',[position(1) position(2)-1.0*extent(4) position(3)]);
                  Alignment = 'tc';
                else
                  ht = text(Xlims(2),Ylims(2),CurrentReplacement,...
                    'fontsize',FontSize,'fontname',FontName,...
                    'HorizontalAlignment','center','VerticalAlignment','bottom',...
                    'parent',handle);
                  extent = get(ht,'extent');
                  position = get(ht,'position');
                  set(ht,'position',[position(1) position(2)+1.0*extent(4) position(3)]);
                  Alignment = 'bc';
                end

                % Y axis scale
              else
                if strcmpi(XAlignment,'bottom')
                  if strcmpi(YAlignment,'left')
                    ht = text(Xlims(1),Ylims(2),CurrentReplacement,...
                      'fontsize',FontSize,'fontname',FontName,...
                      'HorizontalAlignment','center','VerticalAlignment','bottom',...
                      'parent',handle);
                  else
                    ht = text(Xlims(2),Ylims(2),CurrentReplacement,...
                      'fontsize',FontSize,'fontname',FontName,...
                      'HorizontalAlignment','center','VerticalAlignment','bottom',...
                      'parent',handle);
                  end
                  extent = get(ht,'extent');
                  position = get(ht,'position');
                  set(ht,'position',[position(1) position(2)+0.5*extent(4) position(3)]);
                  Alignment = 'bc';
                else
                  if strcmpi(YAlignment,'left')
                    ht = text(Xlims(1),Ylims(1),CurrentReplacement,...
                      'fontsize',FontSize,'fontname',FontName,...
                      'HorizontalAlignment','center','VerticalAlignment','top',...
                      'parent',handle);
                  else
                    ht = text(Xlims(2),Ylims(1),CurrentReplacement,...
                      'fontsize',FontSize,'fontname',FontName,...
                      'HorizontalAlignment','center','VerticalAlignment','top',...
                      'parent',handle);
                  end
                  extent = get(ht,'extent');
                  position = get(ht,'position');
                  set(ht,'position',[position(1) position(2)-0.5*extent(4) position(3)]);
                  Alignment = 'tc';
                end
              end

              % Create the replacement command
              AddPsfragCommand(LatexScale,CurrentReplacement,Alignment,FontSize,...
                tickcolour,FontAngle,FontWeight,FixedWidth,[jj,'scale']);
              % Delete the label
              AddUndoAction('Delete axis scale', @() delete(ht) );
            else
              % Why is this so hard?
              warning('matlabfrag:scaled3Daxis',...
                ['It looks like your %s axis is scaled on a 3D plot. Unfortunately\n',...
                'these are very hard to handle, so there may be a problem with\n',...
                'its placement. If you know of a better algorithm for placing it,\n',...
                'please let me know at zebb.prime+matlabfrag@gmail.com',...
                ],jj);
              % :-(
              CurrentReplacement = ReplacementString();
              Xlim = get(handle,'xlim');
              Ylim = get(handle,'ylim');
              Zlim = get(handle,'zlim');
              axlen = @(x) x(2)-x(1);
              switch lower( jj )
                case 'x'
                  ht = text(Xlim(1)+0.6*axlen(Xlim),...
                    Ylim(1)-0.3*axlen(Ylim),...
                    Zlim(1),...
                    CurrentReplacement,'fontsize',FontSize,...
                    'fontname',FontName,'parent',handle);
                  Alignment = 'bl';
                case 'y'
                  ht = text(Xlim(1)-0.3*axlen(Xlim),...
                    Ylim(1)+0.6*axlen(Ylim),...
                    Zlim(1),...
                    CurrentReplacement,'fontsize',FontSize,...
                    'fontname',FontName,'horizontalalignment',...
                    'right','parent',handle);
                  Alignment = 'br';
                case 'z'
                  ht = text(Xlim(1),Ylim(2),Zlim(2)+0.2*axlen(Zlim),...
                    CurrentReplacement,'fontsize',FontSize,...
                    'fontname',FontName,'horizontalalignment',...
                    'right','parent',handle);
                  Alignment = 'br';
                otherwise
                  error('matlabfrag:wtf',['Bad axis; this error shouldn''t happen.\n',...
                    'please report it as a bug.']);
              end
              % Create the replacement command
              AddPsfragCommand(LatexScale,CurrentReplacement,Alignment,FontSize,...
                tickcolour,FontAngle,FontWeight,FixedWidth,[jj,'scale']);
              % Delete the label
              AddUndoAction('DeleteAxesScale', @() delete(ht) );
            end
          end
        end

        % Test whether all of the ticks are numbers, if so wrap them in $
        if ~iscell(ticklabels)
          ticklabels = mat2cell(ticklabels,ones(1,size(ticklabels,1)),size(ticklabels,2));
        end
        TicksAreNumbers = 1;
        for kk=1:size(ticklabels,1)
          if isempty(ticklabels{kk,:})
            continue;
          end
          if isnan(str2double(ticklabels{kk,:}))
            TicksAreNumbers = 0;
            break;
          end
        end
        if TicksAreNumbers
          if strcmpi(jj,'x')
            for kk=1:size(ticklabels)
              if isempty(ticklabels{kk,:})
                continue;
              end
              ticklabels{kk,:} = ['$',...
              RemoveSpaces( regexprep(ticklabels{kk,:},'-',['\\',NEGXTICK_COMMAND,' ']) ),...
              '$'];
            end
          else
            for kk=1:size(ticklabels)
              if isempty(ticklabels{kk,:})
                continue;
              end
              ticklabels{kk,:} = ['$',RemoveSpaces(ticklabels{kk,:}),'$'];
            end
          end
        end
        clear TicksAreNumbers

        tickreplacements = cell(1,size(ticklabels,1));
        % Process the X and Y tick alignment
        if ~strcmpi(jj,'z')
          switch get(handle,[jj,'axislocation'])
            case 'left'
              tickalignment = 'rc';
            case 'right'
              tickalignment = 'lc';
            case 'bottom'
              tickalignment = 'ct';
            case 'top'
              tickalignment = 'cb';
            otherwise
              tickalignment = 'cr';
              warning('matlabfrag:UnknownAxisLocation',...
                'Unknown axis location defaulting to ''cr''');
          end
        else
        % Fixed Z tick alignment
          tickalignment = 'cr';
        end

        % Now process the actual tick labels themselves...
        for kk=1:size(ticklabels,1)
          if isempty( ticklabels{kk,:} )
            tickreplacements{kk} = '';
            continue;
          end
          tickreplacements{kk} = ReplacementString();
          AddPsfragCommand(ticklabels{kk,:},tickreplacements{kk},...
            tickalignment,FontSize,tickcolour,FontAngle,FontWeight,...
            FixedWidth,[jj,'tick']);
        end
        % Now add the replacement action...
        SetUnsetProperties('Tick replacement',handle,[jj,'ticklabel'],tickreplacements);
      end
    end
  end    % of ProcessTicks

% Get the next replacement string
  function CurrentReplacement = ReplacementString()
    CurrentReplacement = sprintf(REPLACEMENT_FORMAT,StringCounter);
    StringCounter = StringCounter+1;
  end

% Extract and process the options that are common to text labels as
% well as axes ticks
  function [FontSize,FontAngle,FontWeight,FixedWidth] = CommonOptions(handle)
    % First get the fontsize (making sure it is in points)
    temp_prop = get(handle,'FontUnits');
    if ~strcmpi(temp_prop,'points')
      SetUnsetProperties('FontUnits to points',handle,'FontUnits','points');
    end
    FontSize = get(handle,'FontSize');
% %     SetUnsetProperties('FontSize to 10',handle,'Fontsize',10);
    % Now get the font angle (read - italics)
    switch get(handle,'FontAngle')
      case 'normal'
        FontAngle = 0;
      case 'italic'
        FontAngle = 1;
      case 'oblique'
        warning('matlabfrag:ObliqueFont',...
          'Nobody in their right mind uses Oblique font. Defaulting to italic.');
        FontAngle = 1;
      otherwise
        warning('matlabfrag:UnknownFontType',...
          'Unknown FontAngle for the string "%s"',get(handle,'String'));
        FontAngle = 0;
    end
% %     if FontAngle
% %       SetUnsetProperties('FontAngle to normal',handle,'FontAngle','normal');
% %     end
    % Now get the FontWeight (read - bold)
    switch get(handle,'FontWeight')
      case 'light'
        warning('matlabfrag:LightFontNotSupported',...
          'Light FontWeight does not really translate to LaTeX... Defaulting to normal.');
        FontWeight = 0;
      case 'normal'
        FontWeight = 0;
      case 'demi'
        warning('matlabfrag:DemiFontNotSupported',...
          'Demi FontWeight does not really translate to LaTeX... Defaulting to normal.');
        FontWeight = 0;
      case 'bold'
        FontWeight = 1;
      otherwise
        warning('matlabfrag:UnknownFontWeight',...
          'Unknown FontWeight for the string %s',get(handle,'String'));
    end
% %     if FontWeight
% %       SetUnsetProperties('FontWeight to normal',handle,'FontWeight','normal');
% %     end
    % Test to see if the font is 'fixed width'
    if strcmpi(get(handle,'FontName'),'FixedWidth')
      FixedWidth = 1;
    else
      FixedWidth = 0;
    end
% %     if ~FixedWidth
% %       SetUnsetProperties('Set text to FixedWidth',handle,'FontName','fixed-width');
% %     end
  end

% Adds a PsFrag command to the cell. This is a function to ensure allow a
%  standard calling convention to be established.
  function AddPsfragCommand(LatexString,ReplacementString,Alignment,...
      FontSize,Colour,FontAngle,FontWeight,FixedWidth,Type)
    PsfragCmds(size(PsfragCmds,1)+1,:) = {LatexString,ReplacementString,...
      Alignment,FontSize,Colour,FontAngle,FontWeight,FixedWidth,Type};
  end

% Set and then unset some handle properties using 'Actions' and
% 'UndoActions'
  function SetUnsetProperties(description,handle,varargin)
    Props = varargin(1:2:end);
    PropVals = varargin(2:2:end);
    TempPropVals = get(handle,Props);
    AddAction(description, @() set(handle,Props,PropVals) );
    AddUndoAction(description, @() set(handle,Props,TempPropVals) );
  end

% Add an 'action' function to the list of actions to perform before the
%  image is saved.
  function AddAction(description,action)
    Actions.length = Actions.length + 1;
    Actions.( ACTION_FUNC_NAME( Actions.length ) ) = action;
    Actions.( ACTION_DESC_NAME( Actions.length ) ) = description;
  end

% Adds an 'undo-action' function to the list... these get processed after
%  the image has been saved, to restore the screen state.
  function AddUndoAction(description,action)
    UndoActions.length = UndoActions.length + 1;
    UndoActions.( ACTION_FUNC_NAME( UndoActions.length ) ) = action;
    UndoActions.( ACTION_DESC_NAME( UndoActions.length ) ) = description;
  end

% Remove leading and trailing edge white spaces
% from any string.
  function cropped_string = RemoveSpaces(string)
    if iscell(string)
      string = string{:};
    end
    if isempty( string )
      cropped_string = string;
      return;
    end
    if all( string == ' ' )
      cropped_string = '';
      return;
    end
    I = regexp(string,'[^\s]');
    cropped_string = string(I(1):I(end));
    if cropped_string(end) == '\'
      cropped_string = [ cropped_string, ' ' ];
    end
  end

  function [halign,valign] = GetAlignment(handle)
    HAlign = get(handle,'HorizontalAlignment');
    switch HAlign
      case 'left'
        halign = 'l';
      case 'right'
        halign = 'r';
      case 'center'
        halign = 'c';
      otherwise
        warning('matlabfrag:UnknownHorizAlign',...
          'Unknown text horizontal alignment for "%s", defaulting to left',string);
        halign = 'l';
    end
    VAlign = get(handle,'VerticalAlignment');
    switch VAlign
      case {'baseline','bottom','base'}
        valign = 'b';
      case {'top','cap'}
        valign = 't';
      case {'middle'}
        valign = 'c';
      otherwise
        warning('matlabfrag:UnknownVertAlign',...
          'Unknown text vertical alignment for "%s", defaulting to bottom',string);
        valign = 'l';
    end
  end

% Busy waits for a file to finish being created. This is necessary because
% on some platforms the file isn't available immediately after performing a
% print.
  function FileWait(filename)
    counter = 0;
    while ~exist(filename,'file')
      pause(0.05);
      assert( counter < 100, 'matlabfrag:filetimeout',...
        'File Timeout. This occured after printing %s and trying to then read it.',filename);
      counter = counter + 1;
    end
  end
% Print two versions of the file, one renderered with the renderer of
% choice, and another rendererd with painters. Then perform some epscombine
% magic to recombine them.
  function EpsCombine(handle,renderer,filename,dpiswitch,keep_tempfile)
    TEXTOBJ_REGEXP = ['-?\d+\s+-?\d+\s+mt(\s+-?\d+\s+rotate)?',...
      '\s+\(.+?\)\s+s',...
      '(\s+-?\d+\s+rotate)?'];
    TEXTHDR_REGEXP = '%%IncludeResource:\s+font.*?\n.?\n';
    if keep_tempfile
      tmp_file = [filename,'-painters'];
    else
      tmp_file = tempname;
    end

    % Show all of the hidden handles
    hidden = get(0,'showhiddenhandles');
    set(0,'showhiddenhandles','on');

    ht = findobj(handle,'type','text');
    ht = findobj(ht,'visible','on');
    ha = findobj(handle,'type','axes');

    % Hide all of the text handles again
    set(0,'showhiddenhandles',hidden);

    % Make the text invisible
    set(ht,'visible','off');
    hnam = @(x) ['h',num2str(x)];
    for jj=1:length(ha)
      tickvals.(hnam(jj)).xtl = get(ha(jj),'xticklabel');
      tickvals.(hnam(jj)).ytl = get(ha(jj),'yticklabel');
      tickvals.(hnam(jj)).ztl = get(ha(jj),'zticklabel');
      set(ha(jj),'xticklabel','','yticklabel','','zticklabel','');
    end
    % Now print it.
    drawnow;
    print(handle,'-depsc2','-loose',dpiswitch,...
      ['-',renderer],filename);
    FileWait([filename,'.eps']);
    % Restore the text
    set(ht,'visible','on');
    for jj=1:length(ha)
      set(ha(jj),'xticklabel',tickvals.(hnam(jj)).xtl);
      set(ha(jj),'yticklabel',tickvals.(hnam(jj)).ytl);
      set(ha(jj),'zticklabel',tickvals.(hnam(jj)).ztl);
    end
    % Now print a painters version.
    drawnow;
    print(handle,'-depsc2','-loose',dpiswitch,...
      '-painters',tmp_file);
    FileWait([tmp_file,'.eps']);
    % Open it up and extract the text
    try
      fh = fopen([tmp_file,'.eps'],'r');
      paintersfile = fread(fh,inf,'uint8=>char').';
      fh = fclose(fh);
    catch                  %#ok -- required for r2007a support
      err = lasterror;     %#ok
      if fh > 0
        fh = close(fh);
      end
      rethrow( err );
    end
    if ~keep_tempfile
      delete([tmp_file,'.eps']);
    end
    textobj = regexpi(paintersfile,TEXTOBJ_REGEXP,'match');
    textobjpos = regexpi(paintersfile,TEXTOBJ_REGEXP);
    texthdr = regexpi(paintersfile,TEXTHDR_REGEXP,'match');
    texthdrpos = regexpi(paintersfile,TEXTHDR_REGEXP);
    textData = cell(length(textobjpos)+length(texthdrpos),2);
    textData(:,1) = num2cell([texthdrpos.';textobjpos.']);
    textData(:,2) = [texthdr,textobj].';
    [Ysort,Isort] = sortrows( cell2mat( textData(:,1) ) );
    textData = textData(Isort,:);

    % Open up the target file, and read the contents.
    try
      fh = fopen([filename,'.eps'],'r');
      epsfile = fread(fh,inf,'uint8=>char').';
      fh = fclose(fh);
    catch                  %#ok -- this is required for r2007a support
      err = lasterror;     %#ok
      if fh > 0
        fh = close(fh);
      end
      rethrow( err );
    end
    % Insert the new text
    findex = regexp(epsfile,'end %%Color Dict');
    epsfile = sprintf('%s\n\n%s\n%s',...
      epsfile(1:findex-1),...
      sprintf('%s\n',textData{:,2}),...
      epsfile(findex:end));
    try
      fh = fopen([filename,'.eps'],'w');
      fwrite(fh,epsfile);
      fh = fclose(fh);
    catch                %#ok -- this is required for r2007a support
      err = lasterror;   %#ok
      if fh > 0
        fh = fclose(fh);
      end
      rethrow( err );
    end
  end

% Test to see if there is any text in the figure
  function NoText = FigureHasNoText(p)
    NoText = 0;

    hidden = get(0,'showhiddenhandles');
    set(0,'showhiddenhandles','on');
    tempht = findobj(p.Results.handle,'type','text','visible','on');
    tempha = findobj(p.Results.handle,'type','axes','visible','on');
    set(0,'showhiddenhandles',hidden);

    for kk=tempht.'
      temptext = get(kk,'string');
      if ischar(temptext)
        temptext = mat2cell(temptext,ones(1,size(temptext,1)));
      end
      if isempty( regexp( temptext, '\S', 'once' ));
        tempht = setxor(tempht,kk);
      end
    end

    for kk=tempha.'
      if isempty( get(kk,'xticklabel') )
        if isempty( get(kk,'yticklabel') )
          if isempty( get(kk,'zticklabel') )
            tempha = setxor(tempha,kk);
          end
        end
      end
    end

    if isempty(tempht) && isempty(tempha)
      % No Text! Why are you using this then?
      warning('matlabfrag:noText',['No text in image. You would be better off ',...
        'using a function like savefig.\n',...
        '.tex file will not be created.']);

      % Set up the figure
      OrigUnits = get(p.Results.handle,'units');
      set(p.Results.handle,'units','centimeters');
      Pos = get(p.Results.handle,'position');
      OrigPPos = get(p.Results.handle,{'paperunits','paperposition'});
      set(p.Results.handle,'paperunits','centimeters','paperposition',Pos);

      % Test to see if the directory (if specified) exists
      [pathstr,namestr] = fileparts(p.Results.FileName);
      if ~isempty(pathstr)
        if ~exist(['./',pathstr],'dir')
          mkdir(pathstr);
        end
        % Tidy up the FileName
        FileName = [pathstr,filesep,namestr];
      else
        FileName = namestr;
      end

      % Print the image
      print(p.Results.handle,'-depsc2',['-',p.Results.renderer],...
        sprintf('-r%i',p.Results.dpi),'-loose',FileName);

      % Restore the figure
      set(p.Results.handle,'units',OrigUnits,'paperunits',...
        OrigPPos{1},'paperposition',OrigPPos{2});

      NoText = 1;
    end
  end

end % of matlabfrag(FileName,p.Results.handle)


text:
using System;
using System.Collections.Generic;
using Cottle.Documents.Simple.Evaluators;
using Cottle.Documents.Simple.Nodes;
using Cottle.Documents.Simple.Nodes.AssignNodes;

namespace Cottle.Documents.Simple
{
    internal static class Compiler
    {
        public static INode Compile(Statement statement)
        {
            return Compiler.CompileStatement(statement);
        }

        private static IEvaluator CompileExpression(Expression expression)
        {
            switch (expression.Type)
            {
                case ExpressionType.Access:
                    return new AccessEvaluator(Compiler.CompileExpression(expression.Source),
                        Compiler.CompileExpression(expression.Subscript));

                case ExpressionType.Constant:
                    return new ConstantEvaluator(expression.Value);

                case ExpressionType.Invoke:
                    var arguments = new IEvaluator[expression.Arguments.Count];

                    for (var i = 0; i < arguments.Length; ++i)
                        arguments[i] = Compiler.CompileExpression(expression.Arguments[i]);

                    return new InvokeEvaluator(Compiler.CompileExpression(expression.Source), arguments);

                case ExpressionType.Map:
                    var elements = new KeyValuePair<IEvaluator, IEvaluator>[expression.Elements.Count];

                    for (var i = 0; i < elements.Length; ++i)
                    {
                        var key = Compiler.CompileExpression(expression.Elements[i].Key);
                        var value = Compiler.CompileExpression(expression.Elements[i].Value);

                        elements[i] = new KeyValuePair<IEvaluator, IEvaluator>(key, value);
                    }

                    return new MapEvaluator(elements);

                case ExpressionType.Symbol:
                    return new SymbolEvaluator(expression.Value);

                default:
                    throw new ArgumentOutOfRangeException(nameof(expression));
            }
        }

        private static INode CompileStatement(Statement statement)
        {
            switch (statement.Type)
            {
                case StatementType.AssignFunction:
                    return new FunctionAssignNode(statement.Key, statement.Arguments,
                        Compiler.CompileStatement(statement.Body), statement.Mode);

                case StatementType.AssignRender:
                    return new RenderAssignNode(statement.Key, Compiler.CompileStatement(statement.Body),
                        statement.Mode);

                case StatementType.AssignValue:
                    return new ValueAssignNode(statement.Key, Compiler.CompileExpression(statement.Operand),
                        statement.Mode);

                case StatementType.Composite:
                    var nodes = new List<INode>();

                    for (; statement.Type == StatementType.Composite; statement = statement.Next)
                        nodes.Add(Compiler.CompileStatement(statement.Body));

                    nodes.Add(Compiler.CompileStatement(statement));

                    return new CompositeNode(nodes);

                case StatementType.Dump:
                    return new DumpNode(Compiler.CompileExpression(statement.Operand));

                case StatementType.Echo:
                    return new EchoNode(Compiler.CompileExpression(statement.Operand));

                case StatementType.For:
                    return new ForNode(Compiler.CompileExpression(statement.Operand), statement.Key, statement.Value,
                        Compiler.CompileStatement(statement.Body),
                        statement.Next.Type != StatementType.None ? Compiler.CompileStatement(statement.Next) : null);

                case StatementType.If:
                    var branches = new List<KeyValuePair<IEvaluator, INode>>();

                    for (; statement.Type == StatementType.If; statement = statement.Next)
                    {
                        var condition = Compiler.CompileExpression(statement.Operand);
                        var body = Compiler.CompileStatement(statement.Body);

                        branches.Add(new KeyValuePair<IEvaluator, INode>(condition, body));
                    }

                    var fallback = statement.Type != StatementType.None ? Compiler.CompileStatement(statement) : null;

                    return new IfNode(branches, fallback);

                case StatementType.Literal:
                    return new LiteralNode(statement.Value);

                case StatementType.None:
                    return new LiteralNode(string.Empty);

                case StatementType.Return:
                    return new ReturnNode(Compiler.CompileExpression(statement.Operand));

                case StatementType.Unwrap:
                    throw new NotImplementedException(
                        $"'unwrap' is not supported with {nameof(SimpleDocument)}, use {nameof(Document)}.{nameof(Document.CreateDefault)} instead");

                case StatementType.While:
                    return new WhileNode(Compiler.CompileExpression(statement.Operand),
                        Compiler.CompileStatement(statement.Body));

                case StatementType.Wrap:
                    throw new NotImplementedException(
                        $"'wrap' is not supported with {nameof(SimpleDocument)}, use {nameof(Document)}.{nameof(Document.CreateDefault)} instead");

                default:
                    throw new ArgumentOutOfRangeException(nameof(statement));
            }
        }
    }
}


text:
apt-get -qqy update
apt-get -qqy install postgresql python-psycopg2
apt-get -qqy install python-sqlalchemy
apt-get -qqy install python-pip
pip install werkzeug
pip install flask
pip install Flask-Login
pip install oauth2client
pip install requests
pip install httplib2


text:
{% extends 'base.html' %}
{% load staticfiles %}
{% block 'header_scripts' %}

{% endblock%}

{% block 'content' %}

Sorry, seems you have somehow reached a page that does not exist...

    You will be redirected to my homepage in  seconds

    Sincerely,

    Joe

{% endblock %}


text:
class Profile < ApplicationRecord
  has_attached_file :avatar, styles: { medium: '300x>', thumbnail: '100x>' }
  validates_attachment_content_type :avatar, content_type: %r{^image\/.*}
  do_not_validate_attachment_file_type :avatar

  validates_presence_of :user_id
  validates_presence_of :avatar
end


text:
package org.gradle.platform.base;

import org.gradle.api.Incubating;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Declares that a custom {@link org.gradle.platform.base.BinarySpec} type.
 *
 * The following example demonstrates how to register a custom component type using a plugin with a
 * {@link org.gradle.platform.base.BinaryType} annotation.
 *
 * <pre autoTested=''>
 * import org.gradle.model.*
 * import org.gradle.model.collection.*
 *
 * interface SampleBinary extends BinarySpec {}
 * class DefaultSampleBinary extends BaseBinarySpec implements SampleBinary {}
 *
 * apply plugin: MySamplePlugin
 *
 * class MySamplePlugin implements Plugin<Project> {
 *     void apply(final Project project) {}
 *
 *     {@literal @}RuleSource
 *     static class ComponentModel {
 *         {@literal @}BinaryType
 *         void defineBinaryType(BinaryTypeBuilder<SampleBinary> builder) {
 *             builder.defaultImplementation(DefaultSampleBinary)
 *         }
 *     }
 * }
 * </pre>
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Incubating
public @interface BinaryType {
}


text:
using System;
using Cake.Core.Scripting;
using Cake.Host.Scripting;

namespace Cake.Host.Commands
{
    /// <summary>
    /// A command that dry runs a build script.
    /// </summary>
    public sealed class DryRunCommand : ICommand
    {
        private readonly IScriptRunner _scriptRunner;
        private readonly DryRunScriptHost _host;

        // Delegate factory used by Autofac.
        public delegate DryRunCommand Factory();

        public DryRunCommand(IScriptRunner scriptRunner, DryRunScriptHost host)
        {
            _scriptRunner = scriptRunner;
            _host = host;
        }

        public bool Execute(CakeOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            _scriptRunner.Run(_host, options.Script, options.Arguments);
            return true;
        }
    }
}


text:
package com.google.gerrit.server.schema;

import static com.google.common.truth.Truth.assertThat;

import com.google.gerrit.extensions.api.GerritApi;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.meta.MetaDataUpdate;
import com.google.gerrit.server.project.ProjectConfig;
import com.google.gerrit.testing.InMemoryTestEnvironment;
import com.google.gerrit.testing.TestUpdateUI;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.junit.Rule;
import org.junit.Test;

public class Schema_161_to_162_Test {
  @Rule public InMemoryTestEnvironment testEnv = new InMemoryTestEnvironment();

  @Inject private AllProjectsName allProjectsName;
  @Inject private AllUsersName allUsersName;
  @Inject private GerritApi gApi;
  @Inject private GitRepositoryManager repoManager;
  @Inject private Schema_162 schema162;
  @Inject private ReviewDb db;
  @Inject @GerritPersonIdent private PersonIdent serverUser;

  @Test
  public void skipCorrectInheritance() throws Exception {
    assertThatAllUsersInheritsFrom(allProjectsName.get());
    ObjectId oldHead;
    try (Repository git = repoManager.openRepository(allUsersName)) {
      oldHead = git.findRef(RefNames.REFS_CONFIG).getObjectId();
    }

    schema162.migrateData(db, new TestUpdateUI());

    // Check that the parent remained unchanged and that no commit was made
    assertThatAllUsersInheritsFrom(allProjectsName.get());
    try (Repository git = repoManager.openRepository(allUsersName)) {
      assertThat(oldHead).isEqualTo(git.findRef(RefNames.REFS_CONFIG).getObjectId());
    }
  }

  @Test
  public void fixIncorrectInheritance() throws Exception {
    String testProject = gApi.projects().create("test").get().name;
    assertThatAllUsersInheritsFrom(allProjectsName.get());

    try (Repository git = repoManager.openRepository(allUsersName);
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git)) {
      ProjectConfig cfg = ProjectConfig.read(md);
      cfg.getProject().setParentName(testProject);
      md.getCommitBuilder().setCommitter(serverUser);
      md.getCommitBuilder().setAuthor(serverUser);
      md.setMessage("Test");
      cfg.commit(md);
    } catch (ConfigInvalidException | IOException ex) {
      throw new OrmException(ex);
    }
    assertThatAllUsersInheritsFrom(testProject);

    schema162.migrateData(db, new TestUpdateUI());

    assertThatAllUsersInheritsFrom(allProjectsName.get());
  }

  private void assertThatAllUsersInheritsFrom(String parent) throws Exception {
    assertThat(gApi.projects().name(allUsersName.get()).access().inheritsFrom.name)
        .isEqualTo(parent);
  }
}


text:
title:  Prísaha
date:   30/10/2019
---

>

> 12Nato odvetili: Vrátime a nebudeme od nich nič požadovať. Urobíme, ako vravíš. Zavolal som kňazov, pred ktorými som ich zaviazal prísahou, že budú konať podľa tohto sľubu. 13Vytriasol som aj záhyby svojho rúcha a povedal som: Nech Boh takto vytrasie z domu i majetku každého, kto nedodrží toto slovo. Nech bude takto vytrasený a prázdny. Nato celý zbor prisvedčil: Amen! Potom oslavovali Hospodina. A ľud urobil, ako sľúbil.  (Neh 5,12.13)

`Uvažuj o texte Neh 5,12.13. Ako rozumieš slovám kliatby, ktorú Nehemiáš vyslovil nad tými, čo by sa rozhodli svoju prísahu porušiť?`

Hoci šľachtici a hodnostári súhlasili s tým, že vrátia, čo si nespravodlivo privlastnili, Nehemiáš sa neuspokojil s obyčajným sľubom. Chcel mať istotu, a preto ich zaviazal prísahou pred kňazmi. Takýto postup dal celému konaniu právne záväznú platnosť pre prípad, že by bolo potrebné v budúcnosti sa naň odvolať. Prečo však Nehemiáš vyslovil slová kliatby? Išlo o symbolický čin, pri ktorom si najprv urobil záhyby na rúchu, akoby v ňom niečo mal, a potom si to vytriasol ako znamenie, že sa toho zbavil. Vyjadril tým, že každý, kto by nerešpektoval prijatú prísahu, príde o všetko. V tom čase bolo zvykom vysloviť kliatbu, aby sa dodalo vážnosti určitému zákonu alebo pravidlu. Ľudia si zároveň dávali väčší pozor na dodržiavanie zákona, ktorého porušenie bolo priamo spojené s kliatbou. Nehemiáš očividne cítil, že ide naozaj o vážnu vec. Rozhodol sa preto vykonať radikálne kroky, aby čo najviac zvýšil pravdepodobnosť, že celé jeho snaženie dopadne úspešne.

**Uvažuj o svätosti prísahy (sľubu) pre ľudí spomenutých v týchto starozmluvných veršoch. Pokús sa zhrnúť svoje pozorovania vlastnými slovami.**

`4Moj 30,3`

`5Moj 23,22-24`

`Kaz 5,4.5`

`3Moj 19,12`

`1Moj 26,31`

Slovo a reč sú mocnými darmi, ktoré Boh dal ľudstvu. Je to niečo úplne odlišné od toho, čo nachádzame vo svete zvierat. Naše slová majú veľkú moc – dokonca moc života a smrti. Preto potrebujeme byť veľmi opatrní v tom, čo a komu hovoríme, aké sľuby dávame a čo sa zaväzujeme urobiť. Okrem toho je dôležité, aby naše činy boli v súlade s našimi slovami. Mnoho ľudí sa odvrátilo od kresťanstva len preto, že slová niektorých kresťanov síce zneli zbožne, ale ich činy sa s nimi nezhodovali, alebo boli v ich priamom rozpore.

`Uvažuj o vplyve svojich slov na druhých ľudí. Ako sa môžeš naučiť opatrnosti v tom, čo hovoríš, kedy to hovoríš a ako to hovoríš?`


text:
/**
 * @file Manages Salesforce Chatter REST API calls
 * @author Shinichi Tomita <shinichi.tomita@gmail.com>
 */

var util = require('util'),
    _ = require('underscore'),
    Promise = require('./promise');

/**
 * API class for Chatter REST API call
 *
 * @class
 * @param {Connection} conn Connection
 */
var Chatter = module.exports = function(conn) {
  this._conn = conn;
};

/**
 * Sending request to API endpoint
 * @private
 */
Chatter.prototype._request = function(params, callback) {
  if (/^(put|post|patch)$/i.test(params.method)) {
    if (_.isObject(params.body)) {
      params.headers = {
        "Content-Type": "application/json"
      };
      params.body = JSON.stringify(params.body);
    }
  }
  params.url = this._normalizeUrl(params.url);
  return this._conn._request(params, callback);
};

/**
 * Convert path to site root relative url
 * @private
 */
Chatter.prototype._normalizeUrl = function(url) {
  if (url.indexOf('/chatter/') === 0 || url.indexOf('/connect/') === 0) {
    return '/services/data/v' + this._conn.version + url;
  } else if (/^\/v[\d]+\.[\d]+\//.test(url)) {
    return '/services/data' + url;
  } else if (url.indexOf('/services/') !== 0 && url[0] === '/') {
    return '/services/data/v' + this._conn.version + '/chatter' + url;
  } else {
    return url;
  }
};

/**
 * @typedef {Object} Chatter~RequestParams
 * @prop {String} method - HTTP method
 * @prop {String} url - Resource URL
 * @prop {String} [body] - HTTP body (in POST/PUT/PATCH methods)
 */

/**
 * @typedef {Object} Chatter~RequestResult
 */

/**
 * Make a request for chatter API resource
 *
 * @param {Chatter~RequestParams} params - Paramters representing HTTP request
 * @param {Callback.<Chatter~RequestResult>} [callback] - Callback func
 * @returns {Chatter~Request}
 */
Chatter.prototype.request = function(params, callback) {
  return new Request(this, params).thenCall(callback);
};

/**
 * Make a resource request to chatter API
 *
 * @param {String} url - Resource URL
 * @param {Object} [queryParams] - Query parameters (in hash object)
 * @returns {Chatter~Resource}
 */
Chatter.prototype.resource = function(url, queryParams) {
  return new Resource(this, url, queryParams);
};

/**
 * @typedef {Object} Chatter~BatchRequestResult
 * @prop {Boolean} hasError - Flag if the batch has one or more errors
 * @prop {Array.<Object>} results - Batch request results in array
 * @prop {Number} results.statusCode - HTTP response status code
 * @prop {Chatter~RequestResult} results.result - Parsed HTTP response body
 */

/**
 * Make a batch request to chatter API
 *
 * @params {Array.<Chatter~Request>} requests - Chatter API requests
 * @param {Callback.<Chatter~BatchRequestResult>} [callback] - Callback func
 * @returns {Promise.<Chatter~BatchRequestResult>}
 */
Chatter.prototype.batch = function(requests, callback) {
  var self = this;
  var batchRequests = [], batchDeferreds = [];
  _.forEach(requests, function(request) {
    var deferred = Promise.defer();
    request._promise = deferred.promise;
    batchRequests.push(request.batchParams());
    batchDeferreds.push(deferred);
  });
  var params = {
    method: 'POST',
    url: this._normalizeUrl('/connect/batch'),
    body: {
      batchRequests: batchRequests
    }
  };
  return this._request(params).then(function(res) {
    _.forEach(res.results, function(result, i) {
      var deferred = batchDeferreds[i];
      if (result.statusCode >= 400) {
        deferred.reject(result.result);
      } else {
        deferred.resolve(result.result);
      }
    });
    return res;
  }).thenCall(callback);
};

/*--------------------------------------------*/
/**
 * A class representing chatter API request
 *
 * @protected
 * @class Chatter~Request
 * @implements {Promise.<Chatter~RequestResult>}
 * @param {Chatter} chatter - Chatter API object
 * @param {Chatter~RequestParams} params - Paramters representing HTTP request
 */
var Request = function(chatter, params) {
  this._chatter = chatter;
  this._params = params;
  this._promise = null;
};

/**
 * @typedef {Object} Chatter~BatchRequestParams
 * @prop {String} method - HTTP method
 * @prop {String} url - Resource URL
 * @prop {String} [richInput] - HTTP body (in POST/PUT/PATCH methods)
 */

/**
 * Retrieve parameters in batch request form
 *
 * @method Chatter~Request#batchParams
 * @returns {Chatter~BatchRequestParams}
 */
Request.prototype.batchParams = function() {
  var params = this._params;
  var batchParams = {
    method: params.method,
    url: this._chatter._normalizeUrl(params.url)
  };
  if (this._params.body) {
    batchParams.richInput = this._params.body;
  }
  return batchParams;
};

/**
 * Retrieve parameters in batch request form
 *
 * @method Chatter~Request#promise
 * @returns {Promise.<Chatter~RequestResult>}
 */
Request.prototype.promise = function() {
  return this._promise || this._chatter._request(this._params);
};

/**
 * Returns Node.js Stream object for request
 *
 * @method Chatter~Request#stream
 * @returns {stream.Stream}
 */
Request.prototype.stream = function() {
  return this._chatter._request(this._params).stream();
};

/**
 * Promise/A+ interface
 * http://promises-aplus.github.io/promises-spec/
 *
 * Delegate to deferred promise, return promise instance for batch result
 *
 * @method Chatter~Request#then
 */
Request.prototype.then = function(onResolve, onReject) {
  return this.promise().then(onResolve, onReject);
};

/**
 * Promise/A+ extension
 * Call "then" using given node-style callback function
 *
 * @method Chatter~Request#thenCall
 */
Request.prototype.thenCall = function(callback) {
  return _.isFunction(callback) ? this.promise().thenCall(callback) : this;
};

/*--------------------------------------------*/
/**
 * A class representing chatter API resource
 *
 * @protected
 * @class Chatter~Resource
 * @extends Chatter~Request
 * @param {Chatter} chatter - Chatter API object
 * @param {String} url - Resource URL
 * @param {Object} [queryParams] - Query parameters (in hash object)
 */
var Resource = function(chatter, url, queryParams) {
  if (queryParams) {
    var qstring = _.map(_.keys(queryParams), function(name) {
      return name + "=" + encodeURIComponent(queryParams[name]);
    }).join('&');
    url += (url.indexOf('?') > 0 ? '&' : '?') + qstring;
  }
  Resource.super_.call(this, chatter, { method: 'GET', url: url });
  this._url = url;
};

util.inherits(Resource, Request);

/**
 * Create a new resource
 *
 * @method Chatter~Resource#create
 * @param {Object} data - Data to newly post
 * @param {Callback.<Chatter~RequestResult>} [callback] - Callback function
 * @returns {Chatter~Request}
 */
Resource.prototype.create = function(data, callback) {
  return this._chatter.request({
    method: 'POST',
    url: this._url,
    body: data
  }).thenCall(callback);
};

/**
 * Retrieve resource content
 *
 * @method Chatter~Resource#retrieve
 * @param {Callback.<Chatter~RequestResult>} [callback] - Callback function
 * @returns {Chatter~Request}
 */
Resource.prototype.retrieve = function(callback) {
  return this.thenCall(callback);
};

/**
 * Update specified resource
 *
 * @method Chatter~Resource#update
 * @param {Obejct} data - Data to update
 * @param {Callback.<Chatter~RequestResult>} [callback] - Callback function
 * @returns {Chatter~Request}
 */
Resource.prototype.update = function(data, callback) {
  return this._chatter.request({
    method: 'POST',
    url: this._url,
    body: data
  }).thenCall(callback);
};

/**
 * Synonym of Resource#delete()
 *
 * @method Chatter~Resource#del
 * @param {Callback.<Chatter~RequestResult>} [callback] - Callback function
 * @returns {Chatter~Request}
 */
/**
 * Delete specified resource
 *
 * @method Chatter~Resource#delete
 * @param {Callback.<Chatter~RequestResult>} [callback] - Callback function
 * @returns {Chatter~Request}
 */
Resource.prototype.del =
Resource.prototype["delete"] = function(callback) {
  return this._chatter.request({
    method: 'DELETE',
    url: this._url
  }).thenCall(callback);
};


text:
@interface PlaySlider : UISlider
@property (nonatomic,weak) UIImageView *dotView;
@end


text:
import type { PageId } from "./state";
import type { Project, Workflow, Statistics } from "./datamodel";

type StatusSuccess = "success";
type StatusWaiting = "pending" | "error";
type Status = StatusSuccess | StatusWaiting;
type Dispatch = (action: Action) => void;

export type Action =
  | INIT
  | NAVIGATE
  | LOAD_APP_DATA
  | SELECT_JOB
  | DESELECT_JOB
  | TOGGLE_USERBAR
  | OPEN_USERBAR
  | CLOSE_USERBAR
  | CHANGE_JOBSEARCH_INPUT
  | SELECT_FILTERTAG
  | DESELECT_FILTERTAG
  | TOGGLE_FILTERTAG;

// Actions
type INIT = { type: "INIT" };
export const init = (): INIT => ({ type: "INIT" });

// Action that should be dispatched by the "redux-url router"
type NAVIGATE = { type: "NAVIGATE", pageId: PageId };
export const navigToPage = (pageId: PageId): NAVIGATE => ({
  type: "NAVIGATE",
  pageId
});

type LOAD_ACTION<DATA_TYPE, ACTION_FLAG> =
  | {
      type: ACTION_FLAG,
      status: StatusSuccess,
      globalErrorMessage?: string,
      data: DATA_TYPE
    }
  | {
      type: ACTION_FLAG,
      status: StatusWaiting,
      globalErrorMessage?: string
    };

type LOAD_APP_DATA = LOAD_ACTION<[Project, Workflow], "LOAD_APP_DATA">;
export const loadAppData = () =>
  (dispatch: Dispatch) => {
    dispatch(
      ({
        type: "LOAD_APP_DATA",
        status: "pending"
      }: LOAD_APP_DATA)
    );
    Promise.all([
      fetch("/api/project_definition"),
      fetch("/api/workflow_definition")
    ]).then(responses => {
      Promise.all(responses.map(r => r.json())).then(
        ([project: Project, workflow: Workflow]) =>
          dispatch(
            ({
              type: "LOAD_APP_DATA",
              status: "success",
              data: [project, workflow]
            }: LOAD_APP_DATA)
          ),
        () =>
          dispatch(
            ({
              type: "LOAD_APP_DATA",
              status: "error",
              globalErrorMessage: "Cannot parse Project definition data"
            }: LOAD_APP_DATA)
          )
      );
    });
  };

type UPDATE_STATISTICS = { type: "UPDATE_STATISTICS", statistics: Statistics };
export const updateStatistics = (
  statistics: Statistics
): UPDATE_STATISTICS => ({
  type: "UPDATE_STATISTICS",
  statistics
});

// Jobs selection

type SELECT_JOB = { type: "SELECT_JOB", jobId: string };
export const selectJob = (dispatch: Dispatch) =>
  (id: string) =>
    dispatch({
      type: "SELECT_JOB",
      jobId: id
    });

type DESELECT_JOB = { type: "DESELECT_JOB", jobId: string };
export const deselectJob = (dispatch: Dispatch) =>
  (id: string) =>
    dispatch({
      type: "DESELECT_JOB",
      jobId: id
    });

// Userbar

type TOGGLE_USERBAR = { type: "TOGGLE_USERBAR" };
export const toggleUserbar = (dispatch: Dispatch) =>
  () =>
    dispatch({
      type: "TOGGLE_USERBAR"
    });

type CLOSE_USERBAR = { type: "CLOSE_USERBAR" };
export const closeUserbar = (dispatch: Dispatch) =>
  () =>
    dispatch({
      type: "CLOSE_USERBAR"
    });

type OPEN_USERBAR = { type: "OPEN_USERBAR" };
export const openUserbar = (dispatch: Dispatch) =>
  () =>
    dispatch({
      type: "OPEN_USERBAR"
    });

// Job filtering

type CHANGE_JOBSEARCH_INPUT = {
  type: "CHANGE_JOBSEARCH_INPUT",
  inputText: string
};
export const changeJobSearchInput = (dispatch: Dispatch) =>
  (text: string) =>
    dispatch({
      type: "CHANGE_JOBSEARCH_INPUT",
      inputText: text
    });

type SELECT_FILTERTAG = { type: "SELECT_FILTERTAG", tagName: string };
export const selectFilterTag = (dispatch: Dispatch) =>
  (tagName: string) =>
    dispatch({
      type: "SELECT_FILTERTAG",
      tagName
    });

type DESELECT_FILTERTAG = { type: "DESELECT_FILTERTAG", tagName: string };
export const deselectFilterTag = (dispatch: Dispatch) =>
  (tagName: string) =>
    dispatch({
      type: "SELECT_FILTERTAG",
      tagName
    });

type TOGGLE_FILTERTAG = { type: "TOGGLE_FILTERTAG", tagName: string };
export const toggleFilterTag = (dispatch: Dispatch) =>
  (tagName: string) =>
    dispatch({
      type: "TOGGLE_FILTERTAG",
      tagName
    });


text:
package com.monotonic.map_visualiser;

import java.lang.reflect.Field;
import java.util.TreeMap;

public class TreeMapVisualiser
{
    private static final boolean BLACK = true;
    private static final boolean RED = false;

    private static final Field rootField;
    private static final Field colorField;
    private static final Field leftField;
    private static final Field rightField;

    static
    {
        Type entry = new Type("java.util.TreeMap$Entry");
        Type treeMap = new Type(TreeMap.class);

        rootField = treeMap.getField("root");
        leftField = entry.getField("left");
        rightField = entry.getField("right");
        colorField = entry.getField("color");
    }

    private final Console console;

    public TreeMapVisualiser(final Console console)
    {
        this.console = console;
    }

    public void visualise(final TreeMap<?, ?> map)
    {
        console.printf("Size: %d, %n", map.size());

        Object root = Type.get(rootField, map);

        visualiseSubTree(root, 0);
    }

    private int visualiseSubTree(final Object node, int index)
    {
        console.indent(index);
        final boolean colour = (boolean) Type.get(colorField, node);
        if (colour == RED)
        {
            console.red();
        }

        console.println(node);
        console.resetColour();

        return 1
             + visualiseBranch(node, index, leftField)
             + visualiseBranch(node, index, rightField);
    }

    private int visualiseBranch(final Object node, final int index, final Field field)
    {
        Object branch = Type.get(field, node);
        if (branch != null)
        {
            return visualiseSubTree(branch, index + 1);
        }
        return 0;
    }
}


text:
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit)
// Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus
// Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues
// License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved.

using System;
using System.Linq;
using System.Linq.Expressions;

namespace Z.EntityFramework.Plus
{
    public partial class AuditConfiguration
    {
        /// <summary>Excludes from the audit all properties.</summary>
        /// <returns>An AuditConfiguration.</returns>
        public AuditConfiguration ExcludeProperty()
        {
            ExcludeIncludePropertyPredicates.Add((x, s) => false);
            return this;
        }

        /// <summary>
        ///     Excludes from the audit all properties from entities of 'T' type or entities which the type
        ///     derive from 'T'.
        /// </summary>
        /// <typeparam name="T">Generic type to exclude all properties.</typeparam>
        /// <returns>An AuditConfiguration.</returns>
        public AuditConfiguration ExcludeProperty<T>()
        {
            ExcludeIncludePropertyPredicates.Add((x, s) => x is T ? (bool?) false : null);
            return this;
        }

        /// <summary>
        ///     Excludes from the audit selected properties from entities of 'T' type or entities which the
        ///     type derive from 'T'.
        /// </summary>
        /// <typeparam name="T">Generic type to exclude selected properties.</typeparam>
        /// <param name="propertySelector">The property selector.</param>
        /// <returns>An AuditConfiguration.</returns>
        public AuditConfiguration ExcludeProperty<T>(Expression<Func<T, object>> propertySelector)
        {
            var propertyNames = propertySelector.GetPropertyOrFieldAccessors().Select(x => x.ToString()).ToList();

            foreach (var accessor in propertyNames)
            {
                ExcludeIncludePropertyPredicates.Add((x, s) => x is T && s == accessor ? (bool?) false : null);
            }

            return this;
        }
    }
}