text:
<link href="__STATIC__/datetimepicker/css/datetimepicker.css" rel="stylesheet" type="text/css">
<php>if(C('COLOR_STYLE')=='blue_color') echo '<link href="__STATIC__/datetimepicker/css/datetimepicker_blue.css" rel="stylesheet" type="text/css">';</php>
<link href="__STATIC__/datetimepicker/css/dropdown.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="__STATIC__/datetimepicker/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="__STATIC__/datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
<script type="text/javascript">
$(function(){
  //搜索功能
  $("#search").click(function(){
    var url = $(this).attr('url');
    var segment = $("#sch-sort-txt").attr("data");
        var query  = $('.search-form').find('input').serialize();
        query = query.replace(/(&|^)(\w*?\d*?\-*?_*?)*?=?((?=&)|(?=$))/g,'');
        query = query.replace(/^&/g,'');
    if(segment != ''){
      if(query != ''){
        query += '&segment=' + segment;
        }else{
        query += 'segment=' + segment;
        }
        }
        if( url.indexOf('?')>0 ){
            url += '&' + query;
        }else{
            url += '?' + query;
        }
    window.location.href = url;
  });

  /* 状态搜索子菜单 */
  $(".search-form").find(".drop-down").hover(function(){
    $("#sub-sch-menu").removeClass("hidden");
  },function(){
    $("#sub-sch-menu").addClass("hidden");
  });
  $("#sub-sch-menu li").find("a").each(function(){
    $(this).click(function(){
      var text = $(this).text();
      $("#sch-sort-txt").text(text).attr("data",$(this).attr("value"));
      $("#sub-sch-menu").addClass("hidden");
    })
  });

  //点击排序
  $('.list_sort').click(function(){
    var url = $(this).attr('url');
    var ids = $('.ids:checked');
    var param = '';
    if(ids.length > 0){
      var str = new Array();
      ids.each(function(){
        str.push($(this).val());
      });
      param = str.join(',');
    }

    if(url != undefined && url != ''){
      window.location.href = url + '/ids/' + param;
    }
  });

    //回车自动提交
    $('.search-form').find('input').keyup(function(event){
        if(event.keyCode===13){
            $("#search").click();
        }
    });

    $('#time-start').datetimepicker({
        format: 'yyyy-mm-dd',
        language:"zh-CN",
      minView:2,
      autoclose:true
    });

    $('#time-end').datetimepicker({
        format: 'yyyy-mm-dd',
        language:"zh-CN",
      minView:2,
      autoclose:true
    });

	$('#submit').click(function(){
	  $('#form').submit();
	});

	$(function(){
	    $('.time').datetimepicker({
	        format: 'yyyy-mm-dd',
	        language:"zh-CN",
	        minView:2,
	        autoclose:true
	    });
	    showTab();

	});

	/**
	 *查看内容快捷挂件
	 */
	$("a#list_category").click(function(){
	  $.get("{:U('Admin/Wechat/contentGuide',array('segment'=>'category'))}",function(data,status){
		$("#dialog").show();
		$("div#content_guide").empty().html(data);
	  });
	});

	$("a#list_articles").click(function(){
	  $.get("{:U('Admin/Wechat/contentGuide',array('segment'=>'article'))}",function(data,status){
		$("#dialog").show();
		$("div#content_guide").empty().html(data);
	  });
	});

	$("a#list_text").click(function(){
	  $.get("{:U('Admin/Wechat/contentGuide',array('segment'=>'text'))}",function(data,status){
		$("#dialog").show();
		$("div#content_guide").empty().html(data);
	  });
	});

 })

 	//关闭灰色 jQuery 遮罩
	function closeBg() {
	$("#dialog").hide();
	}

</script>


text:
#include <paddle/framework/op_registry.h>

#include <vector>

namespace paddle {
namespace framework {

std::unique_ptr<OperatorBase> OpRegistry::CreateOp(
    const std::string& type, const VariableNameMap& inputs,
    const VariableNameMap& outputs, AttributeMap attrs) {
  auto& info = OpInfoMap::Instance().Get(type);
  if (info.Checker() != nullptr) {
    info.Checker()->Check(attrs);
  }
  auto op = info.Creator()(type, inputs, outputs, attrs);
  return std::unique_ptr<OperatorBase>(op);
}

static VariableNameMap ConvertOpDescVarsToVarNameMap(
    const google::protobuf::RepeatedPtrField<OpDesc::Var>& op_desc_vars) {
  VariableNameMap ret_val;
  for (auto& var : op_desc_vars) {
    auto& var_names = ret_val[var.parameter()];
    auto& var_names_in_proto = var.arguments();
    var_names.reserve(static_cast<size_t>(var_names_in_proto.size()));
    std::copy(var_names_in_proto.begin(), var_names_in_proto.end(),
              std::back_inserter(var_names));
  }
  return ret_val;
}

std::unique_ptr<OperatorBase> OpRegistry::CreateOp(const OpDesc& op_desc) {
  VLOG(1) << "CreateOp directly from OpDesc is deprecated. It should only be"
             "used in unit tests. Use CreateOp(const OpDescBind& op_desc) "
             "instead.";
  VariableNameMap inputs = ConvertOpDescVarsToVarNameMap(op_desc.inputs());
  VariableNameMap outputs = ConvertOpDescVarsToVarNameMap(op_desc.outputs());
  AttributeMap attrs;
  for (auto& attr : op_desc.attrs()) {
    attrs[attr.name()] = GetAttrValue(attr);
  }

  return CreateOp(op_desc.type(), inputs, outputs, attrs);
}

std::unique_ptr<OperatorBase> OpRegistry::CreateOp(const OpDescBind& op_desc) {
  return CreateOp(op_desc.Type(), op_desc.Inputs(), op_desc.Outputs(),
                  op_desc.GetAttrMap());
}

}  // namespace framework
}  // namespace paddle

redpajama_set_name: RedPajamaGithub


text:
"""add table for mt940 parsing errors

Revision ID: 8ff6f90b98fa
Revises: 08fa5b3cc555
Create Date: 2018-12-20 18:34:05.289624

"""
from alembic import op
import sqlalchemy as sa
import pycroft
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '8ff6f90b98fa'
down_revision = '08fa5b3cc555'
branch_labels = None
depends_on = None

