text:
require 'thrift'
require_relative 'article_manager_types'

module ColdBlossom
  module Darius
    module ArticleManager
      class Client
        include ::Thrift::Client

        def health()
          send_health()
          return recv_health()
        end

        def send_health()
          send_message('health', Health_args)
        end

        def recv_health()
          result = receive_message(Health_result)
          return result.success unless result.success.nil?
          raise ::Thrift::ApplicationException.new(::Thrift::ApplicationException::MISSING_RESULT, 'health failed: unknown result')
        end

        def version()
          send_version()
          return recv_version()
        end

        def send_version()
          send_message('version', Version_args)
        end

        def recv_version()
          result = receive_message(Version_result)
          return result.success unless result.success.nil?
          raise ::Thrift::ApplicationException.new(::Thrift::ApplicationException::MISSING_RESULT, 'version failed: unknown result')
        end

        def getDocument(request)
          send_getDocument(request)
          return recv_getDocument()
        end

        def send_getDocument(request)
          send_message('getDocument', GetDocument_args, :request => request)
        end

        def recv_getDocument()
          result = receive_message(GetDocument_result)
          return result.success unless result.success.nil?
          raise result.e unless result.e.nil?
          raise ::Thrift::ApplicationException.new(::Thrift::ApplicationException::MISSING_RESULT, 'getDocument failed: unknown result')
        end

        def getArchive(request)
          send_getArchive(request)
          return recv_getArchive()
        end

        def send_getArchive(request)
          send_message('getArchive', GetArchive_args, :request => request)
        end

        def recv_getArchive()
          result = receive_message(GetArchive_result)
          return result.success unless result.success.nil?
          raise result.e unless result.e.nil?
          raise ::Thrift::ApplicationException.new(::Thrift::ApplicationException::MISSING_RESULT, 'getArchive failed: unknown result')
        end

      end

      class Processor
        include ::Thrift::Processor

        def process_health(seqid, iprot, oprot)
          args = read_args(iprot, Health_args)
          result = Health_result.new()
          result.success = @handler.health()
          write_result(result, oprot, 'health', seqid)
        end

        def process_version(seqid, iprot, oprot)
          args = read_args(iprot, Version_args)
          result = Version_result.new()
          result.success = @handler.version()
          write_result(result, oprot, 'version', seqid)
        end

        def process_getDocument(seqid, iprot, oprot)
          args = read_args(iprot, GetDocument_args)
          result = GetDocument_result.new()
          begin
            result.success = @handler.getDocument(args.request)
          rescue ::ColdBlossom::Darius::ServiceException => e
            result.e = e
          end
          write_result(result, oprot, 'getDocument', seqid)
        end

        def process_getArchive(seqid, iprot, oprot)
          args = read_args(iprot, GetArchive_args)
          result = GetArchive_result.new()
          begin
            result.success = @handler.getArchive(args.request)
          rescue ::ColdBlossom::Darius::ServiceException => e
            result.e = e
          end
          write_result(result, oprot, 'getArchive', seqid)
        end

      end

      # HELPER FUNCTIONS AND STRUCTURES

      class Health_args
        include ::Thrift::Struct, ::Thrift::Struct_Union

        FIELDS = {

        }

        def struct_fields; FIELDS; end

        def validate
        end

        ::Thrift::Struct.generate_accessors self
      end

      class Health_result
        include ::Thrift::Struct, ::Thrift::Struct_Union
        SUCCESS = 0

        FIELDS = {
          SUCCESS => {:type => ::Thrift::Types::STRING, :name => 'success'}
        }

        def struct_fields; FIELDS; end

        def validate
        end

        ::Thrift::Struct.generate_accessors self
      end

      class Version_args
        include ::Thrift::Struct, ::Thrift::Struct_Union

        FIELDS = {

        }

        def struct_fields; FIELDS; end

        def validate
        end

        ::Thrift::Struct.generate_accessors self
      end

      class Version_result
        include ::Thrift::Struct, ::Thrift::Struct_Union
        SUCCESS = 0

        FIELDS = {
          SUCCESS => {:type => ::Thrift::Types::LIST, :name => 'success', :element => {:type => ::Thrift::Types::I32}}
        }

        def struct_fields; FIELDS; end

        def validate
        end

        ::Thrift::Struct.generate_accessors self
      end

      class GetDocument_args
        include ::Thrift::Struct, ::Thrift::Struct_Union
        REQUEST = 1

        FIELDS = {
          REQUEST => {:type => ::Thrift::Types::STRUCT, :name => 'request', :class => ::ColdBlossom::Darius::GetDocumentRequest}
        }

        def struct_fields; FIELDS; end

        def validate
        end

        ::Thrift::Struct.generate_accessors self
      end

      class GetDocument_result
        include ::Thrift::Struct, ::Thrift::Struct_Union
        SUCCESS = 0
        E = 1

        FIELDS = {
          SUCCESS => {:type => ::Thrift::Types::STRUCT, :name => 'success', :class => ::ColdBlossom::Darius::GetDocumentResult},
          E => {:type => ::Thrift::Types::STRUCT, :name => 'e', :class => ::ColdBlossom::Darius::ServiceException}
        }

        def struct_fields; FIELDS; end

        def validate
        end

        ::Thrift::Struct.generate_accessors self
      end

      class GetArchive_args
        include ::Thrift::Struct, ::Thrift::Struct_Union
        REQUEST = 1

        FIELDS = {
          REQUEST => {:type => ::Thrift::Types::STRUCT, :name => 'request', :class => ::ColdBlossom::Darius::GetArchiveRequest}
        }

        def struct_fields; FIELDS; end

        def validate
        end

        ::Thrift::Struct.generate_accessors self
      end

      class GetArchive_result
        include ::Thrift::Struct, ::Thrift::Struct_Union
        SUCCESS = 0
        E = 1

        FIELDS = {
          SUCCESS => {:type => ::Thrift::Types::STRUCT, :name => 'success', :class => ::ColdBlossom::Darius::GetArchiveResult},
          E => {:type => ::Thrift::Types::STRUCT, :name => 'e', :class => ::ColdBlossom::Darius::ServiceException}
        }

        def struct_fields; FIELDS; end

        def validate
        end

        ::Thrift::Struct.generate_accessors self
      end

    end

  end
end


text:
const categories = [
    { text: 'Fruit', domain: ['Apples', 'Bananas'] },
    { text: 'Meat', domain: ['Sausages'] },
    { text: 'Drink', domain: ['Soda'] },
    { text: 'Vegetables', domain: ['Pickles', 'Aubergines'] }
];

const bandContainer = document.querySelector('#band-container');

const domain = categories.reduce((acc, curr) => [...acc, ...curr.domain], []);

const bandScale = d3.scaleBand().domain(domain);

const bandAxis = fc.axisOrdinalBottom(bandScale).tickPadding(5);

d3.select(bandContainer)
    .on('draw', () => {
        d3.select(bandContainer)
            .select('svg')
            .call(bandAxis);
    })
    .on('measure', () => {
        const { width } = event.detail;
        bandScale.range([0, width]);
    });

bandContainer.requestRedraw();

const categoryContainer = document.querySelector('#category-container');

const map = value => categories.find(m => m.text === value).domain;

const categorisedScale = () => {
    const customScale = value => {
        const values = map(value);
        return values.reduce((sum, d) => sum + bandScale(d), 0) / values.length;
    };
    customScale.ticks = () => categories.map(c => c.text);
    fc.rebindAll(customScale, bandScale, fc.exclude('ticks'));
    return customScale;
};

const categoryAxis = fc
    .axisOrdinalBottom(categorisedScale())
    .tickPadding(5)
    .tickOffset(d => (map(d).length * bandScale.step()) / 2);

d3.select(categoryContainer).on('draw', () => {
    d3.select(categoryContainer)
        .select('svg')
        .call(categoryAxis);
});

categoryContainer.requestRedraw();

redpajama_set_name: RedPajamaGithub


text:
ActiveRecord::Migration.verbose = false

ActiveRecord::Schema.define do

  create_table :categories, :force => true do |t|
    t.string :name
  end

  create_table :posts, :force => true do |t|
    t.text :body
    t.integer :category_id
    t.string :title
  end

  create_table :products, :force => true do |t|
    t.string :name
    t.integer :price
  end

  create_table :paypal_orders, :force => true do |t|
    t.integer :paypal_id
  end

  create_table :users, :force => true do |t|
    t.string :email
    t.string :login
    t.string :name
    t.integer :paypal_id
  end

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProjectData;
using Approve.Common;
using ProjectBLL;
using System.Data;
using Approve.RuleCenter;
using System.Text;
using System.Collections;
using System.Web.UI.HtmlControls;

public partial class JNCLEnt_mangeInfo_entJJ : System.Web.UI.Page
{
    RCenter rc = new RCenter(); Share sh = new Share();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.btnSave.Attributes.Add("onclick", "if(checkInfo()){return true;}else{return false;}");
            showInfo();
        }
    }
    public void showInfo()
    {
        pageTool tool = new pageTool(this.Page, "t_");
        string sql = "select * from YW_JN_AppEntJJ where fbaseid='" + CurrentEntUser.EntId + "' and Fappid = 'JBQK' ";
        DataTable dt = sh.GetTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            tool.fillPageControl(dt.Rows[0]);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string sql = ""; pageTool tool = new pageTool(this.Page, "t_");
        if (!string.IsNullOrEmpty(t_FID.Value))
        { sql += " update YW_JN_AppEntJJ set jianjie='" + t_jianjie.Text + "' where FID='" + t_FID.Value + "'"; }
        else
        {
            t_FID.Value = Guid.NewGuid().ToString();
            sql += " insert YW_JN_AppEntJJ (FID, Fappid, fbaseid, ftime, editTime, jianjie) values ('" + t_FID.Value
                + "','JBQK','" + CurrentEntUser.EntId + "',getdate(),getdate(),'" + t_jianjie.Text + "')";
        }
        if (sh.PExcute(sql))
        { tool.showMessage("保存成功"); showInfo(); }
        else
        { tool.showMessage("保存失败"); }
    }

}


text:
"""
All the commands possible for the bot. This is basically a big routing table.
"""

import zonebot

import logging
from abc import ABCMeta, abstractmethod

LOGGER = logging.getLogger("zonebot")

