text:
using fileapi::FileSystemFileUtil;
using fileapi::FileSystemMountPointProvider;
using fileapi::FileSystemOperation;
using fileapi::FileSystemURL;
using fileapi::FileUpdateObserver;
using fileapi::LocalFileSystemOperation;
using fileapi::UpdateObserverList;
using webkit_blob::BlobData;
using webkit_blob::BlobStorageController;

namespace content {

namespace {

void RevokeFilePermission(int child_id, const base::FilePath& path) {
  ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile(
    child_id, path);
}

}  // namespace

FileAPIMessageFilter::FileAPIMessageFilter(
    int process_id,
    net::URLRequestContextGetter* request_context_getter,
    fileapi::FileSystemContext* file_system_context,
    ChromeBlobStorageContext* blob_storage_context)
    : process_id_(process_id),
      context_(file_system_context),
      request_context_getter_(request_context_getter),
      request_context_(NULL),
      blob_storage_context_(blob_storage_context) {
  DCHECK(context_);
  DCHECK(request_context_getter_.get());
  DCHECK(blob_storage_context);
}

FileAPIMessageFilter::FileAPIMessageFilter(
    int process_id,
    net::URLRequestContext* request_context,
    fileapi::FileSystemContext* file_system_context,
    ChromeBlobStorageContext* blob_storage_context)
    : process_id_(process_id),
      context_(file_system_context),
      request_context_(request_context),
      blob_storage_context_(blob_storage_context) {
  DCHECK(context_);
  DCHECK(request_context_);
  DCHECK(blob_storage_context);
}

void FileAPIMessageFilter::OnChannelConnected(int32 peer_pid) {
  BrowserMessageFilter::OnChannelConnected(peer_pid);

  if (request_context_getter_.get()) {
    DCHECK(!request_context_);
    request_context_ = request_context_getter_->GetURLRequestContext();
    request_context_getter_ = NULL;
    DCHECK(request_context_);
  }
}

void FileAPIMessageFilter::OnChannelClosing() {
  BrowserMessageFilter::OnChannelClosing();

  // Unregister all the blob URLs that are previously registered in this
  // process.
  for (base::hash_set<std::string>::const_iterator iter = blob_urls_.begin();
       iter != blob_urls_.end(); ++iter) {
    blob_storage_context_->controller()->RemoveBlob(GURL(*iter));
  }

  in_transit_snapshot_files_.clear();

  // Close all files that are previously OpenFile()'ed in this process.
  if (!on_close_callbacks_.IsEmpty()) {
    DLOG(INFO)
        << "File API: Renderer process shut down before NotifyCloseFile"
        << " for " << on_close_callbacks_.size() << " files opened in PPAPI";
  }

  for (OnCloseCallbackMap::iterator itr(&on_close_callbacks_);
       !itr.IsAtEnd(); itr.Advance()) {
    itr.GetCurrentValue()->Run();
  }

  on_close_callbacks_.Clear();
  operation_runner()->Shutdown();
  operations_.clear();
}

base::TaskRunner* FileAPIMessageFilter::OverrideTaskRunnerForMessage(
    const IPC::Message& message) {
  if (message.type() == FileSystemHostMsg_SyncGetPlatformPath::ID)
    return context_->task_runners()->file_task_runner();
  return NULL;
}

bool FileAPIMessageFilter::OnMessageReceived(
    const IPC::Message& message, bool* message_was_ok) {
  *message_was_ok = true;
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(FileAPIMessageFilter, message, *message_was_ok)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_Open, OnOpen)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_DeleteFileSystem, OnDeleteFileSystem)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_Move, OnMove)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_Copy, OnCopy)
    IPC_MESSAGE_HANDLER(FileSystemMsg_Remove, OnRemove)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_ReadMetadata, OnReadMetadata)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_Create, OnCreate)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_Exists, OnExists)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_ReadDirectory, OnReadDirectory)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_Write, OnWrite)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_Truncate, OnTruncate)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_TouchFile, OnTouchFile)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_CancelWrite, OnCancel)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_OpenFile, OnOpenFile)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_NotifyCloseFile, OnNotifyCloseFile)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_CreateSnapshotFile,
                        OnCreateSnapshotFile)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_DidReceiveSnapshotFile,
                        OnDidReceiveSnapshotFile)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_WillUpdate, OnWillUpdate)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_DidUpdate, OnDidUpdate)
    IPC_MESSAGE_HANDLER(FileSystemHostMsg_SyncGetPlatformPath,
                        OnSyncGetPlatformPath)
    IPC_MESSAGE_HANDLER(BlobHostMsg_StartBuildingBlob, OnStartBuildingBlob)
    IPC_MESSAGE_HANDLER(BlobHostMsg_AppendBlobDataItem, OnAppendBlobDataItem)
    IPC_MESSAGE_HANDLER(BlobHostMsg_SyncAppendSharedMemory,
                        OnAppendSharedMemory)
    IPC_MESSAGE_HANDLER(BlobHostMsg_FinishBuildingBlob, OnFinishBuildingBlob)
    IPC_MESSAGE_HANDLER(BlobHostMsg_CloneBlob, OnCloneBlob)
    IPC_MESSAGE_HANDLER(BlobHostMsg_RemoveBlob, OnRemoveBlob)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP_EX()
  return handled;
}

FileAPIMessageFilter::~FileAPIMessageFilter() {}

void FileAPIMessageFilter::BadMessageReceived() {
  RecordAction(UserMetricsAction("BadMessageTerminate_FAMF"));
  BrowserMessageFilter::BadMessageReceived();
}

void FileAPIMessageFilter::OnOpen(
    int request_id, const GURL& origin_url, fileapi::FileSystemType type,
    int64 requested_size, bool create) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (type == fileapi::kFileSystemTypeTemporary) {
    RecordAction(UserMetricsAction("OpenFileSystemTemporary"));
  } else if (type == fileapi::kFileSystemTypePersistent) {
    RecordAction(UserMetricsAction("OpenFileSystemPersistent"));
  }
  // TODO(kinuko): Use this mode for IPC too.
  fileapi::OpenFileSystemMode mode =
      create ? fileapi::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT
             : fileapi::OPEN_FILE_SYSTEM_FAIL_IF_NONEXISTENT;
  context_->OpenFileSystem(origin_url, type, mode, base::Bind(
      &FileAPIMessageFilter::DidOpenFileSystem, this, request_id));
}

void FileAPIMessageFilter::OnDeleteFileSystem(
    int request_id,
    const GURL& origin_url,
    fileapi::FileSystemType type) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  context_->DeleteFileSystem(origin_url, type, base::Bind(
      &FileAPIMessageFilter::DidDeleteFileSystem, this, request_id));
}