def upgrade():
    op.create_table('mt940_error',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('mt940', sa.Text(), nullable=False),
    sa.Column('exception', sa.Text(), nullable=False),
    sa.Column('author_id', sa.Integer(), nullable=False),
    sa.Column('imported_at', pycroft.model.types.DateTimeTz(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
    sa.Column('bank_account_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['author_id'], ['user.id'], ),
    sa.ForeignKeyConstraint(['bank_account_id'], ['bank_account.id'], ),
    sa.PrimaryKeyConstraint('id')
    )

def downgrade():
    op.drop_table('mt940_error')


text:
const webpack = require("webpack");
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const widgetConfig = {
    entry: "./src/components/SwitchContainer.ts",
    output: {
        path: path.resolve(__dirname, "dist/tmp"),
        filename: "src/com/mendix/widget/custom/switch/Switch.js",
        libraryTarget: "umd"
    },
    resolve: {
        extensions: [ ".ts", ".js", ".json" ]
    },
    module: {
        rules: [
            { test: /\.ts$/, use: "ts-loader" },
            {
                test: /\.css$/, loader: ExtractTextPlugin.extract({
                fallback: "style-loader",
                use: "css-loader"
            })
            },
            {
                test: /\.scss$/, loader: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader!sass-loader"
                }
            )
            }
        ]
    },
    devtool: "source-map",
    externals: [ "react", "react-dom" ],
    plugins: [
        new CopyWebpackPlugin(
            [
                { from: "src/**/*.xml" }
            ],
            { copyUnmodified: true }
        ),
        new ExtractTextPlugin({ filename: "./src/com/mendix/widget/custom/switch/ui/Switch.css" }),
        new webpack.LoaderOptionsPlugin({ debug: true })
    ]
};

const previewConfig = {
    entry: "./src/Switch.webmodeler.ts",
    output: {
        path: path.resolve(__dirname, "dist/tmp"),
        filename: "src/Switch.webmodeler.js",
        libraryTarget: "commonjs"
    },
    resolve: {
        extensions: [ ".ts", ".js" ]
    },
    module: {
        rules: [
            { test: /\.ts$/, use: "ts-loader" },
            { test: /\.css$/, use: "raw-loader" },
            { test: /\.scss$/, use: [
                { loader: "raw-loader" },
                { loader: "sass-loader" }
            ] }
        ]
    },
    devtool: "inline-source-map",
    externals: [ "react", "react-dom" ],
    plugins: [
        new webpack.LoaderOptionsPlugin({ debug: true })
    ]
};

module.exports = [ widgetConfig, previewConfig ];


text:
comments: true
date: 2011-04-18 11:57:00+00:00
layout: post
title: Ha Long Bay
wordpress_id: 802
image: https://c3.staticflickr.com/2/1640/26647295986_1a33dc3ab7_q.jpg
locations:
  - Vietnam
  - Ha-Long-Bay
redirect_from:
  - /vietnam/ha-long-bay/vietnam-2011/ha-long-bay/
---

The next morning we had a fairly early start. We had to sort out an overnight bag for staying on a
boat in the bay, have breakfast and checkout by 7am. A tall order on most days, but especially
considering the amount of sleep we had all had in the last 2 days. However, by 07:05 we were getting
on the bus for another seemingly long journey south to Ha Long Bay. Hai spent about 45 minutes
giving us an endless stream of information about Hanoi and Ha Long Bay, what the plan was for the
next 24 hours and what we should expect. Unfortunately, by that time, he had lost half of his
audience to sleep so he gave in. We stopped at an interesting lacquer ware place on route but it was
only a loo stop so we weren't there long. We arrived at the boat station at about 12 and jumped on a
transport boat to reach our accommodation for the next night.

{% flickr_image 26400444900 alignright %}

It was a lovely private boat for our group with twin and double sleeping rooms for everyone and a
sunbathing deck up top too. We checked into our rooms while lunch was prepared and then met up for a
selection of Ha Long Bay specialities for lunch. A much more seafood based meal this time, which
suited us, but not everyone likes seafood as much as we do. Unfortunately the spectacular views we
had been anticipated were nicely hidden behind the mists of the bay, but this gave a mystical look
to what we could see.

We cruised through the mist for a while before pulling into a small cove with a boat house and cave
behind. This was to be our first stop of the boat trip. The caves were just that, caves, but the
views out over the bay were stunning and absolutely worth the effort of walking up the
hillside/steps. After a quick look around the caves we jumped back on the boat for a trip to a pearl
farm.

{% flickr_photoset 72157667579889356 %}

The mist was clearing gradually as we approached the pearl farm so we were able to see more and more
of the bay. It was everything we had expected it to be apart from the blue skies, or lack thereof.
On arrival at the pearl farm, we were given double kayaks to explore the bay ourselves. This was
brilliant. Once we got used to being in the same kayak we were sorted and paddled around the whole
area for ages before heading back to the boat for a swim, well, I swam and Rosie watched. The water
was a bit murky, but quite pleasant to swim in, although I definitely felt the need for a shower
once I was back on board!

{% flickr_image 26581110302 aligncentre %}

As the dark began to settle over the bay, we had our evening meal and cruised into the only spot in
the area where we were allowed to drop anchor for the night, so we were soon surrounded by boats
like ours. Quite a comforting feeling really. After a few hours chatting and getting to know the
other people on the trip, we all turned in.

{% flickr_photoset 72157667579889336 %}


text:
int main(int argc, char *argv[])
{
   using namespace boost::interprocess;

   //Define file names
   //<-
   #if 1
   std::string file_name(boost::interprocess::ipcdetail::get_temporary_path());
   file_name += "/"; file_name += test::get_process_id_name();
   const char *FileName = file_name.c_str();
   #else
   //->
   const char *FileName  = "file.bin";
   //<-
   #endif
   //->
   const std::size_t FileSize = 10000;

   if(argc == 1){ //Parent process executes this
      {  //Create a file
         file_mapping::remove(FileName);
         std::filebuf fbuf;
         fbuf.open(FileName, std::ios_base::in | std::ios_base::out
                              | std::ios_base::trunc | std::ios_base::binary);
         //Set the size
         fbuf.pubseekoff(FileSize-1, std::ios_base::beg);
         fbuf.sputc(0);
      }

      //Remove on exit
      struct file_remove
      {
         file_remove(const char *FileName)
            : FileName_(FileName) {}
         ~file_remove(){ file_mapping::remove(FileName_); }
         const char *FileName_;
      } remover(FileName);

      //Create a file mapping
      file_mapping m_file(FileName, read_write);

      //Map the whole file with read-write permissions in this process
      mapped_region region(m_file, read_write);

      //Get the address of the mapped region
      void * addr       = region.get_address();
      std::size_t size  = region.get_size();

      //Write all the memory to 1
      std::memset(addr, 1, size);

      //Launch child process
      std::string s(argv[0]); s += " child ";
      //<-
      s += "\""; s+= FileName; s += "\"";
      //->
      if(0 != std::system(s.c_str()))
         return 1;
   }
   else{  //Child process executes this
      {  //Open the file mapping and map it as read-only
         //<-
         #if 1
         file_mapping m_file(argv[2], read_only);
         #else
         //->
         file_mapping m_file(FileName, read_only);
         //<-
         #endif
         //->

         mapped_region region(m_file, read_only);

         //Get the address of the mapped region
         void * addr       = region.get_address();
         std::size_t size  = region.get_size();

         //Check that memory was initialized to 1
         const char *mem = static_cast<char*>(addr);
         for(std::size_t i = 0; i < size; ++i)
            if(*mem++ != 1)
               return 1;   //Error checking memory
      }
      {  //Now test it reading the file
         std::filebuf fbuf;
         //<-
         #if 1
         fbuf.open(argv[2], std::ios_base::in | std::ios_base::binary);
         #else
         //->
         fbuf.open(FileName, std::ios_base::in | std::ios_base::binary);
         //<-
         #endif
         //->

         //Read it to memory
         std::vector<char> vect(FileSize, 0);
         fbuf.sgetn(&vect[0], std::streamsize(vect.size()));

         //Check that memory was initialized to 1
         const char *mem = static_cast<char*>(&vect[0]);
         for(std::size_t i = 0; i < FileSize; ++i)
            if(*mem++ != 1)
               return 1;   //Error checking memory
      }
   }

   return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>


text:
This gem adds the capability of validating email addresses to `ActiveModel`.
The gem only supports Rails 3 (has dependencies in ActiveModel and ActiveSupport 3.0)

### Installation
    # add this to your Gemfile
    gem "validate_email"

    # and then run
    rake gems:install

    # or just run
    sudo gem install validate_email

### Usage

#### With ActiveRecord
    class Pony < ActiveRecord::Base
      # standard validation
      validates :email_address, :email => true

      # with allow_nil
      validates :email_address, :email => {:allow_nil => true}

      # with allow_blank
      validates :email_address, :email => {:allow_blank => true}
    end

#### With ActiveModel
    class Unicorn
      include ActiveModel::Validations

      attr_accessor :email_address

      # with legacy syntax (the syntax above works also)
      validates_email :email_address, :allow_blank => true
    end

#### I18n

The error message will be looked up according to the standard ActiveModel::Errors scheme.
For the above Unicorn class this would be:

 * activemodel.errors.models.unicorn.attributes.email_address.email
 * activemodel.errors.models.unicorn.email
 * activemodel.errors.messages.email
 * errors.attributes.email_address.email
 * errors.messages.email

A default errors.messages.email of `is not a valid email address` is provided.
You can also pass the `:message => "my custom error"` option to your validation to define your own custom message.

## Authors

**Tanel Suurhans** (<http://twitter.com/tanelsuurhans>)
**Tarmo Lehtpuu** (<http://twitter.com/tarmolehtpuu>)

## License
Copyright 2010 by PerfectLine LLC (<http://www.perfectline.co.uk>) and is released under the MIT license.


text:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="/" path="/"/>
</paths>


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
Irontest::Application.initialize!


text:
var render = function (theme, data, meta, require) {

    data.header.config = data.config;
    data.header.hideFavouriteMenu = true;

    var searchQuery =  data.search.query;
    if(typeof(searchQuery) != typeof({})){
        searchQuery = {overview_name : searchQuery, searchTerm: 'overview_name', search : searchQuery};
    }else{
        for (var key in searchQuery) {
            if (searchQuery.hasOwnProperty(key)) {
                if(key.indexOf("overview_") !== -1){
                    searchQuery.searchTerm = key;
                    searchQuery.search = searchQuery[key];
                }
            }
        }
    }

    var categories = data.navigation.assets[data.type].categories;
    var selectedPlatform = data.selectedPlatform;
    var selectedCategory = data.selectedCategory;

    var assets = require('/helpers/page-content-all-mobile-apps.js');
    var bodyContext = assets.currentPage(data.assets, data.sso, data.user, data.pagination, data.config);
    bodyContext.searchQuery =searchQuery;
    var searchUrl = "/assets/mobileapp";

    theme('2-column-left', {
        title: data.title,
        header: [
            {
                partial: 'header',
                context: data.header
            }
        ],
        leftColumn: [
            {
                partial: 'left-column',
                context: {
                    navigation: createLeftNavLinks(data),
                    tags: data.tags,
                    recentApps: data.recentAssets,
                    assetType: data.type
                }
            }
        ],
        search: [
            {
                partial: 'search',
                context: {searchQuery: searchQuery, categories: categories, selectedPlatform: selectedPlatform,
                    selectedCategory: selectedCategory,searchUrl:searchUrl}
            }
        ],
        pageHeader: [
            {
                partial: 'page-header',
                context: {
                    title: "Mobile Apps",
                    sorting: createSortOptions(data)
                }
            }
        ],
        pageContent: [
            {
                partial: 'page-content-all-mobile-apps',
                context: bodyContext
            }
        ]
    });

};

function createSortOptions(data) {
    var url = "/assets/mobileapp?sort=";
    var sortOptions = {};
    var sortByPopularity = {url: url + "popular", title: "Sort by Popularity", class: "fw fw-star"};
    var sortByAlphabet = {url: url + "az", title: "Sort by Alphabetical Order", class: "fw fw-list-sort"};
    var sortByRecent = {url: url + "recent", title: "Sort by Recent", class: "fw fw-calendar"};

    var options = [];
    options.push(sortByAlphabet);
    options.push(sortByRecent);// recently created
    options.push(sortByPopularity);
    sortOptions["options"] = options;
    return sortOptions;
}

function createLeftNavLinks(data) {
    var enabledTypeList = data.config.enabledTypeList;
    var subscriptionOn = true;
    if (!data.config.isSelfSubscriptionEnabled && !data.config.isEnterpriseSubscriptionEnabled) {
        subscriptionOn = false;
    }
    var currentAppType = 'mobileapp';
    var leftNavigationData = [];

    if(data.user) {
        var data =  {
            active: true, partial: currentAppType, url: "/assets/" + currentAppType,
            myapps: false, myappsUrl: "/extensions/assets/" + currentAppType + "/myapps"
        }
        leftNavigationData.push(data)
    } else {
        var data =  {
            active: true, partial: currentAppType, url: "/assets/" + currentAppType
        }
        leftNavigationData.push(data)
    }

    for (var i = 0; i < enabledTypeList.length; i++) {
        if (enabledTypeList[i] != currentAppType) {
            var data;
            if (subscriptionOn) {
                data = {
                    active: false, partial: enabledTypeList[i], url: "/assets/" +
                                                                     enabledTypeList[i]
                }
            } else {
                data = {
                    active: false, partial: enabledTypeList[i], url: "/extensions/assets/" +
                                                                     enabledTypeList[i] + "/apps"
                }
            }
            leftNavigationData.push(data);
        }

    }
    return leftNavigationData;
}


text:
<?xml version="1.0" ?>
<tei>
	<teiHeader>
		<fileDesc xml:id="55001234"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>
	<docTitle>
	<titlePart>FXT1 Texture Compression Technology White Paper<lb/> By 3dfx Interactive<lb/> </titlePart>
	</docTitle>

Introduction:

		</front>
	</text>
</tei>


text:
package org.jgroups.protocols.jzookeeper.zabclient;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.Version;
import org.jgroups.View;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.util.Util;

public class ZabClient extends ReceiverAdapter {
	private String props;
	private static String ProtocotName = "Zab";
	private String channelName;
	private JChannel channel;
	private Address local_addr = null;
	final AtomicInteger actually_sent = new AtomicInteger(0);
	private final CyclicBarrier barrier;
	private AtomicLong local = new AtomicLong(0);
	private final byte[] payload;
	private final long numsMsg;
	private long num_msgsPerThreads;
	private Sender sender;
	private AtomicInteger  msgReceived;
	private List<Address> zabBox = new ArrayList<Address>();
	private List<Long> latencies = new ArrayList<Long>();
	private View view;
	private static Calendar cal = Calendar.getInstance();
	private short ID;
	private static int load = 1;
	private static int count = 0;
	//private long numSendMsg = 0;
	private static boolean is_warmUp = false;
	private long warmUpRequests = 0;
	private long currentLoad = 0;
	private int sendTime = 0;
	private ZabTestThreads zabTest = new ZabTestThreads();
	private double read_percentage = 0; // 0% reads, 100% writes
	private static Random rand = new Random();
	private static int min = 0, max = 0;
	private ConcurrentMap<Long, MessageInfo> KeysForRead;
	private AtomicInteger numReceive = new AtomicInteger(0);
	private AtomicInteger numSend = new AtomicInteger(0);

	private List<Long> readLatencies = new ArrayList<Long>();
	private List<Long> writeLatencies = new ArrayList<Long>();
	private AtomicLong numdel;

	public ZabClient(List<Address> zabbox, CyclicBarrier barrier, long numsMsg, AtomicLong local, byte[] payload,
			String ProtocotName, long num_msgsPerThreads, String propsFile, int load, long warmUpRequests, int sendTime,
			double read_percentage, AtomicInteger numReceive, String channelName, ZabTestThreads zabTest) {
		this.barrier = barrier;
		this.local = local;
		this.payload = payload;
		this.numsMsg = numsMsg;
		this.zabBox = zabbox;
		this.ProtocotName = ProtocotName;
		this.num_msgsPerThreads = num_msgsPerThreads;
		this.warmUpRequests = warmUpRequests;
		this.props = propsFile;
		this.load = load;
		this.sendTime = sendTime;
		this.min = sendTime - ((int) (sendTime * 0.25));
		this.max = sendTime + ((int) (sendTime * 0.25));
		this.read_percentage = read_percentage;
		this.zabTest = zabTest;
		this.KeysForRead = new ConcurrentHashMap<Long, MessageInfo>();
		this.msgReceived = new AtomicInteger(0);
		this.numdel = new AtomicLong(0);
		this.numReceive = numReceive;
		this.channelName = channelName;
		this.ID = ClassConfigurator.getProtocolId(Zab.class);

	}

	public void init() {
		msgReceived = new AtomicInteger(0);
		//numSendMsg = 0;
		numSend.set(0);

		latencies.clear();
	}

	public void setWarmUp(boolean warmUp) {
		is_warmUp = warmUp;
	}

	public void viewAccepted(View new_view) {
		view = new_view;
		System.out.println("** view: " + new_view);
	}

	public void start() throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("\n\n----------------------- ZABPerf -----------------------\n");
		sb.append("Date: ").append(new Date()).append('\n');
		sb.append("Run by: ").append(System.getProperty("user.name")).append("\n");
		sb.append("JGroups version: ").append(Version.description).append('\n');
		System.out.println(sb);
		channel = new JChannel(props);
		channel.setReceiver(this);
		channel.connect(channelName);
		local_addr = channel.getAddress();
	}

	public void sendMessages(long numMsgs) {
		msgReceived =  new AtomicInteger(0);
		this.currentLoad = numMsgs;
		this.sender = new Sender(this.barrier, this.local, this.payload, numMsgs, load, sendTime);
		System.out.println("Start sending " + sender.getName());
		sender.start();
	}

	public void receive(Message msg) {
		synchronized (this) {
			long arriveTime = System.nanoTime();
			ZabHeader zabHdr = (ZabHeader) msg.getHeader(ID);
			if (is_warmUp) {
				if (msgReceived.incrementAndGet() >= warmUpRequests) {
					try {
						zabTest.finishedWarmupTest();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
			if (!is_warmUp) {
				numReceive.incrementAndGet();
				System.out.println("#Deleiverd: "+numReceive.get());
				if(zabHdr.getType() == ZabHeader.RESPONSEW){
					synchronized (KeysForRead) {
						KeysForRead.put(zabHdr.getMessageInfo().getZxid(), zabHdr.getMessageInfo());
						long SendTime = zabHdr.getMessageInfo().getId().getStartTime();
						writeLatencies.add((arriveTime-SendTime));
						numdel.set(zabHdr.getMessageInfo().getZxid());
					}
				}
				else{
					if (zabHdr.getMessageInfo()!=null){
						//numReceive.incrementAndGet();
						long SendTime = zabHdr.getMessageInfo().getId().getStartTime();
						readLatencies.add((arriveTime-SendTime));
					}
				}
				if (msgReceived.incrementAndGet() >= num_msgsPerThreads)
					zabTest.finishedRealTest();
			}

		}

	}

	public int getNumReceive(){
		return numReceive.get();
	}

	public long getMaxDelivered(){
		return numdel.get();
	}

	public List<Long> getReadLatencies(){
		return readLatencies;
	}

	public List<Long> getWriteLatencies(){
		return writeLatencies;
	}

	public class Sender extends Thread {
		private final CyclicBarrier barrier;
		private AtomicLong local = new AtomicLong(0);// , actually_sent;
		private final byte[] payload;
		private long num_msgsPerThreads;
		private int load = 1;
		private int sendTime = 100;

		protected Sender(CyclicBarrier barrier, AtomicLong local, byte[] payload, long num_msgsPerThreads, int load,
				int sendTime) {
			super("" + (count++));
			this.barrier = barrier;
			this.payload = payload;
			this.local = local;
			this.num_msgsPerThreads = num_msgsPerThreads;
			this.load = load;
			this.sendTime = sendTime;

		}

		public void run() {
			System.out.println("Thread start " + getName());
			//numSendMsg = 0;
			MessageId messageId =null;
			ZabHeader hdrReq = null;
			for (int i = 0; i < num_msgsPerThreads; i++) {
				//	numSendMsg = i;
				//	if (is_warmUp) {
				while ((numSend.get() - msgReceived.get()) > load) {
					System.out.println("TName: "+ this.getName() + " "+ numSend.get() +"-" + msgReceived.get()+
							"="+(numSend.get() - msgReceived.get()));
					try {
						Thread.sleep(0, 1);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
				}
				//}
				try {
					//boolean get = Util.tossWeightedCoin(read_percentage);
					boolean get = false;
					if (!is_warmUp){
						if (get && !KeysForRead.isEmpty()){
							//	System.out.println("Sending read ");
							List<MessageInfo> MessageInfoList = new ArrayList<MessageInfo>(KeysForRead.values());
							int randomIndex = new Random().nextInt(MessageInfoList.size());
							messageId = new MessageId(local_addr, local.getAndIncrement(), System.nanoTime());
							MessageInfo messageInfoRead = MessageInfoList.get(randomIndex);
							messageInfoRead.setId(messageId);
							hdrReq = new ZabHeader(ZabHeader.REQUESTR, messageInfoRead);
						}
						else{
							messageId = new MessageId(local_addr, local.getAndIncrement(), System.nanoTime());
							MessageInfo messageInfo = new MessageInfo(messageId);
							hdrReq = new ZabHeader(ZabHeader.REQUESTW, messageInfo);
						}
					}
					else{
						messageId = new MessageId(local_addr, local.getAndIncrement());
						MessageInfo messageInfo = new MessageInfo(messageId);
						hdrReq = new ZabHeader(ZabHeader.REQUESTW, messageInfo);
					}
					Message msg = new Message(null);
					msg.putHeader(ID, hdrReq);
					// System.out.println("sender " + this.getName()+ " Sending
					// " + i + " out of " + num_msgsPerThreads);
					channel.send(msg);
					System.out.println("TName: "+ this.getName()+ " #R: "+msgReceived.get());
					System.out.println("TName: "+ this.getName()+ " #S: "+numSend.get());
					numSend.incrementAndGet();
					//					if (!is_warmUp) {
					//						sendTime = min + rand.nextInt((max - min) + 1);
					//						Thread.sleep(sendTime);
					//					}

				} catch (Exception e) {
				}
			}
		}
	}

}


text:
    Ansible Related Posts

    {% for post in site.posts %}
    {% if post.tags contains 'ansible' %}

      {{ post.title }}

      {{ post.excerpt }}

Continue Reading →

    {% endif %}
  {% endfor %}


text:
export * from "./table-row";
export * from "./table-row-properties";
export * from "./table-row-height";


text:
Hello, <?php echo $username; ?>

                     Online

            <form action="#" method="get" class="sidebar-form">

                    <input type="text" name="q" class="form-control" placeholder="Search..."/>

	    	            <button type='submit' name='seach' id='search-btn' class="btn btn-flat"></button>

            </form>

            <?php $this->load->view($menu);?>


text:
/**
 * Implementations of serializer and derserializer interfaces.
 */
package org.apache.reef.wake.avro.impl;


text:
package org.ovirt.engine.core.common.utils;

import java.io.Serializable;
import java.util.Objects;

public class Pair<T, K> implements Serializable {
    private static final long serialVersionUID = -6761191157220811690L;

    private T first;
    private K second;

    public Pair() {
    }

    public Pair(T first, K second) {
        this.first = first;
        this.second = second;
    }

    public Pair(Pair<T, K> original) {
        this.first = original.getFirst();
        this.second = original.getSecond();
    }

    public void setFirst(T value) {
        this.first = value;
    }

    public T getFirst() {
        return this.first;
    }

    public void setSecond(K value) {
        this.second = value;
    }

    public K getSecond() {
        return this.second;
    }

    @Override
    public String toString() {
        return "<" + first + ", " + second + '>';
    }

    @Override
    public int hashCode() {
        return Objects.hash(
                first,
                second
        );
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Pair)) {
            return false;
        }
        Pair<?, ?> other = (Pair<?, ?>) obj;
        return Objects.equals(first, other.first)
                && Objects.equals(second, other.second);
    }
}


text:
namespace task_management {

namespace {

// Gets the profile name associated with the browser context of the given
// |render_process_host| from the profile info cache.
base::string16 GetRendererProfileName(
    const content::RenderProcessHost* render_process_host) {
  Profile* profile =
      Profile::FromBrowserContext(render_process_host->GetBrowserContext());
  DCHECK(profile);
  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index =
      cache.GetIndexOfProfileWithPath(profile->GetOriginalProfile()->GetPath());
  if (index != std::string::npos)
    return cache.GetNameOfProfileAtIndex(index);

  return base::string16();
}

}  // namespace

RendererTask::RendererTask(const base::string16& title,
                           const gfx::ImageSkia* icon,
                           content::WebContents* web_contents)
    : Task(title, icon, web_contents->GetRenderProcessHost()->GetHandle()),
      web_contents_(web_contents),
      render_process_host_(web_contents->GetRenderProcessHost()),
      render_process_id_(render_process_host_->GetID()),
      v8_memory_allocated_(0),
      v8_memory_used_(0),
      webcache_stats_(),
      profile_name_(GetRendererProfileName(render_process_host_)) {
}

RendererTask::~RendererTask() {
}

void RendererTask::Activate() {
  if (!web_contents_->GetDelegate())
    return;

  web_contents_->GetDelegate()->ActivateContents(web_contents_);
}

void RendererTask::Refresh(const base::TimeDelta& update_interval) {
  Task::Refresh(update_interval);

  // TODO(afakhry):
  // 1- Add code to disable this refresh if it was never requested by clients of
  //    the task manager.
  // 2- Figure out a way to refresh V8 and WebCache stats cleanly either by
  //    working with amistry, or by implementing something myself.
}

Task::Type RendererTask::GetType() const {
  return Task::RENDERER;
}

int RendererTask::GetChildProcessUniqueID() const {
  return render_process_id_;
}

base::string16 RendererTask::GetProfileName() const {
  return profile_name_;
}

int64 RendererTask::GetV8MemoryAllocated() const {
  return v8_memory_allocated_;
}

int64 RendererTask::GetV8MemoryUsed() const {
  return v8_memory_used_;
}

bool RendererTask::ReportsWebCacheStats() const {
  return true;
}

blink::WebCache::ResourceTypeStats RendererTask::GetWebCacheStats() const {
  return webcache_stats_;
}

// static
base::string16 RendererTask::GetTitleFromWebContents(
    content::WebContents* web_contents) {
  DCHECK(web_contents);
  base::string16 title = web_contents->GetTitle();
  if (title.empty()) {
    GURL url = web_contents->GetURL();
    title = base::UTF8ToUTF16(url.spec());
    // Force URL to be LTR.
    title = base::i18n::GetDisplayStringInLTRDirectionality(title);
  } else {
    // Since the title could later be concatenated with
    // IDS_TASK_MANAGER_TAB_PREFIX (for example), we need to explicitly set the
    // title to be LTR format if there is no strong RTL charater in it.
    // Otherwise, if IDS_TASK_MANAGER_TAB_PREFIX is an RTL word, the
    // concatenated result might be wrong. For example, http://mail.yahoo.com,
    // whose title is "Yahoo! Mail: The best web-based Email!", without setting
    // it explicitly as LTR format, the concatenated result will be "!Yahoo!
    // Mail: The best web-based Email :BAT", in which the capital letters "BAT"
    // stands for the Hebrew word for "tab".
    base::i18n::AdjustStringForLocaleDirection(&title);
  }
  return title;
}

// static
const gfx::ImageSkia* RendererTask::GetFaviconFromWebContents(
    content::WebContents* web_contents) {
  DCHECK(web_contents);

  // Tag the web_contents with a |ContentFaviconDriver| (if needed) so that
  // we can use it to retrieve the favicon if there is one.
  favicon::CreateContentFaviconDriverForWebContents(web_contents);
  gfx::Image image =
      favicon::ContentFaviconDriver::FromWebContents(web_contents)->
          GetFavicon();
  if (image.IsEmpty())
    return nullptr;

  return image.ToImageSkia();
}

// static
const base::string16 RendererTask::PrefixRendererTitle(
    const base::string16& title,
    bool is_app,
    bool is_extension,
    bool is_incognito) {
  int message_id = IDS_TASK_MANAGER_TAB_PREFIX;

  if (is_incognito && !is_app && !is_extension) {
    message_id = IDS_TASK_MANAGER_TAB_INCOGNITO_PREFIX;
  } else if (is_app) {
    if (is_incognito)
      message_id = IDS_TASK_MANAGER_APP_INCOGNITO_PREFIX;
    else
      message_id = IDS_TASK_MANAGER_APP_PREFIX;
  } else if (is_extension) {
    if (is_incognito)
      message_id = IDS_TASK_MANAGER_EXTENSION_INCOGNITO_PREFIX;
    else
      message_id = IDS_TASK_MANAGER_EXTENSION_PREFIX;
  }

  return l10n_util::GetStringFUTF16(message_id, title);
}

}  // namespace task_management


text:
require 'rails_helper'
include ActionDispatch::TestProcess

RSpec.describe TimePredictor do
  before do
    FactoryGirl.reload
  end

  let(:distance_factor) { SegmentTimeCalculator::DISTANCE_FACTOR }
  let(:vert_gain_factor) { SegmentTimeCalculator::VERT_GAIN_FACTOR }
  let(:test_event) { FactoryGirl.build_stubbed(:event_functional, laps_required: 3, splits_count: 4, efforts_count: 1) }
  let(:test_effort) { test_event.efforts.first }
  let(:test_split_times) { test_effort.split_times }
  let(:start) { test_event.splits.first }
  let(:aid_1) { test_event.splits.second }
  let(:aid_2) { test_event.splits.third }
  let(:finish) { test_event.splits.last }
  let(:lap_1_zero_start) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: start, begin_in_out: 'in',
                                             end_lap: 1, end_split: start, end_in_out: 'in') }
  let(:aid_1_in_to_aid_1_in) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: aid_1, begin_in_out: 'in',
                                                 end_lap: 1, end_split: aid_1, end_in_out: 'in') }
  let(:lap_1_in_aid_2) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: aid_2, begin_in_out: 'in',
                                           end_lap: 1, end_split: aid_2, end_in_out: 'out') }
  let(:lap_1_start_to_lap_1_aid_1) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: start, begin_in_out: 'in',
                                                       end_lap: 1, end_split: aid_1, end_in_out: 'in') }
  let(:lap_1_start_to_lap_1_finish) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: start, begin_in_out: 'in',
                                                        end_lap: 1, end_split: finish, end_in_out: 'in') }
  let(:lap_1_aid_1_to_lap_1_aid_2_inclusive) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: aid_1, begin_in_out: 'in',
                                                                 end_lap: 1, end_split: aid_2, end_in_out: 'out') }
  let(:lap_1_aid_2_to_lap_1_finish) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: aid_2, begin_in_out: 'out',
                                                        end_lap: 1, end_split: finish, end_in_out: 'in') }
  let(:lap_1_aid_1_to_lap_1_finish) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: aid_1, begin_in_out: 'out',
                                                        end_lap: 1, end_split: finish, end_in_out: 'in') }
  let(:lap_1_start_to_lap_2_aid_1) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: start, begin_in_out: 'in',
                                                       end_lap: 2, end_split: aid_1, end_in_out: 'in') }
  let(:lap_1_start_to_lap_3_finish) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: start, begin_in_out: 'in',
                                                        end_lap: 3, end_split: finish, end_in_out: 'in') }
  let(:lap_1_start_to_completed) { FactoryGirl.build(:segment, begin_lap: 1, begin_split: start, begin_in_out: 'in',
                                                     end_lap: completed_split_time.lap, end_split: completed_split_time.split,
                                                     end_in_out: SubSplit.kind(completed_split_time.bitkey)) }

  describe '#initialize' do
    it 'initializes with a segment, lap_splits, and completed_split_time in an args hash' do
      segment = FactoryGirl.build(:segment)
      lap_splits, _ = lap_splits_and_time_points(test_event)
      completed_split_time = test_split_times.last
      expect { TimePredictor.new(segment: segment,
                                 lap_splits: lap_splits,
                                 completed_split_time: completed_split_time) }
          .not_to raise_error
    end

    it 'raises an ArgumentError if no segment is given' do
      lap_splits, _ = lap_splits_and_time_points(test_event)
      completed_split_time = test_split_times.last
      expect { TimePredictor.new(lap_splits: lap_splits,
                                 completed_split_time: completed_split_time) }
          .to raise_error(/must include segment/)
    end

    it 'raises an ArgumentError if no effort or lap_splits are given' do
      segment = FactoryGirl.build(:segment)
      completed_split_time = test_split_times.last
      expect { TimePredictor.new(segment: segment,
                                 completed_split_time: completed_split_time) }
          .to raise_error(/must include one of effort or lap_splits and completed_split_time/)
    end

    it 'raises an ArgumentError if no effort or completed_split_time are given' do
      segment = FactoryGirl.build(:segment)
      lap_splits, _ = lap_splits_and_time_points(test_event)
      expect { TimePredictor.new(segment: segment, lap_splits: lap_splits) }
          .to raise_error(/must include one of effort or lap_splits and completed_split_time/)
    end
  end

  describe '#segment_time' do
    context 'for a partially completed effort' do
      let(:completed_split_time) { test_split_times.first(5).last }

      it 'predicts zero time for a zero start segment' do
        segment = lap_1_zero_start
        expected = 0
        verify_segment_time(segment, expected)
      end

      it 'predicts zero time for a zero intermediate segment' do
        segment = aid_1_in_to_aid_1_in
        expected = 0
        verify_segment_time(segment, expected)
      end

      it 'predicts zero time for a a segment in aid' do
        segment = lap_1_in_aid_2
        expected = 0
        verify_segment_time(segment, expected)
      end

      it 'predicts the actual segment time for the segment beginning with start and ending with the completed split time' do
        segment = lap_1_start_to_completed
        expected = completed_split_time.time_from_start
        verify_segment_time(segment, expected)
      end

      it 'predicts the correct segment time for a segment beginning with start and ending before the completed split time' do
        segment = lap_1_start_to_lap_1_aid_1
        expected = 6300
        verify_segment_time(segment, expected)
      end

      it 'predicts the correct segment time for a segment beginning with start and ending after the completed split time' do
        segment = lap_1_start_to_lap_1_finish
        expected = 18900
        verify_segment_time(segment, expected)
      end

      it 'functions properly for segments starting before the completed split time and ending at the completed split time' do
        segment = lap_1_aid_1_to_lap_1_aid_2_inclusive
        expected = 6300
        verify_segment_time(segment, expected)
      end

      it 'functions properly for segments starting at the completed split time and ending after the completed split time' do
        segment = lap_1_aid_2_to_lap_1_finish
        expected = 6300
        verify_segment_time(segment, expected)
      end

      it 'functions properly for segments starting before the completed split time and ending after the completed split time' do
        segment = lap_1_aid_1_to_lap_1_finish
        expected = 12600
        verify_segment_time(segment, expected)
      end

      it 'functions properly for segments starting on one lap and ending on another' do
        segment = lap_1_start_to_lap_2_aid_1
        expected = 25200
        verify_segment_time(segment, expected)
      end

      it 'functions properly for segments containing multiple finished laps' do
        segment = lap_1_start_to_lap_3_finish
        expected = 56700
        verify_segment_time(segment, expected)
      end
    end

    context 'for an unstarted effort' do
      let(:completed_split_time) { test_split_times.first }

      it 'predicts zero time for a zero segment' do
        segment = lap_1_zero_start
        expected = 0
        verify_segment_time(segment, expected)
      end
    end

    def verify_segment_time(segment, expected)
      course = test_event.course
      allow(course).to receive(:distance).and_return(finish.distance_from_start)
      allow(course).to receive(:vert_gain).and_return(finish.vert_gain_from_start)
      allow(course).to receive(:vert_loss).and_return(finish.vert_loss_from_start)
      lap_splits, _ = lap_splits_and_time_points(test_event)
      [segment.end_lap_split, segment.begin_lap_split]
          .each { |lap_split| allow(lap_split).to receive(:course).and_return(course) }
      margin = expected * 0.01
      predictor = TimePredictor.new(segment: segment,
                                    effort: test_effort,
                                    lap_splits: lap_splits,
                                    completed_split_time: completed_split_time,
                                    calc_model: :terrain)
      expect(predictor.segment_time).to be_within(margin).of(expected)
    end
  end

  describe '#data_status' do
    let(:completed_split_time) { test_split_times.first(5).last }
    let(:completed_segment) { lap_1_start_to_completed }
    let(:limit_factors) { DataStatus::LIMIT_FACTORS }
    let(:typical_time_in_aid) { DataStatus::TYPICAL_TIME_IN_AID }

    it 'for a zero segment, sends to DataStatus a limits hash containing all zeros' do
      segment = lap_1_zero_start
      expected = {low_bad: 0, low_questionable: 0, high_questionable: 0, high_bad: 0}
      verify_data_status(segment, expected)
    end

    it 'for an in_aid segment, sends to DataStatus a limits hash containing zeros for low limits and pace-adjusted times for high limits' do
      imputed_pace = imputed_pace(completed_segment)
      segment = lap_1_in_aid_2
      typical_time = typical_time_in_aid
      expected = [:low_bad, :low_questionable, :high_questionable, :high_bad]
                     .map { |limit| [limit, (typical_time * limit_factors[:in_aid][limit] * imputed_pace).to_i] }
                     .to_h
      verify_data_status(segment, expected)
    end

    it 'for an inter-split segment, sends to DataStatus a limits hash containing pace-adjusted times for all limits' do
      imputed_pace = imputed_pace(completed_segment)
      segment = lap_1_start_to_lap_1_finish
      typical_time = segment.distance * distance_factor + segment.vert_gain * vert_gain_factor
      expected = [:low_bad, :low_questionable, :high_questionable, :high_bad]
                     .map { |limit| [limit, (typical_time * limit_factors[:terrain][limit] * imputed_pace).to_i] }
                     .to_h
      verify_data_status(segment, expected)
    end

    it 'for a segment covering multiple laps, sends to DataStatus a limits hash containing pace-adjusted times for all limits' do
      imputed_pace = imputed_pace(completed_segment)
      segment = lap_1_start_to_lap_3_finish
      typical_time = segment.distance * distance_factor + segment.vert_gain * vert_gain_factor
      expected = [:low_bad, :low_questionable, :high_questionable, :high_bad]
                     .map { |limit| [limit, (typical_time * limit_factors[:terrain][limit] * imputed_pace).to_i] }
                     .to_h
      verify_data_status(segment, expected)
    end

    def verify_data_status(segment, expected)
      course = test_event.course
      allow(course).to receive(:distance).and_return(finish.distance_from_start)
      allow(course).to receive(:vert_gain).and_return(finish.vert_gain_from_start)
      allow(course).to receive(:vert_loss).and_return(finish.vert_loss_from_start)
      lap_splits, _ = lap_splits_and_time_points(test_event)
      [segment.end_lap_split, segment.begin_lap_split]
          .each { |lap_split| allow(lap_split).to receive(:course).and_return(course) }
      seconds = 999
      allow(DataStatus).to receive(:determine)
      TimePredictor.new(segment: segment,
                        effort: test_effort,
                        lap_splits: lap_splits,
                        completed_split_time: completed_split_time,
                        calc_model: :terrain).data_status(seconds)
      expect(DataStatus).to have_received(:determine).with(expected, seconds)
    end

    def imputed_pace(segment)
      course = test_event.course
      allow(course).to receive(:distance).and_return(finish.distance_from_start)
      allow(course).to receive(:vert_gain).and_return(finish.vert_gain_from_start)
      allow(course).to receive(:vert_loss).and_return(finish.vert_loss_from_start)
      [segment.end_lap_split, segment.begin_lap_split]
          .each { |lap_split| allow(lap_split).to receive(:course).and_return(course) }
      completed_typical_time = completed_segment.distance * distance_factor + completed_segment.vert_gain * vert_gain_factor
      completed_split_time.time_from_start / completed_typical_time
    end
  end
