text:
"""Parses Adrian code and returns its AST."""

from dataclasses import dataclass
from typing import List, NoReturn, Tuple, Union, Optional
from itertools import zip_longest
from functools import partial

from .adrian_ast import (
    ConstantDeclaration, FunctionDeclaration, Statement, Expression, InterfaceDeclaration, Type,
    StructDeclaration, Call, FieldDeclaration, FunctionPrototypeDeclaration, Void, Return, Reassignment,
    Annotation, ArgumentDeclaration, ParameterDeclaration, Name, ParameterizedType, NamedParameter,
    Name, NamedArgument, StringLiteral, IntLiteral, Member)
from .adrian_compilation_context import CompilationContext
from .adrian_errors import syntax_error, internal_no_proper_case_error

INDENTATION_UNIT = " " * 4

def parse(context: CompilationContext) -> List[Statement]:
    return Parser(context).parse_ast()

class Trailer:
    pass

@dataclass
class TrailerCall(Trailer):
    parentheses_line_pos: Tuple[Tuple[int, int], Tuple[int, int]]
    arguments: List[Expression]

@dataclass
class TrailerMember(Trailer):
    dot_line_pos: Tuple[int, int]
    member: str

class Parser:
    def __init__(self, context: CompilationContext):
        self.context = context
        self.code = context.code
        self.indentation_level = 0
        self.cached_indentation = None

        self.parse_expression = self._make_expression_parser(
            self.parse_name,
            self.parse_string_literal,
            self.parse_integer_literal
        )
        self.parse_function_argument_expression = self._make_expression_parser(
            self.parse_named_argument_or_name,
            self.parse_string_literal,
            self.parse_integer_literal
        )

        self.parse_call_arguments = self._make_arguments_parser(self.parse_function_argument_expression)
        self.parse_type_parameters = self._make_arguments_parser(partial(self.parse_type, True))
        self.parse_function_declaration_arguments = self._make_arguments_parser(
            self.parse_function_declaration_argument)
        self.parse_annotation_arguments = self._make_arguments_parser(self.parse_name)

        self.parse_declaration_parameters = self._make_arguments_parser(self.parse_parameter_declaration)
        self.parse_declaration_interfaces = self._make_arguments_parser(
            self.parse_type, possibly_without_parentheses=True)
        self.parse_interface_body = self._make_body_parser(
            self.parse_function_prototype_declaration,
            self.parse_field_declaration
        )
        self.parse_struct_body = self._make_body_parser(
            self.parse_function_declaration,
            self.parse_field_declaration
        )
        self.parse_function_body = self._make_body_parser(
            self.parse_constant_declaration,
            self.parse_return_statement,
            self.parse_reassignment_or_call
        )

    # Parser methods
    def parse_ast(self) -> List[Statement]:
        result = []
        self.spaces()
        node = self.parse_top_lvl_node()
        while node is not None:
            result.append(node)
            self.spaces()
            node = self.parse_top_lvl_node()
        if self.code:
            self.syntax_error("unknown language statement")
        return result

    def parse_top_lvl_node(self) -> Optional[Statement]:
        funcs = [
            self.parse_constant_declaration,
            self.parse_interface_declaration,
            self.parse_struct_declaration,
            self.parse_function_declaration,
            self.parse_call
        ]
        for func in funcs:
            result = func()
            if result is not None:
                return result
        return None

    def parse_constant_declaration(self) -> Optional[ConstantDeclaration]:
        annotations = self.parse_annotations()
        let_keyword = (self.context.line, self.context.pos)
        if not self.parse_keyword("let"):
            return None
        self.spaces()
        name = self.parse_name()
        if name is None:
            self.syntax_error("expected name")
        colon = (self.context.line, self.context.pos)
        if self.parse_string(":"):
            self.spaces()
            type_ = self.parse_type()
            if type_ is None:
                self.syntax_error("expected type")
            self.spaces()
            eq_sign = (self.context.line, self.context.pos)
            if self.parse_string("="):
                self.spaces()
                expression = self.parse_expression()
                if expression is None:
                    self.syntax_error("expected expression")
                return ConstantDeclaration(
                    let_keyword, name, colon, type_, eq_sign, expression, annotations=annotations)
            else:
                return ConstantDeclaration(
                    let_keyword, name, colon, type_, eq_sign=None, expression=None, annotations=annotations)
        self.spaces()
        eq_sign = (self.context.line, self.context.pos)
        if not self.parse_string("="):
            self.syntax_error("expected ':' or '='")
        self.spaces()
        expression = self.parse_expression()
        if expression is None:
            self.syntax_error("expected expression")
        return ConstantDeclaration(
            let_keyword, name, colon=None, type_=None, eq_sign=eq_sign, expression=expression, annotations=annotations)

    def parse_interface_declaration(self) -> Optional[InterfaceDeclaration]:
        interface_keyword = self.context.line, self.context.pos
        if not self.parse_keyword("interface"):
            return None
        self.spaces()
        name = self.parse_name()
        if name is None:
            self.syntax_error("expected name")
        parentheses_line_pos, parameters = self.parse_declaration_parameters()
        if parameters is None:
            parameters = []
        self.spaces()
        interfaces: List[Type] = []
        is_operator_line_pos: Optional[Tuple[int, int]] = (self.context.line, self.context.pos)
        if self.parse_keyword("is"):
            self.spaces()
            interfaces = self.parse_declaration_interfaces()
            if interfaces is None:
                self.syntax_error("expected interfaces")
        else:
            is_operator_line_pos = None
        if not self.parse_string(":"):
            return InterfaceDeclaration(
                interface_keyword, name, parentheses_line_pos, parameters, is_operator_line_pos, interfaces, [])
        body = self.parse_interface_body()
        if not body:
            self.syntax_error("expected at least 1 indented statement")
        return InterfaceDeclaration(
            interface_keyword, name, parentheses_line_pos, parameters, is_operator_line_pos, interfaces, body)

    def parse_struct_declaration(self) -> Optional[StructDeclaration]:
        struct_keyword = self.context.line, self.context.pos
        if not self.parse_keyword("struct"):
            return None
        self.spaces()
        name = self.parse_name()
        if name is None:
            self.syntax_error("expected name")
        parentheses_line_pos, parameters = self.parse_declaration_parameters()
        if parameters is None:
            parameters = []
        self.spaces()
        interfaces: List[Type] = []
        is_operator_line_pos: Optional[Tuple[int, int]] = (self.context.line, self.context.pos)
        if self.parse_keyword("is"):
            self.spaces()
            interfaces = self.parse_declaration_interfaces()
            if interfaces is None:
                self.syntax_error("expected interfaces")
        else:
            is_operator_line_pos = None
        if not self.parse_string(":"):
            return StructDeclaration(
                struct_keyword, name, parentheses_line_pos, parameters, is_operator_line_pos, interfaces, [])
        body = self.parse_struct_body()
        if not body:
            self.syntax_error("expected at least 1 indented statement")
        return StructDeclaration(
            struct_keyword, name, parentheses_line_pos, parameters, is_operator_line_pos, interfaces, body)

    def parse_call(self) -> Optional[Call]:
        expression = self.parse_expression()
        if isinstance(expression, Call):
            return expression
        return None

    def parse_field_declaration(self) -> Optional[FieldDeclaration]:
        name = self.parse_name()
        if name is None:
            return None
        if not self.parse_string(":"):
            self.syntax_error("expected ':'")
        self.spaces()
        type_ = self.parse_type()
        if type_ is None:
            self.syntax_error("expected type")
        prev_code, prev_line = self.spaces(return_prev_state=True)
        eq_sign: Optional[Tuple[int, int]] = (self.context.line, self.context.pos)
        if self.parse_string("="):
            self.spaces()
            expression = self.parse_expression()
            if expression is None:
                self.syntax_error("expected expression")
        else:
            self.code, tmp = prev_code, prev_line
            assert(isinstance(tmp, int))
            self.context.line = tmp
            eq_sign = None
            expression = None
            self.cached_indentation = None
        return FieldDeclaration(name, type_, eq_sign, expression)

    def parse_function_prototype_declaration(self) -> Optional[FunctionPrototypeDeclaration]:
        fun_keyword = self.context.line, self.context.pos
        if not self.parse_keyword("fun"):
            return None
        self.spaces()
        name = self.parse_name()
        if name is None:
            self.syntax_error("expected name")
        parentheses_line_pos, arguments = self.parse_function_declaration_arguments()
        if arguments is None:
            self.syntax_error("expected '('")
        self.spaces()
        arrow_line_pos = self.context.line, self.context.pos
        if not self.parse_string("->"):
            return_type: Optional[Type] = Void()
        else:
            self.spaces()
            return_type = self.parse_type()
        if return_type is None:
            self.syntax_error("expected type")
        return FunctionPrototypeDeclaration(
            fun_keyword, name, parentheses_line_pos, arguments, arrow_line_pos, return_type)

    def parse_function_declaration(self) -> Optional[FunctionDeclaration]:
        prototype = self.parse_function_prototype_declaration()
        if prototype is None:
            return None
        if not self.parse_string(":"):
            return FunctionDeclaration(
                prototype.fun_keyword, prototype.name, prototype.parentheses_line_pos, prototype.arguments,
                prototype.arrow_line_pos, prototype.return_type, [])
        body = self.parse_function_body()
        if not body:
            self.syntax_error("expected at least 1 indented statement")
        return FunctionDeclaration(
            prototype.fun_keyword, prototype.name, prototype.parentheses_line_pos, prototype.arguments,
            prototype.arrow_line_pos, prototype.return_type, body)

    def parse_return_statement(self) -> Optional[Return]:
        line_pos = self.context.line, self.context.pos
        if not self.parse_keyword("return"):
            return None
        self.spaces()
        expression = self.parse_expression()
        if expression is None:
            self.syntax_error("expected expression")
        return Return(line_pos, expression)

    def parse_reassignment_or_call(self) -> Optional[Union[Reassignment, Call]]:
        expression = self.parse_expression()
        if expression is None:
            return None
        elif isinstance(expression, Call):
            return expression
        self.spaces()
        operator_line_pos = self.context.line, self.context.pos
        if not self.parse_string("="):
            self.syntax_error("expected '='")
        self.spaces()
        right_expression = self.parse_expression()
        return Reassignment(expression, operator_line_pos, "=", right_expression)

    # Secondary parser methods
    def parse_annotations(self) -> List[Annotation]:
        result = []
        annotation = self.parse_annotation()
        while annotation is not None:
            result.append(annotation)
            self.spaces()
            annotation = self.parse_annotation()
        self.spaces()
        return result

    def parse_annotation(self) -> Optional[Annotation]:
        at_sign = self.context.line, self.context.pos
        if not self.parse_string("@"):
            return None
        name = self.parse_name()
        if name is None:
            self.syntax_error("expected name")
        parentheses_line_pos, arguments = self.parse_annotation_arguments()
        if arguments is None:
            return Annotation(at_sign, name, None, [])
        return Annotation(at_sign, name, parentheses_line_pos, arguments)

    def parse_function_declaration_argument(self) -> Optional[ArgumentDeclaration]:
        outer_name = self.parse_name()
        if outer_name is None:
            return None
        self.spaces()
        inner_name = self.parse_name()
        if inner_name is None:
            inner_name = outer_name
        self.spaces()
        colon = (self.context.line, self.context.pos)
        if not self.parse_string(":"):
            self.syntax_error("expected ':'")
        self.spaces()
        type_ = self.parse_type()
        if type_ is None:
            self.syntax_error("expected type")
        self.spaces()
        eq_sign: Optional[Tuple[int, int]] = (self.context.line, self.context.pos)
        if self.parse_string("="):
            self.spaces()
            default_expression = self.parse_expression()
        else:
            eq_sign = None
            default_expression = None
        return ArgumentDeclaration(outer_name, inner_name, colon, type_, eq_sign, default_expression)

    def parse_parameter_declaration(self) -> Optional[ParameterDeclaration]:
        outer_name = self.parse_name()
        if outer_name is None:
            return None
        inner_name = outer_name
        if self.parse_string(" "):
            self.spaces()
            _inner_name = self.parse_name()
            if _inner_name is None:
                self.syntax_error("expected inner name")
            inner_name = _inner_name
        if self.parse_string(":"):
            self.spaces()
            type_ = self.parse_type()
            if type_ is None:
                self.syntax_error("expected type")
            return ParameterDeclaration(outer_name, inner_name, type_)
        return ParameterDeclaration(outer_name, inner_name)

    def parse_type(self, named_parameters_allowed: bool = False) -> Optional[Type]:
        result = self.parse_type_atom(named_parameters_allowed)
        if result is None:
            return None
        parentheses_line_pos, parameters = self.parse_type_parameters()
        if parameters is None or parentheses_line_pos is None:
            return result
        if not parameters:
            self.syntax_error("expected parameters")
        assert(isinstance(result, Name))
        return ParameterizedType(result, parentheses_line_pos, parameters)

    def parse_type_atom(self, named_parameters_allowed: bool = False) -> Optional[Type]:
        funcs = [self.parse_named_parameter_or_name if named_parameters_allowed else self.parse_name]
        for func in funcs:
            result = func()
            if result is not None:
                return result
        return None

    def parse_named_parameter_or_name(self) -> Optional[Union[NamedParameter, Name]]:
        name = self.parse_name()
        if name is None:
            return None
        if self.parse_string(":"):
            self.spaces()
            type_ = self.parse_type()
            if type_ is None:
                self.syntax_error("expected type")
            return NamedParameter(name, type_)
        return name

    def parse_name(self) -> Optional[Name]:
        line_pos = self.context.line, self.context.pos
        module = self.parse_subname()
        if module is None:
            return None
        if self.parse_string("#"):
            name = self.parse_subname()
            if name is None:
                self.syntax_error("expected module member")
            return Name(line_pos, name, without_mangling=name, module=module)
        return Name(line_pos, name=module, without_mangling=module, module=None)

    def parse_named_argument_or_name(self) -> Optional[Union[NamedArgument, Name]]:
        name = self.parse_name()
        if name is None:
            return None
        if name.module is None and self.parse_string(":"):
            self.spaces()
            expression = self.parse_expression()
            if expression is None:
                self.syntax_error("expected expression")
            return NamedArgument(name, expression)
        return name

    def parse_string_literal(self) -> Optional[StringLiteral]:
        line_pos = self.context.line, self.context.pos
        if not self.parse_string('"'):
            return None
        chars_passed = 0
        end_seen = False
        literal = []
        prev_char = ""
        for char in self.code:
            chars_passed += 1
            if char == '"' and prev_char != "\\":
                end_seen = True
                break
            literal.append(char)
            prev_char = char
        self.context.pos += chars_passed
        self.code = self.code[chars_passed:]
        if not end_seen:
            self.syntax_error("expected ending '\"'")
        return StringLiteral(line_pos, "".join(literal))

    def parse_integer_literal(self) -> Optional[IntLiteral]:
        line_pos = self.context.line, self.context.pos
        chars_passed = 0
        result = []
        for char in self.code:
            if not char.isdigit():
                break
            result.append(char)
            chars_passed += 1
        if not result:
            return None
        self.context.pos += chars_passed
        self.code = self.code[chars_passed:]
        res = "".join(result)
        return IntLiteral(line_pos, int(res), res)

    def parse_subname(self) -> Optional[str]:
        result = []
        chars_passed = 0
        is_first_char = True
        for char in self.code:
            if char.isalpha() or char == "_" or (char.isnumeric() and not is_first_char):
                result.append(char)
                chars_passed += 1
                is_first_char = False
            else:
                break
        if result:
            self.context.pos += chars_passed
            self.code = self.code[chars_passed:]
            return "".join(result)
        return None

    # Utility methods
    def next_nonspace_char_is(self, expected: str) -> bool:
        """'expected' must be of length 1."""
        for char in self.code:
            if not char.isspace():
                return char == expected
        return False

    def is_newline_and_indentation(self, string: str) -> bool:
        """If string starts with newlines and than contains only proper indentation it returns True."""
        if string.startswith("\n"):
            without_newlines = string.lstrip("\n")
            return without_newlines == (INDENTATION_UNIT * self.indentation_level)
        return False

    def spaces(self, return_prev_state: bool = False) -> Union[str, Tuple[str, int]]:
        """Parses possible whitespaces and comments and returns a string of newlines and spaces matched.

        If return_prev_state is True -> it returns previous code and line
        """
        result = []
        in_line_comment = False
        in_multiline_comment = False
        number_of_minuses = 0
        number_of_minuses_buffer = 0    # Only for multiline comments!
        add_to_buffer = False
        chars_passed = 0
        prev_line = self.context.line
        for char in self.code:
            if char == "\n":
                if not in_multiline_comment and in_line_comment:
                    number_of_minuses = 0
                if not in_multiline_comment and not in_line_comment and number_of_minuses != 0:
                    # -->
                    # <---
                    #    ^
                    # problem (number of minuses != 0)
                    self.context.pos -= 1
                    break
                self.context.line += 1
                self.context.pos = 0
                in_line_comment = False
                number_of_minuses_buffer = 0
                add_to_buffer = False
                result.append(char)
            elif char == "-":
                if add_to_buffer:
                    # In multiline comment and '<' was seen
                    number_of_minuses_buffer += 1
                    if number_of_minuses_buffer == number_of_minuses:
                        # Exiting multiline comment
                        in_multiline_comment = False
                        number_of_minuses = 0
                        number_of_minuses_buffer = 0
                        add_to_buffer = False
                elif not in_multiline_comment:
                    number_of_minuses += 1
                    if number_of_minuses == 2:
                        in_line_comment = True
                        chars_passed += 1
                        self.context.pos += 1
                        continue
            elif char == ">" and in_line_comment and not in_multiline_comment and number_of_minuses != 0:
                # Starting multiline comment
                add_to_buffer = False
                in_multiline_comment = True
            elif char == "<" and in_multiline_comment:
                # Starting to count following dashes
                add_to_buffer = True
            elif not char.isspace():
                if not in_multiline_comment and in_line_comment:
                    number_of_minuses = 0
                if not in_line_comment and not in_multiline_comment:
                    self.context.pos -= number_of_minuses
                    chars_passed -= number_of_minuses
                    break
                add_to_buffer = False
            elif char == " ":
                if not in_multiline_comment and in_line_comment:
                    number_of_minuses = 0
                if not in_multiline_comment and not in_line_comment and number_of_minuses != 0:
                    self.context.pos -= number_of_minuses
                    chars_passed -= number_of_minuses
                    break
                result.append(char)
            chars_passed += 1
            self.context.pos += 1
        prev_code = self.code
        self.code = self.code[chars_passed:]
        if return_prev_state:
            return prev_code, prev_line
        return "".join(result)

    def parse_string(self, s: str) -> bool:
        chars_passed = 0
        for got, expected in zip_longest(self.code, s):
            if expected is None:
                break
            if got != expected:
                return False
            chars_passed += 1
        self.context.pos += chars_passed
        self.code = self.code[chars_passed:]
        return True

    def parse_keyword(self, keyword: str) -> bool:
        return self.parse_string(keyword) and (not self.code or self.code[0].isspace() or self.code[0] == ":")

    def parse_trailer(self) -> Optional[Trailer]:
        dot_line_pos = self.context.line, self.context.pos
        if self.parse_string("."):
            name = self.parse_subname()
            if name is None:
                return None
            return TrailerMember(dot_line_pos, name)
        else:
            parentheses_line_pos, arguments = self.parse_call_arguments()
            if arguments is None:
                return None
            return TrailerCall(parentheses_line_pos, arguments)

    def syntax_error(self, message: str) -> NoReturn:
        """Just an interface to a syntax_error function."""
        syntax_error(self.context.line, self.context.pos, self.context.module, message, self.context.code.splitlines())

    # Maker functions
    def _make_expression_parser(self, *atom_parsers):
        def parse_atom():
            for func in atom_parsers:
                result = func()
                if result is not None:
                    return result
            return None

        def parse_atom_expression():
            result = parse_atom()
            if result is None:
                return None
            trailer = self.parse_trailer()
            while trailer is not None:
                if isinstance(trailer, TrailerCall):
                    result = Call(result, trailer.parentheses_line_pos, trailer.arguments)
                elif isinstance(trailer, TrailerMember):
                    if isinstance(result, Member):
                        result.members.append(trailer.member)
                    else:
                        result = Member(result, [trailer.member])
                else:
                    internal_no_proper_case_error(self.context, parse_atom_expression, type(trailer))
                trailer = self.parse_trailer()
            return result

        def parse_expression():
            return parse_atom_expression()
        return parse_expression

    def _make_arguments_parser(self, argument_parser_func, possibly_without_parentheses=False):
        def helper():
            arguments: List[Expression] = []
            argument = argument_parser_func()
            while argument is not None:
                arguments.append(argument)
                if self.parse_string(","):
                    self.spaces()
                    argument = argument_parser_func()
                elif self.next_nonspace_char_is(")"):
                    break
                else:
                    if possibly_without_parentheses:
                        break
                    self.syntax_error("expected ',' or ')'")
            return arguments

        def parser():
            start_paren = self.context.line, self.context.pos
            if not self.parse_string("(") and not possibly_without_parentheses:
                return None, None
            self.spaces()
            arguments = helper()
            self.spaces()
            end_paren = self.context.line, self.context.pos
            if not self.parse_string(")") and not possibly_without_parentheses:
                self.syntax_error("expected ')'")
            if possibly_without_parentheses:
                return arguments
            return (start_paren, end_paren), arguments
        return parser

    def _make_body_parser(self, *available_statements_parser_functions):
        def statement_parser() -> Optional[Statement]:
            for func in available_statements_parser_functions:
                result = func()
                if result is not None:
                    return result
            return None

        def body_parser() -> List[Statement]:
            spaces = self.spaces()
            body: List[Statement] = []
            self.indentation_level += 1
            while self.is_newline_and_indentation(spaces):
                statement = statement_parser()
                if statement is None:
                    self.cached_indentation = spaces
                    self.indentation_level -= 1
                    return body
                body.append(statement)
                spaces = self.cached_indentation
                if spaces is None:
                    spaces = self.spaces()
            self.cached_indentation = spaces
            self.indentation_level -= 1
            return body
        return body_parser


