text:
require 'concurrent'
require 'thread'

module TZInfo
  # {InvalidDataSource} is raised if the selected {DataSource} doesn't implement
  # one of the required methods.
  class InvalidDataSource < StandardError
  end

  # {DataSourceNotFound} is raised if no data source could be found (i.e. if
  # `'tzinfo/data'` cannot be found on the load path and no valid zoneinfo
  # directory can be found on the system).
  class DataSourceNotFound < StandardError
  end

  # TZInfo can be used with different data sources for time zone and country
  # data. Each source of data is implemented as a subclass of {DataSource}.
  #
  # To choose a data source and override the default selection, use the
  # {DataSource.set} method.
  #
  # @abstract To create a custom data source, create a subclass of {DataSource}
  #   and implement the {load_timezone_info}, {data_timezone_identifiers},
  #   {linked_timezone_identifiers}, {load_country_info} and {country_codes}
  #   methods.
  class DataSource
    # The currently selected data source.
    #
    # @private
    @@instance = nil

    # A `Mutex` used to ensure the default data source is only created once.
    #
    # @private
    @@default_mutex = Mutex.new

    class << self
      # @return [DataSource] the currently selected source of data.
      def get
        # If a DataSource hasn't been manually set when the first request is
        # made to obtain a DataSource, then a default data source is created.
        #
        # This is done at the first request rather than when TZInfo is loaded to
        # avoid unnecessary attempts to find a suitable DataSource.
        #
        # A `Mutex` is used to ensure that only a single default instance is
        # created (this avoiding the possibility of retaining two copies of the
        # same data in memory).

        unless @@instance
          @@default_mutex.synchronize do
            set(create_default_data_source) unless @@instance
          end
        end

        @@instance
      end

      # Sets the currently selected data source for time zone and country data.
      #
      # This should usually be set to one of the two standard data source types:
      #
      # * `:ruby` - read data from the Ruby modules included in the TZInfo::Data
      #   library (tzinfo-data gem).
      # * `:zoneinfo` - read data from the zoneinfo files included with most
      #   Unix-like operating systems (e.g. in /usr/share/zoneinfo).
      #
      # To set TZInfo to use one of the standard data source types, call
      # `TZInfo::DataSource.set`` in one of the following ways:
      #
      #     TZInfo::DataSource.set(:ruby)
      #     TZInfo::DataSource.set(:zoneinfo)
      #     TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir)
      #     TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)
      #
      # `DataSource.set(:zoneinfo)` will automatically search for the zoneinfo
      # directory by checking the paths specified in
      # {DataSources::ZoneinfoDataSource.search_path}.
      # {DataSources::ZoneinfoDirectoryNotFound} will be raised if no valid
      # zoneinfo directory could be found.
      #
      # `DataSource.set(:zoneinfo, zoneinfo_dir)` uses the specified
      # `zoneinfo_dir` directory as the data source. If the directory is not a
      # valid zoneinfo directory, a {DataSources::InvalidZoneinfoDirectory}
      # exception will be raised.
      #
      # `DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)` uses the
      # specified `zoneinfo_dir` directory as the data source, but loads the
      # `iso3166.tab` file from the path given by `iso3166_tab_file`. If the
      # directory is not a valid zoneinfo directory, a
      # {DataSources::InvalidZoneinfoDirectory} exception will be raised.
      #
      # Custom data sources can be created by subclassing TZInfo::DataSource and
      # implementing the following methods:
      #
      # * {load_timezone_info}
      # * {data_timezone_identifiers}
      # * {linked_timezone_identifiers}
      # * {load_country_info}
      # * {country_codes}
      #
      # To have TZInfo use the custom data source, call {DataSource.set},
      # passing an instance of the custom data source implementation as follows:
      #
      #     TZInfo::DataSource.set(CustomDataSource.new)
      #
      # Calling {DataSource.set} will only affect instances of {Timezone} and
      # {Country} obtained with {Timezone.get} and {Country.get} subsequent to
      # the {DataSource.set} call. Existing {Timezone} and {Country} instances
      # will be unaffected.
      #
      # If {DataSource.set} is not called, TZInfo will by default attempt to use
      # TZInfo::Data as the data source. If TZInfo::Data is not available (i.e.
      # if `require 'tzinfo/data'` fails), then TZInfo will search for a
      # zoneinfo directory instead (using the search path specified by
      # {DataSources::ZoneinfoDataSource.search_path}).
      #
      # @param data_source_or_type [Object] either `:ruby`, `:zoneinfo` or an
      #   instance of a {DataSource}.
      # @param args [Array<Object>] when `data_source_or_type` is a symbol,
      #   optional arguments to use when initializing the data source.
      # @raise [ArgumentError] if `data_source_or_type` is not `:ruby`,
      #   `:zoneinfo` or an instance of {DataSource}.
      def set(data_source_or_type, *args)
        if data_source_or_type.kind_of?(DataSource)
          @@instance = data_source_or_type
        elsif data_source_or_type == :ruby
          @@instance = DataSources::RubyDataSource.new
        elsif data_source_or_type == :zoneinfo
          @@instance = DataSources::ZoneinfoDataSource.new(*args)
        else
          raise ArgumentError, 'data_source_or_type must be a DataSource instance or a data source type (:ruby or :zoneinfo)'
        end
      end

      private

      # Creates a {DataSource} instance for use as the default. Used if no
      # preference has been specified manually.
      #
      # @return [DataSource] the newly created default {DataSource} instance.
      def create_default_data_source
        has_tzinfo_data = false

        begin
          require 'tzinfo/data'
          has_tzinfo_data = true
        rescue LoadError
        end

        return DataSources::RubyDataSource.new if has_tzinfo_data

        begin
          return DataSources::ZoneinfoDataSource.new
        rescue DataSources::ZoneinfoDirectoryNotFound
          raise DataSourceNotFound, "No source of timezone data could be found.\nPlease refer to https://tzinfo.github.io/datasourcenotfound for help resolving this error."
        end
      end
    end

    # Initializes a new {DataSource} instance. Typically only called via
    # subclasses of {DataSource}.
    def initialize
      @timezones = Concurrent::Map.new
    end

    # Returns a {DataSources::TimezoneInfo} instance for the given identifier.
    # The result will derive from either {DataSources::DataTimezoneInfo} for
    # time zones that define their own data or {DataSources::LinkedTimezoneInfo}
    # for links or aliases to other time zones.
    #
    # {get_timezone_info} calls {load_timezone_info} to create the
    # {DataSources::TimezoneInfo} instance. The returned instance is cached and
    # returned in subsequent calls to {get_timezone_info} for the identifier.
    #
    # @param identifier [String] A time zone identifier.
    # @return [DataSources::TimezoneInfo] a {DataSources::TimezoneInfo} instance
    #   for a given identifier.
    # @raise [InvalidTimezoneIdentifier] if the time zone is not found or the
    #   identifier is invalid.
    def get_timezone_info(identifier)
      result = @timezones[identifier]

      unless result
        # Thread-safety: It is possible that multiple equivalent TimezoneInfo
        # instances could be created here in concurrently executing threads. The
        # consequences of this are that the data may be loaded more than once
        # (depending on the data source). The performance benefit of ensuring
        # that only a single instance is created is unlikely to be worth the
        # overhead of only allowing one TimezoneInfo to be loaded at a time.

        result = load_timezone_info(identifier)
        @timezones[result.identifier] = result
      end

      result
    end

    # @return [Array<String>] a frozen `Array`` of all the available time zone
    #   identifiers. The identifiers are sorted according to `String#<=>`.
    def timezone_identifiers
      # Thread-safety: It is possible that the value of @timezone_identifiers
      # may be calculated multiple times in concurrently executing threads. It
      # is not worth the overhead of locking to ensure that
      # @timezone_identifiers is only calculated once.
      @timezone_identifiers ||= build_timezone_identifiers
    end

    # Returns a frozen `Array` of all the available time zone identifiers for
    # data time zones (i.e. those that actually contain definitions). The
    # identifiers are sorted according to `String#<=>`.
    #
    # @return [Array<String>] a frozen `Array` of all the available time zone
    #   identifiers for data time zones.
    def data_timezone_identifiers
      raise_invalid_data_source('data_timezone_identifiers')
    end

    # Returns a frozen `Array` of all the available time zone identifiers that
    # are links to other time zones. The identifiers are sorted according to
    # `String#<=>`.
    #
    # @return [Array<String>] a frozen `Array` of all the available time zone
    #   identifiers that are links to other time zones.
    def linked_timezone_identifiers
      raise_invalid_data_source('linked_timezone_identifiers')
    end

    # @param code [String] an ISO 3166-1 alpha-2 country code.
    # @return [DataSources::CountryInfo] a {DataSources::CountryInfo} instance
    #   for the given ISO 3166-1 alpha-2 country code.
    # @raise [InvalidCountryCode] if the country could not be found or the code
    #   is invalid.
    def get_country_info(code)
      load_country_info(code)
    end

    # Returns a frozen `Array` of all the available ISO 3166-1 alpha-2 country
    # codes. The identifiers are sorted according to `String#<=>`.
    #
    # @return [Array<String>] a frozen `Array` of all the available ISO 3166-1
    #   alpha-2 country codes.
    def country_codes
      raise_invalid_data_source('country_codes')
    end

    # @return [String] a description of the {DataSource}.
    def to_s
      "Default DataSource"
    end

    # @return [String] the internal object state as a programmer-readable
    #   `String`.
    def inspect
      "#<#{self.class}>"
    end

    protected

    # Returns a {DataSources::TimezoneInfo} instance for the given time zone
    # identifier. The result should derive from either
    # {DataSources::DataTimezoneInfo} for time zones that define their own data
    # or {DataSources::LinkedTimezoneInfo} for links to or aliases for other
    # time zones.
    #
    # @param identifier [String] A time zone identifier.
    # @return [DataSources::TimezoneInfo] a {DataSources::TimezoneInfo} instance
    #   for the given time zone identifier.
    # @raise [InvalidTimezoneIdentifier] if the time zone is not found or the
    #   identifier is invalid.
    def load_timezone_info(identifier)
      raise_invalid_data_source('load_timezone_info')
    end

    # @param code [String] an ISO 3166-1 alpha-2 country code.
    # @return [DataSources::CountryInfo] a {DataSources::CountryInfo} instance
    #   for the given ISO 3166-1 alpha-2 country code.
    # @raise [InvalidCountryCode] if the country could not be found or the code
    #   is invalid.
    def load_country_info(code)
      raise_invalid_data_source('load_country_info')
    end

    # @return [Encoding] the `Encoding` used by the `String` instances returned
    #   by {data_timezone_identifiers} and {linked_timezone_identifiers}.
    def timezone_identifier_encoding
      Encoding::UTF_8
    end

    # Checks that the given identifier is a valid time zone identifier (can be
    # found in the {timezone_identifiers} `Array`). If the identifier is valid,
    # the `String` instance representing that identifier from
    # `timezone_identifiers` is returned. Otherwise an
    # {InvalidTimezoneIdentifier} exception is raised.
    #
    # @param identifier [String] a time zone identifier to be validated.
    # @return [String] the `String` instance equivalent to `identifier` from
    #   {timezone_identifiers}.
    # @raise [InvalidTimezoneIdentifier] if `identifier` was not found in
    #   {timezone_identifiers}.
    def validate_timezone_identifier(identifier)
      raise InvalidTimezoneIdentifier, "Invalid identifier: #{identifier.nil? ? 'nil' : identifier}" unless identifier.kind_of?(String)

      valid_identifier = try_with_encoding(identifier, timezone_identifier_encoding) {|id| find_timezone_identifier(id) }
      return valid_identifier if valid_identifier

      raise InvalidTimezoneIdentifier, "Invalid identifier: #{identifier.encode(Encoding::UTF_8)}"
    end

    # Looks up a given code in the given hash of code to
    # {DataSources::CountryInfo} mappings. If the code is found the
    # {DataSources::CountryInfo} is returned. Otherwise an {InvalidCountryCode}
    # exception is raised.
    #
    # @param hash [String, DataSources::CountryInfo] a mapping from ISO 3166-1
    #   alpha-2 country codes to {DataSources::CountryInfo} instances.
    # @param code [String] a country code to lookup.
    # @param encoding [Encoding] the encoding used for the country codes in
    #   `hash`.
    # @return [DataSources::CountryInfo] the {DataSources::CountryInfo} instance
    #   corresponding to `code`.
    # @raise [InvalidCountryCode] if `code` was not found in `hash`.
    def lookup_country_info(hash, code, encoding = Encoding::UTF_8)
      raise InvalidCountryCode, "Invalid country code: #{code.nil? ? 'nil' : code}" unless code.kind_of?(String)

      info = try_with_encoding(code, encoding) {|c| hash[c] }
      return info if info

      raise InvalidCountryCode, "Invalid country code: #{code.encode(Encoding::UTF_8)}"
    end

    private

    # Raises {InvalidDataSource} to indicate that a method has not been
    # overridden by a particular data source implementation.
    #
    # @raise [InvalidDataSource] always.
    def raise_invalid_data_source(method_name)
      raise InvalidDataSource, "#{method_name} not defined"
    end

    # Combines {data_timezone_identifiers} and {linked_timezone_identifiers}
    # to create an `Array` containing all valid time zone identifiers. If
    # {linked_timezone_identifiers} is empty, the {data_timezone_identifiers}
    # instance is returned.
    #
    # The returned `Array` is frozen. The identifiers are sorted according to
    # `String#<=>`.
    #
    # @return [Array<String>] an `Array` containing all valid time zone
    #   identifiers.
    def build_timezone_identifiers
      data = data_timezone_identifiers
      linked = linked_timezone_identifiers
      linked.empty? ? data : (data + linked).sort!.freeze
    end

    if [].respond_to?(:bsearch)
      # If the given `identifier` is contained within the {timezone_identifiers}
      # `Array`, the `String` instance representing that identifier from
      # {timezone_identifiers} is returned. Otherwise, `nil` is returned.
      #
      # @param identifier [String] A time zone identifier to search for.
      # @return [String] the `String` instance representing `identifier` from
      #   {timezone_identifiers} if found, or `nil` if not found.
      #
      # :nocov_no_array_bsearch:
      def find_timezone_identifier(identifier)

        result = timezone_identifiers.bsearch {|i| i >= identifier }
        result == identifier ? result : nil
      end
      # :nocov_no_array_bsearch:
    else
      # If the given `identifier` is contained within the {timezone_identifiers}
      # `Array`, the `String` instance representing that identifier from
      # {timezone_identifiers} is returned. Otherwise, `nil` is returned.
      #
      # @param identifier [String] A time zone identifier to search for.
      # @return [String] the `String` instance representing `identifier` from
      #   {timezone_identifiers} if found, or `nil` if not found.
      #
      # :nocov_array_bsearch:
      def find_timezone_identifier(identifier)
        identifiers = timezone_identifiers
        low = 0
        high = identifiers.length

        while low < high do
          mid = (low + high).div(2)
          mid_identifier = identifiers[mid]
          cmp = mid_identifier <=> identifier

          return mid_identifier if cmp == 0

          if cmp > 0
            high = mid
          else
            low = mid + 1
          end
        end

        nil
      end
      # :nocov_array_bsearch:
    end

    # Tries an operation using `string` directly. If the operation fails, the
    # string is copied and encoded with `encoding` and the operation is tried
    # again.
    #
    # @param string [String] The `String` to perform the operation on.
    # @param encoding [Encoding] The `Encoding` to use if the initial attempt
    #   fails.
    # @yield [s] the caller will be yielded to once or twice to attempt the
    #   operation.
    # @yieldparam s [String] either `string` or an encoded copy of `string`.
    # @yieldreturn [Object] The result of the operation. Must be truthy if
    #   successful.
    # @return [Object] the result of the operation or `nil` if the first attempt
    # fails and `string` is already encoded with `encoding`.
    def try_with_encoding(string, encoding)
      result = yield string
      return result if result

      unless encoding == string.encoding
        string = string.encode(encoding)
        yield string
      end
    end
  end
