text:
namespace cobalt {
namespace watchdog {

namespace {

const char kWatchdogViolationsJson[] = "watchdog_test.json";
const int64_t kWatchdogMonitorFrequency = 100000;

}  // namespace

class WatchdogTest : public testing::Test {
 protected:
  WatchdogTest() {}

  void SetUp() final {
    watchdog_ = new watchdog::Watchdog();
    watchdog_->InitializeCustom(nullptr, std::string(kWatchdogViolationsJson),
                                kWatchdogMonitorFrequency);
    watchdog_->GetWatchdogViolations();
  }

  void TearDown() final {
    watchdog_->Uninitialize();
    delete watchdog_;
    watchdog_ = nullptr;
  }

  base::Value CreateDummyViolationDict(std::string desc, int begin, int end) {
    base::Value violation_dict(base::Value::Type::DICTIONARY);
    violation_dict.SetKey("description", base::Value(desc));
    base::Value list(base::Value::Type::LIST);
    for (int i = begin; i < end; i++)
      list.GetList().emplace_back(CreateDummyViolation(i));
    violation_dict.SetKey("violations", list.Clone());
    return violation_dict.Clone();
  }

  base::Value CreateDummyViolation(int timestamp_violation) {
    base::Value violation(base::Value::Type::DICTIONARY);
    base::Value ping_infos(base::Value::Type::LIST);
    violation.SetKey("pingInfos", ping_infos.Clone());
    violation.SetKey("monitorState",
                     base::Value(std::string(GetApplicationStateString(
                         base::kApplicationStateStarted))));
    violation.SetKey("timeIntervalMilliseconds", base::Value("0"));
    violation.SetKey("timeWaitMilliseconds", base::Value("0"));
    violation.SetKey("timestampRegisteredMilliseconds", base::Value("0"));
    violation.SetKey("timestampLastPingedMilliseconds", base::Value("0"));
    violation.SetKey("timestampViolationMilliseconds",
                     base::Value(std::to_string(timestamp_violation)));
    violation.SetKey("violationDurationMilliseconds", base::Value("0"));
    base::Value registered_clients(base::Value::Type::LIST);
    violation.SetKey("registeredClients", registered_clients.Clone());
    return violation.Clone();
  }

  watchdog::Watchdog* watchdog_;
};

TEST_F(WatchdogTest, RedundantRegistersShouldFail) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));

  ASSERT_FALSE(watchdog_->Register("test-name", "test-desc",
                                   base::kApplicationStateStarted,
                                   kWatchdogMonitorFrequency));
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 0, PING));
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 0, ALL));
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, RegisterOnlyAcceptsValidParameters) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 0));
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
  ASSERT_FALSE(watchdog_->Register("test-name-1", "test-desc-1",
                                   base::kApplicationStateStarted, 1, 0));
  ASSERT_FALSE(watchdog_->Unregister("test-name-1"));
  ASSERT_FALSE(watchdog_->Register("test-name-2", "test-desc-2",
                                   base::kApplicationStateStarted, 0, 0));
  ASSERT_FALSE(watchdog_->Unregister("test-name-2"));
  ASSERT_FALSE(watchdog_->Register("test-name-3", "test-desc-3",
                                   base::kApplicationStateStarted, -1, 0));
  ASSERT_FALSE(watchdog_->Unregister("test-name-3"));
  ASSERT_TRUE(watchdog_->Register("test-name-4", "test-desc-4",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 1));
  ASSERT_TRUE(watchdog_->Unregister("test-name-4"));
  ASSERT_TRUE(watchdog_->Register("test-name-5", "test-desc-5",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 0));
  ASSERT_TRUE(watchdog_->Unregister("test-name-5"));
  ASSERT_FALSE(watchdog_->Register("test-name-6", "test-desc-6",
                                   base::kApplicationStateStarted,
                                   kWatchdogMonitorFrequency, -1));
  ASSERT_FALSE(watchdog_->Unregister("test-name-6"));
}

TEST_F(WatchdogTest, UnmatchedUnregistersShouldFail) {
  ASSERT_FALSE(watchdog_->Unregister("test-name"));
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
  ASSERT_FALSE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, UnmatchedPingsShouldFail) {
  ASSERT_FALSE(watchdog_->Ping("test-name"));
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  ASSERT_TRUE(watchdog_->Ping("test-name"));
  ASSERT_TRUE(watchdog_->Ping("test-name"));
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
  ASSERT_FALSE(watchdog_->Ping("test-name"));
}

TEST_F(WatchdogTest, PingOnlyAcceptsValidParameters) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  ASSERT_TRUE(watchdog_->Ping("test-name", "42"));
  ASSERT_FALSE(
      watchdog_->Ping("test-name",
                      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                      "xxxxxxxxxxxxxxxxxxxxxxxxxxx"));
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, ViolationsJsonShouldPersistAndBeValid) {
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  ASSERT_TRUE(watchdog_->Ping("test-name", "test-ping"));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
  TearDown();
  watchdog_ = new watchdog::Watchdog();
  watchdog_->InitializeCustom(nullptr, std::string(kWatchdogViolationsJson),
                              kWatchdogMonitorFrequency);

  // Validates Violation json file.
  std::string json = watchdog_->GetWatchdogViolations();
  ASSERT_NE(json, "");
  std::unique_ptr<base::Value> violations_map = base::JSONReader::Read(json);
  ASSERT_NE(violations_map, nullptr);
  base::Value* violation_dict = violations_map->FindKey("test-name");
  ASSERT_NE(violation_dict, nullptr);
  base::Value* description = violation_dict->FindKey("description");
  ASSERT_NE(description, nullptr);
  ASSERT_EQ(description->GetString(), "test-desc");
  base::Value* violations = violation_dict->FindKey("violations");
  ASSERT_NE(violations, nullptr);
  ASSERT_EQ(violations->GetList().size(), 1);
  base::Value* monitor_state = violations->GetList()[0].FindKey("monitorState");
  ASSERT_NE(monitor_state, nullptr);
  ASSERT_EQ(
      monitor_state->GetString(),
      std::string(GetApplicationStateString(base::kApplicationStateStarted)));
  base::Value* ping_infos = violations->GetList()[0].FindKey("pingInfos");
  ASSERT_NE(ping_infos, nullptr);
  ASSERT_EQ(ping_infos->GetList().size(), 1);
  base::Value* info = ping_infos->GetList()[0].FindKey("info");
  ASSERT_NE(info, nullptr);
  ASSERT_EQ(info->GetString(), "test-ping");
  base::Value* timestamp_milliseconds =
      ping_infos->GetList()[0].FindKey("timestampMilliseconds");
  ASSERT_NE(timestamp_milliseconds, nullptr);
  std::stoll(timestamp_milliseconds->GetString());
  base::Value* registered_clients =
      violations->GetList()[0].FindKey("registeredClients");
  ASSERT_NE(registered_clients, nullptr);
  ASSERT_EQ(registered_clients->GetList().size(), 1);
  ASSERT_EQ(registered_clients->GetList()[0].GetString(), "test-name");
  base::Value* time_interval_milliseconds =
      violations->GetList()[0].FindKey("timeIntervalMilliseconds");
  ASSERT_NE(time_interval_milliseconds, nullptr);
  std::stoll(time_interval_milliseconds->GetString());
  base::Value* time_wait_milliseconds =
      violations->GetList()[0].FindKey("timeWaitMilliseconds");
  ASSERT_NE(time_wait_milliseconds, nullptr);
  std::stoll(time_wait_milliseconds->GetString());
  base::Value* timestamp_last_pinged_milliseconds =
      violations->GetList()[0].FindKey("timestampLastPingedMilliseconds");
  ASSERT_NE(timestamp_last_pinged_milliseconds, nullptr);
  std::stoll(timestamp_last_pinged_milliseconds->GetString());
  base::Value* timestamp_registered_milliseconds =
      violations->GetList()[0].FindKey("timestampRegisteredMilliseconds");
  ASSERT_NE(timestamp_registered_milliseconds, nullptr);
  std::stoll(timestamp_registered_milliseconds->GetString());
  base::Value* timestamp_violation_milliseconds =
      violations->GetList()[0].FindKey("timestampViolationMilliseconds");
  ASSERT_NE(timestamp_violation_milliseconds, nullptr);
  std::stoll(timestamp_violation_milliseconds->GetString());
  base::Value* violation_duration_milliseconds =
      violations->GetList()[0].FindKey("violationDurationMilliseconds");
  ASSERT_NE(violation_duration_milliseconds, nullptr);
  std::stoll(violation_duration_milliseconds->GetString());
}

