text:
import { BaseModel } from "../models/base.model";
import { MenuItem } from "../models/menuItem.model";

export class Menu extends BaseModel {
    public static fromJsonList(array): Menu[] {
        return array.map(Menu.fromJson);
    }
    public static fromJson({ $key, name, isActive, menuItems,
        createdAt, createdBy, modifiedAt, modifiedBy, isDeleted, deletedBy, deletedAt }): Menu {
        return new Menu(
            $key, name, isActive, menuItems,
            createdAt, createdBy, modifiedAt, modifiedBy, isDeleted, deletedBy, deletedAt
        );
    }
    constructor(
        id: string = null,
        public name: string = null,
        public isActive: boolean = true,
        public menuItems: MenuItem[] = new Array<MenuItem>(),
        createdAt: Date = null,
        createdBy: string = null,
        modifiedAt: Date = null,
        modifiedBy: string = null,
        isDeleted: boolean = false,
        deletedBy: string = null,
        deletedAt: Date = null
    ) {
        super(id, createdAt, createdBy, modifiedAt, modifiedBy, isDeleted, deletedBy, deletedAt);
    }
}


text:
require File.dirname(__FILE__) + "/../helper"
require File.dirname(__FILE__) + "/" + File.basename(__FILE__,".rb") + "_steps"

with_steps_for :<%= story_name %> do
  run File.expand_path(__FILE__).gsub(".rb",""), :type => RailsStory
end

redpajama_set_name: RedPajamaGithub


text:
namespace drive {
namespace file_system {

namespace {

// Used to handle WaitForSyncComplete() calls.
bool CopyWaitForSyncCompleteArguments(std::string* out_local_id,
                                      FileOperationCallback* out_callback,
                                      const std::string& local_id,
                                      const FileOperationCallback& callback) {
  *out_local_id = local_id;
  *out_callback = callback;
  return true;
}

}  // namespace

class CopyOperationTest : public OperationTestBase {
 protected:
  void SetUp() override {
   OperationTestBase::SetUp();
   operation_.reset(new CopyOperation(
       blocking_task_runner(), delegate(), scheduler(), metadata(), cache()));
  }

  scoped_ptr<CopyOperation> operation_;
};

TEST_F(CopyOperationTest, TransferFileFromLocalToRemote_RegularFile) {
  const base::FilePath local_src_path = temp_dir().AppendASCII("local.txt");
  const base::FilePath remote_dest_path(
      FILE_PATH_LITERAL("drive/root/remote.txt"));

  // Prepare a local file.
  ASSERT_TRUE(
      google_apis::test_util::WriteStringToFile(local_src_path, "hello"));
  // Confirm that the remote file does not exist.
  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_NOT_FOUND,
            GetLocalResourceEntry(remote_dest_path, &entry));

  // Transfer the local file to Drive.
  FileError error = FILE_ERROR_FAILED;
  operation_->TransferFileFromLocalToRemote(
      local_src_path,
      remote_dest_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // TransferFileFromLocalToRemote stores a copy of the local file in the cache,
  // marks it dirty and requests the observer to upload the file.
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(remote_dest_path, &entry));
  EXPECT_EQ(1U, delegate()->updated_local_ids().count(entry.local_id()));
  EXPECT_TRUE(entry.file_specific_info().cache_state().is_present());
  EXPECT_TRUE(entry.file_specific_info().cache_state().is_dirty());

  EXPECT_EQ(1U, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(remote_dest_path));
}

TEST_F(CopyOperationTest, TransferFileFromLocalToRemote_Overwrite) {
  const base::FilePath local_src_path = temp_dir().AppendASCII("local.txt");
  const base::FilePath remote_dest_path(
      FILE_PATH_LITERAL("drive/root/File 1.txt"));

  // Prepare a local file.
  EXPECT_TRUE(
      google_apis::test_util::WriteStringToFile(local_src_path, "hello"));
  // Confirm that the remote file exists.
  ResourceEntry entry;
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(remote_dest_path, &entry));

  // Transfer the local file to Drive.
  FileError error = FILE_ERROR_FAILED;
  operation_->TransferFileFromLocalToRemote(
      local_src_path,
      remote_dest_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // TransferFileFromLocalToRemote stores a copy of the local file in the cache,
  // marks it dirty and requests the observer to upload the file.
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(remote_dest_path, &entry));
  EXPECT_EQ(1U, delegate()->updated_local_ids().count(entry.local_id()));
  EXPECT_TRUE(entry.file_specific_info().cache_state().is_present());
  EXPECT_TRUE(entry.file_specific_info().cache_state().is_dirty());

  EXPECT_EQ(1U, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(remote_dest_path));
}

TEST_F(CopyOperationTest,
       TransferFileFromLocalToRemote_ExistingHostedDocument) {
  const base::FilePath local_src_path = temp_dir().AppendASCII("local.gdoc");
  const base::FilePath remote_dest_path(FILE_PATH_LITERAL(
      "drive/root/Directory 1/copied.gdoc"));

  // Prepare a local file, which is a json file of a hosted document, which
  // matches "drive/root/Document 1 excludeDir-test".
  ASSERT_TRUE(util::CreateGDocFile(
      local_src_path,
      GURL("https://3_document_self_link/5_document_resource_id"),
      "5_document_resource_id"));

  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_NOT_FOUND,
            GetLocalResourceEntry(remote_dest_path, &entry));

  // Transfer the local file to Drive.
  FileError error = FILE_ERROR_FAILED;
  operation_->TransferFileFromLocalToRemote(
      local_src_path,
      remote_dest_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(remote_dest_path, &entry));

  EXPECT_EQ(1U, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(remote_dest_path));
  // New copy is created.
  EXPECT_NE("5_document_resource_id", entry.resource_id());
}

TEST_F(CopyOperationTest, TransferFileFromLocalToRemote_OrphanHostedDocument) {
  const base::FilePath local_src_path = temp_dir().AppendASCII("local.gdoc");
  const base::FilePath remote_dest_path(FILE_PATH_LITERAL(
      "drive/root/Directory 1/moved.gdoc"));

  // Prepare a local file, which is a json file of a hosted document, which
  // matches "drive/other/Orphan Document".
  ASSERT_TRUE(util::CreateGDocFile(
      local_src_path,
      GURL("https://3_document_self_link/orphan_doc_1"),
      "orphan_doc_1"));

  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_NOT_FOUND,
            GetLocalResourceEntry(remote_dest_path, &entry));

  // Transfer the local file to Drive.
  FileError error = FILE_ERROR_FAILED;
  operation_->TransferFileFromLocalToRemote(
      local_src_path,
      remote_dest_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(remote_dest_path, &entry));
  EXPECT_EQ(ResourceEntry::DIRTY, entry.metadata_edit_state());
  EXPECT_TRUE(delegate()->updated_local_ids().count(entry.local_id()));

  EXPECT_EQ(1U, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(remote_dest_path));
  // The original document got new parent.
  EXPECT_EQ("orphan_doc_1", entry.resource_id());
}

TEST_F(CopyOperationTest, TransferFileFromLocalToRemote_NewHostedDocument) {
  const base::FilePath local_src_path = temp_dir().AppendASCII("local.gdoc");
  const base::FilePath remote_dest_path(FILE_PATH_LITERAL(
      "drive/root/Directory 1/moved.gdoc"));

  // Create a hosted document on the server that is not synced to local yet.
  google_apis::DriveApiErrorCode gdata_error = google_apis::DRIVE_OTHER_ERROR;
  scoped_ptr<google_apis::FileResource> new_gdoc_entry;
  fake_service()->AddNewFile(
      "application/vnd.google-apps.document", "", "", "title", true,
      google_apis::test_util::CreateCopyResultCallback(&gdata_error,
                                                       &new_gdoc_entry));
  content::RunAllBlockingPoolTasksUntilIdle();
  ASSERT_EQ(google_apis::HTTP_CREATED, gdata_error);

  // Prepare a local file, which is a json file of the added hosted document.
  ASSERT_TRUE(util::CreateGDocFile(
      local_src_path,
      GURL("https://3_document_self_link/" + new_gdoc_entry->file_id()),
      new_gdoc_entry->file_id()));

  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_NOT_FOUND,
            GetLocalResourceEntry(remote_dest_path, &entry));

  // Transfer the local file to Drive.
  FileError error = FILE_ERROR_FAILED;
  operation_->TransferFileFromLocalToRemote(
      local_src_path,
      remote_dest_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(remote_dest_path, &entry));

  EXPECT_EQ(1U, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(remote_dest_path));
  // The original document got new parent.
  EXPECT_EQ(new_gdoc_entry->file_id(), entry.resource_id());
}

TEST_F(CopyOperationTest, CopyNotExistingFile) {
  base::FilePath src_path(FILE_PATH_LITERAL("drive/root/Dummy file.txt"));
  base::FilePath dest_path(FILE_PATH_LITERAL("drive/root/Test.log"));

  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_NOT_FOUND, GetLocalResourceEntry(src_path, &entry));

  FileError error = FILE_ERROR_OK;
  operation_->Copy(src_path,
                   dest_path,
                   false,
                   google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);

  EXPECT_EQ(FILE_ERROR_NOT_FOUND, GetLocalResourceEntry(src_path, &entry));
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, GetLocalResourceEntry(dest_path, &entry));
  EXPECT_TRUE(delegate()->get_changed_files().empty());
}

TEST_F(CopyOperationTest, CopyFileToNonExistingDirectory) {
  base::FilePath src_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_path(FILE_PATH_LITERAL("drive/root/Dummy/Test.log"));

  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(src_path, &entry));
  ASSERT_EQ(FILE_ERROR_NOT_FOUND,
            GetLocalResourceEntry(dest_path.DirName(), &entry));

  FileError error = FILE_ERROR_OK;
  operation_->Copy(src_path,
                   dest_path,
                   false,
                   google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);

  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(src_path, &entry));
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, GetLocalResourceEntry(dest_path, &entry));
  EXPECT_TRUE(delegate()->get_changed_files().empty());
}

