text:
message_commands = { version=true, verack=true, addr=true, inv=true, getdata=true }

bitmessage_header_length = 24

bitmessage_proto = Proto("bitmessage","Bitmessage protocol")
-- create a function to dissect it
function bitmessage_proto.dissector(buffer,pinfo,tree)
    local magic = buffer(0,4):uint()
    if magic ~= 3921589465 then
	    tree:add(bitmessage_proto,buffer(),"Invalid Bitmessage data (invalid magic value " .. buffer(0,4) .. ")" )
	else
	    local offset = 0
		local command = buffer(4,12):stringz()
		local length = buffer(16,4):uint()
		local pdu_length = length + bitmessage_header_length
	    local subtree = tree:add(bitmessage_proto,buffer(),"Bitmessage protocol data (" .. command .. ")")
	    local headertree = subtree:add(buffer(0,bitmessage_header_length), "Header")
		headertree:add(buffer(4,12),"Command: " .. command)
		headertree:add(buffer(16,4),"Payload length: " .. length)
		headertree:add(buffer(20,4),"Checksum: " .. buffer(20,4) )

	    pinfo.cols.protocol = "BITMESSAGE"
	    local commandinfoname = "obj: " .. command
	    if message_commands[command] then
	    	commandinfoname = "msg: " .. command
	    end
		pinfo.cols.info = "["..commandinfoname.."], len: "..length

		if pdu_length > buffer:len() then
			pinfo.desegment_len = pdu_length - buffer:len()
		else
			local payload_buffer = buffer:range(bitmessage_header_length,length)
			do_payload_dissection(payload_buffer,pinfo,subtree,command)
		end
    end
end

function do_payload_dissection(buffer,pinfo,subtree,command)
	if message_commands[command] then
		do_message_dissection(buffer,pinfo,subtree,command)
	else
		do_object_dissection(buffer,pinfo,subtree,command)
	end
end

function do_message_dissection(buffer,pinfo,subtree,command)
	local offset = 0
	if command == "version" then
		subtree = subtree:add(buffer(), "version")
		local version = buffer(0,4):int()
		subtree:add(buffer(0,4), "Version: " .. version)
		subtree:add(buffer(4,8), "Services: " .. services_bitfield_to_string( buffer(4,8) ) )
		subtree:add(buffer(12,8), "Timestamp: " .. uint_to_date(buffer(12,8):uint64()))
		offset = 20
		offset = offset + parse_net_addr(buffer(offset,26),subtree:add(buffer(offset,26),"Receiver address"),version,false)
		offset = offset + parse_net_addr(buffer(offset,26),subtree:add(buffer(offset,26),"Sender address"),version,false)
		subtree:add(buffer(offset,8),"Nonce: " .. buffer(72,8) )
		offset = offset + 8
		local ua, ua_len = parse_var_string( buffer:range( 80 ) )
		subtree:add(buffer(80,ua_len), "User agent: " .. ua )
		offset = offset + ua_len
		local stream_nums, sn_len = parse_var_int_list( buffer:range( offset ) )
		subtree:add(buffer(offset,sn_len), "Stream numbers: [" .. table.concat( stream_nums, ", " ) .. "]" )
	elseif command == "verack" then
		-- No payload in verack
	elseif command == "addr" then
		subtree = subtree:add(buffer(), "addr")
		local addr_count, offset = parse_var_int(buffer)
		subtree:add(buffer(0,offset), "Address count: " .. addr_count)
		for i = 1, addr_count do
			local addr_tree = subtree:add(buffer(offset), "Address " .. i)
			local version = 1
			if buffer(offset,4):uint() == 0 then
				-- Assume version 2 (time length = 8)
				version = 2
			end
			local offset_add = parse_net_addr(buffer(offset),addr_tree,version,true)
			addr_tree:set_len(offset_add)
			offset = offset + offset_add
		end
	elseif command == "inv" then
		subtree = subtree:add(buffer(), "inv")
		local inv_count, offset = parse_var_int(buffer)
		subtree:add(buffer(0,offset), "Inventory count: " .. inv_count)
	elseif command == "getdata" then
		subtree = subtree:add(buffer(), "getdata")
		local inv_count, offset = parse_var_int(buffer)
		subtree:add(buffer(0,offset), "Inventory count: " .. inv_count)
	else
		subtree:add(buffer(),"Payload: " .. buffer() )
	end
end

function do_object_dissection(buffer,pinfo,subtree,command)
	local offset = 0
	if command == "getpubkey" then
		subtree = subtree:add(buffer(), "getpubkey")
		subtree:add(buffer(0,8), "POW nonce: " .. buffer(0,8))
		subtree:add(buffer(8,8), "Time: " .. uint_to_date( buffer(8,8):uint64()))
		offset = 16
		local addr_ver, offset_add = parse_var_int(buffer(offset))
		subtree:add(buffer(offset,offset_add), "Address version: " .. addr_ver)
		offset = offset + offset_add
		local stream_no, offset_add = parse_var_int(buffer(offset))
		subtree:add(buffer(offset,offset_add), "Stream number: " .. stream_no)
		offset = offset + offset_add
		if addr_ver <= 3 then
			subtree:add(buffer(offset,20), "RipeMD hash: " .. buffer(offset,20))
			offset = offset + 20
		end
		if addr_ver >= 4 then
			subtree:add(buffer(offset,32), "Tag: " .. buffer(offset,32) )
			offset = offset + 32
		end
	elseif command == "pubkey" then
		subtree = subtree:add(buffer(), "pubkey")
		subtree:add(buffer(0,8), "POW nonce: " .. buffer(0,8))
		subtree:add(buffer(8,8), "Time: " .. uint_to_date( buffer(8,8):uint64()))
		offset = 16
		local addr_ver, offset_add = parse_var_int(buffer(offset))
		subtree:add(buffer(offset,offset_add), "Address version: " .. addr_ver)
		offset = offset + offset_add
		local stream_no, offset_add = parse_var_int(buffer(offset))
		subtree:add(buffer(offset,offset_add), "Stream number: " .. stream_no)
		offset = offset + offset_add
		if addr_ver == 2 or addr_ver == 3 then
			subtree:add(buffer(offset,4), "Behaviour bitfield: " .. buffer(offset,4):bitfield(0,4))
			offset = offset + 4
			subtree:add(buffer(offset,64), "Public signing key: " .. buffer(offset,64))
			offset = offset + 64
			subtree:add(buffer(offset,64), "Public encryption key: " .. buffer(offset,64))
			offset = offset + 64
			if addr_ver == 3 then
				-- Version 3 pubkey
				local nonce_trials, int_len = parse_var_int(buffer(offset))
				subtree:add(buffer(offset,int_len), "Nonce trials per byte: " .. nonce_trials)
				offset = offset + int_len
				local extra_bytes, int_len = parse_var_int(buffer(offset))
				subtree:add(buffer(offset,int_len), "Extra bytes: " .. extra_bytes)
				offset = offset + int_len
				local sig_len, int_len = parse_var_int(buffer(offset))
				offset = offset + int_len
				subtree:add(buffer(offset,sig_len), "ECDSA signature: " .. buffer(offset,sig_len))
				offset = offset + sig_len
			end
		elseif addr_ver == 4 then
			subtree:add(buffer(offset,32), "Tag: " .. buffer(offset,32) )
			offset = offset + 32
			local encrypted_len = buffer:len() - offset
			parse_encrypted_payload(buffer(offset,encrypted_len),subtree:add(buffer(offset,encrypted_len), "Encrypted payload"))
		end
	elseif command == "msg" then
		subtree = subtree:add(buffer(), "msg")
		subtree:add(buffer(offset,8), "POW nonce: " .. buffer(offset,8))
		offset = offset + 8
		subtree:add(buffer(offset,8), "Time: " .. uint_to_date( buffer(offset,8):uint64()))
		offset = offset + 8
		local stream_no, offset_add = parse_var_int(buffer(offset))
		subtree:add(buffer(offset,offset_add), "Stream number: " .. stream_no)
		offset = offset + offset_add
		local encrypted_len = buffer:len() - offset
		if encrypted_len < 54 then
			subtree:add(buffer(offset,encrypted_len),"(Short encrypted payload, possibly an acknowledgement)")
		else
			parse_encrypted_payload(buffer(offset,encrypted_len),subtree:add(buffer(offset,encrypted_len), "Encrypted payload"))
		end
	elseif command == "broadcast" then
		subtree = subtree:add(buffer(), "broadcast")
		subtree:add(buffer(offset,8), "POW nonce: " .. buffer(offset,8))
		offset = offset + 8
		subtree:add(buffer(offset,8), "Time: " .. uint_to_date( buffer(offset,8):uint64()))
		offset = offset + 8
		local broadcast_ver, offset_add = parse_var_int(buffer(offset))
		subtree:add(buffer(offset,offset_add), "Broadcast version: " .. broadcast_ver)
		offset = offset + offset_add
		local stream_no, offset_add = parse_var_int(buffer(offset))
		subtree:add(buffer(offset,offset_add), "Stream number: " .. stream_no)
		offset = offset + offset_add
		if broadcast_ver >= 3 then
			subtree:add(buffer(offset,32), "Tag: " .. buffer(offset,32) )
			offset = offset + 32
		end
		parse_encrypted_payload(buffer(offset,encrypted_len),subtree:add(buffer(offset,encrypted_len), "Encrypted payload"))
	end
end

function parse_net_addr(buffer,subtree,version,include_time_and_stream)
	local offset = 0
	if include_time_and_stream then
		if version == 1 then
			subtree:add(buffer(0,4), "Time: " .. uint_to_date( buffer(0,4):uint()))
			offset = 4
		elseif version == 2 then
			subtree:add(buffer(0,8), "Time: " .. uint_to_date( buffer(0,8):uint64()))
			offset = 8
		end
		subtree:add(buffer(offset,4), "Stream number: " .. buffer(offset,4):uint() )
		offset = offset + 4
	end
	subtree:add(buffer(offset,8), "Services " .. services_bitfield_to_string( buffer(offset,8 ) ) )
	offset = offset + 8
	subtree:add(buffer(offset,16), "Address: " .. ipv6_to_string( buffer( offset, 16 ) ) )
	offset = offset + 16
	subtree:add(buffer(offset,2), "Port: " .. buffer(offset,2):uint() )
	offset = offset + 2

	return offset
end

function parse_encrypted_payload(buffer,subtree)
	local offset = 0
	subtree:add(buffer(offset,16),"Initialization vector: " .. buffer(offset,16))
	offset = offset + 16
	subtree:add(buffer(offset,2),"Elliptic curve type: " .. buffer(offset,2):uint())
	offset = offset + 2
	local x_len = buffer(offset,2):uint()
	subtree:add(buffer(offset,2), "X length: " .. x_len)
	offset = offset + 2
	subtree:add(buffer(offset,x_len),"X : " .. buffer(offset,x_len))
	offset = offset + x_len
	local y_len = buffer(offset,2):uint()
	subtree:add(buffer(offset,2), "Y length: " .. y_len)
	offset = offset + 2
	subtree:add(buffer(offset,x_len),"Y : " .. buffer(offset,y_len))
	offset = offset + y_len
	local encrypted_len = buffer:len() - offset - 32
	subtree:add(buffer(offset,encrypted_len), "(Cipher text)")
	offset = offset + encrypted_len
	subtree:add(buffer(offset,32), "HMAC: " .. buffer(offset, 32))
	offset = offset + 32
end

function ipv6_to_string(buffer)
	-- For now, only support IPv4 mapped address (the last 4 bytes of the 16 byte string is the IPv4 address)
	return "IPv4: " .. buffer(12,1):uint() .. "." .. buffer(13,1):uint() .. "." .. buffer(14,1):uint() .. "." .. buffer(15,1):uint()
end

