text:
namespace
{
    struct A { };
    struct B { };
    struct C { };
    struct D { };
    struct E { };
    inline UNUSED A foo(signed char, float) { return A(); }
    struct X
    {
        B operator () (signed char, float)                { return B(); }
        C operator () (signed char, float) const          { return C(); }
        D operator () (signed char, float) volatile       { return D(); }
        E operator () (signed char, float) const volatile { return E(); }
    };
}

static_assert(GTFO_RESULT_OF_FUN2_IS(decltype(foo), long int, long double, A), "");
static_assert(GTFO_RESULT_OF_FUN2_IS(X, long int, long double, B), "");
static_assert(GTFO_RESULT_OF_FUN2_IS(X &, long int, long double, B), "");
static_assert(GTFO_RESULT_OF_FUN2_IS(const X, long int, long double, C), "");
static_assert(GTFO_RESULT_OF_FUN2_IS(volatile X, long int, long double, D), "");
static_assert(GTFO_RESULT_OF_FUN2_IS(const volatile X, long int, long double, E), "");


text:
var _ = require('lodash');
var Q = require('q');
var routeHandler;

/* eslint no-console:0 */

/**
 * Add web routes
 * @param opts
 */
function addWebRoutes(opts) {
    var server = opts.server;
    var socialProviders = opts.config && opts.config.security && opts.config.security.social;
    var me = this;

    // first add social auth routes
    _.each(socialProviders, function (provider, providerName) {
        server.route({
            method:     ['GET', 'POST'],
            path:       '/auth/' + providerName,
            handler:    me.getWebRouteHandler(opts),
            config:     { auth: providerName }
        });
    });

    routeHandler = this.getWebRouteHandler(opts);

    // all other URLs checked against app config files for dymanic web routes
    server.route({
        method:     '*',
        path:       '/{p*}',
        handler:    routeHandler,
        config: {
            state: {
                parse:      true,
                failAction: 'log'
            }
        }
    });

    // for now simple access logging for errors
    server.on('response', function (request) {
        var resp = request.response || {};
        var statusCode = resp.statusCode || 0;
        var method = (request.method || '').toUpperCase();
        var reqInfo = request.info || {};
        var referrer = reqInfo.referrer || '';
        var host = reqInfo.hostname || '';
        var url = request.url || {};
        var urlPath = url.path || '';

        if (statusCode > 399 && method.toUpperCase && host && urlPath) {

            var lapse = -1;
            if (reqInfo.responded && reqInfo.received) {
                lapse = reqInfo.responded - reqInfo.received;
            }

            var msg = method + ' ' + host + urlPath + ' -> ' + statusCode + ' ' + '(' + lapse + 'ms)';
            if (referrer) {
                msg += ' ref: ' + request.info.referrer;
            }

            console.log(msg);
        }
    });
}

/**
 * The idea here is to use the same request and reply
 * but a different route handler based on the given URL override
 */
function processRoute(opts) {
    if (routeHandler) {
        routeHandler(opts.request, opts.reply, opts.urlOverride, opts.returnCode);
    }
    else {
        opts.reply.continue();
    }
}

/**
 * Execute the server preprocessing method and return true if the preprocessor
 * handled the request
 *
 * @param request
 * @param reply
 * @returns {Function}
 */
function getServerPreProcessing(request, reply) {
    var me = this;

    return function (routeInfo, page, model) {
        if (!page.serverPreprocessing) { return false; }

        var deps = { request: request, reply: reply, model: model, routeInfo: routeInfo };
        return me.pancakes.cook(page.serverPreprocessing, { dependencies: deps });
    };
}

/**
 * Render the web route for one of the dynamic routes. These routes are based off of
 * the .app config files for each app.
 *
 * @param opts
 */
function getWebRouteHandler(opts) {
    var webRouteHandler = this.pancakes.webRouteHandler;
    var me = this;

    return function handleWebRoute(request, reply, urlOverride, returnCode) {
        var appName = request.app.name;
        var url = urlOverride || request.url.pathname;
        var routeInfo = null;
        var referrer = request && request.headers && request.headers.referer ? request.headers.referer : '';
        var routeHelper = me.pancakes.cook('routeHelper');
        // var newrelic = require('newrelic');

        Q.fcall(function () {
            routeInfo = webRouteHandler.getRouteInfo(appName, url, request.query, request.app.lang, request.user, referrer);
            // newrelic.setTransactionName(routeInfo.appName + '||' + routeInfo.lang + '||' + routeInfo.urlPattern);

            // if redirect URL exists, just redirect right away
            if (routeInfo.redirect) {

                // make sure tokens in the redirect URL are replaced
                var redirectUrl = routeInfo.redirect;
                _.each(routeInfo.tokens, function (value, key) {
                    redirectUrl = redirectUrl.replace('{' + key + '}', value);
                });

                if (redirectUrl.indexOf('{') >= 0) {
                    //throw new Error('Redirect URL has token that was not replaced: ' + redirectUrl);
                    // we can't just throw errors in here
                    console.log('Bad redirect: ' + redirectUrl);
                    reply(new Error('So sorry, but there is an error here right now, and we are trying to fix it. Please try again later.'));
                    return new Q();
                }

                // do full url for all redirects
                if (redirectUrl.indexOf('http') !== 0) {
                    redirectUrl = (routeHelper.getBaseUrl(routeInfo.appName) + '') + redirectUrl;
                }

                reply().redirect(redirectUrl).permanent(true);
                return new Q();
            }

            // if the app is handling this request, don't do anything
            if (opts.preProcess && opts.preProcess(request, reply)) {
                return new Q();
            }

            var callbacks = {
                serverPreprocessing:    me.getServerPreProcessing(request, reply),
                addToModel:             opts.addToModel,
                pageCacheService:       opts.pageCacheService
            };

            return webRouteHandler.processWebRequest(routeInfo, callbacks)
                .then(function (renderedPage) {

                    // if no rendered page, it means request was handled earlier somewhere (ex. serverPreprocess redirect)
                    if (!renderedPage) {
                        //console.log('No rendered page for ' + url);
                        return false;
                    }

                    var response = reply(renderedPage).code(returnCode || 200);

                    // add content type if in the route info
                    if (routeInfo.contentType) {
                        response.header('Content-Type', routeInfo.contentType);
                    }

                    // as long as the nocache attribute is NOT set, add cache headers (sorry for double negative :-))
                    if (!routeInfo.nocache) {
                        response.header('cache-control', 'public, max-age=60');
                    }

                    return true;
                });
        })
            .catch(function (err) {
                console.error(err);
                reply(err);
            });
    };
}

module.exports = {
    processRoute: processRoute,
    addWebRoutes: addWebRoutes,
    getWebRouteHandler: getWebRouteHandler,
    getServerPreProcessing: getServerPreProcessing
};

redpajama_set_name: RedPajamaGithub


text:
angular.module('iotgo')

.factory('WS', [ 'Settings', function (Settings) {
  var ws;
  var callbacks = [];

  var connect = function (send) {
    console.log('typeof websocket: ' + typeof WebSocket);
    if (typeof WebSocket === 'undefined') return;
    ws = new WebSocket(Settings.websocketServer + '/api/ws');

    ws.addEventListener('message', function (message) {
      try {
        var data = JSON.parse(message.data);
        callbacks.forEach(function (callback) {
          callback(data);
        });
      }
      catch (err) {
        // Do nothing
      }
    });

    ws.addEventListener('error', function () {
      console.log('WebSocket Error');
    });

    ws.addEventListener('close', function () {
      console.log('WebSocket closed!');
    });

    if (typeof send === 'function') {
      ws.addEventListener('open', send);
    }
  };

  document.addEventListener('deviceready', function () {
    console.log('After deviceready');
    connect();
  });

  return {
    send: function (req) {
      if (typeof req !== 'object' || req === null) {
        return;
      }

      req.userAgent = 'web';
      req = angular.toJson(req);

      if (ws && ws.readyState === 1) {
        ws.send(req);
        return;
      }

      connect(function () {
        ws.send(req);
      });
    },
    addListener: function (callback) {
      callbacks.push(callback);
    },
    removeListener: function (callback) {
      var _index = callbacks.indexOf(callback);
      if (_index === -1) return;
      callbacks.splice(_index, 1);
    }
  };
} ]);


text:
package org.hisp.dhis.android.dashboard;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.squareup.okhttp.HttpUrl;

import org.hisp.dhis.android.dashboard.api.controllers.DhisController;
import org.hisp.dhis.android.dashboard.api.job.Job;
import org.hisp.dhis.android.dashboard.api.job.JobExecutor;
import org.hisp.dhis.android.dashboard.api.job.NetworkJob;
import org.hisp.dhis.android.dashboard.api.models.UserAccount;
import org.hisp.dhis.android.dashboard.api.models.meta.Credentials;
import org.hisp.dhis.android.dashboard.api.network.APIException;
import org.hisp.dhis.android.dashboard.api.persistence.preferences.ResourceType;
import org.hisp.dhis.android.dashboard.api.utils.EventBusProvider;
import org.hisp.dhis.android.dashboard.api.utils.SyncStrategy;
import org.hisp.dhis.android.dashboard.ui.events.UiEvent;

/**
 * @author Araz Abishov <araz.abishov.gsoc@gmail.com>.
 */
public final class DhisService extends Service {
    public static final int LOG_IN = 1;
    public static final int CONFIRM_USER = 2;
    public static final int LOG_OUT = 3;
    public static final int SYNC_DASHBOARDS = 5;
    public static final int SYNC_DASHBOARD_CONTENT = 6;
    public static final int SYNC_INTERPRETATIONS = 7;
    public static final int PULL_INTERPRETATION_IMAGES = 8;
    public static final int PULL_DASHBOARD_IMAGES = 9;
    private static final int SYNC_DATAMAPS = 10;

    private final IBinder mBinder = new ServiceBinder();
    private DhisController mDhisController;