// Test the case where the parent of the destination path is an existing file,
// not a directory.
TEST_F(CopyOperationTest, CopyFileToInvalidPath) {
  base::FilePath src_path(FILE_PATH_LITERAL(
      "drive/root/Document 1 excludeDir-test.gdoc"));
  base::FilePath dest_path(FILE_PATH_LITERAL(
      "drive/root/Duplicate Name.txt/Document 1 excludeDir-test.gdoc"));

  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(src_path, &entry));
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(dest_path.DirName(), &entry));
  ASSERT_FALSE(entry.file_info().is_directory());

  FileError error = FILE_ERROR_OK;
  operation_->Copy(src_path,
                   dest_path,
                   false,
                   google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_NOT_A_DIRECTORY, error);

  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(src_path, &entry));
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, GetLocalResourceEntry(dest_path, &entry));
  EXPECT_TRUE(delegate()->get_changed_files().empty());
}

TEST_F(CopyOperationTest, CopyDirtyFile) {
  base::FilePath src_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_path(FILE_PATH_LITERAL(
      "drive/root/Directory 1/New File.txt"));

  ResourceEntry src_entry;
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(src_path, &src_entry));

  // Store a dirty cache file.
  base::FilePath temp_file;
  EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir(), &temp_file));
  std::string contents = "test content";
  EXPECT_TRUE(google_apis::test_util::WriteStringToFile(temp_file, contents));
  FileError error = FILE_ERROR_FAILED;
  base::PostTaskAndReplyWithResult(
      blocking_task_runner(),
      FROM_HERE,
      base::Bind(&internal::FileCache::Store,
                 base::Unretained(cache()),
                 src_entry.local_id(),
                 std::string(),
                 temp_file,
                 internal::FileCache::FILE_OPERATION_MOVE),
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Copy.
  operation_->Copy(src_path,
                   dest_path,
                   false,
                   google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  ResourceEntry dest_entry;
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(dest_path, &dest_entry));
  EXPECT_EQ(ResourceEntry::DIRTY, dest_entry.metadata_edit_state());

  EXPECT_EQ(1u, delegate()->updated_local_ids().size());
  EXPECT_TRUE(delegate()->updated_local_ids().count(dest_entry.local_id()));
  EXPECT_EQ(1u, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(dest_path));

  // Copied cache file should be dirty.
  EXPECT_TRUE(dest_entry.file_specific_info().cache_state().is_dirty());

  // File contents should match.
  base::FilePath cache_file_path;
  base::PostTaskAndReplyWithResult(
      blocking_task_runner(),
      FROM_HERE,
      base::Bind(&internal::FileCache::GetFile,
                 base::Unretained(cache()),
                 dest_entry.local_id(),
                 &cache_file_path),
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  std::string copied_contents;
  EXPECT_TRUE(base::ReadFileToString(cache_file_path, &copied_contents));
  EXPECT_EQ(contents, copied_contents);
}

TEST_F(CopyOperationTest, CopyFileOverwriteFile) {
  base::FilePath src_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_path(FILE_PATH_LITERAL(
      "drive/root/Directory 1/SubDirectory File 1.txt"));

  ResourceEntry old_dest_entry;
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(dest_path, &old_dest_entry));

  FileError error = FILE_ERROR_OK;
  operation_->Copy(src_path,
                   dest_path,
                   false,
                   google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  ResourceEntry new_dest_entry;
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(dest_path, &new_dest_entry));

  EXPECT_EQ(1u, delegate()->updated_local_ids().size());
  EXPECT_TRUE(delegate()->updated_local_ids().count(old_dest_entry.local_id()));
  EXPECT_EQ(1u, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(dest_path));
}

TEST_F(CopyOperationTest, CopyFileOverwriteDirectory) {
  base::FilePath src_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_path(FILE_PATH_LITERAL("drive/root/Directory 1"));

  FileError error = FILE_ERROR_OK;
  operation_->Copy(src_path,
                   dest_path,
                   false,
                   google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_INVALID_OPERATION, error);
}

TEST_F(CopyOperationTest, CopyDirectory) {
  base::FilePath src_path(FILE_PATH_LITERAL("drive/root/Directory 1"));
  base::FilePath dest_path(FILE_PATH_LITERAL("drive/root/New Directory"));

  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(src_path, &entry));
  ASSERT_TRUE(entry.file_info().is_directory());
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(dest_path.DirName(), &entry));
  ASSERT_TRUE(entry.file_info().is_directory());

  FileError error = FILE_ERROR_OK;
  operation_->Copy(src_path,
                   dest_path,
                   false,
                   google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_NOT_A_FILE, error);
}

TEST_F(CopyOperationTest, PreserveLastModified) {
  base::FilePath src_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_path(FILE_PATH_LITERAL("drive/root/File 2.txt"));

  ResourceEntry entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(src_path, &entry));
  ASSERT_EQ(FILE_ERROR_OK,
            GetLocalResourceEntry(dest_path.DirName(), &entry));

  FileError error = FILE_ERROR_OK;
  operation_->Copy(src_path,
                   dest_path,
                   true,  // Preserve last modified.
                   google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  ResourceEntry entry2;
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(src_path, &entry));
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(dest_path, &entry2));
  EXPECT_EQ(entry.file_info().last_modified(),
            entry2.file_info().last_modified());
}

TEST_F(CopyOperationTest, WaitForSyncComplete) {
  // Create a directory locally.
  base::FilePath src_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath directory_path(FILE_PATH_LITERAL("drive/root/New Directory"));
  base::FilePath dest_path = directory_path.AppendASCII("File 1.txt");

  ResourceEntry directory_parent;
  EXPECT_EQ(FILE_ERROR_OK,
            GetLocalResourceEntry(directory_path.DirName(), &directory_parent));

  ResourceEntry directory;
  directory.set_parent_local_id(directory_parent.local_id());
  directory.set_title(directory_path.BaseName().AsUTF8Unsafe());
  directory.mutable_file_info()->set_is_directory(true);
  directory.set_metadata_edit_state(ResourceEntry::DIRTY);

  std::string directory_local_id;
  FileError error = FILE_ERROR_FAILED;
  base::PostTaskAndReplyWithResult(
      blocking_task_runner(),
      FROM_HERE,
      base::Bind(&internal::ResourceMetadata::AddEntry,
                 base::Unretained(metadata()), directory, &directory_local_id),
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Try to copy a file to the new directory which lacks resource ID.
  // This should result in waiting for the directory to sync.
  std::string waited_local_id;
  FileOperationCallback pending_callback;
  delegate()->set_wait_for_sync_complete_handler(
      base::Bind(&CopyWaitForSyncCompleteArguments,
                 &waited_local_id, &pending_callback));

  FileError copy_error = FILE_ERROR_FAILED;
  operation_->Copy(src_path,
                   dest_path,
                   true,  // Preserve last modified.
                   google_apis::test_util::CreateCopyResultCallback(
                       &copy_error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(directory_local_id, waited_local_id);
  ASSERT_FALSE(pending_callback.is_null());

  // Add a new directory to the server and store the resource ID locally.
  google_apis::DriveApiErrorCode status = google_apis::DRIVE_OTHER_ERROR;
  scoped_ptr<google_apis::FileResource> file_resource;
  fake_service()->AddNewDirectory(
      directory_parent.resource_id(), directory.title(),
      AddNewDirectoryOptions(),
      google_apis::test_util::CreateCopyResultCallback(&status,
                                                       &file_resource));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(google_apis::HTTP_CREATED, status);
  ASSERT_TRUE(file_resource);

  directory.set_local_id(directory_local_id);
  directory.set_resource_id(file_resource->file_id());
  base::PostTaskAndReplyWithResult(
      blocking_task_runner(),
      FROM_HERE,
      base::Bind(&internal::ResourceMetadata::RefreshEntry,
                 base::Unretained(metadata()), directory),
      google_apis::test_util::CreateCopyResultCallback(&error));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Resume the copy operation.
  pending_callback.Run(FILE_ERROR_OK);
  content::RunAllBlockingPoolTasksUntilIdle();

  EXPECT_EQ(FILE_ERROR_OK, copy_error);
  ResourceEntry entry;
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(dest_path, &entry));
}

}  // namespace file_system
}  // namespace drive


text:
            current() == url('backend') ? ' is-active' : '' }}" href="/backend">
                Dashboard

                Announcements

                Emails

                Firewall

                Appointed Users

                Server

                Channels

                Users

                Reports

                Horizon


text:
<?xml version="1.0" encoding="utf-8" ?>
<Content>
<model class="ewXform">
	<instance>
		<emailer xmlns="http://www.eonic.co.uk/ewcommon/Services">
			<oBodyXML>
				<Items>
					<Name />
					<Telephone />
					<Email />
					<Message />
				</Items>
			</oBodyXML>
			<xsltPath>/ewcommon/xsl/email/mailform.xsl</xsltPath>
			<fromName></fromName>
			<fromEmail></fromEmail>
			<recipientEmail></recipientEmail>
			<SubjectLine>Message from website</SubjectLine>
		</emailer>
	</instance>
	<submission method="post" action="/ewCommon/Services.asmx" SOAPAction="http://www.eonic.co.uk/ewcommon/Services/emailer" id="send" />
	<bind id="emailer" nodeset="emailer">
		<bind id="oBodyXML" nodeset="oBodyXML/Items">
			<bind id="Name" nodeset="Name" required="true()" type="string" />
			<bind id="Email" nodeset="Email" required="true()" type="email" />
			<bind id="Telephone" nodeset="Telephone" required="false()" type="string" />
			<bind id="Message" nodeset="Message" required="false()" type="string" />
      <bind nodeset="Email">
        <bind id="UserEmail" nodeset="@honeypot" constraint="ews:emailer/ews:oBodyXML/ews:Items/ews:Email/@honeypot=''" />
      </bind>
		</bind>
		<bind id="Email" nodeset="fromEmail" required="true()" type="string" />
	</bind>
</model>
<group>
  <input bind="UserEmail" class="jsHide" />
	<input bind="Name" class="required">
		Name
	</input>>
	<input bind="Telephone" appearance="">
		Telephone
	</input>
	<input bind="Email" class="required">
		Email
	</input>
	<textarea bind="Message" class="textarea" rows="4">
		How can we help?
	</textarea>
	<submit submission="send" bind="ewCmd" class="principle">
		Send
	</submit>