class Command:
    """ Static mapping of Slack user IDs to user names """

    __metaclass__ = ABCMeta

    _usermap = {}

    def __init__(self, config=None):
        self.config = config

    @abstractmethod
    def perform(self, user_name, commands, zoneminder):
        pass

    @abstractmethod
    def report(self, slack, user, channel):
        pass

    @staticmethod
    def log_slack_result(result):
        """
        Logs the result of a slack API call.

        :param result: The result object from Slack
        """

        if not result:
            return

        if not result['ok']:
            error = "Error: "
            if 'error' in result:
                error = result['error']
            elif 'warning' in result:
                error = result['warning']

            LOGGER.error("Could not respond to the command: %s", error)

    @staticmethod
    def resolve_user(user_id, slack):
        """
        Resolve (if not already cached) the Slack user ID into a user name

        :param user_id: Slack user ID of the user (e.g. 'U1234567890')
        :type user_id: str
        :param slack: A fully configured `slackclient` instance
        :return: The resolved name of the user or `None` if the user ID could not be resolved.
        """

        if not user_id:
            return None

        user_name = None
        if user_id in Command._usermap:
            user_name = Command._usermap[user_id]

        if not user_name:
            LOGGER.info("Doing Slack lookup for user ID %s", user_id)
            result = slack.api_call("users.info",
                                    user=user_id,
                                    as_user=True)

            if result['ok']:
                user_name = result['user']['name'].lower()
                Command._usermap[user_id] = user_name
            else:
                LOGGER.error("Could not convert %s to a user name: %s", user_id, result['error'])

        return user_name

    @staticmethod
    def has_permission(user_name, config, command, permission):
        """
        Checks to see if the user has the required permissions to execute the provided
        command.

        :param user_name: Name of the user (*not* the Slack user ID)
        :type user_name: str
        :param permission:
        :param command:
        :param config:
        :return: True if the user is allow the execute the command and false if they are not.
        :rtype: bool
        """

        if 'any' == permission:
            return True

        # Now things get complicated.

        # First check to see if any permissions are defined. If they are not, then
        # anyone can do anything.
        if not config or not config.has_section('Permissions'):
            LOGGER.info("No config section")
            return True

        if not user_name:
            LOGGER.error('Could not resolve user ID %s', user_name)
            return False

        # Not listed in the permissions section, they only have read access
        access = config.get('Permissions', user_name.lower(), fallback='read')
        access = [x.strip() for x in access.split(',')]

        # They have specific permissions listed. See if this command is one of them

        if 'any' in access:
            # they are allowed to do anything
            return True
        if permission in access:
            # check by type
            return True
        elif command in access:
            # check by specific command
            return True

        # No match, not allowed
        LOGGER.info("User %s has access %s. They are not allowed the %s command",
                    user_name,
                    ', '.join(access),
                    command)

        return False

    @staticmethod
    def get_monitor(commands, index, zoneminder):
        """
        Returns the name of the monitor based on the provided commands

        :param commands: List of commands
        :param index: Where in the commands to look for the name of the monitor
        :param zoneminder: The ZoneMinder instance
        :return: name, error text
        :rtype: str, :class:`zonebot.zoneminder.Monitors`, str
        """

        if len(commands) <= index:
            return None, None, '*Error*: the name of the monitor is required. ' \
                               '_\'list monitors\'_ will display them all'

        name = commands[index].strip().lower()

        monitors = zoneminder.get_monitors()
        monitors.load()

        if name not in monitors.monitors:
            return None, None, '*Error*: monitor {0} not found. ' \
                               '_\'list monitors\'_ will display them all'.format(name)

        return name, monitors, None

class About(Command):
    """
    Prints about text.
    """
    def __init__(self, config=None):
        super(About, self).__init__(config=config)

    def perform(self, user_name, commands, zoneminder):
        pass

    def report(self, slack, user, channel):
        text = "*{0}* version {1}\n".format(zonebot.__project_name__, zonebot.__version__)
        text += "_Copyright_ (c) 2016 <mailto:{1}|{0}> .".format(zonebot.__author__, zonebot.__email__)

        return slack.api_call("chat.postMessage",
                              channel=channel,
                              text=text,
                              as_user=True)

class Status(Command):
    """
    Prints ZoneMinder status
    """
    def __init__(self, config=None):
        super(Status, self).__init__(config=config)
        self.status = {}

    def perform(self, user_name, commands, zoneminder):
        self.status = zoneminder.get_status()

    def report(self, slack, user, channel):
        text = ''

        text += '• _ZoneMinder version_: {0}\n'.format(self.status['version'])
        text += '• _ZoneMinder daemon_: {0}\n'.format(self.status['daemon'])
        text += '• _Load average_: {0}\n'.format(self.status['load'])

        #
        # Disk usage. This very, ***VERY*** often times out and is currently disabled.
        #
        # gb = 1024 * 1024 * 1024
        # for usage in self.status['usage']:
        #     text += '• _{0} monitor disk usage_: {1}\n'\
        #         .format(usage['name'], humansize(usage['space'] * gb))

        return slack.api_call("chat.postMessage",
                              channel=channel,
                              text=text,
                              as_user=True)

class Help(Command):
    """
    Generates the help test that lists available commands
    """

    def __init__(self, config=None):
        super(Help, self).__init__(config=config)
        self.user_name = None
        self.config = config

    def perform(self, user_name, commands, zoneminder):
        self.user_name = user_name

    def report(self, slack, user, channel):
        text = 'Supported commands for <@{0}>\n'.format(user)

        for command_name in sorted(_all_commands.keys(), key=lambda x: _all_commands[x]['index']):
            command = _all_commands[command_name]

            if 'meta' in command and command['meta']:
                continue

            permission = command['permission']
            if Command.has_permission(self.user_name, self.config, command_name, permission):
                text += "• _{0}_ : {1}\n".format(command_name, command['help'])

        return slack.api_call("chat.postMessage",
                              channel=channel,
                              text=text,
                              as_user=True)

class Unknown(Command):
    def __init__(self, config=None):
        super(Unknown, self).__init__(config=config)
        self.commands = None

    def perform(self, user_name, commands, zoneminder):
        self.commands = ' '.join(commands)

    def report(self, slack, user, channel):
        text = "_*Error*_: Unrecognized command '{0}'. Use 'help' for a list of supported commands"\
            .format(self.commands)

        return slack.api_call("chat.postMessage",
                              channel=channel,
                              text=text,
                              as_user=True)

class Denied(Unknown):
    def __init__(self, config=None):
        super(Denied, self).__init__(config=config)

    def report(self, slack, user, channel):
        text = "_*Error*_: <@{0}> You do not have permission to execute {1}".format(
            user, self.commands)

        return slack.api_call("chat.postMessage",
                              channel=channel,
                              text=text,
                              as_user=True)

class ListMonitors(Command):
    def __init__(self, config=None):
        super(ListMonitors, self).__init__(config=config)

        self.attachments = []

    def perform(self, user_name, commands, zoneminder):
        monitors = zoneminder.get_monitors()
        monitors.load()

        for monitor_name in monitors.monitors:
            monitor = monitors.monitors[monitor_name]

            enabled = 'Yes' if monitor['Enabled'] == '1' else 'No'
            color = '#2fa44f' if monitor['Enabled'] == '1' else '#d52000'

            self.attachments.append({
                'text': '{0} (ID: {1})'.format(monitor['Name'], monitor['Id']),
                'fields': [
                    {
                        'title': 'Enabled',
                        'value': enabled,
                        'short': True
                    },
                    {
                        'title': 'Detection',
                        'value': monitor['Function'],
                        'short': True
                    }
                ],
                'color': color
            })

    def report(self, slack, user, channel):
        return slack.api_call("chat.postMessage",
                              channel=channel,
                              attachments=self.attachments,
                              as_user=True)

class ToggleMonitor(Command):
    def __init__(self, config=None):
        super(ToggleMonitor, self).__init__(config=config)
        self.result = None

    def perform(self, user_name, commands, zoneminder):

        name, monitors, error_text = Command.get_monitor(commands, 2, zoneminder)
        if not name:
            self.result = error_text
            return

        on = True if commands[0] == 'enable' else False
        changed = monitors.set_state(name, on)

        self.result = 'Monitor {0} state {1}'.format(name, changed)

    def report(self, slack, user, channel):
        return slack.api_call("chat.postMessage",
                              channel=channel,
                              text=self.result,
                              as_user=True)

class GetStillImage(Command):
    """
    Returns the current still image from a monitor and replies to the channel with it.
    """

    def __init__(self, config=None):
        super(GetStillImage, self).__init__(config=config)
        self.error_text = None
        self.image = None
        self.name = None

    def perform(self, user_name, commands, zoneminder):
        name, monitors, error_text = Command.get_monitor(commands, 2, zoneminder)
        if not name:
            self.error_text = error_text
            return

        self.name = monitors.get_value(name, 'Name')

        image, error_text = zoneminder.get_still_image(monitors.get_value(name, 'Id'))
        if error_text:
            self.error_text = error_text
        else:
            self.image = image

    def report(self, slack, user, channel):
        if self.error_text:
            return slack.api_call("chat.postMessage",
                                  channel=channel,
                                  text=self.error_text,
                                  as_user=True)

        comment = 'Latest still image from {0}'.format(self.name)
        filename = '{0} Latest.jpeg'.format(self.name)

        # And off it goes ...
        return slack.api_call('files.upload',
                              initial_comment=comment,
                              filename=filename,
                              channels=channel,
                              # Note: this is broken in slackclient 1.0.1 and earlier
                              file=self.image
                              )

#
# meta - true for meta (not user) command that should not show up in the help
# index - the oder in which the command should be displayed in the help output
#
_all_commands = {
    'unknown': {
        'permission': 'any',
        'meta': True,
        'classname': Unknown,
        'index': 0
    },
    'help': {
        'permission': 'any',
        'meta': True,
        'classname': Help,
        'index': 0
    },
    'denied': {
        'permission': 'any',
        'meta': True,
        'classname': Denied,
        'index': 0
    },
    'about': {
        'permission': 'any',
        'classname': About,
        'help': 'Display bot version information',
        'index': 1
    },
    'status': {
        'permission': 'any',
        'classname': Status,
        'help': 'Display the current ZoneMinder status',
        'index': 2
    },
    'list monitors': {
        'permission': 'read',
        'help': 'List all monitors and their current state',
        'classname': ListMonitors,
        'index': 3
    },
    'enable monitor': {
        'permission': 'write',
        'help': 'Enable alarms on a monitor (supplied by name, not ID)',
        'classname': ToggleMonitor,
        'index': 4
    },
    'disable monitor': {
        'permission': 'write',
        'help': 'Disable alarms on a monitor (supplied by name, not ID)',
        'classname': ToggleMonitor,
        'index': 5
    },
    'get image': {
        'permission': 'read',
        'help': 'Get a still image from the named monitor (supplied by name, not ID)',
        'classname': GetStillImage,
        'index': 6
    }
}

