text:
from __future__ import print_function

import pymysql
import datetime

def escape(value, conn):
    if isinstance(value, tuple):
        return [escape(v, conn) for v in value]
    elif isinstance(value, unicode):
        result = (u'"' + unicode(conn.escape_string(value)) + u'"')
        return result
    elif isinstance(value, str):
        return '"' + conn.escape_string(value) + '"'
    elif isinstance(value, datetime.datetime):
        return u'"' + str(value) + u'"'
    elif value is None:
        return 'NULL'
    else:
        return str(value)

def insert(table, columns, values, replace=False):
    if replace:
        verb=u"REPLACE"
    else:
        verb=u"INSERT"
    return verb + u" INTO " + table + u" (" + u",".join(columns) + u") VALUES (" + u",".join(values) + u");"

def renumber(id):
    if id in concept_renumber:
        return concept_renumber[id]
    elif id in ciel_contributions:
        return ciel_contributions[id]
    else:
        return id

# Known CIEL concepts
# Some CIEL concepts we have added manually, then contributed back to CIEL
# These are treated differently to ones we have added and not contributed back
# map is original Buendia Number: CIEL Number
ciel_contributions = {
    162730: 162826, # Np PCR threshold value
    162729: 162827, # L gene PCR threshold value
    162695: 162750, # Able to walk independently
    162696: 162751, # Able to walk with assistance
    162694: 162752, # Bedridden
}

conn = pymysql.connect(host='localhost', port=3316, user='openmrs', passwd='dxAeApzr97hT', db='openmrs-sdk', charset='utf8')

old_concept_ids = []
new_concept_ids = []

# Concept renumber: We don't want newly added CIEL concepts to clash with ours. So we will prefix ours with 777,000,000.
# This will hopefully make them easily recognisable, significantly less than MAX Int 32, and have plenty of space from
# the CIEL dictionary.
concept_base_id = 777000000
concept_next_id = concept_base_id
concept_renumber = {}

# Make sure that we start higher than any Buendia concept already adjusted above concept_base_id
cur = conn.cursor()
cur.execute("SELECT max(concept_id) FROM concept")
for row in cur:  # No need, but no harm in loop
    concept_next_id = max(row[0], concept_next_id)
cur.close()

print('\n#\n# Extra dictionary changes for the Google/MSF Ebola effort (Project Buendia)\n#')

# Read all new concepts (by making assumptions about the UUID), and create INSERT statements for them.
# If we renumber we will need to renumber all forms as well.
# We will also need to renumber data if we keep old data.
print('\n#\n# Buendia specific concepts, with class etc\n#')
cur = conn.cursor()
concept_columns = ["concept_id","datatype_id","class_id","creator","date_created","uuid"]
cur.execute("SELECT " +  ",".join(concept_columns) + " FROM concept WHERE concept.uuid NOT LIKE '%AAAA' and concept.retired = 0")
for row in cur:
    id = row[0]
    if id in ciel_contributions:
        continue
    newid = id
    if id<concept_base_id:
        newid = concept_next_id
        concept_next_id = concept_next_id + 1
        concept_renumber[id] = newid
        print('-- renumbered ' + str(id) + " as " + str(newid))

    values = escape(row, conn)
    old_concept_ids.append(id)
    new_concept_ids.append(newid)
    values[0] = str(newid)
    print(insert("concept", concept_columns, values).encode('utf-8'))
cur.close()

# insert all the non-voided strings for the given concepts
print('\n#\n# Names for Buendia specific concepts\n#')
cur = conn.cursor()
concept_name_columns = ["concept_id","name","locale","creator","date_created","uuid","concept_name_type","locale_preferred"]
cur.execute("SELECT " + ",".join(concept_name_columns) + " FROM concept_name WHERE concept_id IN (" + ",".join([str(i) for i in old_concept_ids]) + ") AND voided=0;")
for row in cur:
    values = escape(row, conn)
    values[0] = str(renumber(row[0]));
    print(insert("concept_name", concept_name_columns, values).encode('utf-8'))
cur.close()

print('\n#\n# Client specific name changes for all concepts\n#')
# Copy all client specific name changes, these can be found from our custom locale.
cur = conn.cursor()
# Use REPLACE (MySQL specific) in case any were also done in above step
cur.execute("SELECT " + ",".join(concept_name_columns) + " FROM concept_name where locale LIKE '%_client' and voided=0 ORDER BY concept_id")
for row in cur:
    values = escape(row, conn)
    values[0] = str(renumber(row[0]));
    print(insert("concept_name", concept_name_columns, values, replace=True).encode('utf-8'))
cur.close()

# We need to find any changes we have made to concept answers. Tricky. We have almost certainly done this via the UI.
# We will use the fact that having too many is not bad, but having too few is, and 3 heuristics:
# 1) The original concept_answer_uuid from the original database is filled with 'CCCCCC'
# 2) The original sort_weight is the concept_answer_id
# 3) The original creator was 1
# We can't just get our new answers, we also need to find any changes we made to answer order ids.
# The way we will do this is use the 3 heuristics aboce to find any potentially changed questions (concept_id)
# then dump all answers for those questions, to get the sort weights right.
# We will also dump all previous answers for those concepts

print('\n#\n# Buendia specific associations between questions and answers, or changes in ordering of answers\n#')
questions = set()
cur = conn.cursor()
cur.execute("SELECT concept_id FROM concept_answer WHERE sort_weight != concept_answer_id OR creator != 1 OR uuid NOT LIKE '%CCCCC';")
for row in cur:
    questions.add(row[0])
cur.close()
print('DELETE FROM concept_answer WHERE concept_id IN (' + ",".join([str(i) for i in questions]) + ');')

# update the answers
print('# Answer updates')
answers = set()
cur = conn.cursor()
cur.execute("SELECT * FROM concept_answer WHERE concept_id IN (" + ",".join([str(i) for i in questions]) + ") ORDER BY concept_id,concept_answer_id;")
columns = [col[0] for col in cur.description]
concept_answer_next_id = concept_base_id
for row in cur:
    id = concept_answer_next_id
    concept_answer_next_id = concept_answer_next_id + 1
    values = escape(row, conn)

    # Renumber the concepts from our concept renumber map
    for i in range(len(columns)):
        if columns[i] == 'concept_id':
            values[i] = str(renumber(row[i]))
        if columns[i] == 'answer_concept':
            values[i] = str(renumber(row[i]))
            answers.add(row[i])

    # Renumber the concept_answers. O(n) lookup, but that's fine
    for i in range(len(columns)):
        if columns[i] in ['concept_answer_id']:
            values[i] = str(id)
    print(insert('concept_answer', columns, values).encode('utf-8'))
cur.close()

# Make sure we update all concept class/datatypes for these questions and answer concepts too
print('# Data type updates')
cur = conn.cursor()
cur.execute("SELECT concept_id,datatype_id FROM concept WHERE concept_id IN (" + ",".join([str(i) for i in questions.union(answers)])+ ");")
for row in cur:
    concept_id = row[0]
    datatype_id = row[1]
    if concept_id not in concept_renumber: # coded
        print("UPDATE concept SET datatype_id=" + str(datatype_id) + " WHERE concept_id=" + str(concept_id) + ";")

print('\n#\n# Update forms to renumbered concepts\n#')
# As we have done renumbering, renumber all the forms to use the new concept numbers.
for old_id in old_concept_ids + ciel_contributions.keys():
    print("UPDATE field SET concept_id=" + str(renumber(old_id)) + " WHERE concept_id=" + str(old_id) + ";")

# Hopefully data has been wiped too, but in case it hasn't
print('\n#\n# Update observations to renumbered concepts\n#')
for old_id in old_concept_ids + ciel_contributions.keys():
    print("UPDATE obs SET concept_id=" + str(renumber(old_id)) + " WHERE concept_id=" + str(old_id) + ";")
    print("UPDATE obs SET value_coded=" + str(renumber(old_id)) + " WHERE value_coded=" + str(old_id) + ";")

conn.close()


text:
ToDoList
========
This is a sample project for GREAT Training Program 19 - 20 September 2014

ToDo List project

### OW OW OW IT'S MAGIC ###

redpajama_set_name: RedPajamaGithub


text:
/**
* zmultiselect6
* v0.0.6 (2020-12-16)
* @author: Andrea Mariani
* @email: andrea.mariani@fasys.it
* @twitter: @andreamariani2k
* @web: www.fasys.it
*/

/*!
MIT LICENSE

Copyright (c) 2020 Andrea Mariani

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.
!*/
!function(a){"use strict";a.zmultiselect_i18n=a.extend(a.zmultiselect_i18n||{},{"it-IT":{"Check all":"Seleziona tutto","Uncheck all":"Deseleziona tutto",Search:"Cerca...",Selected:"Selezionati",of:"di",showed:"Visualizzati"}})}(jQuery);


text:
var headerHtml = require('./header.html');

$(function(){
    $('header').html(headerHtml);
    $("#jqxMenu").jqxMenu({ width: '100%', height: '30px' });
});


text:
module RExtensions
  module ActionView
    module Helpers
      module TranslationHelper

        #alias_method :default_translate, :translate

        # Override the built in Rails translation method to handle Textile
        # formatting in translation files (i.e. WYSIWYMean-ish translations)
        def translate(key, options = {})
          super(key, options).to_s.textilize(:trim => true)
        end

      end
    end
  end
end


text:
def foo(some_pa<caret>ram: str):
    pass


text:
//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/ArgumentsAdjusters.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "gtest/gtest.h"
#include <algorithm>
#include <string>
#include <vector>

namespace clang {
namespace tooling {

namespace {
/// Takes an ast consumer and returns it from CreateASTConsumer. This only
/// works with single translation unit compilations.
class TestAction : public clang::ASTFrontendAction {
public:
  /// Takes ownership of TestConsumer.
  explicit TestAction(std::unique_ptr<clang::ASTConsumer> TestConsumer)
      : TestConsumer(std::move(TestConsumer)) {}

protected:
  std::unique_ptr<clang::ASTConsumer>
  CreateASTConsumer(clang::CompilerInstance &compiler,
                    StringRef dummy) override {
    /// TestConsumer will be deleted by the framework calling us.
    return std::move(TestConsumer);
  }

private:
  std::unique_ptr<clang::ASTConsumer> TestConsumer;
};

class FindTopLevelDeclConsumer : public clang::ASTConsumer {
 public:
  explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
      : FoundTopLevelDecl(FoundTopLevelDecl) {}
  bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) override {
    *FoundTopLevelDecl = true;
    return true;
  }
 private:
  bool * const FoundTopLevelDecl;
};
} // end namespace

TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) {
  bool FoundTopLevelDecl = false;
  EXPECT_TRUE(runToolOnCode(
      std::make_unique<TestAction>(
          std::make_unique<FindTopLevelDeclConsumer>(&FoundTopLevelDecl)),
      ""));
  EXPECT_FALSE(FoundTopLevelDecl);
}

namespace {
class FindClassDeclXConsumer : public clang::ASTConsumer {
 public:
  FindClassDeclXConsumer(bool *FoundClassDeclX)
      : FoundClassDeclX(FoundClassDeclX) {}
  bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) override {
    if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
            *GroupRef.begin())) {
      if (Record->getName() == "X") {
        *FoundClassDeclX = true;
      }
    }
    return true;
  }
 private:
  bool *FoundClassDeclX;
};
bool FindClassDeclX(ASTUnit *AST) {
  for (std::vector<Decl *>::iterator i = AST->top_level_begin(),
                                     e = AST->top_level_end();
       i != e; ++i) {
    if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) {
      if (Record->getName() == "X") {
        return true;
      }
    }
  }
  return false;
}
} // end namespace

