text:
package leaks.InterproceduralRefute;
public class FakeMap {

    private final static Object[] EMPTY_TABLE = new Object[1];
    private Object[] table;
    private int capacity;
    private int size;

    public FakeMap() {
	table = EMPTY_TABLE;
	capacity = -1;
	size = 0;
    }

    public Object put(String i, Object value) {
	if (size > capacity) table = new Object[capacity];
	table[size++] = value;
	return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#66cccc" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/menu_chs_mdl"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:textSize="24sp"
            android:text="选择模板"
            />
         <TextView
            android:id="@+id/menu_cus_chs_mdl"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:textSize="24sp"
            android:text="自定义模板"
            />
          <TextView
            android:id="@+id/menu_cus_draw"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:textSize="24sp"
            android:text="自定义绘制"
            />
           <TextView
            android:id="@+id/menu_save_mdl"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:textSize="24sp"
            android:text="保存模板"
            />
    </LinearLayout>

</RelativeLayout>


text:
      <?php if(empty($company_for_graph_count)):?>

                    Company Name
                    Number of trainees

      <?php else:?>
      <form action="deleteStudent" method="POST" name="formDel">

                            Company Name
                            Number of trainees

                      <?php foreach($company_for_graph_count as $company): ?>

                         <?php echo $company['company_name'] ?>
                         <?php echo $company['count'] ?>

                    <?php endforeach; ?>

        <?php endif;?>
        </form>


text:
import csv
import math
import random
import matplotlib.pyplot as plt
import numpy as np

#
# Returns a dictionary of probabilities of a feature given a class in the form:
# {class:{(position, value): probability ... }...}
#
def getIrisModel(inFile):
    # Set up the CSV file
    iris_data = open(inFile, "rt")
    iris_data_csv = csv.reader(iris_data, delimiter=',')
    # Read the CSV file into a 3d dict
    iris_dict = {"Iris-setosa":{}, "Iris-versicolor":{}, "Iris-virginica":{}}
    for i, row in enumerate(iris_data_csv):
        if(row[4] == "Iris-setosa"):
            iris_dict["Iris-setosa"][i] = row[0:4]
        elif(row[4] == "Iris-virginica"):
            iris_dict["Iris-virginica"][i] = row[0:4]
        elif(row[4] == "Iris-versicolor"):
            iris_dict["Iris-versicolor"][i] = row[0:4]

    iris_data.close()

    # Calculate all of the probabilities we need
    feature_probabilities = {"Iris-setosa":{}, "Iris-versicolor":{}, "Iris-virginica":{}}
    # Store the overall probability of a class
    NUM_ENTRIES = NUM_ENTRIES = len(iris_dict["Iris-setosa"]) + len(iris_dict["Iris-versicolor"]) + len(iris_dict["Iris-virginica"])
    feature_probabilities["Iris-setosa-p"] = float(len(iris_dict["Iris-setosa"]))/NUM_ENTRIES
    feature_probabilities["Iris-virginica-p"] = float(len(iris_dict["Iris-virginica"]))/NUM_ENTRIES
    feature_probabilities["Iris-versicolor-p"] = float(len(iris_dict["Iris-versicolor"]))/NUM_ENTRIES

    # Compute the conditional probabilities of feature x_i given C
    # Each entry is in the form of (position, value): probability
    for classification in iris_dict:
        for entry in iris_dict[classification].values():
            for i, value in enumerate(entry):
                if(not (i,value) in feature_probabilities[classification]):
                    feature_count = 0
                    for entry in iris_dict[classification].values():
                        if(entry[i] == value):
                            feature_count += 1
                    feature_probabilities[classification][(i,value)] = float(feature_count)/50

    return feature_probabilities

#
# Classify a given vector v based on the model.
# Returns the predicted classification.
#
def classify(v, model):
    # Probabilities of each class
    setosa_p = 0
    versicolor_p = 0
    virginica_p = 0
    # Probabilities of each class across the whole dataset
    IRIS_SETOSA_P = model["Iris-setosa-p"]
    IRIS_VERSICOLOR_P = model["Iris-versicolor-p"]
    IRIS_VIRGINICA_P = model["Iris-virginica-p"]
    for i, f_i in enumerate(v):
        # Using log-space
        if((i, f_i) in model["Iris-setosa"]):
            setosa_p += math.log(model["Iris-setosa"][(i, f_i)] + 1)
        if((i, f_i) in model["Iris-versicolor"]):
            versicolor_p += math.log(model["Iris-versicolor"][(i, f_i)] + 1)
        if((i, f_i) in model["Iris-virginica"]):
            virginica_p += math.log(model["Iris-virginica"][(i, f_i)] + 1)
    setosa_p *= IRIS_SETOSA_P
    versicolor_p *= IRIS_VERSICOLOR_P
    virginica_p *= IRIS_VIRGINICA_P
    probabilities = {setosa_p:"Iris-setosa", versicolor_p:"Iris-versicolor", virginica_p:"Iris-virginica"}
    return probabilities[max(probabilities)]

#
# Calculates the accuracy of the model
#
def calcAccuracy(training_data_file, test_data_file):
    naive_bayes_model = getIrisModel(training_data_file)
    test_data = open(test_data_file, "rt")
    test_data_csv = csv.reader(test_data, delimiter=",")
    test_data_dict = {}
    for i, row in enumerate(test_data_csv):
        test_vector = []
        for j in range(0,5):
            test_vector.append(row[j])
        test_data_dict[i] = test_vector

    correct_count = 0
    for entry in test_data_dict.values():
        if(classify(entry, naive_bayes_model) == entry[4]):
            correct_count += 1
    accuracy = float(correct_count)/len(test_data_dict)
    test_data.close()
    return accuracy

#
# Shuffles the dataset based on a ratio training:test
#
def shuffleData(training, test):
    iris_data = open("iris.data", "r+")
    iris_training = open("iris.training.data", "w")
    iris_test = open("iris.test.data", "w")

    all_data = iris_data.readlines()
    random.shuffle(all_data)
    all_data_len = len(all_data)

    split_point = int( all_data_len * ( float(training) / (training + test)))
    for i in range(0, split_point):
        iris_training.write(all_data[i])
    for j in range(split_point, all_data_len - 1):
        iris_test.write(all_data[j])

    iris_data.close()
    iris_training.close()
    iris_test.close()

#
# Calculates the accuracy distribution given an iris data file, returns dict
#
def calcAccuracyDist():
    ratio_max = 15
    accuracyDist = {}
    for ratio in range(1, ratio_max):
        total = 0
        tests = 20000
        for trial in range(0, tests):
            shuffleData(ratio, 1)
            total += calcAccuracy("iris.training.data", "iris.test.data")
        average = total/tests
        average = average * 100
        print("(" + str(ratio) + ":1) = " + str(average) + "%")
        accuracyDist[ratio] = average
    return accuracyDist

dist = calcAccuracyDist()

# Plot the Results
x = dist.keys()
y = dist.values()
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 4))(np.unique(x)), label="Best Fit Line")
plt.scatter(x,y)
plt.xlabel("Ratio")
plt.ylabel("% Accuracy")
plt.show()


text:
'use strict';

import type {VariablesOf} from 'relay-runtime/util/RelayRuntimeTypes';
import type {Options} from './useRefetchableFragmentInternal_REACT_CACHE';

import type {LoadMoreFn, UseLoadMoreFunctionArgs} from '../useLoadMoreFunction';
import type {RefetchFnDynamic} from './useRefetchableFragmentInternal_REACT_CACHE';
import type {
  FragmentType,
  GraphQLResponse,
  GraphQLTaggedNode,
  Observer,
  OperationType,
} from 'relay-runtime';

const useLoadMoreFunction = require('../useLoadMoreFunction');
const useStaticFragmentNodeWarning = require('../useStaticFragmentNodeWarning');
const useRefetchableFragmentInternal = require('./useRefetchableFragmentInternal_REACT_CACHE');
const {useCallback, useDebugValue, useState} = require('react');
const {
  getFragment,
  getFragmentIdentifier,
  getPaginationMetadata,
} = require('relay-runtime');
import useRelayEnvironment from '../useRelayEnvironment';

export type ReturnType<TQuery: OperationType, TKey, TFragmentData> = {
  data: TFragmentData,
  loadNext: LoadMoreFn<TQuery>,
  loadPrevious: LoadMoreFn<TQuery>,
  hasNext: boolean,
  hasPrevious: boolean,
  isLoadingNext: boolean,
  isLoadingPrevious: boolean,
  refetch: RefetchFnDynamic<TQuery, TKey>,
};

function usePaginationFragment<
  TQuery: OperationType,
  TKey: ?{+$data?: mixed, +$fragmentSpreads: FragmentType, ...},
>(
  fragmentInput: GraphQLTaggedNode,
  parentFragmentRef: TKey,
): ReturnType<
  TQuery,
  TKey,
  // NOTE: This $Call ensures that the type of the returned data is either:
  //   - nullable if the provided ref type is nullable
  //   - non-nullable if the provided ref type is non-nullable
  // prettier-ignore
  $Call<
    & (<TFragmentData>( { +$data?: TFragmentData, ... }) =>  TFragmentData)
    & (<TFragmentData>(?{ +$data?: TFragmentData, ... }) => ?TFragmentData),
    TKey,
  >,
