text:
---
title: facil.io - Native Pub/Sub
sidebar: 0.6.x/_sidebar.md
---
# {{{title}}}

The facil.io framework offers a native Pub/Sub implementation which can be found in the "services" folder.

This Pub/Sub implementation covers the whole process cluster and it can be easily scaled by using Redis (which isn't required except for horizontal scaling).

## Connection based vs. non-connection based Pub/Sub

The Websockets extension allows for connection based subscription in adition to the regular Pub/Sub subscriptions.

When using connection based subscription, the connection's `on_close` callback will automatically unsubscribes from any existing subscriptions.

This allows messages to be be either forwarded directly to the client or handled by a server-side callback.

An example for this approach can be seen in the [chatroom example](index.md#an-easy-chatroom-example) using the `websocket_subscribe` function. The same function could have been used with a server-side callback.

A non-connection based Pub/Sub allows a local event to fire whenever a message arrives.

This event allows the server to react to certain channels, allowing remotely published events (by clients or through Redis) to invoke server routines.

This approach uses the `pubsub_subscribe` function directly rather than a connection related function.

## Connecting Redis as a Pub/Sub Service

A built-in Redis engine is bundled with facil.io (it can be removed safely by deleting the folder).

It's simple to add Redis for multi-machine clustering by creating a Redis engine and setting it as the default engine.

i.e.:

```c
int main(void) {
  PUBSUB_DEFAULT_ENGINE =
      redis_engine_create(/** Redis server's address */
                              .address = "localhost", .ping_interval = 2, );
  /* code */
  facil_run(/* settings */);
  redis_engine_destroy(PUBSUB_DEFAULT_ENGINE);
  return 0;
}
```

## Connecting a custom Pub/Sub Service

It's possible. The documentation is available within the header file `pubsub.h` (using `pubsub_engine_s`).

Notice, that the `on_subscribe` will be called for all the channels in the process cluster, so it's possible to connect to the external pub/sub service from a single process (minimizing network traffic) and to publish to the whole cluster.

Also, be aware that messages arrive **at least** once. When using pattern matching, messages might arrive far more than once (i.e., if the service sends two copies, one for the channel and one for the pattern, the cluster might receive four copies, due to internal pattern matching).

Also, see known issues for lost messages when connection is disrupted (this might be pub/sub service specific).

## Details and Limitations:

* facil.io v.0.6.x uses a Hash table for the Pub/Sub channels (replacing the [4 bit trie](https://en.wikipedia.org/wiki/Trie) approach from facil.io v.0.5.x).

    This means that hash collision (using SipHash) might cause excessive `memcmp` calls.

    Pattern publishing (which isn't supported by Redis and shouldn't be confused with pattern subscriptions) was deprecated due to the change in data structure.

* The Redis client engine does *not* support multiple databases. This is both becasue [database scoping is ignored by Redis during pub/sub](https://redis.io/topics/pubsub#database-amp-scoping) and because [Redis Cluster doesn't support multiple databases](https://redis.io/topics/cluster-spec). This indicated that multiple database support just isn't worth the extra effort.

   It's possible to manually send commands to the Redis client and overcome this issue, but disconnections will require resetting the database.

* The Redis client engine will use a single Redis connection **per process** (for publishing) + a single connection **per cluster** (for subscriptions).

    Note that **outgoing** messages are guarantied to be published **at least** once (automatic network error recovery)... however, **incoming** messages might be lost due to network connectivity issues (nothing I can do about this, it's on the Redis server side).


text:
package ccm.libs.org.codehaus.plexus.util;

import java.util.Properties;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;

/**
 * Static methods to create Properties loaded from various sources.
 *
 * @author Jason van Zyl
 * @author Michal Maczka
 *
 * @version $Id$
 */
public class PropertyUtils
{

    public static Properties loadProperties( URL url )
    {
        try
        {
            return loadProperties( url.openStream() );
        }
        catch ( Exception e )
        {
            // ignore
        }

        return null;
    }

    public static Properties loadProperties( File file )
    {
        try
        {
            return loadProperties( new FileInputStream( file ) );
        }
        catch ( Exception e )
        {
            // ignore
        }

        return null;
    }

    public static Properties loadProperties( InputStream is )
    {
        try
        {
            Properties properties = new Properties();

            // Make sure the properties stream is valid
            if ( is != null )
            {
                properties.load( is );
            }

            return properties;
        }
        catch ( IOException e )
        {
            // ignore
        }
        finally
        {
            try
            {
                if ( is != null )
                {
                    is.close();
                }
            }
            catch ( IOException e )
            {
                // ignore
            }
        }

        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
export * from "./base/BaseClassMethodParameterDefinition";
export * from "./base/BaseClassMethodDefinition";
export * from "./base/BaseClassPropertyDefinition";
export * from "./base/ScopedDefinition";


text:
/* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
#include "core/pubnub_version.h"

#include "core/pubnub_version_internal.h"

#define PUBNUB_SDK_NAME "POSIX"

char const *pubnub_sdk_name(void)
{
    return PUBNUB_SDK_NAME;
}

char const *pubnub_version(void)
{
    return PUBNUB_SDK_VERSION;
}

char const *pubnub_uname(void)
{
    return PUBNUB_SDK_NAME "-PubNub-C++-core/" PUBNUB_SDK_VERSION;
}

char const *pubnub_uagent(void)
{
    return PUBNUB_SDK_NAME "-PubNub-C++-core/" PUBNUB_SDK_VERSION;
}


text:
class Post < ApplicationRecord
  belongs_to :user
  has_many :comments
end


text:
/* Set height of the grid so .sidenav can be 100% (adjust if needed) */
.row.content {
  height: calc(100vh - 60px);
}

.row.content > .col-sm-9 {
  margin-left: 25%;
}

/* Set gray background color and 100% height */
.sidenav {
  background-color: #f1f1f1;
  height: 100%;
  position: fixed;
}

/* Set black background color, white text and some padding */
footer {
  background-color: #555;
  color: white;
  padding: 15px;
  width: 100%;
  position: absolute;
}

.file-input {
  display: flex;
}

.file-input input[type="submit"] {
  margin-left: 10px;
}

.machine-cell {
  cursor:pointer;
}

.machine-cell:hover {
  background-color: #efefef;
}

.loading-indicator {
  text-align: center;
  margin: 0 auto;
  font-size: 32px;
}

td, th {
  max-width: 24vw;
  overflow: hidden;
  text-overflow: ellipsis;
}

td * {
  vertical-align: middle;
}

.delete {
  position: absolute;
  right: 5px;
  top: 10%;
  font-size: 18px;
  cursor: pointer;
}

.delete:hover {
  color: black;
}


text:
package edu.gemini.spModel.smartgcal;

import au.com.bytecode.opencsv.CSVReader;
import edu.gemini.spModel.gemini.calunit.smartgcal.Calibration;
import edu.gemini.spModel.gemini.calunit.smartgcal.CalibrationFile;
import edu.gemini.spModel.gemini.calunit.smartgcal.ConfigurationKey;
import edu.gemini.spModel.gemini.calunit.smartgcal.CalibrationMap;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 */
public class CalibrationMapReader {

    private static final Logger LOG = Logger.getLogger(CalibrationMapReader.class.getName());

    private CalibrationMap map;
    private List<String> errors;
    private int line;

    public CalibrationMapReader(CalibrationMap map) {
        this.map = map;
        this.errors = new ArrayList<>();
        this.line = 0;
    }

    public boolean hasErrors() {
        return errors.size() > 0;
    }

    public List<String> getErrors() {
        return errors;
    }

    public CalibrationMap getMap() {
        return map;
    }

    public void read(byte[] data) {
        read(new ByteArrayInputStream(data));
    }

    public CalibrationMap read(InputStream is) {

        try {
            createFromData(is);

        // -- parse exception that was not catched below is supposed to stop parsing e.g. because header is invalid
        } catch (ParseException e) {
            LOG.log(Level.FINE, e.getMessage());
        // -- io exception, not much we can do about...
        }  catch (IOException e) {
            LOG.log(Level.SEVERE, "io exception while reading input", e);
            addError("io exception while reading from input stream " + e.getMessage());
        }

        return map;
    }

    public static List<String> validateData(String instrument, CalibrationFile file) {
         CalibrationMap map = CalibrationMapFactory.createEmpty(instrument, file.getVersion());
         CalibrationMapReader reader = new CalibrationMapReader(map);
         reader.read(file.getData().getBytes());
         return reader.getErrors();
     }

    private void createFromData(InputStream is) throws IOException, ParseException
    {

        CSVReader csvReader = new CSVReader(new InputStreamReader(is));

        List<String> header = null;
        for (String[] values : csvReader.readAll()) {
            line++;

            // skip empty lines and comments
            if (isEmptyLine(values)) {
                continue;
            }

            // first line with data MUST be the header (column names)
            if (header == null) {
                header = parseHeader(values);
                continue;
            }

            try {
                // translate this line
                Properties properties = createProperties(header, values);
                Calibration calibration = map.createCalibration(properties);
                Set<ConfigurationKey> keys = map.createConfig(properties);
                // insert all keys and the calibration
                for (ConfigurationKey key : keys) {
                    map.put(key, properties, calibration);
                }

            } catch (Exception e) {
                addError(e.getMessage());
            }
        }

        csvReader.close();

    }

    private boolean isEmptyLine(String[] values) {
        // skip comments
        if (values[0].trim().startsWith("#")) {
            return true;
        }
        // skip lines with only commas but no values
        for (String value : values) {
            if (!value.trim().isEmpty()) {
                // there is data, this is not an empty line
                return false;
            }
        }
        // no values detected, empty
        return true;
    }

    private List<String> parseHeader(String[] values) throws ParseException {
        List<String> header = new LinkedList<>();
        for (String value : values) {
            String v = value.trim();
            // check for duplicate column names (ignore "empty" columns)
            if (!v.isEmpty() && header.contains(v)) {
                addError("duplicate column name '" + v + "'");
            }
            header.add(v);
        }

        // check that header has all necessary columns for key
        for (ConfigurationKey.Values v : map.getKeyValueNames()) {
            if (!header.contains(v.toString())) {
                addError("missing mandatory key column '" + v.toString() + "'");
            }
        }

        // check that header has all necessary columns for calibration
        for (ConfigurationKey.Values v : map.getCalibrationValueNames()) {
            if (!header.contains(v.toString())) {
                addError("missing mandatory calibration column '" + v.toString() + "'");
            }
        }

        if (hasErrors()) {
            addErrorAndStop("header is invalid, stop parsing");
        }

        // -- ok
        return header;
    }

    private Properties createProperties(List<String> header, String[] values) throws ParseException {
        // check if line is valid
        if (values.length < header.size()) {
            addErrorAndStop("too few values on this line");
        }
        if (values.length > header.size()) {
            addErrorAndStop("too many values on this line");
        }

        // create lookup map
        Properties properties = new Properties();
        int i = 0;
        for (String column : header) {
            properties.setProperty(column, values[i++].trim());
        }
        return properties;
    }

    private void addError(String error) {
        errors.add("line " + line + ": " + error);
    }

    private void addErrorAndStop(String error) throws ParseException {
        addError(error);
        throw new ParseException(error, line);
    }

}


text:
package com.sivalabs.myservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableCircuitBreaker
public class Application
{
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
}


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
---

# pause

Das Ereignis wird ausgelöst, wenn eine Anwendung in den Hintergrund gelegt wird.

    document.addEventListener("pause", yourCallbackFunction, false);

## Details

Das `pause` -Ereignis wird ausgelöst, wenn die einheitlichen Plattform die Anwendung in den Hintergrund, in der Regel, setzt wenn der Benutzer zu einer anderen Anwendung wechselt.

Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst.

## Unterstützte Plattformen

*   Amazon Fire OS
*   Android
*   BlackBerry 10
*   iOS
*   Windows Phone 8
*   Windows 8

## Kurzes Beispiel

    document.addEventListener("pause", onPause, false);

    function onPause() {
        // Handle the pause event
    }

## Vollständiges Beispiel

    <!DOCTYPE html>
    <html>
      <head>
        <title>Pause Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // device APIs are available
        //
        function onDeviceReady() {
            document.addEventListener("pause", onPause, false);
        }

        // Handle the pause event
        //
        function onPause() {
        }

        </script>
      </head>
      <body onload="onLoad()">
      </body>
    </html>

## iOS Macken

In der `pause` Handler, keine Anrufe an die Cordova-API oder native Plugins, die Objective-C durchlaufen funktionieren nicht, zusammen mit interaktiven Aufrufe, z. B. Warnungen oder `console.log()` . Sie werden nur verarbeitet, wenn die app auf der nächsten laufen Schleife fortgesetzt wird.

Die iOS-spezifische `resign` Ereignis ist verfügbar als Alternative zu `pause` , und erkennt, wenn Benutzer die **Lock** -Taste um das Gerät mit der app im Vordergrund ausgeführt zu sperren können. Wenn die app (und Gerät) für Multitasking aktiviert ist, ist dies gepaart mit einer anschließenden `pause` Ereignis, aber nur unter iOS 5. In der Tat werden alle gesperrten apps in iOS 5, die Multitasking aktiviert haben in den Hintergrund gedrängt. Für Anwendungen, die ausgeführt werden, wenn unter iOS 5 gesperrt, deaktivieren die app Multitasking, indem [UIApplicationExitsOnSuspend][1] auf `YES` . Um beim gesperrt auf iOS 4 auszuführen, spielt diese Einstellung keine Rolle.

 [1]: http://developer.apple.com/library/ios/#documentation/general/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html


text:
#include <inviwo/core/datastructures/camerafactory.h>

namespace inviwo {

} // namespace


text:
package net.sf.mmm.data.api.entity;

import net.sf.mmm.data.api.DataObject;
import net.sf.mmm.data.api.reflection.DataClassAnnotation;
import net.sf.mmm.data.api.reflection.DataClassIds;

/**
 * This is the interface for a {@link net.sf.mmm.data.api.DataObject} that is a regular persistent entity.
 * This is the top-most {@link net.sf.mmm.data.api.reflection.DataClass type} that can be
 * {@link net.sf.mmm.data.api.reflection.DataClassModifiers#isExtendable() extended} by end-users.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.0.0
 */
@DataClassAnnotation(id = DataEntity.CLASS_ID, title = DataEntity.CLASS_TITLE)
public interface DataEntity extends DataObject {

  /**
   * The {@link net.sf.mmm.data.api.datatype.DataId#getClassId() class-ID} of the
   * {@link net.sf.mmm.data.api.reflection.DataClass} reflecting this type.
   */
  long CLASS_ID = DataClassIds.ID_ENTITY;

  /**
   * The {@link DataObject#getTitle() title} of the {@link net.sf.mmm.data.api.reflection.DataClass}
   * reflecting this type.
   */
  String CLASS_TITLE = "DataEntity";

  /**
   * This method gets the proxy-source of this object. If the {@link #getProxyTarget() proxy-target} is NOT
   * null, this object is a proxy on another instance of the same
   * {@link net.sf.mmm.data.api.reflection.DataClass type}. This method returns the unwrapped instance where
   * the proxy feature is switched off.

   * This is e.g. useful to implement an editor where the end-user can see which
   * {@link net.sf.mmm.data.api.reflection.DataField fields} are actually set in the proxy object itself.
   *
   * @return the proxy-source of this entity or the instance itself ( this) if this is already
   *         the unwrapped instance.
   */
  DataEntity getProxySource();

  /**
   * This method gets the proxy-target of this object. If the proxy-target is NOT null, this
   * object is a proxy on another instance of the same {@link net.sf.mmm.data.api.reflection.DataClass type}.
   * Then all unset {@link net.sf.mmm.data.api.reflection.DataField fields} are "inherited" from the
   * {@link #getProxyTarget() proxy-target}. This rule does NOT apply for {@link #getId() ID},
   * {@link #getModificationCounter() modification counter}, {@link #getRevision() revision},
   * {@link #getProxySource() proxy source}, and {@link #getProxyTarget() proxy target}. Further, only getters
   * are delegated to the {@link #getProxyTarget() proxy target}, whereas setters act on the
   * {@link #getProxySource() proxy source} . A proxy that has no field set acts like a link in a Unix
   * filesystem.

   * INFORMATION:

   * The returned object needs to have the same {@link net.sf.mmm.data.api.reflection.DataClass type} as this
   * instance.
   *
   * @return the proxy-target or null if this is a regular content-object.
   */
  DataEntity getProxyTarget();

  /**
   * This method sets the {@link #getProxyTarget() proxy target}.
   *
   * @param proxyTarget is the {@link DataEntity} this entity will delegate to.
   */
  void setProxyTarget(DataEntity proxyTarget);

}


text:
require 'rubygems'
lib_root = '../lib'
require File.expand_path("#{lib_root}/dsl",File.dirname(__FILE__))
require 'pp'

service_repo_loc = '/home/git/repositories'

if Dir[service_repo_loc]
  service_directories = Dir.entries(service_repo_loc).select {|entry| entry.to_s.include?('--sm--') }
  service_directories.each do |service_repo|
    dir_parser = DtkCommon::DSL::DirectoryParser::Git.new(:service_module, "#{service_repo_loc}/#{service_repo}")
    pp dir_parser.parse_directory(:component_module_refs)
  end
else
  puts "Not able to find '#{service_repo_loc}' ment to be run on repo-manager"
end


text:
package com.squareup.otto;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Wraps a 'producer' method on a specific object.
 *
 * <p> This class only verifies the suitability of the method and event type if something fails.  Callers are expected
 * to verify their uses of this class.
 *
 * @author Jake Wharton
 */
class EventProducer {

  /** Object sporting the producer method. */
  final Object target;
  /** Producer method. */
  private final Method method;
  /** Object hash code. */
  private final int hashCode;
  /** Should this producer produce events? */
  private boolean valid = true;

  EventProducer(Object target, Method method) {
    if (target == null) {
      throw new NullPointerException("EventProducer target cannot be null.");
    }
    if (method == null) {
      throw new NullPointerException("EventProducer method cannot be null.");
    }

    this.target = target;
    this.method = method;
    method.setAccessible(true);

    // Compute hash code eagerly since we know it will be used frequently and we cannot estimate the runtime of the
    // target's hashCode call.
    final int prime = 31;
    hashCode = (prime + method.hashCode()) * prime + target.hashCode();
  }

  public boolean isValid() {
    return valid;
  }

  /**
   * If invalidated, will subsequently refuse to produce events.
   *
   * Should be called when the wrapped object is unregistered from the Bus.
   */
  public void invalidate() {
    valid = false;
  }

  /**
   * Invokes the wrapped producer method.
   *
   * @throws java.lang.IllegalStateException  if previously invalidated.
   * @throws java.lang.reflect.InvocationTargetException  if the wrapped method throws any {@link Throwable} that is not
   *     an {@link Error} ({@code Error}s are propagated as-is).
   */
  public Object produceEvent() throws InvocationTargetException {
    if (!valid) {
      throw new IllegalStateException(toString() + " has been invalidated and can no longer produce events.");
    }
    try {
      return method.invoke(target);
    } catch (IllegalAccessException e) {
      throw new AssertionError(e);
    } catch (InvocationTargetException e) {
      if (e.getCause() instanceof Error) {
        throw (Error) e.getCause();
      }
      throw e;
    }
  }

  @Override public String toString() {
    return "[EventProducer " + method + "]";
  }

  @Override public int hashCode() {
    return hashCode;
  }

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

    if (obj == null) {
      return false;
    }

    if (getClass() != obj.getClass()) {
      return false;
    }

    final EventProducer other = (EventProducer) obj;

    return method.equals(other.method) && target == other.target;
  }
}


text:
def _render(code):
    return compile(code, '<string>', 'eval')

def rowcol_to_cell(row, col, row_abs=False, col_abs=False):
    # Code based upon utils from xlwt distribution
    """
    Convert numeric row/col notation to an Excel cell
    reference string in A1 notation.
    """
    d = col // 26
    m = col % 26
    chr1 = ""    # Most significant character in AA1
    if row_abs:
        row_abs = '$'
    else:
        row_abs = ''
    if col_abs:
        col_abs = '$'
    else:
        col_abs = ''
    if d > 0:
        chr1 = chr(ord('A') + d - 1)
    chr2 = chr(ord('A') + m)
    # Zero index to 1-index
    return col_abs + chr1 + chr2 + row_abs + str(row + 1)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
FROM debian:jessie
MAINTAINER Mark Santa Ana <booyaa@booyaa.org>
WORKDIR /usr/src
ADD tester.sh /usr/src/
ENV PATH=$PATH:/usr/src
CMD tester.sh


text:
"""
fuzza.transformer._hex
----------------------

The hex encoding transformer module.
"""
import binascii

def transform(data):
    """
    Transform data using hex encoding.

    Args:
        data (list): A list of data in bytes literals.

    Returns:
        list: A list of hex-encoded data in bytes literals.
    """
    return [binascii.hexlify(d) for d in data]


text:
package com.opengamma.strata.calc;

import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.ImmutableConstructor;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import org.joda.beans.impl.direct.DirectPrivateBeanBuilder;

import com.google.common.collect.ImmutableList;
import com.opengamma.strata.collect.Guavate;
import com.opengamma.strata.collect.Messages;
import com.opengamma.strata.collect.result.Result;
import com.opengamma.strata.data.scenario.ScenarioArray;

/**
 * Calculation results of performing calculations for a set of targets and columns.
 *

 * This defines a grid of results where the grid contains a row for each target and a column for each measure.
 * Each result may be a single value or a multi-scenario value.
 * A multi-scenario value will implement {@link ScenarioArray} unless it has been aggregated.
 */
@BeanDefinition(builderScope = "private")
public final class Results implements ImmutableBean {

  /**
   * The column headers.
   *

   * Each column in the results is defined by a header consisting of the name and measure.
   * The size of this list defines the number of columns, which is needed to interpret the list of cells.
   */
  @PropertyDefinition(validate = "notNull")
  private final ImmutableList<ColumnHeader> columns;
  /**
   * The grid of results, stored as a flat list.
   *

   * This list contains the calculated result for each cell in the grid.
   * The cells are grouped by target, then column.
   * Thus, the index of a given cell is {@code (targetRowIndex * columnCount) + columnIndex}.
   *

   * For example, given a set of results with two targets, t1 and t2,
   * and three columns c1, c2, and c3, the results will be:
   *

   *   [t1c1, t1c2, t1c3, t2c1, t2c2, t2c3]
   *

   */
  @PropertyDefinition(validate = "notNull", builderType = "List<? extends Result<?>>")
  private final ImmutableList<Result<?>> cells;
  /**
   * The number of rows.
   */
  private final transient int rowCount;  // derived, not a property
  /**
   * The number of columns.
   */
  private final transient int columnCount;  // derived, not a property

  //-------------------------------------------------------------------------
  /**
   * Obtains an instance containing the results of the calculation for each cell.
   *

   * The number of cells must be exactly divisible by the number of columns.
   *
   * @param columns  the names of each column
   * @param cells  the calculated results, one for each cell
   * @return a set of results for the calculations
   */
  public static Results of(List<ColumnHeader> columns, List<? extends Result<?>> cells) {
    return new Results(columns, cells);
  }

  @ImmutableConstructor
  private Results(List<ColumnHeader> columns, List<? extends Result<?>> cells) {
    JodaBeanUtils.notNull(columns, "columns");
    JodaBeanUtils.notNull(cells, "cells");
    this.columns = ImmutableList.copyOf(columns);
    this.cells = ImmutableList.copyOf(cells);
    this.columnCount = columns.size();
    this.rowCount = (columnCount == 0 ? 0 : cells.size() / columnCount);

    if (rowCount * columnCount != cells.size()) {
      throw new IllegalArgumentException(
          Messages.format(
              "The number of cells ({}) must equal the number of rows ({}) multiplied by the number of columns ({})",
              this.cells.size(),
              this.rowCount,
              this.columnCount));
    }
  }

  // ensure standard constructor is invoked
  private Object readResolve() {
    return new Results(columns, cells);
  }

  //-------------------------------------------------------------------------
  /**
   * Gets the number of rows in the results.
   *

   * The number of rows equals the number of targets input to the calculation.
   *
   * @return the number of rows
   */
  public int getRowCount() {
    return rowCount;
  }

  /**
   * Gets the number of columns in the results.
   *
   * @return the number of columns
   */
  public int getColumnCount() {
    return columnCount;
  }

  //-------------------------------------------------------------------------
  /**
   * Returns the results for a target and column index.
   *

   * The result may be a single value or a multi-scenario value.
   * A multi-scenario value will implement {@link ScenarioArray} unless it has been aggregated.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *
   * @param rowIndex   the index of the row containing the results for a target
   * @param columnIndex  the index of the column
   * @return the result for the specified row and column for a set of scenarios
   * @throws IllegalArgumentException if the row or column index is invalid
   */
  public Result<?> get(int rowIndex, int columnIndex) {
    if (rowIndex < 0 || rowIndex >= rowCount) {
      throw new IllegalArgumentException(invalidRowIndexMessage(rowIndex));
    }
    if (columnIndex < 0 || columnIndex >= columnCount) {
      throw new IllegalArgumentException(invalidColumnIndexMessage(columnIndex));
    }
    return get0(rowIndex, columnIndex);
  }

  // trusted low level method to get the cell
  private Result<?> get0(int rowIndex, int columnIndex) {
    int index = (rowIndex * columnCount) + columnIndex;
    return cells.get(index);
  }

  private String invalidRowIndexMessage(int rowIndex) {
    return Messages.format(
        "Row index must be greater than or equal to zero and less than the row count ({}), but it was {}",
        rowCount,
        rowIndex);
  }

  private String invalidColumnIndexMessage(int columnIndex) {
    return Messages.format(
        "Column index must be greater than or equal to zero and less than the column count ({}), but it was {}",
        columnCount,
        columnIndex);
  }

  /**
   * Returns the results for a target and column index, casting the result to a known type.
   *

   * The result may be a single value or a multi-scenario value.
   * A multi-scenario value will implement {@link ScenarioArray} unless it has been aggregated.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *
   * @param <T>  the result type
   * @param rowIndex   the index of the row containing the results for a target
   * @param columnIndex  the index of the column
   * @param type  the result type
   * @return the result for the specified row and column for a set of scenarios, cast to the specified type
   * @throws IllegalArgumentException if the row or column index is invalid
   * @throws ClassCastException if the result is not of the specified type
   */
  public <T> Result<T> get(int rowIndex, int columnIndex, Class<T> type) {
    return cast(get(rowIndex, columnIndex), type);
  }

  /**
   * Returns the results for a target and column name.
   *

   * The result may be a single value or a multi-scenario value.
   * A multi-scenario value will implement {@link ScenarioArray} unless it has been aggregated.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *
   * @param rowIndex   the index of the row containing the results for a target
   * @param columnName  the name of the column
   * @return the result for the specified row and column for a set of scenarios
   * @throws IllegalArgumentException if the row index or column name is invalid
   */
  public Result<?> get(int rowIndex, ColumnName columnName) {
    return get(rowIndex, columnIndexByName(columnName));
  }

  /**
   * Gets the column index by name.
   *
   * @param columnName  the column name
   * @return the column index
   * @throws IllegalArgumentException if the column name is invalid
   */
  public int columnIndexByName(ColumnName columnName) {
    for (int i = 0; i < columns.size(); i++) {
      if (columns.get(i).getName().equals(columnName)) {
        return i;
      }
    }
    throw new IllegalArgumentException(invalidColumnNameMessage(columnName));
  }

  private String invalidColumnNameMessage(ColumnName columnName) {
    return Messages.format("Column name not found: {}", columnName);
  }

  /**
   * Returns the results for a target and column name, casting the result to a known type.
   *

   * The result may be a single value or a multi-scenario value.
   * A multi-scenario value will implement {@link ScenarioArray} unless it has been aggregated.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *
   * @param <T>  the result type
   * @param rowIndex   the index of the row containing the results for a target
   * @param columnName  the name of the column
   * @param type  the result type
   * @return the result for the specified row and column for a set of scenarios, cast to the specified type
   * @throws IllegalArgumentException if the row index or column name is invalid
   * @throws ClassCastException if the result is not of the specified type
   */
  public <T> Result<T> get(int rowIndex, ColumnName columnName, Class<T> type) {
    return cast(get(rowIndex, columnName), type);
  }

  //-------------------------------------------------------------------------
  /**
   * Returns multi-scenario results for a target and column index, casting the result to a known type.
   *

   * The result is a multi-scenario {@link ScenarioArray}.
   * Typed subclasses of {@code ScenarioArray} can also be obtained using {@link #get(int, int, Class)}.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *
   * @param <C>  the type parameter of {@code ScenarioArray}
   * @param rowIndex   the index of the row containing the results for a target
   * @param columnIndex  the index of the column
   * @param componentType  the type parameter of {@code ScenarioArray}
   * @return the result for the specified row and column for a set of scenarios, cast to the specified type
   * @throws IllegalArgumentException if the row or column index is invalid
   * @throws ClassCastException if the result is not of the specified type
   */
  public <C> Result<ScenarioArray<C>> getScenarios(int rowIndex, int columnIndex, Class<C> componentType) {
    return castScenario(get(rowIndex, columnIndex), componentType);
  }

  /**
   * Returns multi-scenario results for a target and column name, casting the result to a known type.
   *

   * The result is a multi-scenario {@link ScenarioArray}.
   * Typed subclasses of {@code ScenarioArray} can also be obtained using {@link #get(int, ColumnName, Class)}.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *
   * @param <C>  the type parameter of {@code ScenarioArray}
   * @param rowIndex   the index of the row containing the results for a target
   * @param columnName  the name of the column
   * @param componentType  the type parameter of {@code ScenarioArray}
   * @return the result for the specified row and column for a set of scenarios, cast to the specified type
   * @throws IllegalArgumentException if the row or column index is invalid
   * @throws ClassCastException if the result is not of the specified type
   */
  public <C> Result<ScenarioArray<C>> getScenarios(int rowIndex, ColumnName columnName, Class<C> componentType) {
    return castScenario(get(rowIndex, columnName), componentType);
  }

  //-------------------------------------------------------------------------
  /**
   * Returns a stream of results for a single column by column index.
   *

   * The result may be a single value or a multi-scenario value.
   * A multi-scenario value will implement {@link ScenarioArray} unless it has been aggregated.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *

   * Large streams can be processed in parallel via {@link Stream#parallel()}.
   * See {@link Guavate#zipWithIndex(Stream)} if the row index is required.
   *
   * @param <T>  the result type
   * @param columnIndex  the index of the column
   * @return the stream of results for the specified column
   * @throws IllegalArgumentException if the column index is invalid
   */
  public <T> Stream<Result<?>> columnResults(int columnIndex) {
    if (columnIndex < 0 || columnIndex >= columnCount) {
      throw new IllegalArgumentException(invalidColumnIndexMessage(columnIndex));
    }
    Spliterator<Result<?>> spliterator = new ResultSpliterator(this, columnIndex, 0, rowCount);
    return StreamSupport.stream(spliterator, false);
  }

  /**
   * Returns a stream of results for a single column by column index.
   *

   * The result may be a single value or a multi-scenario value.
   * A multi-scenario value will implement {@link ScenarioArray} unless it has been aggregated.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *

   * Large streams can be processed in parallel via {@link Stream#parallel()}.
   * See {@link Guavate#zipWithIndex(Stream)} if the row index is required.
   * The stream will throw {@code ClassCastException} if the result is not of the specified type.
   *
   * @param <T>  the result type
   * @param columnIndex  the index of the column
   * @param type  the result type
   * @return the stream of results for the specified column, cast to the specified type
   * @throws IllegalArgumentException if the column index is invalid
   */
  public <T> Stream<Result<T>> columnResults(int columnIndex, Class<T> type) {
    return columnResults(columnIndex).map(result -> cast(result, type));
  }

  /**
   * Returns a stream of multi-scenario results for a single column by column index.
   *

   * The result is a multi-scenario {@link ScenarioArray}.
   * Typed subclasses of {@code ScenarioArray} can also be obtained using {@link #columnResults}.
   *

   * If the calculation did not complete successfully, a failure result will be returned
   * explaining the problem. Callers must check whether the result is a success or failure
   * before examining the result value.
   *

   * Large streams can be processed in parallel via {@link Stream#parallel()}.
   * See {@link Guavate#zipWithIndex(Stream)} if the row index is required.
   * The stream will throw {@code ClassCastException} if the result is not of the specified type.
   *
   * @param <C>  the type parameter of {@code ScenarioArray}
   * @param columnIndex  the index of the column
   * @param componentType  the type parameter of {@code ScenarioArray}
   * @return the stream of results for the specified column, cast to the specified type
   * @throws IllegalArgumentException if the column index is invalid
   */
  public <C> Stream<Result<ScenarioArray<C>>> columnResultsScenarios(int columnIndex, Class<C> componentType) {
    return columnResults(columnIndex).map(result -> castScenario(result, componentType));
  }

  // efficient spliterator for larger result sets
  private static class ResultSpliterator implements Spliterator<Result<?>> {
    private final Results results;
    private final int columnIndex;
    private final int endRowExclusive;
    private int currentRow;

    private ResultSpliterator(Results results, int columnIndex, int startRow, int endRowExclusive) {
      this.results = results;
      this.columnIndex = columnIndex;
      this.endRowExclusive = endRowExclusive;
      this.currentRow = startRow;
    }

    @Override
    public void forEachRemaining(Consumer<? super Result<?>> action) {
      while (currentRow < endRowExclusive) {
        action.accept(results.get0(currentRow, columnIndex));
        currentRow++;
      }
    }

    @Override
    public boolean tryAdvance(Consumer<? super Result<?>> action) {
      if (currentRow < endRowExclusive) {
        action.accept(results.get0(currentRow, columnIndex));
        currentRow++;
        return true;
      } else {
        return false;
      }
    }

    @Override
    public Spliterator<Result<?>> trySplit() {
      // split in two
      int lo = currentRow;
      int mid = (lo + endRowExclusive) / 2;
      if (lo >= mid) {
        // no split possible
        return null;
      }
      // this spliterator now represents the second half
      currentRow = mid;
      // the returned spliterator represents the first half
      return new ResultSpliterator(results, columnIndex, lo, mid);
    }

    @Override
    public long estimateSize() {
      return endRowExclusive - currentRow;
    }

    @Override
    public long getExactSizeIfKnown() {
      return estimateSize();
    }

    @Override
    public int characteristics() {
      return IMMUTABLE | NONNULL | ORDERED | SIZED | SUBSIZED;
    }
  }

  //-------------------------------------------------------------------------
  // casts the result, ensuring the type is the expected one
  @SuppressWarnings("unchecked")
  private static <T> Result<T> cast(Result<?> result, Class<T> type) {
    // cannot use result.map() as we want the exception to be thrown
    if (result.isFailure() || type.isInstance(result.getValue())) {
      return (Result<T>) result;
    }
    throw new ClassCastException(Messages.format(
        "Result queried with type '{}' but was '{}'", type.getName(), result.getValue().getClass().getName()));
  }

  // casts the result, ensuring the type is a ScenarioArray and the first element is of the expected type
  // choosing to do only the first element is done to avoid the performance hit from checking large scenarios
  @SuppressWarnings("unchecked")
  private static <C> Result<ScenarioArray<C>> castScenario(Result<?> result, Class<C> componentType) {
    if (result.isFailure()) {
      return (Result<ScenarioArray<C>>) result;
    }
    if (ScenarioArray.class.isInstance(result.getValue())) {
      ScenarioArray<?> array = (ScenarioArray<?>) result.getValue();
      if (array.getScenarioCount() > 0 && !componentType.isInstance(array.get(0))) {
        throw new ClassCastException(Messages.format(
            "Result queried with component type '{}' but was '{}'",
            componentType.getName(),
            array.get(0).getClass().getName()));
      }
      return (Result<ScenarioArray<C>>) result;
    }
    throw new ClassCastException(Messages.format(
        "Result queried with type 'ScenarioArray' but was '{}'", result.getValue().getClass().getName()));
  }

  //------------------------- AUTOGENERATED START -------------------------
  /**
   * The meta-bean for {@code Results}.
   * @return the meta-bean, not null
   */
  public static Results.Meta meta() {
    return Results.Meta.INSTANCE;
  }

  static {
    MetaBean.register(Results.Meta.INSTANCE);
  }

  @Override
  public Results.Meta metaBean() {
    return Results.Meta.INSTANCE;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the column headers.
   *

   * Each column in the results is defined by a header consisting of the name and measure.
   * The size of this list defines the number of columns, which is needed to interpret the list of cells.
   * @return the value of the property, not null
   */
  public ImmutableList<ColumnHeader> getColumns() {
    return columns;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the grid of results, stored as a flat list.
   *

   * This list contains the calculated result for each cell in the grid.
   * The cells are grouped by target, then column.
   * Thus, the index of a given cell is {@code (targetRowIndex * columnCount) + columnIndex}.
   *

   * For example, given a set of results with two targets, t1 and t2,
   * and three columns c1, c2, and c3, the results will be:
   *

   * [t1c1, t1c2, t1c3, t2c1, t2c2, t2c3]
   *

   * @return the value of the property, not null
   */
  public ImmutableList<Result<?>> getCells() {
    return cells;
  }

  //-----------------------------------------------------------------------
  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      Results other = (Results) obj;
      return JodaBeanUtils.equal(columns, other.columns) &&
          JodaBeanUtils.equal(cells, other.cells);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(columns);
    hash = hash * 31 + JodaBeanUtils.hashCode(cells);
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(96);
    buf.append("Results{");
    buf.append("columns").append('=').append(JodaBeanUtils.toString(columns)).append(',').append(' ');
    buf.append("cells").append('=').append(JodaBeanUtils.toString(cells));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code Results}.
   */
  public static final class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code columns} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<ImmutableList<ColumnHeader>> columns = DirectMetaProperty.ofImmutable(
        this, "columns", Results.class, (Class) ImmutableList.class);
    /**
     * The meta-property for the {@code cells} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<ImmutableList<Result<?>>> cells = DirectMetaProperty.ofImmutable(
        this, "cells", Results.class, (Class) ImmutableList.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "columns",
        "cells");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 949721053:  // columns
          return columns;
        case 94544721:  // cells
          return cells;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends Results> builder() {
      return new Results.Builder();
    }

    @Override
    public Class<? extends Results> beanType() {
      return Results.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code columns} property.
     * @return the meta-property, not null
     */
    public MetaProperty<ImmutableList<ColumnHeader>> columns() {
      return columns;
    }

    /**
     * The meta-property for the {@code cells} property.
     * @return the meta-property, not null
     */
    public MetaProperty<ImmutableList<Result<?>>> cells() {
      return cells;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 949721053:  // columns
          return ((Results) bean).getColumns();
        case 94544721:  // cells
          return ((Results) bean).getCells();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code Results}.
   */
  private static final class Builder extends DirectPrivateBeanBuilder<Results> {

    private List<ColumnHeader> columns = ImmutableList.of();
    private List<? extends Result<?>> cells = ImmutableList.of();

    /**
     * Restricted constructor.
     */
    private Builder() {
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case 949721053:  // columns
          return columns;
        case 94544721:  // cells
          return cells;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @SuppressWarnings("unchecked")
    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case 949721053:  // columns
          this.columns = (List<ColumnHeader>) newValue;
          break;
        case 94544721:  // cells
          this.cells = (List<? extends Result<?>>) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Results build() {
      return new Results(
          columns,
          cells);
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(96);
      buf.append("Results.Builder{");
      buf.append("columns").append('=').append(JodaBeanUtils.toString(columns)).append(',').append(' ');
      buf.append("cells").append('=').append(JodaBeanUtils.toString(cells));
      buf.append('}');
      return buf.toString();
    }

  }

  //-------------------------- AUTOGENERATED END --------------------------
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\bootstrap\Modal;
use yii\helpers\Url;

/* @var $this yii\web\View */
/* @var $searchModel app\models\ContratacaoJustificativasSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$session = Yii::$app->session;
$id_contratacao = $session['sess_contratacao'];

$this->title = 'Justificativas para Correção  ';
$this->params['breadcrumbs'][] = ['label' => 'Contratações Pendentes', 'url' => ['contratacao-pendente/index']];
$this->params['breadcrumbs'][] = ['label' => $id_contratacao, 'url' => ['contratacao-pendente/view', 'id' => $id_contratacao]];
$this->params['breadcrumbs'][] = $this->title;

?>

<?= Html::encode($this->title) ."Solicitação de Contratação: ".$id_contratacao. "" ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::button('Inserir Justificativa', ['value'=> Url::to('index.php?r=contratacao-justificativas-pendentes/create'), 'class' => 'btn btn-success', 'id'=>'modalButton']) ?>

    <?php
        Modal::begin([
            'header' => '
Justificativa
',
            'id' => 'modal',
            'size' => 'modal-lg',
            ]);

        echo "

";

        Modal::end();

   ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'descricao',
            'usuario',
        ],
    ]); ?>


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import {
  ViroSceneNavigator,
  ViroScene,
  ViroBox,
  ViroMaterials,
  ViroNode,
  ViroOrbitCamera,
  ViroCamera,
  ViroAmbientLight,
  ViroOmniLight,
  ViroSpotLight,
  ViroDirectionalLight,
  ViroImage,
  ViroVideo,
  Viro360Image,
  Viro360Video,
  ViroFlexView,
  ViroUtils,
  ViroText,
  ViroAnimations,
  ViroQuad,
  ViroSkyBox,
  ViroSphere,
  Viro3DObject,
  ViroPolyline
} from 'react-viro';

var createReactClass = require('create-react-class');

let polarToCartesian = ViroUtils.polarToCartesian;

var ReleaseMenu = require("./ReleaseMenu.js");

var Uri360Image = {uri:"https://lh3.googleusercontent.com/dB3Dvgf3VIglusoGJAfpNUAANhTXW8K9mvIsiIPkhJUAbAKGKJcEMPTf0mkSexzLM5o=w300"};
var Local360Image = require("../res/sun_2302.jpg");

var points = [[[0,0,0]],
              [[0,0,0], [.5,.5,-.5]],
              [[0,0,0], [.5,.5,-.5], [1,0,0]],
              [[0,0,0], [.5,.5,-.5], [1,0,0], [1.5,1,.5]],
              [[0,0,0], [.5,.5,-.5], [1,0,0], [1.5,1,.5], [5,5,0]]];

var ViroPolylineTest = createReactClass({
  getInitialState() {
    return {
      materials:false,
      closed: false,
      pointSet:0,
      thickness: .05,
      orbit : false,
    };
  },
  render: function() {
    var image = this.state.showUrlImage ? Uri360Image : Local360Image;
    return (
      <ViroScene>
        <ViroCamera position={[0, 0, 0]} active={!this.state.orbit}/>
        <ViroOrbitCamera focalPoint={[0, -.25, -2]} active={this.state.orbit}/>
        <ReleaseMenu sceneNavigator={this.props.sceneNavigator}/>
        <ViroPolyline position={[0,0,-2]} points={this._getPoints()} closed={this.state.closed} thickness={this.state.thickness}
          materials={this.state.materials ? "whitePolyline" : "redPolyline"} onClick={()=>{this.setState({orbit : !this.state.orbit})}}/>
        {this._getTestControls()}
      </ViroScene>
    );
  },

  _getTestControls(){
    return(
      <ViroNode position={[0,-0.5,-3]}>
        <ViroText style={styles.baseTextTwo}  position={[0, 0, 0]} width={2} height ={2}
                  text={"Toggle Points: " + (this.state.pointSet + 1)}
                  onClick={this._nextPoints}/>

        <ViroText style={styles.baseTextTwo}  position={[0, -.5, 0]} width={2} height ={2}
                  text={"Toggle Material : " + (this.state.materials ? " whitePolyline" : "redPolyline")} textLineBreakMode='Justify'
                  onClick={this._toggleMaterial}/>

        <ViroText style={styles.baseTextTwo}  position={[0, -1, 0]} width={2} height ={2}
                  text={"Toggle Thickness: " + this.state.thickness}
                  onClick={this._toggleThickness}/>

        <ViroText style={styles.baseTextTwo}  position={[2.1, -1, 0]} width={2} height ={2}
                  text={"Toggle Closed: " + this.state.closed}
                  onClick={this._toggleClosed}/>
      </ViroNode>
    );
  },

  _nextPoints() {
    this.setState({
      pointSet : this.state.pointSet == 4 ? 0 : ++this.state.pointSet
    })
  },

  _getPoints() {
    return points[this.state.pointSet];
  },

  _showNext() {
    this.props.sceneNavigator.replace({scene:require('./Viro360ImageTest')});
  },

  _toggleMaterial() {
    this.setState({
      materials : !this.state.materials
    })
  },

  _toggleThickness() {
    this.setState({
      thickness : this.state.thickness >= .5 ? .05 : this.state.thickness + .05
    })
  },

  _toggleClosed() {
    this.setState({
      closed: !this.state.closed,
    });
  },
  _onLoadStart() {
    console.log("ViroSkyBoxtest: _onLoadStart");
  },

  _onLoadEnd() {
    console.log("ViroSkyBoxtest: _onLoadEnd");
  },
});

var styles = StyleSheet.create({
  baseTextTwo: {
      fontFamily: 'Arial',
      fontSize: 15,
      color: '#ffffff',
      flex: 1,
      textAlignVertical: 'center',
      textAlign: 'center',
  },
});

ViroMaterials.createMaterials({
  whitePolyline: {
    diffuseColor: "#ffffff",
  },
  redPolyline: {
    diffuseColor: "#ff0000",
  },
});

module.exports = ViroPolylineTest;


text:
local lib = {}

-- Return true if the file exists, else false
function lib.exists(name)
  local f = io.open(name,'r')
  if f ~= nil then
    io.close(f)
    return true
  else
    return false
  end
end

-- Takes a list of path parts, returns a string with the parts delimited by '/'
function lib.toPath(...) return table.concat({...}, '/') end

-- Splits a string by '/', returning the parent dir, filename (with extension),
-- and the extension alone.
function lib.splitPath(file)
  local parent = file:match('(.+)/[^/]+$')
  if parent == nil then parent = '.' end
  local filename = file:match('/([^/]+)$')
  if filename == nil then filename = file end
  local ext = filename:match('%.([^.]+)$')
  return parent, filename, ext
end

-- Make a parent dir for a file. Does not error if it exists already.
function lib.makeParentDir(path)
  local parent, _, _ = lib.splitPath(path)
  local ok, err = hs.fs.mkdir(parent)
  if ok == nil then
    if err == 'File exists' then
      ok = true
    end
  end
  return ok, err
end

-- Create a file (making parent directories if necessary).
function lib.create(path)
  if lib.makeParentDir(path) then
    io.open(path, 'w'):close()
  end
end

-- Append a line of text to a file.
function lib.append(file, text)
  if text == '' then return end

  local f = io.open(file, 'a')
  f:write(tostring(text) .. '\n')
  f:close()
end

-- Move a file. This calls task (so runs asynchronously), so calls onSuccess
-- and onFailure callback functions depending on the result. Set force to true
-- to overwrite.
function lib.move(from, to, force, onSuccess, onFailure)
  force = force and '-f' or '-n'

  local function callback(exitCode, stdOut, stdErr)
    if exitCode == 0 then
      onSuccess(stdOut)
    else
      onFailure(stdErr)
    end
  end

  if lib.exists(from) then
    hs.task.new('/bin/mv', callback, {force, from, to}):start()
  end
end

-- If the given file is older than the given time (in epoch seconds), return
-- true. This checks the inode change time, not the original file creation
-- time.
function lib.isOlderThan(file, seconds)
  local age = os.time() - hs.fs.attributes(file, 'change')
  if age > seconds then return true end
  return false
end

-- Return the last modified time of a file in epoch seconds.
function lib.lastModified(file)
  local when = os.time()
  if lib.exists(file) then when = hs.fs.attributes(file, 'modification') end
  return when
end

-- If any files are found in the given path, make a list of them and call the
-- given callback function with that list.
function lib.runOnFiles(path, callback)
  local iter, data = hs.fs.dir(path)
  local files = {}
  repeat
    local item = iter(data)
    if item ~= nil then table.insert(files, lib.toPath(path, item)) end
  until item == nil
  if #files > 0 then callback(files) end
end

-- Unhide the extension on the given file, if it matches the extension given,
-- and that extension does not exist in the given hiddenExtensions table.
function lib.unhideExtension(file, ext, hiddenExtensions)
  if ext == nil or hiddenExtensions == nil or hiddenExtensions[ext] == nil then
    local function unhide(exitCode, stdOut, stdErr)
      if exitCode == 0 and tonumber(stdOut) == 1 then
        hs.task.new('/usr/bin/SetFile', nil, {'-a', 'e', file}):start()
      end
    end
    hs.task.new('/usr/bin/GetFileInfo', unhide, {'-aE', file}):start()
  end
end

-- Returns true if the file has any default OS X color tag enabled.
function lib.isColorTagged(file)
  local colors = {
    Red = true,
    Orange = true,
    Yellow = true,
    Green = true,
    Blue = true,
    Purple = true,
    Gray = true,
  }
  local tags = hs.fs.tagsGet(file)

  if tags ~= nil then
    for _,tag in ipairs(tags) do
      if colors[tag] then return true end
    end
  end
  return false
end

-- Simply set a single tag on a file
function lib.setTag(file, tag) hs.fs.tagsAdd(file, {tag}) end

-- Return a string that ensures the given file ends with the given extension.
function lib.withExtension(filePath, ext)
  local path = filePath
  local extMatch = '%.'..ext..'$'
  if not string.find(path, extMatch) then path = path..'.'..ext end
  return path
end

-- load a json file into a lua table and return it
function lib.loadJSON(file)
  local data = nil
  local f = io.open(file, 'r')
  if f then
    local content = f:read('*all')
    f:close()
    if content then
      ok, data = pcall(function() return hs.json.decode(content) end)
      if not ok then
        hsm.log.e('loadJSON:', data)
        data = nil
      end
    end
  end
  return data
end

-- Find the most recent path in a directory
-- attr should be one of: access, change, modification, creation
function lib.mostRecent(parent, attr)
  if not lib.exists(parent) then return nil end

  -- make sure attr is valid and default to modification
  local attrs = {access=true, change=true, modification=true, creation=true}
  if not attrs[attr] then attr = 'modification' end

  local max = 0
  local mostRecent = nil
  local iterFn, dirObj = hs.fs.dir(parent)
  local child = iterFn(dirObj)
  while child do
    -- ignore dotfiles
    if string.find(child, '^[^%.]') then
      local path = lib.toPath(parent, child)
      local last = hs.fs.attributes(path, attr)
      if last > max then
        mostRecent = path
        max = last
      end
    end
    child = iterFn(dirObj)
  end

  return mostRecent
end

return lib


text:
// <file>
//     <copyright see="prj:///doc/copyright.txt"/>
//     <license see="prj:///doc/license.txt"/>
//     <owner name="David Srbecký" email="dsrbecky@gmail.com"/>
//     <version>$Revision$</version>
// </file>

namespace Debugger.Wrappers.MetaData
{
	enum CorMethodAttr: uint
	{
	    // member access mask - Use this mask to retrieve accessibility information.
	    mdMemberAccessMask          =   0x0007,
	    mdPrivateScope              =   0x0000,     // Member not referenceable.
	    mdPrivate                   =   0x0001,     // Accessible only by the parent type.
	    mdFamANDAssem               =   0x0002,     // Accessible by sub-types only in this Assembly.
	    mdAssem                     =   0x0003,     // Accessibly by anyone in the Assembly.
	    mdFamily                    =   0x0004,     // Accessible only by type and sub-types.
	    mdFamORAssem                =   0x0005,     // Accessibly by sub-types anywhere, plus anyone in assembly.
	    mdPublic                    =   0x0006,     // Accessibly by anyone who has visibility to this scope.
	    // end member access mask

	    // method contract attributes.
	    mdStatic                    =   0x0010,     // Defined on type, else per instance.
	    mdFinal                     =   0x0020,     // Method may not be overridden.
	    mdVirtual                   =   0x0040,     // Method virtual.
	    mdHideBySig                 =   0x0080,     // Method hides by name+sig, else just by name.

	    // vtable layout mask - Use this mask to retrieve vtable attributes.
	    mdVtableLayoutMask          =   0x0100,
	    mdReuseSlot                 =   0x0000,     // The default.
	    mdNewSlot                   =   0x0100,     // Method always gets a new slot in the vtable.
	    // end vtable layout mask

	    // method implementation attributes.
	    mdCheckAccessOnOverride     =   0x0200,     // Overridability is the same as the visibility.
	    mdAbstract                  =   0x0400,     // Method does not provide an implementation.
	    mdSpecialName               =   0x0800,     // Method is special.  Name describes how.

	    // interop attributes
	    mdPinvokeImpl               =   0x2000,     // Implementation is forwarded through pinvoke.
	    mdUnmanagedExport           =   0x0008,     // Managed method exported via thunk to unmanaged code.

	    // Reserved flags for runtime use only.
	    mdReservedMask              =   0xd000,
	    mdRTSpecialName             =   0x1000,     // Runtime should check name encoding.
	    mdHasSecurity               =   0x4000,     // Method has security associate with it.
	    mdRequireSecObject          =   0x8000,     // Method calls another method containing security code.

	}
}


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"strconv"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
)

// SnmpTraphostResponse List of SNMP traphosts, along with their corresponding SNMP users, configured in ONTAP. This includes SNMPv1/SNMPv2 traphosts as well as SNMPv3 traphosts.
//
// swagger:model snmp_traphost_response
type SnmpTraphostResponse struct {

	// links
	Links *SnmpTraphostResponseLinks `json:"_links,omitempty"`

	// Number of records.
	NumRecords int64 `json:"num_records,omitempty"`

	// records
	Records []*SnmpTraphost `json:"records,omitempty"`
}

// Validate validates this snmp traphost response
func (m *SnmpTraphostResponse) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateLinks(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateRecords(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *SnmpTraphostResponse) validateLinks(formats strfmt.Registry) error {
	if swag.IsZero(m.Links) { // not required
		return nil
	}

	if m.Links != nil {
		if err := m.Links.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links")
			}
			return err
		}
	}

	return nil
}

func (m *SnmpTraphostResponse) validateRecords(formats strfmt.Registry) error {
	if swag.IsZero(m.Records) { // not required
		return nil
	}

	for i := 0; i < len(m.Records); i++ {
		if swag.IsZero(m.Records[i]) { // not required
			continue
		}

		if m.Records[i] != nil {
			if err := m.Records[i].Validate(formats); err != nil {
				if ve, ok := err.(*errors.Validation); ok {
					return ve.ValidateName("records" + "." + strconv.Itoa(i))
				}
				return err
			}
		}

	}

	return nil
}

// ContextValidate validate this snmp traphost response based on the context it is used
func (m *SnmpTraphostResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateLinks(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateRecords(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *SnmpTraphostResponse) contextValidateLinks(ctx context.Context, formats strfmt.Registry) error {

	if m.Links != nil {
		if err := m.Links.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links")
			}
			return err
		}
	}

	return nil
}

func (m *SnmpTraphostResponse) contextValidateRecords(ctx context.Context, formats strfmt.Registry) error {

	for i := 0; i < len(m.Records); i++ {

		if m.Records[i] != nil {
			if err := m.Records[i].ContextValidate(ctx, formats); err != nil {
				if ve, ok := err.(*errors.Validation); ok {
					return ve.ValidateName("records" + "." + strconv.Itoa(i))
				}
				return err
			}
		}

	}

	return nil
}

// MarshalBinary interface implementation
func (m *SnmpTraphostResponse) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *SnmpTraphostResponse) UnmarshalBinary(b []byte) error {
	var res SnmpTraphostResponse
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// SnmpTraphostResponseLinks snmp traphost response links
//
// swagger:model SnmpTraphostResponseLinks
type SnmpTraphostResponseLinks struct {

	// next
	Next *Href `json:"next,omitempty"`

	// self
	Self *Href `json:"self,omitempty"`
}

// Validate validates this snmp traphost response links
func (m *SnmpTraphostResponseLinks) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateNext(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateSelf(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *SnmpTraphostResponseLinks) validateNext(formats strfmt.Registry) error {
	if swag.IsZero(m.Next) { // not required
		return nil
	}

	if m.Next != nil {
		if err := m.Next.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links" + "." + "next")
			}
			return err
		}
	}

	return nil
}

func (m *SnmpTraphostResponseLinks) validateSelf(formats strfmt.Registry) error {
	if swag.IsZero(m.Self) { // not required
		return nil
	}

	if m.Self != nil {
		if err := m.Self.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links" + "." + "self")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this snmp traphost response links based on the context it is used
func (m *SnmpTraphostResponseLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateNext(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateSelf(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *SnmpTraphostResponseLinks) contextValidateNext(ctx context.Context, formats strfmt.Registry) error {

	if m.Next != nil {
		if err := m.Next.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links" + "." + "next")
			}
			return err
		}
	}

	return nil
}

func (m *SnmpTraphostResponseLinks) contextValidateSelf(ctx context.Context, formats strfmt.Registry) error {

	if m.Self != nil {
		if err := m.Self.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links" + "." + "self")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *SnmpTraphostResponseLinks) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *SnmpTraphostResponseLinks) UnmarshalBinary(b []byte) error {
	var res SnmpTraphostResponseLinks
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
import inspect
import os
import sys
import yaml

from rtmbot import RtmBot

def main():
    config = yaml.load(open('rtmbot.conf', 'r'))

    debug = os.getenv('CBBP_DEBUG')  # bool
    active_plugins = os.getenv('CBBP_ACTIVE_PLUGINS')  # array of module paths
    slack_token = os.getenv('CBBP_SLACK_TOKEN')

    plugins = []
    for (dirpath, dirnames, filenames) in os.walk('./plugins'):
        for file in filenames:
            if file.startswith('plugin'):
                filename = file[:-3]
                class_name = ''.join(
                    x.capitalize() for x in filename.split('_')
                )
                plug = [dirpath[2:], filename, class_name]
                plugins.append('.'.join(plug))

    if debug is not None:
        config['DEBUG'] = debug
    if active_plugins:
        config['ACTIVE_PLUGINS'] = active_plugins
    else:
        config['ACTIVE_PLUGINS'] = plugins
    if slack_token:
        config['SLACK_TOKEN'] = slack_token

    bot = RtmBot(config)
    try:
        bot.start()
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == "__main__":
    main()


text:
export const ROUTER__LOCATION_CHANGE = '@@router/LOCATION_CHANGE';

export const APPLICATION__TOGGLE_SIDEMENU = 'APPLICATION__TOGGLE_SIDEMENU';
export const APPLICATION__CLOSE_SIDELISTS = 'APPLICATION__CLOSE_SIDELISTS';
export const APPLICATION__TOGGLE_PLAYLIST = 'APPLICATION__TOGGLE_PLAYLIST';

export const ARTISTS__FETCH_LIST = 'ARTISTS__FETCH_LIST';
export const ARTISTS__LIST_FETCH_FAILED = 'ARTISTS__LIST_FETCH_FAILED';
export const ARTISTS__UPDATE_LIST = 'ARTISTS__UPDATE_LIST';
export const ARTISTS__FETCH_ARTIST = 'ARTISTS__UPDATE_LIST';
export const ARTISTS__SET_SHOWING_ARTIST = 'ARTISTS__SET_SHOWING_ARTIST';
export const ARTISTS__ARTIST_FETCH_FAILED = 'ARTISTS__ARTIST_FETCH_FAILED';

export const ALBUMS__FETCH_LIST = 'ALBUMS__FETCH_LIST';
export const ALBUMS__UPDATE_LIST = 'ALBUMS__UPDATE_LIST';
export const ALBUMS__LIST_FETCH_FAILED = 'ALBUMS__LIST_FETCH_FAILED';

export const ALBUMS__FETCH_ALBUM = 'ALBUMS__FETCH_ALBUM';
export const ALBUMS__SET_SHOWING_ALBUM = 'ALBUMS__SET_SHOWING_ALBUM';
export const ALBUMS__ALBUM_FETCH_FAILED = 'ALBUMS__ALBUM_FETCH_FAILED';


text:
#ifndef GLM_GTX_vec1
#define GLM_GTX_vec1 GLM_VERSION

// Dependency:
#include "../glm.h"
#include "../core/type_vec1.hpp"

#if(defined(GLM_MESSAGES) && !defined(glm_ext))
#	pragma message("GLM: GLM_GTX_vec1 extension included")
#endif

namespace glm
{
	//! 1 component vector of high precision floating-point numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::highp_vec1_t			highp_vec1;
	//! 1 component vector of medium precision floating-point numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::mediump_vec1_t			mediump_vec1;
	//! 1 component vector of low precision floating-point numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::lowp_vec1_t				lowp_vec1;

	//! 1 component vector of high precision signed integer numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::highp_ivec1_t			highp_ivec1;
	//! 1 component vector of medium precision signed integer numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::mediump_ivec1_t			mediump_ivec1;
	//! 1 component vector of low precision signed integer numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::lowp_ivec1_t			lowp_ivec1;

	//! 1 component vector of high precision unsigned integer numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::highp_uvec1_t			highp_uvec1;
	//! 1 component vector of medium precision unsigned integer numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::mediump_uvec1_t			mediump_uvec1;
	//! 1 component vector of low precision unsigned integer numbers.
	//! There is no guarantee on the actual precision.
	//! From GLM_GTX_vec1 extension.
	typedef detail::lowp_uvec1_t			lowp_uvec1;

	//////////////////////////
	// vec1 definition

	//! 1 component vector of boolean.
	//! From GLM_GTX_vec1 extension.
	typedef detail::tvec1<bool>	bvec1;

#if(defined(GLM_PRECISION_HIGHP_FLOAT))
	typedef highp_vec1			vec1;
#elif(defined(GLM_PRECISION_MEDIUMP_FLOAT))
	typedef mediump_vec1			vec1;
#elif(defined(GLM_PRECISION_LOWP_FLOAT))
	typedef lowp_vec1			vec1;
#else
	//! 1 component vector of floating-point numbers.
	//! From GLM_GTX_vec1 extension.
	typedef mediump_vec1			vec1;
#endif//GLM_PRECISION

#if(defined(GLM_PRECISION_HIGHP_INT))
	typedef highp_ivec1			ivec1;
#elif(defined(GLM_PRECISION_MEDIUMP_INT))
	typedef mediump_ivec1		ivec1;
#elif(defined(GLM_PRECISION_LOWP_INT))
	typedef lowp_ivec1			ivec1;
#else
	//! 1 component vector of signed integer numbers.
	//! From GLM_GTX_vec1 extension.
	typedef mediump_ivec1		ivec1;
#endif//GLM_PRECISION

#if(defined(GLM_PRECISION_HIGHP_UINT))
	typedef highp_uvec1			uvec1;
#elif(defined(GLM_PRECISION_MEDIUMP_UINT))
	typedef mediump_uvec1		uvec1;
#elif(defined(GLM_PRECISION_LOWP_UINT))
	typedef lowp_uvec1			uvec1;
#else
	//! 1 component vector of unsigned integer numbers.
	//! From GLM_GTX_vec1 extension.
	typedef mediump_uvec1		uvec1;
#endif//GLM_PRECISION

}// namespace glm

#include "vec1.inl"

#endif//GLM_GTX_vec1


text:
dotnet pack ../Weixing.AspNetCore.Toolkit/ -c Release -o ../nuget
del Weixing.AspNetCore.Toolkit.*.symbols.nupkg /f /q
nuget push Weixing.AspNetCore.Toolkit.*.nupkg 178079be-7c67-4f49-914c-e11c6f502336 -src https://www.nuget.org/
del Weixing.AspNetCore.Toolkit.*.nupkg /f /q
pause


text:
class StaticController < ApplicationController
  #layout :get_layout

  def index

  end

  def admin
  end

  private

  def get_layout
    case action_name
      when "index",
        "empty"
      else
        "application"
    end
  end
end


text:
/*	$NetBSD: pam_get_mapped_authtok.c,v 1.2.2.2 2015/06/08 20:33:20 snj Exp $	*/

/*-
 * Copyright (c) 2002-2003 Networks Associates Technology, Inc.
 * Copyright (c) 2004-2011 Dag-Erling Smørgrav
 * All rights reserved.
 *
 * This software was developed for the FreeBSD Project by ThinkSec AS and
 * Network Associates Laboratories, the Security Research Division of
 * Network Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
 * ("CBOSS"), as part of the DARPA CHATS research program.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Id: pam_get_mapped_authtok.c 648 2013-03-05 17:54:27Z des
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <sys/cdefs.h>
__RCSID("$NetBSD: pam_get_mapped_authtok.c,v 1.2.2.2 2015/06/08 20:33:20 snj Exp $");

#include <security/pam_appl.h>

/*
 * XSSO 4.2.1
 * XSSO 6 page 48
 *
 * Get mapped password for the user
 */

int
pam_get_mapped_authtok(pam_handle_t *pamh,
	const char *target_module_username,
	const char *target_module_type,
	const char *target_authn_domain,
	size_t *target_authtok_len,
	unsigned char **target_module_authtok)
{

	ENTER();
	RETURNC(PAM_SYSTEM_ERR);
}

/*
 * NODOC
 */


text:
<?php

namespace pedroac\url\normalization\rule;

use PHPUnit\Framework\TestCase;
use pedroac\url\Parsed;
use pedroac\url\URL;

class StripDotSegmentsRuleTest extends TestCase
{
    /**
     * @covers pedroac\url\normalization\rule\StripDotSegmentsRule::apply
     */
    public function testApply()
    {
        $rule = new StripDotSegmentsRule;

        $components1 = (new Parsed(new URL('http://test.com/./abc/def/../ghi/')))
                       ->toComponents();
        $rule->apply($components1);
        $this->assertEquals('http://test.com/abc/ghi/', $components1);
    }
}


text:
#include "operators.h"

Operator::Operator(char op, int priority): operator_(op), priority_(priority) {}

char Operator::get_operator() const {
    return operator_;
}

int Operator::get_priority() const {
    return priority_;
}

/* ------------- */

Add::Add(): Operator('+', 0) {}

double Add::calculate(double a, double b) const {
    return a + b;
}

Subtract::Subtract(): Operator('-', 0) {}

double Subtract::calculate(double a, double b) const {
    return a - b;
}

Multiply::Multiply(): Operator('*', 1) {}

double Multiply::calculate(double a, double b) const {
    return a * b;
}

Divide::Divide(): Operator('/', 1) {}

double Divide::calculate(double a, double b) const {
    return a / b;
}


text:
var schema = require('mongoose').Schema;
var crypto = require('crypto');

var ParticipantSchema = new Schema({
    name : { type : String, default : '' },
    email : {type : String, default : '' },
    cagnote : { type : Schema.ObjectId, ref : 'cagnotes'},
    user : { type : Schema.ObjectId, ref : 'users'},
    amount : {type : Number, default : 0 }
});

var Participant = mongoose.model('Participant', ParticipantSchema);

exports = module.exports = Participant;


text:
package org.springframework.cache.jcache.interceptor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLong;
import javax.cache.annotation.CacheDefaults;
import javax.cache.annotation.CacheKey;
import javax.cache.annotation.CacheResult;

import org.junit.Before;
import org.junit.Test;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.cache.jcache.config.JCacheConfigurerSupport;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static org.junit.Assert.*;

/**
 *
 * @author Stephane Nicoll
 */
public class JCacheKeyGeneratorTests {

	private TestKeyGenerator keyGenerator;

	private SimpleService simpleService;

	private Cache cache;

	@Before
	public void setup() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
		this.keyGenerator = context.getBean(TestKeyGenerator.class);
		this.simpleService = context.getBean(SimpleService.class);
		this.cache = context.getBean(CacheManager.class).getCache("test");
	}

	@Test
	public void getSimple() {
		this.keyGenerator.expect(1L);
		Object first = this.simpleService.get(1L);
		Object second = this.simpleService.get(1L);
		assertSame(first, second);

		Object key = new SimpleKey(1L);
		assertEquals(first, cache.get(key).get());
	}

	@Test
	public void getFlattenVararg() {
		this.keyGenerator.expect(1L, "foo", "bar");
		Object first = this.simpleService.get(1L, "foo", "bar");
		Object second = this.simpleService.get(1L, "foo", "bar");
		assertSame(first, second);

		Object key = new SimpleKey(1L, "foo", "bar");
		assertEquals(first, cache.get(key).get());
	}

	@Test
	public void getFiltered() {
		this.keyGenerator.expect(1L);
		Object first = this.simpleService.getFiltered(1L, "foo", "bar");
		Object second = this.simpleService.getFiltered(1L, "foo", "bar");
		assertSame(first, second);

		Object key = new SimpleKey(1L);
		assertEquals(first, cache.get(key).get());
	}

	@Configuration
	@EnableCaching
	static class Config extends JCacheConfigurerSupport {

		@Bean
		@Override
		public CacheManager cacheManager() {
			return new ConcurrentMapCacheManager();
		}

		@Bean
		@Override
		public KeyGenerator keyGenerator() {
			return new TestKeyGenerator();
		}

		@Bean
		public SimpleService simpleService() {
			return new SimpleService();
		}

	}

	@CacheDefaults(cacheName = "test")
	public static class SimpleService {
		private AtomicLong counter = new AtomicLong();

		@CacheResult
		public Object get(long id) {
			return counter.getAndIncrement();
		}

		@CacheResult
		public Object get(long id, String... items) {
			return counter.getAndIncrement();
		}

		@CacheResult
		public Object getFiltered(@CacheKey long id, String... items) {
			return counter.getAndIncrement();
		}

	}

	private static class TestKeyGenerator extends SimpleKeyGenerator {

		private Object[] expectedParams;

		private void expect(Object... params) {
			this.expectedParams = params;
		}

		@Override
		public Object generate(Object target, Method method, Object... params) {
			assertTrue("Unexpected parameters: expected: "
							+ Arrays.toString(this.expectedParams) + " but got: " + Arrays.toString(params),
					Arrays.equals(expectedParams, params));
			return new SimpleKey(params);
		}
	}
}


text:
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace FreeFoodUs.Models
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public static List<User> All()
        {
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ConnectionString))
            {
                return connection.Query<User>(@"SELECT * FROM Users").ToList();
            }
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.twitter</groupId>
  <artifactId>jsr166e</artifactId>
  <name>JSR166e</name>
  <packaging>jar</packaging>
  <version>1.1.0</version>
  <url>http://github.com/twitter/jsr166e</url>
  <description>JSR166e</description>

  <scm>
    <connection>scm:git:git@github.com:twitter/jsr166e.git</connection>
    <url>scm:git:git@github.com:twitter/jsr166e.git</url>
    <developerConnection>scm:git:git@github.com:twitter/jsr166e.git</developerConnection>
  </scm>

  <licenses>
    <license>
      <name>CC0 1.0 Universal</name>
      <url>http://creativecommons.org/publicdomain/zero/1.0/</url>
    </license>
  </licenses>

  <developers>
    <developer>
      <name>Steve Gury</name>
      <email>stevegury@twitter.com</email>
    </developer>
    <developer>
      <name>Marius Eriksen</name>
      <email>marius@twitter.com</email>
    </developer>
  </developers>

  <properties>
    <maven.compiler.source>1.6</maven.compiler.source>
    <maven.compiler.target>1.6</maven.compiler.target>
    <encoding>UTF-8</encoding>
  </properties>

  <distributionManagement>
    <snapshotRepository>
      <id>sonatype-nexus-snapshots</id>
      <name>Sonatype OSS</name>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>sonatype-nexus-staging</id>
      <name>Nexus Release Repository</name>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
  </distributionManagement>

  <repositories>
    <repository>
      <id>sonatype-nexus-snapshots</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
     </repository>
  </repositories>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-release-plugin</artifactId>
         <version>2.1</version>
         <configuration>
          <mavenExecutorId>forked-path</mavenExecutorId>
          <useReleaseProfile>false</useReleaseProfile>
          <arguments>-Psonatype-oss-release</arguments>
         </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12</version>
        <configuration>
          <argLine>-Xmx1024m</argLine>
          <redirectTestOutputToFile>false</redirectTestOutputToFile>
          <includes>
            <include>**/Test*.java</include>
            <include>**/*Test.java</include>
            <include>**/*Spec.java</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <profiles>
    <profile>
      <id>sonatype-oss-release</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <version>2.1.2</version>
            <executions>
              <execution>
                <id>attach-sources</id>
                <goals>
                  <goal>jar-no-fork</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>2.7</version>
            <executions>
              <execution>
                <id>attach-javadocs</id>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <version>1.1</version>
            <executions>
              <execution>
                <id>sign-artifacts</id>
                <phase>verify</phase>
                <goals>
                  <goal>sign</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
Counts the number of words that are in the file word.txt

##Requirements
* Download and install Java from https://www.java.com/es/download/ or from distribution Ubuntu:
```
	$ sudo apt install icedtea-8-plugin openjdk-8-jre
```
* Download Spark from http://spark.apache.org/downloads.html and install:
```
	$ sudo tar xvfz spark.version.tgz -C   /usr/local/
	$ sudo ln -s /usr/local/spark.version   /usr/local/spark
```
#Run

Open a terminal and type:
```
	$ sudo /usr/local/spark/sbin/start-all.sh
	$ sh run.sh
```

#Output

The output shows many lines of status information of the run. Between these lines is the result of the count of words

	INFO StandaloneSchedulerBackend: Connected to Spark cluster with app ID app-20160822095815-0002
	INFO NettyBlockTransferService: Server created on localhost:33983
	INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20160822095815-0002/0 on worker-20160822094931-localhost-46544 (localhost:46544) with 2 cores
	INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20160822095815-0002/0 is now RUNNING
	INFO StandaloneSchedulerBackend: SchedulerBackend is ready for scheduling beginning after reached minRegisteredResourcesRatio: 0.0
	INFO SparkContext: Starting job: collect at /usr/local/spark/examples/src/main/python/wordcount.py:40
	INFO DAGScheduler: Registering RDD 5 (reduceByKey at /usr/local/spark/examples/src/main/python/wordcount.py:39)
	INFO DAGScheduler: Got job 0 (collect at /usr/local/spark/examples/src/main/python/wordcount.py:40) with 1 output partitions
	INFO DAGScheduler: Final stage: ResultStage 1 (collect at /usr/local/spark/examples/src/main/python/wordcount.py:40)
	INFO DAGScheduler: Submitting ShuffleMapStage 0 (PairwiseRDD[5] at reduceByKey at /usr/local/spark/examples/src/main/python/wordcount.py:39), which has no missing parents
	INFO DAGScheduler: Submitting 1 missing tasks from ShuffleMapStage 0 (PairwiseRDD[5] at reduceByKey at /usr/local/spark/examples/src/main/python/wordcount.py:39)

	INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, localhost, partition 0, PROCESS_LOCAL, 5958 bytes)
	INFO CoarseGrainedSchedulerBackend$DriverEndpoint: Launching task 0 on executor id: 0 hostname: localhost.
	INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 4029 ms on localhost (1/1)
	INFO DAGScheduler: ShuffleMapStage 0 (reduceByKey at /usr/local/spark/examples/src/main/python/wordcount.py:39) finished in 4,056 s
	INFO DAGScheduler: Submitting ResultStage 1 (PythonRDD[8] at collect at /usr/local/spark/examples/src/main/python/wordcount.py:40), which has no missing parents
	INFO DAGScheduler: Submitting 1 missing tasks from ResultStage 1 (PythonRDD[8] at collect at /usr/local/spark/examples/src/main/python/wordcount.py:40)

	INFO TaskSetManager: Starting task 0.0 in stage 1.0 (TID 1, localhost, partition 0, NODE_LOCAL, 5286 bytes)
	INFO CoarseGrainedSchedulerBackend$DriverEndpoint: Launching task 1 on executor id: 0 hostname: localhost.
	INFO MapOutputTrackerMasterEndpoint: Asked to send map output locations for shuffle 0 to localhost:35154
	INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 1) in 191 ms on localhost (1/1)
	INFO DAGScheduler: ResultStage 1 (collect at /usr/local/spark/examples/src/main/python/wordcount.py:40) finished in 0,193 s
	INFO DAGScheduler: Job 0 finished: collect at /usr/local/spark/examples/src/main/python/wordcount.py:40, took 4,552225 s

	world: 2
	Hello: 3

# References

 * [Apache Spark 2.0.0 - Quick Start](http://spark.apache.org/docs/latest/quick-start.html)
 * [Apache Spark 2.0.0 - Spark Cluster](http://spark.apache.org/docs/latest/cluster-overview.html)
 * [Apache Spark 2.0.0 - Submitting Applications](http://spark.apache.org/docs/latest/submitting-applications.html)