TEST_F(WatchdogTest, RedundantViolationsShouldStack) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  std::string json = watchdog_->GetWatchdogViolations(false);
  ASSERT_NE(json, "");
  std::unique_ptr<base::Value> uncleared_violations_map =
      base::JSONReader::Read(json);
  ASSERT_NE(uncleared_violations_map, nullptr);
  base::Value* violation_dict = uncleared_violations_map->FindKey("test-name");
  base::Value* violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 1);
  std::string uncleared_timestamp =
      violations->GetList()[0]
          .FindKey("timestampLastPingedMilliseconds")
          ->GetString();
  int64_t uncleared_duration =
      std::stoll(violations->GetList()[0]
                     .FindKey("violationDurationMilliseconds")
                     ->GetString());
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  json = watchdog_->GetWatchdogViolations(false);
  ASSERT_NE(json, "");
  std::unique_ptr<base::Value> violations_map = base::JSONReader::Read(json);
  ASSERT_NE(violations_map, nullptr);
  violation_dict = violations_map->FindKey("test-name");
  violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 1);
  std::string timestamp = violations->GetList()[0]
                              .FindKey("timestampLastPingedMilliseconds")
                              ->GetString();
  int64_t duration = std::stoll(violations->GetList()[0]
                                    .FindKey("violationDurationMilliseconds")
                                    ->GetString());
  ASSERT_EQ(uncleared_timestamp, timestamp);
  ASSERT_LT(uncleared_duration, duration);
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, ViolationsShouldResetAfterFetch) {
  ASSERT_TRUE(watchdog_->Register("test-name-1", "test-desc-1",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  ASSERT_TRUE(watchdog_->Unregister("test-name-1"));
  std::string json = watchdog_->GetWatchdogViolations();
  ASSERT_NE(json.find("test-name-1"), std::string::npos);
  ASSERT_EQ(json.find("test-name-2"), std::string::npos);
  ASSERT_TRUE(watchdog_->Register("test-name-2", "test-desc-2",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  ASSERT_TRUE(watchdog_->Unregister("test-name-2"));
  json = watchdog_->GetWatchdogViolations();
  ASSERT_EQ(json.find("test-name-1"), std::string::npos);
  ASSERT_NE(json.find("test-name-2"), std::string::npos);
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
}

TEST_F(WatchdogTest, PingInfosAreEvictedAfterMax) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test_desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  for (int i = 0; i < 21; i++) {
    ASSERT_TRUE(watchdog_->Ping("test-name", std::to_string(i)));
  }
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  std::string json = watchdog_->GetWatchdogViolations();
  ASSERT_NE(json, "");
  std::unique_ptr<base::Value> violations_map = base::JSONReader::Read(json);
  ASSERT_NE(violations_map, nullptr);
  base::Value* violation_dict = violations_map->FindKey("test-name");
  base::Value* violations = violation_dict->FindKey("violations");
  base::Value* pingInfos = violations->GetList()[0].FindKey("pingInfos");
  ASSERT_EQ(pingInfos->GetList().size(), 20);
  ASSERT_EQ(pingInfos->GetList()[0].FindKey("info")->GetString(), "1");
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, ViolationsAreEvictedAfterMax) {
  // Creates maxed Violation json file.
  std::unique_ptr<base::Value> dummy_map =
      std::make_unique<base::Value>(base::Value::Type::DICTIONARY);
  dummy_map->SetKey("test-name-1",
                    CreateDummyViolationDict("test-desc-1", 0, 99));
  dummy_map->SetKey("test-name-2",
                    CreateDummyViolationDict("test-desc-2", 1, 102));
  std::string json;
  base::JSONWriter::Write(*dummy_map, &json);
  starboard::ScopedFile file(watchdog_->GetWatchdogFilePath().c_str(),
                             kSbFileCreateAlways | kSbFileWrite);
  file.WriteAll(json.c_str(), static_cast<int>(json.size()));

  ASSERT_TRUE(watchdog_->Register("test-name-3", "test-desc-3",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  ASSERT_TRUE(watchdog_->Register("test-name-4", "test-desc-4",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);

  json = watchdog_->GetWatchdogViolations(false);
  ASSERT_NE(json, "");
  std::unique_ptr<base::Value> uncleared_violations_map =
      base::JSONReader::Read(json);
  ASSERT_NE(uncleared_violations_map, nullptr);
  base::Value* violation_dict =
      uncleared_violations_map->FindKey("test-name-1");
  base::Value* violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 99);
  violation_dict = uncleared_violations_map->FindKey("test-name-2");
  violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 99);
  ASSERT_EQ(violations->GetList()[0]
                .FindKey("timestampViolationMilliseconds")
                ->GetString(),
            "3");
  violation_dict = uncleared_violations_map->FindKey("test-name-3");
  violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 1);
  violation_dict = uncleared_violations_map->FindKey("test-name-4");
  violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 1);

  ASSERT_TRUE(watchdog_->Ping("test-name-3"));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);

  json = watchdog_->GetWatchdogViolations();
  ASSERT_NE(json, "");
  std::unique_ptr<base::Value> violations_map = base::JSONReader::Read(json);
  ASSERT_NE(violations_map, nullptr);
  violation_dict = violations_map->FindKey("test-name-1");
  violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 98);
  ASSERT_EQ(violations->GetList()[0]
                .FindKey("timestampViolationMilliseconds")
                ->GetString(),
            "1");
  violation_dict = violations_map->FindKey("test-name-2");
  violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 99);
  violation_dict = violations_map->FindKey("test-name-3");
  violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 2);
  violation_dict = violations_map->FindKey("test-name-4");
  violations = violation_dict->FindKey("violations");
  ASSERT_EQ(violations->GetList().size(), 1);

  ASSERT_TRUE(watchdog_->Unregister("test-name-3"));
  ASSERT_TRUE(watchdog_->Unregister("test-name-4"));
}

TEST_F(WatchdogTest, UpdateStateShouldPreventViolations) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  watchdog_->UpdateState(base::kApplicationStateBlurred);
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, TimeWaitShouldPreventViolations) {
  ASSERT_TRUE(watchdog_->Register(
      "test-name", "test-desc", base::kApplicationStateStarted,
      kWatchdogMonitorFrequency, kWatchdogMonitorFrequency * 3));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, PingsShouldPreventViolations) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  SbThreadSleep(kWatchdogMonitorFrequency / 2);
  ASSERT_TRUE(watchdog_->Ping("test-name"));
  SbThreadSleep(kWatchdogMonitorFrequency / 2);
  ASSERT_TRUE(watchdog_->Ping("test-name"));
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
  SbThreadSleep(kWatchdogMonitorFrequency / 2);
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 0, PING));
  SbThreadSleep(kWatchdogMonitorFrequency / 2);
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 0, PING));
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
  SbThreadSleep(kWatchdogMonitorFrequency / 2);
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 0, ALL));
  SbThreadSleep(kWatchdogMonitorFrequency / 2);
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency, 0, ALL));
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, UnregisterShouldPreventViolations) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
}

TEST_F(WatchdogTest, KillSwitchShouldPreventViolations) {
  TearDown();
  watchdog_ = new watchdog::Watchdog();
  watchdog_->InitializeStub();
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  ASSERT_EQ(watchdog_->GetWatchdogViolations(), "");
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
}

TEST_F(WatchdogTest, FrequentConsecutiveViolationsShouldNotWrite) {
  ASSERT_TRUE(watchdog_->Register("test-name", "test-desc",
                                  base::kApplicationStateStarted,
                                  kWatchdogMonitorFrequency));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  std::string write_json = "";
  starboard::ScopedFile read_file(watchdog_->GetWatchdogFilePath().c_str(),
                                  kSbFileOpenOnly | kSbFileRead);
  if (read_file.IsValid()) {
    int64_t kFileSize = read_file.GetSize();
    std::vector<char> buffer(kFileSize + 1, 0);
    read_file.ReadAll(buffer.data(), kFileSize);
    write_json = std::string(buffer.data());
  }
  ASSERT_NE(write_json, "");
  ASSERT_TRUE(watchdog_->Ping("test-name"));
  SbThreadSleep(kWatchdogMonitorFrequency * 2);
  ASSERT_TRUE(watchdog_->Unregister("test-name"));
  std::string no_write_json = "";
  starboard::ScopedFile read_file_again(
      watchdog_->GetWatchdogFilePath().c_str(), kSbFileOpenOnly | kSbFileRead);
  if (read_file_again.IsValid()) {
    int64_t kFileSize = read_file_again.GetSize();
    std::vector<char> buffer(kFileSize + 1, 0);
    read_file_again.ReadAll(buffer.data(), kFileSize);
    no_write_json = std::string(buffer.data());
  }
  ASSERT_NE(no_write_json, "");
  ASSERT_EQ(write_json, no_write_json);
  std::string json = watchdog_->GetWatchdogViolations();
  ASSERT_NE(write_json, json);
}

}  // namespace watchdog
}  // namespace cobalt


text:
#import <UIKit/UIKit.h>
#import "ANHeightViewController.h"

@interface ANWelcomeHeightMetricsViewController : ANHeightViewController

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace GoPague\Exceptions;

use Exception;

/**
 * Exception when a validation on GoPague objects occurs
 *
 * @see GoPagueExceptionInterface
 */
class ValidationException extends RequestException
{
}


text:
package com.amazonaws.services.transcribe.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteVocabularyFilterRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The name of the custom vocabulary filter you want to delete. Vocabulary filter names are case sensitive.
     *

     */
    private String vocabularyFilterName;

    /**
     *

     * The name of the custom vocabulary filter you want to delete. Vocabulary filter names are case sensitive.
     *

     *
     * @param vocabularyFilterName
     *        The name of the custom vocabulary filter you want to delete. Vocabulary filter names are case sensitive.
     */

    public void setVocabularyFilterName(String vocabularyFilterName) {
        this.vocabularyFilterName = vocabularyFilterName;
    }

    /**
     *

     * The name of the custom vocabulary filter you want to delete. Vocabulary filter names are case sensitive.
     *

     *
     * @return The name of the custom vocabulary filter you want to delete. Vocabulary filter names are case sensitive.
     */

    public String getVocabularyFilterName() {
        return this.vocabularyFilterName;
    }

    /**
     *

     * The name of the custom vocabulary filter you want to delete. Vocabulary filter names are case sensitive.
     *

     *
     * @param vocabularyFilterName
     *        The name of the custom vocabulary filter you want to delete. Vocabulary filter names are case sensitive.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DeleteVocabularyFilterRequest withVocabularyFilterName(String vocabularyFilterName) {
        setVocabularyFilterName(vocabularyFilterName);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getVocabularyFilterName() != null)
            sb.append("VocabularyFilterName: ").append(getVocabularyFilterName());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DeleteVocabularyFilterRequest == false)
            return false;
        DeleteVocabularyFilterRequest other = (DeleteVocabularyFilterRequest) obj;
        if (other.getVocabularyFilterName() == null ^ this.getVocabularyFilterName() == null)
            return false;
        if (other.getVocabularyFilterName() != null && other.getVocabularyFilterName().equals(this.getVocabularyFilterName()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getVocabularyFilterName() == null) ? 0 : getVocabularyFilterName().hashCode());
        return hashCode;
    }

    @Override
    public DeleteVocabularyFilterRequest clone() {
        return (DeleteVocabularyFilterRequest) super.clone();
    }

}


text:
package net.uchoice.exf.model.variable;

import java.lang.reflect.Type;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

public class VariableSpec {

	private String name;

	private VariableMode mode;

	private Class<?> type;

	private Type generateType;

	private int index;

	private boolean required;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public VariableMode getMode() {
		return mode;
	}

	public void setMode(VariableMode mode) {
		this.mode = mode;
	}

	public Class<?> getType() {
		return type;
	}

	public void setType(Class<?> type) {
		this.type = type;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public Type getGenerateType() {
		return generateType;
	}

	public void setGenerateType(Type generateType) {
		this.generateType = generateType;
	}

	public boolean isRequired() {
		return required;
	}

	public void setRequired(boolean required) {
		this.required = required;
	}

	public static VariableSpec of (VariableMode mode, String name, Class<?> type, int index, boolean isRequired) {
		VariableSpec variableSpec = new VariableSpec();
		variableSpec.setIndex(index);
		variableSpec.setMode(mode);
		variableSpec.setName(name);
		variableSpec.setType(type);
		variableSpec.setRequired(isRequired);
		return variableSpec;
	}

	public static VariableSpec of (VariableMode mode, String name, Class<?> type, int index) {
		return of(mode, name, type, index, false);
	}

	public String toString() {
		return ReflectionToStringBuilder.toString(this);
	}
}


text:
class TextBlockMigration {

  void concatenationWithMultipleNewLines() {
    String text = "This text should be on the same line as \\n this one<caret>\n" +
                  "foo\n" +
                  "bar\n";
  }
}


text:
#include "renderer.h"
#include "pass_raymarching.h"
#include "pass_fire.h"

#include <elements/rendering/effects/blur.h>

namespace eps {
namespace experiment {
namespace fire {

bool renderer::initialize()
{
    using namespace rendering;

    passes_.initialize(3);

    link_raymarching_ = passes_.add_pass<pass_raymarching>();
    if(link_raymarching_.expired())
        return false;

    link_blur_ = passes_.add_pass<effect::blur>();
    if(link_blur_.expired())
        return false;

    link_fire_ = passes_.add_pass<pass_fire>();
    if(link_fire_.expired())
        return false;

    passes_.add_dependency(link_blur_, link_raymarching_, pass_slot::slot_0);
    passes_.add_dependency(link_fire_, link_blur_, pass_slot::slot_0);

    return true;
}

bool renderer::construct(const math::uvec2 & size, size_t texture_size)
{
    texture_size = std::max(texture_size, (size_t)256);

    math::uvec2 size_reduction;
    if(size.y < size.x)
    {
        size_reduction.x = texture_size;
        size_reduction.y = texture_size * ((float)size.y / (float)size.x);
    }
    else
    {
        size_reduction.y = texture_size;
        size_reduction.x = texture_size * ((float)size.x / (float)size.y);
    }

    if(size_reduction_ != size_reduction)
    {
        size_reduction_ = size_reduction;

        const float scale = texture_size / 128.0f;
        if(auto link = link_blur_.lock())
            link->set_strong(0.15f * scale);

        passes_.construct(size_reduction);

        return true;
    }

    return false;
}

void renderer::render(float dt)
{
    passes_.process(dt);
}

bool renderer::set_background(const char * background)
{
    if(auto link = link_fire_.lock())
        return link->set_background(background);
    return false;
}

void renderer::set_intensity(float intensity)
{
    if(auto link = link_raymarching_.lock())
        link->set_intensity(intensity);
}

void renderer::set_covering(float covering)
{
    if(auto link = link_raymarching_.lock())
        link->set_covering(covering);
}

void renderer::set_color_hot(const math::vec3 & color)
{
    if(auto link = link_raymarching_.lock())
        link->set_color_hot(color);
}

void renderer::set_color_cold(const math::vec3 & color)
{
    if(auto link = link_raymarching_.lock())
        link->set_color_cold(color);
}

} /* fire */
} /* experiment */
} /* eps */