    @Override
    public void onCreate() {
        super.onCreate();
        mDhisController = DhisController.getInstance();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class ServiceBinder extends Binder {
        public DhisService getService() {
            return DhisService.this;
        }
    }

    public void logInUser(final HttpUrl serverUrl, final Credentials credentials) {
        JobExecutor.enqueueJob(new NetworkJob<UserAccount>(LOG_IN,
                ResourceType.USERS) {

            @Override
            public UserAccount execute() throws APIException {
                return mDhisController.logInUser(serverUrl, credentials);
            }
        });
    }

    public void logOutUser() {
        JobExecutor.enqueueJob(new Job<UiEvent>(LOG_OUT) {
            @Override
            public UiEvent inBackground() {
                mDhisController.logOutUser();
                return new UiEvent(UiEvent.UiEventType.USER_LOG_OUT);
            }

            @Override
            public void onFinish(UiEvent result) {
                EventBusProvider.post(result);
            }
        });
    }

    public void confirmUser(final Credentials credentials) {
        JobExecutor.enqueueJob(new NetworkJob<UserAccount>(CONFIRM_USER,
                ResourceType.USERS) {

            @Override
            public UserAccount execute() throws APIException {
                return mDhisController.confirmUser(credentials);
            }
        });
    }

    public void syncDashboardContents() {
        JobExecutor.enqueueJob(new NetworkJob<Object>(SYNC_DASHBOARD_CONTENT,
                ResourceType.DASHBOARDS_CONTENT) {

            @Override
            public Object execute() throws APIException {
                mDhisController.syncDashboardContent();
                return new Object();
            }
        });
    }

    public void syncDashboardsAndContent(final SyncStrategy syncStrategy) {
        JobExecutor.enqueueJob(new NetworkJob<Object>(SYNC_DASHBOARDS,
                ResourceType.DASHBOARDS) {

            @Override
            public Object execute() throws APIException {
                mDhisController.syncDashboardContent();
                mDhisController.syncDashboards(syncStrategy);
                return new Object();
            }
        });
    }

    public void syncDashboards(final SyncStrategy syncStrategy) {
        JobExecutor.enqueueJob(new NetworkJob<Object>(SYNC_DASHBOARDS,
                ResourceType.DASHBOARDS) {

            @Override
            public Object execute() throws APIException {
                mDhisController.syncDashboards(syncStrategy);
                return new Object();
            }
        });
    }

    public void syncInterpretations(final SyncStrategy syncStrategy) {
        JobExecutor.enqueueJob(new NetworkJob<Object>(SYNC_INTERPRETATIONS,
                ResourceType.INTERPRETATIONS) {
            @Override
            public Object execute() throws APIException {
                mDhisController.syncInterpretations(syncStrategy);
                return new Object();
            }
        });
    }

    public void syncDataMaps() {
        JobExecutor.enqueueJob(new NetworkJob<Object>(SYNC_DATAMAPS,
                ResourceType.DATAMAPS) {

            @Override
            public Object execute() throws APIException {
                mDhisController.syncDataMaps();
                return new Object();
            }
        });
    }

    public void pullInterpretationImages(final DhisController.ImageNetworkPolicy imageNetworkPolicy, final Context context) {
        JobExecutor.enqueueJob(new NetworkJob<Object>(PULL_INTERPRETATION_IMAGES,
                ResourceType.INTERPRETATION_IMAGES) {
            @Override
            public Object execute() throws APIException {
                mDhisController.pullInterpretationImages(imageNetworkPolicy,context);
                return new Object();
            }
        });
    }

    public void pullDashboardImages(final DhisController.ImageNetworkPolicy imageNetworkPolicy, final Context context) {
        JobExecutor.enqueueJob(new NetworkJob<Object>(PULL_DASHBOARD_IMAGES,
                ResourceType.DASHBOARD_IMAGES) {
            @Override
            public Object execute() throws APIException {
                mDhisController.pullDashboardImages(imageNetworkPolicy,context);
                return new Object();
            }
        });
    }

    public boolean isJobRunning(int jobId) {
        return JobExecutor.isJobRunning(jobId);
    }
}


text:
package main

import (
    "fmt"
    "math/rand"
    "sort"
)

type Organism interface {
    Breed(Organism) Organism
    Measure() float64
}

type organismWithMeasure struct {
    org     Organism
    measure float64
}

type organismCollection []organismWithMeasure

func (oc organismCollection) Less(i, j int) bool {
    return oc[i].measure > oc[j].measure
}

func (oc organismCollection) Len() int { return len(oc) }
func (oc organismCollection) Swap(i, j int) { oc[i], oc[j] = oc[j], oc[i] }

func Evolve(adam Organism, popSize, breedSize, generations int, rng *rand.Rand) Organism {
    population := make(organismCollection, 0, popSize)
    population = append(population, organismWithMeasure{adam, 0.0})

    for i := 1; i != popSize; i++ {
        population = append(population, organismWithMeasure{adam.Breed(adam), 0.0})
    }

    for i := 0; i != generations; i++ {
        sum := 0.0

        for j := 0; j != popSize; j++ {
            population[j].measure = population[j].org.Measure()
            sum += population[j].measure
        }

        sort.Sort(population)

        for k := breedSize; k < popSize; k++ {
            population[k].org = population[rng.Intn(breedSize)].org.Breed(population[rng.Intn(breedSize)].org)
        }

        fmt.Println(sum / float64(popSize))
    }

    return population[0].org
}


text:
(function() {
  var toggleDropdown = function (e) {
    e.preventDefault();
    var $inputDiv = $(this).closest('[data-behavior="dropdown"]');
    if ($inputDiv.hasClass('open')) {
      closeDropdown.apply(this);
    } else {
      openDropdown.apply(this);
    }
  };

  var openDropdown = function () {
    var $inputDiv = $(this).closest('[data-behavior="dropdown"]');
    $inputDiv.addClass('active open');
    $inputDiv.find('.select-options').focus();
  };

  var closeDropdown = function (e) {
    if ($(e.target).is('[type="checkbox"]')) {
      return true;
    }

    var $inputDiv = $(this).closest('[data-behavior="dropdown"]');
    $inputDiv.removeClass('open');
    if ($inputDiv.data().multiSelect) {
      updateSelectCheckboxPlaceholder($inputDiv);
    } else {
      var isEmpty = ($inputDiv.find('select').val() === '');
      $inputDiv.toggleClass('active', isEmpty);
    }
  };

  var updateFakeSelect = function (value, $inputDiv) {
    var $option = $inputDiv.find('.select-options li[data-value="' + value + '"]');
    var label = $option.text();

    $inputDiv.find('.selectable').removeClass('selected');
    $option.addClass('selected');
    $inputDiv.find('.display-selected').html('<span>' + label + '</span>');
    $inputDiv.addClass('active').removeClass('open');
  };

  var updateSelectCheckboxPlaceholder = function ($inputDiv) {
    var $checked = $inputDiv.find('input:checked'),
        $selected = $inputDiv.find('.display-selected'),
        label = $inputDiv.children('label').text(),
        placeholder = 'Add ' + label;
    if ($checked.length === 1) {
      placeholder = $checked.first().siblings('label').text();
    } else if ($checked.length > 1) {
      placeholder = $checked.length + ' ' + label;
    }
    $selected.text(placeholder);
  };

  var optionSelected = function () {
    if ($(this).hasClass('input-check')) {
      $(this).find('[type="checkbox"]').click();
    } else {
      var $inputDiv = $(this).closest('[data-behavior="dropdown"]');
      var value = $(this).data('value');
      $inputDiv.find('select').val(value).change();
    }
  };

  var selectChanged = function () {
    updateFakeSelect($(this).val(), $(this).closest('[data-behavior="dropdown"]'));
  };

  $(document).on('mousedown', '[data-behavior="dropdown"] .display-selected', toggleDropdown);
  $(document).on('blur focusout', '[data-behavior="dropdown"] .select-options', closeDropdown);
  $(document).on('click', '[data-behavior="dropdown"] .select-options li.selectable', optionSelected);
  $(document).on('change', '[data-behavior="dropdown"] select', selectChanged);
}());


text:
namespace wgt
{
class TestPlugin2TestObject;
class TestPlugin2Interface;
typedef ObjectHandleT<TestPlugin2TestObject> TestPlugin2TestObjectPtr;
typedef ManagedObject<TestPlugin2TestObject> TestPlugin2TestObjectObj;
typedef ObjectHandleT<TestPlugin2Interface> TestPlugin2InterfacePtr;
typedef ManagedObject<TestPlugin2Interface> TestPlugin2InterfaceObj;

//------------------------------------------------------------------------------
class TestPlugin2TestObject
{
	DECLARE_REFLECTED

public:
	int counter_;
	std::string text_;
	std::vector<float> values_;

	void setCounter(const int& value)
	{
		counter_ = value;
	}
	void getCounter(int* value) const
	{
		*value = counter_;
	}

	void setText(const std::string& value)
	{
		text_ = value;
	}
	const std::string& getText() const
	{
		return text_;
	}

	bool operator==(const TestPlugin2TestObject& tdo) const
	{
		if (counter_ != tdo.counter_ || text_ != tdo.text_ || values_.size() != tdo.values_.size())
		{
			return false;
		}

		size_t i = 0;
		for (; i < values_.size() && values_[i] == tdo.values_[i]; ++i)
			;
		return i == values_.size();
	}
};

class ITestPlugin2
{
public:
	virtual ~ITestPlugin2()
	{
	}
	virtual TestPlugin2TestObjectPtr getObject() = 0;
};

//------------------------------------------------------------------------------
class TestPlugin2Interface : public Implements<ITestPlugin2>
{
	DECLARE_REFLECTED

public:
	TestPlugin2Interface() : object_(nullptr)
	{
	}

	TestPlugin2TestObjectPtr getObject()
	{
		if (object_ == nullptr)
		{
			object_ = TestPlugin2TestObjectObj::make();
		}
        return object_.getHandleT();
	}

private:
    TestPlugin2TestObjectObj object_;
};
} // end namespace wgt
#endif // PLUGIN2_OBJECTS_HPP


text:
class testApp : public ofBaseApp, public BoundBlobListener {

public:
	void setup();
	void update();
	void draw();

	void keyPressed  (int key);
	void keyReleased(int key);
	void mouseMoved(int x, int y );
	void mouseDragged(int x, int y, int button);
	void mousePressed(int x, int y, int button);
	void mouseReleased(int x, int y, int button);
	void windowResized(int w, int h);
	void dragEvent(ofDragInfo dragInfo);
	void gotMessage(ofMessage msg);
	void doPersonTracking();
	KinectThresholder kinect;
	map<int,BoundBlob> people;

