text:
namespace mojo {
namespace edk {

struct SharedMemoryHeader {
  uint32_t data_size;
  uint32_t read_buffer_size;
};

void DataPipeConsumerDispatcher::Init(
    ScopedPlatformHandle message_pipe,
    char* serialized_read_buffer, size_t serialized_read_buffer_size) {
  if (message_pipe.is_valid()) {
    channel_ = RawChannel::Create(message_pipe.Pass());
    channel_->SetSerializedData(
        serialized_read_buffer, serialized_read_buffer_size, nullptr, 0u,
        nullptr, nullptr);
    internal::g_io_thread_task_runner->PostTask(
        FROM_HERE, base::Bind(&DataPipeConsumerDispatcher::InitOnIO, this));
  } else {
    // The data pipe consumer could have read all the data and the producer
    // closed its end subsequently (before the consumer was sent). In that case
    // when we deserialize the consumer we must make sure to set error_ or
    // otherwise the peer-closed signal will never be satisfied.
    error_ = true;
  }
}

void DataPipeConsumerDispatcher::InitOnIO() {
  base::AutoLock locker(lock());
  calling_init_ = true;
  if (channel_)
    channel_->Init(this);
  calling_init_ = false;
}

void DataPipeConsumerDispatcher::CloseOnIO() {
  base::AutoLock locker(lock());
  if (channel_) {
    channel_->Shutdown();
    channel_ = nullptr;
  }
}

Dispatcher::Type DataPipeConsumerDispatcher::GetType() const {
  return Type::DATA_PIPE_CONSUMER;
}

scoped_refptr<DataPipeConsumerDispatcher>
DataPipeConsumerDispatcher::Deserialize(
    const void* source,
    size_t size,
    PlatformHandleVector* platform_handles) {
  MojoCreateDataPipeOptions options;
  ScopedPlatformHandle shared_memory_handle;
  size_t shared_memory_size = 0;

  ScopedPlatformHandle platform_handle =
      DataPipe::Deserialize(source, size, platform_handles, &options,
      &shared_memory_handle, &shared_memory_size);

  scoped_refptr<DataPipeConsumerDispatcher> rv(Create(options));

  char* serialized_read_buffer = nullptr;
  size_t serialized_read_buffer_size = 0;
  scoped_refptr<PlatformSharedBuffer> shared_buffer;
  scoped_ptr<PlatformSharedBufferMapping> mapping;
  if (shared_memory_size) {
    shared_buffer = internal::g_platform_support->CreateSharedBufferFromHandle(
        shared_memory_size, shared_memory_handle.Pass());
    mapping = shared_buffer->Map(0, shared_memory_size);
    char* buffer = static_cast<char*>(mapping->GetBase());
    SharedMemoryHeader* header = reinterpret_cast<SharedMemoryHeader*>(buffer);
    buffer += sizeof(SharedMemoryHeader);
    if (header->data_size) {
      rv->data_.assign(buffer, buffer + header->data_size);
      buffer += header->data_size;
    }

    if (header->read_buffer_size) {
      serialized_read_buffer = buffer;
      serialized_read_buffer_size = header->read_buffer_size;
      buffer += header->read_buffer_size;
    }
  }

  rv->Init(platform_handle.Pass(), serialized_read_buffer,
           serialized_read_buffer_size);
  return rv;
}

DataPipeConsumerDispatcher::DataPipeConsumerDispatcher(
    const MojoCreateDataPipeOptions& options)
    : options_(options),
      channel_(nullptr),
      calling_init_(false),
      in_two_phase_read_(false),
      two_phase_max_bytes_read_(0),
      error_(false),
      serialized_(false) {
}

DataPipeConsumerDispatcher::~DataPipeConsumerDispatcher() {
  // |Close()|/|CloseImplNoLock()| should have taken care of the channel.
  DCHECK(!channel_);
}

void DataPipeConsumerDispatcher::CancelAllAwakablesNoLock() {
  lock().AssertAcquired();
  awakable_list_.CancelAll();
}

void DataPipeConsumerDispatcher::CloseImplNoLock() {
  lock().AssertAcquired();
  internal::g_io_thread_task_runner->PostTask(
      FROM_HERE, base::Bind(&DataPipeConsumerDispatcher::CloseOnIO, this));
}

scoped_refptr<Dispatcher>
DataPipeConsumerDispatcher::CreateEquivalentDispatcherAndCloseImplNoLock() {
  lock().AssertAcquired();

  SerializeInternal();

  scoped_refptr<DataPipeConsumerDispatcher> rv = Create(options_);
  data_.swap(rv->data_);
  serialized_read_buffer_.swap(rv->serialized_read_buffer_);
  rv->serialized_platform_handle_ = serialized_platform_handle_.Pass();
  rv->serialized_ = true;

  return scoped_refptr<Dispatcher>(rv.get());
}

MojoResult DataPipeConsumerDispatcher::ReadDataImplNoLock(
    void* elements,
    uint32_t* num_bytes,
    MojoReadDataFlags flags) {
  lock().AssertAcquired();
  if (channel_)
    channel_->EnsureLazyInitialized();
  if (in_two_phase_read_)
    return MOJO_RESULT_BUSY;

  if ((flags & MOJO_READ_DATA_FLAG_QUERY)) {
    if ((flags & MOJO_READ_DATA_FLAG_PEEK) ||
        (flags & MOJO_READ_DATA_FLAG_DISCARD))
      return MOJO_RESULT_INVALID_ARGUMENT;
    DCHECK(!(flags & MOJO_READ_DATA_FLAG_DISCARD));  // Handled above.
    DVLOG_IF(2, elements)
        << "Query mode: ignoring non-null |elements|";
    *num_bytes = static_cast<uint32_t>(data_.size());
    return MOJO_RESULT_OK;
  }

  bool discard = false;
  if ((flags & MOJO_READ_DATA_FLAG_DISCARD)) {
    // These flags are mutally exclusive.
    if (flags & MOJO_READ_DATA_FLAG_PEEK)
      return MOJO_RESULT_INVALID_ARGUMENT;
    DVLOG_IF(2, elements)
        << "Discard mode: ignoring non-null |elements|";
    discard = true;
  }

  uint32_t max_num_bytes_to_read = *num_bytes;
  if (max_num_bytes_to_read % options_.element_num_bytes != 0)
    return MOJO_RESULT_INVALID_ARGUMENT;

  bool all_or_none = flags & MOJO_READ_DATA_FLAG_ALL_OR_NONE;
  uint32_t min_num_bytes_to_read =
      all_or_none ? max_num_bytes_to_read : 0;

  if (min_num_bytes_to_read > data_.size())
    return error_ ? MOJO_RESULT_FAILED_PRECONDITION : MOJO_RESULT_OUT_OF_RANGE;

  uint32_t bytes_to_read = std::min(max_num_bytes_to_read,
                                    static_cast<uint32_t>(data_.size()));
  if (bytes_to_read == 0)
    return error_ ? MOJO_RESULT_FAILED_PRECONDITION : MOJO_RESULT_SHOULD_WAIT;

  if (!discard)
    memcpy(elements, &data_[0], bytes_to_read);
  *num_bytes = bytes_to_read;

  bool peek = !!(flags & MOJO_READ_DATA_FLAG_PEEK);
  if (discard || !peek)
    data_.erase(data_.begin(), data_.begin() + bytes_to_read);

  return MOJO_RESULT_OK;
}

MojoResult DataPipeConsumerDispatcher::BeginReadDataImplNoLock(
    const void** buffer,
    uint32_t* buffer_num_bytes,
    MojoReadDataFlags flags) {
  lock().AssertAcquired();
  if (channel_)
    channel_->EnsureLazyInitialized();
  if (in_two_phase_read_)
    return MOJO_RESULT_BUSY;

  // These flags may not be used in two-phase mode.
  if ((flags & MOJO_READ_DATA_FLAG_DISCARD) ||
      (flags & MOJO_READ_DATA_FLAG_QUERY) ||
      (flags & MOJO_READ_DATA_FLAG_PEEK))
    return MOJO_RESULT_INVALID_ARGUMENT;

  uint32_t max_num_bytes_to_read = static_cast<uint32_t>(data_.size());
  if (max_num_bytes_to_read == 0)
    return error_ ? MOJO_RESULT_FAILED_PRECONDITION : MOJO_RESULT_SHOULD_WAIT;

  in_two_phase_read_ = true;
  *buffer = &data_[0];
  *buffer_num_bytes = max_num_bytes_to_read;
  two_phase_max_bytes_read_ = max_num_bytes_to_read;

  return MOJO_RESULT_OK;
}

MojoResult DataPipeConsumerDispatcher::EndReadDataImplNoLock(
    uint32_t num_bytes_read) {
  lock().AssertAcquired();
  if (!in_two_phase_read_)
    return MOJO_RESULT_FAILED_PRECONDITION;

  HandleSignalsState old_state = GetHandleSignalsStateImplNoLock();
  MojoResult rv;
  if (num_bytes_read > two_phase_max_bytes_read_ ||
      num_bytes_read % options_.element_num_bytes != 0) {
    rv = MOJO_RESULT_INVALID_ARGUMENT;
  } else {
    rv = MOJO_RESULT_OK;
    data_.erase(data_.begin(), data_.begin() + num_bytes_read);
  }

  in_two_phase_read_ = false;
  two_phase_max_bytes_read_ = 0;
  if (!data_received_during_two_phase_read_.empty()) {
    if (data_.empty()) {
      data_received_during_two_phase_read_.swap(data_);
    } else {
      data_.insert(data_.end(), data_received_during_two_phase_read_.begin(),
                   data_received_during_two_phase_read_.end());
      data_received_during_two_phase_read_.clear();
    }
  }

  HandleSignalsState new_state = GetHandleSignalsStateImplNoLock();
  if (!new_state.equals(old_state))
    awakable_list_.AwakeForStateChange(new_state);

  return rv;
}

HandleSignalsState DataPipeConsumerDispatcher::GetHandleSignalsStateImplNoLock()
    const {
  lock().AssertAcquired();

  HandleSignalsState rv;
  if (!data_.empty()) {
    if (!in_two_phase_read_)
      rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_READABLE;
    rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE;
  } else if (!error_) {
    rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE;
  }

  if (error_)
    rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
  rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
  return rv;
}

MojoResult DataPipeConsumerDispatcher::AddAwakableImplNoLock(
    Awakable* awakable,
    MojoHandleSignals signals,
    uintptr_t context,
    HandleSignalsState* signals_state) {
  lock().AssertAcquired();
  if (channel_)
    channel_->EnsureLazyInitialized();
  HandleSignalsState state = GetHandleSignalsStateImplNoLock();
  if (state.satisfies(signals)) {
    if (signals_state)
      *signals_state = state;
    return MOJO_RESULT_ALREADY_EXISTS;
  }
  if (!state.can_satisfy(signals)) {
    if (signals_state)
      *signals_state = state;
    return MOJO_RESULT_FAILED_PRECONDITION;
  }

  awakable_list_.Add(awakable, signals, context);
  return MOJO_RESULT_OK;
}

void DataPipeConsumerDispatcher::RemoveAwakableImplNoLock(
    Awakable* awakable,
    HandleSignalsState* signals_state) {
  lock().AssertAcquired();
  awakable_list_.Remove(awakable);
  if (signals_state)
    *signals_state = GetHandleSignalsStateImplNoLock();
}

void DataPipeConsumerDispatcher::StartSerializeImplNoLock(
    size_t* max_size,
    size_t* max_platform_handles) {
  if (!serialized_) {
    // Handles the case where we have messages read off RawChannel but not ready
    // by MojoReadMessage.
    SerializeInternal();
  }

  DataPipe::StartSerialize(serialized_platform_handle_.is_valid(),
                           !data_.empty() || !serialized_read_buffer_.empty(),
                           max_size, max_platform_handles);
}

bool DataPipeConsumerDispatcher::EndSerializeAndCloseImplNoLock(
    void* destination,
    size_t* actual_size,
    PlatformHandleVector* platform_handles) {
  ScopedPlatformHandle shared_memory_handle;
  size_t shared_memory_size =  data_.size() + serialized_read_buffer_.size();
  if (shared_memory_size) {
    shared_memory_size += sizeof(SharedMemoryHeader);
    SharedMemoryHeader header;
    header.data_size = static_cast<uint32_t>(data_.size());
    header.read_buffer_size =
        static_cast<uint32_t>(serialized_read_buffer_.size());

    scoped_refptr<PlatformSharedBuffer> shared_buffer(
        internal::g_platform_support->CreateSharedBuffer(
            shared_memory_size));
    scoped_ptr<PlatformSharedBufferMapping> mapping(
        shared_buffer->Map(0, shared_memory_size));

    char* start = static_cast<char*>(mapping->GetBase());
    memcpy(start, &header, sizeof(SharedMemoryHeader));
    start += sizeof(SharedMemoryHeader);

    if (!data_.empty()) {
      memcpy(start, &data_[0], data_.size());
      start += data_.size();
    }

    if (!serialized_read_buffer_.empty()) {
      memcpy(start, &serialized_read_buffer_[0],
             serialized_read_buffer_.size());
      start += serialized_read_buffer_.size();
    }

    shared_memory_handle.reset(shared_buffer->PassPlatformHandle().release());
  }

  DataPipe::EndSerialize(
      options_,
      serialized_platform_handle_.Pass(),
      shared_memory_handle.Pass(), shared_memory_size,
      destination, actual_size, platform_handles);
  CloseImplNoLock();
  return true;
}

void DataPipeConsumerDispatcher::TransportStarted() {
  started_transport_.Acquire();
}

void DataPipeConsumerDispatcher::TransportEnded() {
  started_transport_.Release();

  base::AutoLock locker(lock());

  // If transporting of DP failed, we might have got more data and didn't awake
  // for.
  // TODO(jam): should we care about only alerting if it was empty before
  // TransportStarted?
  if (!data_.empty())
    awakable_list_.AwakeForStateChange(GetHandleSignalsStateImplNoLock());
}

bool DataPipeConsumerDispatcher::IsBusyNoLock() const {
  lock().AssertAcquired();
  return in_two_phase_read_;
}

void DataPipeConsumerDispatcher::OnReadMessage(
    const MessageInTransit::View& message_view,
    ScopedPlatformHandleVectorPtr platform_handles) {
  const char* bytes_start = static_cast<const char*>(message_view.bytes());
  const char* bytes_end = bytes_start + message_view.num_bytes();
  if (started_transport_.Try()) {
    // We're not in the middle of being sent.

    // Can get synchronously called back in Init if there was initial data.
    scoped_ptr<base::AutoLock> locker;
    if (!calling_init_) {
      locker.reset(new base::AutoLock(lock()));
    }

    if (in_two_phase_read_) {
      data_received_during_two_phase_read_.insert(
          data_received_during_two_phase_read_.end(), bytes_start, bytes_end);
    } else {
      bool was_empty = data_.empty();
      data_.insert(data_.end(), bytes_start, bytes_end);
      if (was_empty)
        awakable_list_.AwakeForStateChange(GetHandleSignalsStateImplNoLock());
    }
    started_transport_.Release();
  } else {
    // See comment in MessagePipeDispatcher about why we can't and don't need
    // to lock here.
    data_.insert(data_.end(), bytes_start, bytes_end);
  }
}

void DataPipeConsumerDispatcher::OnError(Error error) {
  switch (error) {
    case ERROR_READ_SHUTDOWN:
      // The other side was cleanly closed, so this isn't actually an error.
      DVLOG(1) << "DataPipeConsumerDispatcher read error (shutdown)";
      break;
    case ERROR_READ_BROKEN:
      LOG(ERROR) << "DataPipeConsumerDispatcher read error (connection broken)";
      break;
    case ERROR_READ_BAD_MESSAGE:
      // Receiving a bad message means either a bug, data corruption, or
      // malicious attack (probably due to some other bug).
      LOG(ERROR) << "DataPipeConsumerDispatcher read error (received bad "
                 << "message)";
      break;
    case ERROR_READ_UNKNOWN:
      LOG(ERROR) << "DataPipeConsumerDispatcher read error (unknown)";
      break;
    case ERROR_WRITE:
      LOG(ERROR) << "DataPipeConsumerDispatcher shouldn't write messages";
      break;
  }

  error_ = true;
  if (started_transport_.Try()) {
    base::AutoLock locker(lock());
    // We can get two OnError callbacks before the post task below completes.
    // Although RawChannel still has a pointer to this object until Shutdown is
    // called, that is safe since this class always does a PostTask to the IO
    // thread to self destruct.
    if (channel_) {
      awakable_list_.AwakeForStateChange(GetHandleSignalsStateImplNoLock());
      channel_->Shutdown();
      channel_ = nullptr;
    }
    started_transport_.Release();
  } else {
    // We must be waiting to call ReleaseHandle. It will call Shutdown.
  }
}

void DataPipeConsumerDispatcher::SerializeInternal() {
  DCHECK(!in_two_phase_read_);
  // We need to stop watching handle immediately, even though not on IO thread,
  // so that other messages aren't read after this.
  if (channel_) {
    std::vector<char> serialized_write_buffer;
    std::vector<int> fds;
    bool write_error = false;
    serialized_platform_handle_ = channel_->ReleaseHandle(
        &serialized_read_buffer_, &serialized_write_buffer, &fds, &fds,
        &write_error);
    CHECK(serialized_write_buffer.empty());
    CHECK(fds.empty());
    CHECK(!write_error) << "DataPipeConsumerDispatcher doesn't write.";

    channel_ = nullptr;
  }

  serialized_ = true;
}

}  // namespace edk
}  // namespace mojo


