text:
Lirc API:s

The LIRC lib/ directory is indeed code used in various places. It offers
three views:

External  applications uses the lirc_client.h header file and links to
     liblirc.so using -llirc. This is a mature, reasonably stable interface.
     See the client api

User space drivers includes the lirc_driver.h header and links to
     liblirc_driver.so using -llirc_driver. The other way around lirc
     accesses the driver as defined in the driver.h file (the driver
     structure). This interface is new and will probably need some time
     to stabilize. See the driver api

Internal lirc  applications includes the lirc_private.h header file and
     links to liblirc_private.so using -llirc_private. This interface is
     subject to change without notice, and external applications are
     strongly adviced to not use it.


text:
@interface TGLocationDetector : NSObject

+(NSString *)cityWithLocation:(CGPoint)point;

@end

redpajama_set_name: RedPajamaGithub


text:
package io.teknek.nibiru.engine;

import io.teknek.nibiru.Store;
import io.teknek.nibiru.Token;
import io.teknek.nibiru.engine.atom.AtomKey;
import io.teknek.nibiru.engine.atom.AtomValue;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;

public class TombstoneReaper implements Runnable {

  private final DefaultColumnFamily columnFamily;
  private volatile boolean goOn;

  public TombstoneReaper(DefaultColumnFamily columnFamily){
    this.columnFamily = columnFamily;
    goOn = true;
  }

  @Override
  public void run() {
    while(goOn){
      long now = System.currentTimeMillis();
      processColumnFamily(this.columnFamily, now);
      try {
        Thread.sleep(2);
      } catch (InterruptedException e) {
      }
    }
  }

  //VisibleForTesting
  public void processColumnFamily(Store columnFamily, long currentTimeMillis){
    long graceMillis = columnFamily.getStoreMetadata().getTombstoneGraceMillis();
    for (Entry<Token, ConcurrentSkipListMap<AtomKey, AtomValue>> entry : ((DefaultColumnFamily) columnFamily).getMemtable().getData().entrySet()){
      for (Entry<AtomKey, AtomValue> innerEntry : entry.getValue().entrySet()){
        /*
        if (innerEntry.getValue().getValue() == null){
          if (innerEntry.getValue().getCreateTime() + graceMillis < currentTimeMillis){
            entry.getValue().remove(innerEntry.getKey());
          }
        }*/
      }
    }
  }

  public boolean isGoOn() {
    return goOn;
  }

  public void setGoOn(boolean goOn) {
    this.goOn = goOn;
  }

}


text:
/**
 * @fileoverview
 * @author Random | http://weibo.com/random
 * Licensed under the MIT license.
 * @date 2014-03-26
 */

var Reader=require("./reader.js");

var newState;
var state;
var reader;
var tokenList = [];
var token = {};

var TOKEN_TYPE = {
	CHAR : 1,
	TAG : 2,
	COMMENT : 3,
	START_TAG : 4,
	END_TAG : 5
};

function emitToken(){
	tokenList.push(token);
	token = {};
}

function createToken(type, value){
	if(type === TOKEN_TYPE.CHAR){
		token = {
			type : type,
			value : value
		};

	}else if(type === TOKEN_TYPE.TAG){
		token = {
			type : type,
			tag : value.tag || {},
			attributes : value.attributes || []
		};

	}else if(type === TOKEN_TYPE.COMMENT){
		token = {
			type : type,
			data : value
		}
	}
}

function appendTokenAttributeName(c){
	token.attributes[token.attributes.length - 1].name += c;
}
function appendTokenAttributeValue(c){
	token.attributes[token.attributes.length - 1].value += c;
}

function parseError(){
	console.log("parseError");
}

function dataState(c){
	if(c === "<"){
		return tagOpenState;

	}else if(c === "\u0000"){
		parseError();
		createToken(TOKEN_TYPE.CHAR, c);
		emitToken();

	}else{
		// createToken(TOKEN_TYPE.CHAR, c);
		// emitToken();
		return dataState;
	}
}

function tagOpenState(c){
	if(c === "!"){
		return markupDeclarationOpenState;

	}else if(c === "/"){
		return endTagOpenState;

	}else if(/[a-z]/i.test(c)){
		createToken(TOKEN_TYPE.TAG, {
			tag : {
				type : TOKEN_TYPE.START_TAG,
				name : c.toLowerCase()
			}
		});
		return tagNameState;

	}else if(c === "?"){
		return dataState; //*

	}else{
		createToken(TOKEN_TYPE.CHAR, c);
		emitToken();
		reader.prev();
		return dataState;
	}
}

function markupDeclarationOpenState(c){
	if(c === "-" && reader.nchar === "-"){
		reader.next();
		createToken(TOKEN_TYPE.COMMENT, "");
		return commentStartState;

	}else{
		return dataState;
	}
}

function commentStartState(c){
	if(c === "-"){
		return commentStartDashState;

	}else if(c === ">"){
		parseError();
		emitToken();
		return dataState;

	}else{
		token.data += c;
		return commentState;
	}
}

function commentStartDashState(c){
	if(c === "-"){
		return commentEndState;

	}else if(c === ">"){
		parseError();
		emitToken();
		return dataState;

	}else{
		token.data += "-" + c;
		return commentState;
	}
}

function commentState(c){
	if(c === "-"){
		return commentEndDashState;

	}else{
		token.data += c;
	}
}

function commentEndDashState(c){
	if(c === "-"){
		return commentEndState;

	}else{
		token.data += "-" + c;
		return commentState;
	}
}

function commentEndState(c){
	if(c === ">"){
		emitToken();
		return dataState;

	}else if(c === "!"){
		parseError();
		return commentEndBangState;

	}else if(c === "-"){
		parseError();
		token.data += "-";

	}else{
		parseError();
		token.data += "--" + c;
		return commentState;
	}
}

function commentEndBangState(c){
	if(c === "-"){
		token.data += "--!";
		return commentEndDashState;

	}else if(c === ">"){
		emitToken();
		return dataState;

	}else{
		token.data += "--!" + c;
		return commentState;
	}
}

function endTagOpenState(c){
	if(/[a-z]/i.test(c)){
		createToken(TOKEN_TYPE.TAG, {
			tag : {
				type : TOKEN_TYPE.END_TAG,
				name : c.toLowerCase()
			}
		});

		return tagNameState;

	}else if(c === ">"){
		parseError();
		return dataState;

	}else{

	}
}

function tagNameState(c){
	if((new RegExp("[\u0009\u000a\u000c\u0020]")).test(c)){
		return beforeAttributeNameState;

	}else if(c === "/"){
		return selfClosingStartTagState;

	}else if(c === ">"){
		emitToken();
		return dataState;

	}else if(/[A-Z]/.test(c)){
		token.tag.name += c.toLowerCase();

	}else if(c === "\u0000"){
		token.tag.name += "\ufffd";

	}else{
		token.tag.name += c;
	}
}

function beforeAttributeNameState(c){
	if((new RegExp("[\u0009\u000a\u000c\u0020]")).test(c)){
		return beforeAttributeNameState;

	}else if(c === "/"){
		return selfClosingStartTagState;

	}else if(c === ">"){
		emitToken();
		return dataState;

	}else if(/[A-Z]/.test(c)){
		token.attributes.push({
			name : c.toLowerCase(),
			value : ""
		});
		return attributeNameState;

	}else if(c === "\u0000"){
		parseError();
		return attributeNameState;

	}else if((new RegExp("[\u0022\u0027\u003c\u003d]")).test(c)){
		parseError();
		token.attributes.push({
			name : c,
			value : ""
		});
		return attributeNameState;

	}else{
		token.attributes.push({
			name : c,
			value : ""
		});
		return attributeNameState;
	}
}

function selfClosingStartTagState(c){
	if(c === ">"){
		token.selfClosing = true;
		emitToken();
		return dataState;

	}else{
		parseError();
		reader.prev();
		return beforeAttributeNameState;
	}
}

function attributeNameState(c){
	if((new RegExp("[\u0009\u000a\u000c\u0020]")).test(c)){
		return afterAttributeNameState;

	}else if(c === "/"){
		return selfClosingStartTagState;

	}else if(c === "="){
		return beforeAttributeValueState;

	}else if(c === ">"){
		emitToken();
		return dataState;

	}else if(/[A-Z]/.test(c)){
		appendTokenAttributeName(c.toLowerCase());

	}else if(c === "\u0000"){
		appendTokenAttributeName("\ufffd");

	}else if((new RegExp("[\u0022\u0027\u003c]")).test(c)){
		parseError();
		appendTokenAttributeName(c);

	}else{
		appendTokenAttributeName(c);
	}
}

function afterAttributeNameState(c){
	if((new RegExp("[\u0009\u000a\u000c\u0020]")).test(c)){
		return afterAttributeNameState;

	}else if(c === "/"){
		return selfClosingStartTagState;

	}else if(c === "="){
		return beforeAttributeValueState;

	}else if(c === ">"){
		emitToken();
		return dataState;

	}else if(/[A-Z]/.test(c)){
		token.attributes.push({
			name : c.toLowerCase(),
			value : ""
		});
		return attributeNameState;

	}else if(c === "\u0000"){
		parseError();
		token.attributes.push({
			name : "\ufffd",
			value : ""
		});
		return attributeNameState;

	}else if((new RegExp("[\u0022\u0027\u003c]")).test(c)){
		parseError();
		token.attributes.push({
			name : c,
			value : ""
		});
		return attributeNameState;

	}else{
		token.attributes.push({
			name : c,
			value : ""
		});
		return attributeNameState;
	}
}

function beforeAttributeValueState(c){
	if((new RegExp("[\u0009\u000a\u000c\u0020]")).test(c)){
		return beforeAttributeValueState;

	}else if(c === "\u0022"){
		return attributeValueDoubleQuotedState;

	}else if(c === "\u0026"){
		reader.prev();
		return attributeValueUnquotedState;

	}else if(c === "\u0027"){
		return attributeValueSingleQuotedState;

	}else if(c === "\u0000"){
		appendTokenAttributeValue("\ufffd");
		return attributeValueUnquotedState;

	}else if(c === "\u003e"){
		parseError();
		emitToken();
		return dataState;

	}else if((new RegExp("[\u003c\u003d\u0060]")).test(c)){
		parseError();
		appendTokenAttributeValue(c);
		return attributeValueUnquotedState;

	}else{
		appendTokenAttributeValue(c);
		return attributeValueUnquotedState;
	}
}

function attributeValueDoubleQuotedState(c){
	if(c === "\u0022"){
		return afterAttributeValueQuotedState;

	}else if(c === "\u0000"){
		parseError();
		appendTokenAttributeValue("\ufffd");

	}else{
		appendTokenAttributeValue(c);
	}
}

function attributeValueSingleQuotedState(c){
	if(c === "\u0027"){
		return afterAttributeValueQuotedState;

	}else if(c === "\u0000"){
		parseError();
		appendTokenAttributeValue("\ufffd");

	}else{
		appendTokenAttributeValue(c);
	}
}