function parse_var_int(buffer)
	local marker = buffer(0,1):uint()
	if marker < 0xfd then
		return marker, 1
	elseif marker == 0xfd then
		return buffer(1,2):uint(), 3
	elseif marker == 0xfe then
		return buffer(1,4):uint(), 5
	else
		return buffer(1,8):uint64(), 9
	end
end

function parse_var_string(buffer)
	local len, offset = parse_var_int(buffer)
	if len == 0 then
		return "", 1
	else
		local str = buffer(offset,len):string()
		return str, offset + len
	end
end

function parse_var_int_list(buffer)
	local len, offset = parse_var_int(buffer)
	local result = {}
	for i = 1, len do
		local entry, offset_add = parse_var_int(buffer:range(offset))
		table.insert( result, entry )
		offset = offset + offset_add
	end
	return result, offset
end

function services_bitfield_to_string(buffer)
	return buffer(0,8):bitfield(0,8)
end

function uint_to_date(uint)
	-- http://ask.wireshark.org/answer_link/11697/
	return format_date(tonumber(tostring(uint)))
end

-- load the tcp.port table
tcp_table = DissectorTable.get("tcp.port")
-- register our protocol to handle tcp port 8444
tcp_table:add(8444,bitmessage_proto)


text:
package org.apache.cassandra.thrift;

public enum RequestType
{
    READ,
    WRITE
}

redpajama_set_name: RedPajamaGithub


text:
import PhpStorm from '../../src/editors/phpstorm';

const sinon = require('sinon');

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

const { expect } = chai;
chai.use(chaiAsPromised);

describe('PhpStorm', () => {
  let phpStorm: PhpStorm;
  let isDirectorySyncStub: any;
  let isFileSyncStub: any;

  beforeEach(() => {
    phpStorm = new PhpStorm();
    isDirectorySyncStub = sinon.stub(phpStorm, 'isDirectorySync');
    isFileSyncStub = sinon.stub(phpStorm, 'isFileSync');
  });
  afterEach(() => {
    isDirectorySyncStub.restore();
    isFileSyncStub.restore();
  });
  it('should return the correct key name', () => {
    const result = phpStorm.key;
    expect(result).to.equal('phpstorm');
  });
  it('should return the correct editor name', () => {
    const result = phpStorm.name;
    expect(result).to.equal('PhpStorm');
  });
  it('should return TRUE if editor is installed', async () => {
    isDirectorySyncStub.returns(true);
    const result = await phpStorm.isEditorInstalled();
    expect(result).to.be.true;
  });
  it('should return TRUE if editor is not installed', async () => {
    isDirectorySyncStub.returns(false);
    const result = await phpStorm.isEditorInstalled();
    expect(result).to.be.false;
  });
  it('should return TRUE if plugin is installed', async () => {
    isFileSyncStub.returns(true);
    const result = await phpStorm.isPluginInstalled();
    expect(result).to.be.true;
  });
  it('should return FALSE if plugin is not installed', async () => {
    isFileSyncStub.returns(false);
    const result = await phpStorm.isPluginInstalled();
    expect(result).to.be.false;
  });
});


text:
package org.apache.sqoop.manager.oracle.util;

/**
 * Generates test data for Oracle INTERVAL YEAR TO MONTH columns.
 */
