text:
package com.facebook.LinkBench.neo4j;

import com.facebook.LinkBench.*;
import com.facebook.LinkBench.Node;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.index.UniqueFactory;
import org.neo4j.helpers.collection.IteratorUtil;
import org.neo4j.kernel.EmbeddedGraphDatabase;

import java.io.IOException;
import java.util.*;

/**
 * @author mh
 * @since 04.04.13
 * remove visibility for invisible links
 */
public class Neo4jGraphStore extends GraphStore {
    private static final int BATCH_SIZE = 30000;
    GraphDatabaseService db;
    private Index<org.neo4j.graphdb.Node> nodeIndex;
    private UniqueFactory.UniqueNodeFactory uniqueNodeFactory;

    @Override
    public void initialize(Properties p, Phase currentPhase, int threadId) throws IOException, Exception {
        // ignore it if db already exists
        if (this.db!=null) return;
        final HashMap<String, String> config = new HashMap<String, String>();
        for (Map.Entry<Object, Object> entry : p.entrySet()) {
            config.put(entry.getKey().toString(), entry.getValue().toString());
        }
        this.db = new EmbeddedGraphDatabase(p.getProperty(Config.DBID), config);
        nodeIndex = db.index().forNodes("nodes");
        uniqueNodeFactory = new UniqueFactory.UniqueNodeFactory(nodeIndex) {
            @Override
            protected void initialize(org.neo4j.graphdb.Node created, Map<String, Object> properties) {
                created.setProperty("id", properties.get("id"));
            }
        };
    }

    public void resetNodeStore(String dbid, long startID) throws Exception {
    }

    public long addNode(String dbid, Node node) throws Exception {
        final Transaction tx = db.beginTx();
        try {
            final long result = doAddNode(node);
            tx.success();
            return result;
        } finally {
            tx.finish();
        }
    }

    private long doAddNode(Node node) {
        final org.neo4j.graphdb.Node neoNode = obtainNode(node.id);
        neoNode.setProperty("data", node.data);
        neoNode.setProperty("time", node.time);
        neoNode.setProperty("version", node.version);
        neoNode.setProperty("type", node.type); // todo label
        return node.id;
    }

    public Node getNode(String dbid, int type, long id) throws Exception {
        final org.neo4j.graphdb.Node neoNode = getNodeById(id);
        return new Node(neoNode.getId(),
                (Integer) neoNode.getProperty("type"),
                (Long) neoNode.getProperty("version"),
                (Integer) neoNode.getProperty("time"),
                (byte[]) neoNode.getProperty("data"));
    }

    private org.neo4j.graphdb.Node getNodeById(long id) {
        return nodeIndex.get("id",id).getSingle();
        // return db.getNodeById(id);
    }

    public boolean updateNode(String dbid, Node node) throws Exception {
        final Transaction tx = db.beginTx();
        try {
            final org.neo4j.graphdb.Node neoNode = getNodeById(node.id);
            neoNode.setProperty("data", node.data);
            neoNode.setProperty("time", node.time);
            neoNode.setProperty("version", node.version);
            neoNode.setProperty("type", node.type); // todo label
            tx.success();
            return true;
        } catch (NotFoundException nfe) {
            return false;
        } finally {
            tx.finish();
        }
    }

    public boolean deleteNode(String dbid, int type, long id) throws Exception {
        final Transaction tx = db.beginTx();
        try {
            final org.neo4j.graphdb.Node neoNode = getNodeById(id);
            if (neoNode==null) return false;
            for (Relationship relationship : neoNode.getRelationships()) {
                relationship.delete();
            }
            neoNode.delete();
            tx.success();
            return true;
        } catch (NotFoundException nfe) {
            tx.failure();
            return false;
        } finally {
            tx.finish();
        }
    }

    @Override
    public void close() {
        db.shutdown();
        db=null;
    }

    @Override
    public void clearErrors(int threadID) {

    }

    @Override
    public boolean addLink(String dbid, Link link, boolean noinverse) throws Exception {
        final Transaction tx = db.beginTx();
        try {
            final boolean result = doAddLink(link, noinverse);
            tx.success();
            return result;
        } catch (NotFoundException nfe) {
            tx.failure();
            return false;
        } finally {
            tx.finish();
        }
    }

    private org.neo4j.graphdb.Node obtainNode(long id) {
        return uniqueNodeFactory.getOrCreate("id", id);
    }

    private boolean doAddLink(Link link, boolean noinverse) {
        final long link_type = link.link_type;
        org.neo4j.graphdb.Node start = obtainNode(link.id1);
        org.neo4j.graphdb.Node end = obtainNode(link.id2);
        Relationship rel = findLink(link.id1, link.link_type, link.id2);
        if (rel == null) {
            rel = start.createRelationshipTo(end, relType(link_type));
            updateRel(rel, link, noinverse);
            return true;
        } else {
            updateRel(rel, link, noinverse);
            return false;
        }
    }

    private void updateRel(Relationship rel, Link link, boolean noinverse) {
        rel.setProperty("data", link.data);
        rel.setProperty("time", link.time);
        rel.setProperty("version", link.version);
        rel.setProperty("visibility", link.visibility);
        rel.setProperty("noinverse", noinverse);
    }

    // todo cache
    private DynamicRelationshipType relType(long link_type) {
        return DynamicRelationshipType.withName(String.valueOf(link_type));
    }

    private Relationship findLink(long id1, long link_type, long id2) {
        final org.neo4j.graphdb.Node start = getNodeById(id1);
        final org.neo4j.graphdb.Node end = getNodeById(id2);
        if (start==null || end==null) return null;
        for (Relationship rel : start.getRelationships(relType(link_type))) {
            if (rel.getOtherNode(start).equals(end)) {
                return rel;
            }
        }
        return null;
    }

    @Override
    public boolean deleteLink(String dbid, long id1, long link_type, long id2, boolean noinverse, boolean expunge) throws Exception {
        final Transaction tx = db.beginTx();
        try {
            final org.neo4j.graphdb.Node start = getNodeById(id1);
            final org.neo4j.graphdb.Node end = getNodeById(id2);
            if (start==null || end==null) return false;
            for (Relationship rel : start.getRelationships(relType(link_type))) {
                if (rel.getOtherNode(start).equals(end)) {
                    if (expunge) rel.delete();
                    else rel.removeProperty("visibility");
                    tx.success();
                    return true;
                }
            }
            return false;
        } catch (NotFoundException nfe) {
            tx.failure();
            return false;
        } finally {
            tx.finish();
        }
    }

    @Override
    public boolean updateLink(String dbid, Link a, boolean noinverse) throws Exception {
        final Transaction tx = db.beginTx();
        try {
            final Relationship rel = findLink(a.id1, a.link_type, a.id2);
            if (rel == null) return false;
            updateRel(rel, a, noinverse);
            tx.success();
            return true;
        } finally {
            tx.finish();
        }
    }

    @Override
    public Link getLink(String dbid, long id1, long link_type, long id2) throws Exception {
        final Relationship rel = findLink(id1, link_type, id2);
        if (rel==null) return null;
        return createLink(id1, link_type, id2, rel);
    }

    private Link createLink(long id1, long link_type, long id2, Relationship rel) {
        return new Link(id1, link_type, id2, (Byte) rel.getProperty("visibility", (byte)0), (byte[]) rel.getProperty("data"), (Integer) rel.getProperty("version",0), (Long) rel.getProperty("time",0));
    }

    @Override
    public Link[] getLinkList(String dbid, long id1, long link_type) throws Exception {
        try {
            List<Link> links = new ArrayList<Link>(100);
            final org.neo4j.graphdb.Node start = getNodeById(id1);
            if (start==null) return null;
            for (Relationship rel : start.getRelationships(relType(link_type), Direction.OUTGOING)) {
                if (!isVisible(rel)) continue;
                links.add(createLink(id1, link_type, (Long)rel.getOtherNode(start).getProperty("id"), rel));
            }
            return toSortedLinkArray(links);
        } catch (NotFoundException nfe) {
            return null;
        }
    }

    @Override
    public Link[] getLinkList(String dbid, long id1, long link_type, long minTimestamp, long maxTimestamp, int offset, int limit) throws Exception {
        try {
            List<Link> links = new ArrayList<Link>(100);
            final org.neo4j.graphdb.Node start = getNodeById(id1);
            for (Relationship rel : start.getRelationships(relType(link_type), Direction.OUTGOING)) {
                long time = (Long) rel.getProperty("time");
                if (time < minTimestamp || time > maxTimestamp || !isVisible(rel)) continue;
                links.add(createLink(id1, link_type, (Long) rel.getEndNode().getProperty("id"), rel));
            }
            return toLimitedSortedLinkArray(links, offset, limit);
        } catch (NotFoundException nfe) {
            return null;
        }
    }

    private Link[] toLimitedSortedLinkArray(List<Link> links, int offset, int limit) {
        if (links.isEmpty()) return null;
        Collections.sort(links, new LinkComparator());
        links = links.subList(offset, Math.min(offset + limit,links.size()));
        return links.toArray(new Link[links.size()]);
    }

    private Link[] toSortedLinkArray(List<Link> links) {
        if (links.isEmpty()) return null;
        final Link[] result = links.toArray(new Link[links.size()]);
        Arrays.sort(result, new LinkComparator());
        return result;
    }

    @Override
    public long countLinks(String dbid, long id1, long link_type) throws Exception {
        try {
            final org.neo4j.graphdb.Node node = getNodeById(id1);
            if (node==null) return -1;
            int count = 0;
            for (Relationship rel : node.getRelationships(relType(link_type),Direction.OUTGOING)) {
                if (isVisible(rel)) count++;
            }
            return count;
        } catch(NotFoundException nfe) {
            return -1;
        }
    }

    private boolean isVisible(Relationship rel) {
        return (Byte)rel.getProperty("visibility",(byte)0)!=0;
    }

    @Override
    public long[] bulkAddNodes(String dbid, List<Node> nodes) throws Exception {
        final Transaction tx = db.beginTx();
        try {
            long ids[] = new long[nodes.size()];
            int i = 0;
            for (Node node : nodes) {
                long id = doAddNode(node);
                ids[i++] = id;
            }
            tx.success();
            return ids;
        } finally {
            tx.finish();
        }
    }

    @Override
    public void addBulkLinks(String dbid, List<Link> a, boolean noinverse) throws Exception {
        final Transaction tx = db.beginTx();
        try {
            for (Link link : a) {
                doAddLink(link, noinverse);
            }
            tx.success();
        } finally {
            tx.finish();
        }
    }

    @Override
    public void addBulkCounts(String dbid, List<LinkCount> a) throws Exception {
        // don't know what to do with this super.addBulkCounts(dbid, a);
    }

    @Override
    public int bulkLoadBatchSize() {
        return BATCH_SIZE;
    }

    private static class LinkComparator implements Comparator<Link> {
        public int compare(Link o1, Link o2) {
            return o1.time > o2.time ? -1 : 1;
        }
    }
}


text:
package archive

import (
	"reflect"

	"github.com/sacloud/iaas-service-go/archive"
	"github.com/sacloud/usacloud/pkg/commands/iaas/category"
	"github.com/sacloud/usacloud/pkg/core"
)

var Resource = &core.Resource{
	PlatformName: "iaas",
	Name:         "archive",
	ServiceType:  reflect.TypeOf(&archive.Service{}),
	Category:     category.ResourceCategoryStorage,
}

redpajama_set_name: RedPajamaGithub


text:
import sys, os, csv
import itertools
import numpy as np
import scipy.stats as ss
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import gc

try:
    import grass.script as grass
    import grass.script.array as garray
except:
    pass

#----------------------------------------------------
def rm_mask(kind='cell'):
    ''' removes any existing mask, defaults to raster '''
    exists = bool(grass.find_file('MASK', element=kind)['file'])
    if exists:
        grass.run_command('r.mask', flags='r')

