text:
#pragma once

#include <memory>
#include <string>
#include <vector>

#include "modules/prediction/network/net_layer.h"
#include "modules/prediction/proto/network_model.pb.h"

/**
 * @namespace apollo::prediction::network
 * @brief apollo::prediction::network
 */
namespace apollo {
namespace prediction {
namespace network {

/**
 * @class NetModel
 * @brief NetModel is a base class for specific network model
 *        It contains a pure virtual function Run which must be implemented
 *        in derived class
 */
class NetModel {
 public:
  /**
   * @brief Constructor
   */
  NetModel() = default;

  /**
   * @brief Destructor
   */
  virtual ~NetModel() = default;

  /**
   * @brief Compute the model output from inputs
   * @param Inputs to a network
   * @param Output of a network will be returned
   */
  virtual void Run(const std::vector<Eigen::MatrixXf>& inputs,
                   Eigen::MatrixXf* output) const = 0;

  /**
   * @brief Set the internal state of a network model
   * @param A specified internal state in a vector of Eigen::MatrixXf
   */
  virtual void SetState(const std::vector<Eigen::MatrixXf>& states) {}

  /**
   * @brief Access to the internal state of a network model
   * @return Internal state in a vector of Eigen::MatrixXf of the model
   */
  virtual void State(std::vector<Eigen::MatrixXf>* states) const {}

  /**
   * @brief Set the internal state of a model
   * @param A specified internal state in a vector of Eigen::MatrixXf
   */
  virtual void ResetState() const {}

  /**
   * @brief Load network parameters from a protobuf message
   * @param NetParameter is a protobuf message
   * @return True if successfully loaded, otherwise False
   */
  bool LoadModel(const NetParameter& net_parameter);

  /**
   * @brief Shows the performance information of a network
   * @return Performance of a network model
   */
  std::string PerformanceString() const;

  /**
   * @brief Name of a network model
   * @return Name of a network model
   */
  const std::string& Name() const;

  /**
   * @brief Id of a network model
   * @return Id of a network model
   */
  int Id() const;

  /**
   * @brief Indicate the state of a network model
   * @return True of a network model is load successively, otherwise False.
   */
  bool IsOk() const;

 protected:
  std::vector<std::unique_ptr<Layer>> layers_;
  NetParameter net_parameter_;
  bool ok_ = false;
};

}  // namespace network
}  // namespace prediction
}  // namespace apollo

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Wesnick\Infusionsoft\Command;

use KzykHys\ClassGenerator\Builder\ClassBuilder;
use KzykHys\ClassGenerator\Builder\MethodBuilder;
use KzykHys\ClassGenerator\Builder\PropertyBuilder;
use KzykHys\ClassGenerator\Compiler\Compiler;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class InfusionsoftClassBuilderCommand extends Command
{

    protected function configure()
    {
        $this
            ->setName('wesnick:infusionsoft:classbuilder')
            ->setDescription('Build Proxy Classes for Infusionsoft Web Service')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $simple = simplexml_load_file(__DIR__ . '/../../../../doc/api_field_access.xml');

        $api = array();

        /** @var $table \SimpleXMLElement */
        foreach ($simple->table as $table) {
            $attr = $table->attributes();
            $name = (string) $attr['name'];
            foreach ($table as $key => $node) {

                switch ($key) {
                    case 'fields':
                        $value = $this->processFieldDefinitions($node);
                        break;
                    case 'restriction':
                        $value = array();
                        foreach ($node as $rkey => $rvalue) {
                            $value[$rkey] = (string) $rvalue;
                        }
                        break;
                    case 'description':
                    case 'table-name':
                    case 'sql-join':
                    case 'custom-field-table-name':
                    default:
                        $value = (string) $node;
                        break;
                }

                $api[$name][$key] = $value;
            }
        }

        foreach ($api as $class => $rows) {
            $this->buildClass($class, $rows);
        }
    }

    private function processFieldDefinitions($nodeValue)
    {
        $fields = array();
        foreach ($nodeValue->field as $field) {
            $attr = $field->attributes();
            $type = (string) $attr['type'];
            $phpType = 'string';
            $options = array();
            switch ($type) {
                case 'String':
                case 'Blog':
                    $phpType = 'string';
                    break;
                case 'Enum':
                    if (isset($field->options)) {
                        foreach ($field->options->option as $option) {
                            $options[(string) $option] = (string) $option;
                        }
                    }
                    $phpType = 'string';
                    break;
                case 'Date':
                case 'DateTime':
                    $phpType = '\DateTime';
                    break;
                case 'Double':
                    $phpType = 'float';
                    break;
                case 'Long':
                case 'Int':
                    $phpType = 'int';
                    break;
                case 'Boolean':
                    $phpType = 'bool';
                    break;
                case 'Id':
                    // If there is an explicit relationship, then we link the Type
                    if (isset($field->relationship)) {
                        $relationship = $field->relationship->attributes();

                        $relatedOrdinality = (string) $relationship['type'];
                        $relatedType = (string) $relationship['table'];
                        $phpType = ($relatedOrdinality === 'MANY_TO_MANY') ? 'array<' . $relatedType. '>' : $relatedType;
                    } else {
                        $phpType = 'int';
                    }
            }

            $fields[(string) $attr['name']] = array(
                'XMLType'   => (string) $attr['type'],
                'var'       => $phpType,
                'options'   => $options,
            );
        }
        return $fields;
    }

    private function buildClass($class, $rows)
    {

        $fileDir = __DIR__ . '/../Proxy';
        if (!file_exists($fileDir)) {
            mkdir($fileDir);
        }

        $namespace = "Wesnick\Infusionsoft\Proxy\\";
        $className = $namespace . $class;
        $file = $fileDir . '/' . $class . '.php';

        $classBuilder = new ClassBuilder();
        $classBuilder->setClass($className);
        $classBuilder->addImports("Wesnick\\Infusionsoft\\Remote\\BaseObject");
        $classBuilder->setExtends("BaseObject");

        $docblock[] = "class $class";
        $keys = array(
            'description',
            'table-name',
            'sql-join'
        );

        foreach ($keys as $key) {
            if (isset($rows[$key])) {
                $docblock[] = $rows[$key];
            }
        }

        $classBuilder->setDocblock($docblock);

        $propertyMap = array();

        foreach ($rows['fields'] as $fieldName => $field) {

            // Don't include dot delimited properties
            if (strpos($fieldName, ".") !== false) {
                continue;
            }

            $propertyBuilder = $this->processProperty($fieldName, $field);
            $propertyMap[] = "'" . $propertyBuilder->getName() . "' => '" . $propertyBuilder->getType() . "'";
            $classBuilder->addProperty($propertyBuilder);
        }

        $compiler = new Compiler(array(
            'indent_spaces' => '4',
            'lineFeed' => "\n"
        ));

        // Add our class property map
        $pb = new PropertyBuilder();
        $pb->setName('propertyMap');
        $pb->setType('array');
        $pb->setVisibility('protected static');
        $pb->setDefault('array(' . implode(", ", $propertyMap) . ')');
        $classBuilder->addProperty($pb);

        $streamWriter = $compiler->compile($classBuilder);
        $streamWriter->save($file);

    }

    private function processProperty($fieldName, $field)
    {

        $comments[] = $field['XMLType'];
        if ($field['options']) {
            $comments[] = 'Options: ' . implode(", ", $field['options']);
        }

        $propertyBuilder = new PropertyBuilder();
        $propertyBuilder->setName($fieldName);
        $propertyBuilder->setComments($comments);
        $propertyBuilder->setType($field['var']);
        $propertyBuilder->setVisibility('public');

        return $propertyBuilder;
    }

}


text:
const bcrypt = require('bcrypt');
const uniqid = require('uniqid');
const shuffle = require('lodash/shuffle');

// Require local dependencies
const mongoose = require('../services/mongoose');

// Spread mongoose
const { Schema, SchemaTypes: Types } = mongoose;

// Define schema
const UserSchema = new Schema({
    firstname: {
        type: Types.String,
        minlength: 2,
        maxlength: 24,
    },
    lastname: {
        type: Types.String,
        minlength: 2,
        maxlength: 24,
    },
    username: {
        type: Types.String,
        minlength: 6,
        maxlength: 24,
        required: true,
    },
    password: {
        type: Types.String,
        minlength: 6,
        maxlength: 64,
        required: true,
    },
    email: {
        type: Types.String,
        validate: [
            {
                validator: value => /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value),
                message: '{VALUE} is not email!',
            },
            {
                async validator(value) {
                    try {
                        // find user by email
                        const user = await this.constructor.findOne({
                            email: value,
                        });

                        // if not new, check user
                        if (!this.isNew) {
                            return !user || user._id.equals(this._id);
                        }

                        // check user
                        return !user;
                    } catch (err) {
                        return false;
                    }
                },
                message: '{VALUE} is not unique!',
            },
        ],
        minlength: 6,
        maxlength: 64,
        required: true,
    },
    token: {
        type: Types.String,
    },
    code: {
        type: Types.String,
    },
    status: {
        type: Types.String,
        enum: ['unconfirmed', 'forgotten', 'active'],
        default: 'unconfirmed',
    },
}, {
    timestamps: true,
});

// Define generate token method
UserSchema.methods.generateToken = function generateToken() {
    return uniqid() + shuffle(this._id.toString().split('')).join('');
};

// Define compare password method
UserSchema.methods.comparePassword = function comparePassword(password) {
    return bcrypt.compareSync(password, this.password);
};

// Define pre-save hook
UserSchema.pre('save', function save(done) {
    // bcrypt password
    if (this.isNew || this.isModified('password')) {
        this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(10), null);
    }

    // hook is done
    done();
});

// Define model
const User = mongoose.model('User', UserSchema);

// Export model
module.exports = User;


text:
DROP TABLE CLONE_DIFF_MOUSE CASCADE CONSTRAINTS PURGE
/

--
-- CLONE_DIFF_MOUSE  (Table)
--
CREATE TABLE CLONE_DIFF_MOUSE ( IMAGE_ID VARCHAR2(50 BYTE) NOT NULL ) TABLESPACE CABIO_MAP_FUT LOGGING NOCOMPRESS NOCACHE NOPARALLEL MONITORING
/


text:
Code

{% highlight js %}
Ink.requireModules(['Ink.Util.String_1'], function(InkString) {

    var result1 = InkString.htmlEntitiesDecode('<p>text with a <a href="#">link</a></p>');
    Ink.log(result1); //
text sample with a link

});
{% endhighlight %}


text:
Factory.define :research_advancement do |f|
  f.reason "For the hell of it."
  f.parameter "technology_cost"
  f.adjustment -1 * rand(5)
  f.association :state
end


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeightLarge">

    <RelativeLayout
        android:id="@+id/item_contain_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?attr/selectableItemBackground"
        android:clickable="true"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingTop="@dimen/activity_vertical_margin">

        <CheckBox
            android:id="@+id/select_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_centerInParent="true"
            android:layout_marginStart="@dimen/activity_horizontal_margin"
            android:gravity="center"
            android:visibility="gone" />

        <ImageView
            android:id="@+id/iv_file_image"
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:layout_marginStart="@dimen/activity_horizontal_margin"
            android:layout_toEndOf="@id/select_checkbox"
            android:gravity="center"
            android:padding="1dp"
            android:scaleType="centerCrop" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="10dp"
            android:layout_toEndOf="@+id/iv_file_image"
            android:orientation="vertical"
            android:paddingStart="12dp"
            android:paddingTop="5dp">

            <TextView
                android:id="@+id/tv_file_name"
                style="@style/TextAppearance.AppCompat.Body1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="middle"
                android:maxLines="1"
                android:textSize="16sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/tv_file_size"
                    style="@style/TextAppearance.AppCompat.Widget.ActionMode.Subtitle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="@dimen/default_margin"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:paddingTop="3dp"
                    android:textSize="13sp" />

                <TextView
                    android:id="@+id/tv_file_modified_time"
                    style="@style/TextAppearance.AppCompat.Widget.ActionMode.Subtitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:paddingTop="3dp"
                    android:textSize="13sp" />
            </LinearLayout>

        </LinearLayout>

    </RelativeLayout>
</FrameLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="talkback_service_description">TalkBack är en skärmläsare som främst är avsedd för personer med helt eller delvis nedsatt syn så att de kan använda enheten med hjälp av talad feedback.</string>
  <string name="welcome_to_talkback_text">Få talad feedback så att du kan använda klockan utan att titta på skärmen.</string>
</resources>


text:
package com.quyeying.charity.storage.controller;

import com.quyeying.charity.commons.IResultDto;
import com.quyeying.charity.commons.ResultDto;
import com.quyeying.charity.domain.Goods;
import com.quyeying.charity.goods.service.GoodsRepository;
import com.quyeying.charity.storage.dto.GoodsSaleDto;
import com.quyeying.framework.utils.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * User: bysun
 * Date: 2014/7/19
 * Time: 15:44
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    protected Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Resource(name = "goodsRepository")
    private GoodsRepository repo;

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView sale(String salesStr) {
        JsonMapper mapper = JsonMapper.nonDefaultMapper();
        List<GoodsSaleDto> sales = mapper.fromJson(
            salesStr,
            mapper.contructCollectionType(List.class, GoodsSaleDto.class)
        );
        for (GoodsSaleDto sale : sales) {
            sale.setGoods(repo.findOne(sale.getId()));
        }
        ModelAndView result = new ModelAndView("storage/order");
        result.addObject("salesJson", JsonMapper.nonDefaultMapper().toJson(sales));
        result.addObject("sales", sales);
        return result;
    }

    @RequestMapping(method = RequestMethod.PUT)
    public @ResponseBody IResultDto confirm(@RequestBody List<GoodsSaleDto> datas) {

        for (GoodsSaleDto data : datas) {
            Goods goods = repo.findOne(data.getId());

            List<Goods.SaleInfo> sales = goods.getSaleInfos();
            if (null == sales)
                sales = new ArrayList<>();

            sales.add(data.toSaleInfo());

            goods.setSaleInfos(sales);

            repo.save(goods);
        }

        return ResultDto.get(true,"操作成功!");
    }

}


text:
package.cpath = package.cpath .. ';./build/?.so'

-- clang -cc1 -ast-dump your_file.c
-- clang -Xclang -ast-dump -fsyntax-only your_file.c

local clang = require 'luaclang-parser'
--local sqlite3 = require 'luasql.sqlite3'.sqlite3

-- from http://stevedonovan.github.com/Penlight/api/modules/pl.text.html#format_operator
do
  local format = string.format

  -- a more forgiving version of string.format, which applies
  -- tostring() to any value with a %s format.
  local function formatx (fmt,...)
    local args = {...}
    local i = 1
    for p in fmt:gmatch('%%.') do
      if p == '%s' and type(args[i]) ~= 'string' then
        args[i] = tostring(args[i])
      end
      i = i + 1
    end
    return format(fmt,unpack(args))
  end

  -- Note this goes further than the original, and will allow these cases:
  -- 1. a single value
  -- 2. a list of values
  getmetatable("").__mod = function(a, b)
    if b == nil then
      return a
    elseif type(b) == "table" then
      return formatx(a,unpack(b))
    else
      return formatx(a,b)
    end
  end
end

do
  local start = os.clock()
  local lastTime = start
  function SECTION(...)
    local now = os.clock()
    local line = debug.getinfo(2).currentline
    local func_name = debug.getinfo(2).name or "__main__"
    print(("[%6.3f/%6.3f] %s:%d"):format(now-start, now-lastTime, func_name, line), ...)
    lastTime = now
  end
end