end


text:
package status

// StatusGroup encapsulates constants for mapping group status
type StatusGroup int

// constants representing an enum of all possible StatusGroups
const (
	Staged StatusGroup = iota
	Unmerged
	Unstaged
	Untracked
)

// ColorGroup encapsulates constants for mapping color output categories
type ColorGroup int

const (
	rst ColorGroup = iota
	del
	mod
	neu //'new' is reserved in Go
	ren
	cpy
	typ
	unt
	dark
	branch
	header
)

var colorMap = map[ColorGroup]string{
	rst:    "\033[0m",
	del:    "\033[0;31m",
	mod:    "\033[0;32m",
	neu:    "\033[0;33m",
	ren:    "\033[0;34m",
	cpy:    "\033[0;33m",
	typ:    "\033[0;35m",
	unt:    "\033[0;36m",
	dark:   "\033[2;37m",
	branch: "\033[1m",
	header: "\033[0m",
}

// TODO: Why does scm_breeze define these without the leading escape codes?
// Let's audit our usage and see if always used in same way, if so should be
// integrated into constants here...
//
// Ah, I see, sometimes used with bold, sometimes without.  Might be worth
// extracting that logic into a helper method to improve readability of print
// functions.
var groupColorMap = map[StatusGroup]string{
	Staged:    "33m",
	Unmerged:  "31m",
	Unstaged:  "32m",
	Untracked: "36m",
}