text:
<?php namespace Themes\Repositories;

use S36DataObject\S36DataObject, PDO, StdClass, Helpers, DB, S36Auth;

class DBThemes extends S36DataObject {

    private $table_name  = 'Themes';

	public function get_themes() {
		return DB::table($this->table_name)->get();
	}

	public function get_theme_by_name($name) {
		return DB::table($this->table_name)->where('theme_name', '=', $name)->first();
	}
}


text:
from default_arg_values import *

d = Display()

if d.draw1() != 0:
    raise RuntimeError

if d.draw1(12) != 12:
    raise RuntimeError

p = createPtr(123)
if d.draw2() != 0:
    raise RuntimeError

if d.draw2(p) != 123:
    raise RuntimeError

if d.bool0() != False or type(d.bool0()) != type(False):
    raise RuntimeError

if d.bool1() != True or type(d.bool1()) != type(True):
    raise RuntimeError

if d.mybool0() != False or type(d.mybool0()) != type(False):
    raise RuntimeError

if d.mybool1() != True or type(d.mybool1()) != type(True):
    raise RuntimeError


text:
enum ETypeNames {
	ITEM = 'item()',
	XSANYSIMPLETYPE = 'xs:anySimpleType',
	XSANYATOMICTYPE = 'xs:anyAtomicType',
	XSUNTYPEDATOMIC = 'xs:untypedAtomic',
	XSSTRING = 'xs:string',
	XSBOOLEAN = 'xs:boolean',
	XSDECIMAL = 'xs:decimal',
	XSFLOAT = 'xs:float',
	XSDOUBLE = 'xs:double',
	XSDURATION = 'xs:duration',
	XSDATETIME = 'xs:dateTime',
	XSTIME = 'xs:time',
	XSDATE = 'xs:date',
	XSGYEARMONTH = 'xs:gYearMonth',
	XSGYEAR = 'xs:gYear',
	XSGMONTHDAY = 'xs:gMonthDay',
	XSGDAY = 'xs:gDay',
	XSGMONTH = 'xs:gMonth',
	XSHEXBINARY = 'xs:hexBinary',
	XSBASE64BINARY = 'xs:base64Binary',
	XSANYURI = 'xs:anyURI',
	XSQNAME = 'xs:QName',
	XSNOTATION = 'xs:NOTATION',
	XSNORMALIZEDSTRING = 'xs:normalizedString',
	XSTOKEN = 'xs:token',
	XSLANGUAGE = 'xs:language',
	XSNMTOKEN = 'xs:NMTOKEN',
	XSNMTOKENS = 'xs:NMTOKENS',
	XSNAME = 'xs:Name',
	XSNCNAME = 'xs:NCName',
	XSID = 'xs:ID',
	XSIDREF = 'xs:IDREF',
	XSIDREFS = 'xs:IDREFS',
	XSENTITY = 'xs:ENTITY',
	XSENTITIES = 'xs:ENTITIES',
	XSINTEGER = 'xs:integer',
	XSNONPOSITIVEINTEGER = 'xs:nonPositiveInteger',
	XSNEGATIVEINTEGER = 'xs:negativeInteger',
	XSLONG = 'xs:long',
	XSINT = 'xs:int',
	XSSHORT = 'xs:short',
	XSBYTE = 'xs:byte',
	XSNONNEGATIVEINTEGER = 'xs:nonNegativeInteger',
	XSUNSIGNEDLONG = 'xs:unsignedLong',
	XSUNSIGNEDINT = 'xs:unsignedInt',
	XSUNSIGNEDSHORT = 'xs:unsignedShort',
	XSUNSIGNEDBYTE = 'xs:unsignedByte',
	XSPOSITIVEINTEGER = 'xs:positiveInteger',
	XSYEARMONTHDURATION = 'xs:yearMonthDuration',
	XSDAYTIMEDURATION = 'xs:dayTimeDuration',
	FUNCTION = 'function(*)',
	MAP = 'MAP(*)',
	ARRAY = 'array(*)',
	NODE = 'node()',
	ELEMENT = 'element()',
	COMMENT = 'comment()',
	ATTRIBUTE = 'attribute()',
	PROCESSINGINSTRUCTION = 'processing-instruction()',
	DOCUMENT = 'document-node()',
	XSNUMERIC = 'xs:numeric',
	NONE = 'none',
}

export default ETypeNames;


text:
<?php

namespace Flarum\Forum\Auth;

use Flarum\Http\Rememberer;
use Flarum\User\LoginProvider;
use Flarum\User\RegistrationToken;
use Flarum\User\User;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response\HtmlResponse;

class ResponseFactory
{
    /**
     * @var Rememberer
     */
    protected $rememberer;

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

    public function make(string $provider, string $identifier, callable $configureRegistration): ResponseInterface
    {
        if ($user = LoginProvider::logIn($provider, $identifier)) {
            return $this->makeLoggedInResponse($user);
        }

        $configureRegistration($registration = new Registration);

        $provided = $registration->getProvided();

        if (! empty($provided['email']) && $user = User::where(array_only($provided, 'email'))->first()) {
            $user->loginProviders()->create(compact('provider', 'identifier'));

            return $this->makeLoggedInResponse($user);
        }

        $token = RegistrationToken::generate($provider, $identifier, $provided, $registration->getPayload());
        $token->save();

        return $this->makeResponse(array_merge(
            $provided,
            $registration->getSuggested(),
            [
                'token' => $token->id,
                'provided' => array_keys($provided)
            ]
        ));
    }

    private function makeResponse(array $payload): HtmlResponse
    {
        $content = sprintf(
            '<script>window.close(); window.opener.app.authenticationComplete(%s);</script>',
            json_encode($payload)
        );

        return new HtmlResponse($content);
    }

    private function makeLoggedInResponse(User $user)
    {
        $response = $this->makeResponse(['loggedIn' => true]);

        return $this->rememberer->rememberUser($response, $user->id);
    }
}


text:
<?php

namespace Metro\Clock;

class Moment
{
    private $timestamp;

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

    /** @return float */
    public function timestamp()
    {
        return $this->timestamp;
    }

    /** @return string */
    public function iso()
    {
        list($integral, $fractional) = explode('.', strval($this->timestamp), 2);

        $dt = new \DateTime();
        $dt->setTimestamp($integral);
        $dt->setTimezone(new \DateTimeZone('UTC'));

        return sprintf(
            "%s.%d+0000",
            $dt->format('Y-m-d\TH:i:s'),
            str_pad($fractional, 6, '0')
        );
    }

    public function __toString()
    {
        return $this->iso();
    }
}


text:
package org.apache.directory.server.ssl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.security.cert.X509Certificate;
import java.util.Hashtable;

import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;

import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.util.Strings;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.annotations.SaslMechanism;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.apache.directory.server.core.security.TlsKeyGenerator;
import org.apache.directory.server.ldap.handlers.extended.StoredProcedureExtendedOperationHandler;
import org.apache.directory.server.ldap.handlers.sasl.cramMD5.CramMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.digestMD5.DigestMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.gssapi.GssapiMechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.ntlm.NtlmMechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.plain.PlainMechanismHandler;
import org.apache.directory.server.operations.bind.BogusNtlmProvider;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * Test case to verify DIREVE-216.  Starts up the server binds via SUN JNDI provider
 * to perform add modify operations on entries.
 *
 * @author Apache Directory Project
 */
@RunWith(FrameworkRunner.class)
@CreateDS(allowAnonAccess = true, name = "LdapsUpdateCertificateIT-class")
@CreateLdapServer(
    transports =
        {
            @CreateTransport(protocol = "LDAP"),
            @CreateTransport(protocol = "LDAPS")
    },
    saslHost = "localhost",
    saslMechanisms =
        {
            @SaslMechanism(name = SupportedSaslMechanisms.PLAIN, implClass = PlainMechanismHandler.class),
            @SaslMechanism(name = SupportedSaslMechanisms.CRAM_MD5, implClass = CramMd5MechanismHandler.class),
            @SaslMechanism(name = SupportedSaslMechanisms.DIGEST_MD5, implClass = DigestMd5MechanismHandler.class),
            @SaslMechanism(name = SupportedSaslMechanisms.GSSAPI, implClass = GssapiMechanismHandler.class),
            @SaslMechanism(name = SupportedSaslMechanisms.NTLM, implClass = NtlmMechanismHandler.class),
            @SaslMechanism(name = SupportedSaslMechanisms.GSS_SPNEGO, implClass = NtlmMechanismHandler.class)
    },
    extendedOpHandlers =
        {
            StoredProcedureExtendedOperationHandler.class
    },
    ntlmProvider = BogusNtlmProvider.class)
public class LdapsUpdateCertificateIT extends AbstractLdapTestUnit
{
    /**
     * Create an entry for a person.
     */
    public DirContext getSecureConnection() throws Exception
    {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put( "java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory" );
        env.put( "java.naming.provider.url", "ldap://localhost:" + getLdapServer().getPortSSL() + "/ou=system" );
        env.put( "java.naming.ldap.factory.socket", SSLSocketFactory.class.getName() );
        env.put( "java.naming.security.principal", "uid=admin,ou=system" );
        env.put( "java.naming.security.credentials", "secret" );
        env.put( "java.naming.security.authentication", "simple" );
        return new InitialDirContext( env );
    }