do
  local cache = setmetatable({}, {__mode="k"})
  function getExtent(file, fromRow, fromCol, toRow, toCol)
    if not file then
      DBG(file, fromRow, fromCol, toRow, toCol)
      return ''
    end
    if toRow - fromRow > 3 then
      return ('%s: %d:%d - %d:%d'):format(file, fromRow, fromCol, toRow, toCol)
    end
    if not cache[file] then
      local f = assert(io.open(file))
      local t, n = {}, 0
      for l in f:lines() do
        n = n + 1
        t[n] = l
      end
      cache[file] = t
    end
    local lines = cache[file]
    if not (lines and lines[fromRow] and lines[toRow]) then
      DBG('!!! Missing lines '..fromRow..'-'..toRow..' in file '..file)
      return ''
    end
    if fromRow == toRow then
      return lines[fromRow]:sub(fromCol, toCol-1)
    else
      local res = {}
      for i=fromRow, toRow do
        if i==fromRow then
          res[#res+1] = lines[i]:sub(fromCol)
        elseif i==toRow then
          res[#res+1] = lines[i]:sub(1,toCol-1)
        else
          res[#res+1] = lines[i]
        end
      end
      return table.concat(res, '\n')
    end
  end
end

SECTION "Start"
SECTION 'Creating index'
local index = clang.createIndex(false, true)
SECTION 'Creating index ...'

SECTION 'Creating translation unit'
local tu = assert(index:parse(arg))
SECTION 'Creating translation unit ...'

local function trim(s)
  local from = s:match"^%s*()"
  local res = from > #s and "" or s:match(".*%S", from)
  return (res:gsub('&', '&'):gsub('<', '<'):gsub('>', '>'):gsub('"', '"'))
end

local function xprint(fmt, ...)
  local line = debug.getinfo(2).currentline
  local func_name = debug.getinfo(2).name or "__main__"
  local args = {...}
  local i = 1
  for p in fmt:gmatch('%%.') do
    if p == '%s' and type(args[i]) ~= 'string' then
      args[i] = tostring(args[i])
    end
    i = i + 1
  end

  fmt = "%s():%d: "..fmt
  print( fmt:format( func_name, line, unpack(args)) )
end

local function sprint(fmt, ...)
  local line = debug.getinfo(2).currentline
  local func_name = debug.getinfo(2).name or "__main__"
  local args = {...}
  local i = 1
  for p in fmt:gmatch('%%.') do
    if p == '%s' and type(args[i]) ~= 'string' then
      args[i] = tostring(args[i])
    end
    i = i + 1
  end

  fmt = "%s():%d: "..fmt
  return( fmt:format( func_name, line, unpack(args)) )
end

local function visitAST2(cur)
  local tag = cur:kind()
  local name = trim(cur:name())
  local attr = ' name="' .. name .. '"'
  local dname = trim(cur:displayName())
  if dname ~= name then
    attr = attr .. ' display="' .. dname .. '"'
  end
  attr = attr ..' text="' .. trim(getExtent(cur:location())) .. '"'
  if tag == "ParmDecl" or tag == "TypeRef" then
    return
  end
  local children = cur:children()
  if #children == 0 then
    if tag == "FunctionDecl" then
      local result_type = cur:resultType()
      xprint("\t tag=%s, %s, return=%s", tag, attr, tostring(result_type:name()))
    else
      xprint("\t tag=%s, %s", tag, attr)
    end
  else
    local result_type = cur:resultType()
    local func_type
    if tag == "FunctionDecl" then
      result_type = result_type:canonical()
      func_type = cur:type()
    end
    xprint("\t tag=%s, %s, return=%s, type=%s"
    , tag, attr
    , tostring(result_type and result_type:name())
    , tostring(func_type)
    )
    for _,c in ipairs(children) do
      visitAST(c)
    end
    --xprint("\t --tag=%s, name=%s",  tag, name)
  end
end
local __func__decls = {}
local primitive_type_list = {
  "Void",
  "Int", "UInt",
  "Long" , "ULong",
  "Short", "UShort",
  "LongLong", "ULongLong",
  "Char_S", "UChar"
}

local primitive_type_map
local function isPrimitiveType(_type)
  if not primitive_type_map then
    primitive_type_map = {}
    for _, xtype in ipairs(primitive_type_list) do
      primitive_type_map[ xtype ] = true
    end
  end
  return primitive_type_map [tostring(_type)] or false
end

local function toType(xtype)
  if tostring(xtype) == "Pointer" then
    return xtype
  end
  return xtype:canonical()
end

local last_func
local errmsg = ""
local function visitAST(cur)
  local kind = cur:kind()
  --xprint("kind=%s", kind)

  if kind == "FunctionDecl" then
    local f = {}
    f.func_name = trim(cur:name())
    f.func_dname = trim(cur:displayName())
    f.func_fname, f.func_line = cur:location()
    f.return_t = assert(cur:resultType())

    f.return_t = toType(f.return_t)
    xprint(" func=%s, dname=%s, loc=%s:%d, return_t=%s, \n\t\t is_primitive = %s",
    f.func_name, f.func_dname, f.func_fname, f.func_line,  f.return_t
    , isPrimitiveType(f.return_t))
    __func__decls[f.func_name] = f
    last_func = f.func_name

  elseif kind == "CallExpr" then
    local func_name = trim(cur:name())
    if func_name == "gc_root_new"  or func_name == "gc_root_new_with_complex_return" then
      assert(last_func)
      local f = __func__decls[last_func]
      if func_name == "gc_root_new" then
        if (not isPrimitiveType(f.return_t)) then
          local msg = sprint (" error: call gc_root_new() within %s:%d:%s(), return_t=%s, isPrimitiveType=%s\n",
          f.func_fname, f.func_line, f.func_name, f.return_t
          , isPrimitiveType(f.return_t))
          errmsg = errmsg .. msg
        end
      elseif func_name == "gc_root_new_with_complex_return" then
        --assert(isPrimitiveType(f.return_t) == false)
        if (isPrimitiveType(f.return_t)) then
          local msg = sprint (" error: call gc_root_new_with_complex_return() within %s:%d:%s(), return_t=%s, p=%s",
          f.func_fname, f.func_line, f.func_name, f.return_t
          , isPrimitiveType(f.return_t))
          errmsg = errmsg .. msg
        end
      end
    end
  end

  local childrens = cur:children()
  if #childrens > 0 then
    for _,c in ipairs(childrens) do
      local c_kind =s
      if c then
        c_kind = c:kind()
      else
        c_kind = "nil"
      end
      visitAST(c)
    end
  end
end

do
  local diagnostics = tu:diagnostics()
  if diagnostics and #diagnostics > 0 then
    for _,v in ipairs(diagnostics) do
      xprint("category=%s, text=%s", v.category, v.text)
    end
    os.exit(0)
  end
end

SECTION "visit AST ... begin"
xprint("tu=%s",tu)
visitAST(tu:cursor())
SECTION "visit AST ... end"
if #errmsg > 0 then
  xprint("\n\n...... [%s] has errors...... \n\n%s" ,arg[1], errmsg)
else
  print("")
  xprint("...... [%s] looks good ......", arg[1])
  print("")
end
SECTION "all finish"
os.exit(0)


text:
1. [Overview](#overview)
2. [Module Description - What the module does and why it is useful](#module-description)
3. [Setup - The basics of getting started with wget](#setup)
4. [Usage - Configuration options and additional functionality](#usage)
5. [Reference - An under-the-hood peek at what the module is doing and how](#reference)
5. [Limitations - OS compatibility, etc.](#limitations)
6. [Development - Guide for contributing to the module](#development)

## Overview

This module has two main purposes:

- Manage the *static* data associated with the ```wget``` package
- Provide a wrapper around binaries in the ```wget``` package that are useful inside Puppet configuration

## Module Description

The *static* data associated with the binaries contained in the ```wget``` package are stored in a puppet module data Hiera store. This allows higer level Hiera lookups to override binary paths, configuration files, etc...

## Setup

```
puppet module install -i /path/to/moudles bi-bi_wget
```

## Usage

### Consistent static data

To use the *statc* data (for instance in another ```class``` or ```define```):

```puppet

define my_define() {
    require bi_wget
    ...
    notify ("The wget binary is $bi_wget::$exe_path")
}

```

This allows an end user a consistent location to obtain the binary paths of executables that will be updated via the module data for each platform (or overridden for custom binaries).

### Executable wrappers

The binary *wrapper* for useful programs contained in ```wget``` for example:

```puppet

define my_define() {
    bi_wget::wget { 'http://mirror.centos.org/centos/6/os/x86_64/RPM-GPG-KEY-CentOS-Debug-6':
        output_document => '/etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-Debug-6-test-2',
        owner => 'vagrant',
        group => 'vagrant',
        mode => '654',
        no_clobber => true,
    }
}

```

## Reference

For more information see the projects [wiki](https://github.com/boundedinfinity/bi-puppet-wget/wiki)

## Limitations

## Development

For more information see the projects [wiki](https://github.com/boundedinfinity/bi-puppet-wget/wiki)


text:
@interface LoginViewController : UIViewController

@property (nonatomic, strong) IBOutlet UITextField *userName;

@end


text:
#include <cmath>
#include <memory>
#include <unordered_map>

#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/tensor_bundle/tensor_bundle.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"

namespace tensorflow {
using str_util::Split;
using str_util::StringReplace;
using strings::StrCat;

namespace graph_transforms {

// Sparsify Tensor of shape [N, 1]. Return the indices and values vectors for
// non-zero tensor content.
Status SparsifyWeights(const Tensor& tensor, Tensor* indices_tensor,
                       Tensor* values_tensor) {
  if (tensor.dims() != 2 || tensor.dim_size(1) != 1) {
    return tensorflow::errors::FailedPrecondition(
        "Transform only applicable to subgraph with 'Const' with "
        "tensor of shape [N, 1]. But instead get shape ",
        tensor.shape().DebugString(), ".");
  }

  auto flat = tensor.flat<float>();
  std::vector<int64> indices;
  std::vector<float> values;

  for (int64 i = 0; i < flat.size(); i++) {
    float val = flat(i);
    if (std::abs(val) >= 1.0e-5) {
      indices.push_back(i);
      values.push_back(val);
    }
  }

  // During model initialization, InitializeTableOp makes use of
  // KeyValueTensorIterator, which does not accept empty keys or values.
  // Consequently, adding a dummy pair of indices and values as a walkaround.
  if (indices.empty() || values.empty()) {
    indices.push_back(0);
    values.push_back(0);
  }
  *indices_tensor = Tensor(DataTypeToEnum<int64>::value,
                           {static_cast<int64>(indices.size())});
  std::copy_n(indices.begin(), indices.size(),
              indices_tensor->flat<int64>().data());

  *values_tensor =
      Tensor(DataTypeToEnum<float>::value, {static_cast<int64>(values.size())});
  std::copy_n(values.begin(), values.size(),
              values_tensor->flat<float>().data());

  return Status::OK();
}

void CreateConstNode(const Tensor& tensor, const string& name,
                     NodeDef* node_def) {
  node_def->set_op("Const");
  node_def->set_name(name);
  SetNodeTensorAttr<float>("value", tensor, node_def);
}

string GetMonolithicTensorKey(const string& tensor_slice_name) {
  std::vector<string> names = Split(tensor_slice_name, "/");
  if (absl::StartsWith(names[names.size() - 1], "part_")) {
    CHECK_GE(names.size(), 2);
    names.pop_back();
  }
  return absl::StrJoin(names, "/");
}

Status ObtainTensorSlice(const GraphDef& input_graph_def,
                         const string& target_name,
                         string* shape_slice_string) {
  string restore_node_name;
  for (const auto& node : input_graph_def.node()) {
    std::vector<string> node_name_parts = Split(node.name(), "/");
    if (node_name_parts.size() == 2 &&
        absl::StartsWith(node_name_parts[0], "save") &&
        absl::StartsWith(node_name_parts[1], "Assign") &&
        node.input(0) == target_name) {
      restore_node_name = node.input(1);
      break;
    }
  }

  std::vector<string> restore_node_parts = Split(restore_node_name, ":");
  CHECK_LE(restore_node_parts.size(), 2);
  string tensor_names_node;
  string shape_and_slices_node;
  for (const auto& node : input_graph_def.node()) {
    if ((node.name() == restore_node_parts[0]) && (node.op() == "RestoreV2")) {
      tensor_names_node = node.input(1);
      shape_and_slices_node = node.input(2);
      break;
    }
  }

  int offset = -1;
  for (const auto& node : input_graph_def.node()) {
    if (node.name() == tensor_names_node) {
      Tensor tensor_names_tensor;
      TF_RETURN_IF_ERROR(GetNodeAttr(node, "value", &tensor_names_tensor));
      const auto& tensor_names_value = tensor_names_tensor.flat<tstring>();
      for (int i = 0; i < tensor_names_value.size(); i++) {
        if (tensor_names_value(i) == GetMonolithicTensorKey(target_name)) {
          offset = i;
          break;
        }
      }
    }
  }
  if (offset == -1) {
    return errors::Internal("Unable to find RestoreV2 entry for variable: ",
                            target_name);
  }
  for (const auto& node : input_graph_def.node()) {
    if (node.name() == shape_and_slices_node) {
      Tensor shape_and_slices_tensor;
      TF_RETURN_IF_ERROR(GetNodeAttr(node, "value", &shape_and_slices_tensor));
      const auto& shape_and_slices_value =
          shape_and_slices_tensor.flat<tstring>();
      *shape_slice_string = shape_and_slices_value(offset);
      return Status::OK();
    }
  }
  return errors::Internal("Unable to find slice for variable: ", target_name);
}

Status ReadTensorFromCheckpoint(
    const string& tensor_name, const std::unique_ptr<BundleReader>& ckpt_reader,
    const string& shape_and_slice, Tensor* tensor) {
  if (ckpt_reader) {
    TensorShape parsed_full_shape;
    TensorSlice parsed_slice;
    TensorShape parsed_slice_shape;

    bool get_slice = false;
    if (!shape_and_slice.empty()) {
      TF_RETURN_IF_ERROR(
          checkpoint::ParseShapeAndSlice(shape_and_slice, &parsed_full_shape,
                                         &parsed_slice, &parsed_slice_shape));
      get_slice = (parsed_full_shape != parsed_slice_shape);
    }
    if (get_slice) {
      TF_RETURN_IF_ERROR(ckpt_reader->LookupSlice(
          GetMonolithicTensorKey(tensor_name), parsed_slice, tensor));
    } else {
      TF_RETURN_IF_ERROR(
          ckpt_reader->Lookup(GetMonolithicTensorKey(tensor_name), tensor));
    }
    return Status::OK();
  }
  return errors::Internal("Checkpoint reader was not initialized. ");
}

Status InitializeCheckpointReader(const TransformFuncContext& context,
                                  std::unique_ptr<BundleReader>* ckpt_reader) {
  if (context.params.count("input_checkpoint")) {
    const string input_checkpoint = context.params.at("input_checkpoint")[0];
    ckpt_reader->reset(new BundleReader(Env::Default(), input_checkpoint));
    TF_RETURN_IF_ERROR((*ckpt_reader)->status());
  }
  return Status::OK();
}

Status ObtainVariableInfo(
    const GraphDef& input_graph_def,
    std::unique_ptr<std::unordered_map<string, string> >* shapes_and_slices) {
  shapes_and_slices->reset(new std::unordered_map<string, string>());
  for (const auto& node : input_graph_def.node()) {
    if ((node.op() == "Variable") || (node.op() == "VariableV2")) {
      string s;
      TF_RETURN_IF_ERROR(ObtainTensorSlice(input_graph_def, node.name(), &s));
      (**shapes_and_slices)[node.name()] = s;
    }
  }
  return Status::OK();
}

Status RemoveInputAtIndex(NodeDef* n, int index) {
  for (int i = index; i < n->input_size() - 1; i++) {
    n->mutable_input()->SwapElements(i, i + 1);
  }
  n->mutable_input()->RemoveLast();
  return Status::OK();
}

Status RemoveNodeAtIndex(GraphDef* g, int index) {
  for (int i = index; i < g->node_size() - 1; i++) {
    g->mutable_node()->SwapElements(i, i + 1);
  }
  g->mutable_node()->RemoveLast();
  return Status::OK();
}

Status SparsifyGatherInternal(
    const GraphDef& input_graph_def,
    const std::unique_ptr<std::unordered_map<string, string> >&
        shapes_and_slices,
    const TransformFuncContext& context, const OpTypePattern& pattern,
    const std::unique_ptr<BundleReader>& ckpt_reader,
    GraphDef* output_graph_def) {
  string group_init_node = "group_deps";
  if (context.params.count("group_init_node")) {
    group_init_node = context.params.at("group_init_node")[0];
  }
  GraphDef current_graph_def = input_graph_def;
  bool any_match_found = false;

  // Populate references.
  std::unordered_map<string, int> refs;
  for (const auto& node : current_graph_def.node()) {
    for (const auto& input : node.input()) {
      auto parsed_input = StringReplace(input, "^", "", true);
      refs[parsed_input] += 1;
    }
  }

  // The subgraphs may have overlapping components, therefore GraphMatcher
  // doesn't return all subgraphs in one round -- this has to be multi-round
  // update.
  do {
    any_match_found = false;
    GraphDef replaced_graph_def = current_graph_def;
    std::vector<string> init_table_node_names;
    std::vector<string> removed_node_names;

    TF_RETURN_IF_ERROR(ReplaceMatchingOpTypes(
        current_graph_def, pattern,
        [&ckpt_reader, &any_match_found, &init_table_node_names,
         &shapes_and_slices, &removed_node_names,
         &refs](const NodeMatch& match, const std::set<string>& input_nodes,
                const std::set<string>& output_nodes,
                std::vector<NodeDef>* new_nodes) {
          any_match_found = true;

          // The captured subgraph should be of the following pattern:
          // Const --> Identity --> Gather --> ...
          //                          ^
          //                          |
          //                        (ids)
          //
          // After transform, it becomes:
          //                   --> NoOp(group_deps)
          //                   |
          // Const --> InitializeTable --> HashTable
          //                   ^              |
          //                   |              |
          // Const -------------              |
          //                                  v
          //               (ids) ---> LookupTableFind <--- Const(default)
          //                                  |
          //                                  v
          //                                 ...

          // clang-format off
          // For each subgraph, do the following
          // 1. Sparsify the `Const`, creating two `Const`, for hashtable
          // key/val.
          // 2. Create a `InitializeTable` op connecting to the above 2 `Const`.
          // 3. Create a `HashTable` op connecting to `InitializeTable` op.
          // 4. Replace the `Gather` with a `LookupTableFind` op.
          // 5. Connect the `LookupTableFind` with
          //    a. `HashTable`
          //    b. `Gather`'s ids input
          //    c. a `default_val` arg, valued at 0
          // clang-format on
          const NodeDef& gather_node = match.node;

          // GatherV2 adds an "axis" parameter. sparsify_gather only supports
          // axis 0 gathers.
          if (gather_node.op() == "GatherV2") {
            // Per the OpTypePattern, the 3rd input to Gather must be a Const.
            const NodeDef& axis_node = match.inputs[2].node;

            Tensor axis_t;
            TF_RETURN_IF_ERROR(GetNodeAttr(axis_node, "value", &axis_t));
            int64 axis = 0;
            if (axis_t.dtype() == DT_INT32) {
              axis = axis_t.scalar<int32>()();
            } else if (axis_t.dtype() == DT_INT64) {
              axis = axis_t.scalar<int64>()();
            } else {
              return tensorflow::errors::FailedPrecondition(
                  "Gather axis was not int32 or int64.");
            }

            if (axis != 0) {
              return tensorflow::errors::FailedPrecondition(
                  "Transform only applicable to subgraph with GatherV2 over "
                  "axis 0. Found axis ",
                  axis, ".");
            }
          }

          const NodeDef& weights_node = match.inputs[0].inputs[0].node;

          DataType data_type;
          TF_RETURN_IF_ERROR(GetNodeAttr(weights_node, "dtype", &data_type));
          if (data_type != DT_FLOAT) {
            return tensorflow::errors::FailedPrecondition(
                "Transform only applicable to subgraph with 'Const',"
                "'Variable', or 'VariableV2' of dtype "
                "'DT_FLOAT'. Found '" +
                    weights_node.op() + "' with name '",
                weights_node.name(), "' and dtype '", data_type, "'.");
          }

          Tensor weight;
          if (weights_node.op() == "Const") {
            weight = GetNodeTensorAttr(weights_node, "value");
          } else {
            TF_RETURN_IF_ERROR(ReadTensorFromCheckpoint(
                weights_node.name(), ckpt_reader,
                (*shapes_and_slices)[weights_node.name()], &weight));
          }
          // Add both both weight and identity node names.
          removed_node_names.push_back(weights_node.name());
          removed_node_names.push_back(match.inputs[0].node.name());
          for (auto input_node : match.inputs[0].node.input()) {
            auto parsed_input = StringReplace(input_node, "^", "", true);
            refs[parsed_input]--;
          }
          Tensor indices_tensor;
          Tensor values_tensor;
          TF_RETURN_IF_ERROR(
              SparsifyWeights(weight, &indices_tensor, &values_tensor));

          // indices and values of sparsified `Const`
          DataType key_dtype = DT_INT64;
          NodeDef indices_node;
          CreateConstNode(indices_tensor,
                          StrCat(weights_node.name(), "/indices"),
                          &indices_node);
          SetNodeAttr("dtype", key_dtype, &indices_node);

          NodeDef values_node;
          CreateConstNode(values_tensor, StrCat(weights_node.name(), "/values"),
                          &values_node);
          SetNodeAttr("dtype", data_type, &values_node);

          // HashTable node
          NodeDef hashtable_node;
          hashtable_node.set_op("HashTable");
          hashtable_node.set_name(StrCat(weights_node.name(), "/HashTable"));
          SetNodeAttr("key_dtype", key_dtype, &hashtable_node);
          SetNodeAttr("value_dtype", data_type, &hashtable_node);

          // InitializeTable node
          NodeDef init_table_node;
          init_table_node.set_op("InitializeTable");
          init_table_node.set_name(
              StrCat(weights_node.name(), "/InitializeTable"));
          SetNodeAttr("Tkey", key_dtype, &init_table_node);
          SetNodeAttr("Tval", data_type, &init_table_node);
          init_table_node_names.push_back(init_table_node.name());

          // LookupTableFind node
          NodeDef lookup_node;
          lookup_node.set_op("LookupTableFind");
          lookup_node.set_name(StrCat(gather_node.name(), "/LookupTableFind"));
          SetNodeAttr("Tin", key_dtype, &lookup_node);
          SetNodeAttr("Tout", data_type, &lookup_node);

          // Default return value of hashtable lookup
          Tensor zero_tensor(data_type, TensorShape({}));
          zero_tensor.flat<float>()(0) = 0.0;
          NodeDef default_value_node;
          CreateConstNode(zero_tensor, StrCat(gather_node.name(), "/Const"),
                          &default_value_node);
          SetNodeAttr("dtype", data_type, &default_value_node);

          // ExpandDims argument
          Tensor dim_idx(DT_INT32, TensorShape({}));
          dim_idx.flat<int32>()(0) = -1;
          NodeDef dim_idx_node;
          dim_idx_node.set_op("Const");
          dim_idx_node.set_name(
              StrCat(gather_node.name(), "/ExpandDims/Const"));
          SetNodeAttr("value", dim_idx, &dim_idx_node);
          SetNodeAttr("dtype", DT_INT32, &dim_idx_node);

          // ExpandDims node
          NodeDef expand_dims_node;
          expand_dims_node.set_op("ExpandDims");
          // Reuse gather_node's name so not to change dependent's inputs
          expand_dims_node.set_name(gather_node.name());
          SetNodeAttr("T", data_type, &expand_dims_node);

          // Connect nodes
          AddNodeInput(hashtable_node.name(), &init_table_node);
          refs[hashtable_node.name()]++;
          AddNodeInput(indices_node.name(), &init_table_node);
          refs[indices_node.name()]++;
          AddNodeInput(values_node.name(), &init_table_node);
          refs[values_node.name()]++;

          AddNodeInput(hashtable_node.name(), &lookup_node);
          refs[hashtable_node.name()]++;
          AddNodeInput(gather_node.input(1), &lookup_node);
          refs[gather_node.input(1)]++;
          AddNodeInput(default_value_node.name(), &lookup_node);
          refs[default_value_node.name()]++;

          AddNodeInput(lookup_node.name(), &expand_dims_node);
          refs[lookup_node.name()]++;
          AddNodeInput(dim_idx_node.name(), &expand_dims_node);
          refs[dim_idx_node.name()]++;

          // Copy 'ids' input of original 'Gather'
          new_nodes->push_back(match.inputs[1].node);
          new_nodes->push_back(indices_node);
          new_nodes->push_back(values_node);
          new_nodes->push_back(hashtable_node);
          new_nodes->push_back(init_table_node);
          new_nodes->push_back(lookup_node);
          new_nodes->push_back(default_value_node);
          new_nodes->push_back(dim_idx_node);
          new_nodes->push_back(expand_dims_node);

          return Status::OK();
        },
        {true}, &replaced_graph_def));

    NodeDef* init_op = nullptr;
    for (int i = 0; i < replaced_graph_def.node_size(); i++) {
      if (replaced_graph_def.node(i).name() == group_init_node &&
          replaced_graph_def.node(i).op() == "NoOp") {
        init_op = replaced_graph_def.mutable_node(i);
        break;
      }
    }
    if (!init_op) {
      // Init node
      init_op = replaced_graph_def.mutable_node()->Add();
      init_op->set_op("NoOp");
      init_op->set_name(group_init_node);
    }
    for (const string& name : init_table_node_names) {
      // Add control dependence from init_table_node to group_deps_node
      AddNodeInput(StrCat("^", name), init_op);
      refs[name]++;
    }

    // Erase inputs and outputs as they are not considered for deletion.
    for (const auto& output : context.output_names) {
      refs.erase(output);
    }

    for (const auto& input : context.input_names) {
      refs.erase(input);
    }

    // Add nodes with a reference count of 0 for deletion.
    for (auto entry : refs) {
      if (entry.second == 0) {
        removed_node_names.push_back(entry.first);
      }
    }

    while (!removed_node_names.empty()) {
      auto name = removed_node_names.back();
      removed_node_names.pop_back();

      int i = 0;
      while (i < replaced_graph_def.node_size()) {
        // Revisit this to see if we can safely remove RestoreV2 nodes.
        if ((replaced_graph_def.node(i).name() == name) &&
            (replaced_graph_def.node(i).op() != "RestoreV2")) {
          for (const auto& input : replaced_graph_def.node(i).input()) {
            auto parsed_input = StringReplace(input, "^", "", true);
            refs[parsed_input] -= 1;
            if (refs[parsed_input] == 0) {
              removed_node_names.push_back(parsed_input);
            }
          }
          TF_RETURN_IF_ERROR(RemoveNodeAtIndex(&replaced_graph_def, i));
          continue;
        }
        int j = 0;
        bool deleted_inputs = false;
        while (j < replaced_graph_def.node(i).input_size()) {
          if (replaced_graph_def.node(i).input(j) == name ||
              replaced_graph_def.node(i).input(j) == ("^" + name)) {
            TF_RETURN_IF_ERROR(
                RemoveInputAtIndex(replaced_graph_def.mutable_node(i), j));
            deleted_inputs = true;
            continue;
          }
          j++;
        }
        if (deleted_inputs) {
          if (replaced_graph_def.node(i).op() == "ConcatV2") {
            if (replaced_graph_def.node(i).input_size() > 2) {
              SetNodeAttr("N", replaced_graph_def.node(i).input_size() - 1,
                          replaced_graph_def.mutable_node(i));
            } else if (replaced_graph_def.node(i).input_size() == 2) {
              if (refs[replaced_graph_def.node(i).input(1)] != 1) {
                return errors::Internal(
                    "Expect axis tensor of ConcatV2 node to only be referenced "
                    "once.");
              }
              refs[replaced_graph_def.node(i).input(1)] -= 1;
              removed_node_names.push_back(replaced_graph_def.node(i).input(1));
              replaced_graph_def.mutable_node(i)->mutable_input()->RemoveLast();
              replaced_graph_def.mutable_node(i)->mutable_attr()->erase("N");
              replaced_graph_def.mutable_node(i)->set_op("Identity");
            } else {
              return errors::Internal(
                  "ConcatV2 should have at least two elements");
            }
          }
          if ((replaced_graph_def.node(i).op() == "Assign" ||
               replaced_graph_def.node(i).op() == "Reshape" ||
               replaced_graph_def.node(i).op() == "Equal" ||
               replaced_graph_def.node(i).op() == "Mean" ||
               replaced_graph_def.node(i).op() == "ScalarSummary") &&
              replaced_graph_def.node(i).input_size() == 1) {
            removed_node_names.push_back(replaced_graph_def.node(i).name());
          }
          if (!replaced_graph_def.node(i).input_size()) {
            removed_node_names.push_back(replaced_graph_def.node(i).name());
          }
        }
        i++;
      }
    }
    current_graph_def = replaced_graph_def;
  } while (any_match_found);
  *output_graph_def = current_graph_def;
  return Status::OK();
}

Status SparsifyGather(const GraphDef& input_graph_def,
                      const TransformFuncContext& context,
                      GraphDef* output_graph_def) {
  // clang-format off
  const OpTypePattern gather_pattern =
    {"Gather",
     {
       {"Identity",
        {
          {"Const|Variable|VariableV2"}
        }
       },
       {"*"},
     }
    };
  const OpTypePattern gather_v2_pattern =
    {"GatherV2",
      {
        {"Identity",
          {
            {"Const|Variable|VariableV2"}
          }
        },
        {"*"},
        // GatherV2's axis must be constant.
        {"Const"},
      }
    };
  // clang-format on

  GraphDef cleaned_input_graph_def;
  RemoveAttributes(input_graph_def, {"_output_shapes"},
                   &cleaned_input_graph_def);

  GraphDef temp_output;

  std::unique_ptr<BundleReader> ckpt_reader;
  TF_RETURN_IF_ERROR(InitializeCheckpointReader(context, &ckpt_reader));

  std::unique_ptr<std::unordered_map<string, string> > shapes_and_slices;
  TF_RETURN_IF_ERROR(
      ObtainVariableInfo(cleaned_input_graph_def, &shapes_and_slices));

  TF_RETURN_IF_ERROR(SparsifyGatherInternal(
      cleaned_input_graph_def, shapes_and_slices, context, gather_pattern,
      ckpt_reader, &temp_output));

  TF_RETURN_IF_ERROR(SparsifyGatherInternal(temp_output, shapes_and_slices,
                                            context, gather_v2_pattern,
                                            ckpt_reader, output_graph_def));

  return Status::OK();
}

REGISTER_GRAPH_TRANSFORM("sparsify_gather", SparsifyGather);

}  // namespace graph_transforms
}  // namespace tensorflow


text:
@implementation Person

@dynamic name;
@dynamic age;
@dynamic member;

@end


text:
#ifndef SkTypeface_win_DEFINED
#define SkTypeface_win_DEFINED

#include "SkTypeface.h"

/**
 *  Like the other Typeface create methods, this returns a new reference to the
 *  corresponding typeface for the specified logfont. The caller is responsible
 *  for calling unref() when it is finished.
 */
SK_API SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);

/**
 *  Copy the LOGFONT associated with this typeface into the lf parameter. Note
 *  that the lfHeight will need to be set afterwards, since the typeface does
 *  not track this (the paint does).
 *  typeface may be NULL, in which case we return the logfont for the default font.
 */
SK_API void SkLOGFONTFromTypeface(const SkTypeface* typeface, LOGFONT* lf);

#endif


text:
package org.zstack.sdk.iam2.api;

public class Permission  {

    public boolean allow;
    public void setAllow(boolean allow) {
        this.allow = allow;
    }
    public boolean getAllow() {
        return this.allow;
    }

}


text:
#include "config.h"
#include "DOMRectList.h"

#include "DOMRect.h"

namespace WebCore {

DOMRectList::DOMRectList(const Vector<FloatQuad>& quads)
{
    m_items.reserveInitialCapacity(quads.size());
    for (auto& quad : quads)
        m_items.uncheckedAppend(DOMRect::create(quad.boundingBox()));
}

DOMRectList::DOMRectList(const Vector<FloatRect>& rects)
{
    m_items.reserveInitialCapacity(rects.size());
    for (auto& rect : rects)
        m_items.uncheckedAppend(DOMRect::create(rect));
}

DOMRectList::~DOMRectList() = default;

} // namespace WebCore


text:
OSTYPE ?=

ifeq ($(OS),Windows_NT)
  OSTYPE = windows
else
  UNAME_S := $(shell uname -s)

  ifeq ($(UNAME_S),Linux)
    OSTYPE = linux
    lto := no

    ifneq (,$(shell which gcc-ar 2> /dev/null))
      AR = gcc-ar
      lto := yes
    endif

    ifdef LTO
      lto := yes
    endif
  endif

  ifeq ($(UNAME_S),Darwin)
    OSTYPE = osx
    lto := yes
  endif

  ifeq ($(UNAME_S),FreeBSD)
    OSTYPE = freebsd
    CXX = c++
    lto := no
  endif
endif

# Default settings (silent debug build).
config ?= debug
arch ?= native

ifndef verbose
  SILENT = @
else
  SILENT =
endif

ifneq ($(wildcard .git),)
tag := $(shell git describe --tags --always)
git := yes
else
tag := $(shell cat VERSION)
git := no
endif

package_version := $(tag)
archive = ponyc-$(package_version).tar
package = build/ponyc-$(package_version)

symlink := yes

ifdef destdir
  ifndef prefix
    symlink := no
  endif
endif

prefix ?= /usr/local
destdir ?= $(prefix)/lib/pony/$(tag)

LIB_EXT ?= a
BUILD_FLAGS = -mcx16 -march=$(arch) -Werror -Wconversion \
  -Wno-sign-conversion -Wextra -Wall
LINKER_FLAGS = -mcx16 -march=$(arch)
AR_FLAGS =
ALL_CFLAGS = -std=gnu11 -DPONY_VERSION=\"$(tag)\" -DPONY_COMPILER=\"$(CC)\" -DPONY_ARCH=\"$(arch)\"
ALL_CXXFLAGS = -std=gnu++11 -fno-rtti

PONY_BUILD_DIR   ?= build/$(config)
PONY_SOURCE_DIR  ?= src
PONY_TEST_DIR ?= test
LLVM_FALLBACK := /usr/local/opt/llvm/bin/llvm-config

ifdef use
  ifneq (,$(filter $(use), valgrind))
    ALL_CFLAGS += -DUSE_VALGRIND
    PONY_BUILD_DIR := $(PONY_BUILD_DIR)-valgrind
  endif
endif

ifdef config
  ifeq (,$(filter $(config),debug release))
    $(error Unknown configuration "$(config)")
  endif
endif

ifeq ($(config),release)
  BUILD_FLAGS += -O3 -DNDEBUG

  ifeq ($(lto),yes)
    BUILD_FLAGS += -flto -DPONY_USE_LTO
    LINKER_FLAGS += -flto

    ifdef LTO
      AR_FLAGS += --plugin $(LTO)
    endif

    ifeq ($(OSTYPE),linux)
      LINKER_FLAGS += -fuse-linker-plugin -fuse-ld=gold
    endif
  endif
else
  BUILD_FLAGS += -g -DDEBUG
endif

ifeq ($(OSTYPE),osx)
  ALL_CFLAGS += -mmacosx-version-min=10.8
  ALL_CXXFLAGS += -stdlib=libc++ -mmacosx-version-min=10.8
endif

ifndef LLVM_CONFIG
  ifneq (,$(shell which llvm-config 2> /dev/null))
    LLVM_CONFIG = llvm-config
  endif

  ifneq (,$(shell which llvm-config-3.6 2> /dev/null))
    LLVM_CONFIG = llvm-config-3.6
  endif

  ifneq (,$(shell which llvm-config36 2> /dev/null))
    LLVM_CONFIG = llvm-config36
  endif
endif

ifneq ("$(wildcard $(LLVM_FALLBACK))","")
  LLVM_CONFIG = $(LLVM_FALLBACK)
endif

ifndef LLVM_CONFIG
  $(error No LLVM 3.6 installation found!)
endif

$(shell mkdir -p $(PONY_BUILD_DIR))

lib   := $(PONY_BUILD_DIR)
bin   := $(PONY_BUILD_DIR)
tests := $(PONY_BUILD_DIR)
obj  := $(PONY_BUILD_DIR)/obj

# Libraries. Defined as
# (1) a name and output directory
libponyc  := $(lib)
libponycc := $(lib)
libponyrt := $(lib)

ifeq ($(OSTYPE),linux)
  libponyrt-pic := $(lib)
endif

# Define special case rules for a targets source files. By default
# this makefile assumes that a targets source files can be found
# relative to a parent directory of the same name in $(PONY_SOURCE_DIR).
# Note that it is possible to collect files and exceptions with
# arbitrarily complex shell commands, as long as ':=' is used
# for definition, instead of '='.
ifneq ($(OSTYPE),windows)
  libponyc.except += src/libponyc/platform/signed.cc
  libponyc.except += src/libponyc/platform/unsigned.cc
  libponyc.except += src/libponyc/platform/vcvars.c
endif

# Handle platform specific code to avoid "no symbols" warnings.
libponyrt.except =

ifneq ($(OSTYPE),windows)
  libponyrt.except += src/libponyrt/asio/iocp.c
  libponyrt.except += src/libponyrt/lang/win_except.c
endif

ifneq ($(OSTYPE),linux)
  libponyrt.except += src/libponyrt/asio/epoll.c
endif

ifneq ($(OSTYPE),osx)
  ifneq ($(OSTYPE),freebsd)
    libponyrt.except += src/libponyrt/asio/kqueue.c
  endif
endif

libponyrt.except += src/libponyrt/asio/sock.c
libponyrt.except += src/libponyrt/dist/dist.c
libponyrt.except += src/libponyrt/dist/proto.c

ifeq ($(OSTYPE),linux)
  libponyrt-pic.dir := src/libponyrt
  libponyrt-pic.except := $(libponyrt.except)
endif

# Third party, but requires compilation. Defined as
# (1) a name and output directory.
# (2) a list of the source files to be compiled.
libgtest := $(lib)
libgtest.dir := lib/gtest
libgtest.files := $(libgtest.dir)/gtest_main.cc $(libgtest.dir)/gtest-all.cc

ifeq ($(OSTYPE), linux)
  libraries := libponyc libponyrt libponyrt-pic libgtest
else
  libraries := libponyc libponyrt libgtest
endif

# Third party, but prebuilt. Prebuilt libraries are defined as
# (1) a name (stored in prebuilt)
# (2) the linker flags necessary to link against the prebuilt library/libraries.
# (3) a list of include directories for a set of libraries.
# (4) a list of the libraries to link against.
llvm.ldflags := $(shell $(LLVM_CONFIG) --ldflags)
llvm.include := -isystem $(shell $(LLVM_CONFIG) --includedir)
llvm.libs    := $(shell $(LLVM_CONFIG) --libs) -lz -lncurses

ifeq ($(OSTYPE), freebsd)
  llvm.libs += -lpthread
endif

prebuilt := llvm

# Binaries. Defined as
# (1) a name and output directory.
ponyc := $(bin)

binaries := ponyc

# Tests suites are directly attached to the libraries they test.
libponyc.tests  := $(tests)
libponyrt.tests := $(tests)

tests := libponyc.tests libponyrt.tests

# Define include paths for targets if necessary. Note that these include paths
# will automatically apply to the test suite of a target as well.
libponyc.include := -I src/common/ -I src/libponyrt/ $(llvm.include)/
libponycc.include := -I src/common/ $(llvm.include)/
libponyrt.include := -I src/common/ -I src/libponyrt/
libponyrt-pic.include := $(libponyrt.include)

libponyc.tests.include := -I src/common/ -I src/libponyc/ -isystem lib/gtest/
libponyrt.tests.include := -I src/common/ -I src/libponyrt/ -isystem lib/gtest/

ponyc.include := -I src/common/ -I src/libponyrt/ $(llvm.include)/
libgtest.include := -isystem lib/gtest/

ifneq (,$(filter $(OSTYPE), osx freebsd))
  libponyrt.include += -I /usr/local/include
endif

# target specific build options
libponyc.buildoptions = -D__STDC_CONSTANT_MACROS
libponyc.buildoptions += -D__STDC_FORMAT_MACROS
libponyc.buildoptions += -D__STDC_LIMIT_MACROS

ponyc.buildoptions = $(libponyc.buildoptions)

ifeq ($(OSTYPE), linux)
  libponyrt-pic.buildoptions += -fpic
endif

# target specific disabling of build options
libgtest.disable = -Wconversion -Wno-sign-conversion -Wextra

# Link relationships.
ponyc.links = libponyc libponyrt llvm
libponyc.tests.links = libgtest libponyc libponyrt llvm
libponyrt.tests.links = libgtest libponyrt

ifeq ($(OSTYPE),linux)
  ponyc.links += pthread dl
  libponyc.tests.links += pthread dl
  libponyrt.tests.links += pthread dl
endif

# Overwrite the default linker for a target.
ponyc.linker = $(CXX) #compile as C but link as CPP (llvm)

# make targets
targets := $(libraries) $(binaries) $(tests)

.PHONY: all $(targets)
all: $(targets)
	@:

# Dependencies
libponyc.depends := libponyrt
libponyc.tests.depends := libponyc libgtest
libponyrt.tests.depends := libponyrt libgtest
ponyc.depends := libponyc libponyrt

# Generic make section, edit with care.
##########################################################################
#                                                                        #
# DIRECTORY: Determines the source dir of a specific target              #
#                                                                        #
# ENUMERATE: Enumerates input and output files for a specific target     #
#                                                                        #
# CONFIGURE_COMPILER: Chooses a C or C++ compiler depending on the       #
#                     target file.                                       #
#                                                                        #
# CONFIGURE_LIBS: Builds a string of libraries to link for a targets     #
#                 link dependency.                                       #
#                                                                        #
# CONFIGURE_LINKER: Assembles the linker flags required for a target.    #
#                                                                        #
# EXPAND_COMMAND: Macro that expands to a proper make command for each   #
#                 target.                                                #
#                                                                        #
##########################################################################
define DIRECTORY
  $(eval sourcedir := )
  $(eval outdir := $(obj)/$(1))

  ifdef $(1).dir
    sourcedir := $($(1).dir)
  else ifneq ($$(filter $(1),$(tests)),)
    sourcedir := $(PONY_TEST_DIR)/$(subst .tests,,$(1))
    outdir := $(obj)/tests/$(subst .tests,,$(1))
  else
    sourcedir := $(PONY_SOURCE_DIR)/$(1)
  endif
endef

define ENUMERATE
  $(eval sourcefiles := )

  ifdef $(1).files
    sourcefiles := $$($(1).files)
  else
    sourcefiles := $$(shell find $$(sourcedir) -type f -name "*.c" -or -name\
      "*.cc" | grep -v '.*/\.')
  endif

  ifdef $(1).except
    sourcefiles := $$(filter-out $($(1).except),$$(sourcefiles))
  endif
endef

define CONFIGURE_COMPILER
  $(eval compiler := $(CC))
  $(eval flags := $(ALL_CFLAGS) $(CFLAGS) $(CXXFLAGS))

  ifeq ($(suffix $(1)),.cc)
    compiler := $(CXX)
    flags := $(ALL_CXXFLAGS)
  endif

  ifeq ($(suffix $(1)),.c)
    compiler := $(CC)
    flags := $(ALL_CFLAGS)
  endif
endef

define CONFIGURE_LIBS
  ifneq (,$$(filter $(1),$(prebuilt)))
    linkcmd += $($(1).ldflags)
    libs += $($(1).libs)
  else
    libs += -l$(subst lib,,$(1))
  endif
endef

define CONFIGURE_LINKER
  $(eval linkcmd := $(LINKER_FLAGS) -L $(lib))
  $(eval linker := $(CC))
  $(eval libs :=)

  ifdef $(1).linker
    linker := $($(1).linker)
  else ifneq (,$$(filter .cc,$(suffix $(sourcefiles))))
    linker := $(CXX)
  endif

  $(foreach lk,$($(1).links),$(eval $(call CONFIGURE_LIBS,$(lk))))
  linkcmd += $(libs) $($(1).linkoptions)
endef

define PREPARE
  $(eval $(call DIRECTORY,$(1)))
  $(eval $(call ENUMERATE,$(1)))
  $(eval $(call CONFIGURE_LINKER,$(1)))
  $(eval objectfiles  := $(subst $(sourcedir)/,$(outdir)/,$(addsuffix .o,\
    $(sourcefiles))))
  $(eval dependencies := $(subst .c,,$(subst .cc,,$(subst .o,.d,\
    $(objectfiles)))))
endef

define EXPAND_OBJCMD
$(eval file := $(subst .o,,$(1)))
$(eval $(call CONFIGURE_COMPILER,$(file)))

$(subst .c,,$(subst .cc,,$(1))): $(subst $(outdir)/,$(sourcedir)/,$(file))
	@echo '$$(notdir $$<)'
	@mkdir -p $$(dir $$@)
	$(SILENT)$(compiler) -MMD -MP $(filter-out $($(2).disable),$(BUILD_FLAGS)) \
    $(flags) $($(2).buildoptions) -c -o $$@ $$<  $($(2).include)
endef

define EXPAND_COMMAND
$(eval $(call PREPARE,$(1)))
$(eval ofiles := $(subst .c,,$(subst .cc,,$(objectfiles))))
$(eval depends := )
$(foreach d,$($(1).depends),$(eval depends += $($(d))/$(d).$(LIB_EXT)))

ifneq ($(filter $(1),$(libraries)),)
$($(1))/$(1).$(LIB_EXT): $(depends) $(ofiles)
	@echo 'Linking $(1)'
	$(SILENT)$(AR) -rcs $$@ $(ofiles) $(AR_FLAGS)
$(1): $($(1))/$(1).$(LIB_EXT)
else
$($(1))/$(1): $(depends) $(ofiles)
	@echo 'Linking $(1)'
	$(SILENT)$(linker) -o $$@ $(ofiles) $(linkcmd)
$(1): $($(1))/$(1)
endif

$(foreach ofile,$(objectfiles),$(eval $(call EXPAND_OBJCMD,$(ofile),$(1))))
-include $(dependencies)
endef

$(foreach target,$(targets),$(eval $(call EXPAND_COMMAND,$(target))))

define EXPAND_RELEASE
$(eval branch := $(shell git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,'))
ifneq ($(branch),master)
prerelease:
	$$(error "Releases not allowed on $(branch) branch.")
else
ifndef version
prerelease:
	$$(error "No version number specified.")
else
$(eval tag := $(version))
$(eval unstaged := $(shell git status --porcelain 2>/dev/null | wc -l))
ifneq ($(unstaged),0)
prerelease:
	$$(error "Detected unstaged changes. Release aborted")
else
prerelease: libponyc libponyrt ponyc
	@while [ -z "$$$$CONTINUE" ]; do \
	read -r -p "New version number: $(tag). Are you sure? [y/N]: " CONTINUE; \
	done ; \
	[ $$$$CONTINUE = "y" ] || [ $$$$CONTINUE = "Y" ] || (echo "Release aborted."; exit 1;)
	@echo "Releasing ponyc v$(tag)."
endif
endif
endif
endef

define EXPAND_INSTALL
install: libponyc libponyrt ponyc
	@mkdir -p $(destdir)/bin
	@mkdir -p $(destdir)/lib
	@mkdir -p $(destdir)/include
	@cp $(PONY_BUILD_DIR)/libponyrt.a $(destdir)/lib
	@cp $(PONY_BUILD_DIR)/libponyc.a $(destdir)/lib
	@cp $(PONY_BUILD_DIR)/ponyc $(destdir)/bin
	@cp src/libponyrt/pony.h $(destdir)/include
	@cp -r packages $(destdir)/
ifeq ($$(symlink),yes)
	@mkdir -p $(prefix)/bin
	@mkdir -p $(prefix)/lib
	@mkdir -p $(prefix)/include
	@ln -sf $(destdir)/bin/ponyc $(prefix)/bin/ponyc
	@ln -sf $(destdir)/lib/libponyrt.a $(prefix)/lib/libponyrt.a
	@ln -sf $(destdir)/lib/libponyc.a $(prefix)/lib/libponyc.a
	@ln -sf $(destdir)/include/pony.h $(prefix)/include/pony.h
endif
endef

$(eval $(call EXPAND_INSTALL))

uninstall:
	-@rm -rf $(destdir) 2>/dev/null ||:
	-@rm $(prefix)/bin/ponyc 2>/dev/null ||:
	-@rm $(prefix)/lib/libponyrt.a 2>/dev/null ||:
	-@rm $(prefix)/lib/libponyc.a 2>/dev/null ||:
	-@rm $(prefix)/include/pony.h 2>/dev/null ||:

test: all
	@$(PONY_BUILD_DIR)/libponyc.tests
	@$(PONY_BUILD_DIR)/libponyrt.tests
	@$(PONY_BUILD_DIR)/ponyc -s packages/stdlib
	@./stdlib
	@rm stdlib

ifeq ($(git),yes)
setversion:
	@echo $(tag) > VERSION

$(eval $(call EXPAND_RELEASE))

release: prerelease setversion
	@git add VERSION
	@git commit -m "Releasing version $(tag)"
	@git tag $(tag)
	@git push
	@git push --tags
	@git checkout release
	@git pull
	@git merge master
	@git push
	@git checkout $(branch)
endif

deploy: test
	@mkdir build/bin
	@mkdir -p $(package)/usr/bin
	@mkdir -p $(package)/usr/include
	@mkdir -p $(package)/usr/lib
	@mkdir -p $(package)/usr/lib/pony/$(package_version)/bin
	@mkdir -p $(package)/usr/lib/pony/$(package_version)/include
	@mkdir -p $(package)/usr/lib/pony/$(package_version)/lib
	@cp build/release/libponyc.a $(package)/usr/lib/pony/$(package_version)/lib
	@cp build/release/libponyrt.a $(package)/usr/lib/pony/$(package_version)/lib
	@cp build/release/ponyc $(package)/usr/lib/pony/$(package_version)/bin
	@cp src/libponyrt/pony.h $(package)/usr/lib/pony/$(package_version)/include
	@ln -s /usr/lib/pony/$(package_version)/lib/libponyrt.a $(package)/usr/lib/libponyrt.a
	@ln -s /usr/lib/pony/$(package_version)/lib/libponyc.a $(package)/usr/lib/libponyc.a
	@ln -s /usr/lib/pony/$(package_version)/bin/ponyc $(package)/usr/bin/ponyc
	@ln -s /usr/lib/pony/$(package_version)/include/pony.h $(package)/usr/include/pony.h
	@cp -r packages $(package)/usr/lib/pony/$(package_version)/
	@build/release/ponyc packages/stdlib -rexpr -g -o $(package)/usr/lib/pony/$(package_version)
	@fpm -s dir -t deb -C $(package) -p build/bin --name ponyc --version $(package_version) --description "The Pony Compiler"
	@fpm -s dir -t rpm -C $(package) -p build/bin --name ponyc --version $(package_version) --description "The Pony Compiler"
	@git archive release > build/bin/$(archive)
	@cp -r $(package)/usr/lib/pony/$(package_version)/stdlib-docs stdlib-docs
	@tar rvf build/bin/$(archive) stdlib-docs
	@bzip2 build/bin/$(archive)
	@rm -rf $(package) build/bin/$(archive) stdlib-docs

stats:
	@echo
	@echo '------------------------------'
	@echo 'Compiler and standard library '
	@echo '------------------------------'
	@echo
	@cloc --read-lang-def=pony.cloc src packages
	@echo
	@echo '------------------------------'
	@echo 'Test suite:'
	@echo '------------------------------'
	@echo
	@cloc --read-lang-def=pony.cloc test

clean:
	@rm -rf $(PONY_BUILD_DIR)
	-@rmdir build 2>/dev/null ||:
	@echo 'Repository cleaned ($(PONY_BUILD_DIR)).'

help:
	@echo
	@echo 'Usage: make [config=name] [arch=name] [use=opt,...] [target]'
	@echo
	@echo 'CONFIGURATIONS:'
	@echo '  debug (default)'
	@echo '  release'
	@echo
	@echo 'ARCHITECTURE:'
	@echo '  native (default)'
	@echo '  [any compiler supported architecture]'
	@echo
	@echo 'USE OPTIONS:'
	@echo '   valgrind'
	@echo
	@echo 'TARGETS:'
	@echo '  libponyc          Pony compiler library'
	@echo '  libponyrt         Pony runtime'
	@echo '  libponyrt-pic     Pony runtime -fpic'
	@echo '  libponyc.tests    Test suite for libponyc'
	@echo '  libponyrt.tests   Test suite for libponyrt'
	@echo '  ponyc             Pony compiler executable'
	@echo
	@echo '  all               Build all of the above (default)'
	@echo '  test              Run test suite'
	@echo '  install           Install ponyc'
	@echo '  uninstall         Remove all versions of ponyc'
	@echo '  stats             Print Pony cloc statistics'
	@echo '  clean             Delete all build files'
	@echo


text:
ActiveRecord::Schema.define(version: 20160822083838) do

#ActiveRecord::Schema.define(version: 20160821141921) do
#ActiveRecord::Schema.define(version: 20160817114445) do
  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "answers", force: :cascade do |t|
    t.integer  "question_id"
    t.string   "content"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "books", force: :cascade do |t|
    t.string   "name"
    t.string   "location"
    t.string   "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "user_id"
    t.integer  "host_id"
    t.datetime "start_at"
    t.datetime "end_at"
    t.index ["host_id"], name: "index_books_on_host_id", using: :btree
    t.index ["user_id"], name: "index_books_on_user_id", using: :btree
  end

  create_table "conversations", force: :cascade do |t|
    t.integer  "sender_id",      null: false
    t.string   "sender_type",    null: false
    t.integer  "recipient_id",   null: false
    t.string   "recipient_type", null: false
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
  end

  create_table "hosts", force: :cascade do |t|
    t.string   "name"
    t.string   "password_digest"
    t.string   "email"
    t.string   "phone_number"
    t.string   "document"
    t.string   "img_link"
    t.boolean  "is_super",        default: false
    t.datetime "created_at",                      null: false
    t.datetime "updated_at",                      null: false
    t.string   "description"
  end

  create_table "messages", force: :cascade do |t|
    t.text     "body"
    t.integer  "conversation_id", null: false
    t.integer  "user_id",         null: false
    t.string   "user_type",       null: false
    t.datetime "read_at"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.index ["conversation_id"], name: "index_messages_on_conversation_id", using: :btree
    t.index ["user_id", "user_type"], name: "index_messages_on_user_id_and_user_type", using: :btree
  end

  create_table "questions", force: :cascade do |t|
    t.integer  "survey_id"
    t.text     "content"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "reviews", force: :cascade do |t|
    t.string   "reviewable_type"
    t.integer  "reviewable_id"
    t.text     "content"
    t.integer  "user_id",         null: false
    t.string   "user_type",       null: false
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  create_table "surveys", force: :cascade do |t|
    t.string   "name"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.string   "phone_number"
    t.string   "password_digest"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.text     "description"
  end

  add_foreign_key "books", "hosts"
  add_foreign_key "books", "users"
end


text:
package com.digitalpetri.ethernetip.cip.logix.services

import com.digitalpetri.ethernetip.cip.epath.PaddedEPath
import com.digitalpetri.ethernetip.cip.logix.services.WriteTagService.WriteTagRequest
import com.digitalpetri.ethernetip.cip.logix.{CipStructure, LogixServiceCodes, TagType}
import com.digitalpetri.ethernetip.cip.structs.MessageRouterRequest
import com.digitalpetri.ethernetip.client.cip.services.AbstractInvokableService
import com.digitalpetri.ethernetip.util.Buffers
import io.netty.buffer.ByteBuf

import scala.util.Try

class WriteTagService(request: WriteTagRequest, requestPath: PaddedEPath) extends AbstractInvokableService[Unit] {

  override def getRequestData: ByteBuf = {
    val routerRequest = MessageRouterRequest(
      serviceCode = LogixServiceCodes.WriteTag,
      requestPath = requestPath,
      requestData = WriteTagRequest.encode(request))

    MessageRouterRequest.encode(routerRequest)
  }

  /**
   * Decode `responseData` and return a response.
   * @param responseData the [[ByteBuf]] containing the response data.
   * @return a decoded response.
   */
  override def decodeResponse(responseData: ByteBuf): Try[Unit] = Try(Unit)

}

object WriteTagService {

  case class WriteTagRequest(tagType: TagType, elements: Int, data: ByteBuf)

  object WriteTagRequest {

    def encode(request: WriteTagRequest, buffer: ByteBuf = Buffers.unpooled()): ByteBuf = {
      request.tagType match {
        case CipStructure(_) =>
          buffer.writeByte(0xA0).writeByte(0x02)
          TagType.encode(request.tagType, buffer)
        case _ =>
          TagType.encode(request.tagType, buffer)
      }

      buffer.writeShort(request.elements)
      buffer.writeBytes(request.data)
    }

    def decode(buffer: ByteBuf): WriteTagRequest = {
      WriteTagRequest(
        tagType   = TagType.decode(buffer),
        elements  = buffer.readUnsignedShort(),
        data      = buffer.readSlice(buffer.readableBytes()))
    }

  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Schemas — Citizens Agenda 0.1 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Citizens Agenda 0.1 documentation" href="index.html" />
    <link rel="prev" title="Types of documents" href="data.html" />

Navigation

          index

          previous |

Citizens Agenda 0.1 documentation »

Schemas¶

Goal of schema is to describe data structure. see here for more details.

Documents that use schema to validate must include the links attribute. See base schema

>>> curl-oauth --domain cz-api -X GET http://api.devel.czagenda.org/api/schema/base-abstract

Events are validated against the schema /schema/event, this schema include relations to /schema/who, /schema/localization, /schema/geo.

Previous topic

Types of documents

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          previous |

Citizens Agenda 0.1 documentation »

        © Copyright 2011, Oxys SARL.
      Created using Sphinx 1.1.3.


text: Moved to [ruby-jmeter](https://github.com/flood-io/ruby-jmeter).


text:
layout: post
title: "Free Pascal Macros"
date: 2018-06-25
permalink: /fpc-macros
description:
  Uma linguagem simples e com um design elegante como Object Pascal não necessitaria de suporte a macros como existem em C/C++. No entanto, Free Pascal as tem. Devemos utilizá-las?
image: /images/2018/remi-jacquaint-441559-unsplash.jpg
tags:
  - macro
keywords:
  - freepascal
  - fpc
  - delphi
  - lazarus
  - pascal
  - object pascal
  - object-oriented
  - oop
  - mdbs99
  - macro
---

Uma linguagem simples e com um design elegante como Object Pascal não necessitaria de suporte a macros como existem em C/C++. No entanto, Free Pascal as tem. Devemos utilizá-las?

![Unsplash image]({{ page.image }})
Photo by Rémi Jacquaint on Unsplash

## Introdução {#introducao}

O uso de [macros](https://en.wikipedia.org/wiki/Macro_(computer_science)) já existe no Free Pascal faz tempo, porém nunca havia pensando utilizar tal feature.

Se você é leitor assíduo do blog já deve ter percebido que eu prefiro ter um bom design e consistência no código do que utilizar "hacks" para escrever menos, porém com a perda da legibilidade e da manutenibilidade.

Na minha opinião, macros são *hacks*.

Bem, talvez a maioria...

Não acho que o suporte a macros não tenha sido implementado com o objetivo de melhorar o design e legibilidade do código.

No entanto, acredito que podemos tirar proveito dessa feature.

## Macros {#macros}

No código Pascal podemos definir macros que serão pré-processadas pelo compilador. Esse processamento irá gerar um resultado, que será como uma constante. Mas, essa constante pode representar uma expressão, um algorítimo, uma unidade, etc.

Vejamos um exemplo:

    {$macro on}
    {$define VALUE := A+B}

    function Sum(A, B: Integer): Integer;
    begin
      Result := VALUE;
    end;

    function Concat(const A, B: string): string;
    begin
      Result := VALUE;
    end;
    { TForm1 }

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      ShowMessage(Sum(1,2).ToString); // 3
      ShowMessage(Concat('A','B'));   // 'AB'
    end;

A primeira coisa a se fazer é ativar o uso de macros utilizando a diretiva `{$macro on}`, pois macros não são ativadas por padrão. Outra maneira de ativá-as para todas as unidades é passando o argumento `-Sm` para o compilador.

O exemplo acima não faz muito sentido, pois para se fazer uma soma não é necessário o uso de macros. No entanto, serviu para lhe mostrar o que é possível fazer com elas.

Repare que `A` e `B` são definidos na macro como 2 identificadores que ainda não existem. Esses identificadores virão do contexto onde as macros serão chamadas, ou seja, as funções `Sum` e `Concat`.

Para a macro, não importa o tipo de `A` e `B`. Então, elas funcionam como *Generics*, o que já é bem legal.

Mas *Generics* são muito mais poderosos do que isso, então não pense em macros como substitutos aos Generics.

Vamos a outro exemplo onde Generics não ajudam em nada:

    {$macro on}
    {$ifdef debug}
      {$define foo := foo.debug}
    {$else}
      {$define foo := foo.run}
    {$endif}

    uses
      foo;
    begin
      foo.SomeFunc;
    end.

Nesse exemplo acima, há um teste se a diretiva `debug` foi definida. Se for verdadeiro, definimos uma macro `foo` com o nome da unidade `foo.debug`, senão definimos `foo` como `foo.run`.

Repare que na cláusula `uses` há somente `foo`. Imagine agora por as diretivas em outro lugar, talvez arquivos `.inc`, e teremos uma unidade com o código limpo que irá utilizar as classes corretas dependendo da diretiva escolhida.

Bem legal, não é?

Entretanto, isso também não foi o que mais me chamou atenção no uso das macros. Pois, para fazer o mesmo que no exemplo acima, não é preciso macros. Basta você ter unidades como o mesmo nome, porém em diretórios diferentes, e passar o path correspondente ao compilador dependendo se há ou não a diretiva `debug`. O Lazarus IDE lhe dá essa opção.

Se há outras alternativas na própria linguagem para o uso de macros, por quê então utilizá-las?

## Unit Alias {#alias}

Faz muito tempo que solicitei a implementação de uma nova sintaxe à equipe Free Pascal para ser possível [redeclarar]({% post_url 2017-08-21-redeclarando-classes %}) uma unidade diretamente no código. A linguagem C# tem isso, assim como Python.

A razão para esse pedido é poder declarar unidades com nomes longos no código, mas dar-lhes um apelido curto para servir de prefixo a algumas classes que tem nomes iguais em unidades diferentes.

Então pensei numa alternativa que chamei de [API Unit]({% post_url 2017-10-30-api-unit %}). As vantagens e desvantagens estão no artigo.

Infelizmente essa ideia não se mostrou muito eficaz para projetos com muitas unidades, já que é necessário redeclarar todas as unidades, suas classes e interfaces em um único arquivo.

Mas com macros, tudo muda.

Hipoteticamente, vamos supor que as unidades `Windows` e `Graphics` pertencem ao namespace `FPC.RTL.`, ou seja, um "nome longo".

Então, minha proposta (antiga) seria utilizar essa sintaxe:

    uses
      FPC.RTL.Windows as Win,
      FPC.RTL.Graphics as Graph;
    var
      B1: Win.TBitmap;
      B2: Graph.TBitmap;

Eu não estou me referindo aqui o uso de namespaces do Delphi — que já foi implementado no Free Pascal — onde poderíamos definir um `NS="FPC.RTL"` e declarar apenas `Windows` e `Graphics` respectivamente.

Não é isso.

Utilizando essa sintaxe, teríamos o *controle local* sobre a nomenclatura das unidades.

Quando solicitei isso na época, eu pensava que iria exigir mudanças no parser da linguagem, que daria muito trabalho, etc.

Não era prioridade.

Porém, veja que com o uso de macros, bastaria o compilador substituir os `uses` acima, que utiliza a palavra reservada `as`, pelo código abaixo:

    uses
      {$macro on}
      FPC.RTL.Windows,
      {$define Win := FPC.RTL.Windows}
      FPC.RTL.Graphics;
      {$define Graph := FPC.RTL.Graphics}
    var
      B1: Win.TBitmap;
      B2: Graph.TBitmap;

E então eu poderia "renomear" as unidades com nomes longos como `Acme.SysFoo.Finances.Billing.Utils.Classes` para apenas `Billing`. Porém, em outra unidade, eu poderia renomear para `Utils` se assim o desejasse.

Teríamos a possibilidade de definir um apelido local (por unidade) a cada unidade. Perfeito.

## Conclusão {#conclusao}

A resposta a pergunta inicial é, sim. O uso de macros, quando bem utilizado, pode melhorar muito a legibilidade e design do código.

Não temos (ainda?) a sintaxe com o uso de `as`, que seria apenas uma *syntax sugar* para o uso de macros, porém já podemos renomear unidades localmente. O que é um grande avanço, na minha opinião.

O único contra que eu vejo é que, infelizmente, essa feature não existe no Delphi... por enquanto?

Até logo.


text:
elm-webaudio
============

This project is abandoned! It has been superseded by [trotha01's implementation](https://github.com/trotha01/elm-webaudio).

**ABANDONED**: This project has been abandoned. When this library was authored,
there was no good way to put a functional wrapper around a very non-functional
API such as WebAudio. I thought this was a decent attempt, for the time. Since
then, elm has grown to include new language constructs that would make the
implementation easier. However, I do not have the time or interest to rewrite
this library using the new language features. If you'd like to take the torch,
[submit an issue](https://github.com/bmatcuk/elm-webaudio/issues) with your
project's URL and I'll include it in this README so that others may find it.

The `elm-webaudio` library connects your [Elm](http://elm-lang.org/) programs
to the [Web Audio API](http://webaudio.github.io/web-audio-api/). This library
is somewhat experimental and incomplete, but it is useable. Check out an example
of the library in use: [oscillator scales](http://www.squeg.net/elm-webaudio/Scales.html).

And another, much more complicated example:
[soundcloud](http://www.squeg.net/elm-webaudio/Visual.html).

I highly recommend you check out the documentation for the Web Audio API to
make sure you understand the concepts before trying to use this library. This
library basically represents a fairly thin wrapper around the Web Audio API,
so everything in the Web Audio API documentation applies.


text:
'use strict';

var Lab = require('lab'),
  Hapi = require('hapi');

var describe = Lab.experiment;
var it = Lab.test;
var expect = Lab.expect;
var before = Lab.before;
var beforeEach = Lab.beforeEach;
var after = Lab.after;

describe('<%= safeSlugname %>', function() {
  describe('composer', function() {
    var manifest;

    beforeEach(function (done) {
      // Require a new composer manifest before every test
      manifest = require('../lib/');
      done();
    });

    it('can be required without throwing', function(done) {
      expect(manifest).to.exist;
      expect(typeof manifest).to.equal('object');
      done();
    });
  });
});


text:
slug: amelia-sposa
name: Amelia Sposa
---


text:
package jp.ne.sakura.uhideyuki.brt.brtsyn;

public abstract class Atom {
    public abstract String inspect();
}


text:
<?php

// Resend the activation email for a user that has registered an account.  Note that this is enabled regardless of whether or not email activation is enabled.
// This is to prevent "orphaned" accounts, who registered while email activation was still required.
// Request method: POST

require_once("../models/config.php");

set_error_handler('logAllErrors');

// Request method: POST
$ajax = checkRequestMode("post");

//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) {
	addAlert("danger", "I'm sorry, you cannot activate an account while logged in.  Please log out first.");
	apiReturnError($ajax, getReferralPage());
}

//Forms posted
if(!empty($_POST))
{
	$email = $_POST["email"];
	$username = $_POST["username"];

	//Perform some validation
	//Feel free to edit / change as required
	if(trim($email) == "")
	{
		$errors[] = lang("ACCOUNT_SPECIFY_EMAIL");
	}
	//Check to ensure email is in the correct format / in the db
	else if(!isValidEmail($email) || !emailExists($email))
	{
		$errors[] = lang("ACCOUNT_INVALID_EMAIL");
	}

	if(trim($username) == "")
	{
		$errors[] =  lang("ACCOUNT_SPECIFY_USERNAME");
	}
	else if(!usernameExists($username))
	{
		$errors[] = lang("ACCOUNT_INVALID_USERNAME");
	}

	if(count($errors) == 0)
	{
		//Check that the username / email are associated to the same account
		if(!emailUsernameLinked($email,$username))
		{
			$errors[] = lang("ACCOUNT_USER_OR_EMAIL_INVALID");
		}
		else
		{
			$userdetails = fetchUserAuthByUserName($username);

			//See if the user's account is activation
			if($userdetails["active"]==1)
			{
				$errors[] = lang("ACCOUNT_ALREADY_ACTIVE");
			}
			else
			{
				if ($resend_activation_threshold == 0) {
					$hours_diff = 0;
				}
				else {
					$last_request = $userdetails["last_activation_request"];
					$hours_diff = round((time()-$last_request) / (3600*$resend_activation_threshold),0);
				}

				if($resend_activation_threshold!=0 && $hours_diff <= $resend_activation_threshold)
				{
					$errors[] = lang("ACCOUNT_LINK_ALREADY_SENT",array($resend_activation_threshold));
				}
				else
				{
					//For security create a new activation url;
					$new_activation_token = generateActivationToken();

					if(!updateLastActivationRequest($new_activation_token,$username,$email))
					{
						$errors[] = lang("SQL_ERROR");
					}
					else
					{
						$mail = new userCakeMail();

						$activation_url = SITE_ROOT."api/activate_user.php?token=".$new_activation_token;

						//Setup our custom hooks
						$hooks = array(
							"searchStrs" => array("#ACTIVATION-URL","#USERNAME#"),
							"subjectStrs" => array($activation_url,$userdetails["display_name"])
							);

						if(!$mail->newTemplateMsg("resend-activation.txt",$hooks))
						{
							$errors[] = lang("MAIL_TEMPLATE_BUILD_ERROR");
						}
						else
						{
							if(!$mail->sendMail($userdetails["email"],"Activate your ".$websiteName." Account"))
							{
								$errors[] = lang("MAIL_ERROR");
							}
							else
							{
								//Success, user details have been updated in the db now mail this information out.
								$successes[] = lang("ACCOUNT_NEW_ACTIVATION_SENT");
							}
						}
					}
				}
			}
		}
	}
} else {
	$errors[] = lang("NO_DATA");
}

restore_error_handler();

foreach ($errors as $error){
  addAlert("danger", $error);
}
foreach ($successes as $success){
  addAlert("success", $success);
}

// Send to home page if failure
if (count($errors) > 0){
    apiReturnError($ajax, SITE_ROOT . "index.php");
} else {
    apiReturnSuccess($ajax, SITE_ROOT . "resend_activation.php");
}

?>


text:
package runconfig

import (
	"encoding/json"
	"io"

	"github.com/hyperhq/hyper-api/types/container"
)

// DecodeHostConfig creates a HostConfig based on the specified Reader.
// It assumes the content of the reader will be JSON, and decodes it.
func DecodeHostConfig(src io.Reader) (*container.HostConfig, error) {
	decoder := json.NewDecoder(src)

	var w ContainerConfigWrapper
	if err := decoder.Decode(&w); err != nil {
		return nil, err
	}

	hc := w.getHostConfig()
	return hc, nil
}

// SetDefaultNetModeIfBlank changes the NetworkMode in a HostConfig structure
// to default if it is not populated. This ensures backwards compatibility after
// the validation of the network mode was moved from the docker CLI to the
// docker daemon.
func SetDefaultNetModeIfBlank(hc *container.HostConfig) *container.HostConfig {
	if hc != nil {
		if hc.NetworkMode == container.NetworkMode("") {
			hc.NetworkMode = container.NetworkMode("default")
		}
	}
	return hc
}


text:
package v2ch01.optional;

import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import java.util.*;

public class OptionalTest
{
   public static void main(String[] args) throws IOException
   {
      String contents = new String(Files.readAllBytes(
            Paths.get("../gutenberg/alice30.txt")), StandardCharsets.UTF_8);
      List<String> wordList = Arrays.asList(contents.split("\\PL+"));

      Optional<String> optionalValue = wordList.stream()
         .filter(s -> s.contains("fred"))
         .findFirst();
      System.out.println(optionalValue.orElse("No word") + " contains fred");

      Optional<String> optionalString = Optional.empty();
      String result = optionalString.orElse("N/A");
      System.out.println("result: " + result);
      result = optionalString.orElseGet(() -> Locale.getDefault().getDisplayName());
      System.out.println("result: " + result);
      try
      {
         result = optionalString.orElseThrow(IllegalStateException::new);
         System.out.println("result: " + result);
      }
      catch (Throwable t)
      {
         t.printStackTrace();
      }

      optionalValue = wordList.stream()
         .filter(s -> s.contains("red"))
         .findFirst();
      optionalValue.ifPresent(s -> System.out.println(s + " contains red"));

      Set<String> results = new HashSet<>();
      optionalValue.ifPresent(results::add);
      Optional<Boolean> added = optionalValue.map(results::add);
      System.out.println(added);

      System.out.println(inverse(4.0).flatMap(OptionalTest::squareRoot));
      System.out.println(inverse(-1.0).flatMap(OptionalTest::squareRoot));
      System.out.println(inverse(0.0).flatMap(OptionalTest::squareRoot));
      Optional<Double> result2 = Optional.of(-4.0)
         .flatMap(OptionalTest::inverse).flatMap(OptionalTest::squareRoot);
      System.out.println(result2);
   }

   public static Optional<Double> inverse(Double x)
   {
      return x == 0 ? Optional.empty() : Optional.of(1 / x);
   }

   public static Optional<Double> squareRoot(Double x)
   {
      return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
   }
}


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

public class TeakPostLaunchSummary {
    /// The link used to launch the game, or ``null``.
    public string LaunchLink { get; private set; }

    /// The name of the schedule for the notification on the Teak Dashboard, or ``null`` if it was not a scheduled notification.
    public string ScheduleName { get; private set; }

    /// The id of the schedule in the Teak CMS, or ``null`` if it was not a scheduled notification.
    public string ScheduleId { get; private set; }

    /// The name of the link or notification on the Teak Dashboard.
    public string CreativeName { get; private set; }

    /// The id of the link or notification in the Teak CMS.
    public string CreativeId { get; private set; }

    /// Opaque reward identifier, or ``null`` if no reward.
    public string RewardId { get; private set; }

    ///
    /// The name of the Teak 'channel', one of: ``ios_push``, ``android_push``, ``fb_a2u``, ``email``, ``generic_link``.
    ///
    public string ChannelName { get; private set; }

    /// The deep link used to launch the game, or ``null``.
    public string DeepLink { get; private set; }

    /// Opaque notification or email identifyer, or ``null``.
    public string SourceSendId { get; private set; }

    ///
    /// Returns a string that represents the current object.
    ///
    /// <returns>A string that represents the current object.</returns>
    public override string ToString() {
        string formatString = "{{ LaunchLink = '{0}', ScheduleName = '{1}', ScheduleId = '{2}', CreativeName = '{3}', CreativeId = '{4}', RewardId = '{5}', ChannelName = '{6}', DeepLink = '{7}', SourceSendId = '{8}' }}";
        return string.Format(formatString,
                             this.LaunchLink,
                             this.ScheduleName,
                             this.ScheduleId,
                             this.CreativeName,
                             this.CreativeId,
                             this.RewardId,
                             this.ChannelName,
                             this.DeepLink,
                             this.SourceSendId
                            );
    }

    /// @cond hide_from_doxygen
    public TeakPostLaunchSummary(Dictionary<string, object> json) {
        this.LaunchLink = json.ContainsKey("launch_link") ? json["launch_link"] as string : null;
        this.ScheduleName = json.ContainsKey("teakScheduleName") ? json["teakScheduleName"] as string : null;
        this.ScheduleId = json.ContainsKey("teakScheduleId") ? json["teakScheduleId"] as string : null;
        this.CreativeName = json.ContainsKey("teakCreativeName") ? json["teakCreativeName"] as string : null;
        this.CreativeId = json.ContainsKey("teakCreativeId") ? json["teakCreativeId"] as string : null;
        this.RewardId = json.ContainsKey("teakRewardId") ? json["teakRewardId"] as string : null;
        this.ChannelName = json.ContainsKey("teakChannelName") ? json["teakChannelName"] as string : null;
        this.DeepLink = json.ContainsKey("teakDeepLink") ? json["teakDeepLink"] as string : null;
        this.SourceSendId = json.ContainsKey("teakNotifId") ? json["teakNotifId"] as string : null;
    }
    /// @endcond
}


text:
<?php

namespace Pinq\Tests\Integration\Caching;

use Doctrine\Common\Cache\FilesystemCache;
use Pinq\Caching\DoctrineCache;

class DoctrineCacheTest extends DirectoryCacheTestBase
{
    protected function setUpCache()
    {
        return new DoctrineCache(new FilesystemCache(self::$cacheDirectoryPath));
    }
}


text:
package nginx.clojure.asm.commons;

import nginx.clojure.asm.Opcodes;
import nginx.clojure.asm.signature.SignatureVisitor;

/**
 * A {@link SignatureVisitor} adapter for type mapping.
 *
 * @author Eugene Kuleshov
 */
public class RemappingSignatureAdapter extends SignatureVisitor {

    private final SignatureVisitor v;

    private final Remapper remapper;

    private String className;

    public RemappingSignatureAdapter(final SignatureVisitor v,
            final Remapper remapper) {
        this(Opcodes.ASM4, v, remapper);
    }

    protected RemappingSignatureAdapter(final int api,
            final SignatureVisitor v, final Remapper remapper) {
        super(api);
        this.v = v;
        this.remapper = remapper;
    }

    @Override
    public void visitClassType(String name) {
        className = name;
        v.visitClassType(remapper.mapType(name));
    }

    @Override
    public void visitInnerClassType(String name) {
        String remappedOuter = remapper.mapType(className) + '$';
        className = className + '$' + name;
        String remappedName = remapper.mapType(className);
        int index = remappedName.startsWith(remappedOuter) ? remappedOuter
                .length() : remappedName.lastIndexOf('$') + 1;
        v.visitInnerClassType(remappedName.substring(index));
    }

    @Override
    public void visitFormalTypeParameter(String name) {
        v.visitFormalTypeParameter(name);
    }

    @Override
    public void visitTypeVariable(String name) {
        v.visitTypeVariable(name);
    }

    @Override
    public SignatureVisitor visitArrayType() {
        v.visitArrayType();
        return this;
    }

    @Override
    public void visitBaseType(char descriptor) {
        v.visitBaseType(descriptor);
    }

    @Override
    public SignatureVisitor visitClassBound() {
        v.visitClassBound();
        return this;
    }

    @Override
    public SignatureVisitor visitExceptionType() {
        v.visitExceptionType();
        return this;
    }

    @Override
    public SignatureVisitor visitInterface() {
        v.visitInterface();
        return this;
    }

    @Override
    public SignatureVisitor visitInterfaceBound() {
        v.visitInterfaceBound();
        return this;
    }

    @Override
    public SignatureVisitor visitParameterType() {
        v.visitParameterType();
        return this;
    }

    @Override
    public SignatureVisitor visitReturnType() {
        v.visitReturnType();
        return this;
    }

    @Override
    public SignatureVisitor visitSuperclass() {
        v.visitSuperclass();
        return this;
    }

    @Override
    public void visitTypeArgument() {
        v.visitTypeArgument();
    }

    @Override
    public SignatureVisitor visitTypeArgument(char wildcard) {
        v.visitTypeArgument(wildcard);
        return this;
    }

    @Override
    public void visitEnd() {
        v.visitEnd();
    }
}