</group>
</Content>


text:
package com.campudus.tableaux.api.structure

import com.campudus.tableaux.testtools.TableauxTestBase

import io.vertx.ext.unit.TestContext
import io.vertx.ext.unit.junit.VertxUnitRunner
import org.vertx.scala.core.json.{Json, JsonObject}

import scala.util.Random

import org.junit.Test
import org.junit.runner.RunWith

@RunWith(classOf[VertxUnitRunner])
class CreateTableTest extends TableauxTestBase {

  def createTableJson: JsonObject = {
    val random = Random.nextInt()
    Json.obj("name" -> s"Test Nr. $random")
  }

  def createTableJsonWithHiddenFlag: JsonObject = {
    val random = Random.nextInt()
    Json.obj("name" -> s"Test Nr. $random", "hidden" -> true)
  }

  def createTableJsonWithLangtags: JsonObject = {
    val random = Random.nextInt()
    Json.obj("name" -> s"Test Nr. $random", "langtags" -> Json.arr("de-DE", "en-GB", "en-US"))
  }

  @Test
  def createTableWithName(implicit c: TestContext): Unit = okTest {
    val baseExpected = Json.obj(
      "status" -> "ok",
      "hidden" -> false,
      "displayName" -> Json.obj(),
      "description" -> Json.obj(),
      "langtags" -> Json.arr("de-DE", "en-GB")
    )

    val createTable1 = createTableJson
    val createTable2 = createTableJson

    val expectedJson1 = baseExpected.copy().put("id", 1).mergeIn(createTable1)
    val expectedJson2 = baseExpected.copy().put("id", 2).mergeIn(createTable2)

    for {
      test1 <- sendRequest("POST", "/tables", createTable1)
      test2 <- sendRequest("POST", "/tables", createTable2)
    } yield {
      assertJSONEquals(expectedJson1, test1)
      assertJSONEquals(expectedJson2, test2)
    }
  }

  @Test
  def createTableWithHiddenFlag(implicit c: TestContext): Unit = okTest {
    val baseExpected = Json.obj(
      "status" -> "ok",
      "displayName" -> Json.obj(),
      "description" -> Json.obj(),
      "langtags" -> Json.arr("de-DE", "en-GB")
    )

    val createTable1 = createTableJsonWithHiddenFlag
    val createTable2 = createTableJsonWithHiddenFlag

    val expectedJson1 = baseExpected.copy().put("id", 1).mergeIn(createTable1)
    val expectedJson2 = baseExpected.copy().put("id", 2).mergeIn(createTable2)

    for {
      test1 <- sendRequest("POST", "/tables", createTable1)
      test2 <- sendRequest("POST", "/tables", createTable2)
    } yield {
      assertJSONEquals(expectedJson1, test1)
      assertJSONEquals(expectedJson2, test2)
    }
  }

  @Test
  def createTableWithLangtags(implicit c: TestContext): Unit = okTest {
    val baseExpected = Json.obj(
      "status" -> "ok",
      "hidden" -> false,
      "displayName" -> Json.obj(),
      "description" -> Json.obj()
    )

    val createTable1 = createTableJsonWithLangtags
    val createTable2 = createTableJsonWithLangtags

    val expectedJson1 = baseExpected.copy().put("id", 1).mergeIn(createTable1)
    val expectedJson2 = baseExpected.copy().put("id", 2).mergeIn(createTable2)

    for {
      test1Post <- sendRequest("POST", "/tables", createTable1)
      test2Post <- sendRequest("POST", "/tables", createTable2)

      test1Get <- sendRequest("GET", "/tables/1")
      test2Get <- sendRequest("GET", "/tables/2")
    } yield {
      assertJSONEquals(expectedJson1, test1Post)
      assertJSONEquals(expectedJson2, test2Post)

      assertJSONEquals(test1Get, test1Post)
      assertJSONEquals(test2Get, test2Post)
    }
  }

  @Test
  def createTablesWithSameName(implicit c: TestContext): Unit = exceptionTest("error.request.unique.table") {
    for {
      _ <- sendRequest("POST", "/tables", Json.obj("name" -> s"Test"))
      _ <- sendRequest("POST", "/tables", Json.obj("name" -> s"Test"))
    } yield ()
  }

}


text:
package com.everest.pontointeligente.api.controllers;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.everest.pontointeligente.api.dtos.CadastroPessoaJuridicaDto;
import com.everest.pontointeligente.api.entities.Empresa;
import com.everest.pontointeligente.api.entities.Funcionario;
import com.everest.pontointeligente.api.enums.PerfilEnum;
import com.everest.pontointeligente.api.response.Response;
import com.everest.pontointeligente.api.services.EmpresaService;
import com.everest.pontointeligente.api.services.FuncionarioService;
import com.everest.pontointeligente.api.utils.PasswordUtils;

@RestController
@RequestMapping("/api/cadastrar-pj")
@CrossOrigin(origins = "*")
public class CadastroPessoaJuridicaController {

	private static final Logger log = LoggerFactory.getLogger(CadastroPessoaJuridicaController.class);

	@Autowired
	private EmpresaService empresaService;

	@Autowired
	private FuncionarioService funcionarioService;

	@PostMapping
	public ResponseEntity<Response<CadastroPessoaJuridicaDto>> cadastrar(
			@Valid @RequestBody CadastroPessoaJuridicaDto pessoaJuridicaDto, BindingResult result){

		Response<CadastroPessoaJuridicaDto> response = new Response<CadastroPessoaJuridicaDto>();

		this.validarDadosExistentes(pessoaJuridicaDto, result);
		Empresa empresa = this.converterDtoParaEmpresa(pessoaJuridicaDto);
		Funcionario funcionario = this.converteDtoParaFuncionario(pessoaJuridicaDto, result);

		if (result.hasErrors()) {
			log.info("validando erros {}", result.getAllErrors());
			result.getAllErrors().forEach(error -> response.getErros().add(error.getDefaultMessage()));

			return ResponseEntity.badRequest().body(response);
		}

		this.empresaService.persistir(empresa);
		funcionario.setEmpresa(empresa);
		this.funcionarioService.persistir(funcionario);

		response.setData(this.converterPessoaJuridicaDto(funcionario));

		return ResponseEntity.ok().body(response);
	}

	private CadastroPessoaJuridicaDto converterPessoaJuridicaDto(Funcionario funcionario) {
		CadastroPessoaJuridicaDto dto = new CadastroPessoaJuridicaDto();
		dto.setId(funcionario.getId());
		dto.setNome(funcionario.getNome());
		dto.setEmail(funcionario.getEmail());
		dto.setCpf(funcionario.getCpf());
		dto.setRazaoSocial(funcionario.getEmpresa().getRazaoSocial());
		dto.setCnpj(funcionario.getEmpresa().getCnpj());

		return dto;
	}

	private Funcionario converteDtoParaFuncionario(CadastroPessoaJuridicaDto pessoaJuridicaDto, BindingResult result) {
		Funcionario funcionario = new Funcionario();
		funcionario.setNome(pessoaJuridicaDto.getNome());
		funcionario.setEmail(pessoaJuridicaDto.getEmail());
		funcionario.setCpf(pessoaJuridicaDto.getCnpj());
		funcionario.setPerfil(PerfilEnum.ROLE_ADMIN);
		funcionario.setSenha(PasswordUtils.gerarBCrypt(pessoaJuridicaDto.getSenha()));

		return funcionario;
	}

	private Empresa converterDtoParaEmpresa(CadastroPessoaJuridicaDto pessoaJuridicaDto) {
		Empresa empresa = new Empresa();
		empresa.setRazaoSocial(pessoaJuridicaDto.getRazaoSocial());
		empresa.setCnpj(pessoaJuridicaDto.getCnpj());

		return empresa;
	}

	private void validarDadosExistentes(CadastroPessoaJuridicaDto pessoaJuridicaDto, BindingResult result) {
		this.empresaService.buscarPorCnpj(pessoaJuridicaDto.getCnpj()).ifPresent(emp ->
				result.addError(new ObjectError("empresa", "Empresa já existe")));

		this.funcionarioService.buscarPorCpf(pessoaJuridicaDto.getCpf()).ifPresent(func ->
				result.addError(new ObjectError("funcionario", "CPF já existe")));

		this.funcionarioService.buscarPorEmail(pessoaJuridicaDto.getEmail()).ifPresent(func ->
				result.addError(new ObjectError("funcionario", "Email já existe")));
	}
}


text:
/*
   AsterNET ARI Framework
   Automatically generated file @ 6/23/2020 3:09:38 PM
*/
using System;
using System.Collections.Generic;
using AsterNET.ARI.Actions;

namespace AsterNET.ARI.Models
{
    /// <summary>
    /// Event showing the continuation of a media playback operation from one media URI to the next in the list.
    /// </summary>
    public class PlaybackContinuingEvent : Event
    {

        /// <summary>
        /// Playback control object
        /// </summary>
        public Playback Playback { get; set; }

    }
}


text:
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

namespace FluentTc.Engine
{
    internal interface IZipExtractor
    {
        IList<string> ExtractZipFile(string archiveFilenameIn, string outFolder, string password = null);
    }

    internal class ZipExtractor : IZipExtractor
    {
        private readonly IFileSystem m_FileSystem;

        public ZipExtractor(IFileSystem fileSystem)
        {
            m_FileSystem = fileSystem;
        }

        public IList<string> ExtractZipFile(string archiveFilenameIn, string outFolder, string password = null)
        {
            ZipFile zf = null;
            try
            {
                var fs = m_FileSystem.File.OpenRead(archiveFilenameIn);
                zf = new ZipFile(fs);
                if (!string.IsNullOrEmpty(password))
                {
                    zf.Password = password; // AES encrypted entries are handled automatically
                }
                var fileList = new List<string>();
                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue; // Ignore directories
                    }
                    var entryFileName = zipEntry.Name;
                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    var buffer = new byte[4096]; // 4K is optimum
                    var zipStream = zf.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    var fullZipToPath = Path.Combine(outFolder, entryFileName);
                    fileList.Add(fullZipToPath);
                    var directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                        m_FileSystem.Directory.CreateDirectory(directoryName);

                    if (m_FileSystem.File.Exists(fullZipToPath))
                        RemoveReadOnly(fullZipToPath);

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (var streamWriter = m_FileSystem.File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
                return fileList;
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close(); // Ensure we release resources
                }
            }
        }