#----------------------------------------------------
def raster_as_1d_array(raster):
    ''' return GRASS raster as numpy array - keep null values '''
    print ('----------   raster_as_1d_array   ----------')
    print (raster)
    grass.run_command('g.region', raster=raster, flags='pa')
    raster_array = garray.array()
    raster_array.read(raster, null=np.nan)
    print ('----------  raster_as_1d_array OK ----------')
    return raster_array.flatten(order='C')

#----------------------------------------------------
def round5(x):
    ''' round to nearest 5 '''
    rounded = int(round(x/5.0)*5.0)
    return rounded

#----------------------------------------------------
def round_arb(x,y):
    ''' round to nearest (arbitrary) value '''
    rounded = int(round(x/float(y))*float(y))
    return rounded

#----------------------------------------------------
def rmse(predictions, targets):
    ''' calculate RMSE from 2 values or lists or arrays '''
    return np.sqrt(((predictions - targets) ** 2).mean())

def calc_stats(raster):
    ''' get stats from a list of values
    (min, max, range, mean, median, stddev, p25, p75, skew, kurt)
    removes NaNs from array'''
    print ('----------   calc_stats   ----------')
    rast = raster[~np.isnan(raster)]
    rast_max = np.max(rast).item()
    rast_min = np.min(rast).item()
    rast_range = rast_max - rast_min
    rast_mean = np.mean(rast).item()
    rast_median = np.median(rast).item()
    rast_stddev = np.std(rast).item()
    rast_p25 = np.percentile(rast, 25)
    rast_p75 = np.percentile(rast, 75)
    rast_skew = ss.skew(rast)
    rast_kurt = ss.kurtosis(rast)
    print ('---------- calc_stats OK  ----------')
    return [rast_min,rast_max,rast_range,rast_mean,rast_median,rast_stddev,rast_skew,rast_kurt,rast_p25,rast_p75]

#----------------------------------------------------
# calculates a histogram for each DEM tile and saves it to an svg file
# uses matplotlib histogram
def do_histogram_np(dem_list,bin_width,x_lim,density_plot):
    ''' calculates histogram on DEM tiles '''
    area_name = dem_list[0].split('_')[1]
    fileOutName = area_name + '_histogram.pdf' # output file
    sns.set_palette(sns.color_palette("Set1", n_colors=len(dem_list)+2, desat=.5))
        # get data for each dem
    for dem in dem_list:
        dem_1d = raster_as_1d_array(dem)
        elev = dem_1d[~np.isnan(dem_1d)]
        # define bins
        g_max = int(np.ceil(np.max(elev)))
        g_min = int(np.min(elev))
        nbins = round5((g_max - g_min)/bin_width)
        # plot histogram
        # plt.hist(elev, bins=nbins, normed=density_plot, histtype='step', label=dem)
        hist, edges = np.histogram(elev, bins=nbins, density=density_plot)
        plt.plot(edges[:-1], hist, label=dem)
    # plot decorations
    plt.title(area_name + ' (bin width = ' + str(bin_width) +'m)')
    plt.xlabel('Elevation')
    if density_plot == True:
        plt.ylabel('Normalized probability density function')
    else:
        plt.ylabel('Cell count')
    plt.xlim(x_lim)
    plt.legend()
    plt.tight_layout()
    plt.savefig(fileOutName)
    print 'histogram OK'
    # plt.show()
    plt.clf()
    plt.cla()

#----------------------------------------------------
# calculates a histogram for each DEM tile and saves it to an svg file
# uses matplotlib histogram
# uses min-max as limits, one dem per run (does not accept lists of dems)
def do_histogram_full(dem,bin_width):
    ''' calculates histogram on DEM tiles '''
    area_name = dem.split('_')[-1]
    fileOutName = area_name + '_histogram_full_srtm.pdf' # output file
    dem_1d = raster_as_1d_array(dem)
    elev = dem_1d[~np.isnan(dem_1d)]
    # define bins
    g_max = int(np.ceil(np.max(elev)))
    g_min = int(np.min(elev))
    nbins = round5((g_max - g_min)/bin_width)
    hist, edges = np.histogram(elev, bins=nbins, density=True)
    plt.plot(edges[:-1], hist, label=dem)
    # plot decorations
    plt.title(area_name + ' (bin width = ' + str(bin_width) +'m)')
    plt.xlabel('Elevation')
    plt.ylabel('Normalized probability density function')
    plt.xlim((g_min,g_max))
    plt.legend()
    plt.tight_layout()
    plt.savefig(fileOutName)
    print 'histogram OK'
    # plt.show()
    plt.clf()
    plt.cla()

#----------------------------------------------------
# calculates histograms for slope
def do_histogram_slope(dem_list,bin_width,x_lim,density_plot,n_colors):
    ''' calculates histogram on DEM tiles '''
    area_name = dem_list[0].split('_')[1]
    fileOutName = area_name + '_histogram_slope.pdf' # output file
    for dem in dem_list:
        slope_rast = dem + '_slope'
        slope_1d = raster_as_1d_array(slope_rast)
        slope = slope_1d[~np.isnan(slope_1d)]
        sns.set_palette(sns.color_palette("Set1", n_colors=n_colors, desat=.5))
        # slope = slope[~np.isnan(slope)]
        # define bins
        g_max = int(np.ceil(np.max(slope)))
        g_min = int(np.min(slope))
        nbins = round5((g_max - g_min)/bin_width)
        # plot histogram
        # plt.hist(slope, bins=nbins, normed=density_plot, histtype='step', label=dem)
        hist, edges = np.histogram(slope, bins=nbins, density=density_plot)
        plt.plot(edges[:-1], hist, label=slope_rast)
    # plot decorations
    plt.title(area_name + ' slope (bin width = ' + str(bin_width) +'m)')
    plt.xlabel('Slope (degrees)')
    if density_plot == True:
        plt.ylabel('Normalized probability density function')
    else:
        plt.ylabel('Cell count')
    plt.xlim(x_lim)
    plt.legend()
    plt.tight_layout()
    plt.savefig(fileOutName)
    print 'histogram OK'
    # plt.show()
    plt.clf()
    plt.cla()

#----------------------------------------------------
# plot mean_slope per elevation
def mean_slope_elev(area_list,elev_interval,ymin,ymax):
    ''' plot of mean slope per elevation interval'''
    area_name = area_list[0].split('_')[-1]
    file_svg = area_name + '_mean_slope_elev.pdf'
    sns.set_palette(sns.color_palette("muted", n_colors=len(area_list), desat=.5))
    for dem in area_list:
        # read raster data and put that into a DataFrame
        slope_rast = dem + '_slope'
        df = pd.DataFrame()
        df['elev'] = raster_as_1d_array(dem)
        df['slope'] = raster_as_1d_array(slope_rast)
        # bins
        zmin = int(round(df['elev'].min()/elev_interval)*elev_interval)
        zmax = int(round(df['elev'].max()/elev_interval)*elev_interval)
        bins = range(zmin,zmax+1,int(elev_interval))
        # aggregate slope into breaks
        df['cut'] = pd.cut(df['elev'], bins=bins)
        pvt = pd.pivot_table(df, columns='cut', values='slope', aggfunc=np.mean)
        # plot
        x = pvt.values[0]
        y = [l.mid for l in list(pvt)]
        print('x = %s, y = %s' %(len(x),len(y)))
        plt.plot(x,y, label=dem)
        df = None
    # plot decorations
    plt.title(area_name + ' - mean slope x elevation ')
    plt.xlabel('Mean slope - interval:' + str(elev_interval) + ' m')
    plt.ylabel('Elevation')
    plt.ylim(ymin, ymax)
    plt.xlim(0,90)
    plt.legend()
    plt.tight_layout()
    plt.savefig(file_svg)
    print 'plot OK'
    plt.clf()
    plt.cla()

#----------------------------------------------------
# error metrics
# error metrics are just a copy from:
# http://www.statsmodels.org/dev/_modules/statsmodels/tools/eval_measures.html
# except mean error, that was adapted from mean squared error
def err_me(x1, x2, axis=0):
    """mean error"""
    x1 = np.asanyarray(x1)
    x2 = np.asanyarray(x2)
    return np.mean((x1-x2), axis=axis)

def err_mse(x1, x2, axis=0):
    """mean squared error"""
    x1 = np.asanyarray(x1)
    x2 = np.asanyarray(x2)
    return np.mean((x1-x2)**2, axis=axis)

def err_rmse(x1, x2, axis=0):
    """root mean squared error"""
    x1 = np.asanyarray(x1)
    x2 = np.asanyarray(x2)
    return np.sqrt(err_mse(x1, x2, axis=axis))

def err_mae(x1, x2, axis=0):
    """mean absolute error"""
    x1 = np.asanyarray(x1)
    x2 = np.asanyarray(x2)
    return np.mean(np.abs(x1-x2), axis=axis)

def err_std(x1, x2, axis=0):
    """standard deviation of error"""
    x1 = np.asanyarray(x1)
    x2 = np.asanyarray(x2)
    return np.std(x1-x2, axis=axis)

def err_min(x1, x2, axis=0):
    """mean error"""
    x1 = np.asanyarray(x1)
    x2 = np.asanyarray(x2)
    return np.min((x1-x2), axis=axis)

def err_max(x1, x2, axis=0):
    """mean error"""
    x1 = np.asanyarray(x1)
    x2 = np.asanyarray(x2)
    return np.max((x1-x2), axis=axis)

#----------------------------------------------------
# calculate error metric (rmse, mae, me, std)
def calc_error_metrics(areas):
    ''' error metrics (rmse, mae, me, std) between two raster maps'''
    area_list = []
    dem_list = []
    rmse_list = []
    me_list = []
    std_list = []
    le90_list = []
    le95_list = []
    le99_list = []
    min_list = []
    max_list = []
    for area in areas:
        area_name = area[0].split('_')[-1]
        suffix = area_name + '_12m_bicubic'
        df = pd.DataFrame()
        for dem in area:
            if dem.startswith('tdx12'):
                df[dem] = raster_as_1d_array(dem)
            else:
                dem = dem + '_12m_bicubic'
                df[dem] = raster_as_1d_array(dem)
            print(dem + ' added to DataFrame')
        dfna = df.dropna(axis=0, how='any')
        for column in ['tdx30_'+suffix,'srtm30_wgs84_'+suffix,'aster30_wgs84_'+suffix,'aw3d30_wgs84_'+suffix]:
            # calculate errors
            rmse = err_rmse(dfna['tdx12_'+area_name],dfna[column])
            me = err_me(dfna['tdx12_'+area_name],dfna[column])
            std = err_std(dfna['tdx12_'+area_name],dfna[column])
            le90 = 1.6449 * std
            le95 = 1.9600 * std
            le99 = 3.0000 * std
            min_err = err_min(dfna['tdx12_'+area_name],dfna[column])
            max_err = err_max(dfna['tdx12_'+area_name],dfna[column])
            # append data to lists
            rmse_list.append(rmse)
            me_list.append(me)
            std_list.append(std)
            le90_list.append(le90)
            le95_list.append(le95)
            le99_list.append(le99)
            dem_list.append(column)
            area_list.append(area_name)
            min_list.append(min_err)
            max_list.append(max_err)
        # clean memory
        df = None
        dfna = None
        print('\n\n')
    return rmse_list, me_list, std_list, le90_list, le95_list, le99_list, dem_list, area_list, min_list, max_list

