text:
<?php

# Copyright (c)  2008 - Marcus Lunzenauer <mlunzena@uos.de>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

class Flexi_TemplateFactory {

  /**
   * include path for templates
   *
   * @var string
   */
  protected $path;

  /**
   * mapping of file extensions to supported template classes
   *
   * @var array
   */
  protected $handlers = array(
      'php' => array('Flexi_PhpTemplate', array()),
      'pjs' => array('Flexi_JsTemplate',  array())
  );

  /**
   * Constructor of TemplateFactory.
   *
   * @param string the template include path
   *
   * @return void
   */
  function __construct($path) {
    $this->set_path($path);
  }

  /**
   * Sets a new include path for the factory and returns the old one.
   *
   * @param string the new path
   *
   * @return string the old path
   */
  function set_path($path) {

    $old_path = $this->get_path();

    if (substr($path, -1) != '/')
      $path .= '/';

    $this->path = $path;

    return $old_path;
  }

  /**
   * Returns the include path of the factory
   *
   * @return string the current include path
   */
  function get_path() {
    return $this->path;
  }

  /**
   * Open a template of the given name using the factory method pattern.
   * If a string was given, the path of the factory is searched for a matching
   * template.
   * If this string starts with a slash or with /\w+:\/\//, the string is
   * interpreted as an absolute path. Otherwise the path of the factory will be
   * prepended.
   * After that the factory searches for a file extension in this string. If
   * there is none, the directory where the template is supposed to live is
   * searched for a file starting with the template string and a supported
   * file extension.
   * At last the factory instantiates a template object of the matching template
   * class.
   *
   * Examples:
   *
   *   $factory->open('/path/to/template')
   *     does not prepend the factory's path but searches for "template.*" in
   *     "/path/to"
   *
   *   $factory->open('template')
   *     prepends the factory's path and searches there for "template.*"
   *
   *  $factory->open('template.php')
   *     prepends the factory's path but does not search and instantiates a
   *     PHPTemplate instead
   *
   * This method returns it's parameter, if it is not a string. This
   * functionality is useful for helper methods like #render_partial
   *
   * @throws Flexi_TemplateNotFoundException
   *
   * @param string A name of a template.
   *
   * @return mixed the factored object
   *
   * @throws Flexi_TemplateNotFoundException  if the template could not be found
   */
  function open($template) {

    # if it is not a string, this method behaves like identity
    if (!is_string($template)) {
      return $template;
    }

    # get file
    $file = $this->get_template_file($template);

    # retrieve handler
    list($class, $options) = $this->get_template_handler($file);

    return new $class($file, $this, $options);
  }

  /**
   * This method returns the absolute filename of the template
   *
   * @param  string     a template string
   *
   * @return string     an absolute filename
   *
   * @throws Flexi_TemplateNotFoundException  if the template could not be found
   */
  function get_template_file($template0) {

    $template = $this->get_absolute_path($template0);
    $extension = $this->get_extension($template);

    # extension defined, is there a matching template class?
    if ($extension !== NULL) {
      if (file_exists($template)) {
        return $template;
      }
    }

    # no extension defined, find it
    else {
      $file = $this->find_template($template);
      if ($file !== NULL) {
        return $file;
      }
    }

    # falling through to throw exception
    throw new Flexi_TemplateNotFoundException(
      sprintf('Missing template "%s" in "%s".', $template0, $this->path));
  }

  /**
   * Matches an extension to a template handler.
   *
   * @param  string     the template
   *
   * @return array      an array containing the class name and an array of
   *                    options of the matched extension;
   *                    or NULL if the extension did not match
   */
  function get_template_handler($template) {
    $extension = $this->get_extension($template);
    return isset($this->handlers[$extension])
           ? $this->handlers[$extension]
           : NULL;
  }

  /**
   * Registers a handler for templates with a matching extension.
   *
   * @param string  the extension of the templates to handle
   * @param string  the name of the already loaded class
   * @param array   optional; an array of options which is used
   *                when constructing a new instance
   */
  function add_handler($extension, $class, $options = array())
  {
      $this->handlers[$extension] = array($class, $options);
  }

  /**
   * Returns the absolute path to the template. If the given argument starts
   * with a slash or with a protocoll, this method just returns its arguments.
   *
   * @param  string     an incomplete template name
   *
   * @return string     an absolute path to the incomplete template name
   */
  function get_absolute_path($template) {
    return preg_match('#^(/|\w+://)#', $template)
           ? $template
           : $this->get_path() . $template;
  }

  /**
   * Find template given w/o extension.
   *
   * @param  string     the template's filename w/o extension
   *
   * @return mixed      NULL if there no such file could be found, a string
   *                    containing the complete file name otherwise
   */
  function find_template($template) {
    foreach ($this->handlers as $ext => $handler) {
      $file = "$template.$ext";
      if (file_exists($file)) {
        return $file;
      }
    }
    return NULL;
  }

  /**
   * Returns the file extension if there is one.
   *
   * @param  string     an possibly incomplete template file name
   *
   * @return mixed      a string containing the file extension if there is one,
   *                    NULL otherwise
   */
  function get_extension($file) {
    $matches = array();
    $matched = preg_match('/\.([^\/.]+)$/', $file, $matches);
    return $matched ? $matches[1] : NULL;
  }

  /**
   * Class method to parse, render and return the presentation of a
   * template.
   *
   * @param string A name of a template.
   * @param array  An associative array of attributes and their associated
   *               values.
   * @param string A name of a layout template.
   *
   * @return string A string representing the rendered presentation.
   */
  function render($name, $attributes = null, $layout = null) {
    return $this->open($name)->render($attributes, $layout);
  }
}


text:
import rehype from "rehype"
import highlight from "rehype-highlight"
import removeLangAuto from "./remove-lang-auto"

function addHighlight(html) {
  return rehype()
    .use(removeLangAuto)
    .use(highlight)
    .process(html)
    .toString()
}

export default ({ result }) => {
  return {
    ...result,
    body: addHighlight(result.body),
  }
}

redpajama_set_name: RedPajamaGithub


text:
//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang driver; it is a thin wrapper
// for functionality in the Driver clang library.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Driver.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/Stack.h"
#include "clang/Config/config.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "clang/Frontend/ChainedDiagnosticConsumer.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/SerializedDiagnosticPrinter.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/Utils.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/BuryPointer.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <set>
#include <system_error>
using namespace clang;
using namespace clang::driver;
using namespace llvm::opt;

std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
  if (!CanonicalPrefixes) {
    SmallString<128> ExecutablePath(Argv0);
    // Do a PATH lookup if Argv0 isn't a valid path.
    if (!llvm::sys::fs::exists(ExecutablePath))
      if (llvm::ErrorOr<std::string> P =
              llvm::sys::findProgramByName(ExecutablePath))
        ExecutablePath = *P;
    return std::string(ExecutablePath.str());
  }

  // This just needs to be some symbol in the binary; C++ doesn't
  // allow taking the address of ::main however.
  void *P = (void*) (intptr_t) GetExecutablePath;
  return llvm::sys::fs::getMainExecutable(Argv0, P);
}

static const char *GetStableCStr(std::set<std::string> &SavedStrings,
                                 StringRef S) {
  return SavedStrings.insert(std::string(S)).first->c_str();
}

/// ApplyQAOverride - Apply a list of edits to the input argument lists.
///
/// The input string is a space separate list of edits to perform,
/// they are applied in order to the input argument lists. Edits
/// should be one of the following forms:
///
///  '#': Silence information about the changes to the command line arguments.
///
///  '^': Add FOO as a new argument at the beginning of the command line.
///
///  '+': Add FOO as a new argument at the end of the command line.
///
///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
///  line.
///
///  'xOPTION': Removes all instances of the literal argument OPTION.
///
///  'XOPTION': Removes all instances of the literal argument OPTION,
///  and the following argument.
///
///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
///  at the end of the command line.
///
/// \param OS - The stream to write edit information to.
/// \param Args - The vector of command line arguments.
/// \param Edit - The override command to perform.
/// \param SavedStrings - Set to use for storing string representations.
static void ApplyOneQAOverride(raw_ostream &OS,
                               SmallVectorImpl<const char*> &Args,
                               StringRef Edit,
                               std::set<std::string> &SavedStrings) {
  // This does not need to be efficient.

  if (Edit[0] == '^') {
    const char *Str =
      GetStableCStr(SavedStrings, Edit.substr(1));
    OS << "### Adding argument " << Str << " at beginning\n";
    Args.insert(Args.begin() + 1, Str);
  } else if (Edit[0] == '+') {
    const char *Str =
      GetStableCStr(SavedStrings, Edit.substr(1));
    OS << "### Adding argument " << Str << " at end\n";
    Args.push_back(Str);
  } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
             Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
    StringRef MatchPattern = Edit.substr(2).split('/').first;
    StringRef ReplPattern = Edit.substr(2).split('/').second;
    ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);

    for (unsigned i = 1, e = Args.size(); i != e; ++i) {
      // Ignore end-of-line response file markers
      if (Args[i] == nullptr)
        continue;
      std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);

      if (Repl != Args[i]) {
        OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
        Args[i] = GetStableCStr(SavedStrings, Repl);
      }
    }
  } else if (Edit[0] == 'x' || Edit[0] == 'X') {
    auto Option = Edit.substr(1);
    for (unsigned i = 1; i < Args.size();) {
      if (Option == Args[i]) {
        OS << "### Deleting argument " << Args[i] << '\n';
        Args.erase(Args.begin() + i);
        if (Edit[0] == 'X') {
          if (i < Args.size()) {
            OS << "### Deleting argument " << Args[i] << '\n';
            Args.erase(Args.begin() + i);
          } else
            OS << "### Invalid X edit, end of command line!\n";
        }
      } else
        ++i;
    }
  } else if (Edit[0] == 'O') {
    for (unsigned i = 1; i < Args.size();) {
      const char *A = Args[i];
      // Ignore end-of-line response file markers
      if (A == nullptr)
        continue;
      if (A[0] == '-' && A[1] == 'O' &&
          (A[2] == '\0' ||
           (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
                             ('0' <= A[2] && A[2] <= '9'))))) {
        OS << "### Deleting argument " << Args[i] << '\n';
        Args.erase(Args.begin() + i);
      } else
        ++i;
    }
    OS << "### Adding argument " << Edit << " at end\n";
    Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
  } else {
    OS << "### Unrecognized edit: " << Edit << "\n";
  }
}

/// ApplyQAOverride - Apply a comma separate list of edits to the
/// input argument lists. See ApplyOneQAOverride.
static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
                            const char *OverrideStr,
                            std::set<std::string> &SavedStrings) {
  raw_ostream *OS = &llvm::errs();

  if (OverrideStr[0] == '#') {
    ++OverrideStr;
    OS = &llvm::nulls();
  }

  *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";

  // This does not need to be efficient.

  const char *S = OverrideStr;
  while (*S) {
    const char *End = ::strchr(S, ' ');
    if (!End)
      End = S + strlen(S);
    if (End != S)
      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
    S = End;
    if (*S != '\0')
      ++S;
  }
}

extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
                    void *MainAddr);
extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
                      void *MainAddr);

static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
                                    SmallVectorImpl<const char *> &ArgVector,
                                    std::set<std::string> &SavedStrings) {
  // Put target and mode arguments at the start of argument list so that
  // arguments specified in command line could override them. Avoid putting
  // them at index 0, as an option like '-cc1' must remain the first.
  int InsertionPoint = 0;
  if (ArgVector.size() > 0)
    ++InsertionPoint;

  if (NameParts.DriverMode) {
    // Add the mode flag to the arguments.
    ArgVector.insert(ArgVector.begin() + InsertionPoint,
                     GetStableCStr(SavedStrings, NameParts.DriverMode));
  }

  if (NameParts.TargetIsValid) {
    const char *arr[] = {"-target", GetStableCStr(SavedStrings,
                                                  NameParts.TargetPrefix)};
    ArgVector.insert(ArgVector.begin() + InsertionPoint,
                     std::begin(arr), std::end(arr));
  }
}

static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
                               SmallVectorImpl<const char *> &Opts) {
  llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
  // The first instance of '#' should be replaced with '=' in each option.
  for (const char *Opt : Opts)
    if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
      *NumberSignPtr = '=';
}

static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
  auto CheckEnvVar = [](const char *EnvOptSet, const char *EnvOptFile,
                        std::string &OptFile) {
    bool OptSet = !!::getenv(EnvOptSet);
    if (OptSet) {
      if (const char *Var = ::getenv(EnvOptFile))
        OptFile = Var;
    }
    return OptSet;
  };

  TheDriver.CCPrintOptions =
      CheckEnvVar("CC_PRINT_OPTIONS", "CC_PRINT_OPTIONS_FILE",
                  TheDriver.CCPrintOptionsFilename);
  TheDriver.CCPrintHeaders =
      CheckEnvVar("CC_PRINT_HEADERS", "CC_PRINT_HEADERS_FILE",
                  TheDriver.CCPrintHeadersFilename);
  TheDriver.CCLogDiagnostics =
      CheckEnvVar("CC_LOG_DIAGNOSTICS", "CC_LOG_DIAGNOSTICS_FILE",
                  TheDriver.CCLogDiagnosticsFilename);
  TheDriver.CCPrintProcessStats =
      CheckEnvVar("CC_PRINT_PROC_STAT", "CC_PRINT_PROC_STAT_FILE",
                  TheDriver.CCPrintStatReportFilename);
}

static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
                                   const std::string &Path) {
  // If the clang binary happens to be named cl.exe for compatibility reasons,
  // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
  StringRef ExeBasename(llvm::sys::path::stem(Path));
  if (ExeBasename.equals_insensitive("cl"))
    ExeBasename = "clang-cl";
  DiagClient->setPrefix(std::string(ExeBasename));
}

// This lets us create the DiagnosticsEngine with a properly-filled-out
// DiagnosticOptions instance.
static DiagnosticOptions *
CreateAndPopulateDiagOpts(ArrayRef<const char *> argv, bool &UseNewCC1Process) {
  auto *DiagOpts = new DiagnosticOptions;
  unsigned MissingArgIndex, MissingArgCount;
  InputArgList Args = getDriverOptTable().ParseArgs(
      argv.slice(1), MissingArgIndex, MissingArgCount);
  // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
  // Any errors that would be diagnosed here will also be diagnosed later,
  // when the DiagnosticsEngine actually exists.
  (void)ParseDiagnosticArgs(*DiagOpts, Args);

  UseNewCC1Process =
      Args.hasFlag(clang::driver::options::OPT_fno_integrated_cc1,
                   clang::driver::options::OPT_fintegrated_cc1,
                   /*Default=*/CLANG_SPAWN_CC1);

  return DiagOpts;
}

static void SetInstallDir(SmallVectorImpl<const char *> &argv,
                          Driver &TheDriver, bool CanonicalPrefixes) {
  // Attempt to find the original path used to invoke the driver, to determine
  // the installed path. We do this manually, because we want to support that
  // path being a symlink.
  SmallString<128> InstalledPath(argv[0]);

  // Do a PATH lookup, if there are no directory components.
  if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
    if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
            llvm::sys::path::filename(InstalledPath.str())))
      InstalledPath = *Tmp;

  // FIXME: We don't actually canonicalize this, we just make it absolute.
  if (CanonicalPrefixes)
    llvm::sys::fs::make_absolute(InstalledPath);

  StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
  if (llvm::sys::fs::exists(InstalledPathParent))
    TheDriver.setInstalledDir(InstalledPathParent);
}

static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV) {
  // If we call the cc1 tool from the clangDriver library (through
  // Driver::CC1Main), we need to clean up the options usage count. The options
  // are currently global, and they might have been used previously by the
  // driver.
  llvm::cl::ResetAllOptionOccurrences();

  llvm::BumpPtrAllocator A;
  llvm::StringSaver Saver(A);
  llvm::cl::ExpandResponseFiles(Saver, &llvm::cl::TokenizeGNUCommandLine, ArgV,
                                /*MarkEOLs=*/false);
  StringRef Tool = ArgV[1];
  void *GetExecutablePathVP = (void *)(intptr_t)GetExecutablePath;
  if (Tool == "-cc1")
    return cc1_main(makeArrayRef(ArgV).slice(1), ArgV[0], GetExecutablePathVP);
  if (Tool == "-cc1as")
    return cc1as_main(makeArrayRef(ArgV).slice(2), ArgV[0],
                      GetExecutablePathVP);
  // Reject unknown tools.
  llvm::errs() << "error: unknown integrated tool '" << Tool << "'. "
               << "Valid tools include '-cc1' and '-cc1as'.\n";
  return 1;
}

extern "C" int ZigClang_main(int Argc, const char **Argv);
int ZigClang_main(int Argc, const char **Argv) {
  noteBottomOfStack();
  // ZIG PATCH: On Windows, InitLLVM calls GetCommandLineW(),
  // and overwrites the args.  We don't want it to do that,
  // and we also don't need the signal handlers it installs
  // (we have our own already), so we just use llvm_shutdown_obj
  // instead.
  // llvm::InitLLVM X(Argc, Argv);
  llvm::llvm_shutdown_obj X;

  llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
                        " and include the crash backtrace, preprocessed "
                        "source, and associated run script.\n");
  size_t argv_offset = (strcmp(Argv[1], "-cc1") == 0 || strcmp(Argv[1], "-cc1as") == 0) ? 0 : 1;
  SmallVector<const char *, 256> Args(Argv + argv_offset, Argv + Argc);

  if (llvm::sys::Process::FixupStandardFileDescriptors())
    return 1;

  llvm::InitializeAllTargets();

  llvm::BumpPtrAllocator A;
  llvm::StringSaver Saver(A);

  // Parse response files using the GNU syntax, unless we're in CL mode. There
  // are two ways to put clang in CL compatibility mode: Args[0] is either
  // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
  // command line parsing can't happen until after response file parsing, so we
  // have to manually search for a --driver-mode=cl argument the hard way.
  // Finally, our -cc1 tools don't care which tokenization mode we use because
  // response files written by clang will tokenize the same way in either mode.
  bool ClangCLMode =
      IsClangCL(getDriverMode(Args[0], llvm::makeArrayRef(Args).slice(1)));
  enum { Default, POSIX, Windows } RSPQuoting = Default;
  for (const char *F : Args) {
    if (strcmp(F, "--rsp-quoting=posix") == 0)
      RSPQuoting = POSIX;
    else if (strcmp(F, "--rsp-quoting=windows") == 0)
      RSPQuoting = Windows;
  }

  // Determines whether we want nullptr markers in Args to indicate response
  // files end-of-lines. We only use this for the /LINK driver argument with
  // clang-cl.exe on Windows.
  bool MarkEOLs = ClangCLMode;

  llvm::cl::TokenizerCallback Tokenizer;
  if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
    Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
  else
    Tokenizer = &llvm::cl::TokenizeGNUCommandLine;

  if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).startswith("-cc1"))
    MarkEOLs = false;
  llvm::cl::ExpandResponseFiles(Saver, Tokenizer, Args, MarkEOLs);

  // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
  // file.
  auto FirstArg = std::find_if(Args.begin() + 1, Args.end(),
                               [](const char *A) { return A != nullptr; });
  if (FirstArg != Args.end() && StringRef(*FirstArg).startswith("-cc1")) {
    // If -cc1 came from a response file, remove the EOL sentinels.
    if (MarkEOLs) {
      auto newEnd = std::remove(Args.begin(), Args.end(), nullptr);
      Args.resize(newEnd - Args.begin());
    }
    return ExecuteCC1Tool(Args);
  }

  // Handle options that need handling before the real command line parsing in
  // Driver::BuildCompilation()
  bool CanonicalPrefixes = true;
  for (int i = 1, size = Args.size(); i < size; ++i) {
    // Skip end-of-line response file markers
    if (Args[i] == nullptr)
      continue;
    if (StringRef(Args[i]) == "-no-canonical-prefixes") {
      CanonicalPrefixes = false;
      break;
    }
  }

  // Handle CL and _CL_ which permits additional command line options to be
  // prepended or appended.
  if (ClangCLMode) {
    // Arguments in "CL" are prepended.
    llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
    if (OptCL.hasValue()) {
      SmallVector<const char *, 8> PrependedOpts;
      getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);

      // Insert right after the program name to prepend to the argument list.
      Args.insert(Args.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
    }
    // Arguments in "_CL_" are appended.
    llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
    if (Opt_CL_.hasValue()) {
      SmallVector<const char *, 8> AppendedOpts;
      getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);

      // Insert at the end of the argument list to append.
      Args.append(AppendedOpts.begin(), AppendedOpts.end());
    }
  }

  std::set<std::string> SavedStrings;
  // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
  // scenes.
  if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
    // FIXME: Driver shouldn't take extra initial argument.
    ApplyQAOverride(Args, OverrideStr, SavedStrings);
  }

  // Pass local param `Argv[0]` as fallback.
  // See https://github.com/ziglang/zig/pull/3292 .
  std::string Path = GetExecutablePath(Argv[0], CanonicalPrefixes);

  // Whether the cc1 tool should be called inside the current process, or if we
  // should spawn a new clang subprocess (old behavior).
  // Not having an additional process saves some execution time of Windows,
  // and makes debugging and profiling easier.
  bool UseNewCC1Process;

  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
      CreateAndPopulateDiagOpts(Args, UseNewCC1Process);

  TextDiagnosticPrinter *DiagClient
    = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
  FixupDiagPrefixExeName(DiagClient, Path);

  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());

  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);

  if (!DiagOpts->DiagnosticSerializationFile.empty()) {
    auto SerializedConsumer =
        clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
                                        &*DiagOpts, /*MergeChildRecords=*/true);
    Diags.setClient(new ChainedDiagnosticConsumer(
        Diags.takeClient(), std::move(SerializedConsumer)));
  }

  ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);

  Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
  SetInstallDir(Args, TheDriver, CanonicalPrefixes);
  auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(Args[0]);
  TheDriver.setTargetAndMode(TargetAndMode);

  insertTargetAndModeArgs(TargetAndMode, Args, SavedStrings);

  SetBackdoorDriverOutputsFromEnvVars(TheDriver);

  if (!UseNewCC1Process) {
    TheDriver.CC1Main = &ExecuteCC1Tool;
    // Ensure the CC1Command actually catches cc1 crashes
    llvm::CrashRecoveryContext::Enable();
  }

  std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(Args));
  int Res = 1;
  bool IsCrash = false;
  if (C && !C->containsError()) {
    SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
    Res = TheDriver.ExecuteCompilation(*C, FailingCommands);

    // Force a crash to test the diagnostics.
    if (TheDriver.GenReproducer) {
      Diags.Report(diag::err_drv_force_crash)
        << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");

      // Pretend that every command failed.
      FailingCommands.clear();
      for (const auto &J : C->getJobs())
        if (const Command *C = dyn_cast<Command>(&J))
          FailingCommands.push_back(std::make_pair(-1, C));

      // Print the bug report message that would be printed if we did actually
      // crash, but only if we're crashing due to FORCE_CLANG_DIAGNOSTICS_CRASH.
      if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
        llvm::dbgs() << llvm::getBugReportMsg();
    }

    for (const auto &P : FailingCommands) {
      int CommandRes = P.first;
      const Command *FailingCommand = P.second;
      if (!Res)
        Res = CommandRes;

      // If result status is < 0, then the driver command signalled an error.
      // If result status is 70, then the driver command reported a fatal error.
      // On Windows, abort will return an exit code of 3.  In these cases,
      // generate additional diagnostic information if possible.
      IsCrash = CommandRes < 0 || CommandRes == 70;
#ifdef _WIN32
      IsCrash |= CommandRes == 3;
#endif
#if LLVM_ON_UNIX
      // When running in integrated-cc1 mode, the CrashRecoveryContext returns
      // the same codes as if the program crashed. See section "Exit Status for
      // Commands":
      // https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html
      IsCrash |= CommandRes > 128;
#endif
      if (IsCrash) {
        TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
        break;
      }
    }
  }

  Diags.getClient()->finish();

  if (!UseNewCC1Process && IsCrash) {
    // When crashing in -fintegrated-cc1 mode, bury the timer pointers, because
    // the internal linked list might point to already released stack frames.
    llvm::BuryPointer(llvm::TimerGroup::aquireDefaultGroup());
  } else {
    // If any timers were active but haven't been destroyed yet, print their
    // results now.  This happens in -disable-free mode.
    llvm::TimerGroup::printAll(llvm::errs());
    llvm::TimerGroup::clearAll();
  }

