text:
/**
 * thrift - a lightweight cross-language rpc/serialization tool
 *
 * This file contains the main compiler engine for Thrift, which invokes the
 * scanner/parser to build the thrift object tree. The interface generation
 * code for each language lives in a file by the language name under the
 * generate/ folder, and all parse structures live in parse/
 *
 */

#ifndef _WIN32
#  include <unistd.h>
#endif
#include <ctime>

#include <thrift/compiler/generate/t_generator.h>
#include <thrift/compiler/mutator.h>
#include <thrift/compiler/platform.h>
#include <thrift/compiler/validator.h>

/**
 * Flags to control code generation
 */
bool gen_cpp = false;
bool gen_dense = false;
bool gen_java = false;
bool gen_javabean = false;
bool gen_rb = false;
bool gen_py = false;
bool gen_py_newstyle = false;
bool gen_php = false;
bool gen_phpi = false;
bool gen_phps = true;
bool gen_phpa = false;
bool gen_phpo = false;
bool gen_rest = false;
bool gen_perl = false;
bool gen_erl = false;
bool gen_ocaml = false;
bool gen_hs = false;
bool gen_cocoa = false;
bool gen_csharp = false;
bool gen_st = false;
bool gen_recurse = false;

ofstream genfile_file;
bool record_genfiles = false;

/**
 * Diplays the usage message and then exits with an error code.
 */
[[noreturn]] static void usage() {
  fprintf(stderr, "Usage: thrift [options] file\n");
  fprintf(stderr, "Options:\n");
  fprintf(stderr, "  -o dir      Set the output directory for gen-* packages\n");
  fprintf(stderr, "               (default: current directory)\n");
  fprintf(stderr, "  -out dir    Set the output location for generated files\n");
  fprintf(stderr, "  --templates dir    Set the directory containing mstch templates\n");
  fprintf(stderr, "               (no gen-* folder will be created)\n");
  fprintf(stderr, "  -I dir      Add a directory to the list of directories\n");
  fprintf(stderr, "                searched for include directives\n");
  fprintf(stderr, "  -nowarn     Suppress all compiler warnings (BAD!)\n");
  fprintf(stderr, "  -strict     Strict compiler warnings on\n");
  fprintf(stderr, "  -v[erbose]  Verbose mode\n");
  fprintf(stderr, "  -r[ecurse]  Also generate included files\n");
  fprintf(stderr, "  -debug      Parse debug trace to stdout\n");
  fprintf(stderr, "  --allow-neg-keys  Allow negative field keys (Used to "
          "preserve protocol\n");
  fprintf(stderr, "                compatibility with older .thrift files)\n");
  fprintf(stderr, "  --allow-neg-enum-vals Allow negative enum vals\n");
  fprintf(stderr, "  --allow-64bit-consts  Do not print warnings about using 64-bit constants\n");
  fprintf(stderr, "  --gen STR   Generate code with a dynamically-registered generator.\n");
  fprintf(stderr, "                STR has the form language[:key1=val1[,key2,[key3=val3]]].\n");
  fprintf(stderr, "                Keys and values are options passed to the generator.\n");
  fprintf(stderr, "                Many options will not require values.\n");
  fprintf(stderr, "  --record-genfiles FILE\n");
  fprintf(stderr, "              Save the list of generated files to FILE\n");
  fprintf(stderr, "  --python-compiler FILE\n");
  fprintf(
      stderr,
      "              Path to the python implementation of the thrift compiler\n");
  fprintf(stderr, "\n");
  fprintf(stderr, "Available generators (and options):\n");

  t_generator_registry::gen_map_t gen_map = t_generator_registry::get_generator_map();
  t_generator_registry::gen_map_t::iterator iter;
  for (iter = gen_map.begin(); iter != gen_map.end(); ++iter) {
    fprintf(stderr, "  %s (%s):\n",
        iter->second->get_short_name().c_str(),
        iter->second->get_long_name().c_str());
    fprintf(stderr, "%s", iter->second->get_documentation().c_str());
  }
  exit(1);
}

static void preprocess_cpp2_generator_strings(
    std::string& gen_string,
    bool& gen_py_cpp2,
    bool& gen_mstch_cpp2,
    bool& gen_py_cpp2_reflection) {
  // Use cpp2 python generator if only cpp2 is marked
  if (gen_string.find("cpp2") != std::string::npos &&
      gen_string.find("mstch_cpp2") == std::string::npos) {
    gen_py_cpp2 = true;
  }

  // Use cpp2 python generator if mstch_cpp2 and any of these flags are present
  if (gen_string.find("mstch_cpp2") != std::string::npos &&
      (gen_string.find("future") != std::string::npos ||
       gen_string.find("py_generator") != std::string::npos ||
       gen_string.find("fatal") != std::string::npos ||
       gen_string.find("compatibility") != std::string::npos ||
       gen_string.find("implicit_templates") != std::string::npos ||
       gen_string.find("separate_processmap") != std::string::npos ||
       gen_string.find("process_in_event_base") != std::string::npos ||
       gen_string.find("terse_writes") != std::string::npos ||
       gen_string.find("modulemap") != std::string::npos)) {
    gen_py_cpp2 = true;
  }

  // Use mstch_cpp2 generator if gen_py_cpp2 is false and mstch_cpp2 is present
  if (!gen_py_cpp2 && gen_string.find("mstch_cpp2") != std::string::npos) {
    gen_mstch_cpp2 = true;
  }

  // Use mstch_cpp2 and python generator if mstch_cpp2 and reflection present
  if (gen_mstch_cpp2 && gen_string.find("reflection") != std::string::npos) {
    gen_py_cpp2_reflection = true;
  }
}

static bool python_generator(
    std::string& options,
    const std::string& user_python_compiler,
    std::vector<std::string>& arguments) {
  // Attempt to call the new python compiler if we can find it
  string path = arguments[0];
  size_t last = path.find_last_of("/");
  if (last != string::npos) {
    ifstream ifile;
    auto dirname = path.substr(0, last + 1);
    std::string pycompiler;
    std::vector<std::string> pycompilers;
    if (!user_python_compiler.empty()) {
      pycompilers.push_back(user_python_compiler);
    }
    pycompilers.insert(
      pycompilers.end(),
      {
        dirname + "py/thrift.lpar",
        dirname + "../py/thrift.lpar",
        dirname + "py/thrift.par",
        dirname + "../py/thrift.par",
        dirname + "py/thrift.xar",
        dirname + "../py/thrift.xar",
        dirname + "py/thrift.pex",
        dirname + "../py/thrift.pex",
      });
    for (const auto& comp : pycompilers) {
      pycompiler = comp;
      ifile.open(pycompiler.c_str());
      if (ifile) break;
    }
    int ret = 0;
    if (ifile) {
      // Convert arguments to argv
      std::vector<char*> argv(arguments.size() + 1);
      for (size_t i = 0; i < arguments.size(); ++i) {
        if (arguments[i][0] == '-' &&
            arguments[i] != "-I" &&
            arguments[i] != "-o") {
          arguments[i].insert(0, "-");
        }
        argv[i] = const_cast<char *>(arguments[i].c_str());
      }
      argv[arguments.size()] = nullptr;
      ret = execv(pycompiler.c_str(), argv.data());
    }
    if (!ifile || ret < 0) {
      pwarning(
        1,
        "Unable to get a generator for \"%s\" ret: %d.\n",
        options.c_str(),
        ret);
    }
  }
  return true;
}

static void search_and_replace_args(
    std::vector<std::string>& arguments,
    std::string search,
    std::string replace) {
  for (size_t i = 0; i < arguments.size(); ++i) {
    if (arguments[i] == "-gen") {
      auto pos = arguments[i + 1].find(search);
      if (pos != std::string::npos) {
        arguments[i + 1] = arguments[i + 1].replace(
            pos, search.size(), replace);
      }
      break;
    }
  }
}

static bool generate_cpp2(
    t_program* program,
    std::string& gen_string,
    const std::string& user_python_compiler,
    std::vector<std::string>& arguments) {
  bool gen_py_cpp2 = false;
  bool gen_mstch_cpp2 = false;
  bool gen_py_cpp2_reflection = false;
  preprocess_cpp2_generator_strings(
      gen_string,
      gen_py_cpp2,
      gen_mstch_cpp2,
      gen_py_cpp2_reflection);

  if (gen_mstch_cpp2) {
    t_generator* generator =
        t_generator_registry::get_generator(program, gen_string);
    if (generator) {
      pverbose("Generating \"%s\"\n", gen_string.c_str());
      generator->generate_program();
      if (record_genfiles) {
        for (const std::string& s : generator->get_genfiles()) {
          genfile_file << s << "\n";
        }
      }
      delete generator;
    }
  }

  if (gen_py_cpp2 || gen_py_cpp2_reflection) {
    //mstch_cpp2 -> cpp2
    if (gen_mstch_cpp2) {
      search_and_replace_args(arguments, "mstch_cpp2", "cpp2");
    }

    //reflection -> only_reflection
    if (gen_py_cpp2_reflection) {
      search_and_replace_args(arguments, "reflection", "only_reflection");
    }

    python_generator(gen_string, user_python_compiler, arguments);
  }
  return true;
}

/**
 * Generate code
 */
static bool generate(
    t_program* program,
    vector<string>& generator_strings,
    std::set<std::string>& already_generated,
    const std::string& user_python_compiler,
    std::vector<std::string>& arguments) {
  // Oooohh, recursive code generation, hot!!
  if (gen_recurse) {
    const vector<t_program*>& includes = program->get_includes();
    for (const auto& include : includes) {
      if (already_generated.count(include->get_path())) {
        continue;
      }

      // Propogate output path from parent to child programs
      include->set_out_path(
          program->get_out_path(), program->is_out_path_absolute());

      if (!generate(
              include,
              generator_strings,
              already_generated,
              user_python_compiler,
              arguments)) {
        return false;
      } else {
        already_generated.insert(include->get_path());
      }
    }
  }

  // Generate code!
  try {
    pverbose("Program: %s\n", program->get_path().c_str());

    if (dump_docs) {
      dump_docstrings(program);
    }

    for (auto gen_string : generator_strings) {
      auto pos = gen_string.find(":");
      std::string lang = gen_string.substr(0, pos);
      if (lang.find("cpp2") != std::string::npos) {
        generate_cpp2(program, gen_string, user_python_compiler, arguments);
        continue;
      }

      t_generator* generator =
          t_generator_registry::get_generator(program, gen_string);
      if (generator) {
        pverbose("Generating \"%s\"\n", gen_string.c_str());
        generator->generate_program();
        if (record_genfiles) {
          for (const std::string& s : generator->get_genfiles()) {
            genfile_file << s << "\n";
          }
        }
        delete generator;
      }
    }

  } catch (const string& s) {
    printf("Error: %s\n", s.c_str());
    return false;
  } catch (const char* exc) {
    printf("Error: %s\n", exc);
    return false;
  }

  return true;
}