text:
/* eslint-disable max-statements, complexity */
import fs from 'fs'
import os from 'os'
import path from 'path'
import fse from 'fs-extra'
import pFilter from 'p-filter'
import resolveFrom from 'resolve-from'
import deburr from 'lodash/deburr'
import noop from 'lodash/noop'
import {loadJson} from '@sanity/util/lib/safeJson'
import {reduceConfig} from '@sanity/util'
import debug from '../../debug'
import clientWrapper from '../../util/clientWrapper'
import getUserConfig from '../../util/getUserConfig'
import getProjectDefaults from '../../util/getProjectDefaults'
import createProject from '../project/createProject'
import login from '../login/login'
import dynamicRequire from '../../util/dynamicRequire'
import {prefixCommand} from '../../util/isNpx'
import promptForDatasetName from './promptForDatasetName'
import bootstrapTemplate from './bootstrapTemplate'
import templates from './templates'

/* eslint-disable no-process-env */
const commandPrefix = prefixCommand()
const isCI = process.env.CI
const sanityEnv = process.env.SANITY_INTERNAL_ENV
const environment = sanityEnv ? sanityEnv : process.env.NODE_ENV
/* eslint-enable no-process-env */

export default async function initSanity(args, context) {
  const {output, prompt, workDir, apiClient, yarn, chalk} = context
  const cliFlags = args.extOptions
  const unattended = cliFlags.y || cliFlags.yes
  const print = unattended ? noop : output.print
  const specifiedOutputPath = cliFlags['output-path']
  const intendedPlan = cliFlags['project-plan']
  const intendedCoupon = cliFlags.coupon
  let selectedPlan
  let reconfigure = cliFlags.reconfigure
  let defaultConfig = cliFlags['dataset-default']
  let showDefaultConfigPrompt = !defaultConfig

  // Only allow either --project-plan or --coupon
  if (intendedCoupon && intendedPlan) {
    throw new Error(
      'Error! --project-plan and --coupon cannot be used together; please select only one flag'
    )
  }

  // Don't allow --coupon and --project
  if (intendedCoupon && cliFlags.project) {
    throw new Error(
      'Error! --project and --coupon cannot be used together; coupons can only be applied to new projects'
    )
  }

  if (intendedCoupon) {
    try {
      selectedPlan = await getPlanFromCoupon(apiClient, intendedCoupon)
      print(`Coupon "${intendedCoupon}" validated!\n`)
    } catch (err) {
      throw new Error(`Unable to validate coupon code "${intendedCoupon}":\n\n${err.message}`)
    }
  } else if (intendedPlan) {
    selectedPlan = intendedPlan
  }

  // Check if we have a project manifest already
  const manifestPath = path.join(workDir, 'sanity.json')
  let inProjectContext = false
  let projectManifest
  try {
    projectManifest = await fse.readJson(manifestPath)
    inProjectContext = Boolean(projectManifest.root)
  } catch (err) {
    // Intentional noop
  }

  const toDifferentPath = specifiedOutputPath && absolutify(specifiedOutputPath) !== workDir

  // If explicitly reconfiguring, make sure we have something to reconfigure
  if (reconfigure && !inProjectContext) {
    throw new Error(
      projectManifest
        ? 'Reconfigure flag passed, but no `sanity.json` found'
        : 'Reconfigure flag passed, but `sanity.json` does not have "root" property set'
    )
  }

  // If we are in a Sanity studio project folder and the project manifest has projectId/dataset,
  // ASK if we want to reconfigure. If no projectId/dataset is present, we assume reconfigure
  const hasProjectId = projectManifest && projectManifest.api && projectManifest.api.projectId
  if (!toDifferentPath && hasProjectId && !reconfigure) {
    reconfigure = await promptImplicitReconfigure(prompt)
    if (!reconfigure) {
      print(
        'Init cancelled. If you want to create a new project, try running `sanity init` in an empty folder'
      )
      return
    }
  } else if (!toDifferentPath) {
    reconfigure = inProjectContext
  }

  if (reconfigure) {
    print(`The Sanity Studio in this folder will be tied to a new project on Sanity.io!`)
    if (hasProjectId) {
      print('The previous project configuration will be overwritten.')
    }
    print(`We're first going to make sure you have an account with Sanity.io. Hang on.`)
    print('Press ctrl + C at any time to quit.\n')
  } else {
    print(`You're setting up a Sanity.io project!`)
    print(`We'll make sure you're logged in with Sanity.io.`)
    print(`Then, we'll install a Sanity Studio for your project.\n`)
    print('Press ctrl + C at any time to quit.\n')
  }

  // If the user isn't already authenticated, make it so
  const userConfig = getUserConfig()
  const hasToken = userConfig.get('authToken')

  debug(hasToken ? 'User already has a token' : 'User has no token')

  if (hasToken) {
    print('Looks like you already have a Sanity-account. Sweet!\n')
  } else if (!unattended) {
    await getOrCreateUser()
  }

  const flags = await prepareFlags(cliFlags)

  // We're authenticated, now lets select or create a project
  debug('Prompting user to select or create a project')
  const {projectId, displayName, isFirstProject} = await getOrCreateProject()
  const sluggedName = deburr(displayName.toLowerCase())
    .replace(/\s+/g, '-')
    .replace(/[^a-z0-9-]/g, '')

  debug(`Project with name ${displayName} selected`)

  // Now let's pick or create a dataset
  debug('Prompting user to select or create a dataset')
  const {datasetName} = await getOrCreateDataset(
    {
      projectId,
      displayName,
      dataset: flags.dataset,
      aclMode: flags.visibility,
      defaultConfig: flags['dataset-default'],
    },
    context
  )

  debug(`Dataset with name ${datasetName} selected`)

  let outputPath = workDir
  let successMessage
  let defaults
  let importCmd = ''
  let shouldPrintImportCommand = false

  if (reconfigure) {
    // Rewrite project manifest (sanity.json)
    const projectInfo = projectManifest.project || {}
    const newProps = {
      root: true,
      api: {
        ...(projectManifest.api || {}),
        projectId,
        dataset: datasetName,
      },
      project: {
        ...projectInfo,
        // Keep original name if present
        name: projectInfo.name || displayName,
      },
    }

    // Ensure root, api and project keys are at top to follow sanity.json key order convention
    projectManifest = {
      ...newProps,
      ...projectManifest,
      ...newProps,
    }

    await fse.outputJSON(manifestPath, projectManifest, {spaces: 2})

    const hasNodeModules = await fse.pathExists(path.join(workDir, 'node_modules'))
    if (hasNodeModules) {
      print('Skipping installation of dependencies since node_modules exists.')
      print(`Run ${commandPrefix} install to reinstall dependencies`)
    } else {
      try {
        await yarn(['install'], {...output, rootDir: workDir})
      } catch (err) {
        throw err
      }
    }
  } else {
    // Gather project defaults based on environment
    defaults = await getProjectDefaults(workDir, {isPlugin: false, context})

    // Prompt the user for required information
    const answers = await getProjectInfo()

    // Ensure we are using the output path provided by user
    outputPath = answers.outputPath || workDir

    // Prompt for template to use
    const templateName = await selectProjectTemplate()

    // Build a full set of resolved options
    const initOptions = {
      template: templateName,
      outputDir: outputPath,
      name: sluggedName,
      displayName: displayName,
      dataset: datasetName,
      projectId: projectId,
      ...answers,
    }

    const template = templates[templateName]
    if (!template) {
      throw new Error(`Template "${templateName}" not found`)
    }

    // If the template has a sample dataset, prompt the user whether or not we should import it
    const shouldImport =
      !unattended && template.datasetUrl && (await promptForDatasetImport(template.importPrompt))

    // Bootstrap Sanity, creating required project files, manifests etc
    await bootstrapTemplate(initOptions, context)

    // Now for the slow part... installing dependencies
    try {
      await yarn(['install'], {...output, rootDir: outputPath})
    } catch (err) {
      throw err
    }

    // Make sure we have the required configs
    const corePath = resolveFrom.silent(outputPath, '@sanity/core')

    debug('@sanity/core path resolved to %s', corePath || 'null')
    debug('(from %s)', outputPath)

    let coreCommands
    try {
      const coreModule = corePath && dynamicRequire(corePath)
      coreCommands = coreModule && coreModule.commands
    } catch (err) {
      debug(`Failed to require '@sanity/core': ${err instanceof Error ? err.message : err}`)
    }

    if (Array.isArray(coreCommands)) {
      const configCheckCmd = coreCommands.find((cmd) => cmd.name === 'configcheck')
      await configCheckCmd.action(
        {extOptions: {quiet: true}},
        Object.assign({}, context, {
          workDir: outputPath,
        })
      )

      // Prompt for dataset import (if a dataset is defined)
      if (shouldImport) {
        await doDatasetImport({
          outputPath,
          coreCommands,
          template,
          datasetName,
          context,
        })

        print('')
        print('If you want to delete the imported data, use')
        print(`\t${chalk.cyan(`${commandPrefix} dataset delete ${datasetName}`)}`)
        print('and create a new clean dataset with')
        print(`\t${chalk.cyan(`${commandPrefix} dataset create <name>`)}\n`)
      }
    } else {
      debug('Skipping configcheck since `@sanity/core` could not be found')
      shouldPrintImportCommand = shouldImport
      importCmd = `${commandPrefix} dataset import ${template.datasetUrl} ${datasetName}`
    }

    // See if the template has a success message handler and print it
    successMessage = template.getSuccessMessage
      ? template.getSuccessMessage(initOptions, context)
      : ''
  }

  const isCurrentDir = outputPath === process.cwd()
  if (isCurrentDir && shouldPrintImportCommand) {
    print(`\n${chalk.green('Success!')} Now, use these commands to continue:\n`)
    print(`First: ${chalk.cyan(importCmd)} - to import the sample data`)
    print(`Then:  ${chalk.cyan(`${commandPrefix} start`)} - to run Sanity Studio\n`)
  } else if (isCurrentDir) {
    print(`\n${chalk.green('Success!')} Now, use this command to continue:\n`)
    print(`${chalk.cyan(`${commandPrefix} start`)} - to run Sanity Studio\n`)
  } else if (shouldPrintImportCommand) {
    print(`\n${chalk.green('Success!')} Now, use these commands to continue:\n`)
    print(`First: ${chalk.cyan(`cd ${outputPath}`)} - to enter project's directory`)
    print(`Then:  ${chalk.cyan(importCmd)}`)
    print(`       (to import the sample data)`)
    print(`Lastly: ${chalk.cyan(`${commandPrefix} start`)} - to run Sanity Studio\n`)
  } else {
    print(`\n${chalk.green('Success!')} Now, use these commands to continue:\n`)
    print(`First: ${chalk.cyan(`cd ${outputPath}`)} - to enter project's directory`)
    print(`Then:  ${chalk.cyan(`${commandPrefix} start`)} - to run Sanity Studio\n`)
  }

  print(`Other helpful commands`)
  print(`${commandPrefix} docs - to open the documentation in a browser`)
  print(`${commandPrefix} manage - to open the project settings in a browser`)
  print(`${commandPrefix} help - to explore the CLI manual`)

  if (successMessage) {
    print(`\n${successMessage}`)
  }

  const sendInvite =
    isFirstProject &&
    (await prompt.single({
      type: 'confirm',
      message:
        'We have an excellent developer community, would you like us to send you an invitation to join?',
      default: true,
    }))

  if (sendInvite) {
    apiClient({requireProject: false})
      .request({
        uri: '/invitations/community',
        method: 'POST',
      })
      .catch(noop)
  }

  async function getOrCreateUser() {
    print(`We can't find any auth credentials in your Sanity config`)
    print('- log in or create a new account\n')

    // Provide login options (`sanity login`)
    await login(args, context)

    print("Good stuff, you're now authenticated. You'll need a project to keep your")
    print('datasets and collaborators safe and snug.')
  }

  async function getOrCreateProject() {
    let projects
    let organizations
    try {
      const client = apiClient({requireUser: true, requireProject: false})
      const [allProjects, allOrgs] = await Promise.all([
        client.projects.list(),
        client.request({uri: '/organizations'}),
      ])
      projects = allProjects
      organizations = allOrgs
    } catch (err) {
      if (unattended) {
        return {projectId: flags.project, displayName: 'Unknown project', isFirstProject: false}
      }

      throw new Error(`Failed to communicate with the Sanity API:\n${err.message}`)
    }

    if (projects.length === 0 && unattended) {
      throw new Error('No projects found for current user')
    }

    if (flags.project) {
      const project = projects.find((proj) => proj.id === flags.project)
      if (!project && !unattended) {
        throw new Error(
          `Given project ID (${flags.project}) not found, or you do not have access to it`
        )
      }

      return {
        projectId: flags.project,
        displayName: project ? project.displayName : 'Unknown project',
        isFirstProject: false,
      }
    }

    if (flags.organization) {
      const organization =
        organizations.find((org) => org.id === flags.organization) ||
        organizations.find((org) => org.slug === flags.organization)

      if (!organization) {
        throw new Error(
          `Given organization ID (${flags.organization}) not found, or you do not have access to it`
        )
      }

      if (!(await hasProjectAttachGrant(flags.organization))) {
        throw new Error(
          'You lack the necessary permissions to attach a project to this organization'
        )
      }
    }

    // If the user has no projects or is using a coupon (which can only be applied to new projects)
    // just ask for project details instead of showing a list of projects
    const isUsersFirstProject = projects.length === 0
    if (isUsersFirstProject || intendedCoupon) {
      debug(
        isUsersFirstProject
          ? 'No projects found for user, prompting for name'
          : 'Using a coupon - skipping project selection'
      )

      const projectName = await prompt.single({message: 'Project name:'})
      return createProject(apiClient, {
        displayName: projectName,
        organizationId: await getOrganizationId(organizations),
        subscription: {planId: selectedPlan},
        metadata: {coupon: intendedCoupon},
      }).then((response) => ({
        ...response,
        isFirstProject: isUsersFirstProject,
      }))
    }

    debug(`User has ${projects.length} project(s) already, showing list of choices`)

    const projectChoices = projects.map((project) => ({
      value: project.id,
      name: `${project.displayName} [${project.id}]`,
    }))

    const selected = await prompt.single({
      message: 'Select project to use',
      type: 'list',
      choices: [
        {value: 'new', name: 'Create new project'},
        new prompt.Separator(),
        ...projectChoices,
      ],
    })

    if (selected === 'new') {
      debug('User wants to create a new project, prompting for name')
      return createProject(apiClient, {
        displayName: await prompt.single({
          message: 'Your project name:',
          default: 'My Sanity Project',
        }),
        organizationId: await getOrganizationId(organizations),
        subscription: {planId: selectedPlan},
        metadata: {coupon: intendedCoupon},
      }).then((response) => ({
        ...response,
        isFirstProject: isUsersFirstProject,
      }))
    }

    debug(`Returning selected project (${selected})`)
    return {
      projectId: selected,
      displayName: projects.find((proj) => proj.id === selected).displayName,
      isFirstProject: isUsersFirstProject,
    }
  }

  async function getOrCreateDataset(opts) {
    if (opts.dataset && isCI) {
      return {datasetName: opts.dataset}
    }

    const client = apiClient({api: {projectId: opts.projectId}})
    const [datasets, projectFeatures] = await Promise.all([
      client.datasets.list(),
      client.request({uri: '/features'}),
    ])

    const privateDatasetsAllowed = projectFeatures.includes('privateDataset')
    const allowedModes = privateDatasetsAllowed ? ['public', 'private'] : ['public']

    if (opts.aclMode && !allowedModes.includes(opts.aclMode)) {
      throw new Error(`Visibility mode "${opts.aclMode}" not allowed`)
    }

    // Getter in order to present prompts in a more logical order
    const getAclMode = () => {
      if (opts.aclMode) {
        return opts.aclMode
      }

      if (unattended || !privateDatasetsAllowed || defaultConfig) {
        return 'public'
      } else if (privateDatasetsAllowed) {
        return promptForAclMode(prompt, output)
      }

      return opts.aclMode
    }

    if (opts.dataset) {
      debug('User has specified dataset through a flag (%s)', opts.dataset)
      const existing = datasets.find((ds) => ds.name === opts.dataset)

      if (!existing) {
        debug('Specified dataset not found, creating it')
        const aclMode = await getAclMode()
        const spinner = context.output.spinner('Creating dataset').start()
        await client.datasets.create(opts.dataset, {aclMode})
        spinner.succeed()
      }

      return {datasetName: opts.dataset}
    }

    const datasetInfo =
      'Your content will be stored in a dataset that can be public or private, depending on\nwhether you want to query your content with or without authentication.\nThe default dataset configuration has a public dataset named "production".'

    if (datasets.length === 0) {
      debug('No datasets found for project, prompting for name')
      if (showDefaultConfigPrompt) {
        output.print(datasetInfo)
        defaultConfig = await promptForDefaultConfig(prompt)
      }
      const name = defaultConfig
        ? 'production'
        : await promptForDatasetName(prompt, {
            message: 'Name of your first dataset:',
          })
      const aclMode = await getAclMode()
      const spinner = context.output.spinner('Creating dataset').start()
      await client.datasets.create(name, {aclMode})
      spinner.succeed()
      return {datasetName: name}
    }

    debug(`User has ${datasets.length} dataset(s) already, showing list of choices`)
    const datasetChoices = datasets.map((dataset) => ({value: dataset.name}))

    const selected = await prompt.single({
      message: 'Select dataset to use',
      type: 'list',
      choices: [
        {value: 'new', name: 'Create new dataset'},
        new prompt.Separator(),
        ...datasetChoices,
      ],
    })

    if (selected === 'new') {
      const existingDatasetNames = datasets.map((ds) => ds.name)
      debug('User wants to create a new dataset, prompting for name')
      if (showDefaultConfigPrompt && !existingDatasetNames.includes('production')) {
        output.print(datasetInfo)
        defaultConfig = await promptForDefaultConfig(prompt)
      }

      const newDatasetName = defaultConfig
        ? 'production'
        : await promptForDatasetName(
            prompt,
            {
              message: 'Dataset name:',
            },
            existingDatasetNames
          )
      const aclMode = await getAclMode()
      const spinner = context.output.spinner('Creating dataset').start()
      await client.datasets.create(newDatasetName, {aclMode})
      spinner.succeed()
      return {datasetName: newDatasetName}
    }

    debug(`Returning selected dataset (${selected})`)
    return {datasetName: selected}
  }

  function promptForDatasetImport(message) {
    return prompt.single({
      type: 'confirm',
      message: message || 'This template includes a sample dataset, would you like to use it?',
      default: true,
    })
  }

  function selectProjectTemplate() {
    const defaultTemplate = unattended || flags.template ? flags.template || 'clean' : null
    if (defaultTemplate) {
      return defaultTemplate
    }

    return prompt.single({
      message: 'Select project template',
      type: 'list',
      choices: [
        {
          value: 'moviedb',
          name: 'Movie project (schema + sample data)',
        },
        {
          value: 'ecommerce',
          name: 'E-commerce (schema + sample data)',
        },
        {
          value: 'blog',
          name: 'Blog (schema)',
        },
        {
          value: 'clean',
          name: 'Clean project with no predefined schemas',
        },
      ],
    })
  }

  async function getProjectInfo() {
    const specifiedPath = flags['output-path'] && path.resolve(flags['output-path'])

    if (unattended) {
      return Object.assign({license: 'UNLICENSED'}, defaults, {
        outputPath: specifiedPath,
      })
    }

    const workDirIsEmpty = (await fse.readdir(workDir)).length === 0
    return {
      description: defaults.description,
      gitRemote: defaults.gitRemote,
      author: defaults.author,
      license: 'UNLICENSED',

      outputPath:
        specifiedPath ||
        (await prompt.single({
          type: 'input',
          message: 'Project output path:',
          default: workDirIsEmpty ? workDir : path.join(workDir, sluggedName),
          validate: validateEmptyPath,
          filter: absolutify,
        })),
    }
  }

  async function prepareFlags() {
    const createProjectName = cliFlags['create-project']
    if (cliFlags.dataset || cliFlags.visibility || cliFlags['dataset-default'] || unattended) {
      showDefaultConfigPrompt = false
    }

    if (cliFlags.project && createProjectName) {
      throw new Error(
        'Both `--project` and `--create-project` specified, only a single is supported'
      )
    }

    if (cliFlags.project && cliFlags.organization) {
      throw new Error(
        'You have specified both a project and an organization. To move a project to an organization please visit https://www.sanity.io/manage'
      )
    }

    if (createProjectName === true) {
      throw new Error('Please specify a project name (`--create-project <name>`)')
    }

    if (typeof createProjectName === 'string' && createProjectName.trim().length === 0) {
      throw new Error('Please specify a project name (`--create-project <name>`)')
    }

    if (unattended) {
      debug('Unattended mode, validating required options')
      const requiredForUnattended = ['dataset', 'output-path']
      requiredForUnattended.forEach((flag) => {
        if (!cliFlags[flag]) {
          throw new Error(`\`--${flag}\` must be specified in unattended mode`)
        }
      })

      if (!cliFlags.project && !createProjectName) {
        throw new Error(
          '`--project <id>` or `--create-project <name>` must be specified in unattended mode'
        )
      }
    }

    if (createProjectName) {
      debug('--create-project specified, creating a new project')
      const createdProject = await createProject(apiClient, {
        displayName: createProjectName.trim(),
        organizationId: cliFlags.organization || undefined,
        subscription: {planId: selectedPlan},
        metadata: {coupon: intendedCoupon},
      })
      debug('Project with ID %s created', createdProject.projectId)

      if (cliFlags.dataset) {
        debug('--dataset specified, creating dataset (%s)', cliFlags.dataset)
        const client = apiClient({api: {projectId: createdProject.projectId}})
        const spinner = context.output.spinner('Creating dataset').start()

        const createBody = cliFlags.visibility && {aclMode: cliFlags.visibility}
        await client.datasets.create(cliFlags.dataset, createBody)
        spinner.succeed()
      }

      const newFlags = Object.assign({}, cliFlags, {project: createdProject.projectId})
      delete newFlags['create-project']

      return newFlags
    }

    return cliFlags
  }

  async function getOrganizationId(organizations) {
    let organizationId = flags.organization
    if (unattended) {
      return organizationId || undefined
    }

    const shouldPrompt = organizations.length > 0 && !organizationId
    if (shouldPrompt) {
      debug(`User has ${organizations.length} organization(s), checking attach access`)
      const withGrant = await getOrganizationsWithAttachGrant(organizations)
      if (withGrant.length === 0) {
        debug('User lacks project attach grant in all organizations, not prompting')
        return undefined
      }

      debug('User has attach access to %d organizations, prompting.', withGrant.length)
      const organizationChoices = [
        {value: 'none', name: 'None'},
        new prompt.Separator(),
        ...withGrant.map((organization) => ({
          value: organization.id,
          name: `${organization.name} [${organization.id}]`,
        })),
      ]

      const chosenOrg = await prompt.single({
        message: 'Select organization to attach project to',
        type: 'list',
        choices: organizationChoices,
      })

      if (chosenOrg && chosenOrg !== 'none') {
        organizationId = chosenOrg
      }
    } else if (organizationId) {
      debug(`User has defined organization flag explicitly (%s)`, organizationId)
    } else if (organizations.length === 0) {
      debug('User has no organizations, skipping selection prompt')
    }

    return organizationId || undefined
  }

  async function hasProjectAttachGrant(organizationId) {
    const requiredGrantGroup = 'sanity.organization.projects'
    const requiredGrant = 'attach'

    const client = apiClient({requireProject: false, requireUser: true})
      .clone()
      .config({apiVersion: 'v2021-06-07'})

    const grants = await client.request({uri: `organizations/${organizationId}/grants`})
    const group = grants[requiredGrantGroup] || []
    return group.some(
      (resource) => resource.grants && resource.grants.some((grant) => grant.name === requiredGrant)
    )
  }

  function getOrganizationsWithAttachGrant(organizations) {
    return pFilter(organizations, (org) => hasProjectAttachGrant(org.id), {concurrency: 3})
  }
}