def get_command(words, user_name=None, config=None):
    """
    Gets the command that matches the input words.

    :param words: The list of words that make up the command and its arguments.
    :type words: List[str]
    :param user_name: Name (not ID) of the user requesting the command
    :param config:
    :return: The command matching the input. A command is always returned
    :rtype: Command
    """

    if not words or len(words) < 1:
        return Help()

    command_text = words[0].strip().lower()
    if command_text not in _all_commands:
        if len(words) > 1:
            command_text = '{0} {1}'.format(words[0].strip().lower(), words[1].strip().lower())

    if command_text not in _all_commands:
        return Unknown()

    perms = _all_commands[command_text]['permission']

    if not Command.has_permission(user_name, config, command_text, perms):
        return Denied()

    return _all_commands[command_text]['classname'](config=config)

suffixes = ['bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb']

def humansize(nbytes):
    if nbytes == 0:
        return '0 bytes'

    i = 0
    while nbytes >= 1024 and i < len(suffixes)-1:
        nbytes /= 1024.
        i += 1
    f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
    return '%s %s' % (f, suffixes[i])


text:
<?php
/**
 * Receive API calls to process it.
 *
 *
 *
 * OUTPUT FORMAT:
 *      # JSON
 *      # JSONP (use the "callback" parameter)
 *
 * QUERY:
 *      # GET Entities list:
 *          /api/entity/
 *              @param <optional> page  [1-*]  default: 1
 *              @param <optional> limit [1-30] default: 5
 *
 *      # GET Entity with id (or MID):
 *          /api/entity/ID/
 *
 *
 *      # GET Relation list:
 *          /api/relation/
 *              @param <optional> page  [1-*]  default: 1
 *              @param <optional> limit [1-30] default: 5
 *
 *      # GET Relation with id:
 *          /api/relation/ID/
 *
 * STATUS MESSAGE:
 *      # 200: OK
 *      # 204: Empty content
 *      # 405: Wrong parameter(s)
 *      # 412: Method not allowed
 *      # 501: Method not emplemented
 *      # 600: Quota exceeted
 *
 * QUOTA LIMITS:
 *      # GET   : 120 query by hour
 *      # PUT   : 120 query by hour
 *      # POST  : 120 query by hour
 *      # DELETE: 120 query by hour
 *      # HEAD  : 120 query by hour
 *
 * @author Pirhoo <pierre@owni.fr>
 * @version 1.0
 * @package API
 *
 */
class API {

    const PUT    = 'PUT';
    const GET    = 'GET';
    const POST   = 'POST';
    const HEAD   = 'HEAD';
    const DELETE = 'DELETE';

    /**
     * @var DbMySQL
     * @access protected
     */
    protected $db;

    /**
     * @var array
     * @access protected
     */
    protected $managers;

    /**
     * @var array
     * @access protected
     */
    protected $err;

    /**
     * GET action (to consult)
     * @access protected
     * @param array $param
     */
    protected function get($param) {

        // get the target resource
        $resource = $param["resource"];

        // check the resource
        if(!$this->isGoodResource($resource) ) {
            // unknown resource
            $this->result(601);
        }

        // control the quota
        if(! $this->isUnderQuota(self::GET) ) {

            // user over the quota limit
            $this->result(600);

        }else {

            // if the user ask an id, it must be a number or mid
            if(isset($param["id"]) && !(is_numeric($param["id"]) || preg_match("#^/[a-z0-9_-]+/[a-z0-9_-]+$#i", $param["id"])) ) {

                // wrong parameter
                $this->result(405);

            // or id is all right
            } elseif( isset($param["id"]) ) {

                // get the resource
                $result = $this->getResource($resource, $param["id"]);

                // if the resource doesn't exist
                if(!$result)
                    // no content header
                    $this->result (204);

                // insert the query in the database to limit quota
                $this->saveQuery(self::GET);

                // send the result
                $this->result(200, $result);

            // or user just want a list of resources
            } else {

                // take the page number from parameter
                $page = isset($param["page"]) && is_numeric($param["page"]) ? $param["page"] : 1;

                // take number of resources by page from parameter
                $limit = isset($param["limit"]) && is_numeric($param["limit"])  ? $param["limit"] : 5;

                // get the resources
                $result = $this->getResources($resource, $page, $limit);

                // if the resource doesn't exist
                if(!$result)
                    // no content header
                    $this->result (204);

                // insert the query in the database to limit quota
                $this->saveQuery(self::GET);

                // send the result
                $this->result(200, $result);
            }

        }
    }

    /**
     * Send the result
     *
     * @access protected
     * @param integer $code
     */
    protected function result($code, $content = null) {

        // list of HTTP code
        $error = array();

        // 1XX INFORMATION
        $error[100] = "Continue";
        $error[101] = "Switching Protocols";
        $error[102] = "Processing";

        // 2XX SUCCESS
        $error[200] = "OK";
        $error[201] = "Created";
        $error[202] = "Accepted";
        $error[203] = "Non-Authoritative Information";
        $error[204] = "No Content";
        $error[205] = "Reset Content";
        $error[206] = "Partial Content";
        $error[207] = "Multi-Status";
        $error[210] = "Content Different";

        // 3XX REDIRECTION
        $error[300] = "Multiple Choices";
        $error[301] = "Moved Permanently";
        $error[302] = "Found";
        $error[303] = "See Other";
        $error[304] = "Not Modified";
        $error[305] = "Use Proxy";
        $error[307] = "Temporary Redirect";
        $error[310] = "Too many Redirect";

        // 4XX CLIENT ERROR
        $error[400] = "Bad Request";
        $error[401] = "Unauthorized";
        $error[402] = "Payment Required";
        $error[403] = "Forbidden";
        $error[404] = "Not Found";
        $error[405] = "Method Not Allowed";
        $error[406] = "Not Acceptable";
        $error[407] = "Proxy Authentication Required";
        $error[408] = "Request Time-out";
        $error[409] = "Conflict";
        $error[410] = "Gone";
        $error[411] = "Length Required";
        $error[412] = "Precondition Failed";
        $error[413] = "Request Entity Too Large";
        $error[414] = "Request-URI Too Long";
        $error[415] = "Unsupported Media Type";
        $error[416] = "Requested range unsatisfiable";
        $error[417] = "Expectation failed";
        $error[418] = "I'm a teapot";
        $error[422] = "Unprocessable entity";
        $error[423] = "Locked";
        $error[424] = "Method failure";
        $error[425] = "Unordered Collection";
        $error[426] = "Upgrade Required";
        $error[449] = "Retry With";
        $error[450] = "Blocked by Windows Parental Controls";

        // 5XX SERVER ERROR
        $error[500] = "Internal Server Error";
        $error[501] = "Not Implemented";
        $error[502] = "Bad Gateway ou Proxy Error";
        $error[503] = "Service Unavailable";
        $error[504] = "Gateway Time-out";
        $error[505] = "HTTP Version not supported";
        $error[507] = "Insufficient storage";
        $error[509] = "Bandwidth Limit Exceeded";

        // 6XX CUSTOM ERROR
        $error[600] = "API Quota Exceeded";
        $error[601] = "Unknown resource";

        // if no callback function specified
        if(! isset($_REQUEST["callback"]) ) {

            // here following the error code
            header('HTTP/1.0 '.$code.' '.$error[$code]);
            header('Content-Type: application/json', true, $code);

            // result with status and status code
            $result = array("status" => $code.' '.$error[$code], "status_code" => $code);

            // add the content, if  there is a content
            if($content !== null) $result["content"] = $content;

            // JSON encode and show the result
            echo json_encode($result);

        // if callback function is specified
        } else {

            // here following the error code
            header('HTTP/1.0 200 '.$error[200]);
            header('Content-Type: text/javascript', true, 200);

            // result with status and status code
            $result = array("status" => $code.' '.$error[$code], "status_code" => $code);

            // add the content, if  there is a content
            if($content !== null) $result["content"] = $content;

            // JSON encode and show the result
            echo $_REQUEST["callback"]."(".json_encode($result).");";
        }

        // it's done !
        exit;
    }

    /**
     * True if the resource type is allowed. Else false.
     *
     * @access protected
     * @param string $resource
     * @return boolean
     */
    protected function isGoodResource($resource) {
           $resource = strtolower($resource);
           return $resource == "entity" || $resource == "relation";
    }

    /**
     * Save the user API query
     *
     * @access protected
     * @param  string $method
     * @return boolean
     */
    protected function saveQuery($method) {

        $param = $_REQUEST;
        // useless variable
        unset($param["api"]);

        // escape quotes
        foreach($param as $key => $val)
            $param[$key] = htmlentities($val, ENT_QUOTES);

        // query to insert
        $api_query = str_replace("\\\\", "\\", json_encode($param) );
        // ip to insert
        $IP        = $_SERVER["REMOTE_ADDR"];

        $query  = "INSERT INTO ".TABLE_PREFIX."api_query ";
        $query .= "(IP, method, query)";
        $query .= "VALUES(";
            $query .= "'{$IP}',";
            $query .= "'{$method}',";
            $query .= "'{$api_query}'";
        $query .= ")";

        // insert
        return $this->db->query($query);
    }

    /**
     * Say if the user can ask the api for this method
     *
     * @param string $method
     * @return boolean
     */
    protected function isUnderQuota($method) {

        // ip to track
        $IP = $_SERVER["REMOTE_ADDR"];

        // query to count query for this method
        $query  = "SELECT COUNT(id) FROM ".TABLE_PREFIX."api_query ";
        $query .= "WHERE ";
            $query .= "IP = '{$IP}' ";
            $query .= "AND method = '{$method}' ";
            // every line older than 1 hour
            $query .= "AND date > (NOW() - INTERVAL 60 MINUTE)";

        // ask the database
        $this->db->query($query);
        list($count) = $this->db->fetch();

        return $count < $this->getMethodQuota($method);

    }