#ifdef _WIN32
  // Exit status should not be negative on Win32, unless abnormal termination.
  // Once abnormal termination was caught, negative status should not be
  // propagated.
  if (Res < 0)
    Res = 1;
#endif

  // If we have multiple failing commands, we return the result of the first
  // failing command.
  return Res;
}


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>278 nips-2010-Universal Consistency of Multi-Class Support Vector Classification</title>

nips nips2010 nips2010-278 nips2010-278-reference knowledge-graph by maker-knowledge-mining

278 nips-2010-Universal Consistency of Multi-Class Support Vector Classification

Source: pdf

Author: Tobias Glasmachers

Abstract: Steinwart was the first to prove universal consistency of support vector machine classification. His proof analyzed the 'standard' support vector machine classifier, which is restricted to binary classification problems. In contrast, recent analysis has resulted in the common belief that several extensions of SVM classification to more than two classes are inconsistent. Countering this belief, we prove the universal consistency of the multi-class support vector machine by Crammer and Singer. Our proof extends Steinwart's techniques to the multi-class case. 1

reference text

[1] C. Cortes and V. Vapnik. Support-Vector Networks. Machine Learning, 20(3):273–297, 1995.

[2] K. Crammer and Y. Singer. On the algorithmic implementation of multiclass kernel-based vector machines. Journal of Machine Learning Research, 2:265–292, 2002.

[3] S. Hill and A. Doucet. A Framework for Kernel-Based Multi-Category Classification. Journal of Artificial Intelligence Research, 30:525–564, 2007.

[4] Y. Lee, Y. Lin, and G. Wahba. Multicategory Support Vector Machines: Theory and Application to the Classification of Microarray Data and Satellite Radiance Data. Journal of the American Statistical Association, 99(465):67–82, 2004.

[5] Y. Liu. Fisher Consistency of Multicategory Support Vector Machines. Journal of Machine Learning Research, 2:291–298, 2007.

[6] I. Steinwart. Support Vector Machines are Universally Consistent. J. Complexity, 18(3):768– 791, 2002.

[7] A. Tewari and P. L. Bartlett. On the Consistency of Multiclass Classification Methods. Journal of Machine Learning Research, 8:1007–1025, 2007.

[8] V. Vapnik. Statistical Learning Theory. Wiley, New-York, 1998.

[9] J. Weston and C. Watkins. Support vector machines for multi-class pattern recognition. In M. Verleysen, editor, Proceedings of the Seventh European Symposium On Artificial Neural Networks (ESANN), pages 219–224, 1999.  9


text:
require 'boson-daemon/collider'

module Boson
  module Daemon

    def initialize
    	@collider = Boson::Daemon::Collider.new
    end

  end
end


text:
namespace System.Runtime.CompilerServices
{

#if CONFIG_COM_INTEROP

using System.Runtime.InteropServices;

[AttributeUsage(AttributeTargets.Field |
				AttributeTargets.Parameter,
				Inherited=false)]
public sealed class IDispatchConstantAttribute : CustomConstantAttribute
{
	// Constructors.
	public IDispatchConstantAttribute() : base() {}

	// Properties.
	public override Object Value
			{
				get
				{
					return new DispatchWrapper(null);
				}
			}

}; // class IDispatchConstantAttribute

#endif // CONFIG_COM_INTEROP

}; // namespace System.Runtime.CompilerServices


text:
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Configuration.Models;

namespace Umbraco.Cms.Web.BackOffice.Middleware
{
    /// <summary>
    /// Ensures the Keep Alive middleware is part of
    /// </summary>
    public sealed class ConfigureGlobalOptionsForKeepAliveMiddlware : IPostConfigureOptions<GlobalSettings>
    {
        private readonly IOptions<KeepAliveSettings> _keepAliveSettings;

        public ConfigureGlobalOptionsForKeepAliveMiddlware(IOptions<KeepAliveSettings> keepAliveSettings) => _keepAliveSettings = keepAliveSettings;

        /// <summary>
        /// Append the keep alive ping url to the reserved URLs
        /// </summary>
        /// <param name="name"></param>
        /// <param name="options"></param>
        public void PostConfigure(string name, GlobalSettings options) => options.ReservedUrls += _keepAliveSettings.Value.KeepAlivePingUrl;
    }
}


text: <!doctype html>


text:
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;

namespace EdiEngine.Standards.X12_004010.Maps
{
	public class M_819 : MapLoop
	{
		public M_819() : base(null)
		{
			Content.AddRange(new MapBaseEntity[] {
				new BOS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
				new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
				new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
				new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
				new L_JIL(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 10000 },
				new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
				new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
				new TDS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
				new L_PSA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
				new CTT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
			});
		}

		//1000
		public class L_N1 : MapLoop
		{
			public L_N1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
					new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
					new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
				});
			}
		}

		//2000
		public class L_JIL : MapLoop
		{
			public L_JIL(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new JIL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
					new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
					new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
					new ITA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
					new PSA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new L_JID(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
				});
			}
		}

		//2100
		public class L_JID : MapLoop
		{
			public L_JID(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new JID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
					new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
					new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
				});
			}
		}

		//3000
		public class L_PSA : MapLoop
		{
			public L_PSA(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new PSA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
					new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
				});
			}
		}

	}
 }


text: Core library code for other `@modernfidelity/fabric` components.


text:
from .. import mesonlib
from .. import mlog
from .common import cmake_is_debug
import typing as T

if T.TYPE_CHECKING:
    from .traceparser import CMakeTraceParser, CMakeTarget