text:
typedef NS_ENUM(NSInteger, OBASectionType) {
    OBASectionTypeNone,
    OBASectionTypeTitle,
    OBASectionTypeServiceAlerts,
    OBASectionTypeSchedule,
    OBASectionTypeActions
};

@interface OBAArrivalAndDepartureViewController ()

@property (nonatomic, strong) OBAArrivalAndDepartureInstanceRef *instance;
@property (nonatomic, strong) OBAArrivalAndDepartureV2 *arrivalAndDeparture;
@property (nonatomic, strong) OBAArrivalEntryTableViewCellFactory *arrivalCellFactory;
@property (nonatomic, strong) OBAServiceAlertsModel *serviceAlerts;

@end

@implementation OBAArrivalAndDepartureViewController

- (id)initWithApplicationDelegate:(OBAApplicationDelegate *)appDelegate arrivalAndDepartureInstance:(OBAArrivalAndDepartureInstanceRef *)instance {
    if (self = [super initWithApplicationDelegate:appDelegate]) {
        _instance = instance;
        _arrivalAndDeparture = nil;
        _arrivalCellFactory = [[OBAArrivalEntryTableViewCellFactory alloc] initWithappDelegate:appDelegate tableView:self.tableView];
        _arrivalCellFactory.showServiceAlerts = NO;
        self.refreshable = YES;
        self.refreshInterval = 30;
        self.showUpdateTime = YES;
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor whiteColor];
}

- (id)initWithApplicationDelegate:(OBAApplicationDelegate *)appDelegate arrivalAndDeparture:(OBAArrivalAndDepartureV2 *)arrivalAndDeparture {
    self = [self initWithApplicationDelegate:appDelegate arrivalAndDepartureInstance:arrivalAndDeparture.instance];
    _arrivalAndDeparture = arrivalAndDeparture;
    return self;
}

- (BOOL)isLoading {
    return _arrivalAndDeparture == nil;
}

- (id<OBAModelServiceRequest>)handleRefresh {
    return [self.appDelegate.modelService
            requestArrivalAndDepartureForStop:_instance
                              completionBlock:^(id jsonData, NSUInteger responseCode, NSError *error) {
                                  if (error) {
                                  [self refreshFailedWithError:error];
                                  }
                                  else {
                                  OBAEntryWithReferencesV2 *entry = jsonData;
                                  self.arrivalAndDeparture = entry.entry;

                                  OBAModelDAO *modelDao = self.appDelegate.modelDao;
                                  self.serviceAlerts = [modelDao getServiceAlertsModelForSituations:self->_arrivalAndDeparture.situations];
                                  [self refreshCompleteWithCode:responseCode];
                                  }
                              }];
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([self isLoading]) return [super numberOfSectionsInTableView:tableView];

    int count = 3;

    if (_serviceAlerts.unreadCount > 0) count++;

    return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self isLoading]) return [super tableView:tableView numberOfRowsInSection:section];

    OBASectionType sectionType = [self sectionTypeForSection:section];

    switch (sectionType) {
        case OBASectionTypeTitle:
            return 1;

        case OBASectionTypeServiceAlerts:
            return 1;

        case OBASectionTypeSchedule:
            return 2;

        case OBASectionTypeActions: {
            int count = 2;

            if (_arrivalAndDeparture.tripStatus.vehicleId && ![_arrivalAndDeparture.tripStatus.vehicleId isEqualToString:@""]) count++;

            return count;
        }

        default:
            return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self isLoading]) return [super tableView:tableView cellForRowAtIndexPath:indexPath];

    OBASectionType sectionType = [self sectionTypeForSection:indexPath.section];

    switch (sectionType) {
        case OBASectionTypeTitle:
            return [self titleCellForRowAtIndexPath:indexPath tableView:tableView];

        case OBASectionTypeServiceAlerts:
            return [self serviceAlertsCellForRowAtIndexPath:indexPath tableView:tableView];

        case OBASectionTypeSchedule:
            return [self scheduleCellForRowAtIndexPath:indexPath tableView:tableView];

        case OBASectionTypeActions:
            return [self actionCellForRowAtIndexPath:indexPath tableView:tableView];

        default:
            break;
    }

    return [UITableViewCell getOrCreateCellForTableView:tableView];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self isLoading]) {
        [self tableView:tableView didSelectRowAtIndexPath:indexPath];
        return;
    }

    OBASectionType sectionType = [self sectionTypeForSection:indexPath.section];

    switch (sectionType) {
        case OBASectionTypeServiceAlerts:
            [self didSelectServiceAlertRowAtIndexPath:indexPath tableView:tableView];
            break;

        case OBASectionTypeSchedule:
            [self didSelectScheduleRowAtIndexPath:indexPath tableView:tableView];
            break;

        case OBASectionTypeActions:
            [self didSelectActionRowAtIndexPath:indexPath tableView:tableView];
            break;

        default:
            break;
    }
}

