text:
namespace extensions {

namespace {

// Pass into ServiceWorkerTest::StartTestFromBackgroundPage to indicate that
// registration is expected to succeed.
std::string* const kExpectSuccess = nullptr;

void DoNothingWithBool(bool b) {}

}  // namespace

class ServiceWorkerTest : public ExtensionApiTest {
 public:
  ServiceWorkerTest() : current_channel_(version_info::Channel::UNKNOWN) {}

  ~ServiceWorkerTest() override {}

 protected:
  // Returns the ProcessManager for the test's profile.
  ProcessManager* process_manager() { return ProcessManager::Get(profile()); }

  // Starts running a test from the background page test extension.
  //
  // This registers a service worker with |script_name|, and fetches the
  // registration result.
  //
  // If |error_or_null| is null (kExpectSuccess), success is expected and this
  // will fail if there is an error.
  // If |error_or_null| is not null, nothing is assumed, and the error (which
  // may be empty) is written to it.
  const Extension* StartTestFromBackgroundPage(const char* script_name,
                                               std::string* error_or_null) {
    const Extension* extension =
        LoadExtension(test_data_dir_.AppendASCII("service_worker/background"));
    CHECK(extension);
    ExtensionHost* background_host =
        process_manager()->GetBackgroundHostForExtension(extension->id());
    CHECK(background_host);
    std::string error;
    CHECK(content::ExecuteScriptAndExtractString(
        background_host->host_contents(),
        base::StringPrintf("test.registerServiceWorker('%s')", script_name),
        &error));
    if (error_or_null)
      *error_or_null = error;
    else if (!error.empty())
      ADD_FAILURE() << "Got unexpected error " << error;
    return extension;
  }

  // Navigates the browser to a new tab at |url|, waits for it to load, then
  // returns it.
  content::WebContents* Navigate(const GURL& url) {
    ui_test_utils::NavigateToURLWithDisposition(
        browser(), url, NEW_FOREGROUND_TAB,
        ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    content::WaitForLoadStop(web_contents);
    return web_contents;
  }

  // Navigates the browser to |url| and returns the new tab's page type.
  content::PageType NavigateAndGetPageType(const GURL& url) {
    return Navigate(url)->GetController().GetActiveEntry()->GetPageType();
  }

  // Extracts the innerText from |contents|.
  std::string ExtractInnerText(content::WebContents* contents) {
    std::string inner_text;
    if (!content::ExecuteScriptAndExtractString(
            contents,
            "window.domAutomationController.send(document.body.innerText)",
            &inner_text)) {
      ADD_FAILURE() << "Failed to get inner text for "
                    << contents->GetVisibleURL();
    }
    return inner_text;
  }

  // Navigates the browser to |url|, then returns the innerText of the new
  // tab's WebContents' main frame.
  std::string NavigateAndExtractInnerText(const GURL& url) {
    return ExtractInnerText(Navigate(url));
  }

 private:
  // Sets the channel to "trunk" since service workers are restricted to trunk.
  ScopedCurrentChannel current_channel_;

  DISALLOW_COPY_AND_ASSIGN(ServiceWorkerTest);
};

class ServiceWorkerBackgroundSyncTest : public ServiceWorkerTest {
 public:
  ServiceWorkerBackgroundSyncTest() {}
  ~ServiceWorkerBackgroundSyncTest() override {}

  void SetUpCommandLine(base::CommandLine* command_line) override {
    // ServiceWorkerRegistration.sync requires experimental flag.
    command_line->AppendSwitch(
        switches::kEnableExperimentalWebPlatformFeatures);
    ServiceWorkerTest::SetUpCommandLine(command_line);
  }

  void SetUp() override {
    content::background_sync_test_util::SetIgnoreNetworkChangeNotifier(true);
    ServiceWorkerTest::SetUp();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ServiceWorkerBackgroundSyncTest);
};

class ServiceWorkerPushMessagingTest : public ServiceWorkerTest {
 public:
  ServiceWorkerPushMessagingTest()
      : gcm_service_(nullptr), push_service_(nullptr) {}
  ~ServiceWorkerPushMessagingTest() override {}

  void GrantNotificationPermissionForTest(const GURL& url) {
    GURL origin = url.GetOrigin();
    DesktopNotificationProfileUtil::GrantPermission(profile(), origin);
    ASSERT_EQ(
        CONTENT_SETTING_ALLOW,
        DesktopNotificationProfileUtil::GetContentSetting(profile(), origin));
  }

  PushMessagingAppIdentifier GetAppIdentifierForServiceWorkerRegistration(
      int64 service_worker_registration_id,
      const GURL& origin) {
    PushMessagingAppIdentifier app_identifier =
        PushMessagingAppIdentifier::FindByServiceWorker(
            profile(), origin, service_worker_registration_id);

    EXPECT_FALSE(app_identifier.is_null());
    return app_identifier;
  }

  // ExtensionApiTest overrides.
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(switches::kEnablePushMessagePayload);
    ServiceWorkerTest::SetUpCommandLine(command_line);
  }
  void SetUpOnMainThread() override {
    gcm_service_ = static_cast<gcm::FakeGCMProfileService*>(
        gcm::GCMProfileServiceFactory::GetInstance()->SetTestingFactoryAndUse(
            profile(), &gcm::FakeGCMProfileService::Build));
    gcm_service_->set_collect(true);
    push_service_ = PushMessagingServiceFactory::GetForProfile(profile());

    ServiceWorkerTest::SetUpOnMainThread();
  }

  gcm::FakeGCMProfileService* gcm_service() const { return gcm_service_; }
  PushMessagingServiceImpl* push_service() const { return push_service_; }

 private:
  gcm::FakeGCMProfileService* gcm_service_;
  PushMessagingServiceImpl* push_service_;

  DISALLOW_COPY_AND_ASSIGN(ServiceWorkerPushMessagingTest);
};

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, RegisterSucceedsOnTrunk) {
  StartTestFromBackgroundPage("register.js", kExpectSuccess);
}

