text:
"use strict";

var vows = require("vows");
var assert = require("assert");

var Layers = require("../../lib/hub/http/layers");

vows.describe("Layers").addBatch({
    "Given Layers that will error when calling handle": {
        topic: function () {
            var topic = {};
            topic.used = [
                function layerA(req, res, nextLayer) {
                    topic.a_args = [req, res, nextLayer];
                    topic.a = true;
                    topic.first = true;
                    nextLayer();
                },
                function layerB(req, res, nextLayer) {
                    topic.b_args = [req, res, nextLayer];
                    topic.a_req = req;
                    topic.a = false;
                    topic.b = true;
                    topic.first = false;
                    nextLayer();
                },
                function layerFirstErrorHandler(err, req, res, nextLayer) {
                    topic.first_err_called = true;
                    nextLayer();
                },
                function layerC(req, res, nextLayer) {
                    topic.c_args = [req, res, nextLayer];
                    topic.c = true;
                    throw new Error("Failure.");
                },
                function layerErrorHandler(err, req, res, nextLayer) {
                    topic.err_args = [err, req, res, nextLayer];
                    topic.c = false;
                    if (err) {
                        topic.err = true;
                    }
                }
            ];

            topic.layers = new Layers();

            topic.used.forEach(function (fn) {
                topic.layers.use(fn);
            });

            topic.layers.handle("FIXTURE_REQ", "FIXTURE_RES");

            return topic;
        },
        "is ok": function (topic) {
            if (topic instanceof Error) { throw topic; }
        },
        "layers ran in order": function (topic) {
            assert.strictEqual(topic.b, true);
            assert.strictEqual(topic.a, false);
            assert.strictEqual(topic.first, false);
            assert.strictEqual(topic.c, false);
        },
        "error was handled by error handling middleware": function (topic) {
            assert.strictEqual(topic.err, true);
        },
        "normal middleware recieved correct arguments": function (topic) {
            assert.strictEqual(topic.a_args[0], "FIXTURE_REQ");
            assert.strictEqual(topic.b_args[0], "FIXTURE_REQ");
            assert.strictEqual(topic.c_args[0], "FIXTURE_REQ");
            assert.strictEqual(topic.a_args[1], "FIXTURE_RES");
            assert.strictEqual(topic.b_args[1], "FIXTURE_RES");
            assert.strictEqual(topic.c_args[1], "FIXTURE_RES");
            assert.isFunction(topic.a_args[2]);
            assert.isFunction(topic.b_args[2]);
            assert.isFunction(topic.c_args[2]);
        },
        "error handling middleware recieved correct arguments": function (topic) {
            assert(topic.err_args[0] instanceof Error, "error handling middleware did not recieve Error object");
            assert.strictEqual(topic.err_args[1], "FIXTURE_REQ");
            assert.strictEqual(topic.err_args[2], "FIXTURE_RES");
            assert.isFunction(topic.err_args[3]);
        },
        "error handling middleware that did not handle an error was skipped": function (topic) {
            assert.isUndefined(topic.first_err_called);
        }
    },
    "Given Layers that will not error when calling handle": {
        topic: function () {
            var topic = {};
            topic.used = [
                function layerA(req, res, nextLayer) {
                    topic.a_args = [req, res, nextLayer];
                    topic.a = true;
                    topic.first = true;
                    nextLayer();
                },
                function layerFirstErrorHandler(err, req, res, nextLayer) {
                    topic.first_err_called = true;
                    nextLayer();
                },
                function layerB(req, res, nextLayer) {
                    topic.b_args = [req, res, nextLayer];
                    topic.a_req = req;
                    topic.a = false;
                    topic.b = true;
                    topic.first = false;
                    nextLayer();
                }
            ];

            topic.layers = new Layers();

            topic.used.forEach(function (fn) {
                topic.layers.use(fn);
            });

            topic.layers.handle("FIXTURE_REQ", "FIXTURE_RES");

            return topic;
        },
        "is ok": function (topic) {
            if (topic instanceof Error) { throw topic; }
        },
        "layers ran in order": function (topic) {
            assert.strictEqual(topic.b, true);
            assert.strictEqual(topic.a, false);
            assert.strictEqual(topic.first, false);
        },
        "error handling middlware did not run": function (topic) {
            assert.isUndefined(topic.first_err_called);
        }
    }
}).export(module);


text:
/** @author Brian Cavalier */
/** @author John Hann */
import { Sink, Time } from '@most/types'

export default class SafeSink<A> implements Sink<A> {
  private readonly sink: Sink<A>
  private active: boolean;

  constructor(sink: Sink<A>) {
    this.sink = sink
    this.active = true
  }

  event(t: Time, x: A): void {
    if (!this.active) {
      return
    }
    this.sink.event(t, x)
  }

  end(t: Time): void{
    if (!this.active) {
      return
    }
    this.disable()
    this.sink.end(t)
  }

  error(t: Time, e: Error): void{
    this.disable()
    this.sink.error(t, e)
  }

  disable(): Sink<A> {
    this.active = false
    return this.sink
  }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe "manuals/show.html.erb" do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
package com.java.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.java.domain.Role;
import com.java.service.IRoleService;

@Controller
@RequestMapping("/role")
public class RoleController {

	@Autowired
	private IRoleService service;

	@RequestMapping("/findAll")
	@ResponseBody
	public List<Role> findAll() {
		List<Role> list = service.find();
		return list;
	}

	@RequestMapping("/save")
	public void save(Role role) {
		service.save(role);
	}

	@RequestMapping("/delete")
	public void save(int rid) {
		service.delete(rid);
	}

	@RequestMapping("/update")
	public void update(Role role) {
		service.update(role);
	}

	@RequestMapping("/findOne")
	@ResponseBody
	public Role update(int rid) {
		return service.find(rid);
	}

}


text:
package com.bobynoby.items.tools;

import com.bobynoby.main.MainRegistry;
import com.bobynoby.main.Reference;

import net.minecraft.item.ItemShears;
import net.minecraft.item.Item.ToolMaterial;

public class ToolObbyShears extends ItemShears{

	public ToolObbyShears() {
		setCreativeTab(MainRegistry.CREATIVE_TAB_TOOL);
		setUnlocalizedName(Reference.BobyEXitems.OBBYSHEARS.getUnlocalizedName());
		setRegistryName(Reference.BobyEXitems.OBBYSHEARS.getRegistryName());
		setMaxDamage(4867);
	}

}


text:
from optparse import OptionParser

import h5py
import yaml
from whoosh.index import create_in, os
from whoosh.fields import *
from whoosh.analysis import *
import logging

__author__ = 'Hendrik Strobelt'

CONFIG_FILE_NAME = 'lstm.yml'

def configuration(project_dir):
    """
    checks, if dir and config file exist. if so, returns it as python dict.
    :param project_dir:
    :return: config dictionary
    """
    if not os.path.isdir(project_dir):
        logging.error('%s is not a dir', project_dir)
        return

    config_file_name = os.path.join(project_dir, CONFIG_FILE_NAME)
    if not os.path.isfile(config_file_name):
        logging.error('no config file found: %s', config_file_name)
        return

    # else:

    # config = {}
    try:
        with open(config_file_name, 'r') as cf:
            res = yaml.load(cf)
    except IOError:
        logging.error('cannot read config file')
        sys.exit(-1)
    return res

def dictionary(project_dir, config):
    """
    loads the word dictionary file
    :param project_dir:
    :param config:
    :return: id2word dictionary
    """
    id2word = {}
    dict_file_name = os.path.join(project_dir, config['files'][config['word_sequence']['dict_file']])
    try:
        with open(dict_file_name, 'r') as df:
            for line in df:
                if len(line.split()) == 2:
                    k, v = line.split()
                elif line[0] == " ":
                    k = " "
                    v = line.strip()
                try:
                    id2word[int(v)] = unicode(k, 'utf-8')
                except UnicodeError:
                    logging.error('unicode error in: %s', line)
                    break
    except IOError:
        logging.error('cannot read dict file %s', dict_file_name)
        sys.exit(-1)
    return id2word

def sequence_data(project_dir, config):
    """
    opens word sequence HDF5 file
    :param project_dir:
    :param config:
    :return: pointer to word sequence array
    """
    try:
        h5_seq = h5py.File(os.path.join(project_dir, config['files'][config['word_sequence']['file']]))
    except IOError:
        logging.error('cannot open HDF5 file %s', config['files'][config['word_sequence']['file']])
        sys.exit(-1)
    res = h5_seq[config['word_sequence']['path']]
    return res

def index_project(project_dir, options):
    config = configuration(project_dir)

    id2word = dictionary(project_dir=project_dir, config=config)

    sequence = sequence_data(project_dir=project_dir, config=config)

    my_analyzer = SpaceSeparatedTokenizer() | LowercaseFilter()

    schema = Schema(index=NUMERIC(stored=True),
                    content=TEXT(stored=True, analyzer=my_analyzer))

    # create new dir if it doesn't exist yet
    index_dir_path = os.path.join(project_dir, 'indexdir')
    if not os.path.exists(index_dir_path):
        os.mkdir(index_dir_path)

    # create index
    ix = create_in(index_dir_path, schema)
    writer = ix.writer(limitmb=1024, procs=4)  # uses up to 4GB of RAM
    logging.info('starting indexing')
    for i in range(7, len(sequence)):
        tokens = map(lambda x: id2word[x], sequence[i - 7:i])
        tokens.insert(2, '||')
        a = u" ".join(tokens)
        writer.add_document(index=(i - 5),
                            content=a)
        if i % 10000 == 0:
            logging.info('pos: %i, string: %s', i, a)

    logging.info(' writing index...')
    writer.commit()
    logging.info(' .. done.')

def main():
    parser = OptionParser(usage='%prog [options] <project_directory>\nCreates an search index for LSTMVis.')