function attributeValueUnquotedState(c){
	if((new RegExp("[\u0009\u000a\u000c\u0020]")).test(c)){
		return beforeAttributeNameState;

	}else if(c === "\u003e"){
		emitToken();
		return dateState();

	}else if(c === "\u0000"){
		parseError();
		appendTokenAttributeValue("\ufffd");

	}else if((new RegExp("[\u0022\u0027\u003c\u003d\u0060]")).test(c)){
		parseError();
		appendTokenAttributeValue("\ufffd");

	}else{
		appendTokenAttributeValue(c);
	}
}

function afterAttributeValueQuotedState(c){
	if((new RegExp("[\u0009\u000a\u000c\u0020]")).test(c)){
		return beforeAttributeNameState;

	}else if(c === "/"){
		return selfClosingStartTagState;

	}else if(c === "\u003e"){
		emitToken();
		return dataState;

	}else{
		parseError();
		reader.prev();
		return beforeAttributeNameState;
	}
}

var Parser = {

	TOKEN_TYPE : TOKEN_TYPE,

	tokenize : function(stream){
		reader = Reader(stream);

		state=dataState;
		while(!reader.eof){
			newState=state(reader.char);
			newState && (state=newState);
			reader.next();
		}
		emitToken();

		return tokenList;
	}
};

module.exports = Parser;


text:
import logging

from aiohttp import ClientSession, BasicAuth

from radio.services.exceptions import ImproperlyConfiguredServiceError
from config.settings import (
    MAIL_GUN_API_KEY,
    MAIL_GUN_API_URL,
    INFO_EMAIL,
    FEEDBACK_SUBJECT
)

server_logger = logging.getLogger('aiohttp.server')

async def send_mail(sender: str, body: str) -> None:
    """
    Args:
        sender: email sender
        body: text body of email that in going to be sent

    """
    if not all([MAIL_GUN_API_KEY, INFO_EMAIL, MAIL_GUN_API_URL]):
        raise ImproperlyConfiguredServiceError('Email sending variables are not defined! Please check your settings!')

    try:
        # async with statement needed to auto close session after request was made.
        async with ClientSession() as client:
            async with client.post(MAIL_GUN_API_URL,
                                   auth=BasicAuth("api", MAIL_GUN_API_KEY),
                                   data={"from": sender,
                                         "to": INFO_EMAIL,
                                         "subject": FEEDBACK_SUBJECT,
                                         "text": body}) as response:
                    return response.read()
    except Exception as e:
        # log exception as we don't have anything else to do here.
        # raising exception doesn't make much sense. At least now.
        server_logger.error('Error occurred while sending email {}!'.format(str(e)))


text:
Consider the following definition of a tree in Haskell.
```haskell
data Tree = Nil | Node Tree Int Tree
  deriving (Show,Read)
```

A *leaf* is a node with no children. Write a function `leaflist :: Tree -> [Int]` that prints out the values at the leaves of the tree as a list, from left to right.

**Sample Test Cases**

Test Case | Input	| Output
--------- | ----- | ------
Test Case 1	| `leaflist (Node Nil 7 Nil)` | `[7]`
Test Case 2	| `leaflist (Node (Node Nil 5 Nil) 8 (Node (Node Nil 6 Nil) 7 Nil))` | `[5,6]`


text:
import datetime

import jwt
from flask import current_app

