text:
from flask import Flask, render_template, request, redirect
from flask_mysqldb import MySQL
import json
import optparse
import yaml

import seolinter

app = Flask(__name__, template_folder='.', static_folder='static', static_url_path='/static')
db = MySQL()

default_page_length = 50

lint_desc = {t[0]: t[1] for t in seolinter.rules}
lint_level = {t[0]: t[2] for t in seolinter.rules}

def delete_run(run_id):
    conn = db.connection
    c = conn.cursor()
    try:
        c.execute('DELETE FROM crawl_urls WHERE run_id = %s', [run_id])
        conn.commit()
    except:
        conn.rollback()
        raise

def fetch_latest_run_id():
    run_id = None
    c = db.connection.cursor()
    c.execute('SELECT run_id FROM crawl_urls ORDER BY timestamp DESC LIMIT 1')
    result = c.fetchone()
    if result:
        run_id = result[0]
    return run_id

def fetch_run(run_id, page=1, page_length=default_page_length, lint=None, order_by=None, order_by_asc=1):
    lint = '%%%s%%' % lint if lint else '%'
    c = db.connection.cursor()
    start = (page - 1) * page_length
    # Define the ordering
    order_by_sql = 'ORDER BY lint_critical DESC, lint_error DESC, lint_warn DESC, lint_info DESC'
    if order_by is not None:
        order_by_sql = 'ORDER BY %s %s' % (order_by, 'ASC' if order_by_asc else 'DESC')

    c.execute('SELECT * FROM crawl_urls WHERE run_id = %s AND external = 0 AND lint_results LIKE %s ' + order_by_sql + ' LIMIT %s, %s',
        [run_id, lint, start, page_length])
    return cols_to_props(c)

def fetch_run_stats(run_id):
    c = db.connection.cursor()
    c.execute('SELECT COUNT(id) AS count, SUM(lint_critical) AS lint_critical, SUM(lint_error) AS lint_error, SUM(lint_warn) AS lint_warn, SUM(lint_info) AS lint_info FROM crawl_urls WHERE run_id = %s', [run_id])
    return cols_to_props(c)[0]

def fetch_run_ids():
    c = db.connection.cursor()
    c.execute('SELECT run_id, timestamp, domain FROM crawl_urls GROUP BY run_id ORDER BY timestamp ASC ')
    return cols_to_props(c)

def fetch_url(url_id):
    c = db.connection.cursor()
    c.execute('SELECT * FROM crawl_urls WHERE id = %s', [url_id])
    return cols_to_props(c)

def fetch_from_links(url_id):
    c = db.connection.cursor()
    c.execute('SELECT crawl_links.*,crawl_urls.path as from_url_path FROM crawl_links LEFT JOIN (crawl_urls) ON (crawl_links.from_url_id=crawl_urls.id) WHERE to_url_id = %s;', [url_id])
    return cols_to_props(c)

def fetch_to_links(url_id):
    c = db.connection.cursor()
    c.execute('SELECT crawl_links.*,crawl_urls.path as to_url_path FROM crawl_links LEFT JOIN (crawl_urls) ON (crawl_links.to_url_id=crawl_urls.id) WHERE from_url_id = %s;', [url_id])
    return cols_to_props(c)

def cols_to_props(c):
    output = []
    descriptions = [t[0] for t in c.description]
    for result in c.fetchall():
        url = dict(zip(descriptions, result))
        # unmarshal keywords
        if 'keywords' in url:
            keywords = json.loads(url.get('keywords', '{}')) or {}
            url['keywords'] = sorted(keywords.items(), key=lambda x: x[1].get('total'), reverse=True)
        output.append(url)
    return output

@app.route("/")
def index():
    run_id = request.args.get('run_id', fetch_latest_run_id())
    filter_lint = request.args.get('filter_lint', None)
    order_by = request.args.get('order_by', None)
    order_by_asc = request.args.get('order_by_asc', None) == '1'
    page = int(request.args.get('page', 1))
    page_length = int(request.args.get('page_length', default_page_length))

    crawl_urls = fetch_run(run_id, page, page_length, lint=filter_lint, order_by=order_by, order_by_asc=order_by_asc)
    run_ids = fetch_run_ids()
    crawl_stats = fetch_run_stats(run_id)

    return render_template('index.html',
        run_id=run_id,
        run_ids=run_ids,
        filter_lint=filter_lint,
        lint_desc=lint_desc,
        lint_level=lint_level,
        crawl_urls=crawl_urls,
        crawl_stats=crawl_stats,
        page=page,
        prev_page=(page - 1 if page > 1 else None),
        next_page=(page + 1 if len(crawl_urls) == page_length else None),
        order_by=order_by,
        order_by_asc=order_by_asc,
        page_length=page_length,
        )

@app.route("/url/")
def url_page():
    url_id = request.args.get('url_id', 1)
    # Fetch all run ids.
    run_ids = fetch_run_ids()
    # Fetch details about the url
    crawl_urls = fetch_url(url_id)
    url = crawl_urls[0]
    lint_results = json.loads(url.get('lint_results'))
    # Fetch associated links.
    from_links = fetch_from_links(url_id)
    to_links = fetch_to_links(url_id)

    return render_template('url.html',
        run_ids=run_ids,
        run_id=url.get('run_id'),
        url_id=url_id,
        url=url,
        from_links=from_links,
        to_links=to_links,
        lint_results=lint_results,
        lint_desc=lint_desc,
        lint_level=lint_level,
    )

@app.route("/delete/")
def delete():
    run_id = request.args.get('run_id', fetch_latest_run_id())
    delete_run(run_id)
    return redirect('/')

def main():
    global db
    global app

    parser = optparse.OptionParser(description='SEO Dashboard presents crawl data viewable in the browser.')
    parser.add_option('--database', type="string", default='config.yaml',
        help='A yaml configuration file with the database configuration properties.')
    parser.add_option('--host', type="string", default='127.0.0.1',
        help='IP address to listen to. e.g.: 0.0.0.0 to listen to all interfaces. (default t0 127.0.0.1)')
    parser.add_option('--port', type="string", default='5000',
        help='Port to listen to. (default to 5000)')
    args = parser.parse_args()[0]

    # Try to open the config file.
    try:
        with open(args.database) as f:
            env = yaml.load(f)
    except IOError as e:
        print(str(e))
        exit(1)

    # Initialize the database cursor
    db_conf = env.get('db', {})
    app.config['MYSQL_HOST'] = db_conf.get('host')
    app.config['MYSQL_USER'] = db_conf.get('user')
    app.config['MYSQL_PASSWORD'] = db_conf.get('pass')
    app.config['MYSQL_DB'] = db_conf.get('name')
    app.config['MYSQL_USE_UNICODE'] = True
    db.init_app(app)

    app.run(host=args.host, port=int(args.port), debug=True)

if __name__ == "__main__":
    main()


text:
package android.coolweather.com.coolweather.gson;

import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
 * Created by hackywit on 2017/3/31.
 */

public class Weather {
    public String status;
    public Basic basic;
    public AQI aqi;
    public Now now;
    public Suggestion suggestion;
    @SerializedName("daily_forecast")//这边我少写了一个e,导致隐射没有建立,也就是根本没有forecastList对象,所以遍历查找的时候出现找不到对象,就闪退了
    public List<Forecast> forecastList;
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using EventEmitter.AdminServices.Models;

namespace EventEmitter.AdminServices.Interfaces
{
    public interface IUserAdmin
    {
        void UpdateUserType(Guid userId, Guid newUserType);
        IEnumerable<User> GetPage(int page);
    }
}


text:
Accounts.emailTemplates.siteName = "TechChapsPortal";
Accounts.emailTemplates.from = "no-reply@techchaps.com";
Accounts.emailTemplates.enrollAccount.subject = function(user) {
    return "Password Reset Instruction, " + user.profile.name;
};
Accounts.emailTemplates.enrollAccount.text = function(user, url) {
    var forgetPasswordUrl = url.replace("#/", "");

    return "To activate your account, simply click the link below:\n\n"
            + forgetPasswordUrl + "http://localhost/" + "\n\n"
            + "Please disregard this email if you have not requested password recovery.\n\n"
            + "Thanks, TechChapsPortal Team";
};

Meteor.startup(function() {
    process.env.MAIL_URL = 'smtp://postmaster@sandbox44239.mailgun.org:95p6917kjti7@smtp.mailgun.org:587';
});


text:
<?php

namespace Spatie\Backup\Notifications\Senders;

use Maknz\Slack\Client;
use Illuminate\Contracts\Config\Repository;
use Spatie\Backup\Notifications\BaseSender;

class Slack extends BaseSender
{
    /** @var \Maknz\Slack\Client */
    protected $client;

    /** @var array */
    protected $config;

    /**
     * @param \Maknz\Slack\Client $client
     * @param Repository          $config
     */
    public function __construct(Client $client, Repository $config)
    {
        $this->config = $config->get('laravel-backup.notifications.slack');

        $client->setDefaultUsername($this->config['username']);
        $client->setDefaultIcon($this->config['icon']);

        $this->client = $client;
    }

    public function send()
    {
        $this->client
            ->to($this->config['channel'])
            ->attach([
                'text' => $this->message,
                'color' => $this->type === static::TYPE_SUCCESS ? 'good' : 'warning',
            ])
            ->send($this->subject);
    }
}


text:
package com.sun.tools.internal.xjc.reader.gbind;

import java.util.Collections;
import java.util.Iterator;

/**
 * A set over a list of {@link Element}.
 *
 * @author Kohsuke Kawaguchi
 */
interface ElementSet extends Iterable<Element> {
    /**
     * For each element in this set, adds an edge to the given element.
     */
    void addNext(Element element);

    public static final ElementSet EMPTY_SET = new ElementSet() {
        public void addNext(Element element) {
            // noop
        }

        public boolean contains(ElementSet element) {
            return this==element;
        }

        public Iterator<Element> iterator() {
            return Collections.<Element>emptySet().iterator();
        }
    };

    /**
     * Doesn't have to be strict (it's OK for this method to return false
     * when it's actually true) since this is used just for optimization.
     *
     * (Erring on the other side is NG)
     */
    boolean contains(ElementSet rhs);
}


text:
#include "gep/interfaces/logging.h"

namespace gpp
{
    class DummyLogging : public gep::ILogging
    {
    public:
        static DummyLogging& instance()
        {
            static DummyLogging defaultInstance;
            return defaultInstance;
        }

        virtual void logMessage(GEP_PRINTF_FORMAT_STRING const char* fmt, ...) override {}
        virtual void logWarning(GEP_PRINTF_FORMAT_STRING const char* fmt, ...) override {}
        virtual void logError(GEP_PRINTF_FORMAT_STRING const char* fmt, ...) override {}