// This feature is restricted to trunk, so on dev it should have existing
// behavior - which is for it to fail.
IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, RegisterFailsOnDev) {
  ScopedCurrentChannel current_channel_override(
      version_info::Channel::DEV);
  std::string error;
  const Extension* extension =
      StartTestFromBackgroundPage("register.js", &error);
  EXPECT_EQ(
      "Failed to register a ServiceWorker: The URL protocol of the current "
      "origin ('chrome-extension://" +
          extension->id() + "') is not supported.",
      error);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, FetchArbitraryPaths) {
  const Extension* extension =
      StartTestFromBackgroundPage("fetch.js", kExpectSuccess);

  // Open some arbirary paths. Their contents should be what the service worker
  // responds with, which in this case is the path of the fetch.
  EXPECT_EQ(
      "Caught a fetch for /index.html",
      NavigateAndExtractInnerText(extension->GetResourceURL("index.html")));
  EXPECT_EQ("Caught a fetch for /path/to/other.html",
            NavigateAndExtractInnerText(
                extension->GetResourceURL("path/to/other.html")));
  EXPECT_EQ("Caught a fetch for /some/text/file.txt",
            NavigateAndExtractInnerText(
                extension->GetResourceURL("some/text/file.txt")));
  EXPECT_EQ("Caught a fetch for /no/file/extension",
            NavigateAndExtractInnerText(
                extension->GetResourceURL("no/file/extension")));
  EXPECT_EQ("Caught a fetch for /",
            NavigateAndExtractInnerText(extension->GetResourceURL("")));
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
                       LoadingBackgroundPageBypassesServiceWorker) {
  const Extension* extension =
      StartTestFromBackgroundPage("fetch.js", kExpectSuccess);

  std::string kExpectedInnerText = "background.html contents for testing.";

  // Sanity check that the background page has the expected content.
  ExtensionHost* background_page =
      process_manager()->GetBackgroundHostForExtension(extension->id());
  ASSERT_TRUE(background_page);
  EXPECT_EQ(kExpectedInnerText,
            ExtractInnerText(background_page->host_contents()));

  // Close the background page.
  background_page->Close();
  BackgroundPageWatcher(process_manager(), extension).WaitForClose();
  background_page = nullptr;

  // Start it again.
  process_manager()->WakeEventPage(extension->id(),
                                   base::Bind(&DoNothingWithBool));
  BackgroundPageWatcher(process_manager(), extension).WaitForOpen();

  // Content should not have been affected by the fetch, which would otherwise
  // be "Caught fetch for...".
  background_page =
      process_manager()->GetBackgroundHostForExtension(extension->id());
  ASSERT_TRUE(background_page);
  content::WaitForLoadStop(background_page->host_contents());

  // TODO(kalman): Everything you've read has been a LIE! It should be:
  //
  // EXPECT_EQ(kExpectedInnerText,
  //           ExtractInnerText(background_page->host_contents()));
  //
  // but there is a bug, and we're actually *not* bypassing the service worker
  // for background page loads! For now, let it pass (assert wrong behavior)
  // because it's not a regression, but this must be fixed eventually.
  //
  // Tracked in crbug.com/532720.
  EXPECT_EQ("Caught a fetch for /background.html",
            ExtractInnerText(background_page->host_contents()));
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
                       ServiceWorkerPostsMessageToBackgroundClient) {
  const Extension* extension = StartTestFromBackgroundPage(
      "post_message_to_background_client.js", kExpectSuccess);

  // The service worker in this test simply posts a message to the background
  // client it receives from getBackgroundClient().
  const char* kScript =
      "var messagePromise = null;\n"
      "if (test.lastMessageFromServiceWorker) {\n"
      "  messagePromise = Promise.resolve(test.lastMessageFromServiceWorker);\n"
      "} else {\n"
      "  messagePromise = test.waitForMessage(navigator.serviceWorker);\n"
      "}\n"
      "messagePromise.then(function(message) {\n"
      "  window.domAutomationController.send(String(message == 'success'));\n"
      "})\n";
  EXPECT_EQ("true", ExecuteScriptInBackgroundPage(extension->id(), kScript));
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
                       BackgroundPagePostsMessageToServiceWorker) {
  const Extension* extension =
      StartTestFromBackgroundPage("post_message_to_sw.js", kExpectSuccess);

  // The service worker in this test waits for a message, then echoes it back
  // by posting a message to the background page via getBackgroundClient().
  const char* kScript =
      "var mc = new MessageChannel();\n"
      "test.waitForMessage(mc.port1).then(function(message) {\n"
      "  window.domAutomationController.send(String(message == 'hello'));\n"
      "});\n"
      "test.registeredServiceWorker.postMessage(\n"
      "    {message: 'hello', port: mc.port2}, [mc.port2])\n";
  EXPECT_EQ("true", ExecuteScriptInBackgroundPage(extension->id(), kScript));
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
                       ServiceWorkerSuspensionOnExtensionUnload) {
  // For this test, only hold onto the extension's ID and URL + a function to
  // get a resource URL, because we're going to be disabling and uninstalling
  // it, which will invalidate the pointer.
  std::string extension_id;
  GURL extension_url;
  {
    const Extension* extension =
        StartTestFromBackgroundPage("fetch.js", kExpectSuccess);
    extension_id = extension->id();
    extension_url = extension->url();
  }
  auto get_resource_url = [&extension_url](const std::string& path) {
    return Extension::GetResourceURL(extension_url, path);
  };

  // Fetch should route to the service worker.
  EXPECT_EQ("Caught a fetch for /index.html",
            NavigateAndExtractInnerText(get_resource_url("index.html")));

  // Disable the extension. Opening the page should fail.
  extension_service()->DisableExtension(extension_id,
                                        Extension::DISABLE_USER_ACTION);
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(content::PAGE_TYPE_ERROR,
            NavigateAndGetPageType(get_resource_url("index.html")));
  EXPECT_EQ(content::PAGE_TYPE_ERROR,
            NavigateAndGetPageType(get_resource_url("other.html")));

  // Re-enable the extension. Opening pages should immediately start to succeed
  // again.
  extension_service()->EnableExtension(extension_id);
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ("Caught a fetch for /index.html",
            NavigateAndExtractInnerText(get_resource_url("index.html")));
  EXPECT_EQ("Caught a fetch for /other.html",
            NavigateAndExtractInnerText(get_resource_url("other.html")));
  EXPECT_EQ("Caught a fetch for /another.html",
            NavigateAndExtractInnerText(get_resource_url("another.html")));

  // Uninstall the extension. Opening pages should fail again.
  base::string16 error;
  extension_service()->UninstallExtension(
      extension_id, UninstallReason::UNINSTALL_REASON_FOR_TESTING,
      base::Bind(&base::DoNothing), &error);
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(content::PAGE_TYPE_ERROR,
            NavigateAndGetPageType(get_resource_url("index.html")));
  EXPECT_EQ(content::PAGE_TYPE_ERROR,
            NavigateAndGetPageType(get_resource_url("other.html")));
  EXPECT_EQ(content::PAGE_TYPE_ERROR,
            NavigateAndGetPageType(get_resource_url("anotherother.html")));
  EXPECT_EQ(content::PAGE_TYPE_ERROR,
            NavigateAndGetPageType(get_resource_url("final.html")));
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, BackgroundPageIsWokenIfAsleep) {
  const Extension* extension =
      StartTestFromBackgroundPage("wake_on_fetch.js", kExpectSuccess);

  // Navigate to special URLs that this test's service worker recognises, each
  // making a check then populating the response with either "true" or "false".
  EXPECT_EQ("true", NavigateAndExtractInnerText(extension->GetResourceURL(
                        "background-client-is-awake")));
  EXPECT_EQ("true", NavigateAndExtractInnerText(
                        extension->GetResourceURL("ping-background-client")));
  // Ping more than once for good measure.
  EXPECT_EQ("true", NavigateAndExtractInnerText(
                        extension->GetResourceURL("ping-background-client")));

  // Shut down the event page. The SW should detect that it's closed, but still
  // be able to ping it.
  ExtensionHost* background_page =
      process_manager()->GetBackgroundHostForExtension(extension->id());
  ASSERT_TRUE(background_page);
  background_page->Close();
  BackgroundPageWatcher(process_manager(), extension).WaitForClose();

  EXPECT_EQ("false", NavigateAndExtractInnerText(extension->GetResourceURL(
                         "background-client-is-awake")));
  EXPECT_EQ("true", NavigateAndExtractInnerText(
                        extension->GetResourceURL("ping-background-client")));
  EXPECT_EQ("true", NavigateAndExtractInnerText(
                        extension->GetResourceURL("ping-background-client")));
  EXPECT_EQ("true", NavigateAndExtractInnerText(extension->GetResourceURL(
                        "background-client-is-awake")));
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
                       GetBackgroundClientFailsWithNoBackgroundPage) {
  // This extension doesn't have a background page, only a tab at page.html.
  // The service worker it registers tries to call getBackgroundClient() and
  // should fail.
  // Note that this also tests that service workers can be registered from tabs.
  EXPECT_TRUE(RunExtensionSubtest("service_worker/no_background", "page.html"));
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, NotificationAPI) {
  EXPECT_TRUE(RunExtensionSubtest("service_worker/notifications/has_permission",
                                  "page.html"));
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerBackgroundSyncTest, Sync) {
  const Extension* extension = LoadExtensionWithFlags(
      test_data_dir_.AppendASCII("service_worker/sync"), kFlagNone);
  ASSERT_TRUE(extension);
  ui_test_utils::NavigateToURL(browser(),
                               extension->GetResourceURL("page.html"));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Prevent firing by going offline.
  content::background_sync_test_util::SetOnline(web_contents, false);

  ExtensionTestMessageListener sync_listener("SYNC: send-chats", false);
  sync_listener.set_failure_message("FAIL");

  std::string result;
  ASSERT_TRUE(content::ExecuteScriptAndExtractString(
      web_contents, "window.runServiceWorker()", &result));
  ASSERT_EQ("SERVICE_WORKER_READY", result);

  EXPECT_FALSE(sync_listener.was_satisfied());
  // Resume firing by going online.
  content::background_sync_test_util::SetOnline(web_contents, true);
  EXPECT_TRUE(sync_listener.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
                       FetchFromContentScriptShouldNotGoToServiceWorkerOfPage) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  GURL page_url = embedded_test_server()->GetURL(
      "/extensions/api_test/service_worker/content_script_fetch/"
      "controlled_page/index.html");
  content::WebContents* tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  ui_test_utils::NavigateToURL(browser(), page_url);
  content::WaitForLoadStop(tab);

  std::string value;
  ASSERT_TRUE(
      content::ExecuteScriptAndExtractString(tab, "register();", &value));
  EXPECT_EQ("SW controlled", value);

  ASSERT_TRUE(RunExtensionTest("service_worker/content_script_fetch"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerPushMessagingTest, OnPush) {
  const Extension* extension = LoadExtensionWithFlags(
      test_data_dir_.AppendASCII("service_worker/push_messaging"), kFlagNone);
  ASSERT_TRUE(extension);
  GURL extension_url = extension->url();

  ASSERT_NO_FATAL_FAILURE(GrantNotificationPermissionForTest(extension_url));

  GURL url = extension->GetResourceURL("page.html");
  ui_test_utils::NavigateToURL(browser(), url);

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Start the ServiceWorker.
  ExtensionTestMessageListener ready_listener("SERVICE_WORKER_READY", false);
  ready_listener.set_failure_message("SERVICE_WORKER_FAILURE");
  const char* kScript = "window.runServiceWorker()";
  EXPECT_TRUE(content::ExecuteScript(web_contents->GetMainFrame(), kScript));
  EXPECT_TRUE(ready_listener.WaitUntilSatisfied());

  PushMessagingAppIdentifier app_identifier =
      GetAppIdentifierForServiceWorkerRegistration(0LL, extension_url);
  ASSERT_EQ(app_identifier.app_id(), gcm_service()->last_registered_app_id());
  EXPECT_EQ("1234567890", gcm_service()->last_registered_sender_ids()[0]);

  // Send a push message via gcm and expect the ServiceWorker to receive it.
  ExtensionTestMessageListener push_message_listener("OK", false);
  push_message_listener.set_failure_message("FAIL");
  gcm::IncomingMessage message;
  message.sender_id = "1234567890";
  message.raw_data = "testdata";
  message.decrypted = true;
  push_service()->OnMessage(app_identifier.app_id(), message);
  EXPECT_TRUE(push_message_listener.WaitUntilSatisfied());
}

}  // namespace extensions


text:
$(document).ready(function() {
    PromotionGroup.init();
    PromotionGroup.loadImage();
    $('#add-new-promotion').on('click', function(){
        PromotionGroup.addNew();
    })

    $('#update-promotion').on('click', function(){
        PromotionGroup.update();
    })

    // date picker
    $('#promotion-add-end-date').datepicker({
        format: "dd/mm/yyyy"
    });
    $('#promotion-add-start-date').datepicker({
        format: "dd/mm/yyyy"
    });
    $('#promotion-update-start-date').datepicker({
        format: "dd/mm/yyyy"
    });

    $('#promotion-update-end-date').datepicker({
        format: "dd/mm/yyyy"
    });

    //editor
    CKEDITOR.replace('promotionContent');
    CKEDITOR.replace('promotionContentUpdate');

});

var PromotionGroup = function () {

    // load list promotion
    var loadListPromotion = function() {

        var html = '';

        $.ajax({
            url: URL + 'spaCMS/promotion/xhrLoad_promotion_list',
            type: 'get',
            dataType: 'json',
        })
        .done(function(data) {
            $('span#promotion-title-spa').text('DANH SÁCH TIN KHUYẾN MÃI');
            if(data['list'].length >0 ){
                $('#promotion-mesage-list').hide('fast');
                var totalPublish = 0;
                $.each(data['list'], function(k, val){
                    totalPublish = (val.promotion_state == 1)? totalPublish+1 : totalPublish;
                    var state = (val.promotion_state == 0)? "button-other": "hide";
                    var nowDay = new Date();
                    var endDay  = val.promotion_end_date;

                    var createDay = val.promotion_create_date;
                    var end_Day = val.promotion_end_date;
                    var startDay = val.promotion_start_date;
                    var strMark = "";
                    strMark = (new Date(end_Day) < new Date())? "color: red; text-decoration: line-through;" : "";
                        createDay = createDay.substr(8, 2)+'/'+ createDay.substr(5, 2)+'/'+createDay.substr(0, 4);
                        startDay = startDay.substr(8, 2)+'/'+ startDay.substr(5, 2)+'/'+startDay.substr(0, 4);
                        end_Day = end_Day.substr(8, 2)+'/'+ end_Day.substr(5, 2)+'/'+end_Day.substr(0, 4);
                    // var promotion_img = JSON.parse(val.promotion_img);

                    html += '
';
                    html += '
'+val.promotion_title+'
';
                    html += '
'+createDay+'
';
                    html += '
'+startDay+'
';
                    html += '
'+end_Day+'
';
                    // html += '
'+totalDay+'
';
                    html += '
';

                        html += '<button class="button '+state+' promotion-items-publish" data-promotion-id="'+val.promotion_id+'" title="Kích hoạt"> ';
                        html += '';
                        html += '</button> ';
                        html += '<button class="button button-secondary redeem promotion-items-delete" data-promotion-id="'+val.promotion_id+'" title="Xóa"> ';
                        html += '';
                        html += '</button>';
                    html += '
';
                    html += '
';
                });
                     html += '<input class="input-hide-state" type="hidden" value="'+totalPublish+'">';
                $('#promotion-content').html(html);
            }else{
                $('#promotion-content').html('');
                $('#promotion-mesage-list').fadeIn('fast');
            }
        })
        .always(function(){

             $('.promotion-items-delete').on('click',function(e){
                var id_promotion = $(this).attr('data-promotion-id');
                e.stopPropagation();
                var cfr = confirm('Bạn có muốn xóa promotion này không?');
                    if(cfr == true){
                        deletePromotion(id_promotion);
                    }
            });

            $('.promotion-items-publish').on('click',function(e){
                var id_promotion = $(this).attr('data-promotion-id');
                var self = $(this);
                var state = 1; // kich hoat
                e.stopPropagation();
                if($('input.input-hide-state').val() >4){
                    alert('Chỉ hiển thị được 5 promotion.');
                }else{
                     publishPromotion(id_promotion, state);
                }
            });

            $('.btn-close-modal').on('click',function (){
                $(".modal").modal('hide');
            })
            $('#refres-promotion').on('click', function(){
                refresh();
            });

            $('li.promotion-list-item').on('click', function(){
                var self = $(this);
                var id_promotion = self.attr('data-id-promotion');
                $.ajax({
                    url: URL + 'spaCMS/promotion/xhrLoad_promotion_item',
                    type: 'post',
                    dataType: 'json',
                    data: {promotion_id: id_promotion},
                })
                .done(function(data) {
                    $.each(data, function(index, value) {
                        var title = value.promotion_title;
                        var id_promotion = value.promotion_id;

                        // img
                        var image   = JSON.parse(value.promotion_img);
                        var img   = image.img;
                        var thumbnail = image.thumbnail;

                        //date
                        var sDate = value.promotion_start_date;
                            sDate = sDate.replace(/-/g,' ');
                        var startDate = new Date(sDate);

                        var endDate  = value.promotion_end_date;
                            endDate = new Date(endDate.replace(/-/g,' '));

                        var mainUpdate = $('#updatePromotion');
                        mainUpdate.find('#promotion-update-title').val(title);
                        mainUpdate.attr('data-id-promotion', id_promotion);

                        $('#promotion-update-start-date').datepicker('update',startDate);
                        $('#promotion-update-end-date').datepicker('update',endDate);

                        CKEDITOR.instances.promotionContentUpdate.setData(value.promotion_content);

                        var items = $('#ListIM_editUS');
                        var caller = $('#iM_editUS');
                          // ktra so luong hinh anh da co
                        caller.hide();
                        var out = null;
                        var html = '
';
                            html += '
';
                            html += '';
                            html += '<input type="hidden" name="user_service_image[]" value=":image">';
                            html += '
';
                            html += '

';
                            html += '
';

                        out = html.replace(':img_thumbnail', thumbnail);
                        out = out.replace(':data-image', img);
                        out = out.replace(':image', img);
                        items.html(out);
                        // del image
                    $('.del_image').on("click", function(){
                        var self = $(this).parent();
                        // self.attr("disabled","disabled");
                        self.remove();

                        // Truong hop dac biet, ktra so luong hinh anh da co
                        var childrens = items.children().length;
                        if(childrens < 5) {
                            caller.fadeIn();
                        }
                    });
                    });
                })
                .always(function() {
                });

                })

        });
    }

    function loadAsidePublish() {
        var html = '';
        $.ajax({
            url: URL + 'spaCMS/promotion/xhrLoad_promotion_publish',
            type: 'post',
            dataType: 'json',
            data: {promotion_state: 1},
        })
        .done(function(respon) {
            if(respon.length > 0){
                $.each(respon, function(index, val) {
                    // img
                    var title   = val.promotion_title;
                    var image   = JSON.parse(val.promotion_img);
                    var img   = image.img;
                    var thumbnail = image.thumbnail;

                    html += '
';
                        html += '
';
                            html += '
';
                                html += '';
                                html += ''+title+'';
                            html += '
';
                            // html += '
';
                                html += '<button class="btn btn-black promotion-items-change-publish" data-promotion-id="'+val.promotion_id+'" title="Tạm ngưng"> </button>';
                            html += '
';
                        // html += '
';

                        html += '
';
                            html += '  ';
                        html += '
';
                    html += '
';
                }); //end each
            }else{
                html +='
 Hiện tại không có quảng cáo nào hiển thị.
';
            }
            $('.promotion-item-publish-wrap').html(html);
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            $('.promotion-items-change-publish').on('click', function(){
                var promotion_id = $(this).attr('data-promotion-id');
                publishPromotion(promotion_id,0);
            });

        });

    }
    // add new promotion
    var addNewPromotion = function() {
        var title = $('#promotion-add-title').val();
        var now = new Date();
            month = now.getMonth()+1;
        var start_day = $('#promotion-add-start-date').val();
            if(start_day.length >0){
                start_day = start_day.substring(6,10)+'-'+start_day.substring(3,5)+'-'+start_day.substring(0,2)+' 00:00:00';
            }else{
                start_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00';
            }

        var end_day = $('#promotion-add-end-date').val();
            if(end_day.length >0){
                end_day = end_day.substring(6,10)+'-'+end_day.substring(3,5)+'-'+end_day.substring(0,2)+' 00:00:00';
            }else{
                end_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00';
            }

        var url_img = "";
        var tagImg  = $('#user_slide_thumbnail');
            if(tagImg[0]){
                var img = tagImg.attr('data-img');
                var thumbnail = tagImg.attr('src');
                url_img={};
                url_img.img = img;
                url_img.thumbnail = thumbnail;
            }else{
                url_img={};
                url_img.img = URL+'/public/assets/img/noimage.jpg';
                url_img.thumbnail = URL+'/public/assets/img/noimage.jpg';
            }

        var content = CKEDITOR.instances.promotionContent.getData();
        var message = $('.promotion-message');
        var jdata = {"title": title, "start_date": start_day, "end_date": end_day, "url_img": JSON.stringify(url_img), "content": content};

        if(title.length<4){
            message.text('Tiêu đề phải hơn 4 kí tự.').fadeIn('fast');
            return false;
        }else{
            $.ajax({
                url: URL + 'spaCMS/promotion/xhrInsert_promotion_item',
                type: 'post',
                dataType: 'json',
                data: jdata,
            })
            .done(function(respon) {
                if(respon === 1){
                    alert('Thêm promotion thành công.')
                }else{
                    alert('Thêm promotion thất bại, bạn vui lòng thử lại.')
                }
            })
            .fail(function() {

            })
            .always(function() {
                loadListPromotion();
                $(".modal").modal('hide');
                refresh();
            });

        }
    }

    //delete Promotion
    var deletePromotion = function(id_promotion) {
        $.ajax({
            url: URL + 'spaCMS/promotion/xhrDelete_promotion_item',
            type: 'post',
            dataType: 'json',
            data: {'id_promotion': id_promotion},
        })
        .done(function(respon) {
            if(respon==0){
                alert('Xóa promotion thất bại, Xin vui lòng kiểm tra lại');
            }
        })
        .fail(function(error) {
            console.log("error: "+error);
        })
        .always(function() {
            loadListPromotion();
            loadAsidePublish();
        });
    }

    var publishPromotion = function(id_promotion,state){
          $.ajax({
            url: URL + 'spaCMS/promotion/xhrPublish_promotion_item',
            type: 'post',
            dataType: 'json',
            data: {'id_promotion': id_promotion, 'state_promotion': state},
        })
        .done(function(respon) {
            if(respon == 0){
                alert('Kích hoạt promotion thất bại, Xin vui lòng kiểm tra lại');
            }
        })
        .fail(function(error) {
            console.log("error: "+error);
        })
        .always(function() {
            loadListPromotion();
            loadAsidePublish()
        });
    }

    // update Promotion
    var updatePromotion = function(){
        var title = $('#promotion-update-title').val();
        var id_promotion = $('#updatePromotion').attr('data-id-promotion');
        var start_day = $('#promotion-update-start-date').val();
        var end_day = $('#promotion-update-end-date').val();
        var now = new Date();
        var month = now.getMonth()+1;
            if( end_day.length >0 ){

                end_day = end_day.substring(6,10)+'-'+end_day.substring(3,5)+'-'+end_day.substring(0,2)+' 00:00:00';
            } else {
                end_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00';
            }

            if( start_day.length >0 ){
                start_day = start_day.substring(6,10)+'-'+start_day.substring(3,5)+'-'+start_day.substring(0,2)+' 00:00:00';
            } else {
                start_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00';
            }

        var url_img = "";
        var tagImg  = $('#user_slide_thumbnail');
            if(tagImg[0]){
                var img = tagImg.attr('data-img');
                var thumbnail = tagImg.attr('src');
                // url_img = '{"img": "'+img+'", "thumbnail": "'+thumbnail+'"}';
                url_img={};
                url_img.img = img;
                url_img.thumbnail = thumbnail;
            }else{
                url_img={};
                url_img.img = URL+'/public/assets/img/noimage.jpg';
                url_img.thumbnail = URL+'/public/assets/img/noimage.jpg';
            }

        var content = CKEDITOR.instances.promotionContentUpdate.getData();
        var message = $('.promotion-message');
        var jdata = {"id_promotion": id_promotion, "title": title, "start_date": start_day, "end_date": end_day, "url_img": JSON.stringify(url_img), "content": content};

        if(title.length<4){
            message.text('Tiêu đề phải hơn 4 kí tự.').fadeIn('fast');
            return false;
        }else{
            $.ajax({
                url: URL + 'spaCMS/promotion/xhrUpdate_promotion_item',
                type: 'post',
                dataType: 'json',
                data: jdata,
            })
            .done(function(respon) {
                if(respon === 1){
                    alert('Cập nhật promotion thành công.')
                }else{
                    alert('Cập nhật promotion thất bại, bạn vui lòng thử lại.')
                }
            })
            .fail(function() {
                console.log("error");
            })
            .always(function() {
                loadListPromotion();
                loadAsidePublish();
                $(".modal").modal('hide');
            });

        }
    }
    // refresh form promotion
    var refresh = function(){
        var frmPromotion = $('#form-promotion');
        frmPromotion.find('input#promotion-add-title').val('');
        frmPromotion.find('input#promotion-add-end-date').val('');
        frmPromotion.find('input#promotion-add-end-date').val('');
        frmPromotion.find('span.promotion-message').fadeOut('fast').text('');
        CKEDITOR.instances.promotionContent.setData('');
          // del image

        var self = $('.del_image').parent();
        self.remove();
        $('#iM_addUS').fadeIn('fast');
    }

    // Image Manager
    var imageManager = function() {

        // Gán thuộc tính cover_id tương ứng
        $('#iM_editUS').click(function(){
            $('#imageManager_saveChange').attr('cover_id','editUS');
        });

        $('#iM_addUS').click(function(){
            $('#imageManager_saveChange').attr('cover_id','addUS');
        });

        //
        $('#imageManager_saveChange').on('click', function(evt) {
            evt.preventDefault();
            // Define position insert to image
            var cover_id = $(this).attr('cover_id');
            // Define selected image
            var radio_checked = $("input:radio[name='iM-radio']:checked"); // Radio checked
            // image and thumbnail_image
            var image = radio_checked.val();
            var thumbnail = radio_checked.attr('data-image');

            // Truong hop dac biet
            if(cover_id == 'addUS') {
                var caller = $('#iM_addUS');
                var items = $('#ListIM_addUS');
            }
            else if(cover_id == 'editUS') {
                var caller = $('#iM_editUS');
                var items = $('#ListIM_editUS');
            }

            // ktra so luong hinh anh da co
            var childrens = items.children().length + 1;
            if(childrens == 1) {
                caller.hide();
            }

            var out = null;
            var html = '
';
                html += '
';
                html += '';
                html += '<input type="hidden" name="user_service_image[]" value=":image">';
                html += '
';
                html += '

';
                html += '
';

            out = html.replace(':img_thumbnail', thumbnail);
            out = out.replace(':data-image', image);
            out = out.replace(':image', image);

            items.html(out);

            // del image
            $('.del_image').on("click", function(){
                var self = $(this).parent();
                // self.attr("disabled","disabled");
                self.remove();

                // Truong hop dac biet, ktra so luong hinh anh da co
                var childrens = items.children().length;
                if(childrens < 1) {
                    caller.fadeIn();
                }
            });

            // Hide Modal
            $("#imageManager_modal").modal('hide');
        });
    }

    return {
        init: function() { loadListPromotion(); loadAsidePublish();},
        addNew: function(){ addNewPromotion(); },
        update: function(){ updatePromotion(); },
        loadImage: function(){ imageManager(); }
    }

    var refresh = function() {
        console.log('refresh');
    }
}();

// function offsetDay(dayStart, dayEnd){
//     var offset = dayEnd.getTime() - dayStart.getTime();
//         console.log(dayEnd.getTime()+'-'+dayStart.getTime());
//     // lấy độ lệch của 2 mốc thời gian, đơn vị tính là millisecond
//     var totalDays = Math.round(offset / 1000 / 60 / 60 / 24);
//     console.log(dayStart.getTime());
//     return totalDays;
// }

redpajama_set_name: RedPajamaGithub


text:
package gamerules

import (
	"math/rand"

	. "github.com/huin/chunkymonkey/types"
)

// The distance from the edge of a block that items spawn at in fractional
// blocks.
const blockItemSpawnFromEdge = 4.0 / PixelsPerBlock

// The interface required of a chunk by block behaviour.
type IChunkBlock interface {
	Rand() *rand.Rand
	ItemType(itemTypeId ItemTypeId) (itemType *ItemType, ok bool)
	AddEntity(s INonPlayerEntity)
	SetBlockByIndex(blockIndex BlockIndex, blockId BlockId, blockData byte)
	TileEntity(blockIndex BlockIndex) ITileEntity
	SetTileEntity(blockIndex BlockIndex, extra ITileEntity)
	AddOnUnsubscribe(entityId EntityId, observer IUnsubscribed)
	RemoveOnUnsubscribe(entityId EntityId, observer IUnsubscribed)

	// AddActiveBlock flags a block in any chunk as active.
	AddActiveBlock(blockXyz *BlockXyz)

	// AddActiveBlockIndex flags a block in the chunk itself as active by index.
	AddActiveBlockIndex(blockIndex BlockIndex)
}

// IUnsubscribed is the interface by which blocks (and potentially other
// things) can register themselves to be called when a player unsubscribes from
// a chunk.
type IUnsubscribed interface {
	Unsubscribed(entityId EntityId)
}

// BlockInstance represents the instance of a block within a chunk. It is used
// to pass context to a IBlockAspect method call. A BlockInstance belongs to
// the chunk that creates it - a copy must be made if a block aspect needs to
// persist the value of one.
type BlockInstance struct {
	Chunk     IChunkBlock
	BlockLoc  BlockXyz
	SubLoc    SubChunkXyz
	Index     BlockIndex
	BlockType *BlockType
	// Note that only the lower nibble of data is stored.
	Data byte
}

// Defines the behaviour of a block.
type IBlockAspect interface {
	setAttrs(blockAttrs *BlockAttrs)

	// Name is currently used purely for the serialization of aspect
	// configuration data.
	Name() string

	// Check tests that the block aspect has been configured correctly,
	// returning nil if it is correct.
	Check() error

	// Hit is called when the player hits a block.
	Hit(instance *BlockInstance, player IPlayerClient, digStatus DigStatus) (destroyed bool)

	// Interact is called when a player right-clicks a block.
	Interact(instance *BlockInstance, player IPlayerClient)

	// InventoryClick is called when the player clicked on a slot inside the
	// inventory for the block (assuming it still has one).
	InventoryClick(instance *BlockInstance, player IPlayerClient, click *Click)

	// InventoryUnsubscribed is called when the player closes the window for the
	// inventory for the block (assuming it still has one).
	InventoryUnsubscribed(instance *BlockInstance, player IPlayerClient)

	// Destroy is called when the block is destroyed by a player hitting it.
	// TODO And in other situations, maybe?
	Destroy(instance *BlockInstance)

	// Tick tells the aspect to run the block for a tick. It should return false
	// if the block should not tick again.
	Tick(instance *BlockInstance) bool
}


text:
import { createSelector } from 'reselect'

import { LEFT, RIGHT } from '../pipettes'
import { selectors as RobotSelectors } from '../robot'
import { getCalibrateLocation } from './selectors'

import type { State } from '../types'
import type { SubnavLocation } from './types'

// TODO(mc, 2019-12-10): i18n
const NO_PIPETTE_SPECIFIED_FOR_THIS_MOUNT =
  'No pipette specified for this mount'
const PIPETTE_IS_NOT_USED_IN_THIS_PROTOCOL =
  'This pipette is not used in this protocol'

export const getCalibratePipettesLocations: State => {|
  left: SubnavLocation,
  right: SubnavLocation,
|} = createSelector(
  getCalibrateLocation,
  RobotSelectors.getPipettes,
  (parentLocation, pipettes) => {
    const makePath = mount => `${parentLocation.path}/pipettes/${mount}`
    const makeDisReason = mount => {
      const pipette = pipettes.find(p => p.mount === mount)
      let disabledReason = null

      if (parentLocation.disabledReason != null) {
        disabledReason = parentLocation.disabledReason
      } else if (!pipette) {
        disabledReason = NO_PIPETTE_SPECIFIED_FOR_THIS_MOUNT
      } else if (pipette.tipRacks.length === 0) {
        disabledReason = PIPETTE_IS_NOT_USED_IN_THIS_PROTOCOL
      }

      return disabledReason
    }

    return {
      left: { path: makePath(LEFT), disabledReason: makeDisReason(LEFT) },
      right: { path: makePath(RIGHT), disabledReason: makeDisReason(RIGHT) },
    }
  }
)


text:
<?php

namespace Kunstmaan\AdminListBundle\Tests\AdminList\FilterType\DBAL;

use Codeception\Test\Unit;
use Kunstmaan\AdminListBundle\AdminList\FilterType\DBAL\BooleanFilterType;
use Kunstmaan\AdminListBundle\Tests\UnitTester;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class BooleanFilterTypeTest
 * @package Tests\Kunstmaan\AdminListBundle\AdminList\FilterType\DBAL
 */
class BooleanFilterTypeTest extends Unit
{
    /**
     * @var UnitTester
     */
    protected $tester;

    /**
     * @var BooleanFilterType
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function _before()
    {
        $this->object = new BooleanFilterType('boolean', 'e');
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    public function testBindRequest()
    {
        $request = new Request(array('filter_value_boolean' => 'true'));

        $data = array();
        $uniqueId = 'boolean';
        $this->object->bindRequest($request, $data, $uniqueId);

        $this->assertEquals(array('value' => 'true'), $data);
    }

    /**
     * @param mixed $value
     *
     * @dataProvider applyDataProvider
     */
    public function testApply($value)
    {
        $qb = $this->tester->getDBALQueryBuilder();
        $qb->select('*')
           ->from('entity', 'e');
        $this->object->setQueryBuilder($qb);
        $this->object->apply(array('value' => $value), 'boolean');

        $this->assertEquals("SELECT * FROM entity e WHERE e.boolean = $value", $qb->getSQL());
    }

    /**
     * @return array
     */
    public static function applyDataProvider()
    {
        return array(
            array('true'),
            array('false'),
        );
    }

    public function testGetTemplate()
    {
        $this->assertEquals('KunstmaanAdminListBundle:FilterType:booleanFilter.html.twig', $this->object->getTemplate());
    }
}


text:
package org.openmhealth.shim.jawbone.mapper;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.testng.annotations.Test;

import java.io.IOException;
import java.time.*;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

// TODO rename. what's "getTimeZone"?
/**
 * @author Chris Schaefbauer
 */
public class JawboneGetTimeZoneUnitTests {

    ObjectMapper objectMapper = new ObjectMapper();

    /* Test JawboneDataPointMapper.parseZone */

    @Test
    public void parseZoneShouldReturnCorrectOlsonTimeZoneId() throws IOException {

        JsonNode testOlsonTimeZoneNode = objectMapper.readTree("\"America/New_York\"");

        ZoneId testZoneId = JawboneDataPointMapper.parseZone(testOlsonTimeZoneNode);
        ZoneId expectedZoneId = ZoneId.of("America/New_York");
        assertThat(testZoneId, equalTo(expectedZoneId));

        OffsetDateTime testOffsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(1438747200), testZoneId);
        OffsetDateTime expectedOffsetDateTime = OffsetDateTime.parse("2015-08-05T00:00:00-04:00");
        assertThat(testOffsetDateTime, equalTo(expectedOffsetDateTime));

    }

    @Test
    public void parseZoneShouldReturnCorrectSecondsOffsetTimeZoneId() throws IOException {

        JsonNode testSecondOffsetTimeZoneNode = objectMapper.readTree("-21600");

        ZoneId testZoneId = JawboneDataPointMapper.parseZone(testSecondOffsetTimeZoneNode);
        ZoneId expectedZoneId = ZoneId.of("-06:00");
        assertThat(testZoneId.getRules(), equalTo(expectedZoneId.getRules()));

        OffsetDateTime testOffsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(1438747200), testZoneId);
        OffsetDateTime expectedOffsetDateTime = OffsetDateTime.parse("2015-08-04T22:00:00-06:00");
        assertThat(testOffsetDateTime, equalTo(expectedOffsetDateTime));

        // Testing fractional for seconds offset
        testSecondOffsetTimeZoneNode = objectMapper.readTree("12600");
        testZoneId = JawboneDataPointMapper.parseZone(testSecondOffsetTimeZoneNode);
        expectedZoneId = ZoneId.of("+03:30");
        assertThat(testZoneId.getRules(), equalTo(expectedZoneId.getRules()));

    }

    @Test
    public void parseZoneShouldReturnCorrectGmtOffsetTimeZoneID() throws IOException {

        JsonNode testGmtOffsetTimeZoneNode = objectMapper.readTree("\"GMT-0600\"");

        ZoneId testZoneId = JawboneDataPointMapper.parseZone(testGmtOffsetTimeZoneNode);
        ZoneId expectedZoneId = ZoneId.of("-06:00");
        assertThat(testZoneId.getRules(), equalTo(expectedZoneId.getRules()));

        OffsetDateTime testOffsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(1438747200), testZoneId);
        OffsetDateTime expectedOffsetDateTime = OffsetDateTime.parse("2015-08-04T22:00:00-06:00");
        assertThat(testOffsetDateTime, equalTo(expectedOffsetDateTime));
    }

    @Test
    public void parseZoneShouldReturnCorrectTimeZoneForFractionalOffsetTimeZones() throws IOException {

        JsonNode fractionalTimeZoneWithName = objectMapper.readTree("\"Asia/Kathmandu\"");

        ZoneId testZoneId = JawboneDataPointMapper.parseZone(fractionalTimeZoneWithName);
        ZoneId expectedZoneId = ZoneId.of("+05:45");
        assertThat(testZoneId.getRules().toString(), equalTo(expectedZoneId.getRules()
                .toString())); //comparing toString because parsing fractional stores a bit more information so the
        // rules don't appear identical

        OffsetDateTime testOffsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(1438747200), testZoneId);
        OffsetDateTime expectedOffsetDateTime = OffsetDateTime.parse("2015-08-05T09:45:00+05:45");
        assertThat(testOffsetDateTime, equalTo(expectedOffsetDateTime));

        JsonNode fractionalTimeZoneWithOffset = objectMapper.readTree("\"GMT+0330\"");
        testZoneId = JawboneDataPointMapper.parseZone(fractionalTimeZoneWithOffset);
        expectedZoneId = ZoneId.of("+03:30");
        assertThat(testZoneId.getRules(), equalTo(expectedZoneId.getRules()));

        testOffsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(1438747200), testZoneId);
        expectedOffsetDateTime = OffsetDateTime.parse("2015-08-05T07:30:00+03:30");
        assertThat(testOffsetDateTime, equalTo(expectedOffsetDateTime));

    }

    /* Test JawboneDataPointMapper.getTimeZoneForTimestamp */

    @Test
    public void getTimeZoneForTimestampShouldReturnCorrectTimeZoneForResponseWithoutTimeZoneList() throws IOException {

        JsonNode testDateTimeNode = objectMapper.readTree("{\n" +
                "\"details\": {\n" +
                "\"tz\": \"GMT-0200\"\n" +
                "},\n" +
                "\"time_created\": 1439990403,\n" +
                "\"time_updated\": 1439867504,\n" +
                "\"time_completed\": 1439994003\n" +
                "}");

        ZoneId timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1439990403L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("-02:00").getRules()));
    }

    @Test
    public void getTimeZoneForTimestampShouldReturnZTimeZoneWhenTimeZoneIsMissing() throws IOException {

        JsonNode testDateTimeNode = objectMapper.readTree("{\n" +
                "\"details\": {\n" +
                "},\n" +
                "\"time_created\": 1439990403,\n" +
                "\"time_updated\": 1439867504,\n" +
                "\"time_completed\": 1439994003\n" +
                "}");

        ZoneId timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1439990403L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("Z").getRules()));
    }

    @Test
    public void getTimeZoneForTimestampShouldReturnZTimeZoneWhenTimeZoneIsNull() throws IOException {

        JsonNode testDateTimeNode = objectMapper.readTree("{\n" +
                "\"details\": {\n" +
                "\"tz\": null\n" +
                "},\n" +
                "\"time_created\": 1439990403,\n" +
                "\"time_updated\": 1439867504,\n" +
                "\"time_completed\": 1439994003\n" +
                "}");

        ZoneId timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1439990403L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("Z").getRules()));
    }

    @Test
    public void getTimeZoneForTimestampShouldReturnCorrectTimeZonesForSingleTimeZoneInList() throws IOException {

        JsonNode testDateTimeNode = objectMapper.readTree("{\n" +
                "\"details\": {\n" +
                "\"tz\": null,\n" +
                "\"tzs\": [\n" +
                "[\n" +
                "1439219760,\n" +
                "\"America/Denver\"\n" +
                "]\n" +
                "]" +
                "},\n" +
                "\"time_created\": 1439990403,\n" +
                "\"time_updated\": 1439867504,\n" +
                "\"time_completed\": 1439994003\n" +
                "}");

        ZoneId timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1439990403L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("America/Denver").getRules()));

        OffsetDateTime testOffsetDateTime = OffsetDateTime.of(2015, 07, 25, 8, 20, 00, 00,
                timeZoneForTimestamp.getRules().getOffset(LocalDateTime.of(2015, 07, 25, 8, 20)));
        assertThat(testOffsetDateTime, equalTo(OffsetDateTime.parse("2015-07-25T08:20:00-06:00")));

    }

    @Test
    public void getTimeZoneForTimestampShouldReturnCorrectTimeZonesForMultipleTimeZones() throws IOException {

        JsonNode testDateTimeNode = objectMapper.readTree("{\n" +
                "\"details\": {\n" +
                "\"tz\": null,\n" +
                "\"tzs\": [\n" +
                "[\n" +
                "1439219760,\n" +
                "\"America/Denver\"\n" +
                "],\n" +
                "[\n" +
                "1439494003,\n" +
                "\"America/Los_Angeles\"\n" +
                "],\n" +
                "[\n" +
                "1439994003,\n" +
                "\"Pacific/Honolulu\"\n" +
                "]\n" +
                "]" +
                "},\n" +
                "\"time_created\": 1439990403,\n" +
                "\"time_updated\": 1439867504,\n" +
                "\"time_completed\": 1439994003\n" +
                "}");

        // Testing early time after first time zone, but before second
        ZoneId timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1439221760L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("America/Denver").getRules()));

        OffsetDateTime testOffsetDateTime = OffsetDateTime.of(2015, 07, 25, 8, 20, 00, 00,
                timeZoneForTimestamp.getRules().getOffset(LocalDateTime.of(2015, 07, 25, 8, 20)));
        assertThat(testOffsetDateTime, equalTo(OffsetDateTime.parse("2015-07-25T08:20:00-06:00")));

        //Testing time equal to last timezone change
        timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1439994003L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("Pacific/Honolulu").getRules()));

        testOffsetDateTime = OffsetDateTime.of(2015, 07, 25, 8, 20, 00, 00,
                timeZoneForTimestamp.getRules().getOffset(LocalDateTime.of(2015, 07, 25, 8, 20)));
        assertThat(testOffsetDateTime, equalTo(OffsetDateTime.parse("2015-07-25T08:20:00-10:00")));

        //Testing time after last timezone change
        timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1440004003L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("Pacific/Honolulu").getRules()));

        testOffsetDateTime = OffsetDateTime.of(2015, 07, 25, 8, 20, 00, 00,
                timeZoneForTimestamp.getRules().getOffset(LocalDateTime.of(2015, 07, 25, 8, 20)));
        assertThat(testOffsetDateTime, equalTo(OffsetDateTime.parse("2015-07-25T08:20:00-10:00")));

        //Testing time between second and last timezone
        timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1439894003L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("America/Los_Angeles").getRules()));

        testOffsetDateTime = OffsetDateTime.of(2015, 07, 25, 8, 20, 00, 00,
                timeZoneForTimestamp.getRules().getOffset(LocalDateTime.of(2015, 07, 25, 8, 20)));
        assertThat(testOffsetDateTime, equalTo(OffsetDateTime.parse("2015-07-25T08:20:00-07:00")));

    }

    @Test
    public void getTimeZoneForTimestampShouldReturnCorrectTimeZoneBehaviorForDaylightSavings() throws IOException {

        JsonNode testDateTimeNode = objectMapper.readTree("{\n" +
                "\"details\": {\n" +
                "\"tz\": null,\n" +
                "\"tzs\": [\n" +
                "[\n" +
                "1425796620,\n" +
                "\"America/Denver\"\n" +
                "]\n" +
                "]" +
                "},\n" +
                "\"time_created\": 1425796620,\n" +
                "\"time_updated\": 1439867504,\n" +
                "\"time_completed\": 1425845420\n" +
                "}");

        ZoneId timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1425798620L);
        assertThat(timeZoneForTimestamp.getRules(), equalTo(ZoneId.of("America/Denver").getRules()));
        assertThat(timeZoneForTimestamp.getRules().getOffset(Instant.ofEpochSecond(1425798620)), equalTo(ZoneOffset.of(
                "-07:00")));
        OffsetDateTime testOffsetDateTime =
                OffsetDateTime.ofInstant(Instant.ofEpochSecond(1425796620), timeZoneForTimestamp);
        OffsetDateTime expectedDateTime = OffsetDateTime.parse("2015-03-07T23:37:00-07:00");
        assertThat(testOffsetDateTime, equalTo(expectedDateTime));

        timeZoneForTimestamp = JawboneDataPointMapper.getTimeZoneForTimestamp(testDateTimeNode, 1425845420L);
        assertThat(timeZoneForTimestamp.getRules().getOffset(Instant.ofEpochSecond(1425845420)),
                equalTo(ZoneOffset.of("-06:00")));

        testOffsetDateTime =
                OffsetDateTime.ofInstant(Instant.ofEpochSecond(1425845420), timeZoneForTimestamp);
        expectedDateTime = OffsetDateTime.parse("2015-03-08T14:10:20-06:00");
        assertThat(testOffsetDateTime, equalTo(expectedDateTime));

    }

}