function promptForDefaultConfig(prompt) {
  return prompt.single({
    type: 'confirm',
    message: 'Use the default dataset configuration?',
    default: true,
  })
}

function promptImplicitReconfigure(prompt) {
  return prompt.single({
    type: 'confirm',
    message:
      'The current folder contains a configured Sanity studio. Would you like to reconfigure it?',
    default: true,
  })
}

function validateEmptyPath(dir) {
  const checkPath = absolutify(dir)
  return pathIsEmpty(checkPath) ? true : 'Given path is not empty'
}

function pathIsEmpty(dir) {
  // We are using fs instead of fs-extra because it silently, weirdly, crashes on windows
  try {
    // eslint-disable-next-line no-sync
    const content = fs.readdirSync(dir)
    return content.length === 0
  } catch (err) {
    if (err.code === 'ENOENT') {
      return true
    }

    throw err
  }
}

function expandHome(filePath) {
  if (filePath.charCodeAt(0) === 126 /* ~ */) {
    if (filePath.charCodeAt(1) === 43 /* + */) {
      return path.join(process.cwd(), filePath.slice(2))
    }

    const home = os.homedir()
    return home ? path.join(home, filePath.slice(1)) : filePath
  }

  return filePath
}

function absolutify(dir) {
  const pathName = expandHome(dir)
  return path.isAbsolute(pathName) ? pathName : path.resolve(process.cwd(), pathName)
}