        virtual void registerSink(gep::ILogSink* pSink) override {}
        virtual void deregisterSink(gep::ILogSink* pSink) override {}
    };
}


text:
import java.util.*;

public class CollectionAlgorithms {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            list.add((int) (Math.random() * 100));
        }
        Collections.sort(list);
        System.out.println("Sorted Array: " + list);
        int testNumber = 10;
        int index = Collections.binarySearch(list, testNumber);
        if (index >= 0) {
            System.out.println("Number " + testNumber
                    + " found at index: " + index);
        } else {
            System.out.println("Number " + testNumber + " not found");
        }
        System.out.println("Max number: " + Collections.max(list));
        System.out.println("Min number: " + Collections.min(list));
        System.out.println("Frequency of " + testNumber + ": "
                + Collections.frequency(list, testNumber));
        Set<Integer> sortedList = new HashSet<>();
        sortedList.addAll(list);
        System.out.println("Number of distinct elements: " + sortedList.size());
        list.clear();
        list.addAll(sortedList);
        Collections.shuffle(list);
        List<Integer> topTenList = list.subList(0, 10);
        Collections.sort(topTenList);
        System.out.println("Top 10: " + topTenList);
    }
}


text:
static NSString * const kRequiredHostname = @"navigate";
static NSString * const kPrimaryURLKey = @"primaryUrl";
static NSString * const kPrimaryTrackingURLKey = @"primaryTrackingUrl";
static NSString * const kFallbackURLKey = @"fallbackUrl";
static NSString * const kFallbackTrackingURLKey = @"fallbackTrackingUrl";

////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation MPEnhancedDeeplinkRequest

- (instancetype)initWithURL:(NSURL *)URL
{
    self = [super init];
    if (self) {
        if (![[[URL host] lowercaseString] isEqualToString:kRequiredHostname]) {
            return nil;
        }

        NSString *primaryURLString = [URL mp_queryParameterForKey:kPrimaryURLKey];
        if (![primaryURLString length]) {
            return nil;
        }
        _primaryURL = [NSURL URLWithString:primaryURLString];
        _originalURL = [URL copy];

        NSMutableArray *primaryTrackingURLs = [NSMutableArray array];
        NSArray *primaryTrackingURLStrings = [URL mp_queryParametersForKey:kPrimaryTrackingURLKey];
        for (NSString *URLString in primaryTrackingURLStrings) {
            [primaryTrackingURLs addObject:[NSURL URLWithString:URLString]];
        }
        _primaryTrackingURLs = [NSArray arrayWithArray:primaryTrackingURLs];

        NSString *fallbackURLString = [URL mp_queryParameterForKey:kFallbackURLKey];
        _fallbackURL = [NSURL URLWithString:fallbackURLString];

        NSMutableArray *fallbackTrackingURLs = [NSMutableArray array];
        NSArray *fallbackTrackingURLStrings = [URL mp_queryParametersForKey:kFallbackTrackingURLKey];
        for (NSString *URLString in fallbackTrackingURLStrings) {
            [fallbackTrackingURLs addObject:[NSURL URLWithString:URLString]];
        }
        _fallbackTrackingURLs = [NSArray arrayWithArray:fallbackTrackingURLs];
    }
    return self;
}

@end


text:
// render.cpp
#include "renderer-shared.h"
#include "../../source/core/slang-math.h"
#include "../../source/core/slang-blob.h"
#include "open-gl/render-gl.h"
#include "debug-layer/debug-device.h"

#include <cstring>