- (OBASectionType)sectionTypeForSection:(NSUInteger)section {
    NSUInteger offset = 0;

    if (offset == section) return OBASectionTypeTitle;

    offset++;

    if (_serviceAlerts.unreadCount > 0) {
        if (offset == section) return OBASectionTypeServiceAlerts;

        offset++;
    }

    if (offset == section) return OBASectionTypeSchedule;

    offset++;

    if (offset == section) return OBASectionTypeActions;

    return OBASectionTypeNone;
}

- (UITableViewCell *)titleCellForRowAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    OBAArrivalEntryTableViewCell *cell = [_arrivalCellFactory createCellForArrivalAndDeparture:_arrivalAndDeparture];

    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UITableViewCell *)serviceAlertsCellForRowAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    return [UITableViewCell tableViewCellForUnreadServiceAlerts:_serviceAlerts tableView:tableView];
}

- (UITableViewCell *)scheduleCellForRowAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    UITableViewCell *cell = [UITableViewCell getOrCreateCellForTableView:tableView];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    cell.textLabel.textColor = [UIColor blackColor];
    cell.textLabel.textAlignment = NSTextAlignmentLeft;
    cell.textLabel.font = [UIFont systemFontOfSize:18];

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = NSLocalizedString(@"Show as map", @"text");
            break;

        case 1:
            cell.textLabel.text = NSLocalizedString(@"Show as list", @"text");
            break;
    }

    return cell;
}

- (UITableViewCell *)actionCellForRowAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    switch (indexPath.row) {
        case 0: {
            return [UITableViewCell tableViewCellForServiceAlerts:_serviceAlerts tableView:tableView];
        }

        case 1: {
            UITableViewCell *cell = [UITableViewCell getOrCreateCellForTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.textColor = [UIColor blackColor];
            cell.textLabel.textAlignment = NSTextAlignmentLeft;
            cell.textLabel.font = [UIFont systemFontOfSize:18];
            cell.textLabel.text = NSLocalizedString(@"Report a problem for this trip", @"text");
            return cell;
        }

        case 2: {
            UITableViewCell *cell = [UITableViewCell getOrCreateCellForTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.textColor = [UIColor blackColor];
            cell.textLabel.textAlignment = NSTextAlignmentLeft;
            cell.textLabel.font = [UIFont systemFontOfSize:18];
            cell.textLabel.text = NSLocalizedString(@"Vehicle Info", @"cell.textLabel.text");
            return cell;
        }

        default:
            break;
    }

    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self sectionTypeForSection:indexPath.section] == OBASectionTypeTitle) {
        return 50;
    }

    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch ([self sectionTypeForSection:section]) {
        case OBASectionTypeSchedule:
            return 40;

        case OBASectionTypeActions:
            return 30;

        default:
            return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];

    view.backgroundColor = OBAGREENBACKGROUND;
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 200, 30)];
    title.font = [UIFont systemFontOfSize:18];
    title.backgroundColor = [UIColor clearColor];

    switch ([self sectionTypeForSection:section]) {
        case OBASectionTypeSchedule:
            title.text = NSLocalizedString(@"Trip Details", @"OBASectionTypeSchedule");
            break;

        case OBASectionTypeActions:
            //title.text = NSLocalizedString(@"Actions",@"OBASectionTypeActions");
            break;

        default:
            break;
    }
    [view addSubview:title];

    return view;
}

- (void)didSelectServiceAlertRowAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    [self showSituations];
}

- (void)didSelectScheduleRowAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    OBATripInstanceRef *tripInstance = _arrivalAndDeparture.tripInstance;

    if (indexPath.row == 0) {
        OBATripScheduleMapViewController *vc = [[OBATripScheduleMapViewController alloc] initWithApplicationDelegate:self.appDelegate];
        vc.tripInstance = tripInstance;
        vc.currentStopId = _arrivalAndDeparture.stopId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.row == 1) {
        OBATripScheduleListViewController *vc = [[OBATripScheduleListViewController alloc] initWithApplicationDelegate:self.appDelegate tripInstance:tripInstance];
        vc.currentStopId = _arrivalAndDeparture.stopId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)didSelectActionRowAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    switch (indexPath.row) {
        case 0: {
            [self showSituations];
            break;
        }

        case 1: {
            OBATripInstanceRef *tripInstance = _arrivalAndDeparture.tripInstance;
            OBAReportProblemWithTripViewController *vc = [[OBAReportProblemWithTripViewController alloc] initWithApplicationDelegate:self.appDelegate tripInstance:tripInstance trip:_arrivalAndDeparture.trip];
            vc.currentStopId = _arrivalAndDeparture.stopId;
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }

        case 2: {
            OBAVehicleDetailsController *vc = [[OBAVehicleDetailsController alloc] initWithApplicationDelegate:self.appDelegate vehicleId:_arrivalAndDeparture.tripStatus.vehicleId];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
    }
}

- (void)showSituations {
    NSDictionary *args = @{ @"arrivalAndDeparture": _arrivalAndDeparture };

    [OBASituationsViewController showSituations:_arrivalAndDeparture.situations withappDelegate:self.appDelegate navigationController:self.navigationController args:args];
}

@end

redpajama_set_name: RedPajamaGithub


text:
"""Convnet example using CIFAR10 or CIFAR100 dataset

This code is a custom loop version of train_cifar.py. That is, we train
models without using the Trainer class in chainer and instead write a
training loop that manually computes the loss of minibatches and
applies an optimizer to update the model.
"""
import argparse
import os

import chainer
from chainer import configuration
from chainer.dataset import convert
import chainer.links as L
from chainer import serializers

from chainer.datasets import get_cifar10
from chainer.datasets import get_cifar100

import models.VGG

def main():
    parser = argparse.ArgumentParser(description='Chainer CIFAR example:')
    parser.add_argument('--dataset', default='cifar10',
                        help='The dataset to use: cifar10 or cifar100')
    parser.add_argument('--batchsize', '-b', type=int, default=64,
                        help='Number of images in each mini-batch')
    parser.add_argument('--learnrate', '-l', type=float, default=0.05,
                        help='Learning rate for SGD')
    parser.add_argument('--epoch', '-e', type=int, default=300,
                        help='Number of sweeps over the dataset to train')
    parser.add_argument('--device', '-d', type=str, default='-1',
                        help='Device specifier. Either ChainerX device '
                        'specifier or an integer. If non-negative integer, '
                        'CuPy arrays with specified device id are used. If '
                        'negative integer, NumPy arrays are used')
    parser.add_argument('--out', '-o', default='result',
                        help='Directory to output the result')
    parser.add_argument('--test', action='store_true',
                        help='Use tiny datasets for quick tests')
    parser.add_argument('--resume', '-r', type=str,
                        help='Directory that has `vgg.model` and `vgg.state`')
    group = parser.add_argument_group('deprecated arguments')
    group.add_argument('--gpu', '-g', dest='device',
                       type=int, nargs='?', const=0,
                       help='GPU ID (negative value indicates CPU)')
    args = parser.parse_args()

    device = chainer.get_device(args.device)
    device.use()

    print('Device: {}'.format(device))
    print('# Minibatch-size: {}'.format(args.batchsize))
    print('# epoch: {}'.format(args.epoch))
    print('')

    # Set up a neural network to train.
    # Classifier reports softmax cross entropy loss and accuracy at every
    # iteration, which will be used by the PrintReport extension below.
    if args.dataset == 'cifar10':
        print('Using CIFAR10 dataset.')
        class_labels = 10
        train, test = get_cifar10()
    elif args.dataset == 'cifar100':
        print('Using CIFAR100 dataset.')
        class_labels = 100
        train, test = get_cifar100()
    else:
        raise RuntimeError('Invalid dataset choice.')

    if args.test:
        train = train[:200]
        test = test[:200]

    train_count = len(train)
    test_count = len(test)

    model = L.Classifier(models.VGG.VGG(class_labels))
    model.to_device(device)

    optimizer = chainer.optimizers.MomentumSGD(args.learnrate)
    optimizer.setup(model)
    optimizer.add_hook(chainer.optimizer.WeightDecay(5e-4))

    if args.resume is not None:
        resume = args.resume
        if os.path.exists(resume):
            serializers.load_npz(os.path.join(resume, 'vgg.model'), model)
            serializers.load_npz(os.path.join(resume, 'vgg.state'), optimizer)
        else:
            raise ValueError(
                '`args.resume` ("{}") is specified,'
                ' but it does not exist.'.format(resume)
            )

    train_iter = chainer.iterators.SerialIterator(train, args.batchsize)
    test_iter = chainer.iterators.SerialIterator(test, args.batchsize,
                                                 repeat=False, shuffle=False)

    sum_acc = 0
    sum_loss = 0

    while train_iter.epoch < args.epoch:
        batch = train_iter.next()
        # Reduce learning rate by 0.5 every 25 epochs.
        if train_iter.epoch % 25 == 0 and train_iter.is_new_epoch:
            optimizer.lr *= 0.5
            print('Reducing learning rate to: {}'.format(optimizer.lr))

        x, t = convert.concat_examples(batch, device)
        optimizer.update(model, x, t)
        sum_loss += float(model.loss.array) * len(t)
        sum_acc += float(model.accuracy.array) * len(t)

        if train_iter.is_new_epoch:
            print('epoch: {}'.format(train_iter.epoch))
            print('train mean loss: {}, accuracy: {}'.format(
                sum_loss / train_count, sum_acc / train_count))
            sum_acc = 0
            sum_loss = 0
            # Enable evaluation mode.
            with configuration.using_config('train', False):
                # This is optional but can reduce computational overhead.
                with chainer.using_config('enable_backprop', False):
                    for batch in test_iter:
                        x, t = convert.concat_examples(batch, device)
                        loss = model(x, t)
                        sum_loss += float(loss.array) * len(t)
                        sum_acc += float(model.accuracy.array) * len(t)

            test_iter.reset()
            print('test mean  loss: {}, accuracy: {}'.format(
                sum_loss / test_count, sum_acc / test_count))
            sum_acc = 0
            sum_loss = 0

    # Save the model and the optimizer
    out = args.out
    if not os.path.exists(out):
        os.makedirs(out)
    print('save the model')
    serializers.save_npz(os.path.join(out, 'vgg.model'), model)
    print('save the optimizer')
    serializers.save_npz(os.path.join(out, 'vgg.state'), optimizer)

if __name__ == '__main__':
    main()


text:
package com.planet_ink.coffee_mud.Items.MiscTech;
import com.planet_ink.coffee_mud.Items.Basic.StdPortal;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;

public class GenSSPortal extends StdPortal implements Electronics
{
	public String ID(){	return "GenSSPortal";}
	protected String readableText="";
	public GenSSPortal()
	{
		super();
		setName("a space ship portal");
		setDisplayText("a space ship portal is here.");
		setMaterial(RawMaterial.RESOURCE_STEEL);
		setDescription("");
		recoverEnvStats();
	}

	public boolean isGeneric(){return true;}

	public String text()
	{
		return CMLib.coffeeMaker().getPropertiesStr(this,false);
	}

	public String readableText(){return readableText;}
	public void setReadableText(String text){readableText=text;}
	public void setMiscText(String newText)
	{
		miscText="";
		CMLib.coffeeMaker().setPropertiesStr(this,newText,false);
		recoverEnvStats();
	}

	public int fuelType(){return -1;}
	public void setFuelType(int resource){}
	public long powerCapacity(){return 0;}
	public void setPowerCapacity(long capacity){}
	public long powerRemaining(){return 0;}
	public void setPowerRemaining(long remaining){}
	public void activate(boolean truefalse){}
	public boolean activated(){return true;}