#----------------------------------------------------
# calculates a histogram for each DEM tile and saves it to an svg file
# uses matplotlib histogram
def do_histogram_dod(dem_list,bin_width,density_plot):
    ''' calculates histogram on DEM tiles '''
    area_name = dem_list[0].split('_')[1]
    fileOutName = area_name + '_histograms_DoD.pdf' # output file
    sns.set_palette(sns.color_palette("Set1", n_colors=len(dem_list)+2, desat=.5))
        # get data for each dem
    for dem in dem_list:
        dem_1d = raster_as_1d_array(dem)
        elev = dem_1d[~np.isnan(dem_1d)]
        # define bins
        g_max = int(np.ceil(np.max(elev)))
        g_min = int(np.min(elev))
        nbins = round(g_max - g_min)
        # plot histogram
        # plt.hist(elev, bins=nbins, normed=density_plot, histtype='step', label=dem)
        hist, edges = np.histogram(elev, bins=nbins, density=density_plot)
        plt.plot(edges[:-1], hist, label=dem)
    # plot decorations
    plt.title(area_name + ' (bin width = ' + str(bin_width) +'m)')
    plt.xlabel('Difference in Elevation from TanDEM-X 12m')
    if density_plot == True:
        plt.ylabel('Normalized probability density function')
    else:
        plt.ylabel('Cell count')
    plt.legend()
    plt.tight_layout()
    plt.savefig(fileOutName)
    print 'histogram OK'
    # plt.show()
    plt.clf()
    plt.cla()

#----------------------------------------------------
# scatter plots of original elevations
def do_scatter_elev(elev1,elev2,file_out,area_name,dem_name):
    ''' scatter plots of original elevations '''
    elev_x = raster_as_1d_array(elev1)
    elev_y = raster_as_1d_array(elev2)
    plt.plot(elev_x,elev_y,'+')
    plt.title(area_name + ' - TDX 12m x ' + dem_name)
    plt.xlabel('TDX 12m elevation')
    plt.ylabel(dem_name + ' elevation')
    xmin = plt.gca().get_xlim()[0]
    xmax = plt.gca().get_xlim()[1]
    plt.plot((xmin,xmax),(xmin,xmax))
    # plt.ylim(xmin,xmax)
    # plt.xlim(xmin,xmax)
    # plt.legend()
    plt.tight_layout()
    plt.savefig(file_out)
    print 'scatterplot OK'
    # plt.show()
    plt.clf()
    plt.cla()

#----------------------------------------------------
# scatter plots of aspect x DoD
def do_scatter_aspect(asp_name,dod_name,file_out):
    ''' scatter plots of original elevations '''
    elev_x = raster_as_1d_array(asp_name)
    elev_y = raster_as_1d_array(dod_name)
    fig = plt.figure(figsize=(10,6))
    plt.plot(elev_x,elev_y,'+',color='k',alpha=.2,ms=2)
    plt.title('DoD x aspect')
    plt.xlabel(asp_name)
    plt.ylabel(dod_name)
    plt.xlim(-20,380)
    plt.ylim(-100,100)
    plt.savefig(file_out, dpi=(600))
    print 'scatterplot OK'
    # plt.show()
    plt.clf()
    plt.cla()
    plt.close(fig)

# scatter plots of aspect x DoD with reunning mean
# unused, left here as reference and example
# def do_scatter_aspect_mean(asp_name,dod_name,file_out):
#     ''' scatter plots of original elevations '''
#     # elev_x = raster_as_1d_array(asp_name)
#     # elev_y = raster_as_1d_array(dod_name)
#     bins = np.arange(0,361,5)
#     df = pd.DataFrame({'X':raster_as_1d_array(asp_name), 'Y':raster_as_1d_array(dod_name)})
#     data_cut = pd.cut(df.X,bins)
#     grp = df.groupby(by=data_cut)
#     ret = grp.aggregate(np.median)
#     plt.figure(figsize=(10,7.5))
#     plt.plot(df.X,df.Y,'+',color='k',alpha=.2,ms=2)
#     plt.plot(ret.X,ret.Y,'r-',lw=2,alpha=.8)
#     # plt.plot(elev_x,elev_y,'+')
#     plt.title('DoD x aspect')
#     plt.xlabel(asp_name)
#     plt.ylabel(dod_name)
#     plt.xlim(0,360)
#     plt.ylim(-300,300)
#     plt.savefig(file_out)
#     print 'scatterplot OK'
#     # plt.show()
#     plt.clf()
#     plt.cla()

#----------------------------------------------------
#  make a png of a diff map and plot topo profile
def make_diff_map_png(dem,area,n,s,w,e,shade_map,grid_size,suffix):
    ''' make a png of a diff map and plot topo profile
    tdx: 'tdx12' or 'tdx30'
    area: name of study area (as in 'Barcelos')
    n,s,w,e: limits of GRASS region
    shade_map: boolean
    grid_size: interval of grid on output map
    suffix: so we can have outputs name differently
    '''
    diff_map = 'tdx12_diff_'+dem+'_wgs84_'+area
    diff_map_inset = diff_map+'_inset'+suffix
    shade = 'tdx12_'+area+'_shade_315_20'
    grass.run_command('g.region', raster=diff_map, flags='a')
    grass.run_command('g.region', n=n, s=s, w=w, e=e)
    # make new map (for new color table)
    print('clipping with r.mapcalc...')
    grass.mapcalc("${out} = ${orig}",
        out=diff_map_inset,
        orig=diff_map,
        overwrite = True)
    # export map as png
    if shade_map==True:
        grass.run_command('d.mon', start='cairo', output=diff_map_inset+'_shade.png', resolution='3', height=500, width=500, overwrite=True)
        grass.run_command('d.shade', shade=shade, color=diff_map)
    else:
        grass.run_command('d.mon', start='cairo', output=diff_map_inset+'.png', resolution='3', height=500, width=500, overwrite=True)
        grass.run_command('d.rast', map=diff_map_inset)
    grass.run_command('d.grid', size=grid_size, text_color='black', flags='c')
    grass.run_command('d.legend', raster=diff_map_inset, flags='tsbd', at='4,25,92,94', font='Helvetica', fontsize=12, bgcolor='240:240:240')
    grass.run_command('d.mon', stop='cairo')
    print('export as png OK')
    # export simple PNG + world file
    grass.run_command('r.out.png',input=diff_map_inset, output=diff_map_inset+'_wld.png', flags='w', overwrite=True)

def make_diff_profile(area,n,s,w,e,coords,fig_aspect):
    df_tdx = None
    df_srtm = None
    grass.run_command('g.region', n=n, s=s, w=w, e=e, res='0:0:01')
    # make profile
    csv_file_tdx = 'tdx12_'+area+'_profile.csv'
    csv_file_srtm = 'srtm30_'+area+'_profile.csv'
    grass.run_command('r.profile', input='tdx12_'+area, output=csv_file_tdx, coordinates=coords, overwrite=True)
    grass.run_command('r.profile', input='srtm30_wgs84_'+area, output=csv_file_srtm, coordinates=coords, overwrite=True)
    # read csv and plot profile
    df_tdx = pd.read_csv(work_dir + csv_file_tdx, sep=' ', header=None, names=['nan','dist','elev'],na_values='*')
    df_srtm = pd.read_csv(work_dir + csv_file_srtm, sep=' ', header=None, names=['nan','dist','elev'],na_values='*')
    file_svg = area + '_diff_profile.pdf'
    plt.plot(df_tdx['dist'],df_tdx['elev'],'k-',label='TanDEM-X 12m')
    plt.plot(df_srtm['dist'],df_srtm['elev'],'b-',label='SRTM 30m')
    xmax = round_arb(df_tdx['dist'].max(),500)
    plt.xlim(0,xmax)
    plt.axes().set_aspect(fig_aspect)
    plt.title('Topographic profiles - ' + area)
    plt.xlabel('Distance along profile')
    plt.ylabel('Elevation')
    plt.legend()
    # plt.show()
    # plt.tight_layout()
    plt.savefig(file_svg, format='pdf', bbox_inches = 'tight')
    plt.clf()
    plt.cla()
    print('export plot as PDF OK')

#----------------------------------------------------
# make contours only in a small area
def make_zoom_contour(area_name,cont_param,n,s,w,e):
    ''' make contours only in a small area'''
    dems = ['aster30_wgs84_','aw3d30_wgs84_','srtm30_wgs84_','tdx30_','tdx12_']
    for dem in dems:
        dem_in = dem + area_name
        grass.run_command('g.region',raster=dem_in, flags='pa')
        dem_zoom = dem_in + '_zoom'
        print('clipping with r.mapcalc...')
        grass.run_command('g.region',n=n,s=s,w=w,e=e, flags='pa')
        grass.mapcalc("${out} = ${orig}",
            out=dem_zoom,
            orig=dem_in,
            overwrite = True)
        vect_contour = dem + area_name + '_contours_zoom'
        interval = cont_param[0]
        min_c = cont_param[1]
        max_c = cont_param[2]
        grass.run_command('r.contour', input=dem_zoom, output=vect_contour, \
            step=interval, minlevel=min_c, maxlevel=max_c, overwrite=True)

# export PNGs of contours with shaded relief
def make_shade_contour(n,s,w,e,tc,gc):
    ''' make pngs of shaded relief maps overlaid by vector contours'''
    dems = ['aster30_wgs84_','aw3d30_wgs84_','srtm30_wgs84_','tdx30_','tdx12_']
    for dem in dems:
        out_shade = dem + area_name + '_shade_315_20'
        vect_contour = dem + area_name + '_contours_zoom'
        grass.run_command('g.region',n=n,s=s,w=w,e=e, flags='pa')
        grass.run_command('d.mon', start='cairo', output=dem+area_name+'_shade_contours.png', \
            resolution='3', height=500, width=500, overwrite=True)
        grass.run_command('d.rast', map=out_shade)
        grass.run_command('d.vect', map=vect_contour, type='line')
        grass.run_command('d.grid', size='0.025', text_color=tc, color=gc, fontsize=16, flags='c')
        grass.run_command('d.mon', stop='cairo')

# export PNGs of colored shaded relief (tdx12)
def make_shadecolor_zoom(area_name,n,s,w,e,tc,gc):
    ''' export PNGs of colored shaded relief (tdx12)'''
    dem = 'tdx12_' + area_name + '_zoom'
    dem_shade = 'tdx12_' + area_name + '_shade_315_20'
    grass.run_command('g.region',n=n,s=s,w=w,e=e, res='0:0:00.4', flags='pa')
    grass.run_command('d.mon', start='cairo', output=dem+area_name+'_colorshade.png', \
        resolution='3', height=500, width=500, overwrite=True)
    grass.run_command('d.shade', shade=dem_shade, color=dem)
    grass.run_command('d.grid', size='0.025', text_color=tc, color=gc, fontsize=16, flags='c')
    grass.run_command('d.legend', raster=dem, flags='sb', at='4,25,2,4', font='Helvetica', \
        fontsize=13, bgcolor='240:240:240', title='(m)')
    grass.run_command('d.mon', stop='cairo')

# export PNGs of colored shaded relief (tdx12)
def make_shade_slope_zoom(area_name,n,s,w,e,tc,gc):
    ''' export PNGs of colored shaded relief (tdx12)'''
    dem = 'tdx12_' + area_name
    dem_shade = 'tdx12_' + area_name + '_shade_315_20'
    dem_slope = 'tdx12_' + area_name + '_slope'
    grass.run_command('g.region',n=n,s=s,w=w,e=e, res='0:0:00.4', flags='pa')
    grass.run_command('d.mon', start='cairo', output=dem+'_shade_slope.png', \
        resolution='3', height=500, width=500, overwrite=True)
    grass.run_command('d.rast', map=dem_shade)
    grass.run_command('d.rast', map=dem_slope, values='15-90')
    grass.run_command('d.grid', size='0.025', text_color=tc, color=gc, fontsize=16, flags='c')
    grass.run_command('d.legend', raster=dem_slope, flags='sb', at='4,25,2,4', font='Helvetica', \
        fontsize=13, bgcolor='240:240:240', title='(m)', range=(15,90))
    grass.run_command('d.mon', stop='cairo')