    /**
     * Get a resource
     *
     * @param string $resource
     * @param number $id
     *
     * @access protected
     * @return array
     */
    protected function getResource($resource = null, $id = null) {

        // if parameters are fine
        if( $resource !== null && $id !== null ) {
            // select the resource
            switch ($resource) {
                // it's an entity
                case "entity":
                    // we use "entity" to select "node", it seems more user-friendly
                    $node = $this->managers['node']->getNode($id);

                    // array conversion
                    $node = $node instanceof Node ? $node->getArray() : false;

                    // if the result is OK
                    if(is_array($node))

                        // get the relations of the node
                        $node["relations"] = $this->managers['relation']->getNodeRelationArray( $node["id"] );

                    // return the result
                    return $node; break;

                // it's a relation
                case "relation":

                    // relation
                    $relation = $this->managers["relation"]->getRelation($id);

                    // array conversion
                    $relation = $relation instanceof Relation ? $relation->getArray(true) : false;

                    // if the result is OK
                    if(is_array($relation)) {

                        // Get the true node
                        /* $relation["node_right"] = $this->managers['node']->getNode($relation["node_right"]);
                        // if result it's ok
                        if($relation["node_right"] instanceof Node)
                            // convert Object to array
                            $relation["node_right"] = $relation["node_right"]->getArray(true);

                        $relation["node_left"]  = $this->managers['node']->getNode($relation["node_left"]);
                        // if result it's ok
                        if($relation["node_left"] instanceof Node)
                            // convert Object to array
                            $relation["node_left"] = $relation["node_left"]->getArray(true); */

                        // Get the complete type
                        $relation["type"] = $this->managers['relation_type']->getType($relation["type"]);

                        // if the result is OK
                        if($relation["type"] instanceof Relation_type) {

                            // convert Object to array
                            $relation["type"] = $relation["type"]->getArray();
                        }

                        // Get relation properties
                        $relation["properties"] = $this->managers["relation_value"]->getRelationValues($id);

                        // convert properties to array
                        if( is_array($relation["properties"]) ) {

                            // for each property
                            foreach($relation["properties"] as & $prop)

                                // convert Object to Array
                                $prop = $prop->getArray();
                        }

                    }

                    // return the result
                    return $relation; break;

            }
        }

    }

    /**
     *
     * Get a list of resources
     *
     * @param string $resource
     * @param int $page
     * @param int $limit
     *
     * @access protected
     * @return array
     */
    protected function getResources($resource = null, $page = 1, $limit = 5) {

        // minimum and maximun value for limit
        $limit = $limit > 35 || $limit < 1 ? 5 : $limit;
        $offset = ($page - 1) * $limit;

        // if parameters are fine
        if( $resource !== null ) {
            // select the resource
            switch ($resource) {

                // it's an entity
                case "entity":

                    // get the node list
                    $nodes = $this->managers["node"]->getNodesList($offset, $limit);

                    // if the result is an array
                    if( is_array($nodes) )
                        // for each node
                        foreach($nodes as $key => & $node)
                            // get relations
                            $node["relations"] = $this->managers["relation"]->getNodeRelationArray($node["id"]);

                    // return the result
                    return $nodes; break;

                // it's a relation
                case "relation":

                    // get the relation list
                    $relations = $this->managers["relation"]->getRelationsList($offset, $limit);

                    // return the result
                    return $relations; break;

            }
        }

    }

    /**
     * Switch an action following the GET paramater
     * @access public
     */
    public function switchAction() {

        switch($_SERVER['REQUEST_METHOD']) {

            // consult with GET
            case self::GET:
                $this->get($_GET);
                break;

            // delete with DELETE
            case self::DELETE:
                // not implemented yet
                $this->result(501);
                break;

            // update with POST
            case self::POST:
                // not implemented yet
                $this->result(501);
                break;

            // insert with PUT
            case self::PUT:
                // not implemented yet
                $this->result(501);
                break;

            // query not allowed
            default : $this->result(412);

        }

    }

    /**
     * Get the query quota of a method, by our
     *
     * @param string $method
     * @return int
     */
    public function getMethodQuota($method) {

        // quota for each method by hour
        $quota  = array(self::PUT    => 120,
                        self::GET    => 120,
                        self::POST   => 120,
                        self::HEAD   => 120,
                        self::DELETE => 120);

        return $quota[$method];
    }

    /**
     * Constructor
     * @access public
     */
    public function __construct(& $db, & $managers, & $err) {

        // reference to the base
        $this->db = & $db;

        // reference to the managers
        $this->managers = & $managers;

        // reference to the error manager
        $this->err = & $err;

        // switch an action following the GET paramater
        $this->switchAction();

    }

}

?>


text:
<?php

namespace Bpocallaghan\Titan\Models\Traits;

use DB;
use Bpocallaghan\Titan\Models\News;
use Bpocallaghan\Titan\Models\NewsTag;

trait TaggedNews
{
    public $newsLatest = [];

    /**
     * Get the news entries tagged to me
     * @param int $limit
     * @return \Eloquent
     */
    public function news($limit = 5)
    {
        if (count($this->newsLatest) >= 1) {
            return $this->newsLatest;
        }

        // get class name that include this file (model name)
        $parent = str_replace('AppModels', '', stripslashes(static::class));

        $rows = DB::select("SELECT news.* FROM $this->table
            INNER JOIN news_tag ON news_tag.subject_id = $this->table.id
            INNER JOIN news ON news.id = news_tag.news_id
            WHERE $this->table.id = ? AND news_tag.subject_type LIKE ?
            GROUP BY news.id
            ORDER BY news.created_at DESC", [$this->id, '%' . $parent]);

        $news = collect();
        // filter active and get photos for entry
        foreach ($rows as $k => $row) {

            $item = News::where('id', $row->id)->active()->first();
            if ($item) {
                $item->images; // get the images
                $news->push($item);
            }
        }

        $this->newsLatest = $news->take($limit);

        return $this->newsLatest;

        // old / default way
        return $this->hasMany(NewsTag::class, 'subject_id', 'id')
            ->where('subject_type', get_class($this))
            ->with('news')
            ->orderBy('created_at', 'DESC');
    }
}


text:
package edu.mit.media.funf.probe.builtin;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import edu.mit.media.funf.probe.SensorProbe;
import edu.mit.media.funf.probe.builtin.ProbeKeys.TemperatureSensorKeys;

/**
 * Used to record temperature.  Implementation depends on the device and does not exist on all devices.
 *	Some will record temperature of battery, others temperature of CPU or environment.
 *
 */
public class TemperatureSensorProbe extends SensorProbe implements TemperatureSensorKeys {

	public int getSensorType() {
		return Sensor.TYPE_TEMPERATURE;
	}

	public String[] getRequiredFeatures() {
		return new String[]{
			//"android.hardware.sensor.temperature"  doesn't exist yet
		};
	}

	public String[] getValueNames() {
		return new String[] {
			TEMPERATURE
		};
	}

	@Override
	protected long getDefaultDuration() {
		return 10L;
	}

	@Override
	protected long getDefaultPeriod() {
		return 1200;
	}

}


text:
@class DBTEAMLOGPaperContentAddToFolderDetails;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API Object

///
/// The `PaperContentAddToFolderDetails` struct.
///
/// Added Paper doc or folder to a folder.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGPaperContentAddToFolderDetails : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// Event unique identifier.
@property (nonatomic, readonly, copy) NSString *eventUuid;

/// Target asset index.
@property (nonatomic, readonly) NSNumber *targetIndex;

/// Parent asset index.
@property (nonatomic, readonly) NSNumber *parentIndex;

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param eventUuid Event unique identifier.
/// @param targetIndex Target asset index.
/// @param parentIndex Parent asset index.
///
/// @return An initialized instance.
///
- (instancetype)initWithEventUuid:(NSString *)eventUuid
                      targetIndex:(NSNumber *)targetIndex
                      parentIndex:(NSNumber *)parentIndex;

- (instancetype)init NS_UNAVAILABLE;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `PaperContentAddToFolderDetails` struct.
///
@interface DBTEAMLOGPaperContentAddToFolderDetailsSerializer : NSObject

///
/// Serializes `DBTEAMLOGPaperContentAddToFolderDetails` instances.
///
/// @param instance An instance of the `DBTEAMLOGPaperContentAddToFolderDetails`
/// API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGPaperContentAddToFolderDetails` API object.
///
+ (NSDictionary *)serialize:(DBTEAMLOGPaperContentAddToFolderDetails *)instance;

///
/// Deserializes `DBTEAMLOGPaperContentAddToFolderDetails` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGPaperContentAddToFolderDetails` API object.
///
/// @return An instantiation of the `DBTEAMLOGPaperContentAddToFolderDetails`
/// object.
///
+ (DBTEAMLOGPaperContentAddToFolderDetails *)deserialize:(NSDictionary *)dict;

@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PanelContainer — MetPy 1.0</title>

  <link href="../../_static/css/theme.css" rel="stylesheet" />
  <link href="../../_static/css/index.f6b7ca918bee2f46fd9abac01cfb07d5.css" rel="stylesheet" />

  <link rel="stylesheet"
    href="../../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/basic.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-binder.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-dataframe.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-rendered-html.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/theme-unidata.css" />

  <link rel="preload" as="script" href="../../_static/js/index.1e043a052b0af929e4d8.js">

    <link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="PlotObs" href="metpy.plots.PlotObs.html" />
    <link rel="prev" title="MapPanel" href="metpy.plots.MapPanel.html" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="en" />
    <link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.plots.PanelContainer.html" />

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-menu" aria-controls="navbar-menu" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            Version 1.0

            User Guide

            Reference Guide

            Developer's Guide

            Example Gallery

            Support

            Release Notes

      <form class="bd-search d-flex align-items-center" action="../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" >
</form>

   constants

   units

   metpy.io

   calc

   plots

     add_metpy_logo

     add_timestamp

     add_unidata_logo

     convert_gempak_color

     read_colortable

     wx_code_to_numeric

     BarbPlot

     ContourPlot

     FilledContourPlot

     Hodograph

     ImagePlot

     MapPanel

     PanelContainer

     PlotObs

     PlotScalar

     PlotVector

     Plots2D

     SkewT

     StationPlot

     StationPlotLayout

   ctables

   interpolate

   xarray

