text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace SybilResearch.MultiNode
{
    ///
    /// Task status
    ///
    [DataContract(Namespace = "http://www.sybilresearch.com/SybilResearch/Core/2012/08/")]
    public enum TaskStatus
    {
        /// The task is queued for execution
        [EnumMember]
        Queued,
        /// The task is currently executing
        [EnumMember]
        Executing,
        /// The task is currently paused
        [EnumMember]
        Paused,
        /// The task has finished execution and is awaiting result collection
        [EnumMember]
        Finished,
        /// The task has finished and the results have been collected
        [EnumMember]
        Retrieved,
        /// The task has encountered a fault or status could not be retrieved
        [EnumMember]
        Faulted
    }

    ///
    /// This class stores information about a request that has been submitted to
    /// a task broker object. Use this to retrieve information about task status
    /// and to collect results after the task is finished.
    ///
    [DataContract(Namespace = "http://www.sybilresearch.com/SybilResearch/Core/2012/08/")]
    public class RequestHandle
    {
        #region Data members
        [DataMember]
        private string _handle = Guid.NewGuid().ToString();
        [DataMember]
        private DateTime _submitTime = DateTime.MaxValue;
        [DataMember]
        private DateTime _pauseTime = DateTime.MaxValue;
        [DataMember]
        private DateTime _finishTime = DateTime.MaxValue;
        [DataMember]
        private DateTime _collectTime = DateTime.MaxValue;
        [DataMember]
        private TaskStatus _taskStatus = TaskStatus.Queued;
        [DataMember]
        private string _engineId;
        #endregion

        #region Properties
        ///
        /// Gets/sets the request handle - this is also the id of the cache into which the data
        /// for the request will be stored
        ///
        public string Handle
        {
            get { return _handle; }
            set { _handle = value; }
        }

        ///
        /// Gets/sets the submission time for the request
        ///
        public DateTime SubmitTime
        {
            get { return _submitTime; }
            set { _submitTime = value; }
        }

        ///
        /// Gets/sets the time when the request was last paused
        ///
        public DateTime PauseTime
        {
            get { return _pauseTime; }
            set { _pauseTime = value; }
        }

        ///
        /// Gets/sets the finish time for the request
        ///
        public DateTime FinishTime
        {
            get { return _finishTime; }
            set { _finishTime = value; }
        }

        ///
        /// Gets/sets the collection time for the results of this request
        ///
        public DateTime CollectTime
        {
            get { return _collectTime; }
            set { _collectTime = value; }
        }

        ///
        /// Task status
        ///
        public TaskStatus TaskStatus
        {
            get { return _taskStatus; }
            set { _taskStatus = value; }
        }

        ///
        /// Gets/sets the id of the engine the task is executing on
        ///
        public string EngineId
        {
            get { return _engineId; }
            set { _engineId = value; }
        }
        #endregion

        #region Methods
        ///
        /// Collects the results
        ///
        public object CollectResults()
        {
            return null;
        }

        #endregion
    }
}


text:
import tensorflow as tf
import numpy as np
import sys
sys.path.append('..') # so that amnet can be imported
import amnet
from amnet import tf_utils
from tensorflow.examples.tutorials.mnist import input_data

def pca(A, dim):

    M = (A-np.mean(A.T,axis=1)).T # subtract the mean (along columns)

    # computing eigenvalues and eigenvectors of covariance matrix
    cov = np.cov(M)
    [latent,coeff] = np.linalg.eig(cov)
    coeff = coeff.astype(float) # discard complex part that results from numerical error

    idx = np.argsort(latent) # sorting the eigenvalues
    idx = idx[::-1] # in ascending order

    # sorting eigenvectors according to the sorted eigenvalues
    coeff = coeff[:,idx]
    latent = latent[idx] # sorting eigenvalues

    p = np.size(coeff,axis=1)
    if dim < p and dim >= 0: # check if reduction makes sense
        coeff = coeff[:,range(dim)] # cutting dimensionality
    return coeff

def main():

    # hyperparameters
    learning_rate = 0.5
    epochs = 10
    batch_size = 100
    reduced_dim = 40

    # grab mnist data
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    train_labels = mnist.train.labels
    train_pca_images = []

    rotation_reduced = pca(mnist.train.images[:10000], reduced_dim)

    # convert training data to reduced dimension
    for image in mnist.train.images:
        small_transformed_image = np.dot(rotation_reduced.T, image)
        train_pca_images.append(small_transformed_image)

    # same procedure for test labels
    test_labels = mnist.test.labels
    test_pca_images = []

    for image in mnist.test.images:
        small_transformed_image = np.dot(rotation_reduced.T, image)
        test_pca_images.append(small_transformed_image)

    # declare the training data placeholders
    # input x - for 28 x 28 pixels = 784
    x = tf.placeholder(tf.float32, [None, reduced_dim])
    # now declare the output data placeholder - 10 digits
    y = tf.placeholder(tf.float32, [None, 10])

    # declare the weights connecting the input to the hidden layer
    w1 = tf.Variable(tf.random_normal([reduced_dim, 20], stddev=0.03), name='w1')
    b1 = tf.Variable(tf.random_normal([20]), name='b1')
    # and the weights connecting the hidden layer to the output layer
    w2 = tf.Variable(tf.random_normal([20, 10], stddev=0.03), name='w2')
    b2 = tf.Variable(tf.random_normal([10]), name='b2')

    # calculate the output of the hidden layer
    hidden_out = tf.add(tf.matmul(x, w1), b1)
    hidden_out = tf.nn.relu(hidden_out)

    # calculate the hidden layer output - in this case, let's use a softmax activated
    # output layer
    y_ = tf.nn.softmax(tf.add(tf.matmul(hidden_out, w2), b2))

    # now let's define the cost function which we are going to train the model on
    y_clipped = tf.clip_by_value(y_, 1e-10, 0.9999999)
    cross_entropy = -tf.reduce_mean(tf.reduce_sum(y * tf.log(y_clipped)
                                                  + (1 - y) * tf.log(1 - y_clipped), axis=1))

    # add an optimizer
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)

    # finally setup the initialisation operator
    init_op = tf.global_variables_initializer()

    # define an accuracy assessment operation
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    tf_prediction = 0 # used to check correct behavior

    # start the session
    with tf.Session() as sess:
        # initialize the variables
        sess.run(init_op)
        # grab a batch
        total_batch = int(len(mnist.train.labels) / batch_size)
        print("Starting training")
        for epoch in range(epochs):
            avg_cost = 0
            for i in range(total_batch):
                batch_x = train_pca_images[i*batch_size : (i+1)*batch_size]
                batch_y = train_labels[i*batch_size : (i+1)*batch_size]
                # feed batches
                _, c = sess.run([optimizer, cross_entropy], feed_dict={x: batch_x, y: batch_y})
                avg_cost += c / total_batch
            print("Epoch:", (epoch + 1), "cost =", "{:.3f}".format(avg_cost))

        print("\nTraining complete!")
        print(sess.run(accuracy, feed_dict={x: test_pca_images, y: test_labels}))

        weights, biases = tf_utils.get_vars(tf.trainable_variables(), sess)

    # create ReLU AMN
    nn = tf_utils.relu_amn(weights, biases)

    # check if the networks achieve the same classification rate
    corrects = 0
    totals = 0
    for image, label in zip(test_pca_images, test_labels):
        guess = nn.eval(image)
        guess_num = guess.tolist().index(max(guess.tolist()))
        actual_num = label.tolist().index(max(label.tolist()))
        if guess_num == actual_num:
            corrects += 1
        totals += 1

    print('Correct classification of AMNet: ' + str(float(corrects)/float(totals)))

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
using namespace std;
using namespace art_crack;

ArtCrack<long long> c;

inline uintptr_t getLeafValue(Node* node) {
  // The the value stored in the pseudo-leaf
  return reinterpret_cast<uintptr_t>(node) >> 1;
}

void init(long long *arr, int N) {
  c.batch_insert(arr, N);
  // art_debug = 1;
}

void insert(long long value) {
  c.insert(value);
}

void erase(long long value) {
  #ifdef NDEBUG
    c.erase(value);
  #else
    bool ok = c.erase(value);
    assert(ok);
  #endif
}

long long query(long long value) {
  // art_debug = 1;
  // if (value == 277929528LL) art_debug = 1;
  auto it = c.lower_bound(value);
  long long ret = it.first ? it.second : 0;
  // fprintf(stdout, "%lld (%lld)\n", ret, value); fflush(stdout);
  // if (value == 277929528LL) fprintf(stderr, "%d %lld\n", it.first, it.second), exit(1);
  // art_debug = 0;
  return ret;
}

void results(Statistics &s) {
  s.n_leaves = nLeaves;
  s.n_capacity = nCap;
  s.n_internals = nInternals;
  s.ln_size = LEAF_BSIZE;
  c.alloc_sizes(s.ia_free, s.ia_size, s.la_free, s.la_size);
}


text:
(function ( w, doc, stage, map, statusMenu ) {

    /**
     * Private variables
     */
    var container = null;

    /**
     * Public api
     */
    window.contentApi = {
        "init": init,
        "render": render,
        "show": show,
        "hide": hide
    };

    /**
     * Private methods
     */
    function renderContent( element, content ) {
        element.innerHTML = content;
    };

    function init( element ) {

        container = element;

        return this;
    }

    function render() {

        var content = [
            '

',
            '

',
            '

',
            '

'
        ].join( "" );

        renderContent( container, content );

        stage.init( doc.querySelector( ".stage" ) );
        map.init( doc.querySelector( ".map" ) );
        statusMenu.init( doc.querySelector( ".status" ) );

        return this;
    }

    function show() {
        container.classList.remove( "hide" );
    }

    function hide() {
        container.classList.add( "hide" );
    }

})( window,
    document,
    window.stageApi,
    window.mapMenuApi,
    window.statusMenuApi);


text:
package org.jbpm.services.api;

import org.jbpm.services.api.model.DeployedUnit;

public class DeploymentEvent {

    private String deploymentId;
    private DeployedUnit deployedUnit;

    public DeploymentEvent(String deploymentId, DeployedUnit deployedUnit) {
        this.deployedUnit = deployedUnit;
        this.deploymentId = deploymentId;
    }

    public DeployedUnit getDeployedUnit() {
        return deployedUnit;
    }

    public void setDeployedUnit(DeployedUnit deployedUnit) {
        this.deployedUnit = deployedUnit;
    }

    public String getDeploymentId() {
        return deploymentId;
    }

    public void setDeploymentId(String deploymentId) {
        this.deploymentId = deploymentId;
    }

}


text:
/* globals WebAppHashing */

import { WebApp } from 'meteor/webapp';
import { Meteor } from 'meteor/meteor';
import _ from 'underscore';
import less from 'less';
import Autoprefixer from 'less-plugin-autoprefix';
import crypto from 'crypto';