text:
'use strict';

module.exports = function (mongo, request, collection) {
	var query = request.data;
	var param = request.param;
	var conf = mongo.getCollectionProperties(collection);
	if (conf.versionable && query._isLast === undefined)
		query._isLast = true;
	if (param) {
		if (param.lookup) {
			var agregation = {
				$match: param.query,
				$lookup: param.lookup
			};
			if (param.sort !== undefined)
				agregation.$sort = param.sort;
			if (param.skip)
				agregation.$skip = param.skip;
			if (param.limit)
				agregation.$limit = param.limit;
			if (param.project) {
				project = param.project;
				if (!project._id)
					project._id = 0;
			}
			else
				project = { _id: 0 };
			agregation.$project = param.project;
			return mongo.collection(collection).agregate(agregation);
		}
		else {
			var cursor = mongo.collection(collection).find(query);
			if (param.sort !== undefined)
				cursor = cursor.sort(param.sort);
			if (param.skip)
				cursor = cursor.skip(param.skip);
			if (param.limit)
				cursor = cursor.limit(param.limit);
			var project;
			if (param.project) {
				project = param.project;
				if (!project._id)
					project._id = 0;
			}
			else
				project = { _id: 0 };
			cursor = cursor.project(project);
			return cursor;
		}
	}
	else
		return mongo.collection(collection).find(query).project({ _id: 0 });
};


