text:
namespace Microsoft.Hadoop.Client.Data
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using Microsoft.WindowsAzure.Management.HDInsight;
    using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library;
    using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.Json;

    internal class PayloadConverter : PayloadConverterBase
    {
        private readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        private const string ExitValuePropertyName = "exitValue";
        private const string RunStatePropertyName = "runState";
        private const string PercentCompletePropertyName = "percentComplete";
        private const string StatusPropertyName = "status";
        private const string UserArgsPropertyName = "userargs";
        private const string StatusDirectoryPropertyName = "statusdir";
        private const string DefinesPropertyName = "define";
        private const string ArgumentsPropertyName = "arg";
        private const string StartTimePropertyName = "startTime";
        private const string JobNameKey = "hdInsightJobName=";
        private const string DetailPropertyName = "detail";
        private const string ExecutePropertyName = "execute";
        private const string CommandPropertyName = "command";
        private const string UnknownJobId = "unknown";
        private const string ParentId = "parentId";
        private const string JobId = "id";
        private const string ErrorString = "error";
        private const string Callback = "callback";

        internal string DeserializeJobSubmissionResponse(string payload)
        {
            var ret = UnknownJobId;
            using (var parser = new JsonParser(payload))
            {
                var respObj = parser.ParseNext();
                if (respObj == null || respObj.IsError || respObj.IsNullOrMissing || !respObj.IsObject)
                {
                    throw new SerializationException(respObj.ToString());
                }

                var jobId = this.GetJsonPropertyStringValue(respObj, JobId);
                if (string.IsNullOrEmpty(jobId))
                {
                    var errorString = this.GetJsonPropertyStringValue(respObj, ErrorString);
                    if (!string.IsNullOrEmpty(errorString))
                    {
                        throw new InvalidOperationException(errorString);
                    }
                    throw new InvalidOperationException();
                }
                ret = jobId;
            }
            return ret;
        }

        internal JobList DeserializeListJobResult(string payload)
        {
            var ret = new JobList();
            var list = new List<JobDetails>();
            using (var parser = new JsonParser(payload))
            {
                var jobList = parser.ParseNext();
                if (jobList == null || !jobList.IsValidArray())
                {
                    throw new InvalidOperationException();
                }

                if (jobList.IsEmpty)
                {
                    return ret;
                }

                for (var i = 0; i < jobList.Count(); i++)
                {
                    var job = jobList.GetIndex(i);

                    if (job == null || !job.IsValidObject())
                    {
                        continue;
                    }
                    var detailProp = job.GetProperty(DetailPropertyName);
                    if (detailProp != null && detailProp.IsValidObject())
                    {
                        try
                        {
                            var jobDetails = this.DeserializeJobDetails((JsonObject)detailProp);
                            jobDetails.SubmissionTime = jobDetails.SubmissionTime.ToLocalTime();

                            if (jobDetails != null)
                            {
                                list.Add(jobDetails);
                            }
                        }
                        catch (InvalidOperationException)
                        {
                            //Eat it.
                        }
                    }
                }
            }
            ret.Jobs.AddRange((from j in list orderby j.SubmissionTime.ToUniversalTime() select j));
            return ret;
        }

        internal JobDetails DeserializeJobDetails(string payload)
        {
            using (var parser = new JsonParser(payload))
            {
                var job = parser.ParseNext();

                if (!job.IsValidObject())
                {
                    throw new InvalidOperationException();
                }
                return this.DeserializeJobDetails((JsonObject)job);
            }
        }

        private JobDetails DeserializeJobDetails(JsonObject job)
        {
            if (job == null || job.IsError || job.IsNullMissingOrEmpty)
            {
                throw new InvalidOperationException();
            }

            var jobId = string.Empty;
            if (!this.GetJobId(job, out jobId))
            {
                var errorString = this.GetJsonPropertyStringValue(job, ErrorString);
                if (!string.IsNullOrEmpty(errorString))
                {
                    return null;
                }

                throw new InvalidOperationException();
            }

            var ret = new JobDetails()
            {
                JobId = jobId
            };

            //NEIN: this is downcasting a long to an int.... which is ok for an exit code, but we should add a way to parse ints to the json lib
            ret.ExitCode = (int?)this.GetJsonPropertyNullableLongValue(job, ExitValuePropertyName);

            var status = this.GetJsonObject(job, StatusPropertyName);
            if (status != null)
            {
                var startTime = this.GetJsonPropertyLongValue(status, StartTimePropertyName);
                if (startTime != default(long))
                {
                    ret.SubmissionTime = this.unixEpoch.AddMilliseconds(startTime);
                }

                ret.StatusCode = this.GetJobStatusCodeValue(status, RunStatePropertyName);
            }

            var userArgs = this.GetJsonObject(job, UserArgsPropertyName);
            if (userArgs != null)
            {
                ret.StatusDirectory = this.GetJsonPropertyStringValue(userArgs, StatusDirectoryPropertyName);
                ret.Query = this.GetJsonPropertyStringValue(userArgs, ExecutePropertyName);
                if (ret.Query.IsNullOrEmpty())
                {
                    ret.Query = this.GetJsonPropertyStringValue(userArgs, CommandPropertyName);
                }

                var defines = this.GetJsonArray(userArgs, DefinesPropertyName);
                var arguments = this.GetJsonArray(userArgs, ArgumentsPropertyName);

                string jobName = string.Empty;
                if ((defines.IsNull() || !this.TryGetJobNameFromJsonArray(defines, out jobName)) && arguments.IsNotNull())
                {
                    this.TryGetJobNameFromJsonArray(arguments, out jobName);
                }

                ret.Name = jobName;
            }

            ret.PercentComplete = this.GetJsonPropertyStringValue(job, PercentCompletePropertyName);
            ret.Callback = this.GetJsonPropertyStringValue(job, Callback);

            return ret;
        }

        private bool GetJobId(JsonItem details, out string jobId)
        {
            var jobIdJson = details.GetProperty(JobId);
            if (jobIdJson == null || jobIdJson.IsNullOrMissing || jobIdJson.IsError)
            {
                var id = details.GetProperty(ParentId);
                return id.TryGetValue(out jobId);
            }
            return jobIdJson.TryGetValue(out jobId);
        }

        private bool TryGetJobNameFromJsonArray(IEnumerable<string> jsonArray, out string jobName)
        {
            jobName = string.Empty;
            var jobNameItem = jsonArray.FirstOrDefault(s => s.Contains(JobNameKey));
            if (jobNameItem != null)
            {
                var jobNameString = jobNameItem;
                var indexOfNameAssigment = jobNameString.IndexOf('=');
                if (indexOfNameAssigment > -1 && jobNameString.Length > (indexOfNameAssigment + 1))
                {
                    jobName = jobNameString.Substring(indexOfNameAssigment + 1);
                }
            }

            return jobName.IsNotNullOrEmpty();
        }

        private long GetJsonPropertyLongValue(JsonItem item, string property)
        {
            long value;
            var prop = item.GetProperty(property);
            prop.TryGetValue(out value);
            return value;
        }

        private long? GetJsonPropertyNullableLongValue(JsonItem item, string property)
        {
            long value;
            var prop = item.GetProperty(property);
            if (prop.TryGetValue(out value))
            {
                return value;
            }

            return null;
        }

        private JobStatusCode GetJobStatusCodeValue(JsonItem item, string property)
        {
            var jobStatus = JobStatusCode.Unknown;
            var value = string.Empty;
            var prop = item.GetProperty(property);
            prop.TryGetValue(out value);
            if (value.IsNotNullOrEmpty())
            {
                if (!Enum.TryParse(value, true, out jobStatus))
                {
                    jobStatus = JobStatusCode.Unknown;
                }
            }

            return jobStatus;
        }

        private string GetJsonPropertyStringValue(JsonItem item, string property)
        {
            var value = string.Empty;
            var prop = item.GetProperty(property);
            prop.TryGetValue(out value);
            return value;
        }

        private string GetJsonStringValue(JsonItem item)
        {
            var value = string.Empty;
            item.TryGetValue(out value);
            return value;
        }

        private JsonObject GetJsonObject(JsonItem item, string property)
        {
            var prop = item.GetProperty(property);
            if (prop == null || !prop.IsValidObject())
            {
                return null;
            }
            return (JsonObject)prop;
        }

        private IEnumerable<string> GetJsonArray(JsonItem item, string property)
        {
            var prop = item.GetProperty(property);
            if (prop == null || !prop.IsValidArray())
            {
                return null;
            }

            var ret = new List<string>();
            var array = (JsonArray)prop;
            for (var i = 0; i < array.Count(); i++)
            {
                var value = this.GetJsonStringValue(array.GetIndex(i));
                if (!string.IsNullOrEmpty(value))
                {
                    ret.Add(value);
                }
            }
            return ret;
        }
    }

}


text: {!! FormRenderer::widget($form) !!}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_chat_left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/common_measure_24dp"
        android:background="@anim/xml_chat_left"
        android:paddingLeft="@dimen/common_measure_60dp"
        android:paddingRight="@dimen/common_measure_15dp"
        android:paddingTop="@dimen/common_measure_10dp"
        android:text="This is a test "
        android:textColor="#2e2e2e"
        android:textSize="@dimen/common_measure_25sp" />

</LinearLayout>


text:
require_relative '../equipment.rb'

class Shield < Equipment
  def initialize(params={})
    super(params)
  end

end


text:
package org.ray.devnote.spi;

import java.util.List;

public class FileSearch implements Search {

	@Override
	public List<String> search(String keyword) {
		System.out.println("File Search keyword: " + keyword);
		return null;
	}

}


text:
<?php

namespace Miky\Bundle\UserBundle\Controller\Frontend;

use Miky\Bundle\AdBundle\Entity\Ad;
use Miky\Bundle\UserBundle\Entity\Customer;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class FavoriteController extends Controller
{
    /**
     * @return Response|RedirectResponse
     *
     * @throws AccessDeniedException
     */
    public function listFavoriteAdsAction()
    {
        $customer = $this->getUser();
        if (!is_object($customer) || !$customer instanceof Customer) {
            return $this->redirectToRoute("miky_app_home_index");
        }

        return $this->render('MikyUserBundle:Frontend/Favorite:list.html.twig', array(
            'ads' => $customer->getFavoriteAds(),
        ));
    }

    /**
     * @return Response|RedirectResponse
     *
     * @throws AccessDeniedException
     */
    public function removeFavoriteAdAction(Ad $ad)
    {
        $customer = $this->getUser();
        if (!is_object($customer) || !$customer instanceof Customer) {
            return $this->redirectToRoute("miky_app_home_index");
        }
        $customer->removeFavoriteAd($ad);
        $this->get("miky_customer_manager")->updateUser($customer);
        return $this->redirectToRoute("miky_app_favorite_ads_list");
    }

}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.impala.analysis;