	private final static String[] MYCODES={"HASLOCK","HASLID","CAPACITY",
							  "CONTAINTYPES","RIDEBASIS","MOBSHELD"};
	public String getStat(String code)
	{
		if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0)
			return CMLib.coffeeMaker().getGenItemStat(this,code);
		switch(getCodeNum(code))
		{
		case 0: return ""+hasALock();
		case 1: return ""+hasALid();
		case 2: return ""+capacity();
		case 3: return ""+containTypes();
		case 4: return ""+rideBasis();
		case 5: return ""+riderCapacity();
        default:
            return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code);
        }
	}
	public void setStat(String code, String val)
	{
		if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0)
			CMLib.coffeeMaker().setGenItemStat(this,code,val);
		else
		switch(getCodeNum(code))
		{
		case 0: setLidsNLocks(hasALid(),isOpen(),CMath.s_bool(val),false); break;
		case 1: setLidsNLocks(CMath.s_bool(val),isOpen(),hasALock(),false); break;
		case 2: setCapacity(CMath.s_parseIntExpression(val)); break;
		case 3: setContainTypes(CMath.s_parseBitLongExpression(Container.CONTAIN_DESCS,val)); break;
		case 4: break;
		case 5: break;
        default:
            CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val);
            break;
		}
	}
	protected int getCodeNum(String code){
		for(int i=0;i<MYCODES.length;i++)
			if(code.equalsIgnoreCase(MYCODES[i])) return i;
		return -1;
	}
	private static String[] codes=null;
	public String[] getStatCodes()
	{
		if(codes!=null) return codes;
        String[] MYCODES=CMProps.getStatCodesList(GenSSPortal.MYCODES,this);
		String[] superCodes=GenericBuilder.GENITEMCODES;
		codes=new String[superCodes.length+MYCODES.length];
		int i=0;
		for(;i<superCodes.length;i++)
			codes[i]=superCodes[i];
		for(int x=0;x<MYCODES.length;i++,x++)
			codes[i]=MYCODES[x];
		return codes;
	}
	public boolean sameAs(Environmental E)
	{
		if(!(E instanceof GenSSPortal)) return false;
		String[] codes=getStatCodes();
		for(int i=0;i<codes.length;i++)
			if(!E.getStat(codes[i]).equals(getStat(codes[i])))
				return false;
		return true;
	}
}


text:
Initial release.

## 1.0.1

Packaging update.

## 1.0.2

Packaging update.

## 1.0.3

Fixing Typo.

## 1.1.0

Filtering out non-letter characters and accepting lowercase letters.
Better error handling.


text:
class QCli : public QObject {
  Q_OBJECT

 public:
  enum Status {
    OK,
    INCORRECT_COMMAND,
    INCORRECT_ARGUMENT,
    INTERNAL_ERROR,
  };

  typedef Status (*Command)(const std::vector<QString>& args, void* data);

  struct Command_s {
    Command exec;
    void* data;
  };

 private:
  QCli();
  QCli(const QCli&) {}
  ~QCli();
  QCli& operator=(QCli&) {}

  static QCli* instance_;
  QMap<QString, Command_s> commands_;

  QMap<QString, std::shared_ptr<void>> storage_;

 signals:
  void CommandExecuteBefore(QString command_name);
  void CommandExecuteAfter(QString command_name);
  void CommandExecuteError(QString command_name);
  void Exit();

 public:
  static QCli* Instance();

  // Parse entered command. Args should contain command name and (optional) its arguments
  Status Parse(const std::vector<QString>& args);

  // Add a command to CLI. name is the literal name by which the command will be called, cmd is function pointer to command handler
  // and callback is an optional pointer to whatever you might need to be passed to that function (like external function, object, variable, whatever).
  // It is caller's job to make sure that callback is used responsibly and it won't break anything. A good practice is to pass pointer to struct
  void AddCommand(const QString& name, Command cmd, void* data = nullptr);

  // Run the CLI command line. Blocks execution until "quit" or "exit" is encountered
  int Run();

  // Get unsafe storage pointer
  std::shared_ptr<void> GetUnsafeStorage(const QString& key);

  // Set unsafe storage to specified pointer
  void  SetUnsafeStorage(const QString& key, std::shared_ptr<void> data);

  // Remove unsafe storage entry
  void  UnsetUnsafeStorage(const QString& key);

  // Clear unsafe storage
  void ClearUnsafeStorage();

  const QList<QString> SupportedCommands() const;

  QTextStream output { stdout, QIODevice::WriteOnly };
  QTextStream input { stdin, QIODevice::ReadOnly };
};

class QCliExtension : public QObject {
  Q_OBJECT

 public:
  // Register custom commands associated with this extension
  static void Register() {}
};


text:
package com.siziksu.annotations.data.bus;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Subscribe {

}


text:
class Image < ActiveRecord::Base
  dragonfly_for :image
end


text:
import uuid
from datetime import datetime
import time

class Dotable(dict):
    __getattr__ = dict.__getitem__

    def __init__(self, d):
        self.update(**dict((k, self.parse(v))
                           for k, v in d.items()))

    @classmethod
    def parse(cls, v):
        if isinstance(v, dict):
            return cls(v)
        elif isinstance(v, list):
            return [cls.parse(i) for i in v]
        else:
            return v

def unique_string(prefix='', length=0):
    if length == 0:
        return prefix + str(uuid.uuid4()).replace('-', '')
    else:
        return prefix + str(uuid.uuid4()).replace('-', '')[0:(length - len(prefix))]

def unique_tenchar():
    return str(int((time.time() + 0.5) * 1000))[-10:]

def iso_datetime(date_obj=None):
    if date_obj is None:
        date_obj = datetime.now()
    return date_obj.strftime("%Y-%m-%dT%H:%M:%S")

def timestamp_string():
    return datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M')


text:
package main

import (
	"encoding/binary"
	"math/rand"
	"time"
)

const (
	IPHeaderLen  = 20
	UDPHeaderLen = 42
	IPProtoUDP   = 17
	IPProtoTCP   = 6
	IPProtoICMP  = 1
)

//The UDP header structure is the header that will come after the IP header in an IP packet.
//It contains the Source Port, Destination Port, Length, and UDP Checksum
type UDPHeader struct {
	SrcPort  uint16 //Source Port
	DstPort  uint16 //Destination Port
	Len      uint16 //length of header
	Checksum uint16 //checksum of header, optional set to 0 for ipv4
}

//The marshal function packs the UDP header into a raw, network friendly (BigEndian), and returns it as a byte array.
func (uh *UDPHeader) Marshal() ([]byte, error) {
	if uh == nil {
		//no object used sad face
	}
	//check the header len
	b := make([]byte, 8)
	srcportb := make([]byte, 2)
	dstportb := make([]byte, 2)
	lenb := make([]byte, 2)
	checksumb := make([]byte, 2)
	binary.BigEndian.PutUint16(srcportb, uh.SrcPort)
	binary.BigEndian.PutUint16(dstportb, uh.DstPort)
	binary.BigEndian.PutUint16(lenb, uh.Len)
	binary.BigEndian.PutUint16(checksumb, uh.Checksum)
	copy(b[0:2], srcportb)
	copy(b[2:4], dstportb)
	copy(b[4:6], lenb)
	copy(b[6:8], checksumb)

	return b, nil
}

//BUG(Rob): This doesnt work yet
//Generates the proper checksum for the UDP header
//https://github.com/packetbeat/gopacket/blob/9f6f103107a8eeea93a485f4fc7880d7e663e3b9/layers/tcpip.go
func (uh *UDPHeader) GenChecksum() error {
	//calcumete
	uh.Checksum = 0
	return nil
}

//Sets the source port of the packet
func (uh *UDPHeader) SetSrcPort(port uint16) {
	uh.SrcPort = port
}

//Sets the source port to a random port greater than 1025
func (uh *UDPHeader) GenRandomSrcPort() {
	rand.Seed(time.Now().UnixNano() * time.Now().UnixNano())
	uh.SrcPort = uint16(rand.Intn(65535-1025) + 1025)
}

func (uh *UDPHeader) SetDstPort(port uint16) {
	uh.DstPort = port
}

func (uh *UDPHeader) SetLen(l uint16) {
	uh.Len = l
}

func (uh *UDPHeader) SetChecksum(cs uint16) {
	uh.Checksum = cs
}


text:
. ./path.sh

softmax_dim=
remove_last_components=2
# End of config.

echo "$0 $@"  # Print the command line for logging

. utils/parse_options.sh || exit 1;

usage="Usage: $0 <hmm model> <input_network> <output_network> > "
##e.g. renew_nnet_softmax.sh exp/tri3b/final.mdl nnet.old nnet.new

[[ $# -eq 3 ]] || { echo $usage; exit 1; }

mdl=$1    # hmm-gmm mdl file
oldnn=$2  # old dnn
newnn=$3  # new dnn

[[ -e $mdl ]] || { echo "$mdl does not exist"; exit 1; }
[[ -e $oldnn ]] || { echo "$oldnn does not exist"; exit 1; }

nndir=$(mktemp -d)
trap "rm -rf $nndir;" EXIT
echo
#Discover softmax dimensions from number of triphone tree leaves
[[ -z ${softmax_dim} ]] && softmax_dim=$(hmm-info $mdl | grep pdfs | awk '{ print $NF }')
echo "Number of PDFIDs: ${softmax_dim}"

echo "Stripping pre-trained network of softmax layer"
#Remove the softmax layer from pre-trained network which includes
# the last two components: <AffineTransform> and  <Softmax>
oldnnname=$(basename $oldnn)
nnet_stripped=$nndir/${oldnnname}_stripped.init
nnet-copy --binary=false --remove-last-components=${remove_last_components} $oldnn ${nnet_stripped}
echo "Done"
echo

echo "Protyping new softmax layer"
# Create new softmax layer, i.e., both create new <AffineTransform> and  <Softmax> components
##Note the number of hidden neurons must be greater than zero, 1 was arbitrarily chosen
tempnn="softmax"
oldnn_outdim=$(nnet-info ${nnet_stripped}|tail -n 1|awk '{print $NF}'|sed 's/\([0-9]\+\).*/\1/g')
echo "olddnn outdim = ${oldnn_outdim}"
echo "Output dim of last hidden layer = ${oldnn_outdim}"
[[ ! -z ${oldnn_outdim} ]] && [[ ${oldnn_outdim} -gt 0 ]] || { echo "output dim of the old nn is not valid = ${oldnn_outdim}"; exit 1; }
python utils/nnet/make_nnet_proto.py --no-proto-head 39 ${softmax_dim} 1 ${oldnn_outdim}|tail -n 3 > $nndir/${tempnn}.proto
echo "Done"
echo

echo "Initializing new softmax layer randomly"
#Initialize the softmax layer (if you do not specify a seed value, nnet-initialize uses the default seed
# everytime ... thereby generating the same initialized n/w no matter how many times you call nnet-initialize).
nnet-initialize --binary=false $nndir/${tempnn}.proto $nndir/${tempnn}.init
echo "Done"
echo

echo "Concatenating two networks"
#Connect the two networks
#Make sure that the oldnn_outdim = softmax_indim dimensions
nnet-concat ${nnet_stripped} $nndir/${tempnn}.init ${newnn}
echo "New network is stored at" ${newnn}
echo "Done"
echo

##Comment out these lines if there is no need to check work.
#Copy to ASCII for debugging newly created network to binary
#nnet-copy --binary=false $nndir/${newnn}.init $nndir/${newnn}_text.init
#echo "New network is stored at" $nndir/${newnn}_text.init


text:
package com.github.emalock3.camel.jira;

import static org.hamcrest.Matchers.is;

import java.util.Iterator;
import java.util.List;

import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.bridge.SLF4JBridgeHandler;

import com.atlassian.jira.rest.client.domain.Issue;

public class JiraProjectIssueComponentTest extends CamelTestSupport {

	private static volatile StaticJsonFileServer SERVER;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		SLF4JBridgeHandler.removeHandlersForRootLogger();
		SLF4JBridgeHandler.install();
		SERVER = new StaticJsonFileServer(
				StaticJsonFileServer.from("search-issues.json", "/jira/rest/api/latest/search"),
				StaticJsonFileServer.from("issue.json", "/jira/rest/api/latest/issue/*")
		);
		SERVER.start();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		SERVER.shutdown();
		SERVER = null;
	}

	@EndpointInject(uri = "mock:result")
	protected MockEndpoint resultEndpoint;

	@Test
	public void test() {
		template.sendBody("direct:start", "hoge");
		List<Exchange> exchanges = resultEndpoint.getReceivedExchanges();
		assertThat(exchanges.size(), is(1));
		Exchange exchange = exchanges.get(0);
		Iterator<Issue> iter =
				exchange.getIn().getBody(IssueIterator.class);
		assertThat(iter.hasNext(), is(true));
		while (iter.hasNext()) {
			Issue issue = iter.next();
			assertThat(issue.getKey(), is("CAMEL-7253"));
		}
	}

	@Override
	protected RouteBuilder createRouteBuilder() {
		return new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				from("direct:start")
					.toF("jira-project-issue:CAMEL?baseURI=http://localhost:%d/jira",
							SERVER.port())
					.to("mock:result")
					.log("end");
			}
		};
	}

}