text:
package org.immutables.generator.processor;

import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import java.util.List;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import org.immutables.generator.Implicit;
import static com.google.common.base.Preconditions.checkState;

public class Implicits extends Introspection {

  private final TypeMirror implicitTypeErasure;

  Implicits(ProcessingEnvironment environment) {
    super(environment);
    this.implicitTypeErasure = types.erasure(elements.getTypeElement(Implicit.class.getName()).asType());
  }

  public ImplicitResolver resolverFrom(final Iterable<? extends TypeMirror> imports) {
    return new ImplicitResolver() {
      ListMultimap<TypeMirror, TypeMirror> mappings = buildImplicitMappingFrom(imports);

      @Override
      public List<TypeMirror> resolveFor(TypeMirror typeMirror) {
        return mappings.get(typeMirror);
      }
    };
  }

  private ImmutableListMultimap<TypeMirror, TypeMirror> buildImplicitMappingFrom(Iterable<? extends TypeMirror> imports) {
    ImmutableListMultimap.Builder<TypeMirror, TypeMirror> builder = ImmutableListMultimap.builder();

    for (TypeMirror type : imports) {
      if (types.isSubtype(checkDeclaredType(type), implicitTypeErasure)) {
        for (TypeMirror superType : types.directSupertypes(type)) {
          if (types.isSubtype(superType, implicitTypeErasure)) {
            TypeMirror targetType = getTargetTypeArgument(superType);
            builder.put(targetType, type);
          }
        }
      }
    }

    return builder.build();
  }

  private TypeMirror getTargetTypeArgument(TypeMirror facetTypeSupertype) {
    TypeMirror typeArgument = Iterables.getOnlyElement(checkDeclaredType(facetTypeSupertype).getTypeArguments());
    if (typeArgument instanceof TypeVariable) {
      return ((TypeVariable) typeArgument).getUpperBound();
    }
    return typeArgument;
  }

  public interface ImplicitResolver {
    List<TypeMirror> resolveFor(TypeMirror typeMirror);
  }

  private DeclaredType checkDeclaredType(TypeMirror type) {
    checkState(type.getKind() == TypeKind.DECLARED, "'%s' should have been a declared type", type);
    return (DeclaredType) type;
  }
}


text:
package org.ambraproject.wombat.service.remote.orcid;

import com.google.gson.Gson;
import org.ambraproject.wombat.config.site.Site;
import org.ambraproject.wombat.service.remote.CachedRemoteService;
import org.ambraproject.wombat.service.remote.ServiceRequestException;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrcidApiImpl implements OrcidApi {

  private static final Logger log = LoggerFactory.getLogger(OrcidApiImpl.class);

  @Autowired
  private CachedRemoteService<Reader> cachedRemoteReader;
  @Autowired
  private Gson gson;

  /**
   * {@inheritDoc}
   */
  @Override
  public String getOrcidIdFromAuthorizationCode(Site site, String code) throws IOException, URISyntaxException {

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("client_id", getOrcidClientId(site)));
    params.add(new BasicNameValuePair("client_secret", getOrcidClientSecret(site)));
    params.add(new BasicNameValuePair("grant_type", "authorization_code"));
    params.add(new BasicNameValuePair("code", code));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");

    URI orcidAuthUri = getOrcidAuthUri(site);

    HttpPost httpPost = new HttpPost(orcidAuthUri);
    httpPost.setEntity(entity);

    StatusLine statusLine = null;
    Map<String, Object> orcidJson = new HashMap<>();
    log.debug("ORCID API request executing: " + orcidAuthUri);
    try (CloseableHttpResponse response = cachedRemoteReader.getResponse(httpPost)) {
      statusLine = response.getStatusLine();
      String responseJson = EntityUtils.toString(response.getEntity());
      orcidJson = gson.fromJson(responseJson, HashMap.class);
    } catch (ServiceRequestException e) {
      handleOrcidException(e);
    } finally {
      httpPost.releaseConnection();
    }

    if (statusLine != null && statusLine.getStatusCode() != HttpStatus.OK.value()) {
      throw new RuntimeException("bad response from ORCID authorization API: " + statusLine);
    }

    return String.valueOf(orcidJson.get("orcid"));
  }

  private void handleOrcidException(ServiceRequestException e)
      throws OrcidAuthenticationTokenReusedException, OrcidAuthenticationTokenExpiredException {
    Map<String, String> errorJson = gson.fromJson(e.getResponseBody(), HashMap.class);
    final String errorDescription = errorJson.get("error_description");
    if (errorDescription.startsWith("Reused authorization code: ")) {
      throw new OrcidAuthenticationTokenReusedException();
    } else if (errorDescription.contains("expired")) {
      throw new OrcidAuthenticationTokenExpiredException();
    } else {
      log.error("Unknown error from ORCID authorization API: " + errorDescription);
      throw new RuntimeException(e);
    }
  }

  private URI getOrcidAuthUri(Site site) throws URISyntaxException {
    final String host = (String) site.getTheme().getConfigMap("orcid").get("host");
    return new URI(host + "/oauth/token");
  }

  private String getOrcidClientId(Site site) throws URISyntaxException {
    return (String) site.getTheme().getConfigMap("orcid").get("clientId");
  }

  private String getOrcidClientSecret(Site site) throws URISyntaxException {
    return (String) site.getTheme().getConfigMap("orcid").get("clientSecret");
  }

}


text:
Build the code-browser and start it from the top level directory
of the http git repository:

    dylan-compiler -build code-browser
    mkdir logs
    ./_build/bin/code-browser --config `pwd`/examples/code-browser/config.xml

The server will be running on port 8080.

Go to one of these URLs:

* /symbol/<library-name>
* /symbol/<library-name>/<module-name>
* /symbol/<library-name>/<module-name>/<definition-name>
* /search?search=xxx  (seems to have problems)


text:
<?php

require_once __DIR__.'/../vendor/autoload.php';

/*
 * First, we need to create an instance of the ConPHigurator
 * */
use Maiorano\Conphigurator\Config;
use Maiorano\Conphigurator\DriverFactory;

$driver = new DriverFactory;
$config = Config::create($driver->create('yml'));

/*
 * Next, let's set the base directory and load all of our .yml files
 * */

$config->setPath(__DIR__. DIRECTORY_SEPARATOR. 'config')->load();

/*
 * Did it work? Let's look!
 * */

echo '
';var_dump($config->all());echo '
';

/*
 * That's nice, but what if we want to grab a specific configuration file?
 * */

echo '
';var_dump($config->get('database'));echo '
';

/*
 * Even further, let's get a specific value from a configuration file
 * */

echo '
';var_dump($config->get('app.name'));echo '
';

/*
 * If you would like to retrieve files from a nested directory, simply add the directory name
 * */

echo '
';var_dump($config->get('packages/package.name'));echo '
';


text:
import underscore from 'underscore';

const exports = {};

underscore.extend(exports, underscore, {
  logError(...message) {
    const error = message.pop();

    let e;

    if (error && error.stack && error.stack.indexOf(error.message) === 0) {
      e = error.stack;
    } else {
      e = error;
    }

    return console.error.apply(console, message.concat([e]));
  },

  errorInfo(error) {
    let message, stack, trace;

    if ((error == null) || underscore.isString(error)) {
      message = 'Error: ' + error;
    } else {
      try {
        message = '' + error;
      } catch (e) {
        message = 'Unknown Error';
      }
    }

    if (error instanceof Error && error.stack) {
      if (error.stack.indexOf(message + '\n') === 0) {
        stack = error.stack.slice(message.length + 1);
      } else {
        stack = error.stack;
      }
      trace = stack.split('\n');
    } else {
      trace = null;
    }

    return {error, message, trace};
  },

  intersperse(array, v) {
    const result = array.slice(0, 1);
    underscore.each(array.slice(1), (e) => result.push(v, e));
    return result;
  },

  startsWith: function(str, starts) {
    if (starts === '') {
      return true;
    }

    if (str === null || starts === null) {
      return false;
    }

    str = String(str);
    starts = String(starts);

    return str.length >= starts.length && str.slice(0, starts.length) === starts;
  }
});

export default exports;


text:
using ColossalFramework.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSLCoop
{
    /// <summary>
    /// The ServerConfigurationPanel is opened, after the user started a netServer.
    /// </summary>
    public class ServerConfigurationPanel : UIPanel
    {
    }
}


text:
package testresults

import (
	"context"
	"text/template"
	"time"

	"cloud.google.com/go/spanner"
	"go.chromium.org/luci/common/sync/parallel"
	"go.chromium.org/luci/server/span"
	"google.golang.org/protobuf/types/known/timestamppb"

	spanutil "go.chromium.org/luci/analysis/internal/span"
	"go.chromium.org/luci/analysis/pbutil"
	pb "go.chromium.org/luci/analysis/proto/v1"
)

const (
	// The maximum number of workers to run in parallel.
	// Given 100 is the maximum number of test variants queried at once,
	// it is desirable that maxWorkers * batchSize >= 100.
	maxWorkers = 10

	// The size of each batch (in test variants).
	batchSize = 10
)

// QueryFailureRateOptions specifies options for QueryFailureRate().
type QueryFailureRateOptions struct {
	// Project is the LUCI Project to query.
	Project string
	// SubRealms are the realms (of the form "ci", NOT "chromium:ci")
	// within the project to query.
	SubRealms []string
	// TestVariants are the test variants to query.
	TestVariants []*pb.TestVariantIdentifier
	// AsAtTime is latest parititon time to include in the results;
	// outside of testing contexts, this should be the current time.
	// QueryTestVariants returns data for the 5 * 24 weekday hour
	// period leading up to this time.
	AsAtTime time.Time
}