/**
 * Parse it up.. then spit it back out, in pretty much every language. Alright
 * not that many languages, but the cool ones that we care about.
 */
int main(int argc, char** argv) {
  std::string out_path;
  bool out_path_is_absolute = false;
  std::vector<std::string> arguments(argv, argv + argc);

  // Setup time string
  time_t now = time(nullptr);
  g_time_str = ctime(&now);

  // Check for necessary arguments, you gotta have at least a filename and
  // an output language flag
  if (argc < 2) {
    usage();
  }

  std::string user_python_compiler;
  vector<std::string> generator_strings;

  // Set the current path to a dummy value to make warning messages clearer.
  g_curpath = "arguments";

  // Hacky parameter handling... I didn't feel like using a library sorry!
  size_t i;
  for (i = 1; i < arguments.size() - 1; ++i) {

    // Treat double dashes as single dashes
    if (arguments[i][0] == '-' && arguments[i][1] == '-') {
      arguments[i] = arguments[i].replace(0, 1, "");
    }

    if (arguments[i] == "-debug") {
      g_debug = 1;
    } else if (arguments[i] == "-nowarn") {
      g_warn = 0;
    } else if (arguments[i] == "-strict") {
      g_strict = 255;
      g_warn = 2;
    } else if (arguments[i] == "-v" || arguments[i] == "-verbose" ) {
      g_verbose = 1;
    } else if (arguments[i] == "-r" || arguments[i] == "-recurse" ) {
      gen_recurse = true;
    } else if (arguments[i] == "-allow-neg-keys") {
      g_allow_neg_field_keys = true;
    } else if (arguments[i] == "-allow-neg-enum-vals") {
      g_allow_neg_enum_vals = true;
    } else if (arguments[i] == "-allow-64bit-consts") {
      g_allow_64bit_consts = true;
    } else if (arguments[i] == "-record-genfiles") {
      record_genfiles = true;
      if (i + 1 == arguments.size() - 1) {
        fprintf(
            stderr,
            "!!! Missing genfile file specification between %s and '%s'\n",
            arguments[i].c_str(),
            arguments[i + 1].c_str());
        usage();
      }
      genfile_file.open(arguments[++i]);
    } else if (arguments[i] == "-gen") {
      if (i + 1 == arguments.size() - 1) {
        fprintf(
            stderr,
            "!!! Missing generator specification between %s and '%s'\n",
            arguments[i].c_str(),
            arguments[i + 1].c_str());
        usage();
      }
      generator_strings.push_back(arguments[++i]);
    } else if (arguments[i] == "-dense") {
      gen_dense = true;
    } else if (arguments[i] == "-cpp") {
      gen_cpp = true;
    } else if (arguments[i] == "-javabean") {
      gen_javabean = true;
    } else if (arguments[i] == "-java") {
      gen_java = true;
    } else if (arguments[i] == "-php") {
      gen_php = true;
    } else if (arguments[i] == "-phpi") {
      gen_phpi = true;
    } else if (arguments[i] == "-phps") {
      gen_php = true;
      gen_phps = true;
    } else if (arguments[i] == "-phpl") {
      gen_php = true;
      gen_phps = false;
    } else if (arguments[i] == "-phpa") {
      gen_php = true;
      gen_phps = false;
      gen_phpa = true;
    } else if (arguments[i] == "-phpo") {
      gen_php = true;
      gen_phpo = true;
    } else if (arguments[i] == "-rest") {
      gen_rest = true;
    } else if (arguments[i] == "-py") {
      gen_py = true;
    } else if (arguments[i] == "-pyns") {
      gen_py = true;
      gen_py_newstyle = true;
    } else if (arguments[i] == "-rb") {
      gen_rb = true;
    } else if (arguments[i] == "-perl") {
      gen_perl = true;
    } else if (arguments[i] == "-erl") {
      gen_erl = true;
    } else if (arguments[i] == "-ocaml") {
      gen_ocaml = true;
    } else if (arguments[i] == "-hs") {
      gen_hs = true;
    } else if (arguments[i] == "-cocoa") {
      gen_cocoa = true;
    } else if (arguments[i] == "-st") {
      gen_st = true;
    } else if (arguments[i] == "-csharp") {
      gen_csharp = true;
    } else if (arguments[i] == "-cpp_use_include_prefix") {
      g_cpp_use_include_prefix = true;
    } else if (arguments[i] == "-I") {
      if (i + 1 == arguments.size() - 1) {
        fprintf(
            stderr,
            "!!! Missing Include directory between %s and '%s'\n",
            arguments[i].c_str(),
            arguments[i + 1].c_str());
        usage();
      }
      // An argument of "-I\ asdf" is invalid and has unknown results
      g_incl_searchpath.push_back(arguments[++i]);
      continue;
    } else if (arguments[i] == "-templates") {
      if (i + 1 == arguments.size() - 1) {
        fprintf(stderr, "-templates: missing template directory");
        usage();
      }
      g_template_dir = arguments[++i];
      continue;
    } else if (arguments[i] == "-o" || (arguments[i] == "-out")) {
      out_path_is_absolute = (arguments[i] == "-out") ? true : false;
      if (i + 1 == arguments.size() - 1) {
        fprintf(
            stderr,
            "-o: missing output directory between %s and '%s'\n",
            arguments[i].c_str(),
            arguments[i + 1].c_str());
        usage();
      }
      out_path = arguments[++i];

      // Strip out trailing \ on a Windows path
      if (apache::thrift::compiler::isWindows()) {
        int last = out_path.length() - 1;
        if (out_path[last] == '\\') {
          out_path.erase(last);
        }
      }

      struct stat sb;
      if (out_path_is_absolute) {
        // Invoker specified `-out blah`. We are supposed to output directly
        // into blah, e.g. `blah/Foo.java`. Make the directory if necessary,
        // just like how for `-o blah` we make `o/gen-java`
        if (stat(out_path.c_str(), &sb) < 0
            && errno == ENOENT
            && make_dir(out_path.c_str()) < 0) {
          fprintf(
              stderr,
              "Output directory %s is unusable: mkdir: %s\n",
              out_path.c_str(),
              strerror(errno));
          return -1;
        }
      }
      if (stat(out_path.c_str(), &sb) < 0) {
        fprintf(
            stderr,
            "Output directory %s is unusable: %s\n",
            out_path.c_str(),
            strerror(errno));
        return -1;
      }
#       ifndef _WIN32
      if (!S_ISDIR(sb.st_mode)) {
        fprintf(
            stderr,
            "Output directory %s exists but is not a directory\n",
            out_path.c_str());
        return -1;
      }
#       endif
      continue;
    } else if (arguments[i] == "-python-compiler") {
      if (i + 1 == arguments.size() - 1) {
        fprintf(
            stderr,
            "No path was given for the python compiler between "
            "%s and '%s'\n",
            arguments[i].c_str(),
            arguments[i + 1].c_str());
        usage();
      }
      user_python_compiler = arguments[++i];
      continue;
    } else {
      fprintf(stderr, "!!! Unrecognized option: %s\n", arguments[i].c_str());
      usage();
    }
  }

  // TODO(dreiss): Delete these when everyone is using the new hotness.
  if (gen_cpp) {
    pwarning(1, "-cpp is deprecated.  Use --gen cpp");
    string gen_string = "cpp:";
    if (gen_dense) {
      gen_string.append("dense,");
    }
    if (g_cpp_use_include_prefix) {
      gen_string.append("include_prefix,");
    }
    generator_strings.push_back(gen_string);
  }
  if (gen_java) {
    pwarning(1, "-java is deprecated.  Use --gen java");
    generator_strings.push_back("java");
  }
  if (gen_javabean) {
    pwarning(1, "-javabean is deprecated.  Use --gen java:beans");
    generator_strings.push_back("java:beans");
  }
  if (gen_csharp) {
    pwarning(1, "-csharp is deprecated.  Use --gen csharp");
    generator_strings.push_back("csharp");
  }
  if (gen_py) {
    pwarning(1, "-py is deprecated.  Use --gen py");
    generator_strings.push_back("py");
  }
  if (gen_rb) {
    pwarning(1, "-rb is deprecated.  Use --gen rb");
    generator_strings.push_back("rb");
  }
  if (gen_perl) {
    pwarning(1, "-perl is deprecated.  Use --gen perl");
    generator_strings.push_back("perl");
  }
  if (gen_php || gen_phpi) {
    pwarning(1, "-php is deprecated.  Use --gen php");
    string gen_string = "php:";
    if (gen_phpi) {
      gen_string.append("inlined,");
    } else if(gen_phps) {
      gen_string.append("server,");
    } else if(gen_phpa) {
      gen_string.append("autoload,");
    } else if(gen_phpo) {
      gen_string.append("oop,");
    } else if(gen_rest) {
      gen_string.append("rest,");
    }
    generator_strings.push_back(gen_string);
  }
  if (gen_cocoa) {
    pwarning(1, "-cocoa is deprecated.  Use --gen cocoa");
    generator_strings.push_back("cocoa");
  }
  if (gen_erl) {
    pwarning(1, "-erl is deprecated.  Use --gen erl");
    generator_strings.push_back("erl");
  }
  if (gen_st) {
    pwarning(1, "-st is deprecated.  Use --gen st");
    generator_strings.push_back("st");
  }
  if (gen_ocaml) {
    pwarning(1, "-ocaml is deprecated.  Use --gen ocaml");
    generator_strings.push_back("ocaml");
  }
  if (gen_hs) {
    pwarning(1, "-hs is deprecated.  Use --gen hs");
    generator_strings.push_back("hs");
  }

  // You gotta generate something!
  if (generator_strings.empty()) {
    fprintf(stderr, "!!! No output language(s) specified\n\n");
    usage();
  }

  // Real-pathify it
  if (arguments.size() < i) {
    fprintf(stderr, "!!! Missing file name\n");
    usage();
  }

  std::string input_file = compute_absolute_path(arguments[i]);

  // Instance of the global parse tree
  t_program* program = new t_program(input_file);
  if (out_path.size()) {
    program->set_out_path(out_path, out_path_is_absolute);
  }

  // Compute the cpp include prefix.
  // infer this from the filename passed in
  string input_filename = arguments[i];
  string include_prefix;

  string::size_type last_slash = string::npos;
  if ((last_slash = input_filename.rfind("/")) != string::npos) {
    include_prefix = input_filename.substr(0, last_slash);
  }

  program->set_include_prefix(include_prefix);

  // Initialize global types
  g_type_void   = new t_base_type("void",   t_base_type::TYPE_VOID);
  g_type_string = new t_base_type("string", t_base_type::TYPE_STRING);
  g_type_binary = new t_base_type("string", t_base_type::TYPE_STRING);
  ((t_base_type*)g_type_binary)->set_binary(true);
  g_type_slist  = new t_base_type("string", t_base_type::TYPE_STRING);
  ((t_base_type*)g_type_slist)->set_string_list(true);
  g_type_bool   = new t_base_type("bool",   t_base_type::TYPE_BOOL);
  g_type_byte   = new t_base_type("byte",   t_base_type::TYPE_BYTE);
  g_type_i16    = new t_base_type("i16",    t_base_type::TYPE_I16);
  g_type_i32    = new t_base_type("i32",    t_base_type::TYPE_I32);
  g_type_i64    = new t_base_type("i64",    t_base_type::TYPE_I64);
  g_type_double = new t_base_type("double", t_base_type::TYPE_DOUBLE);
  g_type_float  = new t_base_type("float",  t_base_type::TYPE_FLOAT);

  // Parse it!
  g_scope_cache = program->scope();
  std::set<std::string> already_parsed_paths;
  parse(program, already_parsed_paths);

  // Mutate it!
  apache::thrift::compiler::mutator::mutate(program);

  // Validate it!
  auto errors = apache::thrift::compiler::validator::validate(program);
  if (!errors.empty()) {
    for (const auto& error : errors) {
      std::cerr << error << std::endl;
    }
    return 1;
  }

  // The current path is not really relevant when we are doing generation.
  // Reset the variable to make warning messages clearer.
  g_curpath = "generation";
  // Reset yylineno for the heck of it.  Use 1 instead of 0 because
  // That is what shows up during argument parsing.
  yylineno = 1;

  // Generate it!
  bool success;
  try {
    std::set<std::string> already_generated{program->get_path()};
    success = generate(
        program,
        generator_strings,
        already_generated,
        user_python_compiler,
        arguments);
  } catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }

  // Clean up. Who am I kidding... this program probably orphans heap memory
  // all over the place, but who cares because it is about to exit and it is
  // all referenced and used by this wacky parse tree up until now anyways.

  delete program;
  delete g_type_void;
  delete g_type_string;
  delete g_type_bool;
  delete g_type_byte;
  delete g_type_i16;
  delete g_type_i32;
  delete g_type_i64;
  delete g_type_double;
  delete g_type_float;

  // Finished
  if (success) {
    return 0;
  } else {
    return 1;
  }
}