end


text:
package backtype.storm.security.auth;

import java.io.IOException;
import java.net.Socket;
import java.security.Principal;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

import javax.security.auth.Subject;
import javax.security.auth.login.Configuration;
import javax.security.sasl.SaslServer;

import backtype.storm.utils.ExtendedThreadPoolExecutor;
import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TSaslServerTransport;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.TTransportFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import backtype.storm.security.auth.ThriftConnectionType;

/**
 * Base class for SASL authentication plugin.
 */
public abstract class SaslTransportPlugin implements ITransportPlugin {
    protected ThriftConnectionType type;
    protected Map storm_conf;
    protected Configuration login_conf;
    private static final Logger LOG = LoggerFactory.getLogger(SaslTransportPlugin.class);

    @Override
    public void prepare(ThriftConnectionType type, Map storm_conf, Configuration login_conf) {
        this.type = type;
        this.storm_conf = storm_conf;
        this.login_conf = login_conf;
    }

    @Override
    public TServer getServer(TProcessor processor) throws IOException, TTransportException {
        int port = type.getPort(storm_conf);
        TTransportFactory serverTransportFactory = getServerTransportFactory();
        TServerSocket serverTransport = new TServerSocket(port);
        int numWorkerThreads = type.getNumThreads(storm_conf);
        Integer queueSize = type.getQueueSize(storm_conf);

        TThreadPoolServer.Args server_args =
                new TThreadPoolServer.Args(serverTransport).processor(new TUGIWrapProcessor(processor)).minWorkerThreads(numWorkerThreads)
                        .maxWorkerThreads(numWorkerThreads).protocolFactory(new TBinaryProtocol.Factory(false, true));

        if (serverTransportFactory != null) {
            server_args.transportFactory(serverTransportFactory);
        }
        BlockingQueue workQueue = new SynchronousQueue();
        if (queueSize != null) {
            workQueue = new ArrayBlockingQueue(queueSize);
        }
        ThreadPoolExecutor executorService = new ExtendedThreadPoolExecutor(numWorkerThreads, numWorkerThreads, 60, TimeUnit.SECONDS, workQueue);
        server_args.executorService(executorService);
        return new TThreadPoolServer(server_args);
    }

    /**
     * All subclass must implement this method
     *
     * @return
     * @throws IOException
     */
    protected abstract TTransportFactory getServerTransportFactory() throws IOException;

    /**
     * Processor that pulls the SaslServer object out of the transport, and assumes the remote user's UGI before calling through to the original processor.
     *
     * This is used on the server side to set the UGI for each specific call.
     */
    private class TUGIWrapProcessor implements TProcessor {
        final TProcessor wrapped;

        TUGIWrapProcessor(TProcessor wrapped) {
            this.wrapped = wrapped;
        }

        public boolean process(final TProtocol inProt, final TProtocol outProt) throws TException {
            // populating request context
            ReqContext req_context = ReqContext.context();

            TTransport trans = inProt.getTransport();
            // Sasl transport
            TSaslServerTransport saslTrans = (TSaslServerTransport) trans;
            // remote address
            TSocket tsocket = (TSocket) saslTrans.getUnderlyingTransport();
            Socket socket = tsocket.getSocket();
            req_context.setRemoteAddress(socket.getInetAddress());

            // remote subject
            SaslServer saslServer = saslTrans.getSaslServer();
            String authId = saslServer.getAuthorizationID();
            Subject remoteUser = new Subject();
            remoteUser.getPrincipals().add(new User(authId));
            req_context.setSubject(remoteUser);

            // invoke service handler
            return wrapped.process(inProt, outProt);
        }
    }