	void boundBlobEntered(const BoundBlob &blob);
	void boundBlobMoved(const BoundBlob &blob);
	void boundBlobExited(const BoundBlob &blob);
	//SimpleAnim anim;
};


text:
package com.github.ffpojo.samples.decorator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.github.ffpojo.FFPojoHelper;
import com.github.ffpojo.exception.FFPojoException;
import com.github.ffpojo.samples.pojo.Customer;

public class PositionalRecordParsingWithDecoratorReaderExample {

	private static final String INPUT_TXT_RESOURCE_CLASSPATH = "PositionalRecordParsingWithDecoratorExampleInput.txt";

	public static void main(String[] args) {
		PositionalRecordParsingWithDecoratorReaderExample example = new PositionalRecordParsingWithDecoratorReaderExample();
		try {
			System.out.println("Making POJO from TXT...");
			example.readCustomersFromText();
			System.out.println("END !");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FFPojoException e) {
			e.printStackTrace();
		}
	}

	public void readCustomersFromText() throws IOException, FFPojoException {
		FFPojoHelper ffpojo = FFPojoHelper.getInstance();
		BufferedReader textFileReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(INPUT_TXT_RESOURCE_CLASSPATH)));
		String line;
		while ( (line = textFileReader.readLine()) != null) {
			Customer cust = ffpojo.createFromText(Customer.class, line);
			System.out.printf("[%d][%s][%s][%s]\n", cust.getId(), cust.getName(), cust.getEmail(), cust.getBirthDate());
		}
		textFileReader.close();
	}
}


text:
package me.eugeniomarletti.tetheringfixer.android;

import android.animation.Animator;
import android.app.ActionBar;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import me.eugeniomarletti.tetheringfixer.Async;
import me.eugeniomarletti.tetheringfixer.Fixer;
import me.eugeniomarletti.tetheringfixer.R;
import me.eugeniomarletti.tetheringfixer.Steps;
import me.eugeniomarletti.tetheringfixer.Utils;

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

import static me.eugeniomarletti.tetheringfixer.Utils.addOnGlobalLayoutListener;
import static me.eugeniomarletti.tetheringfixer.Utils.getOffsetBetweenViews;

public final class StepsActivity extends Activity implements Steps.StepListListener
{
    private static final int CLICK_RETRY = R.string.click_retry;

    private static final Interpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator();
    private static final Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator();

    private static final int          CARD_SLIDE_DURATION     = 750;
    private static final Interpolator CARD_SLIDE_INTERPOLATOR = DECELERATE_INTERPOLATOR;

    private static final int          TEXT_FIXED_FADE_DURATION     = 500;
    private static final Interpolator TEXT_FIXED_FADE_INTERPOLATOR = DECELERATE_INTERPOLATOR;

    private static final int          TEXT_AROUND_FADE_IN_DURATION     = 400;
    private static final Interpolator TEXT_AROUND_FADE_IN_INTERPOLATOR = DECELERATE_INTERPOLATOR;

    private static final int          TEXT_AROUND_FADE_OUT_DURATION     = TEXT_AROUND_FADE_IN_DURATION;
    private static final Interpolator TEXT_AROUND_FADE_OUT_INTERPOLATOR = ACCELERATE_INTERPOLATOR;

    private List<ListItem> listItems;

    private FrameLayout        card;
    private RelativeLayout     list;
    private BulletExpandEffect bulletExpandEffect;
    private TextView           textClick;
    private TextView           textSuccess;
    private TextView           textError;
    private CompoundButton     fixAtBoot;

    private float    cardCenteredY;
    private int      bulletColorChecked;
    private Drawable background;

    private void adjustSwitchMargin(boolean afterLayout)
    {
        if (fixAtBoot == null) return;
        final Runnable adjustSwitchMargin = new Runnable()
        {
            @Override
            public void run()
            {
                final int margin = (((View)fixAtBoot.getParent()).getHeight() - fixAtBoot.getHeight()) / 2;
                if (fixAtBoot.getRight() != margin)
                {
                    final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)fixAtBoot.getLayoutParams();
                    lp.rightMargin = margin;
                    fixAtBoot.setLayoutParams(lp);
                }
            }
        };
        if (!afterLayout) adjustSwitchMargin.run();
        else addOnGlobalLayoutListener(fixAtBoot, true, new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                adjustSwitchMargin.run();
            }
        });
    }

    private void fadeTextAround(final View view, final boolean in)
    {
        if (view.getVisibility() == View.VISIBLE)
        {
            if (in) view.setAlpha(0f);
            view.animate()
                .withLayer()
                .alpha(in ? 1f : 0f)
                .setDuration(in ? TEXT_AROUND_FADE_IN_DURATION : TEXT_AROUND_FADE_OUT_DURATION)
                .setInterpolator(in ? TEXT_AROUND_FADE_IN_INTERPOLATOR : TEXT_AROUND_FADE_OUT_INTERPOLATOR);
        }
    }

    private void setCurrentListItem(int index, boolean isError, final String errorText, boolean animate)
    {
        int i = 0;
        for (ListItem listItem : listItems)
        {
            boolean activated, checked, working, error;

            if (i < index)
            {
                // before current
                checked = true;
                activated = false;
                working = false;
                error = false;
            }
            else if (i == index)
            {
                // current
                checked = false;
                activated = true;
                working = !isError;
                error = isError;
            }
            else
            {
                // after current
                checked = false;
                activated = false;
                working = false;
                error = false;
            }

            listItem.setError(error);
            listItem.setActivated(activated);
            listItem.setChecked(checked);
            listItem.setWorking(working);

            i++;
        }

        if (isError)
        {
            card.setClickable(true);

            textClick.setText(CLICK_RETRY);
            textClick.setVisibility(View.VISIBLE);
            if (errorText != null)
            {
                textError.setText(Utils.addEmoji(errorText));
                textError.setVisibility(View.VISIBLE);
            }
            else
            {
                textError.setVisibility(View.GONE);
                textError.setText(null);
            }
            if (animate)
            {
                final int oldCardPosition = Utils.getLocationInWindow(card).y;
                addOnGlobalLayoutListener(textClick, true, new ViewTreeObserver.OnGlobalLayoutListener()
                {
                    @Override
                    public void onGlobalLayout()
                    {
                        fadeTextAround(textClick, true);
                        if (errorText != null) fadeTextAround(textError, true);
                        card.setTranslationY(oldCardPosition - Utils.getLocationInWindow(card).y);
                        card.animate()
                            .translationY(0f)
                            .setDuration(CARD_SLIDE_DURATION)
                            .setInterpolator(CARD_SLIDE_INTERPOLATOR)
                            .setListener(null);
                    }
                });
            }
        }
    }

    private void setCurrentListItem(int index)
    {
        setCurrentListItem(index, false, null, true);
    }

    private void success(int index)
    {
        setCurrentListItem(index);
        final ListItem currentListItem = listItems.get(index);
        final Bullet bullet = currentListItem.getBullet();
        bullet.addBulletColorAnimationListener(new SimpleAnimatorListener()
        {
            @Override
            public void onAnimationEnd(Animator animator)
            {
                bullet.removeBulletColorAnimationListener(this);

                final Point offset = getOffsetBetweenViews(bulletExpandEffect, bullet);
                final PointF bulletCenter = bullet.getBulletCenter();
                bulletCenter.offset(offset.x, offset.y);

                bulletExpandEffect.setVisibility(View.VISIBLE); // needs to do layout to be effective
                addOnGlobalLayoutListener(bulletExpandEffect, true, new ViewTreeObserver
                        .OnGlobalLayoutListener()
                {
                    @Override
                    public void onGlobalLayout()
                    {
                        bulletExpandEffect.animateExpand(
                                bulletColorChecked, bulletCenter, bullet.getBulletSize(), new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                // expanded
                                success(true);
                            }
                        });
                    }
                });
            }
        });
        currentListItem.setWorking(false);
        currentListItem.setChecked(true);
    }

    private void success(boolean animate)
    {
        for (ListItem listItem : listItems) listItem.setVisibility(View.INVISIBLE);
        ((View)bulletExpandEffect.getParent()).setBackgroundColor(bulletColorChecked);
        bulletExpandEffect.setVisibility(View.GONE);
        textSuccess.setVisibility(View.VISIBLE);
        if (animate)
        {
            textSuccess.setAlpha(0f);
            textSuccess.animate()
                       .alpha(1f)
                       .setDuration(TEXT_FIXED_FADE_DURATION)
                       .setInterpolator(TEXT_FIXED_FADE_INTERPOLATOR)
                       .withLayer();
        }
        else textSuccess.setAlpha(1f);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        adjustSwitchMargin(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fixer);

        list = (RelativeLayout)findViewById(R.id.list);
        textSuccess = (TextView)findViewById(R.id.text_success);
        textError = (TextView)findViewById(R.id.text_error);
        textClick = (TextView)findViewById(R.id.text_click);
        card = (FrameLayout)findViewById(R.id.card);
        bulletExpandEffect = (BulletExpandEffect)findViewById(R.id.bullet_expand_effect);

        background = ((View)bulletExpandEffect.getParent()).getBackground();

        textSuccess.setText(Utils.addEmoji(textSuccess.getText()));

        card.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Steps.startOrRetry();
            }
        });

        Fixer.isFixAtBootEnabledAsync(new Async.SimpleMainThreadCallback<Boolean>()
        {
            @Override
            public void mainThreadCallback(Boolean result, boolean success, Throwable error)
            {
                if (!success || result == null) throw new RuntimeException(error);
                final ActionBar ab = getActionBar();
                ab.setCustomView(R.layout.activity_fixer_actionbar);
                fixAtBoot = (CompoundButton)ab.getCustomView().findViewById(R.id.fix_at_boot_switch);
                fixAtBoot.setChecked(result);
                fixAtBoot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
                {
                    @Override
                    public void onCheckedChanged(final CompoundButton button, boolean enabled)
                    {
                        button.setEnabled(false);
                        Fixer.setFixAtBootEnabledAsync(new Async.SimpleMainThreadCallback<Void>()
                        {
                            @Override
                            public void mainThreadCallback(Void result, boolean success, Throwable error)
                            {
                                if (!success) throw new RuntimeException(error); // can do better when i'm not lazy
                                if (Steps.isSuccess()) Fixer.shutdown();
                                button.setEnabled(true);
                            }
                        }, enabled);
                    }
                });
                ab.setDisplayShowCustomEnabled(true);
                adjustSwitchMargin(true);
            }
        });

        addOnGlobalLayoutListener(card, true, new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                cardCenteredY = Utils.getLocationInWindow(card).y;
            }
        });

        addOnGlobalLayoutListener(bulletExpandEffect, true, new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                final View parent = (View)bulletExpandEffect.getParent();
                final FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)bulletExpandEffect.getLayoutParams();
                lp.width = parent.getWidth() - parent.getPaddingLeft() - parent.getPaddingRight();
                lp.height = parent.getHeight() - parent.getPaddingTop() - parent.getPaddingBottom();
                bulletExpandEffect.setLayoutParams(lp);
            }
        });

        // inflate views for list items
        final List<String> labels = Steps.getLabels();
        listItems = new ArrayList<>(labels.size());
        for (int i = 0, labelsLength = labels.size(); i < labelsLength; i++)
        {
            final ListItem previousListItem = i > 0 ? listItems.get(i - 1) : null;
            final LayoutInflater inflater = getLayoutInflater();
            final Bullet bullet = (Bullet)inflater.inflate(R.layout.activity_fixer_bullet, list, false);
            final TextView label = (TextView)inflater.inflate(R.layout.activity_fixer_label, list, false);
            final int bulletId = Utils.generateViewId();
            final int labelId = Utils.generateViewId();
            bullet.setId(bulletId);
            label.setId(labelId);
            label.setText(labels.get(i));
            RelativeLayout.LayoutParams bulletLayoutParams = (RelativeLayout.LayoutParams)bullet.getLayoutParams();
            RelativeLayout.LayoutParams labelLayoutParams = (RelativeLayout.LayoutParams)label.getLayoutParams();
            if (previousListItem != null)
                bulletLayoutParams.addRule(RelativeLayout.BELOW, previousListItem.getBullet().getId());
            labelLayoutParams.addRule(RelativeLayout.RIGHT_OF, bulletId);
            labelLayoutParams.addRule(RelativeLayout.ALIGN_TOP, bulletId);
            labelLayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, bulletId);
            list.addView(bullet, bulletLayoutParams);
            list.addView(label, labelLayoutParams);
            listItems.add(new ListItem(bullet, label));
        }
        bulletColorChecked = listItems.get(0).getBullet().getBulletColorChecked();
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        addOnGlobalLayoutListener(card, true, new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                Steps.addListener(StepsActivity.this);
                final boolean isStarted = Steps.isStarted();
                final boolean isError = Steps.isError();
                final boolean isSuccess = Steps.isSuccess();
                textClick.setVisibility(!isStarted || !isSuccess ? View.VISIBLE : View.GONE);
                card.setClickable(!isStarted || isError);
                if (isSuccess) success(false);
                else
                {
                    for (ListItem listItem : listItems) listItem.setVisibility(View.VISIBLE);
                    ((View)bulletExpandEffect.getParent()).setBackground(background);
                    bulletExpandEffect.setVisibility(View.GONE);
                    textSuccess.setVisibility(View.GONE);
                    setCurrentListItem(Steps.getCurrentStep(), isError, Steps.getErrorText(), false);
                }
            }
        });
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        StepsService.cancelNotification();
        StepsService.stop();

        Steps.setActionsDelayed(true);
        Steps.resume();
    }

    @Override
    protected void onPause()
    {
        super.onPause();

        Steps.pause();
        Steps.setActionsDelayed(false);
    }

    @Override
    protected void onStop()
    {
        super.onStop();

        Steps.removeListener(this);
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();

        Steps.removeListener(this);
        Steps.shutdownIfNoListeners();
    }

    @Override
    public void onStepsStart()
    {
        Utils.runOnMainThread(new Runnable()
        {
            @Override
            public void run()
            {
                card.setClickable(false);
                fadeTextAround(textClick, false);
                fadeTextAround(textError, false);
                card.animate()
                    .translationYBy(cardCenteredY - Utils.getLocationInWindow(card).y)
                    .setDuration(CARD_SLIDE_DURATION)
                    .setInterpolator(CARD_SLIDE_INTERPOLATOR)
                    .setListener(new SimpleAnimatorListener()
                    {
                        @Override
                        public void onAnimationEnd(Animator animator)
                        {
                            card.animate().setListener(null);
                            textClick.setVisibility(View.GONE);
                            textError.setVisibility(View.GONE);
                            card.setTranslationY(0f);
                        }
                    });
            }
        });
    }

    @Override
    public void onStepsRetry()
    {
        setCurrentListItem(-1);
    }

    @Override
    public void onStepError(final int itemIndex, final String errorText)
    {
        setCurrentListItem(itemIndex, true, errorText, true);
    }

    @Override
    public void onAdvanceStep(final int itemIndex)
    {
        setCurrentListItem(itemIndex);
    }

    @Override
    public void onStepsSuccess(final int itemIndex)
    {
        success(itemIndex);
    }

    private static final class ListItem
    {
        private final Bullet   bullet;
        private final TextView label;

        public ListItem(Bullet bullet, TextView label)
        {
            this.bullet = bullet;
            this.label = label;
        }

        public Bullet getBullet()
        {
            return bullet;
        }

        public TextView getLabel()
        {
            return label;
        }

        public void setError(boolean error)
        {
            bullet.setError(error);
            label.setError(error);
        }

        public void setWorking(boolean working)
        {
            bullet.setWorking(working);
            label.setWorking(working);
        }

        public void setActivated(boolean activated)
        {
            bullet.setActivated(activated);
            label.setActivated(activated);
        }

        public void setChecked(boolean checked)
        {
            bullet.setChecked(checked);
            label.setChecked(checked);
        }

        public void setVisibility(int visibility)
        {
            bullet.setVisibility(visibility);
            label.setVisibility(visibility);
        }
    }
}