TEST(runToolOnCode, FindsClassDecl) {
  bool FoundClassDeclX = false;
  EXPECT_TRUE(runToolOnCode(
      std::make_unique<TestAction>(
          std::make_unique<FindClassDeclXConsumer>(&FoundClassDeclX)),
      "class X;"));
  EXPECT_TRUE(FoundClassDeclX);

  FoundClassDeclX = false;
  EXPECT_TRUE(runToolOnCode(
      std::make_unique<TestAction>(
          std::make_unique<FindClassDeclXConsumer>(&FoundClassDeclX)),
      "class Y;"));
  EXPECT_FALSE(FoundClassDeclX);
}

TEST(buildASTFromCode, FindsClassDecl) {
  std::unique_ptr<ASTUnit> AST = buildASTFromCode("class X;");
  ASSERT_TRUE(AST.get());
  EXPECT_TRUE(FindClassDeclX(AST.get()));

  AST = buildASTFromCode("class Y;");
  ASSERT_TRUE(AST.get());
  EXPECT_FALSE(FindClassDeclX(AST.get()));
}

TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
  std::unique_ptr<FrontendActionFactory> Factory(
      newFrontendActionFactory<SyntaxOnlyAction>());
  std::unique_ptr<FrontendAction> Action(Factory->create());
  EXPECT_TRUE(Action.get() != nullptr);
}

struct IndependentFrontendActionCreator {
  std::unique_ptr<ASTConsumer> newASTConsumer() {
    return std::make_unique<FindTopLevelDeclConsumer>(nullptr);
  }
};

TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
  IndependentFrontendActionCreator Creator;
  std::unique_ptr<FrontendActionFactory> Factory(
      newFrontendActionFactory(&Creator));
  std::unique_ptr<FrontendAction> Action(Factory->create());
  EXPECT_TRUE(Action.get() != nullptr);
}

TEST(ToolInvocation, TestMapVirtualFile) {
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
      new llvm::vfs::InMemoryFileSystem);
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
  llvm::IntrusiveRefCntPtr<FileManager> Files(
      new FileManager(FileSystemOptions(), OverlayFileSystem));
  std::vector<std::string> Args;
  Args.push_back("tool-executable");
  Args.push_back("-Idef");
  Args.push_back("-fsyntax-only");
  Args.push_back("test.cpp");
  clang::tooling::ToolInvocation Invocation(
      Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
  InMemoryFileSystem->addFile(
      "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n"));
  InMemoryFileSystem->addFile("def/abc", 0,
                              llvm::MemoryBuffer::getMemBuffer("\n"));
  EXPECT_TRUE(Invocation.run());
}

TEST(ToolInvocation, TestVirtualModulesCompilation) {
  // FIXME: Currently, this only tests that we don't exit with an error if a
  // mapped module.map is found on the include path. In the future, expand this
  // test to run a full modules enabled compilation, so we make sure we can
  // rerun modules compilations with a virtual file system.
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
      new llvm::vfs::InMemoryFileSystem);
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
  llvm::IntrusiveRefCntPtr<FileManager> Files(
      new FileManager(FileSystemOptions(), OverlayFileSystem));
  std::vector<std::string> Args;
  Args.push_back("tool-executable");
  Args.push_back("-Idef");
  Args.push_back("-fsyntax-only");
  Args.push_back("test.cpp");
  clang::tooling::ToolInvocation Invocation(
      Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
  InMemoryFileSystem->addFile(
      "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n"));
  InMemoryFileSystem->addFile("def/abc", 0,
                              llvm::MemoryBuffer::getMemBuffer("\n"));
  // Add a module.map file in the include directory of our header, so we trigger
  // the module.map header search logic.
  InMemoryFileSystem->addFile("def/module.map", 0,
                              llvm::MemoryBuffer::getMemBuffer("\n"));
  EXPECT_TRUE(Invocation.run());
}

struct VerifyEndCallback : public SourceFileCallbacks {
  VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {}
  bool handleBeginSource(CompilerInstance &CI) override {
    ++BeginCalled;
    return true;
  }
  void handleEndSource() override { ++EndCalled; }
  std::unique_ptr<ASTConsumer> newASTConsumer() {
    return std::make_unique<FindTopLevelDeclConsumer>(&Matched);
  }
  unsigned BeginCalled;
  unsigned EndCalled;
  bool Matched;
};

#if !defined(_WIN32)
TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) {
  VerifyEndCallback EndCallback;

  FixedCompilationDatabase Compilations("/", std::vector<std::string>());
  std::vector<std::string> Sources;
  Sources.push_back("/a.cc");
  Sources.push_back("/b.cc");
  ClangTool Tool(Compilations, Sources);

  Tool.mapVirtualFile("/a.cc", "void a() {}");
  Tool.mapVirtualFile("/b.cc", "void b() {}");

  std::unique_ptr<FrontendActionFactory> Action(
      newFrontendActionFactory(&EndCallback, &EndCallback));
  Tool.run(Action.get());

  EXPECT_TRUE(EndCallback.Matched);
  EXPECT_EQ(2u, EndCallback.BeginCalled);
  EXPECT_EQ(2u, EndCallback.EndCalled);
}
#endif

struct SkipBodyConsumer : public clang::ASTConsumer {
  /// Skip the 'skipMe' function.
  bool shouldSkipFunctionBody(Decl *D) override {
    NamedDecl *F = dyn_cast<NamedDecl>(D);
    return F && F->getNameAsString() == "skipMe";
  }
};

struct SkipBodyAction : public clang::ASTFrontendAction {
  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
                                                 StringRef) override {
    Compiler.getFrontendOpts().SkipFunctionBodies = true;
    return std::make_unique<SkipBodyConsumer>();
  }
};

TEST(runToolOnCode, TestSkipFunctionBody) {
  std::vector<std::string> Args = {"-std=c++11"};
  std::vector<std::string> Args2 = {"-fno-delayed-template-parsing"};

  EXPECT_TRUE(runToolOnCode(std::make_unique<SkipBodyAction>(),
                            "int skipMe() { an_error_here }"));
  EXPECT_FALSE(runToolOnCode(std::make_unique<SkipBodyAction>(),
                             "int skipMeNot() { an_error_here }"));

  // Test constructors with initializers
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<SkipBodyAction>(),
      "struct skipMe { skipMe() : an_error() { more error } };", Args));
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe(); };"
                          "skipMe::skipMe() : an_error([](){;}) { more error }",
      Args));
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe(); };"
                          "skipMe::skipMe() : an_error{[](){;}} { more error }",
      Args));
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<SkipBodyAction>(),
      "struct skipMe { skipMe(); };"
      "skipMe::skipMe() : a<b<c>(e)>>(), f{}, g() { error }",
      Args));
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe() : bases()... { error } };",
      Args));

  EXPECT_FALSE(runToolOnCodeWithArgs(
      std::make_unique<SkipBodyAction>(), "struct skipMeNot { skipMeNot() : an_error() { } };",
      Args));
  EXPECT_FALSE(runToolOnCodeWithArgs(std::make_unique<SkipBodyAction>(),
                                     "struct skipMeNot { skipMeNot(); };"
                                     "skipMeNot::skipMeNot() : an_error() { }",
                                     Args));

  // Try/catch
  EXPECT_TRUE(runToolOnCode(
      std::make_unique<SkipBodyAction>(),
      "void skipMe() try { an_error() } catch(error) { error };"));
  EXPECT_TRUE(runToolOnCode(
      std::make_unique<SkipBodyAction>(),
      "struct S { void skipMe() try { an_error() } catch(error) { error } };"));
  EXPECT_TRUE(
      runToolOnCode(std::make_unique<SkipBodyAction>(),
                    "void skipMe() try { an_error() } catch(error) { error; }"
                    "catch(error) { error } catch (error) { }"));
  EXPECT_FALSE(runToolOnCode(
      std::make_unique<SkipBodyAction>(),
      "void skipMe() try something;")); // don't crash while parsing

  // Template
  EXPECT_TRUE(runToolOnCode(
      std::make_unique<SkipBodyAction>(), "template<typename T> int skipMe() { an_error_here }"
                          "int x = skipMe<int>();"));
  EXPECT_FALSE(runToolOnCodeWithArgs(
      std::make_unique<SkipBodyAction>(),
      "template<typename T> int skipMeNot() { an_error_here }", Args2));
}

TEST(runToolOnCodeWithArgs, TestNoDepFile) {
  llvm::SmallString<32> DepFilePath;
  ASSERT_FALSE(llvm::sys::fs::getPotentiallyUniqueTempFileName("depfile", "d",
                                                               DepFilePath));
  std::vector<std::string> Args;
  Args.push_back("-MMD");
  Args.push_back("-MT");
  Args.push_back(DepFilePath.str());
  Args.push_back("-MF");
  Args.push_back(DepFilePath.str());
  EXPECT_TRUE(runToolOnCodeWithArgs(std::make_unique<SkipBodyAction>(), "", Args));
  EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str()));
  EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
}

struct CheckColoredDiagnosticsAction : public clang::ASTFrontendAction {
  CheckColoredDiagnosticsAction(bool ShouldShowColor)
      : ShouldShowColor(ShouldShowColor) {}
  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
                                                 StringRef) override {
    if (Compiler.getDiagnosticOpts().ShowColors != ShouldShowColor)
      Compiler.getDiagnostics().Report(
          Compiler.getDiagnostics().getCustomDiagID(
              DiagnosticsEngine::Fatal,
              "getDiagnosticOpts().ShowColors != ShouldShowColor"));
    return std::make_unique<ASTConsumer>();
  }

private:
  bool ShouldShowColor = true;
};

TEST(runToolOnCodeWithArgs, DiagnosticsColor) {
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<CheckColoredDiagnosticsAction>(true), "",
      {"-fcolor-diagnostics"}));
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<CheckColoredDiagnosticsAction>(false), "",
      {"-fno-color-diagnostics"}));
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<CheckColoredDiagnosticsAction>(true), "",
      {"-fno-color-diagnostics", "-fcolor-diagnostics"}));
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<CheckColoredDiagnosticsAction>(false), "",
      {"-fcolor-diagnostics", "-fno-color-diagnostics"}));
  EXPECT_TRUE(runToolOnCodeWithArgs(
      std::make_unique<CheckColoredDiagnosticsAction>(true), "",
      {"-fno-color-diagnostics", "-fdiagnostics-color=always"}));

  // Check that this test would fail if ShowColors is not what it should.
  EXPECT_FALSE(runToolOnCodeWithArgs(
      std::make_unique<CheckColoredDiagnosticsAction>(false), "",
      {"-fcolor-diagnostics"}));
}

TEST(ClangToolTest, ArgumentAdjusters) {
  FixedCompilationDatabase Compilations("/", std::vector<std::string>());

  ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
  Tool.mapVirtualFile("/a.cc", "void a() {}");

  std::unique_ptr<FrontendActionFactory> Action(
      newFrontendActionFactory<SyntaxOnlyAction>());

  bool Found = false;
  bool Ran = false;
  ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
      [&Found, &Ran](const CommandLineArguments &Args, StringRef /*unused*/) {
    Ran = true;
    if (llvm::is_contained(Args, "-fsyntax-only"))
      Found = true;
    return Args;
  };
  Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
  Tool.run(Action.get());
  EXPECT_TRUE(Ran);
  EXPECT_TRUE(Found);

  Ran = Found = false;
  Tool.clearArgumentsAdjusters();
  Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
  Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
  Tool.run(Action.get());
  EXPECT_TRUE(Ran);
  EXPECT_FALSE(Found);
}

TEST(ClangToolTest, NoDoubleSyntaxOnly) {
  FixedCompilationDatabase Compilations("/", {"-fsyntax-only"});

  ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
  Tool.mapVirtualFile("/a.cc", "void a() {}");

  std::unique_ptr<FrontendActionFactory> Action(
      newFrontendActionFactory<SyntaxOnlyAction>());

  size_t SyntaxOnlyCount = 0;
  ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
      [&SyntaxOnlyCount](const CommandLineArguments &Args,
                         StringRef /*unused*/) {
        for (llvm::StringRef Arg : Args) {
          if (Arg == "-fsyntax-only")
            ++SyntaxOnlyCount;
        }
        return Args;
      };

  Tool.clearArgumentsAdjusters();
  Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
  Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
  Tool.run(Action.get());
  EXPECT_EQ(SyntaxOnlyCount, 1U);
}