    public static class User implements Principal {
        private final String name;

        public User(String name) {
            this.name = name;
        }

        /**
         * Get the full name of the user.
         */
        public String getName() {
            return name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            } else if (o == null || getClass() != o.getClass()) {
                return false;
            } else {
                return (name.equals(((User) o).name));
            }
        }

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

        @Override
        public String toString() {
            return name;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "pyPE.hpp"

#include "LIEF/PE/hash.hpp"
#include "LIEF/PE/Symbol.hpp"

#include <string>
#include <sstream>

namespace LIEF {
namespace PE {

template<class T>
using getter_t = T (Symbol::*)(void) const;

template<class T>
using setter_t = void (Symbol::*)(T);

template<class T>
using no_const_getter = T (Symbol::*)(void);

template<>
void create<Symbol>(py::module& m) {
  py::class_<Symbol, LIEF::Symbol>(m, "Symbol")
    .def(py::init<>())

    .def_property("name",
        static_cast<getter_t<std::wstring>>      (&Symbol::wname),
        static_cast<setter_t<const std::string&>>(&Symbol::name))

    .def_property_readonly("section_number",
        &Symbol::section_number)

    .def_property_readonly("type",
        &Symbol::type)

    .def_property_readonly("base_type",
        &Symbol::base_type)

    .def_property_readonly("complex_type",
        &Symbol::complex_type)

    .def_property_readonly("storage_class",
        &Symbol::storage_class)

    .def_property_readonly("numberof_aux_symbols",
        &Symbol::numberof_aux_symbols)

    .def_property_readonly("section",
        static_cast<no_const_getter<Section*>>(&Symbol::section),
        py::return_value_policy::reference)

    .def_property_readonly("has_section",
        &Symbol::has_section,
        "``True`` if symbols are located in a section")

    .def("__eq__", &Symbol::operator==)
    .def("__ne__", &Symbol::operator!=)
    .def("__hash__",
        [] (const Symbol& symbol) {
          return Hash::hash(symbol);
        })

    .def("__str__", [] (const Symbol& symbol)
        {
          std::ostringstream stream;
          stream << symbol;
          std::string str = stream.str();
          return str;
        });
}

}
}


text:
package io.youi.component.bootstrap

trait Modal {
  protected val element: html.Element

  protected def call(content: String): Unit = {
    js.eval(s"$$('#${element.getAttribute("id")}').modal($content)")
    ()
  }

  def initialize(backdrop: String = "true",
                 keyboard: Boolean = true,
                 focus: Boolean = true,
                 show: Boolean = true): Unit = {
    call(s"{backdrop: $backdrop, keyboard: $keyboard, focus: $focus, show: $show}")
  }
  def show(): Unit = call("'show'")
  def hide(): Unit = call("'hide'")
  def toggle(): Unit = call("'toggle'")
  def handleUpdate(): Unit = call("'handleUpdate'")
  def dispose(): Unit = call("'dispose'")
}


text:
require 'spec_helper'

describe CanCan::AccessDenied do
  describe 'with action, subject, and conditions' do
    before(:each) do
      @exception = CanCan::AccessDenied.new(nil, :some_action, :some_subject, :some_conditions)
    end

    it 'has action, subject, and conditions accessors' do
      expect(@exception.action).to eq(:some_action)
      expect(@exception.subject).to eq(:some_subject)
      expect(@exception.conditions).to eq(:some_conditions)
    end

    it 'has a changeable default message' do
      expect(@exception.message).to eq('You are not authorized to access this page.')
      @exception.default_message = 'Unauthorized!'
      expect(@exception.message).to eq('Unauthorized!')
    end

    it 'has debug information on inspect' do
      expect(@exception.inspect).to eq(
        '#<CanCan::AccessDenied action: :some_action, subject: :some_subject, conditions: :some_conditions>'
      )
    end
  end

  describe 'with only a message' do
    before(:each) do
      @exception = CanCan::AccessDenied.new('Access denied!')
    end

    it 'has nil action, subject, and conditions' do
      expect(@exception.action).to be_nil
      expect(@exception.subject).to be_nil
      expect(@exception.conditions).to be_nil
    end

    it 'has passed message' do
      expect(@exception.message).to eq('Access denied!')
    end
  end

  describe 'i18n in the default message' do
    after(:each) do
      I18n.backend = nil
    end

    it 'uses i18n for the default message' do
      I18n.backend.store_translations :en, unauthorized: { default: 'This is a different message' }
      @exception = CanCan::AccessDenied.new
      expect(@exception.message).to eq('This is a different message')
    end

    it 'defaults to a nice message' do
      @exception = CanCan::AccessDenied.new
      expect(@exception.message).to eq('You are not authorized to access this page.')
    end

    it 'does not use translation if a message is given' do
      @exception = CanCan::AccessDenied.new("Hey! You're not welcome here")
      expect(@exception.message).to eq("Hey! You're not welcome here")
      expect(@exception.message).to_not eq('You are not authorized to access this page.')
    end
  end
end


text:
"""Tests for base module of models package."""
import pytest
from backend.database import redis_db
from backend.models.base import BaseModel

def test_BaseModel_raises_TypeError():
    """It tests that BaseModel can't be instantiated directly."""
    with pytest.raises(TypeError):
        BaseModel()

def test_models_from_db(models, time):
    """It tests the models' method from db."""
    model, values, key = models
    redis_db.hmset(key, values)
    model.from_db(key)
    assert hasattr(model, 'time')
    assert hasattr(model, 'test1')
    assert hasattr(model, 'test2')
    assert hasattr(model, 'test3')
    assert hasattr(model, 'test4')

def test_models_from_db_many(models):
    """It tests the models' method from db with flag many."""
    # sbagliato da mettere a posto range for
    model, values, key = models
    expected = [i for i in range(5)]
    for j in range(5):
        values['test_many'] = j
        key = '{}{}'.format(key, j)
        redis_db.hmset(key, values)
    collection = model.from_db(many=True)
    for k, m in enumerate(collection):
        assert m.test_many == expected[k]
        assert isinstance(m.test_many, int)

def test_models_update_and_delete(models):
    """It tests the models' methods update and delete."""
    model, values, key = models
    model.from_dict(values)
    model.update_db()
    fields = values.keys()
    hash_keys = redis_db.hkeys(model.key())
    assert redis_db.hgetall(key)
    for key in hash_keys:
        assert key in fields
    model.delete()
    assert not redis_db.hgetall(model.key())


text:
Tutorials
=========

On this page you will find links to a series of tutorials to help get you
started with Crispy. They are largely based on tutorials kindly provided by
`Amélie Juhin <http://www-ext.impmc.upmc.fr/~juhin>`_. The tutorials are in no
particular order, so you can start with the one that interests you.
Nevertheless, to make things easier to follow, have a look at the quick tour of
the interface below.

.. toctree::
    :maxdepth: 1

    ti_l23_xas.rst
    ni_ligand_field
    fe_spin_transition

Crispy's main window is divided in three parts: the plotting panel (1), the
logging panel (2), and the Quanty module panel (3), as shown in the figure
below.

.. figure:: assets/main_window_annotated.png
    :align: center
    :width: 80 %

The buttons located on the top of the plotting panel can be used to change the
properties of the plot, e.g zoom, scale, aspect ration, color etc. The
displayed plots can also be saved using various file formats.

The progress of the calculation and eventual errors are displayed in the
logging panel.

The panel of the Quanty module has a vertical tab structure. The *General
Setup* tab is located at the top, and will always be displayed when Crispy is
started. Here you can select the element, charge, and symmetry of the absorbing
site. The type of experiment, edge, temperature, and magnetic field can also be
selected here.

.. figure:: assets/experimental_conditions.png
    :align: center
    :width: 35 %

Depending on the type of experiment selected above, the panel below will
display a single tab with the parameters of the *Absorption Energy* for a XAS
calculation, or two tabs, *Incident Energy* and *Energy Transfer*, for a RIXS
calculation.

.. figure:: assets/absorption_energy.png
    :align: center
    :width: 35 %

The parameters include the energy range and the number of points for the
calculated spectrum. Both *Lorentzian* and *Gaussian* functions can be used to
broaden the spectrum. The *Lorentzian* broadening supports more complex input
values. For example an energy dependent broadening can be specify by using two
FWHM values, one for lower energy part of the spectrum, and a second one for
the high energy part. This feature is only available for some of the available
edges. Additionally the energy for the transition point between the two FWHM
values can also be specified as a third parameter. This is by default the
middle of the absorption energy range. Finally, the wave and polarization
vectors can be specified.

At the bottom of the *General Setup* tab you can select the spectra to be
calculated.

.. figure:: assets/spectra.png
    :align: center
    :width: 35 %

In the *Hamiltonian Setup* tab you can change the parameters of the
semi-empirical model used in the calculation. The scale factors for the
Coulomb, exchange, and spin-orbit coupling integrals can be changed using a set
of three input boxes. Note that the scale factors are used to alter the values
of the Hartree---Fock integrals.

.. figure:: assets/scale_factors.png
    :align: center
    :width: 35 %

Below are two panels displaying the list of Hamiltonian terms and parameters.
The terms can be enabled using the tick box placed in front of the name.
Selecting the name of a term will display the parameters associated with it in
the panel below. Double-click on the *Value* or the *Scaling* column of a
parameter to change it.

.. figure:: assets/hamiltonian_parameters.png
    :align: center
    :width: 35 %

At the bottom of the panel is possible to specify the number of initial
Hamiltonian states to consider in the calculation. The maximum number is equal
to the number of states for the initial electronic configuration, e.g. 1 state
for a |d0| configuration, 10 states for a |d1| configuration etc. By default
the number of states considered is automatically determined based on the value
of Boltzmann factors at the selected temperature, i.e. only states which will
have a significant occupation at this temperature will be considered. Finally,
for multiconfigurational calculations it is possible to specify the number of
electronic configurations to consider.

.. figure:: assets/states_and_configurations.png
    :align: center
    :width: 35 %

Completed calculations are displayed in the *Results* tab. The plotting panel
will be automatically updated when the selected calculation changes.
Right-clicking will display a context menu with a list of possible actions,
e.g. saving, loading, removing etc.

.. figure:: assets/results.png
    :align: center
    :width: 35 %

At the bottom of the Quanty module panel and not part of the tab structure
present above, there are two buttons. They can be used to save the input file
in a different location and/or with a different name, and start the
calculation. Once the calculation starts the *Run* button will change into a
*Stop* button, which can be used at any time to interrupt Quanty's run.

.. figure:: assets/buttons.png
    :align: center
    :width: 35 %

.. |L2,3| replace:: L\ :sub:`2,3`\
.. |M4,5| replace:: M\ :sub:`4,5`\
.. |d0| replace:: d\ :sup:`0`\
.. |d1| replace:: d\ :sup:`1`\


text:
from __future__ import print_function
from __future__ import division

import os
import sys
import time

from collections import deque
from json import dumps
from platform import python_version
from pprint import pformat
from signal import signal, SIGTERM, SIGUSR1, SIGTSTP, SIGCONT
from subprocess import Popen
from threading import Event, Thread
from syslog import syslog, LOG_ERR, LOG_INFO, LOG_WARNING
from traceback import extract_tb, format_tb, format_stack

import py3status.docstrings as docstrings
from py3status.command import CommandServer
from py3status.events import Events
from py3status.helpers import print_stderr
from py3status.i3status import I3status
from py3status.parse_config import process_config
from py3status.module import Module
from py3status.profiling import profile
from py3status.version import version

LOG_LEVELS = {'error': LOG_ERR, 'warning': LOG_WARNING, 'info': LOG_INFO, }

DBUS_LEVELS = {'error': 'critical', 'warning': 'normal', 'info': 'low', }

CONFIG_SPECIAL_SECTIONS = [
    '.group_extras',
    '.module_groups',
    'general',
    'i3s_modules',
    'on_click',
    'order',
    'py3_modules',
    'py3status',
]

class Runner(Thread):
    """
    A Simple helper to run a module in a Thread so it is non-locking.
    """
    def __init__(self, module, py3_wrapper):
        Thread.__init__(self)
        self.daemon = True
        self.module = module
        self.py3_wrapper = py3_wrapper

    def run(self):
        try:
            self.module.run()
        except:
            self.py3_wrapper.report_exception('Runner')

class NoneSetting:
    """
    This class represents no setting in the config.
    """
    # this attribute is used to identify that this is a none setting
    none_setting = True

    def __repr__(self):
        # this is for output via module_test
        return 'None'

class Common:
    """
    This class is used to hold core functionality so that it can be shared more
    easily.  This allow us to run the module tests through the same code as
    when we are running for real.
    """

    def __init__(self, py3_wrapper):
        self.py3_wrapper = py3_wrapper
        self.none_setting = NoneSetting()
        self.config = py3_wrapper.config

    def get_config_attribute(self, name, attribute):
        """
        Look for the attribute in the config.  Start with the named module and
        then walk up through any containing group and then try the general
        section of the config.
        """

        # A user can set a param to None in the config to prevent a param
        # being used.  This is important when modules do something like
        #
        # color = self.py3.COLOR_MUTED or self.py3.COLOR_BAD
        config = self.config['py3_config']
        param = config[name].get(attribute, self.none_setting)
        if hasattr(param, 'none_setting') and name in config['.module_groups']:
            for module in config['.module_groups'][name]:
                if attribute in config.get(module, {}):
                    param = config[module].get(attribute)
                    break
        if hasattr(param, 'none_setting'):
            # check py3status config section
            param = config['py3status'].get(attribute, self.none_setting)
        if hasattr(param, 'none_setting'):
            # check py3status general section
            param = config['general'].get(attribute, self.none_setting)
        return param

    def report_exception(self, msg, notify_user=True, level='error',
                         error_frame=None):
        """
        Report details of an exception to the user.
        This should only be called within an except: block Details of the
        exception are reported eg filename, line number and exception type.

        Because stack trace information outside of py3status or it's modules is
        not helpful in actually finding and fixing the error, we try to locate
        the first place that the exception affected our code.

        Alternatively if the error occurs in a module via a Py3 call that
        catches and reports the error then we receive an error_frame and use
        that as the source of the error.

        NOTE: msg should not end in a '.' for consistency.
        """
        # Get list of paths that our stack trace should be found in.
        py3_paths = [os.path.dirname(__file__)]
        user_paths = self.config.get('include_paths', [])
        py3_paths += [os.path.abspath(path) + '/' for path in user_paths]
        traceback = None

        try:
            # We need to make sure to delete tb even if things go wrong.
            exc_type, exc_obj, tb = sys.exc_info()
            stack = extract_tb(tb)
            error_str = '{}: {}\n'.format(exc_type.__name__, exc_obj)
            traceback = [error_str]

            if error_frame:
                # The error occurred in a py3status module so the traceback
                # should be made to appear correct.  We caught the exception
                # but make it look as though we did not.
                traceback += format_stack(error_frame, 1) + format_tb(tb)
                filename = os.path.basename(error_frame.f_code.co_filename)
                line_no = error_frame.f_lineno
            else:
                # This is a none module based error
                traceback += format_tb(tb)
                # Find first relevant trace in the stack.
                # it should be in py3status or one of it's modules.
                found = False
                for item in reversed(stack):
                    filename = item[0]
                    for path in py3_paths:
                        if filename.startswith(path):
                            # Found a good trace
                            filename = os.path.basename(item[0])
                            line_no = item[1]
                            found = True
                            break
                    if found:
                        break
            # all done!  create our message.
            msg = '{} ({}) {} line {}.'.format(
                msg, exc_type.__name__, filename, line_no)
        except:
            # something went wrong report what we can.
            msg = '{}.'.format(msg)
        finally:
            # delete tb!
            del tb
        # log the exception and notify user
        self.py3_wrapper.log(msg, 'warning')
        if traceback:
            # if debug is not in the config  then we are at an early stage of
            # running py3status and logging is not yet available so output the
            # error to STDERR so it can be seen
            if 'debug' not in self.config:
                print_stderr('\n'.join(traceback))
            elif self.config.get('log_file'):
                self.py3_wrapper.log(''.join(['Traceback\n'] + traceback))
        if notify_user:
            self.py3_wrapper.notify_user(msg, level=level)

class Py3statusWrapper:
    """
    This is the py3status wrapper.
    """

    def __init__(self, options):
        """
        Useful variables we'll need.
        """
        self.config = {}
        self.i3bar_running = True
        self.last_refresh_ts = time.time()
        self.lock = Event()
        self.modules = {}
        self.notified_messages = set()
        self.options = options
        self.output_modules = {}
        self.py3_modules = []
        self.py3_modules_initialized = False
        self.running = True
        self.update_queue = deque()
        self.update_request = Event()

        # shared code
        common = Common(self)
        self.get_config_attribute = common.get_config_attribute
        self.report_exception = common.report_exception

        # these are used to schedule module updates
        self.timeout_add_queue = deque()
        self.timeout_due = None
        self.timeout_update_due = deque()
        self.timeout_queue = {}
        self.timeout_queue_lookup = {}
        self.timeout_keys = []

    def timeout_queue_add_module(self, module, cache_time=0):
        """
        Add a module to be run at a future time.
        """
        # add the info to the add queue.  We do this so that actually adding
        # the module is done in the core thread.
        self.timeout_add_queue.append((module, cache_time))
        # if the timeout_add_queue is not due to be processed until after this
        # update request is due then trigger an update now.
        if self.timeout_due is None or cache_time < self.timeout_due:
            self.update_request.set()

    def timeout_process_add_queue(self, module, cache_time):
        """
        Add a module to the timeout_queue if it is scheduled in the future or
        if it is due for an update immediately just trigger that.

        the timeout_queue is a dict with the scheduled time as the key and the
        value is a list of module instance names due to be updated at that
        point. An ordered list of keys is kept to allow easy checking of when
        updates are due.  A list is also kept of which modules are in the
        update_queue to save having to search for modules in it unless needed.
        """
        # If already set to update do nothing
        if module in self.timeout_update_due:
            return

        # remove if already in the queue
        key = self.timeout_queue_lookup.get(module)
        if key:
            queue_item = self.timeout_queue[key]
            queue_item.remove(module)
            if not queue_item:
                del self.timeout_queue[key]
                self.timeout_keys.remove(key)

        if cache_time == 0:
            # if cache_time is 0 we can just trigger the module update
            self.timeout_update_due.append(module)
            self.timeout_queue_lookup[module] = None
        else:
            # add the module to the timeout queue
            if cache_time not in self.timeout_keys:
                self.timeout_queue[cache_time] = set([module])
                self.timeout_keys.append(cache_time)
                # sort keys so earliest is first
                self.timeout_keys.sort()

                # when is next timeout due?
                try:
                    self.timeout_due = self.timeout_keys[0]
                except IndexError:
                    self.timeout_due = None
            else:
                self.timeout_queue[cache_time].add(module)
            # note that the module is in the timeout_queue
            self.timeout_queue_lookup[module] = cache_time

    def timeout_queue_process(self):
        """
        Check the timeout_queue and set any due modules to update.
        """
        # process any items that need adding to the queue
        while self.timeout_add_queue:
            self.timeout_process_add_queue(*self.timeout_add_queue.popleft())
        now = time.time()
        due_timeouts = []
        # find any due timeouts
        for timeout in self.timeout_keys:
            if timeout > now:
                break
            due_timeouts.append(timeout)

        if due_timeouts:
            # process them
            for timeout in due_timeouts:
                modules = self.timeout_queue[timeout]
                # remove from the queue
                del self.timeout_queue[timeout]
                self.timeout_keys.remove(timeout)

                for module in modules:
                    # module no longer in queue
                    del self.timeout_queue_lookup[module]
                    # tell module to update
                    self.timeout_update_due.append(module)

            # when is next timeout due?
            try:
                self.timeout_due = self.timeout_keys[0]
            except IndexError:
                self.timeout_due = None

        # run any modules that are due
        while self.timeout_update_due:
            module = self.timeout_update_due.popleft()

            if isinstance(module, Module):
                r = Runner(module, self)
                r.start()
            else:
                # i3status module
                module.update()

        # we return how long till we next need to process the timeout_queue
        if self.timeout_due is not None:
            return self.timeout_due - time.time()

    def get_config(self):
        """
        Create the py3status based on command line options we received.
        """
        # get home path
        home_path = os.path.expanduser('~')

        # defaults
        config = {
            'minimum_interval': 0.1,  # minimum module update interval
        }

        # include path to search for user modules
        config['include_paths'] = [
            '{}/.i3/py3status/'.format(home_path),
            '{}/i3status/py3status'.format(os.environ.get(
                'XDG_CONFIG_HOME', '{}/.config'.format(home_path))),
            '{}/i3/py3status'.format(os.environ.get(
                'XDG_CONFIG_HOME', '{}/.config'.format(home_path))),
        ]
        config['version'] = version

        # override configuration and helper variables
        options = self.options
        config['cache_timeout'] = options.cache_timeout
        config['debug'] = options.debug
        config['dbus_notify'] = options.dbus_notify
        config['gevent'] = options.gevent
        if options.include_paths:
            config['include_paths'] = options.include_paths
        # FIXME we allow giving interval as a float and then make it an int!
        config['interval'] = int(options.interval)
        config['log_file'] = options.log_file
        config['standalone'] = options.standalone
        config['i3status_config_path'] = options.i3status_conf
        if options.cli_command:
            config['cli_command'] = options.cli_command
        return config

    def gevent_monkey_patch_report(self):
        """
        Report effective gevent monkey patching on the logs.
        """
        try:
            import gevent.socket
            import socket
            if gevent.socket.socket is socket.socket:
                self.log('gevent monkey patching is active')
            else:
                self.notify_user('gevent monkey patching failed')
        except ImportError:
            self.notify_user(
                'gevent is not installed, monkey patching failed')

    def get_user_modules(self):
        """
        Search configured include directories for user provided modules.

        user_modules: {
            'weather_yahoo': ('~/i3/py3status/', 'weather_yahoo.py')
        }
        """
        user_modules = {}
        for include_path in self.config['include_paths']:
            include_path = os.path.abspath(include_path) + '/'
            if not os.path.isdir(include_path):
                continue
            for f_name in sorted(os.listdir(include_path)):
                if not f_name.endswith('.py'):
                    continue
                module_name = f_name[:-3]
                # do not overwrite modules if already found
                if module_name in user_modules:
                    pass
                user_modules[module_name] = (include_path, f_name)
        return user_modules

    def get_user_configured_modules(self):
        """
        Get a dict of all available and configured py3status modules
        in the user's i3status.conf.
        """
        user_modules = {}
        if not self.py3_modules:
            return user_modules
        for module_name, module_info in self.get_user_modules().items():
            for module in self.py3_modules:
                if module_name == module.split(' ')[0]:
                    include_path, f_name = module_info
                    user_modules[module_name] = (include_path, f_name)
        return user_modules

    def load_modules(self, modules_list, user_modules):
        """
        Load the given modules from the list (contains instance name) with
        respect to the user provided modules dict.

        modules_list: ['weather_yahoo paris', 'net_rate']
        user_modules: {
            'weather_yahoo': ('/etc/py3status.d/', 'weather_yahoo.py')
        }
        """
        for module in modules_list:
            # ignore already provided modules (prevents double inclusion)
            if module in self.modules:
                continue
            try:
                my_m = Module(module, user_modules, self)
                # only handle modules with available methods
                if my_m.methods:
                    self.modules[module] = my_m
                elif self.config['debug']:
                    self.log(
                        'ignoring module "{}" (no methods found)'.format(
                            module))
            except Exception:
                err = sys.exc_info()[1]
                msg = 'Loading module "{}" failed ({}).'.format(module, err)
                self.report_exception(msg, level='warning')

    def setup(self):
        """
        Setup py3status and spawn i3status/events/modules threads.
        """

        # SIGTSTP will be received from i3bar indicating that all output should
        # stop and we should consider py3status suspended.  It is however
        # important that any processes using i3 ipc should continue to receive
        # those events otherwise it can lead to a stall in i3.
        signal(SIGTSTP, self.i3bar_stop)
        # SIGCONT indicates output should be resumed.
        signal(SIGCONT, self.i3bar_start)

        # update configuration
        self.config.update(self.get_config())

        if self.config.get('cli_command'):
            self.handle_cli_command(self.config)
            sys.exit()

        # logging functionality now available
        # log py3status and python versions
        self.log('=' * 8)
        self.log('Starting py3status version {} python {}'.format(
            self.config['version'], python_version())
        )

        try:
            # if running from git then log the branch and last commit
            # we do this by looking in the .git directory
            git_path = os.path.join(os.path.dirname(__file__), '..', '.git')
            # branch
            with open(os.path.join(git_path, 'HEAD'), 'r') as f:
                out = f.readline()
            branch = '/'.join(out.strip().split('/')[2:])
            self.log('git branch: {}'.format(branch))
            # last commit
            log_path = os.path.join(git_path, 'logs', 'refs', 'heads', branch)
            with open(log_path, 'r') as f:
                out = f.readlines()[-1]
            sha = out.split(' ')[1][:7]
            msg = ':'.join(out.strip().split('\t')[-1].split(':')[1:])
            self.log('git commit: {}{}'.format(sha, msg))
        except:
            pass

        if self.config['debug']:
            self.log(
                'py3status started with config {}'.format(self.config))

        if self.config['gevent']:
            self.gevent_monkey_patch_report()

        # read i3status.conf
        config_path = self.config['i3status_config_path']
        self.config['py3_config'] = process_config(config_path, self)

        # setup i3status thread
        self.i3status_thread = I3status(self)

        # If standalone or no i3status modules then use the mock i3status
        # else start i3status thread.
        i3s_modules = self.config['py3_config']['i3s_modules']
        if self.config['standalone'] or not i3s_modules:
            self.i3status_thread.mock()
            i3s_mode = 'mocked'
        else:
            i3s_mode = 'started'
            self.i3status_thread.start()
            while not self.i3status_thread.ready:
                if not self.i3status_thread.is_alive():
                    # i3status is having a bad day, so tell the user what went
                    # wrong and do the best we can with just py3status modules.
                    err = self.i3status_thread.error
                    self.notify_user(err)
                    self.i3status_thread.mock()
                    i3s_mode = 'mocked'
                    break
                time.sleep(0.1)
        if self.config['debug']:
            self.log('i3status thread {} with config {}'.format(
                i3s_mode, self.config['py3_config']))

        # setup input events thread
        self.events_thread = Events(self)
        self.events_thread.daemon = True
        self.events_thread.start()
        if self.config['debug']:
            self.log('events thread started')

        # initialise the command server
        self.commands_thread = CommandServer(self)
        self.commands_thread.daemon = True
        self.commands_thread.start()
        if self.config['debug']:
            self.log('commands thread started')

        # suppress modules' ouput wrt issue #20
        if not self.config['debug']:
            sys.stdout = open('/dev/null', 'w')
            sys.stderr = open('/dev/null', 'w')

        # get the list of py3status configured modules
        self.py3_modules = self.config['py3_config']['py3_modules']

        # get a dict of all user provided modules
        user_modules = self.get_user_configured_modules()
        if self.config['debug']:
            self.log('user_modules={}'.format(user_modules))

        if self.py3_modules:
            # load and spawn i3status.conf configured modules threads
            self.load_modules(self.py3_modules, user_modules)

    def notify_user(self, msg, level='error', rate_limit=None, module_name=''):
        """
        Display notification to user via i3-nagbar or send-notify
        We also make sure to log anything to keep trace of it.

        NOTE: Message should end with a '.' for consistency.
        """
        dbus = self.config.get('dbus_notify')
        if dbus:
            # force msg to be a string
            msg = u'{}'.format(msg)
        else:
            msg = u'py3status: {}'.format(msg)
        if level != 'info' and module_name == '':
            fix_msg = u'{} Please try to fix this and reload i3wm (Mod+Shift+R)'
            msg = fix_msg.format(msg)
        # Rate limiting. If rate limiting then we need to calculate the time
        # period for which the message should not be repeated.  We just use
        # A simple chunked time model where a message cannot be repeated in a
        # given time period. Messages can be repeated more frequently but must
        # be in different time periods.

        limit_key = ''
        if rate_limit:
            try:
                limit_key = time.time() // rate_limit
            except TypeError:
                pass
        # We use a hash to see if the message is being repeated.  This is crude
        # and imperfect but should work for our needs.
        msg_hash = hash(u'{}#{}#{}'.format(module_name, limit_key, msg))
        if msg_hash in self.notified_messages:
            return
        else:
            self.log(msg, level)
            self.notified_messages.add(msg_hash)

        try:
            if dbus:
                # fix any html entities
                msg = msg.replace('&', '&')
                msg = msg.replace('<', '<')
                msg = msg.replace('>', '>')
                cmd = ['notify-send', '-u', DBUS_LEVELS.get(level, 'normal'),
                       '-t', '10000', 'py3status', msg]
            else:
                py3_config = self.config.get('py3_config', {})
                nagbar_font = py3_config.get('py3status', {}).get('nagbar_font')
                if nagbar_font:
                    cmd = ['i3-nagbar', '-f', nagbar_font, '-m', msg, '-t', level]
                else:
                    cmd = ['i3-nagbar', '-m', msg, '-t', level]
            Popen(cmd,
                  stdout=open('/dev/null', 'w'),
                  stderr=open('/dev/null', 'w'))
        except Exception as err:
            self.log('notify_user error: %s' % err)

    def stop(self):
        """
        Set the Event lock, this will break all threads' loops.
        """
        self.running = False
        # stop the command server
        try:
            self.commands_thread.kill()
        except:
            pass

        try:
            self.lock.set()
            if self.config['debug']:
                self.log('lock set, exiting')
            # run kill() method on all py3status modules
            for module in self.modules.values():
                module.kill()
        except:
            pass

    def refresh_modules(self, module_string=None, exact=True):
        """
        Update modules.
        if module_string is None all modules are refreshed
        if module_string then modules with the exact name or those starting
        with the given string depending on exact parameter will be refreshed.
        If a module is an i3status one then we refresh i3status.
        To prevent abuse, we rate limit this function to 100ms for full
        refreshes.
        """
        if not module_string:
            if time.time() > (self.last_refresh_ts + 0.1):
                self.last_refresh_ts = time.time()
            else:
                # rate limiting
                return
        update_i3status = False
        for name, module in self.output_modules.items():
            if (module_string is None or
                    (exact and name == module_string) or
                    (not exact and name.startswith(module_string))):
                if module['type'] == 'py3status':
                    if self.config['debug']:
                        self.log('refresh py3status module {}'.format(name))
                    module['module'].force_update()
                else:
                    if self.config['debug']:
                        self.log('refresh i3status module {}'.format(name))
                    update_i3status = True
        if update_i3status:
            self.i3status_thread.refresh_i3status()

    def sig_handler(self, signum, frame):
        """
        SIGUSR1 was received, the user asks for an immediate refresh of the bar
        """
        self.log('received USR1')
        self.refresh_modules()

    def terminate(self, signum, frame):
        """
        Received request to terminate (SIGTERM), exit nicely.
        """
        raise KeyboardInterrupt()

    def purge_module(self, module_name):
        """
        A module has been removed e.g. a module that had an error.
        We need to find any containers and remove the module from them.
        """
        containers = self.config['py3_config']['.module_groups']
        containers_to_update = set()
        if module_name in containers:
            containers_to_update.update(set(containers[module_name]))
        for container in containers_to_update:
            try:
                self.modules[container].module_class.items.remove(module_name)
            except ValueError:
                pass

    def notify_update(self, update, urgent=False):
        """
        Name or list of names of modules that have updated.
        """
        if not isinstance(update, list):
            update = [update]
        self.update_queue.extend(update)

        # if all our py3status modules are not ready to receive updates then we
        # don't want to get them to update.
        if not self.py3_modules_initialized:
            return

        # find containers that use the modules that updated
        containers = self.config['py3_config']['.module_groups']
        containers_to_update = set()
        for item in update:
            if item in containers:
                containers_to_update.update(set(containers[item]))
        # force containers to update
        for container in containers_to_update:
            container_module = self.output_modules.get(container)
            if container_module:
                # If the container registered a urgent_function then call it
                # if this update is urgent.
                if urgent and container_module.get('urgent_function'):
                    container_module['urgent_function'](update)
                # If a container has registered a content_function we use that
                # to see if the container needs to be updated.
                # We only need to update containers if their active content has
                # changed.
                if container_module.get('content_function'):
                    if set(update) & container_module['content_function']():
                        container_module['module'].force_update()
                else:
                    # we don't know so just update.
                    container_module['module'].force_update()

        # we need to update the output
        if self.update_queue:
            self.update_request.set()

    def log(self, msg, level='info'):
        """
        log this information to syslog or user provided logfile.
        """
        if not self.config.get('log_file'):
            # If level was given as a str then convert to actual level
            level = LOG_LEVELS.get(level, level)
            syslog(level, u'{}'.format(msg))
        else:
            # Binary mode so fs encoding setting is not an issue
            with open(self.config['log_file'], 'ab') as f:
                log_time = time.strftime("%Y-%m-%d %H:%M:%S")
                # nice formating of data structures using pretty print
                if isinstance(msg, (dict, list, set, tuple)):
                    msg = pformat(msg)
                    # if multiline then start the data output on a fresh line
                    # to aid readability.
                    if '\n' in msg:
                        msg = u'\n' + msg
                out = u'{} {} {}\n'.format(log_time, level.upper(), msg)
                try:
                    # Encode unicode strings to bytes
                    f.write(out.encode('utf-8'))
                except (AttributeError, UnicodeDecodeError):
                    # Write any byte strings straight to log
                    f.write(out)

    def create_output_modules(self):
        """
        Setup our output modules to allow easy updating of py3modules and
        i3status modules allows the same module to be used multiple times.
        """
        py3_config = self.config['py3_config']
        i3modules = self.i3status_thread.i3modules
        output_modules = self.output_modules
        # position in the bar of the modules
        positions = {}
        for index, name in enumerate(py3_config['order']):
            if name not in positions:
                positions[name] = []
            positions[name].append(index)

        # py3status modules
        for name in self.modules:
            if name not in output_modules:
                output_modules[name] = {}
                output_modules[name]['position'] = positions.get(name, [])
                output_modules[name]['module'] = self.modules[name]
                output_modules[name]['type'] = 'py3status'
                output_modules[name]['color'] = self.mappings_color.get(name)
        # i3status modules
        for name in i3modules:
            if name not in output_modules:
                output_modules[name] = {}
                output_modules[name]['position'] = positions.get(name, [])
                output_modules[name]['module'] = i3modules[name]
                output_modules[name]['type'] = 'i3status'
                output_modules[name]['color'] = self.mappings_color.get(name)

        self.output_modules = output_modules

    def create_mappings(self, config):
        """
        Create any mappings needed for global substitutions eg. colors
        """
        mappings = {}
        for name, cfg in config.items():
            # Ignore special config sections.
            if name in CONFIG_SPECIAL_SECTIONS:
                continue
            color = self.get_config_attribute(name, 'color')
            if hasattr(color, 'none_setting'):
                color = None
            mappings[name] = color
        # Store mappings for later use.
        self.mappings_color = mappings

    def process_module_output(self, module):
        """
        Process the output for a module and return a json string representing it.
        Color processing occurs here.
        """
        outputs = module['module'].get_latest()
        color = module['color']
        if color:
            for output in outputs:
                # Color: substitute the config defined color
                if 'color' not in output:
                    output['color'] = color
        # Create the json string output.
        return ','.join([dumps(x) for x in outputs])

    def i3bar_stop(self, signum, frame):
        self.i3bar_running = False
        # i3status should be stopped
        self.i3status_thread.suspend_i3status()
        self.sleep_modules()

    def i3bar_start(self, signum, frame):
        self.i3bar_running = True
        self.wake_modules()

    def sleep_modules(self):
        # Put all py3modules to sleep so they stop updating
        for module in self.output_modules.values():
            if module['type'] == 'py3status':
                module['module'].sleep()

    def wake_modules(self):
        # Wake up all py3modules.
        for module in self.output_modules.values():
            if module['type'] == 'py3status':
                module['module'].wake()

    @profile
    def run(self):
        """
        Main py3status loop, continuously read from i3status and modules
        and output it to i3bar for displaying.
        """
        # SIGUSR1 forces a refresh of the bar both for py3status and i3status,
        # this mimics the USR1 signal handling of i3status (see man i3status)
        signal(SIGUSR1, self.sig_handler)
        signal(SIGTERM, self.terminate)

        # initialize usage variables
        py3_config = self.config['py3_config']

        # prepare the color mappings
        self.create_mappings(py3_config)

        # self.output_modules needs to have been created before modules are
        # started.  This is so that modules can do things like register their
        # content_function.
        self.create_output_modules()

        # Some modules need to be prepared before they can run
        # eg run their post_config_hook
        for module in self.modules.values():
            module.prepare_module()

        # modules can now receive updates
        self.py3_modules_initialized = True

        # start modules
        for module in self.modules.values():
            module.start_module()

        # this will be our output set to the correct length for the number of
        # items in the bar
        output = [None] * len(py3_config['order'])

        write = sys.__stdout__.write
        flush = sys.__stdout__.flush

        # start our output
        header = {
            'version': 1,
            'click_events': True,
            'stop_signal': SIGTSTP
        }
        write(dumps(header))
        write('\n[[]\n')

        update_due = None
        # main loop
        while True:
            # process the timeout_queue and get interval till next update due
            update_due = self.timeout_queue_process()

            # wait until an update is requested
            if self.update_request.wait(timeout=update_due):
                # event was set so clear it
                self.update_request.clear()

            while not self.i3bar_running:
                time.sleep(0.1)

            # check if an update is needed
            if self.update_queue:
                while (len(self.update_queue)):
                    module_name = self.update_queue.popleft()
                    module = self.output_modules[module_name]
                    out = self.process_module_output(module)

                    for index in module['position']:
                        # store the output as json
                        output[index] = out

                # build output string
                out = ','.join([x for x in output if x])
                # dump the line to stdout
                write(',[{}]\n'.format(out))
                flush()

    def handle_cli_command(self, config):
        """Handle a command from the CLI.
        """
        cmd = config['cli_command']
        # aliases
        if cmd[0] in ['mod', 'module', 'modules']:
            cmd[0] = 'modules'

        # allowed cli commands
        if cmd[:2] in (['modules', 'list'], ['modules', 'details']):
            docstrings.show_modules(config, cmd[1:])
        # docstring formatting and checking
        elif cmd[:2] in (['docstring', 'check'], ['docstring', 'update']):
            if cmd[1] == 'check':
                show_diff = len(cmd) > 2 and cmd[2] == 'diff'
                if show_diff:
                    mods = cmd[3:]
                else:
                    mods = cmd[2:]
                docstrings.check_docstrings(show_diff, config, mods)
            if cmd[1] == 'update':
                if len(cmd) < 3:
                    print_stderr('Error: you must specify what to update')
                    sys.exit(1)

                if cmd[2] == 'modules':
                    docstrings.update_docstrings()
                else:
                    docstrings.update_readme_for_modules(cmd[2:])
        elif cmd[:2] in (['modules', 'enable'], ['modules', 'disable']):
            # TODO: to be implemented
            pass
        else:
            print_stderr('Error: unknown command')
            sys.exit(1)


text:
package com.davidflex.supermarket.ontologies.company;

import com.davidflex.supermarket.ontologies.shop.ShopOntologyVocabulary;

public interface CompanyOntolagyVocabulary extends ShopOntologyVocabulary {
    String ONTOLOGY_NAME = "CompanyOntolagy";
}


text:
class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(interval -> interval[0]));
        LinkedList<int[]> result = new LinkedList<>();