    /**
     * Test for DIRSERVER-1373.
     */
    @Test
    public void testUpdateCertificate() throws Exception
    {
        // create a secure connection
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put( "java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory" );
        env.put( "java.naming.provider.url", "ldaps://localhost:" + getLdapServer().getPortSSL() );
        env.put( "java.naming.ldap.factory.socket", SSLSocketFactory.class.getName() );
        env.put( "java.naming.security.principal", "uid=admin,ou=system" );
        env.put( "java.naming.security.credentials", "secret" );
        env.put( "java.naming.security.authentication", "simple" );
        InitialDirContext ctx = new InitialDirContext( env );

        // create a new certificate
        String newIssuerDN = "cn=new_issuer_dn";
        String newSubjectDN = "cn=new_subject_dn";
        Entry entry = getLdapServer().getDirectoryService().getAdminSession().lookup(
            new Dn( "uid=admin,ou=system" ) );
        TlsKeyGenerator.addKeyPair( entry, newIssuerDN, newSubjectDN, "RSA" );

        // now update the certificate (over the wire)
        ModificationItem[] mods = new ModificationItem[3];
        mods[0] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
            TlsKeyGenerator.PRIVATE_KEY_AT, entry.get( TlsKeyGenerator.PRIVATE_KEY_AT ).getBytes() ) );
        mods[1] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
            TlsKeyGenerator.PUBLIC_KEY_AT, entry.get( TlsKeyGenerator.PUBLIC_KEY_AT ).getBytes() ) );
        mods[2] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
            TlsKeyGenerator.USER_CERTIFICATE_AT, entry.get( TlsKeyGenerator.USER_CERTIFICATE_AT ).getBytes() ) );
        ctx.modifyAttributes( "uid=admin,ou=system", mods );
        ctx.close();

        getLdapServer().reloadSslContext();

        // create a secure connection
        ctx = new InitialDirContext( env );

        // check the received certificate, it must contain the updated server certificate
        X509Certificate[] lastReceivedServerCertificates = BogusTrustManagerFactory.lastReceivedServerCertificates;
        assertNotNull( lastReceivedServerCertificates );
        assertEquals( 1, lastReceivedServerCertificates.length );
        String issuerDN = lastReceivedServerCertificates[0].getIssuerDN().getName();
        String subjectDN = lastReceivedServerCertificates[0].getSubjectDN().getName();
        // converting the values to lowercase is required cause the certificate is
        // having attribute names in capital letters e.c the above newIssuerDN will be present as CN=new_issuer_dn
        assertEquals( "Expected the new certificate with the new issuer",
            Strings.toLowerCase( newIssuerDN ), Strings.toLowerCase( issuerDN ) );
        assertEquals( "Expected the new certificate with the new subject",
            Strings.toLowerCase( newSubjectDN ), Strings.toLowerCase( subjectDN ) );
    }

}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "services/service_manager/background_service_manager.h"

#include <memory>
#include <vector>

#include "base/bind.h"
#include "base/no_destructor.h"
#include "base/run_loop.h"
#include "base/test/task_environment.h"
#include "base/values.h"
#include "build/build_config.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/constants.h"
#include "services/service_manager/public/cpp/manifest.h"
#include "services/service_manager/public/cpp/manifest_builder.h"
#include "services/service_manager/public/cpp/service.h"
#include "services/service_manager/public/cpp/service_receiver.h"
#include "services/service_manager/tests/background.test-mojom.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace service_manager {
namespace {

const char kTestName[] = "background_service_manager_unittest";
const char kAppName[] = "background_service_manager_test_service";

const char kTestServiceCapability[] = "test_service";

const std::vector<Manifest>& GetTestManifests() {
  static base::NoDestructor<std::vector<Manifest>> manifests{
      {ManifestBuilder()
           .WithServiceName(kTestName)
           .RequireCapability(kAppName, kTestServiceCapability)
           .Build(),
       service_manager::ManifestBuilder()
           .WithServiceName(kAppName)
           .WithOptions(ManifestOptionsBuilder()
                            .WithExecutionMode(
                                Manifest::ExecutionMode::kStandaloneExecutable)
                            .WithSandboxType("none")
                            .Build())
           .ExposeCapability(kTestServiceCapability,
                             Manifest::InterfaceList<mojom::TestService>())
           .Build()}};
  return *manifests;
}

// The parent unit test suite service, not the underlying test service.
class ServiceImpl : public Service {
 public:
  explicit ServiceImpl(mojo::PendingReceiver<mojom::Service> receiver)
      : receiver_(this, std::move(receiver)) {}

  ServiceImpl(const ServiceImpl&) = delete;
  ServiceImpl& operator=(const ServiceImpl&) = delete;

  ~ServiceImpl() override = default;

  Connector* connector() { return receiver_.GetConnector(); }

 private:
  ServiceReceiver receiver_;
};

void SetFlagAndRunClosure(bool* flag, base::OnceClosure closure) {
  *flag = true;
  std::move(closure).Run();
}

// Uses BackgroundServiceManager to start the service manager in the background
// and connects to background_service_manager_test_service, verifying we can
// send a message to the service.
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/589784): This test is disabled, as it fails
// on the Android GN bot.
#define MAYBE_Basic DISABLED_Basic
#else
#define MAYBE_Basic Basic
#endif
TEST(BackgroundServiceManagerTest, MAYBE_Basic) {
  base::test::TaskEnvironment task_environment;
  BackgroundServiceManager background_service_manager(GetTestManifests());
  mojo::PendingRemote<mojom::Service> service_remote;
  ServiceImpl service_impl(service_remote.InitWithNewPipeAndPassReceiver());
  background_service_manager.RegisterService(
      Identity(kTestName, kSystemInstanceGroup, base::Token{},
               base::Token::CreateRandom()),
      std::move(service_remote), mojo::NullReceiver() /* metadata_receiver */);

  mojo::Remote<mojom::TestService> test_service;
  service_impl.connector()->Connect(ServiceFilter::ByName(kAppName),
                                    test_service.BindNewPipeAndPassReceiver());
  base::RunLoop run_loop;
  bool got_result = false;
  test_service->Test(base::BindOnce(&SetFlagAndRunClosure, &got_result,
                                    run_loop.QuitClosure()));
  run_loop.Run();
  EXPECT_TRUE(got_result);
}

}  // namespace
}  // namespace service_manager


text:
"""
Note that sometimes you will get duplicate signals emitted, depending on configuration of your systems.
If you do encounter this, you will need to add the "dispatch_uid" to your connect handlers:
http://code.djangoproject.com/wiki/Signals#Helppost_saveseemstobeemittedtwiceforeachsave

"""
from __future__ import unicode_literals

from django.dispatch import Signal

# Sent when a validated, non-duplicated IPN is received.
valid_ipn_received = Signal()

# Sent when a flagged IPN (e.g. duplicate, invalid) is received.
invalid_ipn_received = Signal()


text:
module TranslatorSrt
  module GoogleTranslate
    class ResultParser
      def initialize(result)
        @result = result
      end

      def to_s
        normalize_translation

        @result.join
      end

      private

      def normalize_translation
        to_one_ar

        list_keys = {
            "-->" => ["###"],
            "," => [" ## ", "##"],
            ":" => [" # ", "#"],
        }

        list_keys.each do |key_group, group|
          group.each do |key|
            @result.each_index do |index_translation|
              @result[index_translation] = @result[index_translation].gsub key, key_group
            end

          end
        end
      end

      def to_one_ar
        permit_translation

        result_in_one_array = []
        @result.each do |item|
          result_in_one_array.append item.first
        end

        @result = result_in_one_array
      end

      def permit_translation
        @result = @result.first
      end
    end
  end
end


text:
var mkdirp = require('mkdirp');
var path = require('path');
var ncp = require('ncp');

// Package name
var package = "TEMPLATE";

// Paths
var src = path.join(__dirname, '..', 'Assets', 'FullSerializer', 'Source');
var dir = path.join(__dirname, '..', '..', '..', 'Assets', 'packages', 'fullserializer');

// Create folder if missing
mkdirp(dir, function (err) {
  if (err) {
    console.error(err)
    process.exit(1);
  }

  // Copy files
  ncp(src, dir, function (err) {
    if (err) {
      console.error(err);
      process.exit(1);
    }
  });
});


text:
<?php

namespace Infogold\KonsultantBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Infogold\AccountBundle\Entity\Produkt;
use Infogold\AccountBundle\Form\ProduktyType;

class ProduktController extends Controller
{
    /**
     * Lists all Produkty entities.
     *
     */
    public function indexAction(Request $request) {

        $loggedUser = $this->get('security.context')->getToken()->getUser();
        $userId = $loggedUser->getFirma()->getId();

        $em = $this->getDoctrine()->getManager();

  $form = $this->createFormBuilder()
                ->add('szukaj', 'text', array('required' => true))
                ->add('wedlug', 'choice', array(
                    'choices' => array(
                        'nazwaproduktu' => 'nazwa produktu',
                        'nrproduktu' => 'nr produktu',
                        'ceny' => 'cena od',
                        'wmagazyniedo' => 'w magazynie do'
                    ),
                    'multiple' => false,
                ))
                ->getForm();

        $entities = $em->getRepository('InfogoldAccountBundle:Produkt')->findBy(
                array('userproduktu' => $userId), array('nrproduktu' => 'ASC'), 30
        );

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $entities, $request->query->get('page', 1)/* page number */, 2 /* limit per page */);
        return $this->render('InfogoldKonsultantBundle:Produkty:index.html.twig', array(
                    'pagination' => $pagination,
                    'form' => $form->createView()
        ));
    }

    public function showAction($id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('InfogoldAccountBundle:Produkt')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Produkty entity.');
        }

        $em2 = $this->getDoctrine()->getManager();

        $request = $em2->getRepository('InfogoldAccountBundle:Produkt');

        $qb = $request->createQueryBuilder('p');
        $query2 = $qb
                ->select('p.id, c.id, c.imie, c.nazwisko, c.peselklienta, c.nazwaklienta, c.nipklienta, c.miasto, c.ulica, d.cenaProduktu, d.created, d.ilosc ')
                ->leftJoin('p.produkt', 'd')
                ->leftJoin('d.ProduktyKlienta', 'c')
                ->where('p.id=' . $id)
                ->getQuery();

        $entities2 = $query2->getResult();

        return $this->render('InfogoldKonsultantBundle:Produkty:show.html.twig', array(
                    'entity' => $entity,
                    'klienci' => $entities2,
                   ));
    }

}


text:
package de.ailis.wlandsuite.fnt;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * A Fnt object contains the font characters of Wastelands fnt file.
 *
 * @author Klaus Reimer (k@ailis.de)
 * @version $Revision$
 */

public class Fnt implements Serializable
{
    /** Serial version UID */
    private static final long serialVersionUID = 3848735175735435359L;

    /** The cursors */
    private final List<FntChar> chars;

    /**
     * Private constructor
     */

    private Fnt()
    {
        this.chars = new ArrayList<FntChar>();
    }

    /**
     * Constructor for building a new fnt object.
     *
     * @param chars
     *            The chars
     */

    public Fnt(final List<FntChar> chars)
    {
        this.chars = chars;
    }

    /**
     * Calculates and returns the number of font characters for the given file
     * size.
     *
     * @param size
     *            The file size
     * @return The number of characters
     */

    public static int getQuantity(final long size)
    {
        return (int) (size / (4 * 8));
    }

    /**
     * Loads font characters from a stream. A quantity of 172 characters is
     * assumed.
     *
     * @param stream
     *            The input stream
     * @return The fnt
     * @throws IOException
     *             When file operation fails.
     */

    public static Fnt read(final InputStream stream) throws IOException
    {
        return read(stream, 172);
    }

    /**
     * Loads font characters from a stream.
     *
     * @param stream
     *            The input stream
     * @param quantity
     *            The number of characters
     * @return The fnt
     * @throws IOException
     *             When file operation fails.
     */