namespace gfx {
using namespace Slang;

Result SLANG_MCALL createD3D11Device(const IDevice::Desc* desc, IDevice** outDevice);
Result SLANG_MCALL createD3D12Device(const IDevice::Desc* desc, IDevice** outDevice);
Result SLANG_MCALL createVKDevice(const IDevice::Desc* desc, IDevice** outDevice);
Result SLANG_MCALL createCUDADevice(const IDevice::Desc* desc, IDevice** outDevice);
Result SLANG_MCALL createCPUDevice(const IDevice::Desc* desc, IDevice** outDevice);

Result SLANG_MCALL getD3D11Adapters(List<AdapterInfo>& outAdapters);
Result SLANG_MCALL getD3D12Adapters(List<AdapterInfo>& outAdapters);
Result SLANG_MCALL getVKAdapters(List<AdapterInfo>& outAdapters);
Result SLANG_MCALL getCUDAAdapters(List<AdapterInfo>& outAdapters);

static bool debugLayerEnabled = false;
bool isGfxDebugLayerEnabled() { return debugLayerEnabled; }

/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Global Renderer Functions !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */

#define GFX_FORMAT_SIZE(name, blockSizeInBytes, pixelsPerBlock) {blockSizeInBytes, pixelsPerBlock},

static const uint32_t s_formatSizeInfo[][2] =
{
    GFX_FORMAT(GFX_FORMAT_SIZE)
};

static bool _checkFormat()
{
    Index value = 0;
    Index count = 0;

    // Check the values are in the same order
#define GFX_FORMAT_CHECK(name, blockSizeInBytes, pixelsPerblock) count += Index(Index(Format::name) == value++);
    GFX_FORMAT(GFX_FORMAT_CHECK)

    const bool r = (count == Index(Format::_Count));
    SLANG_ASSERT(r);
    return r;
}

// We don't make static because we will get a warning that it's unused
static const bool _checkFormatResult = _checkFormat();

struct FormatInfoMap
{
    FormatInfoMap()
    {
        // Set all to nothing initially
        for (auto& info : m_infos)
        {
            info.channelCount = 0;
            info.channelType = SLANG_SCALAR_TYPE_NONE;
        }

        set(Format::R32G32B32A32_TYPELESS, SLANG_SCALAR_TYPE_UINT32, 4);
        set(Format::R32G32B32_TYPELESS, SLANG_SCALAR_TYPE_UINT32, 3);
        set(Format::R32G32_TYPELESS, SLANG_SCALAR_TYPE_UINT32, 2);
        set(Format::R32_TYPELESS, SLANG_SCALAR_TYPE_UINT32, 1);

        set(Format::R16G16B16A16_TYPELESS, SLANG_SCALAR_TYPE_UINT16, 4);
        set(Format::R16G16_TYPELESS, SLANG_SCALAR_TYPE_UINT16, 2);
        set(Format::R16_TYPELESS, SLANG_SCALAR_TYPE_UINT16, 1);

        set(Format::R8G8B8A8_TYPELESS, SLANG_SCALAR_TYPE_UINT8, 4);
        set(Format::R8G8_TYPELESS, SLANG_SCALAR_TYPE_UINT8, 2);
        set(Format::R8_TYPELESS, SLANG_SCALAR_TYPE_UINT8, 1);
        set(Format::B8G8R8A8_TYPELESS, SLANG_SCALAR_TYPE_UINT8, 4);

        set(Format::R32G32B32A32_FLOAT, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::R32G32B32_FLOAT, SLANG_SCALAR_TYPE_FLOAT32, 3);
        set(Format::R32G32_FLOAT, SLANG_SCALAR_TYPE_FLOAT32, 2);
        set(Format::R32_FLOAT, SLANG_SCALAR_TYPE_FLOAT32, 1);

        set(Format::R16G16B16A16_FLOAT, SLANG_SCALAR_TYPE_FLOAT16, 4);
        set(Format::R16G16_FLOAT, SLANG_SCALAR_TYPE_FLOAT16, 2);
        set(Format::R16_FLOAT, SLANG_SCALAR_TYPE_FLOAT16, 1);

        set(Format::R32G32B32A32_UINT, SLANG_SCALAR_TYPE_UINT32, 4);
        set(Format::R32G32B32_UINT, SLANG_SCALAR_TYPE_UINT32, 3);
        set(Format::R32G32_UINT, SLANG_SCALAR_TYPE_UINT32, 2);
        set(Format::R32_UINT, SLANG_SCALAR_TYPE_UINT32, 1);

        set(Format::R16G16B16A16_UINT, SLANG_SCALAR_TYPE_UINT16, 4);
        set(Format::R16G16_UINT, SLANG_SCALAR_TYPE_UINT16, 2);
        set(Format::R16_UINT, SLANG_SCALAR_TYPE_UINT16, 1);

        set(Format::R8G8B8A8_UINT, SLANG_SCALAR_TYPE_UINT8, 4);
        set(Format::R8G8_UINT, SLANG_SCALAR_TYPE_UINT8, 2);
        set(Format::R8_UINT, SLANG_SCALAR_TYPE_UINT8, 1);

        set(Format::R32G32B32A32_SINT, SLANG_SCALAR_TYPE_INT32, 4);
        set(Format::R32G32B32_SINT, SLANG_SCALAR_TYPE_INT32, 3);
        set(Format::R32G32_SINT, SLANG_SCALAR_TYPE_INT32, 2);
        set(Format::R32_SINT, SLANG_SCALAR_TYPE_INT32, 1);

        set(Format::R16G16B16A16_SINT, SLANG_SCALAR_TYPE_INT16, 4);
        set(Format::R16G16_SINT, SLANG_SCALAR_TYPE_INT16, 2);
        set(Format::R16_SINT, SLANG_SCALAR_TYPE_INT16, 1);

        set(Format::R8G8B8A8_SINT, SLANG_SCALAR_TYPE_INT8, 4);
        set(Format::R8G8_SINT, SLANG_SCALAR_TYPE_INT8, 2);
        set(Format::R8_SINT, SLANG_SCALAR_TYPE_INT8, 1);

        set(Format::R16G16B16A16_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::R16G16_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 2);
        set(Format::R16_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 1);

        set(Format::R8G8B8A8_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::R8G8B8A8_UNORM_SRGB, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::R8G8_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 2);
        set(Format::R8_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 1);
        set(Format::B8G8R8A8_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::B8G8R8A8_UNORM_SRGB, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::B8G8R8X8_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::B8G8R8X8_UNORM_SRGB, SLANG_SCALAR_TYPE_FLOAT32, 4);

        set(Format::R16G16B16A16_SNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::R16G16_SNORM, SLANG_SCALAR_TYPE_FLOAT32, 2);
        set(Format::R16_SNORM, SLANG_SCALAR_TYPE_FLOAT32, 1);

        set(Format::R8G8B8A8_SNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::R8G8_SNORM, SLANG_SCALAR_TYPE_FLOAT32, 2);
        set(Format::R8_SNORM, SLANG_SCALAR_TYPE_FLOAT32, 1);

        set(Format::D32_FLOAT, SLANG_SCALAR_TYPE_FLOAT32, 1);
        set(Format::D16_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 1);

        set(Format::B4G4R4A4_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::B5G6R5_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 3);
        set(Format::B5G5R5A1_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);

        set(Format::R9G9B9E5_SHAREDEXP, SLANG_SCALAR_TYPE_FLOAT32, 3);
        set(Format::R10G10B10A2_TYPELESS, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::R10G10B10A2_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4);
        set(Format::R10G10B10A2_UINT, SLANG_SCALAR_TYPE_UINT32, 4);
        set(Format::R11G11B10_FLOAT, SLANG_SCALAR_TYPE_FLOAT32, 3);

        set(Format::BC1_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
        set(Format::BC1_UNORM_SRGB, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
        set(Format::BC2_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
        set(Format::BC2_UNORM_SRGB, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
        set(Format::BC3_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
        set(Format::BC3_UNORM_SRGB, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
        set(Format::BC4_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 1, 4, 4);
        set(Format::BC4_SNORM, SLANG_SCALAR_TYPE_FLOAT32, 1, 4, 4);
        set(Format::BC5_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 2, 4, 4);
        set(Format::BC5_SNORM, SLANG_SCALAR_TYPE_FLOAT32, 2, 4, 4);
        set(Format::BC6H_UF16, SLANG_SCALAR_TYPE_FLOAT32, 3, 4, 4);
        set(Format::BC6H_SF16, SLANG_SCALAR_TYPE_FLOAT32, 3, 4, 4);
        set(Format::BC7_UNORM, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
        set(Format::BC7_UNORM_SRGB, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
    }

    void set(Format format, SlangScalarType type, Index channelCount, uint32_t blockWidth = 1, uint32_t blockHeight = 1)
    {
        FormatInfo& info = m_infos[Index(format)];
        info.channelCount = uint8_t(channelCount);
        info.channelType = uint8_t(type);

        auto sizeInfo = s_formatSizeInfo[Index(format)];
        info.blockSizeInBytes = sizeInfo[0];
        info.pixelsPerBlock = sizeInfo[1];
        info.blockWidth = blockWidth;
        info.blockHeight = blockHeight;
    }

    const FormatInfo& get(Format format) const { return m_infos[Index(format)]; }

    FormatInfo m_infos[Index(Format::_Count)];
};

static const FormatInfoMap s_formatInfoMap;

static void _compileTimeAsserts()
{
    SLANG_COMPILE_TIME_ASSERT(SLANG_COUNT_OF(s_formatSizeInfo) == int(Format::_Count));
}

extern "C"
{
    SLANG_GFX_API bool SLANG_MCALL gfxIsCompressedFormat(Format format)
    {
        switch (format)
        {
        case Format::BC1_UNORM:
        case Format::BC1_UNORM_SRGB:
        case Format::BC2_UNORM:
        case Format::BC2_UNORM_SRGB:
        case Format::BC3_UNORM:
        case Format::BC3_UNORM_SRGB:
        case Format::BC4_UNORM:
        case Format::BC4_SNORM:
        case Format::BC5_UNORM:
        case Format::BC5_SNORM:
        case Format::BC6H_UF16:
        case Format::BC6H_SF16:
        case Format::BC7_UNORM:
        case Format::BC7_UNORM_SRGB:
            return true;
        default:
            return false;
        }
    }

    SLANG_GFX_API bool SLANG_MCALL gfxIsTypelessFormat(Format format)
    {
        switch (format)
        {
        case Format::R32G32B32A32_TYPELESS:
        case Format::R32G32B32_TYPELESS:
        case Format::R32G32_TYPELESS:
        case Format::R32_TYPELESS:
        case Format::R16G16B16A16_TYPELESS:
        case Format::R16G16_TYPELESS:
        case Format::R16_TYPELESS:
        case Format::R8G8B8A8_TYPELESS:
        case Format::R8G8_TYPELESS:
        case Format::R8_TYPELESS:
        case Format::B8G8R8A8_TYPELESS:
        case Format::R10G10B10A2_TYPELESS:
            return true;
        default:
            return false;
        }
    }

    SLANG_GFX_API SlangResult SLANG_MCALL gfxGetFormatInfo(Format format, FormatInfo* outInfo)
    {
        *outInfo = s_formatInfoMap.get(format);
        return SLANG_OK;
    }

    SLANG_GFX_API SlangResult SLANG_MCALL gfxGetAdapters(DeviceType type, ISlangBlob** outAdaptersBlob)
    {
        List<AdapterInfo> adapters;

        switch (type)
        {
#if SLANG_WINDOWS_FAMILY
        case DeviceType::DirectX11:
            SLANG_RETURN_ON_FAIL(getD3D11Adapters(adapters));
            break;
        case DeviceType::DirectX12:
            SLANG_RETURN_ON_FAIL(getD3D12Adapters(adapters));
            break;
        case DeviceType::OpenGl:
            return SLANG_E_NOT_IMPLEMENTED;
        case DeviceType::Vulkan:
            SLANG_RETURN_ON_FAIL(getVKAdapters(adapters));
            break;
        case DeviceType::CUDA:
            SLANG_RETURN_ON_FAIL(getCUDAAdapters(adapters));
            break;
#elif SLANG_LINUX_FAMILY && !defined(__CYGWIN__)
        case DeviceType::Vulkan:
            SLANG_RETURN_ON_FAIL(getVKAdapters(adapters));
            break;
        case DeviceType::CUDA:
            SLANG_RETURN_ON_FAIL(getCUDAAdapters(adapters));
            break;
#endif
        case DeviceType::CPU:
            return SLANG_E_NOT_IMPLEMENTED;
        default:
            return SLANG_E_INVALID_ARG;
        }

        auto adaptersBlob = RawBlob::create(adapters.getBuffer(), adapters.getCount() * sizeof(AdapterInfo));
        if (outAdaptersBlob)
            returnComPtr(outAdaptersBlob, adaptersBlob);

        return SLANG_OK;
    }

    SlangResult _createDevice(const IDevice::Desc* desc, IDevice** outDevice)
    {
        switch (desc->deviceType)
        {
#if SLANG_WINDOWS_FAMILY
        case DeviceType::DirectX11:
            {
                return createD3D11Device(desc, outDevice);
            }
        case DeviceType::DirectX12:
            {
                return createD3D12Device(desc, outDevice);
            }
        case DeviceType::OpenGl:
            {
                return createGLDevice(desc, outDevice);
            }
        case DeviceType::Vulkan:
            {
                return createVKDevice(desc, outDevice);
            }
        case DeviceType::CUDA:
            {
                return createCUDADevice(desc, outDevice);
            }
        case DeviceType::Default:
            {
                IDevice::Desc newDesc = *desc;
                newDesc.deviceType = DeviceType::DirectX12;
                if (_createDevice(&newDesc, outDevice) == SLANG_OK)
                    return SLANG_OK;
                newDesc.deviceType = DeviceType::Vulkan;
                if (_createDevice(&newDesc, outDevice) == SLANG_OK)
                    return SLANG_OK;
                newDesc.deviceType = DeviceType::DirectX11;
                if (_createDevice(&newDesc, outDevice) == SLANG_OK)
                    return SLANG_OK;
                newDesc.deviceType = DeviceType::OpenGl;
                if (_createDevice(&newDesc, outDevice) == SLANG_OK)
                    return SLANG_OK;
                return SLANG_FAIL;
            }
            break;
#elif SLANG_LINUX_FAMILY && !defined(__CYGWIN__)
        case DeviceType::Default:
        case DeviceType::Vulkan:
        {
            return createVKDevice(desc, outDevice);
        }
        case DeviceType::CUDA:
        {
            return createCUDADevice(desc, outDevice);
        }
#endif
        case DeviceType::CPU:
            {
                return createCPUDevice(desc, outDevice);
            }
            break;

        default:
            return SLANG_FAIL;
        }
    }

    SLANG_GFX_API SlangResult SLANG_MCALL
        gfxCreateDevice(const IDevice::Desc* desc, IDevice** outDevice)
    {
        ComPtr<IDevice> innerDevice;
        auto resultCode = _createDevice(desc, innerDevice.writeRef());
        if (SLANG_FAILED(resultCode))
            return resultCode;
        if (!debugLayerEnabled)
        {
            returnComPtr(outDevice, innerDevice);
            return resultCode;
        }
        RefPtr<debug::DebugDevice> debugDevice = new debug::DebugDevice();
        debugDevice->baseObject = innerDevice;
        returnComPtr(outDevice, debugDevice);
        return resultCode;
    }

    SLANG_GFX_API SlangResult SLANG_MCALL gfxSetDebugCallback(IDebugCallback* callback)
    {
        _getDebugCallback() = callback;
        return SLANG_OK;
    }

    SLANG_GFX_API void SLANG_MCALL gfxEnableDebugLayer()
    {
        debugLayerEnabled = true;
    }

    const char* SLANG_MCALL gfxGetDeviceTypeName(DeviceType type)
    {
        switch (type)
        {
        case gfx::DeviceType::Unknown:
            return "Unknown";
        case gfx::DeviceType::Default:
            return "Default";
        case gfx::DeviceType::DirectX11:
            return "DirectX11";
        case gfx::DeviceType::DirectX12:
            return "DirectX12";
        case gfx::DeviceType::OpenGl:
            return "OpenGL";
        case gfx::DeviceType::Vulkan:
            return "Vulkan";
        case gfx::DeviceType::CPU:
            return "CPU";
        case gfx::DeviceType::CUDA:
            return "CUDA";
        default:
            return "?";
        }
    }

    void SLANG_MCALL gfxGetIdentityProjection(ProjectionStyle style, float projMatrix[16])
    {
        switch (style)
        {
        case ProjectionStyle::DirectX:
        case ProjectionStyle::OpenGl:
            {
                static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
                ::memcpy(projMatrix, kIdentity, sizeof(kIdentity));
                break;
            }
        case ProjectionStyle::Vulkan:
            {
                static const float kIdentity[] = {1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
                ::memcpy(projMatrix, kIdentity, sizeof(kIdentity));
                break;
            }
        default:
            {
                assert(!"Not handled");
            }
        }
    }
}

} // renderer_test


text:
layout: post
title: Comparison of Hybrid Mobile App Javascript Frameworks
---

[Zak](http://totalgood.org/bicycle) and [I](http://totalgood.org/hope) are building frontends for DRF that we'd like to go mobile with eventually.

So choosing between React and Angular hinges on the hybrid app framework alternatives (ReactNative or Ionic).

Ionic is more mature but it's app ["showcase"](http://ionicframework.com/) is no more impressive than [ReactNative](https://facebook.github.io/react-native/showcase.html)'s

So I guess I'll go with the latest hottness (React) and let Zak use the more standard Angular.


text:
<?php

namespace Auth\Form;

use Zend\Form\Form;
use Zend\Form\Element\Captcha;
use Zend\Captcha\AdapterInterface as CaptchaAdapter;
use Zend\Captcha\Image as CaptchaImage;
use Zend\Form\Element;

class EsqueciSenhaForm extends Form {

    public function __construct($dircaptcha = null, $urlcaptcha = null) {
        parent::__construct('Test Form Captcha');
        $this->setAttribute('method', 'post');

        $this->add(array(
            'name' => 'email',
            'attributes' => array(
                'type' => 'email',
            ),
            'options' => array(
                'label' => 'Informe o e-mail cadastrado:',
            ),
            'attributes' => array(
                'required' => 'required'
            ),
            'filters' => array(
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'EmailAddress',
                    'options' => array(
                        'messages' => array(\Zend\Validator\EmailAddress::INVALID_FORMAT => 'O formato inválido'
                        )
                    )
                )
            )
        ));

        $dirdata = './data';

        //pass captcha image options
        $captchaImage = new CaptchaImage(array(
            'font' => $dirdata . '/fonts/arial.ttf',
            'width' => 150,
            'height' => 60,
            'dotNoiseLevel' => 40,
            'lineNoiseLevel' => 3)
        );

        $captchaImage->setImgDir($dircaptcha);

        //var_dump($urlcaptcha);
        $captchaImage->setImgUrl($urlcaptcha);

        //add captcha element...
        $this->add(array(
            'type' => 'Zend\Form\Element\Captcha',
            'name' => 'captcha',
            'options' => array(
                'label' => 'Digite os caracteres abaixo',
                'captcha' => $captchaImage,
            ),
        ));

        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type' => 'submit',
                'value' => 'Enviar nova senha'
            ),
        ));
    }

}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Multi Step Form</title>

<link href="jquery-multi-step-form.css" media="screen" rel="stylesheet" type="text/css"/>

Account Setup

Social Profiles

Personal Details

        <form action="">

Create your account

This is step 1

		<input type="text" name="email" placeholder="Email">
		<input type="password" name="pass" placeholder="Password">
		<input type="password" name="cpass" placeholder="Confirm Password">
		<input type="button" name="next" class="next button" value="Next">
        </form>

        <form action="">

Social Profiles

Your presence on the social network

		<input type="text" name="twitter" placeholder="Twitter">
		<input type="text" name="facebook" placeholder="Facebook">
		<input type="text" name="gplus" placeholder="Google Plus">
		<input type="button" name="previous" class="previous button" value="Previous">
		<input type="button" name="next" class="next button" value="Next">
        </form>

        <form action="">

Personal Details

We will never sell it

		<input type="text" name="fname" placeholder="First Name">
		<input type="text" name="lname" placeholder="Last Name">
		<input type="text" name="phone" placeholder="Phone">
		<textarea name="address" placeholder="Address"></textarea>
		<input type="button" name="previous" class="previous button" value="Previous">
		<input type="button" name="submit" class="next button" value="Finish">
        </form>


text:
Analog_output
=============

Here we have programs that demonstrate analog output.

**analog.c** is a program that uses software delay() calls in loop() to write
a symmetric sawtooth output voltage on DAC output pin A14.  The layout used is:

.. image:: breadboard1.png
    :width: 295
    :height: 440
    :alt: circuit used to test DAC output (http://fritzing.org/)

Note a great example, but the best I can come up with for the moment.


text:
package shim

import (
	"bufio"
	"fmt"
	"sync"
	"time"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/agent"
	"github.com/influxdata/telegraf/plugins/parsers"
	"github.com/influxdata/telegraf/plugins/processors"
)

// AddProcessor adds the processor to the shim. Later calls to Run() will run this.
func (s *Shim) AddProcessor(processor telegraf.Processor) error {
	p := processors.NewStreamingProcessorFromProcessor(processor)
	return s.AddStreamingProcessor(p)
}

// AddStreamingProcessor adds the processor to the shim. Later calls to Run() will run this.
func (s *Shim) AddStreamingProcessor(processor telegraf.StreamingProcessor) error {
	if p, ok := processor.(telegraf.Initializer); ok {
		err := p.Init()
		if err != nil {
			return fmt.Errorf("failed to init input: %s", err)
		}
	}

	s.Processor = processor
	return nil
}

func (s *Shim) RunProcessor() error {
	acc := agent.NewAccumulator(s, s.metricCh)
	acc.SetPrecision(time.Nanosecond)

	parser, err := parsers.NewInfluxParser()
	if err != nil {
		return fmt.Errorf("Failed to create new parser: %w", err)
	}

	err = s.Processor.Start(acc)
	if err != nil {
		return fmt.Errorf("failed to start processor: %w", err)
	}

	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		s.writeProcessedMetrics()
		wg.Done()
	}()

	scanner := bufio.NewScanner(s.stdin)
	for scanner.Scan() {
		m, err := parser.ParseLine(scanner.Text())
		if err != nil {
			fmt.Fprintf(s.stderr, "Failed to parse metric: %s\b", err)
			continue
		}
		s.Processor.Add(m, acc)
	}

	close(s.metricCh)
	s.Processor.Stop()
	wg.Wait()
	return nil
}


text:
using System;

namespace UniversalDetector.Core
{
    /// <summary>
    /// State machine model
    /// </summary>
    public abstract class SMModel
    {
        public const int START = 0;
        public const int ERROR = 1;
        public const int ITSME = 2;

        public BitPackage classTable;
        public BitPackage stateTable;
        public int[] charLenTable;

        private string name;

        public string Name {
            get { return name;  }
        }

        private int classFactor;

        public int ClassFactor {
            get { return classFactor;  }
        }

        public SMModel(BitPackage classTable, int classFactor,
            BitPackage stateTable, int[] charLenTable, String name)
        {
            this.classTable = classTable;
            this.classFactor = classFactor;
            this.stateTable = stateTable;
            this.charLenTable = charLenTable;
            this.name = name;
        }

        public int GetClass(byte b)
        {
            return classTable.Unpack((int)b);
        }
    }
}


text:
<?php

/* SdzBlogBundle:Blog:voir.html.twig */
class __TwigTemplate_8601fc31f0393e86f7ca82f7c2800cfa extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("SdzBlogBundle::layout.html.twig");

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'sdzblog_body' => array($this, 'block_sdzblog_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "SdzBlogBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 5
    public function block_title($context, array $blocks = array())
    {
        // line 6
        echo "  Lecture d'un article - ";
        $this->displayParentBlock("title", $context, $blocks);
        echo "
";
    }

    // line 9
    public function block_sdzblog_body($context, array $blocks = array())
    {
        // line 10
        echo "

";
        // line 11
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "titre"), "html", null, true);
        echo "

  Par ";
        // line 12
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "auteur"), "html", null, true);
        echo ", le ";
        echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "date"), "d/m/Y"), "html", null, true);
        echo "

