text:
BOOL_PARAM_FLAG(display, false, "Display image for inspection");

namespace tesseract {

const char kEngText[] = "the quick brown fox jumps over the lazy dog";
const char kHinText[] = "पिताने विवाह की | हो गई उद्विग्न वह सोचा";

const char kKorText[] = "이는 것으로 다시 넣을 1234 수는 있지만 선택의 의미는";
const char kArabicText[] =
    "والفكر والصراع ، بالتأمل والفهم والتحليل ، "
    "بالعلم والفن ، وأخيرا بالضحك أوبالبكاء ، ";
const char kMixedText[] = "والفكر 123 والصراع abc";

const char kEngNonLigatureText[] = "fidelity";
// Same as kEngNonLigatureText, but with "fi" replaced with its ligature.
const char kEngLigatureText[] = "fidelity";

static PangoFontMap *font_map;

class StringRendererTest : public ::testing::Test {
protected:
  void SetUp() override {
    if (!font_map) {
      font_map = pango_cairo_font_map_new_for_font_type(CAIRO_FONT_TYPE_FT);
    }
    pango_cairo_font_map_set_default(PANGO_CAIRO_FONT_MAP(font_map));
  }

  static void SetUpTestCase() {
    static std::locale system_locale("");
    std::locale::global(system_locale);

    l_chooseDisplayProg(L_DISPLAY_WITH_XZGV);
    FLAGS_fonts_dir = TESTING_DIR;
    FLAGS_fontconfig_tmpdir = FLAGS_test_tmpdir;
    file::MakeTmpdir();
    PangoFontInfo::SoftInitFontConfig(); // init early
  }

  void DisplayClusterBoxes(Image pix) {
    if (!FLAGS_display) {
      return;
    }
    const std::vector<BoxChar *> &boxchars = renderer_->GetBoxes();
    Boxa *boxes = boxaCreate(0);
    for (const auto &boxchar : boxchars) {
      if (boxchar->box()) {
        boxaAddBox(boxes, const_cast<Box *>(boxchar->box()), L_CLONE);
      }
    }
    Image box_pix = pixDrawBoxaRandom(pix, boxes, 1);
    boxaDestroy(&boxes);
    pixDisplay(box_pix, 0, 0);
    box_pix.destroy();
  }
  std::unique_ptr<StringRenderer> renderer_;
};

TEST_F(StringRendererTest, DoesRenderToImage) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  Image pix = nullptr;
  EXPECT_EQ(strlen(kEngText), renderer_->RenderToImage(kEngText, strlen(kEngText), &pix));
  EXPECT_TRUE(pix != nullptr);
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();

  renderer_ = std::make_unique<StringRenderer>("UnBatang 10", 600, 600);
  EXPECT_EQ(strlen(kKorText), renderer_->RenderToImage(kKorText, strlen(kKorText), &pix));
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();

  renderer_ = std::make_unique<StringRenderer>("Lohit Hindi 10", 600, 600);
  EXPECT_EQ(strlen(kHinText), renderer_->RenderToImage(kHinText, strlen(kHinText), &pix));
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();

  // RTL text
  renderer_ = std::make_unique<StringRenderer>("Arab 10", 600, 600);
  EXPECT_EQ(strlen(kArabicText), renderer_->RenderToImage(kArabicText, strlen(kArabicText), &pix));
  EXPECT_TRUE(pix != nullptr);
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();

  // Mixed direction Arabic + english text
  renderer_ = std::make_unique<StringRenderer>("Arab 10", 600, 600);
  EXPECT_EQ(strlen(kMixedText), renderer_->RenderToImage(kMixedText, strlen(kMixedText), &pix));
  EXPECT_TRUE(pix != nullptr);
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();
}

TEST_F(StringRendererTest, DoesRenderToImageWithUnderline) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  // Underline all words but NOT intervening spaces.
  renderer_->set_underline_start_prob(1.0);
  renderer_->set_underline_continuation_prob(0);
  Image pix = nullptr;
  EXPECT_EQ(strlen(kEngText), renderer_->RenderToImage(kEngText, strlen(kEngText), &pix));
  EXPECT_TRUE(pix != nullptr);
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();
  renderer_->ClearBoxes();

  // Underline all words AND intervening spaces.
  renderer_->set_underline_start_prob(1.0);
  renderer_->set_underline_continuation_prob(1.0);
  EXPECT_EQ(strlen(kEngText), renderer_->RenderToImage(kEngText, strlen(kEngText), &pix));
  EXPECT_TRUE(pix != nullptr);
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();
  renderer_->ClearBoxes();

  // Underline words and intervening spaces with 0.5 prob.
  renderer_->set_underline_start_prob(0.5);
  renderer_->set_underline_continuation_prob(0.5);
  EXPECT_EQ(strlen(kEngText), renderer_->RenderToImage(kEngText, strlen(kEngText), &pix));
  EXPECT_TRUE(pix != nullptr);
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();
}

TEST_F(StringRendererTest, DoesHandleNewlineCharacters) {
  const char kRawText[] = "\n\n\n A \nB \nC \n\n\n";
  const char kStrippedText[] = " A B C "; // text with newline chars removed
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  Image pix = nullptr;
  EXPECT_EQ(strlen(kRawText), renderer_->RenderToImage(kRawText, strlen(kRawText), &pix));
  EXPECT_TRUE(pix != nullptr);
  const std::vector<BoxChar *> &boxchars = renderer_->GetBoxes();
  // 3 characters + 4 spaces => 7 boxes
  EXPECT_EQ(7, boxchars.size());
  if (boxchars.size() == 7) {
    // Verify the text content of the boxchars
    for (size_t i = 0; i < boxchars.size(); ++i) {
      EXPECT_EQ(std::string(1, kStrippedText[i]), boxchars[i]->ch());
    }
  }
  DisplayClusterBoxes(pix);
  pix.destroy();
}

TEST_F(StringRendererTest, DoesRenderLigatures) {
  renderer_ = std::make_unique<StringRenderer>("Arab 12", 600, 250);
  const char kArabicLigature[] = "لا";

  Image pix = nullptr;
  EXPECT_EQ(strlen(kArabicLigature),
            renderer_->RenderToImage(kArabicLigature, strlen(kArabicLigature), &pix));
  EXPECT_TRUE(pix != nullptr);
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  const std::vector<BoxChar *> &boxes = renderer_->GetBoxes();
  EXPECT_EQ(1, boxes.size());
  EXPECT_TRUE(boxes[0]->box() != nullptr);
  EXPECT_STREQ(kArabicLigature, boxes[0]->ch().c_str());
  DisplayClusterBoxes(pix);
  pix.destroy();

  renderer_ = std::make_unique<StringRenderer>("Arab 12", 600, 250);
  const char kArabicMixedText[] = "والفكر والصراع 1234,\nوالفكر لا والصراع";
  renderer_->RenderToImage(kArabicMixedText, strlen(kArabicMixedText), &pix);
  DisplayClusterBoxes(pix);
  pix.destroy();
}

static int FindBoxCharXCoord(const std::vector<BoxChar *> &boxchars, const std::string &ch) {
  for (const auto &boxchar : boxchars) {
    if (boxchar->ch() == ch) {
      return boxchar->box()->x;
    }
  }
  return INT_MAX;
}

TEST_F(StringRendererTest, ArabicBoxcharsInLTROrder) {
  renderer_ = std::make_unique<StringRenderer>("Arab 10", 600, 600);
  Image pix = nullptr;
  // Arabic letters should be in decreasing x-coordinates
  const char kArabicWord[] = "\u0644\u0627\u0641\u0643\u0631";
  const std::string kRevWord = "\u0631\u0643\u0641\u0627\u0644";
  renderer_->RenderToImage(kArabicWord, strlen(kArabicWord), &pix);
  std::string boxes_str = renderer_->GetBoxesStr();
  // Decode to get the box text strings.
  EXPECT_FALSE(boxes_str.empty());
  std::vector<std::string> texts;
  EXPECT_TRUE(ReadMemBoxes(0, false, boxes_str.c_str(), false, nullptr, &texts, nullptr, nullptr));
  std::string ltr_str;
  for (auto &text : texts) {
    ltr_str += text.c_str();
  }
  // The string should come out perfectly reversed, despite there being a
  // ligature.
  EXPECT_EQ(ltr_str, kRevWord);
  // Just to prove there was a ligature, the number of texts is less than the
  // number of unicodes.
  EXPECT_LT(texts.size(), 5);
  pix.destroy();
}