    public static Fnt read(final InputStream stream, final int quantity) throws IOException
    {
        Fnt fnt;

        // Create the Fnt
        fnt = new Fnt();

        // Read the font characters
        for (int i = 0; i < quantity; i++)
        {
            fnt.chars.add(FntChar.read(stream));
        }

        // Return the fnt
        return fnt;
    }

    /**
     * Writes font characters to a stream.
     *
     * @param stream
     *            The output stream
     * @throws IOException
     *             When file operation fails.
     */

    public void write(final OutputStream stream) throws IOException
    {
        // Read the cursors
        for (final FntChar fntChar: this.chars)
        {
            fntChar.write(stream);
        }
    }

    /**
     * Returns the font characters
     *
     * @return The font characters
     */

    public List<FntChar> getChars()
    {
        return this.chars;
    }
}


text:
'use strict'
const Code = require('code')
const Lab = require('lab')

const lab = exports.lab = Lab.script()
const Parser = require('../../../lib/parser.js')
const samples = require('../../fixtures/samples.js')

const describe = lab.describe
const expect = Code.expect
const it = lab.it

describe('parser.js unit test', () => {
  describe('generateConfig', () => {
    it('should return kubernetes config from docker inspect with ports', (done) => {
      const parser = new Parser(samples.inspectExternalPorts())
      const out = parser.getJsonConfigs()
      expect(out).to.equal(samples.configExternalPorts())
      done()
    })

    it('should return kubernetes using image as name', (done) => {
      const parser = new Parser(samples.inspectExternalPorts(), {
        useImageAsName: true
      })
      const out = parser.getJsonConfigs()
      expect(out.deployments['rabbitmq-3-management']).to.exist()
      expect(out.deployments['rabbitmq-3-management'].metadata.name).to.equal('rabbitmq-3-management')
      expect(out.deployments['rabbitmq-3-management'].spec.template.metadata.labels.app).to.equal('rabbitmq-3-management')
      expect(out.deployments['rabbitmq-3-management'].spec.template.spec.containers[0].name).to.equal('rabbitmq-3-management')

      expect(out.services['rabbitmq-3-management']).to.exist()
      expect(out.services['rabbitmq-3-management'].metadata.name).to.equal('rabbitmq-3-management')
      expect(out.services['rabbitmq-3-management'].spec.selector.app).to.equal('rabbitmq-3-management')
      done()
    })

    it('should return kubernetes config from docker inspect with mounts and ignore', (done) => {
      const inspectMount = samples.inspectMounts()
      inspectMount.Mounts.push({
        'Destination': '/docker/app-logs',
        'Mode': 'rw',
        'RW': true,
        'Source': '/docker/app-logs',
        'Propagation': 'rprivate'
      })
      const parser = new Parser(inspectMount, {
        removeMounts: 'logs'
      })
      const out = parser.getJsonConfigs()

      expect(out).to.equal(samples.configMounts())
      done()
    })

    it('should return proper mounts if rootPath is passed', (done) => {
      const inspectMount = samples.inspectMounts()
      inspectMount.Mounts = inspectMount.Mounts.map((mount) => {
        mount.Source = mount.Source.replace(samples.fixturesPath, '')
        return mount
      })
      const parser = new Parser(inspectMount, {
        rootPath: samples.fixturesPath
      })
      const out = parser.getJsonConfigs()
      expect(out).to.equal(samples.configMounts())
      done()
    })
  }) // end generateConfig
})


text:
using System.Runtime.Serialization;

namespace Chiro.Kip.ServiceContracts.DataContracts
{
    /// <summary>
    /// Relevante informatie voor het maken of bijwerken van een membership.
    /// </summary>
    [DataContract]
    public class MembershipGedoe
    {
        /// <summary>
        /// Stamnummer van de groep die het membership aanvraagt.
        /// </summary>
        [DataMember]
        public string StamNummer { get; set; }
        /// <summary>
        /// Moet er meteen een verzekering loonverlies bij?
        /// </summary>
        [DataMember]
        public bool MetLoonVerlies { get; set; }
        /// <summary>
        /// Gaat het om een gratis membership? (Typisch voor kaderploegen.)
        /// </summary>
        [DataMember]
        public bool Gratis { get; set; }
    }
}


text:
class CreateJoinTableAreaZone < ActiveRecord::Migration
  def change
    create_join_table :areas, :zones do |t|
      t.index [:area_id, :zone_id]
      t.index [:zone_id, :area_id]
    end
  end
end


text:
********************************************************************************
	Project owner:		RageQuit community
	Project name: 		GTW-RPG
	Developers:   		Mr_Moose

	Source code:		https://github.com/GTWCode/GTW-RPG/
	Bugtracker: 		http://forum.404rq.com/bug-reports/
	Suggestions:		http://forum.404rq.com/mta-servers-development/

	Version:    		Open source
	License:    		BSD 2-Clause
	Status:     		Stable release
********************************************************************************
]]--

wanted_data = {
	wanted_level 	= { },
	violent_time	= { },
	reduce_timers 	= { },
	fine_charge	= { },
}

--[[ Load system data ]]--
function load_system( )
	for k,v in pairs(getElementsByType("player")) do
		-- Restore wanted level and reduce timers
		if (tonumber(getElementData(v, "Wanted")) or 0) < 0 then setElementData(v, "Wanted", 0) end
		setWl(v, (tonumber(getElementData(v, "Wanted")) or 0), (tonumber(getElementData(v, "violent_seconds")) or 0))
	end
end
addEventHandler("onResourceStart", resourceRoot, load_system)

--[[ Make sure the graphical hud and scoreboards are up to date ]]--
function update_graphical(plr)
	if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end
	local wanted_lvl = (wanted_data.wanted_level[plr] or 0)

	-- Update graphical wanted level
	setElementData(plr, "Wanted", wanted_lvl)
	if wanted_lvl <= 0 then
		setElementData(plr, "Wanted", nil)
	end

	-- Pass violent time to client
	if (wanted_data.violent_time[plr] or 0) > 0 then
		setElementData(plr, "violent_seconds", (wanted_data.violent_time[plr] or nil))
	else
		setElementData(plr, "violent_seconds", nil)
	end

	-- Sync the amount of stars seen on screen
	if wanted_lvl > 0 and wanted_lvl <= 1 then
		setPlayerWantedLevel(plr, 1)
	elseif wanted_lvl > 1 and wanted_lvl <= 6 then
		setPlayerWantedLevel(plr, math.floor(wanted_lvl))
	elseif wanted_lvl > 6 then
		setPlayerWantedLevel(plr, 6)
	else
		setPlayerWantedLevel(plr, 0)
	end
end

--[[ Reduce a players wanted level ]]--
function reduce_wl(crim)
	-- Check if everything is represented
	if not crim or not isElement(crim) or getElementType(crim) ~= "player" then return end

	-- Check if arrested, if so, don't reduce or increase
	local is_arrested = exports.GTWpolice:isArrested(crim)
	if is_arrested then return end

	-- Check if jailed, if so, don't reduce or increase
	local is_jailed = exports.GTWjail:isJailed(crim)
	if is_jailed then return end

	-- Check if it's time to interrupt
	if non_violent(crim) then return end

	-- Setup default reduce margins
	local wl_reduce,viol_reduce = 0.02,1

	-- Justify reducement depending on distance to cop
	-- NOTE Remember to check "alternate_hud" when changing these values
	local dist = exports.GTWpolice:distanceToCop(crim)
	if dist > 3000 and not is_law_unit(crim) then wl_reduce = 0.04 end
	if dist > 2000 and not is_law_unit(crim) then wl_reduce = 0.03 end
	if dist < 1000 and not is_law_unit(crim) then wl_reduce = 0.01 end
	if dist < 500 and not is_law_unit(crim) then wl_reduce = 0.005 end
	if dist < 180 and not is_law_unit(crim) then wl_reduce = 0 end
	if dist < 90 and not is_law_unit(crim) then wl_reduce = -0.001 end

	-- Set the team to criminal
	if getPlayerTeam(crim) and getPlayerTeam(crim) ~= getTeamFromName("Criminals") and wanted_data.wanted_level[crim] > 1 then
		setPlayerTeam(crim, getTeamFromName("Criminals"))
		setPlayerNametagColor(crim, 170, 0, 0)
		setElementData(crim, "Occupation", "Criminal")
		local own_skin = exports.GTWclothes:getBoughtSkin(crim) or getElementModel(crim) or 0
		setElementModel(crim, own_skin)
		exports.GTWtopbar:dm("You are now a criminal due to your wanted level", crim, 255, 100, 0 )
	end

	-- Reduce wantedlevel by 0.1 stars
	if wanted_data.violent_time[crim] <= 0 then
		wanted_data.wanted_level[crim] = round(wanted_data.wanted_level[crim] - wl_reduce, 3)
	elseif wanted_data.violent_time[crim] > 0 then
		wanted_data.violent_time[crim] = math.floor(wanted_data.violent_time[crim] - viol_reduce)
	else
		wanted_data.wanted_level[crim] = nil
		wanted_data.violent_time[crim] = nil
	end

	-- Update graphical data
	update_graphical(crim)
end

--[[ Round numeric values ]]--
function round(number, digits)
  	local mult = 10^(digits or 0)
  	return math.floor(number * mult + 0.5) / mult
end

--[[ Set violent time to nil to indicate a player is non violent ]]--
function non_violent(plr)
	if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end

	-- Check if it's time to go unwanted
	if wanted_data.wanted_level[plr] <= 0 and isTimer(wanted_data.reduce_timers[plr]) then
		killTimer(wanted_data.reduce_timers[plr])
		wanted_data.wanted_level[plr] = nil
		return true
	end
end

--[[ Set player wanted level ]]--
function setWl(plr, level, violent_time, reason, add_to, reduce_health)
	if not plr or not isElement(plr) or getElementType(plr) ~= "player" or not level then return end
	if not add_to then add_to = true end
	if not reduce_health then reduce_health = false end

	-- Don't set wanted level if crime is comitted in jail
	local is_jailed = exports.GTWjail:isJailed(plr)
	if is_jailed and add_to then return end

	if is_law_unit(plr) then level = (level/10) end
	if is_law_unit(plr) then violent_time = (violent_time/10) end

	-- If the crime was in a vehicle collision, reduce health
	if reduce_health and getPedOccupiedVehicle(plr) then
                local loss = level/(getVehicleHandling(getPedOccupiedVehicle(plr)).mass * 0.00001)
		local driver = getVehicleOccupant(getPedOccupiedVehicle(plr), 0)
		for k,v in pairs(getVehicleOccupants(getPedOccupiedVehicle(plr))) do
			local new_health = getElementHealth(v) - loss
			if new_health > 0 then
				setElementHealth(v, new_health)
			else
				killPed(v)
			end
		end

		-- Cancel if suspect isn't the driver
		if driver ~= plr then return end
	end

	-- Set default value to violent time if not present
	if not violent_time then violent_time = 0 end

	-- Start reduce timer if not running
	if not isTimer(wanted_data.reduce_timers[plr]) then
		wanted_data.reduce_timers[plr] = setTimer(reduce_wl, 1000, 0, plr)
	end

	-- Update wanted level and violent time
	local p_level = (wanted_data.wanted_level[plr] or 0)
	local p_viol_time = (wanted_data.violent_time[plr] or 0)
	if p_level < 0 then p_level = 0 end
	if add_to then
		wanted_data.wanted_level[plr] = p_level + level
		wanted_data.violent_time[plr] = p_viol_time + violent_time
	else
		wanted_data.wanted_level[plr] = level
		wanted_data.violent_time[plr] = violent_time
	end

	-- Wanted points for criminals
	local pAcc = getPlayerAccount(plr)
	local wp_stat = getAccountData( pAcc, "acorp_stats_wanted_points" ) or 0
	setAccountData(pAcc, "acorp_stats_wanted_points", wp_stat+level)

	-- Display the reason for the player
	if reason and reason ~= "" then
		exports.GTWtopbar:dm(reason.." ("..round(level, 2).." stars)", plr, 200, 0, 0)
	end

	-- If argument was 0 (fine)
	if level == 0 and violent_time == 0 then
		if isTimer(wanted_data.reduce_timers[plr]) then
			killTimer(wanted_data.reduce_timers[plr])
		end
		wanted_data.wanted_level[plr] = nil
		wanted_data.violent_time[plr] = nil
	end

	-- Update graphical data
	update_graphical(plr)