text:
let canvas = document.getElementById('game') as HTMLCanvasElement;

var gl = canvas.getContext('webgl');
if (!gl) {
	throw new Error('Could not create WebGL Context!');
}

// 🔲 Create NDC Space Quad (attribute vec2 position)
let ndcQuad = [ 1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ];
let indices = [ 0, 1, 2, 1, 2, 3 ];

// Create Buffers
let dataBuffer = gl.createBuffer();
let indexBuffer = gl.createBuffer();

// Bind Data/Indices to Buffers
gl.bindBuffer(gl.ARRAY_BUFFER, dataBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(ndcQuad), gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);

function createProgram(vsSource: string, fsSource: string) {
	let vs = gl.createShader(gl.VERTEX_SHADER);
	gl.shaderSource(vs, vsSource);
	gl.compileShader(vs);
	if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
		console.error('An error occurred compiling the shader: ' + gl.getShaderInfoLog(vs));
	}

	let fs = gl.createShader(gl.FRAGMENT_SHADER);
	gl.shaderSource(fs, fsSource);
	gl.compileShader(fs);
	if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
		console.error('An error occurred compiling the shader: ' + gl.getShaderInfoLog(fs));
	}

	let program = gl.createProgram();
	gl.attachShader(program, vs);
	gl.attachShader(program, fs);
	gl.linkProgram(program);
	if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
		console.error(gl.getProgramInfoLog(program));
	}
	return { vs, fs, program };
}

let vs = `
attribute vec2 aPosition;
varying vec2 vFragCoord;

void main()
{
  vFragCoord = (0.5 * aPosition) + vec2(0.5, 0.5);
  vFragCoord.y  = 1.0 - vFragCoord.y;
  gl_Position = vec4(aPosition, 0.0, 1.0);
}
`;

let fs = `
precision mediump float;

varying vec2 vFragCoord;

uniform sampler2D tBottomLayer;
uniform sampler2D tTopLayer;

// 🌅 Color Dodge
vec4 colorDodge(vec4 col, vec4 blend)
{
  return vec4(mix(col.rgb / clamp(1.0 - blend.rgb, 0.00001, 1.0), col.rgb, blend.a), col.a);
}

void main()
{
  vec2 uv = vFragCoord;
  vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);

  vec4 bottomColor = texture2D(tBottomLayer, uv);
  vec4 topColor = texture2D(tTopLayer, uv);

  outColor = colorDodge(bottomColor, topColor);

  gl_FragColor = outColor;
}
`;

let { program } = createProgram(vs, fs);

// 🖼 Load Textures
function loadTexture(url: string) {
	let tex = gl.createTexture();
	gl.bindTexture(gl.TEXTURE_2D, tex);
	const pixel = new Uint8Array([ 0, 0, 0, 255 ]);
	gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
	let img = new Image();
	img.src = url;
	img.onload = () => {
		gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
		gl.generateMipmap(gl.TEXTURE_2D);
	};
	return tex;
}

let bottomLayer = loadTexture('https://alain.xyz/blog/image-editor-effects/assets/cover.jpg');
let topLayer = loadTexture('https://alain.xyz/blog/unreal-engine-architecture/assets/cover.png');

// 📐 Draw
function draw() {
	// Bind Shaders
	gl.useProgram(program);

	// Bind Vertex Layout
	let loc = gl.getAttribLocation(program, 'aPosition');
	gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 4 * 2, 0);
	gl.enableVertexAttribArray(loc);
	gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

	// Bind Uniforms
	var shaderTexNumber = 0;
	let bottomLayerLoc = gl.getUniformLocation(program, 'tBottomLayer');
	gl.uniform1i(bottomLayerLoc, shaderTexNumber);
	gl.activeTexture(gl.TEXTURE0 + shaderTexNumber);
	gl.bindTexture(gl.TEXTURE_2D, bottomLayer);
	shaderTexNumber++;
	let topLayerLoc = gl.getUniformLocation(program, 'tTopLayer');
	gl.uniform1i(topLayerLoc, shaderTexNumber);
	gl.activeTexture(gl.TEXTURE0 + shaderTexNumber);
	gl.bindTexture(gl.TEXTURE_2D, topLayer);

	gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
}
let resizeHandler = () => {
	canvas.width = innerWidth;
	canvas.height = innerHeight;
	gl.viewport(0, 0, innerWidth, innerHeight);
	draw();
};

window.addEventListener('resize', resizeHandler);
resizeHandler();

function update()
{
  draw();
  requestAnimationFrame(update)
}

requestAnimationFrame(update);


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

<title>org.codehaus.groovy.classgen.asm.sc (groovy 2.4.4 API)</title>
<meta name="keywords" content="org.codehaus.groovy.classgen.asm.sc package">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" title="Style">
<link href="../../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../../groovy.ico" type="image/x-icon" rel="icon">

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Package org.codehaus.groovy.classgen.asm.sc

Class Summary

                        Class
                        Description

                                    StaticCompilationMopWriter

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticInvocationWriter

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticPropertyAccessHelper

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticTypesBinaryExpressionMultiTypeDispatcher

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticTypesCallSiteWriter

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticTypesClosureWriter

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticTypesStatementWriter

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticTypesTypeChooser

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticTypesUnaryExpressionHelper

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticTypesWriterController

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

                                    StaticTypesWriterControllerFactoryImpl

                            Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Copyright © 2003-2015 The Apache Software Foundation. All rights reserved.


text:
package software.sham.ssh;

import org.apache.sshd.common.Factory;
import org.apache.sshd.common.keyprovider.AbstractClassLoadableResourceKeyPairProvider;
import org.apache.sshd.common.util.SecurityUtils;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.CommandFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.pubkey.KeySetPublickeyAuthenticator;
import org.apache.sshd.server.session.ServerSession;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class MockSshServer implements Factory<Command>, CommandFactory {
    public static final String USERNAME = "tester";
    public static final String PASSWORD = "testing";
    protected final SshServer sshServer;
    private Set<PublicKey> keys = new HashSet<PublicKey>();

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private MockSshShell sshShell;

    public MockSshServer(int port) throws IOException {
        this(port, true);
    }

    protected MockSshServer(int port, boolean shouldStartServices) throws IOException {
        sshServer = initSshServer(port);
        if (shouldStartServices) {
            enableShell();
            start();
        }
    }

    /**
     * @param key Key in DER format
     */
    public MockSshServer allowPublicKey(byte[] key) throws GeneralSecurityException {
        final KeySpec spec = new X509EncodedKeySpec(key);
        keys.add(KeyFactory.getInstance("RSA").generatePublic(spec));
        sshServer.setPublickeyAuthenticator(new KeySetPublickeyAuthenticator(this.keys));
        return this;
    }

    public SshResponderBuilder respondTo(Matcher matcher) {
        SshResponderBuilder builder = new SshResponderBuilder();
        sshShell.getDispatcher().add(matcher, builder.getResponder());
        return builder;
    }

    public SshResponderBuilder respondTo(String input) {
        return respondTo(Matchers.equalTo(input));
    }

    public MockSshServer enableShell() {
        logger.info("Mock SSH shell is enabled");
        sshShell = new MockSshShell();
        setDefaults();
        sshServer.setShellFactory(this);
        return this;
    }

    public void start() throws IOException {
        AbstractClassLoadableResourceKeyPairProvider keyPairProvider = SecurityUtils.createClassLoadableResourceKeyPairProvider();
        keyPairProvider.setResources(Arrays.asList("keys/sham-ssh-id-dsa"));
        sshServer.setKeyPairProvider(keyPairProvider);

        sshServer.start();
    }

    public void stop() throws IOException {
        sshServer.stop();
    }

    protected SshServer initSshServer(int port) {
        final SshServer sshd = SshServer.setUpDefaultServer();
        sshd.setPort(port);
        sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
            @Override
            public boolean authenticate(String username, String password, ServerSession session) {
                return USERNAME.equals(username) && PASSWORD.equals(password);
            }

        });
        sshd.setPublickeyAuthenticator(new KeySetPublickeyAuthenticator(this.keys));
        return sshd;
    }

    private void setDefaults() {
        respondTo("exit").withClose();
    }

    @Override
    public Command create() {
        logger.debug("Creating mock SSH shell");
        return sshShell;
    }

    @Override
    public Command createCommand(String command) {
        return create();
    }
}


text:
<?php
namespace Concrete\Core\Backup\ContentImporter\Importer\Routine;

use Concrete\Core\Block\BlockType\BlockType;
use Concrete\Core\Permission\Category;
use Concrete\Core\Validation\BannedWord\BannedWord;

class ImportWorkflowProgressCategoriesRoutine extends AbstractRoutine
{
    public function getHandle()
    {
        return 'workflow_progress_categories';
    }

    public function import(\SimpleXMLElement $sx)
    {
        if (isset($sx->workflowprogresscategories)) {
            foreach ($sx->workflowprogresscategories->category as $wpc) {
                $pkg = static::getPackageObject($wpc['package']);
                $category = \Concrete\Core\Workflow\Progress\Category::getByHandle((string) $wpc['handle']);
                if (!is_object($category)) {
                    \Concrete\Core\Workflow\Progress\Category::add((string) $wpc['handle'], $pkg);
                }
            }
        }
    }

}


text:
---
title: Database Models
keywords: component
tags: [component]
sidebar: home_sidebar
permalink: database-models.html
summary: V1 Specification
---