    (options, args) = parser.parse_args()
    logging.basicConfig(format='%(asctime)s %(levelname)s \t %(message)s', level=logging.INFO)
    if len(args) != 1:
        parser.print_help()
    else:
        index_project(args[0], options)

if __name__ == '__main__':
    main()


text:
package org.apache.dubbo.remoting.exchange.support.header;

import org.apache.dubbo.common.Parameters;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Request;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static java.util.Collections.unmodifiableCollection;
import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT;
import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK;
import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION;
import static org.apache.dubbo.remoting.Constants.TICKS_PER_WHEEL;
import static org.apache.dubbo.remoting.utils.UrlUtils.getHeartbeat;
import static org.apache.dubbo.remoting.utils.UrlUtils.getIdleTimeout;

/**
 * ExchangeServerImpl
 */
public class HeaderExchangeServer implements ExchangeServer {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private final RemotingServer server;
    private AtomicBoolean closed = new AtomicBoolean(false);

    private static final HashedWheelTimer IDLE_CHECK_TIMER = new HashedWheelTimer(new NamedThreadFactory("dubbo-server-idleCheck", true), 1,
            TimeUnit.SECONDS, TICKS_PER_WHEEL);

    private CloseTimerTask closeTimerTask;

    public HeaderExchangeServer(RemotingServer server) {
        Assert.notNull(server, "server == null");
        this.server = server;
        startIdleCheckTask(getUrl());
    }

    public RemotingServer getServer() {
        return server;
    }

    @Override
    public boolean isClosed() {
        return server.isClosed();
    }

    private boolean isRunning() {
        Collection<Channel> channels = getChannels();
        for (Channel channel : channels) {

            /**
             *  If there are any client connections,
             *  our server should be running.
             */

            if (channel.isConnected()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void close() {
        doClose();
        server.close();
    }

    @Override
    public void close(final int timeout) {
        startClose();
        if (timeout > 0) {
            final long max = timeout;
            final long start = System.currentTimeMillis();
            if (getUrl().getParameter(Constants.CHANNEL_SEND_READONLYEVENT_KEY, true)) {
                sendChannelReadOnlyEvent();
            }
            while (isRunning() && System.currentTimeMillis() - start < max) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        }
        doClose();
        server.close(timeout);
    }

    @Override
    public void startClose() {
        server.startClose();
    }

    private void sendChannelReadOnlyEvent() {
        Request request = new Request();
        request.setEvent(READONLY_EVENT);
        request.setTwoWay(false);
        request.setVersion(Version.getProtocolVersion());

        Collection<Channel> channels = getChannels();
        for (Channel channel : channels) {
            try {
                if (channel.isConnected()) {
                    channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true));
                }
            } catch (RemotingException e) {
                logger.warn("send cannot write message error.", e);
            }
        }
    }

    private void doClose() {
        if (!closed.compareAndSet(false, true)) {
            return;
        }
        cancelCloseTask();
    }

    private void cancelCloseTask() {
        if (closeTimerTask != null) {
            closeTimerTask.cancel();
        }
    }

    @Override
    public Collection<ExchangeChannel> getExchangeChannels() {
        Collection<ExchangeChannel> exchangeChannels = new ArrayList<ExchangeChannel>();
        Collection<Channel> channels = server.getChannels();
        if (CollectionUtils.isNotEmpty(channels)) {
            for (Channel channel : channels) {
                exchangeChannels.add(HeaderExchangeChannel.getOrAddChannel(channel));
            }
        }
        return exchangeChannels;
    }

    @Override
    public ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress) {
        Channel channel = server.getChannel(remoteAddress);
        return HeaderExchangeChannel.getOrAddChannel(channel);
    }

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public Collection<Channel> getChannels() {
        return (Collection) getExchangeChannels();
    }

    @Override
    public Channel getChannel(InetSocketAddress remoteAddress) {
        return getExchangeChannel(remoteAddress);
    }

    @Override
    public boolean isBound() {
        return server.isBound();
    }

    @Override
    public InetSocketAddress getLocalAddress() {
        return server.getLocalAddress();
    }

    @Override
    public URL getUrl() {
        return server.getUrl();
    }

    @Override
    public ChannelHandler getChannelHandler() {
        return server.getChannelHandler();
    }

    @Override
    public void reset(URL url) {
        server.reset(url);
        try {
            int currHeartbeat = getHeartbeat(getUrl());
            int currIdleTimeout = getIdleTimeout(getUrl());
            int heartbeat = getHeartbeat(url);
            int idleTimeout = getIdleTimeout(url);
            if (currHeartbeat != heartbeat || currIdleTimeout != idleTimeout) {
                cancelCloseTask();
                startIdleCheckTask(url);
            }
        } catch (Throwable t) {
            logger.error(t.getMessage(), t);
        }
    }

    @Override
    @Deprecated
    public void reset(Parameters parameters) {
        reset(getUrl().addParameters(parameters.getParameters()));
    }

    @Override
    public void send(Object message) throws RemotingException {
        if (closed.get()) {
            throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message
                    + ", cause: The server " + getLocalAddress() + " is closed!");
        }
        server.send(message);
    }

    @Override
    public void send(Object message, boolean sent) throws RemotingException {
        if (closed.get()) {
            throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message
                    + ", cause: The server " + getLocalAddress() + " is closed!");
        }
        server.send(message, sent);
    }

    /**
     * Each interval cannot be less than 1000ms.
     */
    private long calculateLeastDuration(int time) {
        if (time / HEARTBEAT_CHECK_TICK <= 0) {
            return LEAST_HEARTBEAT_DURATION;
        } else {
            return time / HEARTBEAT_CHECK_TICK;
        }
    }

    private void startIdleCheckTask(URL url) {
        if (!server.canHandleIdle()) {
            AbstractTimerTask.ChannelProvider cp = () -> unmodifiableCollection(HeaderExchangeServer.this.getChannels());
            int idleTimeout = getIdleTimeout(url);
            long idleTimeoutTick = calculateLeastDuration(idleTimeout);
            CloseTimerTask closeTimerTask = new CloseTimerTask(cp, idleTimeoutTick, idleTimeout);
            this.closeTimerTask = closeTimerTask;

            // init task and start timer.
            IDLE_CHECK_TIMER.newTimeout(closeTimerTask, idleTimeoutTick, TimeUnit.MILLISECONDS);
        }
    }
}


text:
MLS.modal = {
	counter: 0,

	open: function(msg, noclose, noposition, fixed)
	{
		msg = msg ? msg : "[modules/modal.js] Generic Error Message";

		MLS.modal.counter++;
		var $overlay = $jQ('

').appendTo("body"),
			$container = $overlay.find(".modal-overlay"),
			$content = $overlay.find(".modal-content").html(msg);

		if (fixed)
		{
			$overlay.css({ position: 'fixed' });
		}

		if (!noposition)
		{
			$container.css({
				top: $jQ(window).scrollTop() + ($jQ(window).height() - $container.height()) / 2
			});
		}

		if (noclose)
		{
			$overlay.find(".close-btn").remove();
		}
		else
		{
			$overlay.find(".close-btn, .data-close-btn").click(function(e) {
                MLS.modal.close($overlay);
				return false;
			});
		}

		$overlay.hide().fadeIn();
		return $overlay;
	},

	close: function($overlay)
	{
		$overlay.fadeOut(function() {
			$overlay.remove();
		});
	}
};


text:
layout: post
title: What is the appropriate population scaling of the Affordable Care Act Funding?
subtitle: Analysis of the effects of the Graham-Cassidy Bill on the ACA population
tags: [rstats, healthcare, ggplot2, geofacet]
---

I have been trying to decipher for myself, what is in the current (well, yesterday's) Graham-Cassidy health care bill. I saw this image on many news outlets a few days ago and my inner hate for pie charts bubbled up.

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/ACA_pie_full.jpg)

This is a zoom in on the pie chart ... From what I can gather, these figures are attempting to say that there are specific states that are getting relatively more of the federal health care funds under the Afordable Care Act (ACA) than their relative state population. Among the many things that are really hard to do with pie charts , comparing distributions ranks pretty high up there.

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/ACA_pie.png)

It is common practice when comparing different geographical areas that have different populations levels to scale it using the rate per person (per capita) or per number of people, e.g. rate per 1,000 people. In this case it would be population adjusted state federal funding. The question that needs answering, what is the relevant population.

Many charts in the last week have scaled the funding adjusted to state population (as is alluded to in the figure above), but the funds are not actually being used by everyone in each state, most people have health care from their employer. So, what is the actual population that is being serviced by the federal funding for the ACA? How much of a different picture does that paint from the original figure?

Hopefully this post will help motivate readers to start looking around for more data on what is the effect of the proposed bill on the approprations of federal funds on the state level.

My sources of information is the Kaiser Family Foundation site that have a great database for data on the ACA and the proposed bill, and Wikipedia for auxilary population data. We will end up with the following figure, but along the way I learned a number of things that I didn't know from reading online and seeing the news on TV.

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-17-1.png)<!-- -->

A quick note before you proceed - This is not meant to be an all encompassing analysis of the predicted effects of the Graham-Cassidy bill, as it has been said before: "Healthcare is hard...", and if I made any bad assumptions I apologize in advanced and welcome any comments and suggestions to better understand the subject matter.

Saying that, let's continue:

```r
library(xml2)
library(rvest)
library(dplyr)
library(ggplot2)
library(geofacet)
knitr::opts_chunk$set(fig.height=7,fig.width=12,warning=FALSE,message=FALSE)
```

## Scraping the relevant information

### Kaiser Family Foundation

#### ACA and Graham-Cassidy federal spending by state.

```r
kf_spending <- (xml2::read_html('http://www.kff.org/health-reform/issue-brief/state-by-state-estimates-of-changes-in-federal-spending-on-health-care-under-the-graham-cassidy-bill/')%>%
  rvest::html_table())[[2]][-c(1,2,3,55),]

names(kf_spending) <- c('Location','ACA','GC','DIFF','PCT')

kf_spending$Location[which(kf_spending$Location=='DC')]='District of Columbia'

kf_spending <- kf_spending%>%mutate_at(.vars=vars(ACA,GC,DIFF,PCT),.funs=funs(as.numeric(gsub('[,%]','',.))))
```

#### ACA medicare expansion by state

The decision of each state to accept medicare expansion will have a large affect on the net affect of GC on the redistribution of federal funds. States that did not accept medicare expansion are expected to have a net positive increase of federal funds.

