text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="disparage">
        <note>
            Frames file for 'disparage' based on sentences in wsj.  Verbnet
            entry 33, FRamenet entry Judgement communication.
        </note>

        <roleset id="disparage.01" name="talk trash" vncls="33">
            <roles>
                <role descr="talker, agent" n="0">
                    <vnrole vncls="33" vntheta="Agent"/>
                </role>
                <role descr="victim" n="1">
                    <vnrole vncls="33" vntheta="Theme"/>
                </role>
            </roles>

            <example name="and seldom was heard...">
                <inflection aspect="ns" form="full" person="ns" tense="present" voice="active"/>
                <text>
                    Yet they don't disparage their audiences by disparaging their
                    act.
                </text>
                <arg n="0">they</arg>
                <arg f="NEG" n="M">n't</arg>
                <rel>disparage</rel>
                <arg n="1">their audiences</arg>
                <arg f="MNR" n="M">by disparaging their act</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
MaterialDesignColorPalette
==========================

This is a dev tool to visualize the colours of Material design defined on http://www.google.com/design/spec/style/color.html#color-ui-color-palette

The tool is based on Danielle Vass colors file :
https://gist.github.com/daniellevass/b0b8cfa773488e138037

It uses Gabriele Mariotti library "Cardslib" :
https://github.com/gabrielemariotti/cardslib

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

namespace BestHTTP.SignalR.JsonEncoders
{
    /// <summary>
    /// Interface to be able to write custom Json encoders/decoders.
    /// </summary>
    public interface IJsonEncoder
    {
        /// <summary>
        /// This function must create a json formatted string from the given object. If the encoding fails, it should return null.
        /// </summary>
        string Encode(object obj);

        /// <summary>
        /// This function must create a dictionary the Json formatted string parameter. If the decoding fails, it should return null.
        /// </summary>
        IDictionary<string, object> DecodeMessage(string json);
    }
}

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ZoomAndDraw.Resources;
using System.Windows.Media;
using System.Windows.Shapes;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;

namespace ZoomAndDraw
{
    public partial class MainPage : PhoneApplicationPage
    {
        private PhotoChooserTask _phototask = new PhotoChooserTask();
        private PhotoResult _photoResult;
        private SolidColorBrush _brush;
        private Polyline _polyline;
        private bool _manipulating;
        bool isPinching;
        Point ptPinchPositionStart;

        public MainPage()
        {
            InitializeComponent();
            _phototask.ShowCamera = true;
            _phototask.Completed += PhotoChooserTask_Completed;
        }
        //yve : remove event
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            ManipulationArea.ManipulationStarted -= AnnotationsCanvas_ManipulationStarted;
            ManipulationArea.ManipulationDelta -= AnnotationsCanvas_ManipulationDelta;
            ManipulationArea.ManipulationCompleted -= AnnotationsCanvas_ManipulationCompleted;
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (_photoResult != null)
            {
                if (_brush == null)
                {
                    _brush = new SolidColorBrush(Colors.Red);
                }
            }
            else
            {
                _brush = null;
            }

            if (_photoResult != null)
            {
                var originalBitmap = new BitmapImage
                {
                    DecodePixelWidth = (int)(480.0 * Application.Current.Host.Content.ScaleFactor / 100.0)
                };

                originalBitmap.SetSource(_photoResult.ChosenPhoto);

                OriginalImage.Source = originalBitmap;

                originalBitmap = null;
                _photoResult = null;
            }

            ManipulationArea.ManipulationStarted += AnnotationsCanvas_ManipulationStarted;
            ManipulationArea.ManipulationDelta += AnnotationsCanvas_ManipulationDelta;
            ManipulationArea.ManipulationCompleted += AnnotationsCanvas_ManipulationCompleted;
        }

        private Point NearestPointInElement(double x, double y, FrameworkElement element)
        {
            var clampedX = Math.Min(Math.Max(0, x), element.ActualWidth);
            var clampedY = Math.Min(Math.Max(0, y), element.ActualHeight);

            return new Point(clampedX, clampedY);
        }

        private void AnnotationsCanvas_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
            if (!isPinching)
            {
                _manipulating = true;

                _polyline = new Polyline
                {
                    Stroke = _brush,
                    StrokeThickness = 6
                };

                var manipulationAreaDeltaX = ManipulationArea.Margin.Left;
                var manipulationAreaDeltaY = ManipulationArea.Margin.Top;

                var point = NearestPointInElement(e.ManipulationOrigin.X + manipulationAreaDeltaX, e.ManipulationOrigin.Y + manipulationAreaDeltaY, AnnotationsCanvas);

                _polyline.Points.Add(point);

                CurrentAnnotationCanvas.Children.Add(_polyline);
            }
        }

        private void AnnotationsCanvas_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            if (!isPinching)
            {
                var manipulationAreaDeltaX = ManipulationArea.Margin.Left;
                var manipulationAreaDeltaY = ManipulationArea.Margin.Top;
                //yve : if you remove translation you use old position
                var x = e.ManipulationOrigin.X + manipulationAreaDeltaX;
                var y = e.ManipulationOrigin.Y  + manipulationAreaDeltaY;

                var point = NearestPointInElement(x, y, AnnotationsCanvas);

                _polyline.Points.Add(point);
            }
        }

        private void AnnotationsCanvas_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            if (!isPinching)
            {
                if (_polyline == null || _polyline.Points.Count < 2)
                {
                    CurrentAnnotationCanvas.Children.Clear();

                    _manipulating = false;
                }
                else
                {
                    CurrentAnnotationCanvas.Children.RemoveAt(CurrentAnnotationCanvas.Children.Count - 1);

                    AnnotationsCanvas.Children.Add(_polyline);

                    _manipulating = false;
                }

                _polyline = null;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _phototask.Show();
        }

        private void PhotoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                _photoResult = e;
            }
        }

        void OnGestureListenerPinchStarted(object sender, PinchStartedGestureEventArgs args)
        {
            isPinching = true;

            //yve : remove current annotation
            CurrentAnnotationCanvas.Children.Clear();
            _manipulating = false;
            _polyline = null;

            if (isPinching)
            {
                // Set transform centers
                Point ptPinchCenter = args.GetPosition(OriginalImage);
                ptPinchCenter = previousTransform.Transform(ptPinchCenter);

                scaleTransform.CenterX = ptPinchCenter.X;
                scaleTransform.CenterY = ptPinchCenter.Y;

                ptPinchPositionStart = args.GetPosition(this);
            }
        }

        void OnGestureListenerPinchDelta(object sender, PinchGestureEventArgs args)
        {
            if (isPinching)
            {
                // Set scaling
                scaleTransform.ScaleX = args.DistanceRatio;
                scaleTransform.ScaleY = args.DistanceRatio;

                // Set translation
                Point ptPinchPosition = args.GetPosition(this);
                translateTransform.X = ptPinchPosition.X - ptPinchPositionStart.X;
                translateTransform.Y = ptPinchPosition.Y - ptPinchPositionStart.Y;
            }
        }

        void OnGestureListenerPinchCompleted(object sender, PinchGestureEventArgs args)
        {
            if (isPinching)
            {
                TransferTransforms();
                isPinching = false;
            }
        }

        void TransferTransforms()
        {
            previousTransform.Matrix = Multiply(previousTransform.Matrix, currentTransform.Value);

            // Set current transforms to default values
            scaleTransform.ScaleX = scaleTransform.ScaleY = 1;
            scaleTransform.CenterX = scaleTransform.CenterY = 0;

            translateTransform.X = translateTransform.Y = 0;
        }

        Matrix Multiply(Matrix A, Matrix B)
        {
            return new Matrix(A.M11 * B.M11 + A.M12 * B.M21,
                              A.M11 * B.M12 + A.M12 * B.M22,
                              A.M21 * B.M11 + A.M22 * B.M21,
                              A.M21 * B.M12 + A.M22 * B.M22,
                              A.OffsetX * B.M11 + A.OffsetY * B.M21 + B.OffsetX,
                              A.OffsetX * B.M12 + A.OffsetY * B.M22 + B.OffsetY);
        }
    }
}


text:
package com.mblinn.oo.tinyweb.stepsix

import java.io.{InputStreamReader, BufferedReader}
import java.net.URLDecoder

import com.sun.net.httpserver.HttpExchange

import scala.util.Random

object Example extends App {

  def greetingViewRenderer(model: Map[String, List[String]]) = {
    def renderGreeting(greeting: String) = "
%s
".format(greeting)
    "
Friendly Greetings:%s".format(
        model
        getOrElse("greetings", List[String]())
        map renderGreeting
        mkString ", ")
  }

  def handleGreetingRequest(request: HttpExchange) = {
    val random = new Random()
    def greetings = Vector("Hello", "Greetings", "Salutations", "Hola")
    def makeGreeting(name: String) = "%s, %s".format(greetings(random.nextInt(greetings.size)), name)
    val params = getParameters(request)
    Map("greetings" -> params("users").split(",").toList.map(makeGreeting))
  }

  def getParameters(request: HttpExchange): Map[String, String] = {
    Map(request.getRequestURI.getQuery.split("&").map{
      pair =>
        val idx = pair.indexOf("=")
        URLDecoder.decode(pair.substring(0, idx), "UTF-8") -> URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
    }.toSeq: _*)
  }

  def loggingFilter(request: HttpExchange): HttpExchange = {
    println("In Logging Filter - request for path: %s".format(request.getRequestURI.toString))
    request
  }

  val tinyweb = new TinyWeb(
      Seq("/greeting" -> (greetingViewRenderer _, handleGreetingRequest _)),
      Seq("logger" -> loggingFilter)
  )

  tinyweb.start
//  def testHttpRequest = HttpRequest(
//      body="Mike,Joe,John,Steve",
//      path="/greeting"
//  )

  val in = new BufferedReader(new InputStreamReader(System.in))
  var c: Int = 0
  while('q'.toInt != { c = in.read(); c }){
    println(c.toChar)
  }
  println("-STOP-")
  tinyweb.executor.shutdownNow()
  tinyweb.stop

}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Auth0.ManagementApi.Models;

namespace Auth0.ManagementApi.Clients
{
    /// <summary>
    /// Contains all the methods to call the /stats endpoints.
    /// </summary>
    public interface IStatsClient
    {
        /// <summary>
        ///     Gets the active users count (logged in during the last 30 days).
        /// </summary>
        /// <returns>The number of users.</returns>
        Task<long> GetActiveUsersAsync();

        /// <summary>
        /// Gets the daily stats for a particular period.
        /// </summary>
        /// <param name="from">The first day of the period (inclusive).</param>
        /// <param name="to">The last day of the period (inclusive).</param>
        /// <returns>A list of <see cref="DailyStatistics"/> containing the statistics for each day in the period.</returns>
        Task<IList<DailyStatistics>> GetDailyStatsAsync(DateTime from, DateTime to);
    }
}


text:
package stroom.processor.impl;

import stroom.cache.api.CacheManager;
import stroom.cache.api.LoadingStroomCache;
import stroom.processor.api.ProcessorFilterService;
import stroom.processor.shared.ProcessorFilter;
import stroom.security.api.SecurityContext;
import stroom.util.shared.Clearable;