void FileAPIMessageFilter::OnMove(
    int request_id, const GURL& src_path, const GURL& dest_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  FileSystemURL src_url(context_->CrackURL(src_path));
  FileSystemURL dest_url(context_->CrackURL(dest_path));
  const int src_permissions =
      fileapi::kReadFilePermissions | fileapi::kWriteFilePermissions;
  if (!HasPermissionsForFile(src_url, src_permissions, &error) ||
      !HasPermissionsForFile(
          dest_url, fileapi::kCreateFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->Move(
      src_url, dest_url,
      base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
}

void FileAPIMessageFilter::OnCopy(
    int request_id, const GURL& src_path, const GURL& dest_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  FileSystemURL src_url(context_->CrackURL(src_path));
  FileSystemURL dest_url(context_->CrackURL(dest_path));
  if (!HasPermissionsForFile(src_url, fileapi::kReadFilePermissions, &error) ||
      !HasPermissionsForFile(
          dest_url, fileapi::kCreateFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->Copy(
      src_url, dest_url,
      base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
}

void FileAPIMessageFilter::OnRemove(
    int request_id, const GURL& path, bool recursive) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  FileSystemURL url(context_->CrackURL(path));
  if (!HasPermissionsForFile(url, fileapi::kWriteFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->Remove(
      url, recursive,
      base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
}

void FileAPIMessageFilter::OnReadMetadata(
    int request_id, const GURL& path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  FileSystemURL url(context_->CrackURL(path));
  if (!HasPermissionsForFile(url, fileapi::kReadFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->GetMetadata(
      url, base::Bind(&FileAPIMessageFilter::DidGetMetadata, this, request_id));
}

void FileAPIMessageFilter::OnCreate(
    int request_id, const GURL& path, bool exclusive,
    bool is_directory, bool recursive) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  FileSystemURL url(context_->CrackURL(path));
  if (!HasPermissionsForFile(url, fileapi::kCreateFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  if (is_directory) {
    operations_[request_id] = operation_runner()->CreateDirectory(
        url, exclusive, recursive,
        base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
  } else {
    operations_[request_id] = operation_runner()->CreateFile(
        url, exclusive,
        base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
  }
}

void FileAPIMessageFilter::OnExists(
    int request_id, const GURL& path, bool is_directory) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  FileSystemURL url(context_->CrackURL(path));
  if (!HasPermissionsForFile(url, fileapi::kReadFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  if (is_directory) {
    operations_[request_id] = operation_runner()->DirectoryExists(
        url,
        base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
  } else {
    operations_[request_id] = operation_runner()->FileExists(
        url,
        base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
  }
}

void FileAPIMessageFilter::OnReadDirectory(
    int request_id, const GURL& path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  FileSystemURL url(context_->CrackURL(path));
  if (!HasPermissionsForFile(url, fileapi::kReadFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->ReadDirectory(
      url, base::Bind(&FileAPIMessageFilter::DidReadDirectory,
                      this, request_id));
}

void FileAPIMessageFilter::OnWrite(
    int request_id,
    const GURL& path,
    const GURL& blob_url,
    int64 offset) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (!request_context_) {
    // We can't write w/o a request context, trying to do so will crash.
    NOTREACHED();
    return;
  }

  FileSystemURL url(context_->CrackURL(path));
  base::PlatformFileError error;
  if (!HasPermissionsForFile(url, fileapi::kWriteFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->Write(
      request_context_, url, blob_url, offset,
      base::Bind(&FileAPIMessageFilter::DidWrite, this, request_id));
}

void FileAPIMessageFilter::OnTruncate(
    int request_id,
    const GURL& path,
    int64 length) {
  base::PlatformFileError error;
  FileSystemURL url(context_->CrackURL(path));
  if (!HasPermissionsForFile(url, fileapi::kWriteFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->Truncate(
      url, length,
      base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
}

void FileAPIMessageFilter::OnTouchFile(
    int request_id,
    const GURL& path,
    const base::Time& last_access_time,
    const base::Time& last_modified_time) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  FileSystemURL url(context_->CrackURL(path));
  base::PlatformFileError error;
  if (!HasPermissionsForFile(url, fileapi::kCreateFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->TouchFile(
      url, last_access_time, last_modified_time,
      base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
}

void FileAPIMessageFilter::OnCancel(
    int request_id,
    int request_id_to_cancel) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  OperationsMap::iterator found = operations_.find(request_id_to_cancel);
  if (found != operations_.end()) {
    // The cancel will eventually send both the write failure and the cancel
    // success.
    operation_runner()->Cancel(
        found->second,
        base::Bind(&FileAPIMessageFilter::DidFinish, this, request_id));
  } else {
    // The write already finished; report that we failed to stop it.
    Send(new FileSystemMsg_DidFail(
        request_id, base::PLATFORM_FILE_ERROR_INVALID_OPERATION));
  }
}

void FileAPIMessageFilter::OnOpenFile(
    int request_id, const GURL& path, int file_flags) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  const int open_permissions = base::PLATFORM_FILE_OPEN |
                               (file_flags & fileapi::kOpenFilePermissions);
  FileSystemURL url(context_->CrackURL(path));
  if (!HasPermissionsForFile(url, open_permissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  quota::QuotaLimitType quota_policy = quota::kQuotaLimitTypeUnknown;
  quota::QuotaManagerProxy* quota_manager_proxy =
      context_->quota_manager_proxy();
  CHECK(quota_manager_proxy);
  CHECK(quota_manager_proxy->quota_manager());

  if (quota_manager_proxy->quota_manager()->IsStorageUnlimited(
          url.origin(), FileSystemTypeToQuotaStorageType(url.type()))) {
    quota_policy = quota::kQuotaLimitTypeUnlimited;
  } else {
    quota_policy = quota::kQuotaLimitTypeLimited;
  }

  operations_[request_id] = operation_runner()->OpenFile(
      url, file_flags, peer_handle(),
      base::Bind(&FileAPIMessageFilter::DidOpenFile, this, request_id,
                 quota_policy));
}

void FileAPIMessageFilter::OnNotifyCloseFile(int file_open_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  // Remove |file_open_id| from the map of |on_close_callback|s.
  // It must only be called for a ID that is successfully opened and enrolled in
  // DidOpenFile.
  base::Closure* on_close_callback = on_close_callbacks_.Lookup(file_open_id);
  if (on_close_callback && !on_close_callback->is_null()) {
    on_close_callback->Run();
    on_close_callbacks_.Remove(file_open_id);
  }
}

void FileAPIMessageFilter::OnWillUpdate(const GURL& path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  FileSystemURL url(context_->CrackURL(path));
  if (!url.is_valid())
    return;
  const UpdateObserverList* observers =
      context_->GetUpdateObservers(url.type());
  if (!observers)
    return;
  observers->Notify(&FileUpdateObserver::OnStartUpdate, MakeTuple(url));
}

void FileAPIMessageFilter::OnDidUpdate(const GURL& path, int64 delta) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  FileSystemURL url(context_->CrackURL(path));
  if (!url.is_valid())
    return;
  const UpdateObserverList* observers =
      context_->GetUpdateObservers(url.type());
  if (!observers)
    return;
  observers->Notify(&FileUpdateObserver::OnUpdate, MakeTuple(url, delta));
  observers->Notify(&FileUpdateObserver::OnEndUpdate, MakeTuple(url));
}

void FileAPIMessageFilter::OnSyncGetPlatformPath(
    const GURL& path, base::FilePath* platform_path) {
  SyncGetPlatformPath(context_, process_id_, path, platform_path);
}

void FileAPIMessageFilter::OnCreateSnapshotFile(
    int request_id, const GURL& path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  FileSystemURL url(context_->CrackURL(path));

  // Make sure if this file can be read by the renderer as this is
  // called when the renderer is about to create a new File object
  // (for reading the file).
  base::PlatformFileError error;
  if (!HasPermissionsForFile(url, fileapi::kReadFilePermissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  operations_[request_id] = operation_runner()->CreateSnapshotFile(
      url,
      base::Bind(&FileAPIMessageFilter::DidCreateSnapshot,
                 this, request_id, url));
}

void FileAPIMessageFilter::OnDidReceiveSnapshotFile(int request_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  in_transit_snapshot_files_.erase(request_id);
}

void FileAPIMessageFilter::OnStartBuildingBlob(const GURL& url) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  blob_storage_context_->controller()->StartBuildingBlob(url);
  blob_urls_.insert(url.spec());
}

void FileAPIMessageFilter::OnAppendBlobDataItem(
    const GURL& url, const BlobData::Item& item) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (item.type() == BlobData::Item::TYPE_FILE_FILESYSTEM) {
    base::PlatformFileError error;
    FileSystemURL filesystem_url(context_->CrackURL(item.url()));
    if (!HasPermissionsForFile(filesystem_url,
                               fileapi::kReadFilePermissions, &error)) {
      OnRemoveBlob(url);
      return;
    }
  }
  if (item.type() == BlobData::Item::TYPE_FILE &&
      !ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
          process_id_, item.path())) {
    OnRemoveBlob(url);
    return;
  }
  if (item.length() == 0) {
    BadMessageReceived();
    return;
  }
  blob_storage_context_->controller()->AppendBlobDataItem(url, item);
}

void FileAPIMessageFilter::OnAppendSharedMemory(
    const GURL& url, base::SharedMemoryHandle handle, size_t buffer_size) {
  DCHECK(base::SharedMemory::IsHandleValid(handle));
  if (!buffer_size) {
    BadMessageReceived();
    return;
  }
#if defined(OS_WIN)
  base::SharedMemory shared_memory(handle, true, peer_handle());
#else
  base::SharedMemory shared_memory(handle, true);
#endif
  if (!shared_memory.Map(buffer_size)) {
    OnRemoveBlob(url);
    return;
  }

  BlobData::Item item;
  item.SetToSharedBytes(static_cast<char*>(shared_memory.memory()),
                        buffer_size);
  blob_storage_context_->controller()->AppendBlobDataItem(url, item);
}

void FileAPIMessageFilter::OnFinishBuildingBlob(
    const GURL& url, const std::string& content_type) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  blob_storage_context_->controller()->FinishBuildingBlob(url, content_type);
}

void FileAPIMessageFilter::OnCloneBlob(
    const GURL& url, const GURL& src_url) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  blob_storage_context_->controller()->CloneBlob(url, src_url);
  blob_urls_.insert(url.spec());
}

void FileAPIMessageFilter::OnRemoveBlob(const GURL& url) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  blob_storage_context_->controller()->RemoveBlob(url);
  blob_urls_.erase(url.spec());
}

void FileAPIMessageFilter::DidFinish(int request_id,
                                     base::PlatformFileError result) {
  if (result == base::PLATFORM_FILE_OK)
    Send(new FileSystemMsg_DidSucceed(request_id));
  else
    Send(new FileSystemMsg_DidFail(request_id, result));
  operations_.erase(request_id);
}

void FileAPIMessageFilter::DidGetMetadata(
    int request_id,
    base::PlatformFileError result,
    const base::PlatformFileInfo& info) {
  // TODO(satorux): Remove the third parameter. crbug.com/248480
  if (result == base::PLATFORM_FILE_OK)
    Send(new FileSystemMsg_DidReadMetadata(request_id, info, base::FilePath()));
  else
    Send(new FileSystemMsg_DidFail(request_id, result));
  operations_.erase(request_id);
}

void FileAPIMessageFilter::DidReadDirectory(
    int request_id,
    base::PlatformFileError result,
    const std::vector<fileapi::DirectoryEntry>& entries,
    bool has_more) {
  if (result == base::PLATFORM_FILE_OK)
    Send(new FileSystemMsg_DidReadDirectory(request_id, entries, has_more));
  else
    Send(new FileSystemMsg_DidFail(request_id, result));
  operations_.erase(request_id);
}

void FileAPIMessageFilter::DidOpenFile(int request_id,
                                       quota::QuotaLimitType quota_policy,
                                       base::PlatformFileError result,
                                       base::PlatformFile file,
                                       const base::Closure& on_close_callback,
                                       base::ProcessHandle peer_handle) {
  if (result == base::PLATFORM_FILE_OK) {
    IPC::PlatformFileForTransit file_for_transit =
        file != base::kInvalidPlatformFileValue ?
            IPC::GetFileHandleForProcess(file, peer_handle, true) :
            IPC::InvalidPlatformFileForTransit();
    int file_open_id = on_close_callbacks_.Add(
        new base::Closure(on_close_callback));

    Send(new FileSystemMsg_DidOpenFile(request_id,
                                       file_for_transit,
                                       file_open_id,
                                       quota_policy));
  } else {
    Send(new FileSystemMsg_DidFail(request_id,
                                   result));
  }
  operations_.erase(request_id);
}

void FileAPIMessageFilter::DidWrite(int request_id,
                                    base::PlatformFileError result,
                                    int64 bytes,
                                    bool complete) {
  if (result == base::PLATFORM_FILE_OK) {
    Send(new FileSystemMsg_DidWrite(request_id, bytes, complete));
    if (complete)
      operations_.erase(request_id);
  } else {
    Send(new FileSystemMsg_DidFail(request_id, result));
    operations_.erase(request_id);
  }
}

void FileAPIMessageFilter::DidOpenFileSystem(int request_id,
                                             base::PlatformFileError result,
                                             const std::string& name,
                                             const GURL& root) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (result == base::PLATFORM_FILE_OK) {
    DCHECK(root.is_valid());
    Send(new FileSystemMsg_DidOpenFileSystem(request_id, name, root));
  } else {
    Send(new FileSystemMsg_DidFail(request_id, result));
  }
  // For OpenFileSystem we do not create a new operation, so no unregister here.
}

void FileAPIMessageFilter::DidDeleteFileSystem(
    int request_id,
    base::PlatformFileError result) {
  if (result == base::PLATFORM_FILE_OK)
    Send(new FileSystemMsg_DidSucceed(request_id));
  else
    Send(new FileSystemMsg_DidFail(request_id, result));
  // For DeleteFileSystem we do not create a new operation,
  // so no unregister here.
}

void FileAPIMessageFilter::DidCreateSnapshot(
    int request_id,
    const fileapi::FileSystemURL& url,
    base::PlatformFileError result,
    const base::PlatformFileInfo& info,
    const base::FilePath& platform_path,
    const scoped_refptr<webkit_blob::ShareableFileReference>& snapshot_file) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  operations_.erase(request_id);

  if (result != base::PLATFORM_FILE_OK) {
    Send(new FileSystemMsg_DidFail(request_id, result));
    return;
  }

  if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
          process_id_, platform_path)) {
    // In order for the renderer to be able to read the file, it must be granted
    // read permission for the file's platform path. By now, it has already been
    // verified that the renderer has sufficient permissions to read the file.
    // It is still possible that ChildProcessSecurityPolicyImpl doesn't reflect
    // that the renderer can read the file's platform path. If this is the case
    // the renderer should be granted read permission for the file's platform
    // path. This can happen in the following situations:
    // - the file comes from sandboxed filesystem. Reading sandboxed files is
    //   always permitted, but only implicitly.
    // - the underlying filesystem returned newly created snapshot file.
    // - the nominal path differs from the platform path. This can happen even
    //   when the filesystem has been granted permissions. This happens with:
    //   - Drive filesystems
    //   - Picasa filesystems
    //   - iTunes filesystems
    DCHECK(snapshot_file.get() ||
           fileapi::SandboxMountPointProvider::IsSandboxType(url.type()) ||
           url.type() == fileapi::kFileSystemTypeDrive ||
           url.type() == fileapi::kFileSystemTypePicasa ||
           url.type() == fileapi::kFileSystemTypeItunes);
    ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
        process_id_, platform_path);
    if (snapshot_file.get()) {
      // This will revoke all permissions for the file when the last ref
      // of the file is dropped (assuming it's ok).
      snapshot_file->AddFinalReleaseCallback(
          base::Bind(&RevokeFilePermission, process_id_));
    }
  }

  if (snapshot_file.get()) {
    // This ref is held until OnDidReceiveSnapshotFile is called.
    in_transit_snapshot_files_[request_id] = snapshot_file;
  }

  // Return the file info and platform_path.
  Send(new FileSystemMsg_DidCreateSnapshotFile(
               request_id, info, platform_path));
}

bool FileAPIMessageFilter::HasPermissionsForFile(
    const FileSystemURL& url, int permissions, base::PlatformFileError* error) {
  return CheckFileSystemPermissionsForProcess(context_, process_id_, url,
                                              permissions, error);
}

fileapi::FileSystemOperationRunner* FileAPIMessageFilter::operation_runner() {
  return context_->operation_runner();
}

}  // namespace content


text:
namespace {
// Fake request config types for use in tests.
DEFINE_TEST_OVERLAY_REQUEST_CONFIG(FirstConfig);
DEFINE_TEST_OVERLAY_REQUEST_CONFIG(SecondConfig);
DEFINE_TEST_OVERLAY_REQUEST_CONFIG(ThirdConfig);
}  // namespace

using OverlayRequestSupportTest = PlatformTest;

// Tests that OverlayRequestSupport::All() supports arbitrary requests.
TEST_F(OverlayRequestSupportTest, SupportAll) {
  std::unique_ptr<OverlayRequest> first_request =
      OverlayRequest::CreateWithConfig<FirstConfig>();
  std::unique_ptr<OverlayRequest> second_request =
      OverlayRequest::CreateWithConfig<SecondConfig>();

  const OverlayRequestSupport* support = OverlayRequestSupport::All();
  EXPECT_TRUE(support->IsRequestSupported(first_request.get()));
  EXPECT_TRUE(support->IsRequestSupported(second_request.get()));
}

// Tests that OverlayRequestSupport::None() does not support config types.
TEST_F(OverlayRequestSupportTest, SupportNone) {
  std::unique_ptr<OverlayRequest> first_request =
      OverlayRequest::CreateWithConfig<FirstConfig>();
  std::unique_ptr<OverlayRequest> second_request =
      OverlayRequest::CreateWithConfig<SecondConfig>();

  const OverlayRequestSupport* support = OverlayRequestSupport::None();
  EXPECT_FALSE(support->IsRequestSupported(first_request.get()));
  EXPECT_FALSE(support->IsRequestSupported(second_request.get()));
}

// Tests that the SupportsOverlayRequest template returns true only when
// IsRequestSupported() is called with a request with the config type used to
// create the template specialization.
TEST_F(OverlayRequestSupportTest, SupportsRequestTemplate) {
  std::unique_ptr<OverlayRequestSupport> support =
      std::make_unique<SupportsOverlayRequest<FirstConfig>>();

  // Verify that FirstConfig requests are supported.
  std::unique_ptr<OverlayRequest> supported_request =
      OverlayRequest::CreateWithConfig<FirstConfig>();
  EXPECT_TRUE(support->IsRequestSupported(supported_request.get()));

  // Verify that SecondConfig requests are not supported.
  std::unique_ptr<OverlayRequest> unsupported_request =
      OverlayRequest::CreateWithConfig<SecondConfig>();
  EXPECT_FALSE(support->IsRequestSupported(unsupported_request.get()));
}

// Tests that the vector constructor aggregates support.
TEST_F(OverlayRequestSupportTest, AggregateSupport) {
  // Create an aggregate request support for FirstConfig and SecondConfig, then
  // verify that OverlayResponses created with these two configs are supported.
  OverlayRequestSupport support(
      {FirstConfig::RequestSupport(), SecondConfig::RequestSupport()});
  std::unique_ptr<OverlayRequest> first_request =
      OverlayRequest::CreateWithConfig<FirstConfig>();
  EXPECT_TRUE(support.IsRequestSupported(first_request.get()));
  std::unique_ptr<OverlayRequest> second_request =
      OverlayRequest::CreateWithConfig<SecondConfig>();
  EXPECT_TRUE(support.IsRequestSupported(second_request.get()));

  // Check that OverlayResponses created with a different config are not
  // supported.
  std::unique_ptr<OverlayRequest> unsupported_request =
      OverlayRequest::CreateWithConfig<ThirdConfig>();
  EXPECT_FALSE(support.IsRequestSupported(unsupported_request.get()));
}

redpajama_set_name: RedPajamaGithub


text:
var MapViewModel = L.Evented.extend({

    Initialize: function (opts) {
        var options = opts || {};

        var _view = options.view || { lat: 52.08606, lon: 5.17689, zoom: 11 };
        Object.defineProperty(this, 'view', {
            get: function () { return _view; },
            set: function (newView) {
                if (_view !== newView) {
                    _view = newView;
                    this.fire('view', { view: _view });
                }
            }
        });

        var _lead = options.lead || false;
        Object.defineProperty(this, 'lead', {
            get: function () { return _lead; },
            set: function (newLead) {
                if (_lead !== newLead) {
                    _lead = newLead;
                    this.fire('lead', { lead: _lead });
                }
            }
        });

        var _follow = options.follow || true;
        Object.defineProperty(this, 'follow', {
            get: function () { return _follow; },
            set: function (newFollow) {
                if (_follow !== newFollow) {
                    _follow = newFollow;
                    this.fire('follow', { follow: _follow });
                }
            }
        });
    }
});

// util to parse url parameters ie get the lat/lon/zoom/session
function getParameterByName(name, def) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? def : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// base layers via mapbox, mapbox url's
mapboxUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiY29ybmVsaXNzZW5qYSIsImEiOiJjaWo5end1azYwMDN6dWxrbnI3eDd4ZzF0In0.tkDIhjkvxgARGteWbAeqPg';
mapboxAttribution = '© Mapbox © OpenStreetMap';

// define base layers
var baseLayers = {
    "Street": L.tileLayer(mapboxUrl, { id: 'mapbox.streets', attribution: mapboxAttribution }),
    "Grayscale": L.tileLayer(mapboxUrl, { id: 'mapbox.light', attribution: mapboxAttribution }),
    "Satellite": L.tileLayer(mapboxUrl, { id: 'mapbox.streets-satellite', attribution: mapboxAttribution })
};

// create the map
var map = L.map('map', {
    center: [getParameterByName('lat', 52.08606), getParameterByName('lon', 5.17689)],
    zoom: getParameterByName('zoom', 11), maxZoom: 18, minZoom: 2,
    layers: [baseLayers["Street"]], // default enabled layer
    contextmenu: true,
    contextmenuItems:
        getParameterByName('debug', 0) ?
            [
                { text: 'Show coordinates', callback: showCoordinates },
                { text: 'Deselect objects', callback: handleObjectsDeselect }
            ]
        :
            []
});

// set default icon path
L.Icon.Default.imagePath = location.href.substring(0, location.href.lastIndexOf('/') + 1) + 'Content/libs/images/';

// map context menu helper functions
function showCoordinates(e) {
    alert(e.latlng + " (zoom:" + map._zoom + ")");
}

// create basic layer control and add to map
var layerControl = L.control.layers(baseLayers, {}).addTo(map);

// format of mapView (lat,lon,zoom)
map.mapView = function () {
    var center = map.getCenter();
    return {
        lat: center.lat,
        lon: center.lng,
        zoom: map.getZoom(),
        extent: map.getBounds()
    };
};

// send map view (center and zoom level to backend
map._sendMapViewView = function () {
    var center = map.getCenter();
    wsSend({
        type: 'mapView',
        payload: { view: map.mapView() }
    });
    map._lastMapViewSend = Date.now();
};

// map move handler to send current map view (center location and zoom level) to  publisher
map.on('move', function (e) {
    // only handle if from gui (then e contains field orginalEvent)
    if (typeof e.originalEvent !== 'undefined') {
        if (typeof map._lastMapViewSend === 'undefined' || Date.now() - map._lastMapViewSend >= 100)
            map._sendMapViewView();
    }
});

// map zoom handler to send current map view (center location and zoom level) to  publisher
map.on('zoomend', function (e) {
    map._sendMapViewView();
});

// on end of map move always send current map view (center location and zoom level) to  publisher
map.on('moveend', function (e) {
    if (typeof e.originalEvent !== 'undefined') {
        map._sendMapViewView();
    }
});

// send map view (center and zoom level to backend
map.sendMapView = function () {
    var center = map.getCenter();
    wsSend({
        type: 'mapView',
        payload: {
            lead: map.mapViewModel.lead,
            follow: map.mapViewModel.follow,
            view: map.mapView()
        }
    });
    map._lastMapViewSend = Date.now();
};

map.mapViewModel = new MapViewModel();
map.mapViewModel.Initialize();
map.mapViewModel.on('view', function (e) { map.setView([e.view.lat, e.view.lon], e.view.zoom); }, map);


text:
// ==UserScript==
// @name		Github Rawgit Button
// @namespace	eight04.blogspot.com
// @description	An userscript to add "Rawgit" button on github.
// @include		https://github.com/*
// @include		https://gist.github.com/*
// @version		1.2.2
// @grant 		none
// ==/UserScript==

/*
https://gist.github.com/eight04/186267c150a2dfc0580a/raw/812fd7b418e0a157f02caa144a15c55c06ced8ac/uao_decode.py
https://rawgit.com/eight04/186267c150a2dfc0580a/raw/812fd7b418e0a157f02caa144a15c55c06ced8ac/uao_decode.py

https://github.com/eight04/linky-square/raw/master/demo.html
https://rawgit.com/eight04/linky-square/master/demo.html
*/

"use strict";

function replace(){
	// Check if raw-url button exists
	var btns, i;
	btns = document.querySelectorAll(".file-actions a:not(.rawgit)");
	for (i = 0; i < btns.length; i++) {
		if (btns[i].textContent == "Raw") {
			createButton(btns[i]);
		}
	}
}

function createButton(btn) {
	var url = btn.href;
	if (url.indexOf("gist.github.com") >= 0) {
		url = url.replace("gist.github.com", "rawgit.com");
	} else {
		url = url.replace(/github\.com\/([^/]+\/[^/]+)\/raw/, "rawgit.com/$1");
	}

	var newBtn = btn.cloneNode(false);
	newBtn.href = url;
	newBtn.textContent = "Rawgit";
	newBtn.removeAttribute("id");

	btn.parentNode.insertBefore(newBtn, btn.nextSibling);
	btn.classList.add("rawgit");

	if (!btn.parentNode.classList.contains("btn-group")) {
		var parent = btn.parentNode,
			group = document.createElement("div");
		group.className = "btn-group";
		while (parent.childNodes.length) {
			group.appendChild(parent.childNodes[0]);
		}
		parent.appendChild(group);
	}
}

var container =
	document.querySelector("#js-repo-pjax-container") ||
	document.querySelector("#js-pjax-container");

if (container) {
	new MutationObserver(function(){
		replace();
	}).observe(container, {childList: true, subtree: true});
}

replace();


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_6500627</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753462435</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Gemeente Moerdijk > Golden Tulip Zevenbergen</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Gemeente Moerdijk,Golden Tulip Zevenbergen</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Golden Tulip Zevenbergen</Appelation>
        <LocationNameType>hotel</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>4.6101</Longitude>
        <Latitude>51.6442</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/6500627</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { DisplayMode } from '@microsoft/sp-core-library';
import { SiteScriptInfo, SiteDesignInfo } from '@pnp/sp';
import { panelMode } from '../../webparts/siteDesigns/components/IEnumPanel';

export interface ISiteDesignRightsProps {
  SiteDesignSelectedItem: ISiteDesignSelectedItem;
  context: WebPartContext;
  mode: panelMode;
  onDismiss(refresh?: boolean): void;
  showPanel: boolean;
}

interface ISiteDesignSelectedItem {
  key: string;
  Description: string;
  PreviewImageUrl: string;
  SiteScriptIds: string;
  Title: string;
  WebTemplate: string;
  Id: string;
  numberSiteScripts:number;
  IsDefault: boolean;
  PreviewImageAltText:string;
  Version: string;
  runStatus: boolean;
}


text:
package registrytest

import (
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/plugin/pkg/scheduler/algorithm"
)

type Scheduler struct {
	Err     error
	Pod     *api.Pod
	Machine string
}

func (s *Scheduler) Schedule(pod *api.Pod, lister algorithm.MinionLister) (string, error) {
	s.Pod = pod
	return s.Machine, s.Err
}


text:
package parser

type sConst struct {
	Name  string
	Type  string
	Value string
}

type mapofConsts map[string]sConst

func (m mapofConsts) add(s sConst) bool {
	s.resolveName()
	s.resolveType()

	if _, ok := m[s.Name]; !ok {
		m[s.Name] = s
		return true
	}

	return false
}

func (s *sConst) resolveName() {
	s.Name = makeUnexported(lintName(replaceReservedWords(s.Type + s.Value)))
}

func (s *sConst) resolveType() {
	s.Type = makeUnexported(lintName(s.Type))
}


text:
if (typeof Backbone.JQuery == 'undefined') {
  Backbone.JQuery = {};
}
Backbone.JQuery.CollectionView = Backbone.View.extend({
  initialize: function(options) {
    _.bindAll(this, 'render', '_renderOnReorder', '_setupSubviewElement', '_remove', '_add', '_reset');

    options = options || {};
    this.draggingEnabled = typeof options.dragging != 'undefined' ? options.dragging : true;
    this.dragTolerance = options.dragTolerance || 10;
    this.scrollTolerance = options.scrollTolerance || 40;
    this.draggingClass = options.draggingClass || 'dragging';
    this.positionAttribute = options.positionAttribute;
    this.dragConstrainX = options.dragConstrainX || false;
    this.showPlaceholder = typeof options.showPlaceholder != 'undefined' ? options.showPlaceholder : true;
    this.dropMarkerClass = options.dropMarkerClass || 'drop_marker';

    this._subviews = [];
    this._dragState = null;
    this._containerElement = this.getContainer();

    this.collection.bind('add', this._add);
    this.collection.bind('remove', this._remove);
    this.collection.bind('reset', this._reset);

    var self = this;
    this.collection.each(function(model) {
      self._add(model);
    });

    $(document.documentElement).bind('mousemove', function(event) {
      self._handleMouseMove(event);
      event.stopPropagation();
    });
    $(document.documentElement).bind('mouseup', function(event) {
      self._endDrag();
      event.stopPropagation();
    });
  },

  setDraggingEnabled: function(enabled) {
    if (this.draggingEnabled != enabled) {
      this.draggingEnabled = enabled;
      this.refresh();
    }
  },

  getContainer: function() {
    return this.$('ol, ul')[0] || this.el;
  },

  createSubview: function(model) {
    throw "Not implemented";
  },

  getSubviewFromElement: function(element) {
    return _(this._subviews).select(function(v) { return v.el === element; })[0];
  },

  getSubviewFromModel: function(model) {
    return _(this._subviews).select(function(v) { return v.model === model; })[0];
  },

  _setupSubviewElement: function(view) {
    var el = view.render().el;
    if (this.draggingEnabled) {
      el.unselectable = 'on';
      el.draggable = false;
      $(el).bind('mousedown selectstart', function(event) {
        event.preventDefault();
      });
    }

    var self = this;
    $(el).mousedown(function(event) {
      self._beginDrag(event, view);
      event.stopPropagation();
    });
    return el;
  },

  _add: function(model) {
    var view = this.createSubview(model);
    if (view) {
      this._subviews.push(view);

      // FIXME: This is a lazy way of reordering, we could place it in the right spot right away
      if (this._rendered) {
        $(this._containerElement).append(this._setupSubviewElement(view));
        this._renderOnReorder();
      }
    }
  },

  _remove: function(model) {
    var view = this.getSubviewFromModel(model);
    if (view) {
      this._subviews = _(this._subviews).without(view);
      if (this._rendered) {
        $(view.el).remove();
      }
    }
  },

  _reset: function() {
    this.render();
  },

  render: function() {
    this._rendered = true;

    this._endDrag();

    this._subviews.length = 0;
    $(this._containerElement).empty();

    var self = this;
    this.collection.each(function(model) {
      var view = self.createSubview(model);
      if (view) {
        self._subviews.push(view);
        $(self._containerElement).append(self._setupSubviewElement(view));
      }
    });

    return this;
  },

  _renderOnReorder: function() {
    var self = this;

    // FIXME: This is inefficient, we could also just diff and reorganize the DOM nodes
    this._subviews = _.sortBy(this._subviews, function(view) {
      return self.collection.indexOf(view.model);
    });
    _.each(this._subviews, function(view) {
      if (view.el) {
        $(view.el).detach();
      }
    })
    _.each(this._subviews, function(view) {
      $(self._containerElement).append(view.el);
    })
  },

  _mayDrag: function() {
    return this.draggingEnabled && this._subviews.length > 1;
  },

  _beginDrag: function(event, view) {
    if (!this._dragState) {
      if (!this._mayDrag()) {
        return;
      }
      this._draggingView = view;
      this._dragStartX = $(view.el).offset().left - $(document).scrollLeft();
      this._dragStartY = $(view.el).offset().top - $(document).scrollTop();
      this._dragAnchorX = this._dragStartX - event.clientX;
      this._dragAnchorY = this._dragStartY - event.clientY;
      this._dragSibling = view.el.nextSibling;
      if (this.dragTolerance > 0) {
        this._dragState = 'tolerating';
      } else {
        this._dragState = 'dragging';
        this._handleMouseMove(event);
      }
    }
  },

  _handleMouseMove: function(event) {
    if (this._dragState) {
      var view = this._draggingView;

      if (this._dragState == 'tolerating') {
        if (Math.abs(event.pageX + this._dragAnchorX - this._dragStartX - $(document).scrollLeft()) > this.dragTolerance ||
          Math.abs(event.pageY + this._dragAnchorY - this._dragStartY - $(document).scrollTop()) > this.dragTolerance) {
          this._dragState = 'dragging';

          this._placeholderWidth = $(view.el).outerWidth();
          this._placeholderElement =
            $("<" + view.el.tagName + "></" + view.el.tagName + ">").
            css('width', this._placeholderWidth + 'px').
            css('height', $(view.el).outerHeight() + 'px').
            insertBefore(view.el);
          this._placeholderOffset = $(this._placeholderElement).offset();
          if (!this.showPlaceholder) {
            $(this._placeholderElement).slideUp('fast');
          }

          $(view.el).css('width', $(view.el).width() + 'px');
          $(view.el).css('height', $(view.el).height() + 'px');
          $(view.el).css('position', 'absolute');
          $(view.el).css('zIndex', '65535');
          $(view.el).addClass(this.draggingClass);

          $(view.el).detach();
          $(view.el).appendTo($(document.body));
        }
      }

      if (this._dragState == 'dragging') {
        var scrollTop = $(document).scrollTop();
        if (event.pageY < scrollTop + this.scrollTolerance) {
          $(document).scrollTop(scrollTop - this.scrollTolerance);
        } else if (event.pageY - scrollTop > window.innerHeight - this.scrollTolerance) {
          $(document).scrollTop(scrollTop + this.scrollTolerance);
        }

        if (this.dragConstrainX) {
          $(view.el).css('left', this._placeholderOffset.left + 'px');
        } else {
          $(view.el).css('left', (event.pageX + this._dragAnchorX) + 'px');
        }
        $(view.el).css('top', (event.pageY + this._dragAnchorY) + 'px');

        var previousView;
        if (this._subviews.indexOf(view) > 0) {
          previousView = this._subviews[this._subviews.indexOf(view) - 1];
        }
        this._dropTargetView = this;
        for (var i = 0; i < this._subviews.length; i++) {
          var targetView = this._subviews[i];
          if (targetView != view && event.pageY + this._dragAnchorY >= $(targetView.el).offset().top) {
            this._dropTargetView = targetView;
          }
        }

        if (this._dropTargetView != view && (!this.showPlaceholder || this._dropTargetView != previousView)) {
          if (!this._dropMarkerElement) {
            this._dropMarkerElement = $('

').
              addClass(this.dropMarkerClass).
              css('position', 'absolute').
              css('left', this._placeholderOffset.left + 'px').
              css('width', this._placeholderWidth + 'px');
            $(document.documentElement).append(this._dropMarkerElement);
          }
          if (this._dropTargetView == this) {
            $(this._dropMarkerElement).
              css('top', $(this._subviews[view == this._subviews[0] ? 1 : 0].el).offset().top);
          } else {
            $(this._dropMarkerElement).
              css('top',
                $(this._dropTargetView.el).offset().top +
                $(this._dropTargetView.el).outerHeight());
          }
        } else {
          if (this._dropMarkerElement) {
            this._dropMarkerElement.remove();
            this._dropMarkerElement = null;
          }
        }
      }
    }
  },

  _endDrag: function() {
    if (this._dragState) {
      var view = this._draggingView;
      if (this._dropMarkerElement) {
        this._dropMarkerElement.remove();
        this._dropMarkerElement = null;
      }
      if (this._placeholderElement) {
        this._placeholderElement.detach();
        this._placeholderElement = null;
      }
      if (this._dragState == 'dragging') {
        this._doDrop();
      }
      this._dragState = null;
    }
  },

  _doDrop: function() {
    var view = this._draggingView;
    this._draggingView = null;

    $(view.el).removeClass(this.draggingClass);
    $(view.el).detach();

    if (this._dragSibling) {
      $(view.el).insertBefore(this._dragSibling);
    } else {
      $(view.el).appendTo(this._containerElement);
    }

    $(view.el).
      css('width', '').
      css('height', '').
      css('position', '').
      css('zIndex', '').
      css('left', '').
      css('top', '');

    if (this._dropTargetView) {
      if (this.positionAttribute) {
        var oldPosition = view.model.get(this.positionAttribute);
        var newPosition;
        if (this._dropTargetView == this) {
          newPosition = this._subviews[0].model.get(this.positionAttribute);
        } else {
          newPosition = this._dropTargetView.model.get(this.positionAttribute) + 1;
          if (newPosition > oldPosition) {
            newPosition -= 1;
          }
        }
        if (newPosition != oldPosition) {
          var models = this.collection.toArray();
          for (var i = 0; i < models.length; i++) {
            var item = models[i];
            if (newPosition > oldPosition) {
              if (item.get(this.positionAttribute) > oldPosition && item.get(this.positionAttribute) <= newPosition) {
                item.set({position: item.get(this.positionAttribute) - 1});
              }
            } else {
              if (item.get(this.positionAttribute) < oldPosition && item.get(this.positionAttribute) >= newPosition) {
                item.set({position: item.get(this.positionAttribute) + 1});
              }
            }
          }
          view.model.set({position: newPosition});
          this.collection.sort({silent: true});
          this._renderOnReorder();
        }
      } else {
        var oldPosition = this.collection.indexOf(view.model);
        var newPosition;
        if (this._dropTargetView == this) {
          newPosition = 0;
        } else {
          newPosition = this.collection.indexOf(this._dropTargetView.model) + 1;
          if (newPosition > oldPosition) {
            newPosition -= 1;
          }
        }
        if (newPosition != oldPosition) {
          this.collection.remove(view.model, {silent: true});
          this.collection.add(view.model, {silent: true, at: newPosition});
          this._renderOnReorder();
        }
      }
    }
  }
});


text:
dest_rcmpd_path=/etc/init.d/rcmpd
ws_folder=$HOME/rcmp_ws
installer_folder=$(pwd)
ws_src_folder=$ws_folder/src
ros_folder=/opt/ros

install_rcm_component()
{
    rcm_component_path=$installer_folder/$1
    if [ -e "$rcm_component_path" ]
    then
        cp $rcm_component_path $1
        unzip $1
        rm $1
    else
        echo "The package $1 is not available between the components in $installer_folder"
        read -p "download the component and put it in the installer folder or provide the path: [$installer_folder]: " comp_folder
        if [ -z "$comp_folder" ]
        then
            comp_folder=$installer_folder
        fi
        if [ -d "$comp_folder" ]
        then
            rcm_component_path=$comp_folder/$1
            if [ -e "$rcm_component_path" ]
            then
                cp $rcm_component_path $1
                unzip $1
                rm $1
            else
                echo "The package $1 is not available in $comp_folder and must be installed manually"
            fi
        else
            echo "The folder $comp_folder not found: install $1 manually"
        fi
    fi
}

if [ -e "$dest_rcmpd_path" ]
then
    echo "The old RCM daemon already exists: we trying to stop it"
    sudo service rcmpd stop
fi

is_tun0=$(ifconfig | grep tun0)
if [ ! -z "$is_tun0" ]
then
	# tun0 exists
	# creating the ros workspace for the rcm platform node
	if [ -d "$ws_folder" ]
	then
	    read -p "The workspace rcmp_ws already exists: do you wanna replace it ([Y]es/no)? " replace_ws
        case ${replace_ws} in
            n|no|N|No )
            ;;
            * )
                rm -r $ws_folder
                mkdir $ws_folder
            ;;
        esac
    else
        mkdir $ws_folder
	fi
	if [ ! -d "$ws_src_folder" ]
	then
		echo "creating source folder in rcmp workspace"
		mkdir $ws_src_folder
	fi
	# setting the ros environment variables
	if [ ! -d "$ros_folder" ]
	then
		echo "$ros_folder does not exist"
	fi
	ros_dist=$(ls $ros_folder)
    ros_folder=$ros_folder/$ros_dist
    echo "using ROS distribution $ros_dist"

	sudo ./sub_inst.sh $ros_folder

	# finishing the installation with operation relative to the workspace
	. $ros_folder/setup.sh

    cd $ws_src_folder
    echo "initializing rcmp workspace"
    catkin_init_workspace

    read -p "Do you wanna install firos to communicate with fiware world ([Y]es/no)? " inst_firos
    case ${inst_firos} in
        n|no|N|No )
        ;;
        * )
            echo "installing firos, rcm_driver and robotics_msgs"
            install_rcm_component robotics_msgs.zip
            install_rcm_component rcm_driver.zip
            install_rcm_component firos.zip
        ;;
    esac

    cd $ws_folder
    echo "compiling rcmp workspace"
    catkin_make
    . devel/setup.sh

    echo "configuration completed"

    read -p "Do you wanna start the RCM platform node now ([Y]es/no)? " start_rcm
    case ${start_rcm} in
        n|no|N|No )
        ;;
        * )
            sudo service rcmpd start
        ;;
    esac
else
	echo "The RCM platform works on VPN: no VPN detected; please configure correctly."
	exit 3
fi


text:
using System;
using System.Threading.Tasks;
using System.Web.Cors;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security.OAuth;
using Owin;

[assembly: OwinStartup(typeof(TokenAouthSimple.Startup))]

namespace TokenAouthSimple
{

    public class Startup
    {
        public const string UrlToken = "/api/token";
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            ConfigureOAuth(app);
            app.UseWebApi(config);
        }

        //https://nicolocodev.wordpress.com/2016/11/28/asp-net-web-api-autenticacion-basada-en-tokens-y-lios-con-el-cors/
        private static Task<CorsPolicy> PolicyResolver(IOwinRequest request)
        {
            if (request.Path.Value == UrlToken)
            {
                //Estos valores pueden ser recuperados de un archivo de configuracion
                var corsPolicy = new CorsPolicy
                {
                    Headers = { "Accept", "Content-Type", "Authorization", "Cache-Control", "Pragma", "Origin" },
                    Methods = { "POST", "OPTIONS" },
                    Origins = { "https://localhost:44369" }
                };
                return Task.FromResult(corsPolicy);
            }
            return Task.FromResult<CorsPolicy>(null);
        }

        private void EnableCors(IAppBuilder app)
        {

            app.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = PolicyResolver
                }
            });

        }
        private void ConfigureOAuth(IAppBuilder app)
        {
            // Habilitar Solicitudes desde otro Dominio, Externos //Microsoft.AspNet.WebApi.Cors  //Microsoft.Owin.Cors.

            //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            EnableCors(app);

            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString(UrlToken),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
                Provider = new AouthSimpleAuthorizationServerProvider(),
            };
            app.UseOAuthAuthorizationServer(oAuthServerOptions);

            //Habilitar WebApi para que tenga en cuenta los Tokens en Autenticacion.
            var authOptions = new OAuthBearerAuthenticationOptions()
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
            };
            app.UseOAuthBearerAuthentication(authOptions);
        }
    }
}


text:
module RuboCop
  module Cop
    module Gitlab
      # Cop that disallows the use of `Gitlab::SQL::Union`, in favour of using
      # the `FromUnion` module.
      class Union < RuboCop::Cop::Cop
        MSG = 'Use the `FromUnion` concern, instead of using `Gitlab::SQL::Union` directly'

        def_node_matcher :raw_union?, <<~PATTERN
          (send (const (const (const nil? :Gitlab) :SQL) :Union) :new ...)
        PATTERN

        def on_send(node)
          return unless raw_union?(node)

          add_offense(node, location: :expression)
        end
      end
    end
  end
end


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Enum2459695545.h"
#include "UnityEngine_Networking_UnityEngine_Networking_Chann888737962.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityEngine.Networking.ChannelOption
struct  ChannelOption_t888737962
{
public:
	// System.Int32 UnityEngine.Networking.ChannelOption::value__
	int32_t ___value___1;

public:
	inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ChannelOption_t888737962, ___value___1)); }
	inline int32_t get_value___1() const { return ___value___1; }
	inline int32_t* get_address_of_value___1() { return &___value___1; }
	inline void set_value___1(int32_t value)
	{
		___value___1 = value;
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
title: "This Week in Flynn"
date: December 8, 2014
---

We eliminated several races and panics in the continuous integration suite.

We converted the last rpcplus endpoint in the Flynn controller to HTTP. We will migrate all other rpcplus components to HTTP in the future.

## Changes

### Enhancements

- Updated to Go 1.4rc2 ([#550](https://github.com/flynn/flynn/pull/550))
- Added `SO_REUSEPORT` to discoverd and router to allow zero-downtime replacement ([#541](https://github.com/flynn/flynn/pull/541))
- Converted controller's StreamFormations to HTTP from rpcplus ([#540](https://github.com/flynn/flynn/pull/540))
- Merged `pkg/migrate` into `pkg/postgres` ([#556](https://github.com/flynn/flynn/pull/556))
- Moved some database helpers into `pkg/postgres` ([#557](https://github.com/flynn/flynn/pull/557))
- Imported upstream `pq` package improvements ([#560](https://github.com/flynn/flynn/pull/560))
- Added example generator and support packages to router API ([#548](https://github.com/flynn/flynn/pull/548))

### Bugfixes

- Blobstore now registers with discoverd when using the local filesystem adapter ([#543](https://github.com/flynn/flynn/pull/543))
- PATH in Development Vagrantfile is now escaped properly ([#553](https://github.com/flynn/flynn/pull/553))
- Repaired a broken pipe while downloading images ([#529](https://github.com/flynn/flynn/pull/529))
- Calmed a panic after failing to connect to hosts from the controller scheduler ([#562](https://github.com/flynn/flynn/pull/562))
- Ended several races in integration test helpers ([#561](https://github.com/flynn/flynn/pull/561))
- Prevented timeouts when connecting to containers ([#564](https://github.com/flynn/flynn/pull/564))
- Improved job type sorting in `flynn ps` ([#566](https://github.com/flynn/flynn/pull/566))

## What's Next

We are focused on improving our test suite, documentation, and stability.

## Stay in Touch

* Star us on [GitHub](https://github.com/flynn/flynn)
* Join us on the [#flynn channel](http://webchat.freenode.net?channels=%23flynn) at Freenode
* Help solve an [easy issue](https://github.com/flynn/flynn/labels/easy)
* [Let us know how you're using Flynn](mailto:contact@flynn.io)


text:
function gaoptions = algorithm_gaoptions(algoset,probstruct)

if probstruct.D <= 5; PopSize = 50; else PopSize = 200; end
Generations = max(1,floor(probstruct.MaxFunEvals/PopSize)-1);
CrossoverFraction = 0.8;

MutationFcn = @mutationadaptfeasible;
% MutationFcn = @mutationgaussiancon;

switch algoset
    case 'hixover'; CrossoverFraction = 0.8;
    case 'mexover'; CrossoverFraction = 0.5;
    case 'loxover'; CrossoverFraction = 0.2;
    case 'gausscon'; MutationFcn = @mutationgaussiancon;
    case 'megausscon'; CrossoverFraction = 0.5; MutationFcn = @mutationgaussiancon;
end

gaoptions = gaoptimset(...
    'TolFun', probstruct.TolFun, ...
    'PopInitRange', probstruct.InitRange, ...
    'PopulationSize', PopSize, ...
    'Display', 'iter', ...
    'InitialPopulation', [], ...
    'MutationFcn', MutationFcn, ...
    'CrossoverFcn', @crossoverscattered, ...
    'Generations', Generations, ...
    'CrossoverFraction',CrossoverFraction ...
    );

% No elitism with noisy functions
%if ~isempty(probstruct.Noise) || probstruct.IntrinsicNoisy
%    gaoptions.EliteCount = 0;
%end

end


text:
#include "youbot_driver/testing/YouBotBaseTest.hpp"
#include "youbot_driver/testing/YouBotBaseTestWithoutThread.hpp"
#include "youbot_driver/testing/YouBotArmTestWithoutThread.hpp"
#include "youbot_driver/testing/YouBotBaseKinematicsTest.hpp"
#include "youbot_driver/testing/YouBotArmTest.hpp"
#include "youbot_driver/testing/YouBotGripperTest.hpp"
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/extensions/HelperMacros.h>

CPPUNIT_TEST_SUITE_REGISTRATION( YouBotBaseTestWithoutThread );
CPPUNIT_TEST_SUITE_REGISTRATION( YouBotBaseTest );
CPPUNIT_TEST_SUITE_REGISTRATION( YouBotBaseKinematicsTest );
CPPUNIT_TEST_SUITE_REGISTRATION( YouBotArmTestWithoutThread );
CPPUNIT_TEST_SUITE_REGISTRATION( YouBotArmTest );
CPPUNIT_TEST_SUITE_REGISTRATION( YouBotGripperTest );

int main(int argc, char* argv[]) {
  std::cout << "Attention! All wheels of the youBot will move during the test. \nThe youBot should NOT stand on the ground and the wheels should be in the air! \nAlso the arm will move please be carefull!" << std::endl;
  char input = 0;

  while (input != 'y' && input != 'n') {
    std::cout << "Are all wheels off the ground? [n/y]" << std::endl;
    input = getchar();
    if (input == 'n') {
      return 0;
    }
  }
  Logger::logginLevel = trace;

  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
  CppUnit::TextUi::TestRunner runner;
  runner.addTest( suite );
  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(), std::cerr ) );
  /** let the test run */
  bool wasSucessful = runner.run();

  /** check whether it was sucessfull or not */
  return wasSucessful ? 0 : 1;
}


text:
<?php

namespace Google\Cloud\Samples\Dialogflow;

use PHPUnit\Framework\TestCase;

/**
 * Unit Tests for intent management commands.
 */
class intentTest extends TestCase
{
    use DialogflowTestTrait;

    private static $displayName;
    private static $messageTexts = ['fake_message_for_testing_1', 'fake_message_for_testing_2'];
    private static $trainingPhraseParts = ['fake_phrase_1', 'fake_phrase_2'];

    public static function setUpBeforeClass(): void
    {
        self::$displayName = sprintf('fake_display_%s_%s', rand(100, 999), time());
    }

    public function testCreateIntent()
    {
        $response = $this->runCommand('intent-create', [
            'display-name' => self::$displayName,
            '--training-phrases-parts' => self::$trainingPhraseParts,
            '--message-texts' => self::$messageTexts
        ]);
        $output = $this->runCommand('intent-list');

        $this->assertStringContainsString(self::$displayName, $output);

        $response = str_replace(array("\r", "\n"), '', $response);
        $response = explode('/', $response);
        $intentId = end($response);
        return $intentId;
    }

    /** @depends testCreateIntent */
    public function testDeleteIntent($intentId)
    {
        $this->runCommand('intent-delete', [
            'intent-id' => $intentId
        ]);
        $output = $this->runCommand('intent-list');

        $this->assertStringNotContainsString(self::$displayName, $output);
    }
}


text:
package uk.gov.gchq.gaffer.spark.operation.scalardd;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.spark.rdd.RDD;

import uk.gov.gchq.gaffer.data.element.Element;
import uk.gov.gchq.gaffer.operation.Operation;
import uk.gov.gchq.gaffer.operation.io.Input;
import uk.gov.gchq.koryphe.Since;
import uk.gov.gchq.koryphe.Summary;

import java.util.Map;

/**
 * A {@code ImportRDDOfElements} takes a {@link RDD} containing {@link Element}s
 * and adds them to a target Gaffer store.
 */
@JsonPropertyOrder(value = {"class", "input"}, alphabetic = true)
@Since("1.0.0")
@Summary("Adds an RDD of elements")
public class ImportRDDOfElements implements
        Input<RDD<Element>> {
    public static final String HADOOP_CONFIGURATION_KEY = "Hadoop_Configuration_Key";
    private RDD<Element> input;
    private Map<String, String> options;

    @Override
    public RDD<Element> getInput() {
        return input;
    }

    @Override
    public void setInput(final RDD<Element> input) {
        this.input = input;
    }

    @Override
    public Map<String, String> getOptions() {
        return options;
    }

    @Override
    public void setOptions(final Map<String, String> options) {
        this.options = options;
    }

    @Override
    public ImportRDDOfElements shallowClone() {
        return new ImportRDDOfElements.Builder()
                .input(input)
                .options(options)
                .build();
    }

    public static class Builder extends Operation.BaseBuilder<ImportRDDOfElements, Builder>
            implements Input.Builder<ImportRDDOfElements, RDD<Element>, Builder>,
            Operation.Builder<ImportRDDOfElements, Builder> {
        public Builder() {
            super(new ImportRDDOfElements());
        }
    }
}


text:
@implementation SCOAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Override point for customization after application launch.

  // There's a lot of work going on during the launch...
  sleep(2);

  return YES;
}

@end


text:
import sched
import time

scheduler = sched.scheduler(time.time, time.sleep)

def print_event(name):
    print('EVENT:', time.ctime(time.time()), name)

now = time.time()
print('START:', time.ctime(now))
scheduler.enterabs(now + 2, 2, print_event, ('first',))
scheduler.enterabs(now + 2, 1, print_event, ('second',))

scheduler.run()


text:
import { Readable as ReadableStream } from 'stream';
import { IService } from '../interfaces/IService';
export default abstract class Song {
    readonly service: IService;
    loop: boolean;
    readonly abstract type: string;
    readonly abstract title: string;
    readonly abstract trackID: string | number;
    readonly abstract playlistID?: string | number;
    readonly abstract streamURL: string;
    constructor(service: IService);
    toggleLoop(): boolean;
    abstract next(): Promise<Song | null>;
    abstract stream(): Promise<ReadableStream> | ReadableStream;
}


text:
package jp.ijufumi.openreports.controller.settings

import jp.ijufumi.openreports.controller.common.{ApplicationController, FileUploadController, I18nFeature}
import jp.ijufumi.openreports.service.enums.StatusCode
import jp.ijufumi.openreports.service.settings.ReportTemplateSettingsService

class ReportTemplateSettingsController extends FileUploadController {

  override val activeMenu = "settings/report-template"
  override val requiredMemberInfo = true

  val path = RootPath + "/report-template"
  val viewPath = RootPath + "/report-template"

  def index = {
    val templates = new ReportTemplateSettingsService().getReportTemplates
    set("templates", templates)
    render(viewPath + "/index")
  }

  def showUpload = {
    render(viewPath + "/upload")
  }

  def upload = {
    fileParams.get("uploadFile") match {
      case Some(file) =>
        val statusCode = new ReportTemplateSettingsService().uploadFile(file)
        statusCode match {
          case StatusCode.OK => redirect(url(Controllers.reportTemplateSettings.indexUrl))
        }
        set("customErrorMessages", Seq(i18n.get("error.fileUploadError")))
      case None =>
        logger.info("file not found")
        set("customErrorMessages", Seq(i18n.get("warning.requiredUploadFile")))
    }

    redirect(url(Controllers.reportTemplateSettings.showUploadUrl))
  }

  def showHistory = {
    params.getAs[Long]("id").map { id =>
      val histories = new ReportTemplateSettingsService().getHistories(id)
      set("histories", histories)
      render(viewPath + "/history")
    } getOrElse haltWithBody(404)
  }
}


text:
package org.jzy3d.events;

import java.util.EventObject;

import org.jzy3d.plot3d.rendering.view.modes.ViewPositionMode;

public class ViewModeChangedEvent extends EventObject {

	public ViewModeChangedEvent(Object source, ViewPositionMode mode){
		super(source);
		this.mode = mode;
	}

	public ViewPositionMode getMode(){
		return mode;
	}

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

	private ViewPositionMode mode;
	private static final long serialVersionUID = 7467846578948284603L;
}


text:
from CIM14.ENTSOE.Equipment.Core.IdentifiedObject import IdentifiedObject

class ConnectivityNode(IdentifiedObject):
    """Connectivity nodes are points where terminals of conducting equipment are connected together with zero impedance.
    """

    def __init__(self, Terminals=None, *args, **kw_args):
        """Initialises a new 'ConnectivityNode' instance.

        @param Terminals: Terminals interconnect with zero impedance at a node.  Measurements on a node apply to all of its terminals.
        """
        self._Terminals = []
        self.Terminals = [] if Terminals is None else Terminals

        super(ConnectivityNode, self).__init__(*args, **kw_args)

    _attrs = []
    _attr_types = {}
    _defaults = {}
    _enums = {}
    _refs = ["Terminals"]
    _many_refs = ["Terminals"]

    def getTerminals(self):
        """Terminals interconnect with zero impedance at a node.  Measurements on a node apply to all of its terminals.
        """
        return self._Terminals

    def setTerminals(self, value):
        for x in self._Terminals:
            x.ConnectivityNode = None
        for y in value:
            y._ConnectivityNode = self
        self._Terminals = value

    Terminals = property(getTerminals, setTerminals)

    def addTerminals(self, *Terminals):
        for obj in Terminals:
            obj.ConnectivityNode = self

    def removeTerminals(self, *Terminals):
        for obj in Terminals:
            obj.ConnectivityNode = None


text:
#ifndef _OPENSTACK_KEYSTONE_H
#define _OPENSTACK_KEYSTONE_H

#include <json/json.h>

struct keystone {
	json_object *access;
	char *token;
};

struct keystone *keystone_authenticate(char *, char *, char *, char *);
char *keystone_get_token(struct keystone *);
char *keystone_get_endpoint(struct keystone *, char *, char *);

#endif


text:
package ca.ualberta.cs.cmput301t02project.test;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import ca.ualberta.cs.cmput301t02project.activity.LoginActivity;
import ca.ualberta.cs.cmput301t02project.model.Cache;
import ca.ualberta.cs.cmput301t02project.model.CommentModel;

public class CacheTest extends ActivityInstrumentationTestCase2<LoginActivity>{

	public CacheTest() {
		super(LoginActivity.class);
	}

	public void testCache() {
		Activity activity = getActivity();
		assertNotNull(activity);
		Cache cache = Cache.getInstance(activity.getApplicationContext());
		assertNotNull(cache);
		CommentModel model = new CommentModel("text", null, "user");
		cache.put("i", model);
		assertNotNull(cache.getIfPresent("i"));
		assertEquals(model, cache.getIfPresent("i"));
	}
}


text:
Eyekabob

Local Music Finder


text:
@implementation BTConfiguration (Venmo)

- (BOOL)isVenmoEnabled {
    return self.venmoAccessToken != nil;
}

- (NSString *)venmoAccessToken {
    return [self.json[@"payWithVenmo"][@"accessToken"] asString];
}

- (NSString *)venmoMerchantID {
    return [self.json[@"payWithVenmo"][@"merchantId"] asString];
}

- (NSString *)venmoEnvironment {
    return [self.json[@"payWithVenmo"][@"environment"] asString];
}

@end


text:
/* ListProjections.h
 *
 * Author: Adam Batkin
 * Last modified by: Tien Hoang on 06/29/2005
 *
 * Class for holding a list of projections in FROM line of a SELECT query
 */

#ifndef _LISTPROJECTIONS_H_
#define _LISTPROJECTIONS_H_

#include <string>
#include <list>
#include <map>
#include <utility>

#include "PObject.h"
#include "Projection.h"
#include "constants.h"

using namespace std;

// Variable
class ListProjections : public PObject
{
   protected:
	list<Projection*> m_listProjections;
	map<string, TVariable*> m_tupleEnv;
	map<string, Projection*> m_projectionEnv;
	//string m_projEnv;
	//string m_tupleEnv;

   protected:
		// PObject's constructor is protected because they should not be new directly.
		// A node can be new by using static "create" function
		// This is for the purpose of memory management
		ListProjections();

	public:
		virtual ~ListProjections();
		TVariable* getTuple(string projectionName, string tupleName );
		void dump_env();
		void	add(Projection* e);
		void    ListProjections::addTupleAlias( string pname, string tname, string alias );
		list<Projection*> getProjections();
		string	toString();

	//---------------------------------------------------------------
	// Memory management functions

	public:
		// New a PObject and put it in the m_lpList
		static ListProjections* create();
};

#endif // _LISTPROJECTIONS_H_


text:
#include "slikenet/NativeFeatureIncludes.h"
#if _RAKNET_SUPPORT_ConnectionGraph2==1

#include "slikenet/ConnectionGraph2.h"
#include "slikenet/peerinterface.h"
#include "slikenet/MessageIdentifiers.h"
#include "slikenet/BitStream.h"

using namespace SLNet;

STATIC_FACTORY_DEFINITIONS(ConnectionGraph2,ConnectionGraph2)

int SLNet::ConnectionGraph2::RemoteSystemComp( const RakNetGUID &key, RemoteSystem * const &data )
{
	if (key < data->guid)
		return -1;
	if (key > data->guid)
		return 1;
	return 0;
}

int SLNet::ConnectionGraph2::SystemAddressAndGuidComp( const SystemAddressAndGuid &key, const SystemAddressAndGuid &data )
{
	if (key.guid<data.guid)
		return -1;
	if (key.guid>data.guid)
		return 1;
	return 0;
}
ConnectionGraph2::ConnectionGraph2()
{
	autoProcessNewConnections=true;
}
ConnectionGraph2::~ConnectionGraph2()
{

}
bool ConnectionGraph2::GetConnectionListForRemoteSystem(RakNetGUID remoteSystemGuid, SystemAddress *saOut, RakNetGUID *guidOut, unsigned int *outLength)
{
	if ((saOut==0 && guidOut==0) || outLength==0 || *outLength==0 || remoteSystemGuid==UNASSIGNED_RAKNET_GUID)
	{
		*outLength=0;
		return false;
	}

	bool objectExists;
	unsigned int idx = remoteSystems.GetIndexFromKey(remoteSystemGuid, &objectExists);
	if (objectExists==false)
	{
		*outLength=0;
		return false;
	}

	unsigned int idx2;
	if (remoteSystems[idx]->remoteConnections.Size() < *outLength)
		*outLength=remoteSystems[idx]->remoteConnections.Size();
	for (idx2=0; idx2 < *outLength; idx2++)
	{
		if (guidOut)
			guidOut[idx2]=remoteSystems[idx]->remoteConnections[idx2].guid;
		if (saOut)
			saOut[idx2]=remoteSystems[idx]->remoteConnections[idx2].systemAddress;
	}
	return true;
}
bool ConnectionGraph2::ConnectionExists(RakNetGUID g1, RakNetGUID g2)
{
	if (g1==g2)
		return false;

	bool objectExists;
	unsigned int idx = remoteSystems.GetIndexFromKey(g1, &objectExists);
	if (objectExists==false)
	{
		return false;
	}
	SystemAddressAndGuid sag;
	sag.guid=g2;
	return remoteSystems[idx]->remoteConnections.HasData(sag);
}
uint16_t ConnectionGraph2::GetPingBetweenSystems(RakNetGUID g1, RakNetGUID g2) const
{
	if (g1==g2)
		return 0;

	if (g1==rakPeerInterface->GetMyGUID())
		return (uint16_t) rakPeerInterface->GetAveragePing(g2);
	if (g2==rakPeerInterface->GetMyGUID())
		return (uint16_t) rakPeerInterface->GetAveragePing(g1);

	bool objectExists;
	unsigned int idx = remoteSystems.GetIndexFromKey(g1, &objectExists);
	if (objectExists==false)
	{
		return (uint16_t) -1;
	}

	SystemAddressAndGuid sag;
	sag.guid=g2;
	unsigned int idx2 = remoteSystems[idx]->remoteConnections.GetIndexFromKey(sag, &objectExists);
	if (objectExists==false)
	{
		return (uint16_t) -1;
	}
	return remoteSystems[idx]->remoteConnections[idx2].sendersPingToThatSystem;
}

/// Returns the system with the lowest total ping among all its connections. This can be used as the 'best host' for a peer to peer session
RakNetGUID ConnectionGraph2::GetLowestAveragePingSystem(void) const
{
	float lowestPing=-1.0;
	unsigned int lowestPingIdx=(unsigned int) -1;
	float thisAvePing=0.0f;
	unsigned int idx, idx2;
	int ap, count=0;

	for (idx=0; idx<remoteSystems.Size(); idx++)
	{
		thisAvePing=0.0f;

		ap = rakPeerInterface->GetAveragePing(remoteSystems[idx]->guid);
		if (ap!=-1)
		{
			thisAvePing+=(float) ap;
			count++;
		}
	}

	if (count>0)
	{
		lowestPing=thisAvePing/count;
	}

	for (idx=0; idx<remoteSystems.Size(); idx++)
	{
		thisAvePing=0.0f;
		count=0;

		RemoteSystem *remoteSystem = remoteSystems[idx];
		for (idx2=0; idx2 < remoteSystem->remoteConnections.Size(); idx2++)
		{
			ap=remoteSystem->remoteConnections[idx2].sendersPingToThatSystem;
			if (ap!=-1)
			{
				thisAvePing+=(float) ap;
				count++;
			}
		}

		if (count>0 && (lowestPing==-1.0f || thisAvePing/count < lowestPing))
		{
			lowestPing=thisAvePing/count;
			lowestPingIdx=idx;
		}
	}

	if (lowestPingIdx==(unsigned int) -1)
		return rakPeerInterface->GetMyGUID();
	return remoteSystems[lowestPingIdx]->guid;
}

void ConnectionGraph2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason )
{
	// Send notice to all existing connections
	SLNet::BitStream bs;
	if (lostConnectionReason==LCR_CONNECTION_LOST)
		bs.Write((MessageID)ID_REMOTE_CONNECTION_LOST);
	else
		bs.Write((MessageID)ID_REMOTE_DISCONNECTION_NOTIFICATION);
	bs.Write(systemAddress);
	bs.Write(rakNetGUID);
	SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,true);

	bool objectExists;
	unsigned int idx = remoteSystems.GetIndexFromKey(rakNetGUID, &objectExists);
	if (objectExists)
	{
		SLNet::OP_DELETE(remoteSystems[idx],_FILE_AND_LINE_);
		remoteSystems.RemoveAtIndex(idx);
	}
}
void ConnectionGraph2::SetAutoProcessNewConnections(bool b)
{
	autoProcessNewConnections=b;
}
bool ConnectionGraph2::GetAutoProcessNewConnections(void) const
{
	return autoProcessNewConnections;
}
void ConnectionGraph2::AddParticipant(const SystemAddress &systemAddress, RakNetGUID rakNetGUID)
{
	// Relay the new connection to other systems.
	SLNet::BitStream bs;
	bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION);
	bs.Write((uint32_t)1);
	bs.Write(systemAddress);
	bs.Write(rakNetGUID);
	bs.WriteCasted<uint16_t>(rakPeerInterface->GetAveragePing(rakNetGUID));
	SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,true);

	// Send everyone to the new guy
	DataStructures::List<SystemAddress> addresses;
	DataStructures::List<RakNetGUID> guids;
	rakPeerInterface->GetSystemList(addresses, guids);
	bs.Reset();
	bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION);
	BitSize_t writeOffset = bs.GetWriteOffset();
	bs.Write((uint32_t) addresses.Size());

	unsigned int i;
	uint32_t count=0;
	for (i=0; i < addresses.Size(); i++)
	{
		if (addresses[i]==systemAddress)
			continue;

		bs.Write(addresses[i]);
		bs.Write(guids[i]);
		bs.WriteCasted<uint16_t>(rakPeerInterface->GetAveragePing(guids[i]));
		count++;
	}

	if (count>0)
	{
		BitSize_t writeOffset2 = bs.GetWriteOffset();
		bs.SetWriteOffset(writeOffset);
		bs.Write(count);
		bs.SetWriteOffset(writeOffset2);
		SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,false);
	}

	bool objectExists;
	unsigned int ii = remoteSystems.GetIndexFromKey(rakNetGUID, &objectExists);
	if (objectExists==false)
	{
		RemoteSystem* remoteSystem = SLNet::OP_NEW<RemoteSystem>(_FILE_AND_LINE_);
		remoteSystem->guid=rakNetGUID;
		remoteSystems.InsertAtIndex(remoteSystem,ii,_FILE_AND_LINE_);
	}
}
void ConnectionGraph2::GetParticipantList(DataStructures::OrderedList<RakNetGUID, RakNetGUID> &participantList)
{
	participantList.Clear(true, _FILE_AND_LINE_);
	unsigned int i;
	for (i=0; i < remoteSystems.Size(); i++)
		participantList.InsertAtEnd(remoteSystems[i]->guid, _FILE_AND_LINE_);
}
void ConnectionGraph2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)
{
	(void) isIncoming;
	if (autoProcessNewConnections)
		AddParticipant(systemAddress, rakNetGUID);
}
PluginReceiveResult ConnectionGraph2::OnReceive(Packet *packet)
{
	if (packet->data[0]==ID_REMOTE_CONNECTION_LOST || packet->data[0]==ID_REMOTE_DISCONNECTION_NOTIFICATION)
	{
		bool objectExists;
		unsigned idx = remoteSystems.GetIndexFromKey(packet->guid, &objectExists);
		if (objectExists)
		{
			SLNet::BitStream bs(packet->data,packet->length,false);
			bs.IgnoreBytes(1);
			SystemAddressAndGuid saag;
			bs.Read(saag.systemAddress);
			bs.Read(saag.guid);
			unsigned long idx2 = remoteSystems[idx]->remoteConnections.GetIndexFromKey(saag, &objectExists);
			if (objectExists)
				remoteSystems[idx]->remoteConnections.RemoveAtIndex(idx2);
		}
	}
	else if (packet->data[0]==ID_REMOTE_NEW_INCOMING_CONNECTION)
	{
		bool objectExists;
		unsigned idx = remoteSystems.GetIndexFromKey(packet->guid, &objectExists);
		if (objectExists)
		{
			uint32_t numAddresses;
			SLNet::BitStream bs(packet->data,packet->length,false);
			bs.IgnoreBytes(1);
			bs.Read(numAddresses);
			for (unsigned int idx2=0; idx2 < numAddresses; idx2++)
			{
				SystemAddressAndGuid saag;
				bs.Read(saag.systemAddress);
				bs.Read(saag.guid);
				bs.Read(saag.sendersPingToThatSystem);
				unsigned int ii = remoteSystems[idx]->remoteConnections.GetIndexFromKey(saag, &objectExists);
				if (objectExists==false)
					remoteSystems[idx]->remoteConnections.InsertAtIndex(saag,ii,_FILE_AND_LINE_);
			}
		}
	}

	return RR_CONTINUE_PROCESSING;
}

#endif // _RAKNET_SUPPORT_*


text:
import {Component} from '@angular/core'
import {ViewChild} from '@angular/core'
import {Observable} from 'rxjs/Rx';
import {UserServices} from '../../lib/service/user';
import {NavController, Nav} from 'ionic-angular';
import {STRINGS} from '../../lib/provider/config';
import {TranslateService} from "ng2-translate/ng2-translate";
import { HomePage } from '../home/home';
import { ChangePasswordPage } from '../change-password/change-password';
import { Content, LoadingController, ToastController, PopoverController } from 'ionic-angular';
import { PasswordPopover } from '../../popover/password';

@Component({
  templateUrl: 'register-individual-profile.html'
})
export class RegisterIndividualProfilePage {

  @ViewChild(Content) content: Content;

  public key: string = '';
  public val: string = '';
  public errors: Array<string> = [];

  // Error booleans
  public firstnameerror: boolean = false;
  public lastnameerror: boolean = false;
  public birthdateerror:  boolean = false;
  public my_contactmethod_iderror:  boolean = false;
  public my_volunteertype_iderror:  boolean = false;
  public acceptedwaivererror: boolean = false;
  public acceptedpolicyerror: boolean = false;
  public com_opt_inerror: boolean = false;

  public mobilenumbererror: boolean = false;
  public emailerror: boolean = false;
  public parent_consenterror: boolean = false;

  public gendererror: boolean = false;
  public address1error: boolean = false;
  public address2error: boolean = false;
  public cityerror: boolean = false;
  public stateerror: boolean = false;
  public zipcodeerror:  boolean = false;
  public my_servicearea_iderror:  boolean = false;
  public my_referalsource_iderror:  boolean = false;
  public my_donationtype_iderror:  boolean = false;

  public ecfirstnameerror:  boolean = false;
  public eclastnameerror:  boolean = false;
  public ecrelationerror:  boolean = false;
  public ecmobilenumbererror:  boolean = false;
  public ecaltnumbererror:  boolean = false;

  public passworderror:  boolean = false;
  public password1error:  boolean = false;
  public password2error:  boolean = false;

  public relationships = [
    "Parent/Guardian",
    "Brother/Sister",
    "Relative",
    "Friend"
  ];

  public genders = [
    {id:"1", value: "Male"},
    {id:"2", value: "Female"},
    {id:"3", value: "Other"}
  ];

  // Other private variables
  public myProfile: any = {
    emergency_contact: {}
  };

  public availablePreferences: any = {};
  public myPreferences: any = {};
  public passwordForm: any = {};

  public formServiceAreas: Array<any> = [];

  public profileExists: boolean = false;

  public loadingOverlay;

  public showpassword: string = "password";

  public mobileNumberAreaCode = "";
  public mobileNumberPrefix = "";
  public mobileNumberLineNumber = "";

  public ecMobileNumberAreaCode = "";
  public ecMobileNumberPrefix = "";
  public ecMobileNumberLineNumber = "";

  public ecAltNumberAreaCode = "";
  public ecAltNumberPrefix = "";
  public ecAltNumberLineNumber = "";

  public selectedTab: string = "personal";

  // Constructor
  constructor(public nav: NavController,
              public userServices: UserServices,
              public translate: TranslateService,
              public loadingController: LoadingController,
              public toastController: ToastController,
              public popoverCtrl: PopoverController) {

  }

  // On initialization, get the latest info from the server
  ngOnInit() {
    let getMyProfileObservable =  this.userServices.getMyProfile()
    let getMyPreferencesObservable =  this.userServices.getMyPreferences()
    let getAvailablePreferencesObservable =  this.userServices.getAvailablePreferences()

    this.clearErrors();
    this.cleanBooleans();
    this.showLoading();

    // Get profile and preferences too
    Observable.forkJoin([getMyPreferencesObservable, getAvailablePreferencesObservable, getMyProfileObservable])
        .subscribe(data => {
          this.myPreferences = data[0];
          this.availablePreferences = data[1];
          this.myProfile = data[2];

          this.translateToFormPreferences();

          this.profileExists = true;

          let defaultVolunteerType: string = "Individual";
          let defaultVolunteerTypeId: number = 1;
          for (let volunteerType of this.availablePreferences.volunteertypes) {
            if (volunteerType.name == defaultVolunteerType) {
              defaultVolunteerTypeId = volunteerType.id;
              break;
            }
          }

          if (!this.myProfile.emergency_contact) this.myProfile.emergency_contact = {};
          if (this.myProfile.tc_version == "") this.myProfile.tc_version = null;
          if (!this.myProfile.my_volunteertype_id) this.myProfile.my_volunteertype_id = defaultVolunteerTypeId;
          if (!this.myProfile.volunteertype) this.myProfile.volunteertype = defaultVolunteerType;

          this.translateToFormPhoneNumbers();

          this.hideLoading();
        }, err => {
          this.hideLoading();
          console.log(err);
        });
  }

  presentToast(message: string) {
    let toast = this.toastController.create({
      message: message,
      duration: 2000,
      position: 'middle'
    });
    toast.present();
  }

  showLoading() {
    this.loadingOverlay = this.loadingController.create({
      content: 'Please wait...'
    });
    this.loadingOverlay.present();
  }

  hideLoading() {
    this.loadingOverlay.dismiss();
  }

  register() {
    this.updateProfile();
  }

  updateProfile() {
    this.showLoading();
    this.clearErrors();
    this.cleanBooleans();
    this.translateFromFormPreferences();
    this.translateFromFormPhoneNumbers();

    let updateMyProfileObservable =  this.userServices.updateMyProfile(this.myProfile);
    let updateMyPreferencesObservable =  this.userServices.updateMyPreferences(this.myPreferences);
    let changeMyPasswordObservable = null;

    let observables = [updateMyProfileObservable, updateMyPreferencesObservable];

    // Only call change password if one or more of the form fields are entered
    if (this.passwordForm.old_password ||  this.passwordForm.new_password1 || this.passwordForm.new_password2) {
      changeMyPasswordObservable = this.userServices.changePassword(this.passwordForm);
      observables.push(changeMyPasswordObservable);
    }

    Observable.forkJoin(observables)
      .subscribe(
          key => {
            this.presentToast("Profile saved.")
            this.hideLoading();
            this.passwordForm={};
          },
          err => {
            this.presentToast("Error saving profile.")
            this.hideLoading();
            console.log(err);
            this.setError(err);
          }),
          val => this.val = val;
  }

  cleanBooleans() {
    this.myProfile.accepted_policy = (this.myProfile.accepted_policy) ? 1 : 0;
    this.myProfile.accepted_waiver = (this.myProfile.accepted_waiver) ? 1 : 0;
    this.myProfile.comm_opt_in = (this.myProfile.comm_opt_in) ? 1 : 0;
    this.myProfile.tc_version = (this.myProfile.tc_version) ? 1 : null;
    this.myProfile.parent_consent = (this.myProfile.parent_consent) ? 1 : 0;
  }

  isServiceAreaInMyPreferences(id: number) {
    let serviceAreas = this.myPreferences.serviceareas;
    for (let serviceArea of serviceAreas) {
      if (serviceArea.servicearea_id == id) return true;
    }
    return false;
  }

  translateToFormPhoneNumbers() {
    // Clear all parsed numbers
    this.mobileNumberAreaCode = "";
    this.mobileNumberPrefix = "";
    this.mobileNumberLineNumber = "";

    this.mobileNumberAreaCode = "";
    this.mobileNumberPrefix = "";
    this.mobileNumberLineNumber = "";

    this.mobileNumberAreaCode = "";
    this.mobileNumberPrefix = "";
    this.mobileNumberLineNumber = "";

    // Parse profile mobile number
    if (this.myProfile.mobilenumber && this.myProfile.mobilenumber.length == 11) {
      this.mobileNumberAreaCode = this.myProfile.mobilenumber.substring(1, 4);
      this.mobileNumberPrefix = this.myProfile.mobilenumber.substring(4, 7);
      this.mobileNumberLineNumber = this.myProfile.mobilenumber.substring(7, 11);
    }
    // Parse emergency contact mobile number
    if (this.myProfile.emergency_contact.mobilenumber && this.myProfile.emergency_contact.mobilenumber.length == 11) {
      this.ecMobileNumberAreaCode = this.myProfile.emergency_contact.mobilenumber.substring(1, 4);
      this.ecMobileNumberPrefix = this.myProfile.emergency_contact.mobilenumber.substring(4, 7);
      this.ecMobileNumberLineNumber = this.myProfile.emergency_contact.mobilenumber.substring(7, 11);
    }
    // Parse emergency contact alternate number
    if (this.myProfile.emergency_contact.altnumber && this.myProfile.emergency_contact.altnumber.length == 11) {
      this.ecAltNumberAreaCode = this.myProfile.emergency_contact.altnumber.substring(1, 4);
      this.ecAltNumberPrefix = this.myProfile.emergency_contact.altnumber.substring(4, 7);
      this.ecAltNumberLineNumber = this.myProfile.emergency_contact.altnumber.substring(7, 11);
    }
  }

  translateFromFormPhoneNumbers() {
    if (this.mobileNumberAreaCode || this.mobileNumberPrefix || this.mobileNumberLineNumber) {
      this.myProfile.mobilenumber = "1" + this.mobileNumberAreaCode + this.mobileNumberPrefix + this.mobileNumberLineNumber;
    } else {
      this.myProfile.mobilenumber = "";
    }

    if (this.ecMobileNumberAreaCode || this.ecMobileNumberPrefix || this.ecMobileNumberLineNumber) {
      this.myProfile.emergency_contact.mobilenumber = "1" + this.ecMobileNumberAreaCode + this.ecMobileNumberPrefix + this.ecMobileNumberLineNumber;
    } else {
      this.myProfile.emergency_contact.mobilenumber = "";
    }

    if (this.ecAltNumberAreaCode || this.ecAltNumberPrefix || this.ecAltNumberLineNumber) {
      this.myProfile.emergency_contact.altnumber = "1" + this.ecAltNumberAreaCode + this.ecAltNumberPrefix + this.ecAltNumberLineNumber;
    } else {
      this.myProfile.emergency_contact.altnumber = "";
    }
  }

  translateToFormPreferences() {
    // empty the form array
    this.formServiceAreas = [];

    // Add all available preferences, and for those in "myPreferences.serviceareas", set the selected value to true
    let serviceAreas = this.availablePreferences.serviceareas;
    for (let serviceArea of serviceAreas) {
      let selected = this.isServiceAreaInMyPreferences(serviceArea.id) ? true : false;
      serviceArea.selected = selected;
      this.formServiceAreas.push(serviceArea);
    }

  }

  translateFromFormPreferences() {
    // Start with empty serviceareas list in myPreferences
    this.myPreferences.serviceareas = [];

    // For every item on the form that is selected, add it to myPreferences
    let formServiceAreas = this.formServiceAreas;
    for (let serviceArea of formServiceAreas) {
      if (serviceArea.selected) {
        let newServiceArea = {
          servicearea_id: serviceArea.id
        };
        this.myPreferences.serviceareas.push(newServiceArea);
      }
    }

  }

  clearErrors() {
        this.errors = [];

        this.firstnameerror=false;
        this.lastnameerror=false;
        this.birthdateerror=false;
        this.my_contactmethod_iderror=false;
        this.my_volunteertype_iderror=false;
        this.acceptedwaivererror=false;
        this.acceptedpolicyerror=false;
        this.com_opt_inerror=false;

        this.mobilenumbererror=false;
        this.emailerror=false;
        this.parent_consenterror=false;

        this.gendererror=false;
        this.address1error=false;
        this.address2error=false;
        this.cityerror=false;
        this.stateerror=false;
        this.zipcodeerror=false;
        this.my_servicearea_iderror=false;
        this.my_referalsource_iderror=false;
        this.my_donationtype_iderror=false;

        this.ecfirstnameerror=false;
        this.eclastnameerror=false;
        this.ecrelationerror=false;
        this.ecmobilenumbererror=false;
        this.ecaltnumbererror=false;

        this.passworderror=false;
        this.password1error=false;
        this.password2error=false;
  }

  setError(error) {
    if (error.status === 400) {
      error = error.json();
      for (let key in error) {
        for (let val in error[key]) {
          let field = '';
          if (STRINGS[key]) field = STRINGS[key] + ': ';
          this.errors.push(field + error[key][val].toString());
//          this[key + "error"] = true;
          if (key==='first_name') this.firstnameerror=true;
          if (key==='last_name') this.lastnameerror=true;
          if (key==='birthdate') this.birthdateerror=true;
          if (key==='my_contactmethod_id') this.my_contactmethod_iderror=true;
          if (key==='my_volunteertype_id') this.my_volunteertype_iderror=true;
          if (key==='acceptedwaiver') this.acceptedwaivererror=true;
          if (key==='acceptedpolicy') this.acceptedpolicyerror=true;
          if (key==='com_opt_in') this.com_opt_inerror=true;

          if (key==='mobilenumber') this.mobilenumbererror=true;
          if (key==='email') this.emailerror=true;
          if (key==='parent_consent') this.parent_consenterror=true;

          if (key==='gender') this.gendererror=true;
          if (key==='address1') this.address1error=true;
          if (key==='address2') this.address2error=true;
          if (key==='city') this.cityerror=true;
          if (key==='state') this.stateerror=true;
          if (key==='zipcode') this.zipcodeerror=true;
          if (key==='my_servicearea_id') this.my_servicearea_iderror=true;
          if (key==='my_referalsource_id') this.my_referalsource_iderror=true;
          if (key==='my_donationtype_id') this.my_donationtype_iderror=true;

          if (key==='old_password') this.passworderror=true;
          if (key==='new_password1') this.password1error=true;
          if (key==='new_password2') this.password2error=true;

          if (key==='contact')  {
            let object = error[key];
            if (object.mobilenumber) {
              this.mobilenumbererror=true;
            }
            if (object.email) {
              this.emailerror=true;
            }
          }
          if (key==='emergency_contact')  {
            let object = error[key];
            if (object.mobilenumber) {
              this.ecmobilenumbererror=true;
            }
            if (object.altnumber) {
              this.ecaltnumbererror=true;
            }
          }
          if (key==='emergency_contact_first_name') this.ecfirstnameerror=true;
          if (key==='emergency_contact_last_name') this.eclastnameerror=true;
          if (key==='emergency_contact_relation') this.ecrelationerror=true;
        }
      }
      this.content.scrollToTop();
    }
    if (error.status === 500) {
      this.errors.push('Backend returned 500 error, talk to JOHN :) ');
      this.content.scrollToTop();
    }

  }

  back() {
    this.nav.popToRoot();
  }

  goToChangePassword() {
    this.nav.push(ChangePasswordPage);
  }

  showPassword() {
    if (this.showpassword === 'password') this.showpassword = 'text';
    else this.showpassword = 'password';
  }
  presentPasswordPopover(ev) {

    let popover = this.popoverCtrl.create(PasswordPopover, {
    });

    popover.present({
      ev: ev
    });
  }

}


text:
require 'drb/drb'
require 'drb/extserv'

class EvalAttack
  def initialize
    @four = DRb::DRbServer.new('druby://localhost:0', self, {:safe_level => 4})
  end

  def four
    DRbObject.new_with_uri(@four.uri)
  end

  def remote_class
    DRbObject.new(self.class)
  end
end

if __FILE__ == $0
  def ARGV.shift
    it = super()
    raise "usage: #{$0} <uri> <name>" unless it
    it
  end

  $SAFE = 1

  DRb.start_service('druby://localhost:0', EvalAttack.new, {:safe_level => 2})
  es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
  DRb.thread.join
end