```r
#http://www.kff.org/health-reform/state-indicator/state-activity-around-expanding-medicaid-under-the-affordable-care-act/?currentTimeframe=0&sortModel=%7B%22colId%22:%22Location%22,%22sort%22:%22asc%22%7D
kf_expansion <- read.csv('data/kf_expansion.csv',stringsAsFactors = FALSE,skip = 2)
kf_expansion <- kf_expansion[-c(1,53:61),-3]
names(kf_expansion)[2] <- 'Expansion'
```

#### Population of ACA enrollment by state.

The target population that will be used to scale the federal funds is the total marketplace enrollment for each state. We also add the characteristic of type of marketplace applied in the state to check if that has any effect.

  - Federally-Facilitated Market
  - State-based Marketplace
  - State-based Marketplace (using HealthCare.gov)

```r
#http://www.kff.org/health-reform/state-indicator/total-marketplace-enrollment/?currentTimeframe=0&sortModel=%7B%22colId%22:%22Total%20Individuals%20Who%20Have%20Selected%20a%20Marketplace%20Plan%22,%22sort%22:%22asc%22%7D
kf_marketplace_pop <- read.csv('data/kf_marketplace_pop.csv',stringsAsFactors = FALSE,skip = 2)
kf_marketplace_pop <- kf_marketplace_pop[-c(1,53:59),]
names(kf_marketplace_pop)[c(2,3)] <- c('Marketplace_Type','N')
```

### Wikipedia

#### State characteristics (2016 elections and general population)

To gather more characteristics of each state are the 2016 general election results and the total population in each state, so the prevalent scaling can be used as a comparison.

```r
wiki_elections <- (xml2::read_html('https://en.wikipedia.org/wiki/United_States_presidential_election,_2016')%>%
        rvest::xml_nodes(xpath='//*[@id="mw-content-text"]/div/div[40]/table')%>%
        rvest::html_table())[[1]][-c(1,58),c(1,3,6,23)]

names(wiki_elections) <- c('Location','Clinton','Trump','Total')

wiki_elections$Location[grep('^Nebraska',wiki_elections$Location)] <- 'Nebraska'
wiki_elections$Location[grep('^Maine',wiki_elections$Location)] <- 'Maine'

wiki_elections <- wiki_elections%>%
  mutate_at(.vars = vars(Clinton,Trump,Total),.funs=funs(as.numeric(gsub('[,]','',.))))%>%
  group_by(Location)%>%summarise_at(.vars = vars(Clinton,Trump,Total),.funs = funs(sum))%>%
  mutate(ClintonPct=Clinton/Total,TrumpPct=Trump/Total,TrumpWin=ifelse(TrumpPct>ClintonPct,'Trump Win','Clinton Win'))

wiki_pop <- (xml2::read_html('https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population')%>%
        rvest::xml_nodes(xpath='//*[@id="mw-content-text"]/div/table[1]')%>%
        rvest::html_table())[[1]][-c(30,53:64),c(3,4)]

names(wiki_pop) <- c('Location','Total_N')

wiki_pop$Total_N <- as.numeric(gsub('[,]','',wiki_pop$Total_N))
```

### Join all the data sets

We join all the information and create a new variable - the change in federal funds from ACA to GC. This is done for the rate per 1,000 individuals who have selected a market based plan and the broader per 1,000 individuals state total. The former assumes that this the more consice defition of the population better reflects what is the population serviced by the federal funding, and that it is the potential population that would be serviced by the GC bill.

```r
kf <- kf_marketplace_pop%>%
  left_join(kf_expansion,by='Location')%>%
  left_join(wiki_pop,by='Location')

kf <- kf_spending%>%left_join(kf, by = c('Location'))%>%
  mutate(ratio_ACA=1000*ACA/N,ratio_GC=1000*GC/N,ratio_DIFF = ratio_GC-ratio_ACA,
         tot_ratio_ACA=1000*ACA/Total_N,tot_ratio_GC=1000*GC/Total_N,tot_ratio_DIFF = tot_ratio_GC-tot_ratio_ACA)%>%
  arrange(desc(ratio_DIFF))

kf <- kf%>%left_join(wiki_elections,by='Location')

kf$Expansion <- sprintf('Medicaid Expansion %s',kf$Expansion)

kf$Location <- factor(kf$Location,levels = kf$Location)

kf$Marketplace_Type <- factor(kf$Marketplace_Type,labels=c('Federally-Facilitated Market','State-based Marketplace','State-based Marketplace (using HealthCare.gov)'))
```

## Plots

### Percent of state population enrolled in ACA

First we want to see what is the scope of the population in each state that have selected an ACA market based plan. (note California... not quite 12% of the US population)

```r
kf%>%
  mutate(pop_pct=100*N/Total_N)%>%
  arrange(desc(pop_pct))%>%
  mutate(Location=factor(Location,levels=Location))%>%
  ggplot(aes(x=Location,y=pop_pct))+
  geom_point()+
  coord_flip()+
  labs(y='Percent of Population that have selected an ACA market based plan')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-7-1.png)<!-- -->

### Overall distribution by Medicare Expansion

We then check that there really is a difference between states that expanded and did not expand medicaid under the ACA and if being a state that voted Republican compared to Democratic.

```r
boxplot_dat <- kf%>%
  dplyr::select(Expansion,Marketplace_Type,TrumpWin, ratio_DIFF,tot_ratio_DIFF)%>%
  reshape2::melt(.,id=c('Marketplace_Type','Expansion','TrumpWin'))

levels(boxplot_dat$variable) <- c('per 1,000 Individuals who have\nselected a market based plan','per 1,000 Individuals')

  boxplot_dat%>%
    ggplot(aes(x=Expansion,
             y=value,
             fill=TrumpWin))+
  geom_boxplot()+
  geom_hline(aes(yintercept=0),linetype=2)+
  facet_wrap(~variable,ncol=1,scales='free_y')+
  labs(title='Change in Federal Funds ACA vs Graham-Cassidy, 2020-2026',
         y='Change in Federal Funds ($ Millions) per 1,000 individuals')+
  theme_bw()+
  theme(legend.position = 'bottom')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-8-1.png)<!-- -->

Drilling down to state level figures we show for each state the change from ACA funding to the proposed GC funding per 1,000 persons who selected a market based ACA plan. The arrows move from ACA to GC funding and the y-axis is ordered by the increasing net difference. This comparison is faceted among the different characteristics scrapped from above.

Some things to look for:

  - New York has the largest negative net funding per 1,000 persons.
  - Kentucky has the largest negative net funding per 1,000 persons among Republican leaning states.
  - The net increase in funding per 1,000 persons for states that did not expand medicaid is mostly minimal.

```r
p <- kf%>%ggplot(aes(x=Location,xend=Location,yend=ratio_GC,y=ratio_ACA,colour=ratio_DIFF))+
  geom_segment(arrow = arrow(length = unit(0.02, "npc")))+
  coord_flip()+
  scale_colour_gradient(low = 'red',high = 'blue',name='Difference')+
  labs(title='Change in Federal Funds per 1,000 Individuals who have\nselected a market based plan ACA vs Graham-Cassidy, 2020-2026',
       subtitle='Arrow pointing to movement from ACA to Graham-Cassidy',
       caption='Source: Kaiser Family Foundation',
       y='Federal Funds ($ Millions) per 1,000 individuals who have selected a market based plan')+
  theme_bw()+
  theme(legend.position = 'bottom')
```

### Policial Leaning

```r
p + facet_wrap(~ TrumpWin , scales='free_y')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-10-1.png)<!-- -->

### ACA Medicare expansion

```r
p + facet_wrap(~ Expansion , scales='free_y')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-11-1.png)<!-- -->

### ACA Medicare expansion and Political Leaning

```r
p + facet_wrap(~ Expansion + TrumpWin , scales='free_y')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-12-1.png)<!-- -->

### State Marketplace Type

```r
p + facet_wrap(~ Marketplace_Type, scales='free_y')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-13-1.png)<!-- -->

### ACA Medicare expansion and State Marketplace Type

```r
p + facet_wrap(~ Expansion + Marketplace_Type , scales='free_y')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-14-1.png)<!-- -->

### Geofaceting

Lastly, we construct geographic representation of the difference between the ACA and the GC bill using [Ryan Hafen's](https://twitter.com/hafenstats)  [geofacet](https://CRAN.R-project.org/package=geofacet) package.

```r
states_facet <- state_ranks%>%left_join(kf%>%rename(name=Location),by='name')

states_facet$Expansion <- factor(states_facet$Expansion,labels=c('Expansion','No Expansion'))

states_facet$tile_lbl <- sprintf('%s\n%s',states_facet$Expansion,states_facet$TrumpWin)
```

#### Total State Population

```r
states_facet%>%
  ggplot(aes(x='1', y='1',fill=tot_ratio_DIFF)) +
  geom_tile() +
  geom_text(aes(label=tile_lbl),size=2)+
  theme_bw() +
  facet_geo( ~ state)+
  scale_fill_gradient2(low='red',mid='white',high='green',name='Difference') +
  theme(legend.position = 'bottom',
        axis.text = element_blank(),
        axis.title = element_blank(),
        axis.ticks = element_blank())+
  labs(title='Change in Federal Funds per 1,000 Individuals, 2020-2026',
       caption='Source: Kaiser Family Foundation')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-16-1.png)<!-- -->

#### ACA enrollment population

```r
states_facet%>%
  ggplot(aes(x='1', y='1',fill=ratio_DIFF)) +
  geom_tile() +
  geom_text(aes(label=tile_lbl),size=2)+
  theme_bw() +
  facet_geo( ~ state)+
  scale_fill_gradient2(low='red',mid='white',high='green',name='Difference') +
  theme(legend.position = 'bottom',
        axis.text = element_blank(),
        axis.title = element_blank(),
        axis.ticks = element_blank())+
  labs(title='Change in Federal Funds per 1,000 Individuals who have\nselected a market based plan ACA vs Graham-Cassidy, 2020-2026',
       caption='Source: Kaiser Family Foundation')
```