const logger = new Logger('rocketchat:theme', {
	methods: {
		stop_rendering: {
			type: 'info',
		},
	},
});

WebApp.rawConnectHandlers.use(function(req, res, next) {
	const path = req.url.split('?')[0];
	const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || '';
	if (path === `${ prefix }/__cordova/theme.css` || path === `${ prefix }/theme.css`) {
		const css = RocketChat.theme.getCss();
		const hash = crypto.createHash('sha1').update(css).digest('hex');
		res.setHeader('Content-Type', 'text/css; charset=UTF-8');
		res.setHeader('ETag', `"${ hash }"`);
		res.write(css);
		return res.end();
	} else {
		return next();
	}
});

const { calculateClientHash } = WebAppHashing;

WebAppHashing.calculateClientHash = function(manifest, includeFilter, runtimeConfigOverride) {
	const css = RocketChat.theme.getCss();
	if (css.trim() !== '') {
		const hash = crypto.createHash('sha1').update(css).digest('hex');
		let themeManifestItem = _.find(manifest, function(item) {
			return item.path === 'app/theme.css';
		});
		if (themeManifestItem == null) {
			themeManifestItem = {};
			manifest.push(themeManifestItem);
		}
		themeManifestItem.path = 'app/theme.css';
		themeManifestItem.type = 'css';
		themeManifestItem.cacheable = true;
		themeManifestItem.where = 'client';
		themeManifestItem.url = `/theme.css?${ hash }`;
		themeManifestItem.size = css.length;
		themeManifestItem.hash = hash;
	}
	return calculateClientHash.call(this, manifest, includeFilter, runtimeConfigOverride);
};

RocketChat.theme = new class {
	constructor() {
		this.variables = {};
		this.packageCallbacks = [];
		this.files = ['server/colors.less'];
		this.customCSS = '';
		RocketChat.settings.add('css', '');
		RocketChat.settings.addGroup('Layout');
		RocketChat.settings.onload('css', Meteor.bindEnvironment((key, value, initialLoad) => {
			if (!initialLoad) {
				Meteor.startup(function() {
					process.emit('message', {
						refresh: 'client',
					});
				});
			}
		}));
		this.compileDelayed = _.debounce(Meteor.bindEnvironment(this.compile.bind(this)), 100);
		Meteor.startup(() => {
			RocketChat.settings.onAfterInitialLoad(() => {
				RocketChat.settings.get(/^theme-./, Meteor.bindEnvironment((key, value) => {
					if (key === 'theme-custom-css' && value != null) {
						this.customCSS = value;
					} else {
						const name = key.replace(/^theme-[a-z]+-/, '');
						if (this.variables[name] != null) {
							this.variables[name].value = value;
						}
					}

					this.compileDelayed();
				}));
			});
		});
	}

	compile() {
		let content = [this.getVariablesAsLess()];

		content.push(...this.files.map((name) => Assets.getText(name)));

		content.push(...this.packageCallbacks.map((name) => name()));

		content.push(this.customCSS);
		content = content.join('\n');
		const options = {
			compress: true,
			plugins: [new Autoprefixer()],
		};
		const start = Date.now();
		return less.render(content, options, function(err, data) {
			logger.stop_rendering(Date.now() - start);
			if (err != null) {
				return console.log(err);
			}
			RocketChat.settings.updateById('css', data.css);
			return Meteor.startup(function() {
				return Meteor.setTimeout(function() {
					return process.emit('message', {
						refresh: 'client',
					});
				}, 200);
			});
		});
	}

	addColor(name, value, section, properties) {
		const config = {
			group: 'Colors',
			type: 'color',
			editor: 'color',
			public: true,
			properties,
			section,
		};

		return RocketChat.settings.add(`theme-color-${ name }`, value, config);
	}

	addVariable(type, name, value, section, persist = true, editor, allowedTypes, property) {
		this.variables[name] = {
			type,
			value,
		};
		if (persist) {
			const config = {
				group: 'Layout',
				type,
				editor: editor || type,
				section,
				public: true,
				allowedTypes,
				property,
			};
			return RocketChat.settings.add(`theme-${ type }-${ name }`, value, config);
		}

	}

	addPublicColor(name, value, section, editor = 'color', property) {
		return this.addVariable('color', name, value, section, true, editor, ['color', 'expression'], property);
	}

	addPublicFont(name, value) {
		return this.addVariable('font', name, value, 'Fonts', true);
	}

	getVariablesAsObject() {
		return Object.keys(this.variables).reduce((obj, name) => {
			obj[name] = this.variables[name].value;
			return obj;
		}, {});
	}

	getVariablesAsLess() {
		return Object.keys(this.variables).map((name) => {
			const variable = this.variables[name];
			return `@${ name }: ${ variable.value };`;
		}).join('\n');
	}

	addPackageAsset(cb) {
		this.packageCallbacks.push(cb);
		return this.compileDelayed();
	}

	getCss() {
		return RocketChat.settings.get('css') || '';
	}

};