TEST_F(StringRendererTest, DoesOutputBoxcharsInReadingOrder) {
  renderer_ = std::make_unique<StringRenderer>("Arab 10", 600, 600);
  Image pix = nullptr;
  // Arabic letters should be in decreasing x-coordinates
  const char kArabicWord[] = "والفكر";
  renderer_->RenderToImage(kArabicWord, strlen(kArabicWord), &pix);
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  const std::vector<BoxChar *> &boxchars = renderer_->GetBoxes();
  for (size_t i = 1; i < boxchars.size(); ++i) {
    EXPECT_GT(boxchars[i - 1]->box()->x, boxchars[i]->box()->x) << boxchars[i - 1]->ch();
  }
  pix.destroy();

  // English letters should be in increasing x-coordinates
  const char kEnglishWord[] = "Google";
  renderer_->ClearBoxes();
  renderer_->RenderToImage(kEnglishWord, strlen(kEnglishWord), &pix);
  EXPECT_EQ(boxchars.size(), strlen(kEnglishWord));
  for (size_t i = 1; i < boxchars.size(); ++i) {
    EXPECT_LT(boxchars[i - 1]->box()->x, boxchars[i]->box()->x) << boxchars[i - 1]->ch();
  }
  pix.destroy();

  // Mixed text should satisfy both.
  renderer_->ClearBoxes();
  renderer_->RenderToImage(kMixedText, strlen(kMixedText), &pix);
  EXPECT_LT(FindBoxCharXCoord(boxchars, "a"), FindBoxCharXCoord(boxchars, "b"));
  EXPECT_LT(FindBoxCharXCoord(boxchars, "1"), FindBoxCharXCoord(boxchars, "2"));
  EXPECT_GT(FindBoxCharXCoord(boxchars, "و"), FindBoxCharXCoord(boxchars, "ر"));
  pix.destroy();
}

TEST_F(StringRendererTest, DoesRenderVerticalText) {
  Image pix = nullptr;
  renderer_ = std::make_unique<StringRenderer>("UnBatang 10", 600, 600);
  renderer_->set_vertical_text(true);
  EXPECT_EQ(strlen(kKorText), renderer_->RenderToImage(kKorText, strlen(kKorText), &pix));
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  DisplayClusterBoxes(pix);
  pix.destroy();
}

// Checks that we preserve charboxes across RenderToImage calls, with
// appropriate page numbers.
TEST_F(StringRendererTest, DoesKeepAllImageBoxes) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  Image pix = nullptr;
  int num_boxes_per_page = 0;
  const int kNumTrials = 2;
  for (int i = 0; i < kNumTrials; ++i) {
    EXPECT_EQ(strlen(kEngText), renderer_->RenderToImage(kEngText, strlen(kEngText), &pix));
    EXPECT_TRUE(pix != nullptr);
    pix.destroy();
    EXPECT_GT(renderer_->GetBoxes().size(), 0);
    if (!num_boxes_per_page) {
      num_boxes_per_page = renderer_->GetBoxes().size();
    } else {
      EXPECT_EQ((i + 1) * num_boxes_per_page, renderer_->GetBoxes().size());
    }
    for (int j = i * num_boxes_per_page; j < (i + 1) * num_boxes_per_page; ++j) {
      EXPECT_EQ(i, renderer_->GetBoxes()[j]->page());
    }
  }
}

TEST_F(StringRendererTest, DoesClearBoxes) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  Image pix = nullptr;
  EXPECT_EQ(strlen(kEngText), renderer_->RenderToImage(kEngText, strlen(kEngText), &pix));
  pix.destroy();
  EXPECT_GT(renderer_->GetBoxes().size(), 0);
  const int num_boxes_per_page = renderer_->GetBoxes().size();

  renderer_->ClearBoxes();
  EXPECT_EQ(strlen(kEngText), renderer_->RenderToImage(kEngText, strlen(kEngText), &pix));
  pix.destroy();
  EXPECT_EQ(num_boxes_per_page, renderer_->GetBoxes().size());
}

TEST_F(StringRendererTest, DoesLigatureTextForRendering) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  renderer_->set_add_ligatures(true);
  Image pix = nullptr;
  EXPECT_EQ(strlen(kEngNonLigatureText),
            renderer_->RenderToImage(kEngNonLigatureText, strlen(kEngNonLigatureText), &pix));
  pix.destroy();
#if 0 // not with NFC normalization
  // There should be one less box than letters due to the 'fi' ligature.
  EXPECT_EQ(strlen(kEngNonLigatureText) - 1, renderer_->GetBoxes().size());
  // The output box text should be ligatured.
  EXPECT_STREQ("fi", renderer_->GetBoxes()[0]->ch().c_str());
#endif
}

TEST_F(StringRendererTest, DoesRetainInputLigatureForRendering) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  Image pix = nullptr;
  EXPECT_EQ(strlen(kEngLigatureText),
            renderer_->RenderToImage(kEngLigatureText, strlen(kEngLigatureText), &pix));
  pix.destroy();
  // There should be one less box than letters due to the 'fi' ligature.
  EXPECT_EQ(strlen(kEngNonLigatureText) - 1, renderer_->GetBoxes().size());
  // The output box text should be ligatured.
  EXPECT_STREQ("\uFB01", renderer_->GetBoxes()[0]->ch().c_str());
}

TEST_F(StringRendererTest, DoesStripUnrenderableWords) {
  // Verdana should only be able to render the english letters and numbers in
  // the mixed text.
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  std::string text(kMixedText);
  EXPECT_GT(renderer_->StripUnrenderableWords(&text), 0);
  EXPECT_EQ(" 123  abc", text);
}

TEST_F(StringRendererTest, DoesRenderWordBoxes) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  renderer_->set_output_word_boxes(true);
  Image pix = nullptr;
  EXPECT_EQ(strlen(kEngText), renderer_->RenderToImage(kEngText, strlen(kEngText), &pix));
  pix.destroy();
  // Verify #boxchars = #words + #spaces
  std::vector<std::string> words = split(kEngText, ' ');
  const int kNumSpaces = words.size() - 1;
  const int kExpectedNumBoxes = words.size() + kNumSpaces;
  const std::vector<BoxChar *> &boxchars = renderer_->GetBoxes();
  EXPECT_EQ(kExpectedNumBoxes, boxchars.size());
  // Verify content of words and spaces
  for (size_t i = 0; i < boxchars.size(); i += 2) {
    EXPECT_EQ(words[i / 2], boxchars[i]->ch());
    if (i < boxchars.size() - 1) {
      EXPECT_EQ(" ", boxchars[i + 1]->ch());
      EXPECT_TRUE(boxchars[i + 1]->box() == nullptr);
    }
  }
}

TEST_F(StringRendererTest, DoesRenderWordBoxesFromMultiLineText) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 600, 600);
  renderer_->set_output_word_boxes(true);
  Image pix = nullptr;
  const char kMultlineText[] = "the quick brown fox\njumps over the lazy dog";
  EXPECT_EQ(strlen(kMultlineText), renderer_->RenderToImage(kMultlineText, strlen(kEngText), &pix));
  pix.destroy();
  // Verify #boxchars = #words + #spaces + #newlines
  std::vector<std::string> words;
  for (auto &line : split(kMultlineText, '\n')) {
    for (auto &word : split(line, ' ')) {
      words.push_back(word);
    }
  }
  const int kNumSeparators = words.size() - 1;
  const int kExpectedNumBoxes = words.size() + kNumSeparators;
  const std::vector<BoxChar *> &boxchars = renderer_->GetBoxes();
  EXPECT_EQ(kExpectedNumBoxes, boxchars.size());
  // Verify content of words and spaces
  for (size_t i = 0; i < boxchars.size(); i += 2) {
    EXPECT_EQ(words[i / 2], boxchars[i]->ch());
    if (i + 1 < boxchars.size()) {
      EXPECT_EQ(" ", boxchars[i + 1]->ch());
      EXPECT_TRUE(boxchars[i + 1]->box() == nullptr);
    }
  }
}