## Database Models

```
/*
Navicat MySQL Data Transfer

Source Server         : 104.196.228.46test
Source Server Version : 50716
Source Host           : 104.196.228.46:3306
Source Database       : newdb

Target Server Type    : MYSQL
Target Server Version : 50716
File Encoding         : 65001

Date: 2016-12-28 12:09:38
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for action
-- ----------------------------
DROP TABLE IF EXISTS `action`;
CREATE TABLE `action` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `repository` varchar(255) NOT NULL,
  `workflow` bigint(20) NOT NULL DEFAULT '0',
  `stage` bigint(20) NOT NULL DEFAULT '0',
  `component` bigint(20) NOT NULL DEFAULT '0',
  `service` bigint(20) NOT NULL DEFAULT '0',
  `action` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text,
  `event` bigint(20) DEFAULT '0',
  `manifest` longtext,
  `environment` text,
  `kubernetes` text,
  `swarm` text,
  `input` text,
  `output` text,
  `image_name` varchar(255) DEFAULT NULL,
  `image_tag` varchar(255) DEFAULT NULL,
  `timeout` varchar(255) DEFAULT NULL,
  `requires` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_action_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=1839 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for action_log
-- ----------------------------
DROP TABLE IF EXISTS `action_log`;
CREATE TABLE `action_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `repository` varchar(255) NOT NULL,
  `workflow` bigint(20) NOT NULL DEFAULT '0',
  `from_workflow` bigint(20) NOT NULL DEFAULT '0',
  `sequence` bigint(20) NOT NULL DEFAULT '0',
  `stage` bigint(20) NOT NULL DEFAULT '0',
  `from_stage` bigint(20) NOT NULL DEFAULT '0',
  `from_action` bigint(20) NOT NULL DEFAULT '0',
  `run_state` bigint(20) DEFAULT NULL,
  `component` bigint(20) NOT NULL DEFAULT '0',
  `service` bigint(20) NOT NULL DEFAULT '0',
  `action` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text,
  `event` bigint(20) DEFAULT '0',
  `manifest` longtext,
  `environment` text,
  `kubernetes` text,
  `swarm` text,
  `input` text,
  `output` text,
  `image_name` varchar(255) DEFAULT NULL,
  `image_tag` varchar(255) DEFAULT NULL,
  `timeout` varchar(255) DEFAULT NULL,
  `requires` longtext,
  `auth_list` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  `fail_reason` varchar(255) DEFAULT NULL,
  `container_id` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_action_log_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=2357 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for component
-- ----------------------------
DROP TABLE IF EXISTS `component`;
CREATE TABLE `component` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `version` text,
  `version_code` bigint(20) DEFAULT NULL,
  `component` varchar(255) NOT NULL,
  `type` bigint(20) NOT NULL DEFAULT '0',
  `title` varchar(255) DEFAULT NULL,
  `gravatar` text,
  `description` text,
  `endpoint` text,
  `source` text NOT NULL,
  `environment` text,
  `tag` varchar(255) DEFAULT NULL,
  `volume_location` text,
  `volume_data` text,
  `makefile` text,
  `kubernetes` text,
  `swarm` text,
  `input` text,
  `output` text,
  `timeout` bigint(20) DEFAULT NULL,
  `manifest` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_component_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for event
-- ----------------------------
DROP TABLE IF EXISTS `event`;
CREATE TABLE `event` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `definition` bigint(20) NOT NULL DEFAULT '0',
  `title` varchar(255) NOT NULL,
  `header` text NOT NULL,
  `payload` longtext NOT NULL,
  `authorization` text,
  `type` bigint(20) NOT NULL DEFAULT '0',
  `source` bigint(20) NOT NULL DEFAULT '0',
  `character` bigint(20) NOT NULL DEFAULT '0',
  `namespace` varchar(255) DEFAULT NULL,
  `repository` varchar(255) DEFAULT NULL,
  `workflow` bigint(20) NOT NULL DEFAULT '0',
  `stage` bigint(20) NOT NULL DEFAULT '0',
  `action` bigint(20) NOT NULL DEFAULT '0',
  `sequence` bigint(20) NOT NULL DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_event_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=21561 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for event_definition
-- ----------------------------
DROP TABLE IF EXISTS `event_definition`;
CREATE TABLE `event_definition` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `event` varchar(255) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `namespace` varchar(255) DEFAULT NULL,
  `repository` varchar(255) DEFAULT NULL,
  `workflow` bigint(20) DEFAULT NULL,
  `stage` bigint(20) DEFAULT NULL,
  `action` bigint(20) NOT NULL DEFAULT '0',
  `character` bigint(20) NOT NULL DEFAULT '0',
  `type` bigint(20) NOT NULL DEFAULT '0',
  `source` bigint(20) NOT NULL DEFAULT '0',
  `definition` text,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_event_definition_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=14137 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for event_json
-- ----------------------------
DROP TABLE IF EXISTS `event_json`;
CREATE TABLE `event_json` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `site` varchar(255) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `output` longtext,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for outcome
-- ----------------------------
DROP TABLE IF EXISTS `outcome`;
CREATE TABLE `outcome` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `workflow` bigint(20) NOT NULL DEFAULT '0',
  `real_workflow` bigint(20) NOT NULL DEFAULT '0',
  `stage` bigint(20) NOT NULL DEFAULT '0',
  `real_stage` bigint(20) NOT NULL DEFAULT '0',
  `action` bigint(20) NOT NULL DEFAULT '0',
  `real_action` bigint(20) NOT NULL DEFAULT '0',
  `event` bigint(20) DEFAULT '0',
  `sequence` bigint(20) NOT NULL DEFAULT '0',
  `status` tinyint(1) DEFAULT NULL,
  `result` longtext,
  `output` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_outcome_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=3357 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for serivce_definition
-- ----------------------------
DROP TABLE IF EXISTS `serivce_definition`;
CREATE TABLE `serivce_definition` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `service` varchar(255) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `gravatar` text,
  `endpoints` text,
  `status` text,
  `environment` text,
  `authorization` text,
  `configuration` text,
  `description` text,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `service` (`service`),
  KEY `idx_serivce_definition_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for service
-- ----------------------------
DROP TABLE IF EXISTS `service`;
CREATE TABLE `service` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `service` varchar(255) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `gravatar` text,
  `endpoints` text,
  `environment` text,
  `authorization` text,
  `configuration` text,
  `description` text,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `namespace_service` (`namespace`,`service`),
  KEY `idx_service_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for stage
-- ----------------------------
DROP TABLE IF EXISTS `stage`;
CREATE TABLE `stage` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `repository` varchar(255) NOT NULL,
  `workflow` bigint(20) NOT NULL DEFAULT '0',
  `type` bigint(20) NOT NULL DEFAULT '0',
  `pre_stage` bigint(20) NOT NULL DEFAULT '0',
  `stage` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text,
  `event` bigint(20) DEFAULT '0',
  `manifest` longtext,
  `env` longtext,
  `timeout` varchar(255) DEFAULT NULL,
  `requires` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_stage_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=1836 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for stage_log
-- ----------------------------
DROP TABLE IF EXISTS `stage_log`;
CREATE TABLE `stage_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `repository` varchar(255) NOT NULL,
  `workflow` bigint(20) NOT NULL DEFAULT '0',
  `from_workflow` bigint(20) NOT NULL DEFAULT '0',
  `sequence` bigint(20) NOT NULL DEFAULT '0',
  `from_stage` bigint(20) NOT NULL DEFAULT '0',
  `type` bigint(20) NOT NULL DEFAULT '0',
  `pre_stage` bigint(20) NOT NULL DEFAULT '0',
  `stage` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text,
  `run_state` bigint(20) DEFAULT NULL,
  `event` bigint(20) DEFAULT '0',
  `manifest` longtext,
  `env` longtext,
  `timeout` varchar(255) DEFAULT NULL,
  `requires` longtext,
  `auth_list` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  `fail_reason` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_stage_log_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=2306 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for timer
-- ----------------------------
DROP TABLE IF EXISTS `timer`;
CREATE TABLE `timer` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `repository` varchar(255) NOT NULL,
  `workflow` bigint(20) DEFAULT NULL,
  `available` tinyint(1) DEFAULT NULL,
  `cron` varchar(255) DEFAULT NULL,
  `event_type` varchar(255) DEFAULT NULL,
  `event_name` varchar(255) DEFAULT NULL,
  `start_json` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_timer_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for user_setting
-- ----------------------------
DROP TABLE IF EXISTS `user_setting`;
CREATE TABLE `user_setting` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `repository` varchar(255) NOT NULL,
  `setting` text,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_user_setting_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for workflow
-- ----------------------------
DROP TABLE IF EXISTS `workflow`;
CREATE TABLE `workflow` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `repository` varchar(255) NOT NULL,
  `workflow` varchar(255) NOT NULL,
  `event` bigint(20) DEFAULT '0',
  `version` varchar(255) DEFAULT NULL,
  `version_code` varchar(255) DEFAULT NULL,
  `state` bigint(20) DEFAULT NULL,
  `manifest` longtext,
  `description` text,
  `source_info` longtext,
  `env` longtext,
  `requires` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  `is_limit_instance` tinyint(1) DEFAULT NULL,
  `limit_instance` bigint(20) DEFAULT NULL,
  `current_instance` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_workflow_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for workflow_log
-- ----------------------------
DROP TABLE IF EXISTS `workflow_log`;
CREATE TABLE `workflow_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `namespace` varchar(255) NOT NULL,
  `repository` varchar(255) NOT NULL,
  `workflow` varchar(255) NOT NULL,
  `from_workflow` bigint(20) NOT NULL DEFAULT '0',
  `pre_workflow` bigint(20) NOT NULL DEFAULT '0',
  `pre_workflow_info` varchar(255) DEFAULT NULL,
  `version` varchar(255) DEFAULT NULL,
  `version_code` varchar(255) DEFAULT NULL,
  `sequence` bigint(20) NOT NULL DEFAULT '0',
  `run_state` bigint(20) DEFAULT NULL,
  `event` bigint(20) DEFAULT '0',
  `manifest` longtext,
  `description` text,
  `source_info` longtext,
  `env` longtext,
  `requires` longtext,
  `auth_list` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  `pre_stage` bigint(20) NOT NULL DEFAULT '0',
  `pre_action` bigint(20) NOT NULL DEFAULT '0',
  `fail_reason` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_workflow_log_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=621 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for workflow_sequence
-- ----------------------------
DROP TABLE IF EXISTS `workflow_sequence`;
CREATE TABLE `workflow_sequence` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `workflow` bigint(20) NOT NULL DEFAULT '0',
  `sequence` bigint(20) NOT NULL DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_workflow_sequence_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=621 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for workflow_var
-- ----------------------------
DROP TABLE IF EXISTS `workflow_var`;
CREATE TABLE `workflow_var` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `workflow` bigint(20) DEFAULT NULL,
  `key` varchar(255) DEFAULT NULL,
  `default` longtext,
  `vaule` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_workflow_var_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for workflow_var_log
-- ----------------------------
DROP TABLE IF EXISTS `workflow_var_log`;
CREATE TABLE `workflow_var_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `workflow` bigint(20) DEFAULT NULL,
  `from_workflow` bigint(20) DEFAULT NULL,
  `sequence` bigint(20) DEFAULT NULL,
  `key` varchar(255) DEFAULT NULL,
  `default` longtext,
  `vaule` longtext,
  `change_log` longtext,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

```