end

function setServerWantedLevel(wl, violent_time, reason, require_nearby_cop, reduce_health)
	-- A value indicating if the crime require a cop to be nearby
	if require_nearby_cop then
		local dist = exports.GTWpolice:distanceToCop(client)
		if dist > 180 then return end
	end

	-- Set the wanted level
	setWl(client, wl, violent_time, reason, true, reduce_health)
end
addEvent("GTWwanted.serverSetWl", true)
addEventHandler("GTWwanted.serverSetWl", root, setServerWantedLevel)

--[[ Get player wanted level ]]--
function getWl(plr)
	if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return 0,0 end

	-- Return all player wanted level data
	return (wanted_data.wanted_level[plr] or 0), (wanted_data.violent_time[plr] or 0)
end

--[[ Check if a player is on the law side ]]--
function is_law_unit(plr)
	if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end
	local law_teams = {
		["Government"]=true,
		["Staff"]=true,
	}
	if getPlayerTeam(plr) and law_teams[getTeamName(getPlayerTeam( plr ))] then
		return true
	else
		return false
	end
end

--[[ Crime of damage other players ]]--
function crime_damage(attacker, attackerweapon, bodypart, loss)
	if not attacker or not isElement(attacker) or getElementType(attacker) ~= "player" or attacker == source then return end
	local wl,viol = getWl(source)
	local is_jailed = exports.GTWjail:isJailed(source)
	if is_law_unit(attacker) and (wl > 0 or getElementType(source) == "ped" or is_jailed) then return end
	setWl(attacker, round((loss/150), 2), 5)
end
addEventHandler( "onPlayerDamage", root, crime_damage )

--[[ Crime of killing other players ]]--
function crime_death(totalAmmo, killer, killerWeapon, bodypart, stealth)
	if not killer or not isElement(killer) or getElementType(killer) ~= "player" or killer == source then return end
	local wl,viol = getWl(source)
	local is_jailed = exports.GTWjail:isJailed(source)

	-- Law units will not get wanted for killing players with wanted level or that are jailed
    	if is_law_unit(killer) and (wl > 1 or is_jailed) then return end
	local add_wl = 2.0
	if getElementType(source) == "ped" then
		add_wl = 1.0   -- Reduced by 1.0 for bots
	end
	setWl(killer, round(add_wl, 2), 50)
end
addEventHandler("onPedWasted", root, crime_death)
addEventHandler("onPlayerWasted", root, crime_death)

function crime_grand_theft_auto_attempt(plr, seat, jacked)
    if not jacked or seat > 0  then return end
    if is_law_unit(plr) then return end
    setWl(plr, 0.2, 5, "You committed the crime of grand theft auto (attempt)")
end
addEventHandler("onVehicleStartEnter", root, crime_grand_theft_auto_attempt)
function crime_grand_theft_auto(plr, seat, jacked)
    if not jacked or seat > 0 then return end
    if is_law_unit(plr) then return end
    setWl(plr, 1.0, 10, "You committed the crime of grand theft auto")
end
addEventHandler("onVehicleEnter", root, crime_grand_theft_auto)

function reduce_functionality(loss)

end
addEventHandler("onVehicleDamage", root, reduce_functionality)

function checkSpeeding( )
	-- Get the target
	local target = getPedTarget( client )
	local speedx, speedy, speedz = getElementVelocity( target )
	local actualspeed = (speedx^2 + speedy^2 + speedz^2)^(0.5)
	local kmh = actualspeed * 180

	-- Perform a check
	if not isElement( target ) then return end
	local speeder = getVehicleOccupants(target)[0]
	if not speeder or (speeder and is_law_unit(speeder)) then return end

	-- Tell the speeder
	local n_wl = round((kmh*1.3/400),2)
	setWl(speeder, round(n_wl, 2), 0, "You committed the crime of speeding")

	-- Pay the cop for the catch
	local money = math.floor(kmh*1.3)
	exports.GTWtopbar:dm("You have catched: "..getPlayerName(speeder).." for speeding and earned: $"..tostring(money), client, 0, 255, 0 )
	givePlayerMoney(client, money)
end
addEvent("GTWwanted.onSpeeding", true)
addEventHandler("GTWwanted.onSpeeding", root, checkSpeeding)

--[[ Display wanted level (DEBUG) ]]--
function show_wl(plr)
	local x,y = getWl(plr)
	outputChatBox("WL: "..(x or 0)..", Violent: "..(y or 0), plr, 255, 100, 0)
end
addCommandHandler("wl", show_wl)

--[[ Display wanted players ]]--
function show_wanted_players(plr)
	local c = 0
	local cx,cy,cz = getElementPosition(plr)
	for k,v in pairs(getElementsByType("player")) do
		local x,y = getWl(v)
		local px,py,pz = getElementPosition(v)

		local dist = getDistanceBetweenPoints3D(px,py,pz, cx,cy,cz)
		--[[ Color codes:
		* Green: suspect is in jail and harmless
		* Yellow: suspect is arrested and on his way to jail
		* Orange: suspect is wanted but not violent (you must arrest)
		* Red: suspect is violent, kill arrest is allowed]]--
		local is_arrested = exports.GTWpolice:isArrested(v)
		local is_jailed = exports.GTWjail:isJailed(v)
		local location = getElementData(v, "Location") or getZoneName(px,py,pz)
		if is_jailed then
			local endTime = tonumber( getElementData( v, "jailTime" ))
			local currentTime = tonumber( getElementData( v, "jailTime2" ))
			outputChatBox(getPlayerName(v)..": Jailed: "..round((endTime-currentTime)/1000, 2).." seconds left", plr, 0, 200, 0)
			c = c + 1
		elseif is_arrested and x > 0 then
			outputChatBox(getPlayerName(v)..": Wanted level: "..round(x, 2)..", Violent time (s): "..
				round(y, 2)..", Location: "..location.." ("..getZoneName(px,py,pz,true)..") "..math.floor(dist).."m", plr, 255, 200, 0)
			c = c + 1
		elseif x > 0 and y > 0 then
			outputChatBox(getPlayerName(v)..": Wanted level: "..round(x, 2)..", Violent time (s): "..
				round(y, 2)..", Location: "..location.." ("..getZoneName(px,py,pz,true)..") "..math.floor(dist).."m", plr, 200, 0, 0)
			c = c + 1
		elseif x > 0 then
			outputChatBox(getPlayerName(v)..": Wanted level: "..round(x, 2)..", Violent time (s): "..
				round(y, 2)..", Location: "..location.." ("..getZoneName(px,py,pz,true)..") "..math.floor(dist).."m", plr, 255, 100, 0)
			c = c + 1
		end
	end
	if c == 0 then
		outputChatBox("No wanted players was found, try again later", plr, 255, 100, 0)
	end
end
addCommandHandler("wanted", show_wanted_players)
addCommandHandler("wanteds", show_wanted_players)

--[[ Pays a fine $500/star $200/violent second ]]--
function pay_fine(plr, cmd, plr2)
	local wl,viol = getWl(plr)
	local price = math.floor((wl*300)+(viol*100))
	local disttocop = exports.GTWpolice:distanceToCop(plr)
	if cmd == "adminfine" then
		local accName = getAccountName( getPlayerAccount( plr ))
		if isObjectInACLGroup ("user."..accName, aclGetGroup ( "Admin" )) then
			if plr2 and getPlayerFromName(plr2) then
				setWl(getPlayerFromName(plr2), 0, 0)
				exports.GTWtopbar:dm(getPlayerName(plr).." has removed your wanted level", getPlayerFromName(plr2), 255, 100, 0 )
				exports.GTWtopbar:dm("You have removed "..plr2.."'s wanted level", plr, 255, 100, 0 )
			else
				setWl(plr, 0, 0)
				exports.GTWtopbar:dm("You have removed your wanted level for free", plr, 255, 100, 0 )
			end
			return
		end
	end
	if (tonumber(getElementData(plr, "violent_seconds")) or 0) > 0 then
		exports.GTWtopbar:dm("You are too violent to pay a fine!", plr, 255, 0, 0 )
		return
	end
	if wl > 100 then
		exports.GTWtopbar:dm("Your wanted level is to high!", plr, 255, 0, 0 )
		return
	end
	if getPlayerMoney(plr) < price then
		exports.GTWtopbar:dm("You can't afford a fine! $"..tostring(price), plr, 255, 0, 0 )
		return
	end
	if wl == 0 then
		exports.GTWtopbar:dm("You are clean!", plr, 0, 255, 0 )
		return
	end
	if disttocop < 180 then
		exports.GTWtopbar:dm("You can't pay a fine when a law enforcer is nearby, ("..tostring(180-disttocop).."m to safety)", plr, 255, 0, 0 )
		return
	end
	wanted_data.fine_charge[plr] = price
	exports.GTWtopbar:dm("You have requested a fine, it will cost you $"..tostring(price)..", type /accept to continue", plr, 255, 100, 0 )
end
addCommandHandler("fine", pay_fine)
addCommandHandler("payfine", pay_fine)
addCommandHandler("surrender", pay_fine)
addCommandHandler("giveup", pay_fine)
addCommandHandler("adminfine", pay_fine)
function accept_fine(plr)
	if not wanted_data.fine_charge[plr] then return end
	takePlayerMoney(plr, wanted_data.fine_charge[plr])
	setWl(plr, 0, 0)
	wanted_data.fine_charge[plr] = nil
	exports.GTWtopbar:dm("You have paid a fine of $"..tostring(price), plr, 0, 255, 0 )
end
addCommandHandler("accept", accept_fine)
addCommandHandler("acceptfine", accept_fine)
addCommandHandler("confirm", accept_fine)
addCommandHandler("gtwinfo", function(plr, cmd)
	outputChatBox("[GTW-RPG] "..getResourceName(
	getThisResource())..", by: "..getResourceInfo(
        getThisResource(), "author")..", v-"..getResourceInfo(
        getThisResource(), "version")..", is represented", plr)
end)


text:
package com.mmidgard.piadas;