# export PNGs of shaded relief overlaid by WAM mask
def make_shade_wam(area_name,tc,gc):
    ''' export PNGs of colored shaded relief (tdx12)'''
    dem = 'tdx12_' + area_name
    dem_shade = 'tdx12_' + area_name + '_shade_315_20'
    dem_wam = 'tdx12_wam_' + area_name + '_cats'
    grass.run_command('g.region', raster=dem, flags='pa')
    grass.run_command('d.mon', start='cairo', output=dem+'_wam_colorcats.png', \
        resolution='3', height=600, width=600, overwrite=True)
    # grass.run_command('d.shade', shade=dem_shade, color=dem_wam)
    grass.run_command('d.rast', map=dem_shade)
    grass.run_command('d.rast', map=dem_wam)
    grass.run_command('d.grid', size='0.25', text_color=tc, color=gc, fontsize=24, flags='c')
    grass.run_command('d.mon', stop='cairo')


text: curl -k https://api.github.com/repos/dzhariy/swd-recorder/releases


text:
require 'helper'
require 'media/command/converter'

module Media
  module Command
    class TestConverter < MiniTest::Unit::TestCase

      def subject(args={})
        @subject ||= Converter.new(args.merge(subshell: subshell))
      end

      def subshell
        @subshell ||= MiniTest::Mock.new
      end

      def after
        subshell.verify
      end

      def test_empty_call
        stub = Class.new do
          def success?; true; end
        end

        subshell.expect(:new, subshell, [cmd: ['ffmpeg', '-v', 'info']])
        subshell.expect(:call, stub.new)

        subject.call
      end

      def test_with_options
        assert_equal ['ffmpeg', '-v', 'info', 'option'], subject(options: [['option']]).to_a
      end

      def test_call_with_inputs
        assert_equal ['ffmpeg', '-v', 'info', 'input'], subject(inputs: [['input']]).to_a
      end

      def test_call_with_outputs
        assert_equal ['ffmpeg', '-v', 'info', 'output'], subject(outputs: [['output']]).to_a
      end

      def test_call_with_all
        assert_equal ['ffmpeg', '-v', 'info', 'option', 'input', 'output'],
          subject(options: [['option']], inputs: [['input']], outputs: [['output']]).to_a
      end
    end
  end
end


text:
// -*- C++ -*-
// $Id: event_skel_export.h 14 2007-02-01 15:49:12Z mitza $
// Definition for Win32 Export directives.
// This file is generated automatically by generate_export_file.pl
// ------------------------------
#ifndef TAO_EVENT_SKEL_EXPORT_H
#define TAO_EVENT_SKEL_EXPORT_H

#include "ace/config-all.h"

#if defined (TAO_AS_STATIC_LIBS)
#  if !defined (TAO_EVENT_SKEL_HAS_DLL)
#    define TAO_EVENT_SKEL_HAS_DLL 0
#  endif /* ! TAO_EVENT_SKEL_HAS_DLL */
#else
#  if !defined (TAO_EVENT_SKEL_HAS_DLL)
#    define TAO_EVENT_SKEL_HAS_DLL 1
#  endif /* ! TAO_EVENT_SKEL_HAS_DLL */
#endif

#if defined (TAO_EVENT_SKEL_HAS_DLL) && (TAO_EVENT_SKEL_HAS_DLL == 1)
#  if defined (TAO_EVENT_SKEL_BUILD_DLL)
#    define TAO_Event_Skel_Export ACE_Proper_Export_Flag
#    define TAO_EVENT_SKEL_SINGLETON_DECLARATION(T) ACE_EXPORT_SINGLETON_DECLARATION (T)
#    define TAO_EVENT_SKEL_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
#  else /* TAO_EVENT_SKEL_BUILD_DLL */
#    define TAO_Event_Skel_Export ACE_Proper_Import_Flag
#    define TAO_EVENT_SKEL_SINGLETON_DECLARATION(T) ACE_IMPORT_SINGLETON_DECLARATION (T)
#    define TAO_EVENT_SKEL_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
#  endif /* TAO_EVENT_SKEL_BUILD_DLL */
#else /* TAO_EVENT_SKEL_HAS_DLL == 1 */
#  define TAO_Event_Skel_Export
#  define TAO_EVENT_SKEL_SINGLETON_DECLARATION(T)
#  define TAO_EVENT_SKEL_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
#endif /* TAO_EVENT_SKEL_HAS_DLL == 1 */

#endif /* TAO_EVENT_SKEL_EXPORT_H */

// End of auto generated file.


text:
require 'spec_helper'

describe GraphQL::Schema::TypeReducer do
  it 'finds types from a single type and its fields' do
    reducer = GraphQL::Schema::TypeReducer.new(CheeseType, {})
    expected = {
      "Cheese" => CheeseType,
      "Int" => GraphQL::INT_TYPE,
      "String" => GraphQL::STRING_TYPE,
      "DairyAnimal" => DairyAnimalEnum,
      "Float" => GraphQL::FLOAT_TYPE,
      "Edible" => EdibleInterface,
      "Milk" => MilkType,
      "AnimalProduct" => AnimalProductInterface,
    }
    assert_equal(expected.keys, reducer.result.keys)
    assert_equal(expected, reducer.result)
  end

  it 'finds type from arguments' do
    reducer = GraphQL::Schema::TypeReducer.new(QueryType, {})
    assert_equal(DairyProductInputType, reducer.result["DairyProductInput"])
  end
end


text:
module.exports = function(config) {
    config.set({

        // Base path, that will be used to resolve files and exclude
        basePath: '../',

        // Frameworks to use
        frameworks: ['jasmine'],

        // List of files / patterns to load in the browser
        files: [
            'bower_components/jquery/dist/jquery.js',
            'bower_components/angular/angular.js',
            'bower_components/angular-sanitize/angular-sanitize.js',
            'bower_components/angular-mocks/angular-mocks.js',

            'dist/reselect.js',
            'test/mock/**/*.js',
            'test/spec/**/*.js'
        ],

        // List of files to exclude
        exclude: [],

        // Web server port
        port: 8088,

        // Level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // Enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false,

        colors: true,

        reporters: ['spec'],

        notifyReporter: {
            reportEachFailure: true, // Default: false, Will notify on every failed sepc
            reportSuccess: false, // Default: true, Will notify when a suite was successful
        }
    });
};


text:
//
//  RCPublicServiceClient.h
//  RongPublicService
//
//  Created by 张改红 on 2020/9/10.
//  Copyright © 2020 张改红. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "RCPublicServiceProfile.h"

@interface RCPublicServiceClient : NSObject

+ (instancetype)sharedPublicServiceClient;

/*!
 查找公众服务账号

 @param searchType                  查找匹配方式
 @param searchKey                   查找关键字
 @param successBlock                查找成功的回调
 [accounts:查找到的公众服务账号信息 RCPublicServiceProfile 的数组]
 @param errorBlock                  查找失败的回调 [status:失败的错误码]

 @remarks 公众号
 */
- (void)searchPublicService:(RCSearchType)searchType
                  searchKey:(NSString *)searchKey
                    success:(void (^)(NSArray *accounts))successBlock
                      error:(void (^)(RCErrorCode status))errorBlock;

/*!
 按类型查找公众服务账号

 @param publicServiceType           公众服务账号的类型
 @param searchType                  查找匹配方式
 @param searchKey                   查找关键字
 @param successBlock                查找成功的回调
 [accounts:查找到的公众服务账号信息 RCPublicServiceProfile 的数组]
 @param errorBlock                  查找失败的回调 [status:失败的错误码]

 @remarks 公众号
 */
- (void)searchPublicServiceByType:(RCPublicServiceType)publicServiceType
                       searchType:(RCSearchType)searchType
                        searchKey:(NSString *)searchKey
                          success:(void (^)(NSArray *accounts))successBlock
                            error:(void (^)(RCErrorCode status))errorBlock;

/*!
 关注公众服务账号

 @param publicServiceType       公众服务账号的类型
 @param publicServiceId         公众服务的账号 ID
 @param successBlock            关注成功的回调
 @param errorBlock              关注失败的回调 [status:失败的错误码]

 @remarks 公众号
 */
- (void)subscribePublicService:(RCPublicServiceType)publicServiceType
               publicServiceId:(NSString *)publicServiceId
                       success:(void (^)(void))successBlock
                         error:(void (^)(RCErrorCode status))errorBlock;

/*!
 取消关注公众服务账号

 @param publicServiceType       公众服务账号的类型
 @param publicServiceId         公众服务的账号 ID
 @param successBlock            取消关注成功的回调
 @param errorBlock              取消关注失败的回调 [status:失败的错误码]

 @remarks 公众号
 */
- (void)unsubscribePublicService:(RCPublicServiceType)publicServiceType
                 publicServiceId:(NSString *)publicServiceId
                         success:(void (^)(void))successBlock
                           error:(void (^)(RCErrorCode status))errorBlock;

/*!
 查询已关注的公众服务账号

 @return 公众服务信息 RCPublicServiceProfile 列表

 @remarks 公众号
 */
- (NSArray *)getPublicServiceList;

/*!
 获取公众服务账号信息

 @param publicServiceType       公众服务账号的类型
 @param publicServiceId         公众服务的账号 ID
 @return                        公众服务账号的信息

 @discussion 此方法会从本地缓存中获取公众服务账号信息

 @remarks 公众号
 */
- (RCPublicServiceProfile *)getPublicServiceProfile:(RCPublicServiceType)publicServiceType
                                    publicServiceId:(NSString *)publicServiceId;

/*!
 获取公众服务账号信息

 @param targetId                        公众服务的账号 ID
 @param type                            公众服务账号的类型
 @param onSuccess                       获取成功的回调
 [serviceProfile:获取到的公众账号信息]
 @param onError                         获取失败的回调 [error:失败的错误码]

 @discussion 此方法会从服务器获取公众服务账号信息

 @remarks 公众号
 */
- (void)getPublicServiceProfile:(NSString *)targetId
               conversationType:(RCConversationType)type
                      onSuccess:(void (^)(RCPublicServiceProfile *serviceProfile))onSuccess
                        onError:(void (^)(RCErrorCode errorCode))onError;

/*!
 获取公众服务使用的 WebView Controller

 @param URLString   准备打开的 URL
 @return            公众服务使用的 WebView Controller

 @discussion
 如果您选在用 WebView 打开 URL 连接,则您需要在 App 的 Info.plist 的 NSAppTransportSecurity 中增加
 NSAllowsArbitraryLoadsInWebContent 和 NSAllowsArbitraryLoads 字段,并在苹果审核的时候提供额外的说明。
 更多内容可以参考:https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW55

 @remarks 公众号
 */
- (UIViewController *)getPublicServiceWebViewController:(NSString *)URLString;

@end


text:
"use strict";

var async = require('async');

/**
 * Do initalization stuff
 */
module.exports = exports = function (app) {
  var hooks = module.exports.hooks;

  async.series([
    function (next) {
      hooks.do('hooks.register', hooks, next);
    },
    function (next) {
      hooks.do('hooks.listen', hooks, next);
    },
    function (next) {
      hooks.do('core.init', app, next);
    },
    function (next) {
      hooks.do('core.init.ready', app, next);
    }
  ]);

  return exports;
};

// Load hooks and register init hook
exports.hooks = require('./hooks');
exports.hooks.on('hooks.register', function (hooks, next) {
  hooks.register('core.init');
  hooks.register('core.init.ready');
  next();
});

// Load the rest of the controllers
exports.app = require('./app');
exports.auth = require('./auth');
exports.posts = require('./posts');
exports.render = require('./render');
exports.route = require('./route');
exports.admin = require('./admin');
exports.theme = require('./theme');
exports.public = require('./public');
exports.media = require('./media');