import org.apache.impala.catalog.KuduTable;
import org.apache.impala.common.FrontendTestBase;
import org.apache.impala.testutil.TestUtils;
import org.apache.kudu.ColumnSchema.CompressionAlgorithm;
import org.apache.kudu.ColumnSchema.Encoding;
import org.junit.Test;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

import java.util.List;

/**
 * Tests on DDL analysis for Kudu tables.
 */
public class AnalyzeKuduDDLTest extends FrontendTestBase {

  @Test
  public void TestCreateManagedKuduTable() {
    TestUtils.assumeKuduIsSupported();
    // Test primary keys and partition by clauses
    AnalyzesOk("create table tab (x int primary key) partition by hash(x) " +
        "partitions 8 stored as kudu");
    AnalyzesOk("create table tab (x int, primary key(x)) partition by hash(x) " +
        "partitions 8 stored as kudu");
    AnalyzesOk("create table tab (x int, y int, primary key (x, y)) " +
        "partition by hash(x, y) partitions 8 stored as kudu");
    AnalyzesOk("create table tab (x int, y int, primary key (x)) " +
        "partition by hash(x) partitions 8 stored as kudu");
    AnalyzesOk("create table tab (x int, y int, primary key(x, y)) " +
        "partition by hash(y) partitions 8 stored as kudu");
    AnalyzesOk("create table tab (x timestamp, y timestamp, primary key(x)) " +
        "partition by hash(x) partitions 8 stored as kudu");
    AnalyzesOk("create table tab (x int, y string, primary key (x)) partition by " +
        "hash (x) partitions 3, range (x) (partition values < 1, partition " +
        "1 <= values < 10, partition 10 <= values < 20, partition value = 30) " +
        "stored as kudu");
    AnalyzesOk("create table tab (x int, y int, primary key (x, y)) partition by " +
        "range (x, y) (partition value = (2001, 1), partition value = (2002, 1), " +
        "partition value = (2003, 2)) stored as kudu");
    // Non-literal boundary values in range partitions
    AnalyzesOk("create table tab (x int, y int, primary key (x)) partition by " +
        "range (x) (partition values < 1 + 1, partition (1+3) + 2 < values < 10, " +
        "partition factorial(4) < values < factorial(5), " +
        "partition value = factorial(6)) stored as kudu");
    AnalyzesOk("create table tab (x int, y int, primary key(x, y)) partition by " +
        "range(x, y) (partition value = (1+1, 2+2), partition value = ((1+1+1)+1, 10), " +
        "partition value = (cast (30 as int), factorial(5))) stored as kudu");
    AnalysisError("create table tab (x int primary key) partition by range (x) " +
        "(partition values < x + 1) stored as kudu", "Only constant values are allowed " +
        "for range-partition bounds: x + 1");
    AnalysisError("create table tab (x int primary key) partition by range (x) " +
        "(partition values <= isnull(null, null)) stored as kudu", "Range partition " +
        "values cannot be NULL. Range partition: 'PARTITION VALUES <= " +
        "isnull(NULL, NULL)'");
    AnalysisError("create table tab (x int primary key) partition by range (x) " +
        "(partition values <= (select count(*) from functional.alltypestiny)) " +
        "stored as kudu", "Only constant values are allowed for range-partition " +
        "bounds: (SELECT count(*) FROM functional.alltypestiny)");
    // Multilevel partitioning. Data is split into 3 buckets based on 'x' and each
    // bucket is partitioned into 4 tablets based on the range partitions of 'y'.
    AnalyzesOk("create table tab (x int, y string, primary key(x, y)) " +
        "partition by hash(x) partitions 3, range(y) " +
        "(partition values < 'aa', partition 'aa' <= values < 'bb', " +
        "partition 'bb' <= values < 'cc', partition 'cc' <= values) " +
        "stored as kudu");
    // Key column in upper case
    AnalyzesOk("create table tab (x int, y int, primary key (X)) " +
        "partition by hash (x) partitions 8 stored as kudu");
    // Flexible Partitioning
    AnalyzesOk("create table tab (a int, b int, c int, d int, primary key (a, b, c))" +
        "partition by hash (a, b) partitions 8, hash(c) partitions 2 stored as " +
        "kudu");
    // No columns specified in the PARTITION BY HASH clause
    AnalyzesOk("create table tab (a int primary key, b int, c int, d int) " +
        "partition by hash partitions 8 stored as kudu");
    // Distribute range data types are picked up during analysis and forwarded to Kudu.
    // Column names in distribute params should also be case-insensitive.
    AnalyzesOk("create table tab (a int, b int, c int, d int, primary key(a, b, c, d))" +
        "partition by hash (a, B, c) partitions 8, " +
        "range (A) (partition values < 1, partition 1 <= values < 2, " +
        "partition 2 <= values < 3, partition 3 <= values < 4, partition 4 <= values) " +
        "stored as kudu");
    // Allowing range partitioning on a subset of the primary keys
    AnalyzesOk("create table tab (id int, name string, valf float, vali bigint, " +
        "primary key (id, name)) partition by range (name) " +
        "(partition 'aa' < values <= 'bb') stored as kudu");
    // Null values in range partition values
    AnalysisError("create table tab (id int, name string, primary key(id, name)) " +
        "partition by hash (id) partitions 3, range (name) " +
        "(partition value = null, partition value = 1) stored as kudu",
"Range partition values cannot be NULL. Range partition: 'PARTITION " +
        "VALUE = NULL'");
    // Primary key specified in tblproperties
    AnalysisError(String.format("create table tab (x int) partition by hash (x) " +
        "partitions 8 stored as kudu tblproperties ('%s' = 'x')",
        KuduTable.KEY_KEY_COLUMNS), "PRIMARY KEY must be used instead of the table " +
        "property");
    // Primary key column that doesn't exist
    AnalysisError("create table tab (x int, y int, primary key (z)) " +
        "partition by hash (x) partitions 8 stored as kudu",
        "PRIMARY KEY column 'z' does not exist in the table");
    // Invalid composite primary key
    AnalysisError("create table tab (x int primary key, primary key(x)) stored " +
        "as kudu", "Multiple primary keys specified. Composite primary keys can " +
        "be specified using the PRIMARY KEY (col1, col2, ...) syntax at the end " +
        "of the column definition.");
    AnalysisError("create table tab (x int primary key, y int primary key) stored " +
        "as kudu", "Multiple primary keys specified. Composite primary keys can " +
        "be specified using the PRIMARY KEY (col1, col2, ...) syntax at the end " +
        "of the column definition.");
    // Specifying the same primary key column multiple times
    AnalysisError("create table tab (x int, primary key (x, x)) partition by hash (x) " +
        "partitions 8 stored as kudu",
        "Column 'x' is listed multiple times as a PRIMARY KEY.");
    // Number of range partition boundary values should be equal to the number of range
    // columns.
    AnalysisError("create table tab (a int, b int, c int, d int, primary key(a, b, c)) " +
        "partition by range(a) (partition value = (1, 2), " +
        "partition value = 3, partition value = 4) stored as kudu",
"Number of specified range partition values is different than the number of " +
        "partitioning columns: (2 vs 1). Range partition: 'PARTITION VALUE = (1, 2)'");
    // Key ranges must match the column types.
    AnalysisError("create table tab (a int, b int, c int, d int, primary key(a, b, c)) " +
        "partition by hash (a, b, c) partitions 8, range (a) " +
        "(partition value = 1, partition value = 'abc', partition 3 <= values) " +
        "stored as kudu", "Range partition value 'abc' (type: STRING) is not type " +
        "compatible with partitioning column 'a' (type: INT).");
    AnalysisError("create table tab (a tinyint primary key) partition by range (a) " +
        "(partition value = 128) stored as kudu", "Range partition value 128 " +
        "(type: SMALLINT) is not type compatible with partitioning column 'a' " +
        "(type: TINYINT)");
    AnalysisError("create table tab (a smallint primary key) partition by range (a) " +
        "(partition value = 32768) stored as kudu", "Range partition value 32768 " +
        "(type: INT) is not type compatible with partitioning column 'a' " +
        "(type: SMALLINT)");
    AnalysisError("create table tab (a int primary key) partition by range (a) " +
        "(partition value = 2147483648) stored as kudu", "Range partition value " +
        "2147483648 (type: BIGINT) is not type compatible with partitioning column 'a' " +
        "(type: INT)");
    AnalysisError("create table tab (a bigint primary key) partition by range (a) " +
        "(partition value = 9223372036854775808) stored as kudu", "Range partition " +
        "value 9223372036854775808 (type: DECIMAL(19,0)) is not type compatible with " +
        "partitioning column 'a' (type: BIGINT)");
    // Test implicit casting/folding of partition values.
    AnalyzesOk("create table tab (a int primary key) partition by range (a) " +
        "(partition value = false, partition value = true) stored as kudu");
    // Non-key column used in PARTITION BY
    AnalysisError("create table tab (a int, b string, c bigint, primary key (a)) " +
        "partition by range (b) (partition value = 'abc') stored as kudu",
  "Column 'b' in 'RANGE (b) (PARTITION VALUE = 'abc')' is not a key column. " +
        "Only key columns can be used in PARTITION BY.");
    // No float range partition values
    AnalysisError("create table tab (a int, b int, c int, d int, primary key (a, b, c))" +
        "partition by hash (a, b, c) partitions 8, " +
        "range (a) (partition value = 1.2, partition value = 2) stored as kudu",
        "Range partition value 1.2 (type: DECIMAL(2,1)) is not type compatible with " +
        "partitioning column 'a' (type: INT).");
    // Non-existing column used in PARTITION BY
    AnalysisError("create table tab (a int, b int, primary key (a, b)) " +
        "partition by range(unknown_column) (partition value = 'abc') stored as kudu",
        "Column 'unknown_column' in 'RANGE (unknown_column) " +
        "(PARTITION VALUE = 'abc')' is not a key column. Only key columns can be used " +
        "in PARTITION BY");
    // Kudu num_tablet_replicas is specified in tblproperties
    String kuduMasters = catalog_.getDefaultKuduMasterHosts();
    AnalyzesOk(String.format("create table tab (x int primary key) partition by " +
        "hash (x) partitions 8 stored as kudu tblproperties " +
        "('kudu.num_tablet_replicas'='1', 'kudu.master_addresses' = '%s')",
        kuduMasters));
    // Kudu table name is specified in tblproperties resulting in an error
    AnalysisError("create table tab (x int primary key) partition by hash (x) " +
        "partitions 8 stored as kudu tblproperties ('kudu.table_name'='tab')",
        "Not allowed to set 'kudu.table_name' manually for managed Kudu tables");
    // No port is specified in kudu master address
    AnalyzesOk(String.format("create table tdata_no_port (id int primary key, " +
        "name string, valf float, vali bigint) partition by range(id) " +
        "(partition values <= 10, partition 10 < values <= 30, " +
        "partition 30 < values) stored as kudu tblproperties" +
        "('kudu.master_addresses' = '%s')", kuduMasters));
    // Not using the STORED AS KUDU syntax to specify a Kudu table
    AnalysisError("create table tab (x int) tblproperties (" +
        "'storage_handler'='org.apache.hadoop.hive.kudu.KuduStorageHandler')",
        CreateTableStmt.KUDU_STORAGE_HANDLER_ERROR_MESSAGE);
    // Creating unpartitioned table results in a warning.
    AnalyzesOk("create table tab (x int primary key) stored as kudu tblproperties (" +
        "'storage_handler'='org.apache.hadoop.hive.kudu.KuduStorageHandler')",
        "Unpartitioned Kudu tables are inefficient for large data sizes.");
    // Invalid value for number of replicas
    AnalysisError("create table t (x int primary key) stored as kudu tblproperties (" +
        "'kudu.num_tablet_replicas'='1.1')",
        "Table property 'kudu.num_tablet_replicas' must be an integer.");
    // Don't allow caching
    AnalysisError("create table tab (x int primary key) stored as kudu cached in " +
        "'testPool'", "A Kudu table cannot be cached in HDFS.");
    // LOCATION cannot be used with Kudu tables
    AnalysisError("create table tab (a int primary key) partition by hash (a) " +
        "partitions 3 stored as kudu location '/test-warehouse/'",
        "LOCATION cannot be specified for a Kudu table.");
    // Creating unpartitioned table results in a warning.
    AnalyzesOk("create table tab (a int, primary key (a)) stored as kudu",
        "Unpartitioned Kudu tables are inefficient for large data sizes.");
    AnalysisError("create table tab (a int) stored as kudu",
        "A primary key is required for a Kudu table.");
    // Using ROW FORMAT with a Kudu table
    AnalysisError("create table tab (x int primary key) " +
        "row format delimited escaped by 'X' stored as kudu",
        "ROW FORMAT cannot be specified for file format KUDU.");
    // Using PARTITIONED BY with a Kudu table
    AnalysisError("create table tab (x int primary key) " +
        "partitioned by (y int) stored as kudu", "PARTITIONED BY cannot be used " +
        "in Kudu tables.");
    // Multi-column range partitions
    AnalyzesOk("create table tab (a bigint, b tinyint, c double, primary key(a, b)) " +
        "partition by range(a, b) (partition (0, 0) < values <= (1, 1)) stored as kudu");
    AnalysisError("create table tab (a bigint, b tinyint, c double, primary key(a, b)) " +
        "partition by range(a, b) (partition values <= (1, 'b')) stored as kudu",
        "Range partition value 'b' (type: STRING) is not type compatible with " +
        "partitioning column 'b' (type: TINYINT)");
    AnalysisError("create table tab (a bigint, b tinyint, c double, primary key(a, b)) " +
        "partition by range(a, b) (partition 0 < values <= 1) stored as kudu",
        "Number of specified range partition values is different than the number of " +
        "partitioning columns: (1 vs 2). Range partition: 'PARTITION 0 < VALUES <= 1'");

    // Test unsupported Kudu types
    List<String> unsupportedTypes = Lists.newArrayList("VARCHAR(20)", "CHAR(20)",
        "STRUCT<f1:INT,f2:STRING>", "ARRAY<INT>", "MAP<STRING,STRING>");
    for (String t: unsupportedTypes) {
      String expectedError = String.format(
          "Cannot create table 'tab': Type %s is not supported in Kudu", t);

      // Unsupported type is PK and partition col
      String stmt = String.format("create table tab (x %s primary key) " +
          "partition by hash(x) partitions 3 stored as kudu", t);
      AnalysisError(stmt, expectedError);

      // Unsupported type is not PK/partition col
      stmt = String.format("create table tab (x int primary key, y %s) " +
          "partition by hash(x) partitions 3 stored as kudu", t);
      AnalysisError(stmt, expectedError);
    }

    // Test column options
    String[] nullability = {"not null", "null", ""};
    String[] defaultVal = {"default 10", ""};
    String[] blockSize = {"block_size 4096", ""};
    for (Encoding enc: Encoding.values()) {
      for (CompressionAlgorithm comp: CompressionAlgorithm.values()) {
        for (String nul: nullability) {
          for (String def: defaultVal) {
            for (String block: blockSize) {
              // Test analysis for a non-key column
              AnalyzesOk(String.format("create table tab (x int primary key " +
                  "not null encoding %s compression %s %s %s, y int encoding %s " +
                  "compression %s %s %s %s) partition by hash (x) " +
                  "partitions 3 stored as kudu", enc, comp, def, block, enc,
                  comp, def, nul, block));

              // For a key column
              String createTblStr = String.format("create table tab (x int primary key " +
                  "%s encoding %s compression %s %s %s) partition by hash (x) " +
                  "partitions 3 stored as kudu", nul, enc, comp, def, block);
              if (nul.equals("null")) {
                AnalysisError(createTblStr, "Primary key columns cannot be nullable");
              } else {
                AnalyzesOk(createTblStr);
              }
            }
          }
        }
      }
    }
    // Use NULL as default values
    AnalyzesOk("create table tab (x int primary key, i1 tinyint default null, " +
        "i2 smallint default null, i3 int default null, i4 bigint default null, " +
        "vals string default null, valf float default null, vald double default null, " +
        "valb boolean default null, valdec decimal(10, 5) default null) " +
        "partition by hash (x) partitions 3 stored as kudu");
    // Use NULL as a default value on a non-nullable column
    AnalysisError("create table tab (x int primary key, y int not null default null) " +
        "partition by hash (x) partitions 3 stored as kudu", "Default value of NULL " +
        "not allowed on non-nullable column: 'y'");
    // Primary key specified using the PRIMARY KEY clause
    AnalyzesOk("create table tab (x int not null encoding plain_encoding " +
        "compression snappy block_size 1, y int null encoding rle compression lz4 " +
        "default 1, primary key(x)) partition by hash (x) partitions 3 " +
        "stored as kudu");
    // Primary keys can't be null
    AnalysisError("create table tab (x int primary key null, y int not null) " +
        "partition by hash (x) partitions 3 stored as kudu", "Primary key columns " +
        "cannot be nullable: x INT PRIMARY KEY NULL");
    AnalysisError("create table tab (x int not null, y int null, primary key (x, y)) " +
        "partition by hash (x) partitions 3 stored as kudu", "Primary key columns " +
        "cannot be nullable: y INT NULL");
    // Unsupported encoding value
    AnalysisError("create table tab (x int primary key, y int encoding invalid_enc) " +
        "partition by hash (x) partitions 3 stored as kudu", "Unsupported encoding " +
        "value 'INVALID_ENC'. Supported encoding values are: " +
        Joiner.on(", ").join(Encoding.values()));
    // Unsupported compression algorithm
    AnalysisError("create table tab (x int primary key, y int compression " +
        "invalid_comp) partition by hash (x) partitions 3 stored as kudu",
        "Unsupported compression algorithm 'INVALID_COMP'. Supported compression " +
        "algorithms are: " + Joiner.on(", ").join(CompressionAlgorithm.values()));
    // Default values
    AnalyzesOk("create table tab (i1 tinyint default 1, i2 smallint default 10, " +
        "i3 int default 100, i4 bigint default 1000, vals string default 'test', " +
        "valf float default cast(1.2 as float), vald double default " +
        "cast(3.1452 as double), valb boolean default true, " +
        "valdec decimal(10, 5) default 3.14159, " +
        "primary key (i1, i2, i3, i4, vals)) partition by hash (i1) partitions 3 " +
        "stored as kudu");
    AnalyzesOk("create table tab (i int primary key default 1+1+1) " +
        "partition by hash (i) partitions 3 stored as kudu");
    AnalyzesOk("create table tab (i int primary key default factorial(5)) " +
        "partition by hash (i) partitions 3 stored as kudu");
    AnalyzesOk("create table tab (i int primary key, x int null default " +
        "isnull(null, null)) partition by hash (i) partitions 3 stored as kudu");
    // Invalid default values
    AnalysisError("create table tab (i int primary key default 'string_val') " +
        "partition by hash (i) partitions 3 stored as kudu", "Default value " +
        "'string_val' (type: STRING) is not compatible with column 'i' (type: INT).");
    AnalysisError("create table tab (i int primary key, x int default 1.1) " +
        "partition by hash (i) partitions 3 stored as kudu",
        "Default value 1.1 (type: DECIMAL(2,1)) is not compatible with column " +
        "'x' (type: INT).");
    AnalysisError("create table tab (i tinyint primary key default 128) " +
        "partition by hash (i) partitions 3 stored as kudu", "Default value " +
        "128 (type: SMALLINT) is not compatible with column 'i' (type: TINYINT).");
    AnalysisError("create table tab (i int primary key default isnull(null, null)) " +
        "partition by hash (i) partitions 3 stored as kudu", "Default value of " +
        "NULL not allowed on non-nullable column: 'i'");
    AnalysisError("create table tab (i int primary key, x int not null " +
        "default isnull(null, null)) partition by hash (i) partitions 3 " +
        "stored as kudu", "Default value of NULL not allowed on non-nullable column: " +
        "'x'");
    // Invalid block_size values
    AnalysisError("create table tab (i int primary key block_size 1.1) " +
        "partition by hash (i) partitions 3 stored as kudu", "Invalid value " +
        "for BLOCK_SIZE: 1.1. A positive INTEGER value is expected.");
    AnalysisError("create table tab (i int primary key block_size 'val') " +
        "partition by hash (i) partitions 3 stored as kudu", "Invalid value " +
        "for BLOCK_SIZE: 'val'. A positive INTEGER value is expected.");

    // Sort columns are not supported for Kudu tables.
    AnalysisError("create table tab (i int, x int primary key) partition by hash(x) " +
        "partitions 8 sort by(i) stored as kudu", "SORT BY is not supported for Kudu " +
        "tables.");

    // Range partitions with TIMESTAMP
    AnalyzesOk("create table ts_ranges (ts timestamp primary key) " +
        "partition by range (partition cast('2009-01-01 00:00:00' as timestamp) " +
        "<= VALUES < '2009-01-02 00:00:00') stored as kudu");
    AnalyzesOk("create table ts_ranges (ts timestamp primary key) " +
        "partition by range (partition value = cast('2009-01-01 00:00:00' as timestamp" +
        ")) stored as kudu");
    AnalyzesOk("create table ts_ranges (ts timestamp primary key) " +
        "partition by range (partition value = '2009-01-01 00:00:00') " +
        "stored as kudu");
    AnalyzesOk("create table ts_ranges (id int, ts timestamp, primary key(id, ts))" +
        "partition by range (partition value = (9, cast('2009-01-01 00:00:00' as " +
        "timestamp))) stored as kudu");
    AnalyzesOk("create table ts_ranges (id int, ts timestamp, primary key(id, ts))" +
        "partition by range (partition value = (9, '2009-01-01 00:00:00')) " +
        "stored as kudu");
    AnalysisError("create table ts_ranges (ts timestamp primary key, i int)" +
        "partition by range (partition '2009-01-01 00:00:00' <= VALUES < " +
        "'NOT A TIMESTAMP') stored as kudu",
        "Range partition value 'NOT A TIMESTAMP' cannot be cast to target TIMESTAMP " +
        "partitioning column.");
    AnalysisError("create table ts_ranges (ts timestamp primary key, i int)" +
        "partition by range (partition 100 <= VALUES < 200) stored as kudu",
        "Range partition value 100 (type: TINYINT) is not type " +
        "compatible with partitioning column 'ts' (type: TIMESTAMP).");

    // TIMESTAMP columns with default values
    AnalyzesOk("create table tdefault (id int primary key, ts timestamp default now())" +
        "partition by hash(id) partitions 3 stored as kudu");
    AnalyzesOk("create table tdefault (id int primary key, ts timestamp default " +
        "unix_micros_to_utc_timestamp(1230768000000000)) partition by hash(id) " +
        "partitions 3 stored as kudu");
    AnalyzesOk("create table tdefault (id int primary key, " +
        "ts timestamp not null default '2009-01-01 00:00:00') " +
        "partition by hash(id) partitions 3 stored as kudu");
    AnalyzesOk("create table tdefault (id int primary key, " +
        "ts timestamp not null default cast('2009-01-01 00:00:00' as timestamp)) " +
        "partition by hash(id) partitions 3 stored as kudu");
    AnalysisError("create table tdefault (id int primary key, ts timestamp " +
        "default null) partition by hash(id) partitions 3 stored as kudu",
        "NULL cannot be cast to a TIMESTAMP literal.");
    AnalysisError("create table tdefault (id int primary key, " +
        "ts timestamp not null default cast('00:00:00' as timestamp)) " +
        "partition by hash(id) partitions 3 stored as kudu",
        "CAST('00:00:00' AS TIMESTAMP) cannot be cast to a TIMESTAMP literal.");
    AnalysisError("create table tdefault (id int primary key, " +
        "ts timestamp not null default '2009-1 foo') " +
        "partition by hash(id) partitions 3 stored as kudu",
        "String '2009-1 foo' cannot be cast to a TIMESTAMP literal.");

    // Test column comments.
    AnalyzesOk("create table tab (x int comment 'x', y int comment 'y', " +
        "primary key (x, y)) stored as kudu");

    // Managed table is not allowed to set table property 'kudu.table_id'.
    AnalysisError("create table tab (x int primary key) partition by hash(x) " +
        "partitions 8 stored as kudu tblproperties ('kudu.table_id'='123456')",
        String.format("Table property %s should not be specified when " +
            "creating a Kudu table.", KuduTable.KEY_TABLE_ID));

    // Kudu master address needs to be valid.
    AnalysisError("create table tab (x int primary key) partition by " +
        "hash (x) partitions 8 stored as kudu tblproperties " +
        "('kudu.master_addresses' = 'foo')",
        "Cannot analyze Kudu table 'tab': Error determining if Kudu's integration " +
        "with the Hive Metastore is enabled");
  }