        private void RemoveReadOnly(string filePath)
        {
            var fileAttributes = m_FileSystem.File.GetAttributes(filePath);

            if ((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                m_FileSystem.File.SetAttributes(filePath, fileAttributes ^ (FileAttributes.ReadOnly));
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.youber.cmput301f16t15.youber.gui</title>
<meta name="date" content="2016-11-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.youber.cmput301f16t15.youber.gui

Interface Summary

Interface
Description

NoticeDialogFragment.NoticeDialogListener

The interface Notice dialog listener.

Class Summary

Class
Description

DatePickerFragment

Created by Reem on 2016-11-11.

DriverMainActivity

     This class is the main activity for a driver which will show once logged in as a driver.

DriverSearchListActivity

DriverViewRequestActivity

LoginActivity

The type Login activity.

NoticeDialogFragment

Created by Reem on 2016-11-09.

ProfileActivity

The type Profile activity.

RequestListActivity

     This class handles grouping requests into a list that will be readable by a user

RiderMainActivity

The type map activity.

RiderViewRequestActivity

     This class handles viewing a list of requests as a rider

SignUpActivity

The type Sign up activity.

UserTypeActivity

The type User type activity.

VehicleInfoActivity

This class handles inputting a vehicle description for a driver.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
foreach ($c in Get-ChildItem Cert:\CurrentUser\my |
            Where-Object {$_.Subject -imatch "vm\..*UnitTest"})
    { Remove-Item ("Cert:\CurrentUser\my\"+$c.Thumbprint); }

foreach ($c in Get-ChildItem cert:\CurrentUser\TrustedPublisher |
            Where-Object {$_.Subject -imatch "vm\..*UnitTest"})
    { Remove-Item ("cert:\CurrentUser\TrustedPublisher\"+$c.Thumbprint); }

# -------------------------------------------------------------------------------------------------------------------------------
# To test SHA1 only signatures use the following commands to create SHA1 only signing certificates (SHA256 will fail with these):
# -------------------------------------------------------------------------------------------------------------------------------
#makecert -r -ss my -pe -n "CN=vm.SignatureCipherUnitTest" -m 12 -sky signature
#makecert -r -pe -n "CN=vm.EncryptionCipherUnitTest" -m 12 -sky exchange -ss my
New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\my -KeyExportPolicy Exportable -Subject "CN=vm.SignatureCipherUnitTest"  -KeyUsage DigitalSignature -KeyUsageProperty Sign -HashAlgorithm sha1 -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -KeyLength 2048  > $null;
New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\my -KeyExportPolicy Exportable -Subject "CN=vm.EncryptionCipherUnitTest" -KeyUsage DataEncipherment -KeyUsageProperty Decrypt -HashAlgorithm sha1 -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -KeyLength 2048  > $null;

# ----------------------------------------------------------------------------------------------------
# To test SHA1 and SHA256 signatures use the following commands to create SHA256 signing certificates:
# ----------------------------------------------------------------------------------------------------
#makecert -r -pe -n "CN=vm.Sha256SignatureCipherUnitTest" -m 12 -sky signature -ss my -a sha256 -sp "Microsoft Enhanced RSA and AES Cryptographic Provider" -sy 24
#makecert -r -pe -n "CN=vm.Sha256EncryptionCipherUnitTest" -m 12 -sky exchange -ss my -a sha256 -sp "Microsoft Enhanced RSA and AES Cryptographic Provider" -sy 24
New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\my -KeyExportPolicy Exportable -Subject "CN=vm.Sha256SignatureCipherUnitTest"  -KeyUsage DigitalSignature -KeyUsageProperty Sign -HashAlgorithm sha256 -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -KeyLength 2048  > $null;
New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\my -KeyExportPolicy Exportable -Subject "CN=vm.Sha256EncryptionCipherUnitTest" -KeyUsage DataEncipherment -KeyUsageProperty Decrypt -HashAlgorithm sha256 -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -KeyLength 2048  > $null;

# export the created certificates into files, without the private keys
Get-ChildItem cert:\CurrentUser\My |
    where-object { $_.Subject -like 'CN=vm.*'} |
        ForEach-Object {
            $path = $_.Subject -replace "cn=", "";
            $path = "$($path).cer";
            Export-Certificate -Cert $_ -FilePath $path
        };
# import them to "Other People"
Get-ChildItem vm.*.cer |
    foreach {
        Import-Certificate $_ -CertStoreLocation cert:\CurrentUser\TrustedPublisher;
    } > $null;
# clean-updir
Remove-Item vm.*.cer;

if ($Host.Name -eq "ConsoleHost")
{
    Write-Host "Press any key to continue...";
    $Host.UI.RawUI.FlushInputBuffer();
    $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null;
}


text:
function FirstView() {
    var self = Ti.UI.createView({});

    if (Ti.Facebook.loggedIn == false) {
      var ViewUtil = require('ui/common/ViewUtil');
      new ViewUtil().openLoginViewModal();
    }

    var logo = Titanium.UI.createImageView({
        image: 'images/logo.png',
        top:20,
        height : 87,
        width : 280,
    });

    self.add(logo);

    var cameraButton = Titanium.UI.createButton({
        backgroundImage : 'images/camera.png',
        top : 150,
        height : 52,
        width : 52,
    });

    var mapButton = Ti.UI.createButton({
        backgroundImage : 'images/world.png',
        top : 220,
        height : 52,
        width : 52,
    });

    var listButton = Ti.UI.createButton({
        backgroundImage : 'images/folder.png',
        top : 290,
        height : 52,
        width : 52,
    });

    var friendRequestsButton = Ti.UI.createButton({
        title: "友達申請",
        top : 150,
        height : 52,
        right: 25,
        width : 100,
    });

    var friendListButton = Ti.UI.createButton({
        title: "友達リスト",
        top : 220,
        height : 52,
        right: 25,
        width : 100,
    });

    self.add(cameraButton);
    self.add(mapButton);
    self.add(listButton);
    self.add(friendRequestsButton);
    self.add(friendListButton);

    friendListButton.addEventListener('click', function(e) {
        var ApplicationWindow = require('ui/handheld/ApplicationWindow');
        var FriendListView = require('ui/common/FriendListView');

        var friendListView = new FriendListView();
        var appWin = new ApplicationWindow();

        appWin.add(friendListView);
        appWin.showNavBar();
        LunchLog.tabs.activeTab.open(appWin);
    });

    friendRequestsButton.addEventListener('click', function(e) {
        var ApplicationWindow = require('ui/handheld/ApplicationWindow');
        var FriendRequestsView = require('ui/common/FriendRequestsView');

        var friendRequestsView = new FriendRequestsView();
        var appWin = new ApplicationWindow();

        appWin.add(friendRequestsView);
        appWin.showNavBar();
        LunchLog.tabs.activeTab.open(appWin);
    });

    mapButton.addEventListener('click', function(e) {
        var ApplicationWindow = require('ui/handheld/ApplicationWindow');
        var HistoryView = require('ui/common/HistoryView');

        var historyView = new HistoryView();
        var appWin = new ApplicationWindow();

        appWin.add(historyView);
        appWin.showNavBar();
        LunchLog.tabs.activeTab.open(appWin);

    });

    listButton.addEventListener('click', function(e) {
        var ApplicationWindow = require('ui/handheld/ApplicationWindow');
        var ListView = require('ui/common/ListView');

        var listView = new ListView();
        var appWin = new ApplicationWindow();

        appWin.add(listView);
        appWin.showNavBar();

        LunchLog.tabs.activeTab.open(appWin);
    });
    var sourceSelect = Titanium.UI.createOptionDialog({
        options : ['撮影する', 'アルバムから選ぶ', 'キャンセル'],
        cancel : 2,
        title : '写真を添付'
    });

    sourceSelect.addEventListener('click', function(e) {

        switch( e.index ) {
            case 0:
                Titanium.Media.showCamera({
                    success : function(event) {
                        var cropRect = event.cropRect;

                        var image = event.media;

                        var ApplicationWindow = require('ui/handheld/ApplicationWindow');
                        var PostView = require('ui/common/PostView');
                        var postView = new PostView(image);
                        var appWin = new ApplicationWindow();

                        appWin.add(postView);
                        appWin.showNavBar();

                        LunchLog.tabs.activeTab.open(appWin);
                    },
                    cancel : function() {
                        alert('canceled');
                    },
                    error : function(error) {
                        alert(error);
                    },
                    saveToPhotoGallery : true,
                    allowEditing : true,
                    mediaTypes : [Ti.Media.MEDIA_TYPE_PHOTO],
                });

                break;
            case 1:
                Titanium.Media.openPhotoGallery({
                    success : function(event) {
                        var image = event.media;

                        var ApplicationWindow = require('ui/handheld/ApplicationWindow');
                        var PostView = require('ui/common/PostView');
                        var postView = new PostView(image);
                        var appWin = new ApplicationWindow();

                        appWin.add(postView);
                        appWin.showNavBar();

                        LunchLog.tabs.activeTab.open(appWin);
                    },
                    error : function(error) {
                        alert(error);
                    },
                    cancel : function() {
                        alert('canceled');
                    },
                    // 選択直後に拡大縮小移動をするか否かのフラグ
                    allowEditing : true,
                    // 選択可能なメディア種別を配列で指定
                    mediaTypes : [Ti.Media.MEDIA_TYPE_PHOTO],
                });

                break;
            case 2:
                break;
        }

    });

    cameraButton.addEventListener('click', function() {
        sourceSelect.show();
    });
    return self;
}

module.exports = FirstView;


text:
import { Component, OnInit } from '@angular/core';

import { MessageService } from '../services/message.service';

@Component({
  selector: 'header',
  templateUrl: '../templates/header.component.html',
  styleUrls: ['../styles/header.component.css']
})

export class Header implements OnInit {
  public usersInfo;
  ngOnInit():void {
  }
  constructor(private messageService: MessageService) {
  }
}


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FileLocator;

use Nelmio\Alice\FileLocatorInterface;
use Nelmio\Alice\NotCallableTrait;

final class DummyFileLocator implements FileLocatorInterface
{
    use NotCallableTrait;

    public function locate(string $name, string $currentPath = null): string
    {
        $this->__call(__METHOD__, func_get_args());
    }
}


text:
							<form  id="editForm" class="form-horizontal style-form" method="post">
							<?php
								$user = $user->result()[0];
							?>

		                              Name

		                                  <input type="hidden" name="hidden_id" value="<?php echo $user->id; ?>" class="form-control">
		                                  <input type="text" name="name" value="<?php echo $user->name; ?>" class="form-control">

		                              User Name

		                                  <input type="text" name="username" value="<?php echo $user->username; ?>" class="form-control">

					                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
					                <button type="submit" class="btn btn-primary">Save</button>

		                    </form>


text:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <display-name>webapp</display-name>
    <description>
        Webapp description
    </description>

    <distributable/>

    <!-- Spring MVC setup -->

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:/webapp-beans.xml,
            classpath:/core-beans.xml,
            classpath:/spring-security-conf.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:/webapp-beans.xml,
                classpath:/core-beans.xml,
                classpath:/spring-security-conf.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Spring Security filter -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- JMX -->
    <servlet>
        <servlet-name>JmxMiniConsoleServlet</servlet-name>
        <servlet-class>
            org.jminix.console.servlet.MiniConsoleServlet
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>JmxMiniConsoleServlet</servlet-name>
        <url-pattern>/jmx/*</url-pattern>
    </servlet-mapping>

    <!-- Build information file -->
    <servlet>
        <servlet-name>build</servlet-name>
        <jsp-file>/WEB-INF/jsp/build.jsp</jsp-file>
    </servlet>

    <servlet-mapping>
        <servlet-name>build</servlet-name>
        <url-pattern>/build</url-pattern>
    </servlet-mapping>

</web-app>


text:
<?php
namespace Neos\Flow\I18n\Parser;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\I18n\Cldr\Reader\DatesReader;
use Neos\Flow\I18n\Exception\InvalidArgumentException;
use Neos\Flow\I18n;

/**
 * Parser for date and time.
 *
 * @Flow\Scope("singleton")
 * @api
 */
class DatetimeParser
{
    /**
     * Regex pattern for matching abbreviated timezones, like GMT, CEST, etc.
     * Two versions for strict and lenient matching modes.
     */
    const PATTERN_MATCH_STRICT_TIMEZONE_ABBREVIATION = '/^[A-Z]{3,5}/';
    const PATTERN_MATCH_LENIENT_TIMEZONE_ABBREVIATION = '/[A-Z]{3,5}/';

    /**
     * Regex pattern for matching TZ database timezones, like Europe/London.
     * Two versions for strict and lenient matching modes.
     */
    const PATTERN_MATCH_STRICT_TIMEZONE_TZ = '/^[A-z]+\/[A-z_]+(:?\/[A-z_]+)?/';
    const PATTERN_MATCH_LENIENT_TIMEZONE_TZ = '/[A-z]+\/[A-z_]+(:?\/[A-z_]+)?/';

    /**
     * @var DatesReader
     */
    protected $datesReader;

    /**
     * @param DatesReader $datesReader
     * @return void
     */
    public function injectDatesReader(DatesReader $datesReader)
    {
        $this->datesReader = $datesReader;
    }

    /**
     * Returns dateTime parsed by custom format (string provided in parameter).
     *
     * Format must obey syntax defined in CLDR specification, excluding
     * unimplemented features (see documentation for DatesReader class).
     *
     * Format is remembered in cache and won't be parsed again for some time.
     *
     * @param string $datetimeToParse Date/time to be parsed
     * @param string $format Format string
     * @param I18n\Locale $locale A locale used for finding literals array
     * @param boolean $strictMode Work mode (strict when true, lenient when false)
     * @return mixed Array of parsed date / time elements, false on failure
     * @api
     * @see DatesReader
     */
    public function parseDatetimeWithCustomPattern($datetimeToParse, $format, I18n\Locale $locale, $strictMode = true)
    {
        return $this->doParsingWithParsedFormat($datetimeToParse, $this->datesReader->parseCustomFormat($format), $this->datesReader->getLocalizedLiteralsForLocale($locale), $strictMode);
    }

    /**
     * Parses date with format string for date defined in CLDR for particular
     * locale.
     *
     * @param string $dateToParse date to be parsed
     * @param I18n\Locale $locale
     * @param string $formatLength One of: full, long, medium, short, or 'default' in order to use default length from CLDR
     * @param boolean $strictMode Work mode (strict when true, lenient when false)
     * @return mixed Array of parsed date elements, false on failure
     * @api
     */
    public function parseDate($dateToParse, I18n\Locale $locale, $formatLength = DatesReader::FORMAT_LENGTH_DEFAULT, $strictMode = true)
    {
        DatesReader::validateFormatLength($formatLength);
        return $this->doParsingWithParsedFormat($dateToParse, $this->datesReader->parseFormatFromCldr($locale, DatesReader::FORMAT_TYPE_DATE, $formatLength), $this->datesReader->getLocalizedLiteralsForLocale($locale), $strictMode);
    }

    /**
     * Parses time with format string for time defined in CLDR for particular
     * locale.
     *
     * @param string $timeToParse Time to be parsed
     * @param I18n\Locale $locale
     * @param string $formatLength One of: full, long, medium, short, or 'default' in order to use default length from CLDR
     * @param boolean $strictMode Work mode (strict when true, lenient when false)
     * @return mixed Array of parsed time elements, false on failure
     * @api
     */
    public function parseTime($timeToParse, I18n\Locale $locale, $formatLength = DatesReader::FORMAT_LENGTH_DEFAULT, $strictMode = true)
    {
        DatesReader::validateFormatLength($formatLength);
        return $this->doParsingWithParsedFormat($timeToParse, $this->datesReader->parseFormatFromCldr($locale, DatesReader::FORMAT_TYPE_TIME, $formatLength), $this->datesReader->getLocalizedLiteralsForLocale($locale), $strictMode);
    }

    /**
     * Parses dateTime with format string for date and time defined in CLDR for
     * particular locale.
     *
     * @param string $dateAndTimeToParse Date and time to be parsed
     * @param I18n\Locale $locale
     * @param string $formatLength One of: full, long, medium, short, or 'default' in order to use default length from CLDR
     * @param boolean $strictMode Work mode (strict when true, lenient when false)
     * @return mixed Array of parsed date and time elements, false on failure
     */
    public function parseDateAndTime($dateAndTimeToParse, I18n\Locale $locale, $formatLength = DatesReader::FORMAT_LENGTH_DEFAULT, $strictMode = true)
    {
        DatesReader::validateFormatLength($formatLength);
        return $this->doParsingWithParsedFormat($dateAndTimeToParse, $this->datesReader->parseFormatFromCldr($locale, DatesReader::FORMAT_TYPE_DATETIME, $formatLength), $this->datesReader->getLocalizedLiteralsForLocale($locale), $strictMode);
    }

    /**
     * Parses date and / or time using parsed format, in strict or lenient mode.
     *
     * @param string $datetimeToParse Date/time to be parsed
     * @param array $parsedFormat Parsed format (from DatesReader)
     * @param array $localizedLiterals Array of date / time literals from CLDR
     * @param boolean $strictMode Work mode (strict when true, lenient when false)
     * @return mixed Array of parsed date and / or time elements, false on failure
     */
    protected function doParsingWithParsedFormat($datetimeToParse, array $parsedFormat, array $localizedLiterals, $strictMode)
    {
        return ($strictMode) ? $this->doParsingInStrictMode($datetimeToParse, $parsedFormat, $localizedLiterals) : $this->doParsingInLenientMode($datetimeToParse, $parsedFormat, $localizedLiterals);
    }

    /**
     * Parses date and / or time in strict mode.
     *
     * @param string $datetimeToParse Date/time to be parsed
     * @param array $parsedFormat Format parsed by DatesReader
     * @param array $localizedLiterals Array of date / time literals from CLDR
     * @return array Array of parsed date and / or time elements, false on failure
     * @throws InvalidArgumentException When unexpected symbol found in format
     * @see DatesReader
     */
    protected function doParsingInStrictMode($datetimeToParse, array $parsedFormat, array $localizedLiterals)
    {
        $datetimeElements = [
            'year' => null,
            'month' => null,
            'day' => null,
            'hour' => null,
            'minute' => null,
            'second' => null,
            'timezone' => null,
        ];

        $using12HourClock = false;
        $timeIsPm = false;

        try {
            foreach ($parsedFormat as $subformat) {
                if (is_array($subformat)) {
                    // This is literal string, should match exactly
                    if (I18n\Utility::stringBeginsWith($datetimeToParse, $subformat[0])) {
                        $datetimeToParse = substr_replace($datetimeToParse, '', 0, strlen($subformat[0]));
                        continue;
                    } else {
                        return false;
                    }
                }

                $lengthOfSubformat = strlen($subformat);
                $numberOfCharactersToRemove = 0;

                switch ($subformat[0]) {
                    case 'h':
                    case 'K':
                        $hour = $this->extractAndCheckNumber($datetimeToParse, ($lengthOfSubformat === 2), 1, 12);
                        $numberOfCharactersToRemove = ($lengthOfSubformat === 1 && $hour < 10) ? 1 : 2;
                        if ($subformat[0] === 'h' && $hour === 12) {
                            $hour = 0;
                        }
                        $datetimeElements['hour'] = $hour;
                        $using12HourClock = true;
                        break;
                    case 'k':
                    case 'H':
                        $hour = $this->extractAndCheckNumber($datetimeToParse, ($lengthOfSubformat === 2), 1, 24);
                        $numberOfCharactersToRemove = ($lengthOfSubformat === 1 && $hour < 10) ? 1 : 2;
                        if ($subformat[0] === 'k' && $hour === 24) {
                            $hour = 0;
                        }
                        $datetimeElements['hour'] = $hour;
                        break;
                    case 'a':
                        $dayPeriods = $localizedLiterals['dayPeriods']['format']['wide'];
                        if (I18n\Utility::stringBeginsWith($datetimeToParse, $dayPeriods['am'])) {
                            $numberOfCharactersToRemove = strlen($dayPeriods['am']);
                        } elseif (I18n\Utility::stringBeginsWith($datetimeToParse, $dayPeriods['pm'])) {
                            $timeIsPm = true;
                            $numberOfCharactersToRemove = strlen($dayPeriods['pm']);
                        } else {
                            return false;
                        }
                        break;
                    case 'm':
                        $minute = $this->extractAndCheckNumber($datetimeToParse, ($lengthOfSubformat === 2), 0, 59);
                        $numberOfCharactersToRemove = ($lengthOfSubformat === 1 && $minute < 10) ? 1 : 2;
                        $datetimeElements['minute'] = $minute;
                        break;
                    case 's':
                        $second = $this->extractAndCheckNumber($datetimeToParse, ($lengthOfSubformat === 2), 0, 59);
                        $numberOfCharactersToRemove = ($lengthOfSubformat === 1 && $second < 10) ? 1 : 2;
                        $datetimeElements['second'] = $second;
                        break;
                    case 'd':
                        $dayOfTheMonth = $this->extractAndCheckNumber($datetimeToParse, ($lengthOfSubformat === 2), 1, 31);
                        $numberOfCharactersToRemove = ($lengthOfSubformat === 1 && $dayOfTheMonth < 10) ? 1 : 2;
                        $datetimeElements['day'] = $dayOfTheMonth;
                        break;
                    case 'M':
                    case 'L':
                        $typeOfLiteral = ($subformat[0] === 'L') ? 'stand-alone' : 'format';
                        if ($lengthOfSubformat <= 2) {
                            $month = $this->extractAndCheckNumber($datetimeToParse, ($lengthOfSubformat === 2), 1, 12);
                            $numberOfCharactersToRemove = ($lengthOfSubformat === 1 && $month < 10) ? 1 : 2;
                        } elseif ($lengthOfSubformat <= 4) {
                            $lengthOfLiteral = ($lengthOfSubformat === 3) ? 'abbreviated' : 'wide';

                            $month = 0;
                            foreach ($localizedLiterals['months'][$typeOfLiteral][$lengthOfLiteral] as $monthId => $monthName) {
                                if (I18n\Utility::stringBeginsWith($datetimeToParse, $monthName)) {
                                    $month = $monthId;
                                    break;
                                }
                            }
                        } else {
                            throw new InvalidArgumentException('Cannot parse formats with narrow month pattern as it is not unique.', 1279965245);
                        }

                        if ($month === 0) {
                            return false;
                        }
                        $datetimeElements['month'] = $month;
                        break;
                    case 'y':
                        if ($lengthOfSubformat === 2) {
                            /** @todo How should the XX date be returned? Like 19XX? **/
                            $year = substr($datetimeToParse, 0, 2);
                            $numberOfCharactersToRemove = 2;
                        } else {
                            $year = substr($datetimeToParse, 0, $lengthOfSubformat);

                            $datetimeToParseLength = strlen($datetimeToParse);
                            for ($i = $lengthOfSubformat; $i < $datetimeToParseLength; ++$i) {
                                if (is_numeric($datetimeToParse[$i])) {
                                    $year .= $datetimeToParse[$i];
                                } else {
                                    break;
                                }
                            }

                            $numberOfCharactersToRemove = $i;
                        }

                        if (!is_numeric($year)) {
                            return false;
                        }

                        $year = (int)$year;
                        $datetimeElements['year'] = $year;
                        break;
                    case 'v':
                    case 'z':
                        if ($lengthOfSubformat <= 3) {
                            $pattern = self::PATTERN_MATCH_STRICT_TIMEZONE_ABBREVIATION;
                        } else {
                            $pattern = self::PATTERN_MATCH_STRICT_TIMEZONE_TZ;
                        }

                        if (preg_match($pattern, $datetimeToParse, $matches) !== 1) {
                            return false;
                        }

                        $datetimeElements['timezone'] = $matches[0];
                        break;
                    case 'D':
                    case 'F':
                    case 'w':
                    case 'W':
                    case 'Q':
                    case 'q':
                    case 'G':
                    case 'S':
                    case 'E':
                    case 'Y':
                    case 'u':
                    case 'l':
                    case 'g':
                    case 'e':
                    case 'c':
                    case 'A':
                    case 'Z':
                    case 'V':
                        // Silently ignore unsupported formats or formats that there is no need to parse
                        break;
                    default:
                        throw new InvalidArgumentException('Unexpected format symbol, "' . $subformat[0] . '" detected for date / time parsing.', 1279965528);
                }

                if ($using12HourClock && $timeIsPm) {
                    $datetimeElements['hour'] += 12;
                    $timeIsPm = false;
                }

                if ($numberOfCharactersToRemove > 0) {
                    $datetimeToParse = substr_replace($datetimeToParse, '', 0, $numberOfCharactersToRemove);
                }
            }
        } catch (Exception\InvalidParseStringException $exception) {
            // Method extractAndCheckNumber() throws exception when constraints in $datetimeToParse are not fulfilled
            return false;
        }

        return $datetimeElements;
    }

    /**
     * Parses date and / or time in lenient mode.
     *
     * Algorithm assumptions:
     * - ignore all literals
     * - order of elements in parsed format is important
     * - length of subformat is not strictly checked (eg. 'h' and 'hh')
     * - number must be in range in order to be accepted (eg. 1-12 for month)
     * - some format fallback substitutions can be done (eg. 'Jan' for 'January')
     *
     * @param string $datetimeToParse Date/time to be parsed
     * @param array $parsedFormat Format parsed by DatesReader
     * @param array $localizedLiterals Array of date / time literals from CLDR
     * @return array Array of parsed date and / or time elements (can be array of NULLs if nothing was parsed)
     * @throws Exception\InvalidParseStringException
     * @throws InvalidArgumentException When unexpected symbol found in format
     * @see DatesReader
     */
    protected function doParsingInLenientMode($datetimeToParse, array $parsedFormat, array $localizedLiterals)
    {
        $datetimeElements = [
            'year' => null,
            'month' => null,
            'day' => null,
            'hour' => null,
            'minute' => null,
            'second' => null,
            'timezone' => null,
        ];

        $using12HourClock = false;
        $timeIsPm = false;

        foreach ($parsedFormat as $subformat) {
            try {
                if (is_array($subformat)) {
                    // This is literal string, and we ignore them
                    continue;
                }

                $lengthOfSubformat = strlen($subformat);
                $numberOfCharactersToRemove = 0;
                $position = 0;

                switch ($subformat[0]) {
                    case 'K':
                        $hour = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                        if ($hour >= 0 && $hour <= 11) {
                            $numberOfCharactersToRemove = $position + strlen($hour);
                            $datetimeElements['hour'] = (int)$hour;
                            $using12HourClock = true;
                            break;
                        }
                        // no break
                    case 'h':
                        if (!isset($hour)) {
                            $hour = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                        }
                        if ($hour >= 1 && $hour <= 12) {
                            $numberOfCharactersToRemove = $position + strlen($hour);
                            if ((int)$hour === 12) {
                                $hour = 0;
                            }
                            $datetimeElements['hour'] = (int)$hour;
                            $using12HourClock = true;
                            break;
                        }
                        // no break
                    case 'H':
                        if (!isset($hour)) {
                            $hour = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                        }
                        if ($hour >= 0 && $hour <= 23) {
                            $numberOfCharactersToRemove = $position + strlen($hour);
                            $datetimeElements['hour'] = (int)$hour;
                            break;
                        }
                        // no break
                    case 'k':
                        if (!isset($hour)) {
                            $hour = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                        }
                        if ($hour >= 1 && $hour <= 24) {
                            $numberOfCharactersToRemove = $position + strlen($hour);
                            if ((int)$hour === 24) {
                                $hour = 0;
                            }
                            $datetimeElements['hour'] = (int)$hour;
                            break;
                        } else {
                            throw new Exception\InvalidParseStringException('Unable to match number string to any hour format.', 1280488645);
                        }
                        // no break
                    case 'a':
                        $dayPeriods = $localizedLiterals['dayPeriods']['format']['wide'];
                        $positionOfDayPeriod = strpos($datetimeToParse, $dayPeriods['am']);
                        if ($positionOfDayPeriod !== false) {
                            $numberOfCharactersToRemove = $positionOfDayPeriod + strlen($dayPeriods['am']);
                        } else {
                            $positionOfDayPeriod = strpos($datetimeToParse, $dayPeriods['pm']);
                            if ($positionOfDayPeriod !== false) {
                                $numberOfCharactersToRemove = $positionOfDayPeriod + strlen($dayPeriods['pm']);
                                $timeIsPm = true;
                            } else {
                                throw new Exception\InvalidParseStringException('Unable to match any day period.', 1280489183);
                            }
                        }
                        break;
                    case 'm':
                        $minute = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                        if ($minute < 0 && $minute > 59) {
                            throw new Exception\InvalidParseStringException('Expected minute is out of range.', 1280489411);
                        }
                        $numberOfCharactersToRemove = $position + strlen($minute);
                        $datetimeElements['minute'] = (int)$minute;
                        break;
                    case 's':
                        $second = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                        if ($second < 0 && $second > 59) {
                            throw new Exception\InvalidParseStringException('Expected second is out of range.', 1280489412);
                        }
                        $numberOfCharactersToRemove = $position + strlen($second);
                        $datetimeElements['second'] = (int)$second;
                        break;
                    case 'd':
                        $day = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                        if ($day < 1 && $day > 31) {
                            throw new Exception\InvalidParseStringException('Expected day is out of range.', 1280489413);
                        }
                        $numberOfCharactersToRemove = $position + strlen($day);
                        $datetimeElements['day'] = (int)$day;
                        break;
                    case 'M':
                    case 'L':
                        $typeOfLiteral = ($subformat[0] === 'L') ? 'stand-alone' : 'format';
                        switch ($lengthOfSubformat) {
                            case 1:
                            case 2:
                                try {
                                    $month = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                                    if ($month >= 1 && $month <= 31) {
                                        $numberOfCharactersToRemove = $position + strlen($month);
                                        $datetimeElements['month'] = (int)$month;
                                        break;
                                    }
                                } catch (Exception\InvalidParseStringException $exception) {
                                    // Try to match month's name by cases below
                                }
                            case 3:
                                foreach ($localizedLiterals['months'][$typeOfLiteral]['abbreviated'] as $monthId => $monthName) {
                                    $positionOfMonthName = strpos($datetimeToParse, $monthName);
                                    if ($positionOfMonthName !== false) {
                                        $numberOfCharactersToRemove = $positionOfMonthName + strlen($monthName);
                                        $datetimeElements['month'] = (int)$monthId;
                                        break;
                                    }
                                }

                                if ($datetimeElements['month'] !== null) {
                                    break;
                                }
                                // no break
                            case 4:
                                foreach ($localizedLiterals['months'][$typeOfLiteral]['wide'] as $monthId => $monthName) {
                                    $positionOfMonthName = strpos($datetimeToParse, $monthName);
                                    if ($positionOfMonthName !== false) {
                                        $numberOfCharactersToRemove = $positionOfMonthName + strlen($monthName);
                                        $datetimeElements['month'] = (int)$monthId;
                                        break;
                                    }
                                }

                                if ($datetimeElements['month'] === null) {
                                    throw new Exception\InvalidParseStringException('Neither month name or number were matched.', 1280497950);
                                }
                                // no break
                            default:
                                throw new InvalidArgumentException('Cannot parse formats with narrow month pattern as it is not unique.', 1280495827);
                        }
                        break;
                    case 'y':
                        $year = $this->extractNumberAndGetPosition($datetimeToParse, $position);
                        $numberOfCharactersToRemove = $position + strlen($year);

                        /** @todo Two digits date (like 99) shoud be handled here somehow **/
                        $datetimeElements['year'] = (int)$year;
                        break;
                    case 'v':
                    case 'z':
                        if ($lengthOfSubformat <= 3) {
                            $firstPattern = self::PATTERN_MATCH_LENIENT_TIMEZONE_ABBREVIATION;
                            $secondPattern = self::PATTERN_MATCH_LENIENT_TIMEZONE_TZ;
                        } else {
                            $firstPattern = self::PATTERN_MATCH_LENIENT_TIMEZONE_TZ;
                            $secondPattern = self::PATTERN_MATCH_LENIENT_TIMEZONE_ABBREVIATION;
                        }

                        if (preg_match($firstPattern, $datetimeToParse, $matches) === 0) {
                            if (preg_match($secondPattern, $datetimeToParse, $matches) === 0) {
                                throw new Exception\InvalidParseStringException('Expected timezone identifier was not found.', 1280492312);
                            }
                        }

                        $timezone = $matches[0];
                        $numberOfCharactersToRemove = strpos($datetimeToParse, $timezone) + strlen($timezone);
                        $datetimeElements['timezone'] = $matches[0];
                        break;
                    case 'D':
                    case 'F':
                    case 'w':
                    case 'W':
                    case 'Q':
                    case 'q':
                    case 'G':
                    case 'S':
                    case 'E':
                    case 'Y':
                    case 'u':
                    case 'l':
                    case 'g':
                    case 'e':
                    case 'c':
                    case 'A':
                    case 'Z':
                    case 'V':
                        // Silently ignore unsupported formats or formats that there is no need to parse
                        break;
                    default:
                        throw new InvalidArgumentException('Unexpected format symbol, "' . $subformat[0] . '" detected for date / time parsing.', 1279965529);
                }

                if ($using12HourClock && $timeIsPm) {
                    $datetimeElements['hour'] += 12;
                    $timeIsPm = false;
                }

                if ($numberOfCharactersToRemove > 0) {
                    $datetimeToParse = substr_replace($datetimeToParse, '', 0, $numberOfCharactersToRemove);
                }
            } catch (Exception\InvalidParseStringException $exception) {
                // Matching failed, but in lenient mode we ignore it and try to match next element
                continue;
            }
        }

        return $datetimeElements;
    }

    /**
     * Extracts one or two-digit number from the beginning of the string.
     *
     * If the number has certainly two digits, $isTwoDigits can be set to true
     * so no additional checking is done (this implies from some date/time
     * formats, like 'hh').
     *
     * Number is also checked for constraints: minimum and maximum value.
     *
     * @param string $datetimeToParse Date/time to be parsed
     * @param boolean $isTwoDigits true if number has surely two digits, false if it has one or two digits
     * @param int $minValue
     * @param int $maxValue
     * @return int Parsed number
     * @throws Exception\InvalidParseStringException When string cannot be parsed or number does not conforms constraints
     */
    protected function extractAndCheckNumber($datetimeToParse, $isTwoDigits, $minValue, $maxValue)
    {
        if ($isTwoDigits || is_numeric($datetimeToParse[1])) {
            $number = substr($datetimeToParse, 0, 2);
        } else {
            $number = $datetimeToParse[0];
        }

        if (is_numeric($number)) {
            $number = (int)$number;

            if ($number <= $maxValue || $number >= $minValue) {
                return $number;
            }
        }

        throw new Exception\InvalidParseStringException('Expected one or two-digit number not found at the beginning of the string.', 1279963654);
    }

    /**
     * Extracts and returns first integer number encountered in provided string.
     *
     * Searches for first digit and extracts all adjacent digits. Also returns
     * position of first digit in string.
     *
     * @param string $datetimeToParse String to search number in
     * @param int $position Index of first digit in string
     * @return string Extracted number
     * @throws Exception\InvalidParseStringException When no digit found in string
     */
    protected function extractNumberAndGetPosition($datetimeToParse, &$position)
    {
        $characters = str_split($datetimeToParse);

        $number = '';
        $numberStarted = false;
        foreach ($characters as $index => $character) {
            if (ord($character) >= 48 && ord($character) <= 57) {
                if (!$numberStarted) {
                    $numberStarted = true;
                    $position = $index;
                }
                $number .= $character;
            } elseif ($numberStarted) {
                return $number;
            }
        }

        if ($numberStarted) {
            return $number;
        }

        throw new Exception\InvalidParseStringException('Expected number not found in the string.', 1280498431);
    }
}


text:
package org.wso2.carbon.esb.mediator.test.xquery;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;

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

/**
 * Test:Empty Soap Request is not being processed in XQuery Mediator
 * https://wso2.org/jira/browse/CARBON-13345
 */
public class XQueryEmptyEmptySoapRequestTestCase extends ESBIntegrationTest {
    private OMElement response;

    @BeforeClass(alwaysRun = true)
    public void deployArtifacts() throws Exception {
        super.init();
        loadESBConfigurationFromClasspath("/artifacts/ESB/mediatorconfig/xquery/xquery_empty_soap_request.xml");
    }

    @Test(groups = "wso2.esb", description = "Tests-XQuery test on empty message body")
    public void testEmptyMessageBody() throws AxisFault, XMLStreamException {
        OMElement payload = null;
        response=axis2Client.sendSimpleStockQuoteRequest(getProxyServiceURLHttp("empty"),null, payload);
        assertNotNull(response,"Response is null");
        assertEquals(response.getFirstElement().getFirstChildWithName
                (new QName("http://services.samples/xsd", "symbol")).getText(),
                     "IBM", "Tag does not match");

    }

    @AfterClass(alwaysRun = true)
    public void stop() throws Exception {
        super.cleanup();
    }
}


text:
public class Vector2D implements Iterator<Integer> {
    Deque<Iterator<Integer>> stack;
    public Vector2D(List<List<Integer>> vec2d) {
        stack = new ArrayDeque();
        for (int i = vec2d.size() - 1; i >= 0; i--) {
            List<Integer> list = vec2d.get(i);
            if (list.iterator().hasNext()) {
                stack.push(list.iterator());
            }
        }
    }

    @Override
    public Integer next() {
        Iterator<Integer> i = stack.pop();
        int res = i.next();
        if (i.hasNext())
            stack.push(i);
        return res;
    }

    @Override
    public boolean hasNext() {
        return !stack.isEmpty();
    }
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.hasNext()) v[f()] = i.next();
 */


text:
namespace crypto {

// Mock Keychain wrapper for testing code that interacts with the OS X
// Keychain.
//
// Note that "const" is pretty much meaningless for this class; the const-ness
// of AppleKeychain doesn't apply to the actual keychain data, so all of the
// Mock data is mutable; don't assume that it won't change over the life of
// tests.
class CRYPTO_EXPORT MockAppleKeychain : public AppleKeychain {
 public:
  MockAppleKeychain();

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

  ~MockAppleKeychain() override;

  // AppleKeychain implementation.
  OSStatus FindGenericPassword(UInt32 serviceNameLength,
                               const char* serviceName,
                               UInt32 accountNameLength,
                               const char* accountName,
                               UInt32* passwordLength,
                               void** passwordData,
                               AppleSecKeychainItemRef* itemRef) const override;
  OSStatus ItemFreeContent(void* data) const override;
  OSStatus AddGenericPassword(UInt32 serviceNameLength,
                              const char* serviceName,
                              UInt32 accountNameLength,
                              const char* accountName,
                              UInt32 passwordLength,
                              const void* passwordData,
                              AppleSecKeychainItemRef* itemRef) const override;

  // Returns the password that OSCrypt uses to generate its encryption key.
  std::string GetEncryptionPassword() const;

#if !BUILDFLAG(IS_IOS)
  OSStatus ItemDelete(SecKeychainItemRef itemRef) const override;
#endif  // !BUILDFLAG(IS_IOS)

  // |FindGenericPassword()| can return different results depending on user
  // interaction with the system Keychain.  For mocking purposes we allow the
  // user of this class to specify the result code of the
  // |FindGenericPassword()| call so we can simulate the result of different
  // user interactions.
  void set_find_generic_result(OSStatus result) {
    find_generic_result_ = result;
  }

  // Returns the true if |AddGenericPassword()| was called.
  bool called_add_generic() const { return called_add_generic_; }

  // Returns the number of allocations - deallocations for password data.
  int password_data_count() const { return password_data_count_; }

 private:
  // Result code for the |FindGenericPassword()| method.
  OSStatus find_generic_result_;

  // Records whether |AddGenericPassword()| gets called.
  mutable bool called_add_generic_;

  // Tracks the allocations and frees of password data in |FindGenericPassword|
  // and |ItemFreeContent|.
  mutable int password_data_count_;
};

}  // namespace crypto

#endif  // CRYPTO_MOCK_APPLE_KEYCHAIN_H_


text:
#region BSD License

// Copyright (c) 2015, Michael Bailey (Marcus Llewellyn)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
//    contributors may be used to endorse or promote products derived from this
//    software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#endregion BSD License

using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ChatLogCleaner
{
    public partial class MainForm : Form
    {
        private long PreviousSize = 0;
        private long NewSize = 0;
        private string ViewerLog = string.Empty;
        private string CleanLog = string.Empty;

        private Font ChatFont = null;
        private Color Forecolor = new Color();
        private Color Backcolor = new Color();

        private OpenFileDialog ViewerLogDialog = new OpenFileDialog();
        private SaveFileDialog CleanLogDialog = new SaveFileDialog();
        private FontDialog ChatFontDialog = new FontDialog();
        private ColorDialog ForecolorDialog = new ColorDialog();
        private ColorDialog BackcolorDialog = new ColorDialog();
        private FileSystemWatcher FileWatcher = new FileSystemWatcher();

        private ChatDisplay frmChat = new ChatDisplay();

        public MainForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FileWatcher.Changed += new FileSystemEventHandler(FileWatcher_OnChanged);

            ChatFont = this.Font;

            ViewerLog = CLC.Default.Target;
            CleanLog = CLC.Default.Cleaned;
            Forecolor = CLC.Default.Forecolor;
            Backcolor = CLC.Default.Backcolor;
            ChatFont = CLC.Default.Font;

            txtLogTargetPath.Text = ViewerLog;
            txtLogCleanedPath.Text = CleanLog;
            txtFont.Text = ChatFont.Name + ", " + Math.Round(ChatFont.Size).ToString();
            pnlBackcolor.BackColor = Backcolor;
            pnlForecolor.BackColor = Forecolor;

            if (File.Exists(ViewerLog.Trim('"')))
            {
                Console.WriteLine("Loaded");
                btnStartStop.Enabled = true;
            }
            else
            {
                btnStartStop.Enabled = false;
            }
        }

        private void btnViewerLogBrowse_Click(object sender, EventArgs e)
        {
            ViewerLogDialog.FileOk += new CancelEventHandler(LogTarget_FileOK);
            ViewerLogDialog.ShowDialog();
            txtLogTargetPath.Text = ViewerLogDialog.FileName.Trim('"');
            ViewerLog = txtLogTargetPath.Text;
            CLC.Default.Target = ViewerLog;
            CLC.Default.Save();
        }

        private void btnCleanLogBrowse_Click(object sender, EventArgs e)
        {
            CleanLogDialog.FileOk += new CancelEventHandler(LogCleaned_FileOK);
            CleanLogDialog.Filter = "Log File|*.log|Text File|*.txt";
            CleanLogDialog.Title = "Save Cleaned Log File";
            CleanLogDialog.ShowDialog();
            txtLogCleanedPath.Text = CleanLogDialog.FileName.Trim('"');
            CleanLog = txtLogCleanedPath.Text;
            CLC.Default.Cleaned = CleanLog;
            CLC.Default.Save();
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            if (btnStartStop.Text == "Start Cleaning")
            {
                if (chkEmptyLog.Checked)
                {
                    if (File.Exists(CleanLog))
                    {
                        File.Delete(CleanLog);
                    }
                }
                FileWatcher.Path = Path.GetDirectoryName(ViewerLog);
                FileWatcher.Filter = Path.GetFileName(ViewerLog);
                FileWatcher.NotifyFilter = NotifyFilters.Size;
                FileWatcher.EnableRaisingEvents = true;
                btnStartStop.Text = "Stop Cleaning";
                PreviousSize = new FileInfo(ViewerLog).Length;
            }
            else
            {
                FileWatcher.EnableRaisingEvents = false;
                btnStartStop.Text = "Start Cleaning";
            }
        }

        private void btnShowChat_Click(object sender, EventArgs e)
        {
            if (frmChat.IsDisposed)
            {
                frmChat = new ChatDisplay();
            }
            frmChat.LogFile = CleanLog;
            frmChat.ChatFont = ChatFont;
            frmChat.Color = Forecolor;
            frmChat.BackColor = Backcolor;
            frmChat.Show();
        }

        private void btnFont_Click(object sender, EventArgs e)
        {
            ChatFontDialog.Font = ChatFont;
            ChatFontDialog.ShowDialog();
            ChatFont = ChatFontDialog.Font;
            txtFont.Text = ChatFont.Name + ", " + Math.Round(ChatFont.Size).ToString();
            CLC.Default.Font = ChatFont;
            CLC.Default.Save();
        }

        private void btnForecolor_Click(object sender, EventArgs e)
        {
            ForecolorDialog.ShowDialog();
            Forecolor = ForecolorDialog.Color;
            pnlForecolor.BackColor = Forecolor;
            CLC.Default.Forecolor = Forecolor;
            CLC.Default.Save();
        }

        private void btnBackcolor_Click(object sender, EventArgs e)
        {
            BackcolorDialog.ShowDialog();
            Backcolor = BackcolorDialog.Color;
            pnlBackcolor.BackColor = Backcolor;
            CLC.Default.Backcolor = Backcolor;
            CLC.Default.Save();
        }

        private void LogCleaned_FileOK(object sender, CancelEventArgs e)
        {
            CleanLog = CleanLogDialog.FileName;
            if (!File.Exists(CleanLog))
            {
                File.Create(CleanLog);
            }

            if ((File.Exists(CleanLog) && (File.Exists(ViewerLog))))
            {
                btnStartStop.Enabled = true;
            }
        }

        private void LogTarget_FileOK(object sender, CancelEventArgs e)
        {
            ViewerLog = ViewerLogDialog.FileName;
            if ((File.Exists(CleanLog) && (File.Exists(ViewerLog))))
            {
                btnStartStop.Enabled = true;
            }
        }

        private void FileWatcher_OnChanged(object source, FileSystemEventArgs e)
        {
            NewSize = new FileInfo(ViewerLog).Length;

            if (NewSize > PreviousSize)
            {
                string text = ReadTail(ViewerLog, (int)(NewSize - PreviousSize));
                CleanLogLines(text, CleanLog);
                PreviousSize = NewSize;
            }
        }

        private string ReadTail(string filename, int size)
        {
            using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                fs.Seek(-size, SeekOrigin.End);
                byte[] bytes = new byte[size];
                fs.Read(bytes, 0, size);
                return Encoding.Default.GetString(bytes);
            }
        }

        private void CleanLogLines(string text, string filecleaned)
        {
            string[] Lines = text.Split('\n');
            foreach (string s in Lines)
            {
                string parsed = LineParse(s);

                if (parsed.Trim() == String.Empty) continue;

                using (StreamWriter sw = File.AppendText(filecleaned))
                {
                    sw.WriteLine(parsed);
                }
            }
        }

        private string LineParse(string line)
        {
            string TimeStamp = String.Empty;
            string UserName = String.Empty;
            string HGAddress = String.Empty;
            string Message = String.Empty;
            string CleanLine = String.Empty;

            line = line.TrimEnd();
            if (line == String.Empty) return String.Empty;
            if (line == Environment.NewLine) return String.Empty;

            if (line.StartsWith(" "))
            {
                // This is just a multi-line message.
                return line.Trim();
            }

            char[] Delimiters = { ':' };
            string[] Half = line.Substring(20).Split(Delimiters, 2);
            if (Half.Length <= 1) return String.Empty;

            //We need special handling for HG names.
            string[] HGTest = Half[0].Split(' ');
            if (HGTest.Length > 1)
            {
                if (HGTest[1].Contains('@'))
                {
                    string[] hg = line.Substring(20).Split(Delimiters, 3);

                    UserName = hg[0].Split(' ')[0];
                    if (hg.Length == 3)
                    {
                        // This address has a port number.
                        HGAddress = hg[0].Split(' ')[1].TrimStart('@') + ":" + hg[1];
                        Message = hg[2].Trim();
                    }
                    else
                    {
                        // This address has no port number.
                        HGAddress = hg[0].Split(' ')[1].TrimStart('@');
                        Message = hg[1].Trim();
                    }
                }
                else
                {
                    // This wasn't from an HG visitor.
                    UserName = Half[0].Trim();
                    Message = Half[1].Trim();
                }
            }

            // skip grid messages, on/offline notices, and server version shouts.
            Console.WriteLine(Half[0] + Half[1]);
            if (Message == "is online.") return String.Empty;
            if (Message == "is offline.") return String.Empty;
            if (UserName.Contains("Simulator Version")) return String.Empty;
            if (UserName == "Grid") return String.Empty;

            // Reformat timestamps.
            TimeStamp = "[" + line.Substring(12, 6);

            // Look for emotes.
            if ((Message.Length > 3) && (Message.Substring(0, 3) == "/me"))
            {
                Message = Message.Substring(4, Message.Length - 4);
                if (HGAddress == String.Empty)
                {
                    CleanLine = "───\n" + TimeStamp + " " + UserName + " " + Message;
                }
                else
                {
                    CleanLine = "───\n" + TimeStamp + " " + UserName + "@" + HGAddress + " " + Message;
                }
            }
            else
            {
                if (HGAddress == String.Empty)
                {
                    CleanLine = "───\n" + TimeStamp + " <" + UserName + ">\n" + Message;
                }
                else
                {
                    CleanLine = "───\n" + TimeStamp + " <" + UserName + ">\n" + "(" + HGAddress + ")\n" + Message;
                }
            }

            return CleanLine;
        }
    }
}