   References

     On this page

   Examples using

     metpy.plots.PanelContainer

PanelContainer¶

class metpy.plots.PanelContainer(**kwargs)[source]¶

Collects panels and set complete figure related settings (e.g., size).

Attributes Summary

<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>

cross_validation_lock

A contextmanager for running a block with our cross validation lock set to True.

figure

Provide access to the underlying figure object.

panel

Provide simple access for a single panel.

panels

A list of panels to plot on the figure.

size

This trait takes a tuple of (width, height) to set the size of the figure.

Methods Summary

<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>

__init__(*args, **kwargs)

Initialize self.

add_traits(**traits)

Dynamically add trait attributes to the HasTraits instance.

class_own_trait_events(name)

Get a dict of all event handlers defined on this class, not a parent.

class_own_traits(**metadata)

Get a dict of all the traitlets defined on this class, not a parent.

class_trait_names(**metadata)

Get a list of all the names of this class' traits.

class_traits(**metadata)

Get a dict of all the traits of this class.

draw()

Draw the collection of panels.

has_trait(name)

Returns True if the object has a trait with the specified name.

hold_trait_notifications()

Context manager for bundling trait change notifications and cross validation.

notify_change(change)

Notify observers of a change event

observe(handler[, names, type])

Setup a handler to be called when a trait changes.

on_trait_change([handler, name, remove])

DEPRECATED: Setup a handler to be called when a trait changes.

refresh(_)

Refresh the rendering of all panels.

save(*args, **kwargs)

Save the constructed graphic as an image file.

set_trait(name, value)

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs)

This is called before self.__init__ is called.

show()

Show the constructed graphic on the screen.

trait_defaults(*names, **metadata)

Return a trait's default value or a dictionary of them

trait_events([name])

Get a dict of all the event handlers of this class.

trait_has_value(name)

Returns True if the specified trait has a value.

trait_metadata(traitname, key[, default])

Get metadata values for trait by key.

trait_names(**metadata)

Get a list of all the names of this class' traits.

trait_values(**metadata)

A dict of trait names and their values.

traits(**metadata)

Get a dict of all the traits of this class.

unobserve(handler[, names, type])

Remove a trait change handler.

unobserve_all([name])

Remove trait change handlers of any type for the specified name.

Attributes Documentation

cross_validation_lock¶

A contextmanager for running a block with our cross validation lock set
to True.

At the end of the block, the lock's value is restored to its value
prior to entering the block.

figure¶

Provide access to the underlying figure object.

panel¶

Provide simple access for a single panel.

panels¶

A list of panels to plot on the figure.

This trait must contain at least one panel to plot on the figure.

size¶

This trait takes a tuple of (width, height) to set the size of the
figure.

This trait defaults to None and will assume the default matplotlib.pyplot.figure size.

Methods Documentation

__init__(*args, **kwargs)¶

Initialize self.  See help(type(self)) for accurate signature.

add_traits(**traits)¶

Dynamically add trait attributes to the HasTraits instance.

classmethod class_own_trait_events(name)¶

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata)¶

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_trait_names(**metadata)¶

Get a list of all the names of this class' traits.

This method is just like the trait_names() method,
but is unbound.

classmethod class_traits(**metadata)¶

Get a dict of all the traits of this class.  The dictionary
is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don't know anything about the values
that the various HasTrait's instances are holding.

The metadata kwargs allow functions to be passed in which
filter traits based on metadata values.  The functions should
take a single value as an argument and return a boolean.  If
any function returns False, then the trait is not included in
the output.  If a metadata key doesn't exist, None will be passed
to the function.

draw()[source]¶

Draw the collection of panels.

has_trait(name)¶

Returns True if the object has a trait with the specified name.

hold_trait_notifications()¶

Context manager for bundling trait change notifications and cross
validation.

Use this when doing multiple trait assignments (init, config), to avoid
race conditions in trait notifiers requesting other trait values.
All trait notifications will fire after all values have been assigned.

notify_change(change)¶

Notify observers of a change event

observe(handler, names=traitlets.All, type='change')¶

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters

handler (callable) – A callable that is called when a trait changes. Its
signature should be handler(change), where change is a
dictionary. The change dictionary at least holds a 'type' key.
* type: the type of notification.
Other keys may be passed depending on the value of 'type'. In the
case where type is 'change', we also have the following keys:
* owner : the HasTraits instance
* old : the old value of the modified trait attribute
* new : the new value of the modified trait attribute
* name : the name of the modified trait attribute.

names (list, str, All) – If names is All, the handler will apply to all traits.  If a list
of str, handler will apply to all names in the list.  If a
str, the handler will apply just to that name.

type (str, All (default: 'change')) – The type of notification to filter by. If equal to All, then all
notifications are passed to the observe handler.

on_trait_change(handler=None, name=None, remove=False)¶

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits
subclass with the naming convention '_[traitname]_changed'.  Thus,
to create static handler for the trait 'a', create the method
_a_changed(self, name, old, new) (fewer arguments can be used, see
below).

If remove is True and handler is not specified, all change
handlers for the specified name are uninstalled.

Parameters

handler (callable, None) – A callable that is called when a trait changes.  Its
signature can be handler(), handler(name), handler(name, new),
handler(name, old, new), or handler(name, old, new, self).

name (list, str, None) – If None, the handler will apply to all traits.  If a list
of str, handler will apply to all names in the list.  If a
str, the handler will apply just to that name.

remove (bool) – If False (the default), then install the handler.  If True
then unintall it.

refresh(_)[source]¶

Refresh the rendering of all panels.

save(*args, **kwargs)[source]¶

Save the constructed graphic as an image file.

This method takes a string for saved file name. Additionally, the same arguments and
keyword arguments that matplotlib.pyplot.savefig does.

set_trait(name, value)¶

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs)¶

This is called before self.__init__ is called.

show()[source]¶

Show the constructed graphic on the screen.

trait_defaults(*names, **metadata)¶

Return a trait's default value or a dictionary of them

Notes

Dynamically generated default values may
depend on the current state of the object.

classmethod trait_events(name=None)¶

Get a dict of all the event handlers of this class.

Parameters

name (str (default: None)) – The name of a trait of this class. If name is None then all
the event handlers of this class will be returned instead.

Returns

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name)¶

Returns True if the specified trait has a value.

This will return false even if getattr would return a
dynamically generated default value. These default values
will be recognized as existing only after they have been
generated.

Example

class MyClass(HasTraits):
    i = Int()

mc = MyClass()
assert not mc.trait_has_value("i")
mc.i # generates a default value
assert mc.trait_has_value("i")

trait_metadata(traitname, key, default=None)¶

Get metadata values for trait by key.

trait_names(**metadata)¶

Get a list of all the names of this class' traits.

trait_values(**metadata)¶

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which
filter traits based on metadata values.  The functions should
take a single value as an argument and return a boolean.  If
any function returns False, then the trait is not included in
the output.  If a metadata key doesn't exist, None will be passed
to the function.

Returns

A dict of trait names and their values.

Notes

Trait values are retrieved via getattr, any exceptions raised
by traits or the operations they may trigger will result in the
absence of a trait value in the result dict.

traits(**metadata)¶

Get a dict of all the traits of this class.  The dictionary
is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don't know anything about the values
that the various HasTrait's instances are holding.

The metadata kwargs allow functions to be passed in which
filter traits based on metadata values.  The functions should
take a single value as an argument and return a boolean.  If
any function returns False, then the trait is not included in
the output.  If a metadata key doesn't exist, None will be passed
to the function.

unobserve(handler, names=traitlets.All, type='change')¶

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters

handler (callable) – The callable called when a trait attribute changes.

names (list, str, All (default: All)) – The names of the traits for which the specified handler should be
uninstalled. If names is All, the specified handler is uninstalled
from the list of notifiers corresponding to all changes.

type (str or All (default: 'change')) – The type of notification to filter by. If All, the specified handler
is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name=traitlets.All)¶

Remove trait change handlers of any type for the specified name.
If name is not specified, removes all trait notifiers.

Examples using metpy.plots.PanelContainer¶

Simple Plotting¶

Combined Plotting¶

Upper Air Analysis using Declarative Syntax¶

Surface Analysis using Declarative Syntax¶

MetPy Declarative Syntax Tutorial¶

    MapPanel
    PlotObs

          © Copyright 2008–2021, MetPy Developers. Development supported by National Science Foundation grants AGS-1344155, OAC-1740315, and AGS-1901712.

        Last updated on Apr 28, 2021 at 23:12:45.

        Created using Sphinx 3.5.4.


text:
'use strict';

var assert = require('assert');
var extend = require('extend');
var googleProtoFiles = require('google-proto-files');
var is = require('is');
var nodeutil = require('util');
var proxyquire = require('proxyquire');
var sinon = require('sinon').sandbox.create();

var common = require('@google-cloud/common');
var commonGrpc = require('@google-cloud/common-grpc');
var Cluster = require('../src/cluster.js');
var Instance = require('../src/instance.js');

var promisified = false;
var fakeUtil = extend({}, common.util, {
  promisifyAll: function(Class, options) {
    if (Class.name !== 'Bigtable') {
      return;
    }

    promisified = true;
    assert.deepEqual(options.exclude, ['instance', 'operation']);
  }
});

var fakePaginator = {
  extend: function() {
    this.calledWith_ = arguments;
  },
  streamify: function(methodName) {
    return methodName;
  }
};

function createFake(Class) {
  function Fake() {
    this.calledWith_ = arguments;
    Class.apply(this, arguments);
  }
  nodeutil.inherits(Fake, Class);
  return Fake;
}

var FakeGrpcService = createFake(commonGrpc.Service);
var FakeCluster = createFake(Cluster);
var FakeInstance = createFake(Instance);
var FakeGrpcOperation = createFake(function() {});