text:
/**
 * (c) 2013 uchicom
 */
package com.uchicom.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.uchicom.server.Handler;
import com.uchicom.util.Parameter;

/**
 * @author uchicom: Shigeki Uchiyama
 *
 */
public class HttpHandler implements Handler {

	ByteBuffer readBuff = ByteBuffer.allocate(1024);
	ByteBuffer writeBuff = ByteBuffer.allocate(1024);
	String fileName = null;
	StringBuffer strBuff = new StringBuffer();

	protected static Router router;

	TemporalAccessor ifModified;

	Map<String, List<String>> paramMap = null;
	Map<String, String> headMap = new HashMap<>();
	public HttpHandler(Parameter parameter) {
		router = Context.singleton().getRouter();
	}

	/* (non-Javadoc)
	 * @see com.uchicom.http.Handler#handle(java.nio.channels.SelectionKey)
	 */
	@Override
	public void handle(SelectionKey key) throws IOException {
		SocketChannel channel = (SocketChannel) key.channel();
		if (key.isReadable()) {
			int length = channel.read(readBuff);
			if (length > 0) {
				readBuff.flip();
				fileName = request(new String(readBuff.array()));
			}
			readBuff.clear();
			key.interestOps(SelectionKey.OP_WRITE);
		}

		if (key.isWritable()) {

			ByteBuffer buff = null;
			buff = response(channel, fileName).asReadOnlyBuffer();

			try {
				buff.position(0);
				channel.write(buff);
			} catch (IOException e) {
				System.err.println(channel.socket().getInetAddress());
				e.printStackTrace();
			}
			strBuff.setLength(0);
			readBuff.clear();
			key.cancel();
		}
	}

	public String head(String head) throws IOException {

		String fileName = "";
		String[] heads = head.split(" ");
		if (heads.length == 3) {
			//初期応答行を返却する
			String[] urls = heads[1].split("\\?");
			if (urls[0].endsWith("/")) {
				if (urls[0].startsWith("/")) {
					fileName = urls[0] + "index.htm";
				} else {
					fileName = "/" + urls[0] + "index.htm";
				}
			} else {
				if (urls[0].startsWith("/")) {
					fileName = urls[0];
				} else {
					fileName = "/" + urls[0];
				}

			}
			//			if (router.isForward(fileName)) {
			//				router.forward(fileName, heads, br, os);
			//				return;
			//			}
			if (urls.length > 1) {
				//GETパラメータありなので解析。
				paramMap = createGetParamMap(urls[1]);
			}
		}
		return fileName;
	}

	public Map<String, List<String>> createGetParamMap(String get) {
		String[] keyValues;
		try {
			keyValues = URLDecoder.decode(get, "utf-8").split("&");
		} catch (Exception e) {
			e.printStackTrace();
			keyValues = get.split("&");
		}
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		for (String keyValue : keyValues) {
			String[] split = keyValue.split("=");
			if (split.length > 1) {
				if (map.containsKey(split[0])) {
					List<String> list = map.get(split[0]);
					list.add(split[1]);
				} else {
					List<String> list = new ArrayList<String>();
					list.add(split[1]);
					map.put(split[0], list);
				}
			}
		}
		return map;
	}

	public String request(String request) throws IOException {
		int rnIndex = request.indexOf("\r\n");
		String head = request.substring(0, rnIndex);
		String fileName = head(head);

//		System.out.println("head:" + head);
		String head2 = request.substring(rnIndex + 2);
		String[] heads2 = head2.split("\r\n");
		for (String line : heads2) {
			int index = line.indexOf(":");
			if (index >= 0) {
				headMap.put(line.substring(0, index), line.substring(index + 2));
				if (line.startsWith("If-Modified-Since:")) {
					try {
						ifModified = Constants.formatter.parse(line.substring(19));
					} catch (DateTimeParseException e) {
						e.printStackTrace();
					}
				}
			} else {
				headMap.put(line, line);
			}
		}
		return fileName;
	}

	/**
	 * channel と bytebufferを引き回したほうが早いかも.
	 * @param channel
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public ByteBuffer response(SocketChannel channel, String fileName) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
		if (router.exists(fileName)) {
			router.request(fileName, paramMap, headMap, baos);
		} else {
			//Not Found
			router.error("404", baos);
		}
		return ByteBuffer.wrap(baos.toByteArray());
	}

}


text:
package io.codekvast.javaagent.appversion;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import lombok.extern.java.Log;

/**
 * A strategy for picking the app version from a jar manifest.
 *
 *
It handles the cases {@code manifest some.jar} and {@code manifest some.jar
 * My-Custom-Manifest-Attribute} where some.jar can be either an URI or a file path.
 *
 *
The two-arg version uses {@code Implementation-Version} as manifest attribute.
 *
 * @author olle.hallin@crisp.se
 */
@Log
public class ManifestAppVersionStrategy extends AbstractAppVersionStrategy {

  private static final String DEFAULT_MANIFEST_ATTRIBUTE = "Implementation-Version";

  ManifestAppVersionStrategy() {
    super("manifest", "search");
  }

  @Override
  public boolean canHandle(String[] args) {
    return args != null && (args.length == 2 || args.length == 3) && recognizes(args[0]);
  }

  @Override
  public String resolveAppVersion(Collection<File> codeBases, String[] args) {
    String jarUri = args[1];
    String manifestAttribute = args.length > 2 ? args[2] : DEFAULT_MANIFEST_ATTRIBUTE;
    for (File codeBaseFile : codeBases) {
      try (JarFile jarFile = new JarFile(getJarFile(codeBaseFile, jarUri))) {
        Attributes attributes = jarFile.getManifest().getMainAttributes();
        String resolvedVersion = attributes.getValue(manifestAttribute);
        if (resolvedVersion != null) {
          logger.fine(
              String.format(
                  "%s!/META-INF/MANIFEST.MF:%s=%s", jarUri, manifestAttribute, resolvedVersion));
          return resolvedVersion;
        }
        if (!manifestAttribute.equalsIgnoreCase(DEFAULT_MANIFEST_ATTRIBUTE)) {
          resolvedVersion = attributes.getValue(DEFAULT_MANIFEST_ATTRIBUTE);
        }
        if (resolvedVersion != null) {
          logger.fine(
              String.format(
                  "%s!/META-INF/MANIFEST.MF:%s=%s",
                  jarUri, DEFAULT_MANIFEST_ATTRIBUTE, resolvedVersion));
          return resolvedVersion;
        }
      } catch (Exception e) {
        logger.info("Cannot open " + jarUri + ": " + e);
      }
    }
    logger.info(
        String.format("Cannot resolve %s!/META-INF/MANIFEST.MF:%s", jarUri, manifestAttribute));
    return UNKNOWN_VERSION;
  }

  private File getJarFile(File codeBaseFile, String jarUri) throws IOException, URISyntaxException {
    URL url = null;
    // try to parse it as a URL...
    try {
      url = new URL(jarUri);
    } catch (MalformedURLException ignore) {
      // Ignore
    }

    if (url == null) {
      // Try to treat it as a file...
      File file = new File(jarUri);
      if (file.isFile() && file.canRead() && file.getName().endsWith(".jar")) {
        url = file.toURI().toURL();
      }
    }
    if (url == null) {
      // Search for it in codeBaseFile. Treat it as a regular expression for the basename
      url = search(codeBaseFile, jarUri);
    }

    File result = url == null ? null : new File(url.toURI());
    if (result == null) {
      throw new IOException("Cannot find " + jarUri);
    }
    if (!result.canRead()) {
      throw new IOException("Cannot read " + jarUri);
    }
    return result;
  }

  private URL search(File dir, String regex) throws MalformedURLException {
    if (!dir.isDirectory()) {
      logger.info(dir + " is not a directory");
      return null;
    }

    File[] files = dir.listFiles();

    if (files != null) {
      for (File file : files) {
        if (file.isFile() && file.getName().matches(regex)) {
          logger.fine("Found " + file);
          return new URL(file.toURI().toString());
        }
        if (file.isDirectory()) {
          URL url = search(file, regex);
          if (url != null) {
            return url;
          }
        }
      }
    }
    return null;
  }
}


text:
Images v1
=========

.. include:: ../common/clients.sample.rst

Images service
~~~~~~~~~~~~~~

Now to instantiate the Images service:

.. code-block:: php

  $service = $client->imageService(null, '{region}');

Operations
----------

.. toctree::

  images
  schemas
  sharing
  tags

Glossary
--------

  image
    A virtual machine image is a single file which contains a virtual disk
    that has an installed bootable operating system. In the Cloud Images
    API, an image is represented by a JSON-encoded data structure (the image
    schema) and its raw binary data (the image file).

  schema
    The Cloud Images API supplies JSON documents describing the JSON-encoded
    data structures that represent domain objects, so that a client knows
    exactly what to expect in an API response.

  tag
    An image tag is a string of characters used to identify a specific image
    or images.

Further Links
-------------

  - `Getting Started Guide for the API <http://docs.rackspace.com/images/api/v2/ci-gettingstarted/content/ch_image_preface.html>`_
  - `API Developer Guide <http://docs.rackspace.com/images/api/v2/ci-devguide/content/ch_image_preface.html>`_


text:
PermissionInfobarDelegate::~PermissionInfobarDelegate() {
  if (!action_taken_)
    PermissionContextUmaUtil::PermissionIgnored(type_, requesting_origin_);
}

PermissionInfobarDelegate::PermissionInfobarDelegate(
    const GURL& requesting_origin,
    ContentSettingsType type,
    const base::Callback<void(bool, bool)>& callback)
    : requesting_origin_(requesting_origin),
      action_taken_(false),
      type_(type),
      callback_(callback) {
}

infobars::InfoBarDelegate::Type
PermissionInfobarDelegate::GetInfoBarType() const {
  return PAGE_ACTION_TYPE;
}

void PermissionInfobarDelegate::InfoBarDismissed() {
  SetPermission(false, false);
}

PermissionInfobarDelegate*
PermissionInfobarDelegate::AsPermissionInfobarDelegate() {
  return this;
}

base::string16 PermissionInfobarDelegate::GetButtonLabel(
    InfoBarButton button) const {
  return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
      IDS_PERMISSION_ALLOW : IDS_PERMISSION_DENY);
}

bool PermissionInfobarDelegate::Accept() {
  SetPermission(true, true);
  return true;
}

bool PermissionInfobarDelegate::Cancel() {
  SetPermission(true, false);
  return true;
}

void PermissionInfobarDelegate::SetPermission(bool update_content_setting,
                                              bool allowed) {
  action_taken_ = true;
  callback_.Run(update_content_setting, allowed);
}


text:
layout: post
title: "Tuesday 03.13.18 -  CrossFit"
teaser: "A.  Front Squat 6 x 3
 B.  2 Rounds For Time of Rowing, Push Presses, SkiErg, and Front Squats
 C.  Cool Down "
date: 2018-03-13 00:00:00
categories: wodup
tags: wods tuesday
header: no
---

A.  Front Squat 6 x 3

Every 90 seconds, for 9 minutes (6 sets):
3 Front Squats

Start at 65% and build to no more than 80%

B.  2 Rounds For Time of Rowing, Push Presses, SkiErg, and Front Squats

2 Rounds for Time:
– 30/20 Calories of Rowing
– 30 Push Presses @ 52.5/35 kg
– 30/20 Calories of SkiErg
– 30 Front Squats @ 52.5/35 kg

C.  Cool Down

2 Rounds:

1 minute Couch Stretch (R/L)

1 minute Pigeon Stretch (R/L)

1 minute Hamstring Stretch (sitting and reaching for your toes)

View on WodUp

#### Compare to other Tuesdays
{: .t60 }

{% include list-posts tag='tuesday' %}


text:
 **Undetectable Alignment**