// QueryFailureRate queries the failure rate of nominated test variants.
//
// Must be called in a Spanner transactional context. Context must
// support multiple reads (i.e. NOT spanner.Single()) as request may
// batched over multiple reads.
func QueryFailureRate(ctx context.Context, opts QueryFailureRateOptions) (*pb.QueryTestVariantFailureRateResponse, error) {
	batches := partitionIntoBatches(opts.TestVariants)

	intervals := defineIntervals(opts.AsAtTime)

	err := parallel.WorkPool(maxWorkers, func(c chan<- func() error) {
		for _, b := range batches {
			// Assign batch to a local variable to ensure its current
			// value is captured by function closures.
			batch := b
			c <- func() error {
				var err error
				batchOpts := opts
				batchOpts.TestVariants = batch.input
				// queryFailureRateShard ensures test variants appear
				// in the output in the same order as they appear in the
				// input.
				batch.output, err = queryFailureRateShard(ctx, batchOpts, intervals)
				return err
			}
		}
	})
	if err != nil {
		return nil, err
	}

	// The order of test variants in the output should be the
	// same as the input. Perform the inverse to what we did
	// in batching.
	analysis := make([]*pb.TestVariantFailureRateAnalysis, 0, len(opts.TestVariants))
	for _, b := range batches {
		analysis = append(analysis, b.output...)
	}

	response := &pb.QueryTestVariantFailureRateResponse{
		Intervals:    toPBIntervals(intervals),
		TestVariants: analysis,
	}
	return response, nil
}

type batch struct {
	input  []*pb.TestVariantIdentifier
	output []*pb.TestVariantFailureRateAnalysis
}

// partitionIntoBatches partitions a list of test variants into batches.
func partitionIntoBatches(tvs []*pb.TestVariantIdentifier) []*batch {
	var batches []*batch
	batchInput := make([]*pb.TestVariantIdentifier, 0, batchSize)
	for _, tv := range tvs {
		if len(batchInput) >= batchSize {
			batches = append(batches, &batch{
				input: batchInput,
			})
			batchInput = make([]*pb.TestVariantIdentifier, 0, batchSize)
		}
		batchInput = append(batchInput, tv)
	}
	if len(batchInput) > 0 {
		batches = append(batches, &batch{
			input: batchInput,
		})
	}
	return batches
}

// queryFailureRateShard reads failure rate statistics for test variants.
// Must be called in a spanner transactional context.
func queryFailureRateShard(ctx context.Context, opts QueryFailureRateOptions, intervals []interval) ([]*pb.TestVariantFailureRateAnalysis, error) {
	type testVariant struct {
		TestID      string
		VariantHash string
	}

	tvs := make([]testVariant, 0, len(opts.TestVariants))
	for _, ptv := range opts.TestVariants {
		variantHash := ptv.VariantHash
		if variantHash == "" {
			variantHash = pbutil.VariantHash(ptv.Variant)
		}

		tvs = append(tvs, testVariant{
			TestID:      ptv.TestId,
			VariantHash: variantHash,
		})
	}

	stmt, err := spanutil.GenerateStatement(failureRateQueryTmpl, failureRateQueryTmpl.Name(), nil)
	if err != nil {
		return nil, err
	}
	stmt.Params = map[string]interface{}{
		"project":             opts.Project,
		"testVariants":        tvs,
		"subRealms":           opts.SubRealms,
		"afterPartitionTime":  queryStartTime(intervals),
		"beforePartitionTime": queryEndTime(intervals),
		"skip":                int64(pb.TestResultStatus_SKIP),
	}

	results := make([]*pb.TestVariantFailureRateAnalysis, 0, len(tvs))

	index := 0
	var b spanutil.Buffer
	err = span.Query(ctx, stmt).Do(func(row *spanner.Row) error {
		var testID, variantHash string
		var intervalStats []*intervalStats
		var runFlakyExamples []*verdictExample
		var recentVerdicts []*recentVerdict

		err := b.FromSpanner(
			row,
			&testID,
			&variantHash,
			&intervalStats,
			&runFlakyExamples,
			&recentVerdicts,
		)
		if err != nil {
			return err
		}

		analysis := &pb.TestVariantFailureRateAnalysis{}
		if testID != tvs[index].TestID || variantHash != tvs[index].VariantHash {
			// This should never happen, as the SQL statement is designed
			// to return results in the same order as test variants requested.
			panic("results in incorrect order")
		}

		analysis.TestId = testID
		analysis.Variant = opts.TestVariants[index].Variant
		analysis.VariantHash = opts.TestVariants[index].VariantHash
		analysis.IntervalStats = toPBIntervalStats(intervalStats, intervals)
		analysis.RunFlakyVerdictExamples = toPBVerdictExamples(runFlakyExamples)
		analysis.RecentVerdicts = toPBRecentVerdicts(recentVerdicts)
		results = append(results, analysis)
		index++
		return nil
	})
	if err != nil {
		return nil, err
	}
	return results, nil
}

// jumpBack24WeekdayHours calculates the start time of an interval
// ending at the given endTime, such that the interval includes exactly
// 24 hours of weekday data (in UTC). Where there are multiple interval
// start times satisfying this criteria, the latest time is selected.
//
// For example, if the endTime is 08:21 on Tuesday, we would pick 08:21
// on Monday as the start time, as the period from start time to end time
// includes 24 hours of weekday (split over Monday and Tuesday).
//
// If the endTime is 08:21 on Monday, we would pick 08:21 on the previous
// Friday as the start time, as the period from start time to end time
// includes 24 hours of weekday (split over the Friday and Monday).
//
// If the endTime is midnight on the morning of Tuesday, any start time from
// midnight on Saturday morning to midnight on Monday morning would produce
// an interval that includes 24 hours of weekday data (i.e. the 24 hours of
// Monday). In this case, we pick midnight on Monday. This is the only case
// that is ambiguous.
//
// Rationale:
// Many projects see reduced testing activity on weekends, as fewer CLs are
// submitted. To avoid a dip in the sample size of statistics returned
// on these days (which stops exoneration), we effectively bunch weekend
// data together with Friday data in one period.
func jumpBack24WeekdayHours(endTime time.Time) time.Time {
	endTime = endTime.In(time.UTC)
	var startTime time.Time
	switch endTime.Weekday() {
	case time.Saturday:
		// Take us back to Saturday at 0:00.
		startTime = endTime.Truncate(24 * time.Hour)
		// Now take us back to Friday at 0:00.
		startTime = startTime.Add(-1 * 24 * time.Hour)
	case time.Sunday:
		// Take us back to Sunday at 0:00.
		startTime = endTime.Truncate(24 * time.Hour)
		// Now take us back to Friday at 0:00.
		startTime = startTime.Add(-2 * 24 * time.Hour)
	case time.Monday:
		// Take take us back to the same time
		// on the Friday.
		startTime = endTime.Add(-3 * 24 * time.Hour)
	default:
		// Take take us back to the same time
		// on the previous day (which will be a weekday).
		startTime = endTime.Add(-24 * time.Hour)
	}
	return startTime
}

// interval represents a time interval of data to be returned by
// QueryFailureRate.
type interval struct {
	// The interval start time (inclusive).
	startTime time.Time
	// The interval end time (exclusive).
	endTime time.Time
}

// defineIntervals defines the time intervals that should be returned
// by the QueryFailureRate query. This comprises five consecutive
// 24 weekday hour intervals ending at the given asAtTime.
//
// The first interval is the most recent interval, which ends at asAtTime
// and starts at such a time that means the interval includes 24
// hours of weekday data (as measured in UTC).
// The second interval ends at the start time of the first interval,
// and is generated in a similar fashion, and so on for the other
// three intervals.
// See jumpBack24WeekdayHours for how "24 weekday hours" is defined.
func defineIntervals(asAtTime time.Time) []interval {
	const intervalCount = 5
	result := make([]interval, 0, intervalCount)
	endTime := asAtTime.In(time.UTC)
	for i := 0; i < intervalCount; i++ {
		startTime := jumpBack24WeekdayHours(endTime)
		result = append(result, interval{
			startTime: startTime,
			endTime:   endTime,
		})
		endTime = startTime
	}
	return result
}

// queryStartTime returns the start of the partition time range that
// should be queried (inclusive). Verdicts with a partition time
// earlier than this time should not be included in the results.
func queryStartTime(intervals []interval) time.Time {
	return intervals[len(intervals)-1].startTime
}

// queryEndTime returns the end of the partition time range that should be
// queried (exclusive). Verdicts with partition times later than (or equal to)
// this time should not be included in the results.
func queryEndTime(intervals []interval) time.Time {
	return intervals[0].endTime
}

func toPBIntervals(intervals []interval) []*pb.QueryTestVariantFailureRateResponse_Interval {
	result := make([]*pb.QueryTestVariantFailureRateResponse_Interval, 0, len(intervals))
	for i, iv := range intervals {
		result = append(result, &pb.QueryTestVariantFailureRateResponse_Interval{
			IntervalAge: int32(i + 1),
			StartTime:   timestamppb.New(iv.startTime),
			EndTime:     timestamppb.New(iv.endTime),
		})
	}
	return result
}

// intervalStats represents time interval data returned by the
// QueryFailureRate query. Each interval represents 24 hours of data.
type intervalStats struct {
	// DaysSinceQueryStart is the time interval bucket represented by this
	// row.
	// Interval 0 represents the first 24 hours of the partition time range
	// queried, interval 1 is the the second 24 hours, and so on.
	DaysSinceQueryStart int64
	// TotalRunExpectedVerdicts is the number of verdicts which had only
	// expected runs. An expected run is a run in which at least one test
	// result was expected (excluding skips).
	TotalRunExpectedVerdicts int64
	// TotalRunFlakyVerdicts is the number of verdicts which had both expected
	// and unexpected runs. An expected run is a run in which at least one
	// test result was expected (excluding skips). An unexpected run is a run
	// in which all test results are unexpected (excluding skips).
	TotalRunFlakyVerdicts int64
	// TotalRunExpectedVerdicts is the number of verdicts which had only
	// unexpected runs. An unexpected run is a run in which
	// al test results are unexpected (excluding skips).
	TotalRunUnexpectedVerdicts int64
}

func toPBIntervalStats(stats []*intervalStats, intervals []interval) []*pb.TestVariantFailureRateAnalysis_IntervalStats {
	queryStartTime := queryStartTime(intervals)
	queryEndTime := queryEndTime(intervals)

	results := make([]*pb.TestVariantFailureRateAnalysis_IntervalStats, 0, len(intervals))
	// Ensure every interval is included in the output, even if there are
	// no verdicts in it.
	for i := range intervals {
		results = append(results, &pb.TestVariantFailureRateAnalysis_IntervalStats{
			IntervalAge: int32(i + 1),
		})
	}
	for _, s := range stats {
		// Match the interval data returned by the SQL query to the intervals
		// returned by the RPC. The SQL query returns one interval per
		// rolling 24 hour period, whereas the RPC returns one interval per
		// rolling 24 weekday hour period (including any weekend included
		// in that range). In practice, this means weekend data needs to get
		// summed into the 24 weekday hour period that includes the Friday.

		// Calculate the time interval represented by the interval data
		// returned by the query.
		intervalStartTime := queryStartTime.Add(time.Duration(s.DaysSinceQueryStart) * 24 * time.Hour)
		intervalEndTime := intervalStartTime.Add(24 * time.Hour)
		if queryEndTime.Before(intervalEndTime) {
			intervalEndTime = queryEndTime
		}

		// Find the output interval that contains the query interval.
		intervalIndex := -1
		for i, iv := range intervals {
			if !intervalEndTime.After(iv.endTime) && !intervalStartTime.Before(iv.startTime) {
				intervalIndex = i
				break
			}
		}
		if intervalIndex == -1 {
			// This should never happen.
			panic("could not reconcile query intervals with output intervals")
		}

		results[intervalIndex].TotalRunExpectedVerdicts += int32(s.TotalRunExpectedVerdicts)
		results[intervalIndex].TotalRunFlakyVerdicts += int32(s.TotalRunFlakyVerdicts)
		results[intervalIndex].TotalRunUnexpectedVerdicts += int32(s.TotalRunUnexpectedVerdicts)
	}
	return results
}