![](https://raw.githubusercontent.com/yonicd/yonicd.github.io/master/img/aca/unnamed-chunk-17-1.png)<!-- -->


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;

namespace Sample.RabbitMQ.MongoDB
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IMongoClient>(new MongoClient(Configuration.GetConnectionString("MongoDB")));
            services.AddCap(x =>
            {
                x.UseMongoDB(Configuration.GetConnectionString("MongoDB"));
                x.UseRabbitMQ("");
                x.UseDashboard();
            });
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}


text:
package com.autochime.autochimeapplication.fragments;

import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.autochime.autochimeapplication.R;

public class AddContactFragment extends DialogFragment implements
        LoaderManager.LoaderCallbacks<Cursor>,
        AdapterView.OnItemClickListener{

    private final static String[] FROM_COLUMNS = {
            ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
    };
    private final static int[] TO_IDS = {
            R.id.addcontact_contact_name
    };

    ListView mContactsList;
    Uri mContactUri;
    private SimpleCursorAdapter mCursorAdapter;

    private static final String[] PROJECTION =
            {
                    ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.LOOKUP_KEY,
                    ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
            };

    private static final long CONTACT_ID_INDEX = 0;

    public AddContactFragment() {
    }

    public static AddContactFragment newInstance() {
        AddContactFragment f = new AddContactFragment();
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_addcontact_list,
                container, false);
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContactsList = (ListView) getView().findViewById(R.id.addcontact_list);
        mContactsList.setOnItemClickListener(this);
        mCursorAdapter = new SimpleCursorAdapter(
                getActivity(),
                R.layout.fragment_addcontact,
                null,
                FROM_COLUMNS, TO_IDS,
                0);
        mContactsList.setAdapter(mCursorAdapter);
        getLoaderManager().initLoader(0, null, this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View item, int position, long rowID) {
        Cursor cursor = ((SimpleCursorAdapter)parent.getAdapter()).getCursor();
        cursor.moveToPosition(position);
        mContactUri = ContactsContract.Contacts.getLookupUri(CONTACT_ID_INDEX, null);
        /*
         * You can use mContactUri as the content URI for retrieving
         * the details for a contact.
         */
    }

    @Override
    public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {
        return new CursorLoader(
                getActivity(),
                ContactsContract.Contacts.CONTENT_URI,
                PROJECTION,
                null,
                null,
                null
        );
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        // Put the result Cursor in the adapter for the ListView
        mCursorAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // Delete the reference to the existing Cursor
        mCursorAdapter.swapCursor(null);

    }
}


text:
package com.omnicrola.hermes;

import org.junit.Before;
import org.junit.Test;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Created by Eric on 9/13/2015.
 */
public class JsonWrapperTest {

    private ResultSet mockResultSet;
    private ResultSetMetaData mockMetaData;
    private JsonWrapper jsonWrapper;

    @Before
    public void setup() {
        this.mockResultSet = mock(ResultSet.class);
        this.mockMetaData = mock(ResultSetMetaData.class);
        this.jsonWrapper = new JsonWrapper(mockResultSet);
    }

    @Test
    public void testStringify() throws Exception {
        String expectedColumnName1 = "Bargle";
        String expectedColumnName2 = "feebeeToo44";
        String expectedColumnName3 = "bator cat";
        int expectedInteger1 = 482344;
        int expectedInteger2 = 482344;
        double expectedDecimal1 = 454.23622;
        double expectedDecimal2 = 39.582727374;
        String expectedString1 = "I've got a lovely bunch of cocoanuts";
        String expectedString2 = "There they are a standing in the !@#$%^&*\\() road";

        String expectedJson = "[" +
                "{" +
                "\"" + expectedColumnName1 + "\" : \"" + expectedInteger1 + "\", " +
                "\"" + expectedColumnName2 + "\" : \"" + expectedDecimal1 + "\", " +
                "\"" + expectedColumnName3 + "\" : \"" + expectedString1 + "\"" +
                "}, " +
                "{" +
                "\"" + expectedColumnName1 + "\" : \"" + expectedInteger2 + "\", " +
                "\"" + expectedColumnName2 + "\" : \"" + expectedDecimal2 + "\", " +
                "\"" + expectedColumnName3 + "\" : \"" + expectedString2 + "\"" +
                "}" +
                "]";

        when(mockResultSet.getMetaData()).thenReturn(mockMetaData);
        when(mockMetaData.getColumnCount()).thenReturn(3);
        when(mockMetaData.getColumnName(1)).thenReturn(expectedColumnName1);
        when(mockMetaData.getColumnName(2)).thenReturn(expectedColumnName2);
        when(mockMetaData.getColumnName(3)).thenReturn(expectedColumnName3);

        when(mockResultSet.next())
                .thenReturn(true)
                .thenReturn(true)
                .thenReturn(false);

        when(mockResultSet.getObject(1))
                .thenReturn(expectedInteger1)
                .thenReturn(expectedInteger2);

        when(mockResultSet.getObject(2))
                .thenReturn(expectedDecimal1)
                .thenReturn(expectedDecimal2);

        when(mockResultSet.getObject(3))
                .thenReturn(expectedString1)
                .thenReturn(expectedString2);

        String actualJson = this.jsonWrapper.stringify();
        assertEquals(expectedJson, actualJson);
    }

}


text:
import sys
import json
import csv
import bm_json
import json
import subprocess

columns = []

for row in json.loads(
        subprocess.check_output([
            'bq', '--format=json', 'show', 'microbenchmarks.microbenchmarks'
        ]))['schema']['fields']:
    columns.append((row['name'], row['type'].lower()))

SANITIZE = {
    'integer': int,
    'float': float,
    'boolean': bool,
    'string': str,
    'timestamp': str,
}

if sys.argv[1] == '--schema':
    print ',\n'.join('%s:%s' % (k, t.upper()) for k, t in columns)
    sys.exit(0)

with open(sys.argv[1]) as f:
    js = json.loads(f.read())

if len(sys.argv) > 2:
    with open(sys.argv[2]) as f:
        js2 = json.loads(f.read())
else:
    js2 = None

writer = csv.DictWriter(sys.stdout, [c for c, t in columns])

for row in bm_json.expand_json(js, js2):
    sane_row = {}
    for name, sql_type in columns:
        if name in row:
            if row[name] == '': continue
            sane_row[name] = SANITIZE[sql_type](row[name])
    writer.writerow(sane_row)


text:
///////////////////////////////////////////////////////////////////////////////
//
//  Same as Calc4, this time, we'll incorporate debugging support,
//  plus error handling and reporting.
//
//  [ JDG April 28, 2008 ]      For BoostCon 2008
//  [ JDG February 18, 2011 ]   Pure attributes. No semantic actions.
//
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Spirit v2.5 allows you to suppress automatic generation
// of predefined terminals to speed up complation. With
// BOOST_SPIRIT_NO_PREDEFINED_TERMINALS defined, you are
// responsible in creating instances of the terminals that
// you need (e.g. see qi::uint_type uint_ below).
#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Define this to enable debugging
#define BOOST_SPIRIT_QI_DEBUG

///////////////////////////////////////////////////////////////////////////////
// Uncomment this if you want to enable debugging
//#define BOOST_SPIRIT_QI_DEBUG
///////////////////////////////////////////////////////////////////////////////

#if defined(_MSC_VER)
# pragma warning(disable: 4345)
#endif

#include <boost/spirit/include/qi.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/phoenix/function.hpp>
#include <boost/foreach.hpp>

#include <iostream>
#include <string>

namespace client { namespace ast
{
    ///////////////////////////////////////////////////////////////////////////
    //  The AST
    ///////////////////////////////////////////////////////////////////////////
    struct nil {};
    struct signed_;
    struct program;

    typedef boost::variant<
            nil
          , unsigned int
          , boost::recursive_wrapper<signed_>
          , boost::recursive_wrapper<program>
        >
    operand;

    struct signed_
    {
        char sign;
        operand operand_;
    };

    struct operation
    {
        char operator_;
        operand operand_;
    };

    struct program
    {
        operand first;
        std::list<operation> rest;
    };

    // print function for debugging
    inline std::ostream& operator<<(std::ostream& out, nil) { out << "nil"; return out; }
}}

BOOST_FUSION_ADAPT_STRUCT(
    client::ast::signed_,
    (char, sign)
    (client::ast::operand, operand_)
)

BOOST_FUSION_ADAPT_STRUCT(
    client::ast::operation,
    (char, operator_)
    (client::ast::operand, operand_)
)

BOOST_FUSION_ADAPT_STRUCT(
    client::ast::program,
    (client::ast::operand, first)
    (std::list<client::ast::operation>, rest)
)

namespace client { namespace ast
{
    ///////////////////////////////////////////////////////////////////////////
    //  The AST Printer
    ///////////////////////////////////////////////////////////////////////////
    struct printer
    {
        typedef void result_type;

        void operator()(nil) const {}
        void operator()(unsigned int n) const { std::cout << n; }

        void operator()(operation const& x) const
        {
            boost::apply_visitor(*this, x.operand_);
            switch (x.operator_)
            {
                case '+': std::cout << " add"; break;
                case '-': std::cout << " subt"; break;
                case '*': std::cout << " mult"; break;
                case '/': std::cout << " div"; break;
            }
        }

        void operator()(signed_ const& x) const
        {
            boost::apply_visitor(*this, x.operand_);
            switch (x.sign)
            {
                case '-': std::cout << " neg"; break;
                case '+': std::cout << " pos"; break;
            }
        }