    ";
        // line 15
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "contenu"), "html", null, true);
        echo "

    env, $this->env->getExtension('routing')->getPath("sdzblog_accueil"), "html", null, true);
        echo "\" class=\"btn\">

      Retour à la liste

    env, $this->env->getExtension('routing')->getPath("sdzblog_modifier", array("id" => $this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "id"))), "html", null, true);
        echo "\" class=\"btn\">

      Modifier l'article

    env, $this->env->getExtension('routing')->getPath("sdzblog_supprimer", array("id" => $this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "id"))), "html", null, true);
        echo "\" class=\"btn\">

      Supprimer l'article

";
    }

    public function getTemplateName()
    {
        return "SdzBlogBundle:Blog:voir.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  78 => 27,  71 => 23,  64 => 19,  57 => 15,  49 => 12,  45 => 11,  42 => 10,  39 => 9,  32 => 6,  29 => 5,);
    }
}


text:
simple storage and access of private values, powered by WeakMaps

## Example

```js
const createInternal = require('create-internal');

// never export `internal`,
// as any code with access to it can access the "private" data within
const internal = createInternal();

class MyClass {
  constructor () {
    Object.assign(internal(this), {
      // accessible to code with this exact `internal` in scope
      privateProperty: 'value'
    });
    Object.assign(this, {
      // accessible to any code that can access the constructed object
      publicProperty: 'value'
    });
  }

  method () {
    const { privateProperty } = internal(this);
    // TODO: do something with privateProperty
  }
}
```

## Usage

We use [`WeakMap`s](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) as the underlying store, which means that any value that is not a [primitive type](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) can be a key, e.g. `Object`, `Array`, `Map`, `Set`, `Function`, etc

### `createInternal()`

returns a function that takes an object and returns a private object associated with it

```js
const createInternal = require('create-internal');
const internal = createInternal(); // never export this

const publicObject = {};
const privateObject = internal(publicObject);
privateObject.privateProperty = 'privateValue';
```

### `createMapInternal()`

returns a function that takes an object and returns a private `Map` associated with it

```js
const { createMapInternal } = require('create-internal');
const internal = createMapInternal(); // never export this

const publicObject = {};
const privateMap = internal(publicObject);
privateMap.set('privateProperty', 'privateValue');
```

## See Also