TEST(ClangToolTest, NoOutputCommands) {
  FixedCompilationDatabase Compilations("/", {"-save-temps", "-save-temps=cwd",
                                              "--save-temps",
                                              "--save-temps=somedir"});

  ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
  Tool.mapVirtualFile("/a.cc", "void a() {}");

  std::unique_ptr<FrontendActionFactory> Action(
      newFrontendActionFactory<SyntaxOnlyAction>());

  const std::vector<llvm::StringRef> OutputCommands = {"-save-temps"};
  bool Ran = false;
  ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
      [&OutputCommands, &Ran](const CommandLineArguments &Args,
                              StringRef /*unused*/) {
        for (llvm::StringRef Arg : Args) {
          for (llvm::StringRef OutputCommand : OutputCommands)
            EXPECT_FALSE(Arg.contains(OutputCommand));
        }
        Ran = true;
        return Args;
      };

  Tool.clearArgumentsAdjusters();
  Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
  Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
  Tool.run(Action.get());
  EXPECT_TRUE(Ran);
}

TEST(ClangToolTest, BaseVirtualFileSystemUsage) {
  FixedCompilationDatabase Compilations("/", std::vector<std::string>());
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
      new llvm::vfs::InMemoryFileSystem);
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);

  InMemoryFileSystem->addFile(
      "a.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}"));

  ClangTool Tool(Compilations, std::vector<std::string>(1, "a.cpp"),
                 std::make_shared<PCHContainerOperations>(), OverlayFileSystem);
  std::unique_ptr<FrontendActionFactory> Action(
      newFrontendActionFactory<SyntaxOnlyAction>());
  EXPECT_EQ(0, Tool.run(Action.get()));
}

// Check getClangStripDependencyFileAdjuster doesn't strip args after -MD/-MMD.
TEST(ClangToolTest, StripDependencyFileAdjuster) {
  FixedCompilationDatabase Compilations("/", {"-MD", "-c", "-MMD", "-w"});

  ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
  Tool.mapVirtualFile("/a.cc", "void a() {}");

  std::unique_ptr<FrontendActionFactory> Action(
      newFrontendActionFactory<SyntaxOnlyAction>());

  CommandLineArguments FinalArgs;
  ArgumentsAdjuster CheckFlagsAdjuster =
    [&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) {
      FinalArgs = Args;
      return Args;
    };
  Tool.clearArgumentsAdjusters();
  Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
  Tool.appendArgumentsAdjuster(CheckFlagsAdjuster);
  Tool.run(Action.get());

  auto HasFlag = [&FinalArgs](const std::string &Flag) {
    return llvm::find(FinalArgs, Flag) != FinalArgs.end();
  };
  EXPECT_FALSE(HasFlag("-MD"));
  EXPECT_FALSE(HasFlag("-MMD"));
  EXPECT_TRUE(HasFlag("-c"));
  EXPECT_TRUE(HasFlag("-w"));
}

// Check getClangStripPluginsAdjuster strips plugin related args.
TEST(ClangToolTest, StripPluginsAdjuster) {
  FixedCompilationDatabase Compilations(
      "/", {"-Xclang", "-add-plugin", "-Xclang", "random-plugin"});

  ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
  Tool.mapVirtualFile("/a.cc", "void a() {}");

  std::unique_ptr<FrontendActionFactory> Action(
      newFrontendActionFactory<SyntaxOnlyAction>());

  CommandLineArguments FinalArgs;
  ArgumentsAdjuster CheckFlagsAdjuster =
      [&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) {
        FinalArgs = Args;
        return Args;
      };
  Tool.clearArgumentsAdjusters();
  Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
  Tool.appendArgumentsAdjuster(CheckFlagsAdjuster);
  Tool.run(Action.get());

  auto HasFlag = [&FinalArgs](const std::string &Flag) {
    return llvm::find(FinalArgs, Flag) != FinalArgs.end();
  };
  EXPECT_FALSE(HasFlag("-Xclang"));
  EXPECT_FALSE(HasFlag("-add-plugin"));
  EXPECT_FALSE(HasFlag("-random-plugin"));
}

namespace {
/// Find a target name such that looking for it in TargetRegistry by that name
/// returns the same target. We expect that there is at least one target
/// configured with this property.
std::string getAnyTarget() {
  llvm::InitializeAllTargets();
  for (const auto &Target : llvm::TargetRegistry::targets()) {
    std::string Error;
    StringRef TargetName(Target.getName());
    if (TargetName == "x86-64")
      TargetName = "x86_64";
    if (llvm::TargetRegistry::lookupTarget(TargetName, Error) == &Target) {
      return TargetName;
    }
  }
  return "";
}
}

TEST(addTargetAndModeForProgramName, AddsTargetAndMode) {
  std::string Target = getAnyTarget();
  ASSERT_FALSE(Target.empty());

  std::vector<std::string> Args = {"clang", "-foo"};
  addTargetAndModeForProgramName(Args, "");
  EXPECT_EQ((std::vector<std::string>{"clang", "-foo"}), Args);
  addTargetAndModeForProgramName(Args, Target + "-g++");
  EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target,
                                      "--driver-mode=g++", "-foo"}),
            Args);
}

TEST(addTargetAndModeForProgramName, PathIgnored) {
  std::string Target = getAnyTarget();
  ASSERT_FALSE(Target.empty());

  SmallString<32> ToolPath;
  llvm::sys::path::append(ToolPath, "foo", "bar", Target + "-g++");

  std::vector<std::string> Args = {"clang", "-foo"};
  addTargetAndModeForProgramName(Args, ToolPath);
  EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target,
                                      "--driver-mode=g++", "-foo"}),
            Args);
}

TEST(addTargetAndModeForProgramName, IgnoresExistingTarget) {
  std::string Target = getAnyTarget();
  ASSERT_FALSE(Target.empty());

  std::vector<std::string> Args = {"clang", "-foo", "-target", "something"};
  addTargetAndModeForProgramName(Args, Target + "-g++");
  EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo",
                                      "-target", "something"}),
            Args);

  std::vector<std::string> ArgsAlt = {"clang", "-foo", "-target=something"};
  addTargetAndModeForProgramName(ArgsAlt, Target + "-g++");
  EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo",
                                      "-target=something"}),
            ArgsAlt);
}

TEST(addTargetAndModeForProgramName, IgnoresExistingMode) {
  std::string Target = getAnyTarget();
  ASSERT_FALSE(Target.empty());

  std::vector<std::string> Args = {"clang", "-foo", "--driver-mode=abc"};
  addTargetAndModeForProgramName(Args, Target + "-g++");
  EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target, "-foo",
                                      "--driver-mode=abc"}),
            Args);

  std::vector<std::string> ArgsAlt = {"clang", "-foo", "--driver-mode", "abc"};
  addTargetAndModeForProgramName(ArgsAlt, Target + "-g++");
  EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target, "-foo",
                                      "--driver-mode", "abc"}),
            ArgsAlt);
}

#ifndef _WIN32
TEST(ClangToolTest, BuildASTs) {
  FixedCompilationDatabase Compilations("/", std::vector<std::string>());

  std::vector<std::string> Sources;
  Sources.push_back("/a.cc");
  Sources.push_back("/b.cc");
  ClangTool Tool(Compilations, Sources);

  Tool.mapVirtualFile("/a.cc", "void a() {}");
  Tool.mapVirtualFile("/b.cc", "void b() {}");

  std::vector<std::unique_ptr<ASTUnit>> ASTs;
  EXPECT_EQ(0, Tool.buildASTs(ASTs));
  EXPECT_EQ(2u, ASTs.size());
}

struct TestDiagnosticConsumer : public DiagnosticConsumer {
  TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {}
  void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
                        const Diagnostic &Info) override {
    ++NumDiagnosticsSeen;
  }
  unsigned NumDiagnosticsSeen;
};

TEST(ClangToolTest, InjectDiagnosticConsumer) {
  FixedCompilationDatabase Compilations("/", std::vector<std::string>());
  ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
  Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
  TestDiagnosticConsumer Consumer;
  Tool.setDiagnosticConsumer(&Consumer);
  std::unique_ptr<FrontendActionFactory> Action(
      newFrontendActionFactory<SyntaxOnlyAction>());
  Tool.run(Action.get());
  EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
}

TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) {
  FixedCompilationDatabase Compilations("/", std::vector<std::string>());
  ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
  Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
  TestDiagnosticConsumer Consumer;
  Tool.setDiagnosticConsumer(&Consumer);
  std::vector<std::unique_ptr<ASTUnit>> ASTs;
  Tool.buildASTs(ASTs);
  EXPECT_EQ(1u, ASTs.size());
  EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
}
#endif

TEST(runToolOnCode, TestResetDiagnostics) {
  // This is a tool that resets the diagnostic during the compilation.
  struct ResetDiagnosticAction : public clang::ASTFrontendAction {
    std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
                                                   StringRef) override {
      struct Consumer : public clang::ASTConsumer {
        bool HandleTopLevelDecl(clang::DeclGroupRef D) override {
          auto &Diags = (*D.begin())->getASTContext().getDiagnostics();
          // Ignore any error
          Diags.Reset();
          // Disable warnings because computing the CFG might crash.
          Diags.setIgnoreAllWarnings(true);
          return true;
        }
      };
      return std::make_unique<Consumer>();
    }
  };

  // Should not crash
  EXPECT_FALSE(
      runToolOnCode(std::make_unique<ResetDiagnosticAction>(),
                    "struct Foo { Foo(int); ~Foo(); struct Fwd _fwd; };"
                    "void func() { long x; Foo f(x); }"));
}

} // end namespace tooling
} // end namespace clang