        void operator()(program const& x) const
        {
            boost::apply_visitor(*this, x.first);
            BOOST_FOREACH(operation const& oper, x.rest)
            {
                std::cout << ' ';
                (*this)(oper);
            }
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    //  The AST evaluator
    ///////////////////////////////////////////////////////////////////////////
    struct eval
    {
        typedef int result_type;

        int operator()(nil) const { BOOST_ASSERT(0); return 0; }
        int operator()(unsigned int n) const { return n; }

        int operator()(operation const& x, int lhs) const
        {
            int rhs = boost::apply_visitor(*this, x.operand_);
            switch (x.operator_)
            {
                case '+': return lhs + rhs;
                case '-': return lhs - rhs;
                case '*': return lhs * rhs;
                case '/': return lhs / rhs;
            }
            BOOST_ASSERT(0);
            return 0;
        }

        int operator()(signed_ const& x) const
        {
            int rhs = boost::apply_visitor(*this, x.operand_);
            switch (x.sign)
            {
                case '-': return -rhs;
                case '+': return +rhs;
            }
            BOOST_ASSERT(0);
            return 0;
        }

        int operator()(program const& x) const
        {
            int state = boost::apply_visitor(*this, x.first);
            BOOST_FOREACH(operation const& oper, x.rest)
            {
                state = (*this)(oper, state);
            }
            return state;
        }
    };
}}

namespace client
{
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;
    using boost::phoenix::function;

    ///////////////////////////////////////////////////////////////////////////////
    //  Our error handler
    ///////////////////////////////////////////////////////////////////////////////
    struct error_handler_
    {
        template <typename, typename, typename>
        struct result { typedef void type; };

        template <typename Iterator>
        void operator()(
            qi::info const& what
          , Iterator err_pos, Iterator last) const
        {
            std::cout
                << "Error! Expecting "
                << what                         // what failed?
                << " here: \""
                << std::string(err_pos, last)   // iterators to error-pos, end
                << "\""
                << std::endl
            ;
        }
    };

    function<error_handler_> const error_handler = error_handler_();

    ///////////////////////////////////////////////////////////////////////////////
    //  Our calculator grammar
    ///////////////////////////////////////////////////////////////////////////////
    template <typename Iterator>
    struct calculator : qi::grammar<Iterator, ast::program(), ascii::space_type>
    {
        calculator() : calculator::base_type(expression)
        {
            qi::char_type char_;
            qi::uint_type uint_;
            qi::_2_type _2;
            qi::_3_type _3;
            qi::_4_type _4;

            using qi::on_error;
            using qi::fail;

            expression =
                term
                >> *(   (char_('+') > term)
                    |   (char_('-') > term)
                    )
                ;

            term =
                factor
                >> *(   (char_('*') > factor)
                    |   (char_('/') > factor)
                    )
                ;

            factor =
                    uint_
                |   '(' > expression > ')'
                |   (char_('-') > factor)
                |   (char_('+') > factor)
                ;

            // Debugging and error handling and reporting support.
            BOOST_SPIRIT_DEBUG_NODE(expression);
            BOOST_SPIRIT_DEBUG_NODE(term);
            BOOST_SPIRIT_DEBUG_NODE(factor);

            // Error handling
            on_error<fail>(expression, error_handler(_4, _3, _2));
        }

        qi::rule<Iterator, ast::program(), ascii::space_type> expression;
        qi::rule<Iterator, ast::program(), ascii::space_type> term;
        qi::rule<Iterator, ast::operand(), ascii::space_type> factor;
    };
}

///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int
main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Expression parser...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Type an expression...or [q or Q] to quit\n\n";

    typedef std::string::const_iterator iterator_type;
    typedef client::calculator<iterator_type> calculator;
    typedef client::ast::program ast_program;
    typedef client::ast::printer ast_print;
    typedef client::ast::eval ast_eval;

    std::string str;
    while (std::getline(std::cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        calculator calc;        // Our grammar
        ast_program program;    // Our program (AST)
        ast_print print;        // Prints the program
        ast_eval eval;          // Evaluates the program

        std::string::const_iterator iter = str.begin();
        std::string::const_iterator end = str.end();
        boost::spirit::ascii::space_type space;
        bool r = phrase_parse(iter, end, calc, space, program);

        if (r && iter == end)
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing succeeded\n";
            print(program);
            std::cout << "\nResult: " << eval(program) << std::endl;
            std::cout << "-------------------------\n";
        }
        else
        {
            std::string rest(iter, end);
            std::cout << "-------------------------\n";
            std::cout << "Parsing failed\n";
            std::cout << "-------------------------\n";
        }
    }

    std::cout << "Bye... :-) \n\n";
    return 0;
}


text:
package com.gk.sharefile;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;

    /**
     * http://developer.android.com/training/sharing/send.html
     */
    public class ShareFile extends CordovaPlugin {

        @Override
        public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
            if (action.equals("share")) {
                String FileURI = args.getString(0);
                String title = args.getString(1);
                String mimetype = args.getString(2);
                this.share(FileURI, title, mimetype, callbackContext);
                return true;
            }
            return false;
        }

        private void share(String text, String title, String mimetype, CallbackContext callbackContext) {
          try {
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_STREAM, uriToFile);
            sendIntent.setType(mimetype);
            cordova.getActivity().startActivity(Intent.createChooser(sendIntent, title));
            callbackContext.success();
            } catch(Error e) {
                callbackContext.error(e.getMessage());
            }

        }
    }


text:
@implementation SKUser

- (NSString *)description {
    return [NSString stringWithFormat:@"<%@ username=%@, emoji=%@, needs love=%d, sees your stories=%d, is shared=%d, is local=%d>",
            NSStringFromClass(self.class), self.username, self.friendmojiString, self.needsLove, self.canSeeCustomStories, self.isSharedStory, self.isLocalStory];
}

#pragma mark - Mantle

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return [@{@"friendmojiString": @"friendmoji_string",
              @"friendmojiTypes": @"friendmoji_symbols",
              @"venue": @"venue",
              @"snapStreakCount": @"snap_streak_count",
              @"sharedStoryIdentifier": @"shared_story_id",
              @"canSeeCustomStories": @"can_see_custom_stories",
              @"needsLove": @"needs_love",
              @"isSharedStory": @"is_shared_story",
              @"isLocalStory": @"local_story",
              @"hasCustomDescription": @"has_custom_description",
              @"decayThumbnail": @"dont_decay_thumbnail",
              @"timestamp": @"ts"} mtl_dictionaryByAddingEntriesFromDictionary:[super JSONKeyPathsByPropertyKey]];
}

MTLTransformPropertyDate(timestamp)
MTLTransformPropertyDate(expiration)

#pragma mark - Equality

- (BOOL)isEqual:(id)object {
    if ([object isKindOfClass:[SKUser class]])
        return [self isEqualToUser:object];

    return [super isEqual:object];
}

- (BOOL)isEqualToUser:(SKUser *)user {
    return [self.friendmojiString isEqualToString:user.friendmojiString] && [super isEqual:user];
}

@end


text:
package com.zhaoxinwo.ui;

import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

import com.github.amlcurran.showcaseview.ShowcaseView;
import com.zhaoxinwo.api.ZApi;
import com.zhaoxinwo.api.ZColor;
import com.zhaoxinwo.model.House;
import com.zhaoxinwo.model.Result;
import com.zhaoxinwo.utils.SwipeBackActivity;

public class ResultActivity extends SwipeBackActivity {
	protected static final String TAG = "ResultActivity";
	private String keywords = null;
	private int pageNum = 1;
	private ArrayList<House> houses = new ArrayList<House>();
	private SimpleAdapter listItemAdapter = null;
	private ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
	private ListView listview = null;
	private TextView text_more;
	private Handler resultHandler = new Handler() {
		@Override
		public void handleMessage(Message message) {
			super.handleMessage(message);
			if (message.obj == null) {
				ResultActivity.this.text_more.setText("网络不佳额");
				Toast.makeText(getApplicationContext(), "网络不佳额",
						Toast.LENGTH_SHORT).show();
				return;
			}

			ArrayList<Object> list = (ArrayList<Object>) message.obj;
			ArrayList<House> result = (ArrayList) ((Result) list.get(0)).result;
			if (result.isEmpty()) {
				// Set title
				ResultActivity.this.text_more.setText("没有更多啦");
				Toast.makeText(getApplicationContext(), "没有更多啦",
						Toast.LENGTH_SHORT).show();
				return;

			}

			ArrayList<Bitmap> avatars = (ArrayList<Bitmap>) list.get(1);
			houses.addAll(result);
			for (int i = 0; i < result.size(); i++) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("sim", result.get(i).sim);
				map.put("title", result.get(i).title);
				map.put("name", result.get(i).author.name);
				map.put("pub_time", result.get(i).pub_time);
				map.put("avatar", avatars.get(i));
				map.put("text", result.get(i).text);
				map.put("ditie", result.get(i).ditie);
				map.put("dizhi", result.get(i).dizhi);
				map.put("jushi", result.get(i).jushi);
				map.put("zujin", result.get(i).zujin);
				map.put("shouji", result.get(i).shouji);
				map.put("url", result.get(i).url);
				map.put("image", result.get(i).images);
				listItem.add(map);
			}
			ResultActivity.this.text_more.setText("上拉加载更多");
			listItemAdapter.notifyDataSetChanged();
		}
	};

	private ViewBinder viewbinder = new ViewBinder() {
		@Override
		public boolean setViewValue(View view, Object data,
				String textRepresentation) {
			// Filter empty list and string
			if (data instanceof String) {
				if (((String) data).length() == 0) {
					view.setVisibility(View.GONE);
					return true;
				} else {
					view.setVisibility(View.VISIBLE);
				}
			}
			if (data instanceof ArrayList) {
				if (((ArrayList) data).size() == 0) {
					view.setVisibility(View.GONE);
					return true;
				} else {
					view.setVisibility(View.VISIBLE);
				}
			}

			if (view.getId() == R.id.sim) {
				((TextView) view).setText(String.format("重复发贴%d次",
						((ArrayList<Object>) data).size()));
				return true;

			}
			if (view instanceof ImageView && data instanceof Bitmap) {
				ImageView iv = (ImageView) view;
				iv.setImageBitmap((Bitmap) data);
				return true;
			}
			if (view.getId() == R.id.ditie) {
				ArrayList<String> dities = (ArrayList<String>) data;
				String html = "";
				ZColor color = new ZColor();
				for (String ditie : dities) {
					String ditieColor = color.ditie(ditie);
					html += String.format("%s ",
							ditieColor, ditie);
				}
				((TextView) view).setText(Html.fromHtml(html),
						TextView.BufferType.SPANNABLE);
				return true;

			}
			if (view.getId() == R.id.dizhi) {
				((TextView) view).setText(((ArrayList<String>) data).toString()
						.replaceAll("[\\[\\]]", ""));
				return true;

			}
			if (view.getId() == R.id.text) {
				final String text = (String) data;
				TextView textview = (TextView) view;
				textview.setText(text);
				textview.setMaxLines(5);
				textview.setEllipsize(TruncateAt.END);
				textview.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						TextView textview = (TextView) v;
						textview.setText(text);
						if (textview.getEllipsize() != null) {
							textview.setEllipsize(null);
							textview.setMaxLines(100);
						} else {
							textview.setEllipsize(TruncateAt.END);
							textview.setMaxLines(5);
						}

					}
				});

				return true;
			}
			if (view.getId() == R.id.shouji) {
				((TextView) view).setText((String) data);
				((TextView) view).getPaint()
						.setFlags(Paint.UNDERLINE_TEXT_FLAG);
				final String phoneNum = ((String) data).split(",")[0];
				view.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_DIAL, Uri
								.parse("tel:" + phoneNum));
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						ResultActivity.this.startActivity(intent);
					}
				});
				return true;
			}
			return false;
		}

	};

	private void pullData() {

		new Thread(new Runnable() {
			@Override
			public void run() {

				ZApi api = new ZApi();
				Result result = api.search(keywords, pageNum);
				ArrayList<Bitmap> avatars = new ArrayList<Bitmap>();

				if (result == null) {
					Message message = Message.obtain();
					message.obj = null;
					resultHandler.sendMessage(message);
					return;
				}

				for (House house : result.result) {
					Bitmap avatar = api.doGetImage(house.author.avatar);
					if (avatar == null) {

						Message message = Message.obtain();
						message.obj = null;
						resultHandler.sendMessage(message);
						return;
					}
					avatars.add(avatar);
				}

				ArrayList<Object> list = new ArrayList<Object>();
				list.add(result);
				list.add(avatars);

				Message message = Message.obtain();
				message.obj = list;
				resultHandler.sendMessage(message);
				pageNum++;

			}

		}).start();

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Hide title
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_result);

		// Get keywords from HomeActivity
		keywords = getIntent().getStringExtra("keywords");

		// Set title
		((TextView) findViewById(R.id.text_title)).setText("当前搜索: " + keywords);