describe('Bigtable', function() {
  var PROJECT_ID = 'test-project';

  var Bigtable;
  var bigtable;

  before(function() {
    Bigtable = proxyquire('../', {
      '@google-cloud/common': {
        paginator: fakePaginator,
        util: fakeUtil
      },
      '@google-cloud/common-grpc': {
        Service: FakeGrpcService,
        Operation: FakeGrpcOperation
      },
      './cluster.js': FakeCluster,
      './instance.js': FakeInstance
    });
  });

  afterEach(function() {
    sinon.restore();
  });

  beforeEach(function() {
    delete process.env.BIGTABLE_EMULATOR_HOST;
    bigtable = new Bigtable({ projectId: PROJECT_ID });
  });

  describe('instantiation', function() {
    it('should extend the correct methods', function() {
      var args = fakePaginator.calledWith_;

      assert.strictEqual(args[0], Bigtable);
      assert.deepEqual(args[1], ['getInstances']);
    });

    it('should streamify the correct methods', function() {
      assert.strictEqual(bigtable.getInstancesStream, 'getInstances');
    });

    it('should promisify all the things', function() {
      assert(promisified);
    });

    it('should normalize the arguments', function() {
      var normalizeArguments = fakeUtil.normalizeArguments;
      var normalizeArgumentsCalled = false;
      var fakeOptions = {
        projectId: PROJECT_ID
      };
      var fakeContext = {};

      fakeUtil.normalizeArguments = function(context, options) {
        normalizeArgumentsCalled = true;
        assert.strictEqual(context, fakeContext);
        assert.strictEqual(options, fakeOptions);
        return options;
      };

      Bigtable.call(fakeContext, fakeOptions);
      assert(normalizeArgumentsCalled);

      fakeUtil.normalizeArguments = normalizeArguments;
    });

    it('should inherit from GrpcService', function() {
      assert(bigtable instanceof FakeGrpcService);

      var calledWith = bigtable.calledWith_[0];

      assert.strictEqual(calledWith.baseUrl, 'bigtable.googleapis.com');
      assert.strictEqual(calledWith.service, 'bigtable');
      assert.strictEqual(calledWith.apiVersion, 'v2');
      assert.strictEqual(calledWith.customEndpoint, false);

      assert.deepEqual(calledWith.protoServices, {
        Bigtable: googleProtoFiles('bigtable/v2/bigtable.proto'),
        BigtableTableAdmin: {
          baseUrl: 'bigtableadmin.googleapis.com',
          path: googleProtoFiles(
            'bigtable/admin/v2/bigtable_table_admin.proto'),
          service: 'bigtable.admin'
        },
        BigtableInstanceAdmin: {
          baseUrl: 'bigtableadmin.googleapis.com',
          path: googleProtoFiles(
            'bigtable/admin/v2/bigtable_instance_admin.proto'
          ),
          service: 'bigtable.admin'
        },
        Operations: {
          baseUrl: 'bigtableadmin.googleapis.com',
          path: googleProtoFiles('longrunning/operations.proto'),
          service: 'longrunning',
          apiVersion: 'v1'
        }
      });

      assert.deepEqual(calledWith.scopes, [
        'https://www.googleapis.com/auth/bigtable.admin',
        'https://www.googleapis.com/auth/bigtable.data',
        'https://www.googleapis.com/auth/cloud-platform'
      ]);

      assert.deepEqual(calledWith.packageJson, require('../package.json'));
    });

    it('should work with the emulator', function() {
      var endpoint = 'http://emulator:8288';
      process.env.BIGTABLE_EMULATOR_HOST = endpoint;

      var bigtable = new Bigtable({ projectId: PROJECT_ID });

      var calledWith = bigtable.calledWith_[0];
      assert.strictEqual(calledWith.baseUrl, endpoint);
      assert.strictEqual(calledWith.customEndpoint, true);

      Object.keys(calledWith.protoServices).forEach(function(service) {
        service = calledWith.protoServices[service];

        if (is.object(service)) {
          assert.strictEqual(service.baseUrl, endpoint);
        }
      });

      delete process.env.BIGTABLE_EMULATOR_HOST;
    });

    it('should work with a custom apiEndpoint', function() {
      var options = {
        projectId: PROJECT_ID,
        apiEndpoint: 'http://local:3888'
      };

      var bigtable = new Bigtable(options);

      var calledWith = bigtable.calledWith_[0];
      assert.strictEqual(calledWith.baseUrl, options.apiEndpoint);
      assert.strictEqual(calledWith.customEndpoint, true);

      Object.keys(calledWith.protoServices).forEach(function(service) {
        service = calledWith.protoServices[service];

        if (is.object(service)) {
          assert.strictEqual(service.baseUrl, options.apiEndpoint);
        }
      });
    });

    it('should set the projectName', function() {
      assert.strictEqual(bigtable.projectName, 'projects/' + PROJECT_ID);
    });
  });

  describe('createInstance', function() {
    var INSTANCE_NAME = 'my-instance';

    it('should provide the proper request options', function(done) {
      bigtable.request = function(protoOpts, reqOpts) {
        assert.deepEqual(protoOpts, {
          service: 'BigtableInstanceAdmin',
          method: 'createInstance'
        });

        assert.strictEqual(reqOpts.parent, bigtable.projectName);
        assert.strictEqual(reqOpts.instanceId, INSTANCE_NAME);
        assert.strictEqual(reqOpts.instance.displayName, INSTANCE_NAME);
        done();
      };

      bigtable.createInstance(INSTANCE_NAME, assert.ifError);
    });

    it('should respect the displayName option', function(done) {
      var options = {
        displayName: 'robocop'
      };

      bigtable.request = function(protoOpts, reqOpts) {
        assert.strictEqual(reqOpts.instance.displayName, options.displayName);
        done();
      };

      bigtable.createInstance(INSTANCE_NAME, options, assert.ifError);
    });

    it('should respect the clusters option', function(done) {
      var cluster = {
        name: 'my-cluster',
        location: 'us-central1-b',
        nodes: 3,
        storage: 'ssd'
      };

      var options = {
        clusters: [cluster]
      };

      var fakeLocation = 'a/b/c/d';
      FakeCluster.getLocation_ = function(project, location) {
        assert.strictEqual(project, PROJECT_ID);
        assert.strictEqual(location, cluster.location);
        return fakeLocation;
      };

      var fakeStorage = 20;
      FakeCluster.getStorageType_ = function(storage) {
        assert.strictEqual(storage, cluster.storage);
        return fakeStorage;
      };

      bigtable.request = function(protoOpts, reqOpts) {
        assert.deepEqual(reqOpts.clusters, {
          'my-cluster': {
            location: fakeLocation,
            serveNodes: cluster.nodes,
            defaultStorageType: fakeStorage
          }
        });

        done();
      };

      bigtable.createInstance(INSTANCE_NAME, options, assert.ifError);
    });

    it('should return an error to the callback', function(done) {
      var error = new Error('err');
      var response = {};

      bigtable.request = function(protoOpts, reqOpts, callback) {
        callback(error, response);
      };

      var callback = function(err, instance, operation, apiResponse) {
        assert.strictEqual(err, error);
        assert.strictEqual(instance, null);
        assert.strictEqual(operation, null);
        assert.strictEqual(apiResponse, response);
        done();
      };

      bigtable.createInstance(INSTANCE_NAME, callback);
    });

    it('should pass an operation and instance to the callback', function(done) {
      var response = {
        name: 'my-operation'
      };

      var fakeInstance = {};
      bigtable.instance = function(name) {
        assert.strictEqual(name, INSTANCE_NAME);
        return fakeInstance;
      };

      var fakeOperation = {};
      bigtable.operation = function(name) {
        assert.strictEqual(name, response.name);
        return fakeOperation;
      };

      bigtable.request = function(protoOpts, reqOpts, callback) {
        callback(null, response);
      };

      var callback = function(err, instance, operation, apiResponse) {
        assert.ifError(err);
        assert.strictEqual(instance, fakeInstance);
        assert.strictEqual(operation, fakeOperation);
        assert.strictEqual(operation.metadata, response);
        assert.strictEqual(apiResponse, response);
        done();
      };

      bigtable.createInstance(INSTANCE_NAME, callback);
    });
  });

  describe('getInstances', function() {
    it('should provide the proper request options', function(done) {
      bigtable.request = function(grpcOpts, reqOpts) {
        assert.deepEqual(grpcOpts, {
          service: 'BigtableInstanceAdmin',
          method: 'listInstances'
        });

        assert.strictEqual(reqOpts.parent, bigtable.projectName);
        done();
      };

      bigtable.getInstances(assert.ifError);
    });

    it('should copy all query options', function(done) {
      var fakeOptions = {
        a: 'a',
        b: 'b'
      };

      bigtable.request = function(grpcOpts, reqOpts) {
        Object.keys(fakeOptions).forEach(function(key) {
          assert.strictEqual(reqOpts[key], fakeOptions[key]);
        });

        assert.notStrictEqual(reqOpts, fakeOptions);
        done();
      };

      bigtable.getInstances(fakeOptions, assert.ifError);
    });

    it('should return an error to the callback', function(done) {
      var error = new Error('err');
      var response = {};

      bigtable.request = function(grpcOpts, reqOpts, callback) {
        callback(error, response);
      };

      bigtable.getInstances(function(err, instances, nextQuery, apiResponse) {
        assert.strictEqual(err, error);
        assert.strictEqual(instances, null);
        assert.strictEqual(nextQuery, null);
        assert.strictEqual(apiResponse, response);
        done();
      });
    });

    it('should return an array of instance objects', function(done) {
      var response = {
        instances: [{
          name: 'a'
        }, {
          name: 'b'
        }]
      };

      var fakeInstances = [
        {},
        {}
      ];

      bigtable.request = function(grpcOpts, reqOpts, callback) {
        callback(null, response);
      };

      var instanceCount = 0;

      bigtable.instance = function(name) {
        assert.strictEqual(name, response.instances[instanceCount].name);
        return fakeInstances[instanceCount++];
      };

      bigtable.getInstances(function(err, instances, nextQuery, apiResponse) {
        assert.ifError(err);
        assert.strictEqual(instances[0], fakeInstances[0]);
        assert.strictEqual(instances[0].metadata, response.instances[0]);
        assert.strictEqual(instances[1], fakeInstances[1]);
        assert.strictEqual(instances[1].metadata, response.instances[1]);
        assert.strictEqual(nextQuery, null);
        assert.strictEqual(apiResponse, response);
        done();
      });
    });

    it('should provide a nextQuery object', function(done) {
      var response = {
        instances: [],
        nextPageToken: 'a'
      };

      var options = {
        a: 'b'
      };

      bigtable.request = function(grpcOpts, reqOpts, callback) {
        callback(null, response);
      };

      var callback = function(err, instances, nextQuery) {
        var expectedQuery = extend({}, options, {
          pageToken: response.nextPageToken
        });

        assert.ifError(err);
        assert.deepEqual(nextQuery, expectedQuery);
        done();
      };

      bigtable.getInstances(options, callback);
    });
  });

  describe('instance', function() {
    var INSTANCE_NAME = 'my-instance';

    it('should return an Instance object', function() {
      var instance = bigtable.instance(INSTANCE_NAME);
      var args = instance.calledWith_;

      assert(instance instanceof FakeInstance);
      assert.strictEqual(args[0], bigtable);
      assert.strictEqual(args[1], INSTANCE_NAME);
    });
  });

  describe('operation', function() {
    var OPERATION_NAME = 'my-operation';

    it('should return a GrpcOperation object', function() {
      var operation = bigtable.operation(OPERATION_NAME);
      var args = operation.calledWith_;

      assert(operation instanceof FakeGrpcOperation);
      assert.strictEqual(args[0], bigtable);
      assert.strictEqual(args[1], OPERATION_NAME);
    });
  });

});