// verdictExample is used to store an example verdict returned by
// a Spanner query.
type verdictExample struct {
	PartitionTime        time.Time
	IngestedInvocationId string
	ChangelistHosts      []string
	ChangelistChanges    []int64
	ChangelistPatchsets  []int64
}

func toPBVerdictExamples(ves []*verdictExample) []*pb.TestVariantFailureRateAnalysis_VerdictExample {
	results := make([]*pb.TestVariantFailureRateAnalysis_VerdictExample, 0, len(ves))
	for _, ve := range ves {
		cls := make([]*pb.Changelist, 0, len(ve.ChangelistHosts))
		if len(ve.ChangelistHosts) != len(ve.ChangelistChanges) ||
			len(ve.ChangelistChanges) != len(ve.ChangelistPatchsets) {
			panic("data consistency issue: length of changelist arrays do not match")
		}
		for i := range ve.ChangelistHosts {
			cls = append(cls, &pb.Changelist{
				Host:     ve.ChangelistHosts[i] + GerritHostnameSuffix,
				Change:   ve.ChangelistChanges[i],
				Patchset: int32(ve.ChangelistPatchsets[i]),
			})
		}
		results = append(results, &pb.TestVariantFailureRateAnalysis_VerdictExample{
			PartitionTime:        timestamppb.New(ve.PartitionTime),
			IngestedInvocationId: ve.IngestedInvocationId,
			Changelists:          cls,
		})
	}
	return results
}

// recentVerdict represents one of the most recent verdicts for the test variant.
type recentVerdict struct {
	verdictExample
	HasUnexpectedRun bool
}

func toPBRecentVerdicts(verdicts []*recentVerdict) []*pb.TestVariantFailureRateAnalysis_RecentVerdict {
	results := make([]*pb.TestVariantFailureRateAnalysis_RecentVerdict, 0, len(verdicts))
	for _, v := range verdicts {
		cls := make([]*pb.Changelist, 0, len(v.ChangelistHosts))
		if len(v.ChangelistHosts) != len(v.ChangelistChanges) ||
			len(v.ChangelistChanges) != len(v.ChangelistPatchsets) {
			panic("data consistency issue: length of changelist arrays do not match")
		}
		for i := range v.ChangelistHosts {
			cls = append(cls, &pb.Changelist{
				Host:     v.ChangelistHosts[i] + GerritHostnameSuffix,
				Change:   v.ChangelistChanges[i],
				Patchset: int32(v.ChangelistPatchsets[i]),
			})
		}
		results = append(results, &pb.TestVariantFailureRateAnalysis_RecentVerdict{
			PartitionTime:        timestamppb.New(v.PartitionTime),
			IngestedInvocationId: v.IngestedInvocationId,
			Changelists:          cls,
			HasUnexpectedRuns:    v.HasUnexpectedRun,
		})
	}
	return results
}

var failureRateQueryTmpl = template.Must(template.New("").Parse(`
WITH test_variant_verdicts AS (
	SELECT
		Index,
		TestId,
		VariantHash,
		ARRAY(
			-- Filter verdicts to at most one per unsubmitted changelist under
			-- test. Don't filter verdicts without an unsubmitted changelist
			-- under test (i.e. CI data).
			SELECT
				ANY_VALUE(STRUCT(
				PartitionTime,
				IngestedInvocationId,
				HasUnexpectedRun,
				HasExpectedRun,
				ChangelistHosts,
				ChangelistChanges,
				ChangelistPatchsets,
				PresubmitRunByAutomation)
				-- Prefer the verdict that is flaky. If both (or neither) are flaky,
				-- pick the verdict with the highest partition time. If partition
				-- times are also the same, pick any.
				HAVING MAX IF(HasExpectedRun AND HasUnexpectedRun, TIMESTAMP_ADD(PartitionTime, INTERVAL 365 DAY), PartitionTime)) AS Verdict,
			FROM (
				-- Flatten test runs to test verdicts.
				SELECT
					PartitionTime,
					IngestedInvocationId,
					LOGICAL_OR(UnexpectedRun) AS HasUnexpectedRun,
					LOGICAL_OR(NOT UnexpectedRun) AS HasExpectedRun,
					ANY_VALUE(ChangelistHosts) AS ChangelistHosts,
					ANY_VALUE(ChangelistChanges) AS ChangelistChanges,
					ANY_VALUE(ChangelistPatchsets) AS ChangelistPatchsets,
					ANY_VALUE(PresubmitRunByAutomation) As PresubmitRunByAutomation
				FROM (
					-- Flatten test results to test runs.
					SELECT
						PartitionTime,
						IngestedInvocationId,
						RunIndex,
						LOGICAL_AND(COALESCE(IsUnexpected, FALSE)) AS UnexpectedRun,
						ANY_VALUE(ChangelistHosts) AS ChangelistHosts,
						ANY_VALUE(ChangelistChanges) AS ChangelistChanges,
						ANY_VALUE(ChangelistPatchsets) AS ChangelistPatchsets,
						ANY_VALUE(PresubmitRunOwner IS NOT NULL AND PresubmitRunOwner = "automation") AS PresubmitRunByAutomation
					FROM TestResults
					WHERE Project = @project
						AND PartitionTime >= @afterPartitionTime
						AND PartitionTime < @beforePartitionTime
						AND TestId = tv.TestId And VariantHash = tv.VariantHash
						AND SubRealm IN UNNEST(@subRealms)
						-- Exclude skipped results.
						AND Status <> @skip
						-- Exclude test results testing multiple CLs, as
						-- we cannot ensure at most one verdict per CL for
						-- them.
						AND (ChangelistHosts IS NULL OR ARRAY_LENGTH(ChangelistHosts) <= 1)
					GROUP BY PartitionTime, IngestedInvocationId, RunIndex
				)
				GROUP BY PartitionTime, IngestedInvocationId
				ORDER BY PartitionTime DESC, IngestedInvocationId
			)
			-- Unique CL (if there is a CL under test).
			GROUP BY
				IF(ChangelistHosts IS NOT NULL AND ARRAY_LENGTH(ChangelistHosts) > 0, ChangelistHosts[OFFSET(0)], IngestedInvocationId),
				IF(ChangelistHosts IS NOT NULL AND ARRAY_LENGTH(ChangelistHosts) > 0, ChangelistChanges[OFFSET(0)], NULL)
			ORDER BY Verdict.PartitionTime DESC, Verdict.IngestedInvocationId
		) AS Verdicts,
	FROM UNNEST(@testVariants) tv WITH OFFSET Index
)

SELECT
	TestId,
	VariantHash,
	ARRAY(
		SELECT AS STRUCT
			TIMESTAMP_DIFF(v.PartitionTime, @afterPartitionTime, DAY) as DaysSinceQueryStart,
			COUNTIF(NOT v.HasUnexpectedRun AND v.HasExpectedRun) AS TotalRunExpectedVerdicts,
			COUNTIF(v.HasUnexpectedRun AND v.HasExpectedRun) AS TotalRunFlakyVerdicts,
			COUNTIF(v.HasUnexpectedRun AND NOT v.HasExpectedRun) AS TotalRunUnexpectedVerdicts
		FROM UNNEST(Verdicts) v
		GROUP BY DaysSinceQueryStart
		ORDER BY DaysSinceQueryStart DESC
	) As IntervalStats,
	ARRAY(
		SELECT AS STRUCT
			v.PartitionTime,
			v.IngestedInvocationId,
			v.ChangelistHosts,
			v.ChangelistChanges,
			v.ChangelistPatchsets
		FROM UNNEST(Verdicts) v WITH OFFSET o
		WHERE v.HasUnexpectedRun AND v.HasExpectedRun
		ORDER BY o -- Order by descending partition time.
		LIMIT 10
	) as RunFlakyExamples,
	ARRAY(
		SELECT AS STRUCT
			v.PartitionTime,
			v.IngestedInvocationId,
			v.ChangelistHosts,
			v.ChangelistChanges,
			v.ChangelistPatchsets,
			v.HasUnexpectedRun
		FROM UNNEST(Verdicts) v WITH OFFSET o
		WHERE
			-- Filter out CLs authored by automation.
			NOT PresubmitRunByAutomation
		ORDER BY o
		LIMIT 10
	) as RecentVerdicts,
FROM test_variant_verdicts
ORDER BY Index
`))


text:
'use strict';

const Path = require('path');

const internals = {};

exports = module.exports = internals.Reporter = function (options) {

    this.settings = options;
};

internals.Reporter.prototype.reportln = function (line) {

    this.report(line + '\n');
};

internals.Reporter.prototype.start = function (notebook) {

};

internals.Reporter.prototype.test = function (test) {

};

internals.Reporter.prototype.end = function (notebook) {

    notebook.coverage = notebook.coverage || { files: [] };
    notebook.coverage.files.forEach((file) => {

        this.reportln('TN:');                                                       // Test Name
        this.reportln('SF:' + Path.join(process.cwd(), '/', file.filename));        // Script File

        const lineNums = Object.keys(file.source);
        lineNums.forEach((lineNum) => {

            const line = file.source[lineNum];
            const hits = line.miss ? 0 : (line.hits || 1);
            this.reportln('DA:' + lineNum + ',' + hits);                            // Line and total execution count
        });

        this.reportln('LF:' + file.sloc);
        this.reportln('LH:' + file.hits);
        this.reportln('end_of_record');
    });
};


text:
package middleware

import (
	"fmt"
	"runtime"

	"github.com/labstack/echo"
	"github.com/labstack/gommon/color"
)

type (
	// RecoverConfig defines the config for recover middleware.
	RecoverConfig struct {
		// StackSize is the stack size to be printed.
		// Optional, with default value as 4 KB.
		StackSize int

		// DisableStackAll disables formatting stack traces of all other goroutines
		// into buffer after the trace for the current goroutine.
		// Optional, with default value as false.
		DisableStackAll bool

		// DisablePrintStack disables printing stack trace.
		// Optional, with default value as false.
		DisablePrintStack bool
	}
)

var (
	// DefaultRecoverConfig is the default recover middleware config.
	DefaultRecoverConfig = RecoverConfig{
		StackSize:         4 << 10, // 4 KB
		DisableStackAll:   false,
		DisablePrintStack: false,
	}
)

// Recover returns a middleware which recovers from panics anywhere in the chain
// and handles the control to the centralized HTTPErrorHandler.
func Recover() echo.MiddlewareFunc {
	return RecoverWithConfig(DefaultRecoverConfig)
}

// RecoverWithConfig returns a recover middleware from config.
// See `Recover()`.
func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {
	// Defaults
	if config.StackSize == 0 {
		config.StackSize = DefaultRecoverConfig.StackSize
	}

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			defer func() {
				if r := recover(); r != nil {
					var err error
					switch r := r.(type) {
					case error:
						err = r
					default:
						err = fmt.Errorf("%v", r)
					}
					stack := make([]byte, config.StackSize)
					length := runtime.Stack(stack, !config.DisableStackAll)
					if !config.DisablePrintStack {
						c.Logger().Printf("[%s] %s %s", color.Red("PANIC RECOVER"), err, stack[:length])
					}
					c.Error(err)
				}
			}()
			return next(c)
		}
	}
}