  @Test
  public void TestCreateExternalKuduTable() {
    TestUtils.assumeKuduIsSupported();
    final String kuduMasters = catalog_.getDefaultKuduMasterHosts();
    AnalyzesOk("create external table t stored as kudu " +
        "tblproperties('kudu.table_name'='t')");
    // Use all allowed optional table props.
    AnalyzesOk(String.format("create external table t stored as kudu tblproperties (" +
        "'kudu.table_name'='tab', 'kudu.master_addresses' = '%s', " +
        "'storage_handler'='org.apache.hadoop.hive.kudu.KuduStorageHandler')",
        kuduMasters));
    // Kudu table should be specified using the STORED AS KUDU syntax.
    AnalysisError("create external table t tblproperties (" +
        "'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler'," +
        "'kudu.table_name'='t')",
        CreateTableStmt.KUDU_STORAGE_HANDLER_ERROR_MESSAGE);
    AnalysisError("create external table t tblproperties (" +
        "'storage_handler'='org.apache.hadoop.hive.kudu.KuduStorageHandler'," +
        "'kudu.table_name'='t')",
        CreateTableStmt.KUDU_STORAGE_HANDLER_ERROR_MESSAGE);
    // Columns should not be specified in an external Kudu table
    AnalysisError("create external table t (x int) stored as kudu " +
        "tblproperties('kudu.table_name'='t')",
        "Columns cannot be specified with an external Kudu table.");
    // Primary keys cannot be specified in an external Kudu table
    AnalysisError("create external table t (x int primary key) stored as kudu " +
        "tblproperties('kudu.table_name'='t')", "Primary keys cannot be specified " +
        "for an external Kudu table");
    // Invalid syntax for specifying a Kudu table
    AnalysisError("create external table t (x int) stored as parquet tblproperties (" +
        "'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler'," +
        "'kudu.table_name'='t')", CreateTableStmt.KUDU_STORAGE_HANDLER_ERROR_MESSAGE);
    AnalysisError("create external table t (x int) stored as parquet tblproperties (" +
        "'storage_handler'='org.apache.hadoop.hive.kudu.KuduStorageHandler'," +
        "'kudu.table_name'='t')", CreateTableStmt.KUDU_STORAGE_HANDLER_ERROR_MESSAGE);
    AnalysisError("create external table t stored as kudu tblproperties (" +
        "'storage_handler'='foo', 'kudu.table_name'='t')",
        "Invalid storage handler specified for Kudu table: foo");
    // Cannot specify the number of replicas for external Kudu tables
    AnalysisError("create external table tab (x int) stored as kudu " +
        "tblproperties ('kudu.num_tablet_replicas' = '1', " +
        "'kudu.table_name'='tab')",
        "Table property 'kudu.num_tablet_replicas' cannot be used with an external " +
        "Kudu table.");
    // Don't allow caching
    AnalysisError("create external table t stored as kudu cached in 'testPool' " +
        "tblproperties('kudu.table_name'='t')",
        "A Kudu table cannot be cached in HDFS.");
    // LOCATION cannot be used for a Kudu table
    AnalysisError("create external table t stored as kudu " +
        "location '/test-warehouse' tblproperties('kudu.table_name'='t')",
        "LOCATION cannot be specified for a Kudu table.");
    // External table is not allowed to set table property 'kudu.table_id'.
    AnalysisError("create external table t stored as kudu tblproperties " +
        "('kudu.table_name'='t', 'kudu.table_id'='123456')",
        String.format("Table property %s should not be specified when creating " +
            "a Kudu table.", KuduTable.KEY_TABLE_ID));
  }