        for (int[] interval : intervals) {
            if (result.size() == 0) {
                result.add(interval);
            } else {
                int[] last = result.getLast();
                if (last[1] < interval[0]) {
                    result.add(interval);
                } else {
                    last[1] = Math.max(last[1], interval[1]);
                }
            }
        }

        return result.toArray(new int[result.size()][]);
    }
}
//Runtime: 7 ms, faster than 44.83% of Java online submissions for Merge Intervals.
//Memory Usage: 41.2 MB, less than 98.82% of Java online submissions for Merge Intervals.


text:
module ExpertSenderApi
  VERSION = '0.0.1'
end


text:
package net.soliddesign.iumpr.bus;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Objects;
import java.util.logging.Level;
import java.util.stream.Collectors;

import net.soliddesign.iumpr.IUMPR;

/**
 * Sends a Packet containing an id with data from a source onto the bus
 *
 * @author Joe Batt (joe@soliddesign.net)
 *
 */
public class Packet {

    /**
     * The indication that a packet was transmitted
     */
    public static final String TX = " (TX)";

    public static Packet create(int id, int source, boolean transmitted, int... data) {
        return new Packet(6, id, source, transmitted, data);
    }

    /**
     * Creates an instance of Packet
     *
     * @param id
     *            the ID of the packet
     * @param source
     *            the source address of the packet
     * @param bytes
     *            the data bytes of the packet
     * @return Packet
     */
    public static Packet create(int id, int source, byte... bytes) {
        return create(6, id, source, false, bytes);
    }