text:
package com.devopsbuddy.backend.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

/**
 * Created by madgergely on 2017.02.26..
 */
public class SmtpEmailService extends AbstractEmailService {

    /** The application logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(SmtpEmailService.class);
    private static final String SENDING_EMAIL = "Sending email for: {}";
    private static final String EMAIL_SENT = "Email sent.";

    @Autowired
    private MailSender mailSender;

    @Override
    public void sendGenericEmailMessage(SimpleMailMessage message) {
        LOGGER.debug(SENDING_EMAIL, message);
        mailSender.send(message);
        LOGGER.info(EMAIL_SENT);
    }
}


text:
package com.zookeeper.zkadmin.entities.model.metrics.impl;

import com.zookeeper.zkadmin.entities.model.metrics.Metrics;
import org.joda.time.DateTime;

import java.io.Serializable;

/**
 * @author lamber-ken
 * @date 2017-01-05 19:49
 * @since JDK1.7
 */
public class MntrMetrics implements Metrics,Serializable {

    private static final long serialVersionUID = 1L;

    private String clusterID;
    private String serverID;
    private String version;
    private long avgLatency;
    private long maxLatency;
    private long minLatency;
    private long packetsReceived;
    private long packetsSent;
    private long numAliveConnections;
    private long outstandingRequests;
    private String serverState;
    private long znodeCount;
    private long watchCount;
    private long ephemeralsCount;
    private long approximateDataSize;
    private long openFileDescriptorCount;
    private long followers;
    private long syncedFollowers;
    private long pendingSyncs;

    // extra obtain_timestamp
    private long obtainTimestamp;

    public MntrMetrics(){
        this.obtainTimestamp = DateTime.now().toDate().getTime();
    }

    public String getClusterID() {
        return clusterID;
    }

    public void setClusterID(String clusterID) {
        this.clusterID = clusterID;
    }

    public String getServerID() {
        return serverID;
    }

    public void setServerID(String serverID) {
        this.serverID = serverID;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public long getAvgLatency() {
        return avgLatency;
    }

    public void setAvgLatency(long avgLatency) {
        this.avgLatency = avgLatency;
    }

    public long getMaxLatency() {
        return maxLatency;
    }

    public void setMaxLatency(long maxLatency) {
        this.maxLatency = maxLatency;
    }

    public long getMinLatency() {
        return minLatency;
    }

    public void setMinLatency(long minLatency) {
        this.minLatency = minLatency;
    }

    public long getPacketsReceived() {
        return packetsReceived;
    }

    public void setPacketsReceived(long packetsReceived) {
        this.packetsReceived = packetsReceived;
    }

    public long getPacketsSent() {
        return packetsSent;
    }

    public void setPacketsSent(long packetsSent) {
        this.packetsSent = packetsSent;
    }

    public long getNumAliveConnections() {
        return numAliveConnections;
    }

    public void setNumAliveConnections(long numAliveConnections) {
        this.numAliveConnections = numAliveConnections;
    }

    public long getOutstandingRequests() {
        return outstandingRequests;
    }

    public void setOutstandingRequests(long outstandingRequests) {
        this.outstandingRequests = outstandingRequests;
    }

    public String getServerState() {
        return serverState;
    }

    public void setServerState(String serverState) {
        this.serverState = serverState;
    }

    public long getZnodeCount() {
        return znodeCount;
    }

    public void setZnodeCount(long znodeCount) {
        this.znodeCount = znodeCount;
    }

    public long getWatchCount() {
        return watchCount;
    }

    public void setWatchCount(long watchCount) {
        this.watchCount = watchCount;
    }

    public long getEphemeralsCount() {
        return ephemeralsCount;
    }

    public void setEphemeralsCount(long ephemeralsCount) {
        this.ephemeralsCount = ephemeralsCount;
    }

    public long getApproximateDataSize() {
        return approximateDataSize;
    }

    public void setApproximateDataSize(long approximateDataSize) {
        this.approximateDataSize = approximateDataSize;
    }

    public long getOpenFileDescriptorCount() {
        return openFileDescriptorCount;
    }

    public void setOpenFileDescriptorCount(long openFileDescriptorCount) {
        this.openFileDescriptorCount = openFileDescriptorCount;
    }

    public long getFollowers() {
        return followers;
    }

    public void setFollowers(long followers) {
        this.followers = followers;
    }

    public long getSyncedFollowers() {
        return syncedFollowers;
    }

    public void setSyncedFollowers(long syncedFollowers) {
        this.syncedFollowers = syncedFollowers;
    }

    public long getPendingSyncs() {
        return pendingSyncs;
    }

    public void setPendingSyncs(long pendingSyncs) {
        this.pendingSyncs = pendingSyncs;
    }

    public long getObtainTimestamp() {
        return obtainTimestamp;
    }

    public void setObtainTimestamp(long obtainTimestamp) {
        this.obtainTimestamp = obtainTimestamp;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("version:" + version + "\n");
        sb.append("avgLatency:" + avgLatency + "\n");
        sb.append("maxLatency:" + maxLatency + "\n");
        sb.append("minLatency:" + minLatency + "\n");
        sb.append("packetsReceived:" + packetsReceived + "\n");
        sb.append("packetsSent:" + packetsSent + "\n");
        sb.append("numAliveConnections:" + numAliveConnections + "\n");
        sb.append("outstandingRequests:" + outstandingRequests + "\n");
        sb.append("serverState:" + serverState + "\n");
        sb.append("znodeCount:" + znodeCount + "\n");
        sb.append("watchCount:" + watchCount + "\n");
        sb.append("ephemeralsCount:" + ephemeralsCount + "\n");
        sb.append("approximateDataSize:" + approximateDataSize + "\n");
        sb.append("openFileDescriptorCount:" + openFileDescriptorCount + "\n");
        sb.append("followers:" + followers + "\n");
        sb.append("syncedFollowers:" + syncedFollowers + "\n");
        sb.append("pendingSyncs:" + pendingSyncs + "\n");
        return sb.toString();
    }
}


text: from .slash_ignore_middleware import SlashIgnoreMiddleware


text:
export APP_PATH=/var/www/stt
export SOURCE_PATH=/home/ubuntu/stt
export APP_LOG_PATH=/var/log/stt
export ENV_VARS_FILE=/etc/stt_creds
export NGINX_CONF_PATH=/etc/nginx/conf.d
export LETS_ENCRYPT_PATH=/var/www/letsencrypt

umask 002

# Load environment variables in bashrc
cat /etc/stt_creds | \
  while read line; do
    echo "export $line"
  done >> /home/ubuntu/.bashrc

# Create the required log directories and set permissions
mkdir -p $APP_LOG_PATH
echo "$APP_LOG_PATH/*.log {
	weekly
	rotate 10
	compress
	delaycompress
	missingok
	notifempty
}" > /etc/logrotate.d/stt

# Setup the static files path
rm -rf /var/www/*
mkdir -p /var/www/stt

# Set application file permissions
chown -R stt:stt /var/www $ENV_VARS_FILE $APP_LOG_PATH
chmod -R 6770 /var/www $ENV_VARS_FILE $APP_LOG_PATH

# Export application and database credentials
export $(cat /etc/stt_creds | xargs)

# Setup NGINX
envsubst < ./deploy/nginx/temp.template > $NGINX_CONF_PATH/temp.conf
nginx -t && nginx -s reload

# Setup LetsEncrypt
mkdir -p $LETS_ENCRYPT_PATH /etc/letsencrypt/configs /var/lib/letsencrypt \
  /var/log/letsencrypt
chown -R letsencrypt:letsencrypt $LETS_ENCRYPT_PATH /etc/letsencrypt \
  /var/lib/letsencrypt /var/log/letsencrypt
chmod -R 6770 /etc/letsencrypt /var/lib/letsencrypt /var/log/letsencrypt
envsubst < ./deploy/certbot/certbot_conf.template > \
  /etc/letsencrypt/configs/$TL_HOSTNAME.conf

# Retrieve LetsEncrypt certificates
chmod +x renew_certs.sh
./renew_certs.sh
echo "/var/log/letsencrypt/renew.log {
	weekly
	rotate 10
	compress
	delaycompress
	missingok
	notifempty
}" > /etc/logrotate.d/lerenew

# Load final NGINX config
rm $NGINX_CONF_PATH/temp.conf
envsubst '$TL_HOSTNAME' < ./deploy/nginx/letsencrypt.template > $NGINX_CONF_PATH/letsencrypt.conf
envsubst '$TL_HOSTNAME $LETS_ENCRYPT_PATH' < ./deploy/nginx/stt.template > $NGINX_CONF_PATH/stt.conf
envsubst '$TL_HOSTNAME $LETS_ENCRYPT_PATH' < ./deploy/nginx/odk.template > $NGINX_CONF_PATH/odk.conf
cp ./deploy/nginx/proxy.conf $NGINX_CONF_PATH
nginx -t && nginx -s reload

# Create the STT database
mysql -h $STT_DB_HOST -u $STT_DB_USER --password=$MYSQL_PASSWORD < ./deploy/create_db.sql

# Pull the metadata repository
git submodule update --init

# Start the Docker services
rm docker-compose.yml
ln -s deploy/docker-compose-prod.yml docker-compose.yml
chown -R ubuntu:ubuntu ./
docker-compose up -d

# Bootstrap the application data
docker exec -it app_stt ./app/maintenance/data.js sync
docker exec -it app_stt ./app/maintenance/metadata.js reloadcsv
docker exec -it app_stt ./app/maintenance/users.js add -a $STT_USER $STT_PASSWORD


text:
package org.jivesoftware.sparkimpl.plugin.chat;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JPopupMenu;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.spark.ChatManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.plugin.ContextMenuListener;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.ContactList;
import org.jivesoftware.sparkimpl.plugin.alerts.SparkToaster;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;

/**
 * Allows users to place activity listeners on individual users. This class notifies users when other users
 * come from away or offline to available.
 *
 * @author Derek DeMoro
 */
public class PresenceChangePlugin implements Plugin {