  @Test
  public void TestAlterKuduTable() {
    TestUtils.assumeKuduIsSupported();
    // ALTER TABLE ADD/DROP range partitions
    String[] addDrop = {"add if not exists", "add", "drop if exists", "drop"};
    for (String kw: addDrop) {
      AnalyzesOk(String.format("alter table functional_kudu.testtbl %s range " +
          "partition 10 <= values < 20", kw));
      AnalyzesOk(String.format("alter table functional_kudu.testtbl %s range " +
          "partition value = 30", kw));
      AnalyzesOk(String.format("alter table functional_kudu.testtbl %s range " +
          "partition values < 100", kw));
      AnalyzesOk(String.format("alter table functional_kudu.testtbl %s range " +
          "partition 10 <= values", kw));
      AnalyzesOk(String.format("alter table functional_kudu.testtbl %s range " +
          "partition 1+1 <= values <= factorial(3)", kw));
      AnalyzesOk(String.format("alter table functional_kudu.jointbl %s range " +
          "partition (0, '0') < values", kw));
      AnalyzesOk(String.format("alter table functional_kudu.jointbl %s range " +
          "partition values <= (1, '1')", kw));
      AnalyzesOk(String.format("alter table functional_kudu.jointbl %s range " +
          "partition (0, '0') <= values < (1, '1')", kw));
      AnalyzesOk(String.format("alter table functional_kudu.jointbl %s range " +
          "partition value = (-1, 'a')", kw));
      AnalysisError(String.format("alter table functional.alltypes %s range " +
          "partition 10 < values < 20", kw), "Table functional.alltypes does not " +
          "support range partitions: RANGE PARTITION 10 < VALUES < 20");
      AnalysisError(String.format("alter table functional_kudu.testtbl %s range " +
          "partition values < isnull(null, null)", kw), "Range partition values " +
          "cannot be NULL. Range partition: 'PARTITION VALUES < isnull(NULL, NULL)'");
      AnalysisError(String.format("alter table functional_kudu.jointbl %s range " +
          "partition (0) < values", kw),
          "Number of specified range partition values is different than the number of " +
          "partitioning columns: (1 vs 2). Range partition: 'PARTITION (0) < VALUES'");
      AnalysisError(String.format("alter table functional_kudu.jointbl %s range " +
          "partition values < (0, 0)", kw),
          "Range partition value 0 (type: TINYINT) is not type compatible with " +
          "partitioning column 'test_name' (type: STRING).");
    }

    // ALTER TABLE ADD COLUMNS
    // Columns with different supported data types
    AnalyzesOk("alter table functional_kudu.testtbl add columns (a1 tinyint null, a2 " +
        "smallint null, a3 int null, a4 bigint null, a5 string null, a6 float null, " +
        "a7 double null, a8 boolean null comment 'boolean')");
    // Decimal types
    AnalyzesOk("alter table functional_kudu.testtbl add columns (d1 decimal null, d2 " +
        "decimal(9, 2) null, d3 decimal(15, 15) null, d4 decimal(38, 0) null)");
    // Complex types
    AnalysisError("alter table functional_kudu.testtbl add columns ( "+
        "a struct<f1:int>)", "Kudu tables do not support complex types: " +
        "a STRUCT<f1:INT>");
    // Add primary key
    AnalysisError("alter table functional_kudu.testtbl add columns (a int primary key)",
        "Cannot add a primary key using an ALTER TABLE ADD COLUMNS statement: " +
        "a INT PRIMARY KEY");
    // Columns requiring a default value
    AnalyzesOk("alter table functional_kudu.testtbl add columns (a1 int not null " +
        "default 10)");
    AnalyzesOk("alter table functional_kudu.testtbl add columns (a1 int null " +
        "default 10)");
    AnalyzesOk("alter table functional_kudu.testtbl add columns (d1 decimal(9, 2) null " +
        "default 99.99)");
    // Other Kudu column options
    AnalyzesOk("alter table functional_kudu.testtbl add columns (a int encoding rle)");
    AnalyzesOk("alter table functional_kudu.testtbl add columns (a int compression lz4)");
    AnalyzesOk("alter table functional_kudu.testtbl add columns (a int block_size 10)");

    // REPLACE columns is not supported for Kudu tables
    AnalysisError("alter table functional_kudu.testtbl replace columns (a int null)",
        "ALTER TABLE REPLACE COLUMNS is not supported on Kudu tables");
    // Conflict with existing column
    AnalysisError("alter table functional_kudu.testtbl add columns (zip int)",
        "Column already exists: zip");
    // Kudu column options on an HDFS table
    AnalysisError("alter table functional.alltypes add columns (a int not null)",
        "The specified column options are only supported in Kudu tables: " +
        "a INT NOT NULL");

    // ALTER TABLE DROP COLUMN
    AnalyzesOk("alter table functional_kudu.testtbl drop column name");
    AnalysisError("alter table functional_kudu.testtbl drop column no_col",
        "Column 'no_col' does not exist in table: functional_kudu.testtbl");

    // ALTER TABLE CHANGE COLUMN on Kudu tables
    AnalyzesOk("alter table functional_kudu.testtbl change column name new_name string");
    AnalyzesOk("alter table functional_kudu.testtbl change column zip " +
        "zip int comment 'comment'");
    // Unsupported column options
    AnalysisError("alter table functional_kudu.testtbl change column zip zip_code int " +
        "encoding rle compression lz4 default 90000", "Unsupported column options in " +
        "ALTER TABLE CHANGE COLUMN statement: 'zip_code INT ENCODING RLE COMPRESSION " +
        "LZ4 DEFAULT 90000'. Use ALTER TABLE ALTER COLUMN instead.");
    // Changing the column type is not supported for Kudu tables
    AnalysisError("alter table functional_kudu.testtbl change column zip zip bigint",
        "Cannot change the type of a Kudu column using an ALTER TABLE CHANGE COLUMN " +
        "statement: (INT vs BIGINT)");

    // Setting kudu.table_id is not allowed for Kudu tables.
    AnalysisError("ALTER TABLE functional_kudu.testtbl SET " +
        "TBLPROPERTIES ('kudu.table_id' = '1234')",
        "Property 'kudu.table_id' cannot be altered for Kudu tables");

    // Rename the underlying Kudu table is not supported for managed Kudu tables.
    AnalysisError("ALTER TABLE functional_kudu.testtbl SET " +
        "TBLPROPERTIES ('kudu.table_name' = 'Hans')",
        "Not allowed to set 'kudu.table_name' manually for managed Kudu tables");

    // TODO IMPALA-6375: Allow setting kudu.table_name for managed Kudu tables
    // if the 'EXTERNAL' property is set to TRUE in the same step.
    AnalysisError("ALTER TABLE functional_kudu.testtbl SET " +
        "TBLPROPERTIES ('EXTERNAL' = 'TRUE','kudu.table_name' = 'Hans')",
        "Not allowed to set 'kudu.table_name' manually for managed Kudu tables");

    // ALTER TABLE RENAME TO
    AnalyzesOk("ALTER TABLE functional_kudu.testtbl RENAME TO new_testtbl");

    // ALTER TABLE SORT BY
    AnalysisError("alter table functional_kudu.alltypes sort by (int_col)",
        "ALTER TABLE SORT BY not supported on Kudu tables.");

    // ALTER TABLE SET TBLPROPERTIES for sort.columns
    AnalysisError("alter table functional_kudu.alltypes set tblproperties(" +
        "'sort.columns'='int_col')",
        "'sort.columns' table property is not supported for Kudu tables.");
  }
}