def parse_generator_expressions(
            raw: str,
            trace: 'CMakeTraceParser',
            *,
            context_tgt: T.Optional['CMakeTarget'] = None,
        ) -> str:
    '''Parse CMake generator expressions

    Most generator expressions are simply ignored for
    simplicety, however some are required for some common
    use cases.
    '''

    # Early abort if no generator expression present
    if '$<' not in raw:
        return raw

    out = ''  # type: str
    i = 0     # type: int

    def equal(arg: str) -> str:
        col_pos = arg.find(',')
        if col_pos < 0:
            return '0'
        else:
            return '1' if arg[:col_pos] == arg[col_pos + 1:] else '0'

    def vers_comp(op: str, arg: str) -> str:
        col_pos = arg.find(',')
        if col_pos < 0:
            return '0'
        else:
            return '1' if mesonlib.version_compare(arg[:col_pos], '{}{}'.format(op, arg[col_pos + 1:])) else '0'

    def target_property(arg: str) -> str:
        # We can't really support this since we don't have any context
        if ',' not in arg:
            if context_tgt is None:
                return ''
            return ';'.join(context_tgt.properties.get(arg, []))

        args = arg.split(',')
        props = trace.targets[args[0]].properties.get(args[1], []) if args[0] in trace.targets else []
        return ';'.join(props)

    def target_file(arg: str) -> str:
        if arg not in trace.targets:
            mlog.warning(f"Unable to evaluate the cmake variable '$<TARGET_FILE:{arg}>'.")
            return ''
        tgt = trace.targets[arg]

        cfgs = []
        cfg = ''

        if 'IMPORTED_CONFIGURATIONS' in tgt.properties:
            cfgs = [x for x in tgt.properties['IMPORTED_CONFIGURATIONS'] if x]
            cfg = cfgs[0]

        if cmake_is_debug(trace.env):
            if 'DEBUG' in cfgs:
                cfg = 'DEBUG'
            elif 'RELEASE' in cfgs:
                cfg = 'RELEASE'
        else:
            if 'RELEASE' in cfgs:
                cfg = 'RELEASE'

        if f'IMPORTED_IMPLIB_{cfg}' in tgt.properties:
            return ';'.join([x for x in tgt.properties[f'IMPORTED_IMPLIB_{cfg}'] if x])
        elif 'IMPORTED_IMPLIB' in tgt.properties:
            return ';'.join([x for x in tgt.properties['IMPORTED_IMPLIB'] if x])
        elif f'IMPORTED_LOCATION_{cfg}' in tgt.properties:
            return ';'.join([x for x in tgt.properties[f'IMPORTED_LOCATION_{cfg}'] if x])
        elif 'IMPORTED_LOCATION' in tgt.properties:
            return ';'.join([x for x in tgt.properties['IMPORTED_LOCATION'] if x])
        return ''

    supported = {
        # Boolean functions
        'BOOL': lambda x: '0' if x.upper() in ['0', 'FALSE', 'OFF', 'N', 'NO', 'IGNORE', 'NOTFOUND'] or x.endswith('-NOTFOUND') else '1',
        'AND': lambda x: '1' if all(y == '1' for y in x.split(',')) else '0',
        'OR': lambda x: '1' if any(y == '1' for y in x.split(',')) else '0',
        'NOT': lambda x: '0' if x == '1' else '1',

        'IF': lambda x: x.split(',')[1] if x.split(',')[0] == '1' else x.split(',')[2],

        '0': lambda x: '',
        '1': lambda x: x,

        # String operations
        'STREQUAL': equal,
        'EQUAL': equal,
        'VERSION_LESS': lambda x: vers_comp('<', x),
        'VERSION_GREATER': lambda x: vers_comp('>', x),
        'VERSION_EQUAL': lambda x: vers_comp('=', x),
        'VERSION_LESS_EQUAL': lambda x: vers_comp('<=', x),
        'VERSION_GREATER_EQUAL': lambda x: vers_comp('>=', x),

        # String modification
        'LOWER_CASE': lambda x: x.lower(),
        'UPPER_CASE': lambda x: x.upper(),

        # Always assume the BUILD_INTERFACE is valid.
        # INSTALL_INTERFACE is always invalid for subprojects and
        # it should also never appear in CMake config files, used
        # for dependencies
        'INSTALL_INTERFACE': lambda x: '',
        'BUILD_INTERFACE': lambda x: x,

        # Constants
        'ANGLE-R': lambda x: '>',
        'COMMA': lambda x: ',',
        'SEMICOLON': lambda x: ';',

        # Target related expressions
        'TARGET_EXISTS': lambda x: '1' if x in trace.targets else '0',
        'TARGET_NAME_IF_EXISTS': lambda x: x if x in trace.targets else '',
        'TARGET_PROPERTY': target_property,
        'TARGET_FILE': target_file,
    }  # type: T.Dict[str, T.Callable[[str], str]]

    # Recursively evaluate generator expressions
    def eval_generator_expressions() -> str:
        nonlocal i
        i += 2

        func = ''  # type: str
        args = ''  # type: str
        res = ''   # type: str
        exp = ''   # type: str

        # Determine the body of the expression
        while i < len(raw):
            if raw[i] == '>':
                # End of the generator expression
                break
            elif i < len(raw) - 1 and raw[i] == '$' and raw[i + 1] == '<':
                # Nested generator expression
                exp += eval_generator_expressions()
            else:
                # Generator expression body
                exp += raw[i]

            i += 1

        # Split the expression into a function and arguments part
        col_pos = exp.find(':')
        if col_pos < 0:
            func = exp
        else:
            func = exp[:col_pos]
            args = exp[col_pos + 1:]

        func = func.strip()
        args = args.strip()

        # Evaluate the function
        if func in supported:
            res = supported[func](args)

        return res

    while i < len(raw):
        if i < len(raw) - 1 and raw[i] == '$' and raw[i + 1] == '<':
            # Generator expression detected --> try resolving it
            out += eval_generator_expressions()
        else:
            # Normal string, leave unchanged
            out += raw[i]

        i += 1

    return out


text:
@interface BTDropInContentView () <UIGestureRecognizerDelegate>
@property (nonatomic, strong) NSArray *verticalLayoutConstraints;
/// An array of `NSLayoutConstraint` horizontal constraints on the payment button.
/// These constraints may need to be updated when
@property (nonatomic, strong) NSArray *paymentButtonConstraints;
@property (nonatomic, strong) UIActivityIndicatorView *activityView;
@property (nonatomic, strong) NSLayoutConstraint *heightConstraint;
@end

@implementation BTDropInContentView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialize Subviews

        self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.activityView.translatesAutoresizingMaskIntoConstraints = NO;
        self.activityView.hidden = YES;
        [self addSubview:self.activityView];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]];

        self.summaryView = [[BTUISummaryView alloc] init];

        UIView *summaryBorderBottom = [[UIView alloc] init];
        summaryBorderBottom.backgroundColor = self.theme.borderColor;
        summaryBorderBottom.translatesAutoresizingMaskIntoConstraints = NO;
        [self.summaryView addSubview:summaryBorderBottom];
        [self.summaryView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[border]|"
                                                                                options:0
                                                                                metrics:nil
                                                                                views:@{@"border": summaryBorderBottom}]];
        [self.summaryView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[border(==borderWidth)]|"
                                                                                options:0
                                                                                metrics:@{@"borderWidth": @(self.theme.borderWidth)}
                                                                                views:@{@"border": summaryBorderBottom}]];

        self.cardFormSectionHeader = [[UILabel alloc] init];

        self.cardForm = [[BTUICardFormView alloc] init];
        [self.cardForm setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

        self.selectedPaymentMethodView = [[BTUIPaymentMethodView alloc] init];

        self.changeSelectedPaymentMethodButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.changeSelectedPaymentMethodButton setTitle:BTDropInLocalizedString(DROP_IN_CHANGE_PAYMENT_METHOD_BUTTON_TEXT)
                                                forState:UIControlStateNormal];

        self.ctaControl = [[BTUICTAControl alloc] init];

        // Add Constraints & Subviews

        // Full-Width Views
        for (UIView *view in @[self.selectedPaymentMethodView, self.summaryView, self.ctaControl, self.cardForm]) {
            [self addSubview:view withHorizontalMargins:NO];
        }

        // Not quite full-width views
        for (UIView *view in @[self.cardFormSectionHeader, self.changeSelectedPaymentMethodButton]) {
            [self addSubview:view withHorizontalMargins:YES];
        }

        self.paymentButton = [[BTPaymentButton alloc] init];
        // The payment button horizontal constraints may be updated to add a margin to the button *after*
        // fetching the configuration, so keep a reference to them to update them in updateConstraints
        self.paymentButtonConstraints = [self addSubview:self.paymentButton withHorizontalMargins:NO];

        self.state = BTDropInContentViewStateForm;

        // Keyboard dismissal when tapping outside text field
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped)];
        tapGesture.delegate = self;
        [self addGestureRecognizer:tapGesture];

    }
    return self;
}

/// Adds a subview, and returns an array of constraints applied to the subview
- (NSArray *)addSubview:(UIView *)view withHorizontalMargins:(BOOL)useHorizontalMargins {
    [self addSubview:view];
    view.translatesAutoresizingMaskIntoConstraints = NO;
    NSDictionary *metrics = useHorizontalMargins ? @{@"horizontalMargin": @(self.theme.horizontalMargin)} : @{@"horizontalMargin": @(0)};
    NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(horizontalMargin)-[view]-(horizontalMargin)-|"
                                                                   options:0
                                                                   metrics:metrics
                                                                     views:@{@"view": view}];
    [self addConstraints:constraints];
    return constraints;
}

- (void)updateConstraints {

    if (self.verticalLayoutConstraints != nil) {
        [self removeConstraints:self.verticalLayoutConstraints];
    }

    CGFloat paymentButtonMargin;
    if ([self.paymentButton.enabledPaymentOptions isEqualToOrderedSet:[NSOrderedSet orderedSetWithArray:@[@"PayPal"]]]) {
        paymentButtonMargin = self.theme.horizontalMargin;
    } else {
        paymentButtonMargin = 0;
    }
    for (NSLayoutConstraint *constraint in self.paymentButtonConstraints) {
        constraint.constant = paymentButtonMargin;
    }
    [self.paymentButton setNeedsLayout];
    [self.paymentButton layoutIfNeeded];

    NSDictionary *viewBindings = @{
                                   @"activityView": self.activityView,
                                   @"summaryView": self.summaryView,
                                   @"paymentButton": self.paymentButton,
                                   @"cardFormSectionHeader": self.cardFormSectionHeader,
                                   @"cardForm": self.cardForm,
                                   @"ctaControl": self.ctaControl,
                                   @"selectedPaymentMethodView": self.selectedPaymentMethodView,
                                   @"changeSelectedPaymentMethodButton": self.changeSelectedPaymentMethodButton
                                   };

    NSMutableArray *newConstraints = [NSMutableArray array];
    for (NSString *visualFormat in [self evaluateVisualFormat]) {
        [newConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:visualFormat
                                                                                options:0
                                                                                metrics:nil
                                                                                views:viewBindings]];
    }

    if(self.heightConstraint != nil) {
        [self.superview removeConstraint:self.heightConstraint];
    }

    if (self.state != BTDropInContentViewStateForm) {

        self.heightConstraint = [NSLayoutConstraint constraintWithItem:self
                                                             attribute:NSLayoutAttributeHeight
                                                             relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                                toItem:self.superview
                                                             attribute:NSLayoutAttributeHeight
                                                            multiplier:1.0f
                                                              constant:0];
        [self.superview addConstraint:self.heightConstraint];
    }
    [self.superview setNeedsLayout];

    [self addConstraints:newConstraints];
    self.verticalLayoutConstraints = newConstraints;

    [super updateConstraints];

}
- (void)setHideSummary:(BOOL)hideSummary {
    _hideSummary = hideSummary;
    [self updateContentView];
}

- (void)setHideCTA:(BOOL)hideCTA {
    _hideCTA = hideCTA;
    [self updateContentView];
}

- (void)setState:(BTDropInContentViewStateType)state {
    _state = state;
    [self updateContentView];
}