text:
"""Module containing class for GCP's spark service.

Spark clusters can be created and deleted.
"""

import datetime
import json
import re

from perfkitbenchmarker import flags
from perfkitbenchmarker import providers
from perfkitbenchmarker import spark_service
from perfkitbenchmarker.providers.gcp import util

FLAGS = flags.FLAGS

GCP_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'

class GcpDataproc(spark_service.BaseSparkService):
  """Object representing a GCP Dataproc cluster.

  Attributes:
    cluster_id: ID of the cluster.
    num_workers: Number of nodes in the cluster.
    project: Enclosing project for the cluster.
  """

  CLOUD = providers.GCP
  SERVICE_NAME = 'dataproc'

  @staticmethod
  def _GetStats(stdout):
    results = json.loads(stdout)
    stats = {}
    done_time = datetime.datetime.strptime(
        results['status']['stateStartTime'], GCP_TIME_FORMAT)
    pending_time = None
    start_time = None
    for state in results['statusHistory']:
      if state['state'] == 'PENDING':
        pending_time = datetime.datetime.strptime(state['stateStartTime'],
                                                  GCP_TIME_FORMAT)
      elif state['state'] == 'RUNNING':
        start_time = datetime.datetime.strptime(state['stateStartTime'],
                                                GCP_TIME_FORMAT)

    if done_time and start_time:
      stats[spark_service.RUNTIME] = (done_time - start_time).total_seconds()
    if start_time and pending_time:
      stats[spark_service.WAITING] = (
          (start_time - pending_time).total_seconds())
    return stats

  def _Create(self):
    """Creates the cluster."""

    if self.cluster_id is None:
      self.cluster_id = 'pkb-' + FLAGS.run_uri
    cmd = util.GcloudCommand(self, 'dataproc', 'clusters', 'create',
                             self.cluster_id)
    if self.project is not None:
      cmd.flags['project'] = self.project
    cmd.flags['num-workers'] = self.num_workers
    if self.machine_type:
      cmd.flags['worker-machine-type'] = self.machine_type
      cmd.flags['master-machine-type'] = self.machine_type
    cmd.Issue()

  def _Delete(self):
    """Deletes the cluster."""
    cmd = util.GcloudCommand(self, 'dataproc', 'clusters', 'delete',
                             self.cluster_id)
    cmd.Issue()

  def _Exists(self):
    """Check to see whether the cluster exists."""
    cmd = util.GcloudCommand(self, 'dataproc', 'clusters', 'describe',
                             self.cluster_id)
    stdout, stderr, retcode = cmd.Issue()
    return retcode == 0

  def SubmitJob(self, jarfile, classname, job_poll_interval=None,
                job_arguments=None, job_stdout_file=None):
    cmd = util.GcloudCommand(self, 'dataproc', 'jobs', 'submit', 'spark')
    cmd.flags['cluster'] = self.cluster_id
    cmd.flags['jars'] = jarfile
    cmd.flags['class'] = classname
    # Dataproc gives as stdout an object describing job execution.
    # Its stderr contains a mix of the stderr of the job, and the
    # stdout of the job.  We set the driver log level to FATAL
    # to supress those messages, and we can then separate, hopefully
    # the job standard out from the log messages.
    cmd.flags['driver-log-levels'] = 'root=FATAL'
    if job_arguments:
      cmd.additional_flags = job_arguments
    stdout, stderr, retcode = cmd.Issue()
    if retcode != 0:
      return {spark_service.SUCCESS: False}

    stats = self._GetStats(stdout)
    stats[spark_service.SUCCESS] = True

    if job_stdout_file:
      with open(job_stdout_file, 'w') as f:
        lines = stderr.splitlines(True)
        if (not re.match(r'Job \[.*\] submitted.', lines[0]) or
            not re.match(r'Waiting for job output...', lines[1]) or
            not re.match(r'\r', lines[2])):
          raise Exception('Dataproc output in unexpected format.')
        i = 3
        # Eat these status lines.  The end in \r, so they overwrite themselves
        # at the console or when you cat a file.  But they are part of this
        # string.
        while re.match(r'\[Stage \d+:', lines[i]):
          i += 1
        if not re.match(r' *\r$', lines[i]):
          raise Exception('Dataproc output in unexpected format.')
        while i < len(lines) and not re.match(r'Job \[.*\]', lines[i]):
          f.write(lines[i])
          i += 1
        if i != len(lines) - 1:
          raise Exception('Dataproc output in unexpected format.')
    return stats

  def SetClusterProperty(self):
    pass


text:
**Canonical name**: `testbase.unit.UnitTestCase`