    /**
     * Creates an instance of Packet
     *
     * @param id
     *            the ID of the packet
     * @param source
     *            the source address of the packet
     * @param data
     *            the data of the packet
     * @return Packet
     */
    public static Packet create(int id, int source, int... data) {
        return create(id, source, false, data);
    }

    /**
     * Creates an instance of Packet
     *
     * @param priority
     *            the priority of the packet
     * @param id
     *            the ID of the packet
     * @param source
     *            the source address of the packet
     * @param transmitted
     *            indicates the packet was sent by the application
     * @param bytes
     *            the data bytes of the packet
     * @return Packet
     */
    public static Packet create(int priority, int id, int source, boolean transmitted, byte... bytes) {
        int[] data = new int[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            data[i] = bytes[i];
        }
        return new Packet(priority, id, source, transmitted, data);
    }

    /**
     * Converts the value produced by Packet.toString() back into a Packet
     *
     * @param string
     *            the {@link String} to parse
     * @return a Packet or null if the string could not be parsed
     */
    public static Packet parse(String string) {
        try {
            boolean tx = string.contains(TX);
            if (tx) {
                string = string.replace(TX, "");
            }
            String[] parts = string.split(" ");
            int header = Integer.parseInt(parts[0].trim(), 16);
            int priority = (header & 0xFF000000) >> 26;
            int id = (header & 0xFFFF00) >> 8;
            int source = header & 0xFF;

            byte[] bytes = new byte[parts.length - 1];
            for (int i = 1; i < parts.length; i++) {
                bytes[i - 1] = (byte) (Integer.parseInt(parts[i].trim(), 16) & 0xFF);
            }

            return Packet.create(priority, id, source, tx, bytes);
        } catch (Exception e) {
            IUMPR.getLogger().log(Level.SEVERE, string + " could not be parsed into a Packet", e);
        }
        return null;
    }