text:
node-sms-client
===============

Development of this example package is still in progress!

Demonstrate usage of node-sms with an sms client.

Installation
---------------

	npm install sms-client

Usage
---------------

  1. Run server inside directory: `node server.js`
  2. Call localhost in browser


text:
package org.apache.hadoop.hbase.metrics;

import java.util.Arrays;
import java.util.Random;

import org.apache.hadoop.hbase.metrics.histogram.MetricsHistogram;
import org.apache.hadoop.hbase.metrics.histogram.Snapshot;
import org.junit.Assert;
import org.junit.Test;

public class TestMetricsHistogram {

  @Test
  public void testBasicUniform() {
    MetricsHistogram h = new MetricsHistogram("testHistogram", null);

    for (int i = 0; i < 100; i++) {
      h.update(i);
    }

    Assert.assertEquals(100, h.getCount());
    Assert.assertEquals(0, h.getMin());
    Assert.assertEquals(99, h.getMax());
  }

  private static int safeIndex(int i, int len) {
    if (i < len && i>= 0) {
      return i;
    } else if (i >= len) {
      return len - 1;
    } else {
      return 0;
    }
  }

  @Test
  public void testRandom() {
    final Random r = new Random();
    final MetricsHistogram h = new MetricsHistogram("testHistogram", null);

    final long[] data = new long[1000];

    for (int i = 0; i < data.length; i++) {
      data[i] = (long) (r.nextGaussian() * 10000.0);
      h.update(data[i]);
    }

    final Snapshot s = h.getSnapshot();
    Arrays.sort(data);

    // as long as the histogram chooses an item with index N+/-slop, accept it
    final int slop = 20;

    // make sure the median, 75th percentile and 95th percentile are good
    final int medianIndex = data.length / 2;
    final long minAcceptableMedian = data[safeIndex(medianIndex - slop,
        data.length)];
    final long maxAcceptableMedian = data[safeIndex(medianIndex + slop,
        data.length)];
    Assert.assertTrue(s.getMedian() >= minAcceptableMedian
        && s.getMedian() <= maxAcceptableMedian);

    final int seventyFifthIndex = (int) (data.length * 0.75);
    final long minAcceptableseventyFifth = data[safeIndex(seventyFifthIndex
        - slop, data.length)];
    final long maxAcceptableseventyFifth = data[safeIndex(seventyFifthIndex
        + slop, data.length)];
    Assert.assertTrue(s.get75thPercentile() >= minAcceptableseventyFifth
        && s.get75thPercentile() <= maxAcceptableseventyFifth);

    final int ninetyFifthIndex = (int) (data.length * 0.95);
    final long minAcceptableninetyFifth = data[safeIndex(ninetyFifthIndex
        - slop, data.length)];
    final long maxAcceptableninetyFifth = data[safeIndex(ninetyFifthIndex
        + slop, data.length)];
    Assert.assertTrue(s.get95thPercentile() >= minAcceptableninetyFifth
        && s.get95thPercentile() <= maxAcceptableninetyFifth);

  }
}


text:
'use strict';

// CHART //

/**
* FUNCTION: Chart()
*	Chart constructor.
*
* @constructor
* @returns {Chart} Chart instance
*/
function Chart() {
	if ( !( this instanceof Chart ) ) {
		return new Chart();
	}
	return this;
} // end FUNCTION Chart()

// ATTRIBUTES //

/**
* ATTRIBUTE: paddingLeft
*	Chart canvas left padding.
*
* @type {Null|Number}
* @default null
*/
Chart.prototype.paddingLeft = null;

/**
* ATTRIBUTE: paddingRight
*	Chart canvas right padding.
*
* @type {Null|Number}
* @default null
*/
Chart.prototype.paddingRight = null;

/**
* ATTRIBUTE: paddingBottom
*	Chart canvas bottom padding.
*
* @type {Null|Number}
* @default null
*/
Chart.prototype.paddingBottom = null;

/**
* ATTRIBUTE: paddingTop
*	Chart canvas top padding.
*
* @type {Null|Number}
* @default null
*/
Chart.prototype.paddingTop = null;

/**
* ATTRIBUTE: width
*	Chart canvas width. If not explicitly set, defaults to the width of the parent node.
*
* @type {Number}
* @default null
*/
Chart.prototype.width = null;

/**
* ATTRIBUTE: height
*	Chart canvas height. If not explicitly set, defaults to the height of the parent node.
*
* @type {Number}
* @default null
*/
Chart.prototype.height = null;

/**
* ATTRIBUTE: xLabel
*	Column label.
*
* @type {String}
* @default ''
*/
Chart.prototype.xLabel = '';

/**
* ATTRIBUTE: yLabel
*	Row label.
*
* @type {String}
* @default ''
*/
Chart.prototype.yLabel = '';

/**
* ATTRIBUTE: zValue
*	z-value accessor. If set to a function, the accessor is used to map z-values to a linear scale for fill-opacity.
*
* @type {Number|Function}
* @default 1
*/
Chart.prototype.zValue = 1;

/**
* ATTRIBUTE: zMin
*	Minimum z-limit. If `null`, the limit is computed from the data.
*
* @type {Null|Number}
* @default null
*/
Chart.prototype.zMin = null;

/**
* ATTRIBUTE: zMax
*	Maximum z-limit. If `null`, the limit is computed from the data.
*
* @type {Null|Number}
* @default null
*/
Chart.prototype.zMax = null;

/**
* ATTRIBUTE: cValue( d, i )
*	color-value accessor.
*
* @param {*} d - datum
* @param {Number} i - index
* @returns {Number} 0
*/
Chart.prototype.cValue = function() {
	return 0;
};

/**
* ATTRIBUTE: duration
*	Transition duration.
*
* @type {Number}
* @default 2500 milliseconds
*/
Chart.prototype.duration = 2500; // ms

/**
* ATTRIBUTE: autoUpdate
*	Boolean flag indicating whether a chart should auto update DOM elements whenever an attribute changes.
*
* @type {Boolean}
* @default true
*/
Chart.prototype.autoUpdate = true;

/**
* ATTRIBUTE: autoResize
*	Boolean flag indicating whether a chart should auto resize when the window resizes.
*
* @type {Boolean}
* @default true
*/
Chart.prototype.autoResize = true;

/**
* ATTRIBUTE: isBrushable
*	Boolean flag indicating whether a chart is brushable.
*
* @type {Boolean}
* @default false
*/
Chart.prototype.isBrushable = false;

/**
* ATTRIBUTE: isSortableRows
*	Boolean flag indicating whether rows can be manually sorted.
*
* @type {Boolean}
* @default false
*/
Chart.prototype.isSortableRows = false;

/**
* ATTRIBUTE: isSortableCols
*	Boolean flag indicating whether columns can be manually sorted.
*
* @type {Boolean}
* @default false
*/
Chart.prototype.isSortableCols = false;

// LIFECYCLE //

Chart.prototype.created = require( './lifecycle/created.js' );

Chart.prototype.attached = require( './lifecycle/attached.js' );

Chart.prototype.detached = require( './lifecycle/detached.js' );

// INIT //

Chart.prototype.init = require( './init' );

// CHART CREATION //

Chart.prototype.create = require( './create' );

Chart.prototype.createBase = require( './create/base.js' );

Chart.prototype.createBackground = require( './create/background.js' );

Chart.prototype.createMarks = require( './create/marks.js' );

Chart.prototype.createRows = require( './create/rows.js' );

Chart.prototype.createCols = require( './create/cols.js' );

Chart.prototype.createCells = require( './create/cells.js' );

Chart.prototype.createAxes = require( './create/axes.js' );

Chart.prototype.createBrush = require( './create/brush.js' );

// RESET ELEMENTS //

Chart.prototype.reset = require( './reset' );

Chart.prototype.resetBase = require( './reset/base.js' );

Chart.prototype.resetAxes = require( './reset/axes.js' );

Chart.prototype.resetRows = require( './reset/rows.js' );

Chart.prototype.resetCols = require( './reset/cols.js' );

Chart.prototype.resetCells = require( './reset/cells.js' );

// CLEAR //

Chart.prototype.clear = require( './clear' );

// UTILITY METHODS //

Chart.prototype.graphWidth = require( './utils/graphWidth.js' );

Chart.prototype.graphHeight = require( './utils/graphHeight.js' );

Chart.prototype.x = require( './utils/x.js' );

Chart.prototype.y = require( './utils/y.js' );

Chart.prototype.z = require( './utils/z.js' );

Chart.prototype.cx = require( './utils/cx.js' );

Chart.prototype.color = require( './utils/color.js' );

Chart.prototype.getRowName = require( './utils/getRowName.js' );

Chart.prototype.getColName = require( './utils/getColName.js' );

Chart.prototype.zDomain = require( './utils/zDomain.js' );

Chart.prototype.colorDomain = require( './utils/colorDomain.js' );

Chart.prototype.delay = require( './utils/delay.js' );

Chart.prototype.fontSize = require( './utils/fontSize.js' );

Chart.prototype.calculatePadding = require( './utils/calculatePadding.js' );

Chart.prototype.maxTextLengths = require( './utils/maxTextLengths.js' );

Chart.prototype.validateOrder = require( './utils/validateOrder.js' );

Chart.prototype.toJSON = require( './utils/toJSON.js' );

// WATCHERS //

Chart.prototype.dataChanged = require( './watchers/data.js' );

Chart.prototype.rowOrderChanged = require( './watchers/rowOrder.js' );

Chart.prototype.colOrderChanged = require( './watchers/colOrder.js' );

Chart.prototype.configChanged = require( './watchers/config.js' );

Chart.prototype.widthChanged = require( './watchers/width.js' );

Chart.prototype.heightChanged = require( './watchers/height.js' );

Chart.prototype.paddingLeftChanged = require( './watchers/paddingLeft.js' );

Chart.prototype.paddingRightChanged = require( './watchers/paddingRight.js' );

Chart.prototype.paddingBottomChanged = require( './watchers/paddingBottom.js' );

Chart.prototype.paddingTopChanged = require( './watchers/paddingTop.js' );

Chart.prototype.zValueChanged = require( './watchers/zValue.js' );

Chart.prototype.zMinChanged = require( './watchers/zMin.js' );

Chart.prototype.zMaxChanged = require( './watchers/zMax.js' );

Chart.prototype.cValueChanged = require( './watchers/cValue.js' );

Chart.prototype.colorOrderChanged = require( './watchers/colorOrder.js' );

Chart.prototype.colorsChanged = require( './watchers/colors.js' );

Chart.prototype.xLabelChanged = require( './watchers/xLabel.js' );

Chart.prototype.yLabelChanged = require( './watchers/yLabel.js' );

Chart.prototype.durationChanged = require( './watchers/duration.js' );

Chart.prototype.autoUpdateChanged = require( './watchers/autoUpdate.js' );

Chart.prototype.autoResizeChanged = require( './watchers/autoResize.js' );

Chart.prototype.isBrushableChanged = require( './watchers/isBrushable.js' );

Chart.prototype.isSortableRowsChanged = require( './watchers/isSortableRows.js' );

Chart.prototype.isSortableColsChanged = require( './watchers/isSortableCols.js' );

// LISTENERS //