The `UnitTestCase` class provides helper method for testing Django views. It derives from
[django.test.TestCase](https://docs.djangoproject.com/en/dev/topics/testing/tools/#testcase) and
[BaseTestCase](../base.md).

## Properties

### response

The HttpResponse object returned by the most recent call to the `get` method on this class.

## Methods

### get(self, urlPattern=None, *args, **kwargs)

This shortcut method replaces the following typical pattern:

    url = reverse('obj-detail', kwargs={'id': 123})
    response = self.client.get(url)

The _urlPattern_ argument, if given, provides a named url pattern to reverse and get using the standard test client. The
_args_ and _kwargs_ are passed to the equivalently named arguments of the Django
[reverse](https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse) function to derive the final URL. The above
example would thus become simply:

    self.get('obj-detail', id=123)

The response to the get request is both returned by this method and stored as the `response` property on the test
case.

If no _urlPattern_ is provided then this method will call `self.get_url()` to find the URL. This is particularly useful
when most or all tests in a suite operate on the same URL. For example:

    def get_url(self):
        return reverse('some_url', kwargs={'name': self.randStr()})

    def test_edge_case_number_54(self):
        self.get()
        ...

### assertResponseStatusIsOk(response=None)
### assertResponseStatusIsNotFound(response=None)

These methods check that the HTTP status of the given response object matches that named in the method. These methods
replace the following pattern:

    self.assertEqual(HttpResponseNotFound.status_code, response.status_code)

If no _response_ argument is given then these methods will test against `self.response`.

### assertContextValueEqual(self, response, contextVariableName, expectedValue)
### assertLastContextValueEqual(self, contextVariableName, expectedValue)

These methods check that the context of a response contains a value that matches the expected value. This replaces the
following pattern:

    self.assertEqual(expectedValue, response.context[contextVariableName])

The second form, where no response is given, tests against the context in `self.response`.


text:
package com.lightszentip.module.security.password.util;

public enum AlgorithmType {

    MD5("MD5"), SHA_1("SHA1"), SHA_256("SHA256"), SHA_384("SHA384"), SHA_512("SHA512");

    private String text;

    public String getText() {
        return this.text;
    }

    AlgorithmType(String text) {
        this.text = text;
    }

}


text:
// Qt includes

// CTK includes
#include "ctkVTKScalarBarWidget.h"
#include "ui_ctkVTKScalarBarWidget.h"

// VTK includes
#include <vtkScalarBarActor.h>
#include <vtkScalarBarWidget.h>

//-----------------------------------------------------------------------------
class ctkVTKScalarBarWidgetPrivate: public Ui_ctkVTKScalarBarWidget
{
  Q_DECLARE_PUBLIC(ctkVTKScalarBarWidget);
protected:
  ctkVTKScalarBarWidget* const q_ptr;
public:
  ctkVTKScalarBarWidgetPrivate(ctkVTKScalarBarWidget& object);
  void init();
  void updateFromScalarBarWidget();

  vtkScalarBarWidget* ScalarBarWidget;
};

//-----------------------------------------------------------------------------
ctkVTKScalarBarWidgetPrivate::ctkVTKScalarBarWidgetPrivate(ctkVTKScalarBarWidget& object)
  :q_ptr(&object)
{
  this->ScalarBarWidget = 0;
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidgetPrivate::init()
{
  Q_Q(ctkVTKScalarBarWidget);
  this->setupUi(q);
  q->setEnabled(this->ScalarBarWidget != 0);
  QObject::connect(this->DisplayScalarBarCheckBox, SIGNAL(toggled(bool)),
                   q, SLOT(setDisplay(bool)));
  QObject::connect(this->MaxNumberOfColorsSpinBox, SIGNAL(valueChanged(int)),
                   q, SLOT(setMaxNumberOfColors(int)));
  QObject::connect(this->NumberOfLabelsSpinBox, SIGNAL(valueChanged(int)),
                   q, SLOT(setNumberOfLabels(int)));

  QObject::connect(this->TitleTextPropertyWidget, SIGNAL(textChanged(QString)),
                   q, SLOT(setTitle(QString)));
  QObject::connect(this->TitleTextPropertyWidget, SIGNAL(colorChanged(QColor)),
                   q, SIGNAL(modified()));
  QObject::connect(this->TitleTextPropertyWidget, SIGNAL(opacityChanged(double)),
                   q, SIGNAL(modified()));
  QObject::connect(this->TitleTextPropertyWidget, SIGNAL(fontFamilyChanged(QString)),
                   q, SIGNAL(modified()));
  QObject::connect(this->TitleTextPropertyWidget, SIGNAL(boldChanged(bool)),
                   q, SIGNAL(modified()));
  QObject::connect(this->TitleTextPropertyWidget, SIGNAL(italicChanged(bool)),
                   q, SIGNAL(modified()));
  QObject::connect(this->TitleTextPropertyWidget, SIGNAL(shadowChanged(bool)),
                   q, SIGNAL(modified()));

  QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(textChanged(QString)),
                   q, SLOT(setLabelsFormat(QString)));
  QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(colorChanged(QColor)),
                   q, SIGNAL(modified()));
  QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(opacityChanged(double)),
                   q, SIGNAL(modified()));
  QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(fontFamilyChanged(QString)),
                   q, SIGNAL(modified()));
  QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(boldChanged(bool)),
                   q, SIGNAL(modified()));
  QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(italicChanged(bool)),
                   q, SIGNAL(modified()));
  QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(shadowChanged(bool)),
                   q, SIGNAL(modified()));
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidgetPrivate::updateFromScalarBarWidget()
{
  Q_Q(ctkVTKScalarBarWidget);

  vtkScalarBarActor* actor =
    this->ScalarBarWidget ? this->ScalarBarWidget->GetScalarBarActor() : 0;
  q->setEnabled(actor != 0);
  if (actor == 0)
    {
    return;
    }
  this->DisplayScalarBarCheckBox->setChecked(this->ScalarBarWidget->GetEnabled() != 0);
  this->MaxNumberOfColorsSpinBox->setValue(actor->GetMaximumNumberOfColors());
  this->NumberOfLabelsSpinBox->setValue(actor->GetNumberOfLabels());

  this->TitleTextPropertyWidget->setTextProperty(
    actor->GetTitleTextProperty());
  this->LabelsTextPropertyWidget->setTextProperty(
    actor->GetLabelTextProperty());
  this->TitleTextPropertyWidget->setText(actor->GetTitle());
  this->LabelsTextPropertyWidget->setText(actor->GetLabelFormat());
}

//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::ctkVTKScalarBarWidget(QWidget* parentWidget)
  :QWidget(parentWidget)
  , d_ptr(new ctkVTKScalarBarWidgetPrivate(*this))
{
  Q_D(ctkVTKScalarBarWidget);
  d->init();
}

//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::ctkVTKScalarBarWidget(vtkScalarBarWidget* scalarBarWidget, QWidget* parentWidget)
  :QWidget(parentWidget)
  , d_ptr(new ctkVTKScalarBarWidgetPrivate(*this))
{
  Q_D(ctkVTKScalarBarWidget);
  d->init();
  this->setScalarBarWidget(scalarBarWidget);
}