-   [Mozilla contributor's guide for private properties](https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Contributor_s_Guide/Private_Properties)

-   [namespace](https://www.npmjs.com/package/namespace)


text:
class GuiImageButtonCtrl : public GuiButtonCtrl
{
private:
   typedef GuiButtonCtrl Parent;

protected:
    StringTableEntry                mNormalAssetId;
    StringTableEntry                mHoverAssetId;
    StringTableEntry                mDownAssetId;
    StringTableEntry                mInactiveAssetId;

    AssetPtr<ImageAsset>  mImageNormalAsset;
    AssetPtr<ImageAsset>  mImageHoverAsset;
    AssetPtr<ImageAsset>  mImageDownAsset;
    AssetPtr<ImageAsset>  mImageInactiveAsset;

    void renderButton( ImageAsset* pImageAsset, const U32 frame, Point2I &offset, const RectI& updateRect);

protected:
    enum ButtonState
    {
        NORMAL,
        HOVER,
        DOWN,
        INACTIVE
    };

public:
   GuiImageButtonCtrl();
   bool onWake();
   void onSleep();
   void onRender(Point2I offset, const RectI &updateRect);

   static void initPersistFields();

   void setNormalImage( const char* pImageAssetId );
   inline StringTableEntry getNormalImage( void ) const { return mNormalAssetId; }
   void setHoverImage( const char* pImageAssetId );
   inline StringTableEntry getHoverImage( void ) const { return mHoverAssetId; }
   void setDownImage( const char* pImageAssetId );
   inline StringTableEntry getDownImage( void ) const { return mDownAssetId; }
   void setInactiveImage( const char* pImageAssetId );
   inline StringTableEntry getInactiveImage( void ) const { return mInactiveAssetId; }

   // Declare type.
   DECLARE_CONOBJECT(GuiImageButtonCtrl);

protected:
    static bool setNormalImage(void* obj, const char* data) { static_cast<GuiImageButtonCtrl*>(obj)->setNormalImage( data ); return false; }
    static const char* getNormalImage(void* obj, const char* data) { return static_cast<GuiImageButtonCtrl*>(obj)->getNormalImage(); }
    static bool setHoverImage(void* obj, const char* data) { static_cast<GuiImageButtonCtrl*>(obj)->setHoverImage( data ); return false; }
    static const char* getHoverImage(void* obj, const char* data) { return static_cast<GuiImageButtonCtrl*>(obj)->getHoverImage(); }
    static bool setDownImage(void* obj, const char* data) { static_cast<GuiImageButtonCtrl*>(obj)->setDownImage( data ); return false; }
    static const char* getDownImage(void* obj, const char* data) { return static_cast<GuiImageButtonCtrl*>(obj)->getDownImage(); }
    static bool setInactiveImage(void* obj, const char* data) { static_cast<GuiImageButtonCtrl*>(obj)->setInactiveImage( data ); return false; }
    static const char* getInactiveImage(void* obj, const char* data) { return static_cast<GuiImageButtonCtrl*>(obj)->getInactiveImage(); }
};

#endif //_GUIIMAGEBUTTON_H_


text:
#include "indexer/geometry_coding.hpp"

#include "base/assert.hpp"
#include "base/stl_add.hpp"

#include "std/complex.hpp"
#include "std/vector.hpp"

namespace
{
  inline m2::PointU ClampPoint(m2::PointU const & maxPoint, m2::Point<double> const & point)
  {
    typedef m2::PointU::value_type uvalue_t;
    //return m2::PointU(my::clamp(static_cast<uvalue_t>(point.x), static_cast<uvalue_t>(0), maxPoint.x),
    //                  my::clamp(static_cast<uvalue_t>(point.y), static_cast<uvalue_t>(0), maxPoint.y));

    return m2::PointU(static_cast<uvalue_t>(my::clamp(point.x, 0.0, static_cast<double>(maxPoint.x))),
                      static_cast<uvalue_t>(my::clamp(point.y, 0.0, static_cast<double>(maxPoint.y))));
  }
}

m2::PointU PredictPointInPolyline(m2::PointU const & maxPoint,
                                  m2::PointU const & p1,
                                  m2::PointU const & p2)
{
  // return ClampPoint(maxPoint, m2::PointI64(p1) + m2::PointI64(p1) - m2::PointI64(p2));
  // return ClampPoint(maxPoint, m2::PointI64(p1) + (m2::PointI64(p1) - m2::PointI64(p2)) / 2);
  return ClampPoint(maxPoint, m2::PointD(p1) + (m2::PointD(p1) - m2::PointD(p2)) / 2.0);
}

m2::PointU PredictPointInPolyline(m2::PointU const & maxPoint,
                                  m2::PointU const & p1,
                                  m2::PointU const & p2,
                                  m2::PointU const & p3)
{
  CHECK_NOT_EQUAL(p2, p3, ());

  complex<double> const c1(p1.x, p1.y);
  complex<double> const c2(p2.x, p2.y);
  complex<double> const c3(p3.x, p3.y);
  complex<double> const d = (c1 - c2) / (c2 - c3);
  complex<double> const c0 = c1 + (c1 - c2) * polar(0.5, 0.5 * arg(d));

  /*
  complex<double> const c1(p1.x, p1.y);
  complex<double> const c2(p2.x, p2.y);
  complex<double> const c3(p3.x, p3.y);
  complex<double> const d = (c1 - c2) / (c2 - c3);
  complex<double> const c01 = c1 + (c1 - c2) * polar(0.5, arg(d));
  complex<double> const c02 = c1 + (c1 - c2) * complex<double>(0.5, 0.0);
  complex<double> const c0 = (c01 + c02) * complex<double>(0.5, 0.0);
  */

  return ClampPoint(maxPoint, m2::PointD(c0.real(), c0.imag()));
}

m2::PointU PredictPointInTriangle(m2::PointU const & maxPoint,
                                  m2::PointU const & p1,
                                  m2::PointU const & p2,
                                  m2::PointU const & p3)
{
  // parallelogram prediction
  return ClampPoint(maxPoint, p1 + p2 - p3);
}

namespace geo_coding
{
  bool TestDecoding(InPointsT const & points,
                    m2::PointU const & basePoint,
                    m2::PointU const & maxPoint,
                    OutDeltasT const & deltas,
                    void (* fnDecode)(InDeltasT const & deltas,
                                      m2::PointU const & basePoint,
                                      m2::PointU const & maxPoint,
                                      OutPointsT & points))
  {
    size_t const count = points.size();

    vector<m2::PointU> decoded;
    decoded.resize(count);

    OutPointsT decodedA(decoded);
    fnDecode(make_read_adapter(deltas), basePoint, maxPoint, decodedA);

    for (size_t i = 0; i < count; ++i)
      ASSERT_EQUAL(points[i], decoded[i], ());
    return true;
  }

void EncodePolylinePrev1(InPointsT const & points,
                         m2::PointU const & basePoint,
                         m2::PointU const & maxPoint,
                         OutDeltasT & deltas)
{
  size_t const count = points.size();
  if (count > 0)
  {
    deltas.push_back(EncodeDelta(points[0], basePoint));
    for (size_t i = 1; i < count; ++i)
      deltas.push_back(EncodeDelta(points[i], points[i-1]));
  }

  ASSERT(TestDecoding(points, basePoint, maxPoint, deltas, &DecodePolylinePrev1), ());
}

void DecodePolylinePrev1(InDeltasT const & deltas,
                         m2::PointU const & basePoint,
                         m2::PointU const & /*maxPoint*/,
                         OutPointsT & points)
{
  size_t const count = deltas.size();
  if (count > 0)
  {
    points.push_back(DecodeDelta(deltas[0], basePoint));
    for (size_t i = 1; i < count; ++i)
      points.push_back(DecodeDelta(deltas[i], points.back()));
  }
}

void EncodePolylinePrev2(InPointsT const & points,
                         m2::PointU const & basePoint,
                         m2::PointU const & maxPoint,
                         OutDeltasT & deltas)
{
  size_t const count = points.size();
  if (count > 0)
  {
    deltas.push_back(EncodeDelta(points[0], basePoint));
    if (count > 1)
    {
      deltas.push_back(EncodeDelta(points[1], points[0]));
      for (size_t i = 2; i < count; ++i)
        deltas.push_back(EncodeDelta(points[i],
                                     PredictPointInPolyline(maxPoint, points[i-1], points[i-2])));
    }
  }

  ASSERT(TestDecoding(points, basePoint, maxPoint, deltas, &DecodePolylinePrev2), ());
}

void DecodePolylinePrev2(InDeltasT const & deltas,
                         m2::PointU const & basePoint,
                         m2::PointU const & maxPoint,
                         OutPointsT & points)
{
  size_t const count = deltas.size();
  if (count > 0)
  {
    points.push_back(DecodeDelta(deltas[0], basePoint));
    if (count > 1)
    {
      points.push_back(DecodeDelta(deltas[1], points.back()));
      for (size_t i = 2; i < count; ++i)
      {
        size_t const n = points.size();
        points.push_back(DecodeDelta(deltas[i],
                                     PredictPointInPolyline(maxPoint, points[n-1], points[n-2])));
      }
    }
  }
}

void EncodePolylinePrev3(InPointsT const & points,
                         m2::PointU const & basePoint,
                         m2::PointU const & maxPoint,
                         OutDeltasT & deltas)
{
  ASSERT_LESS_OR_EQUAL(basePoint.x, maxPoint.x, (basePoint, maxPoint));
  ASSERT_LESS_OR_EQUAL(basePoint.y, maxPoint.y, (basePoint, maxPoint));

  size_t const count = points.size();
  if (count > 0)
  {
    deltas.push_back(EncodeDelta(points[0], basePoint));
    if (count > 1)
    {
      deltas.push_back(EncodeDelta(points[1], points[0]));
      if (count > 2)
      {
        m2::PointU const prediction = PredictPointInPolyline(maxPoint, points[1], points[0]);
        deltas.push_back(EncodeDelta(points[2], prediction));
        for (size_t i = 3; i < count; ++i)
        {
          m2::PointU const prediction =
              PredictPointInPolyline(maxPoint, points[i-1], points[i-2], points[i-3]);
          deltas.push_back(EncodeDelta(points[i], prediction));
        }
      }
    }
  }

  ASSERT(TestDecoding(points, basePoint, maxPoint, deltas, &DecodePolylinePrev3), ());
}

void DecodePolylinePrev3(InDeltasT const & deltas,
                         m2::PointU const & basePoint,
                         m2::PointU const & maxPoint,
                         OutPointsT & points)
{
  ASSERT_LESS_OR_EQUAL(basePoint.x, maxPoint.x, (basePoint, maxPoint));
  ASSERT_LESS_OR_EQUAL(basePoint.y, maxPoint.y, (basePoint, maxPoint));

  size_t const count = deltas.size();
  if (count> 0)
  {
    points.push_back(DecodeDelta(deltas[0], basePoint));
    if (count > 1)
    {
      m2::PointU const pt0 = points.back();
      points.push_back(DecodeDelta(deltas[1], pt0));
      if (count > 2)
      {
        points.push_back(DecodeDelta(deltas[2],
                                     PredictPointInPolyline(maxPoint, points.back(), pt0)));
        for (size_t i = 3; i < count; ++i)
        {
          size_t const n = points.size();
          m2::PointU const prediction =
              PredictPointInPolyline(maxPoint, points[n-1], points[n-2], points[n-3]);
          points.push_back(DecodeDelta(deltas[i], prediction));
        }
      }
    }
  }
}

void EncodeTriangleStrip(InPointsT const & points,
                         m2::PointU const & basePoint,
                         m2::PointU const & maxPoint,
                         OutDeltasT & deltas)
{
  size_t const count = points.size();
  if (count > 0)
  {
    ASSERT_GREATER(count, 2, ());

    deltas.push_back(EncodeDelta(points[0], basePoint));
    deltas.push_back(EncodeDelta(points[1], points[0]));
    deltas.push_back(EncodeDelta(points[2], points[1]));

    for (size_t i = 3; i < count; ++i)
    {
      m2::PointU const prediction =
          PredictPointInTriangle(maxPoint, points[i-1], points[i-2], points[i-3]);
      deltas.push_back(EncodeDelta(points[i], prediction));
    }
  }
}

void DecodeTriangleStrip(InDeltasT const & deltas,
                         m2::PointU const & basePoint,
                         m2::PointU const & maxPoint,
                         OutPointsT & points)
{
  size_t const count = deltas.size();
  if (count > 0)
  {
    ASSERT_GREATER(count, 2, ());

    points.push_back(DecodeDelta(deltas[0], basePoint));
    points.push_back(DecodeDelta(deltas[1], points.back()));
    points.push_back(DecodeDelta(deltas[2], points.back()));

    for (size_t i = 3; i < count; ++i)
    {
      size_t const n = points.size();
      m2::PointU const prediction =
          PredictPointInTriangle(maxPoint, points[n-1], points[n-2], points[n-3]);
      points.push_back(DecodeDelta(deltas[i], prediction));
    }
  }
}

}


text:
package org.iisgcp.waterwalk.fragment;

import java.util.HashMap;

import org.iisgcp.waterwalk.R;
import org.iisgcp.waterwalk.activity.PointOfInterestActivity;
import org.iisgcp.waterwalk.activity.PointOfInterestDetailActivity;
import org.iisgcp.waterwalk.adapter.RowItem;
import org.iisgcp.waterwalk.utils.Constants;
import org.iisgcp.waterwalk.utils.OnItemClickedListener;
import org.iisgcp.waterwalk.utils.OnPageSelectedListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class PointOfInterestMapFragment extends SupportMapFragment
		implements
        ConnectionCallbacks,
        OnConnectionFailedListener,
        LocationListener,
		OnMyLocationButtonClickListener {

	private static final String INTENT_POSITION = "position";

	private HashMap<Marker, RowItem> mMarkerInfoMap = new HashMap<Marker, RowItem>();

	private OnItemClickedListener mItemClickedListener;
	private OnPageSelectedListener mPageSelectedListener;

	private GoogleMap mMap;
    private LocationClient mLocationClient;

    private int mZoom;
	private double mDefaultLatitude;
	private double mDefaultLongitude;

	private View mPrevious;
	private View mNext;

	private int [] mPois;

	private int mIndex = 0;

	/**
     * Create a new instance of PointOfInterestListFragment
     */
    public static PointOfInterestMapFragment newInstance(int position) {
    	PointOfInterestMapFragment f = new PointOfInterestMapFragment();

        // Supply title and poi input as an argument.
        Bundle args = new Bundle();
        args.putInt(INTENT_POSITION, position);
        f.setArguments(args);

        return f;
    }

    @Override
    public void onAttach(Activity activity) {
    	super.onAttach(activity);

    	try {
    		mItemClickedListener = (OnItemClickedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnItemClickedListener");
        }

    	try {
    		mPageSelectedListener = (OnPageSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnPageSelectedListener");
        }
    }

    /**
     * Fragment initialization.  We way we want to be retained and
     * start our thread.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);
    }

	@SuppressWarnings("deprecation")
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);

        mPrevious = new ImageButton(getActivity());

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        		FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT;
        mPrevious.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.previous));
        mPrevious.setLayoutParams(params);

        mNext = new ImageButton(getActivity());
        params = new FrameLayout.LayoutParams(
        		FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
        mNext.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.next));
        mNext.setLayoutParams(params);

        ((FrameLayout) view).addView(mPrevious);
        ((FrameLayout) view).addView(mNext);

        return view;
    }

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

		TypedArray routes = getResources().obtainTypedArray(R.array.routes);

		mPois = new int[routes.length()];

		for (int i = 0; i < routes.length(); i++) {
			mPois[i] = routes.getResourceId(i, -1);
		}

		routes.recycle();

		mPrevious.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mIndex == 0) {
					mIndex = 3;
				} else {
					mIndex--;
				}

				updateMarkers(mIndex);
			}
		});

		mNext.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mIndex == 3) {
					mIndex = 0;
				} else {
					mIndex++;
				}

				updateMarkers(mIndex);
			}
		});

	    if (savedInstanceState == null) {
	    	// First incarnation of this activity.
	        setRetainInstance(true);
	    } else {
	        // Reincarnated activity. The obtained map is the same map instance in the previous
	            // activity life cycle. There is no need to reinitialize it.
	        mMap = getMap();
	    }
	    setUpMapIfNeeded();
	}

    @Override
    public void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        setUpLocationClientIfNeeded();
        mLocationClient.connect();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            mLocationClient.disconnect();
        }
    }

	@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.routes_map_fragment_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case R.id.menu_route_locations:
        		goToDefaultLocation();
        		return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }

	private void goToDefaultLocation() {
		CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(mDefaultLatitude,
				mDefaultLongitude), mZoom);
	    mMap.animateCamera(cameraUpdate);
	}

	private void addMarkers(int resId) {
		TypedArray pois = getResources().obtainTypedArray(resId);

	    for (int i = 0; i < pois.length(); i++) {
	        TypedArray poi = getResources().obtainTypedArray(pois.getResourceId(i, -1));

	        String title = getString(poi.getResourceId(0, -1));
	        float lat = poi.getFloat(3, -1);
	        float lng = poi.getFloat(4, -1);

			Marker marker = mMap.addMarker(new MarkerOptions()
	        .position(new LatLng(lat, lng))
	        .title(title));

			RowItem rowItem = new RowItem();
			rowItem.setResId(pois.getResourceId(i, -1));
	        mMarkerInfoMap.put(marker, rowItem);

	        poi.recycle();
	    }

	    pois.recycle();
	}

	public void update(int position) {
		mIndex = position;
		updateMarkers(mIndex);
	}

	private void updateMarkers(int position) {
		mPageSelectedListener.onPageSelected(position);

		int resId = mPois[position];

		TypedArray route = getResources().obtainTypedArray(resId);

		((PointOfInterestActivity) getActivity()).setTitle(getString(route.getResourceId(0, -1)));

		TypedArray pois = getResources().obtainTypedArray(route.getResourceId(5, -1));

		route.recycle();

		mMap.clear();
		mMarkerInfoMap.clear();

	    for (int i = 0; i < pois.length(); i++) {
	        TypedArray poi = getResources().obtainTypedArray(pois.getResourceId(i, -1));

	        String title = getString(poi.getResourceId(0, -1));
	        float lat = poi.getFloat(3, -1);
	        float lng = poi.getFloat(4, -1);

			Marker marker = mMap.addMarker(new MarkerOptions()
	        .position(new LatLng(lat, lng))
	        .title(title));

			RowItem rowItem = new RowItem();
			rowItem.setResId(pois.getResourceId(i, -1));
	        mMarkerInfoMap.put(marker, rowItem);

	        poi.recycle();
	    }

	    pois.recycle();
	}

    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = getMap();
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
    	mMap.setMyLocationEnabled(true);
        mMap.setOnMyLocationButtonClickListener(this);
  	    mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

			@Override
			public void onInfoWindowClick(Marker marker) {
				Intent intent = new Intent(PointOfInterestMapFragment.this.getActivity(), PointOfInterestDetailActivity.class);
				intent.putExtra(Constants.INTENT_TITLE, marker.getTitle());
				intent.putExtra(Constants.INTENT_RES_ID, mMarkerInfoMap.get(marker).getResId());
				mItemClickedListener.onItemClicked(intent);
			}

  	    });

  		TypedArray routes = getResources().obtainTypedArray(R.array.routes);
  		int resId = routes.getResourceId(getArguments().getInt(INTENT_POSITION), -1);
  		routes.recycle();
    	TypedArray route = getResources().obtainTypedArray(resId);

    	mZoom = route.getInteger(2, -1);
    	mDefaultLatitude = route.getFloat(3, -1);
    	mDefaultLongitude = route.getFloat(4, -1);

        addMarkers(route.getResourceId(5, -1));
    	route.recycle();
        goToDefaultLocation();
    }

    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(
            		getActivity().getApplicationContext(),
                    this,  // ConnectionCallbacks
                    this); // OnConnectionFailedListener
        }
    }

    /**
     * Button to get current Location. This demonstrates how to get the current Location as required
     * without needing to register a LocationListener.
     */
    private boolean showMyLocation() {
        if (mLocationClient != null && mLocationClient.isConnected()) {
            Location location = mLocationClient.getLastLocation();

            if (location == null) {
            	final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

            	if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            		startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            		return true;
            	} else {
                	Toast.makeText(getActivity().getApplicationContext(), R.string.gps_error, Toast.LENGTH_LONG).show();
                	return true;
            	}
            }
        }

        return false;
    }

	@Override
	public void onConnected(Bundle connectionHint) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onMyLocationButtonClick() {
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
		return showMyLocation();
	}
}


text:
/* $NetBSD: pci_machdep.h,v 1.2 2002/05/15 19:23:54 thorpej Exp $ */

/*
 * Copyright (c) 1996 Carnegie-Mellon University.
 * All rights reserved.
 *
 * Author: Chris G. Demetriou
 *
 * Permission to use, copy, modify and distribute this software and
 * its documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie the
 * rights to redistribute these changes.
 */

/*
 * __HAVE_PCIIDE_MACHDEP_COMPAT_INTR_ESTABLISH (if used) needs to be
 * defined before this file is included
 */

/*
 * Types provided to machine-independent PCI code
 */
typedef struct mips_pci_chipset *pci_chipset_tag_t;
typedef u_long pcitag_t;
typedef u_long pci_intr_handle_t;

/*
 * Forward declarations.
 */
struct pci_attach_args;

/*
 * mips-specific PCI structure and type definitions.
 * NOT TO BE USED DIRECTLY BY MACHINE INDEPENDENT CODE.
 */
struct mips_pci_chipset {
	void		*pc_conf_v;
	void		(*pc_attach_hook)(struct device *,
			    struct device *, struct pcibus_attach_args *);
	int		(*pc_bus_maxdevs)(void *, int);
	pcitag_t	(*pc_make_tag)(void *, int, int, int);
	void		(*pc_decompose_tag)(void *, pcitag_t, int *,
			    int *, int *);
	pcireg_t	(*pc_conf_read)(void *, pcitag_t, int);
	void		(*pc_conf_write)(void *, pcitag_t, int, pcireg_t);

	void		*pc_intr_v;
	int		(*pc_intr_map)(struct pci_attach_args *,
			    pci_intr_handle_t *);
	const char	*(*pc_intr_string)(void *, pci_intr_handle_t);
	const struct evcnt *(*pc_intr_evcnt)(void *, pci_intr_handle_t);
	void		*(*pc_intr_establish)(void *, pci_intr_handle_t,
			    int, int (*)(void *), void *);
	void		(*pc_intr_disestablish)(void *, void *);

	void		(*pc_conf_interrupt)(void *, int, int, int,
			    int, int *);

#ifdef __HAVE_PCIIDE_MACHDEP_COMPAT_INTR_ESTABLISH
	void		*(*pc_pciide_compat_intr_establish)(void *,
			    struct device *, struct pci_attach_args *, int,
			    int (*)(void *), void *);
#endif
};

/*
 * Functions provided to machine-independent PCI code.
 */
#define	pci_attach_hook(p, s, pba)					\
    (*(pba)->pba_pc->pc_attach_hook)((p), (s), (pba))
#define	pci_bus_maxdevs(c, b)						\
    (*(c)->pc_bus_maxdevs)((c)->pc_conf_v, (b))
#define	pci_make_tag(c, b, d, f)					\
    (*(c)->pc_make_tag)((c)->pc_conf_v, (b), (d), (f))
#define	pci_decompose_tag(c, t, bp, dp, fp)				\
    (*(c)->pc_decompose_tag)((c)->pc_conf_v, (t), (bp), (dp), (fp))
#define	pci_conf_read(c, t, r)						\
    (*(c)->pc_conf_read)((c)->pc_conf_v, (t), (r))
#define	pci_conf_write(c, t, r, v)					\
    (*(c)->pc_conf_write)((c)->pc_conf_v, (t), (r), (v))
#define	pci_intr_map(pa, ihp)						\
    (*(pa)->pa_pc->pc_intr_map)((pa), (ihp))
#define	pci_intr_string(c, ih)						\
    (*(c)->pc_intr_string)((c)->pc_intr_v, (ih))
#define	pci_intr_evcnt(c, ih)						\
    (*(c)->pc_intr_evcnt)((c)->pc_intr_v, (ih))
#define	pci_intr_establish(c, ih, l, h, a)				\
    (*(c)->pc_intr_establish)((c)->pc_intr_v, (ih), (l), (h), (a))
#define	pci_intr_disestablish(c, iv)					\
    (*(c)->pc_intr_disestablish)((c)->pc_intr_v, (iv))
#define	pci_conf_interrupt(c, b, d, p, s, lp)				\
    (*(c)->pc_conf_interrupt)((c)->pc_intr_v, (b), (d), (p), (s), (lp))

#define	pci_enumerate_bus(sc, m, p)					\
	pci_enumerate_bus_generic((sc), (m), (p))

/*
 * mips-specific PCI functions.
 * NOT TO BE USED DIRECTLY BY MACHINE INDEPENDENT CODE.
 */
#ifdef __HAVE_PCIIDE_MACHDEP_COMPAT_INTR_ESTABLISH
#define	mips_pciide_compat_intr_establish(c, d, p, ch, f, a)		\
    ((c)->pc_pciide_compat_intr_establish == NULL ? NULL :		\
     (*(c)->pc_pciide_compat_intr_establish)((c)->pc_conf_v, (d), (p),	\
	(ch), (f), (a)))
#endif


text:
package cmd

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/bleenco/abstruse/internal/auth"
	"github.com/bleenco/abstruse/internal/version"
	"github.com/bleenco/abstruse/pkg/fs"
	"github.com/bleenco/abstruse/pkg/lib"
	"github.com/bleenco/abstruse/pkg/tlsutil"
	"github.com/bleenco/abstruse/server/config"
	"github.com/bleenco/abstruse/server/http"
	"github.com/bleenco/abstruse/server/ws"
	"github.com/jinzhu/gorm"
	"github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

var (
	cfgFile string
	rootCmd = &cobra.Command{
		Use:   "abstruse",
		Short: "Abstruse CI",
		Run: func(cmd *cobra.Command, args []string) {
			app, err := CreateApp()
			if err != nil {
				fatal(err)
			}

			if err := app.run(); err != nil {
				fatal(err)
			}
			os.Exit(0)
		},
	}
	versionCmd = &cobra.Command{
		Use:   "version",
		Short: "Print the version number and build info",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println(version.GenerateBuildVersionString())
			os.Exit(0)
		},
	}
)

type app struct {
	config *config.Config
	db     *gorm.DB
	logger *zap.Logger
	http   *http.Server
	ws     *ws.Server
}

func newApp(
	config *config.Config,
	db *gorm.DB,
	logger *zap.Logger,
	http *http.Server,
	ws *ws.Server,
) *app {
	return &app{config, db, logger, http, ws}
}

func (a app) run() error {
	errch := make(chan error, 1)

	go func() {
		if err := a.http.Run(); err != nil {
			errch <- err
		}
	}()

	go func() {
		if err := a.ws.Run(); err != nil {
			errch <- err
		}
	}()

	return <-errch
}

// Execute executes the root command.
func Execute() error {
	return rootCmd.Execute()
}

func init() {
	rootCmd.AddCommand(versionCmd)
	cobra.OnInitialize(initDefaults)

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/abstruse/abstruse.json)")
	rootCmd.PersistentFlags().String("http-addr", "0.0.0.0:80", "HTTP server listen address")
	rootCmd.PersistentFlags().String("http-uploaddir", "uploads/", "HTTP uploads directory")
	rootCmd.PersistentFlags().Bool("http-compress", false, "enable HTTP response gzip compression")
	rootCmd.PersistentFlags().Bool("http-tls", false, "run HTTP server in TLS mode")
	rootCmd.PersistentFlags().String("websocket-addr", "127.0.0.1:2220", "WebSocket server listen address")
	rootCmd.PersistentFlags().String("tls-cert", "cert.pem", "path to SSL certificate file")
	rootCmd.PersistentFlags().String("tls-key", "key.pem", "path to SSL private key file")
	rootCmd.PersistentFlags().String("db-driver", "mysql", "database client (available options: mysql, postgres, mssql)")
	rootCmd.PersistentFlags().String("db-host", "localhost", "database server host address")
	rootCmd.PersistentFlags().Int("db-port", 3306, "database server port")
	rootCmd.PersistentFlags().String("db-user", "root", "database username")
	rootCmd.PersistentFlags().String("db-password", "", "database password")
	rootCmd.PersistentFlags().String("db-name", "abstruse", "database name (file name when sqlite client used)")
	rootCmd.PersistentFlags().String("db-charset", "utf8", "database charset")
	rootCmd.PersistentFlags().String("logger-level", "info", "logging level (available options: debug, info, warn, error, panic, fatal)")
	rootCmd.PersistentFlags().Bool("logger-stdout", true, "print logs to stdout")
	rootCmd.PersistentFlags().String("logger-filename", "abstruse.log", "log filename")
	rootCmd.PersistentFlags().Int("logger-max-size", 500, "maximum log file size (in MB)")
	rootCmd.PersistentFlags().Int("logger-max-backups", 3, "maximum log file backups")
	rootCmd.PersistentFlags().Int("logger-max-age", 3, "maximum log age")
	rootCmd.PersistentFlags().String("auth-jwtsecret", lib.RandomString(), "JWT authentication secret key")
	rootCmd.PersistentFlags().String("datadir", "data/", "Directory to store build cache and build artifacts")
}

func initDefaults() {
	viper.BindPFlag("http.addr", rootCmd.PersistentFlags().Lookup("http-addr"))
	viper.BindPFlag("http.tls", rootCmd.PersistentFlags().Lookup("http-tls"))
	viper.BindPFlag("http.uploaddir", rootCmd.PersistentFlags().Lookup("http-uploaddir"))
	viper.BindPFlag("http.compress", rootCmd.PersistentFlags().Lookup("http-compress"))
	viper.BindPFlag("websocket.addr", rootCmd.PersistentFlags().Lookup("websocket-addr"))
	viper.BindPFlag("tls.cert", rootCmd.PersistentFlags().Lookup("tls-cert"))
	viper.BindPFlag("tls.key", rootCmd.PersistentFlags().Lookup("tls-key"))
	viper.BindPFlag("db.driver", rootCmd.PersistentFlags().Lookup("db-driver"))
	viper.BindPFlag("db.host", rootCmd.PersistentFlags().Lookup("db-host"))
	viper.BindPFlag("db.port", rootCmd.PersistentFlags().Lookup("db-port"))
	viper.BindPFlag("db.user", rootCmd.PersistentFlags().Lookup("db-user"))
	viper.BindPFlag("db.password", rootCmd.PersistentFlags().Lookup("db-password"))
	viper.BindPFlag("db.name", rootCmd.PersistentFlags().Lookup("db-name"))
	viper.BindPFlag("db.charset", rootCmd.PersistentFlags().Lookup("db-charset"))
	viper.BindPFlag("logger.level", rootCmd.PersistentFlags().Lookup("logger-level"))
	viper.BindPFlag("logger.stdout", rootCmd.PersistentFlags().Lookup("logger-stdout"))
	viper.BindPFlag("logger.filename", rootCmd.PersistentFlags().Lookup("logger-filename"))
	viper.BindPFlag("logger.maxsize", rootCmd.PersistentFlags().Lookup("logger-max-size"))
	viper.BindPFlag("logger.maxbackups", rootCmd.PersistentFlags().Lookup("logger-max-backups"))
	viper.BindPFlag("logger.maxage", rootCmd.PersistentFlags().Lookup("logger-max-age"))
	viper.BindPFlag("auth.jwtsecret", rootCmd.PersistentFlags().Lookup("auth-jwtsecret"))
	viper.BindPFlag("datadir", rootCmd.PersistentFlags().Lookup("datadir"))
}

func newConfig() *config.Config {
	var cfg *config.Config

	if cfgFile == "" {
		home, err := homedir.Dir()
		if err != nil {
			fatal(err)
		}
		cfgFile = filepath.Join(home, "abstruse", "abstruse.json")
	}

	viper.SetConfigFile(cfgFile)
	viper.SetConfigType("json")
	viper.SetEnvPrefix("abstruse")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	viper.AutomaticEnv()

	cfgFileUsed := viper.ConfigFileUsed()

	if !fs.Exists(cfgFileUsed) {
		if !fs.Exists(filepath.Dir(cfgFileUsed)) {
			if err := fs.MakeDir(filepath.Dir(cfgFileUsed)); err != nil {
				fatal(err)
			}
		}

		if err := viper.SafeWriteConfigAs(cfgFileUsed); err != nil {
			fatal(err)
		}
	}

	if err := viper.ReadInConfig(); err != nil {
		fatal(err)
	}

	if err := viper.Unmarshal(&cfg); err != nil {
		fatal(err)
	}

	if !strings.HasPrefix(cfg.HTTP.UploadDir, "/") {
		cfg.HTTP.UploadDir = filepath.Join(filepath.Dir(viper.ConfigFileUsed()), cfg.HTTP.UploadDir)
	}

	if !fs.Exists(cfg.HTTP.UploadDir) {
		if err := fs.MakeDir(cfg.HTTP.UploadDir); err != nil {
			fatal(err)
		}

		if err := fs.MakeDir(filepath.Join(cfg.HTTP.UploadDir, "avatars")); err != nil {
			fatal(err)
		}
	}

	if cfg.DB.Driver == "sqlite3" && !strings.HasPrefix(cfg.DB.Name, "/") {
		cfg.DB.Name = filepath.Join(filepath.Dir(viper.ConfigFileUsed()), cfg.DB.Name)
	}

	if !strings.HasPrefix(cfg.DataDir, "/") {
		cfg.DataDir = filepath.Join(filepath.Dir(viper.ConfigFileUsed()), cfg.DataDir)
	}

	if err := fs.MakeDir(cfg.DataDir); err != nil {
		fatal(err)
	}

	if err := fs.MakeDir(filepath.Join(cfg.DataDir, "cache")); err != nil {
		fatal(err)
	}

	if err := fs.MakeDir(filepath.Join(cfg.DataDir, "store")); err != nil {
		fatal(err)
	}

	if !strings.HasPrefix(cfg.Logger.Filename, "/") {
		cfg.Logger.Filename = filepath.Join(filepath.Dir(viper.ConfigFileUsed()), cfg.Logger.Filename)
	}

	if !strings.HasPrefix(cfg.TLS.Cert, "/") {
		cfg.TLS.Cert = filepath.Join(filepath.Dir(cfgFileUsed), cfg.TLS.Cert)
	}

	if !strings.HasPrefix(cfg.TLS.Key, "/") {
		cfg.TLS.Key = filepath.Join(filepath.Dir(cfgFileUsed), cfg.TLS.Key)
	}

	auth.Init(viper.GetString("auth.jwtsecret"))

	cert, key := cfg.TLS.Cert, cfg.TLS.Key
	if !strings.HasPrefix(cert, "/") {
		cert = filepath.Join(filepath.Dir(viper.ConfigFileUsed()), cert)
	}
	if !strings.HasPrefix(key, "/") {
		key = filepath.Join(filepath.Dir(viper.ConfigFileUsed()), key)
	}

	if err := tlsutil.CheckAndGenerateCert(cert, key); err != nil {
		fatal(err)
	}

	return cfg
}

func fatal(msg interface{}) {
	fmt.Println(msg)
	os.Exit(1)
}


text:
@interface UINavigationController (MM)

@end

// ----------------------------------------------------------------------

@interface MMNavigationController : UINavigationController

@end


text:
'use strict';

var common = require('../common');
var types = require('../types');
var numberProcedures = require('./number');
var charProcedures = require('./char');

var SchemeString = types.SchemeString;
var SchemeChar = types.SchemeChar;
var Unspecified = types.Unspecified;
var guardArgsCountExact = common.guardArgsCountExact;
var guardArgsCountMin = common.guardArgsCountMin;
var guardArgsCountMax = common.guardArgsCountMax;
var guardArgPredicate = common.guardArgPredicate;
var guardImmutable = common.guardImmutable;
var raiseRuntimeError = common.raiseRuntimeError;

var stringProcedures = {
  'string?': function (args, env) {
    guardArgsCountExact(env, args.length, 1);
    return args[0] instanceof SchemeString;
  },
  'make-string': function (args, env) {
    guardArgsCountMin(env, args.length, 1);
    guardArgsCountMax(env, args.length, 2);
    guardArgPredicate(env, args[0], numberProcedures['nonnegative-integer?'], 0, 'procedures', 'nonnegative-integer?');
    var fill = '\x00';
    if (args.length === 2) {
      guardArgPredicate(env, args[1], charProcedures['char?'], 1, 'procedures', 'char?');
      fill = args[1].value;
    }
    var arr = new Array(args[0]);
    for (var i = 0; i < arr.length; i++) {
      arr[i] = fill;
    }
    return new SchemeString(arr.join(''));
  },
  'string': function (args, env) {
    var i;
    for (i = 0; i < args.length; i++) {
      guardArgPredicate(env, args[i], charProcedures['char?'], i, 'procedures', 'char?');
    }
    var arr = new Array(args.length);
    for (i = 0; i < arr.length; i++) {
      arr[i] = args[i].value;
    }
    return new SchemeString(arr.join(''));
  },
  'string-length': function (args, env) {
    guardArgsCountExact(env, args.length, 1);
    guardArgPredicate(env, args[0], stringProcedures['string?'], 0, 'procedures', 'string?');
    return args[0].value.length;
  },
  'string-ref': function (args, env) {
    guardArgsCountExact(env, args.length, 2);
    var k = args[1];
    guardArgPredicate(env, args[0], stringProcedures['string?'], 0, 'procedures', 'string?');
    guardArgPredicate(env, k, numberProcedures['nonnegative-integer?'], 1, 'procedures', 'nonnegative-integer?');
    var str = args[0].value;
    if (k > str.length - 1) {
      raiseRuntimeError(env, 'string_index_out_range', [str.length]);
    }
    return new SchemeChar(str[k]);
  },
  'string-set!': function (args, env) {
    guardArgsCountExact(env, args.length, 3);
    var k = args[1];
    guardArgPredicate(env, args[0], stringProcedures['string?'], 0, 'procedures', 'string?');
    guardArgPredicate(env, k, numberProcedures['nonnegative-integer?'], 1, 'procedures', 'nonnegative-integer?');
    guardArgPredicate(env, args[2], charProcedures['char?'], 2, 'procedures', 'char?');
    guardImmutable(env, args[0]);
    var str = args[0].value;
    if (k > str.length - 1) {
      raiseRuntimeError(env, 'string_index_out_range', [str.length]);
    }
    args[0].value = str.substring(0, k) + args[2].value + str.substring(k + 1);
    return Unspecified;
  },
  'string=?': function (args, env) {
    guardArgsCountMin(env, args.length, 2);
    var i, l;
    for (i = 0; i < args.length; i++) {
      guardArgPredicate(env, args[i], stringProcedures['string?'], i, 'procedures', 'string?');
    }
    for (i = 0, l = args.length - 1; i < l; i++) {
      if (args[i].value !== args[i + 1].value) {
        return false;
      }
    }
    return true;
  },
  'string-append': function (args, env) {
    var i;
    for (i = 0; i < args.length; i++) {
      guardArgPredicate(env, args[i], stringProcedures['string?'], i, 'procedures', 'string?');
    }
    var arr = [];
    for (i = 0; i < args.length; i++) {
      arr.push(args[i].value);
    }
    return new SchemeString(arr.join(''));
  },
  'substring': function (args, env) {
    guardArgsCountExact(env, args.length, 3);
    guardArgPredicate(env, args[0], stringProcedures['string?'], 0, 'procedures', 'string?');
    guardArgPredicate(env, args[1], numberProcedures['nonnegative-integer?'], 1, 'procedures', 'nonnegative-integer?');
    guardArgPredicate(env, args[2], numberProcedures['nonnegative-integer?'], 2, 'procedures', 'nonnegative-integer?');
    var string = args[0].value;
    var start = args[1];
    var end = args[2];
    if (start > string.length - 1) {
      raiseRuntimeError(env, 'string_index_out_range', [string.length]);
    }
    if (end > string.length) {
      raiseRuntimeError(env, 'string_index_out_range', [string.length]);
    }
    if (start > end) {
      raiseRuntimeError(env, 'start_index_greater_end_index');
    }
    return new SchemeString(string.substring(start, end));
  },
};

module.exports = stringProcedures;


text:
class DeliverWelcomeJob

  def initialize(user_id)
    @user_id = user_id
  end

  def perform
    if user = User.find_by_id(@user_id)
      BlueLightSpecialMailer.deliver_mimi_welcome(user)
    end
  end

end


text:
package io.atomix.utils.concurrent;

import java.lang.ref.WeakReference;

/**
 * Atomix thread.
 *

 * The Atomix thread primarily serves to store a {@link ThreadContext} for the current thread.
 * The context is stored in a {@link WeakReference} in order to allow the thread to be garbage collected.
 *

 * There is no {@link ThreadContext} associated with the thread when it is first created.
 * It is the responsibility of thread creators to {@link #setContext(ThreadContext) set} the thread context when appropriate.
 *
 * @author Jordan Halterman
 */
public class AtomixThread extends Thread {
  private WeakReference<ThreadContext> context;

  public AtomixThread(Runnable target) {
    super(target);
  }

  /**
   * Sets the thread context.
   *
   * @param context The thread context.
   */
  public void setContext(ThreadContext context) {
    this.context = new WeakReference<>(context);
  }

  /**
   * Returns the thread context.
   *
   * @return The thread {@link ThreadContext} or {@code null} if no context has been configured.
   */
  public ThreadContext getContext() {
    return context != null ? context.get() : null;
  }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Arbor.Ginkgo
{
	public class Path
	{
		readonly List<string> _pathSegments = new List<string>();

		public Path(string fullName)
		{
			if (string.IsNullOrWhiteSpace(fullName))
			{
				throw new ArgumentNullException(nameof(fullName));
			}

			string normalizedPath = fullName.NormalizePath();

			string[] segments = normalizedPath.Split(System.IO.Path.DirectorySeparatorChar);

			_pathSegments.AddRange(segments);
		}

		public string FullName
		{
			// ReSharper disable SpecifyACultureInStringConversionExplicitly
			get { return string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), _pathSegments); }
			// ReSharper restore SpecifyACultureInStringConversionExplicitly
		}

		public bool Exists
		{
			get
			{
				if (!_pathSegments.Any())
				{
					return false;
				}

				try
				{
					if (File.Exists(FullName))
					{
						return true;
					}
				}
				catch (FileNotFoundException)
				{
					return false;
				}
				try
				{
					if (Directory.Exists(FullName))
					{
						return true;
					}
				}
				catch (DirectoryNotFoundException)
				{
					return false;
				}

				return false;
			}
		}

		public static Path Combine(Path path1, string path2)
		{
			if (path1 == null)
			{
				throw new ArgumentNullException(nameof(path1));
			}

			if (string.IsNullOrWhiteSpace(path2))
			{
				throw new ArgumentNullException(nameof(path2));
			}

			string combined = System.IO.Path.Combine(path1.FullName, path2);

			return new Path(combined);
		}

		public static Path Combine(params string[] paths)
		{
			string combined = System.IO.Path.Combine(paths);

			return new Path(combined);
		}

		public override string ToString()
		{
			return FullName;
		}

		public static Path Combine(Path path1, params string[] paths)
		{
			if (path1 == null)
			{
				throw new ArgumentNullException(nameof(path1));
			}

			var pathList = new List<string>(paths);

			pathList.Insert(0, path1.FullName);

			string combined = System.IO.Path.Combine(pathList.ToArray());

			return new Path(combined);
		}
	}
}