text:
[![npm version](https://badge.fury.io/js/fuzzyis.svg)](https://badge.fury.io/js/fuzzyis)

It is a JavaScript library for building fuzzy inference systems.
Build your own system right in browser or with nodejs.

Install it!

`npm install fuzzyis`

Browser-ready minified version available at `/dist` directory.
Nodejs usage:
`const fuzzyis = require('fuzzyis');`

FuzzyIS contains 4 core objects:

* **LinguisticVariable** - thing described by fuzzy-terms like *fast / slow*, *tall / low*, *hot / cold* etc...
* **Term** - mentioned fuzzy term itself
* **Rule** - thing which describes connection between input and output linguistic variables. These are conditions like: "if **food** is *tasty* AND **service** is *great* -> **tip** should be *generous*", which describes how system works.
* **FIS** - fuzzy inference system. It is created with input and output linguistic variables and with described rules.
FIS calculates precise values for output linguistic variables from precise values of input variables referring to the rules given.

## Example about the tip

Let's see how we can model simple fuzzy inference system. I'll provide an example which works in nodejs environment. For browser it should be the same (full source of example see in `example` folder).

First of all, install `fuzzyis` with `npm i fuzzyis` then import it. And init new fuzzy inference system.

```javascript
const fuzzyis = require('fuzzyis');
const {LinguisticVariable, Term, Rule, FIS} = fuzzyis;

// describe new system, input and output variables

const system = new FIS('Tip system');
```

We need to know how much we should leave for officiant in percentage terms. Tip is output linguistic variable. We suppose it could be 'small', 'average' or 'generous'. And in precise values it could be from 0 to 30% from bill.

```javascript
// init and add variables into system

const TIP = new LinguisticVariable('tip', [0, 30]);
system.addOutput(TIP);
```

We'll draw our conclusion about the tip based on the quality of service and food quality. Food and Service are input linguistic variables.
Let's agree that Food could be only 'bad' or 'good'. Service could be 'poor', 'normal', 'excellent'. We'll rate them both from 0 to 10 on an imaginary scale.

```javascript
const FOOD = new LinguisticVariable('service', [0, 10]);
const SERVICE = new LinguisticVariable('food', [0, 10]);

system.addInput(SERVICE);
system.addInput(FOOD);
```

Now we should explain our fuzzy terms to the system and create the mentioned terms. Each term is described by a function.

Let's define what "good" and "bad" **food** mean in terms of the imaginary 0 to 10 scale.

![food](https://cloud.githubusercontent.com/assets/4989157/21298567/db682a84-c5e6-11e6-85d5-2469cfc729f0.png)

Same thing for **service** terms:

![service](https://cloud.githubusercontent.com/assets/4989157/21298562/be79342c-c5e6-11e6-8d87-27912258a418.png)

And for **tip**:

![tip](https://cloud.githubusercontent.com/assets/4989157/21298571/eceb88be-c5e6-11e6-8752-b53de217e6b9.png)

Code it:

```javascript
// describe terms for each variable

SERVICE.addTerm(new Term('poor', 'gauss', [2.123, 0]));
SERVICE.addTerm(new Term('normal', 'gauss', [2.123, 5]));
SERVICE.addTerm(new Term('excellent', 'gauss', [2.123, 10]));

FOOD.addTerm(new Term('bad', 'trapeze', [0, 0, 1, 3]));
FOOD.addTerm(new Term('good', 'trapeze', [7, 9, 10, 10]));

TIP.addTerm(new Term('small', 'triangle', [0, 5, 10]));
TIP.addTerm(new Term('average', 'triangle', [10, 15, 20]));
TIP.addTerm(new Term('generous', 'triangle', [20, 25, 30]));
```

Now we should explain how tip depend on food and service to our system. Let's agree that the rules are as follows:

> if **service** is *poor* AND **food** is *bad* -> **tip** is *small*

> if **service** is *normal* -> **tip** is *average*

> if **service** is *excellent* AND **food** is *good* -> **tip** is *generous*

```javascript
// NB! It's important to preserve the same order in description
// as you had when defined inputs
// e.g. if you've added SERVICE first, then first value should be one of the possible values for this variable

system.rules = [
  new Rule(
      ['poor', 'bad'],
      ['small'],
      'and'
  ),
  new Rule(
      ['normal', null],
      ['average'],
      'and'
  ),
  new Rule(
      ['excellent', 'good'],
      ['generous'],
      'and'
  )
];
```

Now we have described our system and can ask it to calculate tip (will print result in console):

```
console.log(
  system.getPreciseOutput([7.892, 7.41])
);
```

Result is `[17.40000000000002]`

* `getPreciseOutput` returns an array with values of output variables.


text:
// No features are needed for this test.
var xml = xmlHelper.getXmlObject(config);

xml.head.link += <link rel="stylesheet" href="tests/misc/uri/sms.css" type="text/css" />;


text:
set -e

# We require a parameter for where to put the results
destination="$1"

# The locale identifiers for the languages you want to shoot
languages="en de"

# The iOS version we want to run the script against
ios_version="7.0"

function main {
  _check_destination

  # Attempt to save and restore the language the simulator SDKs were in before
  # running this. If you want to explicitly set the language, use the
  # `screenshooter/bin/choose_sim_language [lang]` after you run this script.
  original_language=$(screenshooter/bin/choose_sim_language)
  echo "Saving original language $original_language..."

  # We have to build and explicitly set the device family to iPhone because
  # otherwise Instruments will always try to launch a universal app on the iPad
  # simulator.
  #
  # If your app isn't universal and only on iPhone or iPad, then you can remove
  # the parts that don't matter for you.
  _xcode clean build TARGETED_DEVICE_FAMILY=1
  screenshooter/bin/choose_sim_device "iPhone Retina (3.5-inch)"
  _shoot_screens_for_all_languages

  screenshooter/bin/close_sim

  screenshooter/bin/choose_sim_device "iPhone Retina (4-inch)"
  _shoot_screens_for_all_languages

  # We have to build again with the iPad device family because otherwise
  # Instruments will only launch the app as we built it before, for the iPhone
  # simulator.
#  _xcode build TARGETED_DEVICE_FAMILY=2
#  screenshooter/bin/choose_sim_device "iPad Retina"
#  _shoot_screens_for_all_languages

  screenshooter/bin/close_sim

  echo "Restoring original language $original_language..."
  screenshooter/bin/choose_sim_language $original_language

  echo
  echo "Screenshots complete!"
}

# Global variables to keep track of where everything goes
destination="screenshots"
tmp_dir="/tmp"
build_dir="$tmp_dir/screen_shooter"
bundle_dir="$build_dir/Bremensa.app"
trace_results_dir="$build_dir/traces"

function _check_destination {
  # Abort if the destination directory already exists. Better safe than sorry.

  if [ -z "$destination" ]; then
    echo "usage: run_screenshooter.sh destination_directory"
    exit 1
  elif [ -d "$destination" ]; then
    echo "Destination directory \"$destination\" already exists! Aborting."
    exit 1
  fi
}

function _shoot_screens_for_all_languages {
  # Loop over all the $languages (set at the top of the script) and execute the
  # automation screen for each one, copying the screenshots to the destination
  # each time

  for language in $languages; do
    _clean_trace_results_dir
    screenshooter/bin/choose_sim_language $language
    _run_automation "screenshooter/automation/take_screenshots.js"
  done
}

function _xcode {
  # A wrapper around `xcodebuild` that tells it to build the app in the temp
  # directory. If your app uses workspaces or special schemes, you'll need to
  # specify them here.
  #
  # Use `man xcodebuild` for more information on how to build your project.

  xcodebuild -workspace BreMensa.xcworkspace -scheme Screenshots -sdk "iphonesimulator$ios_version" CONFIGURATION_BUILD_DIR=$build_dir PRODUCT_NAME=BreMensa
}

function _clean_trace_results_dir {
  # Removes the trace results directory. We need to do this because Instruments
  # keeps appending new trace runs and it's simpler for us to always assume
  # there's just one run recorded where we look for screenshots.

  rm -rf "$trace_results_dir"
  mkdir -p "$trace_results_dir"
}

function _run_automation {
  # Runs the UI Automation JavaScript file that actually takes the screenshots.

  dev_tools_dir=`xcode-select -print-path`
  tracetemplate="$dev_tools_dir/../Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate"

  # Check out the `unix_instruments` script to see why we need this wrapper.
  screenshooter/bin/unix_instruments \
    -D "$trace_results_dir/trace" \
    -t "$tracetemplate" \
    $bundle_dir \
    -e UIARESULTSPATH "$trace_results_dir" \
    -e UIASCRIPT "$1" \
    $*
}

function _copy_screenshots {
  # Since we're always clearing out the trace results before every run, we can
  # assume that any screenshots were saved in the "Run 1" directory. Copy them
  # to the destination!

  mkdir -p "$destination"
  cp $trace_results_dir/Run\ 1/*.png $destination
}

main


text:
Syntax highlighting for the ham language (a fork of Perforce's Jam).

Since Ham is basically the same language as Perforce's Jam this package also syntax highlights Jamfile, Jamrules & .jam files.


text:
// Copyright (c) 2005-2017 Poderosa Project, All Rights Reserved.
// This file is a part of the Granados SSH Client Library that is subject to
// the license included in the distributed package.
// You may not use this file except in compliance with the license.

namespace Granados {

    using System;
    using System.Collections.Concurrent;
    using System.Linq;
    using System.Reflection;

    ///
    /// Exception about SSH operation.
    ///
    public class SSHException : Exception {

        public SSHException(string message)
            : base(message) {
        }

        public SSHException(string message, Exception cause)
            : base(message, cause) {
        }

    }

    ///
    /// Attribute to define algorithm name.
    ///
    [AttributeUsage(AttributeTargets.Field)]
    public class AlgorithmSpecAttribute : Attribute {
        ///
        /// Algorithm name
        ///
        public string AlgorithmName {
            get;
            set;
        }

        ///
        /// Default priority
        ///
        /// <remarks>
        /// Larger number means higher priority.
        /// </remarks>
        public int DefaultPriority {
            get;
            set;
        }
    }

    ///
    /// Utility methods for accessing <see cref="AlgorithmSpecAttribute"/>.
    ///
    public static class AlgorithmSpecUtil<TEnum> {

        // prepare dictionary of AlgorithmSpecAttribute for each given generics type parameter.
        private static readonly ConcurrentDictionary<TEnum, AlgorithmSpecAttribute> _enumToSpec;

        static AlgorithmSpecUtil() {
            _enumToSpec = new ConcurrentDictionary<TEnum, AlgorithmSpecAttribute>();
            Type enumType = typeof(TEnum);
            if (enumType.IsEnum) {
                foreach (string enumName in enumType.GetEnumNames()) {
                    FieldInfo field = enumType.GetField(enumName, BindingFlags.Public | BindingFlags.Static);
                    TEnum enumValue = (TEnum)field.GetValue(null);
                    object[] attrs = field.GetCustomAttributes(typeof(AlgorithmSpecAttribute), false);
                    if (attrs.Length > 0) {
                        AlgorithmSpecAttribute spec = (AlgorithmSpecAttribute)attrs[0];
                        _enumToSpec.TryAdd(enumValue, spec);
                    }
                }
            }
        }

        ///
        /// Get algorithm name from <see cref="AlgorithmSpecAttribute"/> of the specified enum value.
        ///
        /// <param name="enumValue">enum value</param>
        /// <returns>algorithm name, or null if failed</returns>
        public static string GetAlgorithmName(TEnum enumValue) {
            AlgorithmSpecAttribute spec;
            if (_enumToSpec.TryGetValue(enumValue, out spec)) {
                return spec.AlgorithmName;
            }
            return null;
        }

        ///
        /// Get default priority from <see cref="AlgorithmSpecAttribute"/> of the specified enum value.
        ///
        /// <param name="enumValue">enum value</param>
        /// <returns>default priority, or <see cref="Int32.MinValue"/> if failed</returns>
        public static int GetDefaultPriority(TEnum enumValue) {
            AlgorithmSpecAttribute spec;
            if (_enumToSpec.TryGetValue(enumValue, out spec)) {
                return spec.DefaultPriority;
            }
            return Int32.MinValue;
        }

        ///
        /// Get all algorithm names about <typeparamref name="TEnum"/> in priority order.
        ///
        /// <returns>algorithm names sorted by the default priority (high priority first)</returns>
        public static string[] GetAlgorithmNamesByPriorityOrder() {
            return _enumToSpec
                    .OrderByDescending(kv => kv.Value.DefaultPriority)
                    .Select(kv => kv.Value.AlgorithmName)
                    .ToArray();
        }

        ///
        /// Get all <typeparamref name="TEnum"/> vales in priority order.
        ///
        /// <returns>algorithms sorted by the default priority (high priority first)</returns>
        public static TEnum[] GetAlgorithmsByPriorityOrder() {
            return _enumToSpec
                    .OrderByDescending(kv => kv.Value.DefaultPriority)
                    .Select(kv => kv.Key)
                    .ToArray();
        }
    }

    ///
    /// <ja>SSHプロトコルの種類を示します</ja>
    /// <en>Kind of SSH protocol</en>
    ///
    public enum SSHProtocol {
        ///
        /// <ja>SSH1</ja>
        /// <en>SSH1</en>
        ///
        SSH1,
        ///
        /// <ja>SSH2</ja>
        /// <en>SSH2</en>
        ///
        SSH2
    }

    ///
    /// <ja>
    /// アルゴリズムの種類を示します。
    /// </ja>
    /// <en>
    /// Kind of algorithm
    /// </en>
    ///
    public enum CipherAlgorithm {
        ///
        /// TripleDES
        ///
        [AlgorithmSpec(AlgorithmName = "TripleDES", DefaultPriority = 1)]
        TripleDES = 3,
        ///
        /// BlowFish
        ///
        [AlgorithmSpec(AlgorithmName = "Blowfish", DefaultPriority = 2)]
        Blowfish = 6,
        ///
        /// <ja>AES128(SSH2のみ有効)</ja>
        /// <en>AES128(SSH2 only)</en>
        ///
        [AlgorithmSpec(AlgorithmName = "AES128", DefaultPriority = 3)]
        AES128 = 10,
        ///
        /// <ja>AES192(SSH2のみ有効)</ja>
        /// <en>AES192(SSH2 only)</en>
        ///
        [AlgorithmSpec(AlgorithmName = "AES192", DefaultPriority = 5)]
        AES192 = 11,
        ///
        /// <ja>AES256(SSH2のみ有効)</ja>
        /// <en>AES256(SSH2 only)</en>
        ///
        [AlgorithmSpec(AlgorithmName = "AES256", DefaultPriority = 7)]
        AES256 = 12,
        ///
        /// <ja>AES128-CTR(SSH2のみ有効)</ja>
        /// <en>AES128-CTR(SSH2 only)</en>
        ///
        [AlgorithmSpec(AlgorithmName = "AES128CTR", DefaultPriority = 4)]
        AES128CTR = 13,
        ///
        /// <ja>AES192-CTR(SSH2のみ有効)</ja>
        /// <en>AES192-CTR(SSH2 only)</en>
        ///
        [AlgorithmSpec(AlgorithmName = "AES192CTR", DefaultPriority = 6)]
        AES192CTR = 14,
        ///
        /// <ja>AES256-CTR(SSH2のみ有効)</ja>
        /// <en>AES256-CTR(SSH2 only)</en>
        ///
        [AlgorithmSpec(AlgorithmName = "AES256CTR", DefaultPriority = 8)]
        AES256CTR = 15,
    }

    ///
    /// Extension methods for <see cref="CipherAlgorithm"/>
    ///
    public static class CipherAlgorithmMixin {

        public static string GetAlgorithmName(this CipherAlgorithm value) {
            return AlgorithmSpecUtil<CipherAlgorithm>.GetAlgorithmName(value);
        }

        public static int GetDefaultPriority(this CipherAlgorithm value) {
            return AlgorithmSpecUtil<CipherAlgorithm>.GetDefaultPriority(value);
        }
    }

    ///
    /// <ja>認証方式を示します。</ja>
    /// <en>Kind of authentification method</en>
    ///
    public enum AuthenticationType {
        ///
        /// <ja>公開鍵方式</ja>
        /// <en>Public key cryptosystem</en>
        ///
        PublicKey = 2, //uses identity file
        ///
        /// <ja>パスワード方式</ja>
        /// <en>Password Authentication</en>
        ///
        Password = 3,
        ///
        /// <ja>キーボードインタラクティブ</ja>
        /// <en>KeyboardInteractive</en>
        ///
        KeyboardInteractive = 4
    }

    ///
    /// <ja>
    /// 認証状態
    /// </ja>
    /// <en>
    /// Status of the authentication.
    /// </en>
    ///
    public enum AuthenticationStatus {
        ///
        /// <ja>認証がまだ開始されていない</ja>
        /// <en>The authentication has not started yet.</en>
        ///
        NotStarted,

        ///
        /// <ja>認証に成功</ja>
        /// <en>The authentication has succeeded.</en>
        ///
        Success,

        ///
        /// <ja>認証に失敗</ja>
        /// <en>The authentication has failed.</en>
        ///
        Failure,

        ///
        /// <ja>認証のためキー入力が必要(キーボードインタラクティブ認証)</ja>
        /// <en>Need keyboard input for the authentication (keyboard interactive authentication)</en>
        ///
        NeedKeyboardInput,
    }

    ///
    /// Disconnection reason code
    ///
    public enum DisconnectionReasonCode {
        /// SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT (SSH2)
        HostNotAllowedToConnect = 1,
        /// SSH_DISCONNECT_PROTOCOL_ERROR (SSH2)
        ProtocolError = 2,
        /// SSH_DISCONNECT_KEY_EXCHANGE_FAILED (SSH2)
        KeyExchangeFailed = 3,
        /// SSH_DISCONNECT_RESERVED (SSH2)
        Reserved = 4,
        /// SSH_DISCONNECT_MAC_ERROR (SSH2)
        MacError = 5,
        /// SSH_DISCONNECT_COMPRESSION_ERROR (SSH2)
        CompressionError = 6,
        /// SSH_DISCONNECT_SERVICE_NOT_AVAILABLE (SSH2)
        ServiceNotAvailable = 7,
        /// SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED (SSH2)
        ProtocolVersionNotSupported = 8,
        /// SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE (SSH2)
        HostKeyNotVerifiable = 9,
        /// SSH_DISCONNECT_CONNECTION_LOST (SSH2)
        ConnectionLost = 10,
        /// SSH_DISCONNECT_BY_APPLICATION (SSH2)
        ByApplication = 11,
        /// SSH_DISCONNECT_TOO_MANY_CONNECTIONS (SSH2)
        TooManyConnections = 12,
        /// SSH_DISCONNECT_AUTH_CANCELLED_BY_USER (SSH2)
        AuthCancelledByUser = 13,
        /// SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE (SSH2)
        NoMoreAuthMethodsAvailable = 14,
        /// SSH_DISCONNECT_ILLEGAL_USER_NAME (SSH2)
        IllegalUserName = 15
    }

    ///
    ///
    ///
    /// <exclude/>
    public enum MACAlgorithm {
        HMACSHA1
    }

    ///
    /// <ja>鍵交換アルゴリズム</ja>
    /// <en>key exchange algorighm</en>
    ///
    /// <exclude/>
    public enum KexAlgorithm {
        /// diffie-hellman-group1-sha1 described in RFC4253
        [AlgorithmSpec(AlgorithmName = "diffie-hellman-group1-sha1", DefaultPriority = 1)]
        DH_G1_SHA1,
        /// diffie-hellman-group14-sha1 described in RFC4253
        [AlgorithmSpec(AlgorithmName = "diffie-hellman-group14-sha1", DefaultPriority = 2)]
        DH_G14_SHA1,
        /// diffie-hellman-group14-sha256 described in draft-ietf-curdle-ssh-kex-sha2
        [AlgorithmSpec(AlgorithmName = "diffie-hellman-group14-sha256", DefaultPriority = 3)]
        DH_G14_SHA256,
        /// diffie-hellman-group16-sha512 described in draft-ietf-curdle-ssh-kex-sha2
        [AlgorithmSpec(AlgorithmName = "diffie-hellman-group16-sha512", DefaultPriority = 5)]
        DH_G16_SHA512,
        /// diffie-hellman-group18-sha512 described in draft-ietf-curdle-ssh-kex-sha2
        [AlgorithmSpec(AlgorithmName = "diffie-hellman-group18-sha512", DefaultPriority = 4)]
        DH_G18_SHA512,
        /// ecdh-sha2-nistp256 described in RFC5656
        [AlgorithmSpec(AlgorithmName = "ecdh-sha2-nistp256", DefaultPriority = 8)]
        ECDH_SHA2_NISTP256,
        /// ecdh-sha2-nistp384 described in RFC5656
        [AlgorithmSpec(AlgorithmName = "ecdh-sha2-nistp384", DefaultPriority = 7)]
        ECDH_SHA2_NISTP384,
        /// ecdh-sha2-nistp521 described in RFC5656
        [AlgorithmSpec(AlgorithmName = "ecdh-sha2-nistp521", DefaultPriority = 6)]
        ECDH_SHA2_NISTP521,
    }

    ///
    /// Extension methods for <see cref="KexAlgorithm"/>.
    ///
    public static class KexAlgorithmMixin {

        public static string GetAlgorithmName(this KexAlgorithm value) {
            return AlgorithmSpecUtil<KexAlgorithm>.GetAlgorithmName(value);
        }

        public static int GetDefaultPriority(this KexAlgorithm value) {
            return AlgorithmSpecUtil<KexAlgorithm>.GetDefaultPriority(value);
        }

        public static bool IsECDH(this KexAlgorithm value) {
            string algorithmName = GetAlgorithmName(value);
            if (algorithmName != null && algorithmName.StartsWith("ecdh-")) {
                return true;
            }
            return false;
        }
    }

}

namespace Granados.Util {

    using System;
    using System.Reflection;
    using System.Text;
    using System.Threading;

    internal static class SSHUtil {

        ///
        /// Get version string of the Granados.
        ///
        /// <param name="p">SSH protocol type</param>
        /// <returns>a version string</returns>
        public static string ClientVersionString(SSHProtocol p) {
            Assembly assy = Assembly.GetAssembly(typeof(SSHUtil));
            Version ver = assy.GetName().Version;
            string s = String.Format("{0}-{1}.{2}",
                            (p == SSHProtocol.SSH1) ? "SSH-1.5-Granados" : "SSH-2.0-Granados",
                            ver.Major, ver.Minor);
            return s;
        }

        ///
        /// Read Int32 value in network byte order.
        ///
        /// <param name="data">source byte array</param>
        /// <param name="offset">index to start reading</param>
        /// <returns>Int32 value</returns>
        public static int ReadInt32(byte[] data, int offset) {
            return (int)ReadUInt32(data, offset);
        }

        ///
        /// Read UInt32 value in network byte order.
        ///
        /// <param name="data">source byte array</param>
        /// <param name="offset">index to start reading</param>
        /// <returns>UInt32 value</returns>
        public static uint ReadUInt32(byte[] data, int offset) {
            uint ret = 0;
            ret |= data[offset];
            ret <<= 8;
            ret |= data[offset + 1];
            ret <<= 8;
            ret |= data[offset + 2];
            ret <<= 8;
            ret |= data[offset + 3];
            return ret;
        }

        ///
        /// Write Int32 value in network byte order.
        ///
        /// <param name="dst">byte array to be written</param>
        /// <param name="pos">index to start writing</param>
        /// <param name="data">Int32 value</param>
        public static void WriteIntToByteArray(byte[] dst, int pos, int data) {
            WriteUIntToByteArray(dst, pos, (uint)data);
        }

        ///
        /// Write UInt32 value in network byte order.
        ///
        /// <param name="dst">byte array to be written</param>
        /// <param name="pos">index to start writing</param>
        /// <param name="data">UInt32 value</param>
        public static void WriteUIntToByteArray(byte[] dst, int pos, uint data) {
            dst[pos] = (byte)(data >> 24);
            dst[pos + 1] = (byte)(data >> 16);
            dst[pos + 2] = (byte)(data >> 8);
            dst[pos + 3] = (byte)(data);
        }

        ///
        /// Check if a string array contains a particular string.
        ///
        /// <param name="s">a string array</param>
        /// <param name="v">a string</param>
        /// <returns>true if <paramref name="s"/> contains <paramref name="v"/>.</returns>
        public static bool ContainsString(string[] s, string v) {
            foreach (string x in s) {
                if (x == v) {
                    return true;
                }
            }
            return false;
        }

        ///
        /// Check if the contents of two byte arrays are identical.
        ///
        /// <param name="d1">a byte array</param>
        /// <param name="d2">a byte array</param>
        /// <returns>true if the contents of two byte arrays are identical.</returns>
        public static bool ByteArrayEqual(byte[] d1, byte[] d2) {
            if (d1.Length != d2.Length) {
                return false;
            }
            return ByteArrayEqual(d1, 0, d2, 0, d1.Length);
        }

        ///
        /// Check if the partial contents of two byte arrays are identical.
        ///
        /// <param name="d1">a byte array</param>
        /// <param name="o1">index of <paramref name="d1"/> to start comparison</param>
        /// <param name="d2">a byte array</param>
        /// <param name="o2">index of <paramref name="d2"/> to start comparison</param>
        /// <param name="len">number of bytes to compare</param>
        /// <returns>true if the partial contents of two byte arrays are identical.</returns>
        public static bool ByteArrayEqual(byte[] d1, int o1, byte[] d2, int o2, int len) {
            for (int i = 0; i < len; ++i) {
                if (d1[o1++] != d2[o2++]) {
                    return false;
                }
            }
            return true;
        }
    }

    ///
    ///
    ///
    /// <exclude/>
    public class Strings {
        private static StringResources _strings;
        public static string GetString(string id) {
            if (_strings == null)
                Reload();
            return _strings.GetString(id);
        }

        //load resource corresponding to current culture
        public static void Reload() {
            _strings = new StringResources("Granados.strings", typeof(Strings).Assembly);
        }
    }

    internal class DebugUtil {
        public static string DumpByteArray(byte[] data) {
            return DumpByteArray(data, 0, data.Length);
        }
        public static string DumpByteArray(byte[] data, int offset, int length) {
            StringBuilder bld = new StringBuilder();
            for (int i = 0; i < length; i++) {
                bld.Append(data[offset + i].ToString("X2"));
                if ((i % 4) == 3)
                    bld.Append(' ');
            }
            return bld.ToString();
        }

        public static string CurrentThread() {
            Thread t = Thread.CurrentThread;
            return t.GetHashCode().ToString();
        }
    }

    ///
    /// Utility class for pass an object to the single recipient.
    ///
    /// <typeparam name="T">type of the object</typeparam>
    internal class AtomicBox<T> {
        private readonly object _syncSet = new object();
        private readonly object _syncGet = new object();
        private readonly object _syncObject = new object();
        private volatile bool _hasObject;
        private T _object;

        ///
        /// Constructor
        ///
        public AtomicBox() {
            _hasObject = false;
            _object = default(T);
        }

        ///
        /// Clear the state of this box.
        ///
        public void Clear() {
            lock (_syncObject) {
                _object = default(T);
                _hasObject = false;
                Monitor.PulseAll(_syncObject);
            }
        }

        ///
        /// <para>Sets an object in the box.</para>
        /// <para>If another object exists in the box, the thread will be blocked until the object has been received by the recipient thread.</para>
        ///
        /// <param name="obj">an object to set</param>
        /// <param name="msecTimeout">timeout in milliseconds</param>
        /// <returns>true if an object has been set into the box.</returns>
        public bool TrySet(T obj, int msecTimeout) {
            lock (_syncSet) {
                lock (_syncObject) {
                    while (_hasObject) {
                        bool signaled = Monitor.Wait(_syncObject, msecTimeout);
                        if (_hasObject && !signaled) {
                            return false;
                        }
                    }
                    _object = obj;
                    _hasObject = true;
                    Monitor.PulseAll(_syncObject);
                    return true;
                }
            }
        }

        ///
        /// <para>Gets an object from the box.</para>
        /// <para>If no object exists in the box, the thread will be blocked until the object has been set by the sender thread.</para>
        ///
        /// <param name="obj">an object if succeeded</param>
        /// <param name="msecTimeout">timeout in milliseconds</param>
        /// <returns>true if an object has been obtained.</returns>
        public bool TryGet(ref T obj, int msecTimeout) {
            lock (_syncGet) {
                lock (_syncObject) {
                    while (!_hasObject) {
                        bool signaled = Monitor.Wait(_syncObject, msecTimeout);
                        if (!_hasObject && !signaled) {
                            return false;
                        }
                    }
                    obj = _object;
                    _object = default(T);
                    _hasObject = false;
                    Monitor.PulseAll(_syncObject);
                    return true;
                }
            }
        }
    }

    ///
    /// An internal class to pass the protocol events to <see cref="ISSHProtocolEventLogger"/>.
    ///
    internal class SSHProtocolEventManager {

        private readonly ISSHProtocolEventLogger _coreHandler;

        ///
        /// Constructor
        ///
        /// <param name="coreHandler">listener object or null</param>
        public SSHProtocolEventManager(ISSHProtocolEventLogger coreHandler) {
            _coreHandler = coreHandler;
        }

        ///
        /// Notifies OnSend event.
        ///
        /// <typeparam name="MessageTypeEnum">SSH message type enum</typeparam>
        /// <param name="messageType">message type</param>
        /// <param name="format">format string for the "details" text</param>
        /// <param name="args">format arguments for the "details" text</param>
        public void NotifySend<MessageTypeEnum>(MessageTypeEnum messageType, string format, params object[] args) {
            if (_coreHandler == null) {
                return;
            }

            try {
                string details = (args.Length == 0) ? format : String.Format(format, args);
                _coreHandler.OnSend(messageType.ToString(), details);
            }
            catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e.Message);
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
            }
        }

        ///
        /// Notifies OnReceived event.
        ///
        /// <typeparam name="MessageTypeEnum">SSH message type enum</typeparam>
        /// <param name="messageType">message type</param>
        /// <param name="format">format string for the "details" text</param>
        /// <param name="args">format arguments for the "details" text</param>
        public void NotifyReceive<MessageTypeEnum>(MessageTypeEnum messageType, string format, params object[] args) {
            if (_coreHandler == null) {
                return;
            }

            try {
                string details = (args.Length == 0) ? format : String.Format(format, args);
                _coreHandler.OnReceived(messageType.ToString(), details);
            }
            catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e.Message);
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
            }
        }

        ///
        /// Notifies OnTrace event.
        ///
        /// <param name="format">format string for the "details" text</param>
        /// <param name="args">format arguments for the "details" text</param>
        public void Trace(string format, params object[] args) {
            if (_coreHandler == null) {
                return;
            }

            try {
                string details = (args.Length == 0) ? format : String.Format(format, args);
                _coreHandler.OnTrace(details);
            }
            catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e.Message);
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
            }
        }
    }

}


text:
import {
  PIPELINE__CHECKED_IF_ON_PIPELINE,
  PIPELINE__GET_ITEM,
} from '../../../client/actions'

export default (state = {}, { type, result }) => {
  switch (type) {
    case PIPELINE__CHECKED_IF_ON_PIPELINE:
      return {
        ...state,
        pipelineStatus: result,
      }
    case PIPELINE__GET_ITEM:
      return {
        ...state,
        currentPipelineItem: result,
      }
    default:
      return state
  }
}


text:
/**
 * Заголовок для всей книги.
 *
 * @author dew1983@mail.ru <Suvorov Andrey M.>
 */

Ext.define(
    'FBEditor.view.window.hotkeys.slot.titlebody.Titlebody',
    {
        extend: 'FBEditor.view.window.hotkeys.slot.AbstractSlot',

        id: 'window-hotkeys-slot-titlebody',
        xtype: 'window-hotkeys-slot-titlebody',

        titleText: 'Заголовок для всей книги'
    }
);


text:
require 'sprockets/asset_attributes'

Sprockets::AssetAttributes.class_eval do
  IMPLICIT_WRAP_EXTENSION = '.WRAP_IN:'

  def self.wrap_for_format(path, format_extension)
    Pathname.new(path.to_s + IMPLICIT_WRAP_EXTENSION + format_extension)
  end

  def implicitly_wrapped?
    extensions[-2] == IMPLICIT_WRAP_EXTENSION
  end

  def implicit_extensions
    implicitly_wrapped? ? extensions[-2..-1] : []
  end

  def implicit_format_extension
    extensions.last
  end

  def real_logical_path
    return logical_path unless implicitly_wrapped?
    logical_path[0...-implicit_extensions.map(&:size).reduce(:+)]
  end

  def real_pathname
    return pathname unless implicitly_wrapped?
    Pathname.new(pathname.to_s[0...-implicit_extensions.map(&:size).reduce(:+)])
  end
end


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

   describe( "A Logger ", function() {
      var lastLogMessage = null;
      var logConsumer = function consume( message ) { lastLogMessage = message; };
      Log.to( logConsumer );
      //console.log( Log );

      it( "has log level INFO as default.", function() {
         expect( Log.level() ).toEqual( 'INFO' );
      });

      it( "logs Hello.", function() {
         Log.level( 'DEVELOP' );
         Log.develop( 'Hello' );
         expect( lastLogMessage ).toMatch( 'Hello' );
      });

       it( "does not log debug messages if run on level INFO.", function() {
           Log.level( 'INFO' );
           Log.debug( 'not logged' );
           expect( lastLogMessage ).not.toMatch( 'not logged' );
       });

       it( "does log error messages if run on level INFO.", function() {
           Log.level( 'INFO' );
           Log.error( 'logged' );
           expect( lastLogMessage ).toMatch( 'logged' );
       });

       it( "can be set to log level WARN.", function() {
           Log.level( 'WARN' );
           expect( Log.level() ).toEqual( 'WARN' );
       });

       it( "can be called to log something to console.", function() {
           Log.level( 'INFO' );
           Log.to( console.log.bind( console ) );
           Log.info( 'Hello' );
           // back to internal consumer
           expect( function () { Log.to( logConsumer ); } ).not.toThrow( 'TypeError: Illegal invocation' );
       });

       it( "can handle more than one argument.", function() {
           Log.level( 'INFO' );
           Log.info( 'Hello', 'You', 123 );
           expect( lastLogMessage ).toMatch( 'Hello You 123' );
       });

   });

} ) ( Log );


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cmpe451</groupId>
    <artifactId>api</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.0.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <properties>
        <start-class>api.Application</start-class>
        <java.version>1.7</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

</project>


text:
/*
Posizione degli assi su rviz:
# Red - x-axis (Roll About)
# Green - y-axis (Pitch About)
# Blue - z-axis (Yaw About)
Il sistema di riferimento è destrorso e il fixed frame di riferimento è depth_optical_frame (x a destra, y in basso, z in avanti)
*/

#include <ros/ros.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/Point.h>

/**** COSTANTI ****/

// Distance limits
#define OBSTACLE_DETECTION  1.0
#define GO_BACK_LIMIT       0.6

// Rover dimensions
#define LEFT_WIDTH -0.25
#define RIGHT_WIDTH 0.25

/******************/

typedef pcl::PointCloud<pcl::PointXYZ> PointCloud;

//Publisher per la pointcloud limitata
//ros::Publisher points_pub_;

//Publisher per il punto a minima distanza
ros::Publisher min_point_pub_;

void callback(const PointCloud::ConstPtr& msg)
{
  PointCloud tmp_cloud;		// Porzione di Pointcloud presa in considerazione dall'algoritmo
  geometry_msgs::Point min_point;

  // Inizializzazione del vettore a valori oltre il range di operativita' dell'algoritmo
  min_point.x = OBSTACLE_DETECTION + 0.1;
  min_point.y = OBSTACLE_DETECTION + 0.1;
  min_point.z = OBSTACLE_DETECTION + 0.1;

  BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points)  //it works like a loop which assignes the values 1 by 1 to a variable from an array
  {

    if( !pcl_isfinite( pt.x ) || !pcl_isfinite( pt.y ) || !pcl_isfinite( pt.z ) )  // this is done so that the nan values from the pointcloud are not processed
      continue;

    // Vengono considerati solo i punti nel range di OBSTACLE_DETECTION e sopra all'orizzonte della camera
    if (pt.z <= OBSTACLE_DETECTION && pt.y < 0 && pt.x >= LEFT_WIDTH && pt.x <= RIGHT_WIDTH) {

      tmp_cloud.push_back(pt);    //Salvataggio del punto nella porzione di pointcloud

      if (pt.z < min_point.z)
      {
        min_point.x=pt.x;
	      min_point.y=pt.y;
	      min_point.z=pt.z;
      }
    }
  }//foreach

  min_point_pub_.publish(min_point);

 /* if (tmp_cloud.size() > 0) {
    sensor_msgs::PointCloud2 pc2;
    pcl::toROSMsg(tmp_cloud, pc2);
    pc2.header.frame_id = "camera_depth_optical_frame";   //ATTENZIONE: il fixed frame non viene preso dalla pointcloud di input!
    points_pub_.publish(pc2);
  }*/

}//callback()

int main(int argc, char** argv)
{
  ros::init(argc, argv, "sub_pcl");
  ros::NodeHandle nh,nh1;

  ros::Subscriber sub = nh.subscribe<PointCloud>("voxel_grid/output", 1, callback);	//subsciber alla pointcloud della camera
 // points_pub_ = nh1.advertise<sensor_msgs::PointCloud2>("limited_pointcloud", 1);
  min_point_pub_ = nh1.advertise<geometry_msgs::Point>("min_distance_point", 10);

  ros::Rate loop_rate(2);	// 2 Hz

  while (ros::ok()) {
    ros::spinOnce();
    loop_rate.sleep();
  }
}//main()


text:
export type TPoint = {x: number, y: number}

export type TAbsoluteCommand =
    | { c: 'M', x: number, y: number }
    | { c: 'Z'}
    | { c: 'L', x: number, y: number}
    | { c: 'C', x1: number, y1: number, x2: number, y2: number, x: number, y: number}
    | { c: 'S', x2: number, y2: number, x: number, y: number}
    | { c: 'Q', x1: number, y1: number, x: number, y: number}
    | { c: 'T', x: number, y: number}
    | { c: 'A', rx: number, ry: number, xAxisRotation: number, largeArcFlag: number, sweepFlag: number, x: number, y: number}

export type TRelativeCommand =
    | { c: 'm', dx: number, dy: number}
    | { c: 'z'}
    | { c: 'l', dx: number, dy: number}
    | { c: 'H', x: number}
    | { c: 'V', y: number}
    | { c: 'h', dx: number}
    | { c: 'v', dy: number}
    | { c: 'c', dx1: number, dy1: number, dx2: number, dy2: number, dx: number, dy: number}
    | { c: 's', dx2: number, dy2: number, dx: number, dy: number}
    | { c: 'q', dx1: number, dy1: number, dx: number, dy: number}
    | { c: 't', dx: number, dy: number}
    | { c: 'a', rx: number, ry: number, xAxisRotation: number, largeArcFlag: number, sweepFlag: number, dx: number, dy: number}

export type TCommand = TAbsoluteCommand | TRelativeCommand

export type TAbsoluteData = $ReadOnlyArray<TAbsoluteCommand>
export type TRelativeData = $ReadOnlyArray<TRelativeCommand>
export type TData = $ReadOnlyArray<TCommand>

export type TSubPath = TAbsoluteData


text:
export * from './layer-selector.component';
export * from './trip-planner.component';
export * from './trip-planner.module';
export * from './trip-planner.service';


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="HandheldFriendly" content="True">
	<meta name="MobileOptimized" content="320">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<link rel="stylesheet" type="text/css" href="../dist/css/main/main.css">
	<title>Static Page Example</title>

This is a page example

    Go back to index.


text:
package org.tigris.subversion.javahl;

public class ChangePath implements java.io.Serializable, Comparable
{
    // Update the serialVersionUID when there is a incompatible change
    // made to this class.  See any of the following, depending upon
    // the Java release.
    // http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/version.doc7.html
    // http://java.sun.com/j2se/1.4/pdf/serial-spec.pdf
    // http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/version.html#6678
    // http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678
    private static final long serialVersionUID = 2L;

    /**
     * Constructor to be called from the native code
     * @param path              path of the commit item
     * @param copySrcRevision   copy source revision (if any)
     * @param copySrcPath       copy source path (if any)
     * @param action            action performed
     * @param nodeKind          the kind of the changed path
     */
    ChangePath(String path, long copySrcRevision, String copySrcPath,
               char action, int nodeKind)
    {
        this.path = path;
        this.copySrcRevision = copySrcRevision;
        this.copySrcPath = copySrcPath;
        this.action = action;
        this.nodeKind = nodeKind;
    }

    /**
     * A backward-compat constructor.
     */
    public ChangePath(org.apache.subversion.javahl.types.ChangePath aChangePath)
    {
        this(aChangePath.getPath(), aChangePath.getCopySrcRevision(),
             aChangePath.getCopySrcPath(),
              ((aChangePath.getAction() == org.apache.subversion.javahl.types.ChangePath.Action.add) ? 'A' :
              ((aChangePath.getAction() == org.apache.subversion.javahl.types.ChangePath.Action.delete) ? 'D' :
              ((aChangePath.getAction() == org.apache.subversion.javahl.types.ChangePath.Action.replace) ? 'R' :
              ((aChangePath.getAction() == org.apache.subversion.javahl.types.ChangePath.Action.modify) ? 'M' :
                ' ')))),
             NodeKind.fromApache(aChangePath.getNodeKind()));
    }

    public int compareTo(Object other)
    {
        return path.compareTo(((ChangePath)other).path);
    }

    /** Path of committed item */
    private String path;

    /** Source revision of copy (if any). */
    private long copySrcRevision;

    /** Source path of copy (if any). */
    private String copySrcPath;

    /** 'A'dd, 'D'elete, 'R'eplace, 'M'odify */
    private char action;

    /** The kind of the changed path. */
    private int nodeKind;

    /**
     * Retrieve the path to the committed item
     * @return  the path to the committed item
     */
    public String getPath()
    {
        return path;
    }

    /**
     * Retrieve the copy source revision (if any)
     * @return  the copy source revision (if any)
     */
    public long getCopySrcRevision()
    {
        return copySrcRevision;
    }

    /**
     * Retrieve the copy source path (if any)
     * @return  the copy source path (if any)
     */
    public String getCopySrcPath()
    {
        return copySrcPath;
    }

    /**
     * Retrieve action performed
     * @return  action performed
     */
    public char getAction()
    {
        return action;
    }

    /**
     * Retrieve the node kind
     * @return  the node kind
     */
    public int getNodeKind()
    {
        return nodeKind;
    }
}


text:
#ifndef __MFIB_API_H__
#define __MFIB_API_H__

#include <vnet/mfib/mfib_types.h>
#include <vnet/ip/ip.api_types.h>

/**
 * Forward declare the API type, no need to include the generated api headers
 */
struct _vl_api_mfib_path;

/**
 * Encode and decode functions from the API types to internal types
 */
extern void mfib_api_path_encode(const fib_route_path_t *in,
                                 vl_api_mfib_path_t *out);
extern int mfib_api_path_decode(vl_api_mfib_path_t *in,
                                fib_route_path_t *out);

extern mfib_entry_flags_t mfib_api_path_entry_flags_decode (vl_api_mfib_entry_flags_t in);

extern int mfib_api_table_id_decode(fib_protocol_t fproto,
                                    u32 table_id,
                                    u32 *fib_index);

#endif /* __MFIB_API_H__ */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Jard. Bot. Nat. Belg. 47(1-2): 85 (1977)

#### Original name
Leucocoprinus violaceus Heinem.

### Remarks
null


text:
package org.ejml.ops;

import org.ejml.UtilEjml;
import org.ejml.data.DenseMatrix64F;
import org.junit.Test;

import java.util.Random;

import static org.ejml.UtilEjml.parseMatrix;
import static org.junit.Assert.*;

/**
 * @author Peter Abeles
 */
public class TestMatrixFeatures {

    Random rand = new Random(0xff24);

    @Test
    public void hasUncountable() {
        DenseMatrix64F a = new DenseMatrix64F(4,4);

        // check a negative case first
        assertFalse(MatrixFeatures.hasUncountable(a));

        // check two positve cases with different types of uncountables
        a.set(2,2,Double.NaN);
        assertTrue(MatrixFeatures.hasUncountable(a));

        a.set(2,2,Double.POSITIVE_INFINITY);
        assertTrue(MatrixFeatures.hasUncountable(a));
    }

    @Test
    public void isVector() {
        DenseMatrix64F a = new DenseMatrix64F(4,4);

        assertFalse(MatrixFeatures.isVector(a));

        a.reshape(3,1, false);
        assertTrue(MatrixFeatures.isVector(a));

        a.reshape(1,3, false);
        assertTrue(MatrixFeatures.isVector(a));
    }

    /**
     * Check some trial cases.
     */
    @Test
    public void isPositiveDefinite() {
        DenseMatrix64F a = UtilEjml.parseMatrix("2 0 0 2",2);
        DenseMatrix64F b = UtilEjml.parseMatrix("0 1 1 0",2);
        DenseMatrix64F c = UtilEjml.parseMatrix("0 0 0 0",2);

        assertTrue(MatrixFeatures.isPositiveDefinite(a));
        assertFalse(MatrixFeatures.isPositiveDefinite(b));
        assertFalse(MatrixFeatures.isPositiveDefinite(c));

        // make sure the input isn't modified
        assertEquals(2,a.get(0,0),1e-8);
        assertEquals(2,a.get(1,1),1e-8);
    }

    @Test
    public void isPositiveSemidefinite() {
        DenseMatrix64F a = UtilEjml.parseMatrix("2 0 0 2",2);
        DenseMatrix64F b = UtilEjml.parseMatrix("0 1 1 0",2);
        DenseMatrix64F c = UtilEjml.parseMatrix("0 0 0 0",2);

        assertTrue(MatrixFeatures.isPositiveSemidefinite(a));
        assertFalse(MatrixFeatures.isPositiveSemidefinite(b));
        assertTrue(MatrixFeatures.isPositiveSemidefinite(c));

        // make sure the input isn't modified
        assertEquals(2,a.get(0,0),1e-8);
        assertEquals(2,a.get(1,1),1e-8);
    }

    @Test
    public void isSquare() {
        DenseMatrix64F a = new DenseMatrix64F(5,4);

        assertFalse(MatrixFeatures.isSquare(a));

        a.reshape(4,4, false);
        assertTrue(MatrixFeatures.isSquare(a));
    }

    @Test
    public void isDiagonalPositive() {
        DenseMatrix64F m = CommonOps.identity(3);
        assertTrue(MatrixFeatures.isDiagonalPositive(m));

        m.set(1,1,-1);
        assertFalse(MatrixFeatures.isDiagonalPositive(m));

        m.set(1,1,Double.NaN);
        assertFalse(MatrixFeatures.isDiagonalPositive(m));
    }

    @Test
    public void isSymmetric() {
        DenseMatrix64F m = CommonOps.identity(3);
        m.set(1,2,5);m.set(2,1,5);
        assertTrue(MatrixFeatures.isSymmetric(m));

        m.set(1,2,50);
        assertTrue(!MatrixFeatures.isSymmetric(m));

        m.set(1,2,Double.NaN);
        assertTrue(!MatrixFeatures.isSymmetric(m));
    }

    @Test
    public void isSkewSymmetric() {
        DenseMatrix64F m = CommonOps.identity(3);
        m.set(1,2,5);m.set(2,1,-5);
        assertTrue(MatrixFeatures.isSkewSymmetric(m,1e-8));

        m.set(1,2,-5);
        assertTrue(!MatrixFeatures.isSkewSymmetric(m,1e-8));

        m.set(1,2,Double.NaN);
        assertTrue(!MatrixFeatures.isSkewSymmetric(m,1e-8));
    }

    @Test
    public void isEquals() {
        String a = "-0.779094   1.682750   0.039239\n" +
                 "   1.304014  -1.880739   1.438741\n" +
                 "  -0.746918   1.382356  -0.520416";

        DenseMatrix64F m = parseMatrix(a,3);
        DenseMatrix64F n = parseMatrix(a,3);

        assertTrue(MatrixFeatures.isEquals(m,n));

        n.set(2,1,-0.5);
        assertFalse(MatrixFeatures.isEquals(m,n));

        m.set(2,1,Double.NaN);
        n.set(2,1,Double.NaN);
        assertFalse(MatrixFeatures.isEquals(m,n));
        m.set(2,1,Double.POSITIVE_INFINITY);
        n.set(2,1,Double.POSITIVE_INFINITY);
        assertTrue(MatrixFeatures.isEquals(m,n));
    }

    @Test
    public void isEquals_tol() {
        String a = "-0.779094   1.682750   0.039239\n" +
                 "   1.304014  -1.880739   1.438741\n" +
                 "  -0.746918   1.382356  -0.520416";

        DenseMatrix64F m = parseMatrix(a,3);
        DenseMatrix64F n = parseMatrix(a,3);

        assertTrue(MatrixFeatures.isEquals(m,n,1e-6));

        n.set(2,1,n.get(2,1)+1e-25);
        assertTrue(MatrixFeatures.isEquals(m,n,1e-6));

        n.set(2,1,n.get(2,1)+1e-2);
        assertFalse(MatrixFeatures.isEquals(m,n,1e-6));

        m.set(2,1,Double.NaN);
        n.set(2,1,Double.NaN);
        assertFalse(MatrixFeatures.isEquals(m,n,1e-6));
        m.set(2,1,Double.POSITIVE_INFINITY);
        n.set(2,1,Double.POSITIVE_INFINITY);
        assertFalse(MatrixFeatures.isEquals(m,n,1e-6));
    }

    @Test
    public void isEqualsTriangle() {

        // see if it works with different sized matrices
        for( int m = 2; m < 10; m+=3) {
            for( int n = 2; n < 10; n += 3 ) {
                DenseMatrix64F a = RandomMatrices.createRandom(m,n,rand);
                DenseMatrix64F b = a.copy();

                // make the bottom triangle not the same
                b.set(m-1,0,0);

                assertTrue("m = "+m+" n = "+n,MatrixFeatures.isEqualsTriangle(a,b, true, 1e-8));
                assertFalse(MatrixFeatures.isEqualsTriangle(a,b, false, 1e-8));

                // make the upper triangle not the same
                b = a.copy();
                b.set(0,n-1,0);

                assertFalse(MatrixFeatures.isEqualsTriangle(a,b, true, 1e-8));
                assertTrue(MatrixFeatures.isEqualsTriangle(a,b, false, 1e-8));
            }
        }
    }

    @Test
    public void isIdentical() {

        double values[] = new double[]{1.0,Double.NaN,Double.POSITIVE_INFINITY,Double.NEGATIVE_INFINITY};

        for( int i = 0; i < values.length; i++ ) {
            for( int j = 0; j < values.length; j++ ) {
                checkIdentical(values[i],values[j],1e-8,i==j);
            }
        }

        checkIdentical(1.0,1.5,1e-8,false);
        checkIdentical(1.5,1.0,1e-8,false);
        checkIdentical(1.0,1.0000000001,1e-8,true);
        checkIdentical(1.0,Double.NaN,1e-8,false);
        checkIdentical(Double.NaN,1.0,1e-8,false);
    }

    private void checkIdentical( double valA , double valB , double tol , boolean expected ) {
        DenseMatrix64F A = new DenseMatrix64F(2,2);
        CommonOps.fill(A, valA);
        DenseMatrix64F B = new DenseMatrix64F(2,2);
        CommonOps.fill(B, valB);

        assertEquals(expected,MatrixFeatures.isIdentical(A,B,tol));
    }

    @Test
    public void isInverse() {
        DenseMatrix64F A = RandomMatrices.createRandom(3,3,-1,1,rand);
        DenseMatrix64F A_inv = A.copy();

        CommonOps.invert(A_inv);

        assertTrue(MatrixFeatures.isInverse(A,A_inv,1e-10));

        A_inv.set(1,2,3);
        assertFalse(MatrixFeatures.isInverse(A,A_inv,1e-10));

        A_inv.set(1,2,Double.NaN);
        assertFalse(MatrixFeatures.isInverse(A,A_inv,1e-10));
    }

    /**
     * Makes sure it isn't modifying the input
     */
    @Test
    public void isInverse_nomodify() {
        DenseMatrix64F A = RandomMatrices.createRandom(3,3,-1,1,rand);
        DenseMatrix64F B = RandomMatrices.createRandom(3,3,-1,1,rand);
        DenseMatrix64F A_copy = A.copy();
        DenseMatrix64F B_copy = B.copy();

        MatrixFeatures.isInverse(A,B,1e-10);

        assertTrue(MatrixFeatures.isIdentical(A,A_copy,1e-8));
        assertTrue(MatrixFeatures.isIdentical(B,B_copy,1e-8));
    }

    @Test
    public void hasNaN() {
        DenseMatrix64F m = new DenseMatrix64F(3,3);
        assertFalse(MatrixFeatures.hasNaN(m));

        m.set(1,2,-Double.NaN);
        assertTrue(MatrixFeatures.hasNaN(m));
    }

    @Test
    public void isOrthogonal() {
        // rotation matrices are orthogonal
        double c = Math.cos(0.1);
        double s = Math.sin(0.1);

        DenseMatrix64F A = new DenseMatrix64F(new double[][]{{c,s},{-s,c}});

        assertTrue(MatrixFeatures.isOrthogonal(A,1e-6f));

        // try a negative case now
        A.set(0,1,495);

        assertFalse(MatrixFeatures.isOrthogonal(A,1e-6f));

        A.set(0,1,Double.NaN);

        assertFalse(MatrixFeatures.isOrthogonal(A,1e-6f));
    }

    @Test
    public void isRowsLinearIndependent() {
        // test a positive case
        DenseMatrix64F A = new DenseMatrix64F(2,3, true, 1, 2, 3, 2, 3, 4);
        assertTrue(MatrixFeatures.isRowsLinearIndependent(A));

        // make sure the input wasn't modified
        DenseMatrix64F A_copy = new DenseMatrix64F(2,3, true, 1, 2, 3, 2, 3, 4);
        assertTrue(MatrixFeatures.isIdentical(A,A_copy,1e-8));

        // test negative case
        A = new DenseMatrix64F(2,3, true, 1, 2, 3, 1, 2, 3);
        assertFalse(MatrixFeatures.isRowsLinearIndependent(A));
    }

    @Test
    public void isConstantVal() {
        DenseMatrix64F a = new DenseMatrix64F(3,4);

        CommonOps.fill(a, 2.4);

        assertTrue(MatrixFeatures.isConstantVal(a,2.4,1e-8));
        assertFalse(MatrixFeatures.isConstantVal(a,6,1e-8));

        a.set(1,1,Double.NaN);
        assertFalse(MatrixFeatures.isConstantVal(a,2.4,1e-8));
    }

    @Test
    public void isIdentity() {
        DenseMatrix64F I = CommonOps.identity(4);

        assertTrue(MatrixFeatures.isIdentity(I,1e-8));

        I.set(3,2,0.1);
        assertFalse(MatrixFeatures.isIdentity(I,1e-8));

        I.set(3,2,Double.NaN);
        assertFalse(MatrixFeatures.isIdentity(I,1e-8));
    }

    @Test
    public void isNegative() {
        DenseMatrix64F a = RandomMatrices.createRandom(4,5,rand);
        DenseMatrix64F b = a.copy();
        CommonOps.scale(-1,b);

        // test the positive case first
        assertTrue(MatrixFeatures.isNegative(a,b,1e-8));

        // now the negative case
        b.set(2,2,10);
        assertFalse(MatrixFeatures.isNegative(a,b,1e-8));

        b.set(2,2,Double.NaN);
        assertFalse(MatrixFeatures.isNegative(a,b,1e-8));
    }

    @Test
    public void isUpperTriangle() {
        // test matrices that are upper triangular to various degree hessenberg
        for( int hessenberg = 0; hessenberg < 2; hessenberg++ ) {
            DenseMatrix64F A = new DenseMatrix64F(6,6);
            for( int i = 0; i < A.numRows; i++ ) {
                int s = i <= hessenberg ? 0 : i-hessenberg;

                for( int j = s; j < A.numCols; j++ ) {
                   A.set(i,j,2);
                }
            }

            // test positive
            for( int i = hessenberg; i < A.numRows; i++ ) {
                assertTrue(MatrixFeatures.isUpperTriangle(A,i,1e-8));
            }

            // test negative
            for( int i = 0; i < hessenberg; i++ ) {
                assertFalse(MatrixFeatures.isUpperTriangle(A,i,1e-8));
            }

            // see if it handles NaN well
            A.set(4,0,Double.NaN);
            assertFalse(MatrixFeatures.isUpperTriangle(A,0,1e-8));
        }
    }

    @Test
    public void rank() {
        DenseMatrix64F a = UtilEjml.parseMatrix("2 0 0 2",2);
        DenseMatrix64F a_copy = a.copy();

        assertEquals(2,MatrixFeatures.rank(a));
        // make sure the input wasn't modified
        assertTrue(MatrixFeatures.isIdentical(a,a_copy,1e-8));

        a = UtilEjml.parseMatrix("2 0 0 0",2);
        assertEquals(1,MatrixFeatures.rank(a));
    }

    @Test
    public void rank_threshold() {
        DenseMatrix64F a = UtilEjml.parseMatrix("2 0 0 2",2);
        DenseMatrix64F a_copy = a.copy();

        assertEquals(2,MatrixFeatures.rank(a,1e-14));
        // make sure the input wasn't modified
        assertTrue(MatrixFeatures.isIdentical(a,a_copy,1e-8));

        a = UtilEjml.parseMatrix("2 0 0 1e-20",2);
        assertEquals(1,MatrixFeatures.rank(a,1e-14));

        // make sure it's using the threshold parameter
        a = UtilEjml.parseMatrix("2 0 0 1e-20",2);
        assertEquals(2,MatrixFeatures.rank(a,1e-200));
    }

    @Test
    public void nullity() {
        DenseMatrix64F a = UtilEjml.parseMatrix("2 0 0 2",2);
        DenseMatrix64F a_copy = a.copy();

        assertEquals(0,MatrixFeatures.nullity(a));
        // make sure the input wasn't modified
        assertTrue(MatrixFeatures.isIdentical(a,a_copy,1e-8));

        a = UtilEjml.parseMatrix("2 0 0 0",2);
        assertEquals(1,MatrixFeatures.nullity(a));
    }

    @Test
    public void nullity_threshold() {
        DenseMatrix64F a = UtilEjml.parseMatrix("2 0 0 2",2);
        DenseMatrix64F a_copy = a.copy();

        assertEquals(0,MatrixFeatures.nullity(a, 1e-14));
        // make sure the input wasn't modified
        assertTrue(MatrixFeatures.isIdentical(a,a_copy,1e-8));

        a = UtilEjml.parseMatrix("2 0 0 1e-20",2);
        assertEquals(1,MatrixFeatures.nullity(a, 1e-14));

        // make sure it's using the threshold parameter
        a = UtilEjml.parseMatrix("2 0 0 1e-20",2);
        assertEquals(0,MatrixFeatures.nullity(a, 1e-200));
    }
}


text:
package com.koch.ambeth.cache.util;

import com.koch.ambeth.util.collections.ISet;

public class AppendableCachePath {
	public final int memberIndex;

	public final String memberName;

	public final Class<?> memberType;

	public ISet<AppendableCachePath> children;

	public AppendableCachePath(Class<?> memberType, int memberIndex, String memberName) {
		this.memberIndex = memberIndex;
		this.memberName = memberName;
		this.memberType = memberType;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		if (!(obj instanceof AppendableCachePath)) {
			return false;
		}
		return memberIndex == ((AppendableCachePath) obj).memberIndex;
	}

	@Override
	public int hashCode() {
		return getClass().hashCode() ^ memberIndex;
	}

	@Override
	public String toString() {
		return memberName;
	}
}


text:
package com.anji_ahni.nn.activationfunction;

/**
 * Logic AND activation function.
 *
 * @author Oliver Coleman
 */
public class LogicAndActivationFunction extends LogicActivationFunction {
	/**
	 * identifying string
	 */
	public final static String NAME = "and";

	/**
	 * @see Object#toString()
	 */
	public String toString() {
		return NAME;
	}

	/**
	 * This class should only be accessed via ActivationFunctionFactory.
	 */
	LogicAndActivationFunction() {
	}

	/**
	 * Returns the result of a logical AND over all inputs, where an input value greater than or equal to 0.5 is
	 * considered logical true, and less than 0.5 false.
	 *
	 * @return 1 or 0 depending on result of logic operation.
	 */
	public double apply(double[] input, double bias) {
		boolean result = false;
		for (int i = 0; i < input.length; i++)
			result &= input[i] >= 0.5;
		return result ? 1 : 0;
	}
}


text:
layout: default
title: Home
---

    {% for post in paginator.posts %}

        {% assign item = post %}
        {% include screenshot.html %}

{{ post.title }}

{{ post.date | date: "%B %-d, %Y" }}

    {% endfor %}

  {% include pagination.html %}