//		Toast.makeText(getApplicationContext(), keywords, Toast.LENGTH_SHORT).show();

		listview = (ListView) findViewById(R.id.listview_result);

		listItemAdapter = new SimpleAdapter(ResultActivity.this, listItem,
				R.layout.listview_item, new String[] { "sim", "title", "name",
						"pub_time", "avatar", "text", "ditie", "dizhi",
						"jushi", "zujin", "shouji" }, new int[] { R.id.sim,
						R.id.title, R.id.name, R.id.pub_time, R.id.avatar,
						R.id.text, R.id.ditie, R.id.dizhi, R.id.jushi,
						R.id.zujin, R.id.shouji }) {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = super.getView(position, convertView, parent);
				final TextView html = (TextView) view
						.findViewById(com.zhaoxinwo.ui.R.id.html);
				final TextView image = (TextView) view
						.findViewById(com.zhaoxinwo.ui.R.id.image);
				final TextView favorate = (TextView) view
						.findViewById(com.zhaoxinwo.ui.R.id.favorate);

				final int index = position;

				if (houses.get(index).images.isEmpty()) {
					image.setVisibility(View.GONE);
				} else {
					image.setVisibility(View.VISIBLE);
				}

				OnClickListener listener = new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (v == html) {
							Intent browserIntent = new Intent(
									Intent.ACTION_VIEW, Uri.parse(houses
											.get(index).url));
							startActivity(browserIntent);
						}
						if (v == image) {
							Intent intent = new Intent(ResultActivity.this,
									ImageActivity.class);

							ArrayList<String> imageUrls = new ArrayList<String>();
							ArrayList<String> imageTitles = new ArrayList<String>();
							for (ArrayList<String> list : houses.get(index).images) {
								imageUrls.add(list.get(0));
								imageTitles.add(list.get(1));
							}
							if (!imageUrls.isEmpty()) {
								intent.putExtra("urls", imageUrls);
								intent.putExtra("titles", imageTitles);
								startActivity(intent);
							}
						}
						if (v == favorate) {
							Intent intent = new Intent(Intent.ACTION_SEND);
							intent.setType("text/plain");
							intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
							intent.putExtra(
									Intent.EXTRA_TEXT,
									new Formatter()
											.format("来源: %s\n收藏自找新窝(zhaoxinwo.com)\n\n%s",
													houses.get(index).url,
													houses.get(index).text)
											.toString());
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivity(Intent.createChooser(intent,
									getTitle()));
						}

					}
				};
				html.setOnClickListener(listener);
				image.setOnClickListener(listener);
				favorate.setOnClickListener(listener);
				return view;
			}

		};

		listItemAdapter.setViewBinder(viewbinder);
		pullData();

		// Load more data
		text_more = new TextView(ResultActivity.this);
		text_more.setGravity(Gravity.CENTER_HORIZONTAL);
		text_more.setPadding(0, 0, 0, 24);
		text_more.setBackgroundColor(getResources()
				.getColor(R.color.WhiteSmoke));
		text_more.setText("加载中...");
		/*
		text_more.setText("点击加载更多");
		text_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				pullData();
			}
		});
		*/

		listview.addFooterView(text_more);
		listview.setAdapter(listItemAdapter);
		listview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){	//滚动停止
					if(view.getLastVisiblePosition() == view.getCount()-1){
						Log.v(TAG, "now at the bottom of listview, auto load more");
						ResultActivity.this.text_more.setText("加载中...");
						pullData();
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});

		SharedPreferences sharedata = getSharedPreferences("first_run", 0);
        Boolean isSoupon = sharedata.getBoolean("isSoupon", true);
        if (isSoupon) {
			ShowcaseView showcaseView = new ShowcaseView.Builder(this)
	        .setStyle(R.style.Custom_semi_transparent_demo)//setStyle instead of setTarget!
	        .hideOnTouchOutside()
	        .build();
	//		showcaseView.setBackground(getResources().getDrawable(R.drawable.swipe_back_en));//minAPI=16
			showcaseView.setBackgroundDrawable(getResources().getDrawable(R.drawable.swipe_back_en));//deprecated.
			//更新flag,第二次打开时不再显示
			Editor sharedataEditor = getSharedPreferences("first_run", 0).edit();
			sharedataEditor.putBoolean("isSoupon", false);
			sharedataEditor.commit();
        }
	}
}


text:
export function foo() {}
foo.bar = 12;
const _private = Symbol();
foo[_private] = "ok";

const x: string = foo[_private];


text:
body {
    min-height: 2000px;
    padding-top: 70px;
}

label{
    display: inline-block;
    padding-top: 5px;
}

.growl-container.growl-fixed.top-center {
    top : 2em!important;
    width: 25%!important;
    max-width: 50%!important;
    text-align: center;
}

.growl-container > .growl-item {
    padding-right:0!important;
}

.pagination {
    margin:0!important;
}

.table-header-rotated th.row-header{
  width: auto;
}

.table-header-rotated td{
  width: 40px;
  border-top: 1px solid #dddddd;
  border-left: 1px solid #dddddd;
  border-right: 1px solid #dddddd;
  border-bottom: 1px solid #dddddd;
  vertical-align: middle;
  text-align: center;
}

.table-header-rotated th.rotate-45{
  height: 140px;
  width: 50px;
  min-width: 40px;
  max-width: 50px;
  position: relative;
  vertical-align: bottom;
  padding: 0;
  font-size: 12px;
  line-height: 0.8;
}

.table-header-rotated th.rotate-45 > div{
  position: relative;
  top: 12px;
  left: 70px; /* 80 * tan(45) / 2 = 40 where 80 is the height on the cell and 45 is the transform angle*/
  height: 100%;
  -ms-transform:skew(-45deg,0deg);
  -moz-transform:skew(-45deg,0deg);
  -webkit-transform:skew(-45deg,0deg);
  -o-transform:skew(-45deg,0deg);
  transform:skew(-45deg,0deg);
  overflow: hidden;
  border-left: 1px solid #dddddd;
  border-right: 1px solid #dddddd;
  border-top: 1px solid #dddddd;
}

.table-header-rotated th.rotate-45 span {
  -ms-transform:skew(45deg,0deg) rotate(315deg);
  -moz-transform:skew(45deg,0deg) rotate(315deg);
  -webkit-transform:skew(45deg,0deg) rotate(315deg);
  -o-transform:skew(45deg,0deg) rotate(315deg);
  transform:skew(45deg,0deg) rotate(315deg);
  position: absolute;
  bottom: 65px; /* 40 cos(45) = 28 with an additional 2px margin*/
  left: -35px; /*Because it looked good, but there is probably a mathematical link here as well*/
  display: inline-block;
  // width: 100%;
  width: 160px; /* 80 / cos(45) - 40 cos (45) = 85 where 80 is the height of the cell, 40 the width of the cell and 45 the transform angle*/
  text-align: left;
  // white-space: nowrap; /*whether to display in one line or not*/
  word-wrap: break-word;
}


text:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="../bower_components/iron-pages/iron-pages.html">
<link rel="import" href="ta-day-dependent-behavior.html">
<link rel="import" href="ta-shell-behavior.html">
<link rel="import" href="ta-shell-layout.html">
<link rel="import" href="ta-shell-search-layout.html">
<link rel="import" href="ta-place-search.html">