text:
package org.vorthmann.zome.export.java2d;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.vecmath.Vector3f;

import org.vorthmann.ui.DefaultController;

/**
 * Renders out to PDF, Postscript, or SVG.
 *
 * TODO extract model from controller, to support headless export.
 *
 * @author vorth
 */
public class Java2dSnapshot extends DefaultController
{
    public Java2dSnapshot( Java2dExporter exporter )
    {
        this .mLineDrawing = false;
        this .monochrome = true;
        this .doLighting = true;
        this .doOutlines = true;
        this.setExporter( exporter );
    }

    private final static String[] DRAW_STYLES = new String[]{ "outlined shapes", "shaded shapes", "shaded, outlined shapes", "colored lines", "black lines" };

    @Override
    public String[] getCommandList( String listName )
    {
        if ( "draw.styles" .equals( listName ) )
        {
            return DRAW_STYLES;
        }
        else
            return super .getCommandList( listName );
    }

    @Override
    public String getProperty( String propName )
    {
        if ( "showBackground" .equals( propName ) )
            return Boolean .toString( mShowBackground );
        if ( "lineDrawing" .equals( propName ) )
            return Boolean .toString( mLineDrawing );
        if ( "monochrome" .equals( propName ) )
            return Boolean .toString( monochrome );
        if ( "drawStyle" .equals( propName ) )
        {
            if ( this .mLineDrawing )
                if ( this .monochrome )
                    return "black lines";
                else
                    return "colored lines";
            else if ( this .doLighting )
                if ( this .doOutlines )
                    return "shaded, outlined shapes";
                else
                    return "shaded shapes";
            else
                return "outlined shapes";
        }
        return super.getProperty( propName );
    }

    @Override
    public void actionPerformed( ActionEvent e )
    {
        String action = e .getActionCommand();

        if ( action .equals( "refresh" ) )
        {
            current = false;
        }
        else if ( action .equals( "toggleBackground" ) )
        {
            current = false;
            mShowBackground = !mShowBackground;
        }
        else if ( action .equals( "toggleLineDrawing" ) )
        {
            current = false;
            mLineDrawing = !mLineDrawing;
        }
        else if ( action .equals( "toggleMonochrome" ) )
        {
            monochrome = !monochrome;
            if ( mLineDrawing )
                current = false;
        }
        else if ( action .startsWith( "setDrawStyle." ) )
        {
            String drawStyle = action .substring( "setDrawStyle." .length() );
            if ( "black lines" .equals(  drawStyle ) ) {
                this .monochrome = true;
                this .mLineDrawing = true;
            }
            else if ( "colored lines" .equals(  drawStyle ) ) {
                this .monochrome = false;
                this .mLineDrawing = true;
            }
            else if ( "outlined shapes" .equals(  drawStyle ) ) {
                this .mLineDrawing = false;
                this .doLighting = false;
                this .doOutlines = true;
            }
            else if ( "shaded shapes" .equals(  drawStyle ) ) {
                this .mLineDrawing = false;
                this .doLighting = true;
                this .doOutlines = false;
            }
            else if ( "shaded, outlined shapes" .equals(  drawStyle ) ) {
                this .mLineDrawing = false;
                this .doLighting = true;
                this .doOutlines = true;
            }
            current = false;
        }
        else
            super.actionPerformed( e );
    }

//    private void refresh()
//    {
//
//        mSnapshot .setBackgroundColor( new java.awt.Color( colors .getColor( Colors.BACKGROUND ) .getRGB() ) );
//    }

    @Override
    public void doFileAction( String command, File file )
    {
        try {
            SnapshotExporter snapshotExporter = null;
            switch (command) {
                case "export.2d.pdf":
                    snapshotExporter = new PDFExporter();
                    break;
                case "export.2d.ps":
                    snapshotExporter = new PostScriptExporter();
                    break;
                case "export.2d.svg":
                    snapshotExporter = new SVGExporter();
                    break;
                default:
                    break;
            }
            if ( snapshotExporter == null )
                return;
            // A try-with-resources block closes the resource even if an exception occurs
            try (Writer out = new FileWriter( file )) {
                snapshotExporter .export( this, out );
            }
            openApplication( file );
        } catch ( Exception e ) {
            mErrors .reportError( UNKNOWN_ERROR_CODE, new Object[]{ e } );
        }
    }

    @Override
    public void repaintGraphics( String panelName, Graphics graphics, Dimension size )
    {
        if ( ! current )
            try {
                mPolygons .clear();
                mLines .clear();
                this .exporter .doExport( new File(""), null, size.height, size.width );
                current = true;
            } catch ( Exception e1 ) {
                mErrors .reportError( UNKNOWN_ERROR_CODE, new Object[]{ e1 } );
            }

        Graphics2D g2d = (Graphics2D) graphics;

        g2d .setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
        g2d .clearRect( 0, 0, (int) size .getWidth(), (int) size .getHeight() );

        if ( mShowBackground ) {
            g2d .setPaint( this .getBackgroundColor() );
            Rectangle2D rect = new Rectangle2D.Float();
            rect .setFrame( new Point2D.Float(), size );
            g2d .fill( rect );
        }

        if ( mLineDrawing ) {
            g2d .setStroke( new BasicStroke( 3*mStrokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND ) );
            g2d .setPaint( java.awt.Color.BLACK );

            for (LineSegment line : mLines) {
                if ( monochrome )
                    if ( mShowBackground )
                        g2d .setPaint( java.awt.Color.WHITE );
                    else
                        g2d .setPaint( java.awt.Color.BLACK );
                else
                    g2d .setPaint( line .getColor() );
                g2d .draw( line .getPath() );
            }
        }
        else {
            g2d .setStroke( new BasicStroke( mStrokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND ) );
            for ( Java2dSnapshot.Polygon poly : mPolygons ){
                g2d .setPaint( poly .getColor() );
                g2d .fill( poly .getPath() );
                if ( this .doOutlines ) {
                    g2d .setPaint( java.awt.Color.BLACK );
                    g2d .draw( poly .getPath() );
                }
            }
        }

        g2d.dispose(); //clean up
    }

    private Java2dExporter exporter;

    private boolean mShowBackground, mLineDrawing, monochrome, doLighting, doOutlines;

    private boolean current;

	private List<Polygon> mPolygons = new ArrayList<>();

    private List<LineSegment> mLines = new ArrayList<>();

	private Rectangle2D mRect;

	private float mStrokeWidth;

    public boolean isLineDrawing()
    {
        return mLineDrawing;
    }

    public boolean isMonochrome()
    {
        return monochrome;
    }

    public boolean hasLighting()
    {
        return doLighting;
    }

	public void addPolygon( Polygon polygon )
	{
		mPolygons .add( polygon );
	}

    public void addLineSegment( Color color, Vector3f start, Vector3f end )
    {
        mLines .add( new LineSegment( color, start, end ) );
    }

	public void depthSort()
	{
        if ( mLineDrawing )
            Collections .sort( mLines );
            // TODO eliminate duplicates
        else
            Collections .sort( mPolygons );
	}

	public void setRect( Rectangle2D rect )
	{
		mRect = rect;
	}

	public void setStrokeWidth( float strokeWidth )
	{
		mStrokeWidth = strokeWidth;
	}

	public Rectangle2D getRect()
	{
	    return mRect;
	}

	public float getStrokeWidth()
	{
	    if ( this .mLineDrawing || this .doOutlines )
	        return mStrokeWidth;
	    else
	        return -1f;
	}

    public Dimension getDimension()
    {
        return new Dimension( (int) mRect .getWidth(), (int) mRect .getHeight() ) ;
    }

    public static class LineSegment implements Comparable<LineSegment>
    {
        private final GeneralPath mPath;
        private float mDepth;
        private final Color mPolyColor;

        public GeneralPath getPath()
        {
            return mPath;
        }

        public LineSegment( Color color, Vector3f start, Vector3f end )
        {
            mPolyColor = color;
            mPath = new GeneralPath();
            mPath .moveTo( start.x, start.y );
            mPath .lineTo( end.x, end.y );
            mDepth = ( start.z + end.z ) / 2.0f;
        }

        public Color getColor()
        {
            return mPolyColor;
        }

        @Override
        public int compareTo( LineSegment other )
        {
            double otherZ = other .mDepth;
            if ( mDepth > otherZ )
                return 1;
            if ( mDepth < otherZ )
                return -1;
            return 0;
        }
    }

	public static class Polygon implements Comparable<Polygon>
	{
		private final GeneralPath mPath;
		private float mDepth;
		private int mSize = 0;
		private Color mPolyColor;

		public GeneralPath getPath()
		{
			return mPath;
		}

		public int size()
		{
			return mSize;
		}

		public void addVertex( Vector3f vertex )
		{
			++ mSize;
			if ( mSize == 1 ) {
				mPath .moveTo( vertex.x, vertex.y );
				mDepth = vertex.z;
			}
			else {
				mPath .lineTo( vertex.x, vertex.y );
				mDepth += vertex.z;
			}
		}

		public void close()
		{
			mDepth /= mSize;
			mPath .closePath();
		}

		public Polygon( Color color )
		{
			mPolyColor = color;
			mPath = new GeneralPath();
		}

		public Color getColor()
		{
			return mPolyColor;
		}

        @Override
		public int compareTo( Polygon other )
		{
			double otherZ = other .mDepth;
			if ( mDepth > otherZ )
				return 1;
			if ( mDepth < otherZ )
				return -1;
			return 0;
		}

        public void applyLighting( Vector3f normal, Vector3f[] lightDirs, Color[] lightColors, Color ambient )
        {
            float redIntensity = ambient .getRed() / 255f;
            float greenIntensity = ambient .getGreen() / 255f;
            float blueIntensity = ambient .getBlue() / 255f;
            for ( int i = 0; i < lightColors.length; i++ ) {
                float intensity = Math .max( normal .dot( lightDirs[ i ] ), 0f );
                redIntensity += intensity * ( lightColors[ i ].getRed() / 255f );
                greenIntensity += intensity * ( lightColors[ i ].getGreen() / 255f );
                blueIntensity += intensity * ( lightColors[ i ].getBlue() / 255f );
            }
            int red = (int) ( mPolyColor.getRed() * Math.min( redIntensity, 1f ) );
            int green = (int) ( mPolyColor.getGreen() * Math.min( greenIntensity, 1f ) );
            int blue = (int) ( mPolyColor.getBlue() * Math.min( blueIntensity, 1f ) );
            mPolyColor = new Color( red, green, blue );
        }
    }

    public Iterator<LineSegment> getLines()
    {
        return mLines .iterator();
    }

    public Iterator<Polygon> getPolygons()
    {
        return mPolygons .iterator();
    }

    public void setExporter( Java2dExporter exporter )
    {
        current = false;
        this.exporter = exporter;
        exporter .setSnapshot( this );
    }

    public Color getBackgroundColor()
    {
        if ( this .mShowBackground )
            return this .exporter .getBackgroundColor();
        else
            return null;
    }
}


text:
@implementation ZPCoverView

+ (instancetype)show
{
    ZPCoverView   *view=[[ZPCoverView alloc]init];
    //设置背景颜色
    view.backgroundColor=[UIColor blackColor];
    view.alpha=0.6;
    view.frame=[UIScreen mainScreen].bounds ;

    //把要显示的内容添加到窗口

    [[UIApplication sharedApplication].keyWindow addSubview:view];
    return view;

}

+(void)hidden
{
    for (UIView *view in [UIApplication sharedApplication].keyWindow.subviews) {
        if([view isKindOfClass:[ZPCoverView class]])
        {

            [view removeFromSuperview];
        }
    }

}
@end


text: A NautilusChanged is raised when a NautilusUI send th message #changed:


text:
function unescape(input: string): string {
    return input.replace(/\\('|\\)/g, '$1').replace(/[\r\t\n]/g, ' ')
}

export default unescape