import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;

@Singleton
public class ProcessorFilterCache implements Clearable {

    private static final String CACHE_NAME = "Processor Filter Cache";

    private final LoadingStroomCache<Integer, Optional<ProcessorFilter>> cache;
    private final ProcessorFilterService processorFilterService;
    private final SecurityContext securityContext;

    @Inject
    public ProcessorFilterCache(final CacheManager cacheManager,
                                final ProcessorFilterService processorFilterService,
                                final SecurityContext securityContext,
                                final Provider<ProcessorConfig> processorConfigProvider) {
        this.processorFilterService = processorFilterService;
        this.securityContext = securityContext;
        cache = cacheManager.createLoadingCache(
                CACHE_NAME,
                () -> processorConfigProvider.get().getProcessorFilterCache(),
                this::create);
    }

    public Optional<ProcessorFilter> get(final int id) {
        return cache.get(id);
    }

    private Optional<ProcessorFilter> create(final int id) {
        return securityContext.asProcessingUserResult(() -> processorFilterService.fetch(id));
    }

    @Override
    public void clear() {
        cache.clear();
    }
}


text:
import re
import logging

from pp.pkglib.osutil import run

RE_VERSION = re.compile('\d+\.\d+\.\d+')

def get_log():
    return logging.getLogger('pp.pkglib.vcs')

def get_tags():
    """ Returns a list of tags for the cwd
    """
    items =  [ i.strip() for i in  \
               run(['hg','tags'], capture=True).split('\n') \
               if i.strip() ]
    res = {}
    for i in items:
        tag, rev = i.split()
        if tag == 'tip' or not RE_VERSION.match(tag): continue
        res[tag] = rev.split(':')[1]
    return res

def get_revno():
    """ Returns the revision number of the cwd
    """
    return run(['hg','id','-i'],capture=True).strip()

def get_previous_revno(revno):
    """ Retuns the revision number before this one, used
        for detecting similar tags.
    """
    return run(['hg','parents', '-r', revno, '--template',
                '{node}'],capture=True)[:12].strip()


text:
/*
 * Program used in the experimental evaluation of the following paper.
 * 2010SAS - Alias,Darte,Feautrier,Gonnord, Multi-dimensional Rankings, Program Termination, and Complexity Bounds of Flowchart Programs
 *
 * Date: 2014
 * Author: Caterina Urban
 */

extern int __VERIFIER_nondet_int(void);

int main() {
	int N = __VERIFIER_nondet_int();
	int j;
	int i = N;
	while (i > 0) {
		j = N;
		while (j > 0)
			j--;
		i--;
	}
	return 0;
}