text:
package com.github.gwtmaterialdesign.client.application.sidenavmini;

import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewImpl;

import javax.inject.Inject;

public class MiniSideNavView extends ViewImpl implements MiniSideNavPresenter.MyView {
    interface Binder extends UiBinder<Widget, MiniSideNavView> {
    }

    @Inject
    MiniSideNavView(Binder uiBinder) {
        initWidget(uiBinder.createAndBindUi(this));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".ui.activity.multifragments.MultiFragmentsActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/MyTheme.AppBarOverlay">

        <!--<android.support.v7.widget.Toolbar-->
        <!--android:id="@+id/toolbar"-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="?attr/actionBarSize"-->
        <!--android:layout_weight="1"-->
        <!--android:background="?attr/colorPrimary"-->
        <!--app:layout_scrollFlags="scroll|enterAlways"-->
        <!--app:popupTheme="@style/MyTheme.PopupOverlay"-->
        <!--app:title="@string/app_name">-->

        <!--</android.support.v7.widget.Toolbar>-->

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.google.android.material.appbar.AppBarLayout>

    <TextView
        android:id="@+id/under_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="under flow"
        android:textColor="@color/cpb_red"
        android:textSize="22sp"
        android:textStyle="bold" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/transparent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
<!DOCTYPE HTML>

<title>喵了个咪</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<php>print_r($data);</php>


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="description" content="About The Liner Shipping Game " />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Alice</title>
    <link
      type="text/css"
      rel="stylesheet"
      href="styles/fonts.css"
      media="screen"
    />
    <link href="styles/material.cyan-deep_orange.min.css" rel="stylesheet" />
    <link
      rel="stylesheet"
      href="styles/custom.css"
      type="text/css"
      media="screen"
    />
    <link
      rel="stylesheet"
      href="styles/font-awesome.css"
      type="text/css"
      media="screen"
    />
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css" />

Alice

Incident or Request?

                        Every interaction between a customer and a supplier is
                        either an incident or a request, and Alice figures it
                        out automatically! Alice then figures out what service
                        desk should handle the given ticket.

It's Polyglot!

                        Alice reads, classifies, and routes any text in any
                        language. Well, almost. Alice supports no less than 22
                        different languages.

It's Service-minded

                        Alice runs using web services. It means that is can be
                        integrated with ServiceNow without impacting the
                        performance or memory requirements of your ServiceNow
                        implementation.

It needs training!

                        Alice needs a set of messages or tickets as well as
                        information on how they were categorised or routed. Once
                        trained, it suits your specific purposes. With 4,000
                        entries, it is about 70% correct. With 8,000 entries, it
                        gets about 80% right.

How does it work?

                        Alice takes all of your previous tickets, reads their
                        descriptions and creates a Machine Learning model. But
                        it's clever! It reads the sentences, delineates them and
                        then feeds the model with the most important
                        information. It make Alice better than the others.

Under the hood

                        The engine of Alice is composed of Tensorflow, Python,
                        NLTK, Linear SVM, React, Flask, Docker and NoSQL. The
                        fuel is the tickets that have been filed in the past.


text:
#region License

#endregion

using System;

namespace ObjectGL.Api.Context
{
    public struct StencilOperationSettings : IEquatable<StencilOperationSettings>
    {
        public StencilOp StencilFail;
        public StencilOp DepthFail;
        public StencilOp DepthPass;

        public bool Equals(StencilOperationSettings other)
        {
            return StencilFail == other.StencilFail && DepthFail == other.DepthFail && DepthPass == other.DepthPass;
        }

        public override bool Equals(object obj)
        {
            return obj is StencilOperationSettings && Equals((StencilOperationSettings)obj);
        }

        public override int GetHashCode()
        {
            return (int)StencilFail ^ ((int)DepthFail << 8) ^ ((int)DepthPass << 16);
        }

        public override string ToString()
        {
            return string.Format("[SFail: {0}; DFail: {1}; DPass: {2}]", StencilFail, DepthFail, DepthPass);
        }
    }
}


text:
![Logo](bankochip.jpg)

Tools and toys for Big Banko processing

[![Build Status](https://travis-ci.org/diku-dk/openbanko.svg?branch=master)](https://travis-ci.org/diku-dk/openbanko)

## Bankopladeformat

The specification for banko cards: [bankopladeformat.md](bankopladeformat.md)

## Utilities

+ [bankoconv](bankoconv): Convert between banko formats
+ [bankopak](bankopak): Compress and decompress banko boards
+ [bankopladeformat](bankopladeformat): Perform miscellaneous
  operations on banko cards in the bankopladeformat format
+ [bankoviser](bankoviser): Interact with banko boards in the terminal
+ [barc](barc): Check if boards are valid banko boards -- also
  generalizes to other games through a DSL
+ [cbankosim](cbankosim/): Automatically simulate playing banko
+ [futbankosim](futbankosim/): GPU-accelerated massively parallel banko simulation

## Citation

If you use any of this code for research, please cite it as:

    @Misc{bigbanko,
      author =   {Henriksen, Troels; Fuck, Brain; Serup, Niels Gustav Westphal},
      title =    {Big Banko},
      institution = {EggsML}
      year = {2015--2018}
    }

## In case of addiction

The OpenBanko project recognises that gambling can be a significant
harmful influence.  If you find that your quality of life is
negatively impacted by banko, please seek help immediately.  Danes can
inquire at [Ludomanilinjen](http://www.ludomanilinjen.dk/).


text:
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'

# import class that derives itself from the step mountpoint.
from mapclientplugins.mocapdataviewerstep import step


text:
import { toArray, debounce as _debounce } from '../util/index'
import { orderBy, filterBy, limitBy } from './array-filters'
const digitsRE = /(\d{3})(?=\d)/g

// asset collections must be a plain object.
export default {

  orderBy,
  filterBy,
  limitBy,

  /**
   * Stringify value.
   *
   * @param {Number} indent
   */

  json: {
    read: function (value, indent) {
      return typeof value === 'string'
        ? value
        : JSON.stringify(value, null, arguments.length > 1 ? indent : 2)
    },
    write: function (value) {
      try {
        return JSON.parse(value)
      } catch (e) {
        return value
      }
    }
  },

  /**
   * 'abc' => 'Abc'
   */

  capitalize (value) {
    if (!value && value !== 0) return ''
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)
  },

  /**
   * 'abc' => 'ABC'
   */

  uppercase (value) {
    return (value || value === 0)
      ? value.toString().toUpperCase()
      : ''
  },

  /**
   * 'AbC' => 'abc'
   */

  lowercase (value) {
    return (value || value === 0)
      ? value.toString().toLowerCase()
      : ''
  },

  /**
   * 12345 => $12,345.00
   *
   * @param {String} sign
   * @param {Number} decimals Decimal places
   */

  currency (value, currency, decimals) {
    value = parseFloat(value)
    if (!isFinite(value) || (!value && value !== 0)) return ''
    currency = currency != null ? currency : '$'
    decimals = decimals != null ? decimals : 2
    var stringified = Math.abs(value).toFixed(decimals)
    var _int = decimals
      ? stringified.slice(0, -1 - decimals)
      : stringified
    var i = _int.length % 3
    var head = i > 0
      ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
      : ''
    var _float = decimals
      ? stringified.slice(-1 - decimals)
      : ''
    var sign = value < 0 ? '-' : ''
    return sign + currency + head +
      _int.slice(i).replace(digitsRE, '$1,') +
      _float
  },

  /**
   * 'item' => 'items'
   *
   * @params
   *  an array of strings corresponding to
   *  the single, double, triple ... forms of the word to
   *  be pluralized. When the number to be pluralized
   *  exceeds the length of the args, it will use the last
   *  entry in the array.
   *
   *  e.g. ['single', 'double', 'triple', 'multiple']
   */

  pluralize (value) {
    var args = toArray(arguments, 1)
    return args.length > 1
      ? (args[value % 10 - 1] || args[args.length - 1])
      : (args[0] + (value === 1 ? '' : 's'))
  },

  /**
   * Debounce a handler function.
   *
   * @param {Function} handler
   * @param {Number} delay = 300
   * @return {Function}
   */

  debounce (handler, delay) {
    if (!handler) return
    if (!delay) {
      delay = 300
    }
    return _debounce(handler, delay)
  }
}


text:
<?php

namespace Google\Service\DLP;

class GooglePrivacyDlpV2BigQueryTable extends \Google\Model
{
  /**
   * @var string
   */
  public $datasetId;
  /**
   * @var string
   */
  public $projectId;
  /**
   * @var string
   */
  public $tableId;

  /**
   * @param string
   */
  public function setDatasetId($datasetId)
  {
    $this->datasetId = $datasetId;
  }
  /**
   * @return string
   */
  public function getDatasetId()
  {
    return $this->datasetId;
  }
  /**
   * @param string
   */
  public function setProjectId($projectId)
  {
    $this->projectId = $projectId;
  }
  /**
   * @return string
   */
  public function getProjectId()
  {
    return $this->projectId;
  }
  /**
   * @param string
   */
  public function setTableId($tableId)
  {
    $this->tableId = $tableId;
  }
  /**
   * @return string
   */
  public function getTableId()
  {
    return $this->tableId;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GooglePrivacyDlpV2BigQueryTable::class, 'Google_Service_DLP_GooglePrivacyDlpV2BigQueryTable');


text:
package com.memory.platform.core.aop;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.memory.platform.common.util.ConvertUtils;
import com.memory.platform.core.springmvc.WebContextUtils;
import com.memory.platform.modules.system.base.model.SystemUser;

/**
 * Hiberate拦截器:实现创建人,创建时间,创建人名称自动注入;
 *                修改人,修改时间,修改人名自动注入;
 * @author
 */
@Component
public class HiberateAspect extends EmptyInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(HiberateAspect.class);
	private static final long serialVersionUID = 1L;

public boolean onSave(Object entity, Serializable id, Object[] state,
		String[] propertyNames, Type[] types) {
	SystemUser currentUser = null;
	try {
		currentUser = WebContextUtils.getSessionUser();
	} catch (RuntimeException e) {
		logger.warn("当前session为空,无法获取用户");
	}
	if(currentUser==null){
		return true;
	}
	try {
		//添加数据
		 for (int index=0;index<propertyNames.length;index++)
		 {
		     /*找到名为"创建时间"的属性*/
		     if ("createDate".equals(propertyNames[index]))
		     {
		         /*使用拦截器将对象的"创建时间"属性赋上值*/
		    	 if(ConvertUtils.isEmpty(state[index])){
		    		 state[index] = new Date();
		    	 }
		         continue;
		     }
		     /*找到名为"创建人"的属性*/
		     else if ("createBy".equals(propertyNames[index]))
		     {
		         /*使用拦截器将对象的"创建人"属性赋上值*/
		    	 if(ConvertUtils.isEmpty(state[index])){
		    		  state[index] = currentUser.getLoginName();
		    	 }
		         continue;
		     }
		     /*找到名为"创建人名称"的属性*/
		     else if ("createName".equals(propertyNames[index]))
		     {
		         /*使用拦截器将对象的"创建人名称"属性赋上值*/
		    	 if(ConvertUtils.isEmpty(state[index])){
		    		 state[index] = currentUser.getName();
		    	 }
		         continue;
		     }
		 }
	} catch (RuntimeException e) {
		e.printStackTrace();
	}
	 return true;
}

public boolean onFlushDirty(Object entity, Serializable id,
		Object[] currentState, Object[] previousState,
		String[] propertyNames, Type[] types) {
	SystemUser currentUser = null;
	try {
		currentUser = WebContextUtils.getSessionUser();
	} catch (RuntimeException e1) {
		logger.warn("当前session为空,无法获取用户");
	}
	if(currentUser==null){
		return true;
	}
	//添加数据
     for (int index=0;index<propertyNames.length;index++)
     {
         /*找到名为"修改时间"的属性*/
         if ("updateDate".equals(propertyNames[index]))
         {
             /*使用拦截器将对象的"修改时间"属性赋上值*/
        	 currentState[index] = new Date();
             continue;
         }
         /*找到名为"修改人"的属性*/
         else if ("updateBy".equals(propertyNames[index]))
         {
             /*使用拦截器将对象的"修改人"属性赋上值*/
        	 currentState[index] = currentUser.getLoginName();
        	 continue;
         }
         /*找到名为"修改人名称"的属性*/
         else if ("updateName".equals(propertyNames[index]))
         {
             /*使用拦截器将对象的"修改人名称"属性赋上值*/
        	 currentState[index] = currentUser.getName();
        	 continue;
         }
     }
	 return true;
}
}


text:
class RailsInfo::Logs::Test::RspecPresenter < ::RailsInfo::Presenter
  def initialize(subject, options = {})
    super(subject, options)

    @rails_info_log = ::RailsInfo::Logs::Test::Rspec.new(
      log: options[:log], debug: options[:debug]
    )
  end

  def summary
    text = ["#{@rails_info_log.number_of_files} files"]
    text << @rails_info_log.summary unless @rails_info_log.summary.blank?

    content_tag :p, text.join(', ')
  end

  def accordion
    @index = 0

    if @rails_info_log.hash.is_a?(Hash)
      content_tag :div, id: 'files', class: 'accordions' do
        html = ''

        @rails_info_log.hash.each do |file, examples|
          file_presenter = ::RailsInfo::Logs::Test::Rspec::FilePresenter.new(
            @subject, name: "#{file} (#{examples.length})",
            tabs_data: examples, index: @index, rails_root: @rails_info_log.rails_root
          )
          @index += 1
          html += raw file_presenter.tabs
        end

        raw html
      end
    else
      content_tag :pre, @rails_info_log.hash.join("\n")
    end
  end
end


text:
<?php

namespace Frontend\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="school")
 */
class School {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=false)
     */
    protected $school_name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $description;

    /**
     * @ORM\Column(type="object")
     */
    protected $body;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $slug;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set school_name
     *
     * @param string $schoolName
     * @return School
     */
    public function setSchoolName($schoolName)
    {
        $this->school_name = $schoolName;

        return $this;
    }

    /**
     * Get school_name
     *
     * @return string
     */
    public function getSchoolName()
    {
        return $this->school_name;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return School
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set body
     *
     * @param \stdClass $body
     * @return School
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

    /**
     * Get body
     *
     * @return \stdClass
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Set slug
     *
     * @param string $slug
     * @return School
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }
}


text:
require 'spec_helper'
require 'mcollective/validator/length_validator'

module MCollective
  module Validator
    describe "#validate" do
      it "should raise an exception if the given string's length is greater than the given value" do
        expect{
          LengthValidator.validate("test", 3)
        }.to raise_error(ValidatorError, "Input string is longer than 3 character(s)")
      end

      it "should not raise an exception if the given string's length is less than the given value" do
        LengthValidator.validate("test", 4)
      end
    end
  end
end


text:
<?php

namespace Frontend\Modules\Blog\Widgets;

use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget;
use Frontend\Modules\Blog\Engine\Model as FrontendBlogModel;

/**
 * This is a widget with the link to the archive
 */
class Archive extends FrontendBaseWidget
{
    public function execute(): void
    {
        parent::execute();
        $this->loadTemplate();
        $this->parse();
    }

    private function parse(): void
    {
        $this->template->assign('widgetBlogArchive', FrontendBlogModel::getArchiveNumbers());
    }
}


text:
@interface ViewControls : NSObject
{
	IBOutlet NSView * view;
}

- (NSView *) view;
- (NSString *) title;

@end


text:
import { showInvitePlayerModal } from '../actions/AppActions'
import { fetchLeague } from '../actions/LeagueActions';
import LeagueDetail from '../components/LeagueDetail';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getLeague } from '../reducers/LeaguesReducer';

export class LeagueDetailContainer extends Component {
  componentDidMount() {
    this.props.fetchLeague(this.props.params.leagueId);
  }

  render() {
    return (
      <LeagueDetail
        league={ this.props.league }
        isLoading={ !this.props.league }
        showInvitePlayerModal={ this.props.showInvitePlayerModal }
      />
    );
  }
}

const mapStateToProps = (state, props) => ({
  league: getLeague(state, props.params.leagueId)
});

const mapDispatchToProps = {
  fetchLeague,
  showInvitePlayerModal
};

export default connect(mapStateToProps, mapDispatchToProps)(LeagueDetailContainer);


text:
.class public final Landroid/media/videoeditor/MediaProperties$H264Profile;
.super Ljava/lang/Object;
.source "MediaProperties.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/videoeditor/MediaProperties;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x11
    name = "H264Profile"
.end annotation

# static fields
.field public static final H264ProfileBaseline:I = 0x1

.field public static final H264ProfileExtended:I = 0x4

.field public static final H264ProfileHigh:I = 0x8

.field public static final H264ProfileHigh10:I = 0x10

.field public static final H264ProfileHigh422:I = 0x20

.field public static final H264ProfileHigh444:I = 0x40

.field public static final H264ProfileMain:I = 0x2

.field public static final H264ProfileUnknown:I = 0x7fffffff

# instance fields
.field final synthetic this$0:Landroid/media/videoeditor/MediaProperties;

# direct methods
.method public constructor <init>(Landroid/media/videoeditor/MediaProperties;)V
    .locals 0
    .parameter

    .prologue
    .line 153
    iput-object p1, p0, Landroid/media/videoeditor/MediaProperties$H264Profile;->this$0:Landroid/media/videoeditor/MediaProperties;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
package org.apache.cassandra.service.disk.usage;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.config.CassandraRelevantProperties;
import org.apache.cassandra.config.DataStorageSpec;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Directories;
import org.apache.cassandra.db.Memtable;
import org.apache.cassandra.db.guardrails.Guardrails;
import org.apache.cassandra.db.guardrails.GuardrailsConfig;
import org.apache.cassandra.io.util.FileUtils;

/**
 * Schedule periodic task to monitor local disk usage and notify {@link DiskUsageBroadcaster} if local state changed.
 */
public class DiskUsageMonitor
{
    private static final Logger logger = LoggerFactory.getLogger(DiskUsageMonitor.class);

    public static DiskUsageMonitor instance = new DiskUsageMonitor();

    private final Supplier<GuardrailsConfig> guardrailsConfigSupplier = () -> Guardrails.CONFIG_PROVIDER.getOrCreate(null);
    private final Supplier<Multimap<FileStore, Directories.DataDirectory>> dataDirectoriesSupplier;

    private volatile DiskUsageState localState = DiskUsageState.NOT_AVAILABLE;

    @VisibleForTesting
    public DiskUsageMonitor()
    {
        this.dataDirectoriesSupplier = DiskUsageMonitor::dataDirectoriesGroupedByFileStore;
    }

    @VisibleForTesting
    public DiskUsageMonitor(Supplier<Multimap<FileStore, Directories.DataDirectory>> dataDirectoriesSupplier)
    {
        this.dataDirectoriesSupplier = dataDirectoriesSupplier;
    }

    /**
     * Start monitoring local disk usage and call notifier when local disk usage state changed.
     */
    public void start(Consumer<DiskUsageState> notifier)
    {
        // start the scheduler regardless guardrail is enabled, so we can enable it later without a restart
        ScheduledExecutors.scheduledTasks.scheduleAtFixedRate(() -> {

            if (!Guardrails.localDataDiskUsage.enabled(null))
                return;

            updateLocalState(getDiskUsage(), notifier);
        }, 0, CassandraRelevantProperties.DISK_USAGE_MONITOR_INTERVAL_MS.getLong(), TimeUnit.MILLISECONDS);
    }

    @VisibleForTesting
    public void updateLocalState(double usageRatio, Consumer<DiskUsageState> notifier)
    {
        double percentage = usageRatio * 100;
        long percentageCeiling = (long) Math.ceil(percentage);

        DiskUsageState state = getState(percentageCeiling);

        Guardrails.localDataDiskUsage.guard(percentageCeiling, state.toString(), false, null);

        // if state remains unchanged, no need to notify peers
        if (state == localState)
            return;

        localState = state;
        notifier.accept(state);
    }

    /**
     * @return local node disk usage state
     */
    @VisibleForTesting
    public DiskUsageState state()
    {
        return localState;
    }

    /**
     * @return The current disk usage (including all memtable sizes) ratio. This is the ratio between the space taken by
     * all the data directories and the addition of that same space and the free available space on disk. The space
     * taken by the data directories is the addition of the actual space on disk plus the size of the memtables.
     * Memtables are included in that calculation because they are expected to be eventually flushed to disk.
     */
    @VisibleForTesting
    public double getDiskUsage()
    {
        // using BigInteger to handle large file system
        BigInteger used = BigInteger.ZERO; // space used by data directories
        BigInteger usable = BigInteger.ZERO; // free space on disks

        for (Map.Entry<FileStore, Collection<Directories.DataDirectory>> e : dataDirectoriesSupplier.get().asMap().entrySet())
        {
            usable = usable.add(BigInteger.valueOf(usableSpace(e.getKey())));

            for (Directories.DataDirectory dir : e.getValue())
                used = used.add(BigInteger.valueOf(dir.getRawSize()));
        }

        // The total disk size for data directories is the space that is actually used by those directories plus the
        // free space on disk that might be used for storing those directories in the future.
        BigInteger total = used.add(usable);

        // That total space can be limited by the config property data_disk_usage_max_disk_size.
        DataStorageSpec diskUsageMaxSize = guardrailsConfigSupplier.get().getDataDiskUsageMaxDiskSize();
        if (diskUsageMaxSize != null)
            total = total.min(BigInteger.valueOf(diskUsageMaxSize.toBytes()));

        // Add memtables size to the amount of used space because those memtables will be flushed to data directories.
        used = used.add(BigInteger.valueOf(getAllMemtableSize()));

        if (logger.isTraceEnabled())
            logger.trace("Disk Usage Guardrail: current disk usage = {}, total disk usage = {}.",
                         FileUtils.stringifyFileSize(used.doubleValue()),
                         FileUtils.stringifyFileSize(total.doubleValue()));

        return new BigDecimal(used).divide(new BigDecimal(total), 5, RoundingMode.UP).doubleValue();
    }

    @VisibleForTesting
    public long getAllMemtableSize()
    {
        long size = 0;

        for (ColumnFamilyStore cfs : ColumnFamilyStore.all())
        {
            for (Memtable memtable : cfs.getTracker().getView().getAllMemtables())
            {
                size += memtable.getLiveDataSize();
            }
        }

        return size;
    }

    @VisibleForTesting
    public DiskUsageState getState(long usagePercentage)
    {
        if (!Guardrails.localDataDiskUsage.enabled())
            return DiskUsageState.NOT_AVAILABLE;

        if (Guardrails.localDataDiskUsage.failsOn(usagePercentage, null))
            return DiskUsageState.FULL;

        if (Guardrails.localDataDiskUsage.warnsOn(usagePercentage, null))
            return DiskUsageState.STUFFED;

        return DiskUsageState.SPACIOUS;
    }

    private static Multimap<FileStore, Directories.DataDirectory> dataDirectoriesGroupedByFileStore()
    {
        Multimap<FileStore, Directories.DataDirectory> directories = HashMultimap.create();
        try
        {
            for (Directories.DataDirectory dir : Directories.dataDirectories.getAllDirectories())
            {
                FileStore store = Files.getFileStore(dir.location.toPath());
                directories.put(store, dir);
            }
        }
        catch (IOException e)
        {
            throw new RuntimeException("Cannot get data directories grouped by file store", e);
        }
        return directories;
    }

    public static long totalDiskSpace()
    {
        BigInteger size = dataDirectoriesGroupedByFileStore().keys()
                                                             .stream()
                                                             .map(DiskUsageMonitor::totalSpace)
                                                             .map(BigInteger::valueOf)
                                                             .reduce(BigInteger.ZERO, BigInteger::add);

        return size.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) >= 0
               ? Long.MAX_VALUE
               : size.longValue();
    }

    public static long totalSpace(FileStore store)
    {
        try
        {
            long size = store.getTotalSpace();
            return size < 0 ? Long.MAX_VALUE : size;
        }
        catch (IOException e)
        {
            throw new RuntimeException("Cannot get total space of file store", e);
        }
    }

    public static long usableSpace(FileStore store)
    {
        try
        {
            long size = store.getUsableSpace();
            return size < 0 ? Long.MAX_VALUE : size;
        }
        catch (IOException e)
        {
            throw new RuntimeException("Cannot get usable size of file store", e);
        }
    }
}


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

#pragma once

#include <carve/carve.hpp>
#include <carve/collection_types.hpp>
#include <carve/iobj.hpp>

namespace carve {
namespace csg {

/**
 * \class Intersections
 * \brief Storage for computed intersections between vertices, edges and faces.
 *
 */
struct Intersections
    : public std::unordered_map<IObj, IObjVMapSmall, IObj_hash> {
  typedef carve::mesh::MeshSet<3>::vertex_t vertex_t;
  typedef carve::mesh::MeshSet<3>::edge_t edge_t;
  typedef carve::mesh::MeshSet<3>::face_t face_t;

  typedef std::unordered_map<IObj, IObjVMapSmall, IObj_hash> super;

  ~Intersections() {}

  /**
   * \brief Record the position of intersection between a pair of intersection
   * objects.
   *
   * @param a The first intersecting object.
   * @param b The second intersecting object.
   * @param p The point of intersection.
   */
  void record(IObj a, IObj b, vertex_t* p) {
    if (a > b) {
      std::swap(a, b);
    }
    (*this)[a][b] = p;
    (*this)[b][a] = p;
  }

  /**
   * \brief Test whether vertex \a v intersects face \a f.
   *
   * @param v The vertex to test.
   * @param f The face to test.
   *
   * @return true, if \a v intersects \a f.
   */
  bool intersectsFace(vertex_t* v, face_t* f) const;

  /**
   * \brief Collect sets of vertices, edges and faces that intersect \a obj
   *
   * @param[in] obj The intersection object to search for intersections.
   * @param[out] collect_v A vector of vertices intersecting \a obj.
   * @param[out] collect_e A vector of edges intersecting \a obj.
   * @param[out] collect_f A vector of faces intersecting \a obj.
   */
  void collect(const IObj& obj, std::vector<vertex_t*>* collect_v,
               std::vector<edge_t*>* collect_e,
               std::vector<face_t*>* collect_f) const;

  /**
   * \brief Determine whether two intersection objects intersect.
   *
   * @param a The first intersection object.
   * @param b The second intersection object.
   *
   * @return true, if \a a and \a b intersect.
   */
  bool intersectsExactly(const IObj& a, const IObj& b) {
    Intersections::const_iterator i = find(a);
    if (i == end()) {
      return false;
    }
    return i->second.find(b) != i->second.end();
  }

  /**
   * \brief Determine whether an intersection object intersects a vertex.
   *
   * @param a The intersection object.
   * @param v The vertex.
   *
   * @return true, if \a a and \a v intersect.
   */
  bool intersects(const IObj& a, vertex_t* v) {
    Intersections::const_iterator i = find(a);
    if (i == end()) {
      return false;
    }
    if (i->second.find(v) != i->second.end()) {
      return true;
    }
    return false;
  }

  /**
   * \brief Determine whether an intersection object intersects an edge.
   *
   * @param a The intersection object.
   * @param e The edge.
   *
   * @return true, if \a a and \a e intersect (either on the edge,
   *         or at either endpoint).
   */
  bool intersects(const IObj& a, edge_t* e) {
    Intersections::const_iterator i = find(a);
    if (i == end()) {
      return false;
    }
    for (super::mapped_type::const_iterator j = i->second.begin();
         j != i->second.end(); ++j) {
      const IObj& obj = j->first;
      switch (obj.obtype) {
        case IObj::OBTYPE_VERTEX:
          if (obj.vertex == e->v1() || obj.vertex == e->v2()) {
            return true;
          }
          break;
        case IObj::OBTYPE_EDGE:
          if (obj.edge == e) {
            return true;
          }
          break;
        default:
          break;
      }
    }
    return false;
  }

  /**
   * \brief Determine whether an intersection object intersects a face.
   *
   * @param a The intersection object.
   * @param f The face.
   *
   * @return true, if \a a and \a f intersect (either on the face,
   *         or at any associated edge or vertex).
   */
  bool intersects(const IObj& a, face_t* f) {
    Intersections::const_iterator i = find(a);
    if (i == end()) {
      return false;
    }
    if (i->second.find(f) != i->second.end()) {
      return true;
    }
    edge_t* e = f->edge;
    do {
      if (i->second.find(e) != i->second.end()) {
        return true;
      }
      if (i->second.find(e->vert) != i->second.end()) {
        return true;
      }
      e = e->next;
    } while (e != f->edge);
    return false;
  }

  /**
   * \brief Determine whether an edge intersects another edge.
   *
   * @param e The edge.
   * @param f The face.
   *
   * @return true, if \a e and \a f intersect.
   */
  bool intersects(edge_t* e1, edge_t* e2) {
    if (intersects(e1->v1(), e2) || intersects(e1->v2(), e2) ||
        intersects(IObj(e1), e2)) {
      return true;
    }
    return false;
  }

  /**
   * \brief Determine whether an edge intersects a face.
   *
   * @param e The edge.
   * @param f The face.
   *
   * @return true, if \a e and \a f intersect.
   */
  bool intersects(edge_t* e, face_t* f) {
    if (intersects(e->v1(), f) || intersects(e->v2(), f) ||
        intersects(IObj(e), f)) {
      return true;
    }
    return false;
  }

  /**
   * \brief Determine the faces intersected by an edge.
   *
   * @tparam face_set_t A collection type holding face_t *
   * @param[in] e The edge.
   * @param[out] f The resulting set of faces.
   */
  template <typename face_set_t>
  void intersectedFaces(edge_t* e, face_set_t& f) const {
    std::vector<face_t*> intersected_faces;
    std::vector<edge_t*> intersected_edges;
    std::vector<vertex_t*> intersected_vertices;

    collect(e, &intersected_vertices, &intersected_edges, &intersected_faces);

    for (unsigned i = 0; i < intersected_vertices.size(); ++i) {
      facesForVertex(intersected_vertices[i], f);
    }
    for (unsigned i = 0; i < intersected_edges.size(); ++i) {
      facesForEdge(intersected_edges[i], f);
    }
    f.insert(intersected_faces.begin(), intersected_faces.end());
  }

  /**
   * \brief Determine the faces intersected by a vertex.
   *
   * @tparam face_set_t A collection type holding face_t *
   * @param[in] v The vertex.
   * @param[out] f The resulting set of faces.
   */
  template <typename face_set_t>
  void intersectedFaces(vertex_t* v, face_set_t& f) const {
    std::vector<face_t*> intersected_faces;
    std::vector<edge_t*> intersected_edges;
    std::vector<vertex_t*> intersected_vertices;

    collect(v, &intersected_vertices, &intersected_edges, &intersected_faces);

    for (unsigned i = 0; i < intersected_vertices.size(); ++i) {
      facesForVertex(intersected_vertices[i], f);
    }
    for (unsigned i = 0; i < intersected_edges.size(); ++i) {
      facesForEdge(intersected_edges[i], f);
    }
    f.insert(intersected_faces.begin(), intersected_faces.end());
  }

  /**
   * \brief Collect the set of faces that contain all vertices in \a verts.
   *
   * @tparam vertex_set_t A collection type holding vertex_t *
   * @tparam face_set_t A collection type holding face_t *
   * @param[in] verts A set of vertices.
   * @param[out] result The resulting set of faces.
   */
  template <typename vertex_set_t, typename face_set_t>
  void commonFaces(const vertex_set_t& verts, face_set_t& result) {
    std::set<face_t *> ifaces, temp, out;
    typename vertex_set_t::const_iterator i = verts.begin();
    if (i == verts.end()) {
      return;
    }
    intersectedFaces((*i), ifaces);
    while (++i != verts.end()) {
      temp.clear();
      intersectedFaces((*i), temp);

      out.clear();
      std::set_intersection(temp.begin(), temp.end(), ifaces.begin(),
                            ifaces.end(), set_inserter(out));
      ifaces.swap(out);
    }
    std::copy(ifaces.begin(), ifaces.end(), set_inserter(result));
  }

  void clear() { super::clear(); }
};
}  // namespace csg
}  // namespace carve


text:
try:
    from setuptools import setup, find_packages
except ImportError:
    import distribute_setup
    distribute_setup.use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='MPDC',
    version='1.1',
    license='MIT',
    description='A XMMS2-like collections system for MPD, aimed at '
                'helping you to feed and manipulate your playlist with '
                'great flexibility',
    author='nhrx.org',
    url='http://nhrx.org/mpdc',
    packages=find_packages(),
    entry_points={
          'console_scripts': [
              'mpdc-playlist = mpdc.mpdc_playlist:main',
              'mpdc-collections = mpdc.mpdc_collections:main',
              'mpdc-database = mpdc.mpdc_database:main',
              'mpdc-configure = mpdc.mpdc_configure:main'
          ]
    },
    install_requires=['ply >= 3.4', 'python-mpd2 >= 0.4.0']
)