async function promptForAclMode(prompt, output) {
  const mode = await prompt.single({
    type: 'list',
    message: 'Choose dataset visibility – this can be changed later',
    choices: [
      {
        value: 'public',
        name: 'Public (world readable)',
      },
      {
        value: 'private',
        name: 'Private (authenticated requests only)',
      },
    ],
  })

  if (mode === 'private') {
    output.print(
      'Please note that while documents are private, assets (files and images) are still public\n'
    )
  }

  return mode
}

async function doDatasetImport(options) {
  const {outputPath, coreCommands, template, datasetName, context} = options
  const manifestPath = path.join(outputPath, 'sanity.json')
  const baseManifest = await loadJson(manifestPath)
  const manifest = reduceConfig(baseManifest || {}, environment, {
    studioRootPath: outputPath,
  })

  const importCmd = coreCommands.find((cmd) => cmd.name === 'import' && cmd.group === 'dataset')
  return importCmd.action(
    {argsWithoutOptions: [template.datasetUrl, datasetName], extOptions: {}},
    Object.assign({}, context, {
      apiClient: clientWrapper(manifest, manifestPath),
      workDir: outputPath,
      fromInitCommand: true,
    })
  )
}

async function getPlanFromCoupon(apiClient, couponCode) {
  const response = await apiClient({
    requireUser: false,
    requireProject: false,
  }).request({
    method: 'GET',
    uri: `plans/coupon/${couponCode}`,
  })

  try {
    const planId = response[0].id
    if (!planId) {
      throw new Error('Unable to find a plan from coupon code')
    }
    return planId
  } catch (err) {
    throw err
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.badlogic.gdx.graphics.glutils;

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.utils.BufferUtils;

/**

 * Convenience class for working with OpenGL vertex arrays. It interleaves all data in the order you specified in the constructor
 * via {@link VertexAttribute}.
 *

 *
 *

 * This class does not support shaders and for that matter OpenGL ES 2.0. For this {@link VertexBufferObject}s are needed.
 *

 *
 * @author mzechner, Dave Clayton <contact@redskyforge.com> */
public class VertexArray implements VertexData {
	final VertexAttributes attributes;
	final FloatBuffer buffer;
	final ByteBuffer byteBuffer;
	boolean isBound = false;

	/** Constructs a new interleaved VertexArray
	 *
	 * @param numVertices the maximum number of vertices
	 * @param attributes the {@link VertexAttribute}s */
	public VertexArray (int numVertices, VertexAttribute... attributes) {
		this(numVertices, new VertexAttributes(attributes));
	}

	/** Constructs a new interleaved VertexArray
	 *
	 * @param numVertices the maximum number of vertices
	 * @param attributes the {@link VertexAttributes} */
	public VertexArray (int numVertices, VertexAttributes attributes) {
		this.attributes = attributes;
		byteBuffer = BufferUtils.newUnsafeByteBuffer(this.attributes.vertexSize * numVertices);
		buffer = byteBuffer.asFloatBuffer();
		buffer.flip();
		byteBuffer.flip();
	}

	@Override
	public void dispose () {
		BufferUtils.disposeUnsafeByteBuffer(byteBuffer);
	}

	@Override
	public FloatBuffer getBuffer () {
		return buffer;
	}

	@Override
	public int getNumVertices () {
		return buffer.limit() * 4 / attributes.vertexSize;
	}

	public int getNumMaxVertices () {
		return byteBuffer.capacity() / attributes.vertexSize;
	}

	@Override
	public void setVertices (float[] vertices, int offset, int count) {
		BufferUtils.copy(vertices, byteBuffer, count, offset);
		buffer.position(0);
		buffer.limit(count);
	}

	@Override
	public void updateVertices (int targetOffset, float[] vertices, int sourceOffset, int count) {
		final int pos = byteBuffer.position();
		byteBuffer.position(targetOffset * 4);
		BufferUtils.copy(vertices, sourceOffset, count, byteBuffer);
		byteBuffer.position(pos);
	}

	@Override
	public void bind (final ShaderProgram shader) {
		bind(shader, null);
	}

	@Override
	public void bind (final ShaderProgram shader, final int[] locations) {
		final GL20 gl = Gdx.gl20;
		final int numAttributes = attributes.size();
		byteBuffer.limit(buffer.limit() * 4);
		if (locations == null) {
			for (int i = 0; i < numAttributes; i++) {
				final VertexAttribute attribute = attributes.get(i);
				final int location = shader.getAttributeLocation(attribute.alias);
				if (location < 0) continue;
				shader.enableVertexAttribute(location);

				if (attribute.type == GL20.GL_FLOAT) {
					buffer.position(attribute.offset / 4);
					shader.setVertexAttribute(location, attribute.numComponents, attribute.type, attribute.normalized, attributes.vertexSize,
							buffer);
				} else {
					byteBuffer.position(attribute.offset);
					shader.setVertexAttribute(location, attribute.numComponents, attribute.type, attribute.normalized, attributes.vertexSize,
						byteBuffer);
				}
			}
		} else {
			for (int i = 0; i < numAttributes; i++) {
				final VertexAttribute attribute = attributes.get(i);
				final int location = locations[i];
				if (location < 0) continue;
				shader.enableVertexAttribute(location);

				if (attribute.type == GL20.GL_FLOAT) {
					buffer.position(attribute.offset / 4);
					shader.setVertexAttribute(location, attribute.numComponents, attribute.type, attribute.normalized, attributes.vertexSize,
							buffer);
				} else {
					byteBuffer.position(attribute.offset);
					shader.setVertexAttribute(location, attribute.numComponents, attribute.type, attribute.normalized, attributes.vertexSize,
						byteBuffer);
				}
			}
		}
		isBound = true;
	}

	/** Unbinds this VertexBufferObject.
	 *
	 * @param shader the shader */
	@Override
	public void unbind (ShaderProgram shader) {
		unbind(shader, null);
	}

	@Override
	public void unbind (ShaderProgram shader, int[] locations) {
		final GL20 gl = Gdx.gl20;
		final int numAttributes = attributes.size();
		if (locations == null) {
			for (int i = 0; i < numAttributes; i++) {
				shader.disableVertexAttribute(attributes.get(i).alias);
			}
		} else {
			for (int i = 0; i < numAttributes; i++) {
				final int location = locations[i];
				if (location >= 0) shader.disableVertexAttribute(location);
			}
		}
		isBound = false;
	}

	@Override
	public VertexAttributes getAttributes () {
		return attributes;
	}
}


text:
package Paws::ECS::KernelCapabilities;
  use Moose;
  has Add => (is => 'ro', isa => 'ArrayRef[Str|Undef]', request_name => 'add', traits => ['NameInRequest']);
  has Drop => (is => 'ro', isa => 'ArrayRef[Str|Undef]', request_name => 'drop', traits => ['NameInRequest']);
1;

### main pod documentation begin ###

=head1 NAME

Paws::ECS::KernelCapabilities

=head1 USAGE

This class represents one of two things:

=head3 Arguments in a call to a service

Use the attributes of this class as arguments to methods. You shouldn't make instances of this class.
Each attribute should be used as a named argument in the calls that expect this type of object.

As an example, if Att1 is expected to be a Paws::ECS::KernelCapabilities object:

  $service_obj->Method(Att1 => { Add => $value, ..., Drop => $value  });

=head3 Results returned from an API call

Use accessors for each attribute. If Att1 is expected to be an Paws::ECS::KernelCapabilities object:

  $result = $service_obj->Method(...);
  $result->Att1->Add

=head1 DESCRIPTION

The Linux capabilities for the container that are added to or dropped
from the default configuration provided by Docker. For more information
on the default capabilities and the non-default available capabilities,
see Runtime privilege and Linux capabilities in the I<Docker run
reference>. For more detailed information on these Linux capabilities,
see the capabilities(7) Linux manual page.

=head1 ATTRIBUTES

=head2 Add => ArrayRef[Str|Undef]

  The Linux capabilities for the container that have been added to the
default configuration provided by Docker. This parameter maps to
C<CapAdd> in the Create a container section of the Docker Remote API
and the C<--cap-add> option to docker run.

=head2 Drop => ArrayRef[Str|Undef]

  The Linux capabilities for the container that have been removed from
the default configuration provided by Docker. This parameter maps to
C<CapDrop> in the Create a container section of the Docker Remote API
and the C<--cap-drop> option to docker run.

=head1 SEE ALSO

This class forms part of L<Paws>, describing an object used in L<Paws::ECS>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
"""Tools for working with Levenshtein distance algorithm and distance ratio between strings.
"""

__author__ = ['Luke Hollis <lukehollis@gmail.com>', 'Eleftheria Chatziargyriou <ele.hatzy@gmail.com>']
__license__ = 'MIT License. See LICENSE.'

class Levenshtein:
    """A wrapper class for fuzzywuzzy's Levenshtein distance calculation methods."""

    def __init__(self):
        """Initialize class. Currently empty."""
        return

    @staticmethod
    def Levenshtein_Distance(w1, w2):
        """
        Computes Levenshtein Distance between two words

        Args:
            :param w1: str
            :param w2: str
            :return: int

        Examples:

            >>> Levenshtein.Levenshtein_Distance('noctis', 'noctem')
            2

            >>> Levenshtein.Levenshtein_Distance('nox', 'nochem')
            4

            >>> Levenshtein.Levenshtein_Distance('orbis', 'robis')
            2
        """
        m, n = len(w1), len(w2)
        v1 = [i for i in range(n + 1)]
        v2 = [0 for i in range(n + 1)]

        for i in range(m):
            v2[0] = i + 1

            for j in range(n):
                delCost = v1[j + 1] + 1
                insCost = v2[j] + 1

                subCost = v1[j]
                if w1[i] != w2[j]: subCost += 1

                v2[j + 1] = min(delCost, insCost, subCost)
            v1, v2 = v2, v1

        return v1[-1]

    @staticmethod
    def Damerau_Levenshtein_Distance(w1, w2):
        """
        Computes Damerau-Levenshtein Distance between two words

        Args:
            :param w1: str
            :param w2: str
            :return int:

        Examples:
            For the most part, Damerau-Levenshtein behaves
            identically to Levenshtein:

            >>> Levenshtein.Damerau_Levenshtein_Distance('noctis', 'noctem')
            2

            >>> Levenshtein.Levenshtein_Distance('nox', 'nochem')
            4

            The strength of DL lies in detecting transposition of characters:

            >>> Levenshtein.Damerau_Levenshtein_Distance('orbis', 'robis')
            1

        """
        # Define alphabet
        alph = sorted(list(set(w1 + w2)))
        # Calculate alphabet size
        alph_s = len(alph)
        dam_ar = [0 for _ in range(alph_s)]
        mat = [[0 for _ in range(len(w2) + 2)] for _ in range(len(w1) + 2)]

        max_dist = len(w1) + len(w2)
        mat[0][0] = max_dist

        # Initialize matrix margin to the maximum possible distance (essentially inf) for ease of calculations (avoiding try blocks)

        for i in range(1, len(w1) + 2):
            mat[i][0] = max_dist
            mat[i][1] = i - 1

        for i in range(1, len(w2) + 2):
            mat[0][i] = max_dist
            mat[1][i] = i - 1

        for i in range(2, len(w1) + 2):
            tem = 0

            for j in range(2, len(w2) + 2):

                k = dam_ar[alph.index(w2[j - 2])]
                l = tem

                if w1[i - 2] == w2[j - 2]:
                    cost = 0
                    tem = j
                else:
                    cost = 1

                # The reccurence relation of DL is identical to that of Levenshtein with the addition of transposition
                mat[i][j] = min(mat[i - 1][j - 1] + cost, mat[i][j - 1] + 1, mat[i - 1][j] + 1,
                                mat[k - 1][l - 1] + i + j - k - l - 1)

            dam_ar[alph.index(w1[i - 2])] = i

        return mat[-1][-1]

    @staticmethod
    def ratio(string_a, string_b):
        """At the most basic level, return a Levenshtein distance ratio via
        fuzzywuzzy.
        :param string_a: str
        :param string_b: str
        :return: float
        """
        from cltk.utils.cltk_logger import logger
        try:
            from fuzzywuzzy import fuzz

        except ImportError as imp_err:  # pragma: no cover
            message = "'fuzzywuzzy' library required for this module: %s. Install with `pip install fuzzywuzzy python-Levenshtein`" % imp_err
            logger.error(message)
            print(message)
            raise ImportError

        return fuzz.ratio(string_a, string_b) / 100


text:
package com.mmnaseri.utils.spring.data.repository;

import com.mmnaseri.utils.spring.data.domain.DataStoreAware;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.domain.Parameter;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataAware;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.domain.impl.SelectDataStoreOperation;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfigurationAware;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfigurationAware;
import com.mmnaseri.utils.spring.data.query.QueryDescriptor;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.tools.PropertyUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * @author Milad Naseri (m.m.naseri@gmail.com)
 * @since 1.0 (6/8/16, 11:57 AM)
 */
public class DefaultQueryByExampleExecutor
    implements DataStoreAware,
        RepositoryConfigurationAware,
        RepositoryMetadataAware,
        RepositoryFactoryConfigurationAware {

  private final ExampleMatcherQueryDescriptionExtractor queryDescriptionExtractor;
  private DataStore<Object, Object> dataStore;
  private RepositoryConfiguration repositoryConfiguration;
  private RepositoryMetadata repositoryMetadata;
  private RepositoryFactoryConfiguration configuration;

  public DefaultQueryByExampleExecutor() {
    queryDescriptionExtractor = new ExampleMatcherQueryDescriptionExtractor();
  }

  public Object findOne(Example example) {
    final Collection found = retrieveAll(example);
    if (found.isEmpty()) {
      return null;
    } else if (found.size() > 1) {
      throw new InvalidArgumentException(
          "Expected to see exactly one item found, but found "
              + found.size()
              + ". You should use a better example.");
    }
    return found.iterator().next();
  }

  public Iterable findAll(Example example) {
    return retrieveAll(example);
  }

  public Iterable findAll(Example example, Sort sort) {
    return PagingAndSortingUtils.sort(retrieveAll(example), sort);
  }

  public Page findAll(Example example, Pageable pageable) {
    return PagingAndSortingUtils.page(retrieveAll(example), pageable);
  }

  public long count(Example example) {
    return retrieveAll(example).size();
  }

  public boolean exists(Example example) {
    return count(example) > 0;
  }

  @Override
  public void setDataStore(DataStore dataStore) {
    //noinspection unchecked
    this.dataStore = dataStore;
  }

  @Override
  public void setRepositoryConfiguration(RepositoryConfiguration repositoryConfiguration) {
    this.repositoryConfiguration = repositoryConfiguration;
  }

  @Override
  public void setRepositoryMetadata(RepositoryMetadata repositoryMetadata) {
    this.repositoryMetadata = repositoryMetadata;
  }

  @Override
  public void setRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) {
    this.configuration = configuration;
  }

  /**
   * Retrieves all entities that match the given example
   *
   * @param example the example for finding the entities
   * @return a collection of matched entities
   */
  private Collection<?> retrieveAll(Example example) {
    final QueryDescriptor descriptor =
        queryDescriptionExtractor.extract(repositoryMetadata, configuration, example);
    final Invocation invocation = createInvocation(descriptor, example);
    final SelectDataStoreOperation<Object, Object> select =
        new SelectDataStoreOperation<>(descriptor);
    return select.execute(dataStore, repositoryConfiguration, invocation);
  }

  /**
   * This method will create an invocation that had it occurred on a query method would provide
   * sufficient data for a parsed query method expression to be evaluated
   *
   * @param descriptor the query descriptor
   * @param example the example that is used for evaluation
   * @return the fake method invocation corresponding to the example probe
   */
  private Invocation createInvocation(QueryDescriptor descriptor, Example example) {
    final List<Object> values = new ArrayList<>();
    // since according to
    // http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example
    // the matcher only supports AND condition, so, we expect to see only one branch
    final List<List<Parameter>> branches = descriptor.getBranches();
    final List<Parameter> parameters = branches.get(0);
    for (Parameter parameter : parameters) {
      final String propertyPath = parameter.getPath();
      final Object propertyValue = PropertyUtils.getPropertyValue(example.getProbe(), propertyPath);
      final ExampleMatcher.PropertySpecifier specifier =
          example.getMatcher().getPropertySpecifiers().getForPath(propertyPath);
      //noinspection ConstantConditions
      values.add(
          specifier == null
              ? propertyValue
              : specifier
                  .getPropertyValueTransformer()
                  .apply(Optional.ofNullable(propertyValue))
                  .orElse(null));
    }
    return new ImmutableInvocation(null, values.toArray());
  }
}


text:
/**
 * Event emitting
 * @namespace Event emitting
 * @requires tent
 * @requires tent.arrays
 * @name tent.events
 */
tent.declare('tent.events', function(){

    /**
     * Extends all argument objects as event emitters.
     * Adds all functions in {@link tent.events.extendFunctions}
     * @example
     *
     * 		var dog = { name: 'Bobby' }, cat = {name: 'Kitty'}, status;
     * 		tent.events.extend(dog);
     * 		dog.bind({bark: function(e, at) {
     * 			status = this.name+ ' barked at '+at.name;
     * 		});
     * 		dog.trigger('bark',cat);
     *
     * 		equals(status, "Bobby barked at Kitty", "bark event was handled");
     *
     */
    tent.events.extend = function(){
        for (var i = 0; i < arguments.length; i++) {
            var arg = arguments[i];
	        if (typeof arg == 'object' && !arg.__events__) {
				// add private event map
	            arg.__events__ = {};
				// add functions
	            for (fname in tent.events._extendFunctions){
					arg[fname]= tent.events.extendFunctions[fname];
				}
	        }
        }
        return arguments[0];
    }

    /**
     * Unextends event emitters.
     */
    tent.events.unextend = function(){
        for (var i = 0; i < arguments.length; i++) {
            var arg = arguments[i];
	        if (typeof arg == 'object' && arg.__events__) {
	            delete arg.__events__;
	            for (fname in tent.events._extendFunctions){
					delete arg[fname];
				}
	        }
        }
    }

	/**
	 * Functions added to event emitters (see {@link tent.events.extend})
	 * @name tent.events.extendFunctions
	 * @namespace Functions added to event emitters (see {@link tent.events.extend})
	 */
    tent.events.extendFunctions = {

		/**
		 * Binds functions to an event (or events)
		 *
		 * @example
		 *
		 * 		// bind by name
		 * 		obj.bind('click', function(e) {
		 * 			alert(this.id+' clicked at '+e.data.position);
		 * 		};
		 *
		 * 		// bind with a map
		 * 		obj.bind({
		 * 			activate: function(e) {
		 *				console.log('activated');
		 * 		}, desactivate: function(e) {
		 * 				console.log('deactivated');
		 * 		});
		 *
		 * 		// bind passing data
		 * 		obj.bind('load', { context: this.title }, function(e) {
		 * 			alert(e.data.context+' clicked at '+e.data.position);
		 * 		};
		 *
		 * @param {String} eventType
		 * @param {Object} [data] data to include in eventData, if an order field is included it's used to sort handler invocations
		 * @param {Object|function()} handler
		 * @return the context object (this) for chaining
		 */
        bind: function(eventType, data, handler){

            if (typeof eventType == 'object') {
                // first param is a hash of events and handlers
                for (var et in eventType) {
                    if (eventType.hasOwnProperty(et)) {
                        this.bind(et, eventType[et]);
                    }
                }
                return this;
            }

            if (typeof handler == 'undefined') {
                handler = data;
                data = null;
            }

            if (!handler) {
                throw 'a handler function or object is required';
            }
            if ((typeof handler != 'function') && (typeof handler.handle != 'function')) {
                throw 'handler must be function(data) or a handler object (with a "handle(sender,data)" function)';
            }

            var eventTypes = eventType.split(' ');
            var order = data ? (data.order || 0) : 0;
            for (var eti = 0; eti < eventTypes.length; eti++) {
                var evType = eventTypes[eti];
                if (evType) {
                    if (!this.__events__[evType]) {
                        this.__events__[evType] = {
                            handlers: []
                        };
                    }
                    var handlers = this.__events__[evType].handlers;
                    // find position to insert handler based on order
                    var position = handlers.length;
                    for (var hi = handlers.length - 1; hi >= 0; hi--) {
                        var h = handlers[hi];
                        if ((h.order || 0) <= order) {
                            position = hi + 1;
                            break;
                        }
                    };

                    handlers.splice(position, 0, {
                        order: order,
                        data: data,
                        handler: handler
                    });
                }
            }
            return this;
        },

        /**
         * Triggers an event notifying suscribers, aditional arguments are passed to handlers.
         * Propagation can be stopped calling by handlers using: e.stopImmediatePropagation();
         * @param {String} eventType an event type name
		 * @return the context object (this) for chaining
         */
        trigger: function(eventType){
            if (!this.__events__[eventType]) {
                return;
            }
            var handlers = this.__events__[eventType].handlers;

            var e = {
                target: this,
                type: eventType
            };

			/**
			 * @inner
			 */
			var stopProp = function(){
                this.immediatePropagationStopped = true;
            };
			e.stopImmediatePropagation = stopProp;

            var hargs = Array.prototype.slice.call(arguments, 1);
            hargs.unshift(e);

            for (var hi = 0, hl = handlers.length; hi < hl; hi++) {
                var h = handlers[hi];
                e.data = h.data;
                if (typeof h.handler == 'function') {
                    try {
                        e.result = h.handler.apply(this, hargs);
                    }
                    catch (err) {
                        console.error(err);
                    }
                }
                else
                    if (typeof h.handler.handle == 'function') {
                        try {
                            e.result = h.handler.handle.apply(h.handler, hargs);
                        }
                        catch (err) {
                            console.error(err);
                        }
                    }

                if (e.immediatePropagationStopped) {
                    break;
                }
            }
            return this;
        },

		/**
		 * Removes an event binding.
		 * If only event type is specified all binding to that type are remove.
		 * If only a handler is specified the handler is removed from all event types
		 * If both are specified the handler is removed from the specific event type
		 * @param {String} [eventType] event type name to unbind
		 * @param {Object|function()} [handler] a handler object or function to unbind
		 * @return the context object (this) for chaining
		 */
        unbind: function(eventType, handler){

            if (typeof handler == 'undefined' && typeof eventType == 'function') {
                handler = eventType;
                eventType = null;
            }

            if (typeof handler == 'undefined') {
                if (typeof eventType == 'undefined') {
                    this.__events__ = {};
                }
                else {
                    delete this.__events__[eventType];
                }
            }
            else {
                if (eventType) {
                    if (!this.__events__[eventType]) {
                        return;
                    }
                    var handlers = this.__events__[eventType].handlers;

                    for (var hi = handlers.length; hi >= 0; hi--) {
                        var h = handlers[hi];
                        if (h.handler === handler) {
                            handlers.splice(hi, 1);
                        }
                    }
                }
                else {
                    for (var et in this.__events__) {
                        var handlers = this.__events__[et].handlers;

                        for (var hi = handlers.length; hi >= 0; hi--) {
                            var h = handlers[hi];
                            if (h.handler === handler) {
                                handlers.splice(hi, 1);
                            }
                        }
                    }
                }
            }
            return this;
        }

    };

});


text:
cask 'preference-manager' do
  version '4.4.2.0'
  sha256 'b39ece3b79d5d72987abf0aa79b8d5fcb996dfd29dff6016f37c3529fd3ecefd'

  url "https://www.digitalrebellion.com/download/prefman?version=#{version.no_dots}"
  appcast 'https://www.digitalrebellion.com/rss/appcasts/pref_man.xml'
  name 'Preference Manager'
  homepage 'https://www.digitalrebellion.com/prefman/'

  app 'Preference Manager.app'
end


text:
'use strict'
function postRequest(url,params){
    var headers = new Headers({
        'content-type':'application/json;charset=utf-8'
    });
    var request = new Request(url,{
        method:'post',
        headers,
        body:params
    })
    return sendRequest(request);
}

function getRequest(url,params){

    var body = [];
    for(let o in params){
        body.push(o+'='+params[o]);
    }
    if(body.length){
        url+='?'+body.join('&')
    }
    var request = new Request(url,{
        method:'get',
    })
    return sendRequest(request);
}
function sendRequest(request){
    request.credentials =  'include';
    return fetch(request)
}
module.exports = {
    postRequest,
    getRequest
}


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

<!-- http://www.phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit
        backupGlobals="false"
        backupStaticAttributes="false"
        colors="true"
        convertErrorsToExceptions="true"
        convertNoticesToExceptions="true"
        convertWarningsToExceptions="true"
        processIsolation="false"
        stopOnFailure="false"
        syntaxCheck="false"
        bootstrap="tests/bootstrap.php">

    <testsuites>
        <testsuite name="unitary">
            <directory phpVersion="5.3.0" phpVersionOperator=">=">tests/Unitary</directory>
        </testsuite>
        <testsuite name="functional">
            <directory phpVersion="5.3.0" phpVersionOperator=">=">tests/Functional</directory>
            <exclude>tests/Functional/Data</exclude>
        </testsuite>
    </testsuites>

    <logging>
        <log type="junit" target="target/report/phpunit-junit.xml" logIncompleteSkipped="false"/>
        <log type="coverage-html" target="target/report/phpunit-coverage" lowUpperBound="35" highLowerBound="70"/>
    </logging>

    <filter><!-- for code coverage -->
        <whitelist>
            <directory>src</directory>
        </whitelist>
    </filter>
</phpunit>


text:
<?php

namespace DataBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use DataBundle\Form\MediaType;

class customUploadBandType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('name', 'text', [
                    // readonly if we're in edit mode
                    'disabled' => $options['is_edit'],
                    'data_class' => null
                ])
                ->add('genre', 'text', array('data_class' => null))
                ->add('image', new MediaType(), array())
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => null,
            'is_edit' => true,
        ));

        /**
         * @return string
         */
    }

    public function getName()
    {
        return 'mk_musicbundle_band_edit';
    }

}