text:
/*
*
* 20150425-6.c
*
* Created by Sam Niemoeller on 4/25/15
*
* Chapter 6, Problem 39
*
* Write a program that creates the following pattern,
* given the height (#rows) and width (*'s per row)
*
*  * * * * * * * *
*  * * * * * * * *
*  * * * * * * * *
*  * * * * * * * *
*  * * * * * * * *
*
*/

#include <stdio.h>

int getHeight();
int getWidth();
void printPattern(int height, int width);

int main()
{
	//Local Definitions

	//Local Statements

printPattern (getHeight(), getWidth());

	return 0;
}

/*
* This function prompts the user to enter the height (aka number of rows) and returns it.
*/
int getHeight()
{
//Local Definitions
int height;

//Statements
printf("\nEnter number of rows to print (i.e. the height): ");
scanf("%d", &height);

while (height<=0)
	{
	printf("Invalid height. Please enter a positive integer for height: ");
	scanf("%d", &height);
	}

	return height;
}

/*
* This function prompts the user to enter the width (aka number of asterisks) and returns it.
*/
int getWidth()
{
//Local Definitions
int width;

//Statements
printf("\nEnter number of asterisks to prints in each row (i.e. the width): ");
scanf("%d", &width);

while (width<=0)
	{
	printf("Invalid width. Please enter a positive integer for the width: ");
	scanf("%d", &width);
	}

	return width;
}

void printPattern (int height, int width)
{
//Local Definitions
int rowLooper;
int asteriskLooper;

//Statements
printf("\n\n");

for(rowLooper=1; rowLooper<=height; rowLooper++)
{
	for(asteriskLooper=1; asteriskLooper<=width; asteriskLooper++)
	{
		printf("*");
	}

	printf("\n");
}

	return;
}


text:
package org.bouncycastle.pqc.crypto.sike;

import java.security.SecureRandom;

import org.bouncycastle.crypto.KeyGenerationParameters;

public class SIKEKeyGenerationParameters
    extends KeyGenerationParameters
{
    private SIKEParameters params;

    public SIKEKeyGenerationParameters(
            SecureRandom random,
            SIKEParameters sikeParameters
    )
    {
        super(random, 256);
        this.params = sikeParameters;
    }
    public SIKEParameters getParameters()
    {
        return params;
    }
}


text:
[TOC]

    View source on GitHub

Applies tfgnn.pad_to_total_sizes() to a GraphTensor.

tfgnn.keras.layers.PadToTotalSizes(
    sizes_constraints: tfgnn.SizeConstraints,
    *,
    validate: bool = True,
    **kwargs
)

This Keras layer maps a GraphTensor to a GraphTensor by calling
tfgnn.pad_to_total_sizes() with the additional arguments, notably
`sizes_constraints`, passed at initialization time. See that function
for detailed documentation.

Serialization to a Keras model config requires the `sizes_constraints` to
contain Python integers or eager Tensors, not symbolic Tensors.


text:
<?php

namespace Chaplean\Bundle\RestClientBundle\Command;

use Chaplean\Bundle\RestClientBundle\Utility\RestLogUtility;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ChapleanRestLogCleanCommand extends ContainerAwareCommand
{
    /**
     * Configures the current command.
     *
     * @return void
     */
    protected function configure()
    {
        $this->setName('chaplean:rest-log:clean');
        $this->setDescription('Delete logs older than one month');
    }

    /**
     * Execute command
     *
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var RestLogUtility $restLogUtility */
        $restLogUtility = $this->getContainer()->get('chaplean_rest_client.utility.rest_log');

        $dateLimit = new \DateTime('now - 1 month midnight');
        $restLogsDeleted = $restLogUtility->deleteMostRecentThan($dateLimit);

        $output->writeln($restLogsDeleted . ' logs removed');
    }
}


text:
using System.IO;

namespace SOLID.OCP
{
    public class FileDocumentStorage : DocumentStorage
    {
        public override string GetData(string sourceFileName)
        {
            string input;
            using (var stream = File.OpenRead(sourceFileName))
            using (var reader = new StreamReader(stream))
            {
                input = reader.ReadToEnd();
            }

            return input;
        }

        public override void Persist(string serializedDoc, string targetFileName)
        {
            using (var stream = File.Open(targetFileName, FileMode.Create, FileAccess.Write))
            using (var sw = new StreamWriter(stream))
            {
                sw.Write(serializedDoc);
                sw.Close();
            }
        }
    }
}