text:
package com.linkedin.pinot.perf;

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

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;

import com.google.common.collect.Lists;
import com.linkedin.pinot.common.metadata.segment.IndexLoadingConfigMetadata;
import com.linkedin.pinot.common.segment.ReadMode;
import com.linkedin.pinot.core.segment.index.loader.Loaders;

public class BitmapIndexCreationBenchmark {

  public static void main(String[] args) throws Exception {

    System.out.println("Starting generation");
    Configuration tableDataManagerConfig = new PropertiesConfiguration();
    List<String> indexColumns = Lists.newArrayList("contract_id", "seat_id");
    tableDataManagerConfig.setProperty(IndexLoadingConfigMetadata.KEY_OF_LOADING_INVERTED_INDEX,
        indexColumns);
    IndexLoadingConfigMetadata indexLoadingConfigMetadata =
        new IndexLoadingConfigMetadata(tableDataManagerConfig);
    ReadMode mode = ReadMode.heap;
    File indexDir = new File(
        "/home/kgopalak/pinot_perf/index_dir/capReportingEvents_OFFLINE/capReportingEvents_capReportingEvents_daily_2");
    long start = System.currentTimeMillis();
    Loaders.IndexSegment.load(indexDir, mode, indexLoadingConfigMetadata);
    long end = System.currentTimeMillis();
    System.out.println("Took " + (end - start) + " to generate bitmap index");
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dp" android:color="#fff">
</stroke>
    <corners android:radius="30dp"/>
    <padding android:bottom="3dp" android:top="3dp" android:left="3dp" android:right="3dp"/>
    <solid android:color="?attr/colorControlHighlight"/>
</shape>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.operator.scalar;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface ScalarFunction
{
    String value() default "";

    String[] alias() default {};

    boolean hidden() default false;

    boolean deterministic() default true;
}


text:
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace VisualObjects.WebService
{
    using System;
    using System.Fabric;
    using System.Threading;

    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                using (FabricRuntime fabricRuntime = FabricRuntime.Create())
                {
                    fabricRuntime.RegisterServiceType(Service.ServiceTypeName, typeof(Service));
                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceHostInitializationFailed(e);
                throw;
            }
        }
    }
}


text:
layout: page
title: Harrington Flex Systems Dinner
date: 2016-05-24
author: Abigail Ball
tags: weekly links, java
status: published
summary: Proin mi libero, ornare in mauris.
banner: images/banner/people.jpg
booking:
  startDate: 06/09/2017
  endDate: 06/10/2017
  ctyhocn: WASSSHX
  groupCode: HFSD
published: true
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eleifend elit orci, at tincidunt erat tempor at. In hac habitasse platea dictumst. Mauris vitae posuere sem. Integer at orci id magna luctus feugiat id blandit sapien. Cras venenatis porta tellus, vel pretium dolor sodales sed. Maecenas congue est libero, hendrerit porttitor quam pharetra sit amet. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed et faucibus tellus. Ut dui sem, scelerisque a nisi a, ultricies semper leo. Aliquam id lectus enim. Mauris vitae tempor justo. Nunc ut nunc in mi mollis bibendum. Pellentesque venenatis nec sem et tincidunt.

* Pellentesque nec nibh ac risus luctus blandit vel quis elit
* Fusce commodo ex vitae nisi commodo ornare
* Vivamus rhoncus nisi ut nulla hendrerit porta sit amet non eros
* Aenean laoreet nibh malesuada magna semper pellentesque
* Nam vulputate ex vel augue volutpat, quis placerat nisl sodales
* Maecenas sollicitudin dui et quam lacinia, a suscipit libero fringilla.

Quisque fermentum ante eget suscipit fringilla. Phasellus enim orci, posuere sed semper sit amet, dapibus et tortor. Praesent auctor tortor vel mauris tincidunt, at auctor lacus varius. Curabitur congue pretium lectus, gravida rhoncus risus aliquet non. Nulla fringilla lacus non augue vestibulum vehicula. Suspendisse in nulla dapibus sem fringilla fermentum. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Curabitur tristique congue mauris eu convallis. Proin dapibus felis arcu, commodo commodo sem tincidunt sed. Praesent quis congue nibh. Vestibulum et aliquam turpis. Nunc eget leo dolor. Suspendisse aliquet nulla eget lacus pulvinar, non blandit nibh vehicula. Nullam nisl libero, interdum ut est sit amet, imperdiet pharetra nulla. Integer porttitor rhoncus congue. Vestibulum nec erat iaculis, posuere quam non, tristique massa. Phasellus non rutrum metus, eget vestibulum lacus.


text:
module.exports = function () {
    this.first = "This is a function message.";
};


text:
<?php

/*# declare(strict_types=1); */

namespace Phossa\Logger\Formatter;

/**
 * FormatterAwareInterface
 *
 * @interface
 * @package Phossa\Logger
 * @author  Hong Zhang <phossa@126.com>
 * @version 1.0.4
 * @since   1.0.0 added
 */
interface FormatterAwareInterface
{
    /**
     * Set formatter
     *
     * @param  callable $formatter
     * @return void
     * @access public
     * @api
     */
    public function setFormatter(callable $formatter);

    /**
     * Get formatter
     *
     * If not set, return the Phossa\Logger\Formatter\DefaultFormatter
     *
     * @return callable
     * @access public
     * @api
     */
    public function getFormatter()/*# : callable */;
}


text:
<!DOCTYPE html>

    <link rel="shortcut icon" href="<?php echo base_url(); ?>public/favicon.ico">
    <link href="<?php echo base_url(); ?>public/css/bootstrap.min.css?v=3.3.5" rel="stylesheet">
    <link href="<?php echo base_url(); ?>public/css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
    <link href="<?php echo base_url(); ?>public/css/plugins/dataTables/dataTables.bootstrap.css" rel="stylesheet">

    <link href="<?php echo base_url(); ?>public/css/animate.min.css" rel="stylesheet">
    <link href="<?php echo base_url(); ?>public/css/style.min.css?v=4.0.0" rel="stylesheet">
    <base target="_blank">

                            编号
                            登录地址
                            登录ip
                            登录时间

                        <?php
                        foreach ($admin_log as $item) {
                            ?>

                                <?php echo $item->loginLog_id ?>
                                <?php echo $item->loginLog_address ?>
                                <?php echo $item->loginLog_IP ?>
                                <?php echo $item->loginLog_time ?>

                            <?php
                        }
                        ?>

<?php echo $admin_info["username"] ?>

                                    个人信息

                                            <?php echo $admin_info["username"] ?> 用户名

                                            <?php echo $admin_info["name"] ?>姓名

                                            <?php echo $admin_info["email"] ?> 邮件地址

                                            <?php echo $admin_info["phone"] ?>电话号码

                                            <?php echo $admin_info["sex"] ?>性别

                                            <?php echo $admin_info["add_time"] ?>注册时间


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using chart_function.Models;
using Xunit;
using Shouldly;

namespace crash_statistics.tests
{
    public class ChartTests
    {
        [Fact]
        public void ChartDataAddsMissingValuesForMultipleSeries()
        {
            var original = new List<Row>
            {
                new Row(1, "a1", "weather"),
                new Row(2, "b1", "weather"),
                new Row(3, "c1", "weather"),
                new Row(11, "a2", "weather")
            };

            var comparison = new List<Row>
            {
                new Row(11, "a2", "weather"),
                new Row(12, "b2", "weather"),
                new Row(2, "b1", "weather")
            };

            var chart = new Chart(new[] {original, comparison}, "node", "pie");

            chart.Categories.ShouldBe(new[] { "a1", "a2", "b1", "b2", "c1" });
            chart.Categories.ShouldBe(chart.Series[0].Data.Select(x => x[0]));
            chart.Categories.ShouldBe(chart.Series[1].Data.Select(x => x[0]));
        }