    private final int[] data;

    private final int id;

    private final int priority;

    private final int source;

    private final LocalDateTime timestamp;

    private final boolean transmitted;

    /**
     * Creates a Packet
     *
     * @param priority
     *            the priority of the packet
     * @param id
     *            the ID of the packet
     * @param source
     *            the source address of the packet
     * @param transmitted
     *            indicates the packet was sent by the application
     * @param data
     *            the data of the packet
     */
    private Packet(int priority, int id, int source, boolean transmitted, int... data) {
        timestamp = LocalDateTime.now();
        this.priority = priority;
        this.id = id;
        this.source = source;
        this.transmitted = transmitted;
        this.data = new int[data.length];
        for (int i = 0; i < data.length; i++) {
            this.data[i] = (0xFF & data[i]);
        }
    }

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

        Packet that = (Packet) obj;
        return id == that.id && priority == that.priority && source == that.source && transmitted == that.transmitted
                && Objects.deepEquals(data, that.data);
    }

    /**
     * Returns one byte (8-bits) from the data at the given index
     *
     * @param i
     *            the index
     * @return int
     */
    public int get(int i) {
        return data[i];
    }

    /**
     * Returns two bytes (16-bits) from the data at the given index and index+1
     *
     * @param i
     *            the index
     * @return int
     */
    public int get16(int i) {
        return (data[i + 1] << 8) | data[i];
    }

    /**
     * Returns two bytes (16-bits) from the data in Big-endian format at the
     * given index and index+1
     *
     * @param i
     *            the index
     * @return int
     */
    public int get16Big(int i) {
        return (data[i] << 8) | data[i + 1];
    }

    /**
     * Returns three bytes (24-bits) from the data at the given index, index+1
     * and index+2
     *
     * @param i
     *            the index
     * @return int
     */
    public int get24(int i) {
        return (data[i + 2] << 16) | (data[i + 1] << 8) | data[i];
    }

    /**
     * Returns three bytes (24-bits) from the data in Big-endian format at the
     * given index, index+1, and index+2
     *
     * @param i
     *            the index
     * @return int
     */
    public int get24Big(int i) {
        return (data[i] << 16) | (data[i + 1] << 8) | data[i + 2];
    }

    /**
     * Returns four bytes (32-bits) from the data at the given index, index+1,
     * index+2, and index+3
     *
     * @param i
     *            the index
     * @return int
     */
    public long get32(int i) {
        return (data[i + 3] << 24) | (data[i + 2] << 16) | (data[i + 1] << 8) | data[i];
    }

    /**
     * Returns four bytes (32-bits) from the data in Big-endian format at the
     * given index, index+1, index+2, and index+3
     *
     * @param i
     *            the index
     * @return int
     */
    public long get32Big(int i) {
        return (data[i] << 24) | (data[i + 1] << 16) | (data[i + 2] << 8) | data[i + 3];
    }

    /**
     * Returns the data as an array of bytes
     *
     * @return byte[]
     */
    public byte[] getBytes() {
        byte[] bytes = new byte[data.length];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) data[i];
        }
        return bytes;
    }

    /**
     * Returns the data from the beginIndex to the endIndex (inclusive).
     *
     * @param beginIndex
     *            the first data value to return
     * @param endIndex
     *            the last data value to return
     * @return int[]
     */
    public int[] getData(int beginIndex, int endIndex) {
        return Arrays.copyOfRange(data, beginIndex, endIndex);
    }

    /**
     * Returns the ID of the packet
     *
     * @return int
     */
    public int getId() {
        return id;
    }

    /**
     * Returns the total number of data bytes in the packet
     *
     * @return int
     */
    public int getLength() {
        return data.length;
    }

    /**
     * Returns the priority of the packet
     *
     * @return int
     */
    public int getPriority() {
        return priority;
    }

    /**
     * Returns the source address of the packet
     *
     * @return int
     */
    public int getSource() {
        return source;
    }

    /**
     * Returns the Time the packet was received
     *
     * @return {@link LocalDateTime}
     */
    public LocalDateTime getTimestamp() {
        return timestamp;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, priority, source, transmitted, Arrays.hashCode(data));
    }

    /**
     * Returns true if this packet was transmitted by the application
     *
     * @return boolean
     */
    public boolean isTransmitted() {
        return transmitted;
    }

    @Override
    public String toString() {
        return toString(null);
    }

    /**
     * Creates the {@link String} of the Packet including the time received
     * formatted by the {@link DateTimeFormatter}. If the formatter is null, the
     * time is not included
     *
     * @param formatter
     *            the {@link DateTimeFormatter} to format the time received
     * @return a {@link String}
     */
    public String toString(DateTimeFormatter formatter) {
        return (formatter == null ? "" : (formatter.format(timestamp) + " "))
                + String.format("%06X%02X %s", priority << 18 | id, source,
                        Arrays.stream(data).mapToObj(x -> String.format("%02X", x)).collect(Collectors.joining(" "))
                                + (transmitted ? TX : ""));
    }
}