text:
[![](https://developer.android.com/images/brand/en_app_rgb_wo_60.png)](https://play.google.com/store/apps/details?id=hu.supercluster.gameoflife)

An Android implementation of Conway's Game of Life, focusing on clean design and implementation

## About Game of Life
* [Stephen Hawking's The Meaning of Life (John Conway's Game of Life segment)](https://www.youtube.com/watch?v=CgOcEZinQ2I)
* [Video showing some epic creations](https://www.youtube.com/watch?v=C2vgICfQawE)
* [Wikipedia article] (http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life)

## About the app
Changeable automaton rules, presets, and interactive board. Some interesting outcomes:

![](http://i.imgur.com/jZPfMlv.png)
![](http://i.imgur.com/sDMRCJW.png)
![](http://i.imgur.com/FOdxb8i.png)
![](http://i.imgur.com/8bi2kLT.png)
![](http://i.imgur.com/wmSrTRt.png)
![](http://i.imgur.com/cwAe79y.png)

## About the code
#### Used technologies
* [AndroidAnnotations](https://github.com/excilys/androidannotations)
* [Otto](square.github.io/otto/)
* [Hugo](https://github.com/JakeWharton/hugo)

#### Running tests
Type ```./gradlew app:test```.

Results can be checked in the generated HTML under ```app/build/reports/tests/debug/index.html```

#### Tampering around
The code is intentionally implemented in a way to make it easy to create other types of cellular automata. Feel free to fork it and play around. For a starter:

1. Add your own implementation for Rule and CellularAutomata, and for CellColors if your automaton needs more than a basic dead / alive coloring:
   * [Rule](https://github.com/zsoltk/GameOfLife/tree/master/app/src/main/java/hu/supercluster/gameoflife/game/rule)
   * [CellullarAutomaton](https://github.com/zsoltk/GameOfLife/tree/master/app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton)
   * [CellColors](https://github.com/zsoltk/GameOfLife/tree/master/app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell)

2. Use them in:
   * [MainPresenter](https://github.com/zsoltk/GameOfLife/blob/master/app/src/main/java/hu/supercluster/gameoflife/app/activity/main/MainPresenter.java)

3. If you're interested how the transformation is done, check:
   * [Transformer](https://github.com/zsoltk/GameOfLife/tree/master/app/src/main/java/hu/supercluster/gameoflife/game/transformer)

4. Have fun and message me if you create something cool!

#### Known limitations
The approach used in the transformation logic is that only cell state changes are observed, and a counter of dead / alive neighbors is updated in every surrounding cell. By using the [ThreadedGridTransformer](https://github.com/zsoltk/GameOfLife/blob/master/app/src/main/java/hu/supercluster/gameoflife/game/transformer/ThreadedGridTransformer.java) it's fast enough to be smooth for Game of Life and most other rules. However, rules resulting in lots of changes around the screen might slow the game down.

## Translations
**A big thank you to the translators:**
* Croatian by Lotti Sándorfi
* Estonian by Angéla Nagy and Berit Puidet
* French by Angéla Nagy
* German by Zoltán Török
* Latvian by Rolands Pragulbicks
* Russian by Natália Szvetlána Vaszkevics
* Ukrainian by Natália Szvetlána Vaszkevics


text:
alias gs='git status '
alias gc='git commit '
alias ga='git add '
alias gb='git branch '
alias go='git checkout '
alias gd='git diff '
alias gk='gitk --all&'
alias gx='gitx --all'

github_username=GuiltyDolphin

# Clone a repository from the user's GitHub.
git-clone-my() {
    gurl="https://github.com/$github_username/$1"
    git clone "$gurl"
}

# Update the GIT_HASH environment variable to the current
# commit's hash.
ghash() {
  export GHASH=$(git log -1 --pretty=format:%H)
}

# Perform a commit, but preserve hash.
# For use with git-rebase so that author time-stamps aren't
# messed up.
basec() {
  git commit -c $GHASH
}

# Reset head, but keep track of the original hash.
# Use instead of 'git reset HEAD^' when rebasing.
resh() {
  ghash && git reset HEAD^
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * The template for displaying the sidebar right
 *
 * Displays all of the sidebar right element.
 *
 * @package Codeigniter
 * @subpackage Tamtv Template
 * @author Vicky Nitinegoro <pkpvicky@gmail.com>
 * @since Tamtv 1.0
 */
?>
		<div class="col-xs-4 box-sidebar">
			<?php
			/**
			 * Load the elements sidebar
			 *
			 * @param string ( themes layout )
			 **/
			foreach ($this->themes->layout('sidebar-live') as $row)
			{
				$this->load->view('box-elements/'.$row->meta_key);
			}
			?>
		</div>
	</div>
<?php
/* End of file sidebar-live.php */
/* Location: ./application/views/sidebar-live.php */


text:
package com.grapp.soosec.common.mvvm.fields.connector.common;

import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public abstract class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
    private final RecyclerView mRecyclerView;
    private final GestureDetector mGestureDetector;

    public RecyclerViewTouchListener(final RecyclerView recyclerView) {
        mRecyclerView = recyclerView;
        mGestureDetector = new GestureDetector(recyclerView.getContext(), new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null) {
                    onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
    }

    public RecyclerView view() {
        return mRecyclerView;
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && mGestureDetector.onTouchEvent(e)) {
            onClick(child, rv.getChildPosition(child));
        }
        return false;
    }
    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }
    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }

    public abstract void onClick(View view, int position);
    public abstract void onLongClick(View view, int position);

    public static abstract class OfType<T> extends RecyclerViewTouchListener {

        public OfType(RecyclerView recyclerView) {
            super(recyclerView);
        }

        @Override
        public void onClick(View view, int position) {
            T item = getItem(position);
            onClick(item);
        }

        @Override
        public void onLongClick(View view, int position) {
            T item = getItem(position);
            onLongClick(item);
        }

        public abstract void onClick(T model);
        public abstract void onLongClick(T model);

        public abstract T getItem(int position);
    }
}


text:
<?php echo validation_errors(); ?>

<?php echo form_open('users/login'); ?>
    <fieldset>

            <input autocomplete="on" autofocus class="form-control" name="email" placeholder="Email" type="text"/>

            <input class="form-control" name="password" placeholder="Password" type="password"/>

            <button class="btn btn-default" type="submit">

                Log In
            </button>

    </fieldset>
</form>

    or register for an account


text:
using Esprima.Ast;
using Jint.Native;
using Jint.Native.Promise;

namespace Jint.Runtime.Interpreter.Expressions;

internal sealed class JintImportExpression : JintExpression
{
    private JintExpression _importExpression;

    public JintImportExpression(Import expression) : base(expression)
    {
        _initialized = false;
        _importExpression = null!;
    }

    protected override void Initialize(EvaluationContext context)
    {
        var expression = ((Import) _expression).Source;
        _importExpression = Build(expression);
    }

    /// <summary>
    /// https://tc39.es/ecma262/#sec-import-calls
    /// </summary>
    protected override object EvaluateInternal(EvaluationContext context)
    {
        var referencingScriptOrModule = context.Engine.GetActiveScriptOrModule();
        var argRef = _importExpression.Evaluate(context);
        var specifier = context.Engine.GetValue(argRef); //.UnwrapIfPromise();
        var promiseCapability = PromiseConstructor.NewPromiseCapability(context.Engine, context.Engine.Realm.Intrinsics.Promise);

        string specifierString;
        try
        {
            specifierString = TypeConverter.ToString(specifier);
        }
        catch (JavaScriptException e)
        {
            promiseCapability.Reject.Call(JsValue.Undefined, new[] { e.Error });
            return JsValue.Undefined;
        }

        context.Engine._host.ImportModuleDynamically(referencingScriptOrModule, specifierString, promiseCapability);
        context.Engine.RunAvailableContinuations();
        return promiseCapability.PromiseInstance;
    }
}


text:
"""
    ambari_jinja2.filters
    ~~~~~~~~~~~~~~

    Bundled jinja filters.

    :copyright: (c) 2010 by the Jinja Team.
    :license: BSD, see LICENSE for more details.
"""
import re
import math
from random import choice
from operator import itemgetter
from itertools import imap, groupby
from ambari_jinja2.utils import Markup, escape, pformat, urlize, soft_unicode
from ambari_jinja2.runtime import Undefined
from ambari_jinja2.exceptions import FilterArgumentError, SecurityError

_word_re = re.compile(r'\w+(?u)')

def contextfilter(f):
    """Decorator for marking context dependent filters. The current
    :class:`Context` will be passed as first argument.
    """
    f.contextfilter = True
    return f

def evalcontextfilter(f):
    """Decorator for marking eval-context dependent filters.  An eval
    context object is passed as first argument.  For more information
    about the eval context, see :ref:`eval-context`.

    .. versionadded:: 2.4
    """
    f.evalcontextfilter = True
    return f

def environmentfilter(f):
    """Decorator for marking evironment dependent filters.  The current
    :class:`Environment` is passed to the filter as first argument.
    """
    f.environmentfilter = True
    return f

def do_forceescape(value):
    """Enforce HTML escaping.  This will probably double escape variables."""
    if hasattr(value, '__html__'):
        value = value.__html__()
    return escape(unicode(value))

@evalcontextfilter
def do_replace(eval_ctx, s, old, new, count=None):
    """Return a copy of the value with all occurrences of a substring
    replaced with a new one. The first argument is the substring
    that should be replaced, the second is the replacement string.
    If the optional third argument ``count`` is given, only the first
    ``count`` occurrences are replaced:

    .. sourcecode:: jinja

        {{ "Hello World"|replace("Hello", "Goodbye") }}
            -> Goodbye World

        {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
            -> d'oh, d'oh, aaargh
    """
    if count is None:
        count = -1
    if not eval_ctx.autoescape:
        return unicode(s).replace(unicode(old), unicode(new), count)
    if hasattr(old, '__html__') or hasattr(new, '__html__') and \
       not hasattr(s, '__html__'):
        s = escape(s)
    else:
        s = soft_unicode(s)
    return s.replace(soft_unicode(old), soft_unicode(new), count)

def do_upper(s):
    """Convert a value to uppercase."""
    return soft_unicode(s).upper()

def do_lower(s):
    """Convert a value to lowercase."""
    return soft_unicode(s).lower()

@evalcontextfilter
def do_xmlattr(_eval_ctx, d, autospace=True):
    """Create an SGML/XML attribute string based on the items in a dict.
    All values that are neither `none` nor `undefined` are automatically
    escaped:

    .. sourcecode:: html+jinja

        ...

    Results in something like this:

    .. sourcecode:: html

        ...

    As you can see it automatically prepends a space in front of the item
    if the filter returned something unless the second parameter is false.
    """
    rv = u' '.join(
        u'%s="%s"' % (escape(key), escape(value))
        for key, value in d.iteritems()
        if value is not None and not isinstance(value, Undefined)
    )
    if autospace and rv:
        rv = u' ' + rv
    if _eval_ctx.autoescape:
        rv = Markup(rv)
    return rv

def do_capitalize(s):
    """Capitalize a value. The first character will be uppercase, all others
    lowercase.
    """
    return soft_unicode(s).capitalize()

def do_title(s):
    """Return a titlecased version of the value. I.e. words will start with
    uppercase letters, all remaining characters are lowercase.
    """
    return soft_unicode(s).title()

def do_dictsort(value, case_sensitive=False, by='key'):
    """Sort a dict and yield (key, value) pairs. Because python dicts are
    unsorted you may want to use this function to order them by either
    key or value:

    .. sourcecode:: jinja

        {% for item in mydict|dictsort %}
            sort the dict by key, case insensitive

        {% for item in mydict|dicsort(true) %}
            sort the dict by key, case sensitive

        {% for item in mydict|dictsort(false, 'value') %}
            sort the dict by key, case insensitive, sorted
            normally and ordered by value.
    """
    if by == 'key':
        pos = 0
    elif by == 'value':
        pos = 1
    else:
        raise FilterArgumentError('You can only sort by either '
                                  '"key" or "value"')
    def sort_func(item):
        value = item[pos]
        if isinstance(value, basestring) and not case_sensitive:
            value = value.lower()
        return value

    return sorted(value.items(), key=sort_func)

def do_sort(value, reverse=False, case_sensitive=False):
    """Sort an iterable.  Per default it sorts ascending, if you pass it
    true as first argument it will reverse the sorting.

    If the iterable is made of strings the third parameter can be used to
    control the case sensitiveness of the comparison which is disabled by
    default.

    .. sourcecode:: jinja

        {% for item in iterable|sort %}
            ...
        {% endfor %}
    """
    if not case_sensitive:
        def sort_func(item):
            if isinstance(item, basestring):
                item = item.lower()
            return item
    else:
        sort_func = None
    return sorted(value, key=sort_func, reverse=reverse)

def do_default(value, default_value=u'', boolean=False):
    """If the value is undefined it will return the passed default value,
    otherwise the value of the variable:

    .. sourcecode:: jinja

        {{ my_variable|default('my_variable is not defined') }}

    This will output the value of ``my_variable`` if the variable was
    defined, otherwise ``'my_variable is not defined'``. If you want
    to use default with variables that evaluate to false you have to
    set the second parameter to `true`:

    .. sourcecode:: jinja

        {{ ''|default('the string was empty', true) }}
    """
    if (boolean and not value) or isinstance(value, Undefined):
        return default_value
    return value

@evalcontextfilter
def do_join(eval_ctx, value, d=u''):
    """Return a string which is the concatenation of the strings in the
    sequence. The separator between elements is an empty string per
    default, you can define it with the optional parameter:

    .. sourcecode:: jinja

        {{ [1, 2, 3]|join('|') }}
            -> 1|2|3

        {{ [1, 2, 3]|join }}
            -> 123
    """
    # no automatic escaping?  joining is a lot eaiser then
    if not eval_ctx.autoescape:
        return unicode(d).join(imap(unicode, value))

    # if the delimiter doesn't have an html representation we check
    # if any of the items has.  If yes we do a coercion to Markup
    if not hasattr(d, '__html__'):
        value = list(value)
        do_escape = False
        for idx, item in enumerate(value):
            if hasattr(item, '__html__'):
                do_escape = True
            else:
                value[idx] = unicode(item)
        if do_escape:
            d = escape(d)
        else:
            d = unicode(d)
        return d.join(value)

    # no html involved, to normal joining
    return soft_unicode(d).join(imap(soft_unicode, value))

def do_center(value, width=80):
    """Centers the value in a field of a given width."""
    return unicode(value).center(width)

@environmentfilter
def do_first(environment, seq):
    """Return the first item of a sequence."""
    try:
        return iter(seq).next()
    except StopIteration:
        return environment.undefined('No first item, sequence was empty.')

@environmentfilter
def do_last(environment, seq):
    """Return the last item of a sequence."""
    try:
        return iter(reversed(seq)).next()
    except StopIteration:
        return environment.undefined('No last item, sequence was empty.')

@environmentfilter
def do_random(environment, seq):
    """Return a random item from the sequence."""
    try:
        return choice(seq)
    except IndexError:
        return environment.undefined('No random item, sequence was empty.')

def do_filesizeformat(value, binary=False):
    """Format the value like a 'human-readable' file size (i.e. 13 KB,
    4.1 MB, 102 bytes, etc).  Per default decimal prefixes are used (mega,
    giga, etc.), if the second parameter is set to `True` the binary
    prefixes are used (mebi, gibi).
    """
    bytes = float(value)
    base = binary and 1024 or 1000
    middle = binary and 'i' or ''
    if bytes < base:
        return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')
    elif bytes < base * base:
        return "%.1f K%sB" % (bytes / base, middle)
    elif bytes < base * base * base:
        return "%.1f M%sB" % (bytes / (base * base), middle)
    return "%.1f G%sB" % (bytes / (base * base * base), middle)

def do_pprint(value, verbose=False):
    """Pretty print a variable. Useful for debugging.

    With Jinja 1.2 onwards you can pass it a parameter.  If this parameter
    is truthy the output will be more verbose (this requires `pretty`)
    """
    return pformat(value, verbose=verbose)

@evalcontextfilter
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False):
    """Converts URLs in plain text into clickable links.

    If you pass the filter an additional integer it will shorten the urls
    to that number. Also a third argument exists that makes the urls
    "nofollow":

    .. sourcecode:: jinja

        {{ mytext|urlize(40, true) }}
            links are shortened to 40 chars and defined with rel="nofollow"
    """
    rv = urlize(value, trim_url_limit, nofollow)
    if eval_ctx.autoescape:
        rv = Markup(rv)
    return rv

def do_indent(s, width=4, indentfirst=False):
    """Return a copy of the passed string, each line indented by
    4 spaces. The first line is not indented. If you want to
    change the number of spaces or indent the first line too
    you can pass additional parameters to the filter:

    .. sourcecode:: jinja

        {{ mytext|indent(2, true) }}
            indent by two spaces and indent the first line too.
    """
    indention = u' ' * width
    rv = (u'\n' + indention).join(s.splitlines())
    if indentfirst:
        rv = indention + rv
    return rv

def do_truncate(s, length=255, killwords=False, end='...'):
    """Return a truncated copy of the string. The length is specified
    with the first parameter which defaults to ``255``. If the second
    parameter is ``true`` the filter will cut the text at length. Otherwise
    it will try to save the last word. If the text was in fact
    truncated it will append an ellipsis sign (``"..."``). If you want a
    different ellipsis sign than ``"..."`` you can specify it using the
    third parameter.

    .. sourcecode jinja::

        {{ mytext|truncate(300, false, '»') }}
            truncate mytext to 300 chars, don't split up words, use a
            right pointing double arrow as ellipsis sign.
    """
    if len(s) <= length:
        return s
    elif killwords:
        return s[:length] + end
    words = s.split(' ')
    result = []
    m = 0
    for word in words:
        m += len(word) + 1
        if m > length:
            break
        result.append(word)
    result.append(end)
    return u' '.join(result)

def do_wordwrap(s, width=79, break_long_words=True):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`.
    """
    import textwrap
    return u'\n'.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))

def do_wordcount(s):
    """Count the words in that string."""
    return len(_word_re.findall(s))

def do_int(value, default=0):
    """Convert the value into an integer. If the
    conversion doesn't work it will return ``0``. You can
    override this default using the first parameter.
    """
    try:
        return int(value)
    except (TypeError, ValueError):
        # this quirk is necessary so that "42.23"|int gives 42.
        try:
            return int(float(value))
        except (TypeError, ValueError):
            return default

def do_float(value, default=0.0):
    """Convert the value into a floating point number. If the
    conversion doesn't work it will return ``0.0``. You can
    override this default using the first parameter.
    """
    try:
        return float(value)
    except (TypeError, ValueError):
        return default

def do_format(value, *args, **kwargs):
    """
    Apply python string formatting on an object:

    .. sourcecode:: jinja

        {{ "%s - %s"|format("Hello?", "Foo!") }}
            -> Hello? - Foo!
    """
    if args and kwargs:
        raise FilterArgumentError('can\'t handle positional and keyword '
                                  'arguments at the same time')
    return soft_unicode(value) % (kwargs or args)

def do_trim(value):
    """Strip leading and trailing whitespace."""
    return soft_unicode(value).strip()

def do_striptags(value):
    """Strip SGML/XML tags and replace adjacent whitespace by one space.
    """
    if hasattr(value, '__html__'):
        value = value.__html__()
    return Markup(unicode(value)).striptags()

def do_slice(value, slices, fill_with=None):
    """Slice an iterator and return a list of lists containing
    those items. Useful if you want to create a div containing
    three ul tags that represent columns:

    .. sourcecode:: html+jinja

          {%- for column in items|slice(3) %}

            {%- for item in column %}

{{ item }}

            {%- endfor %}

          {%- endfor %}

    If you pass it a second argument it's used to fill missing
    values on the last iteration.
    """
    seq = list(value)
    length = len(seq)
    items_per_slice = length // slices
    slices_with_extra = length % slices
    offset = 0
    for slice_number in xrange(slices):
        start = offset + slice_number * items_per_slice
        if slice_number < slices_with_extra:
            offset += 1
        end = offset + (slice_number + 1) * items_per_slice
        tmp = seq[start:end]
        if fill_with is not None and slice_number >= slices_with_extra:
            tmp.append(fill_with)
        yield tmp

def do_batch(value, linecount, fill_with=None):
    """
    A filter that batches items. It works pretty much like `slice`
    just the other way round. It returns a list of lists with the
    given number of items. If you provide a second parameter this
    is used to fill missing items. See this example:

    .. sourcecode:: html+jinja

        {%- for row in items|batch(3, ' ') %}

          {%- for column in row %}
            {{ column }}
          {%- endfor %}

        {%- endfor %}

    """
    result = []
    tmp = []
    for item in value:
        if len(tmp) == linecount:
            yield tmp
            tmp = []
        tmp.append(item)
    if tmp:
        if fill_with is not None and len(tmp) < linecount:
            tmp += [fill_with] * (linecount - len(tmp))
        yield tmp

def do_round(value, precision=0, method='common'):
    """Round the number to a given precision. The first
    parameter specifies the precision (default is ``0``), the
    second the rounding method:

    - ``'common'`` rounds either up or down
    - ``'ceil'`` always rounds up
    - ``'floor'`` always rounds down

    If you don't specify a method ``'common'`` is used.

    .. sourcecode:: jinja

        {{ 42.55|round }}
            -> 43.0
        {{ 42.55|round(1, 'floor') }}
            -> 42.5

    Note that even if rounded to 0 precision, a float is returned.  If
    you need a real integer, pipe it through `int`:

    .. sourcecode:: jinja

        {{ 42.55|round|int }}
            -> 43
    """
    if not method in ('common', 'ceil', 'floor'):
        raise FilterArgumentError('method must be common, ceil or floor')
    if method == 'common':
        return round(value, precision)
    func = getattr(math, method)
    return func(value * (10 ** precision)) / (10 ** precision)

@environmentfilter
def do_groupby(environment, value, attribute):
    """Group a sequence of objects by a common attribute.

    If you for example have a list of dicts or objects that represent persons
    with `gender`, `first_name` and `last_name` attributes and you want to
    group all users by genders you can do something like the following
    snippet:

    .. sourcecode:: html+jinja

        {% for group in persons|groupby('gender') %}

{{ group.grouper }}

            {% for person in group.list %}

{{ person.first_name }} {{ person.last_name }}

            {% endfor %}

        {% endfor %}

    Additionally it's possible to use tuple unpacking for the grouper and
    list:

    .. sourcecode:: html+jinja

        {% for grouper, list in persons|groupby('gender') %}
            ...
        {% endfor %}

    As you can see the item we're grouping by is stored in the `grouper`
    attribute and the `list` contains all the objects that have this grouper
    in common.
    """
    expr = lambda x: environment.getitem(x, attribute)
    return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))

class _GroupTuple(tuple):
    __slots__ = ()
    grouper = property(itemgetter(0))
    list = property(itemgetter(1))

    def __new__(cls, (key, value)):
        return tuple.__new__(cls, (key, list(value)))

def do_list(value):
    """Convert the value into a list.  If it was a string the returned list
    will be a list of characters.
    """
    return list(value)

def do_mark_safe(value):
    """Mark the value as safe which means that in an environment with automatic
    escaping enabled this variable will not be escaped.
    """
    return Markup(value)

def do_mark_unsafe(value):
    """Mark a value as unsafe.  This is the reverse operation for :func:`safe`."""
    return unicode(value)

def do_reverse(value):
    """Reverse the object or return an iterator the iterates over it the other
    way round.
    """
    if isinstance(value, basestring):
        return value[::-1]
    try:
        return reversed(value)
    except TypeError:
        try:
            rv = list(value)
            rv.reverse()
            return rv
        except TypeError:
            raise FilterArgumentError('argument must be iterable')

@environmentfilter
def do_attr(environment, obj, name):
    """Get an attribute of an object.  ``foo|attr("bar")`` works like
    ``foo["bar"]`` just that always an attribute is returned and items are not
    looked up.

    See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
    """
    try:
        name = str(name)
    except UnicodeError:
        pass
    else:
        try:
            value = getattr(obj, name)
        except AttributeError:
            pass
        else:
            if environment.sandboxed and not \
               environment.is_safe_attribute(obj, name, value):
                return environment.unsafe_undefined(obj, name)
            return value
    return environment.undefined(obj=obj, name=name)

FILTERS = {
    'attr':                 do_attr,
    'replace':              do_replace,
    'upper':                do_upper,
    'lower':                do_lower,
    'escape':               escape,
    'e':                    escape,
    'forceescape':          do_forceescape,
    'capitalize':           do_capitalize,
    'title':                do_title,
    'default':              do_default,
    'd':                    do_default,
    'join':                 do_join,
    'count':                len,
    'dictsort':             do_dictsort,
    'sort':                 do_sort,
    'length':               len,
    'reverse':              do_reverse,
    'center':               do_center,
    'indent':               do_indent,
    'title':                do_title,
    'capitalize':           do_capitalize,
    'first':                do_first,
    'last':                 do_last,
    'random':               do_random,
    'filesizeformat':       do_filesizeformat,
    'pprint':               do_pprint,
    'truncate':             do_truncate,
    'wordwrap':             do_wordwrap,
    'wordcount':            do_wordcount,
    'int':                  do_int,
    'float':                do_float,
    'string':               soft_unicode,
    'list':                 do_list,
    'urlize':               do_urlize,
    'format':               do_format,
    'trim':                 do_trim,
    'striptags':            do_striptags,
    'slice':                do_slice,
    'batch':                do_batch,
    'sum':                  sum,
    'abs':                  abs,
    'round':                do_round,
    'groupby':              do_groupby,
    'safe':                 do_mark_safe,
    'xmlattr':              do_xmlattr
}


text:
  do {                                                                                \
    std::cerr << (s) << std::endl;                                                                 \
  } while (0)
#else
#define DEBUG_LOG(s)
#endif

using namespace Envoy::Tools::TypeWhisperer;

namespace ApiBooster {

class ApiBooster : public clang::ast_matchers::MatchFinder::MatchCallback,
                   public clang::tooling::SourceFileCallbacks {
public:
  ApiBooster(std::map<std::string, clang::tooling::Replacements>& replacements)
      : replacements_(replacements) {}

  // AST match callback dispatcher.
  void run(const clang::ast_matchers::MatchFinder::MatchResult& match_result) override {
    clang::SourceManager& source_manager = match_result.Context->getSourceManager();
    DEBUG_LOG("AST match callback dispatcher");
    for (const auto it : match_result.Nodes.getMap()) {
      const std::string match_text = getSourceText(it.second.getSourceRange(), source_manager);
      const clang::SourceRange spelling_range =
          getSpellingRange(it.second.getSourceRange(), source_manager);
      const std::string spelling_text = getSourceText(spelling_range, source_manager);
      DEBUG_LOG(absl::StrCat("  Result for ", it.first, " [", truncateForDebug(match_text), "]"));
      if (match_text != spelling_text) {
        DEBUG_LOG(absl::StrCat("    with spelling text [", truncateForDebug(spelling_text), "]"));
      }
    }
    if (const auto* type_loc = match_result.Nodes.getNodeAs<clang::TypeLoc>("type")) {
      onTypeLocMatch(*type_loc, source_manager);
      return;
    }
    if (const auto* using_decl = match_result.Nodes.getNodeAs<clang::UsingDecl>("using_decl")) {
      onUsingDeclMatch(*using_decl, source_manager);
      return;
    }
    if (const auto* decl_ref_expr =
            match_result.Nodes.getNodeAs<clang::DeclRefExpr>("decl_ref_expr")) {
      onDeclRefExprMatch(*decl_ref_expr, *match_result.Context, source_manager);
      return;
    }
    if (const auto* call_expr = match_result.Nodes.getNodeAs<clang::CallExpr>("call_expr")) {
      onCallExprMatch(*call_expr, *match_result.Context, source_manager);
      return;
    }
    if (const auto* member_call_expr =
            match_result.Nodes.getNodeAs<clang::CXXMemberCallExpr>("member_call_expr")) {
      onMemberCallExprMatch(*member_call_expr, source_manager);
      return;
    }
    if (const auto* tmpl =
            match_result.Nodes.getNodeAs<clang::ClassTemplateSpecializationDecl>("tmpl")) {
      onClassTemplateSpecializationDeclMatch(*tmpl, source_manager);
      return;
    }
  }

  // Visitor callback for start of a compilation unit.
  bool handleBeginSource(clang::CompilerInstance& CI) override {
    source_api_proto_paths_.clear();
    return true;
  }

  // Visitor callback for end of a compilation unit.
  void handleEndSource() override {
    // Dump known API header paths to stdout for api_boost.py to rewrite with
    // (no rewriting support in this tool yet).
    for (const std::string& proto_path : source_api_proto_paths_) {
      std::cout << proto_path << std::endl;
    }
  }

private:
  static bool isEnvoyNamespace(absl::string_view s) {
    return absl::StartsWith(s, "envoy::") || absl::StartsWith(s, "::envoy::");
  }

  static std::string truncateForDebug(const std::string& text) {
    const uint32_t MaxExpansionChars = 250;
    return text.size() > MaxExpansionChars ? text.substr(0, MaxExpansionChars) + "..." : text;
  }

  // Match callback for TypeLoc. These are explicit mentions of the type in the
  // source. If we have a match on type, we should track the corresponding .pb.h
  // and attempt to upgrade.
  void onTypeLocMatch(const clang::TypeLoc& type_loc, const clang::SourceManager& source_manager) {
    absl::optional<clang::SourceRange> source_range;
    const std::string type_name =
        type_loc.getType().getCanonicalType().getUnqualifiedType().getAsString();
    // Remove qualifiers, e.g. const.
    const clang::UnqualTypeLoc unqual_type_loc = type_loc.getUnqualifiedLoc();
    DEBUG_LOG(absl::StrCat("Type class ", type_loc.getType()->getTypeClassName()));
    // Today we are only smart enough to rewrite ElaborateTypeLoc, which are
    // full namespace prefixed types. We probably will need to support more, in
    // particular if we want message-level type renaming. TODO(htuch): add more
    // supported AST TypeLoc classes as needed.
    if (unqual_type_loc.getTypeLocClass() == clang::TypeLoc::Elaborated &&
        isEnvoyNamespace(getSourceText(
            getSpellingRange(unqual_type_loc.getSourceRange(), source_manager), source_manager))) {
      source_range = absl::make_optional<clang::SourceRange>(unqual_type_loc.getSourceRange());
      tryBoostType(type_name, source_range, source_manager, type_loc.getType()->getTypeClassName(),
                   false);
    } else {
      // If we're not going to rewrite, we still deliver SourceLocation to
      // tryBoostType to assist with determination of API_NO_BOOST().
      tryBoostType(type_name, unqual_type_loc.getBeginLoc(), -1, source_manager,
                   type_loc.getType()->getTypeClassName(), false);
    }
  }

  // Match callback for clang::UsingDecl. These are 'using' aliases for API type
  // names.
  void onUsingDeclMatch(const clang::UsingDecl& using_decl,
                        const clang::SourceManager& source_manager) {
    // Not all using declaration are types, but we try the rewrite in case there
    // is such an API type database match.
    const clang::SourceRange source_range = clang::SourceRange(
        using_decl.getQualifierLoc().getBeginLoc(), using_decl.getNameInfo().getEndLoc());
    const std::string type_name = getSourceText(source_range, source_manager);
    tryBoostType(type_name, source_range, source_manager, "UsingDecl", true);
  }

  // Match callback for clang::DeclRefExpr. These occur when enums constants,
  // e.g. foo::bar::kBaz, appear in the source.
  void onDeclRefExprMatch(const clang::DeclRefExpr& decl_ref_expr, const clang::ASTContext& context,
                          const clang::SourceManager& source_manager) {
    // We don't need to consider non-namespace qualified DeclRefExprfor now (no
    // renaming support yet).
    if (!decl_ref_expr.hasQualifier()) {
      return;
    }
    const std::string decl_name = decl_ref_expr.getNameInfo().getAsString();
    // There are generated methods to stringify/parse/validate enum values,
    // these need special treatment as they look like types with special
    // suffices.
    for (const std::string& enum_generated_method_suffix : {"_Name", "_Parse", "_IsValid"}) {
      if (absl::EndsWith(decl_name, enum_generated_method_suffix)) {
        // Remove trailing suffix from reference for replacement range and type
        // name purposes.
        const clang::SourceLocation begin_loc =
            source_manager.getSpellingLoc(decl_ref_expr.getBeginLoc());
        const std::string type_name_with_suffix =
            getSourceText(decl_ref_expr.getSourceRange(), source_manager);
        const std::string type_name = type_name_with_suffix.substr(
            0, type_name_with_suffix.size() - enum_generated_method_suffix.size());
        tryBoostType(type_name, begin_loc, type_name.size(), source_manager,
                     "DeclRefExpr suffixed " + enum_generated_method_suffix, false);
        return;
      }
    }
    // Remove trailing : from namespace qualifier.
    const clang::SourceRange source_range =
        clang::SourceRange(decl_ref_expr.getQualifierLoc().getBeginLoc(),
                           decl_ref_expr.getQualifierLoc().getEndLoc().getLocWithOffset(-1));
    // Only try to boost type if it's explicitly an Envoy qualified type.
    const std::string source_type_name = getSourceText(source_range, source_manager);
    const clang::QualType ast_type =
        decl_ref_expr.getDecl()->getType().getCanonicalType().getUnqualifiedType();
    const std::string ast_type_name = ast_type.getAsString();
    if (isEnvoyNamespace(source_type_name)) {
      // Generally we pull the type from the named entity's declaration type,
      // since this allows us to map from things like envoy::type::HTTP2 to the
      // underlying fully qualified envoy::type::CodecClientType::HTTP2 prior to
      // API type database lookup. However, for the generated static methods or
      // field accessors, we don't want to deal with lookup via the function
      // type, so we use the source text directly.
      const std::string type_name = ast_type.isPODType(context) ? ast_type_name : source_type_name;
      tryBoostType(type_name, source_range, source_manager, "DeclRefExpr", true);
    }
    const auto latest_type_info = getTypeInformationFromCType(ast_type_name, true);
    // In some cases we need to upgrade the name the DeclRefExpr points at. If
    // this isn't a known API type, our work here is done.
    if (!latest_type_info) {
      return;
    }
    const clang::SourceRange decl_source_range = decl_ref_expr.getNameInfo().getSourceRange();
    // Deprecated enum constants need to be upgraded.
    if (latest_type_info->enum_type_) {
      const auto enum_value_rename =
          ProtoCxxUtils::renameEnumValue(decl_name, latest_type_info->renames_);
      if (enum_value_rename) {
        const clang::SourceRange decl_source_range = decl_ref_expr.getNameInfo().getSourceRange();
        const clang::tooling::Replacement enum_value_replacement(
            source_manager, source_manager.getSpellingLoc(decl_source_range.getBegin()),
            sourceRangeLength(decl_source_range, source_manager), *enum_value_rename);
        insertReplacement(enum_value_replacement);
      }
      return;
    }
    // We need to map from envoy::type::matcher::StringMatcher::kRegex to
    // envoy::type::matcher::v3::StringMatcher::kHiddenEnvoyDeprecatedRegex.
    const auto constant_rename =
        ProtoCxxUtils::renameConstant(decl_name, latest_type_info->renames_);
    if (constant_rename) {
      const clang::tooling::Replacement constant_replacement(
          source_manager, decl_source_range.getBegin(),
          sourceRangeLength(decl_source_range, source_manager), *constant_rename);
      insertReplacement(constant_replacement);
    }
  }

  // Match callback clang::CallExpr. We don't need to rewrite, but if it's something like
  // loadFromYamlAndValidate, we might need to look at the argument type to
  // figure out any corresponding .pb.validate.h we require.
  void onCallExprMatch(const clang::CallExpr& call_expr, const clang::ASTContext& context,
                       const clang::SourceManager& source_manager) {
    auto* direct_callee = call_expr.getDirectCallee();
    if (direct_callee != nullptr) {
      const std::unordered_map<std::string, int> ValidateNameToArg = {
          {"loadFromYamlAndValidate", 1},
          {"loadFromFileAndValidate", 1},
          {"downcastAndValidate", -1},
          {"validate", 0},
      };
      const std::string& callee_name = direct_callee->getNameInfo().getName().getAsString();
      DEBUG_LOG(absl::StrCat("callee_name ", callee_name));
      const auto arg = ValidateNameToArg.find(callee_name);
      // Sometimes we hit false positives because we aren't qualifying above.
      // TODO(htuch): fix this.
      if (arg != ValidateNameToArg.end() &&
          arg->second < static_cast<int>(call_expr.getNumArgs())) {
        const std::string type_name = arg->second >= 0 ? call_expr.getArg(arg->second)
                                                             ->getType()
                                                             .getCanonicalType()
                                                             .getUnqualifiedType()
                                                             .getAsString()
                                                       : call_expr.getCallReturnType(context)
                                                             .getNonReferenceType()
                                                             .getCanonicalType()
                                                             .getUnqualifiedType()
                                                             .getAsString();
        DEBUG_LOG(absl::StrCat("Validation header boosting ", type_name));
        tryBoostType(type_name, {}, source_manager, "validation invocation", true, true);
      }
    }
  }

  // Match callback for clang::CxxMemberCallExpr. We rewrite things like
  // ->mutable_foo() to ->mutable_foo_new_name() during renames.
  void onMemberCallExprMatch(const clang::CXXMemberCallExpr& member_call_expr,
                             const clang::SourceManager& source_manager) {
    const std::string type_name =
        member_call_expr.getObjectType().getCanonicalType().getUnqualifiedType().getAsString();
    const auto latest_type_info = getTypeInformationFromCType(type_name, true);
    // If this isn't a known API type, our work here is done.
    if (!latest_type_info) {
      return;
    }
    // Figure out if the referenced object was declared under API_NO_BOOST. This
    // only works for simple cases, best effort.
    const auto* object_expr = member_call_expr.getImplicitObjectArgument();
    if (object_expr != nullptr) {
      const auto* decl = object_expr->getReferencedDeclOfCallee();
      if (decl != nullptr &&
          getSourceText(decl->getSourceRange(), source_manager).find("API_NO_BOOST") !=
              std::string::npos) {
        DEBUG_LOG("Skipping method replacement due to API_NO_BOOST");
        return;
      }
    }
    tryRenameMethod(*latest_type_info, member_call_expr.getExprLoc(), source_manager);
  }

  bool tryRenameMethod(const TypeInformation& type_info, clang::SourceLocation method_loc,
                       const clang::SourceManager& source_manager) {
    const clang::SourceRange source_range = {source_manager.getSpellingLoc(method_loc),
                                             source_manager.getSpellingLoc(method_loc)};
    const std::string method_name = getSourceText(source_range, source_manager);
    DEBUG_LOG(absl::StrCat("Checking for rename of ", method_name));
    const auto method_rename = ProtoCxxUtils::renameMethod(method_name, type_info.renames_);
    if (method_rename) {
      const clang::tooling::Replacement method_replacement(
          source_manager, source_range.getBegin(), sourceRangeLength(source_range, source_manager),
          *method_rename);
      insertReplacement(method_replacement);
      return true;
    }
    return false;
  }

  // Match callback for clang::ClassTemplateSpecializationDecl. An additional
  // place we need to look for .pb.validate.h reference is instantiation of
  // FactoryBase.
  void onClassTemplateSpecializationDeclMatch(const clang::ClassTemplateSpecializationDecl& tmpl,
                                              const clang::SourceManager& source_manager) {
    const std::string tmpl_type_name = tmpl.getSpecializedTemplate()
                                           ->getInjectedClassNameSpecialization()
                                           .getCanonicalType()
                                           .getAsString();
    if (absl::EndsWith(tmpl_type_name, "FactoryBase<type-parameter-0-0>")) {
      const std::string type_name = tmpl.getTemplateArgs()
                                        .get(0)
                                        .getAsType()
                                        .getCanonicalType()
                                        .getUnqualifiedType()
                                        .getAsString();
      tryBoostType(type_name, {}, source_manager, "FactoryBase template", true, true);
    }
    if (tmpl_type_name == "FactoryBase<type-parameter-0-0, type-parameter-0-1>") {
      const std::string type_name_0 = tmpl.getTemplateArgs()
                                          .get(0)
                                          .getAsType()
                                          .getCanonicalType()
                                          .getUnqualifiedType()
                                          .getAsString();
      tryBoostType(type_name_0, {}, source_manager, "FactoryBase template", true, true);
      const std::string type_name_1 = tmpl.getTemplateArgs()
                                          .get(1)
                                          .getAsType()
                                          .getCanonicalType()
                                          .getUnqualifiedType()
                                          .getAsString();
      tryBoostType(type_name_1, {}, source_manager, "FactoryBase template", true, true);
    }
  }

  // Attempt to boost a given type and rewrite the given source range.
  void tryBoostType(const std::string& type_name, absl::optional<clang::SourceRange> source_range,
                    const clang::SourceManager& source_manager, absl::string_view debug_description,
                    bool requires_enum_truncation, bool validation_required = false) {
    if (source_range) {
      tryBoostType(type_name, source_range->getBegin(),
                   sourceRangeLength(*source_range, source_manager), source_manager,
                   debug_description, requires_enum_truncation, validation_required);
    } else {
      tryBoostType(type_name, {}, -1, source_manager, debug_description, requires_enum_truncation,
                   validation_required);
    }
  }

  bool underApiNoBoost(clang::SourceLocation loc, const clang::SourceManager& source_manager) {
    if (loc.isMacroID()) {
      const auto macro_name = clang::Lexer::getImmediateMacroName(loc, source_manager, lexer_lopt_);
      if (macro_name.str() == "API_NO_BOOST") {
        return true;
      }
    }
    return false;
  }

  void tryBoostType(const std::string& type_name, clang::SourceLocation begin_loc, int length,
                    const clang::SourceManager& source_manager, absl::string_view debug_description,
                    bool requires_enum_truncation, bool validation_required = false) {
    bool is_skip_macro = false;
    if (underApiNoBoost(begin_loc, source_manager)) {
      DEBUG_LOG("Skipping replacement due to API_NO_BOOST");
      is_skip_macro = true;
    }
    const auto type_info = getTypeInformationFromCType(type_name, !is_skip_macro);
    // If this isn't a known API type, our work here is done.
    if (!type_info) {
      return;
    }
    DEBUG_LOG(absl::StrCat("Matched type '", type_name, "' (", debug_description, ") length ",
                           length, " at ", begin_loc.printToString(source_manager)));
    // Track corresponding imports.
    source_api_proto_paths_.insert(adjustProtoSuffix(type_info->proto_path_, ".pb.h"));
    if (validation_required) {
      source_api_proto_paths_.insert(adjustProtoSuffix(type_info->proto_path_, ".pb.validate.h"));
    }
    // Not all AST matchers know how to do replacements (yet?).
    if (length == -1 || is_skip_macro) {
      return;
    }
    const clang::SourceLocation spelling_begin = source_manager.getSpellingLoc(begin_loc);
    // We need to look at the text we're replacing to decide whether we should
    // use the qualified C++'ified proto name.
    const bool qualified =
        getSourceText(spelling_begin, length, source_manager).find("::") != std::string::npos;
    std::string case_residual;
    if (absl::EndsWith(type_name, "Case")) {
      case_residual = type_name.substr(type_name.rfind(':') - 1);
    }
    // Add corresponding replacement.
    const clang::tooling::Replacement type_replacement(
        source_manager, source_manager.getSpellingLoc(begin_loc), length,
        ProtoCxxUtils::protoToCxxType(type_info->type_name_, qualified,
                                      type_info->enum_type_ && requires_enum_truncation) +
            case_residual);
    insertReplacement(type_replacement);
  }

  void insertReplacement(const clang::tooling::Replacement& replacement) {
    llvm::Error error = replacements_[replacement.getFilePath()].add(replacement);
    if (error) {
      std::cerr << "  Replacement insertion error: " << llvm::toString(std::move(error))
                << std::endl;
    } else {
      std::cerr << "  Replacement added: " << replacement.toString() << std::endl;
    }
  }

  // Modeled after getRangeSize() in Clang's Replacements.cpp. Turns out it's
  // non-trivial to get the actual length of a SourceRange, as the end location
  // point to the start of the last token.
  int sourceRangeLength(clang::SourceRange source_range,
                        const clang::SourceManager& source_manager) {
    const clang::SourceLocation spelling_begin =
        source_manager.getSpellingLoc(source_range.getBegin());
    const clang::SourceLocation spelling_end = source_manager.getSpellingLoc(source_range.getEnd());
    std::pair<clang::FileID, unsigned> start = source_manager.getDecomposedLoc(spelling_begin);
    std::pair<clang::FileID, unsigned> end = source_manager.getDecomposedLoc(spelling_end);
    if (start.first != end.first) {
      return -1;
    }
    end.second += clang::Lexer::MeasureTokenLength(spelling_end, source_manager, lexer_lopt_);
    return end.second - start.second;
  }

  std::string getSourceText(clang::SourceLocation begin_loc, int size,
                            const clang::SourceManager& source_manager) {
    return clang::Lexer::getSourceText(
        {clang::SourceRange(begin_loc, begin_loc.getLocWithOffset(size)), false}, source_manager,
        lexer_lopt_, 0);
  }

  std::string getSourceText(clang::SourceRange source_range,
                            const clang::SourceManager& source_manager) {
    return clang::Lexer::getSourceText(clang::CharSourceRange::getTokenRange(source_range),
                                       source_manager, lexer_lopt_, 0);
  }

  void addNamedspaceQualifiedTypeReplacement() {}

  // Remove .proto from a path, apply specified suffix instead.
  std::string adjustProtoSuffix(absl::string_view proto_path, absl::string_view suffix) {
    return absl::StrCat(proto_path.substr(0, proto_path.size() - 6), suffix);
  }

  // Obtain the latest type information for a given from C++ type, e.g. envoy:config::v2::Cluster,
  // from the API type database.
  absl::optional<TypeInformation> getTypeInformationFromCType(const std::string& c_type_name,
                                                              bool latest) {
    // Ignore compound or non-API types.
    // TODO(htuch): this is all super hacky and not really right, we should be
    // removing qualifiers etc. to get to the underlying type name.
    const std::string type_name = std::regex_replace(c_type_name, std::regex("^(class|enum) "), "");
    if (!isEnvoyNamespace(type_name) || absl::StrContains(type_name, " ")) {
      return {};
    }
    const std::string proto_type_name = ProtoCxxUtils::cxxToProtoType(type_name);

    // Use API type database to map from proto type to path.
    auto result = latest ? ApiTypeDb::getLatestTypeInformation(proto_type_name)
                         : ApiTypeDb::getExistingTypeInformation(proto_type_name);
    if (result) {
      // Remove the .proto extension.
      return result;
    } else if (!absl::StartsWith(proto_type_name, "envoy.HotRestart") &&
               !absl::StartsWith(proto_type_name, "envoy.RouterCheckToolSchema") &&
               !absl::StartsWith(proto_type_name, "envoy.annotations") &&
               !absl::StartsWith(proto_type_name, "envoy.test") &&
               !absl::StartsWith(proto_type_name, "envoy.tracers.xray.daemon")) {
      // Die hard if we don't have a useful proto type for something that looks
      // like an API type(modulo a short whitelist).
      std::cerr << "Unknown API type: " << proto_type_name << std::endl;
      // TODO(htuch): maybe there is a nicer way to terminate AST traversal?
      ::exit(1);
    }

    return {};
  }

  static clang::SourceRange getSpellingRange(clang::SourceRange source_range,
                                             const clang::SourceManager& source_manager) {
    return {source_manager.getSpellingLoc(source_range.getBegin()),
            source_manager.getSpellingLoc(source_range.getEnd())};
  }

  // Set of inferred .pb[.validate].h, updated as the AST matcher callbacks above fire.
  std::set<std::string> source_api_proto_paths_;
  // Map from source file to replacements.
  std::map<std::string, clang::tooling::Replacements>& replacements_;
  // Language options for interacting with Lexer. Currently empty.
  clang::LangOptions lexer_lopt_;
}; // namespace ApiBooster

} // namespace ApiBooster

int main(int argc, const char** argv) {
  // Apply a custom category to all command-line options so that they are the
  // only ones displayed.
  llvm::cl::OptionCategory api_booster_tool_category("api-booster options");

  clang::tooling::CommonOptionsParser options_parser(argc, argv, api_booster_tool_category);
  clang::tooling::RefactoringTool tool(options_parser.getCompilations(),
                                       options_parser.getSourcePathList());

  ApiBooster::ApiBooster api_booster(tool.getReplacements());
  clang::ast_matchers::MatchFinder finder;

  // Match on all mentions of types in the AST.
  auto type_matcher =
      clang::ast_matchers::typeLoc(clang::ast_matchers::isExpansionInMainFile()).bind("type");
  finder.addMatcher(type_matcher, &api_booster);

  // Match on all "using" declarations.
  auto using_decl_matcher =
      clang::ast_matchers::usingDecl(clang::ast_matchers::isExpansionInMainFile())
          .bind("using_decl");
  finder.addMatcher(using_decl_matcher, &api_booster);

  // Match on references to enum constants.
  auto decl_ref_expr_matcher =
      clang::ast_matchers::declRefExpr(clang::ast_matchers::isExpansionInMainFile())
          .bind("decl_ref_expr");
  finder.addMatcher(decl_ref_expr_matcher, &api_booster);

  // Match on all call expressions. We are interested in particular in calls
  // where validation on protos is performed.
  auto call_matcher =
      clang::ast_matchers::callExpr(clang::ast_matchers::isExpansionInMainFile()).bind("call_expr");
  finder.addMatcher(call_matcher, &api_booster);

  // Match on all .foo() or ->foo() expressions. We are interested in these for renames
  // and deprecations.
  auto member_call_expr =
      clang::ast_matchers::cxxMemberCallExpr(clang::ast_matchers::isExpansionInMainFile())
          .bind("member_call_expr");
  finder.addMatcher(member_call_expr, &api_booster);

  // Match on all template instantiations. We are interested in particular in
  // instantiations of factories where validation on protos is performed.
  auto tmpl_matcher = clang::ast_matchers::classTemplateSpecializationDecl(
                          clang::ast_matchers::matchesName(".*FactoryBase.*"))
                          .bind("tmpl");
  finder.addMatcher(tmpl_matcher, &api_booster);

  // Apply ApiBooster to AST matches. This will generate a set of replacements in
  // tool.getReplacements().
  const int run_result = tool.run(newFrontendActionFactory(&finder, &api_booster).get());
  if (run_result != 0) {
    std::cerr << "Exiting with non-zero result " << run_result << std::endl;
    return run_result;
  }

  // Serialize replacements to <main source file path>.clang-replacements.yaml.
  // These are suitable for consuming by clang-apply-replacements.
  for (const auto& file_replacement : tool.getReplacements()) {
    // Populate TranslationUnitReplacements from file replacements (this is what
    // there exists llvm::yaml serialization support for).
    clang::tooling::TranslationUnitReplacements tu_replacements;
    tu_replacements.MainSourceFile = file_replacement.first;
    for (const auto& r : file_replacement.second) {
      tu_replacements.Replacements.push_back(r);
      DEBUG_LOG(r.toString());
    }
    // Serialize TranslationUnitReplacements to YAML.
    std::string yaml_content;
    llvm::raw_string_ostream yaml_content_stream(yaml_content);
    llvm::yaml::Output yaml(yaml_content_stream);
    yaml << tu_replacements;
    // Write to <main source file path>.clang-replacements.yaml.
    std::ofstream serialized_replacement_file(tu_replacements.MainSourceFile +
                                              ".clang-replacements.yaml");
    serialized_replacement_file << yaml_content_stream.str();
  }

  return 0;
}


text:
package com.waynezhang.mcommon.network;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.JsonSyntaxException;
//import com.shandagames.greport.GReport;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.InternalCache;
import com.waynezhang.mcommon.util.BitmapUtil;
import com.waynezhang.mcommon.util.L;
import com.waynezhang.mcommon.util.ThreadUtil;

import org.apache.http.conn.ConnectTimeoutException;

import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by jc0mm0n on 10/22/14.
 */
public class Http {
    private Http() {
    }

    private static final String TAG = "Http";
    private static OkHttpClient client = new OkHttpClient();
    private static HttpPolicyHandlerImp httpCachePolicyHandler;
    private static InternalCache okHttpCache;
    private static CookieManager cookieManager;
    private static Context mContext;
    private static Init mInit;

    private static Handler handler = new Handler(Looper.getMainLooper());

    static {
        cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        client.setCookieHandler(cookieManager);
    }

    public static void removeAllCookies() {
        cookieManager.getCookieStore().removeAll();
    }

    //初始化自定义策略
    public static void initCachePolicyHandler(HttpPolicyHandlerImp httpPolicyHandler) throws IOException {
        initCachePolicyHandler(null, httpPolicyHandler, null);
    }

    public static void initCachePolicyHandler(Context context, HttpPolicyHandlerImp httpPolicyHandler, Init init) throws IOException {
        mContext = context;
        mInit = init;
        if (httpPolicyHandler != null) {
            httpCachePolicyHandler = httpPolicyHandler;
            client.setReadTimeout(httpCachePolicyHandler.getSocketTimeout(), TimeUnit.MILLISECONDS);
            client.setConnectTimeout(httpCachePolicyHandler.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }
    }

    public static void cancel(String url) {
        client.cancel(url);
        httpCachePolicyHandler.cancelTimeoutTask(url);
    }

    public static void cancel(Object tag) {
        client.cancel(tag.hashCode());
        httpCachePolicyHandler.cancelTimeoutTask(tag.hashCode());
    }

    public static String get(final String url, final StringCallback callback) {
        //cancel tag with same url
//        cancel(url);  // Deleted by waynezhang on 5/9/16: 删除取消相同url的request的代码, 转由业务层控制
        UUID tag = UUID.randomUUID();
        L.d(TAG, "Do GET --> " + url);
        final Request request = new Request.Builder().url(url).tag(url).build();

        //检查请求url策略匹配,添加至策略任务
        final String urlKey = url;
        final long startTime = System.currentTimeMillis();
        if (httpCachePolicyHandler == null ? true : httpCachePolicyHandler.preReqPolicyHandle(url, urlKey, "", callback)) {
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(final Request request, final IOException e) {
                    handleErrorWithCache(urlKey, handler, request, e, callback, startTime);
                }

                @Override
                public void onResponse(Response response) {
                    try {
                        final String responseString = response.body().string();
                        L.v(TAG, "[" + url + "] response:" + responseString);
                        if (null != mInit && httpCachePolicyHandler != null) {
                            int responseCode = mInit.getResponseCode(responseString);
                            httpCachePolicyHandler.postReqPolicyHandle(url, urlKey, "", responseString, callback, responseCode == 0);
                            reportTimeCost(url, responseCode, startTime, response.code(), 0);
                        } else {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    callback.onResponse(responseString);
                                }
                            });
                        }
                    } catch (final Throwable e) {
                        handleErrorWithCache(urlKey, handler, request, e, callback, startTime, response.code());
                    }
                }
            });
        }

        return tag.toString();
    }

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    // 上传Json字符串使用
    public static void post(final Object httpTag, final String url, final String json, final StringCallback callback) {
        L.d(TAG, "Do Post --> " + url + " --> " + json);
        RequestBody requestBody = RequestBody.create(JSON, json);
        final Request request = new Request.Builder().url(url).tag(httpTag.hashCode()).post(requestBody).build();

        //检查请求url策略匹配,添加至策略任务
        final String urlKey = url;
        final String params = json;
        final long startTime = System.currentTimeMillis();
        if (httpCachePolicyHandler == null ? true : httpCachePolicyHandler.preReqPolicyHandle(httpTag.hashCode(), urlKey, params, callback)) {
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(final Request request, final IOException e) {
                    handleErrorWithCache(urlKey, handler, request, e, callback, startTime);
                }

                @Override
                public void onResponse(Response response) {
                    try {
                        final String responseString = response.body().string();
                        L.v(TAG, "[" + url + "] response:" + responseString);
                        if (null != mInit && httpCachePolicyHandler != null) {
                            int responseCode = mInit.getResponseCode(responseString);
                            httpCachePolicyHandler.postReqPolicyHandle(httpTag.hashCode(), urlKey, params, responseString, callback, responseCode == 0);
                            reportTimeCost(url, responseCode, startTime, response.code(), 0);
                        } else {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    callback.onResponse(responseString);
                                }
                            });
                        }
                    } catch (final Throwable e) {
                        handleErrorWithCache(urlKey, handler, request, e, callback, startTime, response.code());
                    }
                }
            });
        }

    }

    private static final MediaType MEDIA_TYPE = MediaType.parse("image/jpeg");

    // 上传图片使用
    public static String post(final String url, final Bitmap attachment, final StringCallback callback) {
        return post(url, null, attachment, callback);
    }

    // 上传图片使用
    public static String post(final String url, final Map<String, String> params, final Bitmap attachment, final StringCallback callback) {
        String tag = post(url, params, BitmapUtil.getJpegBytes(attachment), callback);
        attachment.recycle();
        return tag;
    }

    // 上传图片使用
    public static String post(final String url, final Map<String, String> params, final byte[] bytes, final StringCallback callback) {
        L.d(TAG, "Do Post --> " + url);
        MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Iterator<Map.Entry<String, String>> iterator = entrySet.iterator(); iterator.hasNext(); ) {
                Map.Entry<String, String> it = iterator.next();
                builder.addFormDataPart(it.getKey(), it.getValue());
            }
        }
        builder = builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"a.jpg\""),
                RequestBody.create(MEDIA_TYPE, bytes));
        RequestBody requestBody = builder.build();
        final Request request = new Request.Builder().url(url).tag(url).post(requestBody).build();

        final long startTime = System.currentTimeMillis();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(final Request request, final IOException e) {
                handleError(url, handler, request, e, callback, startTime);
            }

            @Override
            public void onResponse(Response response) {
                try {
                    final String responseString = response.body().string();
                    L.v(TAG, "[" + url + "] response:" + responseString);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onResponse(responseString);
                        }
                    });
                    reportTimeCost(url, mInit != null ? mInit.getResponseCode(responseString) : 0, startTime, response.code(), 0);
                } catch (final Throwable e) {
                    handleError(url, handler, request, e, callback, startTime, response.code());
                }
            }
        });

        return url;
    }

    private static void handleErrorWithCache(final String url, final Handler handler, final Request request, final Throwable th, final OnErrorCallback callback, final long startTime) {
        handleErrorWithCache(url, handler, request, th, callback, startTime, 0);
    }

    private static void handleErrorWithCache(final String url, final Handler handler, final Request request, final Throwable th, final OnErrorCallback callback, final long startTime, int httpResponseCode) {
        final ResultCode resultCode = getErrorCode(th);
        reportTimeCost(url, 0, startTime, httpResponseCode, resultCode.nativeInt);
        //检查是否缓存命中过, 如果没有命中过, 则返回onFailure; 如果命中过, 则由缓存策略处理返回
        if (httpCachePolicyHandler != null && !httpCachePolicyHandler.checkCacheHit(url)) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onFailure(request, resultCode, (Exception) th);
                }
            });
        }
    }

    private static void handleError(final String url, Handler handler, final Request request, final Throwable th, final OnErrorCallback cb, final long startTime) {
        handleError(url, handler, request, th, cb, startTime, 0);
    }

    private static void handleError(final String url, Handler handler, final Request request, final Throwable th, final OnErrorCallback cb, final long startTime, int httpResponseCode) {
        final ResultCode resultCode = getErrorCode(th);
        reportTimeCost(url, 0, startTime, httpResponseCode, resultCode.nativeInt);
        handler.post(new Runnable() {
            @Override
            public void run() {
                cb.onFailure(request, resultCode, (Exception) th);
            }
        });
    }

    private static ResultCode getErrorCode(final Throwable th) {
        assert (th != null);

        if (th instanceof ConnectTimeoutException) {
            return ResultCode.RequestTimeout;
        }

        if (th instanceof SocketTimeoutException) {
            return ResultCode.ServerResponseTimeout;
        }

        if (th instanceof IOException) {
            return ResultCode.NetworkException;
        }

        if (th instanceof JsonSyntaxException) {
            return ResultCode.ServerException;
        }

        return ResultCode.DefaultException;
    }

    public static void reportTimeCost(String url, int responseCode, long startTime, int httpResponseCode, int exceptionCode) {
        if (mInit != null) {
            String methodName = mInit.getMethodName(url);
            final HashMap<String, String> map = new HashMap();
            map.put("methodName", methodName);
            map.put("bizCode", "" + responseCode);
            map.put("timeCost", "" + (System.currentTimeMillis() - startTime));
            map.put("httpCode", "" + httpResponseCode);
            map.put("exceptionCode", "" + exceptionCode);
            map.put("url", url);
            ThreadUtil.runOnUiThread(mContext, new Runnable() {
                @Override
                public void run() {
//                    GReport.onEvent(mContext, "ApiStatics", map);
                }
            });
        }
    }

    public static interface OnErrorCallback {
        public void onFailure(Request request, ResultCode code, Exception e);
    }

    public static interface StringCallback extends OnErrorCallback {
        public void onResponse(String result);
    }

    public static interface JsonArrayCallback<T> extends OnErrorCallback {
        public Class<T> getGenericType();

        public void onResponse(List<T> resultList);
    }

    public abstract interface JsonObjectCallback<T> extends OnErrorCallback {
        public Class<T> getGenericType();

        public void onResponse(T result);
    }

    public static interface Init {
        public String getMethodName(String url);

        public int getResponseCode(String result);
    }
}


text:
package rocfox.rdf2xml.transformation.processor.xml;

import java.io.CharArrayWriter;
import org.junit.Test;
import org.w3c.dom.Document;
import rocfox.rdf2xml.transformation.dom.XmlAttribute;
import rocfox.rdf2xml.transformation.processor.context.TransformContext;
import rocfox.rdf2xml.utilities.xml.DocumentReader;
import rocfox.rdf2xml.utilities.xml.XmlWriter;
import rocfox.rdf2xml.utilities.xml.unitTest.XmlAssert;
import static org.junit.Assert.*;

/**
 *
 * @author Nicolas
 */
public class XmlAttributeProcessorTest
{
	private static final String prefix1 = "prefix1";
	private static final String prefix2 = "prefix2";
	private static final String uri1 = "uri1";
	private static final String uri2 = "uri2";
	@Test
	public void transform1()
	{
		transform(null, null, null, null, 1);
	}
	@Test
	public void transform2()
	{
		transform(null, null, null, uri2, 2);
	}
	@Test
	public void transform3()
	{
		transform(null, null, prefix2, null, 3);
	}
	@Test
	public void transform4()
	{
		transform(null, null, prefix2, uri2, 4);
	}
	@Test
	public void transform5()
	{
		transform(null, uri1, null, null, 5);
	}
	@Test
	public void transform6()
	{
		transform(null, uri1, null, uri2, 6);
	}
	@Test
	public void transform7()
	{
		transform(null, uri1, prefix2, null, 7);
	}
	@Test
	public void transform8()
	{
		transform(null, uri1, prefix2, uri2, 8);
	}
	@Test
	public void transform9()
	{
		transform(prefix1, uri1, null, null, 9);
	}
	@Test
	public void transform10()
	{
		transform(prefix1, uri1, null, uri2, 10);
	}
	@Test
	public void transform11()
	{
		transform(prefix1, uri1, prefix2, null, 11);
	}

	@Test
	public void transform12()
	{
		transform(prefix1, uri1, prefix2, uri2, 12);
	}

	@Test
	public void transform13()
	{
		transform(prefix1, uri1, null, uri1, 13);
	}

	@Test
	public void transform14()
	{
		transform(prefix1, uri1, prefix1, null, 14);
	}

	@Test
	public void transform15()
	{
		transform(prefix1, uri1, prefix1, uri1, 15);
	}

	private void transform(String rootPrefix, String rootUri, String prefix, String uri, int index)
	{
		CharArrayWriter buffer = new CharArrayWriter();
		XmlWriter writer = Utility.getWriter(buffer);

		XmlAttribute input = new XmlAttribute();
		input.setName("SomeName");
		input.setNamespaceUri(uri);
		input.setPrefix(prefix);
		XmlAttributeProcessor processor = new XmlAttributeProcessor(Utility.getModel(), input);

		TransformContext context = new TransformContext();

		writer.writeStartDocument("utf-8", "1.0");
		writer.writeStartElement(rootPrefix, "body", rootUri);
		processor.transform(writer, context);
		writer.writeEndElement();

		Document expected = Utility.getXml(getClass(), "output" + index);
		Document actual = DocumentReader.readFromWriter(buffer);
		XmlAssert.assertEquals(expected, actual);
	}
}


text:
[![Build Status](https://travis-ci.org/johnnymast/redbox-twitch.svg?branch=master)](https://travis-ci.org/johnnymast/redbox-twitch)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/johnnymast/redbox-twitch/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/johnnymast/redbox-twitch/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/johnnymast/redbox-twitch/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/johnnymast/redbox-twitch/?branch=master)
[![Twitter URL](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Contact author)](https://twitter.com/intent/tweet?text=@mastjohnny)

# redbox-twitch is not ready!
...

## Howto use it
Look in the examples folder for basic examples of how to use the code.

## Installation

Using [composer](https://packagist.org/packages/redbox/twitch):

```bash
$ composer require redbox/twitch
```
## Requirements

The following versions of PHP are supported by this version.

+ PHP 5.4
+ PHP 5.5
+ PHP 5.6
+ HHVM

## Unit Testing

..

## Author

This package is created and maintained by [Johnny Mast](https://github.com/johnnymast).

## License

Cli is released under the MIT public license.

<https://github.com/johnnymast/redbox-twitch/blob/master/LICENSE.md>


text:
@interface PeerCell ()
@property(weak, nonatomic) IBOutlet UILabel *lbAddress;
@property(weak, nonatomic) IBOutlet UILabel *lbBlocks;
@property(weak, nonatomic) IBOutlet UILabel *lbVersion;
@property(weak, nonatomic) IBOutlet UILabel *lbProtocol;
@property(weak, nonatomic) IBOutlet UILabel *lbPing;

@end

@implementation PeerCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setPeer:(BTPeer *)peer {
    self.lbAddress.text = peer.host;

    if (peer.status == BTPeerStatusConnected) {
        if (peer.userAgent.length > 20) {
            self.lbVersion.text = [NSString stringWithFormat:@"%@...", [peer.userAgent substringToIndex:20]];
        } else {
            self.lbVersion.text = peer.userAgent;
        }
        self.lbVersion.text = peer.userAgent;
        self.lbProtocol.text = [NSString stringWithFormat:@"protocol: %d", (int) peer.version];
        self.lbBlocks.text = [NSString stringWithFormat:@"%d blocks", (int) peer.displayLastBlock];
        self.lbPing.text = [NSString stringWithFormat:@"⇆ %ld ms", (long) (peer.pingTime * 1000)];

    } else {
        self.lbVersion.text = @"----";
        self.lbProtocol.text = [NSString stringWithFormat:@"protocol: %@", @"--"];
        self.lbBlocks.text = [NSString stringWithFormat:@"%@ blocks", @"--"];
        self.lbPing.text = [NSString stringWithFormat:@"%@ ms", @"--"];

    }

}

@end


text:
import sys
import os
path = os.path.realpath(__file__)
sys.path.insert(0, path[0: path.rfind('ixnetwork')])

from ixnetwork.samples.Config import Config
from ixnetwork.IxnHttp import IxnHttp
from ixnetwork.IxnConfigManagement import IxnConfigManagement
import json

# get an IxnHttp instance using the samples Config object
ixnhttp = Config.get_IxnHttp_instance()
ixnhttp.trace = True

# create management objects
config_mgmt = IxnConfigManagement(ixnhttp)

# clear the configuration
config_mgmt.new_config()

# export the configuration
ixnhttp.post('/vport', [{'name': 'abc-%d' % i} for i in range(10)])
json_config = config_mgmt.export_config(include_defaults=False)

# import the whole config
for timing in config_mgmt.import_config(json_config).result:
    print(timing)

# modify part of the configuration
json_config['globals']['preferences']['rebootPortsOnConnect'] = True

# configure using the modified configuration fragment
config_mgmt.configure(json_config['globals']['preferences'])

# configure using a fragment
# if there are not 4 vports then they will be created
config_mgmt.configure({'xpath': '/vport[4]'})

# configure the first vport
config_mgmt.configure({'xpath': '/vport[1]', 'name': 'My Virtual Port', 'type': 'ethernetvm'})

# configure the first traffic item
config_mgmt.configure({'xpath': '/traffic/trafficItem[1]', 'name': 'My Traffic Item'})

# configure a multivalue as a singlevalue
fragment = {
    "xpath": "/multivalue[source = '/globals/topology/ospfv3Router/startRate interval']/singleValue",
    "value": "22"
}
config_mgmt.configure(fragment)