        [Fact]
        public void ChartDataIsFormattedProperlyForComparisonsAndDispareteGroups()
        {
            var original = new List<Row>
            {
                new Row(1, "a", "weather"),
                new Row(3, "c", "weather"),
                new Row(4, "d", "weather"),
                new Row(5, "e", "weather"),
                new Row(6, "z", "road"),
                new Row(7, "x", "road"),
                new Row(8, "y", "road"),
                new Row(9, "w", "road"),
                new Row(10, "f", "road")
            };

            var comparison = new List<Row>
            {
                new Row(10, "a", "weather"),
                new Row(9, "b", "weather"),
                new Row(8, "c", "weather"),
                new Row(7, "d", "weather"),
                new Row(11, "e", "weather"),
                new Row(12, "z", "road"),
                new Row(13, "x", "road"),
                new Row(14, "y", "road"),
                new Row(16, "f", "road")
            };

            var chart = new Chart(new[] {original, comparison}, "node", "pie");

            chart.Categories.ShouldBe(new[] {"a", "b", "c", "d", "e", "f", "w", "x", "y", "z"});

            chart.Series.First().Type.ShouldBe("pie");
            chart.Series.First().Name.ShouldBe("Original");
            chart.Series.First().Center.ShouldBe(new[] {"20%"});
            chart.Series.First().Data.ShouldBe(new[]
            {
                new ArrayList {"a", 1},
                new ArrayList {"b", 0},
                new ArrayList {"c", 3},
                new ArrayList {"d", 4},
                new ArrayList {"e", 5},
                new ArrayList {"f", 10},
                new ArrayList {"w", 9},
                new ArrayList {"x", 7},
                new ArrayList {"y", 8},
                new ArrayList {"z", 6}
            });

            chart.Series.Last().Name.ShouldBe("Comparison");
            chart.Series.Last().Center.ShouldBe(new[] {"80%"});
            chart.Series.Last().Data.ShouldBe(new[]
            {
                new ArrayList {"a", 10},
                new ArrayList {"b", 9},
                new ArrayList {"c", 8},
                new ArrayList {"d", 7},
                new ArrayList {"e", 11},
                new ArrayList {"f", 16},
                new ArrayList {"w", 0},
                new ArrayList {"x", 13},
                new ArrayList {"y", 14},
                new ArrayList {"z", 12}
            });
        }

        [Fact]
        public void ChartDataIsFormattedProperlyForComparisonsAndMultipleGroups()
        {
            var original = new List<Row>
            {
                new Row(1, "a", "weather"),
                new Row(2, "b", "weather"),
                new Row(3, "c", "weather"),
                new Row(4, "d", "weather"),
                new Row(5, "e", "weather"),
                new Row(6, "z", "road"),
                new Row(7, "x", "road"),
                new Row(8, "y", "road"),
                new Row(9, "w", "road"),
                new Row(10, "f", "road")
            };

            var comparison = new List<Row>
            {
                new Row(10, "a", "weather"),
                new Row(9, "b", "weather"),
                new Row(8, "c", "weather"),
                new Row(7, "d", "weather"),
                new Row(11, "e", "weather"),
                new Row(12, "z", "road"),
                new Row(13, "x", "road"),
                new Row(14, "y", "road"),
                new Row(15, "w", "road"),
                new Row(16, "f", "road")
            };

            var chart = new Chart(new[] {original, comparison}, "node", "pie");

            chart.Categories.ShouldBe(new[] {"a", "b", "c", "d", "e", "f", "w", "x", "y", "z"});

            chart.Series.First().Type.ShouldBe("pie");
            chart.Series.First().Name.ShouldBe("Original");
            chart.Series.First().Center.ShouldBe(new[] {"20%"});
            chart.Series.First().Data.ShouldBe(new[]
            {
                new ArrayList {"a", 1},
                new ArrayList {"b", 2},
                new ArrayList {"c", 3},
                new ArrayList {"d", 4},
                new ArrayList {"e", 5},
                new ArrayList {"f", 10},
                new ArrayList {"w", 9},
                new ArrayList {"x", 7},
                new ArrayList {"y", 8},
                new ArrayList {"z", 6}
            });

            chart.Series.Last().Name.ShouldBe("Comparison");
            chart.Series.Last().Center.ShouldBe(new[] {"80%"});
            chart.Series.Last().Data.ShouldBe(new[]
            {
                new ArrayList {"a", 10},
                new ArrayList {"b", 9},
                new ArrayList {"c", 8},
                new ArrayList {"d", 7},
                new ArrayList {"e", 11},
                new ArrayList {"f", 16},
                new ArrayList {"w", 15},
                new ArrayList {"x", 13},
                new ArrayList {"y", 14},
                new ArrayList {"z", 12}
            });
        }

        [Fact]
        public void ChartDataIsFormattedProperlyForComparisonsAndOneGroup()
        {
            var original = new List<Row>
            {
                new Row(1, "a", "weather"),
                new Row(2, "b", "weather"),
                new Row(3, "c", "weather"),
                new Row(4, "d", "weather"),
                new Row(5, "e", "weather")
            };

            var comparison = new List<Row>
            {
                new Row(10, "a", "weather"),
                new Row(9, "b", "weather"),
                new Row(8, "c", "weather"),
                new Row(7, "d", "weather"),
                new Row(6, "e", "weather")
            };

            var chart = new Chart(new[] {original, comparison}, "node", "pie");

            chart.Categories.ShouldBe(new[] {"a", "b", "c", "d", "e"});

            chart.Series.First().Type.ShouldBe("pie");
            chart.Series.First().Name.ShouldBe("Original");
            chart.Series.First().Center.ShouldBe(new[] {"20%"});
            chart.Series.First().Data.ShouldBe(new[]
            {
                new ArrayList {"a", 1},
                new ArrayList {"b", 2},
                new ArrayList {"c", 3},
                new ArrayList {"d", 4},
                new ArrayList {"e", 5}
            });

            chart.Series.Last().Name.ShouldBe("Comparison");
            chart.Series.Last().Center.ShouldBe(new[] {"80%"});
            chart.Series.Last().Data.ShouldBe(new[]
            {
                new ArrayList {"a", 10},
                new ArrayList {"b", 9},
                new ArrayList {"c", 8},
                new ArrayList {"d", 7},
                new ArrayList {"e", 6}
            });
        }

        [Fact]
        public void ChartDataIsFormattedProperlyForMultipleGroups()
        {
            var rows = new List<Row>
            {
                new Row(1, "a", "weather"),
                new Row(2, "b", "weather"),
                new Row(3, "c", "weather"),
                new Row(4, "d", "weather"),
                new Row(5, "e", "weather"),
                new Row(6, "z", "road"),
                new Row(7, "x", "road"),
                new Row(8, "y", "road"),
                new Row(9, "w", "road"),
                new Row(10, "f", "road")
            };

            var chart = new Chart(rows, "node", "pie");

            chart.Categories.ShouldBe(new[] {"a", "b", "c", "d", "e", "f", "w", "x", "y", "z"});
            chart.Series.First().Type.ShouldBe("pie");
            chart.Series.First().Name.ShouldBe("Original");
            chart.Series.First().Data.ShouldBe(new[]
            {
                new ArrayList {"a", 1},
                new ArrayList {"b", 2},
                new ArrayList {"c", 3},
                new ArrayList {"d", 4},
                new ArrayList {"e", 5},
                new ArrayList {"f", 10},
                new ArrayList {"w", 9},
                new ArrayList {"x", 7},
                new ArrayList {"y", 8},
                new ArrayList {"z", 6}
            });
        }

        [Fact]
        public void ChartDataIsFormattedProperlyForOneGroup()
        {
            var rows = new List<Row>
            {
                new Row(1, "a", "weather"),
                new Row(2, "b", "weather"),
                new Row(3, "c", "weather"),
                new Row(4, "d", "weather"),
                new Row(5, "e", "weather")
            };

            var chart = new Chart(rows, "node", "pie");

            chart.Categories.ShouldBe(new[] {"a", "b", "c", "d", "e"});
            chart.Series.First().Type.ShouldBe("pie");
            chart.Series.First().Name.ShouldBe("Original");
            chart.Series.First().Data.ShouldBe(new[]
            {
                new ArrayList {"a", 1},
                new ArrayList {"b", 2},
                new ArrayList {"c", 3},
                new ArrayList {"d", 4},
                new ArrayList {"e", 5}
            });
        }

        [Fact]
        public void ChartDataIsInSameOrderAsCategories()
        {
            var original = new List<Row>
            {
                new Row(1, "a", "weather"),
                new Row(3, "b", "weather"),
                new Row(4, "c", "weather"),
                new Row(5, "d", "weather"),
                new Row(6, "z", "road"),
                new Row(7, "x", "road"),
                new Row(8, "y", "road")
            };

            var chart = new Chart(original, "node", "pie");
            chart.Categories.ShouldBe(chart.Series[0].Data.Select(x => x[0]));
        }