**School** abjuration; **Level** bard 1, cleric 2, paladin 2

**Casting Time** 1 standard action

**Components** V, S

**Range** close (25 ft. + 5 ft./2 levels)

**Target** one creature or object

**Duration** 24 hours

**Saving Throw** [Will](../combat#_will) negates (object); **[Spell Resistance](../glossary#_spell-resistance)** yes (object)

An _undetectable alignment _spell conceals the alignment of an object or a creature from all forms of divination.


text:
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:

```bash
npx create-next-app --example with-redux-observable with-redux-observable-app
# or
yarn create next-app --example with-redux-observable with-redux-observable-app
```

### Download manually

Download the example:

```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-redux-observable
cd with-redux-observable
```

Install it and run:

```bash
npm install
npm run dev
# or
yarn
yarn dev
```

### The idea behind the example

This example is a page that renders information about Star-Wars characters. It
fetches new character every 3 seconds having the initial character fetched on
a server.

Example also uses `redux-logger` to log every action.

![demo page](demo.png)

The main problem with integrating Redux, Redux-Observable and Next.js is
probably making initial requests on a server. That's because, the
`getInitialProps` hook runs on the server-side before epics have been made available by just dispatching actions.

However, we can access and execute epics directly. In order to do so, we need to
pass them an Observable of an action together with StateObservable and they will return an Observable:

```js
static async getInitialProps({ store, isServer }) {
  const state$ = new StateObservable(new Subject(), store.getState());
  const resultAction = await rootEpic(
    of(actions.fetchCharacter(isServer)),
    state$
  ).toPromise(); // we need to convert Observable to Promise
  store.dispatch(resultAction)};
```

Note: we are not using `AjaxObservable` from the `rxjs` library; as of rxjs
v5.5.6, it will not work on both the server- and client-side. Instead we call
the default export from
[universal-rxjs-ajax](https://www.npmjs.com/package/universal-rxjs-ajax) (as
`request`).

We transform the Observable we get from `ajax` into a Promise in order to await
its resolution. That resolution should be a action (since the epic returns
Observables of actions). We immediately dispatch that action to the store.

This server-side solution allows compatibility with Next. It may not be
something you wish to emulate. In other situations, calling or awaiting epics
directly and passing their result to the store would be an anti-pattern. You
should only trigger epics by dispatching actions. This solution may not
generalise to resolving more complicated sets of actions.

The layout of the redux related functionality is split between:

    - actions (in `redux/actions.js`)
    - actionTypes (in `redux/actionTypes.js`)
    - epics (in `redux/epics.js`)
    - reducer (in `redux/reducer.js`)

and organized in `redux/index.js`.

Excepting in those manners discussed above, the configuration is similar the
configuration found in [with-redux example](https://github.com/zeit/next.js/tree/canary/examples/with-redux)
and [redux-observable docs](https://redux-observable.js.org/).


text:
/*
 * Castle API
 * ## Introduction  **Just getting started? Check out our [quick start guide](https://docs.castle.io/docs/quickstart)**  Castle APIs uses standard HTTP response codes, authentication and verbs. JSON is used as data exchange format, both for parsing incoming request bodies, and in the returned response. This means that the `Content-Type` header should to be set to `application/json` in requests with a body, such as `POST` or `PUT`.  All API requests must be made over [HTTPS](http://en.wikipedia.org/wiki/HTTP_Secure). Non-HTTPS calls will fail and the **TLS version needs to be 1.1 or higher**.  ## Supported types  For a list of supported types, see our [Types Reference](https://docs.castle.io/docs/events).   ## Rate limits  Our Risk, Log (and the legacy Authenticate) APIs have a per-user-id rate limit of 6 requests per second and 10 requests per 5 seconds.
 *
 * The version of the OpenAPI document: 1
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package io.castle.client.model.generated;

import java.util.Objects;

import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModelProperty;

/**
 * FilterRequestAllOfParams
 */
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2022-09-05T12:03:37.030848+02:00[Europe/Stockholm]")
public class FilterRequestParams {
  public static final String SERIALIZED_NAME_EMAIL = "email";
  @SerializedName(SERIALIZED_NAME_EMAIL)
  private String email;

  public static final String SERIALIZED_NAME_PHONE = "phone";
  @SerializedName(SERIALIZED_NAME_PHONE)
  private String phone;

  public static final String SERIALIZED_NAME_USERNAME = "username";
  @SerializedName(SERIALIZED_NAME_USERNAME)
  private String username;

  public FilterRequestParams email(String email) {

    this.email = email;
    return this;
  }

   /**
   * The email address sent by the user
   * @return email
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(example = "Rhea.Franecki@example.org", value = "The email address sent by the user")

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public FilterRequestParams phone(String phone) {

    this.phone = phone;
    return this;
  }

   /**
   * The phone number sent by the user
   * @return phone
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(example = "+16175551212", value = "The phone number sent by the user")

  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

  public FilterRequestParams username(String username) {

    this.username = username;
    return this;
  }

   /**
   * The username sent by the user
   * @return username
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(example = "superhero123", value = "The username sent by the user")

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    FilterRequestParams filterRequestAllOfParams = (FilterRequestParams) o;
    return Objects.equals(this.email, filterRequestAllOfParams.email) &&
        Objects.equals(this.phone, filterRequestAllOfParams.phone) &&
        Objects.equals(this.username, filterRequestAllOfParams.username);
  }

  @Override
  public int hashCode() {
    return Objects.hash(email, phone, username);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class FilterRequestAllOfParams {\n");
    sb.append("    email: ").append(toIndentedString(email)).append("\n");
    sb.append("    phone: ").append(toIndentedString(phone)).append("\n");
    sb.append("    username: ").append(toIndentedString(username)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


text:
package cz.metacentrum.perun.cabinet.dao;

import java.util.List;

import cz.metacentrum.perun.cabinet.model.PublicationSystem;
import cz.metacentrum.perun.cabinet.bl.CabinetException;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Interface of DAO layer for handling PublicationSystem entity.
 *
 * @author Jiri Harazim <harazim@mail.muni.cz>
 * @author Pavel Zlámal <zlamal@cesnet.cz>
 */
public interface PublicationSystemManagerDao {

	/**
	 * Create PublicationSystem in Perun
	 *
	 * @param session PerunSession
	 * @param ps PublicationSystem to create
	 * @return PublicationSystem with ID set
	 * @throws InternalErrorException When implementation fails
	 */
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
	PublicationSystem createPublicationSystem(PerunSession session, PublicationSystem ps);

	/**
	 * Update PublicationSystem in Perun (name,type,url,loginNamespace) by its ID.
	 *
	 * @param session PerunSession
	 * @param ps PublicationSystem to update
	 * @return Updated PublicationSystem
	 * @throws CabinetException When PublicationSystem doesn't exists by its ID.
	 * @throws InternalErrorException When implementation fails
	 */
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
	PublicationSystem updatePublicationSystem(PerunSession session, PublicationSystem ps) throws CabinetException;

	/**
	 * Delete PublicationSystem by its ID.
	 *
	 * @param ps PublicationSystem to be deleted
	 * @throws CabinetException When PublicationSystem doesn't exists by its ID
	 * @throws InternalErrorException When implementation fails
	 */
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
	void deletePublicationSystem(PublicationSystem ps) throws CabinetException;

	/**
	 * Get PublicationSystem by its ID.
	 *
	 * @param id ID to get PS by
	 * @return PublicationSystem by its ID.
	 * @throws CabinetException When PublicationSystem doesn't exist by its ID.
	 * @throws InternalErrorException When implementation fails.
	 */
	PublicationSystem getPublicationSystemById(int id) throws CabinetException;

	/**
	 * Get PublicationSystem by its name
	 *
	 * @param name Name to get PS by
	 * @return PublicationSystem by its name.
	 * @throws CabinetException When PublicationSystem doesn't exist by its name.
	 * @throws InternalErrorException When implementation fails.
	 */
	PublicationSystem getPublicationSystemByName(String name) throws CabinetException;

	/**
	 * Get PublicationSystem by its login-namespace
	 *
	 * @param namespace Login-namespace to get PS by
	 * @return PublicationSystem by its login-namespace.
	 * @throws CabinetException When PublicationSystem doesn't exist by its login-namespace.
	 * @throws InternalErrorException When implementation fails.
	 */
	PublicationSystem getPublicationSystemByNamespace(String namespace) throws CabinetException;

	/**
	 * Get all PublicationSystems in Perun. If none, return empty list.
	 *
	 * @return List of all PublicationSystems or empty list.
	 * @throws InternalErrorException When implementation fails
	 */
	List<PublicationSystem> getPublicationSystems();

}


text:
package com.github.dockerjava.api.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import javax.annotation.CheckForNull;
import java.io.Serializable;
import java.util.List;

/**
 * Used in {@link Statistics}
 *
 * @author Yuting Liu
 */
@EqualsAndHashCode
@ToString
public class BlkioStatsConfig extends DockerObject implements Serializable {
    private static final long serialVersionUID = 1L;

    @JsonProperty("io_service_bytes_recursive")
    private List<BlkioStatEntry> ioServiceBytesRecursive;

    @JsonProperty("io_serviced_recursive")
    private List<BlkioStatEntry> ioServicedRecursive;

    @JsonProperty("io_queue_recursive")
    private List<BlkioStatEntry> ioQueueRecursive;

    @JsonProperty("io_service_time_recursive")
    private List<BlkioStatEntry> ioServiceTimeRecursive;

    @JsonProperty("io_wait_time_recursive")
    private List<BlkioStatEntry> ioWaitTimeRecursive;

    @JsonProperty("io_merged_recursive")
    private List<BlkioStatEntry> ioMergedRecursive;

    @JsonProperty("io_time_recursive")
    private List<BlkioStatEntry> ioTimeRecursive;

    @JsonProperty("sectors_recursive")
    private List<BlkioStatEntry> sectorsRecursive;

    /**
     * @see #ioServiceBytesRecursive
     */
    @CheckForNull
    public List<BlkioStatEntry> getIoServiceBytesRecursive() {
        return ioServiceBytesRecursive;
    }

    /**
     * @see #ioServicedRecursive
     */
    @CheckForNull
    public List<BlkioStatEntry> getIoServicedRecursive() {
        return ioServicedRecursive;
    }

    /**
     * @see #ioQueueRecursive
     */
    @CheckForNull
    public List<BlkioStatEntry> getIoQueueRecursive() {
        return ioQueueRecursive;
    }

    /**
     * @see #ioServiceTimeRecursive
     */
    @CheckForNull
    public List<BlkioStatEntry> getIoServiceTimeRecursive() {
        return ioServiceTimeRecursive;
    }

    /**
     * @see #ioWaitTimeRecursive
     */
    @CheckForNull
    public List<BlkioStatEntry> getIoWaitTimeRecursive() {
        return ioWaitTimeRecursive;
    }

    /**
     * @see #ioMergedRecursive
     */
    @CheckForNull
    public List<BlkioStatEntry> getIoMergedRecursive() {
        return ioMergedRecursive;
    }

    /**
     * @see #ioTimeRecursive
     */
    @CheckForNull
    public List<BlkioStatEntry> getIoTimeRecursive() {
        return ioTimeRecursive;
    }

    /**
     * @see #sectorsRecursive
     */
    @CheckForNull
    public List<BlkioStatEntry> getSectorsRecursive() {
        return sectorsRecursive;
    }
}


text:
using J4Pkg
using Base.Test

# write your own tests here
@test 1 == 1


text:
sass:
	node-sass --source-map ./public/stylesheets/style.css.map ./public/stylesheets/style.sass ./public/stylesheets/style.css

help:
	@echo "Please use \`make <target>' where <target> is one of"
	@echo "  sass                            makes sass file, requires node-sass installed globally."
	@echo "  help                            displays this help message."


text:
/**
 * HiloSlot
 */
(function(superClass) {
    var RAD2DEG = 180/Math.PI;
    var TextureAtlas = dragonBones.TextureAtlas;
    var HiloSlot = function() {
        superClass.call(this, this);
        this._display = null;
    };

    __extends(HiloSlot, superClass, {
        dispose: function() {
            if (this._displayList) {
                var length = this._displayList.length;
                for (var i = 0; i < length; i++) {
                    var content = this._displayList[i];
                    if (content instanceof Armature) {
                        content.dispose();
                    }
                }
            }

            superClass.prototype.dispose();
            this._display = null;
        },
        _updateDisplay: function(value) {
            this._display = value;
        },
        _getDisplayIndex: function() {
            if (this._display && this._display.parent) {
                return this._display.parent.getChildIndex(this._display);
            }
            return -1;
        },
        _addDisplayToContainer: function(container, index) {
            if (this._display && container) {
                if(index){
                    container.addChildAt(this._display, index);
                }
                else{
                    container.addChild(this._display);
                }
            }
        },
        _removeDisplayFromContainer: function() {
            if (this._display && this._display.parent) {
                this._display.parent.removeChild(this._display);
            }
        },
        _updateTransform: function() {
            if (this._display) {
                this._display.x = this._global.x;
                this._display.y = this._global.y;
                this._display.scaleX = this._global.scaleX;
                this._display.scaleY = this._global.scaleY;
                this._display.rotation = this._global.skewX * RAD2DEG;
            }
        },
        _updateDisplayVisible: function(value) {
            if (this._display && this._parent) {
                this._display.visible = this._parent._visible && this._visible && value;
            }
        },
        _updateDisplayColor: function(aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier, colorChange) {
            superClass.prototype._updateDisplayColor.call(this, aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier, colorChange);
            if (this._display) {
                this._display.alpha = aMultiplier;
            }
        },
        _updateDisplayBlendMode: function(value) {
            // if (this._display && value) {
            //     this._display.blendMode = value;
            // }
        },
        _calculateRelativeParentTransform: function() {
            this._global.scaleX = this._origin.scaleX * this._offset.scaleX;
            this._global.scaleY = this._origin.scaleY * this._offset.scaleY;
            this._global.skewX = this._origin.skewX + this._offset.skewX;
            this._global.skewY = this._origin.skewY + this._offset.skewY;
            this._global.x = this._origin.x + this._offset.x + this._parent._tweenPivot.x;
            this._global.y = this._origin.y + this._offset.y + this._parent._tweenPivot.y;

            if (this._displayDataList &&
                this._currentDisplayIndex >= 0 &&
                this._displayDataList[this._currentDisplayIndex] &&
                TextureAtlas.rotatedDic[this._displayDataList[this._currentDisplayIndex].name] == 1) {
                this._global.skewX -= 1.57;
                this._global.skewY -= 1.57;
            }
        }
    });

    dragonBones.HiloSlot = HiloSlot;
})(dragonBones.Slot);

/**
 * HiloFactory
 */
(function(superClass){
    var Armature = dragonBones.Armature;
    var HiloSlot = dragonBones.HiloSlot;

    var HiloFactory = function(){
        superClass.call(this, this);
    };
    __extends(HiloFactory, superClass, {
        _generateArmature:function(){
            var armature = new Armature(new Hilo.Container);
            return armature;
        },
        _generateSlot:function(){
            var slot = new HiloSlot();
            return slot;
        },
        _generateDisplay:function(textureAtlas, fullName, pivotX, pivotY){
            var texture = textureAtlas.getTexture(fullName);
            var region = texture.region;
            var bitmap = new Hilo.Bitmap({
                image:textureAtlas.texture,
                rect:[region.x, region.y, region.width, region.height]
            });

            if(isNaN(pivotX)||isNaN(pivotY))
            {
                var subTextureFrame = textureAtlas.getFrame(fullName);
                if(subTextureFrame != null)
                {
                    pivotX = subTextureFrame.width/2;
                    pivotY = subTextureFrame.height/2;
                }
                else
                {
                    pivotX = texture.region.width/2;
                    pivotY = texture.region.height/2;
                }
            }
            bitmap.pivotX = pivotX;
            bitmap.pivotY = pivotY;
            return bitmap;
        }
    });

    dragonBones.HiloFactory = HiloFactory;
}(dragonBones.BaseFactory));


text:
@interface MJGLKRootView ()
@property (nonatomic, strong, readwrite) MJGLKView *view;
@end

@implementation MJGLKRootView

@synthesize view = _view;

#pragma mark -

- (id)initWithView:(MJGLKView*)inView {
    if ((self = [super initWithFrame:CGRectZero])) {
        self.view = inView;
        self.view.rootView = self;
        [self addSubview:self.view.view];
    }
    return self;
}

- (void)dealloc {
    self.view.rootView = nil;
}

#pragma mark -

- (void)reflowLayout {
    CGRect bounds = self.bounds;

    MJGLKDimension width = MJGLKDimensionMake((NSInteger)(bounds.size.width - self.view.layoutSpec.margin.left - self.view.layoutSpec.margin.right), MJGLKSizeConstraintExact);
    MJGLKDimension height = MJGLKDimensionMake((NSInteger)(bounds.size.height - self.view.layoutSpec.margin.top - self.view.layoutSpec.margin.bottom), MJGLKSizeConstraintExact);
    [self.view updateViewWidth:width andHeight:height];

    self.view.view.frame = CGRectMake(0.0f, 0.0f, self.view.measuredSize.width, self.view.measuredSize.height);

    [self.view layoutView];
}

#pragma mark -

- (void)layoutSubviews {
    [super layoutSubviews];
    [self reflowLayout];
}

@end


text:
'use strict';

var _ = require('lodash');
var User = require('./user.model');
var passport = require('passport');
var config = require('../../config/environment');
var jwt = require('jsonwebtoken');
var crypto = require('crypto');
var async = require('async');
var email = require("../../components/email");
var Commit = require('../commit/commit.model');
var ClassYear = require('../classyear/classyear.model');
var Attendance = require('../attendance/attendance.model');
var SmallGroup = require('../smallgroup/smallgroup.model');

// Return a standard error
function handleError(res, err) {
  return res.sendStatus(500, err);
}

var validationError = function(res, err) {
  return res.status(422).json(err);
};

/**
 * Get list of users
 */
exports.index = function(req, res) {
  User.find({}, function (err, users) {
    if(err) return res.send(500, err);
    res.status(200).json(users);
  });
};

/**
 * Get user stats
 */
exports.publicStats = function(req, res) {
  async.parallel([
    // Count active users
    function(callback) {
      User.count({active:true}, function (err, aCount) {
        if (err) return callback(err);
        callback(null, aCount);
      });
    },
    // Count past users
    function(callback) {
      User.count({active:false}, function (err, pCount) {
        if (err) return callback(err);
        callback(null, pCount);
      });
    },
  ],
  function(err, results){
    if (err) {
      return res.send(400);
    }

    if (results === null) {
      return res.send(400);
    }

    //results contains [activeProjectCount, pastProjectCount]
    var stats = {};
    stats.activeUsers = results[0] || 0;
    stats.pastUsers = results[1] || 0;

    return res.status(200).send(stats);
  });
};

/**
 * Returns user or list of users that match a supplied query
 *
 * Takes {query:String, single:Boolean, limit:Integer}
 */
// TODO Make this work with fuzzy queries, multiple results etc.
exports.search = function(req, res){
  if (!req.query.query) return res.send(400, "No query supplied");
  var query = new RegExp(["^", req.query.query, "$"].join(""), "i")
  User.findOne({name: query}, function(err, user){
    if (err) return res.send(500, err);
    if (!user){
      if (req.query.single){
        return res.status(200).json(null);
      }else{
        return res.status(200).json([]);
      }
    }
    if (req.query.single){
      return res.status(200).json(user.profile);
    }else{
      return res.status(200).json([user.profile]);
    }
  });
};

/**
 * Get list of users with stats including last commits
 * in previous 2 weeks
 * restriction: 'admin'
 */
exports.stats = function(req, res) {
  // Only return users who are active and have a github login
  User.find({active: true, 'github.login': {$exists: true}})
  .exec(function (err, users) {
    if(err) return res.send(500, err);
    var twoWeeks = new Date();
    twoWeeks.setDate(twoWeeks.getDate()-14);
    var userInfo = [];
    var count = users.length;

    var getCommits = function(user){
      Commit.find()
      .where('author.login').equals(String(user.github.login))
      .where('date').gt(twoWeeks)
      .exec(function(err, commits){
        var commitList = [];
        commits.forEach(function (c){
          commitList.push(c.toObject());
        }
                       )
                       user.commits = commitList ;
                       count--;
                       userInfo.push(user);
                       if (count === 0){
                         res.status(200).json(userInfo);
                       }
      });
    }

    for (var i = 0; i < users.length; i++){
      var u = users[i].stats;
      getCommits(u);
    }
  });
};

/**
 * Get list of all users with stats including last commits
 * in previous 2 weeks including inactive
 * restriction: 'admin'
 */
exports.allStats = function(req, res) {
  // Only return users who have a github login
  ClassYear.getCurrent(function(err, classYear){
    var classYearId = classYear._id;
    User.find({})
    .exec(function (err, users) {
      if(err) return res.status(500).json(err);
      res.status(200).json(users);
    });
  });
};

/**
 * Get list of active users
 */
exports.list = function(req, res) {
  // Only return users who are active and have a github login
  User.find({active: true, 'github.login': {$exists: true}})
  .select('_id name role avatar email github.login')
  .exec(function (err, users) {
    res.status(200).json(users);
  });
};

/**
 * Get list of all past users
 */
exports.past = function(req, res) {
  User.find({active: false})
  .select('_id name role avatar email github.login')
  .exec(function (err, users) {
    if(err) return res.send(500, err);

    res.status(200).json(users);
  });
};

/**
 * Get a list of all the recent RCOS commits for a user
 */
exports.commits = function(req, res) {
  var userId = String(req.params.id);

  Commit.find({ userId: userId}, function(err, commits){
    if (err) return res.send(500, err);
    res.status(200).json(commits);
  });
};

/**
 * Creates a new user
 */
exports.create = function (req, res, next) {
  var newUser = new User(req.body);
  newUser.provider = 'local';
  newUser.role = 'user';
  newUser.save(function(err, user) {
    if (err) return validationError(res, err);
    var token = jwt.sign({_id: user._id }, config.secrets.session, { expiresInMinutes: 60*5 });
    res.json(201, { token: token });
  });
};

/**
 * Update an existing user
 */
exports.update = function (req, res, next) {
  if(req.body._id) { delete req.body._id; }

  User.findById(req.params.id, function(err, user){
    if (err) { return handleError(res, err); }
    if(!user) { return res.send(404); }

    var updated = _.merge(user, req.body);
    updated.save(function(err) {
      if (err) { return handleError(res, err); }
      return res.json(200, updated);
    });
  });
}

/**
 * Get a single user
 */
exports.show = function (req, res, next) {
  var userId = req.params.id;

  User.findById(userId)
  .populate('smallgroup')
  .exec(function (err, user) {
    if (err) {return next(err);}
    if (!user) {return res.send(404);}
    var profile = user.profile;
    return res.json(profile);
  });
};

/**
 * Get a single user
 */
exports.privateProfile = function (req, res, next) {
  var userId = req.params.id;
  User.findById(userId)
  .populate('projects')
  .populate('favoriteProjects')
  .exec(function (err, user) {
    if (err) {return next(err);}
    if (!user) {return res.send(404);}
    var profile = user.privateProfile;
    return ClassYear.getCurrent(function(err, classYear){
      var classYearId = classYear._id;
      return SmallGroup.findOne({"students":userId, "classYear":classYearId}, function(err, smallgroup){
        if (err) {return next(err);}
        if (smallgroup) {
          var responseObjectSmallgroup = smallgroup.toObject();
          profile.smallgroup = responseObjectSmallgroup;
        }
        // Get how many total attendance days there have been
        var data = user.getTotalDays(classYear, smallgroup);
        profile.totalDates = data.totalDates;
        profile.totalBonusDates = data.totalBonusDates;
        profile.totalSmallDates = data.totalSmallDates;
        profile.totalBonusSmallDates = data.totalBonusSmallDates;

        Attendance.find({classYear:classYearId, user: userId})
        .exec(function (err, attendance) {
          if(err) { return handleError(res, err); }
          profile.attendance = attendance;

          return res.json(profile);
        });
      });
    });
  });
};

/**
 * Get a user's favorite projects
 */
exports.favoriteProjects = function (req, res, next) {
  var userId = req.params.id;
  User.findById(userId)
  .populate('favoriteProjects')
  .exec(function (err, user) {
    if (err) {return next(err);}
    if (!user) {return res.send(404);}

    return res.json(user.favoriteProjects);
  });
};

/**
 * Get a my smallgroup
 */
exports.smallgroup = function (req, res, next) {
  var userId = req.user.id;
  return ClassYear.getCurrent(function(err, classYear){
    var classYearId = classYear._id;
    var query = SmallGroup.findOne({"students":userId, "classYear":classYearId});
    if (req.user.isMentor){
      query.select('+dayCodes.code')
    }
    return query.exec(function(err, smallgroup){
      if (err) return handleError(res, err);
      if (!smallgroup) return res.json({});
      var responseObject = smallgroup.toObject();
      // If user is not a mentor or not authenticated, don't give dayCode
      if (req.user.isMentor){
        // Mentors should get a day code
        // Generate a day code if one does not already exist
        if (smallgroup.dayCode){
          responseObject.dayCode = smallgroup.dayCode;
        }
        if (smallgroup.bonusDayCode){
          responseObject.bonusDayCode = smallgroup.bonusDayCode;
        }
      }
      res.status(200).json(responseObject);
    });
  });
};

/**
 * Get a single user's smallgroup
 */
exports.userSmallgroup = function (req, res, next) {
  var userId = req.params.id;
  return ClassYear.getCurrent(function(err, classYear){
    var classYearId = classYear._id;
    var query = SmallGroup.findOne({"students":userId, "classYear":classYearId})
    if (req.user.isMentor){
      query.select('+dayCodes.code')
    }
    return query.exec(function(err, smallgroup){
      if (err) return handleError(res, err);
      if (!smallgroup) return res.json({});
      var responseObject = smallgroup.toObject();
      // If user is not a mentor or not authenticated, don't give dayCode
      // Mentors should get a day code
      // Generate a day code if one does not already exist
      if (smallgroup.dayCode){
        responseObject.dayCode = smallgroup.dayCode;
      }
      if (smallgroup.bonusDayCode){
        responseObject.bonusDayCode = smallgroup.bonusDayCode;
      }
      res.status(200).json(responseObject);
    });
  });
};

/**
 * Get a single user's avatar
 */
exports.avatar = function (req, res, next) {
  var userId = req.params.id;

  User.findById(userId, function (err, user) {
    if (err) return next(err);
    if (!user) return res.send(404);
    return res.json(user.avatar);
  });
};

/**
 * Deletes a user
 * restriction: 'admin'
 */
exports.destroy = function(req, res) {
  User.findByIdAndRemove(req.params.id, function(err, user) {
    if(err) return res.send(500, err);
    return res.send(204);
  });
  var userId = req.params.id;
  var adminUserId = req.user.id;
  var pass = String(req.body.password);
  var query = {students:{ $in: [userId]}};
  User.findById(adminUserId)
  .select('_id email password provider salt')
  .exec(function (err, user, db) {
    if(user.authenticate(pass)) {
      SmallGroup.findOneAndUpdate(query, {$pull: {students: userId}}, function(err, data){
        if(err) {
          return res.status(500).json({'error' : 'error in deleting address'});
        }
        User.findByIdAndRemove(userId, function(err, user) {
          if(err) return res.send(500, err);
          return res.send(200);
        });
        //res.json(data);
      });
    } else {
      res.send(403);
    }
  });

};

/**
 * Change what role the user is
 * restriction: 'admin'
 */
exports.role = function(req, res) {
  var roles = ['user', 'mentor', 'admin'];
  var userId = req.params.id;
  var newRole = req.body.role;
  // Check that role is valid
  if (roles.indexOf(newRole) === -1){
    res.send(400, {error: "Role does not exist."});
  }
  User.findById(userId, function(err,user){
    if (err){
      res.send(500, err);
    }else{
      if (user.role === newRole) return;
      user.role = newRole;
      user.save(function(err) {
        if (err) return validationError(res, err);
        res.send(200);
      });
    }
  });
}
/**
 * Change a users password
 *
 * This can be done with either the reset token or the user's old
 * password
 */
exports.changePassword = function(req, res, next) {
  var userId = req.user._id;
  var oldPass = String(req.body.oldPassword);
  var token   = String(req.body.token);
  var newPass = String(req.body.newPassword);

  User.findById(userId)
  .select('_id email password provider salt passwordResetToken passwordResetExpiration')
  .exec(function (err, user) {
    if(user.authenticate(oldPass) || user.validResetToken(token)) {
      user.password = newPass;
      user.passwordResetToken = '';
      user.save(function(err) {
        if (err) return validationError(res, err);
        res.send(200);
      });
    } else {
      res.send(403);
    }
  });
};

/**
 * Deactivates a user
 */
exports.deactivate = function(req,res) {
  var userId = String(req.params.id);
  User.findById(userId, function(err, user){
    if (err) return res.send(500, err);
    user.active = false;
    user.save(function(err){
      if (err) return res.send(500, err);
      res.status(200).json({success: true});
    })
  });
};

/**
 * Deactivates a user
 */
exports.deactivate = function(req, res, next) {
  var userId = String(req.params.id);

  User.findOne({ '_id': userId}, function(err, user){
    if (err) return res.send(500, err);

    user.active = false;
    user.save(function(err){
      if (err) return res.send(500, err);
      res.status(200).json({success: true});
    })
  });
};

/**
 * Activates a user
 */
exports.activate = function(req, res, next) {
  var userId = String(req.params.id);
  User.findOne({ '_id': userId}, function(err, user){
    if (err) return res.send(500, err);
    user.active = true;
    user.save(function(err){
      if (err) return res.send(500, err);
      res.status(200).json({success: true});
    })
  });
};

/**
 * Get my info
 */
exports.me = function(req, res, next) {
  var userId = req.user._id;
  User.findOne({
    _id: userId
  })
  .exec(function(err, user) {
    if (err) return next(err);
    if (!user) return res.json(401);
    res.json(user);
  });
};

/**
 * Authentication callback
 */
exports.authCallback = function(req, res, next) {
  res.redirect('/');
};

/**
 * Add an item to the tech array for a user
 */
exports.addTech = function(req,res){
  var userId = req.params.id;
  var newTech = req.body.tech;
  User.findById(userId, function(err,user){
    if (err){
      res.send(500, err);
    }else{
      if (!user.tech) user.tech = [];
      user.tech.push(newTech);
      user.save(function(err) {
        if (err) return validationError(res, err);
        res.send(200);
      });
    }
  });
};

/**
 * Remove an item from the tech array for a user
 */
exports.removeTech = function(req,res){
  var userId = req.params.id;
  var tech = req.body.tech;
  User.findById(userId, function(err,user){
    if (err){
      res.send(500, err);
    }else{
      if (!user.tech) user.tech = [];
      user.tech.splice(user.tech.indexOf(tech), 1);
      user.save(function(err) {
        if (err) return validationError(res, err);
        res.send(200);
      });
    }
  });
};

/**
 * Set reset token for user and email it the password token will expire after 24 hours.
 */
exports.resetPassword = function(req, res){
  var userEmail = req.body.email;
  User.findOne({
    email: userEmail.toLowerCase()
  }, function (err, user){
    if (err) return res.status(401).json(err);
    if (!user) return res.status(200).json({success: true});

    crypto.randomBytes(12, function(ex, buf) {
      var token = buf.toString('hex');
      user.passwordResetToken = token;

      // Get tomorrow's date
      var tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);

      user.passwordResetExpiration = tomorrow;

      user.save(function(err){
        if (err) return validationError(res,err);

        var sub = {
          ":name": [user.name],
          "[%address%]": [config.addr + "/login?token=" + user.passwordResetToken],
        }

        var filter = {
          "templates": {
            "settings": {
              "enable": 1,
              "template_id": "2f31a6c8-770e-4da0-a71c-dc71385d549f"
            }
          }
        }

        // email token to user
        email.sendEmail(user.email, "RCOS.IO Forgot Password", sub, '<br>', filter, function(err, success){
          if (err) return res.status(500).json(err);

          return res.status(200).json(success);
        });
      });

    });

  });

};

/**
 * Add an item to the projects array for the user
 */
exports.addProject = function(req,res){
  var userId = req.params.id;
  var newProject = req.body.project;
  User.findById(userId, function(err,user){
    if (err){
      res.send(500, err);
    }else{
      if (!user.projects) user.projects = [];
      if (user.projects.indexOf(newProject) !== -1) return;
      user.projects.push(newProject);
      user.save(function(err) {
        if (err) return validationError(res, err);
        res.send(200);
      });
    }
  });
};

/**
 * Add an item to the favorite projects array for the user
 */
exports.addFavorite = function(req,res){
  var userId = req.params.id;
  var newFavorite = req.params.project;
  User.findById(userId, function(err,user){
    if (err){
      res.send(500, err);
    }else{
      if (!user.favoriteProjects) user.favoriteProjects = [];
      if (user.favoriteProjects.indexOf(newFavorite) !== -1) return;
      user.favoriteProjects.push(newFavorite);
      user.save(function(err) {
        if (err) return validationError(res, err);
        res.send(200);
      });
    }
  });
};

/**
 * Remove an item from the tech array for a user
 */
exports.removeProject = function(req,res){
  var userId = req.params.id;
  var project = req.body.project;
  User.findById(userId, function(err,user){
    if (err){
      res.send(500, err);
    }else{
      if (!user.projects) user.projects = [];
      user.projects.splice(user.projects.indexOf(project), 1);
      user.save(function(err) {
        if (err) return validationError(res, err);
        res.send(200);
      });
    }
  });
};
/**
 * Remove an item from the favorite projects array for a user
 */
exports.removeFavorite = function(req,res){
  var userId = req.params.id;
  var project = req.params.project;
  User.findById(userId, function(err,user){
    if (err){
      res.send(500, err);
    }else{
      if (!user.favoriteProjects) user.favoriteProjects = [];
      user.favoriteProjects.splice(user.favoriteProjects.indexOf(project), 1);
      user.save(function(err) {
        if (err) return validationError(res, err);
        res.send(200);
      });
    }
  });
};
/*
   Function that is called by removeUser api call
   */
exports.deleteUser = function(req,res,next){

  var userId = req.user.id;
  var pass = String(req.body.password);
  var query = {students:{ $in: [userId]}};
  User.findById(userId)
  .select('_id email password provider salt passwordResetToken passwordResetExpiration')
  .exec(function (err, user,db) {
    if(user.authenticate(pass)) {
      SmallGroup.findOneAndUpdate(query, {$pull: {students: userId}}, function(err, data){
        if(err) {
          return res.status(500).json({'error' : 'error in deleting address'});
        }
        User.findByIdAndRemove(userId, function(err, user) {
          if(err) return res.send(500, err);
          return res.send(200);
        });
        //res.json(data);
      });
    } else {
      res.send(403);
    }
  });
};