import java.io.Serializable;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class AdapterListPiadas extends BaseAdapter implements Serializable {

	private static final long serialVersionUID = 1681578298865327151L;
	private List<Piada> listaPiadas;
	private LayoutInflater mInflater;
	private String corLateral;

	public AdapterListPiadas(List<Piada> listaPiadas, Context c, String corLateral) {
		this.listaPiadas = listaPiadas;
		this.corLateral = corLateral;
		mInflater = LayoutInflater.from(c);
	}

	@Override
	public int getCount() {
		return listaPiadas.size();
	}

	@Override
	public Object getItem(int position) {
		return listaPiadas.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, final View view, ViewGroup parent) {
		final Piada piada = listaPiadas.get(position);
		View v = mInflater.inflate(R.layout.item_piada, null);

		TextView descricao = (TextView) v.findViewById(R.id.item_descricao);
		descricao.setText(piada.getDescricao().replace("\\n", "\n"));

		View cor = (View) v.findViewById(R.id.item_cor);
		cor.setBackgroundColor(Color.parseColor(corLateral));

		return v;
	}
}


text:
using UnityEngine;
using System.Collections;
using ReactionGrid.Jibe;

public class Sit : MonoBehaviour
{
    public string sitPose = "sit1";
    public string groundSitPose = "groundsit";
    private bool isSitting = false;
    private bool isHovering = false;
    public float clickDistanceLimit = 15;
    public float sitTargetOffsetX = 0.0f;
    public float sitTargetOffsetY = 0.0f;
    public float sitTargetOffsetZ = 0.0f;
	public Vector3 unsitOffset = Vector3.zero;
    public string sitText = "sit";
    public string groundSitText = "Sit";
    public bool enableGroundSit = true;

    public Texture2D sitIcon;
    public string standText = "stand";

    public GUISkin skin;

    public bool ShowStandButton = false;

    private Vector3 sitTarget;
    private Quaternion sitRotation;

    private GameObject currentPlayer; // contains movement controls
    public NetworkController networkController; // controls the environment
    public ChatInput chatController; // controls the chat system
    private GameObject playerCam;

    public GameObject cursor;

    private GameObject currentChair;

    private JibeActivityLog jibeLog;
    private string username;
    private string userId;

    private float playerCapsuleRadius = 0.2f;
    private float playerCapsuleHeight = 1.6f;

    private bool showTerrainSit = false;
    private Vector2 terrainSitPosition;
    private Vector3 terrainSitCoordinates;
    private float groundSitShowDuration = 2.0f;
    private float groundSitShowElapsed = 0.0f;
	//used in case another function that takes the same screenspace as the sit screenspace needs to override sitting
	private int sitNextFrame=-1;
	public GameObject standUpButton;
    void Start()
    {
        // Initialize static values
        sitTarget = transform.position;
        sitRotation = transform.rotation;
        if (cursor == null)
            cursor = GameObject.Find("Cursor");
        if (networkController == null)
        {
            networkController = GameObject.FindGameObjectWithTag("NetworkController").GetComponent<NetworkController>();
        }
        if (chatController == null)
        {
            //chatController = GameObject.Find("ChatBox").GetComponent<ChatInput>();
        }
    }

    void Update()
    {
		if(sitNextFrame==0)
		{
			InitiateSit();
		}
        if (!isSitting)
        {
            DetectMousePosition();
        }
        if (isHovering)
        {
            cursor.SendMessage("ShowSitCursor", true, SendMessageOptions.DontRequireReceiver);
        }
        else
        {
            cursor.SendMessage("ShowSitCursor", false, SendMessageOptions.DontRequireReceiver);
        }
        if (showTerrainSit)
        {
            groundSitShowElapsed += Time.deltaTime;
            if (groundSitShowElapsed > groundSitShowDuration)
            {
                showTerrainSit = false;
                groundSitShowElapsed = 0.0f;
            }
        }
		sitNextFrame--;
    }

    private void DetectMousePosition()
    {
        // Can't do this with MouseOver / MouseExit since the camera could be disabled
        // and mouseover doesn't play nice if that has happened!
        if (playerCam == null) playerCam = GameObject.FindGameObjectWithTag("MainCamera");
        if (playerCam != null)
        {
            if (playerCam.GetComponent<Camera>().enabled)
            {
                Ray mouseRay = playerCam.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                if (Physics.Raycast(mouseRay, out hit, clickDistanceLimit))
                {
                    //Debug.Log(hit.transform.name);

                    if (hit.transform.tag == "SitTarget")
                    {
                        // Player is hovering over a sittable object - one tagged as a "SitTarget".
                        // NOTE A sittable object MUST contain a collider (even a simple trigger would do) for this (raycasting) to work.
                        if(!Test.isHitting)
						{
							isHovering = true;
						}
						else
						{
							isHovering=false;
						}
                        sitTarget = hit.transform.position;
                        sitRotation = hit.transform.rotation;
                        if (Input.GetMouseButtonDown(0) && !Input.GetKey(KeyCode.LeftAlt) && !Test.isHitting)
                        {
                            currentChair = hit.transform.gameObject;
                            sitNextFrame=5;
							//InitiateSit();
                        }
                    }
                    else if (enableGroundSit && hit.transform.name == "Terrain")
                    {
                        terrainSitCoordinates = hit.point;
                        if (Input.GetMouseButtonDown(1))
                        {
                            terrainSitPosition = playerCam.GetComponent<Camera>().WorldToScreenPoint(terrainSitCoordinates);
                            showTerrainSit = true;
                        }
                    }
                    else
                    {
                        isHovering = false;
                    }
                }
				else
				{
					isHovering=false;
				}
            }
        }
    }

    void OnGUI()
    {
        GUI.skin = skin;

        if (isSitting)
        {
            // To stand up, the player moves forward or back while not chatting
            if (Input.GetButton("Vertical") || (Input.GetMouseButton(0) && Input.GetMouseButton(1)) || Input.GetButton("Jump"))
            {
                if (!chatController.IsChatting())
                {
                    UnSit();
                }
            }
            if (ShowStandButton)
            {
                // An alternative - show a button so the player can stand up when they are finished
                if (GUI.Button(new Rect(Screen.width/2-50,Screen.height-50,100,25), standText))
                {
                    UnSit();
                }
            }
        }
        if (showTerrainSit)
        {
            Vector2 pos = GUIUtility.ScreenToGUIPoint(new Vector2(terrainSitPosition.x, Screen.height - terrainSitPosition.y));
            GUIStyle buttonStyle = new GUIStyle("Button");
            buttonStyle.fixedWidth = 50;
            if (GUI.Button(new Rect(pos.x, pos.y, 50, 20), groundSitText, buttonStyle))
            {
                InitiateGroundSit();
            }
        }
    }

    private void InitiateGroundSit()
    {
        // update localPlayer
        currentPlayer = GameObject.FindGameObjectWithTag("Player");
        // Sit on the chair/object
        isSitting = true;
        isHovering = false;
        showTerrainSit = false;
        groundSitShowElapsed = 0.0f;
        SitAtPosition(terrainSitCoordinates, currentPlayer.transform.rotation, groundSitPose);
    }

    private void InitiateSit()
    {
		if(!Test.isHitting)
		{
	        // update localPlayer
	        currentPlayer = GameObject.FindGameObjectWithTag("Player");
	        // Sit on the chair/object
	        isSitting = true;
	        isHovering = false;
	        cursor.SendMessage("ShowSitCursor", false);
	        standUpButton.SendMessage("Toggle", false);
	        // Move the player to the correct position and rotation
	        float extraOffsetX = 0.0f;
	        float extraOffsetY = 0.0f;
	        float extraOffsetZ = 0.0f;
	        if (currentChair.GetComponent<SitOffset>() != null)
	        {
	            extraOffsetX = currentChair.GetComponent<SitOffset>().SitOffsetX;
	            extraOffsetY = currentChair.GetComponent<SitOffset>().SitOffsetY;
	            extraOffsetZ = currentChair.GetComponent<SitOffset>().SitOffsetZ;
	            sitPose = currentChair.GetComponent<SitOffset>().SitPose;
	        }
	        Vector3 sitPosition = sitTarget;
	        sitPosition.x = sitTarget.x + sitTargetOffsetX + extraOffsetX;
	        sitPosition.y = sitTarget.y + sitTargetOffsetY + extraOffsetY;
	        sitPosition.z = sitTarget.z + sitTargetOffsetZ + extraOffsetZ;
			sitRotation = Quaternion.Euler(sitRotation.eulerAngles + currentChair.GetComponent<SitOffset>().offsetRotation.eulerAngles);
	        SitAtPosition(sitPosition, sitRotation, sitPose);

	        try
	        {
	            if (currentChair != null)
	            {
	                if (currentChair.GetComponent<ChairController>() != null)
	                {
	                    currentChair.GetComponent<ChairController>().Sit();
	                }
	            }
	        }
	        catch
	        {
	            Debug.Log("No sit camera script on this chair");
	        }
			currentPlayer.SendMessage("SnapCameraToDefault");
			currentPlayer.SendMessage("GetSitRotation", sitRotation);
		}
    }

    private void SitAtPosition(Vector3 targetPosition, Quaternion targetRotation, string animationToPlay)
    {
        // Disable movement controls
//        ((Behaviour)currentPlayer.GetComponent<PlayerCharacter>()).enabled = false;
		currentPlayer.GetComponent<FPSInputController>().enabled=false;
		currentPlayer.GetComponent<CharacterMotor>().enabled=false;
		currentPlayer.GetComponent<MouseLook>().playerControlOn=false;
        // If we're using physical characters, turn off the RB component
/*        PlayerSpawnController psc = networkController.GetComponent<PlayerSpawnController>();
        if (psc != null)
        {
            if (psc.usePhysicalCharacter)
            {
                currentPlayer.GetComponent<Rigidbody>().useGravity = false;
                playerCapsuleRadius = currentPlayer.GetComponent<CapsuleCollider>().radius;
                playerCapsuleHeight = currentPlayer.GetComponent<CapsuleCollider>().height;
                currentPlayer.GetComponent<CapsuleCollider>().radius = 0.01f;
                currentPlayer.GetComponent<CapsuleCollider>().height = 0.01f;
            }
        }*/
//		currentPlayer.GetComponent<CharacterController>().radius=.1f;
//		currentPlayer.GetComponent<CharacterController>().height=.1f;
        currentPlayer.transform.position = targetPosition;
        // Note there is no simple way to control the rotation via user settings in inspector. Best approach, adjust the collider on the
        // sittable object to the correct orientation. This could mean adding an empty cube collider to a chair and rotating to the correct
        // angle for the avatar to face the correct way.
        currentPlayer.transform.rotation = targetRotation;

        // Play the selected sit pose
        AnimateCharacter tpa = currentPlayer.transform.GetChild(0).GetComponent<AnimateCharacter>();
        tpa.SitAnimation(animationToPlay);
        tpa.EnableIdleWakeup(false); // never want an idle wake up while sitting
        currentPlayer.transform.GetChild(0).GetComponent<PlayerMovement>().SetSitting(true, animationToPlay);

        Debug.Log("Sitting: " + isSitting);

        networkController.SendTransform(currentPlayer.transform);
        networkController.SendAnimation(animationToPlay);
        TrackSit();
    }