text:
(function($) {
	/**
	 * @param column
	 * @param row
	 */
	if (!String.prototype.ellipse) {
		String.prototype.ellipse = function(column, row) {
			var i = 0,
				len = this.length,
				ell = '',
				result = '';
			for (i = 0; i < column && i < 3; i++) {
				ell += '.';
			}
			for (i = 0; i < row; i++) {
				if (len - i * column > column) {
					if (i == row - 1) {
						result += this.substring(i * column, (i + 1) * column - ell.length) + ell;
					} else {
						result += this.substring(i * column, (i + 1) * column);
					}
				} else if (len > i * column) {
					result += this.substring(i * column, len);
				}
				result += '<br/>';
			}
			return result;
		};
	}
	if (!Array.prototype.contains) {
		Array.prototype.contains = function(elem) {
			for (var i = 0; i < this.length; i++) {
				if (this[i] == elem) {
					return true;
				}
			}
			return false;
		};
	}
	if (!$.fn.licoTemplate) {
		var licoTemplate = function() {
			return {
				version: '0.1.1',
				options: {
					template: [],
					store: {

					},
					setUpBefore: function(data) {
						return data;
					},
					setUp: function(data) {
						return data;
					},
					getTemplate: function(result, data, opt) {},
					getTemplates: function(results, datas, opts, origin) {}
				},
				getTemplate: function(result, data, opt) {
					(opt.getTemplate || $.fn.licoTemplate.getTemplate).call(
						$.fn.licoTemplate, result, data, opt);
				},

				getTemplates: function(results, datas, opts, origin) {
					(opts.getTemplates || $.fn.licoTemplate.getTemplates).call(
						$.fn.licoTemplate, results, datas, opts, origin);
				},
				parse: function(opts) {
					var scope = this;
					$.licoStore($.extend({}, opts.store, {
						getData: function(r) {
							if (r.success) {
								var data = r.data,
									templates = [],
									datas = [];
								if (opts.setUpBefore) {
									data = opts.setUpBefore.call(opts, data);
								}
								if (Object.prototype.toString.apply(data) === "[object Array]") {
									$.each(data, function(i, d) {
										var d2 = scope.formatData(d, opts);
										var template = scope.initTemplate(d2,
											opts);
										scope.getTemplate(template, d2, opts);
										templates.push(template);
										datas.push(d2);
									});
								} else {
									var d = scope
										.formatData(data, opts);
									var template = scope.initTemplate(d,
										opts);
									scope.getTemplate(template, d, opts);
									templates.push(template);
									datas.push(d);
								}

								scope.getTemplates(templates, datas, opts, r);
							} else {
								console.log('success:' + r.data.success + '\nmessage:' + r.data.msg);
							}
						}
					}));
				},
				formatData: function(data, opts) {
					if (opts.setUp) {
						data = opts.setUp.call(opts, data);
					}
					return data;
				},
				initTemplate: function(data, opts) {
					if (!data) {
						return null;
					}
					var result = opts.template.join('');
					result = result.replace(
						/([{]+)\s*([A-z]|[0-9]|[_]|[.])*\s*([}]+)/gim,
						function(rege) {
							//TODO 以点分隔
							var value = data;
							if (rege) {
								var pro = rege.substring(1, rege.length - 1);
								var pros = pro.split('.');

								for (var i = 0; i < pros.length; i++) {
									if (!value) {
										break;
									}
									value = value[pros[i]];
								}
								return value;
							}
							return null;
						});
					var temp = $(result);
					if (data.listeners) {
						$.each(data.listeners, function(i, v) {
							temp.bind(i, function() {
								v.call(data);
							});
						});
					}
					return temp;
				}
			};
		}();
		$.fn.licoTemplate = function(opts) {
			opts = $.extend({}, licoTemplate.options, opts || {});
			return (function() {
				licoTemplate.parse.apply(licoTemplate, arguments);
			})(opts);;
		};

		$.fn.licoTemplate.getTemplate = function(template, data, opt) {
			//console.log(template);
		};

		$.fn.licoTemplate.getTemplates = function(templates, datas, opts, origin) {
			//console.log(templates);
		};

		$.licoTemplate = $.fn.licoTemplate;
	}
})(jQuery);


text:
package org.lorislab.appky.web.admin.user.resources;

/**
 *
 * @author Andrej Petras <andrej@ajka-andrej.com>
 */
public enum MessageKeys {

    LOAD_USER_PROFILE,
    LOAD_USER_PROFILE_SUCCEED,
    LOAD_USER_PROFILE_FAILED;

}


text:
#ifndef OGR_MDB_H_INCLUDED
#define OGR_MDB_H_INCLUDED

#include <jni.h>
#include <vector>

#include "ogrsf_frmts.h"
#include "cpl_error.h"
#include "cpl_string.h"

/************************************************************************/
/*                            OGRMDBJavaEnv                             */
/************************************************************************/

class OGRMDBJavaEnv
{
    public:
        OGRMDBJavaEnv();
        ~OGRMDBJavaEnv();

        int Init();

    JavaVM *jvm;
    JNIEnv *env;
    int bCalledFromJava;

    int ExceptionOccurred();

    jclass byteArray_class;

    jclass file_class;
    jmethodID file_constructor;
    jclass database_class;
    jmethodID database_open;
    jmethodID database_close;
    jmethodID database_getTableNames;
    jmethodID database_getTable;

    jclass table_class;
    jmethodID table_getColumns;
    jmethodID table_iterator;
    jmethodID table_getRowCount;

    jclass column_class;
    jmethodID column_getName;
    jmethodID column_getType;
    jmethodID column_getLength;
    jmethodID column_isVariableLength;

    jclass datatype_class;
    jmethodID datatype_getValue;

    jclass list_class;
    jmethodID list_iterator;

    jclass set_class;
    jmethodID set_iterator;

    jclass map_class;
    jmethodID map_get;

    jclass iterator_class;
    jmethodID iterator_hasNext;
    jmethodID iterator_next;

    jclass object_class;
    jmethodID object_toString;
    jmethodID object_getClass;

    jclass boolean_class;
    jmethodID boolean_booleanValue;

    jclass byte_class;
    jmethodID byte_byteValue;

    jclass short_class;
    jmethodID short_shortValue;

    jclass integer_class;
    jmethodID integer_intValue;

    jclass float_class;
    jmethodID float_floatValue;

    jclass double_class;
    jmethodID double_doubleValue;
};

/************************************************************************/
/*                           OGRMDBDatabase                             */
/************************************************************************/

class OGRMDBTable;

class OGRMDBDatabase
{
    OGRMDBJavaEnv* env;
    jobject database;

    OGRMDBDatabase();
public:
    static OGRMDBDatabase* Open(OGRMDBJavaEnv* env, const char* pszName);
    ~OGRMDBDatabase();

    std::vector<CPLString>   apoTableNames;
    int                FetchTableNames();
    OGRMDBTable* GetTable(const char* pszTableName);
};

/************************************************************************/
/*                             OGRMDBTable                              */
/************************************************************************/

class OGRMDBTable
{
    OGRMDBJavaEnv* env;
    OGRMDBDatabase* poDB;
    jobject table;

    jobject table_iterator_obj;
    jobject row;

    jobject GetColumnVal(int iCol);

    CPLString osTableName;

    std::vector<CPLString> apoColumnNames;
    std::vector<jstring>   apoColumnNameObjects;
    std::vector<int>       apoColumnTypes;
    std::vector<int>       apoColumnLengths;

public:
    OGRMDBTable(OGRMDBJavaEnv* env, OGRMDBDatabase* poDB, jobject table, const char* pszTableName);
    ~OGRMDBTable();

    OGRMDBDatabase* GetDB() { return poDB; }

    const char* GetName() { return osTableName.c_str(); }

    int GetColumnCount() { return (int)apoColumnNames.size(); }
    int GetColumnIndex(const char* pszColName, int bEmitErrorIfNotFound = FALSE);
    const char* GetColumnName(int iIndex) { return apoColumnNames[iIndex].c_str(); }
    int GetColumnType(int iIndex) { return apoColumnTypes[iIndex]; }
    int GetColumnLength(int iIndex) { return apoColumnLengths[iIndex]; }

    void DumpTable();

    int FetchColumns();

    int GetRowCount();
    int GetNextRow();
    void ResetReading();

    char* GetColumnAsString(int iCol);
    int GetColumnAsInt(int iCol);
    double GetColumnAsDouble(int iCol);
    GByte* GetColumnAsBinary(int iCol, int* pnBytes);

};

typedef enum
{
    MDB_Boolean = 0x01,
    MDB_Byte = 0x02,
    MDB_Short = 0x03,
    MDB_Int = 0x04,
    MDB_Money = 0x05,
    MDB_Float = 0x06,
    MDB_Double = 0x07,
    MDB_ShortDateTime = 0x08,
    MDB_Binary = 0x09,
    MDB_Text = 0x0A,
    MDB_OLE = 0x0B,
    MDB_Memo = 0x0C,
    MDB_Unknown = 0x0D,
    MDB_GUID = 0x0F,
    MDB_Numeric = 0x10
} MDBType;

typedef enum
{
    MDB_GEOM_NONE,
    MDB_GEOM_PGEO,
    MDB_GEOM_GEOMEDIA
} MDBGeometryType;

/************************************************************************/
/*                            OGRMDBLayer                              */
/************************************************************************/

class OGRMDBDataSource;

class OGRMDBLayer : public OGRLayer
{
  protected:
    OGRMDBTable* poMDBTable;

    MDBGeometryType     eGeometryType;

    OGRFeatureDefn     *poFeatureDefn;

    // Layer spatial reference system, and srid.
    OGRSpatialReference *poSRS;
    int                 nSRSId;

    int                 iNextShapeId;

    OGRMDBDataSource    *poDS;

    int                 iGeomColumn;
    char                *pszGeomColumn;
    char                *pszFIDColumn;

    int                *panFieldOrdinals;

    int                 bHasExtent;
    OGREnvelope         sExtent;

    void                LookupSRID( int );

  public:
                        OGRMDBLayer(OGRMDBDataSource* poDS, OGRMDBTable* poMDBTable);
    virtual             ~OGRMDBLayer();

    CPLErr              BuildFeatureDefn();

    CPLErr              Initialize( const char *pszTableName,
                                    const char *pszGeomCol,
                                    int nShapeType,
                                    double dfExtentLeft,
                                    double dfExtentRight,
                                    double dfExtentBottom,
                                    double dfExtentTop,
                                    int nSRID,
                                    int bHasZ );

    CPLErr              Initialize( const char *pszTableName,
                                    const char *pszGeomCol,
                                    OGRSpatialReference* poSRS );

    virtual void        ResetReading();
    virtual GIntBig     GetFeatureCount( int bForce );
    virtual OGRFeature *GetNextRawFeature();
    virtual OGRFeature *GetNextFeature();

    virtual OGRFeature *GetFeature( GIntBig nFeatureId );

    OGRFeatureDefn *    GetLayerDefn() { return poFeatureDefn; }

    virtual int         TestCapability( const char * );

    virtual const char *GetFIDColumn();

    virtual OGRErr      GetExtent( OGREnvelope *psExtent, int bForce );
    virtual OGRErr      GetExtent(int iGeomField, OGREnvelope *psExtent, int bForce)
                { return OGRLayer::GetExtent(iGeomField, psExtent, bForce); }
};

/************************************************************************/
/*                           OGRMDBDataSource                            */
/************************************************************************/

class OGRMDBDataSource : public OGRDataSource
{
    OGRMDBLayer        **papoLayers;
    int                 nLayers;

    OGRMDBLayer        **papoLayersInvisible;
    int                 nLayersWithInvisible;

    char               *pszName;

    OGRMDBJavaEnv       env;

    OGRMDBDatabase*     poDB;

    int                 OpenGDB(OGRMDBTable* poGDB_GeomColumns);
    int                 OpenGeomediaWarehouse(OGRMDBTable* poGAliasTable);
    OGRSpatialReference* GetGeomediaSRS(const char* pszGCoordSystemTable,
                                        const char* pszGCoordSystemGUID);

  public:
                        OGRMDBDataSource();
                        ~OGRMDBDataSource();

    int                 Open( const char * );
    int                 OpenTable( const char *pszTableName,
                                   const char *pszGeomCol,
                                   int bUpdate );

    const char          *GetName() { return pszName; }
    int                 GetLayerCount() { return nLayers; }
    OGRLayer            *GetLayer( int );
    OGRLayer            *GetLayerByName( const char* pszLayerName );

    int                 TestCapability( const char * );
};

/************************************************************************/
/*                             OGRMDBDriver                             */
/************************************************************************/