<dom-module id="ta-goal-create-shell">
    <template>
        <app-route route="{{route}}" pattern="/places/:id/details" data="{{detailsData}}" active="{{detailsActive}}" tail="{{detailsTail}}"></app-route>
        <iron-pages class="flex" selected="[[page]]" fallback-selection="0">
            <ta-shell-search-layout on-back-tap="_handleCancelTap" search-value="{{_searchValue}}" search-placeholder="Find Interesting Place">
                <ta-place-search id="search" user-uid="[[userUid]]" trip-key="[[tripKey]]" day-key="[[dayKey]]" search-value="[[_searchValue]]"></ta-place-search>
            </ta-shell-search-layout>
            <ta-shell-layout burger-button back-button title="[[details.name]]" header-background-url="[[details.photoUrl]]">
                <app-toolbar class="middle"></app-toolbar>
                <app-toolbar class="bottom"></app-toolbar>
                <ta-goal-create-place-details user-uid="[[userUid]]" trip-key="[[tripKey]]" day-key="[[dayKey]]" place-key="[[detailsData.id]]" details="{{details}}" on-goal-created="_handleGoalCreated"></ta-goal-create-place-details>
            </ta-shell-layout>
        </iron-pages>
    </template>
    <script>
    (() => {
        'use strict';
        class TaGoalCreateShell {
            get is() {
                return 'ta-goal-create-shell';
            }
            get behaviors() {
                return [TaShellBehavior, TaDayDependentBehavior];
            }
            get properties() {
                return {
                    page: {
                        type: Number,
                        computed: '_computePage(detailsActive)'
                    },
                    detailsActive: {
                        type: Boolean,
                        value: false
                    },
                    nextShells: {
                        type: Array,
                        value: [
                            '/src/ta-goal-create-place-details.html'
                        ]
                    }
                };
            }
            _computePage(detailsActive) {
                if (detailsActive)
                    return 1;
                else
                    return 0;
            }
            _handleCancelTap() {
                this.$.search.reset();
            }
            _handleGoalCreated() {
                window.history.go(-2);
            }
        }
        Polymer(TaGoalCreateShell);
    })();
    </script>
</dom-module>


text:
function ctsop_submit()
{
	if(document.ctsop_form.ctsop_text.value=="")
	{
		alert("Please enter the message.")
		document.ctsop_form.ctsop_text.focus();
		return false;
	}
	else if(document.ctsop_form.ctsop_status.value=="")
	{
		alert("Please select display status.")
		document.ctsop_form.ctsop_status.focus();
		return false;
	}
	else if(document.ctsop_form.ctsop_group.value=="")
	{
		alert("Please select group name. this field is used to group the message.")
		document.ctsop_form.ctsop_group.focus();
		return false;
	}
	else if(document.ctsop_form.ctsop_order.value=="")
	{
		alert("Please enter display order, only number.")
		document.ctsop_form.ctsop_order.focus();
		return false;
	}
	else if(isNaN(document.ctsop_form.ctsop_order.value))
	{
		alert("Please enter display order, only number.")
		document.ctsop_form.ctsop_order.focus();
		document.ctsop_form.ctsop_order.select();
		return false;
	}
	_ctsop_escapeVal(document.ctsop_form.ctsop_text,'<br>');
}

function ctsop_delete(id)
{
	if(confirm("Do you want to delete this record?"))
	{
		document.frm_ctsop_display.action="options-general.php?page=content-text-slider-on-post&ac=del&did="+id;
		document.frm_ctsop_display.submit();
	}
}

function ctsop_redirect()
{
	window.location = "options-general.php?page=content-text-slider-on-post";
}

function _ctsop_help()
{
	window.open("http://www.gopiplus.com/work/2012/01/02/content-text-slider-on-post-wordpress-plugin/");
}

function _ctsop_escapeVal(textarea,replaceWith)
{
textarea.value = escape(textarea.value) //encode textarea strings carriage returns
for(i=0; i<textarea.value.length; i++)
{
	//loop through string, replacing carriage return encoding with HTML break tag
	if(textarea.value.indexOf("%0D%0A") > -1)
	{
		//Windows encodes returns as \r\n hex
		textarea.value=textarea.value.replace("%0D%0A",replaceWith)
	}
	else if(textarea.value.indexOf("%0A") > -1)
	{
		//Unix encodes returns as \n hex
		textarea.value=textarea.value.replace("%0A",replaceWith)
	}
	else if(textarea.value.indexOf("%0D") > -1)
	{
		//Macintosh encodes returns as \r hex
		textarea.value=textarea.value.replace("%0D",replaceWith)
	}
}
textarea.value=unescape(textarea.value) //unescape all other encoded characters
}


text:
package org.platanios.tensorflow.api.ops

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

/**
  * @author Emmanouil Antonios Platanios
  */
class BasicSpec extends AnyFlatSpec with Matchers {
//  "'ArrayOps.constant'" must "create a constant op when provided a Tensor of the same data type and shape" in {
//    // DataType.Int32 Tensor
//    val tensor1 = Tensor(Tensor(Tensor(2, 3), Tensor(0, 0), Tensor(5, 7)),
//                         Tensor(Tensor(1, 23), Tensor(4, -5), Tensor(7, 9)),
//                         Tensor(Tensor(56, 1), Tensor(-2, -4), Tensor(-7, -9)))
//    val constant1 = ArrayOps.constant(tensor1)
//    val constantValue1 = constant1.value()
//    assert(tensor1.get(1, 1, 1) === -5)
//    assert(constant1.shape === Shape(3, 3, 2))
//    assert(constant1.dataType === DataType.Int32)
//    assert(constantValue1.shape === Shape(3, 3, 2))
//    assert(constantValue1.dataType === DataType.Int32)
//    assert(constantValue1(1, 1, 1) === -5)
//    tensor1.close()
//
//    // DataType.Float64 Tensor
//    val tensor2 = Tensor.create(array, dataType = DataType.Float64)
//    val constant2 = ArrayOps.constant(tensor2)
//    val constantValue2 = constant2.value()
//    assert(tensor2(1, 1, 1) === -5.0)
//    assert(constant2.shape === Shape(3, 3, 2))
//    assert(constant2.dataType === DataType.Float64)
//    assert(constantValue2.shape === Shape(3, 3, 2))
//    assert(constantValue2.dataType === DataType.Float64)
//    assert(constantValue2(1, 1, 1) === -5.0)
//    tensor2.close()
//  }
}


text:
var dom = require('poochie/dom');

var modules = ['hello', 'canvas', 'layout', 'react'];

function mkRow (nm) {
    return dom.element({
        name: 'a',
        attributes: {href: nm + '/index.html'},
        style: {display: 'block'},
        contents: nm
    });
}

var rows = [
    dom.element({name: 'h3', contents: 'Modules'})
];

module.exports = dom.element({
    name: 'div',
    style: {margin: '10px'},
    contents: rows.concat(modules.map(mkRow))
});


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/automl/v1/text.proto

package com.google.cloud.automl.v1;

public interface TextSentimentDatasetMetadataOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.automl.v1.TextSentimentDatasetMetadata)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. A sentiment is expressed as an integer ordinal, where higher value
   * means a more positive sentiment. The range of sentiments that will be used
   * is between 0 and sentiment_max (inclusive on both ends), and all the values
   * in the range must be represented in the dataset before a model can be
   * created.
   * sentiment_max value must be between 1 and 10 (inclusive).
   *

   *
   * int32 sentiment_max = 1;
   *
   * @return The sentimentMax.
   */
  int getSentimentMax();
}


text:
package de.neuland.jade4j.parser.node;

import de.neuland.jade4j.compiler.IndentWriter;
import de.neuland.jade4j.exceptions.JadeCompilerException;
import de.neuland.jade4j.model.JadeModel;
import de.neuland.jade4j.parser.Parser;
import de.neuland.jade4j.template.JadeTemplate;

import java.util.ArrayList;
import java.util.Collection;

public class BlockNode extends Node {

	private boolean yield = false;
	private BlockNode yieldBlock;
	private String mode;
	private Collection<? extends Node> prepended = new ArrayList<Node>();
	private Collection<? extends Node> appended = new ArrayList<Node>();;
	private Parser parser;
	private boolean subBlock;

	public void execute(IndentWriter writer, JadeModel model, JadeTemplate template) throws JadeCompilerException {

		// Pretty print multi-line text
		if (writer.isPp() && getNodes().size() > 1 && !writer.isEscape() && getNodes().get(0) instanceof TextNode && getNodes().get(1) instanceof TextNode)
			writer.prettyIndent(1, true);

		for (int i = 0; i < getNodes().size(); ++i) {
			// Pretty print text
			if (writer.isPp() && i > 0 && !writer.isEscape() && getNodes().get(i) instanceof TextNode && getNodes().get(i - 1) instanceof TextNode)
				writer.prettyIndent(1, false);

			getNodes().get(i).execute(writer, model, template);
			// Multiple text nodes are separated by newlines
			Node nextNode = null;
			if(i+1 < getNodes().size())
				nextNode = getNodes().get(i + 1);
			if (nextNode !=null && getNodes().get(i) instanceof TextNode && nextNode instanceof TextNode)
				writer.append("\n");
		}

	}

	public void setYield(boolean yield) {
		this.yield = yield;
	}

	public boolean isYield() {
		return yield;
	}

	public void setYieldBlock(BlockNode yieldBlock) {
		this.yieldBlock = yieldBlock;
	}

	public BlockNode getYieldBlock() {
		return yieldBlock;
	}

	public BlockNode getIncludeBlock() {
		BlockNode ret = this;
		for (Node node : getNodes()) {
			if (node instanceof BlockNode && ((BlockNode) node).isYield()) {
				return (BlockNode) node;
			}
			else if (node instanceof TagNode && ((TagNode) node).isTextOnly()) {
				continue;
			}
			else if (node instanceof BlockNode && ((BlockNode) node).getIncludeBlock() != null) {
				ret =  ((BlockNode) node).getIncludeBlock();
			}
			else if (node.hasBlock()) {
				ret =  ((BlockNode) node.getBlock()).getIncludeBlock();
			}
			if(ret instanceof BlockNode && ((BlockNode) ret).isYield()){
				return ret;
			}
		}
		return ret;
	}

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public Collection<? extends Node> getPrepended() {
		return prepended;
	}

	public void setPrepended(Collection<? extends Node> prepended) {
		this.prepended = prepended;
	}

	public Collection<? extends Node> getAppended() {
		return appended;
	}

	public void setAppended(Collection<? extends Node> appended) {
		this.appended = appended;
	}

	public void setParser(Parser parser) {
		this.parser = parser;
	}

	public Parser getParser() {
		return parser;
	}

	public void setSubBlock(boolean subBlock) {
		this.subBlock = subBlock;
	}