> {
  const fragmentNode = getFragment(fragmentInput);
  useStaticFragmentNodeWarning(
    fragmentNode,
    'first argument of usePaginationFragment()',
  );
  const componentDisplayName = 'usePaginationFragment()';

  const {
    connectionPathInFragmentData,
    paginationRequest,
    paginationMetadata,
    identifierField,
  } = getPaginationMetadata(fragmentNode, componentDisplayName);

  const {fragmentData, fragmentRef, refetch} = useRefetchableFragmentInternal<
    TQuery,
    TKey,
  >(fragmentNode, parentFragmentRef, componentDisplayName);
  const fragmentIdentifier = getFragmentIdentifier(fragmentNode, fragmentRef);

  // Backward pagination
  const [loadPrevious, hasPrevious, isLoadingPrevious, disposeFetchPrevious] =
    useLoadMore<TQuery>({
      componentDisplayName,
      connectionPathInFragmentData,
      direction: 'backward',
      fragmentData,
      fragmentIdentifier,
      fragmentNode,
      fragmentRef,
      identifierField,
      paginationMetadata,
      paginationRequest,
    });

  // Forward pagination
  const [loadNext, hasNext, isLoadingNext, disposeFetchNext] =
    useLoadMore<TQuery>({
      componentDisplayName,
      connectionPathInFragmentData,
      direction: 'forward',
      fragmentData,
      fragmentIdentifier,
      fragmentNode,
      fragmentRef,
      identifierField,
      paginationMetadata,
      paginationRequest,
    });

  const refetchPagination: RefetchFnDynamic<TQuery, TKey> = useCallback(
    (variables: VariablesOf<TQuery>, options: void | Options) => {
      disposeFetchNext();
      disposeFetchPrevious();
      return refetch(variables, {...options, __environment: undefined});
    },
    [disposeFetchNext, disposeFetchPrevious, refetch],
  );

  if (__DEV__) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useDebugValue({
      fragment: fragmentNode.name,
      data: fragmentData,
      hasNext,
      isLoadingNext,
      hasPrevious,
      isLoadingPrevious,
    });
  }
  return {
    data: fragmentData,
    loadNext,
    loadPrevious,
    hasNext,
    hasPrevious,
    isLoadingNext,
    isLoadingPrevious,
    refetch: refetchPagination,
  };
}

function useLoadMore<TQuery: OperationType>(
  args: $Diff<
    UseLoadMoreFunctionArgs,
    {
      observer: Observer<GraphQLResponse>,
      onReset: () => void,
      ...
    },
  >,
): [LoadMoreFn<TQuery>, boolean, boolean, () => void] {
  const environment = useRelayEnvironment();
  const [isLoadingMore, reallySetIsLoadingMore] = useState(false);
  // Schedule this update since it must be observed by components at the same
  // batch as when hasNext changes. hasNext is read from the store and store
  // updates are scheduled, so this must be scheduled too.
  const setIsLoadingMore = (value: boolean) => {
    const schedule = environment.getScheduler()?.schedule;
    if (schedule) {
      schedule(() => {
        reallySetIsLoadingMore(value);
      });
    } else {
      reallySetIsLoadingMore(value);
    }
  };
  const observer = {
    start: () => setIsLoadingMore(true),
    complete: () => setIsLoadingMore(false),
    error: () => setIsLoadingMore(false),
  };
  const handleReset = () => setIsLoadingMore(false);
  const [loadMore, hasMore, disposeFetch] = useLoadMoreFunction<TQuery>({
    ...args,
    observer,
    onReset: handleReset,
  });
  return [loadMore, hasMore, isLoadingMore, disposeFetch];
}

module.exports = usePaginationFragment;


text:
// ----- this file has been automatically generated - do not edit
import { UAProperty } from "node-opcua-address-space-base"
import { DataType } from "node-opcua-variant"
import { UAString } from "node-opcua-basic-types"
import { EnumBrokerTransportQualityOfService } from "./enum_broker_transport_quality_of_service"
import { UADataSetWriterTransport, UADataSetWriterTransport_Base } from "./ua_data_set_writer_transport"
/**
 * |                |                                                  |
 * |----------------|--------------------------------------------------|
 * |namespace       |http://opcfoundation.org/UA/                      |
 * |nodeClass       |ObjectType                                        |
 * |typedDefinition |BrokerDataSetWriterTransportType ns=0;i=21138     |
 * |isAbstract      |false                                             |
 */
export interface UABrokerDataSetWriterTransport_Base extends UADataSetWriterTransport_Base {
    queueName: UAProperty<UAString, DataType.String>;
    metaDataQueueName: UAProperty<UAString, DataType.String>;
    resourceUri: UAProperty<UAString, DataType.String>;
    authenticationProfileUri: UAProperty<UAString, DataType.String>;
    requestedDeliveryGuarantee: UAProperty<EnumBrokerTransportQualityOfService, DataType.Int32>;
    metaDataUpdateTime: UAProperty<number, DataType.Double>;
}
export interface UABrokerDataSetWriterTransport extends UADataSetWriterTransport, UABrokerDataSetWriterTransport_Base {
}


text:
// define plugin namespace

if(!Repository.Plugins) Repository.Plugins = {};

Repository.Plugins.IconView = {

	construct: function(facade) {
		this.name = Repository.I18N.IconView.name;

		this.icon = '/backend/images/silk/application_view_icons.png';
		this.numOfDisplayedModels = 12;

		// define required data uris
		this.dataUris = ["/meta"];

		arguments.callee.$.construct.apply(this, arguments); // call superclass constructor

	},

	render : function(modelData) {

		this.isRendering = true;

		if( this.myPanel ){
			this.panel.remove( this.myPanel )
		}

		var data = [];
		modelData.each(function( pair ){
			var stencilset = pair.value.type;
			// Try to display stencilset title instead of uri
			this.facade.modelCache.getModelTypes().each(function(type){
				if (stencilset == type.namespace) {
					stencilset = type.title;
					return;
				}
			}.bind(this));

			data.push( [ pair.key, pair.value.thumbnailUri + "?" + Math.random(), unescape(pair.value.title), stencilset, Repository.Helper.CutOpenID(pair.value.author, 45) || 'Unknown' ] )
		}.bind(this));

		var store = new Ext.data.SimpleStore({
	        fields	: ['id', 'icon', 'title', 'type', 'author'],
	        data	: data
	    });

	    this.myPanel = new Ext.Panel({
			border	:false,
	        items	: new DataGridPanel({store: store, listeners:{click:this._onSelectionChange.bind(this), dblclick:this._onDblClick.bind(this)}})
	    });

		this.panel.add( this.myPanel );
		this.panel.doLayout();

		this.isRendering = false;
	},

	_onSelectionChange: function(dataGrid){

		if( this.isRendering || this.isSelecting ){ return }

		var ids = [];
		// Get the selection
		dataGrid.getSelectedRecords().each(function(data){
			ids.push( data.data.id )
		})

		// Change the selection
		this.facade.changeSelection( ids );
	},

	_onDblClick: function(dataGrid, index, node, e){

		// Get the uri from the clicked model
		var id 	= dataGrid.getRecord( node ).data.id

		// Select the new range
		dataGrid.selectRange(index, index)
		this.facade.changeSelection( [id] );

		// Open the model in Editor
		this.facade.openModelInEditor(id);

	},

	selectionChanged: function(modelIds) {

		if( !this.myPanel || this.isRendering ){ return }

		var dg		= this.myPanel.items.get(0);
		var data  	= dg.store.data;

		if( dg.events.click.firing ){ return }

		this.isSelecting = true;

		var selectingIndices = [];

		data.each(function(d, index ){
			if( modelIds.include( d.data.id )){ selectingIndices.push( index ) }
		})

		dg.select( selectingIndices );

		this.isSelecting = false;
	}
};

Repository.Plugins.IconView = Repository.Core.ViewPlugin.extend(Repository.Plugins.IconView);

DataGridPanel = Ext.extend(Ext.DataView, {
	multiSelect		: true,
	//simpleSelect	: true,
    cls				: 'repository_iconview',
    itemSelector	: 'dd',
    overClass		: 'over',
	selectedClass	: 'selected',
    tpl : new Ext.XTemplate(
        '
',
			'
',
            '<tpl for=".">',
				'
',
				'

',
	            '
 30 ? values.title : "" ]}">{[ values.title.truncate(30 - (values.type.length*0.8)) ]}({type})
',
	            '
{author}
',
				'
',
            '</tpl>',
			'
',
        '
'
    )
});


text:
module MindBody
  module Services
    class Response
      attr_reader :response, :result, :status, :error_code, :xml_detail,
                  :result_count, :current_page_index, :total_page_count,
                  :remote_method, :message, :api_status

      def initialize(res)
        @response = res
        @result = {}
        normalize_response
        @api_status = APIStatus.build_status(error_code, status, message)
      end

      # Delegate methods to the @response object
      def method_missing(method, *args, &blk)
        if @response.respond_to?(method)
          self.class.send(:define_method, method) do |*args, &blk|
            @response.send(method, *args, &blk)
          end
          self.send(method)
        else
          super
        end
      end

      def respond_to?(method, include_private = false)
        super || @response.respond_to?(method)
      end

      private
      def normalize_response
        # All responses come back nested in a CallingMethodResponse
        # and then a CallingMethodResult. Strip these two parents
        # so we can get at the meat of the result. This is a naive
        # strip
        result = @response.to_hash
        result = result.flatten.last.flatten[1]

        result = normalize_hash(result)

        # Loop over result. If we respond to a key of the response, consume it,
        # otherwise build the result hash
        @result.clear
        result.each_pair do |key, value|
          if self.respond_to?(key) && key != :class
            self.instance_variable_set("@#{key}", value)
          else
            @result[key] = constantize_key(key, value)
          end
        end
      end

      # Recursively iterate over the hash and perform
      # a number of optimizations:
      #
      #   * Sometimes data comes back like this:
      #     things => {
      #       thing => [thing1, thing2, thing3]
      #     }
      #
      #     Map this pattern to be like this:
      #     things => [thing1, thing2, thing3, ...
      def normalize_hash(hash)
        hash.each_pair do |key, value|
          if value.is_a? Hash
            hash[key] = normalize_hash(value)

            key_singular = map_key(key).singularize.to_sym

            if value.has_key?(key_singular)
              hash[key] = value[key_singular]
            elsif value.has_key?(:string)
              hash[key] = value[:string]
            elsif value.has_key?(:int)
              hash[key] = value[:int]
            end
          elsif value.is_a? Array
            value.map! do |i|
              i.is_a?(Hash) ? normalize_hash(i) : i
            end
          end
        end
        return hash
      end

      def constantize_key(key, value)
        begin
          klass_s = map_key(key).classify
          klass = "MindBody::Models::#{klass_s}".constantize

          # Make sure we return a properly mapped array if needed
          value.is_a?(Array) ? value.map {|v| klass.new(v)} : klass.new(value) unless value.nil?
        rescue
          value
        end
      end

      # We have some keys that need
      # to be mapped to others so that classify works properly.
      #
      # We cannot use inflector to do this because some words are popular
      # enough to stomp on people's namespaces
      def map_key(key)
        case key
        when :staff_members, :organizer
          'staff'
        when :purchases
          'sale_item'
        when :image_url, :mobile_image_url
          'string'
        else
          key.to_s
        end
      end
    end
  end