text:
<!-- badges/ -->
[![Build Status](https://secure.travis-ci.org/kvz/on-the-githubs.png?branch=master)](http://travis-ci.org/kvz/on-the-githubs "Check this project's build status on TravisCI")
[![NPM version](http://badge.fury.io/js/on-the-githubs.png)](https://npmjs.org/package/on-the-githubs "View this project on NPM")
[![Dependency Status](https://david-dm.org/kvz/on-the-githubs.png?theme=shields.io)](https://david-dm.org/kvz/on-the-githubs)
[![Development Dependency Status](https://david-dm.org/kvz/on-the-githubs/dev-status.png?theme=shields.io)](https://david-dm.org/kvz/on-the-githubs#info=devDependencies)

[![Gittip donate button](http://img.shields.io/gittip/kvz.png)](https://www.gittip.com/kvz/ "Sponsor the development of on-the-githubs via Gittip")
[![Flattr donate button](http://img.shields.io/flattr/donate.png?color=yellow)](https://flattr.com/submit/auto?user_id=kvz&url=https://github.com/kvz/on-the-githubs&title=on-the-githubs&language=&tags=github&category=software "Sponsor the development of on-the-githubs via Flattr")
[![PayPayl donate button](http://img.shields.io/paypal/donate.png?color=yellow)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kevin%40vanzonneveld%2enet&lc=NL&item_name=Open%20source%20donation%20to%20Kevin%20van%20Zonneveld&currency_code=USD&bn=PP-DonationsBF%3abtn_donate_SM%2egif%3aNonHosted "Sponsor the development of on-the-githubs via Paypal")
[![BitCoin donate button](http://img.shields.io/bitcoin/donate.png?color=yellow)](https://coinbase.com/checkouts/19BtCjLCboRgTAXiaEvnvkdoRyjd843Dg2 "Sponsor the development of on-the-githubs via BitCoin")
<!-- /badges -->

Demo: http://kvz.github.io/on-the-githubs/#repos/kvz/nsfailover

To grow an open-source community it helps if your site has an active overview of what's going on and who
is contributing.

The GitHub API3 provides all the information we need, but you may hit rate-limiters, or find it hard / have no time to embed this data into your website.

This project aims to make it deadsimple to add community info & activity feeds to your project's site.

## On the Githubs example

On the Githubs is a jquery plugin for a near-realtime overview of activity of a user, project or organisation.
It does not require any buildsteps or setup, just add a few lines of code to your project's HTML.

Demo: http://kvz.github.io/on-the-githubs/#repos/kvz/nsfailover

Or your own:

 - http://kvz.github.io/on-the-githubs/#repos/`{user}`/`{repo}`
 - http://kvz.github.io/on-the-githubs/#users/`{user}`
 - http://kvz.github.io/on-the-githubs/#orgs/`{org}`

To embed this into your site, add a few lines of code:

```html
<link href="//kvz.github.io/on-the-githubs/css/on-the-githubs.min.css" rel="stylesheet" />

<div class="on-the-githubs" data-event-source="repos/kvz/nsfailover">Loading...</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//kvz.github.io/on-the-githubs/js/jquery.on-the-githubs.min.js"></script>

<script type="text/javascript">
  $('.on-the-githubs').onthegithubs();
  // If you use bootstrap and want to enable tooltips
  // $('a[rel]').tooltip();
</script>
```

Don't forget to change the `data-event-source` to repos/`{user}`/`{repo}`.

## On the Githubs development

For local development, here's how to run the repo-included demo:

```bash
npm install --dev
make build
node demo-server.js
```

- Point your browser to http://127.0.0.1:8080

# Bonus: In the Githubs

Activity is limited to the last 20-100 events, but communities grow big.
If you want to give credit where credit is due and show all the faces that make your community,
we can't just pull that in in realtime from the API without hindering the UI or hitting GitHub's
rate-limiter.

So this is something we have to aggregate, cache, and compile at your site's buildtime.

## In the Githubs examples

Get all people involved with `kvz/nsfailver` and echo as json to `stdout`

```bash
./bin/in-the-githubs --user kvz --repo nsfailover --format json --output -
```

Index an entire organization, read `test/about.md`, search it for the `{{community}}` tag,
replace it with the entire `tus` community, write it to `test/about-with-community.md`, do this with `1` request at a time, to ensure the order of userpaths. Enable `debug`ging to see what's going on, because with the amount of API requests & GitHubs rate-limiting, this is going to take a while (the script automatically waits as to not have your IP banned by GitHub).

```bash
./bin/in-the-githubs \
 --user tus \
 --repo tus.io,tusd,tus-jquery-client,tus-ios-client,tus-android-client,tus-resumable-upload-protocol \
 --format html \
 --concurrency 1 \
 --input demo.html \
 --tag '<div class="in-the-githubs" />' \
 --output demo-with-community.html \
 --debug
```

Help:

```bash
./bin/in-the-githubs -h
```

## Integrate In the Githubs

Let's say your site is now built with Jekyll into `./_site`.
You have an `about.md` that you want to add community faces to.

First, let's make on-the-githubs a dependency:

```bash
[ -d node_modules ] || mkdir node_modules
npm install on-the-githubs --save
```

Now add something like this to a `Makefile`:

```bash
community:
	node_modules/on-the-githubs/bin/in-the-githubs \
	 --user tus \
	 --repo tusd,tus-jquery-client \
	 --format html \
	 --concurrency 1 \
	 --input _site/about.html \
	 --tag '<p>replaced-by-in-the-githubs</p>' \
	 --output _site/about.html \
	 --debug
```

Now if you type `make community` after `jekyll build`, `in-the-githubs` will look for the
`<p>replaced-by-in-the-githubs</p>` placeholder, and replace it with all the involved GitHub
profiles.

By default, `in-the-githubs` caches to `~/.in-the-githubs/` to avoid rate-limiters.

## Requirements

- Node 0.8+

## License

This project is licensed under the MIT license, see `LICENSE.txt`.

Contains code of [jquery-timeago](https://github.com/rmm5t/jquery-timeago)
by [Ryan McGeary](https://github.com/rmm5t/jquery-timeago/blob/master/LICENSE.txt)


text:
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.EffectComposer = function ( renderer, renderTarget ) {

	this.renderer = renderer;

	if ( renderTarget === undefined ) {

		var width = window.innerWidth || 1;
		var height = window.innerHeight || 1;
		var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };

		renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );

	}

	this.renderTarget1 = renderTarget;
	this.renderTarget2 = renderTarget.clone();

	this.writeBuffer = this.renderTarget1;
	this.readBuffer = this.renderTarget2;

	this.passes = [];

	if ( THREE.CopyShader === undefined )
		console.error( "THREE.EffectComposer relies on THREE.CopyShader" );

	this.copyPass = new THREE.ShaderPass( THREE.CopyShader );

};

THREE.EffectComposer.prototype = {

	swapBuffers: function() {

		var tmp = this.readBuffer;
		this.readBuffer = this.writeBuffer;
		this.writeBuffer = tmp;

	},

	addPass: function ( pass ) {

		this.passes.push( pass );

	},

	insertPass: function ( pass, index ) {

		this.passes.splice( index, 0, pass );

	},

	render: function ( delta ) {

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

		var maskActive = false;

		var pass, i, il = this.passes.length;

		for ( i = 0; i < il; i ++ ) {

			pass = this.passes[ i ];

			if ( !pass.enabled ) continue;

			pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive );

			if ( pass.needsSwap ) {

				if ( maskActive ) {

					var context = this.renderer.context;

					context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );

					this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta );

					context.stencilFunc( context.EQUAL, 1, 0xffffffff );

				}

				this.swapBuffers();

			}

			if ( pass instanceof THREE.MaskPass ) {

				maskActive = true;

			} else if ( pass instanceof THREE.ClearMaskPass ) {

				maskActive = false;

			}

		}

	},

	reset: function ( renderTarget ) {

		if ( renderTarget === undefined ) {

			renderTarget = this.renderTarget1.clone();

			renderTarget.width = window.innerWidth;
			renderTarget.height = window.innerHeight;

		}

		this.renderTarget1 = renderTarget;
		this.renderTarget2 = renderTarget.clone();

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

	},

	setSize: function ( width, height ) {

		var renderTarget = this.renderTarget1.clone();

		renderTarget.width = width;
		renderTarget.height = height;

		this.reset( renderTarget );

	}

};


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

#import <Foundation/Foundation.h>
#import <DBPerformanceWidgetView.h>

@class DBPerformanceToolkit;

/**
 A protocol used for informing about refreshing the performance data.
 */
@protocol DBPerformanceToolkitDelegate <NSObject>

/**
 Informs the delegate that there are new stats available.
 @param performanceToolkit The object that refreshed stats and can now be accessed to retrieve them.
 */
- (void)performanceToolkitDidUpdateStats:(DBPerformanceToolkit *)performanceToolkit;

@end

/**
 `DBPerformanceToolkit` is a class responsible for the features seen in the `DBPerformanceTableViewController`.
 It calculates the performance stats, handles showing widget and can also simulate memory warning.
 */
@interface DBPerformanceToolkit : NSObject

/**
 Delegate that will be informed about new stats available. It needs to conform to `DBPerformanceToolkitDelegate` protocol.
 */
@property (nonatomic, weak) id <DBPerformanceToolkitDelegate> delegate;

/**
 Created widget showing current CPU usage, memory usage and frames per second value.
 */
@property (nonatomic, readonly) DBPerformanceWidgetView *widget;

/**
 Boolean determining whether the widget should be shown or not.
 */
@property (nonatomic, assign) BOOL isWidgetShown;

///----------
/// @name CPU
///----------

/**
 An array of last measurements of the CPU usage.
 */
@property (nonatomic, readonly) NSArray *cpuMeasurements;

/**
 Current CPU usage.
 */
@property (nonatomic, readonly) CGFloat currentCPU;

/**
 Maximal recorded CPU usage.
 */
@property (nonatomic, readonly) CGFloat maxCPU;

///-------------
/// @name Memory
///-------------

/**
 An array of last measurements of the memory usage.
 */
@property (nonatomic, readonly) NSArray *memoryMeasurements;

/**
 Current memory usage.
 */
@property (nonatomic, readonly) CGFloat currentMemory;

/**
 Maximal recorded memory usage.
 */
@property (nonatomic, readonly) CGFloat maxMemory;

///----------
/// @name FPS
///----------

/**
 An array of last measurements of the frames per second value.
 */
@property (nonatomic, readonly) NSArray *fpsMeasurements;

/**
 Current frames per second value.
 */
@property (nonatomic, readonly) CGFloat currentFPS;

/**
 Minimal recorded frames per second value.
 */
@property (nonatomic, readonly) CGFloat minFPS;

/**
 Maximal recorded frames per second value.
 */
@property (nonatomic, readonly) CGFloat maxFPS;

/**
 The limit of memorized measurements. When reached, a new measurement will override the oldest one.
 */
@property (nonatomic, readonly) NSInteger measurementsLimit;

///---------------------
/// @name Initialization
///---------------------

/**
 Initializes `DBPerformanceToolkit` object with provided delegate, that will be informed about widget taps.

 @param widgetDelegate A delegate for the performance widget. It has to conform to `DBPerformanceWidgetViewDelegate` protocol.
 */
- (instancetype)initWithWidgetDelegate:(id <DBPerformanceWidgetViewDelegate>)widgetDelegate;

/**
 Simulates the memory warning.
 */
- (void)simulateMemoryWarning;

/**
 Returns time in seconds between the measurements.
 */
- (NSTimeInterval)timeBetweenMeasurements;

@end


text:
package io.eels.component.parquet

import com.sksamuel.exts.Logging
import io.eels.schema.StructType
import io.eels.{Predicate, Row}
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import org.apache.parquet.filter2.compat.FilterCompat
import org.apache.parquet.format.converter.ParquetMetadataConverter
import org.apache.parquet.hadoop.api.ReadSupport
import org.apache.parquet.hadoop.{ParquetFileReader, ParquetReader}
import org.apache.parquet.schema.Type

/**
  * Helper function to create a native parquet reader for Row objects, using the apache parquet library.
  * The reader supports optional predicate (for row filtering) and a
  * projection schema (for column filtering).
  */
object RowParquetReaderFn extends Logging {

  private val config = ParquetReaderConfig()

  def schema(path: Path)(implicit conf: Configuration): StructType = {
    val mt = ParquetFileReader.readFooter(conf, path, ParquetMetadataConverter.NO_FILTER).getFileMetaData.getSchema
    ParquetSchemaFns.fromParquetMessageType(mt)
  }

  /**
    * Creates a new reader for the given path.
    *
    * @param predicate  if set then a parquet predicate is applied to the rows
    * @param readSchema optional schema used as a projection in the native parquet reader
    */
  def apply(path: Path,
            predicate: Option[Predicate],
            readSchema: Option[Type],
            dictionaryFiltering: Boolean)(implicit conf: Configuration): ParquetReader[Row] = {
    logger.debug(s"Opening parquet reader for $path")

    // The parquet reader can use a projection by setting a projected schema onto the supplied conf object
    def configuration(): Configuration = {
      val newconf = new Configuration(conf)
      readSchema.foreach { it =>
        newconf.set(ReadSupport.PARQUET_READ_SCHEMA, it.toString)
      }
      //newconf.set(ParquetInputFormat.DICTIONARY_FILTERING_ENABLED, dictionaryFiltering.toString)
      newconf.set(org.apache.parquet.hadoop.ParquetFileReader.PARQUET_READ_PARALLELISM, config.parallelism.toString)
      newconf
    }

    // a filter is set when we have a predicate for the read
    def filter(): FilterCompat.Filter = predicate.map(ParquetPredicateBuilder.build)
      .map(FilterCompat.get)
      .getOrElse(FilterCompat.NOOP)

    ParquetReader.builder(new RowReadSupport, path)
      .withConf(configuration())
      .withFilter(filter())
      .build()
  }
}


text:
% LaTeX resume using res.cls
\documentclass[margin,4pt]{res} % default is 10 pt
\usepackage{hyperref}
\addtolength{\topmargin}{-0.35in}
\addtolength{\oddsidemargin}{-.24in}
\addtolength{\evensidemargin}{.5in}
\addtolength{\textwidth}{0.2in}
\addtolength{\textheight}{0.75in}
\textheight 10.25in

\renewcommand{\familydefault}{\sfdefault}

\begin{document}

\name{Viraj Sinha}

\address{
virajosinha@gmail\\
vsinha.com \\
github.com/vsinha
}

%\address{
%virajosinha@gmail.com\\
%vsinha.com \\
% \hyperref[github.com/vsinha]{''github.com/vsinha''}
%github.com/vsinha

%}%
\address{1629 Summit Ave \#403\\ Seattle, WA 98122\\(408) 505-1275}

\begin{resume}

%\section{OBJECTIVES}To work on interesting projects with knowledgable team members. To continue to build
%my design and software engineering experience, hone my programming abilities, and acquire new skills
%n an environment where people enjoy what they're doing. To learn everything possible.

%\section{OBJECTIVES}To work on interesting projects with good people.

\section{EXPERIENCE}

	{\sl Software Engineer} \hfill January 2016 - Present\\
		Microsoft, Bellevue, WA
		\begin{itemize} \itemsep -2pt
		\item Building a pipeline for \textbf{realtime video processing}, lets you chain together arbitrary machine learning models and techniques for a wide range of scenarios, including traffic anaylsis.
		\item \textbf{Bing Ads} experimentation
		\item Built several \textbf{VR concept projects} in a 3 month experimentation sprint
		\item Built a service for adding \textbf{location awareness to mobile apps} (www.loop.ms)
		\item Built a \textbf{location aware athletics iOS app} to track runs and bike rides
		\item DevOps and tooling for our containerized server infrastructure (\textbf{Docker/Kubernetes})
		\item Experimenting w/ team culture in a \textbf{healthy and cooperative work environment}
		\end{itemize}

	{\sl Software Engineer (part-time)} \hfill January 2018 - Present\\
		Neurolex Diagnostics, Inc
		\begin{itemize} \itemsep -2pt
		\item Machine learning using voice analysis to  \textbf{help diagnose mental health disorders}
		\item Building a pipeline for  \textbf{handling and processing audio files}
		\end{itemize}

%%	{\sl Program Manager} \hfill September - December 2015\\
%%		Microsoft, Bellevue, WA
%%		\begin{itemize} \itemsep -2pt
%%		\item Learned a  \textbf{lot} about Microsoft. Worked on office.com team.
%%		\end{itemize}

	{\sl Software Engineer, Contractor} \hfill April - May 2015\\
		OpenTrons, Inc., Brooklyn, NY
		\begin{itemize} \itemsep -2pt
		\item Worked on a 3D printer-esque robot to  \textbf{automate biology experiments}
		\item Developed control and connectivity systems as the 'brain' of the OT.one robot
		\end{itemize}

%	{\sl Recurse Center (formerly Hacker School) Never Graduate} \hfill Spring I 2015\\
%		Hacker School, Manhattan NYC, NY
%		\begin{itemize} \itemsep -2pt
%		\item Explored functional programming through a massive music player project in Scala and several smaller tools in Haskell
%		\item Created several small projects to explore deep understanding of computers \& computer science, including implementing traceroute
%		\end{itemize}

	{\sl Engineering Intern} \hfill Summer 2014\\
          Numenta, Inc., Redwood City, CA
		\begin{itemize} \itemsep -2pt
%	   	\item Numenta is building computers which use the same general purpose pattern recognition algortihms as our human brains, learned a lot about computational neuroscience and AI
		\item Built a stock market anomaly detection tool using Numenta's open source software
		\item Investigated and worked to optimize ML model serialization \& swapping performance
		\end{itemize}

%	{\sl IT Technician} \hfill March 2012 - May 2014 \\
%        	Krannert School of Management, Purdue University
%		\begin{itemize} \itemsep -2pt
%	        \item Sysadmin duties for Purude econ/business/marketing schools
%           \item Provided patient on-site technical support for nontechnical faculty, staff, and students
%		\end{itemize}

	{\sl Undergraduate Researcher} \hfill Summer 2012\\
          Neuroprosthesis Research Lab, Purdue University
	    	\begin{itemize} \itemsep -2pt
	    	\item Developed software reading from electrodes implanted in rat brains
%	    	\item Worked with graduate students on neural implant electrode coatings research
	    	\end{itemize}

	{\sl Software Development Intern} \hfill Summer 2011\\
          Intrepid Technology, Inc., Palo Alto, CA
          \begin{itemize}  \itemsep -2pt
		\item Contributed Unified Parallel C (UPC) support to GNU Indent
		\item Wrote a multithreaded A/B search-based "AI" Mancala player in C/UPC
		\end{itemize}

\section{EDUCATION (formal)}
	{\sl Recurse Center (formerly Hacker School)} \hfill (SP1'15) February 2015 - May 2015\\
		Manhattan, NY

	{\sl Bachelor of Science} Computer Science\hfill  December 2014\\
		Purdue University, West Lafayette, IN\\
%		Major: Computer Science\\
%		Minors: Biology, Philosophy, Psychology \\
%		\textbf{Major}: Computer Science, \textbf{Minors}: Biology, Philosophy, Psychology \\
		Minors: Biology, Philosophy, Psychology \\
%		GPA: 0x4039999a (IEEE 754) \\
%		GPA: $ ((\lambda x . \lambda y . \lambda z . \, z \, x \, y) (\lambda f . \lambda x . f(f(x)) (\lambda f . \lambda x . f(f(f(f(f(f(f(f(f(x))))))))))))  $
%		Favorite Classes: Compilers, Computational Neurosceince, Organic Chemistry
%

\section{SOME SKILLS}
	{\bf Favorite languages:} Typescript, JavaScript (node.js), Swift (iOS)\\
 	{\bf Experienced with:}  C\#, Python, Java, Embedded C/C++ with the Arduino platform \\
	{\bf Tools:} UNIX, Kubernetes, Mesos / DC/OS, Docker, Unity, Blender

\section{TRIVIA}
%	Executive Teammate on BoilerMake, Purdue's hackathon (400 students, \$250,000 in funding)\\
	Won "Most Viable Startup" and "Most Technically Impressive" awards at MHacks III\\
	FIRST Robotics Competition Mentor (team 1646) and Team Captain (team 2367)\\
%	Purdue FIRST Robotics Mentor for Jefferson High School Team 1646\\
%	FIRST Robotics Team Captain for Saint Francis High School Team 2367\\
%	Co-Founder and Vice President of Student Think Tank for India (STTI) \\
%	Semi-professional event and hobby photographer\\
%	Center For Applied Rationality (CFAR) alumnus\\
%	Amateur Radio (HAM) Technician\\
	Airplane Pilot (Cessna 172)\\
%	Quadcopter Engineer (hobbyist)\\
	Beekeeper\\
%	Learning enthusiast\\
%	Human utility belt\\
%	Vim user \\

%\section{REFERENCES}
%	Available on request.

\end{resume}
\end{document}


text:
namespace visualdl {

struct ScalarTestHelper {
  ImHelper rim;
  ImHelper wim;
  const std::string dir = "./tmp/sdk_test.test";

  void operator()(std::function<void()> read, std::function<void()> write) {
    wim.StartWriteSerice(dir, 200);
    write();

    // should wait for the write service create log's path
    std::this_thread::sleep_for(std::chrono::milliseconds(400));
    rim.StartReadService(dir, 100);
    // should wait for the read service to load "tag0" tablet into memory
    std::this_thread::sleep_for(std::chrono::milliseconds(600));
    read();
  }
};

TEST(Scalar, set_caption) {
  ScalarTestHelper helper;

  const std::vector<std::string> captions({"train", "test"});

  auto write = [&] {
    auto tablet = helper.wim.AddTablet("tag0", -1);
    components::ScalarHelper<float> scalar(tablet, &helper.wim.handler());

    scalar.SetCaptions(captions);
  };

  auto read = [&] {
    auto mytablet = helper.rim.tablet("tag0");
    components::ScalarHelper<float> myscalar(mytablet, &helper.rim.handler());
    auto mycaptions = myscalar.GetCaptions();

    ASSERT_EQ(captions, mycaptions);
  };

  helper(read, write);
}

TEST(Scalar, add_records) {
  ScalarTestHelper helper;

  const std::vector<std::string> captions({"train", "test"});

  const size_t nsteps = 100;

  auto write = [&] {
    auto tablet = helper.wim.AddTablet("tag0", -1);
    components::ScalarHelper<float> scalar(tablet, &helper.wim.handler());

    scalar.SetCaptions(captions);

    for (int i = 0; i < nsteps; i++) {
      scalar.AddRecord(i * 10, std::vector<float>({(float)i, (float)i + 1}));
    }
  };

  auto read = [&] {
    auto mytablet = helper.rim.tablet("tag0");
    components::ScalarHelper<float> myscalar(mytablet, &helper.rim.handler());

    auto records = myscalar.GetRecords();
    ASSERT_EQ(records.size(), nsteps);

    for (int i = 0; i < nsteps; i++) {
      ASSERT_EQ(records[i], std::vector<float>({(float)i, (float)i + 1}));
    }
  };

  helper(read, write);
}

}  // namespace visualdl


text:
package io.motown.mobieurope.destination.service;

import io.motown.domain.api.chargingstation.*;
import io.motown.domain.api.security.IdentityContext;
import io.motown.domain.api.security.SimpleUserIdentity;
import io.motown.domain.api.security.TypeBasedAddOnIdentity;
import io.motown.domain.utils.axon.EventWaitingGateway;
import io.motown.domain.utils.axon.FutureEventCallback;
import io.motown.mobieurope.destination.entities.DestinationAuthorizeRequest;
import io.motown.mobieurope.destination.entities.DestinationRequestStartTransactionRequest;
import io.motown.mobieurope.destination.entities.DestinationRequestStopTransactionRequest;
import io.motown.mobieurope.destination.persistence.repository.DestinationSessionRepository;
import io.motown.mobieurope.destination.util.AuthorizationIdentifier;
import io.motown.mobieurope.shared.persistence.entities.SessionInfo;
import org.axonframework.domain.EventMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DestinationService {

    private static final Logger LOG = LoggerFactory.getLogger(DestinationService.class);

    private DestinationSessionRepository destinationSessionRepository;

    private EventWaitingGateway eventWaitingGateway;

    public void setDestinationSessionRepository(DestinationSessionRepository destinationSessionRepository) {
        this.destinationSessionRepository = destinationSessionRepository;
    }

    public void setEventWaitingGateway(EventWaitingGateway eventWaitingGateway) {
        this.eventWaitingGateway = eventWaitingGateway;
    }

    public String authorize(DestinationAuthorizeRequest destinationAuthorizeRequest) {
        // TODO: Check if all prerequisites within the infrastructure are met before generating an authorizationIdentifier
        String authorizationIdentifier = new AuthorizationIdentifier().getValue();
        createAndPersistSession(destinationAuthorizeRequest, authorizationIdentifier);
        return authorizationIdentifier;
    }

    public void requestStartTransaction(DestinationRequestStartTransactionRequest startTransactionRequest) {
        LOG.trace("requestStartTransaction called");
        final SessionInfo sessionInfo = destinationSessionRepository.findSessionInfoByAuthorizationId(startTransactionRequest.getAuthorizationIdentifier());
        sessionInfo.setRequestIdentifier(startTransactionRequest.getRequestIdentifier());
        sessionInfo.getSessionStateMachine().eventStartRequest();

        ChargingStationId chargingStationId = new ChargingStationId(sessionInfo.getLocalServiceIdentifier());
        IdentifyingToken identifyingToken = new TextualToken(sessionInfo.getAuthorizationIdentifier());
        EvseId evseId = new EvseId(Integer.parseInt(sessionInfo.getConnectorIdentifier()));

        IdentityContext identityContext = new IdentityContext(new TypeBasedAddOnIdentity("MobiEurope", "1"), new SimpleUserIdentity("root"));
        RequestStartTransactionCommand command = new RequestStartTransactionCommand(chargingStationId, identifyingToken, evseId, identityContext);

        FutureEventCallback<RequestStartTransactionResultEvent> futureEventCallback = new FutureEventCallback<RequestStartTransactionResultEvent>() {
            @Override
            public boolean onEvent(EventMessage<?> event) {
                if (event.getPayload() instanceof RequestStartTransactionAcceptedEvent) {
                    RequestStartTransactionAcceptedEvent requestStartTransactionAcceptedEvent = (RequestStartTransactionAcceptedEvent) event.getPayload();
                    LOG.info("RequestStartTransactionAcceptedEvent successfully received " + requestStartTransactionAcceptedEvent);
                    return true;
                }
                if (event.getPayload() instanceof RequestStartTransactionRejectedEvent) {
                    RequestStartTransactionRejectedEvent requestStartTransactionRejectedEvent = (RequestStartTransactionRejectedEvent) event.getPayload();
                    LOG.info("RequestStartTransactionRejectedEvent successfully received " + requestStartTransactionRejectedEvent);
                    return true;
                }
                return false;
            }
        };

        Long timeout = 10000L;

        try {
            eventWaitingGateway.sendAndWaitForEvent(command, futureEventCallback, timeout);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        } finally {
            destinationSessionRepository.insertOrUpdateSessionInfo(sessionInfo);
        }
    }

    public void requestStopTransaction(DestinationRequestStopTransactionRequest stopTransactionRequest) {
        LOG.trace("requestStopTransaction called");
        final SessionInfo sessionInfo = destinationSessionRepository.findSessionInfoByAuthorizationId(stopTransactionRequest.getAuthorizationIdentifier());
        sessionInfo.setRequestIdentifier(stopTransactionRequest.getRequestIdentifier());
        sessionInfo.getSessionStateMachine().eventStopRequest();

        ChargingStationId chargingStationId = new ChargingStationId(sessionInfo.getLocalServiceIdentifier());

        IdentityContext identityContext = new IdentityContext(new TypeBasedAddOnIdentity("MobiEurope", "1"), new SimpleUserIdentity("root"));

        TransactionId transactionId = new NumberedTransactionId(chargingStationId, "OCPP15", sessionInfo.getTransactionId());
        Object command = new RequestStopTransactionCommand(chargingStationId, transactionId, identityContext);

        FutureEventCallback<RequestStopTransactionResultEvent> futureEventCallback = new FutureEventCallback<RequestStopTransactionResultEvent>() {
            @Override
            public boolean onEvent(EventMessage<?> event) {
                if (event.getPayload() instanceof RequestStopTransactionAcceptedEvent) {
                    RequestStopTransactionAcceptedEvent requestStopTransactionAcceptedEvent = (RequestStopTransactionAcceptedEvent) event.getPayload();
                    LOG.info("RequestStopTransactionAcceptedEvent successfully received " + requestStopTransactionAcceptedEvent);
                    return true;
                }
                if (event.getPayload() instanceof RequestStopTransactionRejectedEvent) {
                    RequestStopTransactionRejectedEvent requestStopTransactionRejectedEvent = (RequestStopTransactionRejectedEvent) event.getPayload();
                    LOG.info("RequestStopTransactionRejectedEvent successfully received " + requestStopTransactionRejectedEvent);
                    return true;
                }
                return false;
            }
        };

        Long timeout = 10000L;

        try {
            eventWaitingGateway.sendAndWaitForEvent(command, futureEventCallback, timeout);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        } finally {
            destinationSessionRepository.insertOrUpdateSessionInfo(sessionInfo);
        }
    }

    private void createAndPersistSession(DestinationAuthorizeRequest destinationAuthorizeRequest, String authorizationId) {
        SessionInfo sessionInfo = new SessionInfo(new SessionStateMachineImpl());
        sessionInfo.setAuthorizationIdentifier(authorizationId);
        sessionInfo.setUserIdentifier(destinationAuthorizeRequest.getUserIdentifier());
        sessionInfo.setServiceTypeIdentifier(destinationAuthorizeRequest.getServiceTypeIdentifier());
        sessionInfo.setPmsIdentifier(destinationAuthorizeRequest.getPmsIdentifier());
        sessionInfo.setLocalServiceIdentifier(destinationAuthorizeRequest.getLocalServiceIdentifier());
        sessionInfo.setConnectorIdentifier(destinationAuthorizeRequest.getConnectorIdentifier());
        destinationSessionRepository.insertOrUpdateSessionInfo(sessionInfo);
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace net.authorize.sample
{
    class GetUnsettledTransactionList
    {
    }
}


text:
layout: page
title: Christensen Solutions Conference
date: 2016-05-24
author: Emily Sosa
tags: weekly links, java
status: published
summary: Ut ut elit eget nisl iaculis ultricies.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 04/09/2018
  endDate: 04/11/2018
  ctyhocn: CLLTXHX
  groupCode: CSC
published: true
---
Vivamus justo nisi, rutrum eu sagittis non, gravida sed sem. Aliquam ut finibus risus. Mauris eu sapien egestas, vehicula metus eget, congue ligula. Aliquam mattis, mauris id hendrerit sodales, diam lectus accumsan arcu, interdum scelerisque ipsum augue sed nunc. Integer ornare neque id pellentesque sodales. Etiam aliquam tempor mauris bibendum ultricies. Aenean sit amet efficitur mi. In vitae nisi elementum, accumsan eros sit amet, pretium diam. Proin hendrerit congue risus, eget porttitor nunc commodo venenatis. Vestibulum ac lorem eget ante maximus mollis ut id enim. Phasellus mattis mauris ex, non mattis metus finibus quis. Sed ut dui ac ligula aliquet finibus ac in nunc. Donec eget leo nisi. Mauris volutpat nisi ut nisl venenatis tristique.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam at tortor justo. Ut erat nibh, condimentum ut bibendum sed, pellentesque at leo. Maecenas convallis, odio eget euismod fermentum, arcu libero vestibulum ipsum, sed mollis odio nisl nec nisi. Duis euismod sollicitudin purus. Suspendisse consequat nec nunc sed fermentum. Vivamus facilisis, libero non rutrum pulvinar, metus nibh sollicitudin odio, at ultrices sapien urna ut tortor. Suspendisse et ultrices urna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

* Aliquam lobortis nunc id fermentum rutrum
* Donec venenatis turpis vitae enim maximus, vel consectetur nibh egestas
* Nunc eget nibh accumsan, vestibulum lectus in, porttitor est.

Donec eget magna non metus auctor suscipit eu non erat. Cras nibh ex, fringilla eget mauris ac, vehicula iaculis neque. Etiam augue odio, consequat et ipsum nec, luctus aliquet leo. Aenean et nulla orci. Vivamus pulvinar, augue et aliquam pretium, turpis felis pellentesque orci, nec volutpat mauris velit sed est. Maecenas vel quam ut nunc venenatis dignissim. Morbi at mauris mi. Fusce at sem neque. Integer nec molestie mi.


text:
Welcome to my dotfiles, they target OS X and aim to back up and synchronize my settings and custom commands. The goal is to make setting up a brand new machine as simple as running the install script.

I was inspired by the following
* https://dotfiles.github.io/
* https://github.com/mathiasbynens/dotfiles
* https://github.com/holman/dotfiles
* https://github.com/webpro/dotfiles

## Installation
Clone the repo and run install.sh to kick things off
```sh
git clone https://github.com/rickyabell/dotfiles.git
cd dotfiles && source install.sh
```

## OSX defaults
To configure OSX defaults run
```sh
source osx/.osx
```

## Update
To update the dotfiles on a machine, run
```sh
source install.sh
```
which will update the git repo and update all of the local dotfiles.


text:
/* Detect cycle in singly-linked list using Floyd Cycle Detection algorithm */

typedef struct ListNode ListNode;

struct ListNode {
    int val;
    ListNode* next;
    ListNode(val): val(val), next(NULL) {}
};

bool hasCycle(ListNode* head) {
    if (head == NULL)   return false;
    ListNode* slow = head;
    ListNode* fast = head;
    while (fast->next != NULL && fast->next->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) {
            return true;
        }
    }
    return false;
}


text:
package com.opengamma.analytics.math.function;

import org.apache.commons.lang.NotImplementedException;

import com.opengamma.analytics.math.FunctionUtils;
import com.opengamma.analytics.math.interpolation.PiecewisePolynomialResultsWithSensitivity;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.analytics.math.matrix.MatrixAlgebra;
import com.opengamma.analytics.math.matrix.OGMatrixAlgebra;
import com.opengamma.util.ArgumentChecker;

/**
 * Give a class {@link PiecewisePolynomialResultsWithSensitivity}, Compute node sensitivity of function value, first derivative value and second derivative value
 */
public class PiecewisePolynomialWithSensitivityFunction1D extends PiecewisePolynomialFunction1D {

  private static final MatrixAlgebra MA = new OGMatrixAlgebra();

  /**
   * @param pp {@link PiecewisePolynomialResultsWithSensitivity}
   * @param xKey
   * @return Node sensitivity value at x=xKey
   */
  public DoubleMatrix1D nodeSensitivity(final PiecewisePolynomialResultsWithSensitivity pp, final double xKey) {
    ArgumentChecker.notNull(pp, "null pp");
    ArgumentChecker.isFalse(Double.isNaN(xKey), "xKey containing NaN");
    ArgumentChecker.isFalse(Double.isInfinite(xKey), "xKey containing Infinity");

    if (pp.getDimensions() > 1) {
      throw new NotImplementedException();
    }

    final double[] knots = pp.getKnots().getData();
    final int nKnots = knots.length;
    int interval = FunctionUtils.getLowerBoundIndex(knots, xKey);
    if (interval == nKnots - 1) {
      interval--; // there is 1 less interval that knots
    }

    final double s = xKey - knots[interval];
    final DoubleMatrix2D a = pp.getCoefficientSensitivity(interval);
    final int nCoefs = a.getNumberOfRows();

    DoubleMatrix1D res = a.getRowVector(0);
    for (int i = 1; i < nCoefs; i++) {
      res = (DoubleMatrix1D) MA.scale(res, s);
      res = (DoubleMatrix1D) MA.add(res, a.getRowVector(i));
    }

    return res;
  }

  /**
   * @param pp {@link PiecewisePolynomialResultsWithSensitivity}
   * @param xKeys
   * @return Node sensitivity value at x=xKeys
   */
  public DoubleMatrix1D[] nodeSensitivity(final PiecewisePolynomialResultsWithSensitivity pp, final double[] xKeys) {
    ArgumentChecker.notNull(pp, "null pp");
    ArgumentChecker.notNull(xKeys, "null xKeys");
    final int nKeys = xKeys.length;
    final DoubleMatrix1D[] res = new DoubleMatrix1D[nKeys];

    for (int i = 0; i < nKeys; ++i) {
      ArgumentChecker.isFalse(Double.isNaN(xKeys[i]), "xKey containing NaN");
      ArgumentChecker.isFalse(Double.isInfinite(xKeys[i]), "xKey containing Infinity");
    }
    if (pp.getDimensions() > 1) {
      throw new NotImplementedException();
    }

    final double[] knots = pp.getKnots().getData();
    final int nKnots = knots.length;

    for (int j = 0; j < nKeys; ++j) {
      final double xKey = xKeys[j];
      int interval = FunctionUtils.getLowerBoundIndex(knots, xKey);
      if (interval == nKnots - 1) {
        interval--; // there is 1 less interval that knots
      }

      final double s = xKey - knots[interval];
      final DoubleMatrix2D a = pp.getCoefficientSensitivity(interval);
      final int nCoefs = a.getNumberOfRows();

      res[j] = a.getRowVector(0);
      for (int i = 1; i < nCoefs; i++) {
        res[j] = (DoubleMatrix1D) MA.scale(res[j], s);
        res[j] = (DoubleMatrix1D) MA.add(res[j], a.getRowVector(i));
      }
    }

    return res;
  }

  /**
   * @param pp {@link PiecewisePolynomialResultsWithSensitivity}
   * @param xKey
   * @return Node sensitivity of derivative value at x=xKey
   */
  public DoubleMatrix1D differentiateNodeSensitivity(final PiecewisePolynomialResultsWithSensitivity pp, final double xKey) {
    ArgumentChecker.notNull(pp, "null pp");
    ArgumentChecker.isFalse(Double.isNaN(xKey), "xKey containing NaN");
    ArgumentChecker.isFalse(Double.isInfinite(xKey), "xKey containing Infinity");

    if (pp.getDimensions() > 1) {
      throw new NotImplementedException();
    }
    final int nCoefs = pp.getOrder();
    ArgumentChecker.isFalse(nCoefs < 2, "Polynomial degree is too low");

    final double[] knots = pp.getKnots().getData();
    final int nKnots = knots.length;
    int interval = FunctionUtils.getLowerBoundIndex(knots, xKey);
    if (interval == nKnots - 1) {
      interval--; // there is 1 less interval that knots
    }

    final double s = xKey - knots[interval];
    final DoubleMatrix2D a = pp.getCoefficientSensitivity(interval);

    DoubleMatrix1D res = (DoubleMatrix1D) MA.scale(a.getRowVector(0), nCoefs - 1);
    for (int i = 1; i < nCoefs - 1; i++) {
      res = (DoubleMatrix1D) MA.scale(res, s);
      res = (DoubleMatrix1D) MA.add(res, MA.scale(a.getRowVector(i), nCoefs - 1 - i));
    }

    return res;
  }

  /**
   * @param pp {@link PiecewisePolynomialResultsWithSensitivity}
   * @param xKeys
   * @return Node sensitivity of derivative value at x=xKeys
   */
  public DoubleMatrix1D[] differentiateNodeSensitivity(final PiecewisePolynomialResultsWithSensitivity pp, final double[] xKeys) {
    ArgumentChecker.notNull(pp, "null pp");

    if (pp.getDimensions() > 1) {
      throw new NotImplementedException();
    }
    final int nCoefs = pp.getOrder();
    ArgumentChecker.isFalse(nCoefs < 2, "Polynomial degree is too low");
    final int nIntervals = pp.getNumberOfIntervals();

    final DoubleMatrix2D[] diffSense = new DoubleMatrix2D[nIntervals];
    final DoubleMatrix2D[] senseMat = pp.getCoefficientSensitivityAll();
    final int nData = senseMat[0].getNumberOfColumns();
    for (int i = 0; i < nIntervals; ++i) {
      final double[][] tmp = new double[nCoefs - 1][nData];
      for (int j = 0; j < nCoefs - 1; ++j) {
        for (int k = 0; k < nData; ++k) {
          tmp[j][k] = (nCoefs - 1 - j) * senseMat[i].getData()[j][k];
        }
      }
      diffSense[i] = new DoubleMatrix2D(tmp);
    }

    PiecewisePolynomialResultsWithSensitivity ppDiff = new PiecewisePolynomialResultsWithSensitivity(pp.getKnots(), pp.getCoefMatrix(), nCoefs - 1, pp.getDimensions(), diffSense);
    return nodeSensitivity(ppDiff, xKeys);
  }

  /**
   * @param pp {@link PiecewisePolynomialResultsWithSensitivity}
   * @param xKey
   * @return Node sensitivity of second derivative value at x=xKey
   */
  public DoubleMatrix1D differentiateTwiceNodeSensitivity(final PiecewisePolynomialResultsWithSensitivity pp, final double xKey) {
    ArgumentChecker.notNull(pp, "null pp");
    ArgumentChecker.isFalse(Double.isNaN(xKey), "xKey containing NaN");
    ArgumentChecker.isFalse(Double.isInfinite(xKey), "xKey containing Infinity");

    if (pp.getDimensions() > 1) {
      throw new NotImplementedException();
    }
    final int nCoefs = pp.getOrder();
    ArgumentChecker.isFalse(nCoefs < 3, "Polynomial degree is too low");

    final double[] knots = pp.getKnots().getData();
    final int nKnots = knots.length;
    int interval = FunctionUtils.getLowerBoundIndex(knots, xKey);
    if (interval == nKnots - 1) {
      interval--; // there is 1 less interval that knots
    }

    final double s = xKey - knots[interval];
    final DoubleMatrix2D a = pp.getCoefficientSensitivity(interval);

    DoubleMatrix1D res = (DoubleMatrix1D) MA.scale(a.getRowVector(0), (nCoefs - 1) * (nCoefs - 2));
    for (int i = 1; i < nCoefs - 2; i++) {
      res = (DoubleMatrix1D) MA.scale(res, s);
      res = (DoubleMatrix1D) MA.add(res, MA.scale(a.getRowVector(i), (nCoefs - 1 - i) * (nCoefs - 2 - i)));
    }

    return res;
  }

  /**
   * @param pp {@link PiecewisePolynomialResultsWithSensitivity}
   * @param xKeys
   * @return Node sensitivity of second derivative value at x=xKeys
   */
  public DoubleMatrix1D[] differentiateTwiceNodeSensitivity(final PiecewisePolynomialResultsWithSensitivity pp, final double[] xKeys) {
    ArgumentChecker.notNull(pp, "null pp");

    if (pp.getDimensions() > 1) {
      throw new NotImplementedException();
    }
    final int nCoefs = pp.getOrder();
    ArgumentChecker.isFalse(nCoefs < 3, "Polynomial degree is too low");
    final int nIntervals = pp.getNumberOfIntervals();

    final DoubleMatrix2D[] diffSense = new DoubleMatrix2D[nIntervals];
    final DoubleMatrix2D[] senseMat = pp.getCoefficientSensitivityAll();
    final int nData = senseMat[0].getNumberOfColumns();
    for (int i = 0; i < nIntervals; ++i) {
      final double[][] tmp = new double[nCoefs - 2][nData];
      for (int j = 0; j < nCoefs - 2; ++j) {
        for (int k = 0; k < nData; ++k) {
          tmp[j][k] = (nCoefs - 1 - j) * (nCoefs - 2 - j) * senseMat[i].getData()[j][k];
        }
      }
      diffSense[i] = new DoubleMatrix2D(tmp);
    }

    PiecewisePolynomialResultsWithSensitivity ppDiff = new PiecewisePolynomialResultsWithSensitivity(pp.getKnots(), pp.getCoefMatrix(), nCoefs - 2, pp.getDimensions(), diffSense);
    return nodeSensitivity(ppDiff, xKeys);
  }
}


text:
require "omniauth/dropbox/version"
require "omniauth/strategies/dropbox"


text:
export const SET_SYSTEM_STATS = 'SET_SYSTEM_STATS'

export const setSystemStats = (stats) => {
  return {
    type: SET_SYSTEM_STATS,
    stats
  }
}

export const getSystemStats = () => {
  return async (dispatch) => {
    const stats = await fetch('/api/v1/stats', {credentials: 'same-origin'})
      .then((resp) => {return resp.json()})
    dispatch(setSystemStats(stats))
  }
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyCompany("Vigil Projects")]
[assembly: AssemblyProduct("Vigil.Domain.Tests")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("912c0daf-c955-4e22-a029-2bacb37f1dce")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]


text:
package edu.uchicago.cs.encsel.dataset.column

import org.junit.Test
import org.junit.Assert._
import java.net.URI
import java.io.File
import edu.uchicago.cs.encsel.model.DataType
import edu.uchicago.cs.encsel.dataset.schema.Schema

class SchemaTest {

  @Test
  def testFromParquetFile(): Unit = {
    val schema = Schema.fromParquetFile(new File("src/test/resource/test.schema").toURI)
    assertEquals(22, schema.columns.length)
    assertTrue(schema.hasHeader)

    assertEquals(DataType.STRING, schema.columns(3)._1)
    assertEquals("Block", schema.columns(3)._2)
  }

  @Test
  def testFromParquetFile2(): Unit = {
    val schema = Schema.fromParquetFile(new File("src/test/resource/test2.schema").toURI)
    assertEquals(7, schema.columns.length)
    assertTrue(schema.hasHeader)

    assertEquals(DataType.STRING, schema.columns(1)._1)
    assertEquals("Case_number", schema.columns(1)._2)

    assertEquals(DataType.STRING, schema.columns(3)._1)
    assertEquals("Primary_type", schema.columns(3)._2)

    assertEquals(DataType.STRING, schema.columns(5)._1)
    assertEquals("Loc_description", schema.columns(5)._2)

    assertEquals(DataType.STRING, schema.columns(6)._1)
    assertEquals("update_on", schema.columns(6)._2)
  }

  @Test
  def testFromParquetFile3(): Unit = {
    val schema = Schema.fromParquetFile(new File("src/test/resource/test3.schema").toURI)
    assertEquals(22, schema.columns.length)
    assertFalse(schema.hasHeader)

    assertEquals(DataType.STRING, schema.columns(3)._1)
    assertEquals("Block", schema.columns(3)._2)
  }

}


text:
package org.apache.http.examples.client;

import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Lookup;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.RFC6265CookieSpecProvider;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates how to use a custom public suffix list.
 */
public class ClientCustomPublicSuffixList {

    public final static void main(String[] args) throws Exception {

        // Use PublicSuffixMatcherLoader to load public suffix list from a file,
        // resource or from an arbitrary URL
        PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(
                new URL("https://publicsuffix.org/list/effective_tld_names.dat"));

        // Please use the publicsuffix.org URL to download the list no more than once per day !!!
        // Please consider making a local copy !!!

        DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);

        RFC6265CookieSpecProvider cookieSpecProvider = new RFC6265CookieSpecProvider(publicSuffixMatcher);
        Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
                .register(CookieSpecs.DEFAULT, cookieSpecProvider)
                .register(CookieSpecs.STANDARD, cookieSpecProvider)
                .register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider)
                .build();

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLHostnameVerifier(hostnameVerifier)
                .setDefaultCookieSpecRegistry(cookieSpecRegistry)
                .build();
        try {

            HttpGet httpget = new HttpGet("https://httpbin.org/");

            System.out.println("executing request " + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}


text:
package com.aol.cyclops.matcher.builders;

import java.util.Optional;
import java.util.function.Predicate;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.val;
import lombok.experimental.Wither;

import com.aol.cyclops.matcher.ActionWithReturn;
import com.aol.cyclops.matcher.Predicates;
import com.nurkiewicz.lazyseq.LazySeq;

/**
 * Case builder for Algebraic Data Type or Case class matching
 *
 * @author johnmcclean
 *
 * @param <X> Return type from the Pattern Matching expression
 */
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class CheckTypeAndValues<X> extends CaseBeingBuilt {
	// T : user input (type provided to match)
	// X : match response (thenApply)
	// R : extractor response
	// V : input for matcher / predicate
	@Getter(AccessLevel.PACKAGE)
	@Wither(AccessLevel.PACKAGE)
	private final PatternMatcher patternMatcher;

	/**
	 * Build a Case where we will check if user input matches the Type of the input params on the ActionWithReturn instance supplied
	 * If it does, the ActionWithReturn will be executed (applied) to get the result of the Match.
	 *
	 * isType will attempt to match on the type of the supplied Case class. If it matches the Case class will be 'decomposed' via it's unapply method
	 * and the Case will then attempt to match on each of the elements that make up the Case class. If the Case class implements Decomposable, that interface and it's
	 * unapply method will be used. Otherwise in Extractors it is possible to register Decomposition Funcitons that will unapply Case classes from other sources (e.g.
	 * javaslang, jADT or even Scala). If no Decomposition Function has been registered, reflection will be used to call an unapply method on the Case class if it exists.
	 *
	 * @see com.aol.cyclops.matcher.Extractors#decompose
	 * @see com.aol.cyclops.matcher.Extractors#registerDecompositionFunction
	 *
	 * @param a Action from which the Predicate (by param type) and Function will be extracted to build a Pattern Matching case
	 * @return Next step in Case builder
	 */
	public <T, R> AndMembersMatchBuilder<T, R> isType(ActionWithReturn<T, R> a) {

		return new AndMembersMatchBuilder<T, R>(a);

	}

	@AllArgsConstructor
	public class AndMembersMatchBuilder<T, R> {
		ActionWithReturn<T, R> action;

		/**
		 *
		 * Provide a comparison value, JDK 8 Predicate, or Hamcrest Matcher  for each Element to match on.
		 *
		 * Further & recursively unwrap any element by Predicates.type(ELEMENT_TYPE.class).with(V... values)
		 *
		 * @see Predicates#type
		 *
		 * @param values Matching rules for each element in the decomposed / unapplied user input
		 * @return Pattern Matcher builder with completed Case added to it
		 */
		@SafeVarargs
		public final <V> MatchingInstance<T, X> with(V... values) {

			val type = action.getType();
			val clazz = type.parameterType(type.parameterCount() - 1);

			Predicate predicate = it -> Optional.of(it)
					.map(v -> v.getClass().isAssignableFrom(clazz))
					.orElse(false);
			// add wildcard support
			Predicate<V>[] predicates = LazySeq.of(values)
					.map(nextValue -> convertToPredicate(nextValue)).toList()
					.toArray(new Predicate[0]);

			return addCase(patternMatcher.inCaseOfManyType(predicate, action,
					predicates));

		}
	}

	private <T,R> MatchingInstance<T,R> addCase(PatternMatcher o){
		return new MatchingInstance<>(this.withPatternMatcher(o));
	}

}


text:
package org.apache.directory.shared.kerberos.codec.krbSafeBody.actions;

import org.apache.directory.shared.kerberos.codec.actions.AbstractReadHostAddress;
import org.apache.directory.shared.kerberos.codec.krbSafeBody.KrbSafeBodyContainer;
import org.apache.directory.shared.kerberos.components.HostAddress;

/**
 * Store the s-address of KrbSafeBody.
 *
 * @author Apache Directory Project
 */
public class StoreSenderAddress extends AbstractReadHostAddress<KrbSafeBodyContainer>
{
    public StoreSenderAddress()
    {
        super( "KRB-SAFE-BODY s-address" );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void setAddress( HostAddress hostAddress, KrbSafeBodyContainer krbSafeBodyContainer )
    {
        krbSafeBodyContainer.getKrbSafeBody().setSenderAddress( hostAddress );

        krbSafeBodyContainer.setGrammarEndAllowed( true );
    }
}


text:
// This all-in-one cpp file cuts down on template bloat to allow us to build our Windows release build.

#include "AXObjectCache.cpp"
#include "AccessibilityARIAGrid.cpp"
#include "AccessibilityARIAGridCell.cpp"
#include "AccessibilityARIAGridRow.cpp"
#include "AccessibilityAttachment.cpp"
#include "AccessibilityImageMapLink.cpp"
#include "AccessibilityLabel.cpp"
#include "AccessibilityList.cpp"
#include "AccessibilityListBox.cpp"
#include "AccessibilityListBoxOption.cpp"
#include "AccessibilityMathMLElement.cpp"
#include "AccessibilityMediaControls.cpp"
#include "AccessibilityMenuList.cpp"
#include "AccessibilityMenuListOption.cpp"
#include "AccessibilityMenuListPopup.cpp"
#include "AccessibilityMockObject.cpp"
#include "AccessibilityNodeObject.cpp"
#include "AccessibilityObject.cpp"
#include "AccessibilityProgressIndicator.cpp"
#include "AccessibilityRenderObject.cpp"
#include "AccessibilitySVGElement.cpp"
#include "AccessibilitySVGRoot.cpp"
#include "AccessibilityScrollView.cpp"
#include "AccessibilityScrollbar.cpp"
#include "AccessibilitySlider.cpp"
#include "AccessibilitySpinButton.cpp"
#include "AccessibilityTable.cpp"
#include "AccessibilityTableCell.cpp"
#include "AccessibilityTableColumn.cpp"
#include "AccessibilityTableHeaderContainer.cpp"
#include "AccessibilityTableRow.cpp"
#include "AccessibilityTree.cpp"
#include "AccessibilityTreeItem.cpp"
#include "AccessibleNode.cpp"


text:
package strd.dht

import scala.concurrent.Future
import lmbrd.zn.util.{ByteBuf, PrimitiveBits, MD5Util, BytesHash}
import strd.CByte
import java.io.{DataOutputStream, OutputStream}

/**
 *
 * User: light
 * Date: 9/30/13
 * Time: 12:59 AM
 */

object DHTEntities {

}

trait ConflictResolver {
  def merge( d1 : DHTRow, d2 : DHTRow ) : DHTRow
}

trait ConflictResolver2 {
  def merge( d1 : DHTRow2, d2 : DHTRow2 ) : DHTRow2
}

trait DHTDispatcher {
  def request( req : DHTRequest, toNode : Int ) : Future[DHTResponse]
  def isAlive( nodeId : Int ) : Boolean
}

sealed trait DHTRequest{

}

sealed trait DHTResponse {

}

object DHTPutSuccess extends DHTResponse
object DHTStaleUpdate extends DHTResponse
//object DHTNoData extends DHTResponse

abstract class DHTErrors(id : Int) {

}

object DHTErrors {

  case object UNEXPECTED extends DHTErrors(100)
}

case class DHTError( code : DHTErrors, reason : Option[String] = None ) extends DHTResponse

case class DHTPutRequest( rows      : Seq[DHTRow],
                          toNode    : Int )  extends DHTRequest {
  override def toString = {
    s"Put[${rows.mkString(":")}]"
  }
}

case class DHTPutRequest2( rows      : Seq[DHTRow2],
                          toNode    : Int )  extends DHTRequest {
  override def toString = {
    s"Put[${rows.mkString(":")}]"
  }
}

case class DHTWriteBackOff( rows      : Seq[DHTRow] )  extends DHTRequest {
  override def toString = {
    s"WriteBack[${rows.mkString(":")}]"
  }

}

case class DHTWriteBackOff2( rows      : Seq[DHTRow2] )  extends DHTRequest {
  override def toString = {
    s"WriteBack[${rows.mkString(":")}]"
  }

}

case class DHTGetRequest( keys       : Seq[ BIN ] )  extends DHTRequest {
  override def toString = {
    s"Get[${keys.map(key=>MD5Util.convertToHex(key)).mkString(":")}]"
  }

}

case class DHTGetRequest2( keys       : Seq[ DHTKey2 ] )  extends DHTRequest {
  override def toString = {
    s"Get[${keys.map(key=>s"(${key.table}, ${MD5Util.convertToHex(key.key)})").mkString(":")}]"
  }

}

case class DHTEntries( entries : Seq[DHTEntry] ) extends DHTResponse

/*
case class VersionnedBytes( d : BIN, ver : Long ) {
  override def equals(obj: scala.Any) = {
    val o = obj.asInstanceOf[VersionnedBytes]
    o.ver == ver && BytesHash.compareTo( d, o.d) == 0
  }

  override def hashCode() = {
    BytesHash.instance.computeHashCode( d )
  }
}
*/

case class DHTReplicaNotEnoughException(msg : String = "", thrw : Throwable = null) extends IllegalStateException(msg, thrw)

case class DHTRow( key : BIN, value : BIN, version : Long = System.currentTimeMillis()) {
  override def equals(obj: scala.Any) = {
    val o = obj.asInstanceOf[DHTRow]

    version == o.version && BytesHash.compareTo( value, o.value) == 0 && BytesHash.compareTo( key, o.key) == 0
  }

  override def hashCode() = {
    BytesHash.instance.computeHashCode( value )
  }

  override def toString = {
    s"Row[${MD5Util.convertToHex(key)} -> ${MD5Util.convertToHex(value)}, $version}]"
  }
}

case class DHTKey2( table: Int, key : BIN ) {

  private lazy val _hashCode = BytesHash.instance.computeHashCode(key)

   override def equals(obj: scala.Any) = {
     val o = obj.asInstanceOf[DHTKey2]
     table == o.table && BytesHash.compareTo(key,   o.key) == 0
   }

   override def hashCode() = _hashCode

   override def toString =s"DHTKey($table, ${MD5Util.convertToHex(key)})"

}

case class DHTRow2( table: Int, key : BIN, value : BIN, version : Long = System.currentTimeMillis()) {
  override def equals(obj: scala.Any) = {
    val o = obj.asInstanceOf[DHTRow2]

    table == o.table && version == o.version && BytesHash.compareTo( value, o.value) == 0 && BytesHash.compareTo( key, o.key) == 0
  }

  override def hashCode() = {
    BytesHash.instance.computeHashCode( value )
  }

  override def toString = {
    s"Row[$table, ${MD5Util.convertToHex(key)} -> ${MD5Util.convertToHex(value)}, $version}]"
  }
}

/*
trait DHTEntry {
//  def toValue: DHTEntryValue

  def version : Long
  def md5FromKey : BIN
  def writeValueAndVersionTo( os : OutputStream )
}
*/

object EMPTYDHT extends DHTEntry( new Array[Byte](0), 0)

case class DHTEntry( data : BIN, version : Long ) {

  def writeValueAndVersionTo( bos : ByteBuf ) {
    bos.write(data)
    bos.writeLong(version)
  }

  override def toString = {
    s"DHTEntry[${MD5Util.convertToHex(data)}, $version}]"
  }

  override def equals(obj: scala.Any) = {
    obj match {
      case x : DHTEntry => version == x.version && BytesHash.compareTo(data, x.data) == 0
      case _ => false
    }
  }

}

/*
class DHTEntryWithKey(  kv            : Array[Byte],
                        split         : Int
                      ) extends CByte( kv, 0, split ) with DHTEntry {

  def md5FromKey = MD5Util.md5Bytes(kv, 0, split)

  override def writeKeyTo(bos : OutputStream) {
    bos.write(kv)
  }

  // method write key -> write all data
  def writeValueAndVersionTo(os: OutputStream) = {
    // NOOP
  }

  lazy val version = PrimitiveBits.getLong( kv, kv.length - 8 )

  override def toString = {
    s"EntryKV[${MD5Util.convertToHex(kv, split, kv.length - split - 8)}, $version]"
  }

  def toValue = DHTEntryValue( PrimitiveBits.slice( kv, split, kv.length - 8 - split), version )
}
*/

/*
object DHTEntryWithKey {
  def fromRow(r : DHTRow ) = {
    val kl = r.key.length
    val vl = r.value.length

    val a = new Array[Byte](kl + vl + 8)

    System.arraycopy(r.key, 0, a, 0, kl)
    System.arraycopy(r.value, 0, a, kl, vl)
    PrimitiveBits.putLong(a, kl+vl,  r.version)

    new DHTEntryWithKey(a, kl)
  }
}
*/

trait KeyValueStorage {
  def get(key: CByte): Option[DHTEntry]

  def put(key: CByte, data: DHTEntry)
}


text:
.class Landroid/widget/RemoteViews$TextViewDrawableAction;
.super Landroid/widget/RemoteViews$Action;
.source "RemoteViews.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/RemoteViews;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "TextViewDrawableAction"
.end annotation

# static fields
.field public static final TAG:I = 0xb

# instance fields
.field d1:I

.field d2:I

.field d3:I

.field d4:I

.field i1:Landroid/graphics/drawable/Icon;

.field i2:Landroid/graphics/drawable/Icon;

.field i3:Landroid/graphics/drawable/Icon;

.field i4:Landroid/graphics/drawable/Icon;

.field isRelative:Z

.field final synthetic this$0:Landroid/widget/RemoteViews;

.field useIcons:Z

# direct methods
.method public constructor <init>(Landroid/widget/RemoteViews;IZIIII)V
    .locals 2
    .param p1, "this$0"    # Landroid/widget/RemoteViews;
    .param p2, "viewId"    # I
    .param p3, "isRelative"    # Z
    .param p4, "d1"    # I
    .param p5, "d2"    # I
    .param p6, "d3"    # I
    .param p7, "d4"    # I

    .prologue
    const/4 v1, 0x0

    .line 1427
    iput-object p1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->this$0:Landroid/widget/RemoteViews;

    const/4 v0, 0x0

    invoke-direct {p0, v0}, Landroid/widget/RemoteViews$Action;-><init>(Landroid/widget/RemoteViews$Action;)V

    .line 1539
    iput-boolean v1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    .line 1540
    iput-boolean v1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    .line 1428
    iput p2, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->viewId:I

    .line 1429
    iput-boolean p3, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    .line 1430
    iput-boolean v1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    .line 1431
    iput p4, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d1:I

    .line 1432
    iput p5, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d2:I

    .line 1433
    iput p6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d3:I

    .line 1434
    iput p7, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d4:I

    .line 1427
    return-void
.end method

.method public constructor <init>(Landroid/widget/RemoteViews;IZLandroid/graphics/drawable/Icon;Landroid/graphics/drawable/Icon;Landroid/graphics/drawable/Icon;Landroid/graphics/drawable/Icon;)V
    .locals 2
    .param p1, "this$0"    # Landroid/widget/RemoteViews;
    .param p2, "viewId"    # I
    .param p3, "isRelative"    # Z
    .param p4, "i1"    # Landroid/graphics/drawable/Icon;
    .param p5, "i2"    # Landroid/graphics/drawable/Icon;
    .param p6, "i3"    # Landroid/graphics/drawable/Icon;
    .param p7, "i4"    # Landroid/graphics/drawable/Icon;

    .prologue
    const/4 v1, 0x0

    .line 1437
    iput-object p1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->this$0:Landroid/widget/RemoteViews;

    const/4 v0, 0x0

    invoke-direct {p0, v0}, Landroid/widget/RemoteViews$Action;-><init>(Landroid/widget/RemoteViews$Action;)V

    .line 1539
    iput-boolean v1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    .line 1540
    iput-boolean v1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    .line 1439
    iput p2, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->viewId:I

    .line 1440
    iput-boolean p3, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    .line 1441
    const/4 v0, 0x1

    iput-boolean v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    .line 1442
    iput-object p4, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i1:Landroid/graphics/drawable/Icon;

    .line 1443
    iput-object p5, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i2:Landroid/graphics/drawable/Icon;

    .line 1444
    iput-object p6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i3:Landroid/graphics/drawable/Icon;

    .line 1445
    iput-object p7, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i4:Landroid/graphics/drawable/Icon;

    .line 1438
    return-void
.end method

.method public constructor <init>(Landroid/widget/RemoteViews;Landroid/os/Parcel;)V
    .locals 3
    .param p1, "this$0"    # Landroid/widget/RemoteViews;
    .param p2, "parcel"    # Landroid/os/Parcel;

    .prologue
    const/4 v1, 0x1

    const/4 v2, 0x0

    .line 1448
    iput-object p1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->this$0:Landroid/widget/RemoteViews;

    const/4 v0, 0x0

    invoke-direct {p0, v0}, Landroid/widget/RemoteViews$Action;-><init>(Landroid/widget/RemoteViews$Action;)V

    .line 1539
    iput-boolean v2, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    .line 1540
    iput-boolean v2, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    .line 1449
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->viewId:I

    .line 1450
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    if-eqz v0, :cond_4

    move v0, v1

    :goto_0
    iput-boolean v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    .line 1451
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    if-eqz v0, :cond_5

    :goto_1
    iput-boolean v1, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    .line 1452
    iget-boolean v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    if-eqz v0, :cond_6

    .line 1453
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    if-eqz v0, :cond_0

    .line 1454
    sget-object v0, Landroid/graphics/drawable/Icon;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v0, p2}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/graphics/drawable/Icon;

    iput-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i1:Landroid/graphics/drawable/Icon;

    .line 1456
    :cond_0
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    if-eqz v0, :cond_1

    .line 1457
    sget-object v0, Landroid/graphics/drawable/Icon;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v0, p2}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/graphics/drawable/Icon;

    iput-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i2:Landroid/graphics/drawable/Icon;

    .line 1459
    :cond_1
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    if-eqz v0, :cond_2

    .line 1460
    sget-object v0, Landroid/graphics/drawable/Icon;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v0, p2}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/graphics/drawable/Icon;

    iput-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i3:Landroid/graphics/drawable/Icon;

    .line 1462
    :cond_2
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    if-eqz v0, :cond_3

    .line 1463
    sget-object v0, Landroid/graphics/drawable/Icon;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v0, p2}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/graphics/drawable/Icon;

    iput-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i4:Landroid/graphics/drawable/Icon;

    .line 1448
    :cond_3
    :goto_2
    return-void

    :cond_4
    move v0, v2

    .line 1450
    goto :goto_0

    :cond_5
    move v1, v2

    .line 1451
    goto :goto_1

    .line 1466
    :cond_6
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d1:I

    .line 1467
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d2:I

    .line 1468
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d3:I

    .line 1469
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d4:I

    goto :goto_2
.end method

# virtual methods
.method public apply(Landroid/view/View;Landroid/view/ViewGroup;Landroid/widget/RemoteViews$OnClickHandler;)V
    .locals 10
    .param p1, "root"    # Landroid/view/View;
    .param p2, "rootParent"    # Landroid/view/ViewGroup;
    .param p3, "handler"    # Landroid/widget/RemoteViews$OnClickHandler;

    .prologue
    .line 1513
    iget v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->viewId:I

    invoke-virtual {p1, v6}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v5

    check-cast v5, Landroid/widget/TextView;

    .line 1514
    .local v5, "target":Landroid/widget/TextView;
    if-nez v5, :cond_0

    return-void

    .line 1515
    :cond_0
    iget-boolean v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    if-eqz v6, :cond_6

    .line 1516
    invoke-virtual {v5}, Landroid/widget/TextView;->getContext()Landroid/content/Context;

    move-result-object v0

    .line 1517
    .local v0, "ctx":Landroid/content/Context;
    iget-object v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i1:Landroid/graphics/drawable/Icon;

    if-nez v6, :cond_1

    const/4 v1, 0x0

    .line 1518
    :goto_0
    iget-object v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i2:Landroid/graphics/drawable/Icon;

    if-nez v6, :cond_2

    const/4 v2, 0x0

    .line 1519
    :goto_1
    iget-object v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i3:Landroid/graphics/drawable/Icon;

    if-nez v6, :cond_3

    const/4 v3, 0x0

    .line 1520
    :goto_2
    iget-object v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i4:Landroid/graphics/drawable/Icon;

    if-nez v6, :cond_4

    const/4 v4, 0x0

    .line 1521
    :goto_3
    iget-boolean v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    if-eqz v6, :cond_5

    .line 1522
    invoke-virtual {v5, v1, v2, v3, v4}, Landroid/widget/TextView;->setCompoundDrawablesRelativeWithIntrinsicBounds(Landroid/graphics/drawable/Drawable;Landroid/graphics/drawable/Drawable;Landroid/graphics/drawable/Drawable;Landroid/graphics/drawable/Drawable;)V

    .line 1512
    .end local v0    # "ctx":Landroid/content/Context;
    :goto_4
    return-void

    .line 1517
    .restart local v0    # "ctx":Landroid/content/Context;
    :cond_1
    iget-object v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i1:Landroid/graphics/drawable/Icon;

    invoke-virtual {v6, v0}, Landroid/graphics/drawable/Icon;->loadDrawable(Landroid/content/Context;)Landroid/graphics/drawable/Drawable;

    move-result-object v1

    .local v1, "id1":Landroid/graphics/drawable/Drawable;
    goto :goto_0

    .line 1518
    .end local v1    # "id1":Landroid/graphics/drawable/Drawable;
    :cond_2
    iget-object v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i2:Landroid/graphics/drawable/Icon;

    invoke-virtual {v6, v0}, Landroid/graphics/drawable/Icon;->loadDrawable(Landroid/content/Context;)Landroid/graphics/drawable/Drawable;

    move-result-object v2

    .local v2, "id2":Landroid/graphics/drawable/Drawable;
    goto :goto_1

    .line 1519
    .end local v2    # "id2":Landroid/graphics/drawable/Drawable;
    :cond_3
    iget-object v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i3:Landroid/graphics/drawable/Icon;

    invoke-virtual {v6, v0}, Landroid/graphics/drawable/Icon;->loadDrawable(Landroid/content/Context;)Landroid/graphics/drawable/Drawable;

    move-result-object v3

    .local v3, "id3":Landroid/graphics/drawable/Drawable;
    goto :goto_2

    .line 1520
    .end local v3    # "id3":Landroid/graphics/drawable/Drawable;
    :cond_4
    iget-object v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i4:Landroid/graphics/drawable/Icon;

    invoke-virtual {v6, v0}, Landroid/graphics/drawable/Icon;->loadDrawable(Landroid/content/Context;)Landroid/graphics/drawable/Drawable;

    move-result-object v4

    .local v4, "id4":Landroid/graphics/drawable/Drawable;
    goto :goto_3

    .line 1524
    .end local v4    # "id4":Landroid/graphics/drawable/Drawable;
    :cond_5
    invoke-virtual {v5, v1, v2, v3, v4}, Landroid/widget/TextView;->setCompoundDrawablesWithIntrinsicBounds(Landroid/graphics/drawable/Drawable;Landroid/graphics/drawable/Drawable;Landroid/graphics/drawable/Drawable;Landroid/graphics/drawable/Drawable;)V

    goto :goto_4

    .line 1527
    .end local v0    # "ctx":Landroid/content/Context;
    :cond_6
    iget-boolean v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    if-eqz v6, :cond_7

    .line 1528
    iget v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d1:I

    iget v7, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d2:I

    iget v8, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d3:I

    iget v9, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d4:I

    invoke-virtual {v5, v6, v7, v8, v9}, Landroid/widget/TextView;->setCompoundDrawablesRelativeWithIntrinsicBounds(IIII)V

    goto :goto_4

    .line 1530
    :cond_7
    iget v6, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d1:I

    iget v7, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d2:I

    iget v8, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d3:I

    iget v9, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d4:I

    invoke-virtual {v5, v6, v7, v8, v9}, Landroid/widget/TextView;->setCompoundDrawablesWithIntrinsicBounds(IIII)V

    goto :goto_4
.end method

.method public getActionName()Ljava/lang/String;
    .locals 1

    .prologue
    .line 1536
    const-string/jumbo v0, "TextViewDrawableAction"

    return-object v0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 3
    .param p1, "dest"    # Landroid/os/Parcel;
    .param p2, "flags"    # I

    .prologue
    const/4 v1, 0x1

    const/4 v2, 0x0

    .line 1474
    const/16 v0, 0xb

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1475
    iget v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->viewId:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1476
    iget-boolean v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->isRelative:Z

    if-eqz v0, :cond_0

    move v0, v1

    :goto_0
    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1477
    iget-boolean v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    if-eqz v0, :cond_1

    move v0, v1

    :goto_1
    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1478
    iget-boolean v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->useIcons:Z

    if-eqz v0, :cond_6

    .line 1479
    iget-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i1:Landroid/graphics/drawable/Icon;

    if-eqz v0, :cond_2

    .line 1480
    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 1481
    iget-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i1:Landroid/graphics/drawable/Icon;

    invoke-virtual {v0, p1, v2}, Landroid/graphics/drawable/Icon;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1485
    :goto_2
    iget-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i2:Landroid/graphics/drawable/Icon;

    if-eqz v0, :cond_3

    .line 1486
    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 1487
    iget-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i2:Landroid/graphics/drawable/Icon;

    invoke-virtual {v0, p1, v2}, Landroid/graphics/drawable/Icon;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1491
    :goto_3
    iget-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i3:Landroid/graphics/drawable/Icon;

    if-eqz v0, :cond_4

    .line 1492
    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 1493
    iget-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i3:Landroid/graphics/drawable/Icon;

    invoke-virtual {v0, p1, v2}, Landroid/graphics/drawable/Icon;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1497
    :goto_4
    iget-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i4:Landroid/graphics/drawable/Icon;

    if-eqz v0, :cond_5

    .line 1498
    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 1499
    iget-object v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->i4:Landroid/graphics/drawable/Icon;

    invoke-virtual {v0, p1, v2}, Landroid/graphics/drawable/Icon;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1473
    :goto_5
    return-void

    :cond_0
    move v0, v2

    .line 1476
    goto :goto_0

    :cond_1
    move v0, v2

    .line 1477
    goto :goto_1

    .line 1483
    :cond_2
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_2

    .line 1489
    :cond_3
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_3

    .line 1495
    :cond_4
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_4

    .line 1501
    :cond_5
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_5

    .line 1504
    :cond_6
    iget v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d1:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1505
    iget v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d2:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1506
    iget v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d3:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1507
    iget v0, p0, Landroid/widget/RemoteViews$TextViewDrawableAction;->d4:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_5
.end method