text:
<html>
<body>
<applet code="Gravity.class" width="100%" height="100%">
<param name="img" value="storey$groundfloor$tick$cross$boyWithSling$earth2$moon$apple1$newton1$branch$solarsystem$galaxies$ballthrow$ball$">

</body>
</applet></html>


text:
/*
 * Do not modify this file. This file is generated from the datapipeline-2012-10-29.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.DataPipeline.Model
{
    ///
    /// Contains a logical operation for comparing the value of a field with a specified value.
    ///
    public partial class Operator
    {
        private OperatorType _type;
        private List<string> _values = new List<string>();

        ///
        /// Gets and sets the property Type.
        /// <para>
        ///  The logical operation to be performed: equal (EQ), equal reference (REF_EQ),
        /// less than or equal (LE), greater than or equal (GE), or
        /// between (BETWEEN). Equal reference (REF_EQ) can be used
        /// only with reference fields. The other comparison types can be used only with String
        /// fields. The comparison types you can use apply only to certain object fields, as detailed
        /// below.
        /// </para>
        ///
        /// <para>
        ///  The comparison operators EQ and REF_EQ act on the following fields:
        /// </para>
        ///

name

@sphere

parent

@componentParent

@instanceParent

        ///
@status

@scheduledStartTime

@scheduledEndTime

@actualStartTime

        ///
@actualEndTime

        /// <para>
        ///  The comparison operators GE, LE, and BETWEEN
        /// act on the following fields:
        /// </para>
        ///

@scheduledStartTime

@scheduledEndTime

@actualStartTime

        ///
@actualEndTime

        /// <para>
        /// Note that fields beginning with the at sign (@) are read-only and set by the web service.
        /// When you name fields, you should choose names containing only alpha-numeric values,
        /// as symbols may be reserved by AWS Data Pipeline. User-defined fields that you add
        /// to a pipeline should prefix their name with the string "my".
        /// </para>
        ///
        public OperatorType Type
        {
            get { return this._type; }
            set { this._type = value; }
        }

        // Check to see if Type property is set
        internal bool IsSetType()
        {
            return this._type != null;
        }

        ///
        /// Gets and sets the property Values.
        /// <para>
        /// The value that the actual field value will be compared with.
        /// </para>
        ///
        public List<string> Values
        {
            get { return this._values; }
            set { this._values = value; }
        }

        // Check to see if Values property is set
        internal bool IsSetValues()
        {
            return this._values != null && this._values.Count > 0;
        }

    }
}


text:
[![Stories in Ready](https://badge.waffle.io/amdh/202_Project1_Team16.png?label=ready&title=Ready)](http://waffle.io/amdh/202_Project1_Team16)
[![Stories in In Development](https://badge.waffle.io/amdh/202_Project1_Team16.png?label=readytitle=In%20Progress)](http://waffle.io/amdh/202_Project1_Team16)
[![Stories in In Testing](https://badge.waffle.io/amdh/202_Project1_Team16.png?label=ready&title=In%20Testing)](http://waffle.io/amdh/202_Project1_Team16)
[![Stories in In Review](https://badge.waffle.io/amdh/202_Project1_Team16.png?label=ready&title=In%20Review)](http://waffle.io/amdh/202_Project1_Team16)

# Team :
Aditya Parashar
Amruta Dhondage
Arpita Dixit
Chaya Malik
Jay Nirgudkar

Project Description :

Design a multiplayer game based on FSA.

Implementing FSA for treasure hunt.

image:: https://graphs.waffle.io/amdh/202_Project1_Team16/throughput.svg
 :target: https://waffle.io/amdh/202_Project1_Team16/metrics/throughput
 :alt: 'Throughput Graph'

 {<img alt='Throughput Graph' src='https://graphs.waffle.io/amdh/202_Project1_Team16/throughput.svg' />}[https://waffle.io/amdh/202_Project1_Team16/metrics/throughput]

 Discussion on the flow of cloud application:

## License

TreasureHunt is released under the [MIT License](https://github.com/amdh/202_Project1_Team16/blob/master/LICENSE.md).


text:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

--
-- Database: `openpost`
--

-- --------------------------------------------------------

--
-- Table structure for table `Authors`
--

CREATE TABLE `Authors` (
  `Id` varchar(22) COLLATE utf8mb4_bin NOT NULL,
  `AvatarUrl` longtext COLLATE utf8mb4_bin,
  `DisplayName` longtext COLLATE utf8mb4_bin,
  `Email` longtext COLLATE utf8mb4_bin,
  `PlatformId` longtext COLLATE utf8mb4_bin,
  `RowVersion` longblob,
  `SourcePlatformId` varchar(22) COLLATE utf8mb4_bin DEFAULT NULL,
  `TokenId` varchar(22) COLLATE utf8mb4_bin DEFAULT NULL,
  `IsAnonymous` bit(1) NOT NULL DEFAULT b'0',
  `WebSite` longtext COLLATE utf8mb4_bin
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- --------------------------------------------------------

--
-- Table structure for table `Comments`
--

CREATE TABLE `Comments` (
  `Id` varchar(22) COLLATE utf8mb4_bin NOT NULL,
  `AuthorId` varchar(22) COLLATE utf8mb4_bin DEFAULT NULL,
  `Content` longtext COLLATE utf8mb4_bin,
  `Depth` tinyint(3) UNSIGNED NOT NULL,
  `PageId` varchar(22) COLLATE utf8mb4_bin DEFAULT NULL,
  `ParentId` varchar(22) COLLATE utf8mb4_bin DEFAULT NULL,
  `PostDate` datetime(6) NOT NULL,
  `RowVersion` longblob,
  `Title` longtext COLLATE utf8mb4_bin
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- --------------------------------------------------------

--
-- Table structure for table `Pages`
--

CREATE TABLE `Pages` (
  `Id` varchar(22) COLLATE utf8mb4_bin NOT NULL,
  `CommentsCount` int(11) NOT NULL,
  `PublicIdentifier` longtext COLLATE utf8mb4_bin NOT NULL,
  `SourcePlatformId` varchar(22) COLLATE utf8mb4_bin NOT NULL,
  `AllowAnonymousComments` bit(1) NOT NULL DEFAULT b'0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- --------------------------------------------------------

--
-- Table structure for table `Platforms`
--

CREATE TABLE `Platforms` (
  `Id` varchar(22) COLLATE utf8mb4_bin NOT NULL,
  `Name` longtext COLLATE utf8mb4_bin,
  `ProviderApi` longtext COLLATE utf8mb4_bin,
  `ProviderAuthKey` longtext COLLATE utf8mb4_bin,
  `ProviderAuthPassword` longtext COLLATE utf8mb4_bin,
  `RowVersion` longblob
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- --------------------------------------------------------

--
-- Table structure for table `__EFMigrationsHistory`
--

CREATE TABLE `__EFMigrationsHistory` (
  `MigrationId` varchar(95) COLLATE utf8mb4_bin NOT NULL,
  `ProductVersion` varchar(32) COLLATE utf8mb4_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

--
-- Dumping data for table `__EFMigrationsHistory`
--

INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`) VALUES
('20170401161021_Initial', '1.1.1'),
('20170405171208_AnonymousComments', '1.1.1');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `Authors`
--
ALTER TABLE `Authors`
  ADD PRIMARY KEY (`Id`),
  ADD KEY `IX_Authors_SourcePlatformId` (`SourcePlatformId`);

--
-- Indexes for table `Comments`
--
ALTER TABLE `Comments`
  ADD PRIMARY KEY (`Id`),
  ADD KEY `IX_Comments_AuthorId` (`AuthorId`),
  ADD KEY `IX_Comments_PageId` (`PageId`),
  ADD KEY `IX_Comments_ParentId` (`ParentId`);

--
-- Indexes for table `Pages`
--
ALTER TABLE `Pages`
  ADD PRIMARY KEY (`Id`),
  ADD KEY `IX_Pages_SourcePlatformId` (`SourcePlatformId`);

--
-- Indexes for table `Platforms`
--
ALTER TABLE `Platforms`
  ADD PRIMARY KEY (`Id`);

--
-- Indexes for table `__EFMigrationsHistory`
--
ALTER TABLE `__EFMigrationsHistory`
  ADD PRIMARY KEY (`MigrationId`);

--
-- Constraints for dumped tables
--

--
-- Constraints for table `Authors`
--
ALTER TABLE `Authors`
  ADD CONSTRAINT `FK_Authors_Platforms_SourcePlatformId` FOREIGN KEY (`SourcePlatformId`) REFERENCES `Platforms` (`Id`) ON DELETE NO ACTION;

--
-- Constraints for table `Comments`
--
ALTER TABLE `Comments`
  ADD CONSTRAINT `FK_Comments_Authors_AuthorId` FOREIGN KEY (`AuthorId`) REFERENCES `Authors` (`Id`) ON DELETE NO ACTION,
  ADD CONSTRAINT `FK_Comments_Comments_ParentId` FOREIGN KEY (`ParentId`) REFERENCES `Comments` (`Id`) ON DELETE CASCADE,
  ADD CONSTRAINT `FK_Comments_Pages_PageId` FOREIGN KEY (`PageId`) REFERENCES `Pages` (`Id`) ON DELETE CASCADE;

--
-- Constraints for table `Pages`
--
ALTER TABLE `Pages`
  ADD CONSTRAINT `FK_Pages_Platforms_SourcePlatformId` FOREIGN KEY (`SourcePlatformId`) REFERENCES `Platforms` (`Id`) ON DELETE CASCADE;


text: Sources for various I2C and other sensors


text:
<?php

/**
 * SectionType
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    sf_sandbox
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class SectionType extends BaseSectionType
{

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<channel name="displays" version="1.0">
  <property name="Notify" type="bool" value="true"/>
  <property name="Default" type="empty">
    <property name="LVDS" type="string" value="Laptop">
      <property name="Active" type="bool" value="true"/>
      <property name="Resolution" type="string" value="1280x720"/>
      <property name="RefreshRate" type="double" value="59.855126"/>
      <property name="Rotation" type="int" value="0"/>
      <property name="Reflection" type="string" value="0"/>
      <property name="Primary" type="bool" value="false"/>
      <property name="Position" type="empty">
        <property name="X" type="int" value="0"/>
        <property name="Y" type="int" value="0"/>
      </property>
    </property>
  </property>
</channel>