Chart.prototype.addListeners = require( './listeners/add.js' );

Chart.prototype.removeListeners = require( './listeners/remove.js' );

Chart.prototype.onRowClick = require( './listeners/rowClick.js' );

Chart.prototype.onColClick = require( './listeners/colClick.js' );

Chart.prototype.onCellClick = require( './listeners/cellClick.js' );

Chart.prototype.onRowHover = require( './listeners/rowHover.js' );

Chart.prototype.onRowHoverEnd = require( './listeners/rowHoverEnd.js' );

Chart.prototype.onColHover = require( './listeners/colHover.js' );

Chart.prototype.onColHoverEnd = require( './listeners/colHoverEnd.js' );

Chart.prototype.onCellHover = require( './listeners/cellHover.js' );

Chart.prototype.onCellHoverEnd = require( './listeners/cellHoverEnd.js' );

Chart.prototype.onRowDragStart = require( './listeners/rowDragStart.js' );

Chart.prototype.onRowDrag = require( './listeners/rowDrag.js' );

Chart.prototype.onRowDragEnd = require( './listeners/rowDragEnd.js' );

Chart.prototype.onColDragStart = require( './listeners/colDragStart.js' );

Chart.prototype.onColDrag = require( './listeners/colDrag.js' );

Chart.prototype.onColDragEnd = require( './listeners/colDragEnd.js' );

Chart.prototype.onTransitionEnd = require( './listeners/transitionEnd.js' );

Chart.prototype.onBrushEnd = require( './listeners/brushEnd.js' );

Chart.prototype.onResize = require( './listeners/resize.js' );

// EXPORTS //

module.exports = Chart;


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('feedjack', '0018_use_django_sites'),
    ]

    operations = [
        migrations.AlterField(
            model_name='postmark',
            name='mark',
            field=models.CharField(choices=[(b'U', b'Unread'), (b'R', b'Read'), (b'T', b'To Read'), (b'I', b'Important'), (b'F', b'Favorite')], db_index=True, max_length=1),
        ),
    ]


text:
var jetfuel = require('../lib/jetfuel'),
    assert = require('assert');

describe('#version()', function() {
    it('should be at 1.x', function() {
        assert.ok(/1.\d/.test(jetfuel.version()));
    })
});


text:
package com.gs.collections.impl.lazy.parallel.bag;

import com.gs.collections.api.annotation.Beta;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.bag.ParallelUnsortedBag;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure;
import com.gs.collections.api.multimap.bag.MutableBagMultimap;
import com.gs.collections.api.multimap.bag.UnsortedBagMultimap;
import com.gs.collections.api.set.ParallelUnsortedSetIterable;
import com.gs.collections.impl.bag.mutable.HashBag;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.block.procedure.BagAddOccurrencesProcedure;
import com.gs.collections.impl.lazy.parallel.AbstractParallelIterable;
import com.gs.collections.impl.multimap.bag.SynchronizedPutHashBagMultimap;

@Beta
public abstract class AbstractParallelUnsortedBag<T, B extends UnsortedBagBatch<T>> extends AbstractParallelIterable<T, B> implements ParallelUnsortedBag<T>
{
    @Override
    protected boolean isOrdered()
    {
        return false;
    }

    public ParallelUnsortedSetIterable<T> asUnique()
    {
        throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".asUnique() not implemented yet");
    }

    public ParallelUnsortedBag<T> select(Predicate<? super T> predicate)
    {
        return new ParallelSelectUnsortedBag<T>(this, predicate);
    }

    public <P> ParallelUnsortedBag<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.select(Predicates.bind(predicate, parameter));
    }

    public <S> ParallelUnsortedBag<S> selectInstancesOf(Class<S> clazz)
    {
        return (ParallelUnsortedBag<S>) this.select(Predicates.instanceOf(clazz));
    }

    public ParallelUnsortedBag<T> reject(Predicate<? super T> predicate)
    {
        return this.select(Predicates.not(predicate));
    }

    public <P> ParallelUnsortedBag<T> rejectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.reject(Predicates.bind(predicate, parameter));
    }

    public <V> ParallelUnsortedBag<V> collect(Function<? super T, ? extends V> function)
    {
        return new ParallelCollectUnsortedBag<T, V>(this, function);
    }

    public <P, V> ParallelUnsortedBag<V> collectWith(Function2<? super T, ? super P, ? extends V> function, P parameter)
    {
        return this.collect(Functions.bind(function, parameter));
    }

    public <V> ParallelUnsortedBag<V> collectIf(Predicate<? super T> predicate, Function<? super T, ? extends V> function)
    {
        return this.select(predicate).collect(function);
    }

    public <V> ParallelUnsortedBag<V> flatCollect(Function<? super T, ? extends Iterable<V>> function)
    {
        throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".flatCollect() not implemented yet");
    }

    @Override
    public MutableBag<T> toBag()
    {
        MutableBag<T> result = HashBag.<T>newBag().asSynchronized();
        this.forEachWithOccurrences(BagAddOccurrencesProcedure.on(result));
        return result;
    }

    public <V> UnsortedBagMultimap<V, T> groupBy(final Function<? super T, ? extends V> function)
    {
        final MutableBagMultimap<V, T> result = SynchronizedPutHashBagMultimap.newMultimap();
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                V key = function.valueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    result.put(key, each);
                }
            }
        });
        return result;
    }

    public <V> UnsortedBagMultimap<V, T> groupByEach(final Function<? super T, ? extends Iterable<V>> function)
    {
        final MutableBagMultimap<V, T> result = SynchronizedPutHashBagMultimap.newMultimap();
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                Iterable<V> keys = function.valueOf(each);
                for (V key : keys)
                {
                    for (int i = 0; i < occurrences; i++)
                    {
                        result.put(key, each);
                    }
                }
            }
        });
        return result;
    }
}


text:
/* globals EventSource: true, console: true */
/* jshint unused: false */
(function(exports, undefined) {

  // Insert CSS.
  var domReady = require('domready');
  var aug = require('aug');
  var humane = require('humane-js');

  var defaults = {
    url: '',
    sseTimeout: 3000,
    timeout: 0,
    clickToClose: true,
    waitForMove: false,
    timeoutAfterMove: 0,
    showAdditional: true
  };
  var config;
  var logger;
  var sseClient = {
    status: false
  };
  require('event-source-polyfill');

  function log(entry) {
    try {
      console.log(entry);
    }
    catch (e) {}
  }

  /**
   * Helper function to return a formatted datetime.
   *
   * @param  {[type]} timestamp A UNIX
   * @return {[type]}           [description]
   */
  function getFormattedDate(timestamp) {
    timestamp = timestamp || false;
    var date = (!timestamp) ? new Date() : new Date(Number(timestamp));

    return date.toLocaleTimeString();
  }

  /**
   * EventSource callback for when the connection is open.
   */
  function onOpen() {
    log('SSE connection opened');
  }

  /**
   * EventSource callback for when the there is a message.
   */
  function onMessage(e) {
    notify(JSON.parse(e.data));
  }

  /**
   * EventSource callback for when there is an error.
   */
  function onError(e) {
    if (e.target.readyState === EventSource.CONNECTING) {
      log('SSE connection refused');
    }
    if (e.target.readyState === EventSource.CLOSED) {
      log('SSE connection closed');
    }
  }

  function notify(content, type) {
    type = type || content.type || 'default';
    content.title = content.title || 'Alert!';
    content.timestamp = content.timestamp || undefined;
    // Create humane-js instance if not created yet.
    logger = logger || humane.create(config);

    // Display the notification.
    logger.log([
      '
' + content.title + '
',
      '
' + getFormattedDate(content.timestamp) + '
',
      '
' + content.msg + '
'
    ], {
      addnCls: 'humane-libnotify-' + type
    });

    return logger;
  }

  sseClient.connect = function(options) {
    if (sseClient.status) {
      throw new Error('Already connected');
    }

    config = aug(defaults, options);

    if (!config.url) {
      throw new Error('Deployment notifications server URL is missing. Please contact dev team to resolve this issue.');
    }

    domReady(function() {
      var source = new EventSource(config.url);
      logger = humane.create(config);

      source.onopen = onOpen;
      source.onmessage = onMessage;
      source.onerror = onError;

      // Built-in timeout to prevent browser from trying forever.
      setTimeout(function() {
        if (source.readyState !== 1) {
          source.close();
          logger = humane.create(defaults);
          notify({
            title: 'Error',
            msg: 'Unable to connect to deployment notification server.'
          }, 'error');
        }
      }, config.sseTimeout);
    });
  };

  function run() {
    // Set context.
    var root = (typeof window !== 'undefined') ? window : this;
    var queue;

    if (typeof root.EventSource !== 'function') {
      throw new Error('Your browser does not support HTML5 properly. You won\'t be receiving deployment notifications. Please contact the dev team on which browser to use.');
    }

    // Set up command queue if not set already.
    root.sseClient = root.sseClient || {};
    root.sseClient.q = root.sseClient.q || [];

    // Set any initial queue items aside.
    queue = root.sseClient.q;

    // Implement our own push.
    root.sseClient.q.push = function(item) {
      if (sseClient.status || !(item instanceof Array) || !item[0] || typeof sseClient[item[0]] !== 'function') {
        return false;
      }
      var args = item[1] || {};
      sseClient[item[0]].apply(this, [args]);
    };

    // Process initial queue items.
    if (queue instanceof Array) {
      queue.forEach(root.sseClient.q.push);
    }
  }

  // Show a friendly error message if EventSource is not supported.
  try {
    run();
  }
  catch(err) {
    domReady(function() {
      logger = humane.create(defaults);
      notify({
        title: 'Error',
        msg: err.message
      }, 'error');
    });
  }

  exports.sseClient = sseClient;

}(typeof exports === 'object' && exports || this));


text:
import * as React from 'react';
import { connect } from 'react-redux';
import { ApplicationState } from '../store';
import * as LayoutStore from '../store/layoutService';

import './Layout.scss'
import './Generator.scss'

type LayoutProps =
    LayoutStore.LayoutState
    & typeof LayoutStore.actionCreators

class FetchData extends React.Component<LayoutProps> {
    public componentDidMount() {
        this.props.requestLastUpdate()
    }

    public render() {
        return (
            <React.Fragment>

                            Thornless

                        {this.props.children}

                            © 2020-2021 Weredev

                            {this.props.lastUpdate?.latestBuildDateString ?? ''}

            </React.Fragment>
        )
    }

}

export default connect(
    (state: ApplicationState) => state.layoutState, // Selects which state properties are merged into the component's props
    LayoutStore.actionCreators // Selects which action creators are merged into the component's props
)(FetchData as any);


text:
class RecipientsController < ApplicationController
	before_action :authenticate_user!

  def index
  end

  def new
  	@recipient = Recipient.new
  	@occasion= @recipient.occasions.new
  end

  def create
  	@recipient = current_user.recipients.new(recipient_params)

  	if @recipient.save
      @occasion = @recipient.occasions.last
      @group = @occasion.groups.create(owner:current_user)
  		redirect_to group_path(@group)
  	else
  		render action: :new
  	end
  end

  private

  def recipient_params
  	params.require(:recipient).permit(:giver_id, :name, :age, :gender, :relationship, occasions_attributes: [:recipient_id, :date, :occasion_type, :reminder, groups_attributes: [:owner_id, :occasion_id, :group_status, :custom_url, :description]])
  end
end