end


text:
package org.dominokit.domino.api.server.entrypoint;

import static java.util.Objects.nonNull;

import java.util.function.Consumer;

public class CleanupTask {

  private final Consumer<CleanupTask> operation;
  private CleanupTask next;
  private Consumer<CleanupTask> completeConsumer = cleanupTask -> {};
  private final VertxContext vertxContext;

  public CleanupTask(Consumer<CleanupTask> operation, VertxContext vertxContext) {
    this.operation = operation;
    this.vertxContext = vertxContext;
  }

  public void setNext(CleanupTask next) {
    this.next = next;
  }

  public void setCompleteConsumer(Consumer<CleanupTask> completeConsumer) {
    this.completeConsumer = completeConsumer;
  }

  public Consumer<CleanupTask> getCleanUpService() {
    return operation;
  }

  public VertxContext getVertxContext() {
    return vertxContext;
  }

  public void run() {
    operation.accept(this);
  }

  public void next() {
    if (nonNull(next)) {
      next.run();
    } else {
      completeConsumer.accept(this);
    }
  }
}


text:
$:.unshift(File.dirname(__FILE__)) unless
  $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))

require 'rubygems'
require 'active_support'

require 'zanox/zanox_base'
require 'zanox/zanox_xml'
require 'zanox/zanox_json'
require 'zanox/zanox_soap'

# Module to encapsule the Zanox API.
module Zanox

  class Factory

    def Factory.get_interface(interface, version = false)
      case interface
        when 'xml'
          obj = ZanoxXml.new(version)
        when 'json'
          obj = ZanoxJson.new(version)
        when 'soap'
          obj =  ZanoxSoap.new
        else
          raise 'No such Interface!'
      end

      return obj
    end

  end

end


text:
Bare minimal header-only binary stream based on C++ file streams where the stream operator can be overloaded for your custom type.

```cpp
#include <iostream>
#include "SimpleBinStream.h"

// Testing memory stream
void TestMem()
{
    simple::mem_ostream out;
    out << 23 << 24 << "Hello world!";

    simple::mem_istream in(out.get_internal_vec());
    int num1 = 0, num2 = 0;
    std::string str;
    in >> num1 >> num2 >> str;

    cout << num1 << "," << num2 << "," << str << endl;
}

// Testing file stream
void TestFile()
{
    simple::file_ostream out("file.bin", std::ios_base::out | std::ios_base::binary);
    out << 23 << 24 << "Hello world!";
    out.flush();
    out.close();

    simple::file_istream in("file.bin", std::ios_base::in | std::ios_base::binary);
    int num1 = 0, num2 = 0;
    std::string str;
    in >> num1 >> num2 >> str;

    cout << num1 << "," << num2 << "," << str << endl;
}
```

# Version 0.9.5 Breaking Changes

Requires C++11 compiler and standard library now.

The classes are templates now.

```cpp
template<typename same_endian_type>
class file_istream {...}

template<typename same_endian_type>
class mem_istream  {...}

template<typename same_endian_type>
class ptr_istream  {...}

template<typename same_endian_type>
class file_ostream {...}

template<typename same_endian_type>
class mem_ostream  {...}
```

How to pass in same_endian_type to the class? Use std::is_same<>.

```cpp
// 1st parameter is data endian and 2 parameter is platform endian, if they are different, swap.
using same_endian_type = std::is_same<simple::BigEndian, simple::LittleEndian>;
simple::mem_ostream<same_endian_type> out;
out << (int64_t)23 << (int64_t)24 << "Hello world!";

simple::ptr_istream<same_endian_type> in(out.get_internal_vec());
int64_t num1 = 0, num2 = 0;
std::string str;
in >> num1 >> num2 >> str;

cout << num1 << "," << num2 << "," << str << endl;
```

If your data and platform shares the same endianness, you can skip the test by specifying std::true_type directly.

```cpp
simple::mem_ostream<std::true_type> out;
out << (int64_t)23 << (int64_t)24 << "Hello world!";

simple::ptr_istream<std::true_type> in(out.get_internal_vec());
int64_t num1 = 0, num2 = 0;
std::string str;
in >> num1 >> num2 >> str;

cout << num1 << "," << num2 << "," << str << endl;
```

## Advantages of compile-time check

* For same_endian_type = true_type, the swap function is a empty function which is optimised away.
* For same_endian_type = false_type, the swapping is done without any prior runtime check cost.

## Disadvantages of compile-time check

* Cannot parse file/data which is sometime different endian. I believe this scenario is rare.

Swap functions are listed below.

```cpp
enum class Endian
{
    Big,
    Little
};
using BigEndian = std::integral_constant<Endian, Endian::Big>;
using LittleEndian = std::integral_constant<Endian, Endian::Little>;

template<typename T>
void swap(T& val, std::true_type)
{
    // same endian so do nothing.
}

template<typename T>
void swap(T& val, std::false_type)
{
    std::is_arithmetic<T> is_integral_type;
    swap_if_arithmetic(val, is_integral_type);
}

template<typename T>
void swap_if_arithmetic(T& val, std::false_type)
{
    // T is not arithmetic so do nothing
}

template<typename T>
void swap_if_arithmetic(T& val, std::true_type)
{
    swap_endian<T, sizeof(T)>()(val);
}

template<typename T, size_t N>
struct swap_endian
{
    void operator()(T& ui)
    {
    }
};

template<typename T>
struct swap_endian<T, 8>
{
    void operator()(T& ui)
    {
        union EightBytes
        {
            T ui;
            uint8_t arr[8];
        };

        EightBytes fb;
        fb.ui = ui;
        // swap the endian
        std::swap(fb.arr[0], fb.arr[7]);
        std::swap(fb.arr[1], fb.arr[6]);
        std::swap(fb.arr[2], fb.arr[5]);
        std::swap(fb.arr[3], fb.arr[4]);

        ui = fb.ui;
    }
};

template<typename T>
struct swap_endian<T, 4>
{
    void operator()(T& ui)
    {
        union FourBytes
        {
            T ui;
            uint8_t arr[4];
        };

        FourBytes fb;
        fb.ui = ui;
        // swap the endian
        std::swap(fb.arr[0], fb.arr[3]);
        std::swap(fb.arr[1], fb.arr[2]);

        ui = fb.ui;
    }
};

template<typename T>
struct swap_endian<T, 2>
{
    void operator()(T& ui)
    {
        union TwoBytes
        {
            T ui;
            uint8_t arr[2];
        };

        TwoBytes fb;
        fb.ui = ui;
        // swap the endian
        std::swap(fb.arr[0], fb.arr[1]);

        ui = fb.ui;
    }
};
```

Benchmark of 0.9.7 against 0.9.5

```
   # File streams

   old::file_ostream:  359ms
   old::file_istream:  416ms
   new::file_ostream:  216ms
   new::file_istream:  328ms
new::memfile_ostream:  552ms
new::memfile_istream:   12ms

   # In-memory streams

    new::mem_ostream:  534ms
    new::mem_istream:   16ms
    new::ptr_istream:   15ms
```