class OGRMDBDriver : public OGRSFDriver
{
  public:
                ~OGRMDBDriver();

    const char  *GetName();
    OGRDataSource *Open( const char *, int );

    int          TestCapability( const char * );
};

#endif /* ndef OGR_MDB_H_INCLUDED */


text:
package geoip2

import "fmt"

type Error struct {
	Code string `json:"code,omitempty"`
	Err  string `json:"error,omitempty"`
}

func (e Error) Error() string {
	return fmt.Sprintf("%s: %s", e.Code, e.Err)
}

type City struct {
	Confidence int               `json:"confidence,omitempty"`
	GeoNameId  int               `json:"geoname_id,omitempty"`
	Names      map[string]string `json:"names,omitempty"`
}

type Continent struct {
	Code      string            `json:"code,omitempty"`
	GeoNameId int               `json:"geoname_id,omitempty"`
	Names     map[string]string `json:"names,omitempty"`
}

type Country struct {
	Confidence int               `json:"confidence,omitempty"`
	GeoNameId  int               `json:"geoname_id,omitempty"`
	IsoCode    string            `json:"iso_code,omitempty"`
	Names      map[string]string `json:"names,omitempty"`
}

type Location struct {
	AccuracyRadius    int     `json:"accuracy_radius,omitempty"`
	AverageIncome     int     `json:"average_income,omitempty"`
	Latitude          float64 `json:"latitude,omitempty"`
	Longitude         float64 `json:"longitude,omitempty"`
	MetroCode         int     `json:"metro_code,omitempty"`
	PopulationDensity int     `json:"population_density,omitempty"`
	TimeZone          string  `json:"time_zone,omitempty"`
}

type Postal struct {
	Code       string `json:"code,omitempty"`
	Confidence int    `json:"confidence,omitempty"`
}

type RegisteredCountry struct {
	GeoNameId int               `json:"geoname_id,omitempty"`
	IsoCode   string            `json:"iso_code,omitempty"`
	Names     map[string]string `json:"names,omitempty"`
}

type RepresentedCountry struct {
	GeoNameId int               `json:"geoname_id,omitempty"`
	IsoCode   string            `json:"iso_code,omitempty"`
	Names     map[string]string `json:"names,omitempty"`
	Type      string            `json:"type,omitempty"`
}

type Subdivision struct {
	Confidence int               `json:"confidence,omitempty"`
	GeoNameId  int               `json:"geoname_id,omitempty"`
	IsoCode    string            `json:"iso_code,omitempty"`
	Names      map[string]string `json:"names,omitempty"`
}

type Traits struct {
	AutonomousSystemNumber       int    `json:"autonomous_system_number,omitempty"`
	AutonomousSystemOrganization string `json:"autonomous_system_organization,omitempty"`
	Domain                       string `json:"domain,omitempty"`
	IsAnonymousProxy             bool   `json:"is_anonymous_proxy,omitempty"`
	IsSatelliteProvider          bool   `json:"is_satellite_provider,omitempty"`
	Isp                          string `json:"isp,omitempty"`
	IpAddress                    string `json:"ip_address,omitempty"`
	Organization                 string `json:"organization,omitempty"`
	UserType                     string `json:"user_type,omitempty"`
}

type MaxMind struct {
	QueriesRemaining int `json:"queries_remaining,omitempty"`
}

type Response struct {
	City               City               `json:"city,omitempty"`
	Continent          Continent          `json:"continent,omitempty"`
	Country            Country            `json:"country,omitempty"`
	Location           Location           `json:"location,omitempty"`
	Postal             Postal             `json:"postal,omitempty"`
	RegisteredCountry  RegisteredCountry  `json:"registered_country,omitempty"`
	RepresentedCountry RepresentedCountry `json:"represented_country,omitempty"`
	Subdivisions       []Subdivision      `json:"subdivisions,omitempty"`
	Traits             Traits             `json:"traits,omitempty"`
	MaxMind            MaxMind            `json:"maxmind,omitempty"`
}


text:
#if !defined(FUSION_EQUAL_TO_05052005_1208)
#define FUSION_EQUAL_TO_05052005_1208

#include <boost/type_traits/is_same.hpp>
#include <boost/fusion/support/tag_of.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/fusion/support/is_iterator.hpp>
#include <boost/mpl/and.hpp>
#include <boost/utility/enable_if.hpp>

namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace fusion
{
    // Special tags:
    struct iterator_facade_tag; // iterator facade tag
    struct boost_array_iterator_tag; // pdalboost::array iterator tag
    struct mpl_iterator_tag; // mpl sequence iterator tag
    struct std_pair_iterator_tag; // std::pair iterator tag

    namespace extension
    {
        template <typename Tag>
        struct equal_to_impl
        {
            // default implementation
            template <typename I1, typename I2>
            struct apply
                : is_same<typename add_const<I1>::type, typename add_const<I2>::type>
            {};
        };

        template <>
        struct equal_to_impl<iterator_facade_tag>
        {
            template <typename It1, typename It2, typename Tag1, typename Tag2>
            struct dispatch : mpl::false_ {};

            template <typename It1, typename It2, typename Tag>
            struct dispatch<It1, It2, Tag, Tag> // same tag
              : It1::template equal_to<It1, It2>
            {};

            template<typename It1, typename It2>
            struct apply : dispatch<It1, It2,
                typename It1::fusion_tag, typename It2::fusion_tag>
            {};
        };

        template <>
        struct equal_to_impl<boost_array_iterator_tag>;

        template <>
        struct equal_to_impl<mpl_iterator_tag>;

        template <>
        struct equal_to_impl<std_pair_iterator_tag>;
    }

    namespace result_of
    {
        template <typename I1, typename I2>
        struct equal_to
            : extension::equal_to_impl<typename detail::tag_of<I1>::type>::
                template apply<I1, I2>
        {};
    }

    namespace iterator_operators
    {
        template <typename Iter1, typename Iter2>
        inline typename
        pdalboost::enable_if<
            mpl::and_<is_fusion_iterator<Iter1>, is_fusion_iterator<Iter2> >
            , bool
            >::type
        operator==(Iter1 const&, Iter2 const&)
        {
            return result_of::equal_to<Iter1, Iter2>::value;
        }

        template <typename Iter1, typename Iter2>
        inline typename
        pdalboost::enable_if<
            mpl::and_<is_fusion_iterator<Iter1>, is_fusion_iterator<Iter2> >
            , bool
            >::type
        operator!=(Iter1 const&, Iter2 const&)
        {
            return !result_of::equal_to<Iter1, Iter2>::value;
        }
    }

    using iterator_operators::operator==;
    using iterator_operators::operator!=;
}}

#endif


text:
"""The model module is repsonsible exposes the :class:`sandman.model.Model` class,
from which user models should derive. It also makes the :func:`register`
function available, which maps endpoints to their associated classes."""

from sandman.model.utils import register, activate, Model


text:
const dotenv = require('dotenv');
const glob = require('glob');
const path = require('path');
const {EnvironmentPlugin} = require('webpack');

dotenv.config({path: '.env.default'});
dotenv.config();