	public boolean isSubBlock() {
		return subBlock;
	}
}


text:
#pragma once

#include "Cpp/Fundamental.h"

namespace Intra { namespace Container {

template<typename T> class Array;
template<typename K, typename V> class LinearMap;
template<typename Char> class GenericString;
typedef GenericString<char> String;
typedef GenericString<wchar> WString;
typedef GenericString<dchar> DString;

}

using Container::Array;
using Container::LinearMap;
using Container::GenericString;
using Container::String;
using Container::WString;
using Container::DString;

}


text:
class AddFolderToSharedFiles < ActiveRecord::Migration
  def self.up
    add_column :shared_files, :folder, :string
    execute("UPDATE shared_files SET folder = 'main'")
  end

  def self.down
    remove_column :shared_files, :folder
  end
end


text:
require 'ww/dsl/definition_base'
require 'ww/double/mock/expectation'

module Ww
  module Dsl
    class MockDefinition < DefinitionBase
      def initialize(servlet, verification = nil, &block)
        super(servlet)
        @verification = block_given? ? block : verification
      end

      private
      def expectation_for(verb, path, options)
        Double::Mock::Expectation.new(verb, path, @verification)
      end

      def define_action(verb, path, options = {}, &action)
        expect = expectation_for(verb, path, options)
        servlet.expectations << expect
        action = unbound_action(servlet, expect.identifier, action)

        servlet.stub.send(verb, path, options) do |*args|
          expect.verify(request, self.class.testing_thread)

          action.bind(self).call(*args)
        end
      end
    end
  end
end


text:
using namespace std;

//add to glfwGetKey that gets the pressed key only once (not several times)
char keyOnce[GLFW_KEY_LAST + 1];
#define glfwGetKeyOnce(WINDOW, KEY)             \
    (glfwGetKey(WINDOW, KEY) ?              \
     (keyOnce[KEY] ? false : (keyOnce[KEY] = true)) :   \
     (keyOnce[KEY] = false))

TextureManager* texManager;

TessellatedQuad::TessellatedQuad(GLFWwindow* window, int size)
{
	this->size = size;
	this->window = window;
	planePos = vec3(0.0f, 0.0f, 1.0f);
}

void TessellatedQuad::init()
{
	genPlane();
	genBuffers();

	// init matrices
	modelMatrix = glm::mat4(1.0f);
	viewMatrix = glm::lookAt(
		vec3(0.0f, 0.0f, -1.0f), //eye
		vec3(0.0f, 0.0f, 0.0f), //center
		vec3(0.0f, 1.0f, 0.0f)); //up

	int w, h;
	glfwGetFramebufferSize(window, &w, &h);

	projectionMatrix = glm::perspective(glm::radians(75.0f), (float)w/(float)h, 0.1f, 100.0f);

	// load shaders
	try {
		shader.compileShader("shader/glsl40_tess_disp_mapp.vert", GLSLShader::VERTEX);
		shader.compileShader("shader/glsl40_tess_disp_mapp.tcs", GLSLShader::TESS_CONTROL);
		shader.compileShader("shader/glsl40_tess_disp_mapp.tes", GLSLShader::TESS_EVALUATION);
		shader.compileShader("shader/glsl40_tess_disp_mapp.frag", GLSLShader::FRAGMENT);

		shader.link();
		shader.use();
	}
	catch (GLSLProgramException &e) {
		cerr << e.what() << endl;
		system("pause");
		exit(EXIT_FAILURE);
	}
	shader.printActiveAttribs();

	// Get a TextureManager's instance
	texManager = TextureManager::Inst();

	// Load our color texture with Id 0
	glActiveTexture(GL_TEXTURE0);
	if (!texManager->LoadTexture("..\\..\\resources\\old_bricks_sharp_diff_COLOR.png", 0))
		cout << "Failed to load texture." << endl;

	// Load our displacement texture with Id 1
	glActiveTexture(GL_TEXTURE1);
	if (!texManager->LoadTexture("..\\..\\resources\\old_bricks_sharp_diff_DISP.png", 1))
		cout << "Failed to load texture." << endl;
}

void TessellatedQuad::update(double deltaTime)
{
	processInput();

	//// matrices setup
	modelMatrix = mat4(); // identity
	modelMatrix = glm::translate(modelMatrix, planePos); // translate back
	modelMatrix = glm::rotate(modelMatrix, glm::radians(rot), vec3(0.0f, 1.0f, 0.0f));

	modelViewMatrix = viewMatrix * modelMatrix;
	modelViewProjectionMatrix = projectionMatrix * modelViewMatrix;

	// set var MVP on the shader
	shader.setUniform("MVP", modelViewProjectionMatrix); //ModelViewProjection

	shader.setUniform("TessLevel", tessLevel);

	shader.setUniform("displacementmapSampler", 1);
	shader.setUniform("colorTextureSampler", 0);
}

void TessellatedQuad::processInput()
{
	// Tessellation Level
	if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
	{
		tessLevel++;
		if (tessLevel > 64)
			tessLevel = 64;
	}
	if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
	{
		tessLevel--;
		if (tessLevel < 1)
			tessLevel = 1;
	}

	// Rotation on Y axis
	if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
	{
		rot++;
		if (rot > 360)
			rot = 0;
	}
	if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
	{
		rot--;
		if (rot < 0)
			rot = 360;
	}

	// toggle wireframe
	if (glfwGetKeyOnce(window, 'E')) {
		wireframe = !wireframe;
		if (wireframe) {
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		}
		else {
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
		}
	}
}

void TessellatedQuad::render()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	//// Bind both textures
	//// Color
	glActiveTexture(GL_TEXTURE0);
	TextureManager::Inst()->BindTexture(0);
	//// Displacement
	glActiveTexture(GL_TEXTURE1);
	TextureManager::Inst()->BindTexture(1);

	glBindVertexArray(vaoID);
	glPatchParameteri(GL_PATCH_VERTICES, 4);
	glDrawElements(GL_PATCHES, indices.size(), GL_UNSIGNED_INT, (GLubyte *)NULL);
	glBindVertexArray(0);
}

void TessellatedQuad::genBuffers()
{
	glGenVertexArrays(1, &vaoID);
	glBindVertexArray(vaoID);

	unsigned int handle[3];
	glGenBuffers(3, handle);

	glBindBuffer(GL_ARRAY_BUFFER, handle[0]);
	glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), (GLvoid*)&vertices[0], GL_STATIC_DRAW);
	glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL);
	glEnableVertexAttribArray(0);  // VertexPosition -> layout 0 in the VS

	glBindBuffer(GL_ARRAY_BUFFER, handle[1]);
	glBufferData(GL_ARRAY_BUFFER, texcoord.size() * sizeof(vec2), (GLvoid*)&texcoord[0], GL_STATIC_DRAW);
	glVertexAttribPointer((GLuint)1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL);
	glEnableVertexAttribArray(1);  // TexCoord -> layout 1 in the VS

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle[2]);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(int), (GLvoid*)&indices[0], GL_STATIC_DRAW);

	glBindVertexArray(0);
}

void TessellatedQuad::resize(int x, int y)
{

}

void TessellatedQuad::genPlane()
{
	// v0 -- bottom left
	vertices.push_back(vec3(-size, -size, 0.0f));
	texcoord.push_back(vec2(0.0f, 0.0f));

	//v1 -- top left
	vertices.push_back(vec3(-size, size, 0.0f));
	texcoord.push_back(vec2(0.0f, 1.0f));

	//v2 -- top right
	vertices.push_back(vec3(size, size, 0.0f));
	texcoord.push_back(vec2(1.0f, 1.0f));

	////v3 -- bottom right
	vertices.push_back(vec3(size, -size, 0.0f));
	texcoord.push_back(vec2(1.0f, 0.0f));

	// Quad indices
	indices.push_back(0);
	indices.push_back(1);
	indices.push_back(2);
	indices.push_back(3);
}


text:
import path from 'node:path';
import * as managers from './background-managers/index.js';

let availableApps;

async function setAvailableApps() {
	availableApps = [];

	const promises = Object.values(managers).map(async manager => {
		if (await manager.isAvailable()) {
			availableApps.push(manager);
		}
	});

	await Promise.all(promises);
}

export async function getWallpaper() {
	if (!availableApps) {
		await setAvailableApps();
		return getWallpaper();
	}

	const wallpapersVoted = new Map();
	const promises = availableApps.map(async app => {
		if (typeof app.get !== 'function') {
			return;
		}

		const imagePath = await app.get();

		if (typeof imagePath !== 'undefined') {
			if (!wallpapersVoted.get(imagePath)) {
				wallpapersVoted.set(imagePath, 0);
			}

			wallpapersVoted.set(imagePath, wallpapersVoted.get(imagePath) + 1);
		}
	});

	await Promise.all(promises.map(promise => promise.catch(() => {})));

	let wallpaperMostVoted;
	let wallpaperMostVotedCount;

	for (const [wallpaper] of wallpapersVoted) {
		if (!wallpaperMostVoted || wallpaperMostVoted[wallpaper] > wallpaperMostVotedCount) {
			wallpaperMostVoted = wallpaper;
			wallpaperMostVotedCount = wallpaperMostVoted[wallpaper];
		}
	}

	return wallpaperMostVoted;
}

export async function setWallpaper(imagePath) {
	if (typeof imagePath !== 'string') {
		throw new TypeError('Expected a string');
	}

	if (!availableApps) {
		await setAvailableApps();
		await setWallpaper(imagePath);
		return;
	}

	const promises = availableApps.map(async app => {
		if (typeof app.set === 'function') {
			await app.set(path.resolve(imagePath));
		}
	});

	await Promise.allSettled(promises);
}


text:
import React from 'react';
import { Iterable } from 'immutable';

export default Component => props => {
  const KEY = 0;
  const VALUE = 1;

  const propsInJS = Object.entries(props).reduce(
    (newProps, prop) => ({
      ...newProps,
      [prop[KEY]]: Iterable.isIterable(prop[VALUE])
        ? prop[VALUE].toJS()
        : prop[VALUE],
    }),
    {},
  );

  return <Component {...propsInJS} />;
};