        [Fact]
        public void DatesAreOrderedSundayToSaturday()
        {
            var rows = new List<Row>
            {
                new Row(2, DayOfWeek.Tuesday, "day"),
                new Row(0, DayOfWeek.Sunday, "day"),
                new Row(3, DayOfWeek.Wednesday, "day"),
                new Row(6, DayOfWeek.Saturday, "day"),
                new Row(5, DayOfWeek.Friday, "day"),
                new Row(1, DayOfWeek.Monday, "day")
            };

            var chart = new Chart(rows, "node", "pie");

            chart.Categories.ShouldBe(new[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"});
            chart.Series.First().Type.ShouldBe("pie");
            chart.Series.First().Name.ShouldBe("Original");
            chart.Series.First().Data.First().ShouldBe(new ArrayList {"Sunday", 0});
            chart.Series.First().Data.Last().ShouldBe(new ArrayList {"Saturday", 6});
        }

        [Fact]
        public void DatesAreOrderedSundayToSaturdayInComparison()
        {
            var rows = new List<Row>
            {
                new Row(1, DayOfWeek.Tuesday, "day"),
                new Row(1, DayOfWeek.Wednesday, "day"),
                new Row(1, DayOfWeek.Saturday, "day"),
                new Row(1, DayOfWeek.Friday, "day"),
                new Row(1, DayOfWeek.Monday, "day")
            };

            var comparison = new List<Row>
            {
                new Row(1, DayOfWeek.Sunday, "day"),
                new Row(1, DayOfWeek.Wednesday, "day"),
                new Row(1, DayOfWeek.Thursday, "day"),
                new Row(1, DayOfWeek.Friday, "day"),
                new Row(1, DayOfWeek.Monday, "day")
            };

            var chart = new Chart(new[] {rows, comparison}, "node", "pie");

            chart.Categories.ShouldBe(new[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"});
            chart.Series.First().Type.ShouldBe("pie");
            chart.Series.First().Name.ShouldBe("Original");
            chart.Series.First().Data.First().ShouldBe(new ArrayList {"Sunday", 0});
            chart.Series.First().Data.Last().ShouldBe(new ArrayList {"Saturday", 1});
            chart.Series.Last().Data.First().ShouldBe(new ArrayList {"Sunday", 1});
            chart.Series.Last().Data.Last().ShouldBe(new ArrayList {"Saturday", 0});
        }

    }
}


text:
<?php

namespace Magento\Test\Integrity\Modular;

use Magento\Framework\Component\ComponentRegistrar;

class WidgetConfigFilesTest extends \Magento\TestFramework\TestCase\AbstractConfigFiles
{
    /**
     * Returns the reader class name that will be instantiated via ObjectManager
     *
     * @return string reader class name
     */
    protected function _getReaderClassName()
    {
        return 'Magento\Widget\Model\Config\Reader';
    }

    /**
     * Returns a string that represents the path to the config file
     *
     * @return string
     */
    protected function _getConfigFilePathGlob()
    {
        return 'etc/widget.xml';
    }

    /**
     * Returns an absolute path to the XSD file corresponding to the XML files specified in _getConfigFilePathGlob
     *
     * @return string
     */
    protected function _getXsdPath()
    {
        return $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, 'Magento_Widget')
            . '/etc/widget_file.xsd';
    }
}


text:
/*! \addtogroup ENC28J60 ENC28J60 SPI to Ethernet Device
 * @{
 *
 */

#ifndef HWDL_ENC28J60_H_
#define HWDL_ENC28J60_H_

#include "hwpl.h"
#include "dev/eth.h"
#include "dev/microchip/enc28j60.h"

/*! \details This defines the device specific volatile configuration.
 *
 */
typedef struct {
	const char * buf;
	int nbyte;
	uint8_t cmd[8];
	device_transfer_t op;
	hwpl_callback_t callback;
	void * context;
	uint16_t next_pkt;
} enc28j60_state_t;

typedef struct {
	uint32_t rx_buffer_size;
	uint32_t tx_buffer_size;
} enc28j60_cfg_t;

int enc28j60_open(const device_cfg_t * cfg);
int enc28j60_ioctl(const device_cfg_t * cfg, int request, void * ctl);
int enc28j60_read(const device_cfg_t * cfg, device_transfer_t * rop);
int enc28j60_write(const device_cfg_t * cfg, device_transfer_t * wop);
int enc28j60_close(const device_cfg_t * cfg);

int enc28j60_getattr(const device_cfg_t * cfg, void * ctl);
int enc28j60_setattr(const device_cfg_t * cfg, void * ctl);
int enc28j60_setaction(const device_cfg_t * cfg, void * ctl);
int enc28j60_init_tx_pkt(const device_cfg_t * cfg, void * ctl);
int enc28j60_send_tx_pkt(const device_cfg_t * cfg, void * ctl);
int enc28j60_tx_pkt_busy(const device_cfg_t * cfg, void * ctl);
int enc28j60_rx_pkt_rdy(const device_cfg_t * cfg, void * ctl);
int enc28j60_rx_pkt_complete(const device_cfg_t * cfg, void * ctl);

#endif /* HWDL_ENC28J60_H_ */

/*! @} */


text:
We're making it easy to do interesting things with git, and we'd love to have
your help.

## Licensing

By contributing to libgit2, you agree to release your contribution under the terms of the license.
For code under `examples`, this is governed by the [CC0 Public Domain Dedication](examples/COPYING).
All other code is released under the [GPL v2 with linking exception](COPYING).

## Discussion & Chat

We hang out in the #libgit2 channel on irc.freenode.net.

Also, feel free to open an
[Issue](https://github.com/libgit2/libgit2/issues/new) to start a discussion
about any concerns you have.  We like to use Issues for that so there is an
easily accessible permanent record of the conversation.

## Reporting Bugs

First, know which version of libgit2 your problem is in and include it in
your bug report.  This can either be a tag (e.g.
[v0.17.0](https://github.com/libgit2/libgit2/tree/v0.17.0) ) or a commit
SHA (e.g.
[01be7863](https://github.com/libgit2/libgit2/commit/01be786319238fd6507a08316d1c265c1a89407f)
).  Using [`git describe`](http://git-scm.com/docs/git-describe) is a great
way to tell us what version you're working with.

If you're not running against the latest `development` branch version,
please compile and test against that to avoid re-reporting an issue that's
already been fixed.

It's *incredibly* helpful to be able to reproduce the problem.  Please
include a list of steps, a bit of code, and/or a zipped repository (if
possible).  Note that some of the libgit2 developers are employees of
GitHub, so if your repository is private, find us on IRC and we'll figure
out a way to help you.

## Pull Requests

Our work flow is a typical GitHub flow, where contributors fork the
[libgit2 repository](https://github.com/libgit2/libgit2), make their changes
on branch, and submit a
[Pull Request](https://help.github.com/articles/using-pull-requests)
(a.k.a. "PR").

Life will be a lot easier for you (and us) if you follow this pattern
(i.e. fork, named branch, submit PR).  If you use your fork's `development`
branch, things can get messy.

Please include a nice description of your changes with your PR; if we have
to read the whole diff to figure out why you're contributing in the first
place, you're less likely to get feedback and have your change merged in.

If you are working on a particular area then feel free to submit a PR that
highlights your work in progress (and flag in the PR title that it's not
ready to merge). This will help in getting visibility for your fix, allow
others to comment early on the changes and also let others know that you
are currently working on something.

## Porting Code From Other Open-Source Projects

`libgit2` is licensed under the terms of the GPL v2 with a linking
exception.  Any code brought in must be compatible with those terms.

The most common case is porting code from core Git.  Git is a pure GPL
project, which means that in order to port code to this project, we need the
explicit permission of the author.  Check the
[`git.git-authors`](https://github.com/libgit2/libgit2/blob/development/git.git-authors)
file for authors who have already consented.

Other licenses have other requirements; check the license of the library
you're porting code *from* to see what you need to do.  As a general rule,
MIT and BSD (3-clause) licenses are typically no problem.  Apache 2.0
license typically doesn't work due to GPL incompatibility.

If you are pulling in code from core Git, another project or code you've pulled from
a forum / Stack Overflow then please flag this in your PR and also make sure you've
given proper credit to the original author in the code snippet.

## Style Guide

`libgit2` is written in [ANSI C](http://en.wikipedia.org/wiki/ANSI_C)
(a.k.a. C89) with some specific conventions for function and type naming,
code formatting, and testing.

We like to keep the source code consistent and easy to read.  Maintaining
this takes some discipline, but it's been more than worth it.  Take a look
at the
[conventions file](https://github.com/libgit2/libgit2/blob/development/CONVENTIONS.md).

## Starter Projects

So, you want to start helping out with `libgit2`? That's fantastic? We
welcome contributions and we promise we'll try to be nice.

If you want to jump in, you can look at our issues list to see if there
are any unresolved issues to jump in on.  Also, here is a list of some
smaller project ideas that could help you become familiar with the code
base and make a nice first step:

* Convert a `git_*modulename*_foreach()` callback-based iteration API
  into a `git_*modulename*_iterator` object with a create/advance style
  of API.  This helps folks writing language bindings and usually isn't
  too complicated.
* Write a new `examples/` program that mirrors a particular core git
  command.  (See `examples/diff.c` for example.)  This lets you (and us)
  easily exercise a particular facet of the API and measure compatability
  and feature parity with core git.
* Submit a PR to clarify documentation! While we do try to document all of
  the APIs, your fresh eyes on the documentation will find areas that are
  confusing much more easily.


text:
'use strict';

var _ = require('lodash');

module.exports = function (sandbox) {
  let N = sandbox.N;

  Object.keys(sandbox.config.bundles).forEach(function (bundle_name) {
    N.config.locales.forEach(lang => {
      const bundle_js = sandbox.bundler.createClass('concat', {
        logicalPath: 'public/bundle-' + bundle_name + '.' + lang + '.js'
      });

      sandbox.config.bundles[bundle_name].forEach(function (pkg_name) {
        const package_js = sandbox.bundler.createClass('concat', {
          logicalPath: 'internal/public/package-' + bundle_name + '-' + pkg_name + '.' + lang + '.js',
          virtual: true
        });

        bundle_js.push(package_js);

        _.forEach(sandbox.component_client[pkg_name], (component, type) => {
          if (type === 'i18n') {
            package_js.push(component[lang]);
            return;
          }

          package_js.push(component);
        });
      });
    });
  });
};


text:
from traceback import format_exc

import ldap
import ldap.sasl

DOCUMENTATION = """
---
module: ldap_attr
short_description: Add or remove LDAP attribute values.
description:
    - Add or remove LDAP attribute values.
notes:
    - This only deals with attributes on existing entries. To add or remove
      whole entries, see M(ldap_entry).
    - The default authentication settings will attempt to use a SASL EXTERNAL
      bind over a UNIX domain socket. This works well with the default Ubuntu
      install for example, which includes a cn=peercred,cn=external,cn=auth ACL
      rule allowing root to modify the server configuration. If you need to use
      a simple bind to access your server, pass the credentials in C(bind_dn)
      and C(bind_pw).
    - For C(state=present) and C(state=absent), all value comparisons are
      performed on the server for maximum accuracy. For C(state=exact), values
      have to be compared in Python, which obviously ignores LDAP matching
      rules. This should work out in most cases, but it is theoretically
      possible to see spurious changes when target and actual values are
      semantically identical but lexically distinct.
version_added: null
author: Peter Sagerson
requirements:
    - python-ldap
options:
    dn:
        required: true
        description:
            - The DN of the entry to modify.
    name:
        required: true
        description:
            - The name of the attribute to modify.
    values:
        required: true
        description:
            - The value(s) to add or remove. This can be a string or a list of
              strings. The complex argument format is required in order to pass
              a list of strings (see examples).
    state:
        required: false
        choices: [present, absent, exact]
        default: present
        description:
            - The state of the attribute values. If C(present), all given
              values will be added if they're missing. If C(absent), all given
              values will be removed if present. If C(exact), the set of values
              will be forced to exactly those provided and no others. If
              C(state=exact) and C(values) is empty, all values for this
              attribute will be removed.
    server_uri:
        required: false
        default: ldapi:///
        description:
            - A URI to the LDAP server. The default value lets the underlying
              LDAP client library look for a UNIX domain socket in its default
              location.
    start_tls:
        required: false
        default: false
        description:
            - If true, we'll use the START_TLS LDAP extension.
    bind_dn:
        required: false
        description:
            - A DN to bind with. If this is omitted, we'll try a SASL bind with
              the EXTERNAL mechanism (see note). If this is blank, we'll use an
              anonymous bind.
    bind_pw:
        required: false
        description:
            - The password to use with C(bind_dn).
"""

EXAMPLES = """
# Configure directory number 1 for example.com.
- ldap_attr: dn='olcDatabase={1}hdb,cn=config' name=olcSuffix values='dc=example,dc=com' state=exact
  become: true

# Set up the ACL. The complex argument format is required here to pass a list
# of ACL strings.
- ldap_attr:
  become: true
  args:
    dn: olcDatabase={1}hdb,cn=config
    name: olcAccess
    values:
      - '{0}to attrs=userPassword,shadowLastChange
         by self write
         by anonymous auth
         by dn="cn=admin,dc=example,dc=com" write
         by * none'
      - '{1}to dn.base="dc=example,dc=com"
         by dn="cn=admin,dc=example,dc=com" write
         by * read'
    state: exact

# Declare some indexes.
- ldap_attr: dn='olcDatabase={1}hdb,cn=config' name=olcDbIndex values={{ item }}
  become: true
  with_items:
    - objectClass eq
    - uid eq

# Set up a root user, which we can use later to bootstrap the directory.
- ldap_attr: dn='olcDatabase={1}hdb,cn=config' name={{ item.key }} values={{ item.value }} state=exact
  become: true
  with_dict:
    olcRootDN: 'cn=root,dc=example,dc=com'
    olcRootPW: '{SSHA}mRskON0Stk+5wO5K+MMk2xmakKt8h7eJ'
"""

def main():
    module = AnsibleModule(
        argument_spec={
            'dn': dict(required=True, type='str'),
            'name': dict(required=True, type='str'),
            'values': dict(required=True, type='raw'),
            'state': dict(default='present', choices=['present', 'absent', 'exact'], type='str'),
            'server_uri': dict(default='ldapi:///', type='str'),
            'start_tls': dict(default='false', choices=BOOLEANS, type='bool'),
            'bind_dn': dict(default=None, type='str'),
            'bind_pw': dict(default='', type='str'),
        },
        supports_check_mode=True,
    )

    try:
        LdapAttr(module).main()
    except ldap.LDAPError, e:
        module.fail_json(msg=str(e), exc=format_exc())

class LdapAttr(object):
    def __init__(self, module):
        self.module = module

        # python-ldap doesn't understand unicode strings. Parameters that are
        # just going to get passed to python-ldap APIs are stored as utf-8.
        self.dn = self._utf8_param('dn')
        self.name = self._utf8_param('name')
        self.values = self._normalized_values()
        self.state = self.module.params['state']
        self.server_uri = self.module.params['server_uri']
        self.start_tls = self.module.boolean(self.module.params['start_tls'])
        self.bind_dn = self._utf8_param('bind_dn')
        self.bind_pw = self._utf8_param('bind_pw')

        self._connection = None

    def _utf8_param(self, name):
        return self._force_utf8(self.module.params[name])

    def _normalized_values(self):
        """ Parses the value parameter into a list of utf-8 strings. """
        values = self.module.params['values']

        if isinstance(values, basestring):
            if values == '':
                values = []
            else:
                values = [values]

        if not (isinstance(values, list) and all(isinstance(value, basestring) for value in values)):
            self.module.fail_json(msg="values must be a string or list of strings.")

        return map(self._force_utf8, values)

    def _force_utf8(self, value):
        """ If value is unicode, encode to utf-8. """
        if isinstance(value, unicode):
            value = value.encode('utf-8')

        return value

    def main(self):
        if self.state == 'present':
            modlist = self.handle_present()
        elif self.state == 'absent':
            modlist = self.handle_absent()
        elif self.state == 'exact':
            modlist = self.handle_exact()
        else:
            modlist = []

        if len(modlist) > 0:
            changed = True
            if not self.module.check_mode:
                self.connection.modify_s(self.dn, modlist)
        else:
            changed = False

        self.module.exit_json(changed=changed, modlist=modlist)

    #
    # State Implementations
    #

    def handle_present(self):
        values_to_add = filter(self.is_value_absent, self.values)
        if len(values_to_add) > 0:
            modlist = [(ldap.MOD_ADD, self.name, values_to_add)]
        else:
            modlist = []

        return modlist

    def handle_absent(self):
        values_to_delete = filter(self.is_value_present, self.values)
        if len(values_to_delete) > 0:
            modlist = [(ldap.MOD_DELETE, self.name, values_to_delete)]
        else:
            modlist = []

        return modlist

    def handle_exact(self):
        modlist = []

        current = self.current_values()
        if frozenset(self.values) != frozenset(current):
            if len(current) == 0:
                modlist = [(ldap.MOD_ADD, self.name, self.values)]
            elif len(self.values) == 0:
                modlist = [(ldap.MOD_DELETE, self.name, None)]
            else:
                modlist = [(ldap.MOD_REPLACE, self.name, self.values)]

        return modlist

    #
    # Util
    #

    def is_value_present(self, value):
        """ True if the target attribute has the given value. """
        try:
            is_present = bool(self.connection.compare_s(self.dn, self.name, value))
        except ldap.NO_SUCH_ATTRIBUTE:
            is_present = False

        return is_present

    def is_value_absent(self, value):
        """ True if the target attribute does not have the given value. """
        return (not self.is_value_present(value))

    def current_values(self):
        """ Returns the full list of values on the target attribute. """
        results = self.connection.search_s(self.dn, ldap.SCOPE_BASE, attrlist=[self.name])
        values = results[0][1].get(self.name, [])

        return values

    #
    # LDAP Connection
    #

    @property
    def connection(self):
        """ An authenticated connection to the LDAP server (cached). """
        if self._connection is None:
            self._connection = self._connect_to_ldap()

        return self._connection

    def _connect_to_ldap(self):
        connection = ldap.initialize(self.server_uri)

        if self.start_tls:
            connection.start_tls_s()

        if self.bind_dn is not None:
            connection.simple_bind_s(self.bind_dn, self.bind_pw)
        else:
            connection.sasl_interactive_bind_s('', ldap.sasl.external())

        return connection

from ansible.module_utils.basic import *  # noqa
main()


text:
/**
 * DO NOT EDIT
 *
 * This file was automatically generated by
 *   https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
 *
 * To modify these typings, edit the source file(s):
 *   paper-inky-focus-behavior.js
 */

// tslint:disable:variable-name Describing an API that's defined elsewhere.
// tslint:disable:no-any describes the API as best we are able today

import {IronButtonState} from '@polymer/iron-behaviors/iron-button-state.js';

import {IronControlState} from '@polymer/iron-behaviors/iron-control-state.js';

import {PaperRippleBehavior} from './paper-ripple-behavior.js';

/**
 * `PaperInkyFocusBehavior` implements a ripple when the element has keyboard
 * focus.
 */
interface PaperInkyFocusBehavior extends IronButtonState, IronControlState, PaperRippleBehavior {
  _createRipple(): any;
  _focusedChanged(receivedFocusFromKeyboard: any): void;
}

declare const PaperInkyFocusBehavior: object;

export {PaperInkyFocusBehavior};


text:
<?php
namespace Kir\FakePDO\Tools;

class MethodNameGenerator {
	/** @var string */
	private $className = null;

	/**
	 * @param string $className
	 */
	public function __construct($className) {
		$this->className = $className;
	}

	/**
	 * @param string $methodName
	 * @return string
	 */
	public function getQualifiedMethodName($methodName) {
		return "{$this->className}::{$methodName}";
	}
}


text:
require 'moped'
require_relative 'thread_tracer'

class Moped::Session
  # Check that each Moped::Session is only accessed by the same thread that created it
  module Tracer
    def initialize(seeds, options = {})
      @thread_tracer = ThreadTracer.new("Moped::Session[#{@db_session.object_id}]")
      super
    end

    def current_database
      @thread_tracer.check!
      super
    end
  end

  prepend Tracer

  ThreadTracer.debug { "TRACE Moped::Session @ #{ThreadTracer.caller}" }
end


text:
use crate::arch::x86_64::mm::paging::{BasePageSize, PageSize};
use crate::mm;
use crate::mm::freelist::{FreeList, FreeListEntry};
use crate::scheduler::DisabledPreemption;

static mut KERNEL_FREE_LIST: FreeList = FreeList::new();

/// End of the virtual memory address space reserved for kernel memory (4 GiB).
/// This also marks the start of the virtual memory address space reserved for the task heap.
const KERNEL_VIRTUAL_MEMORY_END: usize = 0x1_0000_0000;

/// End of the virtual memory address space reserved for kernel memory (128 TiB).
/// This is the maximum contiguous virtual memory area possible with current x86-64 CPUs, which only support 48-bit
/// linear addressing (in two 47-bit areas).
const TASK_VIRTUAL_MEMORY_END: usize = 0x8000_0000_0000;

pub fn init() {
	let entry = FreeListEntry {
		start: mm::kernel_end_address(),
		end: KERNEL_VIRTUAL_MEMORY_END,
	};
	unsafe {
		KERNEL_FREE_LIST.list.push_back(entry);
	}
}

pub fn allocate(size: usize) -> usize {
	assert!(size > 0);
	assert!(
		size % BasePageSize::SIZE == 0,
		"Size {:#X} is not a multiple of {:#X}",
		size,
		BasePageSize::SIZE
	);

	let _preemption = DisabledPreemption::new();
	let result = unsafe { KERNEL_FREE_LIST.allocate(size, None) };
	assert!(
		result.is_ok(),
		"Could not allocate {:#X} bytes of virtual memory",
		size
	);
	result.unwrap()
}

pub fn deallocate(virtual_address: usize, size: usize) {
	assert!(
		virtual_address >= mm::kernel_end_address(),
		"Virtual address {:#X} is not >= KERNEL_END_ADDRESS",
		virtual_address
	);
	assert!(
		virtual_address < KERNEL_VIRTUAL_MEMORY_END,
		"Virtual address {:#X} is not < KERNEL_VIRTUAL_MEMORY_END",
		virtual_address
	);
	assert!(
		virtual_address % BasePageSize::SIZE == 0,
		"Virtual address {:#X} is not a multiple of {:#X}",
		virtual_address,
		BasePageSize::SIZE
	);
	assert!(size > 0);
	assert!(
		size % BasePageSize::SIZE == 0,
		"Size {:#X} is not a multiple of {:#X}",
		size,
		BasePageSize::SIZE
	);

	let _preemption = DisabledPreemption::new();
	unsafe {
		KERNEL_FREE_LIST.deallocate(virtual_address, size);
	}
}

pub fn reserve(virtual_address: usize, size: usize) {
	assert!(
		virtual_address >= mm::kernel_end_address(),
		"Virtual address {:#X} is not >= KERNEL_END_ADDRESS",
		virtual_address
	);
	assert!(
		virtual_address < KERNEL_VIRTUAL_MEMORY_END,
		"Virtual address {:#X} is not < KERNEL_VIRTUAL_MEMORY_END",
		virtual_address
	);
	assert!(
		virtual_address % BasePageSize::SIZE == 0,
		"Virtual address {:#X} is not a multiple of {:#X}",
		virtual_address,
		BasePageSize::SIZE
	);
	assert!(size > 0);
	assert!(
		size % BasePageSize::SIZE == 0,
		"Size {:#X} is not a multiple of {:#X}",
		size,
		BasePageSize::SIZE
	);

	let _preemption = DisabledPreemption::new();
	let result = unsafe { KERNEL_FREE_LIST.reserve(virtual_address, size) };
	assert!(
		result.is_ok(),
		"Could not reserve {:#X} bytes of virtual memory at {:#X}",
		size,
		virtual_address
	);
}

pub fn task_heap_start() -> usize {
	KERNEL_VIRTUAL_MEMORY_END
}

pub fn task_heap_end() -> usize {
	TASK_VIRTUAL_MEMORY_END
}


text:
var mocha = require('mocha'),
	assert = require('assert'),
	sinon = require('sinon'),
	child = require('child_process'),
	tadaa = require('../lib/tadaa.js');

describe('Tadaa', function() {
	describe('when result is greater than current', function() {
		beforeEach(function() {
			sinon.stub(child, 'exec').yields();
		});

		afterEach(function() {
			child.exec.restore();
		});

		it('should not error when playCorrectSound called', function(done) {
            var logic = [{fn: tadaa.up, sound: "up.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(1, 2, logic, null, function(err) {
				assert.equal(err, null);
				return done();
			});
		});

		it('should play up.wav', function(done) {
            var logic = [{fn: tadaa.up, sound: "up.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(1, 2, logic, null, function(err) {
				assert(child.exec.calledWith('aplay up.wav'));
				return done();
			});
		});
	});

	describe('when result is less than current', function() {
		beforeEach(function() {
			sinon.stub(child, 'exec').yields(null);
		});

		afterEach(function() {
			child.exec.restore();
		});

		it('should not error when playCorrectSound called', function(done) {
            var logic = [{fn: tadaa.up, sound: "up.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(2, 1, logic, null, function(err) {
				assert.equal(err, null);
				return done();
			});
		});

		it('should play down.wav', function(done) {
            var logic = [{fn: tadaa.up, sound: "up.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(2, 1, logic, null, function(err) {
				assert(child.exec.calledWith('aplay down.wav'));
				return done();
			});
		});
	});

	describe('when result is equal to current', function() {
		beforeEach(function() {
			sinon.stub(child, 'exec').yields(null);
		});

		afterEach(function() {
			child.exec.restore();
		});

		it('should not error when playCorrectSound called', function(done) {
            var logic = [{fn: tadaa.up, sound: "up.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(1, 1, logic, null, function(err) {
				assert.equal(err, null);
				return done();
			});
		});

		it('should not play a sound', function(done) {
            var logic = [{fn: tadaa.up, sound: "up.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(1, 1, logic, null, function(err) {
				assert.equal(child.exec.called, false);
				return done();
			});
		});
	});

	describe('when result drops to zero', function() {
		beforeEach(function() {
			sinon.stub(child, 'exec').yields(null);
		});

		afterEach(function() {
			child.exec.restore();
		});

		it('should not error when playCorrectSound called', function(done) {
            var logic = [{fn: tadaa.dropToZero, sound: "dropToZero.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(1, 0, logic, null, function(err) {
				assert.equal(err, null);
				return done();
			});
		});

		it('should play dropToZero.wav', function(done) {
            var logic = [{fn: tadaa.dropToZero, sound: "dropToZero.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(1, 0, logic, null, function(err) {
				assert(child.exec.calledWith('aplay dropToZero.wav'));
				return done();
			});
		});
	});

	describe('when audio player is set', function() {
		beforeEach(function() {
			sinon.stub(child, 'exec').yields(null);
		});

		afterEach(function() {
			child.exec.restore();
		});

		it('should not error', function(done) {
            var logic = [{fn: tadaa.up, sound: "up.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(2, 1, logic, 'afplay', function(err) {
				assert.equal(err, null);
				done();
			});
		});

		it('should play down.wav with afplay', function(done) {
            var logic = [{fn: tadaa.up, sound: "up.wav"}, {fn: tadaa.down, sound: 'down.wav'}];
			tadaa.playCorrectSound(2, 1, logic, 'afplay', function(err) {
				assert(child.exec.calledWith('afplay down.wav'));
				return done();
			});
		});
	});

	describe('when start called', function() {
        var clock;

		beforeEach(function() {
			sinon.stub(tadaa, 'getValueAndPlaySound');
            clock = sinon.useFakeTimers();
            tadaa.start('NAME', 10, [{fn: tadaa.up, sound:'upsound'}, {fn: tadaa.down, sound:'downsound'}], 'getValue', 'getValueOptions', 'audioPlayer');
            clock.tick(15);
		});

		afterEach(function() {
			tadaa.getValueAndPlaySound.restore();
            clock.restore();
		});

		it('should call getValueAndPlaySound', function() {
            assert(tadaa.getValueAndPlaySound.calledOnce);
            // TODO args coming back undefined in test
            // assert.deepEqual(tadaa.getValueAndPlaySound.args[0][0], 'NAME');
            // assert.deepEqual(tadaa.getValueAndPlaySound.args[0][1], [{fn: tadaa.up, sound:'upsound'}, {fn: tadaa.down, sound:'downsound'}]);
            // assert.deepEqual(tadaa.getValueAndPlaySound.args[0][2], 'getValue');
            // assert.deepEqual(tadaa.getValueAndPlaySound.args[0][3], 'getValueOptions');
            // assert.deepEqual(tadaa.getValueAndPlaySound.args[0][4], 'audioPlayer');
		});
	});

	describe('with two different tags', function() {
        // TODO
		// first : 10 -> 20 -> 30  === up played twice
		// second : 5 -> 15 -> 25  === up played twice

		// -> 20, 15, 30, 25

	});
});


text:
@implementation DurationFormatter

- (BOOL)isPartialStringValid:(NSString *)partial newEditingString:(NSString **)newString errorDescription:(NSString **)error {

	if ([partial length] == 0) {
		return YES;
	}
	*newString = [partial stringByTrimmingCharactersInSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
	return NO;
}

@end


text:
import React from 'react';

export default function Home() {
	return (

Home

	);
}


text:
/* global Swiper, $ */
var mySwiper
function initSwiper () {
  mySwiper = new Swiper('.swiper-container', {
    direction: 'horizontal',
    loop: false,
    pagination: '.swiper-pagination',
    nextButton: '.Swiper__Nav--Next',
    prevButton: '.Swiper__Nav--Prev',
    scrollbar: '.swiper-scrollbar',
    scrollbarHide: true,
    setWrapperSize: true,
    slidesPerView: 3,
    slidesPerGroup: 3,
    spaceBetween: 10,
    resistance: false,
    onSlideChangeEnd: function (swiper) {
      swiper.update()
    }
  })
  mySwiper.pagination = true
  mySwiper.scrollbarHide = true
}

$.featherlight.autoBind = false


text:
	Main Concepts
	Forms - Custom Validators

Finally, we need a way to create our own Validator

		Our validator needs to implements this interface
		<editortab [alone]="true">
interface Validator<T extends Control> {
   (c:T): {[error: string]:any};
}
		</editortab>

		It can then be used with our FormGroup programmatically

<editor [ng2]="true" [plunker]="true" description="Using forms">
    <editortab title="app/app.component.ts" fileType="js" ngNonBindable>
import {Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MyFormCmp} from 'app/my-form.component';

@Component({
    selector: 'app',
    template: '<my-form-cmp></my-form-cmp>'
})
export class App {}

export const ModuleDefs= {
	bootstrap: [App],
	imports: [BrowserModule, FormsModule, ReactiveFormsModule],
	declarations: [App, MyFormCmp]
}
    </editortab>
    <editortab title="app/my-form.component.ts" fileType="js">
import {Component} from '@angular/core';
import {FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';

enum TodoCategory{PRIVATE, PERSO};

class TodoModel{
	constructor(public category: TodoCategory, public details: string){}
}

// THE VALIDATOR FUNCTION
let users= ['John'];

@Component({
	selector:'my-form-cmp',
	templateUrl:'app/my-form.html'
})
export class MyFormCmp{
	categories: string[]= Object.keys(TodoCategory).filter(v => isNaN(parseInt(v, 10)));
	model: TodoModel= new TodoModel();
	userformGroup: FormGroup;
	usernameCtrl: FormControl;

	static userNameExists(c: FormControl){
	    for (var i in users){
	      if ( users[i] === c.value ){
	        return null;
	      }
	    }
	  return {userNameExists: true };
  	}

	constructor(fb: FormBuilder){
	  this.usernameCtrl = fb.control('', [Validators.required, MyFormCmp.userNameExists]);
		this.userformGroup = fb.group({
			'username': this.usernameCtrl
		});
	}

	isSubmit: false;

	onSubmit(){
		this.isSubmit= true;
	}
}
	</editortab>
    <editortab title="app/my-form.html" fileType="html" ngNonBindable>
<style>
  input.ng-invalid.ng-dirty {
   border: 3px red solid;
  }
</style>
<h1>Enter your name</h1>

<form (ngSubmit)="onSubmit()" [formGroup]="userformGroup">
	<p>
	    <label for="name">Name</label>
	    <input
	      name="name"
	      [formControl]="usernameCtrl"
	    >
	    <span *ngIf="!usernameCtrl.valid">Invalid content</span>
	</p>
	<div *ngIf="usernameCtrl.hasError('required')">Username is required</div>
	<button *ngIf="userformGroup.valid" type="submit">Submit</button>
</form>

<p *ngIf="isSubmit">
	Form submited<br/>
	userformGroup.value {{userformGroup.value | json}}

</p>
    </editortab>
</editor>

	You can also declare it as a directive if needed (more here)


text: export { default } from './YiiOriginalWordmark'


text:
import os
import logging
import urllib
import zopkio.runtime as runtime
import zopkio.adhoc_deployer as adhoc_deployer
from zopkio.runtime import get_active_config as c
from samza_job_yarn_deployer import SamzaJobYarnDeployer

logger = logging.getLogger(__name__)
deployers = None
samza_job_deployer = None
samza_install_path = None

def _download_packages():
  for url_key in ['url_hadoop', 'url_kafka', 'url_zookeeper']:
    logger.debug('Getting download URL for: {0}'.format(url_key))
    url = c(url_key)
    filename = os.path.basename(url)
    if os.path.exists(filename):
      logger.debug('Using cached file: {0}'.format(filename))
    else:
      logger.info('Downloading: {0}'.format(url))
      urllib.urlretrieve(url, filename)

def _new_ssh_deployer(config_prefix, name=None):
  deployer_name = config_prefix if name == None else name
  return adhoc_deployer.SSHDeployer(deployer_name, {
    'install_path': os.path.join(c('remote_install_path'), c(config_prefix + '_install_path')),
    'executable': c(config_prefix + '_executable'),
    'post_install_cmds': c(config_prefix + '_post_install_cmds', []),
    'start_command': c(config_prefix + '_start_cmd'),
    'stop_command': c(config_prefix + '_stop_cmd'),
    'extract': True,
    'sync': True,
  })

def setup_suite():
  global deployers, samza_job_deployer, samza_install_path
  logger.info('Current working directory: {0}'.format(os.getcwd()))
  samza_install_path = os.path.join(c('remote_install_path'), c('samza_install_path'))

  _download_packages()

  deployers = {
    'zookeeper': _new_ssh_deployer('zookeeper'),
    'yarn_rm': _new_ssh_deployer('yarn_rm'),
    'yarn_nm': _new_ssh_deployer('yarn_nm'),
    'kafka': _new_ssh_deployer('kafka'),
  }

  # Enforce install order through list.
  for name in ['zookeeper', 'yarn_rm', 'yarn_nm', 'kafka']:
    deployer = deployers[name]
    runtime.set_deployer(name, deployer)
    for instance, host in c(name + '_hosts').iteritems():
      logger.info('Deploying {0} on host: {1}'.format(instance, host))
      deployer.start(instance, {'hostname': host})

  # Setup Samza job deployer.
  samza_job_deployer = SamzaJobYarnDeployer({
    'yarn_site_template': c('yarn_site_template'),
    'yarn_driver_configs': c('yarn_driver_configs'),
    'yarn_nm_hosts': c('yarn_nm_hosts').values(),
    'install_path': samza_install_path,
  })

  samza_job_deployer.install('tests', {
    'executable': c('samza_executable'),
  })

  runtime.set_deployer('samza_job_deployer', samza_job_deployer)

def teardown_suite():
  samza_job_deployer.uninstall('tests')

  # Undeploy everything.
  for name, deployer in deployers.iteritems():
    for instance, host in c(name + '_hosts').iteritems():
      deployer.undeploy(instance)


text:
(function(){
  'use strict';

var _ = require('underscore');

function GeneralError(msg) {
  this.msg = msg;
}

GeneralError.prototype.toString = function() {
  return this.msg;
};

function LexicalError(loc, expected) {
  this.loc      = loc;
  this.expected = expected;
}

LexicalError.prototype.toString = function(filename) {
  var result = [];

  result.push(new Array(30).join('='));
  result.push('Lexical Error');
  result.push(new Array(30).join('-'));
  result.push('\tLine/Col: '+this.loc.first_line+'/'+this.loc.first_column);

  return result.join('\n');
};

function SyntaxError(token, loc, expected) {
  this.token    = token;
  this.loc      = loc;
  this.expected = expected;
}

SyntaxError.prototype.toString = function(filename) {
  var result = [];

  result.push(new Array(30).join('='));
  result.push('Syntax Error');
  result.push(new Array(30).join('-'));
  result.push('Filename: ' + filename);
  result.push('Line/Col: '+this.loc.first_line+'/'+this.loc.first_column);
  result.push('Found: '+this.token);
  result.push('Expected: '+this.expected.join(' '));
  result.push(new Array(30).join('-'));

  return result.join('\n');
};

function ElaborationError() {
}

ElaborationError.prototype.toString = function(filename) {
  return '';
};

function EvaluationError() {
}

EvaluationError.prototype.toString = function(filename) {
  return '';
};

exports.General     = GeneralError;
exports.Lexical     = LexicalError;
exports.Syntax      = SyntaxError;
exports.Elaboration = ElaborationError;
exports.Evaluation  = EvaluationError;

})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<Addon Author="WintyBadass" APIVersion="9" Name="ForgeUI_ActionBars" Description="">
    <Script Name="ForgeUI_ActionBars.lua"/>
    <Form Name="ForgeUI_ActionBars.xml"/>
    <ReplaceAddon Name="ActionBarFrame"/>
	<ReplaceAddon Name="ActionBarShortcut"/>
	<ReplaceAddon Name="Medic"/>
	<ReplaceAddon Name="PathFrame"/>
	<ReplaceAddon Name="RecallFrame"/>
</Addon>


text:
> More info about match all query is in the [official elasticsearch docs][1]

A query that matches all documents

## Simple example

```JSON
{
    "match_all" : { }
}
```

In DSL:

```php
$matchAllQuery = new MatchAllQuery();

$search = new Search();
$search->addQuery($matchAllQuery);

$queryArray = $search->toArray();
```

[1]: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-all-query.html


text:
'use strict';
console.log('%j', process.execArgv)
console.log('%j', process.argv.slice(2))
setTimeout(function () {}, 100)


text:
π<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>

Title

Date

Sub Title

Today is a special day for me since it marks the start of my first blog and the end of Week 1 at Dev Bootcamp. I am pretty new to blogging so please forgive me if my blog drift to other topics and confuses you. I will try my best to keep it organize and interesting. Here is a little bit about myself; my name is Brian Bier and I am currently attending Phase 0 at Dev Bootcamp. I have never thought of blogging because it is one of those things that people just need to enjoy doing. However, when a developer begins to blog it helps them solidify a concept while helping the readers like you understand it. Being that it's only my first week at DBC we started to work on the not so scary Terminal and Git Version Control. I will explain more about what those two things mean in the next paragraph. I will try to be detailed as possible and provide you with helpful links where you can read more about these new concepts.

The majority of people see the famous Terminal as a scary and difficult program to understand.(I will be using the word Terminal because I am a Mac user. If you are a windows user it is called powershell.) The Terminal is one of the most powerful tools in your computer that can execute tasks using simple commands. If you can start familiarizing yourself with terminal, will help you a whole lot.hey! It makes you look cool. Below is a great link for getting started with the command line.

What is Git? Git is a version control system that you download to your computer, which helps keep track of projects that you are working on. As a developer using Git will help you become more organize with your work. Git helps you save your work in specific moments in time, which are called commits, allowing you to solve errors faster. Git has its own commands that plays well with your terminal so you will have to learn a few of them but trust me you only end up using about 7 of the commands. Below is a link to learn git. Its important to know that Git saves everything to your local machine so if something happens to your computer you will lose everything. That is when github comes in to play.

Github is a free open source host where you can securely store and share projects with other people. Git and Github work together but They are not the same thing. Git keeps you organize in your computer and then you use Github to save it in the web for safe storage. Using Github is just essentially saying you store your work in the "cloud" where other can contribute or fork with ease. Yes! Other people can take your work or help you improve it. Github is Open Source so everything is out to the public, but don't get discourage about Github, there are licenses that you can use so that you get credit for your work. I will post a link down below to help you understand open source and the use of different licenses. There are a plenty of open source host out there but Github is one of the most popular. As a new developer Github becomes your online resume so treat it well.


text:
var _               = require('lodash'),
    http            = require('http'),
    xml             = require('xml'),
    config          = require('../../config'),
    errors          = require('../../errors'),
    events          = require('../../events'),
    i18n            = require('../../i18n'),
    pingList;

// ToDo: Make this configurable
//http://blogsearch.google.com/ping/RPC2(谷歌的)
// 改成
// http://ping.baidu.com/ping/RPC2(百度的)

pingList = [{
    host: 'ping.baidu.com',
    path: '/ping/RPC2',
    method:'weblogUpdates.extendedPing'
}, {
    host: 'rpc.pingomatic.com',
    path: '/',
    method:'weblogUpdate.ping'
}];

function ping(post) {
    var pingXML,
        title = post.title,
        url = config.urlFor('post', {post: post}, true);

    // Only ping when in production and not a page
    if (process.env.NODE_ENV !== 'production' || post.page || config.isPrivacyDisabled('useRpcPing')) {
        return;
    }

    // Don't ping for the welcome to ghost post.
    // This also handles the case where during ghost's first run
    // models.init() inserts this post but permissions.init() hasn't
    // (can't) run yet.
    if (post.slug === 'welcome-to-ghost') {
        return;
    }

    // Build XML object.
    // pingXML = xml({
    //     methodCall: [{
    //         methodName: 'weblogUpdate.ping'
    //     }, {
    //         params: [{
    //             param: [{
    //                 value: [{
    //                     string: title
    //                 }]
    //             }]
    //         }, {
    //             param: [{
    //                 value: [{
    //                     string: url
    //                 }]
    //             }]
    //         }]
    //     }]
    // }, {declaration: true});

    // Ping each of the defined services.
    _.each(pingList, function (pingHost) {
        var options = {
                hostname: pingHost.host,
                path: pingHost.path,
                method: 'POST'
            },
            req;

        req = http.request(options);

        pingXML = xml({
            methodCall: [{
                methodName: pingHost.method
            }, {
                params: [{
                    param: [{
                        value: [{
                            string: title
                        }]
                    }]
                }, {
                    param: [{
                        value: [{
                            string: url
                        }]
                    }]
                }]
            }]
        }, {declaration: true});

        req.write(pingXML);
        req.on('error', function handleError(error) {
                errors.logError(
                    error,
                    i18n.t('errors.data.xml.xmlrpc.pingUpdateFailed.error'),
                    i18n.t('errors.data.xml.xmlrpc.pingUpdateFailed.help', {url: 'http://support.ghost.org'})
                );
            }
        );
        req.end();
    });
}

function listener(model) {
    ping(model.toJSON());
}

function listen() {
    events.on('post.published', listener);
}

module.exports = {
    listen: listen
};


text:
// Provides control sap.ui.commons.Menu.
sap.ui.define(['jquery.sap.global', './MenuItemBase', './library', 'sap/ui/unified/Menu'],
	function(jQuery, MenuItemBase, library, Menu1) {
	"use strict";

	/**
	 * Constructor for a new Menu control.
	 *
	 * @param {string} [sId] Id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] Initial settings for the new control
	 *
	 * @class
	 * A menu is an interactive element which provides a choice of different actions to the user. These actions (items) can also be organized in submenus.
	 * Like other dialog-like controls, the menu is not rendered within the control hierarchy. Instead it can be opened at a specified position via a function call.
	 * @extends sap.ui.unified.Menu
	 *
	 * @author SAP SE
	 * @version ${version}
	 * @since 1.0.0
	 *
	 * @constructor
	 * @public
	 * @deprecated Since version 1.21.0.
	 * Please use the control sap.ui.unified.Menu of the library sap.ui.unified instead.
	 * @alias sap.ui.commons.Menu
	 * @ui5-metamodel This control/element will also be described in the UI5 (legacy) design time meta model
	 */
	var Menu = Menu1.extend("sap.ui.commons.Menu", /** @lends sap.ui.commons.Menu.prototype */ { metadata : {

		deprecated : true,
		library : "sap.ui.commons"
	}});

	Menu.prototype.bCozySupported = false;

	/*Ensure MenuItemBase is loaded (incl. loading of unified library)*/

	return Menu;

}, /* bExport= */ true);


text:
///<reference path="APIRequest.ts"/>
///<reference path="APIResponse.ts"/>
///<reference path="CommonUtil.ts"/>
///<reference path="IAdaptiveRP.ts"/>
///<reference path="IAdaptiveRPGroup.ts"/>
///<reference path="IBaseSocial.ts"/>
var Adaptive;
(function (Adaptive) {
    /**
       @class Adaptive.BaseSocialBridge
       Base application for Social purposes

       @author Carlos Lozano Diez
       @since v2.0
    */
    var BaseSocialBridge = (function () {
        /**
           @method constructor
           Default constructor.
        */
        function BaseSocialBridge() {
            this.apiGroup = Adaptive.IAdaptiveRPGroup.Social;
        }
        /**
           @method
           Return the API group for the given interface.
           @return {Adaptive.IAdaptiveRPGroup}
        */
        BaseSocialBridge.prototype.getAPIGroup = function () {
            return this.apiGroup;
        };
        /**
           @method
           Return the API version for the given interface.

           @return {string} The version of the API.
        */
        BaseSocialBridge.prototype.getAPIVersion = function () {
            return Adaptive.bridgeApiVersion;
        };
        return BaseSocialBridge;
    })();
    Adaptive.BaseSocialBridge = BaseSocialBridge;
})(Adaptive || (Adaptive = {}));
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
//# sourceMappingURL=BaseSocialBridge.js.map