module.exports = {
  entry: './packages/node_modules/ciscospark',
  output: {
    filename: 'bundle.js',
    library: 'ciscospark',
    libraryTarget: 'var',
    path: __dirname,
    sourceMapFilename: '[file].map'
  },
  devtool: 'source-map',
  devServer: {
    https: true,
    disableHostCheck: true,
    port: 8000
  },
  resolve: {
    alias: glob
      .sync('**/package.json', {cwd: './packages/node_modules'})
      .map((p) => path.dirname(p))
      .reduce((alias, packageName) => {
        // Always use src as the entry point for local files so that we have the
        // best opportunity for treeshaking; also makes developing easier since
        // we don't need to manually rebuild after changing code.
        alias[`./packages/node_modules/${packageName}`] = path.resolve(__dirname, `./packages/node_modules/${packageName}/src/index.js`);
        alias[`${packageName}`] = path.resolve(__dirname, `./packages/node_modules/${packageName}/src/index.js`);
        return alias;
      }, {})
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: /packages\/node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  plugins: [
    new EnvironmentPlugin({
      CISCOSPARK_LOG_LEVEL: 'log',
      DEBUG: '',
      NODE_ENV: process.env.NODE_ENV || 'development',
      // The follow environment variables are specific to our continuous
      // integration process and should not be used in general
      // Also, yes, CONVERSATION_SERVICE does not end in URL
      CONVERSATION_SERVICE: process.env.CONVERSATION_SERVICE,
      WDM_SERVICE_URL: process.env.WDM_SERVICE_URL,
      HYDRA_SERVICE_URL: process.env.HYDRA_SERVICE_URL,
      ATLAS_SERVICE_UR: process.env.ATLAS_SERVICE_URLL
    })
  ]
};


text:
import { AsyncIterableX } from '../asynciterablex';
import {
  IRefCountList,
  MaxRefCountList,
  RefCountList,
} from '../../iterable/operators/_refcountlist';
import { create } from '../create';
import { OperatorAsyncFunction } from '../../interfaces';
import { throwIfAborted } from '../../aborterror';

export class MemoizeAsyncBuffer<T> extends AsyncIterableX<T> {
  protected _source: AsyncIterator<T>;
  protected _buffer: IRefCountList<T>;
  protected _shared: Promise<IteratorResult<T>> | null;
  protected _error: any;
  protected _stopped: boolean;

  constructor(source: AsyncIterator<T>, buffer: IRefCountList<T>) {
    super();
    this._error = null;
    this._shared = null;
    this._stopped = false;
    this._source = source;
    this._buffer = buffer;
  }

  [Symbol.asyncIterator](signal?: AbortSignal) {
    throwIfAborted(signal);
    return this._getIterable(0);
  }

  protected async *_getIterable(offset = 0) {
    let i = offset - 1;
    let done: boolean | undefined = false;
    const buffer = this._buffer;

    try {
      do {
        if (++i < buffer.count) {
          yield buffer.get(i);
          continue;
        }

        if (this._stopped) {
          throw this._error;
        }

        if (this._shared === null) {
          this._shared = this._source.next().then((r) => {
            this._shared = null;
            if (!r.done) {
              buffer.push(r.value);
            }
            return r;
          });
        }

        ({ done } = await this._shared.catch((e) => {
          this._error = e;
          this._stopped = true;
          throw e;
        }));

        if (!done) {
          yield buffer.get(i);
        }
      } while (!done);
    } finally {
      buffer.done();
    }
  }
}

/**
 * Creates a buffer with a view over the source sequence, causing a specified number of iterators to obtain access
 * to all of the sequence's elements without causing multiple enumerations over the source.
 * @template TSource Source sequence element type.
 * @param {number} [readerCount] Number of iterators that can access the underlying buffer.
 * Once every iterator has obtained an element from the buffer, the element is removed from the buffer.
 * @returns {OperatorAsyncFunction<TSource, TSource>} Buffer enabling a specified number of iterators to retrieve all
 * elements from the shared source sequence, without duplicating source iteration side-effects.
 */
export function memoize<TSource>(readerCount?: number): OperatorAsyncFunction<TSource, TSource>;
/**
 * Memoizes the source sequence within a selector function where a specified number of iterators can get access
 * to all of the sequence's elements without causing multiple iterations over the source.
 *
 * @template TSource Source sequence element type.
 * @template TResult Result sequence element type.
 * @param {number} [readerCount] Number of iterators that can access the underlying buffer. Once every
 * iterator has obtained an element from the buffer, the element is removed from the buffer.
 * @param {(value: AsyncIterableX<TSource>) => AsyncIterable<TResult>} [selector] Selector function with memoized access
 * to the source sequence for a specified number of iterators.
 * @returns {OperatorAsyncFunction<TSource, TResult>} Sequence resulting from applying the selector function to the
 * memoized view over the source sequence.
 */
export function memoize<TSource, TResult>(
  readerCount?: number,
  selector?: (value: AsyncIterable<TSource>) => AsyncIterable<TResult>
): OperatorAsyncFunction<TSource, TResult>;
/**
 * Memoizes the source sequence within a selector function where a specified number of iterators can get access
 * to all of the sequence's elements without causing multiple iterations over the source.
 *
 * @template TSource Source sequence element type.
 * @template TResult Result sequence element type.
 * @param {number} [readerCount=-1] Number of iterators that can access the underlying buffer. Once every
 * iterator has obtained an element from the buffer, the element is removed from the buffer.
 * @param {(value: AsyncIterable<TSource>) => AsyncIterable<TResult>} [selector] Selector function with memoized access
 * to the source sequence for a specified number of iterators.
 * @returns {(OperatorAsyncFunction<TSource, TSource | TResult>)} Sequence resulting from applying the selector function to the
 * memoized view over the source sequence.
 */
export function memoize<TSource, TResult = TSource>(
  readerCount = -1,
  selector?: (value: AsyncIterable<TSource>) => AsyncIterable<TResult>
): OperatorAsyncFunction<TSource, TSource | TResult> {
  return function memoizeOperatorFunction(
    source: AsyncIterable<TSource>
  ): AsyncIterableX<TSource | TResult> {
    if (!selector) {
      return readerCount === -1
        ? new MemoizeAsyncBuffer<TSource>(
            source[Symbol.asyncIterator](),
            new MaxRefCountList<TSource>()
          )
        : new MemoizeAsyncBuffer<TSource>(
            source[Symbol.asyncIterator](),
            new RefCountList<TSource>(readerCount)
          );
    }
    return create<TSource | TResult>(() =>
      selector!(memoize<TSource>(readerCount)(source))[Symbol.asyncIterator]()
    );
  };
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 3856 $ -->
<!-- EN-Revision: 3827 Maintainer: takagi Status: ready -->
<!-- CREDITS: mat-sh,daichi,joe -->
<chapter id="language.modifiers">
 <title>変数の修飾子</title>
 <para>
  変数の修飾子は、
  <link linkend="language.syntax.variables">変数</link> や
  <link linkend="language.custom.functions">カスタム関数</link>
  や文字列を修飾して出力することができます。修飾子を適用するには、
  変数名の後に <literal>|</literal> (パイプ) と修飾子の名前を指定します。
  また、修飾子はその動作に影響を及ぼす追加のパラメータを受け入れる場合もあります。
  そのパラメータは修飾子の後に続き、<literal>:</literal> (コロン) によって区切られます。
  また、<emphasis>すべての PHP 関数は、暗黙的に修飾子として使用でき</emphasis>
  (あとで説明します)、修飾子は <link linkend="language.combining.modifiers">組み合わせる</link>
  こともできます。
 </para>
 <example>
  <title>修飾子の例</title>
  <programlisting>
<![CDATA[
{* 変数に修飾子を適用 *}
{$title|upper}

{* パラメータを持つ修飾子 *}
{$title|truncate:40:"..."}

{* 関数のパラメータに修飾子を適用 *}
{html_table loop=$myvar|upper}

{* パラメータ付き *}
{html_table loop=$myvar|truncate:40:"..."}

{* リテラル文字列に修飾子を適用 *}
{"foobar"|upper}

{* 現在の日付を整形するために date_format を使用 *}
{$smarty.now|date_format:"%Y/%m/%d"}

{* カスタム関数に修飾子を適用 *}
{mailto|upper address="smarty@example.com"}

{* php の str_repeat を使用 *}
{"="|str_repeat:80}

{* php の count *}
{$myArray|@count}

(* 配列全体の大文字変換と切り詰め *}
<select name="name_id">
{html_options output=$my_array|upper|truncate:20}
</select>
]]>
  </programlisting>
 </example>
 <itemizedlist>

 <listitem><para>
  修飾子は、配列やオブジェクトを含む任意の型の変数に適用することができます。

    <note><para>Smarty 3 ではデフォルトの挙動が変わりました。Smarty 2.x の場合は
    配列に修飾子を適用するときには "<literal>@</literal>" を使って
    <literal>{$articleTitle|@count}</literal> のようにする必要がありましたが、
    Smarty 3 では "<literal>@</literal>" は不要になり、無視されます。
    </para>
    <para>
      配列の個々の要素に対して修飾子を適用したい場合は、
      テンプレート内で配列をループさせるか
      修飾子関数の中にその機能を組み込まなければなりません。
    </para></note>
  </para>
 </listitem>

 <listitem><para>
  修飾子は <link
  linkend="variable.plugins.dir"><parameter>$plugins_dir</parameter></link>
  から自動的に読み込むか、明示的に <link
  linkend="api.register.plugin"><varname>registerPlugin()</varname></link>
  関数で登録します。2つ目の方法は、PHP スクリプトと Smarty テンプレートで
  関数を共有する場合などに有用です。
  </para></listitem>

  <listitem><para>
  先ほどの例で示したように、全ての PHP 関数は暗黙で修飾子として使用する事ができます。
  しかし、修飾子としてPHP関数を使うには2つの小さな落とし穴があります。
   <itemizedlist>
  <listitem><para>第1に、 たまに関数のパラメータの順序が望ましいものではなくります。
   <literal>$foo</literal> を
   <literal>{"%2.f"|sprintf:$foo}</literal> でフォーマットすることはできますが、
   Smarty が提供する方式である <literal>{$foo|string_format:"%2.f"}</literal>
   のほうがより直感的です。
  </para></listitem>
   <listitem><para>
   第2に、セキュリティが有効な場合、
   修飾子として使用される全ての PHP 関数は
   セキュリティポリシーの <parameter>$modifiers</parameter>
   プロパティで信頼できるものとして定義される必要があります。
   詳細は <link linkend="advanced.features.security">セキュリティ</link>
   の節を参照ください。
  </para></listitem>
   </itemizedlist>
 </para></listitem>
  </itemizedlist>

 <para>
  <link linkend="api.register.plugin"><varname>registerPlugin()</varname></link>、
  <link linkend="language.combining.modifiers">修飾子の連結</link>
  および
  <link linkend="plugins">プラグインによる Smarty の拡張</link>
  も参照ください。
 </para>

 &designers.language-modifiers.language-modifier-capitalize;
 &designers.language-modifiers.language-modifier-cat;
 &designers.language-modifiers.language-modifier-count-characters;
 &designers.language-modifiers.language-modifier-count-paragraphs;
 &designers.language-modifiers.language-modifier-count-sentences;
 &designers.language-modifiers.language-modifier-count-words;
 &designers.language-modifiers.language-modifier-date-format;
 &designers.language-modifiers.language-modifier-default;
 &designers.language-modifiers.language-modifier-escape;
 &designers.language-modifiers.language-modifier-indent;
 &designers.language-modifiers.language-modifier-lower;
 &designers.language-modifiers.language-modifier-nl2br;
 &designers.language-modifiers.language-modifier-regex-replace;
 &designers.language-modifiers.language-modifier-replace;
 &designers.language-modifiers.language-modifier-spacify;
 &designers.language-modifiers.language-modifier-string-format;
 &designers.language-modifiers.language-modifier-strip;
 &designers.language-modifiers.language-modifier-strip-tags;
 &designers.language-modifiers.language-modifier-truncate;
 &designers.language-modifiers.language-modifier-upper;
 &designers.language-modifiers.language-modifier-wordwrap;

</chapter>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package dm.data;

import java.io.StringWriter;
import java.util.HashSet;
import java.util.Set;

import dm.analyze.transitions.Transition;
import dm.util.Pair;

public class Trace {
	private TraceCall root = null;
	private Set<Pair<TraceCall, Transition>> unmergedTransitions = new HashSet<Pair<TraceCall, Transition>>();

	public TraceCall getRoot() {
		return root;
	}

	public void setRoot(TraceCall root) {
		this.root = root;
	}

	public void addUnmergedTransition(TraceCall call, Transition transition) {
		for (Pair<TraceCall, Transition> unmerged : this.unmergedTransitions) {
			if (unmerged.getFirst().equals(call)) {
				return;
			}
		}
		unmergedTransitions.add(new Pair<TraceCall, Transition>(call,
				transition));
	}

	@Override
	public String toString() {

		StringWriter s = new StringWriter();

		if (unmergedTransitions.size() > 0) {
			for (Pair<TraceCall, Transition> unmerged : unmergedTransitions) {
				s.append(String.format("%s", unmerged.getSecond().toString()));
				s.append("\n");
				s.append(unmerged.getFirst().toString());
				s.append("\n");
				s.append("---\n");
			}
			s.append("\n");
		}

		return String.format("%s%s", s.toString(), root);
	}

	public void resolveUnmerged() {
		Set<Pair<TraceCall, Transition>> remainUnmerged = new HashSet<Pair<TraceCall, Transition>>();
		for (Pair<TraceCall, Transition> unmerged : unmergedTransitions) {
			try {
				root = TraceCall.merge(root, unmerged.getFirst());
			} catch (MergeException e) {
				TraceCall caller = root.getCall(unmerged.getFirst()
						.getCallerID());
				if (caller != null) {
					caller.addCalled(unmerged.getFirst());
				} else {
					remainUnmerged.add(unmerged);
				}
			}
		}
		if (remainUnmerged.size() == unmergedTransitions.size()) {
			return;
		}
		unmergedTransitions = remainUnmerged;
		resolveUnmerged();
	}
}