    private final Set<String> sparkContacts = new HashSet<String>();
    private LocalPreferences localPref = SettingsManager.getLocalPreferences();

    public void initialize() {
        // Listen for right-clicks on ContactItem
        final ContactList contactList = SparkManager.getWorkspace().getContactList();

        final Action listenAction = new AbstractAction() {
	    private static final long serialVersionUID = 7705539667621148816L;

	    public void actionPerformed(ActionEvent e) {

		for (ContactItem item : contactList.getSelectedUsers()) {
		    String bareAddress = StringUtils.parseBareAddress(item
			    .getJID());
		    sparkContacts.add(bareAddress);
		}
            }
        };

        listenAction.putValue(Action.NAME, Res.getString("menuitem.alert.when.online"));
        listenAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_ALARM_CLOCK));

	final Action removeAction = new AbstractAction() {
	    private static final long serialVersionUID = -8726129089417116105L;

	    public void actionPerformed(ActionEvent e) {

		for (ContactItem item : contactList.getSelectedUsers()) {
		    String bareAddress = StringUtils.parseBareAddress(item
			    .getJID());
		    sparkContacts.remove(bareAddress);
		}

	    }
	};

        removeAction.putValue(Action.NAME, Res.getString("menuitem.remove.alert.when.online"));
        removeAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_DELETE));

        contactList.addContextMenuListener(new ContextMenuListener() {
            public void poppingUp(Object object, JPopupMenu popup) {
                if (object instanceof ContactItem) {
                    ContactItem item = (ContactItem)object;
                    String bareAddress = StringUtils.parseBareAddress(item.getJID());
                    if (!item.getPresence().isAvailable() || item.getPresence().isAway()) {
                        if (sparkContacts.contains(bareAddress)) {
                            popup.add(removeAction);
                        }
                        else {
                            popup.add(listenAction);
                        }
                    }
                }
            }

            public void poppingDown(JPopupMenu popup) {

            }

            public boolean handleDefaultAction(MouseEvent e) {
                return false;
            }
        });

        // Check presence changes
        SparkManager.getConnection().addPacketListener(new PacketListener() {
	    public void processPacket(final Packet packet) {
		try {
		    EventQueue.invokeAndWait(new Runnable() {
			public void run() {
			    Presence presence = (Presence) packet;
			    if (!presence.isAvailable() || presence.isAway()) {
				return;
			    }
			    String from = presence.getFrom();

			    ArrayList<String> removelater = new ArrayList<String>();

			    for (final String jid : sparkContacts) {
				if (jid.equals(StringUtils
					.parseBareAddress(from))) {
				    removelater.add(jid);
				    // sparkContacts.remove(jid);

				    String nickname = SparkManager
					    .getUserManager()
					    .getUserNicknameFromJID(jid);
				    String time = SparkManager.DATE_SECOND_FORMATTER
					    .format(new Date());
				    String infoText = Res
					    .getString(
						    "message.user.now.available.to.chat",
						    nickname, time);

				    if (localPref.getShowToasterPopup()) {
					SparkToaster toaster = new SparkToaster();
					toaster.setDisplayTime(5000);
					toaster.setBorder(BorderFactory
						.createBevelBorder(0));

					toaster.setToasterHeight(150);
					toaster.setToasterWidth(200);

					toaster.setTitle(nickname);
					toaster.showToaster(null, infoText);

					toaster.setCustomAction(new AbstractAction() {
					    private static final long serialVersionUID = 4827542713848133369L;

					    @Override
					    public void actionPerformed(
						    ActionEvent e) {
						SparkManager.getChatManager()
							.getChatRoom(jid);
					    }
					});
				    }

				    ChatRoom room = SparkManager.getChatManager().getChatRoom(jid);

				    if (localPref.getWindowTakesFocus())
				    {
					SparkManager.getChatManager().activateChat(jid, nickname);
				    }

				    room.getTranscriptWindow().insertNotificationMessage(infoText, ChatManager.NOTIFICATION_COLOR);

				}
			    }
			    for(String s : removelater){
				sparkContacts.remove(s);
			    }
			}
		    });
		} catch (Exception ex) {
		    ex.printStackTrace();
		}
            }
        }, new PacketTypeFilter(Presence.class));
    }

    public void shutdown() {

    }

    public boolean canShutDown() {
        return true;
    }

    public void uninstall() {
        // Do nothing.
    }

    public void addWatch(String user){
	String bareAddress = StringUtils.parseBareAddress(user);
	sparkContacts.add(bareAddress);
    }

    public void removeWatch(String user){
	String bareAddress = StringUtils.parseBareAddress(user);
	sparkContacts.remove(bareAddress);
    }

    public boolean getWatched(String user)
    {
	String bareAddress = StringUtils.parseBareAddress(user);
	return sparkContacts.contains(bareAddress)
;    }

}


text:
module JFP.Threads where

import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad

-- | Makes asynchronous message handler for handling hard tasks. Messages sent
-- while handling previous message are dropped except last one. Last message is
-- always handled.
makeSequencer
  :: (a -> IO ())
  -> IO (a -> IO ())
makeSequencer handler = do
  msgVar <- newEmptyTMVarIO
  let
    sender msg = atomically $ do
      done <- tryPutTMVar msgVar msg
      unless done $ void $ swapTMVar msgVar msg
    worker = forever $ do
      msg <- atomically $ takeTMVar msgVar
      handler msg
  void $ forkIO worker
  return sender


text:
<!doctype html>

 <meta charset="utf-8" />
 <title>Edit Users</title>
 <link rel="stylesheet" href="css/jquery-ui.min.css">
 <link rel="stylesheet" href="css/font-awesome.min.css" />
 <link rel="stylesheet" href="css/users.css" />
 <link rel="stylesheet" type="text/css" href="css/toastr.css">

Edit User Information

      Server
      Username
      API Key
      Delete

      Double click table cell to edit.

   <button id="save">Save Changes</button>


text:
package juice.spi.util;

/**
 * @author Ricky Fung
 */
public class StringUtils {

    // Empty checks
    //-----------------------------------------------------------------------
    /**
     *
Checks if a CharSequence is empty ("") or null.

     *
     *

     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     *

     *
     *
NOTE: This method changed in Lang version 2.0.
     * It no longer trims the CharSequence.
     * That functionality is available in isBlank().

     *
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is empty or null
     */
    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     *
Checks if a CharSequence is not empty ("") and not null.

     *
     *

     * StringUtils.isNotEmpty(null)      = false
     * StringUtils.isNotEmpty("")        = false
     * StringUtils.isNotEmpty(" ")       = true
     * StringUtils.isNotEmpty("bob")     = true
     * StringUtils.isNotEmpty("  bob  ") = true
     *

     *
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is not empty and not null
     */
    public static boolean isNotEmpty(final CharSequence cs) {
        return !isEmpty(cs);
    }

    public static String capitalize(String str) {
        return changeFirstCharacterCase(str, true);
    }

    public static String uncapitalize(String str) {
        return changeFirstCharacterCase(str, false);
    }

    private static String changeFirstCharacterCase(String str, boolean capitalize) {
        if (str == null || str.length() == 0) {
            return str;
        }
        else {
            char baseChar = str.charAt(0);
            char updatedChar;
            if (capitalize) {
                updatedChar = Character.toUpperCase(baseChar);
            }
            else {
                updatedChar = Character.toLowerCase(baseChar);
            }
            if (baseChar == updatedChar) {
                return str;
            }
            char[] chars = str.toCharArray();
            chars[0] = updatedChar;
            return new String(chars, 0, chars.length);
        }
    }
}


text:
var express = require('express');

module.exports = express.static;


text:
import React from "react";
import { storiesOf } from "@storybook/react";
import Popout, { UncontrolledPopout } from "./index";
import { withKnobs, boolean } from "@storybook/addon-knobs";
import { action } from "@storybook/addon-actions";
import styled from "styled-components";
import ScaleTransition from "./ScaleTransition";

const Trigger = styled.button`
  border-radius: 2px;
  box-shadow: none;
  border: 1px solid #ccc;
  background: white;
  padding: 1em 2em;
  outline: none;

  &:active {
    background-color: #ccc;
  }

  &:focus {
    background-color: #eee;
  }
`;

const CloseButton = styled.button`
  border: none;
  background: none;
  position: absolute;
  top: 2em;
  right: 2em;
  font-size: 1em;
  font-weight: 700;
  color: #444;
  text-transform: uppercase;
`;

const Menu = styled.div`
  background-color: white;
  padding: 2em;
  box-shadow: rgba(0, 0, 0, 0.16) 0 5px 20px 0;
  width: 340px;
`;

const CenterXY = styled.div`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
`;

const CenterDecorator = storyFn => <CenterXY>{storyFn()}</CenterXY>;

const trigger = <Trigger>Click me</Trigger>;
const Content = (
  { onClose } // eslint-disable-line react/prop-types
) => (
  <Menu>
    <CloseButton onClick={onClose}>×</CloseButton>

Hello world

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. In ut ratione
      impedit, culpa cupiditate atque distinctio placeat. Beatae nam voluptas
      magnam, repellendus alias in officia nemo, voluptatum est velit vitae

  </Menu>
);

storiesOf("Popout", module)
  .addDecorator(CenterDecorator)
  .addDecorator(withKnobs)
  .add("Stateless", () => (
    <Popout
      open={boolean("open", false)}
      trigger={trigger}
      onToggleOpen={action("toggle open")}
    >
      <Content />
    </Popout>
  ))
  .add("Stateful", () => (
    <UncontrolledPopout trigger={trigger}>
      <Content />
    </UncontrolledPopout>
  ))
  .add("Animated", () => (
    <UncontrolledPopout trigger={trigger} transition={ScaleTransition}>
      <Content />
    </UncontrolledPopout>
  ));