- (void)setState:(BTDropInContentViewStateType)newState animate:(BOOL)animate completion:(void(^)(void))completionBlock {
    if (!animate) {
        [self setState:newState];
    } else {
        BTDropInContentViewStateType oldState = self.state;
        CGFloat duration = 0.2f;
        if (oldState == BTDropInContentViewStateActivity) {
            if (newState == BTDropInContentViewStateForm) {
                [UIView animateWithDuration:duration animations:^{
                    self.activityView.alpha = 0.0f;
                } completion:^(__unused BOOL finished) {
                    [self setState:newState];
                    self.paymentButton.alpha = 0.0f;
                    self.cardForm.alpha = 0.0f;
                    self.cardFormSectionHeader.alpha = 0.0f;
                    self.ctaControl.alpha = 0.0f;
                    [self setNeedsUpdateConstraints];
                    [self layoutIfNeeded];
                    [UIView animateWithDuration:duration animations:^{
                        self.paymentButton.alpha = 1.0f;
                        self.cardForm.alpha = 1.0f;
                        self.cardFormSectionHeader.alpha = 1.0f;
                        self.ctaControl.alpha = 1.0f;
                        if (completionBlock) {
                            completionBlock();
                        }
                    }];
                }];
                return;
            }

            if (newState == BTDropInContentViewStatePaymentMethodsOnFile) {
                self.activityView.alpha = 1.0f;
                [UIView animateWithDuration:duration animations:^{
                    self.activityView.alpha = 0.0f;
                } completion:^(__unused BOOL finished) {
                    [self setState:newState];
                    self.selectedPaymentMethodView.alpha = 0.0f;
                    self.changeSelectedPaymentMethodButton.alpha = 0.0f;
                    self.ctaControl.alpha = 0.0f;
                    [self setNeedsUpdateConstraints];
                    [self layoutIfNeeded];
                    [UIView animateWithDuration:duration animations:^{
                        self.selectedPaymentMethodView.alpha = 1.0f;
                        self.changeSelectedPaymentMethodButton.alpha = 1.0f;
                        self.ctaControl.alpha = 1.0f;
                        if (completionBlock) {
                            completionBlock();
                        }
                    }];
                }];
                return;
            }
        }
        [self setState:newState];
    }
}

- (void)setState:(BTDropInContentViewStateType)newState animate:(BOOL)animate {
    [self setState:newState animate:animate completion:nil];
}

- (void)setHidePaymentButton:(BOOL)hidePaymentButton {
    _hidePaymentButton = hidePaymentButton;
    self.paymentButton.hidden = hidePaymentButton;
    [self updateContentView];
}

- (void)updateContentView {

    // Reset all to hidden, just for clarity
    self.activityView.hidden = YES;
    self.summaryView.hidden = self.hideSummary;
    self.paymentButton.hidden = YES;
    self.cardFormSectionHeader.hidden = YES;
    self.cardForm.hidden = YES;
    self.selectedPaymentMethodView.hidden = YES;
    self.changeSelectedPaymentMethodButton.hidden = YES;
    self.ctaControl.hidden = YES;

    switch (self.state) {
        case BTDropInContentViewStateForm:
            self.activityView.hidden = YES;
            [self.activityView stopAnimating];
            self.ctaControl.hidden = self.hideCTA;
            self.paymentButton.hidden = self.hidePaymentButton;
            if ([[BTTokenizationService sharedService] isTypeAvailable:@"Card"]) {
                self.cardFormSectionHeader.hidden = NO;
                self.cardForm.hidden = NO;
            }
            break;
        case BTDropInContentViewStatePaymentMethodsOnFile:
            self.activityView.hidden = YES;
            [self.activityView stopAnimating];
            self.ctaControl.hidden = self.hideCTA;
            self.selectedPaymentMethodView.hidden = NO;
            self.changeSelectedPaymentMethodButton.hidden = NO;
            break;
        case BTDropInContentViewStateActivity:
            self.activityView.hidden = NO;
            self.activityView.alpha = 1.0f;
            [self.activityView startAnimating];
            break;
        default:
            break;
    }
    [self setNeedsUpdateConstraints];
}

#pragma mark Tap Gesture Delegate

- (BOOL)gestureRecognizer:(__unused UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    // Disallow recognition of tap gestures on UIControls (like, say, buttons)
    if ([touch.view isKindOfClass:[UIControl class]] || [touch.view isDescendantOfView:self.paymentButton]) {
        return NO;
    }
    return YES;
}

- (void)tapped {
    [self.cardForm endEditing:YES];
}