TEST_F(StringRendererTest, DoesRenderAllFontsToImage) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 1200, 1200);
  size_t offset = 0;
  std::string font_used;
  do {
    Image pix = nullptr;
    font_used.clear();
    offset += renderer_->RenderAllFontsToImage(1.0, kEngText + offset, strlen(kEngText + offset),
                                               &font_used, &pix);
    if (offset < strlen(kEngText)) {
      EXPECT_TRUE(pix != nullptr);
      EXPECT_STRNE("", font_used.c_str());
    }
    if (FLAGS_display) {
      pixDisplay(pix, 0, 0);
    }
    pix.destroy();
  } while (offset < strlen(kEngText));
}

TEST_F(StringRendererTest, DoesNotRenderWordJoiner) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 500, 200);
  const std::string word = "A- -B C-D A BC";
  const std::string joined_word = StringRenderer::InsertWordJoiners(word);
  Image pix = nullptr;
  renderer_->RenderToImage(joined_word.c_str(), joined_word.length(), &pix);
  pix.destroy();
  const std::vector<BoxChar *> &boxchars = renderer_->GetBoxes();
  const std::string kWordJoinerUTF8 = "\u2060";
  ASSERT_EQ(word.length(), boxchars.size());
  for (size_t i = 0; i < boxchars.size(); ++i) {
    EXPECT_NE(kWordJoinerUTF8, boxchars[i]->ch());
    EXPECT_EQ(word.substr(i, 1), boxchars[i]->ch());
  }
}

TEST_F(StringRendererTest, DISABLED_DoesDropUncoveredChars) {
  renderer_ = std::make_unique<StringRenderer>("Verdana 10", 500, 200);
  renderer_->set_drop_uncovered_chars(true);
  const std::string kWord = "office";
  const std::string kCleanWord = "oice";
  Image pix = nullptr;
  EXPECT_FALSE(renderer_->font().CanRenderString(kWord.c_str(), kWord.length()));
  EXPECT_FALSE(renderer_->font().CoversUTF8Text(kWord.c_str(), kWord.length()));
  int offset = renderer_->RenderToImage(kWord.c_str(), kWord.length(), &pix);
  pix.destroy();
  const std::vector<BoxChar *> &boxchars = renderer_->GetBoxes();
  EXPECT_EQ(kWord.length(), offset);
  ASSERT_EQ(kCleanWord.length(), boxchars.size());
  for (size_t i = 0; i < boxchars.size(); ++i) {
    EXPECT_EQ(kCleanWord.substr(i, 1), boxchars[i]->ch());
  }
}

// ------------ StringRenderer::ConvertBasicLatinToFullwidthLatin() ------------

TEST(ConvertBasicLatinToFullwidthLatinTest, DoesConvertBasicLatin) {
  const std::string kHalfAlpha = "ABCD";
  const std::string kFullAlpha = "ABCD";
  EXPECT_EQ(kFullAlpha, StringRenderer::ConvertBasicLatinToFullwidthLatin(kHalfAlpha));

  const std::string kHalfDigit = "0123";
  const std::string kFullDigit = "0123";
  EXPECT_EQ(kFullDigit, StringRenderer::ConvertBasicLatinToFullwidthLatin(kHalfDigit));

  const std::string kHalfSym = "()[]:;!?";
  const std::string kFullSym = "()[]:;!?";
  EXPECT_EQ(kFullSym, StringRenderer::ConvertBasicLatinToFullwidthLatin(kHalfSym));
}

TEST(ConvertBasicLatinToFullwidthLatinTest, DoesNotConvertFullwidthLatin) {
  const std::string kFullAlpha = "ABCD";
  EXPECT_EQ(kFullAlpha, StringRenderer::ConvertBasicLatinToFullwidthLatin(kFullAlpha));

  const std::string kFullDigit = "0123";
  EXPECT_EQ(kFullDigit, StringRenderer::ConvertBasicLatinToFullwidthLatin(kFullDigit));

  const std::string kFullSym = "()[]:;!?";
  EXPECT_EQ(kFullSym, StringRenderer::ConvertBasicLatinToFullwidthLatin(kFullSym));
}

TEST(ConvertBasicLatinToFullwidthLatinTest, DoesNotConvertNonLatin) {
  const std::string kHalfKana = "アイウエオ";
  const std::string kFullKana = "アイウエオ";
  EXPECT_EQ(kHalfKana, StringRenderer::ConvertBasicLatinToFullwidthLatin(kHalfKana));
  EXPECT_EQ(kFullKana, StringRenderer::ConvertBasicLatinToFullwidthLatin(kFullKana));
}

TEST(ConvertBasicLatinToFullwidthLatinTest, DoesNotConvertSpace) {
  const std::string kHalfSpace = " ";
  const std::string kFullSpace = " ";
  EXPECT_EQ(kHalfSpace, StringRenderer::ConvertBasicLatinToFullwidthLatin(kHalfSpace));
  EXPECT_EQ(kFullSpace, StringRenderer::ConvertBasicLatinToFullwidthLatin(kFullSpace));
}

// ------------ StringRenderer::ConvertFullwidthLatinToBasicLatin() ------------

TEST(ConvertFullwidthLatinToBasicLatinTest, DoesConvertFullwidthLatin) {
  const std::string kHalfAlpha = "ABCD";
  const std::string kFullAlpha = "ABCD";
  EXPECT_EQ(kHalfAlpha, StringRenderer::ConvertFullwidthLatinToBasicLatin(kFullAlpha));

  const std::string kHalfDigit = "0123";
  const std::string kFullDigit = "0123";
  EXPECT_EQ(kHalfDigit, StringRenderer::ConvertFullwidthLatinToBasicLatin(kFullDigit));

  const std::string kHalfSym = "()[]:;!?";
  const std::string kFullSym = "()[]:;!?";
  EXPECT_EQ(kHalfSym, StringRenderer::ConvertFullwidthLatinToBasicLatin(kFullSym));
}

TEST(ConvertFullwidthLatinToBasicLatinTest, DoesNotConvertBasicLatin) {
  const std::string kHalfAlpha = "ABCD";
  EXPECT_EQ(kHalfAlpha, StringRenderer::ConvertFullwidthLatinToBasicLatin(kHalfAlpha));

  const std::string kHalfDigit = "0123";
  EXPECT_EQ(kHalfDigit, StringRenderer::ConvertFullwidthLatinToBasicLatin(kHalfDigit));

  const std::string kHalfSym = "()[]:;!?";
  EXPECT_EQ(kHalfSym, StringRenderer::ConvertFullwidthLatinToBasicLatin(kHalfSym));
}

TEST(ConvertFullwidthLatinToBasicLatinTest, DoesNotConvertNonLatin) {
  const std::string kHalfKana = "アイウエオ";
  const std::string kFullKana = "アイウエオ";
  EXPECT_EQ(kHalfKana, StringRenderer::ConvertFullwidthLatinToBasicLatin(kHalfKana));
  EXPECT_EQ(kFullKana, StringRenderer::ConvertFullwidthLatinToBasicLatin(kFullKana));
}

TEST(ConvertFullwidthLatinToBasicLatinTest, DoesNotConvertSpace) {
  const std::string kHalfSpace = " ";
  const std::string kFullSpace = " ";
  EXPECT_EQ(kHalfSpace, StringRenderer::ConvertFullwidthLatinToBasicLatin(kHalfSpace));
  EXPECT_EQ(kFullSpace, StringRenderer::ConvertFullwidthLatinToBasicLatin(kFullSpace));
}
} // namespace tesseract


text:
#import <WatchKit/WatchKit.h>
#import <Foundation/Foundation.h>

@interface NotificationController : WKUserNotificationInterfaceController

@end

redpajama_set_name: RedPajamaGithub


text: export { default } from './RandomButton.js'