[CodeProject Tutorial](http://www.codeproject.com/Tips/808776/Cplusplus-Simplistic-Binary-Streams)


text:
RSpec.describe RuboCop::Cop::Lint::SafeNavigationConsistency, :config do
  let(:cop_config) do
    { 'AllowedMethods' => %w[present? blank? try presence] }
  end

  it 'allows && without safe navigation' do
    expect_no_offenses(<<~RUBY)
      foo.bar && foo.baz
    RUBY
  end

  it 'allows || without safe navigation' do
    expect_no_offenses(<<~RUBY)
      foo.bar || foo.baz
    RUBY
  end

  it 'allows safe navigation when different variables are used' do
    expect_no_offenses(<<~RUBY)
      foo&.bar || foobar.baz
    RUBY
  end

  it 'allows calls to methods that nil responds to' do
    expect_no_offenses(<<~RUBY)
      return true if a.nil? || a&.whatever?
    RUBY
  end

  it 'registers an offense and corrects using safe navigation ' \
    'on the left of &&' do
    expect_offense(<<~RUBY)
      foo&.bar && foo.baz
      ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar && foo&.baz
    RUBY
  end

  it 'registers an offense and corrects using safe navigation ' \
    'on the right of &&' do
    expect_offense(<<~RUBY)
      foo.bar && foo&.baz
      ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar && foo&.baz
    RUBY
  end

  it 'registers an offense and corrects using safe navigation ' \
    'on the left of ||' do
    expect_offense(<<~RUBY)
      foo&.bar || foo.baz
      ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar || foo&.baz
    RUBY
  end

  it 'registers an offense and corrects using safe navigation ' \
    'on the right of ||' do
    expect_offense(<<~RUBY)
      foo.bar || foo&.baz
      ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar || foo&.baz
    RUBY
  end

  it 'registers an offense and corrects when there is code ' \
    'before or after the condition' do
    expect_offense(<<~RUBY)
      foo = nil
      foo&.bar || foo.baz
      ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
      something
    RUBY

    expect_correction(<<~RUBY)
      foo = nil
      foo&.bar || foo&.baz
      something
    RUBY
  end

  it 'registers an offense but does not correct non dot method calls' do
    expect_offense(<<~RUBY)
      foo&.zero? || foo > 5
      ^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.zero? || foo > 5
    RUBY
  end

  it 'registers an offense and corrects assignment' do
    expect_offense(<<~RUBY)
      foo&.bar && foo.baz = 1
      ^^^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar && foo&.baz = 1
    RUBY
  end

  it 'registers an offense and corrects using safe navigation ' \
    'inside of separated conditions' do
    expect_offense(<<~RUBY)
      foo&.bar && foobar.baz && foo.qux
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar && foobar.baz && foo&.qux
    RUBY
  end

  it 'registers an offense and corrects using safe navigation in conditions ' \
    'on the right hand side' do
    expect_offense(<<~RUBY)
      foobar.baz && foo&.bar && foo.qux
                    ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foobar.baz && foo&.bar && foo&.qux
    RUBY
  end

  it 'registers and corrects multiple offenses' do
    expect_offense(<<~RUBY)
      foobar.baz && foo&.bar && foo.qux && foo.foobar
                    ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foobar.baz && foo&.bar && foo&.qux && foo&.foobar
    RUBY
  end

  it 'registers an offense and corrects using unsafe navigation ' \
    'with both && and ||' do
    expect_offense(<<~RUBY)
      foo&.bar && foo.baz || foo.qux
      ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar && foo&.baz || foo&.qux
    RUBY
  end

  it 'registers an offense and corrects using unsafe navigation ' \
    'with grouped conditions' do
    expect_offense(<<~RUBY)
      foo&.bar && (foo.baz || foo.qux)
      ^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar && (foo&.baz || foo&.qux)
    RUBY
  end

  it 'registers an offense and corrects unsafe navigation that appears ' \
    'before safe navigation' do
    expect_offense(<<~RUBY)
      foo.bar && foo.baz || foo&.qux
                 ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar && foo&.baz || foo&.qux
    RUBY
  end

  it 'registers an offense and corrects using unsafe navigation ' \
    'and the safe navigation appears in a group' do
    expect_offense(<<~RUBY)
      (foo&.bar && foo.baz) || foo.qux
       ^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      (foo&.bar && foo&.baz) || foo&.qux
    RUBY
  end

  it 'registers a single offense and corrects when safe navigation is ' \
     'used multiple times' do
    expect_offense(<<~RUBY)
      foo&.bar && foo&.baz || foo.qux
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure that safe navigation is used consistently inside of `&&` and `||`.
    RUBY

    expect_correction(<<~RUBY)
      foo&.bar && foo&.baz || foo&.qux
    RUBY
  end
end


text:
import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import { uglify } from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';

const { NODE_ENV } = process.env;

const globals = {};

const external = Object.keys(globals);

const babelOptions = {
  babelrc: true,
  externalHelpers: true,
  plugins: [],
  exclude: 'node_modules/**'
};

const plugins = [
  babel(babelOptions),
  resolve(),
  commonjs()
];

if (NODE_ENV === 'production') {
  plugins.push(uglify({}, minify));
}

export default {
  input: 'src/index.umd.js',
  output: {
    name: 'dissemination',
    file: `dist/dissemination${NODE_ENV === 'production' ? '.min' : ''}.js`,
    format: 'umd',
    globals
  },
  external,
  plugins
};


text:
package models

import (
	"os"
	"path/filepath"
	"testing"

	"code.gitea.io/gitea/models/unittest"
	"code.gitea.io/gitea/modules/util"

	"github.com/stretchr/testify/assert"
)

func TestFixtureGeneration(t *testing.T) {
	assert.NoError(t, unittest.PrepareTestDatabase())

	test := func(gen func() (string, error), name string) {
		expected, err := gen()
		if !assert.NoError(t, err) {
			return
		}
		bytes, err := os.ReadFile(filepath.Join(unittest.FixturesDir(), name+".yml"))
		if !assert.NoError(t, err) {
			return
		}
		data := string(util.NormalizeEOL(bytes))
		assert.True(t, data == expected, "Differences detected for %s.yml", name)
	}

	test(GetYamlFixturesAccess, "access")
}


text:
<?php

final class FileCreateMailReceiver extends PhabricatorMailReceiver {

  public function isEnabled() {
    $app_class = 'PhabricatorFilesApplication';
    return PhabricatorApplication::isClassInstalled($app_class);
  }

  public function canAcceptMail(PhabricatorMetaMTAReceivedMail $mail) {
    $files_app = new PhabricatorFilesApplication();
    return $this->canAcceptApplicationMail($files_app, $mail);
  }

  protected function processReceivedMail(
    PhabricatorMetaMTAReceivedMail $mail,
    PhabricatorUser $sender) {

    $attachment_phids = $mail->getAttachments();
    if (empty($attachment_phids)) {
      throw new PhabricatorMetaMTAReceivedMailProcessingException(
        MetaMTAReceivedMailStatus::STATUS_UNHANDLED_EXCEPTION,
        'Ignoring email to create files that did not include attachments.');
    }
    $first_phid = head($attachment_phids);
    $mail->setRelatedPHID($first_phid);

    $attachment_count = count($attachment_phids);
    if ($attachment_count > 1) {
      $subject = pht('You successfully uploaded %d files.', $attachment_count);
    } else {
      $subject = pht('You successfully uploaded a file.');
    }
    $subject_prefix =
      PhabricatorEnv::getEnvConfig('metamta.files.subject-prefix');

    $file_uris = array();
    foreach ($attachment_phids as $phid) {
      $file_uris[] =
        PhabricatorEnv::getProductionURI('/file/info/'.$phid.'/');
    }

    $body = new PhabricatorMetaMTAMailBody();
    $body->addRawSection($subject);
    $body->addTextSection(pht('FILE LINKS'), implode("\n", $file_uris));

    id(new PhabricatorMetaMTAMail())
      ->addTos(array($sender->getPHID()))
      ->setSubject($subject)
      ->setSubjectPrefix($subject_prefix)
      ->setFrom($sender->getPHID())
      ->setRelatedPHID($first_phid)
      ->setBody($body->render())
      ->saveAndSend();
  }

}


text:
import org.scalatest.FlatSpec
import org.scalatest.matchers.MustMatchers
import java.io.File

class CheckSetupCleanup extends FlatSpec with MustMatchers
{
	val f = new File("setup")
	"setup file" must "exist" in {
		assert(f.exists, "Setup file didn't exist: " + f.getAbsolutePath)
		f.delete()
	}

	val t = new File("tested")
	"cleanup file" must "not exist" in {
		assert(!t.exists, "Cleanup file already existed: " + t.getAbsolutePath)
		t.createNewFile()
	}
}


text:
package org.apache.activemq.protobuf.compiler;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class EnumDescriptor implements TypeDescriptor {

    private String name;
    private Map<String,EnumFieldDescriptor> fields= new LinkedHashMap<String, EnumFieldDescriptor>();
    private final ProtoDescriptor protoDescriptor;
    private final MessageDescriptor parent;
    private Map<String, OptionDescriptor> options = new LinkedHashMap<String, OptionDescriptor>();

    public EnumDescriptor(ProtoDescriptor protoDescriptor, MessageDescriptor parent) {
        this.protoDescriptor = protoDescriptor;
        this.parent = parent;
    }

    public String getName() {
        return name;
    }

    public Map<String,EnumFieldDescriptor> getFields() {
        return fields;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setFields(Map<String,EnumFieldDescriptor> fields) {
        this.fields = fields;
    }
    public ProtoDescriptor getProtoDescriptor() {
        return protoDescriptor;
    }

    private String getOption(Map<String, OptionDescriptor> options, String optionName, String defaultValue) {
        OptionDescriptor optionDescriptor = options.get(optionName);
        if (optionDescriptor == null) {
            return defaultValue;
        }
        return optionDescriptor.getValue();
    }

    private String constantToUCamelCase(String name) {
        boolean upNext=true;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if( Character.isJavaIdentifierPart(c) && Character.isLetterOrDigit(c)) {
                if( upNext ) {
                    c = Character.toUpperCase(c);
                    upNext=false;
                } else {
                    c = Character.toLowerCase(c);
                }
                sb.append(c);
            } else {
                upNext=true;
            }
        }
        return sb.toString();
    }

    public void validate(List<String> errors) {
        String createMessage = getOption(getOptions(), "java_create_message", null);
        if( "true".equals(createMessage) ) {
            for (EnumFieldDescriptor field : getFields().values()) {
                String type = constantToUCamelCase(field.getName());

                TypeDescriptor typeDescriptor=null;
                // Find the type def for that guy..
                if( parent!=null ) {
                    typeDescriptor = parent.getType(type);
                }
                if( typeDescriptor == null ) {
                    typeDescriptor = protoDescriptor.getType(type);
                }
                if( typeDescriptor == null ) {
                    errors.add("ENUM constant '"+field.getName()+"' did not find expected associated message: "+type);
                } else {
                    field.associate(typeDescriptor);
                    typeDescriptor.associate(field);
                }
            }
        }
    }

    public MessageDescriptor getParent() {
        return parent;
    }

    public String getQName() {
        if( parent==null ) {
            return name;
        } else {
            return parent.getQName()+"."+name;
        }
    }

    public boolean isEnum() {
        return true;
    }

    public Map<String, OptionDescriptor> getOptions() {
        return options;
    }

    public void setOptions(Map<String, OptionDescriptor> options) {
        this.options = options;
    }

    public void associate(EnumFieldDescriptor desc) {
        throw new RuntimeException("not supported.");
    }

}


text:
using illNES.CPU.Types;
using System.Collections.Generic;

namespace illNES.CPU
{
    public partial class Mos6502 : IMos6502
    {
        private readonly IMemoryInterface _m;

        private IList<Operation> _ops;

        /// <inheritdoc />
        public byte A { get; internal set; }

        /// <inheritdoc />
        public byte X { get; internal set; }

        /// <inheritdoc />
        public byte Y { get; internal set; }

        /// <inheritdoc />
        public byte S { get; internal set; } = 0xff; //Init the stack pointer to 255, since it works backwards.

        /// <inheritdoc />
        public ushort PC { get; internal set; } = 0xfffc; // Initialise to the reset vector

        /// <inheritdoc />
        public PFlags P { get; internal set; } = PFlags.R | PFlags.I; //the Always 1 flag is set, and we set Interrupt disable at power on

        //Internal state bits
        private bool _reset = true; //start in reset, means we can execute bootstrap as a reset ;)
        private bool _nmi;
        private bool _irq;
        private bool _xPage;
        private int _skipCycles;

        public Mos6502(IMemoryInterface m)
        {
            _m = m;

            //Build a lookup table of all our ops
            _ops = BuildInstructionSet();
        }

        /// <inheritdoc />
        public void Tick()
        {
            //Only actually tick if we are not skipping cycles
            if (_skipCycles == 0)
            {
                var op = _ops[_m.Read(PC)]; //get the op for the code stored at PC

                // check for interrupts and implement them as a BRK op
                if (_reset || _nmi || _irq && !P.HasFlag(PFlags.I)) //IRQ requires the interrupt flag to be off, the others don't
                    op = _ops[0];

                // Handle addressing mode
                var address = GetAddress(op.Mode);

                PC += op.Length; //increment PC by the expected amount, as GetAddress() has read the op params

                _skipCycles += Exec(op, address);
            }

            //Decrement after the tick (if any) since Exec() will have set the appropriate skip value
            _skipCycles--;

            //At the end of any cycle in which reset was true, set it to false,
            //as we will have performed the reset by now.
            _reset = false;
        }

        /// <summary>
        /// Execute an instruction
        /// </summary>
        /// <param name="op">The Operation containing the instruction details</param>
        /// <param name="address">The address</param>
        /// <returns>The number of cycles the Operation "took"</returns>
        private int Exec(Operation op, ushort address)
        {
            op.Exec(op.Mode, address, 0); //TODO calculate value
            return op.Cycles;
        }

        /// <summary>
        /// Gets the actual memory address for an Operation, based on its addressing mode.
        /// </summary>
        /// <param name="mode">The addressing mode</param>
        /// <returns>The address</returns>
        private ushort GetAddress(AddressModes mode)
        {
            ushort address = 0;

            //set the offset value to X or Y reg ahead of time, even if we don't need it
            byte offset = mode.HasFlag(AddressModes.OffsetY) ? Y : X;

            //conditionally execute addressing stages in order
            if (mode.HasFlag(AddressModes.SetParamAddress))
                address = (ushort)((PC + 1) & ushort.MaxValue);

            if (mode.HasFlag(AddressModes.ReadByte))
                address = _m.Read(address);

            if (mode.HasFlag(AddressModes.ReadWord))
                address = _m.ReadWord(address);

            if (mode.HasFlag(AddressModes.CheckWrap))
                if ((address + offset) > (address | byte.MaxValue))
                    _xPage = true;

            if (mode.HasFlag(AddressModes.Offset))
                address = (ushort)((address + offset) & ushort.MaxValue);

            if (mode.HasFlag(AddressModes.ByteWrapAddress))
                address = (ushort)(address & byte.MaxValue);

            if (mode.HasFlag(AddressModes.ReadWordLate))
                address = _m.ReadWord(address);

            return (ushort)(address & ushort.MaxValue); //safety wrap
        }

        /// <inheritdoc />
        public string DumpRegisters()
        {
            throw new System.NotImplementedException();
        }

        /// <summary>
        /// Checks a register's byte value for Zero or Negative,
        /// and sets the flags if necessary.
        /// These two flags are commonly checked together.
        /// </summary>
        /// <param name="value">the byte value to check</param>
        public void CheckFlagsZN(byte value)
        {
            P &= ~PFlags.N & ~PFlags.Z; //clear both flags first
            if (value == 0) P |= PFlags.Z; //Set Zero
            if (value >= 128) P |= PFlags.N; //Set Negative
        }
    }
}


text:
package ds.framework.v4.db;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.database.DatabaseUtils.InsertHelper;
import android.database.sqlite.SQLiteAbortException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteStatement;

import java.util.HashMap;

import ds.framework.v4.common.Debug;
import ds.framework.v4.db.Table.Column;

public class JSONToDbHelper {

    public static final long ERROR = -2;
    public static final long NO_ID = -1;

    private Column[] mColumns;
    private int mColumnCount;
    private SQLiteStatement mInsertStatement;
    private SQLiteStatement mUpdateStatement;

    /**
     * currently only supporting insert or update
     * TODO: add type parameter to control if insert/update/replace
     *
     * @param table
     * @param row
     */
	public void createStatement(Table table, JSONObject row, Db db) {
// Debug.logD("JSONToDbHelper", "createStatement for table: " + table);
		Column[] columns = table.getColumns();

		mColumnCount = 0;

        String columnNames = "";
        String insertUniqueNames = "";
        String insertQmarks = "";
        String updateWhere = "";
        String updateSet = "";
        boolean hasUnique = false;

		for(Column column : columns) {
            if ((column.type & Table.JOINED_TABLE) > 0 || !row.has(column.name)) {
                continue;
            }

            ++mColumnCount;
        }

        mColumns = new Column[mColumnCount];

        int next = 0;
        int last = mColumnCount;

        for(Column column : columns) {
            if ((column.type & Table.JOINED_TABLE) > 0 || !row.has(column.name)) {
                continue;
            }

            insertQmarks += ",?";

            if ((column.type & (Table.UNIQUE | Table.PRIMARY)) == 0) {
                columnNames += "," + column.name;
                updateSet += ", " + column.name + " = ? ";
                mColumns[next++] = column;
            } else {
                hasUnique = true;
                insertUniqueNames = ", " + column.name + insertUniqueNames;
                updateWhere = ", " + column.name + " = ? " + updateWhere;

                // update where columns go to the end for easier bind
                mColumns[--last] = column;
            }
		}

        if (columnNames.length() > 0) {
            columnNames += insertUniqueNames;
        } else {
            columnNames = insertUniqueNames;
        }

        mInsertStatement = db.getSQLiteStatement("INSERT OR ABORT INTO " + table.getName()
                + " (" + columnNames.substring(1) + ") VALUES (" + insertQmarks.substring(1) + ")");

        if (hasUnique) {
            mUpdateStatement = db.getSQLiteStatement("UPDATE " + table.getName() + " SET " +
                    updateSet.substring(1) + " WHERE " + updateWhere.substring(1));
        } else {
            mUpdateStatement = null;
        }
	}

    /**
     *
     * @param table
     * @param row
     * @param lJSONToDbValueInterface
     * @return
     */
	public long bind(Table table, JSONObject row,
			JSONToDbValueInterface lJSONToDbValueInterface) {

        return bind(table, row, lJSONToDbValueInterface, false);
    }

    /**
     *
     * @param table
     * @param row
     * @param lJSONToDbValueInterface
     * @param implicitOverrideNull
     * @return
     */
    public long bind(Table table, JSONObject row,
                    JSONToDbValueInterface lJSONToDbValueInterface, boolean implicitOverrideNull) {

        // in case previous one was simple insert
        if (mUpdateStatement != null) {
            mUpdateStatement.clearBindings();
        }

		long id = NO_ID;

		Object value = null;
		int type;

		// set values for columns
		for(int i = 0; i < mColumnCount; ++i) {
			try {
				if (mColumns[i] == null) {
					continue;
				}
				if (((!row.has(mColumns[i].name) && implicitOverrideNull) || row.isNull(mColumns[i].name)) && (mColumns[i].type & Table.NULL) > 0) {
					mInsertStatement.bindNull(i + 1);
                    if (mUpdateStatement != null) {
                        mUpdateStatement.bindNull(i + 1);
                    }
// Debug.logD("JSONToDb", "binding null for " + mColumns[i].name);
					continue;
				}
                if (!row.has(mColumns[i].name)) {
                    continue;
                }

				type = mColumns[i].type & Table.TYPE_MASK;

                value = row.get(mColumns[i].name);

				if (lJSONToDbValueInterface != null) {
					try {
						value = lJSONToDbValueInterface.beforeInsert(table.getName(), mColumns[i].name, value);
					} catch(Exception  e) {
						android.util.Log.e("OnValueInsertListener", "Bad value! (" + e.getMessage() + ")");
						if (type == Table.TEXT) {

							// minor ? problem
							value = "";
						} else {
							throw(e);
						}
					}
				}

				switch(type) {
                    case Table.INTEGER:
                        if (value instanceof String) {
                            value = Long.parseLong((String) value);
                        } else if (value instanceof Integer) {
                            value = new Long((Integer) value);
                        }
                        if (mColumns[i].name.equals("id")) {

                            // id for joined tables
                            id = (long) value;
                        }
                        mInsertStatement.bindLong(i + 1, (long) value);
                        if (mUpdateStatement != null) {
                            mUpdateStatement.bindLong(i + 1, (long) value);
                        }
                        break;

                    case Table.BOOLEAN:
                        value = (value instanceof Boolean) ? ((Boolean) value ? 1l : 0l) : (Long) value;
                        mInsertStatement.bindLong(i + 1, (long) value);
                        if (mUpdateStatement != null) {
                            mUpdateStatement.bindLong(i + 1, (long) value);
                        }
                        break;

                    case Table.REAL:
                        try {
                            mInsertStatement.bindDouble(i + 1, (double) value);
                            if (mUpdateStatement != null) {
                                mUpdateStatement.bindDouble(i + 1, (double) value);
                            }
                        } catch(ClassCastException e) {
                            if (value instanceof String && ((String) value).length() == 0) {
                                value = 0.0d;
                                mInsertStatement.bindDouble(i + 1, (double) value);
                                if (mUpdateStatement != null) {
                                    mUpdateStatement.bindDouble(i + 1, (double) value);
                                }
                            } else {
                                mInsertStatement.bindDouble(i + 1, Double.valueOf((String) value));
                                if (mUpdateStatement != null) {
                                    mUpdateStatement.bindDouble(i + 1, Double.valueOf((String) value));
                                }
                            }
                        }
                        break;

                    default:

                        // this way it can either be a string, a jsonobject, etc...
                        mInsertStatement.bindString(i + 1, value.toString());
                        if (mUpdateStatement != null) {
                            mUpdateStatement.bindString(i + 1, value.toString());
                        }
                        break;
				}

// Debug.logD("JSONToDb", "binded " + value + " for " + mColumns[i].name);

			} catch (Exception e) {
				if ((mColumns[i].type & Table.NULL) > 0) {
                    mInsertStatement.bindNull(i + 1);
                    if (mUpdateStatement != null) {
                        mUpdateStatement.bindNull(i + 1);
                    }
// Debug.logD("JSONToDb", "binding null for " + mColumns[i].name);
					continue;
				}

                Debug.logException(e);

				String valStr;

				try {
					valStr = String.valueOf(value);
				} catch(Exception e2) {
					valStr = "unknown";
				}

				android.util.Log.e("Bad data format", "table: " + table.getName() + " / column: " + mColumns[i].name + " / value: " + valStr);
				android.util.Log.e("Bad data format (raw)", row.toString());
			}
		}

		return id;
	}

    /**
     * execute insert or update
     * TODO: add type parameter to control if insert/update/replace
     *
     * @return last inserted id for insert, 0 for update, ERROR (-1) for error
     */
    public long execute() throws SQLiteException {
        long ret = NO_ID;
        try {
            ret = mInsertStatement.executeInsert();
        } catch (SQLiteException e) {
            if (mUpdateStatement != null) {
                ret = mUpdateStatement.executeUpdateDelete() == 0 ? ERROR : 0;
            } else {
                throw e;
            }
        }
        return ret;
    }

	/**
	 *
	 * @param db
	 * @param tableName
	 * @param ids
	 * @param lJSONtoDbValueInterface
	 */
	public void deleteById(Db db, String tableName, int ids[], JSONToDbValueInterface lJSONtoDbValueInterface) {

		// delete from main table
		if (lJSONtoDbValueInterface != null) {
			ids = lJSONtoDbValueInterface.beforeDelete(tableName, ids);
		}
		db.delete(tableName, new Condition("id", ids).toString());

		// delete from joined tables
		for(Column column : db.getTableByName(tableName).getColumns()) {
			if ((column.type & Table.JOINED_TABLE) == 0) {
				continue;
			}
			db.delete(column.name, new Condition(tableName + "_id", ids).toString());
		}
	}

	public interface JSONToDbValueInterface {
		public Object beforeInsert(String tableName, String column, Object value);
		public int[] beforeDelete(String tableName, int[] ids);
	}
}


text:
<?php

namespace Backend\Core\Engine\Base;

use Backend\Core\Engine\Model;
use Common\Exception\RedirectException;
use ForkCMS\App\KernelLoader;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Backend\Core\Engine\Authentication as BackendAuthentication;
use Backend\Core\Engine\Header;
use Backend\Core\Engine\TwigTemplate;

/**
 * This is the base-object for widgets
 */
class Widget extends KernelLoader
{
    /**
     * The column wherein the widget should be shown
     *
     * @var string
     */
    private $column = 'left';

    /**
     * The header object
     *
     * @var Header
     */
    protected $header;

    /**
     * The position in the column where the widget should be shown
     *
     * @var int
     */
    private $position = 0;

    /**
     * Required rights needed for this widget.
     *
     * @var array
     */
    protected $rights = [];

    /**
     * The template to use
     *
     * @var string
     */
    private $templatePath;

    /**
     * A reference to the current template
     *
     * @var TwigTemplate
     */
    protected $template;

    /**
     * The constructor will set some properties, it populates the parameter array with urldecoded
     * values for ease of use.
     *
     * @param KernelInterface $kernel
     */
    public function __construct(KernelInterface $kernel)
    {
        parent::__construct($kernel);

        $this->template = $this->getContainer()->get('template');
        $this->header = $this->getContainer()->get('header');
    }

    /**
     * Display, this wil output the template to the browser
     * If no template is specified we build the path form the current module and action
     *
     * @param string $template The template to use.
     */
    protected function display(string $template = null): void
    {
        if ($template !== null) {
            $this->templatePath = (string) $template;
        }
    }

    public function getColumn(): string
    {
        return $this->column;
    }

    public function getPosition(): int
    {
        return $this->position;
    }

    public function getTemplatePath(): ?string
    {
        return $this->templatePath;
    }

    /**
     * Is this widget allowed for this user?
     *
     * @return bool
     */
    public function isAllowed(): bool
    {
        foreach ($this->rights as $rights) {
            [$module, $action] = explode('/', $rights);

            // check action rights
            if ($module !== '' &&  $action !== '' && !BackendAuthentication::isAllowedAction($action, $module)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Set column for the widget
     *
     * @param string $column Possible values are: left, middle, right.
     */
    protected function setColumn(string $column): void
    {
        $allowedColumns = ['left', 'middle', 'right'];
        $this->column = \SpoonFilter::getValue($column, $allowedColumns, 'left');
    }

    protected function setPosition(int $position): void
    {
        $this->position = $position;
    }

    /**
     * Redirect to a given URL
     *
     * @param string $url The URL whereto will be redirected.
     * @param int $code The redirect code, default is 302 which means this is a temporary redirect.
     *
     * @throws RedirectException
     */
    public function redirect(string $url, int $code = Response::HTTP_FOUND): void
    {
        throw new RedirectException('Redirect', new RedirectResponse($url, $code));
    }

    public function execute(): void
    {
        // placeholder
    }

    /**
     * Get the request from the container.
     *
     * @return Request
     */
    public function getRequest(): Request
    {
        return Model::getRequest();
    }
}


text:
{% extends "zinnia/base.html" %}
{% load i18n zinnia_tags %}

{% block content %}

    {% block content-title %}
        {% if category %}

{% blocktrans %}{{ category }}{% endblocktrans %}

            {% if category.description %}

{{ category.description|striptags|safe }}

            {% endif %}
        {% else %}

{% trans "News" %}

        {% endif %}
    {% endblock %}

    {% block content-loop %}
        {% for object in object_list %}
        {% include object.content_template with object_content=object.html_content|truncatewords_html:100|safe continue_reading=1 %}
        {% if not forloop.last %}
{% endif %}
        {% empty %}

            {% trans "No entries yet." %}

        {% endfor %}
    {% endblock %}

    {% block content-pagination %}
        {% if is_paginated %}
        {% zinnia_pagination page_obj %}
        {% endif %}
    {% endblock %}

    {% block content-related %}{% endblock %}

{% endblock %}


text:
package org.rakam.cache.hazelcast.treemap;

import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;

import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by buremba <Burak Emre Kabakcı> on 15/07/14 20:05.
 */

public final class Counter implements Comparable<Counter>, DataSerializable, Serializable {
    public String id;
    public AtomicLong counter;

    Counter(String id, long counter) {
        this.id = id;
        this.counter = new AtomicLong(counter);
    }

    Counter(String id) {
        this.id = id;
        this.counter = new AtomicLong(0);
    }

    public long increment() {
        return counter.incrementAndGet();
    }

    public long get() {
        return counter.get();
    }

    public long incrementBy(long l) {
        return counter.addAndGet(l);
    }

    public boolean equals(Object obj) {
        if(obj instanceof Counter)
            return ((Counter) obj).id.equals(id);
        else
            return false;
    }

    @Override
    public int compareTo(Counter counter) {
        if(counter.id.equals(id))
            return 0;
        int gap = counter.counter.intValue() - this.counter.intValue();
        return gap>=0 ? gap+1 :gap-1;
    }

    public String toString() {
        return "Counter {id: "+id+", counter: "+counter+"}";
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        out.writeUTF(id);
        out.writeLong(counter.longValue());
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        id = in.readUTF();
        counter = new AtomicLong(in.readLong());
    }
}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.payments;

import android.app.ProgressDialog;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Pair;

import androidx.annotation.IntDef;
import androidx.annotation.Nullable;

import org.chromium.base.Callback;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.autofill.PersonalDataManager;
import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile;
import org.chromium.chrome.browser.autofill.PersonalDataManager.GetSubKeysRequestDelegate;
import org.chromium.chrome.browser.autofill.PhoneNumberUtil;
import org.chromium.chrome.browser.autofill.prefeditor.EditorBase;
import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel;
import org.chromium.chrome.browser.autofill.prefeditor.EditorFieldModel.EditorFieldValidator;
import org.chromium.chrome.browser.autofill.prefeditor.EditorModel;
import org.chromium.chrome.browser.autofill.settings.AutofillProfileBridge;
import org.chromium.chrome.browser.autofill.settings.AutofillProfileBridge.AddressField;
import org.chromium.chrome.browser.autofill.settings.AutofillProfileBridge.AddressUiComponent;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.payments.mojom.AddressErrors;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * An address editor. Can be used for either shipping or billing address editing.
 */
public class AddressEditor
        extends EditorBase<AutofillAddress> implements GetSubKeysRequestDelegate {
    @IntDef({Purpose.PAYMENT_REQUEST, Purpose.AUTOFILL_SETTINGS, Purpose.AUTOFILL_ASSISTANT})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Purpose {
        int PAYMENT_REQUEST = 1;
        int AUTOFILL_SETTINGS = 2;
        int AUTOFILL_ASSISTANT = 3;
    }

    private final Handler mHandler = new Handler();
    private final Map<Integer, EditorFieldModel> mAddressFields = new HashMap<>();
    private final Set<CharSequence> mPhoneNumbers = new HashSet<>();
    private final PhoneNumberUtil.CountryAwareFormatTextWatcher mPhoneFormatter;
    private final CountryAwarePhoneNumberValidator mPhoneValidator;
    @Purpose
    private final int mPurpose;
    private final boolean mSaveToDisk;
    @Nullable
    private AutofillProfileBridge mAutofillProfileBridge;
    @Nullable
    private EditorFieldModel mCountryField;
    @Nullable
    private EditorFieldModel mPhoneField;
    @Nullable
    private EditorFieldModel mEmailField;
    @Nullable
    private List<AddressUiComponent> mAddressUiComponents;
    private boolean mAdminAreasLoaded;
    private String mRecentlySelectedCountry;
    private Runnable mCountryChangeCallback;
    private AutofillProfile mProfile;
    private EditorModel mEditor;
    private ProgressDialog mProgressDialog;
    @Nullable
    private AddressErrors mAddressErrors;

    /**
     * Builds an address editor.
     *
     * @param purpose    The purpose of this address editor. One of Purpose.PAYMENT_REQUEST,
     *                   Purpose.AUTOFILL_SETTINGS, or Purpose.AUTOFILL_ASSISTANT.
     * @param saveToDisk Whether to save changes to disk after editing.
     */
    public AddressEditor(@Purpose int purpose, boolean saveToDisk) {
        mPhoneFormatter = new PhoneNumberUtil.CountryAwareFormatTextWatcher();
        mPhoneValidator = new CountryAwarePhoneNumberValidator();
        mPurpose = purpose;
        mSaveToDisk = saveToDisk;
    }

    /**
     * Adds the given phone number to the autocomplete set, if it's valid.
     * Note that here we consider all non-null and non-empty numbers as valid
     * since we are doing strict validation of Autofill data.
     *
     * @param phoneNumber The phone number to possibly add.
     */
    public void addPhoneNumberIfValid(@Nullable CharSequence phoneNumber) {
        if (!TextUtils.isEmpty(phoneNumber)) mPhoneNumbers.add(phoneNumber.toString());
    }

    /**
     * Sets the address errors to indicate error messages from merchant's retry() call.
     *
     * @param errors The address errors from merchant's retry() call.
     */
    public void setAddressErrors(@Nullable AddressErrors errors) {
        mAddressErrors = errors;
    }

    private String getAddressError(int field) {
        if (mAddressErrors == null) return null;

        switch (field) {
            case AddressField.COUNTRY:
                return mAddressErrors.country;
            case AddressField.ADMIN_AREA:
                return mAddressErrors.region;
            case AddressField.LOCALITY:
                return mAddressErrors.city;
            case AddressField.DEPENDENT_LOCALITY:
                return mAddressErrors.dependentLocality;
            case AddressField.SORTING_CODE:
                return mAddressErrors.sortingCode;
            case AddressField.POSTAL_CODE:
                return mAddressErrors.postalCode;
            case AddressField.STREET_ADDRESS:
                return mAddressErrors.addressLine;
            case AddressField.ORGANIZATION:
                return mAddressErrors.organization;
            case AddressField.RECIPIENT:
                return mAddressErrors.recipient;
        }
        assert false : "Unrecognized address field code";
        return null;
    }

    /**
     * Allows calling |edit| with a single callback used for both 'done' and 'cancel'.
     * @see #edit(AutofillAddress, Callback, Callback)
     */
    public void edit(
            @Nullable final AutofillAddress toEdit, final Callback<AutofillAddress> callback) {
        edit(toEdit, callback, callback);
    }

    /**
     * Builds and shows an editor model with the following fields.
     *
     * [ country dropdown   ] <----- country dropdown is always present.
     * [ an address field   ] \
     * [ an address field   ]  \
     *         ...               <-- field order, presence, required, and labels depend on country.
     * [ an address field   ]  /
     * [ an address field   ] /
     * [ phone number field ] <----- phone is always present and required.
     */
    @Override
    public void edit(@Nullable final AutofillAddress toEdit,
            final Callback<AutofillAddress> doneCallback,
            final Callback<AutofillAddress> cancelCallback) {
        super.edit(toEdit, doneCallback, cancelCallback);

        if (mAutofillProfileBridge == null) mAutofillProfileBridge = new AutofillProfileBridge();

        // If |toEdit| is null, we're creating a new autofill profile with the country code of the
        // default locale on this device.
        boolean isNewAddress = toEdit == null;

        // Ensure that |address| and |mProfile| are always not null.
        final AutofillAddress address =
                isNewAddress ? new AutofillAddress(mContext, new AutofillProfile()) : toEdit;
        mProfile = address.getProfile();

        // The title of the editor depends on whether we're adding a new address or editing an
        // existing address.
        mEditor =
                new EditorModel(isNewAddress ? mContext.getString(R.string.autofill_create_profile)
                                             : toEdit.getEditTitle());

        // When edit is called, a new form is started, so the country on the
        // dropdown list is not changed. => mRecentlySelectedCountry should be null.
        mRecentlySelectedCountry = null;

        // The country dropdown is always present on the editor.
        if (mCountryField == null) {
            mCountryField = EditorFieldModel.createDropdown(
                    mContext.getString(R.string.autofill_profile_editor_country),
                    AutofillProfileBridge.getSupportedCountries(),
                    null /* hint */);
        }

        // Changing the country will update which fields are in the model. The actual fields are not
        // discarded, so their contents are preserved.
        mCountryField.setDropdownCallback(new Callback<Pair<String, Runnable>>() {
            /**
             * If the selected country on the country dropdown list is changed,
             * the first element of eventData is the recently selected dropdown key,
             * the second element is the callback to invoke for when the dropdown
             * change has been processed.
             */
            @Override
            public void onResult(Pair<String, Runnable> eventData) {
                mEditor.removeAllFields();
                showProgressDialog();
                mRecentlySelectedCountry = eventData.first;
                mPhoneFormatter.setCountryCode(mRecentlySelectedCountry);
                mPhoneValidator.setCountryCode(mRecentlySelectedCountry);
                mCountryChangeCallback = eventData.second;
                loadAdminAreasForCountry(mRecentlySelectedCountry);
            }
        });

        // Country dropdown is cached, so the selected item needs to be updated for the new profile
        // that's being edited. This will not fire the dropdown callback.
        mCountryField.setValue(AutofillAddress.getCountryCode(mProfile));

        // Phone number validator and formatter are cached, so their contry code needs to be updated
        // for the new profile that's being edited.
        assert mCountryField.getValue() != null;
        mPhoneValidator.setCountryCode(mCountryField.getValue().toString());
        mPhoneFormatter.setCountryCode(mCountryField.getValue().toString());

        // There's a finite number of fields for address editing. Changing the country will re-order
        // and relabel the fields. The meaning of each field remains the same.
        if (mAddressFields.isEmpty()) {
            // City, dependent locality, and organization don't have any special formatting hints.
            mAddressFields.put(AddressField.LOCALITY, EditorFieldModel.createTextInput());
            mAddressFields.put(AddressField.DEPENDENT_LOCALITY, EditorFieldModel.createTextInput());
            mAddressFields.put(AddressField.ORGANIZATION, EditorFieldModel.createTextInput());

            // Sorting code and postal code (a.k.a. ZIP code) should show both letters and digits on
            // the keyboard, if possible.
            mAddressFields.put(AddressField.SORTING_CODE, EditorFieldModel.createTextInput(
                    EditorFieldModel.INPUT_TYPE_HINT_ALPHA_NUMERIC));
            mAddressFields.put(AddressField.POSTAL_CODE, EditorFieldModel.createTextInput(
                    EditorFieldModel.INPUT_TYPE_HINT_ALPHA_NUMERIC));

            // Street line field can contain \n to indicate line breaks.
            mAddressFields.put(AddressField.STREET_ADDRESS, EditorFieldModel.createTextInput(
                    EditorFieldModel.INPUT_TYPE_HINT_STREET_LINES));

            // Android has special formatting rules for names.
            mAddressFields.put(AddressField.RECIPIENT, EditorFieldModel.createTextInput(
                    EditorFieldModel.INPUT_TYPE_HINT_PERSON_NAME));
        }

        // Phone number is present and required for all countries.
        if (mPhoneField == null) {
            mPhoneField = EditorFieldModel.createTextInput(EditorFieldModel.INPUT_TYPE_HINT_PHONE,
                    mContext.getString(R.string.autofill_profile_editor_phone_number),
                    mPhoneNumbers, mPhoneFormatter, mPhoneValidator, null /* valueIconGenerator */,
                    mContext.getString(R.string.pref_edit_dialog_field_required_validation_message),
                    mContext.getString(R.string.payments_phone_invalid_validation_message),
                    null /* value */);
        }

        // Phone number field is cached, so its value needs to be updated for every new profile
        // that's being edited.
        mPhoneField.setValue(mProfile.getPhoneNumber());

        // Email address is present for autofill settings and autofill assistant.
        if (mPurpose != Purpose.PAYMENT_REQUEST) {
            if (mEmailField == null) {
                mEmailField = EditorFieldModel.createTextInput(
                        EditorFieldModel.INPUT_TYPE_HINT_EMAIL,
                        mContext.getString(R.string.autofill_profile_editor_email_address),
                        null /* suggestions */, null /* formatter */, null /* validator */,
                        null /* valueIconGenerator */, null /* requiredErrorMessage */,
                        mContext.getString(R.string.payments_email_invalid_validation_message),
                        null /* value */);
            }
            // Retrieve and set the email address field.
            mEmailField.setValue(mProfile.getEmailAddress());
        }

        // If the user clicks [Cancel], send |toEdit| address back to the caller, which was the
        // original state (could be null, a complete address, a partial address).
        mEditor.setCancelCallback(() -> {
            // This makes sure that onSubKeysReceived returns early if it's
            // ever called when Cancel has already occurred.
            mAdminAreasLoaded = true;
            PersonalDataManager.getInstance().cancelPendingGetSubKeys();
            cancelCallback.onResult(toEdit);
        });

        // If the user clicks [Done], save changes on disk, mark the address "complete," and send it
        // back to the caller.
        mEditor.setDoneCallback(() -> {
            mAdminAreasLoaded = true;
            PersonalDataManager.getInstance().cancelPendingGetSubKeys();
            commitChanges(mProfile);
            address.completeAddress(mProfile);
            doneCallback.onResult(address);
        });

        loadAdminAreasForCountry(mCountryField.getValue().toString());
        if (mAddressErrors != null) mEditorDialog.validateForm();
    }

    private void showProgressDialog() {
        mProgressDialog = new ProgressDialog(mContext);
        mProgressDialog.setMessage(mContext.getText(R.string.payments_loading_message));
        mProgressDialog.show();
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }

    /** Saves the edited profile on disk. */
    private void commitChanges(AutofillProfile profile) {
        // Country code and phone number are always required and are always collected from the
        // editor model.
        profile.setCountryCode(mCountryField.getValue().toString());
        profile.setPhoneNumber(mPhoneField.getValue().toString());
        if (mEmailField != null) profile.setEmailAddress(mEmailField.getValue().toString());

        // Autofill profile bridge normalizes the language code for the autofill profile.
        profile.setLanguageCode(mAutofillProfileBridge.getCurrentBestLanguageCode());

        // Collect data from all visible fields and store it in the autofill profile.
        Set<Integer> visibleFields = new HashSet<>();
        for (int i = 0; i < mAddressUiComponents.size(); i++) {
            AddressUiComponent component = mAddressUiComponents.get(i);
            visibleFields.add(component.id);
            if (component.id != AddressField.COUNTRY) {
                setProfileField(profile, component.id, mAddressFields.get(component.id).getValue());
            }
        }

        // Clear the fields that are hidden from the user interface, so
        // AutofillAddress.toPaymentAddress() will send them to the renderer as empty strings.
        for (Map.Entry<Integer, EditorFieldModel> entry : mAddressFields.entrySet()) {
            if (!visibleFields.contains(entry.getKey())) {
                setProfileField(profile, entry.getKey(), "");
            }
        }

        // Save the edited autofill profile locally.
        if (mSaveToDisk) {
            profile.setGUID(PersonalDataManager.getInstance().setProfileToLocal(mProfile));
        }

        if (profile.getGUID().isEmpty()) {
            assert !mSaveToDisk;

            // Set a fake guid for a new temp AutofillProfile to be used in CardEditor. Note that
            // this temp AutofillProfile should not be saved to disk.
            profile.setGUID(UUID.randomUUID().toString());
        }

        profile.setIsLocal(true);
    }

    /** Writes the given value into the specified autofill profile field. */
    private static void setProfileField(
            AutofillProfile profile, int field, @Nullable CharSequence value) {
        assert profile != null;
        switch (field) {
            case AddressField.COUNTRY:
                profile.setCountryCode(ensureNotNull(value));
                return;
            case AddressField.ADMIN_AREA:
                profile.setRegion(ensureNotNull(value));
                return;
            case AddressField.LOCALITY:
                profile.setLocality(ensureNotNull(value));
                return;
            case AddressField.DEPENDENT_LOCALITY:
                profile.setDependentLocality(ensureNotNull(value));
                return;
            case AddressField.SORTING_CODE:
                profile.setSortingCode(ensureNotNull(value));
                return;
            case AddressField.POSTAL_CODE:
                profile.setPostalCode(ensureNotNull(value));
                return;
            case AddressField.STREET_ADDRESS:
                profile.setStreetAddress(ensureNotNull(value));
                return;
            case AddressField.ORGANIZATION:
                profile.setCompanyName(ensureNotNull(value));
                return;
            case AddressField.RECIPIENT:
                profile.setFullName(ensureNotNull(value));
                return;
        }

        assert false;
    }

    private static String ensureNotNull(@Nullable CharSequence value) {
        return value == null ? "" : value.toString();
    }

    private void setAddressFieldValuesFromCache() {
        // Address fields are cached, so their values need to be updated for every new profile
        // that's being edited.
        for (Map.Entry<Integer, EditorFieldModel> entry : mAddressFields.entrySet()) {
            entry.getValue().setValue(AutofillAddress.getProfileField(mProfile, entry.getKey()));
        }
    }

    @Override
    public void onSubKeysReceived(
            @Nullable String[] adminAreaCodes, @Nullable String[] adminAreaNames) {
        if (mAdminAreasLoaded) return;
        mAdminAreasLoaded = true;
        // If the dialog is already dismissed, it doesn't make sense to show it.
        // This can happen if the dialog is dismissed while we are getting the
        // subkeys.
        if (mEditorDialog.isDismissed()) return;

        // When there is a timeout in the subkey request process, the admin area codes/names will be
        // null.
        mAddressFields.put(AddressField.ADMIN_AREA,
                (adminAreaCodes != null && adminAreaNames != null && adminAreaCodes.length != 0
                        && adminAreaCodes.length == adminAreaNames.length)
                        ? EditorFieldModel.createDropdown(null /* label */,
                                  AutofillProfileBridge.getAdminAreaDropdownList(
                                          adminAreaCodes, adminAreaNames),
                                  mContext.getString(R.string.select))
                        : EditorFieldModel.createTextInput(
                                  EditorFieldModel.INPUT_TYPE_HINT_REGION));

        // Admin areas need to be fetched in two cases:
        // 1. Initial loading of the form.
        // 2. When the selected country is changed in the form.
        // mRecentlySelectedCountry is not null if and only if it's the second case
        if (mRecentlySelectedCountry != null) {
            dismissProgressDialog();
            // Both country code and language code dictate which fields should be added to the
            // editor.
            // For example, "US" will not add dependent locality to the editor. A "JP" address will
            // start with a person's full name or a with a prefecture name, depending on whether the
            // language code is "ja-Latn" or "ja".
            addAddressFieldsToEditor(mRecentlySelectedCountry, Locale.getDefault().getLanguage());
            // Notify EditorDialog that the fields in the model have changed. EditorDialog should
            // re-read the model and update the UI accordingly.
            mHandler.post(mCountryChangeCallback);
        } else {
            // This should be called when all required fields are put in mAddressField.
            setAddressFieldValuesFromCache();
            addAddressFieldsToEditor(
                    mCountryField.getValue().toString(), mProfile.getLanguageCode());
            mEditorDialog.show(mEditor);
        }
    }

    private static boolean contains(String[] haystack, String needle) {
        if (haystack == null || haystack.length == 0) return false;
        if (TextUtils.isEmpty(needle)) return true;
        for (int i = 0; i < haystack.length; ++i) {
            if (TextUtils.equals(haystack[i], needle)) return true;
        }
        return false;
    }

    /** Requests the list of admin areas. */
    private void loadAdminAreasForCountry(String countryCode) {
        // Used to check if the callback is called (for the cancellation).
        mAdminAreasLoaded = false;
        mEditorDialog.setAsNotDismissed();

        // For tests, the time-out is set to 0. In this case, we should not
        // fetch the admin-areas, and show a text-field instead.
        // This is to have the tests independent of the network status.
        if (PersonalDataManager.getRequestTimeoutMS() == 0) {
            onSubKeysReceived(null, null);
            return;
        }

        // In each rule, admin area keys are saved under sub-keys of country.
        PersonalDataManager.getInstance().loadRulesForSubKeys(countryCode);
        PersonalDataManager.getInstance().getRegionSubKeys(countryCode, this);
    }

    /**
     * Adds fields to the editor model based on the country and language code of
     * the profile that's being edited.
     */
    private void addAddressFieldsToEditor(String countryCode, String languageCode) {
        mAddressUiComponents =
                mAutofillProfileBridge.getAddressUiComponents(countryCode, languageCode);
        // In terms of order, country must be the first field.
        mCountryField.setCustomErrorMessage(getAddressError(AddressField.COUNTRY));
        mEditor.addField(mCountryField);
        for (int i = 0; i < mAddressUiComponents.size(); i++) {
            AddressUiComponent component = mAddressUiComponents.get(i);

            EditorFieldModel field = mAddressFields.get(component.id);

            if (component.id == AddressField.ORGANIZATION && mPurpose != Purpose.PAYMENT_REQUEST
                    && !ChromeFeatureList.isEnabled(
                            ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) {
                continue;
            }

            // Labels depend on country, e.g., state is called province in some countries. These are
            // already localized.
            field.setLabel(component.label);
            field.setIsFullLine(component.isFullLine || component.id == AddressField.LOCALITY
                    || component.id == AddressField.DEPENDENT_LOCALITY);

            // Libaddressinput formats do not always require the full name (RECIPIENT), but
            // PaymentRequest does.
            if (component.isRequired || component.id == AddressField.RECIPIENT) {
                field.setRequiredErrorMessage(mContext.getString(
                        R.string.pref_edit_dialog_field_required_validation_message));
            } else {
                field.setRequiredErrorMessage(null);
            }

            field.setCustomErrorMessage(getAddressError(component.id));
            mEditor.addField(field);
        }
        // Phone number (and email if applicable) are the last fields of the address.
        mPhoneField.setCustomErrorMessage(mAddressErrors != null ? mAddressErrors.phone : null);
        mEditor.addField(mPhoneField);
        if (mEmailField != null) mEditor.addField(mEmailField);
    }

    /** Country based phone number validator. */
    private static class CountryAwarePhoneNumberValidator implements EditorFieldValidator {
        @Nullable
        private String mCountryCode;

        /**
         * Sets the country code used to validate the phone number.
         *
         * @param countryCode The given country code.
         */
        public void setCountryCode(@Nullable String countryCode) {
            mCountryCode = countryCode;
        }

        @Override
        public boolean isValid(@Nullable CharSequence value) {
            // TODO(gogerald): Warn users when the phone number is a possible number but may be
            // invalid, crbug.com/736387.
            // Note that isPossibleNumber is used since the metadata in libphonenumber has to be
            // updated frequently (daily) to do more strict validation.
            return value != null
                    && PhoneNumberUtil.isPossibleNumber(value.toString(), mCountryCode);
        }

        @Override
        public boolean isLengthMaximum(@Nullable CharSequence value) {
            return false;
        }
    }
}


text:
"use strict";

var Animated = require("./Animated");
var AnimatedValue = require("./AnimatedValue");

import type { EndCallback } from "./Animated";

class AnimatedTracking extends Animated {
  _value: AnimatedValue;
  _parent: Animated;
  _callback: ?EndCallback;
  _animationConfig: Object;
  _animationClass: any;

  constructor(
    value: AnimatedValue,
    parent: Animated,
    animationClass: any,
    animationConfig: Object,
    callback?: ?EndCallback
  ) {
    super();
    this._value = value;
    this._parent = parent;
    this._animationClass = animationClass;
    this._animationConfig = animationConfig;
    this._callback = callback;
    this.__attach();
  }

  __getValue(): Object {
    return this._parent.__getValue();
  }

  __attach(): void {
    this._parent.__addChild(this);
  }

  __detach(): void {
    this._parent.__removeChild(this);
  }

  update(): void {
    this._value.animate(
      new this._animationClass({
        ...this._animationConfig,
        toValue: (this._animationConfig.toValue: any).__getValue()
      }),
      this._callback
    );
  }
}

module.exports = AnimatedTracking;