- (NSArray*) evaluateVisualFormat{
    NSString *summaryViewVisualFormat = self.summaryView.hidden ? @"" : @"[summaryView(>=60)]";
    NSString *ctaControlVisualFormat = self.ctaControl.hidden ? @"" : @"[ctaControl(==50)]";

    if (self.state == BTDropInContentViewStateActivity) {
        return @[[NSString stringWithFormat:@"V:|%@-(40)-[activityView]-(>=40)-%@|", summaryViewVisualFormat, ctaControlVisualFormat]];

    } else if (self.state != BTDropInContentViewStatePaymentMethodsOnFile) {
        if (!self.ctaControl.hidden) {
            ctaControlVisualFormat = [NSString stringWithFormat:@"-(15)-%@-(>=0)-", ctaControlVisualFormat];
        }
        if (self.hidePaymentButton){
            return @[[NSString stringWithFormat:@"V:|%@-(35)-[cardFormSectionHeader]-(7)-[cardForm]%@|", summaryViewVisualFormat, ctaControlVisualFormat]];
        } else {
            summaryViewVisualFormat = [NSString stringWithFormat:@"%@-(35)-", summaryViewVisualFormat];
            return @[[NSString stringWithFormat:@"V:|%@[paymentButton(==44)]-(18)-[cardFormSectionHeader]-(7)-[cardForm]%@|", summaryViewVisualFormat, ctaControlVisualFormat]];
        }

    } else {
        NSString *primaryLayout = [NSString stringWithFormat:@"V:|%@-(15)-[selectedPaymentMethodView(==45)]-(15)-[changeSelectedPaymentMethodButton]-(>=15)-%@|", summaryViewVisualFormat, ctaControlVisualFormat];
        NSMutableArray *visualLayouts = [NSMutableArray arrayWithObject:primaryLayout];
        if (!self.ctaControl.hidden) {
            [visualLayouts addObject:@"V:[ctaControl]|"];
        }
        return visualLayouts;
    }
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Dendrophoma salicina Voglino

### Remarks
null


text:
package com.ilivoo.common.socket.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.concurrent.atomic.AtomicInteger;

import com.ilivoo.common.socket.kernel.TSession;
import com.ilivoo.common.socket.service.IMessageInvoke;
import com.ilivoo.common.socket.service.ISessionInvoke;
import com.ilivoo.common.socket.service.MessageInvokeDefinition;
import com.ilivoo.common.socket.service.SessionInvokeDefinition;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;

public class EnhanceUtil {
    private static final AtomicInteger index = new AtomicInteger();

    private static final ClassPool pool = ClassPool.getDefault();

    public static ISessionInvoke createSessionInvoke(SessionInvokeDefinition definition) throws Exception {
	Object bean = definition.getBean();
	String beanName = bean.getClass().getCanonicalName();
	Method method = definition.getMethod();
	String methodName = method.getName();

	CtClass ctClass = buildCtClass(ISessionInvoke.class);
	CtField field = new CtField(pool.get(beanName), "bean", ctClass);
	field.setModifiers(Modifier.PRIVATE);
	ctClass.addField(field);

	CtConstructor constructor = new CtConstructor(new CtClass[] { pool.get(beanName) }, ctClass);
	constructor.setBody("{this.bean=$1;}");
	constructor.setModifiers(Modifier.PUBLIC);
	ctClass.addConstructor(constructor);

	CtMethod invokeMethod = new CtMethod(pool.get(Object.class.getCanonicalName()), "invoke",
		new CtClass[] { pool.get(TSession.class.getCanonicalName()) }, ctClass);
	invokeMethod.setExceptionTypes(new CtClass[]{pool.get(Exception.class.getCanonicalName())});
	invokeMethod.setModifiers(Modifier.PUBLIC + Modifier.FINAL);
	boolean noReturn = method.getReturnType().equals(void.class);
	StringBuilder sb = new StringBuilder();
	sb.append("{");
	if (noReturn) {
	    sb.append("bean." + methodName + "($1);");
	    sb.append("return null;");
	} else {
	    sb.append("return bean." + methodName + "($1);");
	}
	sb.append("}");
	invokeMethod.setBody(sb.toString());
	ctClass.addMethod(invokeMethod);

	Class<?> rClz = ctClass.toClass();
	Constructor<?> con = rClz.getConstructor(bean.getClass());
	ISessionInvoke iSessionInvoke = (ISessionInvoke) con.newInstance(bean);
	return iSessionInvoke;
    }

    /**
	public class IMessageInvokeEnhance1 implements com.ilivoo.common.socket.service.IMessageInvoke
	{
		private Type bean;
		private String[] inSessions;

		public IMessageInvokeEnhance1(Type bean, String[] inSessions){
			this.bean = bean;
			this.inSessions = inSessions;
		}

		public final Object invoke(TSession session, Object message, int opIndex) throws Exception
        	{
        		for(int i = 0; i < inSessions.length; i++)
        		{
        		if(!session.hasAttribute(inSessions[i]))
        		{throw new Exception("属性" + inSessions[i] + "不在Session当中");}
        		}
        		bean.sayHello(session,(com.ilivoo.common.socket.Message)message, opIndex);
        		return null;
        	}
        }

     * @param definition
     * @return
     * @throws Exception
     */
    public static IMessageInvoke createMessageInvoke(MessageInvokeDefinition definition) throws Exception {
	Object bean = definition.getBean();
	String beanName = bean.getClass().getCanonicalName();
	Method method = definition.getMethod();
	String methodName = method.getName();
	Class<?> messageClz = definition.getMessageClz();
	String[] inSessions = definition.getInSessions();
	String stringArrayName = String[].class.getCanonicalName();
	CtClass ctClass = buildCtClass(IMessageInvoke.class);
	CtField field = new CtField(pool.get(beanName), "bean", ctClass);
	field.setModifiers(Modifier.PRIVATE);
	ctClass.addField(field);
	CtField field2 = new CtField(pool.get(stringArrayName), "inSessions", ctClass);
	field.setModifiers(Modifier.PRIVATE);
	ctClass.addField(field2);

	CtConstructor constructor = new CtConstructor(new CtClass[] { pool.get(beanName), pool.get(stringArrayName) }, ctClass);
	constructor.setBody("{this.bean=$1;this.inSessions=$2;}");
	constructor.setModifiers(Modifier.PUBLIC);
	ctClass.addConstructor(constructor);

	CtMethod invokeMethod = new CtMethod(pool.get(Object.class.getCanonicalName()), "invoke",
		pool.get(new String[] { TSession.class.getCanonicalName(), Object.class.getCanonicalName(),
			int.class.getCanonicalName() }),
		ctClass);
	invokeMethod.setExceptionTypes(new CtClass[]{pool.get(Exception.class.getCanonicalName())});
	invokeMethod.setModifiers(Modifier.PUBLIC + Modifier.FINAL);
	boolean noReturn = method.getReturnType().equals(void.class);
	StringBuilder sb = new StringBuilder();
	sb.append("{");
	//for(String attr : inSessions){} --这种形式不支持, 这里可以直接抛出一个没有权限的异常
//	sb.append("for(int i = 0; i < inSessions.length; i++){if(!$1.hasAttribute(inSessions[i])) {throw new Exception(\"属性\" + inSessions[i] + \"不在Session当中\");}}");
	sb.append("for(int i = 0; i < inSessions.length; i++){if(!$1.hasAttribute(inSessions[i])) {throw new com.ilivoo.common.socket.exception.ManagedException(com.ilivoo.common.socket.exception.SocketManagedErrorCode.NO_PERMISSION, com.ilivoo.common.socket.exception.SocketManagedErrorCode.NO_PERMISSION_MESSAGE + \", 属性\" + inSessions[i] + \"不在Session当中\");}}");
	if (noReturn) {
	    switch (definition.getType()) {
	    case INDEX:
		sb.append("bean." + methodName + "($1,(" + messageClz.getCanonicalName() + ")$2, $3);");
		break;
	    case NOINDEX:
		sb.append("bean." + methodName + "($1,(" + messageClz.getCanonicalName() + ")$2);");
		break;
	    }
	    sb.append("return null;");
	} else {
	    switch (definition.getType()) {
	    case INDEX:
		sb.append("return bean." + methodName + "($1,(" + messageClz.getCanonicalName() + ")$2, $3);");
		break;
	    case NOINDEX:
		sb.append("return bean." + methodName + "($1,(" + messageClz.getCanonicalName() + ")$2);");
		break;
	    }
	}
	sb.append("}");
	invokeMethod.setBody(sb.toString());
	ctClass.addMethod(invokeMethod);
	System.out.println(ctClass);
	Class<?> rClz = ctClass.toClass();
	Constructor<?> con = rClz.getConstructor(bean.getClass(), String[].class);
	IMessageInvoke iMessageInvoke = (IMessageInvoke) con.newInstance(bean, inSessions);
	return iMessageInvoke;
    }

    private static CtClass buildCtClass(Class<?> clz) throws Exception {
	CtClass result = pool.makeClass(clz.getSimpleName() + "Enhance" + index.incrementAndGet());
	result.addInterface(pool.get(clz.getCanonicalName()));
	return result;
    }
}


text:
"""
A module to centralize logging settings.
"""

import os, sys, logging, datetime, inspect, traceback

LOGGING_ROOT = '/var/log/analyticobjects'

class TermColor:
	HEADER = '\033[95m'
	OKBLUE = '\033[94m'
	OKGREEN = '\033[92m'
	WARNING = '\033[93m'
	FAIL = '\033[91m'
	ENDC = '\033[0m'
	BOLD = '\033[1m'
	UNDERLINE = '\033[4m'

class Logger:

	@staticmethod
	def introspect_caller():
		"""Climb up the call stack looking for what module is calling this."""
		caller = 'console'
		stack = inspect.stack()
		try:
			for frame in stack:
				module = inspect.getmodule(frame[0])
				if hasattr(module, '__name__'):
					module_name = module.__name__
					if len(module_name) > 1:
						caller = module_name
		except:
			pass
		if caller == '__main__':
			caller = os.path.basename(sys.argv[0]).replace('.py','')
		return caller

	def __init__(self, level = None):
		#print(TermColor.BOLD+'NOTICE:'+TermColor.WARNING+' analyticobjects.util.logger.init called.'+TermColor.ENDC)
		self.datestamp = datetime.datetime.today().date()
		caller = Logger.introspect_caller()
		logr = logging.getLogger(caller)
		logr.handlers = []
		level = level or logging.INFO
		logr.setLevel(level)
		formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
		filepath = os.path.join(LOGGING_ROOT, caller)
		datestr = datetime.datetime.strftime(self.datestamp, '%Y%m%d')
		filename = caller + '_' + datestr + '.log'
		try:
			os.makedirs(filepath)
		except:
			pass
		logpath = os.path.join(filepath, filename)
		filehandler = logging.FileHandler(logpath)
		filehandler.setFormatter(formatter)
		logr.addHandler(filehandler)
		consolehandler = logging.StreamHandler()
		consolehandler.setLevel(level)
		consolehandler.setFormatter(formatter)
		logr.addHandler(consolehandler)
		self.logr = logr

	def info(self, msg):
		self.logr.info(str(msg))

	def debug(self, msg):
		self.logr.debug(TermColor.OKBLUE+str(msg)+TermColor.ENDC)

	def warn(self, msg):
		self.logr.warn(TermColor.WARNING+str(msg)+TermColor.ENDC)

	def error(self, msg):
		self.logr.error(TermColor.FAIL+str(msg)+TermColor.ENDC)

	def critical(self, msg):
		self.logr.critical(TermColor.FAIL+str(msg)+TermColor.ENDC)

	def exception(self, ex, msg = 'EXCEPTION:'):
		self.logr.critical(TermColor.BOLD+TermColor.FAIL+'\n!************EXCEPTION-BEGIN***************!\n'+TermColor.ENDC)
		self.logr.critical(TermColor.WARNING+'ExceptionMessage: '+str(msg)+TermColor.ENDC)
		self.logr.critical(TermColor.WARNING+'ExceptionType: '+str(type(ex))+TermColor.ENDC)
		self.logr.critical(TermColor.WARNING+'Exception: '+str(ex)+TermColor.ENDC)
		self.logr.critical(TermColor.BOLD+TermColor.OKGREEN+'Exception Details:'+TermColor.ENDC)
		self.logr.critical(TermColor.BOLD+TermColor.OKGREEN+traceback.format_exc()+TermColor.ENDC)
		self.logr.critical(TermColor.OKBLUE+'Stack Traceback:'+TermColor.ENDC)
		for stackframe in traceback.format_stack():
			self.logr.critical(TermColor.OKBLUE+stackframe.replace('\n','')+TermColor.ENDC)
		local_vars = inspect.trace()[-1][0].f_locals
		self.logr.critical(TermColor.WARNING+'Local variables:'+TermColor.ENDC)
		for lvar in local_vars:
			self.logr.critical(TermColor.WARNING+'%s:\n\t%s' % (str(lvar), str(local_vars[lvar]))+TermColor.ENDC)
		self.logr.critical(TermColor.BOLD+TermColor.FAIL+'\n!************EXCEPTION-END*****************!\n'+TermColor.ENDC)

_logr = Logger()

def rollover():
	global _logr
	today = datetime.datetime.today().date()
	if today != _logr.datestamp:
		_logr = Logger()

def pre():
	rollover()
	env_level = os.getenv('LOGGING_LEVEL')
	if env_level:
		if env_level == 'CRITICAL':
			_logr.logr.setLevel(logging.CRITICAL)
		elif env_level == 'ERROR':
			_logr.logr.setLevel(logging.ERROR)
		elif env_level == 'WARNING':
			_logr.logr.setLevel(logging.WARNING)
		elif env_level == 'INFO':
			_logr.logr.setLevel(logging.INFO)
		elif env_level == 'DEBUG':
			_logr.logr.setLevel(logging.DEBUG)
		elif env_level == 'NOTSET':
			_logr.logr.setLevel(logging.NOTSET)

def info(msg):
	pre()
	_logr.info(msg)

def debug(msg):
	pre()
	_logr.debug(msg)

def warn(msg):
	pre()
	_logr.warn(msg)

def error(msg):
	pre()
	_logr.error(msg)

def critical(msg):
	pre()
	_logr.critical(msg)

def exception(ex, msg = 'EXCEPTION:'):
	pre()
	_logr.exception(ex, msg)


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">
<title>Uses of Class org.apache.commons.codec.StringEncoderComparator (neohabitat 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2017-01-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.commons.codec.StringEncoderComparator

No usage of org.apache.commons.codec.StringEncoderComparator

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2017. All rights reserved.


text:
import { Component, OnInit, Input } from '@angular/core';

export interface ColumnClass {
  label: string;
  value: string;
}

@Component({
  selector: 'msp-review-part',
  templateUrl: './review-part.component.html',
  styleUrls: ['./review-part.component.scss']
})
export class ReviewPartComponent implements OnInit {
  @Input() label: string;
  @Input() value: string;
  @Input() columnClass: ColumnClass;
  @Input() underlineLabel: boolean = false;

  _defaultColumnClass: ColumnClass = {label: 'col-6', value: 'col-6'};

  constructor() {}

  ngOnInit() {
    if (this.columnClass) {
      Object.keys(this.columnClass).map(x => this._defaultColumnClass[x] = this.columnClass[x]);
    }
  }
}


text:
/**
 * Javascript library that sets up event handling for the confirmation
 * button that saves user information to the database.
 */

function Confirmer() {
    var URL = "/confirm.json";

    this.confirmationButtonEventHandler = function(event) {
        /**
         * An event-handling function that requests a view to
         * submit the user's information to the database.
         */

        $.ajax({
            url: URL,
            type: "GET",
            dataType: 'json',
            success: function(data) {
                if (data["success"] == true) {
                    $("#confirmation_popup").modal({show: true});
                    $("#confirmation_header").html("
It is done!
");
                    $("#confirmation_body").html("
Congratulations! Your pattern is going to the display!
" +
                        "
See you there!
");
                    $("#confirmation_footer").html("Done!");
                } else {
                    $("#confirmation_popup").modal({show: true});
                    $("#confirmation_header").html("
Uh-oh!
");
                    $("#confirmation_body").html("
There seems to have been a problem along the way.
" +
                        "
" + data["failure_message"] + "
");
                    $("#confirmation_footer").html("<button type='button' class='btn btn-default' data-dismiss='modal'>Go Back</button>");
                }
            },
            error: function() {
                $.getScript('static/js/create/ajaxError.js', alertOpenHandler());
                $("#error_alert").css("top", "5%").css("left", "3%");
                $("#error_content").html("
An issue occurred while connecting with the server. Please try again.
");
            }
        });
    }
}


text:
package com.atlassian.plugins.codegen.modules.jira;

import java.io.File;
import java.util.List;
import java.util.regex.Matcher;

import com.atlassian.plugins.codegen.AbstractCodegenTestCase;
import com.atlassian.plugins.codegen.modules.PluginModuleLocation;
import com.atlassian.plugins.codegen.modules.common.Resource;

import org.dom4j.Document;
import org.dom4j.Node;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * @since 3.6
 */
public class CustomFieldSearcherTest extends AbstractCodegenTestCase<CustomFieldSearcherProperties>
{
    public static final String PACKAGE_NAME = "com.atlassian.plugins.jira.customfields";
    public static final String XPATH_RESOURCE = "/atlassian-plugin/*//resource";
    public static final String XPATH_PARAM_RELATIVE = "param";

    @Before
    public void runGenerator() throws Exception
    {
        setCreator(new CustomFieldSearcherModuleCreator());
        setModuleLocation(new PluginModuleLocation.Builder(srcDir)
                .resourcesDirectory(resourcesDir)
                .testDirectory(testDir)
                .templateDirectory(templateDir)
                .build());

        setProps(new CustomFieldSearcherProperties(PACKAGE_NAME + ".MyCustomFieldSearcher"));
        props.setIncludeExamples(false);
    }

    @Test
    public void allFilesAreGenerated() throws Exception
    {
        setProps(new CustomFieldSearcherProperties("com.atlassian.SomeBuiltInSearcher"));
        props.setIncludeExamples(false);

        creator.createModule(moduleLocation, props);
        String packagePath = "com.atlassian".replaceAll("\\.", Matcher.quoteReplacement(File.separator));

        assertFalse("main class was generated", new File(srcDir, packagePath + File.separator + "SomeBuiltInSearcher.java").exists());
        assertFalse("test class was generated", new File(testDir, packagePath + File.separator + "SomeBuiltInSearcherTest.java").exists());
        assertTrue("plugin.xml not generated", new File(resourcesDir, "atlassian-plugin.xml").exists());

    }

    @Test
    public void allFilesAreGeneratedWithCustomClass() throws Exception
    {
        props.setGenerateClass(true);

        creator.createModule(moduleLocation, props);

        String packagePath = PACKAGE_NAME.replaceAll("\\.", Matcher.quoteReplacement(File.separator));
        assertTrue("main class not generated", new File(srcDir, packagePath + File.separator + "MyCustomFieldSearcher.java").exists());
        assertTrue("test class not generated", new File(testDir, packagePath + File.separator + "MyCustomFieldSearcherTest.java").exists());
        assertTrue("plugin.xml not generated", new File(resourcesDir, "atlassian-plugin.xml").exists());
    }

    @Test
    public void moduleIsValid() throws Exception
    {

        String xpath = "/atlassian-plugin/customfield-searcher[@name='My Custom Field Searcher' and @key='my-custom-field-searcher' and @i18n-name-key='my-custom-field-searcher.name' and @class='" + PACKAGE_NAME + ".MyCustomFieldSearcher']";

        creator.createModule(moduleLocation, props);
        Document pluginDoc = getXmlDocument(pluginXml);

        assertNotNull("valid customfield-searcher not found", pluginDoc.selectSingleNode(xpath));
    }

    @Test
    public void moduleHasValidCustomField() throws Exception
    {
        props.setValidCustomFieldPackage("com.atlassian.customfields");
        props.setValidCustomFieldKey("some-searcher");

        String xpath = "/atlassian-plugin/customfield-searcher/valid-customfield-type[@package='com.atlassian.customfields' and @key='some-searcher']";

        creator.createModule(moduleLocation, props);
        Document pluginDoc = getXmlDocument(pluginXml);

        assertNotNull("valid custom field not found", pluginDoc.selectSingleNode(xpath));
    }

    @Test
    public void singleResourceAdded() throws Exception
    {
        Resource resource = new Resource();
        resource.setName("style.css");
        resource.setLocation("com/example/plugin/style.css");
        resource.setType("download");

        props.getResources()
                .add(resource);

        creator.createModule(moduleLocation, props);

        Document pluginDoc = getXmlDocument(pluginXml);
        List<Node> resourceList = pluginDoc.selectNodes(XPATH_RESOURCE);

        assertEquals("expected single resource", 1, resourceList.size());

        String nodeXpath = "//resource[@name='style.css' and @location='com/example/plugin/style.css' and @type='download']";
        assertNotNull("single resource not found", pluginDoc.selectSingleNode(nodeXpath));

    }

    @Test
    public void singleResourceNamePatternAdded() throws Exception
    {
        Resource resource = new Resource();
        resource.setNamePattern("*.css");
        resource.setLocation("com/example/plugin/style.css");
        resource.setType("download");

        props.getResources()
                .add(resource);

        creator.createModule(moduleLocation, props);

        Document pluginDoc = getXmlDocument(pluginXml);
        List<Node> resourceList = pluginDoc.selectNodes(XPATH_RESOURCE);

        assertEquals("expected single resource", 1, resourceList.size());

        String nodeXpath = "//resource[@namePattern='*.css' and @location='com/example/plugin/style.css' and @type='download']";
        assertNotNull("single resource not found", pluginDoc.selectSingleNode(nodeXpath));

    }

    @Test
    public void nameChosenOverPattern() throws Exception
    {
        Resource resource = new Resource();
        resource.setName("style.css");
        resource.setNamePattern("*.css");
        resource.setLocation("com/example/plugin/style.css");
        resource.setType("download");

        props.getResources()
                .add(resource);

        creator.createModule(moduleLocation, props);

        Document pluginDoc = getXmlDocument(pluginXml);
        List<Node> resourceList = pluginDoc.selectNodes(XPATH_RESOURCE);

        assertEquals("expected single resource", 1, resourceList.size());

        String nodeXpath = "//resource[not(@namePattern) and @name='style.css' and @location='com/example/plugin/style.css' and @type='download']";
        assertNotNull("single resource not found", pluginDoc.selectSingleNode(nodeXpath));

    }

    @Test
    public void resourceParamsAdded() throws Exception
    {
        Resource resource = new Resource();
        resource.setName("style.css");
        resource.setLocation("com/example/plugin/style.css");
        resource.setType("download");
        resource.getParams()
                .put("content-type", "text/css");
        resource.getParams()
                .put("awesome", "me");

        props.getResources()
                .add(resource);

        creator.createModule(moduleLocation, props);

        Document pluginDoc = getXmlDocument(pluginXml);
        List<Node> resourceList = pluginDoc.selectNodes(XPATH_RESOURCE);

        assertEquals("expected single resource", 1, resourceList.size());

        String nodeXpath = "//resource[not(@namePattern) and @name='style.css' and @location='com/example/plugin/style.css' and @type='download']";
        Node resourceNode = pluginDoc.selectSingleNode(nodeXpath);

        List<Node> paramList = resourceNode.selectNodes(XPATH_PARAM_RELATIVE);
        assertEquals("expected resource params", 2, paramList.size());

        assertNotNull("missing content param", resourceNode.selectSingleNode("param[@name='content-type' and @value='text/css']"));
        assertNotNull("missing awesome param", resourceNode.selectSingleNode("param[@name='awesome' and @value='me']"));

    }

    @Test
    public void multipleResourcesAdded() throws Exception
    {
        Resource resource = new Resource();
        resource.setName("style.css");
        resource.setLocation("com/example/plugin/style.css");
        resource.setType("download");
        resource.getParams()
                .put("content-type", "text/css");
        resource.getParams()
                .put("awesome", "me");

        Resource resource2 = new Resource();
        resource2.setName("custom.js");
        resource2.setLocation("com/example/plugin/custom.js");
        resource2.setType("download");

        props.getResources()
                .add(resource);
        props.getResources()
                .add(resource2);

        creator.createModule(moduleLocation, props);

        Document pluginDoc = getXmlDocument(pluginXml);
        List<Node> resourceList = pluginDoc.selectNodes(XPATH_RESOURCE);

        assertEquals("expected multiple resources", 2, resourceList.size());

        String nodeXpath = "//resource[not(@namePattern) and @name='style.css' and @location='com/example/plugin/style.css' and @type='download']";
        String node2Xpath = "//resource[not(@namePattern) and @name='custom.js' and @location='com/example/plugin/custom.js' and @type='download']";

        assertNotNull("missing css resource", pluginDoc.selectSingleNode(nodeXpath));
        assertNotNull("missing js resource", pluginDoc.selectSingleNode(node2Xpath));

    }

}


text:
CREATE SCHEMA FMDR AUTHORIZATION DBA
CREATE SEQUENCE fmdr.asset_id_seq


text:
require 'spec_helper'

describe Grape::Formatter::Jbuilder do
  let(:object)   { double }
  let(:env)      { {'api.endpoint' => endpoint, 'api.tilt.root' => '/tmp'} }
  let(:endpoint) { double :options => {} }
  let(:renderer) { double :render  => '' }

  before :each do
    Grape::Jbuilder::Renderer.stub :new => renderer

    endpoint.options[:route_options] = {:jbuilder => 'user'}
  end

  describe '.call' do
    it "passes the call to the Json render if no template is provided" do
      endpoint.options.clear

      expect(Grape::Formatter::Json).to receive(:call).with(object, env)

      Grape::Formatter::Jbuilder.call object, env
    end

    it "creates a renderer with the root and template" do
      expect(Grape::Jbuilder::Renderer).to receive(:new).with('/tmp', 'user').
        and_return(renderer)

      Grape::Formatter::Jbuilder.call object, env
    end

    it "accepts templates in the env hash" do
      env['api.tilt.template'] = 'foo'

      expect(Grape::Jbuilder::Renderer).to receive(:new).with('/tmp', 'foo').
        and_return(renderer)

      Grape::Formatter::Jbuilder.call object, env
    end

    it "passes the endpoint in as the render scope" do
      expect(renderer).to receive(:render).with(endpoint, {}).and_return('')

      Grape::Formatter::Jbuilder.call object, env
    end

    it "accepts custom locals for the render call" do
      env['api.tilt.locals'] = {:foo => :bar}

      expect(renderer).to receive(:render).with(endpoint, {:foo => :bar}).
        and_return('')

      Grape::Formatter::Jbuilder.call object, env
    end
  end
end


text:
import {
  NgModule,
  Component
} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

@Component({
  selector: 'reddit',
  template: `
    <form class="ui large form segment">

Add a Link

        Title:
        <input name="title">

        Link:
        <input name="link">

    </form>
  `
})
class RedditApp { }

@NgModule({
  declarations: [
    RedditApp
  ],
  imports: [ BrowserModule ],
  bootstrap: [ RedditApp ]
})
class RedditAppModule {}

platformBrowserDynamic().bootstrapModule(RedditAppModule);


text:
package com.zuehlke.carrera.api;

import com.zuehlke.carrera.api.client.Client;
import com.zuehlke.carrera.api.client.MessageReceiver;

class Subscription {
    private final String channelName;
    private final MessageReceiver receiver;

    public Subscription(String channelName, MessageReceiver receiver) {
        this.channelName = channelName;
        this.receiver = receiver;
    }

    public void subscribe(Client client) {
        client.subscribe(channelName, receiver);
    }
}


text:
from __future__ import unicode_literals

import json

from django.views.generic import ListView, DeleteView, DetailView, FormView, UpdateView
from django.views.defaults import permission_denied, bad_request
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.urlresolvers import reverse
from django.http import JsonResponse, Http404
from django.shortcuts import redirect

from osf.models.admin_log_entry import (
    update_admin_log,
    ACCEPT_PREREG,
    REJECT_PREREG,
    COMMENT_PREREG,
    CHECKOUT_CHECKUP,
)

from admin.pre_reg import serializers
from admin.pre_reg.forms import DraftRegistrationForm
from framework.exceptions import PermissionsError
from osf.exceptions import NodeStateError

from osf.models import (
    BaseFileNode,
    DraftRegistration,
    RegistrationSchema,
    Node,
    OSFUser,
)
from website.project.metadata.schemas import from_json
from website.prereg.utils import get_prereg_schema

SORT_BY = {
    'initiator': 'initiator__fullname',
    'n_initiator': '-initiator__fullname',
    'title': 'branched_from__title',
    'n_title': '-branched_from__title',
    'date': 'approval__initiation_date',
    'n_date': '-approval__initiation_date',
    'state': 'approval__state',
    'n_state': '-approval__state',
}

class DraftListView(PermissionRequiredMixin, ListView):
    template_name = 'pre_reg/draft_list.html'
    ordering = '-approval__initiation_date'
    context_object_name = 'draft'
    permission_required = 'osf.view_prereg'
    raise_exception = True

    def get_queryset(self):
        return DraftRegistration.objects.filter(
            registration_schema=get_prereg_schema(),
            approval__isnull=False,
        ).order_by(self.get_ordering())

    def get_context_data(self, **kwargs):
        query_set = kwargs.pop('object_list', self.object_list)
        page_size = self.get_paginate_by(query_set)
        paginator, page, query_set, is_paginated = self.paginate_queryset(
            query_set, page_size)
        return {
            'drafts': [
                serializers.serialize_draft_registration(d, json_safe=False)
                for d in query_set
            ],
            'page': page,
            'p': self.get_paginate_by(query_set),
            'SORT_BY': SORT_BY,
            'order': self.get_ordering(),
            'status': self.request.GET.get('status', 'all'),
        }

    def get_paginate_by(self, queryset):
        return int(self.request.GET.get('p', 10))

    def get_paginate_orphans(self):
        return int(self.get_paginate_by(None) / 11.0) + 1

    def get_ordering(self):
        return self.request.GET.get('order_by', self.ordering)

class CheckoutCheckupView(PermissionRequiredMixin, DeleteView):
    """ View for button that checks status of all prereg drafts and removes checkouts that lingered beyond approval/rejection"""
    template_name = 'pre_reg/checkout_checkup.html'
    permission_required = 'osf.view_prereg'
    raise_exception = True

    def get_context_data(self, **kwargs):
        context = {}
        context.setdefault('bad_drafts_count', str(self.get_object().count()))
        return super(CheckoutCheckupView, self).get_context_data(**context)

    def get_object(self, queryset=None):
        self.prereg_admins = OSFUser.objects.filter(groups__name='prereg_view')
        self.bad_drafts = DraftRegistration.objects.filter(
            registration_schema=RegistrationSchema.objects.get(name='Prereg Challenge', schema_version=2),
            approval__state__in=['approved', 'rejected'],
            branched_from__files__checkout__in=self.prereg_admins
        ).distinct().values_list('id', flat=True)
        return self.bad_drafts

    def delete(self, request, *args, **kwargs):
        if not self.get('bad_drafts', None):
            self.get_object()

        for draft_id in self.bad_drafts:
            draft = DraftRegistration.objects.get(id=draft_id)
            for draft_file in draft.branched_from.files.filter(checkout__in=self.prereg_admins):
                draft_file.checkout = None
                draft_file.save()

            update_admin_log(
                user_id=self.request.user.id,
                object_id=draft.branched_from._id,
                object_repr='Node',
                message='Cleared Prereg checkouts from {}'.format(draft.branched_from._id),
                action_flag=CHECKOUT_CHECKUP
            )
        return redirect(reverse('pre_reg:prereg'))

class DraftDetailView(PermissionRequiredMixin, DetailView):
    template_name = 'pre_reg/draft_detail.html'
    context_object_name = 'draft'
    permission_required = 'osf.view_prereg'
    raise_exception = True

    def get_object(self, queryset=None):
        draft = DraftRegistration.objects.select_related('approval').get(_id=self.kwargs.get('draft_pk'))
        self.checkout_files(draft)
        try:
            return serializers.serialize_draft_registration(draft)
        except AttributeError:
            raise Http404('{} with id "{}" not found.'.format(
                self.context_object_name.title(),
                self.kwargs.get('draft_pk')
            ))

    def checkout_files(self, draft):
        # Do not check out files if rejected or approved
        if not draft.approval or draft.approval.state == 'unapproved':
            prereg_user = self.request.user
            for item in get_metadata_files(draft):
                item.checkout = prereg_user
                item.save()

class DraftFormView(PermissionRequiredMixin, FormView):
    template_name = 'pre_reg/draft_form.html'
    form_class = DraftRegistrationForm
    context_object_name = 'draft'
    permission_required = 'osf.view_prereg'
    raise_exception = True

    def dispatch(self, request, *args, **kwargs):
        self.draft = DraftRegistration.load(self.kwargs.get('draft_pk'))
        if self.draft is None:
            raise Http404('{} with id "{}" not found.'.format(
                self.context_object_name.title(),
                self.kwargs.get('draft_pk')
            ))
        return super(DraftFormView, self).dispatch(request, *args, **kwargs)

    def get_initial(self):
        flags = self.draft.flags
        self.initial = {
            'notes': self.draft.notes,
            'assignee': flags.get('assignee'),
            'payment_sent': flags.get('payment_sent'),
            'proof_of_publication': flags.get('proof_of_publication'),
        }
        return super(DraftFormView, self).get_initial()

    def get_context_data(self, **kwargs):
        kwargs.setdefault('draft', serializers.serialize_draft_registration(
            self.draft,
            json_safe=False
        ))
        kwargs.setdefault('IMMEDIATE', serializers.IMMEDIATE)
        return super(DraftFormView, self).get_context_data(**kwargs)

    def form_valid(self, form):
        if 'approve_reject' in form.changed_data:
            osf_user = self.request.user
            try:
                if form.cleaned_data.get('approve_reject') == 'approve':
                    flag = ACCEPT_PREREG
                    message = 'Approved'
                    self.draft.approve(osf_user)
                else:
                    flag = REJECT_PREREG
                    message = 'Rejected'
                    self.draft.reject(osf_user)
            except PermissionsError as e:
                return permission_denied(self.request, e)
            self.checkin_files(self.draft)
            update_admin_log(self.request.user.id, self.kwargs.get('draft_pk'),
                             'Draft Registration', message, flag)
        admin_settings = form.cleaned_data
        self.draft.notes = admin_settings.get('notes', self.draft.notes)
        del admin_settings['approve_reject']
        del admin_settings['notes']
        self.draft.flags = admin_settings
        self.draft.save()
        return super(DraftFormView, self).form_valid(form)

    def checkin_files(self, draft):
        for item in get_metadata_files(draft):
            item.checkout = None
            item.save()

    def get_success_url(self):
        return '{}?page={}'.format(reverse('pre_reg:prereg'),
                                   self.request.POST.get('page', 1))

class CommentUpdateView(PermissionRequiredMixin, UpdateView):
    context_object_name = 'draft'
    permission_required = ('osf.view_prereg', 'osf.administer_prereg')
    raise_exception = True

    def get_object(self, *args, **kwargs):
        return DraftRegistration.load(self.kwargs.get('draft_pk'))

    def post(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body).get('schema_data', {})
            draft = DraftRegistration.load(self.kwargs.get('draft_pk'))
            draft.update_metadata(data)
            draft.save()
            log_message = list()
            for key, value in data.items():
                comments = data.get(key, {}).get('comments', [])
                for comment in comments:
                    log_message.append('{}: {}'.format(key, comment['value']))
            update_admin_log(
                user_id=request.user.id,
                object_id=draft._id,
                object_repr='Draft Registration',
                message='Comments:
{}
'.format('

'.join(log_message)),
                action_flag=COMMENT_PREREG
            )
            return JsonResponse(serializers.serialize_draft_registration(draft))
        except AttributeError:
            raise Http404('{} with id "{}" not found.'.format(
                self.context_object_name.title(),
                self.kwargs.get('draft_pk')
            ))
        except NodeStateError as e:
            return bad_request(request, e)

def view_file(request, node_id, provider, file_id):
    fp = BaseFileNode.load(file_id)
    wb_url = fp.generate_waterbutler_url()
    return redirect(wb_url)

def get_metadata_files(draft):
    data = draft.registration_metadata
    for q, question in get_file_questions('prereg-prize.json'):
        if not isinstance(data[q]['value'], dict):
            for i, file_info in enumerate(data[q]['extra']):
                provider = file_info['data']['provider']
                if provider != 'osfstorage':
                    raise Http404(
                        'File does not exist in OSFStorage ({}: {})'.format(
                            q, question
                        ))
                file_guid = file_info.get('fileId')
                if not file_guid:
                    node = Node.load(file_info.get('nodeId'))
                    path = file_info['data'].get('path')
                    item = BaseFileNode.resolve_class(
                        provider,
                        BaseFileNode.FILE
                    ).get_or_create(node, path)
                    file_guid = item.get_guid(create=True)._id
                    data[q]['extra'][i]['fileId'] = file_guid
                    draft.update_metadata(data)
                    draft.save()
                else:
                    item = BaseFileNode.load(file_info['data']['path'].replace('/', ''))
                if item is None:
                    raise Http404(
                        'File with guid "{}" in "{}" does not exist'.format(
                            file_guid, question
                        ))
                yield item
            continue
        for i, file_info in enumerate(data[q]['value']['uploader']['extra']):
            provider = file_info['data']['provider']
            if provider != 'osfstorage':
                raise Http404(
                    'File does not exist in OSFStorage ({}: {})'.format(
                        q, question
                    ))
            file_guid = file_info.get('fileId')
            if not file_guid:
                node = Node.load(file_info.get('nodeId'))
                path = file_info['data'].get('path')
                item = BaseFileNode.resolve_class(
                    provider,
                    BaseFileNode.FILE
                ).get_or_create(node, path)
                file_guid = item.get_guid(create=True)._id
                data[q]['value']['uploader']['extra'][i]['fileId'] = file_guid
                draft.update_metadata(data)
                draft.save()
            else:
                item = BaseFileNode.load(file_info['data']['path'].replace('/', ''))
            if item is None:
                raise Http404(
                    'File with guid "{}" in "{}" does not exist'.format(
                        file_guid, question
                    ))
            yield item

def get_file_questions(json_file):
    uploader = {
        'id': 'uploader',
        'type': 'osf-upload',
        'format': 'osf-upload-toggle'
    }
    questions = []
    schema = from_json(json_file)
    for item in schema['pages']:
        for question in item['questions']:
            if question['type'] == 'osf-upload':
                questions.append((question['qid'], question['title']))
                continue
            properties = question.get('properties')
            if properties is None:
                continue
            if uploader in properties:
                questions.append((question['qid'], question['title']))
    return questions


text:
package com.mmnaseri.dragonfly.annotations;

import com.mmnaseri.dragonfly.data.impl.Reference;

/**
 * This enum holds different parameter modes.
 *
 * @author Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (2013/9/10, 0:33)
 */
public enum ParameterMode {

    /**
     * The parameter's value will be read by the procedure
     */
    IN,
    /**
     * The procedure will write, as part of its output, into the specified
     * variable. The argument passed for this parameter must be of type
     * {@link Reference}
     */
    OUT,
    /**
     * The procedure will read the argument value and pass output data into
     * the parameter. The argument passed for this parameter must be of type
     * {@link Reference}
     */
    IN_OUT

}