from project import db, bcrypt

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), unique=True, nullable=False)
    email = db.Column(db.String(128), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    active = db.Column(db.Boolean, default=True, nullable=False)
    admin = db.Column(db.Boolean, default=False, nullable=False)
    created_at = db.Column(db.DateTime, nullable=False)

    def __init__(
            self, username, email, password,
            created_at=datetime.datetime.now()):
        self.username = username
        self.email = email
        self.password = bcrypt.generate_password_hash(
            password, current_app.config.get('BCRYPT_LOG_ROUNDS')
        ).decode()
        self.created_at = created_at

    def encode_auth_token(self, user_id):
        """Generates the auth token"""
        try:
            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(
                    days=current_app.config.get('TOKEN_EXPIRATION_DAYS'),
                    seconds=current_app.config.get('TOKEN_EXPIRATION_SECONDS')
                ),
                'iat': datetime.datetime.utcnow(),
                'sub': user_id
            }
            return jwt.encode(
                payload,
                current_app.config.get('SECRET_KEY'),
                algorithm='HS256'
            )
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        """Decodes the auth token - :param auth_token: - :return: integer|string"""
        try:
            payload = jwt.decode(
                auth_token, current_app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.'


text:
package kata.java;

public class BTreeSet {
    private final int pageLength;
    private Page root;
    private int height;

    public BTreeSet(int pageLength) {
        this.pageLength = pageLength;
        this.root = new Page(this.pageLength);
        this.height = 1;
    }

    public boolean contains(int key) {
        return contains(root, key, height);
    }

    private boolean contains(Page page, int key, int height) {
        if (height == 1) {
            for (Entry e : page.keys) {
                if (e != null && e.key == key) return true;
            }
            return false;
        }
        else {
            for (int i = 1; i < pageLength; i++) {
                if (page.keys[i-1] != null && (page.keys[i] == null || key < page.keys[i].key))
                    return contains(page.keys[i-1].next, key, height - 1);
            }
            return false;
        }
    }

    public void add(int key) {
        if (root.add(key, height)) {
            height += 1;
        }
    }

    public int height() {
        return height;
    }

    private class Page {
        private Entry[] keys;
        private int size;

        private Page(int pageLength) {
            keys = new Entry[pageLength];
            size = 0;
        }

        private boolean add(int key, int height) {
            if (height == 1) {
                if (size < pageLength) {
                    keys[size] = new Entry(key);
                    size += 1;
                    return false;
                }
                else {
                    split(key);
                    return true;
                }
            }
            else {
                for (int i = 1; i < pageLength; i++) {
                    if (keys[i-1] != null && (keys[i] == null || key < keys[i].key)) {
                        return keys[i - 1].next.add(key, height - 1);
                    }
                }
                return false;
            }
        }

        private void split(int key) {
            Page left = new Page(pageLength);
            Page right = new Page(pageLength);
            int leftLength = pageLength / 2 + 1;
            fillPage(left, 0, leftLength);
            fillPage(right, leftLength, pageLength);
            right.add(key, 1);
            balance(left, right);
        }

        private void balance(BTreeSet.Page left, BTreeSet.Page right) {
            keys[0].key = left.keys[0].key;
            keys[0].next = left;
            keys[1].key = right.keys[0].key;
            keys[1].next = right;
            cleanUp();
        }

        private void cleanUp() {
            size = 2;
            for (int i = 2; i < pageLength; i++) {
                keys[i] = null;
            }
        }

        private void fillPage(Page page, int from, int length) {
            for (int i = from; i < length; i++) {
                page.add(keys[i].key, 1);
            }
        }

    }

    private class Entry {
        private int key;
        private Page next;

        public Entry(int key) {
            this.key = key;
        }
    }
}


text:
define(['data', 'util', 'form'], function(data, util, form){
	return {form:form};
});


text:
import camelCase from 'camel-case';
import { Record, List, fromJS } from 'immutable';

const Quiz = new Record({
  title: '',
  instruction: '',
  answerKeysLabel: '',
  questions: new List(),
}, 'quiz');

const ACTIONS_MAP = {
  clearQuiz(state) {
    return state
      .delete('title')
      .delete('instruction')
      .delete('answerKeysLabel')
      .delete('questions');
  },

  populateQuiz(state, {
    title,
    instruction,
    answerKeysLabel,
    questions,
  }) {
    return state
      .set('title', title)
      .set('instruction', instruction)
      .set('answerKeysLabel', answerKeysLabel)
      .set('questions', fromJS(questions));
  },
};

const initialState = new Quiz();

export default function quiz(state = initialState, { type, payload }) {
  const reducer = ACTIONS_MAP[camelCase(type)];

  return (reducer) ? reducer(state, payload) : state;
}

// For transit-immutable-js
export const records = [Quiz];


text:
local function trynumber(v)
	return tonumber(v) or v
end

local function copyNode(s,x)
	local attr=x.attributes
	if attr then
		for k,v in pairs(attr) do
			s[k]=trynumber(v)
		end
	end
end

local function parseTileSet(node)
	local set={}
	copyNode(set,node)
	local image=node.children['image'][1]
	assert(image, 'not support tsx')
	set.source=image.attributes['source']
	--todo:property
	return set
end

local function parseProperties(node)
	local l={}
	for i,n in ipairs(node.children['property']) do
		local attr=n.attributes
		l[n['name']]=trynumber(n['value'])
	end
	return l
end

local function parseObject(node)
	local obj={}
	copyNode(obj,node)

	if obj.children and obj.children['properties'] then
		obj.properties=parseProperties(obj.children['properties'][1])
	end
	return obj
end

local function parseObjectGroup(node)
	local group={}
	copyNode(group, node)
	for i,n in ipairs(node.children['object']) do
		group[i]=parseObject(n)
	end
	return group
end

local function parseTileLayer(node)
	local layer={}
	copyNode(layer,node)
	local data=node.children['data'][1]
	local encoding=data.attributes['encoding']
	if encoding=='csv' then
		layer.tiles=loadstring('return {'..data.value..'}')()
	elseif encoding=='base64' then
		--reference: TMXMapLoader from Hanappe
		local decoded=MOAIDataBuffer.base64Decode(data.value)
		if data.attributes['compression'] then
			decoded=MOAIDataBuffer.inflate(decoded,47)
		end
		local tileCount=#decoded/4
		local t={}
		for i=1, tileCount do
			local start=(i-1)*4 + 1
			local a0,a1,a2,a3 = string.byte(decoded, start, start+3)
			t[i] = a0 + a1 * 2^8 + a2 * 2^16 + a3 * 2^32
		end
		layer.tiles=t
	else
		error('unknown encoding')
	end
	return layer
end

local function parseMap(node)
	assert(node.type=='map')
	local map={}
	copyNode(map,node)

	local tileSets={}
	local objectGroups={}
	local tileLayers={}

	if node.children['tileset'] then
		for i, n in ipairs(node.children['tileset']) do
		   tileSets[i]=parseTileSet(n)
		end
	end
	if node.children['objectgroup'] then
		for i, n in ipairs(node.children['objectgroup']) do
			objectGroups[i]=parseObjectGroup(n)
		end
	end
	if node.children['layer'] then
		for i, n in ipairs(node.children['layer']) do
		   tileLayers[i]=parseTileLayer(n)
		end
	end
	map.tileSets=tileSets
	map.tileLayers=tileLayers
	map.objectGroups=objectGroups
	return map
end

local function tmx2lua(file)
	local xml=MOAIXmlParser.parseFile(file)
	return parseMap(xml)
end

CLASS: TMXTool ()
function TMXTool:load(tmxfile)
	local data=tmx2lua(tmxfile)
	self.data=data or false
end

function TMXTool:getObjectLayers()
	return self.data.objectGroups
end

function TMXTool:getTileLayers()
	return self.data.tileLayers
end

function TMXTool:findObject(layerId, objId)
	local layer=self:findObjectLayer(layerId)
	if not layer then return nil end
	for i, obj in ipairs(layer) do
		if obj.name==objId then
			return obj
		end
	end
	return nil
end

function TMXTool:getObjectLayerCount()
	assert(self.data,'not loaded')
	if not self.data then return 0 end
	return #self.data.objectGroups
end

function TMXTool:getTileLayerCount()
	assert(self.data,'not loaded')
	if not self.data then return 0 end
	return #self.data.tileLayers
end

function TMXTool:findTileLayer(id)
	if type(id)=='number' then
		return self.data.tileLayers[id]
	elseif type(id)=='string' then
		for i,l in ipairs(self.data.tileLayers) do
			if l.name==id then return l end
		end
		return nil
	else
		error('layer id unknown')
	end
end

function TMXTool:findObjectLayer(id)
	if type(id)=='number' then
		return self.data.objectGroups[id]
	elseif type(id)=='string' then
		for i,l in ipairs(self.data.objectGroups) do
			if l.name==id then return l end
		end
		return nil
	else
		error('layer id unknown')
	end
end

function TMXTool:buildGrid(tileLayerId)
	assert(self.data,'not loaded')
	local layer=assert(self:findTileLayer(tileLayerId), 'layer not found')
	local tiles=layer.tiles
	if not tiles then return nil end
	local grid=MOAIGrid.new()
	local w,h=self.data.width, self.data.height
	grid:setSize(w,h, self.data.tilewidth,self.data.tileheight)
	local ptr=1
	for y=h,1 ,-1 do
		for x=1,w do
			grid:setTile(x,y,tiles[ptr]) --TODO: multiple tileset support ?
			ptr=ptr+1
		end
	end
	return grid
end

function TMXTool:getMapSize()
	assert(self.data,'not loaded')
	return self.data.width, self.data.height
end

function TMXTool:getMapPixelSize()
	assert(self.data,'not loaded')
	return self.data.width*self.data.tilewidth, self.data.height*self.data.tileheight
end

function TMXTool:getTileSize()
	assert(self.data,'not loaded')
	return self.data.tilewidth, self.data.tileheight
end


text:
This document describes the contents of the `__primitives__` module synthesized by the Clay compiler and implicitly available to all Clay programs. This module provides primitive types, fundamental operations, and functions for compile-time introspection of programs. For information about the Clay language itself, consult the [Language Reference](language-reference.md).

* [Primitive types](#primitivetypes)
    * [`Bool`](#bool)
    * [Integer types](#integertypes)
        * `Int8`, `Int16`, `Int32`, `Int64`, `Int128`, `UInt8`, `UInt16`, `UInt32`, `UInt64`, `UInt128`
    * [Floating-point types](#floatingpointtypes)
        * `Float32`, `Float64`, `Float80`
    * [Imaginary and complex types](#imaginaryandcomplextypes)
        * `Imag32`, `Imag64`, `Imag80`, `Complex32`, `Complex64`, `Complex80`
    * [`Pointer`](#pointer)
    * [`CodePointer`](#codepointer)
    * [External code pointer types](#externalcodepointertypes)
        * `CCodePointer`, `VarArgsCCodePointer`, `LLVMCodePointer`, `StdCallCodePointer`, `FastCallCodePointer`, `ThisCallCodePointer`
    * [`Array`](#array)
    * [`Vec`](#vec)
    * [`Tuple`](#tuple)
    * [`Union`](#union)
    * [`Static`](#static)

* [Data access operations](#dataaccessoperations)
    * [`primitiveCopy`](#primitivecopy)
    * [`arrayRef`](#arrayref)
    * [`arrayElements`](#arrayelements)
    * [`tupleRef`](#tupleref)
    * [`tupleElements`](#tupleelements)
    * [`recordFieldRef`](#recordfieldref)
    * [`recordFieldRefByName`](#recordfieldrefbyname)
    * [`recordFields`](#recordfields)
    * [`enumToInt`](#enumtoint)
    * [`intToEnum`](#inttoenum)

* [Numeric operations](#numericoperations)
    * [`boolNot`](#boolnot)
    * [`numericEquals?`](#numericequals)
    * [`numericLesser?`](#numericlesser)
    * [`numericAdd`](#numericadd)
    * [`numericSubtract`](#numericsubtract)
    * [`numericMultiply`](#numericmultiply)
    * [`numericDivide`](#numericdivide)
    * [`numericNegate`](#numericnegate)
    * [`integerRemainder`](#integerremainder)
    * [`integerShiftLeft`](#integershiftleft)
    * [`integerShiftRight`](#integershiftright)
    * [`integerBitwiseAnd`](#integerbitwiseand)
    * [`integerBitwiseOr`](#integerbitwiseor)
    * [`integerBitwiseXor`](#integerbitwisexor)
    * [`integerBitwiseNot`](#integerbitwisenot)
    * [`numericConvert`](#numericconvert)

* [Checked integer operations](#checkedintegeroperations)
    * `integerAddChecked`, `integerSubtractChecked`, `integerMultiplyChecked`, `integerDivideChecked`, `integerRemainderChecked`, `integerNegateChecked`, `integerShiftLeftChecked`, `integerConvertChecked`

* [Pointer operations](#pointeroperations)
    * [`addressOf`](#addressof)
    * [`pointerDereference`](#pointerdereference)
    * [`pointerEquals?`](#pointerequals)
    * [`pointerLesser?`](#pointerlesser)
    * [`pointerOffset`](#pointeroffset)
    * [`pointerToInt`](#pointertoint)
    * [`intToPointer`](#inttopointer)
    * [`pointerCast`](#pointercast)

* [Function pointer operations](#functionpointeroperations)
    * [`makeCodePointer`](#makecodepointer)
    * [`makeCCodePointer`](#makeccodepointer)
    * [`callCCodePointer`](#callccodepointer)

* [Atomic memory operations](#atomicmemoryoperations)
    * [Memory order symbols](#memoryordersymbols)
        * `OrderUnordered`, `OrderMonotonic`, `OrderAcquire`, `OrderRelease`, `OrderAcqRel`, `OrderSeqCst`
    * [`atomicLoad`](#atomicload)
    * [`atomicStore`](#atomicstore)
    * [`atomicRMW`](#atomicrmw)
        * `RMWXchg`, `RMWAdd`, `RMWSubtract`, `RMWAnd`, `RMWNAnd`, `RMWOr`, `RMWXor`, `RMWMin`, `RMWMax`, `RMWUMin`, `RMWUMax`
    * [`atomicCompareExchange`](#atomiccompareexchange)
    * [`atomicFence`](#atomicfence)

* [Exception handling](#exceptionhandling)
    * [`activeException`](#activeexception)

* [Symbol and function introspection](#symbolandfunctionintrospection)
    * [`Type?`](#type)
    * [`CallDefined?`](#calldefined)
    * [`ModuleName`](#modulename)
    * [`IdentifierModuleName`](#identifiermodulename)
    * [`StaticName`](#staticname)
    * [`IdentifierStaticName`](#identifierstaticname)
    * [`staticFieldRef`](#staticfieldref)

* [Static string manipulation](#staticstringmanipulation)
    * [`Identifier?`](#identifier)
    * [`IdentifierSize`](#identifiersize)
    * [`IdentifierConcat`](#identifierconcat)
    * [`IdentifierSlice`](#identifierslice)

* [Type introspection](#typeintrospection)
    * [`TypeSize`](#typesize)
    * [`TypeAlignment`](#typealignment)
    * [`CCodePointer?`](#ccodepointer)
    * [`TupleElementCount`](#tupleelementcount)
    * [`UnionMemberCount`](#unionmembercount)
    * [`Record?`](#record)
    * [`RecordFieldCount`](#recordfieldcount)
    * [`RecordFieldName`](#recordfieldname)
    * [`RecordWithField?`](#recordwithfield)
    * [`Variant?`](#variant)
    * [`VariantMemberCount`](#variantmembercount)
    * [`VariantMemberIndex`](#variantmemberindex)
    * [`Enum?`](#enum)
    * [`EnumMemberCount`](#enummembercount)
    * [`EnumMemberName`](#enummembername)

* [Compiler flags](#compilerflags)
    * [`ExceptionsEnabled?`](#exceptionsenabled)
    * [`Flag?`](#flag)
    * [`Flag`](#flag)

* [External function attributes](#externalfunctionattributes)
    * [Calling convention attributes](#callingconventionattributes)
        * `AttributeCCall`, `AttributeStdCall`, `AttributeFastCall`, `AttributeThisCall`, `AttributeLLVMCall`
    * [Linkage attributes](#linkageattributes)
        * `AttributeDLLImport`, `AttributeDLLExport`

* [Miscellaneous functions](#miscellaneousfunctions)
    * [`staticIntegers`](#staticintegers)

### Primitive types

Primitive types correspond more or less to the basic LLVM types, with some occasional added higher-level semantics. The primitive types are defined as overloadable symbols with no initial overloads; library code may overload primitive type symbols in order to define constructor functions for the types. Corresponding LLVM and C types for use with external function linkage is provided for each type.

#### Bool

The `Bool` type represents boolean values. Values of the type may only have the values `true` or `false`. This type corresponds to the LLVM `i1` type, the C99 `_Bool` type, and the C++ `bool` type. `false` in LLVM is `i1 0` and `true` is `i1 1`.

#### Integer types

Signed and unsigned integer types are provided for sizes of 8, 16, 32, 64, and 128 bits. The signed types are named `Int8`, `Int16`, etc. and the unsigned types are named `UInt8` etc. Both sets of types correspond to the LLVM `i8`, `i16`, etc. types. (LLVM does not differentiate signed from unsigned types.) They also correspond to the C99 `<stdint.h>` typedefs `int8_t` etc. and `uint8_t` etc.

The compiler internally earmarks the unsigned integer type whose size corresponds to the size of pointer types, and uses that type as the return type for primitives that deal with indexing data structures. This document refers to that type as `SizeT`, although this alias name is not actually available from the `__primitives__` module.

#### Floating-point types

`Float32` and `Float64` floating-point types are provided, corresponding to IEEE-754 single and double precision floating point numbers. For Unix x86 targets, the platform-specific `Float80` type is also provided. These types correspond respectively to the LLVM `float`, `double`, and `x86_fp80` types, or the C `float`, `double`, and `long double` types (the latter implemented as an extension by many x86-targeting compilers).

#### Imaginary and complex types

Imaginary and complex types are provided for each floating-point type. `Imag32` etc. correspond to the same LLVM and C types as `Float32` etc., but semantically represent imaginary values in Clay. `Complex32` etc. correspond to LLVM `{float,float}` etc. types and C99 `_Complex float` etc. types.

#### Pointer

`Pointer[T]` is the type of a pointer to a value of type `T`, for any type `T`. It corresponds to the `%T*` type in LLVM (where `%T` is the LLVM type of `T`), or to the `T*` type in C. Pointers are created by the prefix `&` operator, or by the equivalent [`addressOf`](#addressof) primitive function.

#### CodePointer

`CodePointer[[..In], [..Out]]` is the type of a pointer to a Clay function, instantiated for the argument types `..In` and return types `..Out`. These pointers can be created using the [`makeCodePointer`](#makecodepointer) primitive function. The Clay calling convention is unspecified, so `CodePointer`s have no specific corresponding LLVM or C type beyond being a function pointer of some kind.

#### External code pointer types

`CCodePointer[[..In], [..Out]]` is the type of a pointer to a C function with argument types `..In` and return types `..Out`. `CCodePointer[[A,B,C],[]]` corresponds to the C `void (*)(A,B,C)` type, and `CCodePointer[[A,B,C],[D]]` to the `D (*)(A,B,C)` type. The LLVM type depends on the target platform's C calling convention.

`CCodePointer`s are called using the C calling convention when passed to the [`callCCodePointer`](#callccodepointer) primitive function. Different symbols are provided for function pointers with different calling conventions.

* `LLVMCodePointer[[A,B,C],[D]]` corresponds directly to an LLVM `D (A,B,C) *` function pointer type.
* `VarArgsCCodePointer[[A,B,C], [D]]` points to a variadic C function; it corresponds to the `D (*)(A,B,C,...)` type in C.
* `StdCallCodePointer`, `FastCallCodePointer`, and `ThisCallCodePointer` point to functions using legacy x86 calling conventions on Windows. They correspond to C function pointer types decorated with `__stdcall`, `__fastcall`, or `__thiscall` in Microsoft dialect, or with `__attribute__((stdcall))` etc. in GCC dialect.

`CCodePointer`s, along with the other external code pointer types, may be obtained by evaluating external function names, or as return values from C functions. They may also be derived directly automatically from some Clay functions using the [`makeCCodePointer`](#makeccodepointer) primitive function.

    // Example
    // XXX

#### Array

`Array[T,n]` is the type of a fixed-size, locally-allocated array, containing `n` elements of type `T`. The `n` parameter must currently be an `Int32` (regardless of the target word size). It corresponds to the LLVM `[n x %T]` type, or the C `T [n]` type; however, unlike C arrays, Clay arrays never implicitly devolve to pointers. The [`arrayRef`](#arrayref) and [`arrayElements`](#arrayelements) primitive functions provide access to array elements.

#### Vec

`Vec[T,n]` is the type of a SIMD vector value, containing `n` elements of type `T`. The `n` parameter must currently be an `Int32` (regardless of the target word size). It corresponds to the LLVM `<n x %T>` type, or the GCC extension `T __attribute__((vector_size(n*sizeof(T))))` type.

No primitives are currently provided for manipulating `Vec` types; they are primarily intended to be used directly with LLVM's vector intrinsics.

#### Tuple

`Tuple[..T]` is an anonymous aggregate of the specified types. Tuples are laid out equivalently to naturally-aligned C `struct`s containing the same corresponding types in the same order. `Tuple[A,B,C]` corresponds to an LLVM `{%A, %B, %C}` struct type.

#### Union

`Union[..T]` is an anonymous, nondiscriminated union of the specified types. It is laid out equivalently to a naturally-aligned C `union` containing the corresponding types in the same order. LLVM does not represent unions in its type system; an LLVM type is chosen in order to have the proper size and alignment for the member types of the union.

#### Static

`Static[x]` is a stateless type used to represent compile-time values. Clay symbols, static strings, and `static` expressions evaluate to values of instances of this type.

(`Static` values are actually not quite completely stateless yet; they are emitted as `i8 undef` values at the LLVM level. They thus still unfortunately take up space inside tuples and record types.)

### Data access operations

These functions provide fundamental data manipulation operations. Unlike normal symbols, they may not be overloaded.

#### primitiveCopy

    [T]
    primitiveCopy(dest:T, src:T) :;

`primitiveCopy` performs a bitwise copy of `src` into `dst`. `TypeSize(T)` bytes are copied. The function corresponds to an LLVM `load` instruction followed by a `store`.

#### arrayRef

    [T,n,I | Integer?(I)]
    arrayRef(array:Array[T,n], i:I) : ref T;

`arrayRef` returns a reference to element `i` of `array`. `i` is zero-based and is not bounds checked. The function corresponds to an LLVM `getelementptr` instruction.

#### arrayElements

    [T,n]
    arrayElements(array:Array[T,n]) : ref ..repeatValue(static n, T);

`arrayElements` returns a reference to each element of `array` in order as a multiple value list.

#### tupleRef

    [..T, n | n >= 0 and n < countValues(..T)]
    tupleRef(tuple:Tuple[..T], static n) : ref nthValue(static n, ..T);

`tupleRef` returns a reference to the `n`th element of `tuple`. `n` is zero-based, and must be greater than or equal to zero, and less than the number of elements in `tuple`. The function corresponds to an LLVM `getelementptr` instruction.

#### tupleElements

    [..T]
    tupleElements(tuple:Tuple[..T]) : ref ..T;

`tupleElements` returns a reference to each element of `tuple` in order as a multiple value list.

#### recordFieldRef

    [R, n | Record?(R) and n >= 0 and n < RecordFieldCount(R)]
    recordFieldRef(rec:R, static n) : ref RecordFieldType(R, static N);

`recordFieldRef` returns a reference to the `n`th field of `rec`, which must be of a record type. `n` is zero-based, and must be greater than or equal to zero, and less than the number of fields in the record type `R`. The function corresponds to an LLVM `getelementptr` instruction.

#### recordFieldRefByName

    [R, name | Record?(R) and Identifier?(name) and RecordWithField?(R, name)]
    recordFieldRefByName(rec:R, static name) : ref RecordFieldTypeByName(R, name);

`recordFieldRefByName` returns a reference to the field named by the static string `name` in `rec`, which must be of a record type with a field of that name. The function corresponds to an LLVM `getelementptr` instruction.

#### recordFields

    [R | Record?(R)]
    recordFields(rec:R) : ref ..RecordFieldTypes(R);

`recordFields` returns a reference to each field of `rec` in order as a multiple value list. `rec` must be of a record type.

#### enumToInt

    [E | Enum?(E)]
    enumToInt(en:E) : Int32;

`enumToInt` returns the ordinal value of `en` as an `Int32`. `en` must be of an enum type.

#### intToEnum

    [E | Enum?(E)]
    intToEnum(static E, n:Int32) : E;

`intToEnum` returns a value of the enum type `E` with the ordinal value `n`. `n` is not bounds checked against the defined values of `E`.

### Numeric operations

These functions provide fundamental arithmetic operations for the primitive [`Bool`](#bool), [integer](#integertypes), [floating-point](#floatingpointtypes), and [imaginary](#imaginaryandcomplextypes) types. Unlike normal symbols, they may not be overloaded. Binary numeric primitives generally require inputs of matching types. Conversion rules for heterogeneous types are left to be implemented by the library. These functions also do not operate on complex types; complex math is also left to the library.

#### boolNot

    boolNot(x:Bool) : Bool;

`boolNot` returns the complement of `x`, which must be a `Bool`. It is equivalent to the `not` operator.

#### numericEquals?

    [T | Numeric?(T)]
    numericEquals?(a:T, b:T) : Bool;

`numericEquals?` returns `true` if `a` and `b` are numerically equal, and `false` otherwise. For integer types, the function corresponds to an LLVM `icmp eq` instruction, and for floating-point types, the function corresponds to an LLVM `fcmp ueq` instruction. Floating-point comparison follows IEEE 754 unordered comparison rules; `+0.0` is equal to `-0.0` and comparisons involving NaN are always false and non-signaling.

#### numericLesser?

    [T | Numeric?(T)]
    numericLesser?(a:T, b:T) : Bool;

`numericLesser?` returns `true` if `a` is numerically less than `b`, and `false` otherwise. For signed integer types, the function corresponds to an LLVM `icmp slt` instruction; for unsigned types, `icmp ult`; and for floating-point types, `fcmp ult`. Floating point comparison follows IEEE 754 unordered comparison rules; `-0.0` is not less than `+0.0` and comparisons involving NaN are always false and non-signaling.

(`__primitives__` does not currently provide the full set of floating-point comparison operators. The Clay library currently implements floating-point ordered and unordered comparison using inline LLVM functions. For floating-point, these primitives are used only for compile-time evaluation, which does not support inline LLVM.)

#### numericAdd

    [T | Numeric?(T)]
    numericAdd(a:T, b:T) : T;

`numericAdd` returns the sum of `a` and `b`. Integer signed or unsigned addition overflows following two's-complement arithmetic rules. For integer types, the function corresponds to the LLVM `add` instruction, and for floating-point types, the `fadd` instruction.

#### numericSubtract

    [T | Numeric?(T)]
    numericSubtract(a:T, b:T) : T;

`numericSubtract` returns the difference of `a` and `b`. Integer signed or unsigned subtraction overflows following two's-complement arithmetic rules. For integer types, the function corresponds to the LLVM `sub` instruction, and for floating-point types, the `fsub` instruction.

#### numericMultiply

    [T | Numeric?(T)]
    numericMultiply(a:T, b:T) : T;

`numericMultiply` returns the product of `a` and `b`. Integer signed or unsigned multiplication overflows following two's-complement arithmetic rules. For integer types, the function corresponds to the LLVM `mul` instruction, and for floating-point types, the `fmul` instruction.

#### numericDivide

    [T | Numeric?(T)]
    numericDivide(a:T, b:T) : T;

`numericDivide` returns the quotient of `a` and `b`. Integer division is truncated towards zero. Integer division by zero is undefined, as is signed division overflow (for example, the result of `-0x8000_0000/-1`). Floating-point division by zero, underflow, and overflow follow IEEE 754 rules. For signed integer types, the function corresponds to the LLVM `sdiv` instruction; for unsigned types, `udiv`; and for floating point types, `fdiv`.

#### numericNegate

    [T | Numeric?(T)]
    numericNegate(a:T) : T;

`numericNegate` returns the negation of `a`. Integer negation behaves like two's-complement subtraction from zero (and in fact, LLVM represents integer negation as `sub %T 0, %a`). Unsigned negation thus gives the two's complement, and signed negation overflow (for example, the result of negating `-0x8000_0000`) gives back the original value. Floating-point negation corresponds to `fsub %T -0.0, %a` in LLVM; negating a zero gives the other zero, and negating a NaN gives an unspecified other NaN value.

#### integerRemainder

    [T | Integer?(T)]
    integerRemainder(a:T, b:T) : T;

`integerRemainder` returns the remainder from dividing `a` and `b`. For signed remainder operations, a nonzero remainder has the same sign as `a`. Integer division by zero is undefined, as is signed division overflow (for example, the result of `-0x8000_0000/-1`). (Although the result of the remainder operation itself does not overflow, LLVM still specifies that the remainder of an overflowing division operation is undefined.) For signed integer types, the function corresponds to the LLVM `srem` instruction, and for unsigned types, `urem`.

#### integerShiftLeft

    [T | Integer?(T)]
    integerShiftLeft(a:T, b:T) : T;

`integerShiftLeft` returns the result of bitshifting `a` left by `b` bits. The result is undefined is `b` is either negative or greater than or equal to the bit size of `T`. Overflowed bits are discarded; the value is still defined. The function corresponds to the LLVM `shl` instruction.

#### integerShiftRight

    [T | Integer?(T)]
    integerShiftRight(a:T, b:T) : T;

`integerShiftRight` returns the result of bitshifting `a` right by `b` bits. The result is undefined is `b` is either negative or greater than or equal to the bit size of `T`. For signed integer types, an "arithmetic" shift is performed; the sign bit is propagated rightward, and the operation corresponds to the LLVM `ashr` instruction. For unsigned integer types, a "logical" shift is performed; the high bits of the result are set to zero, and the operation corresponds to the LLVM `lshr` instruction.

#### integerBitwiseAnd

    [T | Integer?(T)]
    integerBitwiseAnd(a:T, b:T) : T;

`integerBitwiseAnd` returns the bitwise-and of `a` and `b`. It corresponds to the LLVM `and` instruction.

#### integerBitwiseOr

    [T | Integer?(T)]
    integerBitwiseOr(a:T, b:T) : T;

`integerBitwiseOr` returns the bitwise-or of `a` and `b`. It corresponds to the LLVM `or` instruction.

#### integerBitwiseXor

    [T | Integer?(T)]
    integerBitwiseXor(a:T, b:T) : T;

`integerBitwiseXor` returns the bitwise-xor of `a` and `b`. It corresponds to the LLVM `xor` instruction.

#### integerBitwiseNot

    [T | Integer?(T)]
    integerBitwiseNot(a:T) : T;

`integerBitwiseNot` returns the bitwise-not of `a`. LLVM represents bitwise-not as an `xor %T %a, -1` instruction.

#### numericConvert

    [T, U | Numeric?(T) and Numeric?(U)]
    numericConvert(static T, a:U) : T;

`numericConvert` returns `a` converted to type `T` while preserving its numeric value. If `T` and `U` are the same type, the value is simply copied. How it works depends on the output and input types:

##### Integer to integer conversion

Conversion from an integer type to a smaller integer type is done by bitwise truncation, corresponding to LLVM's `trunc` instruction. Conversion from an integer type to a larger signed type is done by sign extension, corresponding to LLVM's `sext` instruction, and conversion to a larger unsigned type is done by zero extension, corresponding to `zext`. Conversion to an equal-sized signed or unsigned type is done by bitwise casting, corresponding to the `bitcast` instruction.

##### Floating-point to floating-point conversion

Conversion among floating-point types is done by precision truncation or extension, corresponding to the LLVM `fptrunc` and `fpext` instructions. Overflowing truncation is undefined.

##### Integer to floating-point conversion

Conversion from integer to floating-point types is done corresponding to the LLVM instructions `sitofp` for signed types, and `uitofp` for unsigned types. Overflowing conversion is undefined.

##### Integer to floating-point conversion

Conversion from floating-point to integer types is done corresponding to the LLVM instructions `fptosi` for signed types, and `fptoui` for unsigned types. Overflowing conversion is undefined.

### Checked integer operations

These operations provide integer arithmetic operations checked for overflow. Unlike the previously-described numeric primitives, the results of these operations are always undefined if they overflow; however, an additional boolean value is also returned that will be true if the operation overflowed. For non-overflowing cases, these functions behave like their non-checked counterparts and return false as their second value. Unlike normal symbols, they may not be overloaded.

    [T | Integer?(T)]
    integerAddChecked(a:T, b:T) : T, Bool;
    [T | Integer?(T)]
    integerSubtractChecked(a:T, b:T) : T, Bool;
    [T | Integer?(T)]
    integerMultiplyChecked(a:T, b:T) : T, Bool;
    [T | Integer?(T)]
    integerDivideChecked(a:T, b:T) : T, Bool;
    [T | Integer?(T)]
    integerNegateChecked(a:T) : T, Bool;
    [T | Integer?(T)]
    integerRemainderChecked(a:T, b:T) : T, Bool;
    [T | Integer?(T)]
    integerShiftLeftChecked(a:T, b:T) : T, Bool;
    [T, U | Integer?(T) and Integer?(U)]
    integerConvertChecked(static T, a:U) : T, Bool;

### Pointer operations

These operations create, dereference, compare, and convert pointers. Unlike normal symbols, they may not be overloaded.

#### addressOf

    [T]
    addressOf(ref x:T) : Pointer[T];

`addressOf` returns the address of `x`, which must be an lvalue. It is equivalent to the prefix `&` operator.

#### pointerDereference

    [T]
    pointerDereference(p:Pointer[T]) : ref T;

`pointerDereference` returns a reference to the object pointed to by `p`. (It is effectively a no-op at the LLVM level, because references are themselves represented as pointers.)

#### pointerEquals?

    [T, U]
    pointerEquals?(p:Pointer[T], q:Pointer[U]) : Bool;

`pointerEquals?` returns true if `p` and `q` have the same address value. It corresponds to the LLVM `icmp eq` instruction.

#### pointerLesser?

    [T, U]
    pointerLesser?(p:Pointer[T], q:Pointer[U]) : Bool;

`pointerLesser?` returns true if the address of `p` is numerically less than that of `q`. It corresponds to the LLVM `icmp lt` instruction.

#### pointerOffset

    [T, I | Integer?(I)]
    pointerOffset(p:Pointer[T], i:I) : Pointer[T];

`pointerOffset` returns a new pointer value, offset from the address of `p` by `i * TypeSize(T)` bytes. It corresponds to the LLVM `getelementptr` instruction.

#### pointerToInt

    [T, I | Integer?(I)]
    pointerToInt(static I, p:Pointer[T]) : I;

`pointerToInt` converts the address value of `p` to an integer type `I`. If `I` is larger than a pointer, the address is zero-extended; if smaller, the address is truncated. The function corresponds to the LLVM `ptrtoint` instruction.

#### intToPointer

    [T, I | Integer?(I)]
    intToPointer(static T, address:I) : Pointer[T];

`intToPointer` converts the integer value `address` into a pointer of type `T`. If `I` is larger than a pointer, its value is truncated; if smaller, the value is zero-extended. The function corresponds to the LLVM `inttoptr` instruction.

#### pointerCast

    [P1, P2 | Pointer?(P1) and Pointer?(P2)]
    pointerCast(static P1, p:P2) : P1;

`pointerCast` converts a pointer `p` to a value of another pointer type with the same address value. It corresponds to an LLVM `bitcast` instruction. In addition to casting data pointers (such as `Pointer[T]` to `Pointer[U]`), it may also cast among `CodePointer`, `CCodePointer`, etc. types, and cast data to code pointers and back.

### Function pointer operations

These operations create and invoke pointers to instances of Clay functions. Unlike normal symbols, they may not be overloaded.

#### makeCodePointer

    [F, ..T]
    makeCodePointer(static F, static ..T) : CodePointer[[..T], [..CallType(F, ..T)]];

`makeCodePointer` looks up an overload for `F` matching the input types `..T`. If a matching overload is found, the overload is instantiated for the given input types, and a pointer to the function instance is returned as a [`CodePointer`](#codepointer). The output types parameter of the `CodePointer` is deduced from the matched overload's return types. `F` must be a symbol or a lambda that does not capture its scope (which is equivalent to a symbol). An error is raised if `F` is not a symbol, or no matching overload for `F` is found.

`makeCodePointer` matches overloads as if all input types are lvalues. Taking `CodePointer`s to rvalue functions is currently unsupported.

#### makeCCodePointer

    [F, ..T]
    makeCCodePointer(static F, static ..T) : CCodePointer[[..T], [..CallType(F, ..T)]];

`makeCCodePointer` looks up an overload for `F` matching the input types `..T`. If a matching overload is found and is determined to be C-compatible, the overload is instantiated for the given input types, along with a thunk function adapting the overload to the C calling convention. A pointer to the thunk is returned as a [`CCodePointer`](#ccodepointer). The output types parameter of the `CCodePointer` is deduced from the matched overload's return types. `F` must be a symbol or a lambda that does not capture its scope (which is equivalent to a symbol). An error is raised if `F` is not a symbol, no matching overload for `F` is found, or the matching overload is not C-compatible.

The matched overload must meet the following criteria to be deemed C-compatible:

* It must return zero or one values.
* It must not have any arguments of types with nontrivial `copy`, `move`, or `destroy` operations.

Like an external function, if a Clay exception escapes from the pointed-to overload, the `unhandledExceptionInExternal` operator function is called.

#### callCCodePointer

    define callCCodePointer;
    [..In, ..Out]
    overload callCCodePointer(f:CCodePointer[[..In], [..Out]], ..args:In) : ..Out;
    [..In, ..Out]
    overload callCCodePointer(f:VarArgsCCodePointer[[..In], [..Out]], ..args:In, ..varArgs) : ..Out;
    [..In, ..Out]
    overload callCCodePointer(f:LLVMCodePointer[[..In], [..Out]], ..args:In) : ..Out;
    // and so on for StdCallCodePointer, etc.

`callCCodePointer` invokes an external function, `CCodePointer`, or other external function pointer type.

### Atomic memory operations

The following functions provide uninterruptible, lock-free memory access and synchronization. Unlike normal symbols, they may not be overloaded. Atomic operations are currently not supported by the compile-time evaluator; an error will be raised if an atomic operation is evaluated at compile time.

#### Memory order symbols

    define OrderUnordered;
    define OrderMonotonic;
    define OrderAcquire;
    define OrderRelease;
    define OrderAcqRel;
    define OrderSeqCst;

These symbols are used as parameters by every atomic operation to specify the memory ordering constraints for that operation. These correspond to LLVM's memory ordering constraints, which in turn are a superset of those specified by the C11 and C++11 memory model. See the [LLVM Atomic Instructions and Concurrency Guide](http://llvm.org/docs/Atomics.html) for details.

* `OrderUnordered` corresponds to the LLVM `unordered` memory ordering.
* `OrderMonotonic` corresponds to the LLVM `monotonic` and C++11 `memory_order_relaxed` orderings.
* `OrderAcquire` corresponds to the LLVM `acquire` and C++11 `memory_order_acquire` orderings.
* `OrderRelease` corresponds to the LLVM `release` and C++11 `memory_order_release` orderings.
* `OrderAcqRel` corresponds to the LLVM `acq_rel` and C++11 `memory_order_acq_rel` orderings.
* `OrderSeqCst` corresponds to the LLVM `seq_cst` and C++11 `memory_order_seq_cst` orderings.

#### atomicLoad

    [Order, T | Order?(Order)]
    atomicLoad(static Order, p:Pointer[T]) : T;

`atomicLoad` performs an atomic load of the value pointed to by `p`. If atomic loads of type `T` are not supported by the target platform, an error is raised. The value is bitwise-copied. The load is subject to the memory ordering constraints specified by `Order`. The function corresponds to the LLVM `load atomic` instruction.

#### atomicStore

    [Order, T | Order?(Order)]
    atomicStore(static Order, p:Pointer[T], value:T) :;

`atomicStore` performs an atomic store of `T` to the address of `p`. If atomic stores of type `T` are not supported by the target platform, an error is raised. `value` is bitwise-copied. The store is subject to the memory ordering constraints specified by `Order`. The function corresponds to the LLVM `store atomic` instruction.

#### atomicRMW

    define RMWXchg;
    define RMWAdd;
    define RMWSubtract;
    define RMWAnd;
    define RMWNAnd;
    define RMWOr;
    define RMWXor;
    define RMWMin;
    define RMWMax;
    define RMWUMin;
    define RMWUMax;

    [Order, Op, T | Order?(Order) and RMWOp?(Op)]
    atomicRMW(static Order, static Op, p:Pointer[T], operand:T) : T;

`atomicRMW` applies an atomic read-modify-write update operation to the value pointed to by `p`. The value pointed to by `p` prior to the operation is returned. The `Op` parameter determines the operation used to update `p^`:

* `RMWXchg` causes `operand` to be written to `p^`. The value is bitwise copied.
* `RMWAdd` causes `operand` to be added to `p^`. `T` must be an integer type.
* `RMWSubtract` causes `operand` to be subtracted from `p^`. `T` must be an integer type.
* `RMWMin` causes the signed minimum of `operand` and `p^` to be written to `p`. `T` must be an integer type.
* `RMWMax` causes the signed maximum of `operand` and `p^` to be written to `p`. `T` must be an integer type.
* `RMWUMin` causes the unsigned minimum of `operand` and `p^` to be written to `p`. `T` must be an integer type.
* `RMWUMax` causes the unsigned maximum of `operand` and `p^` to be written to `p`. `T` must be an integer type.
* `RMWAnd` causes `operand` to be bitwise-anded with `p^`.
* `RMWNAnd` causes `operand` to be bitwise-anded with `p^`, and the bitwise-not of the result is written to `p`.
* `RMWOr` causes `operand` to be bitwise-ored with `p^`.
* `RMWXor` causes `operand` to be bitwise-xored with `p^`.

The update is subject to the memory ordering constraints specified by `Order`. The function corresponds to the LLVM `atomicrmw` instruction. An error is raised if the target platform does not atomically support the specified operation for `T`.

#### atomicCompareExchange

    [Order, T | Order?(Order)]
    atomicCompareExchange(static Order, p:Pointer[T], old:T, new:T) : T;

`atomicCompareExchange` performs an atomic compare-and-swap update of the value pointed to by `p`. If `p^` is bitwise equal to `old`, `new` is bitwise-written to `p`, and `old` is returned; otherwise, `p^` is unchanged, and its current value is returned. An error is raised if the target platform does not support atomic compare-and-swap for type `T`. The operation is subject to the memory ordering constraints specified by `Order`. The function corresponds to the LLVM `cmpxchg` instruction.

#### atomicFence

    [Order | Order?(Order)]
    atomicFence(static Order);

`atomicFence` introduces a happens-before edge with `OrderAcquire`, `OrderRelease`, `OrderAcqRel`, or `OrderSeqCst` semantics without an associated memory operation. It corresponds to an LLVM `fence` instruction.

### Exception handling

The following functions support the exception handling implementation. Unlike normal symbols, they may not be overloaded.

#### activeException

    activeException() : Pointer[Int8];

`activeException()` returns a pointer to the exception that is currently instigating unwinding. It is only valid during unwinding itself, specifically not during catch clauses. This primitive is an implementation detail and should not normally be used.

### Symbol and function introspection

The following functions query properties of symbols. Unlike normal symbols, they may not be overloaded.

#### Type?

    [T]
    Type?(static T) : Bool;

`Type?` returns true if the compile-time value `T` is a symbol, and that symbol names a type. If `T` is not a symbol or is a non-type symbol, false is returned.

    // Example
    define foo;
    record bar ();

    main() {
        println(Type?(Type?)); // false
        println(Type?(Int32)); // true

        println(Type?(foo)); // false
        println(Type?(bar)); // true

        println(Type?(static 3)); // false
    }

#### CallDefined?

    [F, ..T]
    CallDefined?(static F, static ..T) : Bool;

`CallDefined?` attempts to find an overload of the symbol `F` matching the input types `..T`. If successful, it returns true; otherwise, it returns false. To find an overload for calling a non-symbol type, `CallDefined?(call, FunctionType, ..T)` can be used.

#### ModuleName

    [S]
    ModuleName(static S) : StringConstant;

`ModuleName` generates a string literal corresponding to the fully-qualified module name of the module containing the symbol `S`. Like a true string literal, it is evaluated into a value using the `StringConstant` operator function. If `S` is itself a module symbol, the module's own name is returned. If `S` is not a symbol, an error is raised.

    // Example
    import foo;
    import foo.bar as bar;

    in baz;

    main() {
        println(ModuleName(main)); // would print "baz"
        println(ModuleName(foo.a)); // would print "foo"
        println(ModuleName(bar.a)); // would print "foo.bar"
        println(ModuleName(bar)); // would print "foo.bar"
    }

#### IdentifierModuleName

    [S]
    IdentifierModuleName(static S);

`IdentifierModuleName` is like `ModuleName`, except that the module's name is returned as a static string rather than as a string literal.

#### StaticName

    [x]
    StaticName(static x) : StringConstant;

`StaticName` generates a string literal corresponding to the name of the static value `x`. The name string is generated as follows:

* If `x` is a symbol, the symbol's name (not including its module name, but including its parameters if any) is used.
* If `x` is a static string, its string value is used.
* If `x` is a numeric value, it is converted into a string in decimal notation.
* If `x` is a tuple, it is converted into a comma-delimited string surrounded in square brackets (`[]`).

Like a true string literal, the generated string is evaluated into a value using the `StringConstant` operator function.

#### IdentifierStaticName

    [x]
    IdentifierStaticName(static x);

`IdentifierStaticName` is like `StaticName`, except that the static object's name is returned as a static string rather than as a string literal.

#### staticFieldRef

    [M, name | Identifier?(name)]
    staticFieldRef(static M, static name);

`staticFieldRef` looks up a public global value in the module `M`. If `name` is found in `M`, it is evaluated as if referenced directly by name. If `name` is not a public member of `M`, an error is raised.

### Static string manipulation

The following functions provide operations on static strings. Unlike normal symbols, they may not be overloaded.

#### Identifier?

    [S]
    Identifier?(static S) : Bool;

`Identifier?` returns true if `S` is a static string, or false otherwise.

#### IdentifierSize

    [S | Identifier?(S)]
    IdentifierSize(static S) : SizeT;

`IdentifierSize` returns the number of characters in the static string `S`.

#### IdentifierConcat

    [..SS | allValues?(Identifier?, ..SS)]
    IdentifierConcat(static ..SS);

`IdentifierConcat` returns the static string consisting of the concatenation of all of its parameters.

#### IdentifierSlice

    [S, n, m |
        Identifier?(S)
        and n >= 0 and n < IdentifierSize(n)
        and m >= 0 and m < IdentifierSize(m)
    ]
    IdentifierSlice(static S, static n, static m);

`IdentifierSlice` returns the static string consisting of the substring of `S` from character `n` up to but not including character `m`.

### Type introspection

The following functions provide information about types. Unlike normal symbols, they may not be overloaded.

#### TypeSize

    [T | Type?(T)]
    TypeSize(static T) : SizeT;

`TypeSize` returns the size in bytes of a value of type `T`.

#### TypeAlignment

    [T | Type?(T)]
    TypeAlignment(static T) : SizeT;

`TypeAlignment` returns the natural alignment in bytes of a value of type `T`.

#### CCodePointer?

    [T]
    CCodePointer?(static T) : Bool;

`CCodePointer?` returns true if `T` is a symbol and is an instance of one of the [external code pointer types](#externalcodepointertypes), such as `CCodePointer`, `LLVMCodePointer`, etc.

#### TupleElementCount

    [..T]
    TupleElementCount(static Tuple[..T]) : SizeT;

`TupleElementCount` returns the number of elements inside values of the tuple type `Tuple[..T]`.

#### UnionMemberCount

    [..T]
    UnionMemberCount(static Union[..T]) : SizeT;

`UnionMemberCount` returns the number of member types of the union type `Union[..T]`.

#### Record?

    [R]
    Record?(static R) : Bool;

`Record?` returns true if `R` is a symbol that names a record type, or false if `R` is not a symbol or is a non-record-type symbol.

#### RecordFieldCount

    [R | Record?(R)]
    RecordFieldCount(static R) : SizeT;

`RecordFieldCount` returns the number of fields inside values of the record type `R`.

#### RecordFieldName

    [R, n | Record?(R) and n >= 0 and n < RecordFieldCount(R)]
    RecordFieldName(static R, static n);

`RecordFieldName` returns the name of the `n`th field of the record type `R` as a static string. `n` is zero-based, and an error is raised if `R` is not a record type or if `n` is less than zero or greater than or equal to the number of fields in `R`.

#### RecordWithField?

    [R, name | Record?(R) and Identifier?(name)]
    RecordWithField?(static R, static name) : Bool;

`RecordWithField?` returns true if `R` is a record type with a field named by the static string `name`, or false otherwise.

#### Variant?

    [V]
    Variant?(static V) : Bool;

`Variant?` returns true if `V` is a symbol that names a variant type, or false if `V` is not a symbol or is a non-variant-type symbol.

#### VariantMemberCount

    [V | Variant?(V)]
    VariantMemberCount(static V) : SizeT;

`VariantMemberCount` returns the number of instance types of the variant type `T`. An error is raised if `V` is not a variant type.

#### VariantMemberIndex

    [V | Variant?(V) and n >= 0 and n < VariantMemberCount(V)]
    VariantMemberIndex(static V, static n);

`VariantMemberIndex` returns the `n`th instance type of the variant type `V`. The correspondence of instance types to indices is unspecified, but calling `VariantMemberIndex` for every integer value from zero up to but not including `VariantMemberCount(V)` will return each instance type once. `n` is zero-based, and an error is raised if `V` is not a variant type, or if `n` is negative or greater than or equal to the number of instance types of `V`.

#### Enum?

    [E]
    Enum?(static E) : Bool;

`Enum?` returns true if `E` is a symbol that names an enum type, or false if `E` is not a symbol or is a non-enum-type symbol.

#### EnumMemberCount

    [E | Enum?(E)]
    EnumMemberCount(static E) : SizeT;

`EnumMemberCount` returns the number of symbolic values defined for the enum type `E`. An error is raised if `E` is not an enum type.

#### EnumMemberName

    [E | Enum?(E) and n >= 0 and n < EnumMemberCount(E)]
    EnumMemberName(static E, static n) : StringConstant;

`EnumMemberName` generates a string literal corresponding to the symbolic name of the `n`th ordinal value of the `E` enum type. Like a true string literal, the generated string is evaluated into a value using the `StringConstant` operator function. `n` is zero-based, and an error is raised if `E` is not an enum type or if `n` is negative or greater than or equal to the number of values of `E`.

### Compiler flags

The following functions query settings for the current compilation unit. Unlike normal symbols, they may not be overloaded.

#### ExceptionsEnabled?

    // If exceptions are enabled
    alias ExceptionsEnabled? = true;
    // If exceptions are disabled
    alias ExceptionsEnabled? = false;

`ExceptionsEnabled?` is a global alias that is set to true if exceptions are enabled.

#### Flag?

    [name | Identifier?(name)]
    Flag?(static name) : Bool;

`Flag?` returns true if the compiler was invoked with a `-D<name>` or `-D<name>=value` flag matching the static string `name`.

#### Flag

    [name | Identifier?(name)]
    Flag(static name);

`Flag` returns the value associated with the compiler flag `-D<name>=value` flag as a static string. If no `-D` flag was provided corresponding to `name`, or a `-D<name>` flag was provided without an associated value, the empty static string `#""` is returned.

### External function attributes

The following symbols are defined for use as attributes of external functions.

#### Calling convention attributes

When used as external attributes, the following symbols control the calling convention used by the external function:

* `AttributeCCall` causes the function to use the C calling convention.
* `AttributeStdCall` causes the function to use the `__stdcall` calling convention on Windows x86 systems.
* `AttributeFastCall` causes the function to use the `__fastcall` calling convention on Windows x86 systems.
* `AttributeThisCall` causes the function to use the `__thiscall` calling convention on Windows x86 systems.
* `AttributeLLVMCall` causes the function to use the LLVM `ccc` calling convention.

#### Linkage attributes

When used as external attributes, the following symbols affect the linkage of the external function:

* `AttributeDLLImport` gives the function `__dllimport` linkage on Windows targets.
* `AttributeDLLExport` gives the function `__dllexport` linkage on Windows targets.

### Miscellaneous functions

Some additional utility functions are provided as primitives. Unlike normal symbols, these functions may not be overloaded.

#### staticIntegers

    [n | n >= 0]
    staticIntegers(static n);

The `staticIntegers` returns a multiple value list of `static` integer values from `static 0` up to `static n - 1`. `staticIntegers(static 0)` returns no values.


text:
package com.google.javascript.jscomp.diagnostic;

/** Fail-fast J2CL stub. */
public final class LogsGson {

  static String toJson(Object o) {
    throw new UnsupportedOperationException("Not available in J2CL");
  }

  /** Fail-fast J2CL stub. */
  public interface Able {
    Object toLogsGson();
  }

  private LogsGson() {
    throw new AssertionError();
  }
}


text:
package main

import (
	"sort"

	"github.com/gocql/gocql"
)

type Table struct {
	Keyspace_name               string
	Table_name                  string
	Bloom_filter_fp_chance      float64
	Caching                     map[string]string
	Comment                     string
	Compaction                  map[string]string
	Compression                 map[string]string
	Crc_check_chance            float64
	Dclocal_read_repair_chance  float64
	Default_time_to_live        int32
	Extensions                  map[string][]byte
	Flags                       []string
	Gc_grace_seconds            int32
	Id                          gocql.UUID
	Max_index_interval          int32
	Memtable_flush_period_in_ms int32
	Min_index_interval          int32
	Read_repair_chance          float64
	Speculative_retry           string
	Columns                     []Column
}

type Column struct {
	Keyspace_name     string
	Table_name        string
	Column_name       string
	Clustering_order  string
	Column_name_bytes []byte
	Kind              string
	Position          int32
	Type              string
}

type ColumnByPosition []Column

func (a ColumnByPosition) Len() int           { return len(a) }
func (a ColumnByPosition) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ColumnByPosition) Less(i, j int) bool { return a[i].Position < a[j].Position }

func getTables(keyspace Keyspace) []Table {
	// TODO: add include and exlude filters
	iter := con.Query(`SELECT
				keyspace_name,
				table_name,
				bloom_filter_fp_chance,
				caching,
				comment,
				compaction,
				compression,
				crc_check_chance,
				dclocal_read_repair_chance,
				default_time_to_live,
				extensions,
				flags,
				gc_grace_seconds,
				id,
				max_index_interval,
				memtable_flush_period_in_ms,
				min_index_interval,
				read_repair_chance,
				speculative_retry
			FROM system_schema.tables
			WHERE keyspace_name = ?`, keyspace.Keyspace_name).Iter()
	var tables []Table
	var t Table
	for iter.Scan(
		&t.Keyspace_name,
		&t.Table_name,
		&t.Bloom_filter_fp_chance,
		&t.Caching,
		&t.Comment,
		&t.Compaction,
		&t.Compression,
		&t.Crc_check_chance,
		&t.Dclocal_read_repair_chance,
		&t.Default_time_to_live,
		&t.Extensions,
		&t.Flags,
		&t.Gc_grace_seconds,
		&t.Id,
		&t.Max_index_interval,
		&t.Memtable_flush_period_in_ms,
		&t.Min_index_interval,
		&t.Read_repair_chance,
		&t.Speculative_retry) {
		// ---
		tables = append(tables, t)
	}
	FatalIfError("getTables", iter.Close())
	for k, table := range tables {
		iter := con.Query(`SELECT
					keyspace_name,
					table_name,
					column_name,
					clustering_order,
					column_name_bytes,
					kind,
					position,
					type
				FROM system_schema.columns
				WHERE keyspace_name = ? AND table_name = ?`, keyspace.Keyspace_name, table.Table_name).Iter()
		var c Column
		for iter.Scan(&c.Keyspace_name, &c.Table_name, &c.Column_name, &c.Clustering_order, &c.Column_name_bytes, &c.Kind, &c.Position, &c.Type) {
			table.Columns = append(table.Columns, c)
		}
		FatalIfError("getTables.getColumns", iter.Close())
		sort.Sort(ColumnByPosition(table.Columns))
		tables[k] = table
	}
	return tables
}


text:
package main

import (
	"github.com/1and1/soma/internal/tree"
	"github.com/satori/go.uuid"
)

func (tk *treeKeeper) treeBucket(q *treeRequest) {
	switch q.Action {
	case `create_bucket`:
		tree.NewBucket(tree.BucketSpec{
			Id:          uuid.NewV4().String(),
			Name:        q.Bucket.Bucket.Name,
			Environment: q.Bucket.Bucket.Environment,
			Team:        tk.team,
			Deleted:     q.Bucket.Bucket.IsDeleted,
			Frozen:      q.Bucket.Bucket.IsFrozen,
			Repository:  q.Bucket.Bucket.RepositoryId,
		}).Attach(tree.AttachRequest{
			Root:       tk.tree,
			ParentType: `repository`,
			ParentId:   tk.repoId,
			ParentName: tk.repoName,
		})
	}
}

func (tk *treeKeeper) treeGroup(q *treeRequest) {
	switch q.Action {
	case `create_group`:
		tree.NewGroup(tree.GroupSpec{
			Id:   uuid.NewV4().String(),
			Name: q.Group.Group.Name,
			Team: tk.team,
		}).Attach(tree.AttachRequest{
			Root:       tk.tree,
			ParentType: `bucket`,
			ParentId:   q.Group.Group.BucketId,
		})
	case `delete_group`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `group`,
			ElementId:   q.Group.Group.Id,
		}, true).(tree.BucketAttacher).Destroy()
	case `reset_group_to_bucket`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `group`,
			ElementId:   q.Group.Group.Id,
		}, true).(tree.BucketAttacher).Detach()
	case `add_group_to_group`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `group`,
			ElementId:   (*q.Group.Group.MemberGroups)[0].Id,
		}, true).(tree.BucketAttacher).ReAttach(tree.AttachRequest{
			Root:       tk.tree,
			ParentType: `group`,
			ParentId:   q.Group.Group.Id,
		})
	}
}

func (tk *treeKeeper) treeCluster(q *treeRequest) {
	switch q.Action {
	case `create_cluster`:
		tree.NewCluster(tree.ClusterSpec{
			Id:   uuid.NewV4().String(),
			Name: q.Cluster.Cluster.Name,
			Team: tk.team,
		}).Attach(tree.AttachRequest{
			Root:       tk.tree,
			ParentType: `bucket`,
			ParentId:   q.Cluster.Cluster.BucketId,
		})
	case `delete_cluster`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `cluster`,
			ElementId:   q.Cluster.Cluster.Id,
		}, true).(tree.BucketAttacher).Destroy()
	case `reset_cluster_to_bucket`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `cluster`,
			ElementId:   q.Cluster.Cluster.Id,
		}, true).(tree.BucketAttacher).Detach()
	case `add_cluster_to_group`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `cluster`,
			ElementId:   (*q.Group.Group.MemberClusters)[0].Id,
		}, true).(tree.BucketAttacher).ReAttach(tree.AttachRequest{
			Root:       tk.tree,
			ParentType: `group`,
			ParentId:   q.Group.Group.Id,
		})
	}
}

func (tk *treeKeeper) treeNode(q *treeRequest) {
	switch q.Action {
	case `assign_node`:
		tree.NewNode(tree.NodeSpec{
			Id:       q.Node.Node.Id,
			AssetId:  q.Node.Node.AssetId,
			Name:     q.Node.Node.Name,
			Team:     q.Node.Node.TeamId,
			ServerId: q.Node.Node.ServerId,
			Online:   q.Node.Node.IsOnline,
			Deleted:  q.Node.Node.IsDeleted,
		}).Attach(tree.AttachRequest{
			Root:       tk.tree,
			ParentType: `bucket`,
			ParentId:   q.Node.Node.Config.BucketId,
		})
	case `delete_node`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `node`,
			ElementId:   q.Node.Node.Id,
		}, true).(tree.BucketAttacher).Destroy()
	case `reset_node_to_bucket`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `node`,
			ElementId:   q.Node.Node.Id,
		}, true).(tree.BucketAttacher).Detach()
	case `add_node_to_group`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `node`,
			ElementId:   (*q.Group.Group.MemberNodes)[0].Id,
		}, true).(tree.BucketAttacher).ReAttach(tree.AttachRequest{
			Root:       tk.tree,
			ParentType: `group`,
			ParentId:   q.Group.Group.Id,
		})
	case `add_node_to_cluster`:
		tk.tree.Find(tree.FindRequest{
			ElementType: `node`,
			ElementId:   (*q.Cluster.Cluster.Members)[0].Id,
		}, true).(tree.BucketAttacher).ReAttach(tree.AttachRequest{
			Root:       tk.tree,
			ParentType: `cluster`,
			ParentId:   q.Cluster.Cluster.Id,
		})
	}
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix


text:
SET(CHIBIOS_VARIOUS_MODULES evtimer shell syscalls)

SET(CHIBIOS_evtimer_SEARCH_PATH ${CHIBIOS_ROOT}/os/various)
SET(CHIBIOS_evtimer_SOURCES evtimer.c)
SET(CHIBIOS_evtimer_SEARCH_HEADERS evtimer.h)

SET(CHIBIOS_shell_SEARCH_PATH ${CHIBIOS_ROOT}/os/various)
SET(CHIBIOS_shell_SOURCES shell.c)
SET(CHIBIOS_shell_SEARCH_HEADERS shell.h)

SET(CHIBIOS_syscalls_SEARCH_PATH ${CHIBIOS_ROOT}/os/various)
SET(CHIBIOS_syscalls_SOURCES syscalls.c)


text:
package gov.nih.nci.nbia.util;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

public abstract class PropertyLoader
{
    /**
     * Looks up a resource named 'name' in the classpath. The resource must map
     * to a file with .properties extention. The name is assumed to be absolute
     * and can use either "/" or "." for package segment separation with an
     * optional leading "/" and optional ".properties" suffix. Thus, the
     * following names refer to the same resource:
     * <pre>
     * some.pkg.Resource
     * some.pkg.Resource.properties
     * some/pkg/Resource
     * some/pkg/Resource.properties
     * /some/pkg/Resource
     * /some/pkg/Resource.properties
     * </pre>
     *
     * @param theName classpath resource name [may not be null]
     * @param loader classloader through which to load the resource [null
     * is equivalent to the application loader]
     *
     * @return resource converted to java.util.Properties [may be null if the
     * resource was not found and THROW_ON_LOAD_FAILURE is false]
     * @throws IllegalArgumentException if the resource was not found and
     * THROW_ON_LOAD_FAILURE is true
     */
    public static Properties loadProperties (String theName, ClassLoader loader)
    {
    	String name = preprocessNameArgument(theName);

        Properties result = null;

        InputStream in = null;
        try
        {
            if (loader == null) {
            	loader = ClassLoader.getSystemClassLoader ();
            }

            if (LOAD_AS_RESOURCE_BUNDLE)
            {
                name = name.replace ('/', '.');

                // Throws MissingResourceException on lookup failures:
                final ResourceBundle rb = ResourceBundle.getBundle (name,
                    Locale.getDefault (), loader);

                result = new Properties ();
                for (Enumeration<String> keys = rb.getKeys (); keys.hasMoreElements ();)
                {
                    final String key = (String) keys.nextElement ();
                    final String value = rb.getString (key);

                    result.put (key, value);
                }
            }
            else
            {
                name = name.replace ('.', '/');

                if (! name.endsWith (SUFFIX)) {
                    name = name.concat (SUFFIX);
                }

                // Returns null on lookup failures:
                in = loader.getResourceAsStream (name);
                if (in != null)
                {
                    result = new Properties ();
                    result.load (in); // Can throw IOException
                }
            }
        }
        catch (Exception e)
        {
            result = null;
        }
        finally
        {
        	closeInputStream(in);
        }

        checkResultStatus(result, name);
        return result;
    }

    /**
     * A convenience overload of {@link #loadProperties(String, ClassLoader)}
     * that uses the current thread's context classloader.
     */
    public static Properties loadProperties (final String name)
    {
        return loadProperties (name,
            Thread.currentThread ().getContextClassLoader ());
    }

    private static final boolean THROW_ON_LOAD_FAILURE = true;
    private static final boolean LOAD_AS_RESOURCE_BUNDLE = false;
    private static final String SUFFIX = ".properties";

    /* ---------------------------------------------- */

	private static void closeInputStream(InputStream in) {
        if (in != null) {
        	try {
        		in.close ();
        	}
        	catch (Throwable ignore) {
        		ignore.printStackTrace();
       		}
        }
	}

	private static String preprocessNameArgument(String name) {
		String processedName = name;
		if (name == null) {
            throw new IllegalArgumentException ("null input: name");
        }
        if (name.startsWith ("/")) {
        	processedName = name.substring (1);
        }
        if (name.endsWith (SUFFIX)) {
        	processedName = name.substring (0, name.length () - SUFFIX.length ());
        }
        return processedName;
	}

	private static void checkResultStatus(Object result, String name) {
        if (THROW_ON_LOAD_FAILURE && (result == null))
        {
            throw new IllegalArgumentException ("could not load [" + name + "]"+
                " as " + (LOAD_AS_RESOURCE_BUNDLE
                ? "a resource bundle"
                : "a classloader resource"));
        }
	}

} // End of class


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Platform.ThemeOverlay.App.BottomSheetDialog" parent="ThemeOverlay.MaterialComponents.DayNight.BottomSheetDialog">
        <item name="android:navigationBarColor">?colorSurface</item>
        <item name="android:windowLightNavigationBar">false</item>
    </style>
</resources>


text:
// Copyright (c) 2014 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;

namespace BuildDependency.TeamCity.RestClasses
{
	public class BuildType
	{
		// <buildType id="bt392" name="Bloom 2 BETA Publish"
		// href="/guestAuth/app/rest/7.0/buildTypes/id:bt392" projectName="Bloom"
		// projectId="project16" webUrl="http://build.palaso.org/viewType.html?buildTypeId=bt392"/>
		public string Id { get; set; }
		public string Name { get; set; }
		public string Href { get; set; }
		public string ProjectName { get; set; }
		public string ProjectId { get; set; }
		public string WebUrl { get; set; }

		public string IdForArtifacts
		{
			get
			{
				const string buildTypeIdString = "?buildTypeId=";
				if (string.IsNullOrEmpty(WebUrl))
					return null;
				var idIndex = WebUrl.IndexOf(buildTypeIdString, StringComparison.Ordinal);
				if (idIndex < 0)
					return null;
				return WebUrl.Substring(idIndex + buildTypeIdString.Length);
			}
		}

		public override bool Equals(object obj)
		{
			var other = obj as BuildType;
			if (other != null)
			{
				return Id == other.Id;
			}
			return base.Equals(obj);
		}

		public override int GetHashCode()
		{
			return base.GetHashCode() ^ Id.GetHashCode();
		}

		public override string ToString()
		{
			// WPF doesn't use Text (see https://github.com/picoe/Eto/issues/414), so we have to
			// return the desired value from ToString as well as Text.
			return Text;
			//return string.Format("[BuildType: Id={0}, Name={1}, Href={2}, ProjectName={3}, ProjectId={4}, WebUrl={5}]", Id, Name, Href, ProjectName, ProjectId, WebUrl);
		}

		public string Text { get { return Name; }}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/main.css" />
<title>Change user actions</title>
<wicket:head>

</wicket:head>

<wicket:extend>
    Role name: role  Back to list roles

</wicket:extend>


text:
using System;

namespace SharpVk.Interop
{
    /// <summary>
    ///
    /// </summary>
    public unsafe delegate ulong VkDeviceGetBufferDeviceAddressDelegate(SharpVk.Interop.Device device, SharpVk.Interop.BufferDeviceAddressInfo* info);
}


text:
namespace views {
namespace switches {

// Please keep alphabetized.
VIEWS_EXPORT extern const char kDisableViewsRectBasedTargeting[];

// Returns true if rect-based targeting in views should be used.
VIEWS_EXPORT bool IsRectBasedTargetingEnabled();

}  // namespace switches
}  // namespace views

#endif  // UI_VIEWS_VIEWS_SWITCHES_H_


text:
package com.tritondigital.counters.akka

import akka.actor.Actor
import com.tritondigital.counters.{Metric, Metrics, Tag}

trait ActorMetricsBase extends Actor {
  protected def metrics: Metrics
  private lazy val path = self.path.toStringWithoutAddress

  protected def monitoredReceive(message: Any)(receive: => Unit) {
    val start = System.currentTimeMillis()

    try {
      receive
    }
    finally {
      val msgClass =
        if (message == null)
          "null"
        else
          message.getClass.getSimpleName

      metrics.updateTimer("akka.actor.message", start, Tag("path", Metric.clean(path)), Tag("mclass", Metric.clean(msgClass)))
    }
  }
}


text:
package org.apache.spark.sql.execution.local

import scala.util.Random

import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.SortOrder

class TakeOrderedAndProjectNodeSuite extends LocalNodeTest {

  private def testTakeOrderedAndProject(desc: Boolean): Unit = {
    val limit = 10
    val ascOrDesc = if (desc) "desc" else "asc"
    test(ascOrDesc) {
      val inputData = Random.shuffle((1 to 100).toList).map { i => (i, i) }.toArray
      val inputNode = new DummyNode(kvIntAttributes, inputData)
      val firstColumn = inputNode.output(0)
      val sortDirection = if (desc) Descending else Ascending
      val sortOrder = SortOrder(firstColumn, sortDirection)
      val takeOrderAndProjectNode = new TakeOrderedAndProjectNode(
        conf, limit, Seq(sortOrder), Some(Seq(firstColumn)), inputNode)
      val expectedOutput = inputData
        .map { case (k, _) => k }
        .sortBy { k => k * (if (desc) -1 else 1) }
        .take(limit)
      val actualOutput = takeOrderAndProjectNode.collect().map { row => row.getInt(0) }
      assert(actualOutput === expectedOutput)
    }
  }

  testTakeOrderedAndProject(desc = false)
  testTakeOrderedAndProject(desc = true)
}


text:
package Generate

import (
	_ "github.com/lib/pq"
)


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('lan', '0023_auto_20220803_1159'),
    ]

    operations = [
        migrations.AddField(
            model_name='tickettype',
            name='frame_background_color',
            field=models.CharField(blank=True, max_length=50, verbose_name='frame background color'),
        ),
        migrations.AddField(
            model_name='tickettype',
            name='frame_foreground_color',
            field=models.CharField(blank=True, max_length=50, verbose_name='frame foreground color'),
        ),
    ]


text:
<?php

/**
 * Url
 *
 * @package Less
 * @subpackage tree
 */
class Less_Tree_Url extends Less_Tree {

	public $attrs;
	public $value;
	public $currentFileInfo;
	public $isEvald;
	public $type = 'Url';

	public function __construct( $value, $currentFileInfo = null, $isEvald = null ) {
		$this->value = $value;
		$this->currentFileInfo = $currentFileInfo;
		$this->isEvald = $isEvald;
	}

	public function accept( $visitor ) {
		$this->value = $visitor->visitObj( $this->value );
	}

	/**
	 * @see Less_Tree::genCSS
	 */
	public function genCSS( $output ) {
		$output->add( 'url(' );
		$this->value->genCSS( $output );
		$output->add( ')' );
	}

	/**
	 * @param Less_Functions $ctx
	 */
	public function compile( $ctx ) {
		$val = $this->value->compile( $ctx );

		if ( !$this->isEvald ) {
			// Add the base path if the URL is relative
			if ( Less_Parser::$options['relativeUrls']
				&& $this->currentFileInfo
				&& is_string( $val->value )
				&& Less_Environment::isPathRelative( $val->value )
			) {
				$rootpath = $this->currentFileInfo['uri_root'];
				if ( !$val->quote ) {
					$rootpath = preg_replace( '/[\(\)\'"\s]/', '\\$1', $rootpath );
				}
				$val->value = $rootpath . $val->value;
			}

			$val->value = Less_Environment::normalizePath( $val->value );
		}

		// Add cache buster if enabled
		if ( Less_Parser::$options['urlArgs'] ) {
			if ( !preg_match( '/^\s*data:/', $val->value ) ) {
				$delimiter = strpos( $val->value, '?' ) === false ? '?' : '&';
				$urlArgs = $delimiter . Less_Parser::$options['urlArgs'];
				$hash_pos = strpos( $val->value, '#' );
				if ( $hash_pos !== false ) {
					$val->value = substr_replace( $val->value, $urlArgs, $hash_pos, 0 );
				} else {
					$val->value .= $urlArgs;
				}
			}
		}

		return new Less_Tree_URL( $val, $this->currentFileInfo, true );
	}

}