text:
title: Not much and none
meaning: Explaining that something is sufficient in supply e.g. money
---


text:
<?php

namespace Anax\Users;

/**
 * Model for Users
 *
 */
class User extends \Anax\MVC\CDatabaseModel
{
    public $online;
    public $permission;
    public $username;
    public $id;
    public $password;

    public function __construct($permission = 0)
    {
        $this->permission = $permission;
        $this->online = 0;
        $this->username = "Unknown";
    }

    /**
     * Find and return specific from name.
     *
     * @return this
     */
    public function findByName($acronym)
    {
        $this->db->select()
                 ->from($this->getSource())
                 ->where("acronym = ?");

        $this->db->execute([$acronym]);
        return $this->db->fetchInto($this);
    }

    public function permissionToString()
    {
        if ($this->permission == 3) {
            return 'Administrator';
        }

        if ($this->permission == 2) {
            return 'Moderator';
        }

        if ($this->permission == 1) {
            return 'User';
        }
    }

    /**
     * Find and return latest.
     *
     * @return array
     */
    public function findLatest($nr)
    {
        $this->db->select()
                 ->from($this->getSource())
                 ->orderBy($this->db->getTablePrefix() . $this->getSource() .'.created DESC')
                 ->limit($nr);

        $this->db->execute();
        $this->db->setFetchModeClass(__CLASS__);
        return $this->db->fetchAll();
    }

    /**
     * Find and return top.
     *
     * @return array
     */
    public function findTop($limit = 5)
    {
        $this->db->select()
                 ->from($this->getSource())
                 ->orderBy($this->db->getTablePrefix() . $this->getSource() .'.score DESC')
                 ->limit($limit);

        $this->db->execute();
        $this->db->setFetchModeClass(__CLASS__);
        return $this->db->fetchAll();
    }

    /**
     * Question score
     *
     * @return array
     */
    public function getQuestionScore($id)
    {
        $this->db->select('phpmvc_question.score')
                 ->from('question')
                 ->where($this->db->getTablePrefix() . 'question' . ".user_id = ?");

        $this->db->execute([$id]);
        return $this->db->fetchAll();
    }

    /**
     * Answer score
     *
     * @return array
     */
    public function getAnswerScore($id)
    {
        $this->db->select('phpmvc_answer.score')
                 ->from('answer')
                 ->where($this->db->getTablePrefix() . 'answer' . ".user_id = ?");

        $this->db->execute([$id]);
        return $this->db->fetchAll();
    }

}


text:
module Translate where

orfs :: String -> [String]
orfs str = [str]