public class IntervalYearMonthGenerator extends
                 OraOopTestDataGenerator<String> {
  private final int precision;
  private final int minYear;
  private final int maxYear;

  /**
   * Create a generator that will generate intervals with the specified
   * precision for years.
   *
   * @param precision
   *          Number of decimal digits in the years part of each interval
   */
  public IntervalYearMonthGenerator(int precision) {
    super();
    this.precision = precision;
    this.minYear = -(int) Math.pow(10, precision) + 1;
    this.maxYear = (int) Math.pow(10, precision) - 1;
  }

  @Override
  public String next() {
    int years = minYear + rng.nextInt(maxYear - minYear + 1);
    int months = rng.nextInt(12);
    return String.format("%+0" + precision + "d-%02d", years, months);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Matlab.Nodes
{
    [Serializable]
    public class AttributeNode : OuterNode
    {
        #region PROPERTIES:

        #region STRUCTURE PROPERTIES:

        [Structure(Index = 0)]
        public NameNode Name
        {
            get
            {
                return this.Children.OfType<NameNode>().First();
            }
        }

        [Structure(Index = 1)]
        public ExpressionNode Value
        {
            get
            {
                return this.Children.OfType<ExpressionNode>().First();
            }
        }

        #endregion

        #endregion

        #region CONSTRUCTORS:

        public AttributeNode()
            : base()
        {
            return;
        }

        #endregion
    }
}


text:
//
// GDataCodeSearch.h
//

#import "GDataElements.h"

// Code Search
#import "GDataCodeSearchFile.h"
#import "GDataCodeSearchPackage.h"
#import "GDataCodeSearchMatch.h"
#import "GDataEntryCodeSearch.h"
#import "GDataFeedCodeSearch.h"


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using PoshSec.Framework.Interface;
using PoshSec.Framework.Strings;

namespace PoshSec.Framework
{
    internal class NetworkBrowser
    {
        private readonly Network _network;

        private static string _arp;
        private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        //public bool CancelScan { get; set; }

        public event EventHandler<NetworkScanCompleteEventArgs> NetworkScanComplete;
        public event EventHandler<EventArgs> NetworkScanCancelled;
        public event EventHandler<ScanStatusEventArgs> ScanStatusUpdate;

        public NetworkBrowser(Network network)
        {
            _network = network;
        }

        private async Task ScanActiveDirectoryAsync()
        {
            var hostPc = new DirectoryEntry { Path = "LDAP://" + _network.Name };
            SearchResultCollection searchResults = null;

            void SearchDirectory()
            {
                using (var directorySearcher = new DirectorySearcher(hostPc))
                {
                    directorySearcher.Filter = "(&(objectClass=computer))";
                    directorySearcher.SearchScope = SearchScope.Subtree;
                    directorySearcher.PropertiesToLoad.Add("description");
                    try
                    {
                        searchResults = directorySearcher.FindAll();
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }

            void HandleResults(Task t)
            {
                if (searchResults != null && searchResults.Count > 0)
                {
                    var hostcnt = 0;
                    foreach (SearchResult result in searchResults)
                    {
                        hostcnt++;
                        var directoryEntry = result.GetDirectoryEntry();
                        var scnmsg = "Scanning " + directoryEntry.Name.Replace("CN=", "") + ", please wait...";
                        OnStatusUpdate(new ScanStatusEventArgs(scnmsg, hostcnt, searchResults.Count));
                        Application.DoEvents();
                        if (directoryEntry.Name.Replace("CN=", "") != "Schema" && directoryEntry.SchemaClassName == "computer")
                        {
                            Ping(directoryEntry.Name.Replace("CN=", ""), 1, 100);
                            _network.Nodes.AddRange(GetSystems(directoryEntry));
                        }
                    }
                }
            }

            var task = Task.Factory
                .StartNew(SearchDirectory, TaskCreationOptions.LongRunning)
                .ContinueWith(HandleResults);

            await task;

            BuildArpTable();
            OnNetworkScanComplete(new NetworkScanCompleteEventArgs(_network));
        }

        private IEnumerable<NetworkNode> GetSystems(DirectoryEntry directoryEntry)
        {
            var nodes = new List<NetworkNode>();
            var ipAddresses = GetIPAddresses(directoryEntry.Name.Replace("CN=", ""));
            foreach (var ip in ipAddresses)
            {
                OnStatusUpdate(new ScanStatusEventArgs("Adding " + directoryEntry.Name.Replace("CN=", "") + ", please wait...", 0, 255));
                var macaddr = GetMac(ip);
                var isup = macaddr != StringValue.BlankMAC;
                var node = new NetworkNode
                {
                    Name = directoryEntry.Name.Replace("CN=", ""),
                    IpAddress = ip,
                    MacAddress = macaddr,
                    Description = (string)directoryEntry.Properties["description"].Value ?? "",
                    Status = isup ? StringValue.Up : StringValue.Down,
                    ClientInstalled = StringValue.NotInstalled,
                    Alerts = 0,
                    LastScanned = DateTime.Now
                };
                nodes.Add(node);
            }
            return nodes;
        }

        private async Task ScanLocalNetworkAsync()
        {
            var localIPs = GetIPAddresses(Dns.GetHostName()).ToArray();
            var localIP = localIPs.First();

            if (localIPs.Length > 1)
                localIP = PromptUserToSelectIP(localIPs);

            if (localIP == null)
            {
                OnScanCancelled(new EventArgs());
                return;
            }

            OnStatusUpdate(new ScanStatusEventArgs("", 0, 255));

            _arp = BuildArpTable();

            var tasks = new List<Task>();

            var maxThread = new SemaphoreSlim(20);

            var localIpBytes = localIP.GetAddressBytes();
            for (byte b = 1; b < 255; b++)
            {
                maxThread.Wait(_cancellationTokenSource.Token);

                var scanIp = new IPAddress(new[] { localIpBytes[0], localIpBytes[1], localIpBytes[2], b });

                var b2 = b;
                var task = Task.Factory.StartNew(() =>
                    {
                        OnStatusUpdate(new ScanStatusEventArgs("Scanning " + scanIp + ", please wait...", b2, 255));
                        var networkNode = Scan(scanIp);
                        if (networkNode.Status == StringValue.Up) _network.Nodes.Add(networkNode);
                    }, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
                    .ContinueWith(t => maxThread.Release());

                tasks.Add(task);
                Application.DoEvents();
                if (_cancellationTokenSource.IsCancellationRequested)
                    break;
            }

            OnStatusUpdate(new ScanStatusEventArgs(StringValue.WaitingForHostResp, 255, 255));

            await Task.WhenAll(tasks).ContinueWith(t =>
            {
                OnStatusUpdate(new ScanStatusEventArgs(StringValue.Ready, 0, 255));

                OnNetworkScanComplete(new NetworkScanCompleteEventArgs(_network));
            });
        }

        private static IPAddress PromptUserToSelectIP(IEnumerable<IPAddress> ipAddresses)
        {
            using (var frm = new frmScan
            {
                IPs = ipAddresses.Select(ip => ip.ToString()).ToArray(),
                StartPosition = FormStartPosition.CenterScreen
            })
            {
                return frm.ShowDialog() == DialogResult.OK ? IPAddress.Parse(frm.SelectedIP) : null;
            }
        }

        public async Task ScanAsync()
        {
            if (_network == null) return;
            _network.Nodes.Clear();
            ClearArpTable();

            switch (_network)
            {
                case LocalNetwork _:
                    await ScanLocalNetworkAsync();
                    break;
                case DomainNetwork _:
                    await ScanActiveDirectoryAsync();
                    break;
            }
        }

        private static NetworkNode Scan(IPAddress ipAddress)
        {
            var host = StringValue.NAHost;
            var isup = false;
            var ipaddr = ipAddress.ToString();
            if (ipaddr != "")
            {
                if (Ping(ipaddr, 1, 100))
                {
                    isup = true;
                    host = GetHostname(ipAddress);
                }
            }
            var networkNode = new NetworkNode
            {
                IpAddress = ipAddress,
                Name = host,
                MacAddress = GetMac(ipAddress),
                Status = isup ? StringValue.Up : StringValue.Down,
                LastScanned = DateTime.Now
            };
            return networkNode;
        }

        public static bool Ping(string host, int attempts, int timeout)
        {
            var response = false;
            try
            {
                var ping = new Ping();

                for (var attempt = 0; attempt < attempts; attempt++)
                    try
                    {
                        var pingReply = ping.Send(host, timeout);
                        if (pingReply?.Status == IPStatus.Success) response = true;
                    }
                    catch (Exception ex)
                    {
                        response = false;
                    }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            return response;
        }

        public static IEnumerable<IPAddress> GetIPAddresses(string host)
        {
            var addressList = new List<IPAddress>();
            try
            {
                var ipentry = Dns.GetHostEntry(host.Replace("CN=", ""));
                var addrs = ipentry.AddressList;
                addressList.AddRange(addrs.Where(addr => addr.AddressFamily == AddressFamily.InterNetwork));
            }
            catch (Exception ex)
            {
                addressList.Add(IPAddress.Any);
            }

            return addressList;
        }

        public static string GetMac(IPAddress ipAddress)
        {
            var rtn = "";
            if (!string.IsNullOrEmpty(_arp))
            {
                string ip = ipAddress.ToString();
                var ipidx = _arp.IndexOf(ip + " ", 0);
                if (ipidx > -1)
                {
                    var mac = _arp.Substring(ipidx, 39).Replace(ip, "").Trim();
                    if (mac.Contains("---")) mac = GetMyMac(ipAddress);
                    rtn += mac + ",";
                }
                else
                {
                    rtn += GetMyMac(ipAddress);
                }

                if (rtn.EndsWith(",")) rtn = rtn.Substring(0, rtn.Length - 1);
            }

            if (rtn == "") rtn = StringValue.BlankMAC;
            return rtn;
        }

        public static string GetMyMac(IPAddress ipAddress)
        {
            var mac = StringValue.BlankMAC;
            try
            {
                var psi = new ProcessStartInfo("ipconfig")
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    Arguments = "/all"
                };
                var prc = new Process { StartInfo = psi };
                prc.Start();
                var ipconfig = prc.StandardOutput.ReadToEnd();
                prc.WaitForExit();

                if (!string.IsNullOrEmpty(ipconfig))
                {
                    var ipaddr = ipAddress.ToString();
                    var ipidx = ipconfig.IndexOf(ipaddr, 0, StringComparison.Ordinal);
                    if (ipidx > -1)
                    {
                        var paidx = ipconfig.ToLower().LastIndexOf("physical address", ipidx, StringComparison.Ordinal);
                        if (paidx > -1)
                            mac = ipconfig.Substring(paidx, 53).Replace("Physical Address. . . . . . . . . : ", "");
                    }
                }
            }
            catch (Exception)
            {
                mac = StringValue.BlankMAC;
            }

            return mac;
        }

        private static string GetHostname(IPAddress ipAddress)
        {
            try
            {
                var ipentry = Dns.GetHostEntry(ipAddress);
                return ipentry.HostName;
            }
            catch
            {
                return StringValue.NAHost;
            }
        }

        private static void ClearArpTable()
        {
            try
            {
                var psi = new ProcessStartInfo("arp")
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    Arguments = "-d"
                };
                var prc = new Process
                {
                    StartInfo = psi
                };
                prc.Start();
                prc.WaitForExit();
            }
            catch (Exception)
            {
                //do nothing
            }
        }

        private static string BuildArpTable()
        {
            try
            {
                var psi = new ProcessStartInfo("arp")
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    Arguments = "-a"
                };
                var prc = new Process
                {
                    StartInfo = psi
                };
                prc.Start();
                var arp = prc.StandardOutput.ReadToEnd();
                prc.WaitForExit();
                return arp;
            }
            catch (Exception)
            {
                //do nothing
            }

            return null;
        }

        private void OnStatusUpdate(ScanStatusEventArgs e)
        {
            Trace.TraceInformation(e.Status);
            var handler = ScanStatusUpdate;
            handler?.Invoke(this, e);
        }

        private void OnNetworkScanComplete(NetworkScanCompleteEventArgs e)
        {
            Trace.TraceInformation($"Scan of {e.Network.Name} complete.");
            var handler = NetworkScanComplete;
            handler?.Invoke(this, e);
        }

        private void OnScanCancelled(EventArgs e)
        {
            var handler = NetworkScanCancelled;
            handler?.Invoke(this, e);
        }

        public void CancelScan()
        {
            _cancellationTokenSource.Cancel();
        }
    }
}


text:
<?xml version="1.0"?>
<monkeyml version="1.0">
    <io_devices/>
    <variables>
	        <variable tag="X" default_value="0" scope="GLOBAL" type="INTEGER" editable="NEVER" logging="WHEN_CHANGED" persistant="NO"/>
    </variables>
    <sounds/>
    <stimuli>
        <stimulus_group tag="mainGroup" full_name="fullname_3">
            <stimulus_group tag="subGroup1A" full_name="fullname_3">
                <stimulus_group tag="subGroup1A-2A" full_name="fullname_3">
                    <stimulus tag="XIM000" full_name="XIM 000" type="image_file" path="./zero.0.jpg" x_size="25" y_size="25" x_position="0" y_position="0" rotation="0"/>
                    <stimulus tag="XIM001" full_name="XIM 001" type="image_file" path="./1.png" x_size="25" y_size="25" x_position="0" y_position="0" rotation="90/11"/>
                </stimulus_group>
                <stimulus_group tag="subGroup1A-2B" full_name="fullname_3">
                    <stimulus tag="XIM002" full_name="XIM 002" type="image_file" path="./2.png" x_size="25" y_size="25" x_position="0" y_position="0" rotation="2*90/11"/>
                    <stimulus tag="XIM003" full_name="XIM 003" type="image_file" path="./3.png" x_size="25" y_size="25" x_position="0" y_position="0" rotation="3*90/11"/>
                </stimulus_group>
                <stimulus_group tag="subGroup1A-2C" full_name="fullname_3">
                    <stimulus tag="XIM004" full_name="XIM 004" type="image_file" path="./4.png" x_size="25" y_size="25" x_position="0" y_position="0" rotation="4*90/11"/>
                    <stimulus tag="XIM005" full_name="XIM 005" type="image_file" path="./5.png" x_size="25" y_size="25" x_position="0" y_position="0" rotation="5*90/11"/>
                </stimulus_group>
            </stimulus_group>
            <stimulus_group tag="subGroup1B" full_name="fullname_3">
                <stimulus_group tag="subGroup1B-2A" full_name="fullname_3">
                    <stimulus tag="XIM006" full_name="XIM 006" type="image_file" path="./6.png" x_size="25" y_size="25" x_position="0" y_position="0" rotation="6*90/11"/>
                    <stimulus tag="XIM007" full_name="XIM 007" type="image_file" path="./7.png" x_size="25" y_size="25" x_position="0" y_position="0" rotation="7*90/11"/>
                </stimulus_group>
                <stimulus_group tag="subGroup1B-2B" full_name="fullname_3">
                    <stimulus tag="XIM008" full_name="XIM 008" type="image_file" path="./ball-crazy-eight.jpg" x_size="25" y_size="25" x_position="0" y_position="0" rotation="8*90/11"/>
                    <stimulus tag="XIM009" full_name="XIM 009" type="image_file" path="./764px-Old_Nine_Network.svg.png" x_size="25" y_size="25" x_position="0" y_position="0" rotation="9*90/11"/>
                </stimulus_group>
                <stimulus_group tag="subGroup1B-2C" full_name="fullname_3">
                    <stimulus tag="XIM010" full_name="XIM 010" type="image_file" path="./ten.jpg" x_size="25" y_size="25" x_position="0" y_position="0" rotation="10*90/11"/>
                    <stimulus tag="XIM011" full_name="XIM 011" type="image_file" path="./eleven-lallone.jpg" x_size="25" y_size="25" x_position="0" y_position="0" rotation="11*90/11"/>
                </stimulus_group>
            </stimulus_group>
        </stimulus_group>
    </stimuli>
    <experiment tag="MultiDimensionalStimuliTest3">
        <protocol tag="Protocol" interruptible="YES" selection="sequential_ascending" nsamples="1" sampling_method="cycles">
            <block tag="Block" interruptible="YES" selection="sequential_ascending" nsamples="1" sampling_method="samples">
                <task_system tag="Task System_Count" interruptible="YES">
                    <task_system_state tag="cycle_stim" interruptible="YES">
                        <action type="queue_stimulus" stimulus="mainGroup[X]"/>
                        <action type="update_stimulus_display"/>
                        <action type="wait" duration="1000000"/>
                        <action type="dequeue_stimulus" stimulus="mainGroup[X]"/>
                        <action type="update_stimulus_display"/>
						<action type="assignment" value="X+1" variable="X"/>
						<transition type="conditional" condition="X#LT12" target="cycle_stim"/>
                        <transition type="yield"/>
                    </task_system_state>
                </task_system>
            </block>
        </protocol>
    </experiment>
</monkeyml>


text:
#ifndef _P_QUEUE_H_
#define _P_QUEUE_H_

struct pqueue_t;

/** inicializa uma fila de prioridades
 * @param <size> quantidade de elementos a serem alocados
 */
struct pqueue_t *_pqueue_init 	(int);

/** desaloca a memória de uma fila de prioridades
 * @param <pqueue> fila para ser desalocada
 */
void _pqueue_destroy (struct pqueue_t *);

/** empilha um elemento na fila de prioridades
 * @param <pqueue> fila para inserir o elemento
 * @param <priority> elemento que será inserido
 */
void _pqueue_push 	(struct pqueue_t *, int);

/** imprime a fila de prioridades de cima pra baixo
 * @param <pqueue> fila para ser impressa
 */
void _pqueue_print_top_down (struct pqueue_t *);

/** imprime a fila de prioridades de baixo para cima
 * @param <pqueue> fila para ser impressa
 */
void _pqueue_print_bottom_up (struct pqueue_t *);

#endif


text:
import { createMergeReducer } from "create-reducer-extra";
import { filter } from "lodash";
import { ConnectionState } from "../state";

const initialState: ConnectionState = {
  collision: false,
  collisionId: 0,
  mergedWords: [],
  saved: undefined,
};

const reducer = createMergeReducer(initialState, {
  AddWord: () => ({mergedWords: [], collision: false}),
  NoWordCollision: () => ({collision: false}),
  SaveConnectionsFailure: () => ({saved: false}),
  SaveConnectionsStart: () => ({saved: undefined}),
  SaveConnectionsSuccess: () => ({saved: true}),
  Unmerge: ({mergedWords}, payload) => ({mergedWords: filter(mergedWords, (w) => w.wordId !== payload)}),
  WordChanged: () => ({collision: undefined}),
  WordCollision: ({}, payload) => ({collision: true, collisionId: payload}),
  WordsMerged: ({mergedWords}, payload) => ({collision: false, mergedWords: [payload, ...mergedWords]}),
  WordsReceived: () => ({collision: false}),
});

export default reducer;


text:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace Smart.Core.Extensions
{
    /// <summary>
    ///
    /// </summary>
    public static class PropertyInfoExtensions
    {
        /// <summary>
        /// 获取属性的显示名称 ,依次从 DescriptionAttribute ,DisplayNameAttribute,DisplayAttribute 特性获取
        /// </summary>
        /// <param name="property"></param>
        /// <param name="inherit">指定是否搜索该成员的继承链以查找这些特性。</param>
        /// <returns></returns>
        public static string GetDisplayName(this PropertyInfo property, bool inherit = true)
        {
            string displayName = string.Empty;
            var attrs = property.GetCustomAttributes(typeof(DescriptionAttribute), inherit);
            if (attrs.Length > 0)
            {
                displayName = (attrs[0] as DescriptionAttribute).Description;
            }

            if (string.IsNullOrEmpty(displayName))
            {
                attrs = property.GetCustomAttributes(typeof(DisplayNameAttribute), inherit);
                if (attrs.Length > 0)
                {
                    displayName = (attrs[0] as DisplayNameAttribute).DisplayName;
                }
            }

            if (string.IsNullOrEmpty(displayName))
            {
                attrs = property.GetCustomAttributes(typeof(DisplayAttribute), inherit);
                if (attrs.Length > 0)
                {
                    displayName = (attrs[0] as DisplayAttribute).Name;
                }
            }

            return string.IsNullOrEmpty(displayName) ? property.Name : displayName;
        }
    }
}


text:
**Ionic version:**  (check one with "x")
[ ] **2.x**
[ ] **3.x**
[ ] **4.x**

**Ion2-calendar mode:**  (check one with "x")
[ ] components mode
[ ] modal mode

**I'm submitting a ...**  (check one with "x")
[ ] bug report
[ ] feature request
[ ] help me

**Current behavior:**
<!-- Describe how the bug manifests. -->

**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->

**Steps to reproduce:**
<!--  Please explain the steps required to duplicate the issue, especially if you are able to provide a sample application. -->

**Related code:**

```
insert short code snippets here
```

**Other information:**

**Ionic info:** (run `ionic info` from a terminal/cmd prompt and paste output below):

```
insert the output from ionic info here
```


text:
/*
 * Conservative rasterization
 *
 * Note: Requires a device that supports the VK_EXT_conservative_rasterization extension
 *
 * Uses an offscreen buffer with lower resolution to demonstrate the effect of conservative rasterization
 */

#pragma once

#include "api_vulkan_sample.h"

#define FB_COLOR_FORMAT VK_FORMAT_R8G8B8A8_UNORM
#define ZOOM_FACTOR 16

class ConservativeRasterization : public ApiVulkanSample
{
  public:
	// Fetch and store conservative rasterization state props for display purposes
	VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative_raster_properties{};

	bool conservative_raster_enabled = true;

	struct Vertex
	{
		float position[3];
		float color[3];
	};

	struct Triangle
	{
		std::unique_ptr<vkb::core::Buffer> vertices;
		std::unique_ptr<vkb::core::Buffer> indices;
		uint32_t                           index_count;
	} triangle;

	std::unique_ptr<vkb::core::Buffer> uniform_buffer;

	struct UniformBuffers
	{
		std::unique_ptr<vkb::core::Buffer> scene;
	} uniform_buffers;

	struct UboScene
	{
		glm::mat4 projection;
		glm::mat4 model;
	} ubo_scene;

	struct PipelineLayouts
	{
		VkPipelineLayout scene;
		VkPipelineLayout fullscreen;
	} pipeline_layouts;

	struct Pipelines
	{
		VkPipeline triangle;
		VkPipeline triangle_conservative_raster;
		VkPipeline triangle_overlay;
		VkPipeline fullscreen;
	} pipelines;

	struct DescriptorSetLayouts
	{
		VkDescriptorSetLayout scene;
		VkDescriptorSetLayout fullscreen;
	} descriptor_set_layouts;

	struct DescriptorSets
	{
		VkDescriptorSet scene;
		VkDescriptorSet fullscreen;
	} descriptor_sets;

	// Framebuffer for offscreen rendering
	struct FrameBufferAttachment
	{
		VkImage        image;
		VkDeviceMemory mem;
		VkImageView    view;
	};
	struct OffscreenPass
	{
		int32_t               width, height;
		VkFramebuffer         framebuffer;
		FrameBufferAttachment color, depth;
		VkRenderPass          render_pass;
		VkSampler             sampler;
		VkDescriptorImageInfo descriptor;
	} offscreen_pass;

	ConservativeRasterization();
	~ConservativeRasterization();
	virtual void request_gpu_features(vkb::PhysicalDevice &gpu) override;
	void         build_command_buffers() override;
	void         prepare_offscreen();
	void         load_assets();
	void         setup_descriptor_pool();
	void         setup_descriptor_set_layout();
	void         setup_descriptor_set();
	void         prepare_pipelines();
	void         prepare_uniform_buffers();
	void         update_uniform_buffers_scene();
	void         draw();
	bool         prepare(vkb::Platform &platform) override;
	virtual void render(float delta_time) override;
	virtual void on_update_ui_overlay(vkb::Drawer &drawer) override;
};

std::unique_ptr<vkb::VulkanSample> create_conservative_rasterization();


text:
layout: page
title: Jarvis Family Reunion
date: 2016-05-24
author: Kyle Miller
tags: weekly links, java
status: published
summary: Nam lacinia viverra tellus, vel luctus ante vestibulum.
banner: images/banner/office-01.jpg
booking:
  startDate: 08/13/2019
  endDate: 08/16/2019
  ctyhocn: WINNJHX
  groupCode: JFR
published: true
---
Sed elit lacus, maximus eu sem in, ornare cursus nisl. Vivamus posuere, sapien vel eleifend volutpat, nunc turpis vulputate leo, quis egestas ligula quam id sem. Aliquam sit amet nulla placerat, vestibulum felis sed, pretium lorem. Vestibulum sed gravida turpis. Praesent malesuada varius mollis. Phasellus eleifend commodo gravida. Nunc eu tortor vulputate, tempor mauris dapibus, semper nisl. Ut sit amet ligula tortor.

* Duis condimentum velit vel turpis fringilla tempus
* Donec quis sem ut lacus gravida dignissim vitae non est.

Integer eu sodales mauris, ac accumsan eros. Nullam ultricies diam ut erat mattis, a imperdiet mi facilisis. Curabitur pretium imperdiet ante ut luctus. Sed condimentum augue eget eros dictum, vel vestibulum ipsum tincidunt. Cras ut auctor erat, ut porta nunc. Donec euismod sit amet ligula in ultrices. Nulla facilisi. Vivamus ac dui tellus. Ut ullamcorper tristique eros, sed tempor tellus varius eu. Nam sed finibus justo, non fringilla sapien. Cras aliquet erat ac lacinia euismod.
Mauris porttitor magna ac massa faucibus, quis venenatis nibh cursus. Praesent porta elementum tellus, vitae posuere mauris ullamcorper at. Aenean diam nulla, tempus sit amet feugiat in, tempus a purus. Curabitur laoreet faucibus est, eu commodo nibh porta ac. Aenean accumsan tincidunt velit, id pharetra sapien molestie in. Phasellus lobortis lobortis bibendum. Mauris tristique tincidunt lacus nec mattis. Donec malesuada purus lorem, a eleifend turpis mollis quis. Ut sagittis molestie eros dapibus semper.


text:
[LuaAV4](http://LuaAV.github.io/LuaAV4)
======

Real-time audiovisual scripting using LuaJIT


text:
. venv/bin/activate

python setup.py bdist_wheel


text:
#include "util/sstream.h"
#include "util/list_fn.h"
#include "util/rb_map.h"
#include "util/fresh_name.h"
#include "kernel/type_checker.h"
#include "kernel/kernel_exception.h"
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/find_fn.h"
#include "kernel/abstract_type_context.h"
#include "kernel/inductive/inductive.h"

/* The implementation is based on the paper: "Inductive Families", Peter Dybjer, 1997
   The main differences are:
      - Support for Prop (when environment is marked as impredicative)
      - Universe levels

   The support for Prop is based on the paper: "Inductive Definitions in the System Coq: Rules and Properties",
   Christine Paulin-Mohring.

   The kernel does not support mutually inductive types anymore. We simulate them using indexed families outside of the kernel.

   Given a sequence of universe levels parameters (m_level_names), a datatype decl is of the form
         I : (A :: \sigma) (a :: \alpha[A]), Type.{l_k}
             I is the name of the k-th inductive datatype
             A is the sequence of global parameters (it must have size m_num_params)
             a is the sequence of indices

   Each inductive declaration has a sequence of introduction rules of the form
         intro_i : (A :: \sigma) (b :: \beta[A]) (u :: \gama[A, b]), I A p[A, b]
               A is the sequence of global parameters (it must have size m_num_params)
               b is the sequence of non-recursive arguments (i.e., they do not include any I)
               u is the sequence of recursive arguments (they contain positive occurrences of I
         each u_i, in the sequence u, is of the form
               x :: \Epsilon[A, b], I A p_i[A, b, x]

         Remark: we don't enforce that all b arguments occur before all u arguments.

         Again, all introduction rules must have the same sequence of global parameters

   The universe levels of arguments b and u must be smaller than or equal to l_k in I.

   When the environment is marked as impredicative, then l_k must be 0 (Prop) or must be different from zero for
   any instantiation of the universe level parameters (and global level parameters).

   This module produces an eliminator/recursor for the inductive datatype I.
   The eliminator has an extra univese level parameter when
          1- Type.{0} is not impredicative in the given environment
          2- l_k is never zero (for any universe level assignment)
          3- There is only one introduction rule
   Let l' be this extra universe level, in the following rules, and 0 if none of the conditions above hold.

        elim : (A :: \sigma)
               (C :: (a :: \alpha[A]) (c : I A a), Type.{l'})
               (e :: \epsilon[A])
               (a :: \alpha[A])
               (n :: I A a),
             C_k a n

          A is the sequence of global parameters
          C is a type former (aka the motive).
          e is the sequence of minor premises. The size of the sequence is equal to the sum of the length of all introduction rules.
          a is the sequence of indices, it is equal to sequence occurring in I
          n is the major premise

    The minor premise e_j : \epsilon_j[A] in (e:: \epsilon[A]) corresponds to the j-th introduction rule in the inductive
    datatype I.

       \epsilon_j[A] : (b :: \beta[A]) (u :: \gama[A, b]) (v :: \delta[A, b]), C p[A, b] intro_j A b u

           b and u are the corresponding arguments in intro_j. \delta[A, b] has the same length of \gama[A, b],
           and \delta[A, b] is (x :: \Epsilon[A, b]), C p[A, b, x] (u x)

     When the environment is impredicative and l_k is zero, then we use nondependent elimination, and we omit
     the argument c in C, and v in the minor premises. That is, C becomes
            (C :: (a :: \alpha[A]), Type.{l'})
     and \epsilon_i_j[A]
            \epsilon_i_j[A] : (b :: \beta[A]) (u :: \gama[A, b]), C p[A, b]

     Finally, this module also generate computational rules for the extended normalizer. Actually, we only generate
     the right hand side for the rules. They have the form

        Fun (A, C, e, b, u), elim A C e p[A,b] (intro_i A b u) ==> Fun (A, C, e, b, u), (e_i b u v)
*/
namespace lean {
namespace inductive {
static name * g_ind_fresh           = nullptr; /* prefix for fresh names created in this module. */
static name * g_inductive_extension = nullptr;

/** \brief Environment extension used to store the computational rules associated with inductive datatype declarations. */
struct inductive_env_ext : public environment_extension {
    struct elim_info {
        name              m_inductive_name; // name of the inductive datatype associated with eliminator
        level_param_names m_level_names; // level parameter names used in computational rule
        unsigned          m_num_params = 0;  // number of global parameters A
        unsigned          m_num_ACe = 0;     // sum of number of global parameters A, type former C, and minor preimises e.
        unsigned          m_num_indices = 0; // number of inductive datatype indices
        /** \brief We support K-like reduction when the inductive datatype is in Type.{0} (aka Prop), proof irrelevance
            is enabled, it has only one introduction rule, the introduction rule has "0 arguments".
            Example: equality defined as

            inductive eq {A : Type} (a : A) : A -> Prop :=
            refl : eq a a

            satisfies these requirements when proof irrelevance is enabled.
            Another example is heterogeneous equality. */
        bool              m_K_target = false;
        /** \brief m_dep_elim == true, if dependent elimination is used for this eliminator */
        bool              m_dep_elim = false;
        elim_info() {}
        elim_info(name const & id_name, level_param_names const & ls, unsigned num_ps, unsigned num_ACe, unsigned num_indices,
                  bool is_K_target, bool dep_elim):
            m_inductive_name(id_name), m_level_names(ls), m_num_params(num_ps), m_num_ACe(num_ACe),
            m_num_indices(num_indices), m_K_target(is_K_target), m_dep_elim(dep_elim) {}
    };

    struct comp_rule {
        name              m_elim_name;     // name of the corresponding eliminator
        unsigned          m_num_bu = 0;    // sum of number of arguments u and v in the corresponding introduction rule.
        expr              m_comp_rhs;      // computational rule RHS: Fun (A, C, e, b, u), (e_k_i b u v)
        expr              m_comp_rhs_body; // body of m_comp_rhs:  (e_k_i b u v)
        comp_rule() {}
        comp_rule(name const & e, unsigned num_bu, expr const & rhs):
            m_elim_name(e), m_num_bu(num_bu), m_comp_rhs(rhs), m_comp_rhs_body(rhs) {
            while (is_lambda(m_comp_rhs_body))
                m_comp_rhs_body = binding_body(m_comp_rhs_body);
        }
    };

    // mapping from introduction rule name to computation rule data
    name_map<elim_info>             m_elim_info;
    name_map<comp_rule>             m_comp_rules;
    // mapping from intro rule to datatype
    name_map<name>                  m_intro_info;
    name_map<inductive_decl>        m_inductive_info;

    inductive_env_ext() {}

    void add_elim(name const & n, name const & id_name, level_param_names const & ls,
                  unsigned num_ps, unsigned num_ace, unsigned num_indices, bool is_K_target,
                  bool dep_elim) {
        m_elim_info.insert(n, elim_info(id_name, ls, num_ps, num_ace, num_indices, is_K_target, dep_elim));
    }

    void add_comp_rhs(name const & n, name const & e, unsigned num_bu, expr const & rhs) {
        m_comp_rules.insert(n, comp_rule(e, num_bu, rhs));
    }

    void add_intro_info(name const & ir_name, name const & id_name) {
        m_intro_info.insert(ir_name, id_name);
    }

    void add_inductive_info(inductive_decl const & d) {
        m_inductive_info.insert(d.m_name, d);
    }
};

/** \brief Auxiliary object for registering the environment extension */
struct inductive_env_ext_reg {
    unsigned m_ext_id;
    inductive_env_ext_reg() { m_ext_id = environment::register_extension(std::make_shared<inductive_env_ext>()); }
};

static inductive_env_ext_reg * g_ext = nullptr;

/** \brief Retrieve environment extension */
static inductive_env_ext const & get_extension(environment const & env) {
    return static_cast<inductive_env_ext const &>(env.get_extension(g_ext->m_ext_id));
}

/** \brief Update environment extension */
static environment update(environment const & env, inductive_env_ext const & ext) {
    return env.update(g_ext->m_ext_id, std::make_shared<inductive_env_ext>(ext));
}

/**\ brief Return recursor name */
name get_elim_name(name const & n) {
    return n + name("rec");
}

/**\ brief Return recursor name */
name get_cases_on_name(name const & n) {
    return n + name("cases_on");
}

environment certified_inductive_decl::add_constant(environment const & env, name const & n, level_param_names const & ls,
                                                   expr const & t) const {
    return env.add(certify_unchecked::certify_or_check(env, mk_constant_assumption(n, ls, t, m_is_trusted)));
}

environment certified_inductive_decl::add_core(environment const & env, bool update_ext_only) const {
    environment new_env = env;
    inductive_env_ext ext(get_extension(new_env));
    // declare inductive types
    if (!update_ext_only)
        new_env = add_constant(new_env, m_decl.m_name, m_decl.m_level_params, m_decl.m_type);
    ext.add_inductive_info(m_decl);
    // declare introduction rules
    for (auto ir : m_decl.m_intro_rules) {
        if (!update_ext_only)
            new_env = add_constant(new_env, intro_rule_name(ir), m_decl.m_level_params, intro_rule_type(ir));
        ext.add_intro_info(intro_rule_name(ir), m_decl.m_name);
    }
    // declare elimination rules
    name elim_name = get_elim_name(m_decl.m_name);
    if (!update_ext_only)
        new_env = add_constant(new_env, elim_name, m_elim_levels, m_elim_type);
    ext.add_elim(elim_name, m_decl.m_name, m_elim_levels, m_decl.m_num_params,
                 m_num_ACe, m_num_indices, m_K_target, m_dep_elim);
    list<comp_rule> rules = m_comp_rules;
    for (auto ir : m_decl.m_intro_rules) {
        comp_rule const & rule = head(rules);
        ext.add_comp_rhs(intro_rule_name(ir), elim_name, rule.m_num_bu, rule.m_comp_rhs);
        rules = tail(rules);
    }
    return update(new_env, ext);
}

environment certified_inductive_decl::add(environment const & env) const {
    if (env.trust_lvl() == 0) {
        return add_inductive(env, m_decl, m_is_trusted).first;
    } else {
        return add_core(env, false);
    }
}

/** \brief Helper functional object for processing inductive datatype declarations. */
struct add_inductive_fn {
    typedef std::unique_ptr<type_checker> type_checker_ptr;
    environment          m_env;
    name_generator       m_name_generator;
    inductive_decl       m_decl;
    // when kernel sets Type.{0} as impredicative, then
    // we track whether the resultant universe cannot be zero for any
    // universe level instantiation
    bool                 m_is_not_zero;
    list<level>          m_levels;       // m_decl.m_level_params ==> m_levels
    type_checker_ptr     m_tc;

    level                m_elim_level;   // extra universe level for eliminator.
    bool                 m_dep_elim;     // true if using dependent elimination

    buffer<expr>         m_param_consts; // local constants used to represent global parameters
    level                m_it_level;     // resultant level
    expr                 m_it_const;     // the constants for inductive datatype
    unsigned             m_it_num_args;  // number of arguments (params + indices) for inductive datatype

    struct elim_info {
        expr             m_C;              // type former constant
        buffer<expr>     m_indices;        // local constant for each index
        expr             m_major_premise;  // major premise for each inductive decl
        buffer<expr>     m_minor_premises; // minor premise for each introduction rule
        bool             m_K_target;
        elim_info():m_K_target(false) {}
    };
    elim_info            m_elim_info; // for datatype being declared
    bool                 m_is_trusted;

    add_inductive_fn(environment            env,
                     inductive_decl const & decl,
                     bool is_trusted):
        m_env(env), m_name_generator(*g_ind_fresh), m_decl(decl),
        m_tc(new type_checker(m_env, true, false)) {
        m_is_not_zero = false;
        m_levels      = param_names_to_levels(decl.m_level_params);
        m_is_trusted  = is_trusted;
    }

    /** \brief Make sure the latest environment is being used by m_tc. */
    void updt_type_checker() {
        m_tc.reset(new type_checker(m_env, true, false));
    }

    type_checker & tc() { return *(m_tc.get()); }
    bool is_def_eq(expr const & t, expr const & s) { return tc().is_def_eq(t, s); }
    expr whnf(expr const & e) { return tc().whnf(e); }
    expr ensure_type(expr const & e) { return tc().ensure_type(e); }

    /** \brief Create a local constant for the given binding. */
    expr mk_local_for(expr const & b) { return mk_local(m_name_generator.next(), binding_name(b), binding_domain(b), binding_info(b)); }

    /** \brief Return type of the i-th global parameter. */
    expr get_param_type(unsigned i) { return mlocal_type(m_param_consts[i]); }

    /** \brief Check if the type of datatype is well typed,
        and the number of parameters match the argument num_params.

        This method also populates the fields m_param_consts, m_elim_info.m_indices, m_it_level, m_it_const. */
    void check_inductive_type() {
        expr t       = m_decl.m_type;
        tc().check(t, m_decl.m_level_params);
        unsigned i    = 0;
        m_it_num_args = 0;
        t = whnf(t);
        while (is_pi(t)) {
            if (i < m_decl.m_num_params) {
                expr l = mk_local_for(t);
                m_param_consts.push_back(l);
                t = instantiate(binding_body(t), l);
                i++;
            } else {
                expr c = mk_local_for(t);
                m_elim_info.m_indices.push_back(c);
                t = instantiate(binding_body(t), c);
            }
            t = whnf(t);
            m_it_num_args++;
        }
        if (i != m_decl.m_num_params)
            throw kernel_exception(m_env, "number of parameters mismatch in inductive datatype declaration");
        t = tc().ensure_sort(t);
        // We track whether the resultant universe
        // is never zero (under any parameter assignment).
        // TODO(Leo): when the resultant universe may be 0 and not zero depending on parameter assignment,
        // we may generate two recursors: one when it is 0, and another one when it is not.
        m_is_not_zero = is_not_zero(sort_level(t));
        m_it_level = sort_level(t);
        m_it_const = mk_constant(m_decl.m_name, m_levels);
    }

    /** \brief Add all datatype declarations to environment. */
    void declare_inductive_type() {
        m_env = m_env.add(check(m_env, mk_constant_assumption(m_decl.m_name, m_decl.m_level_params, m_decl.m_type,
                                                              m_is_trusted)));
        updt_type_checker();
    }

    /** \brief Return true iff \c e is the inductive datatype being declared. */
    bool is_it_occ(expr const & e) {
        return is_constant(e) && const_name(e) == const_name(m_it_const);
    }

    /** \brief Return true if \c t does not contain any occurrence of a datatype being declared. */
    bool has_it_occ(expr const & t) {
        return (bool)find(t, [&](expr const & e, unsigned) { return is_it_occ(e); }); // NOLINT
    }

    /** \brief Return true iff \c t is a term of the form (I As t)
        where I is the inductive datatype being defined, and As are the
        global parameters of this declaration. Moreover I does not occur in t */
    bool is_valid_it_app(expr const & t) {
        buffer<expr> args;
        expr I = get_app_args(t, args);
        if (!is_def_eq(I, m_it_const) || args.size() != m_it_num_args)
            return false;
        unsigned i = 0;
        for (; i < m_decl.m_num_params; i++) {
            if (m_param_consts[i] != args[i])
                return false;
        }
        for (; i < args.size(); i++) {
            if (has_it_occ(args[i]))
                return false;
        }
        return true;
    }

    /** \brief Return some(d_idx) iff \c t is a recursive argument, \c d_idx is the index of the recursive inductive datatype.
        Return none otherwise. */
    bool is_rec_argument(expr t) {
        t = whnf(t);
        while (is_pi(t))
            t = whnf(instantiate(binding_body(t), mk_local_for(t)));
        return is_valid_it_app(t);
    }

    /** \brief Check if \c t contains only positive occurrences of the inductive datatypes being declared. */
    void check_positivity(expr t, name const & intro_name, int arg_idx) {
        t = whnf(t);
        if (!has_it_occ(t)) {
            // nonrecursive argument
        } else if (is_pi(t)) {
            if (has_it_occ(binding_domain(t)))
                throw kernel_exception(m_env, sstream() << "arg #" << (arg_idx + 1) << " of '" << intro_name << "' "
                                       "has a non positive occurrence of the datatypes being declared");
            check_positivity(instantiate(binding_body(t), mk_local_for(t)), intro_name, arg_idx);
        } else if (is_valid_it_app(t)) {
            // recursive argument
        } else {
            throw kernel_exception(m_env, sstream() << "arg #" << (arg_idx + 1) << " of '" << intro_name << "' "
                                   "contains a non valid occurrence of the datatypes being declared");
        }
    }

    /** \brief Check the intro_rule \c ir.
        \see check_intro_rules */
    void check_intro_rule(intro_rule const & ir) {
        expr t = intro_rule_type(ir);
        name n = intro_rule_name(ir);
        /* make sure intro rule type does not contain locals nor metavariables. */
        check_no_mlocal(m_env, n, t, true);
        tc().check(t, m_decl.m_level_params);
        unsigned i     = 0;
        bool found_rec = false;
        while (is_pi(t)) {
            if (i < m_decl.m_num_params) {
                if (!is_def_eq(binding_domain(t), get_param_type(i)))
                    throw kernel_exception(m_env, sstream() << "arg #" << (i + 1) << " of '" << n << "' "
                                           << "does not match inductive datatypes parameters'");
                t = instantiate(binding_body(t), m_param_consts[i]);
            } else {
                expr s = ensure_type(binding_domain(t));
                // the sort is ok IF
                //   1- its level is <= inductive datatype level, OR
                //   2- inductive datatype is at level 0
                if (!(is_geq(m_it_level, sort_level(s)) || is_zero(m_it_level)) && m_is_trusted)
                    throw kernel_exception(m_env, sstream() << "universe level of type_of(arg #" << (i + 1) << ") "
                                           << "of '" << n << "' is too big for the corresponding inductive datatype");
                if (m_is_trusted)
                    check_positivity(binding_domain(t), n, i);
                bool is_rec = (bool)is_rec_argument(binding_domain(t)); // NOLINT
                if (is_rec)
                    found_rec = true;
                if (!found_rec) {
                    t = instantiate(binding_body(t), mk_local_for(t));
                } else {
                    t = binding_body(t);
                    if (!closed(t))
                        throw kernel_exception(m_env, sstream() << "invalid occurrence of recursive arg#" << (i+1) <<
                                               " of '" << n << "', the body of the functional type depends on it.");
                }
            }
            i++;
        }
        if (!is_valid_it_app(t))
            throw kernel_exception(m_env, sstream() << "invalid return type for '" << n << "'");
    }

    /** \brief Check if
        - all introduction rules start with the same parameters
        - the type of all arguments (which are not datatype global params) live in universes <= level of the corresponding datatype
        - inductive datatype occurrences are positive
        - all introduction rules are well typed

        \remark this method must be executed after declare_inductive_types */
    void check_intro_rules() {
        for (auto ir : m_decl.m_intro_rules)
            check_intro_rule(ir);
    }

    /** \brief Add all introduction rules (aka constructors) to environment. */
    void declare_intro_rules() {
        for (auto ir : m_decl.m_intro_rules) {
            m_env = m_env.add(check(m_env, mk_constant_assumption(intro_rule_name(ir),
                                                                  m_decl.m_level_params, intro_rule_type(ir),
                                                                  m_is_trusted)));
        }
        updt_type_checker();
    }

    /** \brief Return true if type former C in the recursor can only map to Type.{0} */
    bool elim_only_at_universe_zero() {
        if (m_is_not_zero) {
            // If Type.{0} is not impredicative or the resultant inductive datatype is not in Type.{0},
            // then the recursor may return Type.{l} where l is a universe level parameter.
            return false;
        }
        unsigned num_intros = length(m_decl.m_intro_rules);
        if (num_intros > 1) {
            // If we have more than one introduction rule, then yes, the type former can only
            // map to Type.{0}
            return true;
        }
        if (num_intros == 0) {
            // if we don't have intro rules, then we don't need to check anything else
            return false;
        }
        // We have only one introduction rule, the final check is, the type of each argument
        // that is not a parameter:
        //  1- It must live in Type.{0}, *OR*
        //  2- It must occur in the return type. (this is essentially what is called a non-uniform parameter in Coq).
        //     We can justify 2 by observing that this information is not a *secret* it is part of the type.
        //     By eliminating to a non-proposition, we would not be revealing anything that is not already known.
        auto ir    = head(m_decl.m_intro_rules);
        expr t     = intro_rule_type(ir);
        unsigned i = 0;
        buffer<expr> to_check; // arguments that we must check if occur in the result type
        while (is_pi(t)) {
            expr local = mk_local_for(t);
            if (i >= m_decl.m_num_params) {
                expr s = ensure_type(binding_domain(t));
                if (!is_zero(sort_level(s))) {
                    // Current argument is not in Type.{0} (i.e., condition 1 failed).
                    // We save it in to_check to be able to try condition 2 above.
                    to_check.push_back(local);
                }
            }
            t = instantiate(binding_body(t), local);
            i++;
        }
        buffer<expr> result_args;
        get_app_args(t, result_args);
        // Check condition 2: every argument in to_check must occur in result_args
        for (expr const & arg : to_check) {
            if (std::find(result_args.begin(), result_args.end(), arg) == result_args.end())
                return true; // condition 2 failed
        }
        return false;
    }

    /** \brief Initialize m_elim_level. */
    void mk_elim_level() {
        if (elim_only_at_universe_zero()) {
            // environment is impredicative, datatype maps to Prop, we have more than one introduction rule.
            m_elim_level = mk_level_zero();
        } else {
            name l("l");
            int i = 1;
            while (std::find(m_decl.m_level_params.begin(), m_decl.m_level_params.end(), l) != m_decl.m_level_params.end()) {
                l = name("l").append_after(i);
                i++;
            }
            m_elim_level = mk_param_univ(l);
        }
    }

    /** \brief Initialize m_dep_elim flag. */
    void set_dep_elim() {
        if (is_zero(m_it_level))
            m_dep_elim = false;
        else
            m_dep_elim = true;
    }

    /** \brief Given t of the form (I As is) where I is the inductive datatypes being defined,
        As are the global parameters, and is the actual indices provided to it.
        Store `is` in the argument \c indices. */
    void get_I_indices(expr const & t, buffer<expr> & indices) {
        lean_assert(is_valid_it_app(t));
        buffer<expr> all_args;
        get_app_args(t, all_args);
        for (unsigned i = m_decl.m_num_params; i < all_args.size(); i++)
            indices.push_back(all_args[i]);
    }

    /** \brief Populate m_elim_info. */
    void mk_elim_info() {
        // First, populate the fields m_C and m_major_premise
        m_elim_info.m_major_premise = mk_local(m_name_generator.next(), "n",
                                               mk_app(mk_app(m_it_const, m_param_consts), m_elim_info.m_indices), binder_info());
        expr C_ty = mk_sort(m_elim_level);
        if (m_dep_elim)
            C_ty = Pi(m_elim_info.m_major_premise, C_ty);
        C_ty = Pi(m_elim_info.m_indices, C_ty);
        name C_name("motive");
        m_elim_info.m_C = mk_local(m_name_generator.next(), C_name, C_ty, binder_info());

        // Populate the field m_minor_premises
        unsigned minor_idx = 1;
        // A declaration is target for K-like reduction when
        // it has one intro, the intro has 0 arguments, proof irrelevance is enabled,
        // and it is a proposition.
        // In the following for-loop we check if the intro rule
        // has 0 arguments.
        bool is_K_target =
            is_zero(m_it_level) &&             // It is a Prop
            length(m_decl.m_intro_rules) == 1; // datatype has only one intro rule
        for (auto ir : m_decl.m_intro_rules) {
            buffer<expr> b_u; // nonrec and rec args
            buffer<expr> u;   // rec args
            buffer<expr> v;   // inductive args
            expr t     = intro_rule_type(ir);
            unsigned i = 0;
            while (is_pi(t)) {
                if (i < m_decl.m_num_params) {
                    t = instantiate(binding_body(t), m_param_consts[i]);
                } else {
                    is_K_target = false; // See comment before for-loop.
                    expr l = mk_local_for(t);
                    b_u.push_back(l);
                    if (is_rec_argument(binding_domain(t)))
                        u.push_back(l);
                    t = instantiate(binding_body(t), l);
                }
                i++;
            }
            buffer<expr> it_indices;
            get_I_indices(t, it_indices);
            expr C_app      = mk_app(m_elim_info.m_C, it_indices);
            if (m_dep_elim) {
                expr intro_app  = mk_app(mk_app(mk_constant(intro_rule_name(ir), m_levels), m_param_consts), b_u);
                C_app = mk_app(C_app, intro_app);
            }
            // populate v using u
            for (unsigned i = 0; i < u.size(); i++) {
                expr u_i    = u[i];
                expr u_i_ty = whnf(mlocal_type(u_i));
                buffer<expr> xs;
                while (is_pi(u_i_ty)) {
                    expr x = mk_local_for(u_i_ty);
                    xs.push_back(x);
                    u_i_ty = whnf(instantiate(binding_body(u_i_ty), x));
                }
                buffer<expr> it_indices;
                get_I_indices(u_i_ty, it_indices);
                expr C_app  = mk_app(m_elim_info.m_C, it_indices);
                if (m_dep_elim) {
                    expr u_app  = mk_app(u_i, xs);
                    C_app = mk_app(C_app, u_app);
                }
                expr v_i_ty = Pi(xs, C_app);
                name ih("ih");
                if (u.size() > 1) {
                    name const & u_i_name = mlocal_pp_name(u_i);
                    if (u_i_name.is_atomic() && u_i_name.is_string()) {
                        ih = ih.append_after("_").append_after(u_i_name.get_string());
                    } else {
                        ih = ih.append_after(i+1);
                    }
                }
                expr v_i    = mk_local(m_name_generator.next(), ih, v_i_ty, binder_info());
                v.push_back(v_i);
            }
            expr minor_ty = Pi(b_u, Pi(v, C_app));
            expr minor = mk_local(m_name_generator.next(), name("e").append_after(minor_idx), minor_ty, binder_info());
            m_elim_info.m_minor_premises.push_back(minor);
            minor_idx++;
        }
        m_elim_info.m_K_target = is_K_target;
    }

    /** \brief Return the name of the eliminator/recursor for the type being defined . */
    name get_elim_name() { return ::lean::inductive::get_elim_name(m_decl.m_name); }

    /** \brief Return the level parameter names for the eliminator. */
    level_param_names get_elim_level_param_names() {
        if (is_param(m_elim_level))
            return level_param_names(param_id(m_elim_level), m_decl.m_level_params);
        else
            return m_decl.m_level_params;
    }

    /** \brief Return the levels for the eliminator application. */
    levels get_elim_level_params() {
        if (is_param(m_elim_level))
            return levels(m_elim_level, m_levels);
        else
            return m_levels;
    }

    /** \brief Declare elimination rule. */
    expr declare_elim_rule_core() {
        elim_info const & info = m_elim_info;
        expr C_app   = mk_app(info.m_C, info.m_indices);
        if (m_dep_elim)
            C_app = mk_app(C_app, info.m_major_premise);
        expr elim_ty = Pi(info.m_major_premise, C_app);
        elim_ty      = Pi(info.m_indices, elim_ty);
        // abstract all introduction rules
        unsigned j = m_elim_info.m_minor_premises.size();
        while (j > 0) {
            --j;
            elim_ty = Pi(m_elim_info.m_minor_premises[j], elim_ty);
        }
        // abstract motive
        elim_ty   = Pi(m_elim_info.m_C, elim_ty);
        // parameters
        elim_ty   = Pi(m_param_consts, elim_ty);
        elim_ty   = infer_implicit(elim_ty, true /* strict */);
        m_env = m_env.add(check(m_env, mk_constant_assumption(get_elim_name(), get_elim_level_param_names(), elim_ty,
                                                              m_is_trusted)));
        return elim_ty;
    }

    /** \brief Declare the eliminator/recursor. */
    expr declare_elim_rule() {
        set_dep_elim();
        mk_elim_level();
        mk_elim_info();
        expr r = declare_elim_rule_core();
        updt_type_checker();
        return r;
    }

    /** \brief Create computional rules RHS, and return certified_inductive_decl object. */
    certified_inductive_decl mk_certified_decl(expr const & elim_type) {
        unsigned minor_idx = 0;
        expr C = m_elim_info.m_C;
        buffer<expr> e; e.append(m_elim_info.m_minor_premises);
        levels ls = get_elim_level_params();
        buffer<certified_inductive_decl::comp_rule> comp_rules;
        for (auto ir : m_decl.m_intro_rules) {
            buffer<expr> b_u; // nonrec and rec arguments
            buffer<expr> u;   // rec arguments only
            expr t = intro_rule_type(ir);
            unsigned i = 0;
            while (is_pi(t)) {
                if (i < m_decl.m_num_params) {
                    t = instantiate(binding_body(t), m_param_consts[i]);
                } else {
                    expr l = mk_local_for(t);
                    b_u.push_back(l);
                    if (is_rec_argument(binding_domain(t)))
                        u.push_back(l);
                    t = instantiate(binding_body(t), l);
                }
                i++;
            }
            buffer<expr> v;
            for (unsigned i = 0; i < u.size(); i++) {
                expr u_i    = u[i];
                expr u_i_ty = whnf(mlocal_type(u_i));
                buffer<expr> xs;
                while (is_pi(u_i_ty)) {
                    expr x = mk_local_for(u_i_ty);
                    xs.push_back(x);
                    u_i_ty = whnf(instantiate(binding_body(u_i_ty), x));
                }
                buffer<expr> it_indices;
                get_I_indices(u_i_ty, it_indices);
                expr elim_app = mk_constant(get_elim_name(), ls);
                elim_app = mk_app(mk_app(mk_app(mk_app(mk_app(elim_app, m_param_consts), C), e), it_indices), mk_app(u_i, xs));
                v.push_back(Fun(xs, elim_app));
            }
            expr e_app = mk_app(mk_app(e[minor_idx], b_u), v);
            expr comp_rhs   = Fun(m_param_consts, Fun(C, Fun(e, Fun(b_u, e_app))));
            tc().check(comp_rhs, get_elim_level_param_names());
            comp_rules.emplace_back(b_u.size(), comp_rhs);
            minor_idx++;
        }
        bool elim_Prop = !is_param(m_elim_level);
        return certified_inductive_decl(m_decl.m_num_params + 1 + e.size(), elim_Prop, m_dep_elim,
                                        get_elim_level_param_names(), elim_type, m_decl,
                                        m_elim_info.m_K_target, m_elim_info.m_indices.size(), to_list(comp_rules),
                                        m_is_trusted);
    }

    pair<environment, certified_inductive_decl> operator()() {
        check_inductive_type();
        declare_inductive_type();
        check_intro_rules();
        declare_intro_rules();
        certified_inductive_decl c = mk_certified_decl(declare_elim_rule());
        m_env = c.add_core(m_env, true);
        return mk_pair(m_env, c);
    }
};

pair<environment, certified_inductive_decl>
add_inductive(environment env, inductive_decl const & decl, bool is_trusted) {
    if (!env.norm_ext().supports(*g_inductive_extension))
        throw kernel_exception(env, "environment does not support inductive datatypes");
    return add_inductive_fn(env, decl, is_trusted)();
}

bool inductive_normalizer_extension::supports(name const & feature) const {
    return feature == *g_inductive_extension;
}

/** \brief Return true if \c e is an introduction rule for an eliminator named \c elim */
static inductive_env_ext::comp_rule const * is_intro_for(inductive_env_ext const & ext, name const & elim, expr const & e) {
    expr const & intro_fn  = get_app_fn(e);
    if (!is_constant(intro_fn))
        return nullptr;
    auto it = ext.m_comp_rules.find(const_name(intro_fn));
    if (it && it->m_elim_name == elim)
        return it;
    else
        return nullptr;
}

/** \brief If \c d_name is the name of a non-empty inductive datatype, then return the
    name of the first introduction rule. Return none otherwise. */
static optional<name> get_first_intro(environment const & env, name const & d_name) {
    inductive_env_ext const & ext = get_extension(env);
    if (inductive_decl const * decl = ext.m_inductive_info.find(d_name)) {
        auto intros = decl->m_intro_rules;
        if (intros)
            return optional<name>(intro_rule_name(head(intros)));
    }
    return optional<name>();
}

static optional<expr> mk_nullary_intro(environment const & env, expr const & type, unsigned num_params) {
    buffer<expr> args;
    expr const & d = get_app_args(type, args);
    if (!is_constant(d))
        return none_expr();
    name const & d_name = const_name(d);
    auto intro_name = get_first_intro(env, d_name);
    if (!intro_name)
        return none_expr();
    args.shrink(num_params);
    return some(mk_app(mk_constant(*intro_name, const_levels(d)), args));
}

// For datatypes that support K-axiom, given e an element of that type, we convert (if possible)
// to the default constructor. For example, if (e : a = a), then this method returns (eq.refl a)
static optional<expr> to_intro_when_K(inductive_env_ext::elim_info const * it,
                                      expr const & e, abstract_type_context & ctx) {
    lean_assert(it->m_K_target);
    environment const & env = ctx.env();
    expr app_type    = ctx.whnf(ctx.infer(e));
    expr const & app_type_I = get_app_fn(app_type);
    if (!is_constant(app_type_I) || const_name(app_type_I) != it->m_inductive_name)
        return none_expr(); // type incorrect
    if (has_expr_metavar(app_type)) {
        buffer<expr> app_type_args;
        get_app_args(app_type, app_type_args);
        for (unsigned i = it->m_num_params; i < app_type_args.size(); i++) {
            if (has_expr_metavar(app_type_args[i]))
                return none_expr();
        }
    }
    auto new_intro_app = mk_nullary_intro(env, app_type, it->m_num_params);
    if (!new_intro_app)
        return none_expr();
    expr new_type    = ctx.infer(*new_intro_app);
    if (!ctx.is_def_eq(app_type, new_type))
        return none_expr();
    return new_intro_app;
}

optional<expr> inductive_normalizer_extension::operator()(expr const & e, abstract_type_context & ctx) const {
    // Reduce terms \c e of the form
    //    elim_k A C e p[A,b] (intro_k_i A b u)
    environment const & env = ctx.env();
    inductive_env_ext const & ext = get_extension(env);
    expr const & elim_fn   = get_app_fn(e);
    if (!is_constant(elim_fn))
        return none_expr();
    auto it1 = ext.m_elim_info.find(const_name(elim_fn));
    if (!it1)
        return none_expr(); // it is not an eliminator
    buffer<expr> elim_args;
    get_app_args(e, elim_args);
    unsigned major_idx = it1->m_num_ACe + it1->m_num_indices;
    if (elim_args.size() < major_idx + 1)
        return none_expr(); // major premise is missing
    expr major = elim_args[major_idx];
    optional<expr> intro_app;
    inductive_env_ext::comp_rule const * it2 = nullptr;
    if (it1->m_K_target) {
        if (auto p = to_intro_when_K(it1, major, ctx)) {
            intro_app = p;
            it2       = ext.m_comp_rules.find(const_name(get_app_fn(*intro_app)));
        }
    }
    if (!intro_app) {
        intro_app         = ctx.whnf(major);
        it2               = is_intro_for(ext, const_name(elim_fn), *intro_app);
        if (!it2)
            return none_expr();
    }
    lean_assert(intro_app);
    lean_assert(it2);
    buffer<expr> intro_args;
    get_app_args(*intro_app, intro_args);
    // Check intro num_args
    if (intro_args.size() != it1->m_num_params + it2->m_num_bu)
        return none_expr();
    // Number of universe levels must match.
    if (length(const_levels(elim_fn)) != length(it1->m_level_names))
        return none_expr();
    buffer<expr> ACebu;
    for (unsigned i = 0; i < it1->m_num_ACe; i++)
        ACebu.push_back(elim_args[i]);
    for (unsigned i = 0; i < it2->m_num_bu; i++)
        ACebu.push_back(intro_args[it1->m_num_params + i]);
    std::reverse(ACebu.begin(), ACebu.end());
    expr r = instantiate_univ_params(it2->m_comp_rhs_body, it1->m_level_names, const_levels(elim_fn));
    r = instantiate(r, ACebu.size(), ACebu.data());
    if (elim_args.size() > major_idx + 1) {
        unsigned num_args = elim_args.size() - major_idx - 1;
        r = mk_app(r, num_args, elim_args.data() + major_idx + 1);
    }
    return some_expr(r);
}

bool inductive_normalizer_extension::is_recursor(environment const & env, name const & n) const {
    return static_cast<bool>(is_elim_rule(env, n));
}

bool inductive_normalizer_extension::is_builtin(environment const & env, name const & n) const {
    return is_inductive_decl(env, n) || is_elim_rule(env, n) || is_intro_rule(env, n);
}

template<typename Ctx>
optional<expr> is_elim_meta_app_core(Ctx & ctx, expr const & e) {
    inductive_env_ext const & ext = get_extension(ctx.env());
    expr const & elim_fn   = get_app_fn(e);
    if (!is_constant(elim_fn))
        return none_expr();
    auto it1 = ext.m_elim_info.find(const_name(elim_fn));
    if (!it1)
        return none_expr();
    buffer<expr> elim_args;
    get_app_args(e, elim_args);
    unsigned major_idx = it1->m_num_ACe + it1->m_num_indices;
    if (elim_args.size() < major_idx + 1)
        return none_expr();
    expr intro_app = ctx.whnf(elim_args[major_idx]);
    if (it1->m_K_target) {
        // TODO(Leo): make it more precise.  Remark: this piece of
        // code does not affect the correctness of the kernel, but the
        // effectiveness of the elaborator.
        return has_expr_metavar_strict(intro_app);
    } else {
        return ctx.is_stuck(intro_app);
    }
}

bool is_elim_meta_app(type_checker & tc, expr const & e) {
    return static_cast<bool>(is_elim_meta_app_core(tc, e));
}

// Return true if \c e is of the form (elim ... (?m ...))
optional<expr> inductive_normalizer_extension::is_stuck(expr const & e, abstract_type_context & ctx) const {
    return is_elim_meta_app_core(ctx, e);
}

optional<inductive_decl> is_inductive_decl(environment const & env, name const & n) {
    inductive_env_ext const & ext = get_extension(env);
    if (auto it = ext.m_inductive_info.find(n))
        return optional<inductive_decl>(*it);
    else
        return optional<inductive_decl>();
}

optional<unsigned> get_num_indices(environment const & env, name const & n) {
    inductive_env_ext const & ext = get_extension(env);
    if (auto it = ext.m_elim_info.find(get_elim_name(n))) {
        return optional<unsigned>(it->m_num_indices);
    } else {
        return optional<unsigned>();
    }
}

optional<unsigned> get_num_minor_premises(environment const & env, name const & n) {
    inductive_env_ext const & ext = get_extension(env);
    if (auto it = ext.m_elim_info.find(get_elim_name(n))) {
        unsigned num_Cs = 1;
        return some(it->m_num_ACe - it->m_num_params - num_Cs);
    } else {
        return optional<unsigned>();
    }
}

optional<unsigned> get_num_intro_rules(environment const & env, name const & n) {
    if (auto decl = is_inductive_decl(env, n)) {
        return some(length(decl->m_intro_rules));
    } else {
        return optional<unsigned>();
    }
}

bool has_dep_elim(environment const & env, name const & n) {
    inductive_env_ext const & ext = get_extension(env);
    if (auto it = ext.m_elim_info.find(get_elim_name(n)))
        return it->m_dep_elim;
    else
        return false;
}

optional<name> is_intro_rule(environment const & env, name const & n) {
    inductive_env_ext const & ext = get_extension(env);
    if (auto it = ext.m_intro_info.find(n))
        return optional<name>(*it);
    else
        return optional<name>();
}

optional<name> is_elim_rule(environment const & env, name const & n) {
    inductive_env_ext const & ext = get_extension(env);
    if (auto it = ext.m_elim_info.find(n))
        return optional<name>(it->m_inductive_name);
    else
        return optional<name>();
}

optional<unsigned> get_elim_major_idx(environment const & env, name const & n) {
    inductive_env_ext const & ext = get_extension(env);
    if (auto it = ext.m_elim_info.find(n))
        return optional<unsigned>(it->m_num_ACe + it->m_num_indices);
    else
        return optional<unsigned>();
}
}

void initialize_inductive_module() {
    inductive::g_ind_fresh           = new name("_ind_fresh");
    register_name_generator_prefix(*inductive::g_ind_fresh);
    inductive::g_inductive_extension = new name("inductive_extension");
    inductive::g_ext                 = new inductive::inductive_env_ext_reg();
}

void finalize_inductive_module() {
    delete inductive::g_ext;
    delete inductive::g_inductive_extension;
    delete inductive::g_ind_fresh;
}
}


text:
package com.salesmanager.web.admin.entity.merchant;

import java.io.Serializable;

import com.salesmanager.core.business.reference.language.model.Language;

public class StoreLandingDescription implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private String title;
	private String description;
	private String keywords;
	private String homePageContent;

	private Language language;

	public void setDescription(String description) {
		this.description = description;
	}

	public String getDescription() {
		return description;
	}

	public void setHomePageContent(String homePageContent) {
		this.homePageContent = homePageContent;
	}

	public String getHomePageContent() {
		return homePageContent;
	}

	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}

	public String getKeywords() {
		return keywords;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setLanguage(Language language) {
		this.language = language;
	}

	public Language getLanguage() {
		return language;
	}

}


text:
package com.someco.model;

public interface SomeCoWorkflowModel {

	// Types
	public static final String NAMESPACE_SOMECO_WORKFLOW_CONTENT_MODEL  = "http://www.someco.com/model/workflow/1.0";

    // Properties
    public static final String PROP_APPROVE_REJECT_OUTCOME = "approveRejectOutcome";

}


text:
SELECT DISTINCT
T271.friendly_name AS "Friendly_Name (Sys Users)",
T271.name AS "Name (Sys Users)",
SUM(T298.nviews) AS "Nviews (VW Stats)",
MAX(T298.time) AS "Time (VW Stats)",
T301.name AS "Name (WB)",
T297.name AS "Name (Views)"
FROM
views_stats T298
INNER JOIN users T290 ON T298.user_id = T290.id
INNER JOIN views T297 ON T298.view_id = T297.id
INNER JOIN workbooks T301 ON T297.workbook_id = T301.id
INNER JOIN system_users T271 ON T290.system_user_id = T271.id
GROUP BY
T271.friendly_name,
T271.name,
T301.name,
T297.name


text:
const settings = require('./../../settings.json');
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    let permissions = message.channel.permissionsFor(message.member);
    if (permissions.has("MANAGE_MESSAGES")) {
        if (!settings["disabled-channels"].includes(message.channel.id)) {
            settings["disabled-channels"].push(message.channel.id);
            message.reply("Disabled fun commands in this channel")
        }
        else {
            let index = settings["disabled-channels"].indexOf(message.channel.id);
            settings["disabled-channels"].splice(index, 1);
            message.reply("Enabled fun commands in this channel")
        }
        return true;
    }
    else {
        await message.reply("You aren't Worthy\nhttps://media.tenor.com/images/c472d1ee8c75a50f700bd028cc1b10b9/tenor.gif")
        return false;
    }
}
/**
 * description of the command
 */
const description = "Disable/enable the bot fun commands in a particular channel";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description,
    mod: true
};


text:
ABSL_FLAG(std::string, sorting_table, "", "sorting table file");
ABSL_FLAG(std::string, ordering_rule, "", "sorting order file");
ABSL_FLAG(std::string, input, "", "symbol dictionary file");
ABSL_FLAG(std::string, user_pos_manager_data, "", "user pos manager data file");
ABSL_FLAG(std::string, output_token_array, "",
          "output token array binary file");
ABSL_FLAG(std::string, output_string_array, "",
          "output string array binary file");

namespace mozc {
namespace {

void GetSortingMap(const std::string &auto_file, const std::string &rule_file,
                   absl::btree_map<std::string, uint16_t> *sorting_map) {
  CHECK(sorting_map);
  sorting_map->clear();
  std::string line;
  int sorting_key = 0;
  InputFileStream rule_ifs(rule_file);
  CHECK(rule_ifs.good());
  while (!std::getline(rule_ifs, line).fail()) {
    if (line.empty() || line[0] == '#') {
      continue;
    }
    sorting_map->insert(std::make_pair(line, sorting_key));
    ++sorting_key;
  }

  InputFileStream auto_ifs(auto_file);
  CHECK(auto_ifs.good());

  while (!std::getline(auto_ifs, line).fail()) {
    if (line.empty() || line[0] == '#') {
      continue;
    }
    const std::vector<std::string> fields =
        absl::StrSplit(line, absl::ByAnyChar("\t "), absl::SkipEmpty());
    CHECK_GE(fields.size(), 2);
    uint32_t ucs4 = 0;
    NumberUtil::SafeHexStrToUInt32(fields[0], &ucs4);
    std::string utf8;
    Util::Ucs4ToUtf8(ucs4, &utf8);
    if (sorting_map->find(utf8) != sorting_map->end()) {
      // ordered by rule
      continue;
    }
    sorting_map->insert(std::make_pair(utf8, sorting_key));
    ++sorting_key;
  }
}

void AddSymbolToDictionary(
    const std::string &pos, const std::string &value,
    const std::vector<std::string> &keys, const std::string &description,
    const std::string &additional_description,
    const absl::btree_map<std::string, uint16_t> &sorting_map,
    rewriter::DictionaryGenerator *dictionary) {
  // use first char of value as sorting key.
  const auto first_value = std::string(Util::Utf8SubString(value, 0, 1));
  absl::btree_map<std::string, uint16_t>::const_iterator itr =
      sorting_map.find(first_value);
  uint16_t sorting_key = 0;
  if (itr == sorting_map.end()) {
    DLOG(WARNING) << first_value << " is not defined in sorting map.";
    // If the character is platform-dependent, put the character at the last.
    if (!Util::IsJisX0208(value)) {
      sorting_key = USHRT_MAX;
    }
  } else {
    sorting_key = itr->second;
  }

  for (size_t i = 0; i < keys.size(); ++i) {
    const std::string &key = keys[i];

    rewriter::Token token;
    token.set_sorting_key(sorting_key);
    token.set_key(key);
    token.set_value(value);
    token.set_pos(pos);
    token.set_description(description);
    token.set_additional_description(additional_description);
    dictionary->AddToken(token);

    std::string fw_key;
    japanese_util::HalfWidthAsciiToFullWidthAscii(key, &fw_key);
    if (fw_key != key) {
      token.set_key(fw_key);
      dictionary->AddToken(token);
    }
  }
}

// Read dic:
void MakeDictionary(const std::string &symbol_dictionary_file,
                    const std::string &sorting_map_file,
                    const std::string &ordering_rule_file,
                    rewriter::DictionaryGenerator *dictionary) {
  absl::btree_set<std::string> seen;
  absl::btree_map<std::string, uint16_t> sorting_map;
  GetSortingMap(sorting_map_file, ordering_rule_file, &sorting_map);

  InputFileStream ifs(symbol_dictionary_file);
  CHECK(ifs.good());

  std::string line;
  CHECK(!std::getline(ifs, line).fail());  // get first line

  while (!std::getline(ifs, line).fail()) {
    // Format:
    // POS <tab> value <tab> readings(space delimitered) <tab>
    // description <tab> memo
    std::vector<std::string> fields =
        absl::StrSplit(line, '\t', absl::AllowEmpty());
    if (fields.size() < 3 || (fields[1].empty() && fields[2].empty())) {
      VLOG(3) << "invalid format. skip line: " << line;
      continue;
    }
    std::string pos = fields[0];
    Util::UpperString(&pos);
    const std::string &value = fields[1];
    if (seen.find(value) != seen.end()) {
      LOG(WARNING) << "already inserted: " << value;
      continue;
    } else {
      seen.insert(value);
    }
    std::string keys_str;
    Util::StringReplace(fields[2], " ",  // Full-width space
                        " ", true, &keys_str);
    const std::vector<std::string> keys =
        absl::StrSplit(keys_str, ' ', absl::SkipEmpty());
    const std::string &description = (fields.size()) > 3 ? fields[3] : "";
    const std::string &additional_description =
        (fields.size()) > 4 ? fields[4] : "";
    AddSymbolToDictionary(pos, value, keys, description, additional_description,
                          sorting_map, dictionary);
  }
  // Add space as a symbol
  std::vector<std::string> keys_space;
  keys_space.push_back(" ");
  AddSymbolToDictionary("記号", " ", keys_space, "空白", "", sorting_map,
                        dictionary);
}
}  // namespace
}  // namespace mozc

int main(int argc, char **argv) {
  mozc::InitMozc(argv[0], &argc, &argv);

  if ((absl::GetFlag(FLAGS_input).empty() ||
       absl::GetFlag(FLAGS_sorting_table).empty() ||
       absl::GetFlag(FLAGS_ordering_rule).empty()) &&
      argc > 3) {
    absl::SetFlag(&FLAGS_input, argv[1]);
    absl::SetFlag(&FLAGS_sorting_table, argv[2]);
    absl::SetFlag(&FLAGS_ordering_rule, argv[3]);
  }

  const std::string tmp_text_file =
      absl::GetFlag(FLAGS_output_token_array) + ".txt";

  // User pos manager data for build tools has no magic number.
  const char *kMagciNumber = "";
  mozc::DataManager data_manager;
  const mozc::DataManager::Status status =
      data_manager.InitUserPosManagerDataFromFile(
          absl::GetFlag(FLAGS_user_pos_manager_data), kMagciNumber);
  CHECK_EQ(status, mozc::DataManager::Status::OK);

  mozc::rewriter::DictionaryGenerator dictionary(data_manager);
  mozc::MakeDictionary(absl::GetFlag(FLAGS_input),
                       absl::GetFlag(FLAGS_sorting_table),
                       absl::GetFlag(FLAGS_ordering_rule), &dictionary);
  dictionary.Output(tmp_text_file);
  mozc::SerializedDictionary::CompileToFiles(
      tmp_text_file, absl::GetFlag(FLAGS_output_token_array),
      absl::GetFlag(FLAGS_output_string_array));
  CHECK_OK(mozc::FileUtil::Unlink(tmp_text_file));

  return 0;
}


text:
title: Live Stats
nav_exclude: true
---

<script>
	window.location.replace("http://pace-nsc.org/live/");
</script>


text:
module LeaderboardElasticsearchRank

  def self.included(klass)
    klass.extend(ClassMethods)
  end

  module ClassMethods
    @@ranks = nil

    def rank_teams
      i = 0
      @@ranks ||= []
      teams = top(1, Team.count)
      teams.is_a?(Team::SearchResultsWrapper) ? {} : teams.inject(Hash.new(0)) { |h, team| h[team.id.to_s] = (i = i+ 1); @@ranks[i]= Team::SearchResultsWrapper.new(team, i); h }
    end

    def ranked_teams
      @@ranked_teams ||= Rails.cache.fetch("teams_ranked_teams", expires_in: 1.hour) { rank_teams }
    end

    def ranks
      @@ranks ||= Rails.cache.fetch("teams_ranks", expires_in: 1.hour) { (rank_teams && @@ranks) }
    end

    def team_rank(team)
      ranked_teams[team.id.to_s] || 0
    end

    def top(page = 1, total = 50, country=nil)
      Team.search("", nil, page, total)
    end
  end

  def next_highest_competitors(number = 2)
    @higher_competitor ||= Team.ranks[rank-number..rank-1].compact
  end

  def higher_competitors(number = 1)
    Team.ranks[rank-number..rank-1].compact
  end

  def lower_competitors(number = 1)
    Team.ranks[rank+1..rank+number].compact
  end

  def next_lowest_competitors(number = 2)
    @lower_competitor ||= Team.ranks[rank+1..rank+number].compact
  end

  def rank
    @rank ||= Team.team_rank(self)
  end
end