text:
{// 引入标签库 }
<tagLib name="html" />
<foreach name="filter_group" item="filter_item">

		{$filter_item.name}:
		<input type="text" class="textbox" name="filter[{$filter_item.id}]" value="{$filter_item.value}" />

</foreach>


text:
using Android.Speech.Tts;
using System;
using System.Collections.Generic;
using System.Threading;
using Android.OS;

namespace Sensus.Android
{
    public class AndroidTextToSpeech : UtteranceProgressListener, TextToSpeech.IOnInitListener
    {
        private TextToSpeech _textToSpeech;
        private ManualResetEvent _initWait;
        private string _utteranceIdToWaitFor;
        private ManualResetEvent _utteranceWait;
        private bool _disposed;

        private readonly object _locker = new object();

        public AndroidTextToSpeech(AndroidSensusService service)
        {
            // initialize wait handles before passing the current object as a listener
            // below. if the listener OnInit method is called before the wait handles are
            // initialized we could get an NRE:  https://insights.xamarin.com/app/Sensus-Production/issues/1099
            _initWait = new ManualResetEvent(false);
            _utteranceWait = new ManualResetEvent(false);
            _disposed = false;

            // initialize speech module
            _textToSpeech = new TextToSpeech(service, this);
            _textToSpeech.SetLanguage(Java.Util.Locale.Default);
            _textToSpeech.SetOnUtteranceProgressListener(this);
        }

        public void OnInit(OperationResult status)
        {
            _initWait.Set();
        }

        public void SpeakAsync(string text, Action callback)
        {
            new Thread(() =>
            {
                lock (_locker)
                {
                    if (_disposed)
                        return;

                    _initWait.WaitOne();
                    _utteranceWait.Reset();
                    _utteranceIdToWaitFor = Guid.NewGuid().ToString();

                    // https://github.com/predictive-technology-laboratory/sensus/wiki/Backwards-Compatibility
#if __ANDROID_21__
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                        _textToSpeech.Speak(text, QueueMode.Add, null, _utteranceIdToWaitFor);
                    else
#endif
                    {
                        // ignore deprecation warning
#pragma warning disable 618
                        Dictionary<string, string> speakParams = new Dictionary<string, string>();
                        speakParams.Add(TextToSpeech.Engine.KeyParamUtteranceId, _utteranceIdToWaitFor);
                        _textToSpeech.Speak(text, QueueMode.Add, speakParams);
#pragma warning restore 618
                    }

                    _utteranceWait.WaitOne();

                    if (callback != null)
                        callback();
                }

            }).Start();
        }

        public override void OnStart(string utteranceId)
        {
        }

        public override void OnDone(string utteranceId)
        {
            if (utteranceId == _utteranceIdToWaitFor)
                _utteranceWait.Set();
        }

        public override void OnError(string utteranceId)
        {
            if (utteranceId == _utteranceIdToWaitFor)
                _utteranceWait.Set();
        }

        protected override void Dispose(bool disposing)
        {
            lock (_locker)
            {
                base.Dispose(disposing);

                _disposed = true;

                try { _textToSpeech.Shutdown(); }
                catch (Exception) { }
            }
        }
    }
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Gx.Rs")]
[assembly: AssemblyDescription("Contains REST specific GEDCOM X model extensions.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("FamilySearch")]
[assembly: AssemblyProduct("Gx.Rs")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("60ebd7bf-0760-44f3-921d-cb452dc213bf")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("1.0.*")]


text:
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using DataAccessLayer;

namespace ConcreteDataStore
{
    /// Class to serialize collections of values.
    internal static class ODataSerializer
    {
        /// Atom namespace
        internal static readonly XNamespace AtomNamespace = "http://www.w3.org/2005/Atom";

        /// Atom namespace
        internal static readonly XNamespace ODataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices";

        /// OData metdata namespace
        internal static readonly XNamespace ODataMetadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

        /// Atom 'content' element name
        internal static readonly XName ODataContentName = AtomNamespace + "content";

        /// OData metadata 'properties' element name
        internal static readonly XName ODataPropertiesName = ODataMetadataNamespace + "properties";

        /// OData metadata 'null' property marker name
        internal static readonly XName NullName = ODataMetadataNamespace + "null";

        /// OData metadata 'type' name
        internal static readonly XName OdataTypeName = ODataMetadataNamespace + "type";

        /// OData default data type (a string) name
        internal const string OdataDefaultTypeName = "Edm.String";

        /// Map of OData types to PropertyType
        private static readonly Dictionary<string, PropertyType> ODataTypeMap = new Dictionary<string, PropertyType>
                {
                    { OdataDefaultTypeName, PropertyType.String },
                    { "Edm.Int32", PropertyType.Int32 },
                    { "Edm.Int64", PropertyType.Int64 },
                    { "Edm.Double", PropertyType.Double },
                    { "Edm.Boolean", PropertyType.Bool },
                    { "Edm.DateTime", PropertyType.Date },
                    { "Edm.Binary", PropertyType.Binary },
                    { "Edm.Guid", PropertyType.Guid }
                };

        /// Determine if the serialization element is a simple property rather than a collection.
        /// <param name="odataName">The OData element name.</param>
        /// <returns>True if the name refers to a simple property.</returns>
        public static bool IsEntityProperty(string odataName)
        {
            var name = new ODataName(odataName);
            return !name.IsAssociation() && !name.IsCollection();
        }

        /// Determine if the serialization element is a simple association rather than a collection.
        /// <param name="odataElement">The OData element.</param>
        /// <returns>True if the name refers to a simple association.</returns>
        public static bool IsSimpleAssociation(ODataElement odataElement)
        {
            if (!odataElement.HasValue)
            {
                return false;
            }

            var odataName = new ODataAssociationName(odataElement.ODataName);
            return odataName.IsAssociation() && !odataName.IsCollection();
        }

        /// Determine if the serialization element is an association.
        /// <param name="odataName">The OData element name.</param>
        /// <returns>True if the name refers to an association.</returns>
        public static bool IsAssociation(string odataName)
        {
            return new ODataAssociationName(odataName).IsAssociation();
        }

        /// Get the collection of OData elements from the OData xml.
        /// <param name="odataXml">The odata xml.</param>
        /// <returns>Collection of ODataElements</returns>
        public static IEnumerable<ODataElement> GetODataElements(XElement odataXml)
        {
            // Note that in development storage we will get back deleted properties with "null" attribute.
            // This shouldn't happen in cloud storage.
            return odataXml.Element(ODataContentName).Element(ODataPropertiesName).Elements()
                .Select(odataProp => ParseODataProperty(odataProp)).ToList();
        }

        /// Parse a single OData property element to an ODataElement object.
        /// <param name="odataProperty">The odata property element.</param>
        /// <returns>An ODataElement object.</returns>
        public static ODataElement ParseODataProperty(XElement odataProperty)
        {
            return new ODataElement
            {
                // If the null attribute is not present, HasValue is true, if the null attribute is present, HasValue has the opposite value
                HasValue = odataProperty.Attribute(NullName) == null || !bool.Parse(odataProperty.Attribute(NullName).Value),
                ODataType = odataProperty.Attribute(OdataTypeName) == null ? OdataDefaultTypeName : odataProperty.Attribute(OdataTypeName).Value,

                // Xml unencode the element name before doing anything further with it.
                ODataName = AzureNameEncoder.UnencodeXmlName(odataProperty.Name.LocalName),
                ODataValue = odataProperty.Value
            };
        }

        /// Get the OData content elements.
        /// <param name="data">The OData xml.</param>
        /// <returns>The OData content xml.</returns>
        public static XElement GetODataContent(XElement data)
        {
            return data.Descendants(ODataPropertiesName).First();
        }

        /// Get the PropertyType value associated with the Odata Type.
        /// <param name="odataProperty">The odata property.</param>
        /// <returns>The PropertyType.</returns>
        public static PropertyType GetPropertyType(ODataElement odataProperty)
        {
            return ODataTypeMap[odataProperty.ODataType];
        }

        /// Get the OData Type associated with a given PropertyType.
        /// <param name="propertyType">The PropertyType.</param>
        /// <returns>ODate type string.</returns>
        public static string GetODataType(PropertyType propertyType)
        {
            return ODataTypeMap.Single(m => m.Value == propertyType).Key;
        }

        /// Serialize a single EntityProperty to the Atom/OData content element.
        /// <param name="odataProperties">The OData properties xml.</param>
        /// <param name="entityProperty">The entity property.</param>
        public static void SerializeEntityProperty(XElement odataProperties, EntityProperty entityProperty)
        {
            if (entityProperty == null)
            {
                // Nothing to serialize
                return;
            }

            var value = entityProperty.Value.SerializationValue;
            var type = GetODataType(entityProperty.Value.DynamicType);
            var name = ODataPropertyName.SerializeProperty(entityProperty);

            // Xml encode the property name before using it as an XElement
            var odataProperty = new XElement(ODataNamespace + AzureNameEncoder.EncodeXmlName(name), value);
            odataProperty.Add(new XAttribute(OdataTypeName, type));
            odataProperties.Add(odataProperty);
        }

        /// Treat the OData element as a collection and deserialize it.
        /// <param name="entity">The entity to add the collection to.</param>
        /// <param name="odataElement">The OData odataElement.</param>
        public static void DeserializeODataToCollection(IEntity entity, ODataElement odataElement)
        {
            var odataName = new ODataName(odataElement.ODataName);

            if (!odataName.IsAssociation() || !odataName.IsCollection())
            {
                throw new DataAccessException("Could not deserialize malformed association in retrieved entity.");
            }

            var associations = DeserializeAssociationCollection(odataElement);
            foreach (var association in associations)
            {
                entity.Associations.Add(association);
            }
        }

        /// Deserialize a single Association from an OData element.
        /// <param name="odataElement">The odata element.</param>
        /// <returns>Association object.</returns>
        public static Association DeserializeAssociation(ODataElement odataElement)
        {
            var association = new Association();

            if (!odataElement.HasValue)
            {
                return association;
            }

            var nameFields = new ODataAssociationName(odataElement.ODataName);
            if (!nameFields.IsAssociation() || nameFields.IsCollection())
            {
                throw new DataAccessException("Could not deserialize malformed association in retrieved entity.");
            }

            var valueFields = new ODataAssociationValue(odataElement.ODataValue);

            // The field name will be of the form v_ptr_Relationship_Company_Agency_ParentCompany
            // The field value will be of the form 00000000000000000000000000000001||Agency||ParentCompany
            // The name will be mangled to conform to our rules so we shouldn't have to
            // validate correctness here. We get Category and AssociationType from the
            // name, TargetEntityId, TargetExternalType, and ExternalName from the value.
            // The other name components are not used here.
            association.TargetEntityCategory = nameFields.TargetEntityCategory;
            association.AssociationType = nameFields.AssociationType;
            association.TargetEntityId = valueFields.TargetEntityId;
            association.TargetExternalType = valueFields.TargetExternalType;
            association.ExternalName = valueFields.ExternalName;

            return association;
        }

        /// Serialize groups of Associations having the same compound key to the odata content xml.
        /// <param name="odataContent">The odata content.</param>
        /// <param name="associationGroupKey">
        /// An Association instance with the association group key fields populated.
        /// </param>
        /// <param name="targetEntityIds">
        /// One or more TargetEntityId's corresponding to the association group key.
        /// </param>
        internal static void SerializeAssociationGroup(XElement odataContent, Association associationGroupKey, EntityId[] targetEntityIds)
        {
            if (targetEntityIds.Length == 0)
            {
                // Nothing to do
                return;
            }

            var odataName = ODataAssociationName.SerializeAssociationGroup(associationGroupKey);
            var odataValue = ODataAssociationValue.SerializeAssociationGroup(targetEntityIds);

            // Xml encode the association group key name before using it as an XElement
            var odataElement = new XElement(ODataNamespace + AzureNameEncoder.EncodeXmlName(odataName), odataValue);
            odataElement.Add(new XAttribute(OdataTypeName, OdataDefaultTypeName));
            odataContent.Add(odataElement);
        }

        /// Deserialize a group of Associations having the same group key.
        /// <param name="odataElement">The OData odataElement.</param>
        /// <returns>List of associations.</returns>
        internal static IEnumerable<Association> DeserializeAssociationGroup(ODataElement odataElement)
        {
            if (!odataElement.HasValue)
            {
                return new List<Association>();
            }

            var nameFields = new ODataAssociationName(odataElement.ODataName);
            if (!nameFields.IsAssociation() || !nameFields.IsCollection())
            {
                // All new associations are association groups. Should not get here if
                // this is not an association and not serialized as a collection.
                throw new DataAccessException("Could not deserialize malformed association in retrieved entity.");
            }

            var groupKey = new ODataAssociationName(odataElement.ODataName).AssociationGroupKey;
            var targetIds = new ODataAssociationValue(odataElement.ODataValue).TargetEntityIds;

            if (groupKey == null || targetIds == null)
            {
                // Could not deserialize the association elements
                throw new DataAccessException("Could not deserialize malformed association in retrieved entity.");
            }

            return targetIds.Select(id => new Association(groupKey) { TargetEntityId = id });
        }

        /// Deserialize to a collection of Associations.
        /// <param name="odataElement">The OData odataElement.</param>
        /// <returns>List of associations.</returns>
        private static IEnumerable<Association> DeserializeAssociationCollection(ODataElement odataElement)
        {
            var associations = new List<Association>();

            if (!odataElement.HasValue)
            {
                return associations;
            }

            var nameFields = new ODataAssociationName(odataElement.ODataName);
            if (!nameFields.IsAssociation() || !nameFields.IsCollection())
            {
                throw new DataAccessException("Could not deserialize malformed association in retrieved entity.");
            }

            IList<string> valueList = ODataAssociationValue.SplitCollectionValues(odataElement.ODataValue);

            foreach (var value in valueList)
            {
                var association = new Association();
                var valueFields = new ODataAssociationValue(value);

                // The field name will be of the form v_ptr_Relationship_Company_Agency_ParentCompany
                // The field value will be of the form 00000000000000000000000000000001||Agency||ParentCompany
                // The name will be mangled to conform to our rules so we shouldn't have to
                // validate correctness here. We get Category and AssociationType from the
                // name, TargetEntityId, TargetExternalType, and ExternalName from the value.
                // The other name components are not used here.
                association.TargetEntityCategory = nameFields.TargetEntityCategory;
                association.AssociationType = nameFields.AssociationType;
                association.TargetEntityId = valueFields.TargetEntityId;
                association.TargetExternalType = valueFields.TargetExternalType;
                association.ExternalName = valueFields.ExternalName;

                associations.Add(association);
            }

            return associations;
        }
    }
}


text:
function Invoke-WinEnum{

    <#
    .SYNOPSIS
    Collects all revelant information about a host and the current user context.

    .DESCRIPTION
    This script conducts user, system, and network enumeration using the current user context or with a specified user and/or keyword.

    .PARAMETER UserName
    Specify a user to enumerate. The default is the current user context.

    .PARAMETER keywords
    Specify a keyword or array of keywords to use in file searches.

    .EXAMPLE
    Conduct enumeration with a username and keyword

    Invoke-WindowsEnum -User "sandersb"

    .EXAMPLE
    Conduct enumeration with a keyword for file searches.

    Invoke-WindowsEnum -keyword "putty"

    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$False,Position=0)]
        [string]$UserName,
        [Parameter(Mandatory=$False,Position=1)]
        [string[]]$keywords
    )

    Function Get-UserInfo{
        if($UserName){
            "UserName: $UserName`n"
            $DomainUser = $UserName
        }
        else{
             #If the username was not provided,
            $DomainUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
            $UserName = $DomainUser.split('\')[-1]
            "UserName: $UserName`n"

        }

        "`n-------------------------------------`n"
        "AD Group Memberships"
        "`n-------------------------------------`n"
        #https://social.technet.microsoft.com/Forums/scriptcenter/en-US/c8001c25-edb5-44b2-ad07-37b39285995f/systemdirectoryservicesaccountmanagement-and-powershell?forum=ITCG
        Add-Type -AssemblyName System.DirectoryServices.AccountManagement
        #Load assembly to User Principal and principalContext .Net classes
        $dsclass = "System.DirectoryServices.AccountManagement"
        $dsclassUP = "$dsclass.userprincipal" -as [type]
        $iType = "SamAccountName"
        $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
        #Get the current domain
        $contextTypeDomain = New-object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Domain,$Domain.Name)
        #Set the context to the current domain
        $cName = $Domain.GetDirectoryEntry().distinguishedName
        #Get the distinguishedName for the domain
        $usr = $dsclassUP::FindByIdentity($contextTypeDomain,$iType,$DomainUser)
        #Grab the user principal object for the domain.
        $usr.GetGroups() | foreach {$_.Name}
        #Enumerate all groups the user is apart of

        "`n-------------------------------------`n"
        "Password Last changed"
        "`n-------------------------------------`n"

        $($usr.LastPasswordSet) + "`n"

        "`n-------------------------------------`n"
        "Last 5 files opened"
        "`n-------------------------------------`n"

        $AllOpenedFiles = Get-ChildItem -Path "C:\" -Recurse -Include @("*.txt","*.pdf","*.docx","*.doc","*.xls","*.ppt") -ea SilentlyContinue | Sort-Object {$_.LastAccessTime}
        $LastOpenedFiles = @()
        $AllOpenedFiles | ForEach-Object {
            $owner = $($_.GetAccessControl()).Owner
            $owner = $owner.split('\')[-1]
            if($owner -eq $UserName){
                $LastOpenedFiles += $_
            }
        }
        if($LastOpenedFiles){
            $LastOpenedFiles | Sort-Object LastAccessTime -Descending | Select-Object FullName, LastAccessTime -First 5 | Format-List | Out-String
        }

        "`n-------------------------------------`n"
        "Interesting Files"
        "`n-------------------------------------`n"
        #If the keyword is set, use it in the file search
        $NewestInterestingFiles = @()
        if($keywords)
        {
            $AllInterestingFiles = Get-ChildItem -Path "C:\" -Recurse -Include $keywords -ea SilentlyContinue | where {$_.Mode.StartsWith('d') -eq $False} | Sort-Object {$_.LastAccessTime}
            $AllInterestingFiles | ForEach-Object {
                $owner = $_.GetAccessControl().Owner
                $owner = $owner.split('\')[-1]
                if($owner -eq $UserName){
                    $NewestInterestingFiles += $_
                }
            }
            if($NewestInterestingFiles){
                $NewestInterestingFiles | Sort-Object LastAccessTime -Descending | Select-Object FullName, LastAccessTime | Format-List | Out-String
            }
        }
        else
        {
            $AllInterestingFiles = Get-ChildItem -Path "C:\" -Recurse -Include @("*.txt","*.pdf","*.docx","*.doc","*.xls","*.ppt","*pass*","*cred*") -ErrorAction SilentlyContinue | where {$_.Mode.StartsWith('d') -eq $False} | Sort-Object {$_.LastAccessTime}
            $AllInterestingFiles | ForEach-Object {
                $owner = $_.GetAccessControl().Owner
                $owner = $owner.split('\')[-1]
                if($owner -eq $UserName){
                    $NewestInterestingFiles += $_
                }
            }
            if($NewestInterestingFiles)
            {
                $NewestInterestingFiles | Sort-Object LastAccessTime -Descending | Select-Object FullName, LastAccessTime | Format-List | Out-String
            }
        }

        "`n-------------------------------------`n"
        "Clipboard Contents"
        "`n-------------------------------------`n"
        #http://www.bgreco.net/powershell/get-clipboard/

        $cmd = {
            Add-Type -Assembly PresentationCore
            [Windows.Clipboard]::GetText() -replace "`r", '' -split "`n"
        }
        if([threading.thread]::CurrentThread.GetApartmentState() -eq 'MTA'){
            & powershell -Sta -Command $cmd
        }
        else{
            $cmd
        }
        "`n"
    }

    Function Get-SysInfo{
        "`n-------------------------------------`n"
        "System Information"
        "`n-------------------------------------`n"
        #Grab the Windows Version and arch
        $OSVersion = (Get-WmiObject -class Win32_OperatingSystem).Caption
        $OSArch = (Get-WmiObject -class win32_operatingsystem).OSArchitecture
        "OS: $OSVersion $OSArch`n"

        if($OSArch -eq '64-bit')
        {
            $registeredAppsx64 = Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName | Sort-Object DisplayName
            $registeredAppsx86 = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName | Sort-Object DisplayName
            $registeredAppsx64 | Where-Object {$_.DisplayName -ne ' '} | Select-Object DisplayName | Format-Table -AutoSize | Out-String
            $registeredAppsx86 | Where-Object {$_.DisplayName -ne ' '} | Select-Object DisplayName | Format-Table -AutoSize | Out-String
        }
        else
        {
            $registeredAppsx86 =  Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName | Sort-Object DisplayName
            $registeredAppsx86 | Where-Object {$_.DisplayName -ne ' '} | Select-Object DisplayName | Format-Table -AutoSize | Out-String
        }

        "`n-------------------------------------`n"
        "Services"
        "`n-------------------------------------`n"

        $AllServices = @()
        Get-WmiObject -class win32_service | ForEach-Object{
            $service = New-Object PSObject -Property @{
                ServiceName = $_.DisplayName
                ServiceStatus = (Get-service | where-object { $_.DisplayName -eq $ServiceName}).status
                ServicePathtoExe = $_.PathName
                StartupType = $_.StartMode
            }
            $AllServices += $service
        }

        $AllServices | Select ServicePathtoExe, ServiceName | Format-Table -AutoSize | Out-String

        "`n-------------------------------------`n"
        "Available Shares"
        "`n-------------------------------------`n"

        Get-WmiObject -class win32_share | Format-Table -AutoSize Name, Path, Description, Status | Out-String

        "`n-------------------------------------`n"
        "AV Solution"
        "`n-------------------------------------`n"

        $AV = Get-WmiObject -namespace root\SecurityCenter2 -class Antivirusproduct
        if($AV){
            $AV.DisplayName + "`n"
            #No documentation from MSDN
            #Best resource found : http://neophob.com/2010/03/wmi-query-windows-securitycenter2/
            $AVstate = $AV.productState
            $statuscode = "{0:x6}" -f $AVstate
            $wscprovider = $statuscode[0,1]
            $wscscanner = $statuscode[2,3]
            $wscuptodate = $statuscode[4,5]
            $statuscode = -join $statuscode

            "AV Product State: " + $AV.productState + "`n"
            #check if the AV is enabled

            if($wscscanner -ge '10'){
                "Enabled: Yes`n"
            }
            elseif($wscscanner -eq '00' -or $wscscanner -eq '01'){
                "Enabled: No`n"
            }
            else{
                "Enabled: Unknown`n"
            }
            #Check if definitions are up to date
            if($wscuptodate -eq '00'){
                "Updated: Yes`n"
            }
            elseif($wscuptodate -eq '10'){
                "Updated: No`n"
            }
            else{
                "Updated: Unknown`n"
            }
        }

        "`n-------------------------------------`n"
        "Windows Last Updated"
        "`n-------------------------------------`n"
        $Lastupdate = Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object InstalledOn -First 1
        if($Lastupdate){
           $Lastupdate.InstalledOn | Out-String
           "`n"
        }
        else{
            "Unknown`n"
        }

    }

    Function Get-NetInfo{
        "`n-------------------------------------`n"
        "Network Adapters"
        "`n-------------------------------------`n"
        #http://thesurlyadmin.com/2013/05/20/using-powershell-to-get-adapter-information/
        foreach ($Adapter in (Get-WmiObject -class win32_networkadapter -Filter "NetConnectionStatus='2'")){
            $config = Get-WmiObject -class win32_networkadapterconfiguration -Filter "Index = '$($Adapter.Index)'"
            "`n"
            "Adapter: " + $Adapter.Name + "`n"
            "`n"
            "IP Address: "
            if($config.IPAddress -is [system.array]){
                $config.IPAddress[0] + "`n"
            }
            else{
                $config.IPAddress + "`n"
            }
            "`n"
            "Mac Address: " + $Config.MacAddress
            "`n"
        }

        "`n-------------------------------------`n"
        "Netstat Established connections and processes"
        "`n-------------------------------------`n"
        #http://blogs.microsoft.co.il/scriptfanatic/2011/02/10/how-to-find-running-processes-and-their-port-number/

        $properties = 'Protocol','LocalAddress','LocalPort'
        $properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'

        netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {

            $item = $_.line.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)

            if($item[1] -notmatch '^\[::')
            {
                if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
                {
                    $localAddress = $la.IPAddressToString
                    $localPort = $item[1].split('\]:')[-1]
                }
                else
                {
                    $localAddress = $item[1].split(':')[0]
                    $localPort = $item[1].split(':')[-1]
                }

                if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
                {
                    $remoteAddress = $ra.IPAddressToString
                    $remotePort = $item[2].split('\]:')[-1]
                }
                else
                {
                    $remoteAddress = $item[2].split(':')[0]
                    $remotePort = $item[2].split(':')[-1]
                }

                $netstat = New-Object PSObject -Property @{
                    PID = $item[-1]
                    ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
                    Protocol = $item[0]
                    LocalAddress = $localAddress
                    LocalPort = $localPort
                    RemoteAddress =$remoteAddress
                    RemotePort = $remotePort
                    State = if($item[0] -eq 'tcp') {$item[3]} else {$null}
                }
                if($netstat.State -eq 'ESTABLISHED' ){
                    $netstat | Format-List ProcessName,LocalAddress,LocalPort,RemoteAddress,RemotePort,State | Out-String | % { $_.Trim() }
                    "`n`n"
                }
            }
        }

        "`n-------------------------------------`n"
        "Mapped Network Drives"
        "`n-------------------------------------`n"

        Get-WmiObject -class win32_logicaldisk | where-object {$_.DeviceType -eq 4} | ForEach-Object{
            $NetPath = $_.ProviderName
            $DriveLetter = $_.DeviceID
            $DriveName = $_.VolumeName
            $NetworkDrive = New-Object PSObject -Property @{
                Path = $NetPath
                Drive = $DriveLetter
                Name = $DriveName
            }
            $NetworkDrive
        }

        "`n-------------------------------------`n"
        "Firewall Rules"
        "`n-------------------------------------`n"
        #http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/03/hey-scripting-guy-weekend-scripter-how-to-retrieve-enabled-windows-firewall-rules.aspx
        #Create the firewall com object to enumerate
        $fw = New-Object -ComObject HNetCfg.FwPolicy2
        #Retrieve all firewall rules
        $FirewallRules = $fw.rules
        #create a hashtable to define all values
        $fwprofiletypes = @{1GB="All";1="Domain"; 2="Private" ; 4="Public"}
        $fwaction = @{1="Allow";0="Block"}
        $FwProtocols = @{1="ICMPv4";2="IGMP";6="TCP";17="UDP";41="IPV6";43="IPv6Route"; 44="IPv6Frag";
                  47="GRE"; 58="ICMPv6";59="IPv6NoNxt";60="IPv60pts";112="VRRP"; 113="PGM";115="L2TP"}
        $fwdirection = @{1="Inbound"; 2="Outbound"}

        #Retrieve the profile type in use and the current rules

        $fwprofiletype = $fwprofiletypes.Get_Item($fw.CurrentProfileTypes)
        $fwrules = $fw.rules

        "Current Firewall Profile Type in use: $fwprofiletype"
        $AllFWRules = @()
        #enumerate the firewall rules
        $fwrules | ForEach-Object{
            #Create custom object to hold properties for each firewall rule
            $FirewallRule = New-Object PSObject -Property @{
                ApplicationName = $_.Name
                Protocol = $fwProtocols.Get_Item($_.Protocol)
                Direction = $fwdirection.Get_Item($_.Direction)
                Action = $fwaction.Get_Item($_.Action)
                LocalIP = $_.LocalAddresses
                LocalPort = $_.LocalPorts
                RemoteIP = $_.RemoteAddresses
                RemotePort = $_.RemotePorts
            }

            $AllFWRules += $FirewallRule

        }
        $AllFWRules | Select-Object Action, Direction, RemoteIP, RemotePort, LocalPort, ApplicationName | Format-List | Out-String
    }

    Get-UserInfo
    Get-SysInfo
    Get-NetInfo

}


text:
package javaselast.examples.app.persistance;

import java.util.List;

public interface Repository<T,K> {

    List<T> find();
    List<T> find( Predicate<T> predicate );
    T findById(K key);
    void delete(T entity);
    void update(T entity);

    /**
     * SDfsfsdfsdfsdfs sdfsdf.
     *
     * sdfj
sdfs

     * f sfsdfsfsdf
     *
     * @param entity (don't check)
     * @return
     */
    T insert(T entity);
    Repository<K,T> copy(Repository<K,T> repository);

    void saveChanges();
}


text:
import {AfterViewInit, Component, OnDestroy, OnInit} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';

import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {MessageService} from 'primeng/api';

import {AppSettings} from '../services/app-settings.service';
import {SettingsService} from '../settings/settings.service';
import {AppModalAbstractComponent} from '../components/modal.component.abstract';
import {EditableFile} from './models/editable-file.model';
import {FileEditService} from './services/file-edit.service';

declare const ace: any;

@Component({
    selector: 'app-modal-file-edit',
    templateUrl: './templates/modal-file-edit.component.html',
    providers: [FileEditService]
})
export class ModalFileEditComponent extends AppModalAbstractComponent<EditableFile> implements OnInit, AfterViewInit, OnDestroy {

    form = new FormGroup({
        id: new FormControl('', [])
    });
    isEditMode = false;
    editor: any;
    errorMessage = '';
    submitted = false;
    loading = false;
    isPathReadOnly = false;
    closeReason = 'canceled';
    uniqueId = '';
    destroyed$ = new Subject<void>();

    constructor(
        public ref: DynamicDialogRef,
        public config: DynamicDialogConfig,
        public dataService: FileEditService,
        private messageService: MessageService,
        private settingsService: SettingsService,
        private appSettings: AppSettings
    ) {
        super(ref, config, dataService);
    }

    ngOnInit(): void {
        this.model = new EditableFile(this.config.data.id, '', '');
        this.model.type = this.config.data.type || 'template';
        if (this.config.data.name) {
            this.isEditMode = true;
            this.model.name = this.config.data.name;
            this.model.path = this.config.data.path;
            this.model.extension = this.config.data.extension;
            this.model.themeName = this.config.data.themeName;
        }
        if (this.isEditMode) {
            this.getContent();
        }
    }

    ngAfterViewInit(): void {
        this.editorInit();
    }

    getContent(): void {
        this.loading = true;
        const filePath = EditableFile.getPath(this.model);
        this.dataService.getItemContent(filePath, this.model.type)
            .pipe(takeUntil(this.destroyed$))
            .subscribe({
                next: (res) => {
                    if (res['content']) {
                        setTimeout(() => {
                            this.model.content = res['content'];
                            this.editor.setValue(this.model.content, -1);
                        }, 0);
                    }
                    this.loading = false;
                },
                error: (err) => {
                    if (err['error']) {
                        this.errorMessage = err['error'];
                    }
                    this.loading = false;
                }
            });
    }

    editorInit(): void {
        const modelist = ace.require('ace/ext/modelist');
        const editorMode = this.isEditMode
            ? modelist.getModeForPath(`${this.model.path}/${this.model.name}`).mode
            : 'ace/mode/twig';

        ace.config.setModuleUrl('ace/mode/javascript_worker', '../js/ace/worker-javascript.js');
        ace.config.setModuleUrl('ace/mode/css_worker', '../js/ace/worker-css.js');

        this.editor = ace.edit(`editor-${this.model.type}-${this.model.id}`, {
            mode: editorMode,
            theme: 'ace/theme/kuroir',
            maxLines: 30,
            minLines: 15,
            fontSize: 18
        });
    }

    saveRequest() {
        return this.dataService.saveContent(this.getFormData());
    }

    getFormData(): any {
        const data = Object.assign({}, this.model);
        data.content = this.editor.getValue();
        return data;
    }
}


text:
package net.andrewhatch.games.field;

public class App {
    public static void main(String[] args) throws Exception {
        new GameFactory()
            .createGame(App.class.getResourceAsStream("/example.field"))
            .play();
    }
}


text:
package dynoapps.exchange_rates.alarm;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.SourcesManager;
import dynoapps.exchange_rates.data.CurrencySource;
import dynoapps.exchange_rates.ui.widget.recyclerview.UpdatableAdapter;
import dynoapps.exchange_rates.util.CollectionUtils;
import dynoapps.exchange_rates.util.RateUtils;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by erdemmac on 14/12/2016.
 */

class AlarmsAdapter extends UpdatableAdapter<List<Alarm>, AlarmsActivity.AlarmViewHolder> {
    private List<Alarm> alarms;
    private final AlarmsRepository alarmRepository;

    AlarmsAdapter(AlarmsRepository alarmsRepository, ArrayList<Alarm> alarms) {
        this.alarmRepository = alarmsRepository;
        this.alarms = new ArrayList<>();
        this.alarms.addAll(alarms);
    }

    private int getToAddIndex(Alarm alarm) {
        if (CollectionUtils.isNullOrEmpty(alarms)) return 0;
        for (int i = 0; i < alarms.size(); i++) {
            Alarm innerAlarm = alarms.get(i);
            if (Alarm.COMPARATOR.compare(alarm, innerAlarm) < 0) {
                return Math.max(0, i);
            }
        }
        return CollectionUtils.size(alarms);
    }

    public void addData(Alarm alarm) {
        if (this.alarms == null) this.alarms = new ArrayList<>();
        int index = getToAddIndex(alarm);
        this.alarms.add(index, alarm);
        notifyItemInserted(index);
    }

    public void addData(List<Alarm> alarms) {
        if (this.alarms == null) this.alarms = new ArrayList<>();
        final int insertRangeStart = getItemCount();
        this.alarms.addAll(alarms);
        notifyItemRangeInserted(insertRangeStart, getItemCount());
    }

    @Override
    public AlarmsActivity.AlarmViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_alarm, parent, false);
        return new AlarmsActivity.AlarmViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final AlarmsActivity.AlarmViewHolder holder, int position) {
        final Alarm alarm = alarms.get(position);
        holder.ivType.setRotation(alarm.isAbove ? 90 : 270);
        holder.ivType.setColorFilter(ContextCompat.getColor(App.context(), alarm.isAbove ?
                android.R.color.holo_green_light :
                android.R.color.holo_red_light));
        holder.tvTypeHint.setText(alarm.isAbove ? R.string.if_above : R.string.if_below);
        holder.tvValue.setText(RateUtils.valueToUI(alarm.val, alarm.rateType));
        holder.ivRateType.setImageResource(RateUtils.getRateIcon(alarm.rateType));
        CurrencySource source = SourcesManager.getSource(alarm.sourceType);
        if (source != null) {
            holder.tvSource.setText(source.getName());
            holder.tvSource.setTextColor(source.getColor());
        } else {
            holder.tvSource.setText("-");
            holder.tvSource.setTextColor(ContextCompat.getColor(App.context(), R.color.colorPrimary));
        }

        holder.vClose.setOnClickListener(view -> {
            int pos = holder.getAdapterPosition();
            AlarmsAdapter.this.alarms.remove(pos);
            notifyItemRemoved(pos);
            alarmRepository.deleteAlarm(alarm).subscribeOn(Schedulers.io()).subscribe();
        });
        holder.swAlarm.setChecked(alarm.isEnabled);
        holder.swAlarm.setOnCheckedChangeListener((compoundButton, b) -> {
            alarm.isEnabled = b;
            alarmRepository.updateAlarm(alarm).subscribeOn(Schedulers.io()).subscribe();
        });
    }

    @Override
    public int getItemCount() {
        return alarms != null ? alarms.size() : 0;
    }

    @Override
    public void update(@NonNull List<Alarm> updatedData) {
        alarms = updatedData;
        notifyDataSetChanged();
    }
}


text:
/**
 * This file includes polyfills needed by Angular and is loaded before the app.
 * You can add your own extra polyfills to this file.
 *
 * This file is divided into 2 sections:
 *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
 *   2. Application imports. Files imported after ZoneJS that should be loaded before your main
 *      file.
 *
 * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
 * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
 * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
 *
 * Learn more in https://angular.io/guide/browser-support
 */

/***************************************************************************************************
 * BROWSER POLYFILLS
 */

import 'core-js/es/reflect';
import 'zone.js';
// import 'classlist-polyfill';
// import 'web-animations-js';
// import 'intl';
// import 'intl/locale-data/jsonp/en';

/***************************************************************************************************
* SCULLY IMPORTS
*/
import 'zone.js/dist/task-tracking';


text:
require "odi_content_models/version"
require "mongoid"
require "govuk_content_models"

begin
  module OdiContentModels
    class Engine < Rails::Engine
      config.to_prepare do
        Dir.glob(File.dirname(__FILE__) + "/../app/decorators/**/*_decorator*.rb").each do |c|
          require_dependency(c)
        end
      end
    end
  end
rescue NameError
  module OdiContentModels
  end
end


text:
int main(int argc, char **argv)
{
  tf2::Transform tf;
  geometry_msgs::Twist tw;
  tw.linear.x = tf.getOrigin().getX();
  return 0;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>J&C System - <?=$Empresa->Nome?></title>

    <link href="<?=$PastaLocal?>template/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="<?=$PastaLocal?>template/bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">

    <link href="<?=$PastaLocal?>template/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet">

    <link href="<?=$PastaLocal?>template/bower_components/datatables-responsive/css/dataTables.responsive.css" rel="stylesheet">

    <link href="<?=$PastaLocal?>template/dist/css/sb-admin-2.css" rel="stylesheet">

    <link href="<?=$PastaLocal?>template/bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

        <?php include('navegacao.php');?>

Visualizar Recursos

                <?php if(isset($_GET['ok'])){?>

                            Dados atualizados com sucesso!

                <?php } if(isset($ExcluirId)){?>
                <?php
                echo form_open('recursos/excluir', 'role="form"');
                echo form_hidden('Id',$ExcluirId->Id)
                ?>

                            Exclusão de Recurso

Deseja realmente excluir o recurso: <?=$ExcluirId->Nome?>?

                            <button type="submit" class="btn btn-success">Sim</button> <button type="button" class="btn btn-danger" onclick="window.location='<?=$PastaLocal?>recursos'">Não</button>

                <?php echo form_close();?>
                <?php }?>

                    <button type="button" class="btn btn-success" onclick="window.location='<?=$PastaLocal?>recursos/cadastro/Id/'">Adicionar</button>

                                    Código
                                    Nome
                                    Módulo

                                <?php
                                foreach ($Recursos as $Recurso) {
                                ?>

                                    <?=$Recurso->Iniciais?>
                                    <div style="cursor: pointer" onclick="window.location='<?=$PastaLocal?>recursos/cadastro/Id/<?=$Recurso->Id?>'"><?php echo $Recurso->Nome;?>

                                        <?php
                                        foreach ($Modulos as $Modulo) {
                                            if($Modulo->Id == $Recurso->ModuloId){
                                                echo $Modulo->Nome;
                                            }
                                        }
                                        ?>

                                    <button type="button" class="btn btn-warning btn-circle" onclick="window.location='?exclui=<?=$Recurso->Id?>'"></button>

                                    <?php }?>


text:
package org.apache.commons.cli;

/**
 *
Base for Exceptions thrown during parsing of a command-line.

 *
 * @author bob mcwhirter (bob @ werken.com)
 * @version $Revision: 1.2 $
 */
public class ParseException extends Exception {

    /**
     *
Construct a new ParseException
     * with the specified detail message.

     *
     * @param message the detail message
     */
    public ParseException(String message) {
        super(message);
    }
}


text:
var postcss = require('postcss');

module.exports = postcss.plugin('postcss-focus', function () {
    return function (css) {
        css.walkRules(function (rule) {
            if ( rule.selector.indexOf(':hover') !== -1 ) {
                var focuses = [];
                rule.selectors.forEach(function (selector) {
                    if ( selector.indexOf(':hover') !== -1 ) {
                        focuses.push(selector.replace(/:hover/g, ':focus'));
                    }
                });
                if ( focuses.length ) {
                    rule.selectors = rule.selectors.concat(focuses);
                }
            }
        });
    };
});


text:
<?php

namespace AppBundle\Form\Type;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class LeagueMatchType extends AbstractProofType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $admin = $options['admin'];

        if ($admin) {
            $builder
                ->add('challenger');
        }

        $scores = $builder->create('scores', 'form', ['mapped' => false, 'label' => false, 'attr' => ['orbital-collapse' => 'Scores']])
            ->add('challenger_score', EntityType::class, [
                'class' => 'AppBundle:Score',
                'required' => false,
            ])
            ->add('challenger_score_value', IntegerType::class, [
                'required' => false,
            ])
            ->add('challengee_score', EntityType::class, [
                'class' => 'AppBundle:Score',
                'required' => false,
            ])
            ->add('challengee_score_value', IntegerType::class, [
                'required' => false,
            ]);

        $builder
            ->add('challengee')
            ->add('round', EntityType::class, [
                'class' => 'AppBundle:Round',
                'required' => true,
            ])
            ->add('accepted', CheckboxType::class, [
                'required' => false,
            ])
            ->add($scores)
            ->add('result', CheckboxType::class, [
                'label' => 'Challenger won?',
                'required' => false,
            ])
            ->add('date_challenged');

        $builder->add($this->getProofForm($builder));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'AppBundle\Entity\LeagueMatch',

            'admin' => false,
        ]);
    }
}