    private void TrackSit()
    {
        // Log the sit interaction to the database, if the activity log is enabled.
        if (jibeLog == null)
        {
            jibeLog = GameObject.Find("Jibe").GetComponent<JibeActivityLog>();
            if (jibeLog != null)
            {
                Debug.Log("Found jibeLog");
            }
        }
        if (jibeLog.logEnabled)
        {
            if (string.IsNullOrEmpty(username))
            {
                username = networkController.GetMyName();
            }
            IJibePlayer localPlayer = networkController.GetLocalPlayer();
            string playerId = localPlayer.PlayerID.ToString();
            if (PlayerPrefs.GetString("useruuid") != null)
                playerId = PlayerPrefs.GetString("useruuid");
            Debug.Log(jibeLog.TrackEvent(JibeEventType.Sit, Application.srcValue, this.transform.position.x, this.transform.position.y, this.transform.position.z, playerId, username, "User Sat on Chair"));
        }
    }

    public void UnSit()
    {
        standUpButton.SendMessage("Toggle", true);
        // Cancel sit
        try
        {
            if (currentChair != null)
            {
                currentChair.GetComponent<ChairController>().UnSit();
            }
        }
        catch
        {
            Debug.Log("No sit camera script on this chair");
        }
        AnimateCharacter tpa = currentPlayer.transform.GetChild(0).GetComponent<AnimateCharacter>();
        tpa.CancelSitAnimation();
        bool idleAnimWakeupEnabledByDefault = networkController.gameObject.GetComponent<PlayerSpawnController>().enableIdleAnimationWakeup;
        tpa.SendMessage("EnableIdleWakeup", idleAnimWakeupEnabledByDefault); // only re-enable if enabled in PSC

        // If we're using physical characters, turn off the RB component
/*        PlayerSpawnController psc = networkController.GetComponent<PlayerSpawnController>();
        if (psc != null)
        {
            if (psc.usePhysicalCharacter)
            {
                currentPlayer.GetComponent<Rigidbody>().useGravity = true;
                currentPlayer.GetComponent<CapsuleCollider>().radius = playerCapsuleRadius;
                currentPlayer.GetComponent<CapsuleCollider>().height = playerCapsuleHeight;
            }
        }*/
		currentPlayer.GetComponent<CharacterController>().radius=.5f;
		currentPlayer.GetComponent<CharacterController>().height=2f;
        currentPlayer.transform.GetChild(0).GetComponent<PlayerMovement>().SetSitting(false, sitPose);
        // Re-enable movement
//        ((Behaviour)currentPlayer.transform.GetChild(0).GetComponent<PlayerCharacter>()).enabled = true;
		currentPlayer.GetComponent<FPSInputController>().enabled=true;
		currentPlayer.GetComponent<CharacterMotor>().enabled=true;
		currentPlayer.GetComponent<MouseLook>().playerControlOn=true;
		//currentPlayer.GetComponent<MouseLook>().SetCurrentTransformAsDefault();
		currentPlayer.transform.Translate(unsitOffset);
		currentPlayer.GetComponent<MouseLook>().SetCurrentTransformAsDefault();
        isSitting = false;
        Debug.Log("Sitting: " + isSitting);
    }
	public void DisableSitThisFrame()
	{
		sitNextFrame=-1;
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>monitorp — Logtalk APIs v3.61.0-b01 documentation</title>
      <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
      <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
      <link rel="stylesheet" href="_static/css/custom.css" type="text/css" />

    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
    <link rel="manifest" href="/site.webmanifest" />
    <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />
    <meta name="msapplication-TileColor" content="#355b95" />
    <meta name="theme-color" content="#ffffff" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="expand_library_alias_paths" href="expand_library_alias_paths_0.html" />
    <link rel="prev" title="monitor" href="monitor_0.html" />

             Logtalk APIs

                3.61.0

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Contents

Libraries

arbitrary

assertions

assignvars

base64

cbor

code_metrics

core

coroutining

csv

dates

dead_code_scanner

debug_messages

debugger

dependents

diagrams

dictionaries

dif

doclet

edcg

events

after_event_registry

before_event_registry

event_registry

event_registryp

monitor

monitorp

expand_library_alias_paths

expecteds

fcube

flags

format

genint

gensym

git

grammars

heaps

help

hierarchies

hook_flows

hook_objects

html

ids

intervals

iso8601

issue_creator

java

json

lgtdoc

lgtunit

library

logging

loops

meta

meta_compiler

metagol

nested_dictionaries

optionals

options

os

packs

pddl_parser

ports_profiler

queues

random

reader

redis

sets

statistics

term_io

timeout

toychr

tutor

types

union_find

uuid

verdi_neruda

wrapper

xml_parser

zippers

Directories

Entities

Predicates

Core diagram

Libraries diagram

Tools diagram

Ports diagram

Contributions diagram

Index

External Contents

Handbook

Logtalk website

GitHub repo

          Logtalk APIs

 »

Libraries »

monitorp

             View page source

protocol

monitorp

Monitor protocol.

Author: Paulo Moura

Version: 1:0:0

Date: 2000-07-24

Compilation flags:

static

Dependencies:

(none)

Remarks:

(none)

Inherited public predicates:

(none)

Public predicates

monitor_activated/0

activate_monitor/0

suspend_monitor/0

reset_monitor/0

spy_point/4

set_spy_point/4

del_spy_points/4

Protected predicates

Private predicates

Operators

Public predicates

monitor_activated/0

True if monitor is currently active.

Compilation flags:

static

Mode and number of proofs:

monitor_activated - zero_or_one

activate_monitor/0

Activates all spy points and start monitoring.

Compilation flags:

static

Mode and number of proofs:

activate_monitor - one

suspend_monitor/0

Suspends monitoring, deactivating all spy points.

Compilation flags:

static

Mode and number of proofs:

suspend_monitor - one

reset_monitor/0

Resets monitor, deactivating and deleting all spy points.

Compilation flags:

static

Mode and number of proofs:

reset_monitor - one

spy_point/4

Current spy point.

Compilation flags:

static

Template:

spy_point(Event,Object,Message,Sender)

Mode and number of proofs:

spy_point(?event,?object,?callable,?object) - zero_or_more

set_spy_point/4

Sets a spy point.

Compilation flags:

static

Template:

set_spy_point(Event,Object,Message,Sender)

Mode and number of proofs:

set_spy_point(?event,?object,?callable,?object) - one

del_spy_points/4

Deletes all matching spy points.

Compilation flags:

static

Template:

del_spy_points(Event,Object,Message,Sender)

Mode and number of proofs:

del_spy_points(@event,@object,@callable,@object) - one

Protected predicates

(none)

Private predicates

(none)

Operators

(none)

See also

monitor, event_registryp

         Previous
        Next

© Copyright 1998-2022, Paulo Moura.

  Built with Sphinx using a
    theme
    provided by Read the Docs.


text:
packages=$(echo "$1")
github_token=$(echo "$2")
swapsize=$(echo "$3")
timezone=$(echo "$4")
# Helpers
composer="php /usr/local/bin/composer"

# System configuration
if ! grep --quiet "swapfile" /etc/fstab; then
  fallocate -l ${swapsize}M /swapfile
  chmod 600 /swapfile
  mkswap /swapfile
  swapon /swapfile
  echo '/swapfile none swap defaults 0 0' >> /etc/fstab
fi

# Configuring timezone
echo ${timezone} | sudo tee /etc/timezone
sudo dpkg-reconfigure --frontend noninteractive tzdata

# Additional repositories
if [ ! -f /etc/apt/sources.list.d/hhvm.list ]; then
    sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0x5a16e7281be7a449
    sudo echo 'deb http://dl.hhvm.com/ubuntu trusty main' >> /etc/apt/sources.list.d/hhvm.list
fi

sudo add-apt-repository -y ppa:ondrej/php

# Configuring server software
sudo update-locale LC_ALL="C"
sudo dpkg-reconfigure locales
echo "mysql-server-5.6 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.6 mysql-server/root_password_again password root" | debconf-set-selections

sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install -y ${packages}

sudo sed -i 's/bind-address.*/bind-address = 0.0.0.0/g' /etc/mysql/my.cnf;
if ! grep --quiet '^xdebug.remote_enable = on$' /etc/php/7.0/mods-available/xdebug.ini; then
    (
     echo "xdebug.remote_enable = on";
     echo "xdebug.remote_connect_back = on";
     echo "xdebug.remote_host = 10.0.2.2";
     echo "xdebug.idekey = \"vagrant\""
    ) >> /etc/php/7.0/mods-available/xdebug.ini
fi
sudo phpenmod mcrypt

# disable xdebug temporarily to avoid composer performance issues
sudo phpdismod xdebug

# install composer
if [ ! -f /usr/local/bin/composer ]; then
	sudo curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
    ${composer} global require fxp/composer-asset-plugin --no-progress --prefer-dist
else
	${composer} self-update
	${composer} global update --no-progress --prefer-dist
fi
${composer} config --global github-oauth.github.com ${github_token}

# init application
if [ ! -d /var/www/vendor ]; then
    cd /var/www && ${composer} install --no-progress --prefer-dist --optimize-autoloader
else
    cd /var/www && ${composer} update --no-progress --prefer-dist --optimize-autoloader
fi

# enable xdebug again
sudo phpenmod xdebug

# copy only if not exists
if [ ! -f /var/www/.env ]; then
    cp /var/www/.env.dist /var/www/.env
fi

# create nginx config
if [ ! -f /etc/nginx/sites-enabled/yii2-starter-kit.dev ]; then
    sudo ln -s /var/www/vagrant/vhost.conf /etc/nginx/sites-enabled/yii2-starter-kit.dev
fi

# Configuring application
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root'" | mysql -uroot -proot
echo "FLUSH PRIVILEGES" | mysql -uroot -proot
echo "CREATE DATABASE IF NOT EXISTS \`yii2-starter-kit\` CHARACTER SET utf8 COLLATE utf8_unicode_ci" | mysql -uroot -proot

php /var/www/console/yii app/setup --interactive=0

sudo service mysql restart
sudo service php7.0-fpm restart
sudo service nginx restart


text:
Remote Foundation
=================

`MRFoundation` is a network communication framework between [`Mac Remote OS X`](https://github.com/MacRemote/MacRemote) and [`Mac Remote iOS`](https://github.com/MacRemote/MacRemote-iOS) and is not finished yet.

***(Under Development)***


text:
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Leaderboard, { LeaderboardItem } from '../Leaderboard'

describe('Leaderboard component test', () => {
  const props = {
    developers: [{
      profile: {
        first_name: 'Xiao',
        last_name: 'Ying'
      },
      maxSummary: {
        grade: 'B',
        score: 75
      }
    }]
  }

  it('should render leaderbaord item message', () => {
    const Wrapper = shallow(<LeaderboardItem developer={props.developers[0]} key={0} idx={0} />)
    expect(Wrapper.contains(
1. Xiao Ying B ( score: 75 )
)).toEqual(true)
  })

  it('should render leaderboard component', () => {
    const Wrapper = shallow(<Leaderboard {...props} />)
    expect(Wrapper.contains(
Leaderboard
)).toEqual(true)
    expect(Wrapper.contains(<LeaderboardItem developer={props.developers[0]} key={0} idx={0} />)).toEqual(true)
  })

  it('should render No players message if developers length is 0', () => {
    const Wrapper = shallow(<Leaderboard developers={[]} />)
    expect(Wrapper.contains('No Players')).toEqual(true)
  })
})