//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::~ctkVTKScalarBarWidget()
{
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setScalarBarWidget(vtkScalarBarWidget* scalarBarWidget)
{
  Q_D(ctkVTKScalarBarWidget);
  if (scalarBarWidget == d->ScalarBarWidget)
    {
    return;
    }
  vtkScalarBarActor* oldActor =
    d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
  vtkScalarBarActor* newActor =
    scalarBarWidget ? scalarBarWidget->GetScalarBarActor() : 0;
  qvtkReconnect(d->ScalarBarWidget, scalarBarWidget, vtkCommand::EnableEvent,
                this, SLOT(onScalarBarModified()));
  qvtkReconnect(d->ScalarBarWidget, scalarBarWidget, vtkCommand::DisableEvent,
                this, SLOT(onScalarBarModified()));
  qvtkReconnect(oldActor, newActor, vtkCommand::ModifiedEvent,
                this, SLOT(onScalarBarModified()));
  d->ScalarBarWidget = scalarBarWidget;
  this->onScalarBarModified();
}

//-----------------------------------------------------------------------------
vtkScalarBarWidget* ctkVTKScalarBarWidget::scalarBarWidget()const
{
  Q_D(const ctkVTKScalarBarWidget);
  return d->ScalarBarWidget;
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::onScalarBarModified()
{
  Q_D(ctkVTKScalarBarWidget);
  d->updateFromScalarBarWidget();
  emit modified();
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setDisplay(bool visible)
{
  Q_D(ctkVTKScalarBarWidget);
  if (d->ScalarBarWidget == 0)
    {
    return;
    }
  d->ScalarBarWidget->SetEnabled(visible);
  // calling SetEnabled might fail, make sure the checkbox is up-to-date
  d->DisplayScalarBarCheckBox->setChecked(d->ScalarBarWidget->GetEnabled());
}

//-----------------------------------------------------------------------------
bool ctkVTKScalarBarWidget::display()const
{
  Q_D(const ctkVTKScalarBarWidget);
  return d->DisplayScalarBarCheckBox->isChecked();
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setMaxNumberOfColors(int colorCount)
{
  Q_D(ctkVTKScalarBarWidget);
  vtkScalarBarActor* actor =
    d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
  if (actor == 0)
    {
    return;
    }
  actor->SetMaximumNumberOfColors(colorCount);
}

//-----------------------------------------------------------------------------
int ctkVTKScalarBarWidget::maxNumberOfColors()const
{
  Q_D(const ctkVTKScalarBarWidget);
  return d->MaxNumberOfColorsSpinBox->value();
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setNumberOfLabels(int labelCount)
{
  Q_D(ctkVTKScalarBarWidget);
  vtkScalarBarActor* actor =
    d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
  if (actor == 0)
    {
    return;
    }
  actor->SetNumberOfLabels(labelCount);
}

//-----------------------------------------------------------------------------
int ctkVTKScalarBarWidget::numberOfLabels()const
{
  Q_D(const ctkVTKScalarBarWidget);
  return d->NumberOfLabelsSpinBox->value();
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setTitle(const QString& title)
{
  Q_D(ctkVTKScalarBarWidget);
  vtkScalarBarActor* actor =
    d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
  if (actor == 0)
    {
    return;
    }
  actor->SetTitle(title.toUtf8());
}

//-----------------------------------------------------------------------------
QString ctkVTKScalarBarWidget::title()const
{
  Q_D(const ctkVTKScalarBarWidget);
  return d->TitleTextPropertyWidget->text();
}

//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setLabelsFormat(const QString& format)
{
  Q_D(ctkVTKScalarBarWidget);
  vtkScalarBarActor* actor =
    d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
  if (actor == 0)
    {
    return;
    }
  actor->SetLabelFormat(format.toUtf8());
}

//-----------------------------------------------------------------------------
QString ctkVTKScalarBarWidget::labelsFormat()const
{
  Q_D(const ctkVTKScalarBarWidget);
  return d->LabelsTextPropertyWidget->text();
}


text:
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.Configuration;

namespace Picums.Mvc
{
	public static class CultureInfoExtension
	{
		public static IList<CultureInfo> ToCulturesList(this IConfigurationSection section)
			=> section
				.GetChildren()
				.Select(x => x.Value)
				.Select(x => new CultureInfo(x))
				.ToList();
	}
}


text:
#if UNITY_EDITOR || DEVELOPMENT_BUILD
    #define DEVELOPMENT
#endif

using System;
using System.Collections;

namespace BeauRoutine.Internal
{
    static internal class DisposeUtils
    {
        /// <summary>
        /// Disposes of an object if it is an IDisposable
        /// and nulls out the reference.
        /// </summary>
        static public void DisposeObject<T>(ref T ioObject) where T : class
        {
            if (ioObject != null)
            {
                if (ioObject is IDisposable)
                    ((IDisposable)ioObject).Dispose();
                ioObject = null;
            }
        }

        /// <summary>
        /// Disposes of an IEnumerator and nulls out the reference.
        /// </summary>
        static public void DisposeEnumerator<T>(ref T ioEnumerator) where T : IEnumerator
        {
            if (ioEnumerator != null)
            {
                ((IDisposable)ioEnumerator).Dispose();
                ioEnumerator = default(T);
            }
        }
    }
}


text:
import { EventsKey } from '../events';
import { Condition } from '../events/condition';
import BaseEvent from '../events/Event';
import MapBrowserEvent from '../MapBrowserEvent';
import { ObjectEvent } from '../Object';
import DragBox, { DragBoxEvent } from './DragBox';

export interface Options {
    className?: string;
    condition?: Condition;
    duration?: number;
    out?: boolean;
    minArea?: number;
}
export default class DragZoom extends DragBox {
    constructor(opt_options?: Options);
    /**
     * Function to execute just before onboxend is fired
     */
    onBoxEnd(event: MapBrowserEvent<UIEvent>): void;
    on(type: string | string[], listener: (p0: any) => any): EventsKey | EventsKey[];
    once(type: string | string[], listener: (p0: any) => any): EventsKey | EventsKey[];
    un(type: string | string[], listener: (p0: any) => any): void;
    on(type: 'boxcancel', listener: (evt: DragBoxEvent) => void): EventsKey;
    once(type: 'boxcancel', listener: (evt: DragBoxEvent) => void): EventsKey;
    un(type: 'boxcancel', listener: (evt: DragBoxEvent) => void): void;
    on(type: 'boxdrag', listener: (evt: DragBoxEvent) => void): EventsKey;
    once(type: 'boxdrag', listener: (evt: DragBoxEvent) => void): EventsKey;
    un(type: 'boxdrag', listener: (evt: DragBoxEvent) => void): void;
    on(type: 'boxend', listener: (evt: DragBoxEvent) => void): EventsKey;
    once(type: 'boxend', listener: (evt: DragBoxEvent) => void): EventsKey;
    un(type: 'boxend', listener: (evt: DragBoxEvent) => void): void;
    on(type: 'boxstart', listener: (evt: DragBoxEvent) => void): EventsKey;
    once(type: 'boxstart', listener: (evt: DragBoxEvent) => void): EventsKey;
    un(type: 'boxstart', listener: (evt: DragBoxEvent) => void): void;
    on(type: 'change', listener: (evt: BaseEvent) => void): EventsKey;
    once(type: 'change', listener: (evt: BaseEvent) => void): EventsKey;
    un(type: 'change', listener: (evt: BaseEvent) => void): void;
    on(type: 'change:active', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:active', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:active', listener: (evt: ObjectEvent) => void): void;
    on(type: 'error', listener: (evt: BaseEvent) => void): EventsKey;
    once(type: 'error', listener: (evt: BaseEvent) => void): EventsKey;
    un(type: 'error', listener: (evt: BaseEvent) => void): void;
    on(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'propertychange', listener: (evt: ObjectEvent) => void): void;
}


text:
require 'database_cleaner/active_record/base'
module DatabaseCleaner::ActiveRecord
  class Transaction
    include ::DatabaseCleaner::ActiveRecord::Base

    def start
      if connection_klass.connection.respond_to?(:increment_open_transactions)
        connection_klass.connection.increment_open_transactions
      else
        connection_klass.__send__(:increment_open_transactions)
      end
      connection_klass.connection.begin_db_transaction
    end

    def clean
      return unless connection_klass.connection.open_transactions > 0

      connection_klass.connection.rollback_db_transaction

      if connection_klass.connection.respond_to?(:decrement_open_transactions)
        connection_klass.connection.decrement_open_transactions
      else
        connection_klass.__send__(:decrement_open_transactions)
      end
    end
  end
end


text:
using System;
using OpenTK.Platform.Egl;

namespace OpenTK.Platform.Linux
{
    internal class LinuxWindowInfo : EglWindowInfo
    {
        public int FD { get; private set; }
        public LinuxDisplay DisplayDevice { get; private set; }
        public IntPtr BufferManager { get; private set; }

        public LinuxWindowInfo(IntPtr display, int fd, IntPtr gbm, LinuxDisplay display_device)
            : base(IntPtr.Zero, display, IntPtr.Zero)
        {
            if (display_device == null)
            {
                throw new ArgumentNullException();
            }

            FD = fd;
            BufferManager = gbm;
            DisplayDevice = display_device;
            // The window handle and surface handle must
            // be filled in manually once they are known.
        }
    }
}


text:
module Softlayer
  class Notification
    module Occurrence
      class Resource
        module Network
          module Application
            autoload :Delivery, 'softlayer/notification/occurrence/resource/network/application/delivery'
          end
        end
      end
    end
  end
end


text:
package org.wso2.carbon.bpmn.rest.service.analytics;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.wso2.carbon.bpmn.analytics.publisher.AnalyticsPublisherConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;

import java.io.IOException;

/**
 * Enables the process variable publishing from BPS to DAS
 */
@Path("/publish-process-variables")
public class PublishProcessVariablesService {
    private static final Log log = LogFactory.getLog(PublishProcessVariablesService.class);

    /**
     * Enables the process variable publishing from BPS to DAS by, receiving (from WSO2 PC) and saving analytics
     * configuration details in config registry.
     *
     * @param processId
     * @param dasConfigDetailsJson
     * @return
     */
    @POST
    @Path("/{processId}")
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
    public Response publishProcessVariables(@PathParam("processId") String processId, String dasConfigDetailsJson)
            throws IOException {
        if (log.isDebugEnabled()) {
            log.debug("Recieved analytics configuration details to from PC to BPS for Process ID:" + processId
                    + "\nRecieved Date:" + dasConfigDetailsJson);
        }

        try {
            saveDASconfigInfo(dasConfigDetailsJson);
        } catch (RegistryException e) {
            String errMsg =
                    "Error in saving DAS Analytics Configuratios in BPS Config-Registry for process :" + processId
                            + "\n Details tried to save:" + dasConfigDetailsJson;
            log.error(errMsg, e);
            return Response.status(500).entity(errMsg + " : " + e.getMessage()).build();
        }
        return Response.ok().build();
    }

    /**
     * Save DAS configuration details (received from PC), in config registry
     *
     * @param dasConfigDetailsJSONString
     * @throws RegistryException
     */
    private void saveDASconfigInfo(String dasConfigDetailsJSONString) throws RegistryException, IOException {

        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        Registry configRegistry = carbonContext.getRegistry(RegistryType.SYSTEM_CONFIGURATION);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode dasConfigDetailsJOb = objectMapper.readTree(dasConfigDetailsJSONString);
        String processDefinitionId = dasConfigDetailsJOb.get(AnalyticsPublisherConstants.PROCESS_DEFINITION_ID)
                .textValue();

        //create a new resource (text file) to keep process variables
        Resource procVariableJsonResource = configRegistry.newResource();
        procVariableJsonResource.setContent(dasConfigDetailsJSONString);
        procVariableJsonResource.setMediaType(MediaType.APPLICATION_JSON);
        configRegistry.put(AnalyticsPublisherConstants.REG_PATH_BPMN_ANALYTICS + processDefinitionId + "/"
                + AnalyticsPublisherConstants.ANALYTICS_CONFIG_FILE_NAME, procVariableJsonResource);
    }
}


text:
<?php
namespace Scopefragger\LaravelSocialy\Controllers;

use App\Http\Controllers\Controller;

class LaravelSocialyController extends Controller
{

}


text:
+++ content/browser/renderer_host/render_widget_host_view_aura.cc	2014-03-26 17:19:35.877467960 -0600
@@ -733,7 +733,7 @@
     return reinterpret_cast<gfx::NativeViewId>(
         dispatcher->host()->GetAcceleratedWidget());
 #endif
-  return static_cast<gfx::NativeViewId>(NULL);
+  return reinterpret_cast<gfx::NativeViewId>(NULL);
 }

 gfx::NativeViewAccessible RenderWidgetHostViewAura::GetNativeViewAccessible() {


text:
import os
import utils
import magic
import subprocess
from models import *
from django.template.defaultfilters import filesizeformat

SCM_DIFF_ALL_CMD[utils.SCM_APIGEN]

INFO="INFO"
PASS="PASS"
VERIFY="VERIFY"
FAIL="FAIL"

def api_diff(apidir, api_version_old, api_version_new):
    """
        Generate API diff text

        @return - tuple - (SEVERITY, TEXT)
    """
    severity = INFO
    cmdline = SCM_DIFF_ALL_CMD[utils.SCM_APIGEN] % (api_version_old, api_version_new)

    proc = subprocess.Popen(cmdline.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=apidir)
    api_diff = proc.communicate()[0]

    if (api_diff == "") and (proc.returncode == 0):
        api_diff = utils.INFO_NO_API_DIFF_FOUND
        severity = PASS

    api_diff = api_diff.decode('UTF8', 'replace')

    return (severity, api_diff)

def full_diff(pkg_scm_type, dirname, version_old, version_new, subpackage_path):
    """
        Generate full diff text
    """
    cmdline = None
    diff = utils.INFO_NOT_AVAILABLE
    # NB: diffing a subpath is the same as diffing changelog only!
    if subpackage_path and SCM_DIFF_CHANGELOG_CMD[pkg_scm_type]:
        cmdline = SCM_DIFF_CHANGELOG_CMD[pkg_scm_type] % (version_old, version_new, subpackage_path)
    elif SCM_DIFF_ALL_CMD[pkg_scm_type]:
        cmdline = SCM_DIFF_ALL_CMD[pkg_scm_type] % (version_old, version_new)

    if cmdline:
        proc = subprocess.Popen(cmdline.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=dirname)
        diff = proc.communicate()[0]
# decode after bzipping in the caller
#        diff = diff.decode('UTF8', 'replace')

    return (INFO, diff)

def diff_stats(scm_type, cwd, old_ver, new_ver, only_last_line, subpackage_path=None):
    """
        Returns something like:
        3 files changed, 5 insertions, 2 deletions

        @scm_type - int - type of SCM - determines which command is used
        @cwd - string - current working directory - usualy a git clone
        @old_ver - string - old version tag/commit
        @new_ver - string - new version tag/commit
        @only_last_line - bool - if True only the short status message is returned
    """
    if SCM_DIFF_STAT_CMD[scm_type] is None:
        return (INFO, utils.INFO_NOT_AVAILABLE)

    cmdline = SCM_DIFF_STAT_CMD[scm_type] % (old_ver, new_ver)
    if subpackage_path:
        cmdline += " -- %s" % subpackage_path

    proc = subprocess.Popen(cmdline.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
    text = proc.communicate()[0]
    text = text.decode('UTF8', 'replace').strip('\n') # keep leading white space for changed files list
    if not text:
        text = utils.INFO_NOT_AVAILABLE

    # take the last line only to avoid using pipes in subprocess.Popen
    # text is stripped of new lines above so no empty list elements at the end
    if only_last_line:
        for l in text.split("\n"):
            text = l.strip() # keep leading white space for changed files list

    return (INFO, text)

def package_size_change(advisory):
    """
        Return size change as text

        @advisory - Advisory object
    """
    severity = PASS
    if advisory.severity == utils.SEVERITY_MEDIUM:
        severity = VERIFY

    if advisory.severity == utils.SEVERITY_HIGH:
        severity = FAIL

    return (severity, "%s »» %s" % (filesizeformat(advisory.old.size), filesizeformat(advisory.new.size)))

def list_modified_files(cwd, old_ver, new_ver):
    """
NB: Uses Git and the tarball/ directory

        Returns the list of changed files with insert delete stats:
         js/jquery/resources/jquery.min.js         |    9 +-
         setup.py                                  |   12 +-

        Severity - INFO if only tests have changed, VERIFY otherwise
    """

    (severity, files_list) = diff_stats(utils.SCM_GIT, cwd, old_ver, new_ver, False)
    files_list = files_list.split('\n')[:-1] # skip the last line, this is the summary

    changed_test_count = 0
    for f in files_list:
        for test_dir in utils.get_test_dirs():
            # if file name doesn't match a common test case pattern
            if f.lower().find(test_dir) > -1:
                changed_test_count += 1
                break # break from the inner loop, this filename already matches test case

    if changed_test_count == len(files_list):
        severity = INFO # only tests have changed
    else:
        severity = VERIFY

    if files_list:
        return (severity, "\n".join(files_list))
    else:
        return (PASS, 'None')

def get_file_list_changes(cwd, old_ver, new_ver):
    """
NB: Uses Git and the tarball/ directory

        Returns a list of added, deleted, renamed and chmod files.
        The data is then filtered through other test cases

    """
    cmdline = "git diff -M --summary %s..%s" % (old_ver, new_ver)
    proc = subprocess.Popen(cmdline.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
    text = proc.communicate()[0]
    text = text.decode('UTF8', 'replace').strip('\n') # keep leading white space for changed files list
    if not text:
        return (FAIL, utils.INFO_NOT_AVAILABLE)

    return (INFO, text)

def filter_added_files(file_list):
    """
        @file_list - string - output of git diff --summary

SEVERITY - INFO - added files are usually new functionality or tests or resources
    """
    files = []
    for f in file_list.split('\n'):
        if f.find('create mode') > -1:
            files.append(f)

    if files:
        return (INFO, "\n".join(files))
    else:
        return (PASS, "None")

def filter_removed_files(file_list):
    """
        @file_list - string - output of git diff -M --summary

SEVERITY- FAIL - removing modules/files can break the API
    """
    files = []
    for f in file_list.split('\n'):
        if f.find('delete mode') > -1:
            files.append(f)

    if files:
        return (FAIL, "\n".join(files))
    else:
        return (PASS, "None")

def filter_renamed_files(file_list):
    """
        @file_list - string - output of git diff -M --summary

SEVERITY- FAIL - renaming modules/files can break the API
    """
    files = []
    for f in file_list.split('\n'):
        if f.find('rename') > -1:
            files.append(f)

    if files:
        return (FAIL, "\n".join(files))
    else:
        return (PASS, "None")

def filter_permission_change(file_list):
    """
        @file_list - string - output of git diff -M --summary

SEVERITY- FAIL - permission changes are bad, usually security thing
but there are valid use-cases too. Just verify manually.
    """
    files = []
    for f in file_list.split('\n'):
        if f.find('mode change') > -1:
            files.append(f)

    if files:
        return (FAIL, "\n".join(files))
    else:
        return (PASS, "None")

def symlinks_test(dirname):
    """
Traverse the directory and report any symlinks found.
Generally packages should not distribute symlinks.

Severity - FAIL if links found, PASS otherwise
    """

    links = []

    for (path, dirs, files) in os.walk(dirname):
        if path.find('/.git') > -1:
            continue

        # search for directory links
        for d in dirs:
            dname = os.path.join(path, d)
            if os.path.islink(dname):
                links.append(os.path.relpath(dname, dirname)+'/')

        # search for file links
        for f in files:
            fname = os.path.join(path, f)
            if os.path.islink(fname):
                links.append(os.path.relpath(fname, dirname))

    if links:
        return (FAIL, '\n'.join(links))
    else:
        return (PASS, "None")

def file_types_diff(cwd, old_ver, new_ver):
    """
NB: Uses Git and the magic/ directory

Select only files that are Copied (C), Modified (M), Renamed (R),
have their type (i.e. regular file, symlink, submodule, ...) changed (T)

        Returns a list of changed file types!
    """
    # diff only Modified and Type changed
    cmdline = "git diff -M --diff-filter=MT %s..%s" % (old_ver, new_ver)
    proc = subprocess.Popen(cmdline.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
    text = proc.communicate()[0]
    text = text.decode('UTF8', 'replace').strip('\n') # keep leading white space

    if text:
        return (FAIL, text)
    else:
        return (PASS, "None")

def virus_scan(cwd):
    """
        Perform virus scan using ClamAV.

        @return  - ClamAV output
    """
    # print only infected files, recursive scan, skip .git/ directory
    cmdline = "/usr/bin/clamscan -i -r --exclude-dir=.git ." # NB: dot at the end prints relative file names
    proc = subprocess.Popen(cmdline.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
    text = proc.communicate()[0]
    text = text.decode('UTF8', 'replace').strip()
    if not text:
        return (FAIL, utils.INFO_NOT_AVAILABLE)

    return (VERIFY, text)

def parse_virus_scan(text):
    """
        Parse ClamAV output
    """

    for line in text.split('\n'):
        if line.find('Infected files:') > -1:
            if line.replace('Infected files:', '').strip() == '0':
                return (PASS, line + '\n\n' + text) # return all lines
            else:
                return (FAIL, line + '\n\n' + text) # return all lines

def test_case_count_callback(filename, contentdir, targetfile):   # FALSE NEGATIVE
    """
        Generate API definition for @filename,
        storing it in @contentdir as @targetfile (absolute path)

        @return - bool - True if content was generated
    """
    if os.path.islink(filename):
        return None

    fname = filename.lower()
    for test_dir in utils.get_test_dirs():
        if fname.startswith(test_dir) or (fname.find('/'+test_dir) > -1):
            return os.path.relpath(targetfile, contentdir)

def test_case_count_change(old_tests, new_tests):
    """
        If new tests are less then FAIL and report
        the names of deleted tests.

        @old_tests, @new_tests - lists of relative file names
    """
    # first sanitize the input. Some elements may be None so remove them
    old_tests = [t for t in old_tests if t]
    new_tests = [t for t in new_tests if t]

    old_count = len(old_tests)
    new_count = len(new_tests)

    if new_count > old_count:
        return (PASS, "%d »» %d" % (old_count, new_count))
    elif new_count == old_count:
        if (new_count == 0):
            return (FAIL, "This package doesn't ship any tests")
        else:
            return (VERIFY, "No tests were added in this release")
    else: # new < old
        removed = ["%d »» %d" % (old_count, new_count)]
        for test in old_tests:
            if test not in new_tests: # NB: this ignores renamed tests
                removed.append("Removed test case: %s" % test)
        return (FAIL, "\n".join(removed))

def file_size_callback(filename, contentdir, targetfile):  # FALSE NEGATIVE
    """
        Return {fname: size}
    """
    if os.path.islink(filename):
        return None

    stat = os.lstat(filename)
    return {os.path.relpath(targetfile, contentdir) : stat.st_size}

def normalize_list_of_dict_into_dict(alist):
    """
        Info is generated as a list of dict
        objects with a single key.

        @alist - the list in question.
        @return - normalized dict with multiple keys
    """

    result = {}
    for element in alist:
        for key in element.keys():
            result[key] = element[key]

    return result

def file_size_changes(sizes_old, sizes_new):
    """
        Inform on any files which are present in both
        versions and:

        * were 0 bytes and became non-zero;
        * were non-zero sized and became 0 bytes;
        * size changed over 20% and 20KB
    """
    results = []
    old_file_names = sizes_old.keys()

    for file_name in sizes_new.keys():
        if file_name in old_file_names: # present in both versions
            old_size = sizes_old[file_name]
            new_size = sizes_new[file_name]

            # keep this before text conversion to speed-up things
            if old_size == new_size:
                continue

            # convert sizes to human readable format
            old_size_text = filesizeformat(old_size)
            new_size_text = filesizeformat(new_size)

            # zero/non-zero changes
            if ((old_size == 0) and (new_size > 0)) or \
                ((old_size > 0) and (new_size == 0)):
                results.append("Zero vs non-zero change: %s from %s to %s" % (file_name, old_size_text, new_size_text))
            else: # neither one is zero
                delta = abs(new_size - old_size)
                percent = int(delta*100/old_size)

                # > 20KB and > 20%
                if (delta > 20*1024*1024) and (percent >= 20):
                    results.append("Too big change: %s from %s to %s" % (file_name, old_size_text, new_size_text))

    if results:
        return (FAIL, "\n".join(results))
    else:
        return (PASS, "Suspicious changes: 0")

def filetype_gen_callback(filename, contentdir, targetfile):  # FALSE NEGATIVE
    """
        Generate file type definition for @filename,
        storing it in @contentdir as @targetfile (absoute path)
    """
    if os.path.islink(filename):
        return None

    # generate file type using python magic
    file_type = magic.from_file(filename)
    f = open(targetfile, 'w')
    f.write(file_type.encode('UTF-8', 'replace'))
    f.write("\n") # always include new line to avoid git complaining
    f.close()

    return {os.path.relpath(targetfile, contentdir) : file_type}

def added_non_text_files(types_old, types_new):
    """
        Inform on newly added files which are not text.
    """
    results = []
    old_names = types_old.keys()

    for file_name in types_new.keys():
        # skip some metadata files
        do_skip = False
        for skip_me in ["checksums.yaml.gz", "checksums.yaml.gz.sig", "metadata.gz.sig", "data.tar.gz.sig"]:
            if file_name.endswith(skip_me):
                do_skip = True
                break
        if do_skip:
            continue

        if file_name in old_names: # skip binaries from old version
            continue

        # inspect only new files
        new_type = types_new[file_name]

        if new_type.find("text") > -1: # skip text files
            continue

        results.append("%s : %s" % (file_name, new_type))

    if results:
        return (FAIL, "\n".join(results))
    else:
        return (PASS, "None")


text:
<?php
	$menusel = ['home'];
	include(base_path('resources/views/opwifi/common.php'));
?>
@extends('opwifi.common.layouts.default')

@section('title', 'Opwifi首页')

@section('content')

首页

欢迎使用OpWiFi管理平台。本平台是配合SuperWRT,进行设备远程管理的工具。
目前,该项目及SuperWRT还在开发测试阶段,欢迎给我们提出问题和建议。

@endsection

@section('header_css')
@endsection
@section('footer_js')

@endsection


text:
package edu.harvard.iq.dataverse;

import javax.ejb.Stateless;
import javax.json.JsonObject;

/**
 *
 * @author Naomi
 */
@Stateless
public class DataTagsContainer {

    private String datasetName;
    private JsonObject tag;

    /**
     * Creates a new instance of DataTagsContainer
     */
    public DataTagsContainer() {
        datasetName = "";
        tag = null;
    }

    public void setDatasetName(String datasetName) {
        this.datasetName = datasetName;
    }

    public String getDatasetName() {
        return datasetName;
    }

    public void setTag(JsonObject tag) {
        this.tag = tag;
    }

    public JsonObject getTag() {
        return tag;
    }

}


text:
import { createAction } from 'redux-actions';

export const SELECT_C9_PROJECT_DIRECTORY = 'SELECT_C9_PROJECT_DIRECTORY';
export const selectC9ProjectDirectory = createAction(SELECT_C9_PROJECT_DIRECTORY);

export const SELECT_PROJECT_DIRECTORY = 'SELECT_PROJECT_DIRECTORY';
export const selectProjectDirectory = createAction(SELECT_PROJECT_DIRECTORY);

export const OPEN_PROJECT = 'OPEN_PROJECT';
export const openProject = createAction(OPEN_PROJECT);

export const UPDATE_SETTINGS = 'UPDATE_SETTINGS';
export const updateStatus = createAction(UPDATE_SETTINGS);


text:
struct SomeLargeType;
struct MuchLargerType([SomeLargeType; 32]);

// Ensure that we don't capture any derefs when moving captures into the closures,
// i.e. only data from the enclosing stack is moved.
fn big_box() {
    let s = MuchLargerType(Default::default());
    let b = Box::new(s);
    let t = (b, 10);

    let c = #[rustc_capture_analysis]
    //~^ ERROR: attributes on expressions are experimental
    //~| NOTE: see issue #15701 <https://github.com/rust-lang/rust/issues/15701>
    || {
    //~^ First Pass analysis includes:
    //~| Min Capture analysis includes:
        let p = t.0.0;
        //~^ NOTE: Capturing t[(0, 0),Deref,(0, 0)] -> ByValue
        //~| NOTE: Min Capture t[(0, 0)] -> ByValue
        println!("{} {:?}", t.1, p);
        //~^ NOTE: Capturing t[(1, 0)] -> ImmBorrow
        //~| NOTE: Min Capture t[(1, 0)] -> ImmBorrow
    };

    c();
}

fn main() {
    big_box();
}


text:
package com.sequenceiq.cloudbreak.orchestrator.marathon.poller;

import com.sequenceiq.cloudbreak.orchestrator.OrchestratorBootstrap;
import com.sequenceiq.cloudbreak.orchestrator.exception.CloudbreakOrchestratorFailedException;

import mesosphere.marathon.client.Marathon;
import mesosphere.marathon.client.model.v2.App;

public class MarathonAppBootstrap implements OrchestratorBootstrap {

    private final Marathon client;

    private final App app;

    public MarathonAppBootstrap(Marathon client, App app) {
        this.client = client;
        this.app = app;
    }

    @Override
    public Boolean call() throws Exception {
        Integer desiredTasksCount = app.getInstances();
        App appResponse = client.getApp(this.app.getId()).getApp();
        Integer tasksRunning = appResponse.getTasksRunning();

        if (tasksRunning < desiredTasksCount) {
            String msg = String.format("Marathon container '%s' instance count: '%s', desired instance count: '%s'!", app.getId(), tasksRunning,
                    desiredTasksCount);
            throw new CloudbreakOrchestratorFailedException(msg);
        }

        return true;
    }
}


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Sihong's Personal Website">
    <meta name="author" content="Sihong">
    <title>Sihong's Website</title>
    <link href="bootstrap.min.css" rel="stylesheet">
    <link href="SihongIndex.css" rel="stylesheet">
    <link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                Toggle navigation

            </button>
            Sihong Huang

Home

Skills

Portfolio

Resume

                    Blog Posts

Technical Blogs

Week 1 Tech Blog

Week 2 Tech Blog

Week 3 Tech Blog

Week 4 Tech Blog

Week 5 Tech Blog

Week 6 Tech Blog

Week 7 Tech Blog

Week 8 Tech Blog

Cultural Blogs

Week 1 Culture Blog

No Week 2 Blog

Week 3 Culture Blog

Week 4 Culture Blog

Week 5 Culture Blog

Week 6 Culture Blog

Week 7 Culture Blog

Week 8 Culture Blog

Week 9 Culture Blog

Contact

Week 6 Tech Blog: OOP-Concepts

Concepts Learned

                  Tags
                  OOP,FP

Date: 4/21/2015

                    This week I got to learn some of the basics of Object-Oriented Programming (OOP). Something central to OOP is the idea that data and the operations around this data are closely related to each other. OOP's main activity is to create new objects and can be used to add additional methods to existing objects. So far in my programming journey, I've worked only with OOP languages so researching a bit about FP will give me a better understanding of what that is.

                After doing some research on Functional Programming (FP), it appears that data in FP is only loosely relaed to its functions. It allows you to write different operations on the same data structure. FP's main activity is to write new functions.

Compared to OOP, the central model for abstraction in FP is the function and not the data structure.

               OO makes it easy to change the way things are put together while it makes it harder for adding new operations. For example, if you already have a certain process in place, but want to change the way in which that process takes in certain rules then you would use OO to handle this.

FP will make it easier to handle new operations that work with existing data types and queries because it is more database oriented.

     OO languages are good for code evolution where new things can be added to a set of operations on things that were already created. For example, adding new classes to work with existing methods.

FP languages are good for adding new operations on things that already exist. For example adding new functions that work with existing data types. I think that overall both OO and FP have their uses in code and software and a combination of both should be used in order to run things efficiently for whatever purpose that the software may be used for.

Email: sihongspring2011@gmail.com

            <form class="form-horizontal" role="form">

Contact

                        Name

                            <input type="text" class="form-control" id="contact-name" placeholder="First & Last Name">

                        Email

                            <input type="text" class="form-control" id="contact-email" placeholder="example@domain.com">

                        Message

                            <textarea class="form-control" rows="4"></textarea>

                    Close
                    <button type="submit" class="btn btn-primary">Send</button>

            </form>


text:
package wybren_erik.hanzespel.interfaces;

/**
 * Created by wybrenoppedijk on 21/08/2017.
 */

public interface InterventionListener {
    void pirateship();

    void boatLeak();

    void crewOverboard();

    void badWeather();

    void bandit();

    void goodWeather();

    void foundHiddenChest();

    void defeatPirateShip();

    void shortCut();
}


text:
interface service_interface : public authentication_interface,public object_memory_manager_interface
{
public:
    virtual std::wstring& get_name() const;

public:
    service_interface();
    virtual ~service_interface();
};


text:
title: Making Firefox faster
author: Andrei
layout: post
categories:
  - Information Technology
  - Solution
tags:
  - browser
---
Did you notice how Firefox doesn't load pages from the local cache upon hitting the Back button? This is what IE and Opera do, but not Firefox.

In order to speed things up, you need to trick Firefox into doing that. No obvious option exists.

Go to "about:config". Right click inside the window and select New Integer. Enter "browser.sessionhistory.max_viewers" with a value of 5.

Test it. If you don't like it, or you have problems having this feature on, then just delete the new option from the list.


text:
import * as angular from "angular";
import * as toast from "toastr";
import "ngstorage";

import { HttpService, NotificationService, SocketService, TrustedFilter, socket } from "./index";

export const SharedModule: string = angular
    .module("pcard.shared", [
        "ngStorage"
    ])
    .value("$toastr", toast)
    .value("socket", socket)
    .service("httpService", HttpService)
    .service("notificationService", NotificationService)
    .service("socketService", SocketService)
    .filter("trusted", TrustedFilter)
    .name;