text:
package events

import (
	"context"
	"encoding/json"
	"sync"

	"github.com/lxc/lxd/lxd/storage/memorypipe"
	"github.com/lxc/lxd/shared/api"
)

// InternalListener represents a internal event listener.
type InternalListener struct {
	handlers       map[string]EventHandler
	listener       *Listener
	server         *Server
	ctx            context.Context
	listenerCtx    context.Context
	listenerCancel context.CancelFunc
	lock           sync.Mutex
}

// NewInternalListener returns an InternalListener.
func NewInternalListener(ctx context.Context, server *Server) *InternalListener {
	return &InternalListener{
		ctx:      ctx,
		handlers: map[string]EventHandler{},
		server:   server,
	}
}

// startListener creates a new listener connection and listener. Also, it starts the gorountines
// needed to notify any registered handlers about new events.
func (l *InternalListener) startListener() {
	var err error

	// Create a listener if necessary. This avoids having a listener around if there are no
	// handlers.
	l.listenerCtx, l.listenerCancel = context.WithCancel(l.ctx)
	aEnd, bEnd := memorypipe.NewPipePair(l.listenerCtx)
	listenerConnection := NewSimpleListenerConnection(aEnd)

	l.listener, err = l.server.AddListener("", true, listenerConnection, []string{"lifecycle", "logging"}, []EventSource{EventSourcePull}, nil, nil)
	if err != nil {
		return
	}

	go func(ctx context.Context) {
		l.listener.Wait(ctx)
		l.listener.Close()
		l.listener = nil
	}(l.listenerCtx)

	go func(ctx context.Context, handlers map[string]EventHandler) {
		for {
			select {
			case <-ctx.Done():
				return
			default:
				var event api.Event

				_ = json.NewDecoder(bEnd).Decode(&event)

				for _, handler := range handlers {
					if handler == nil {
						continue
					}

					go handler(event)
				}
			}
		}
	}(l.listenerCtx, l.handlers)
}

// stopListener cancels the context thus stopping the listener.
func (l *InternalListener) stopListener() {
	if l.listenerCancel != nil {
		l.listenerCancel()
	}
}

// AddHandler adds a new event handler.
func (l *InternalListener) AddHandler(name string, handler EventHandler) {
	l.lock.Lock()
	defer l.lock.Unlock()

	if handler == nil {
		return
	}

	// Add handler to the list of handlers.
	l.handlers[name] = handler

	if l.listener == nil {
		l.startListener()
	}
}

// RemoveHandler removes the event handler with the given name.
func (l *InternalListener) RemoveHandler(name string) {
	l.lock.Lock()
	defer l.lock.Unlock()

	for handlerName := range l.handlers {
		if handlerName == name {
			delete(l.handlers, name)
			break
		}
	}

	if len(l.handlers) == 0 {
		// Stop listener to avoid unnecessary goroutines.
		l.stopListener()
	}
}

redpajama_set_name: RedPajamaGithub


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: avi_controllerproperties
author: Gaurav Rastogi (@grastogi23) <grastogi@avinetworks.com>

short_description: Module for setup of ControllerProperties Avi RESTful Object
description:
    - This module is used to configure ControllerProperties object
    - more examples at U(https://github.com/avinetworks/devops)
requirements: [ avisdk ]
version_added: "2.4"
options:
    state:
        description:
            - The state that should be applied on the entity.
        default: present
        choices: ["absent", "present"]
    avi_api_update_method:
        description:
            - Default method for object update is HTTP PUT.
            - Setting to patch will override that behavior to use HTTP PATCH.
        version_added: "2.5"
        default: put
        choices: ["put", "patch"]
    avi_api_patch_op:
        description:
            - Patch operation to use when using avi_api_update_method as patch.
        version_added: "2.5"
        choices: ["add", "replace", "delete"]
    allow_ip_forwarding:
        description:
            - Field introduced in 17.1.1.
            - Default value when not specified in API or module is interpreted by Avi Controller as False.
        type: bool
    allow_unauthenticated_apis:
        description:
            - Allow unauthenticated access for special apis.
            - Default value when not specified in API or module is interpreted by Avi Controller as False.
        type: bool
    allow_unauthenticated_nodes:
        description:
            - Boolean flag to set allow_unauthenticated_nodes.
            - Default value when not specified in API or module is interpreted by Avi Controller as False.
        type: bool
    api_idle_timeout:
        description:
            - Allowed values are 0-1440.
            - Default value when not specified in API or module is interpreted by Avi Controller as 15.
            - Units(MIN).
    appviewx_compat_mode:
        description:
            - Export configuration in appviewx compatibility mode.
            - Field introduced in 17.1.1.
            - Default value when not specified in API or module is interpreted by Avi Controller as False.
        type: bool
    attach_ip_retry_interval:
        description:
            - Number of attach_ip_retry_interval.
            - Default value when not specified in API or module is interpreted by Avi Controller as 360.
            - Units(SEC).
    attach_ip_retry_limit:
        description:
            - Number of attach_ip_retry_limit.
            - Default value when not specified in API or module is interpreted by Avi Controller as 4.
    bm_use_ansible:
        description:
            - Use ansible for se creation in baremetal.
            - Field introduced in 17.2.2.
            - Default value when not specified in API or module is interpreted by Avi Controller as True.
        version_added: "2.5"
        type: bool
    cluster_ip_gratuitous_arp_period:
        description:
            - Number of cluster_ip_gratuitous_arp_period.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(MIN).
    crashed_se_reboot:
        description:
            - Number of crashed_se_reboot.
            - Default value when not specified in API or module is interpreted by Avi Controller as 900.
            - Units(SEC).
    dead_se_detection_timer:
        description:
            - Number of dead_se_detection_timer.
            - Default value when not specified in API or module is interpreted by Avi Controller as 360.
            - Units(SEC).
    dns_refresh_period:
        description:
            - Number of dns_refresh_period.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(MIN).
    dummy:
        description:
            - Number of dummy.
    enable_memory_balancer:
        description:
            - Enable/disable memory balancer.
            - Field introduced in 17.2.8.
            - Default value when not specified in API or module is interpreted by Avi Controller as True.
        version_added: "2.6"
        type: bool
    fatal_error_lease_time:
        description:
            - Number of fatal_error_lease_time.
            - Default value when not specified in API or module is interpreted by Avi Controller as 120.
            - Units(SEC).
    max_dead_se_in_grp:
        description:
            - Number of max_dead_se_in_grp.
            - Default value when not specified in API or module is interpreted by Avi Controller as 1.
    max_pcap_per_tenant:
        description:
            - Maximum number of pcap files stored per tenant.
            - Default value when not specified in API or module is interpreted by Avi Controller as 4.
    max_seq_attach_ip_failures:
        description:
            - Maximum number of consecutive attach ip failures that halts vs placement.
            - Field introduced in 17.2.2.
            - Default value when not specified in API or module is interpreted by Avi Controller as 3.
        version_added: "2.5"
    max_seq_vnic_failures:
        description:
            - Number of max_seq_vnic_failures.
            - Default value when not specified in API or module is interpreted by Avi Controller as 3.
    persistence_key_rotate_period:
        description:
            - Allowed values are 1-1051200.
            - Special values are 0 - 'disabled'.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(MIN).
    portal_token:
        description:
            - Token used for uploading tech-support to portal.
            - Field introduced in 16.4.6,17.1.2.
        version_added: "2.4"
    query_host_fail:
        description:
            - Number of query_host_fail.
            - Default value when not specified in API or module is interpreted by Avi Controller as 180.
            - Units(SEC).
    safenet_hsm_version:
        description:
            - Version of the safenet package installed on the controller.
            - Field introduced in 16.5.2,17.2.3.
        version_added: "2.5"
    se_create_timeout:
        description:
            - Number of se_create_timeout.
            - Default value when not specified in API or module is interpreted by Avi Controller as 900.
            - Units(SEC).
    se_failover_attempt_interval:
        description:
            - Interval between attempting failovers to an se.
            - Default value when not specified in API or module is interpreted by Avi Controller as 300.
            - Units(SEC).
    se_offline_del:
        description:
            - Number of se_offline_del.
            - Default value when not specified in API or module is interpreted by Avi Controller as 172000.
            - Units(SEC).
    se_vnic_cooldown:
        description:
            - Number of se_vnic_cooldown.
            - Default value when not specified in API or module is interpreted by Avi Controller as 120.
            - Units(SEC).
    secure_channel_cleanup_timeout:
        description:
            - Number of secure_channel_cleanup_timeout.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(MIN).
    secure_channel_controller_token_timeout:
        description:
            - Number of secure_channel_controller_token_timeout.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(MIN).
    secure_channel_se_token_timeout:
        description:
            - Number of secure_channel_se_token_timeout.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(MIN).
    seupgrade_fabric_pool_size:
        description:
            - Pool size used for all fabric commands during se upgrade.
            - Default value when not specified in API or module is interpreted by Avi Controller as 20.
    seupgrade_segroup_min_dead_timeout:
        description:
            - Time to wait before marking segroup upgrade as stuck.
            - Default value when not specified in API or module is interpreted by Avi Controller as 360.
            - Units(SEC).
    ssl_certificate_expiry_warning_days:
        description:
            - Number of days for ssl certificate expiry warning.
            - Units(DAYS).
    unresponsive_se_reboot:
        description:
            - Number of unresponsive_se_reboot.
            - Default value when not specified in API or module is interpreted by Avi Controller as 300.
            - Units(SEC).
    upgrade_dns_ttl:
        description:
            - Time to account for dns ttl during upgrade.
            - This is in addition to vs_scalein_timeout_for_upgrade in se_group.
            - Field introduced in 17.1.1.
            - Default value when not specified in API or module is interpreted by Avi Controller as 5.
            - Units(SEC).
    upgrade_lease_time:
        description:
            - Number of upgrade_lease_time.
            - Default value when not specified in API or module is interpreted by Avi Controller as 360.
            - Units(SEC).
    url:
        description:
            - Avi controller URL of the object.
    uuid:
        description:
            - Unique object identifier of the object.
    vnic_op_fail_time:
        description:
            - Number of vnic_op_fail_time.
            - Default value when not specified in API or module is interpreted by Avi Controller as 180.
            - Units(SEC).
    vs_apic_scaleout_timeout:
        description:
            - Time to wait for the scaled out se to become ready before marking the scaleout done, applies to apic configuration only.
            - Default value when not specified in API or module is interpreted by Avi Controller as 360.
            - Units(SEC).
    vs_awaiting_se_timeout:
        description:
            - Number of vs_awaiting_se_timeout.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(SEC).
    vs_key_rotate_period:
        description:
            - Allowed values are 1-1051200.
            - Special values are 0 - 'disabled'.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(MIN).
    vs_se_attach_ip_fail:
        description:
            - Time to wait before marking attach ip operation on an se as failed.
            - Field introduced in 17.2.2.
            - Default value when not specified in API or module is interpreted by Avi Controller as 3600.
            - Units(SEC).
        version_added: "2.5"
    vs_se_bootup_fail:
        description:
            - Number of vs_se_bootup_fail.
            - Default value when not specified in API or module is interpreted by Avi Controller as 480.
            - Units(SEC).
    vs_se_create_fail:
        description:
            - Number of vs_se_create_fail.
            - Default value when not specified in API or module is interpreted by Avi Controller as 1500.
            - Units(SEC).
    vs_se_ping_fail:
        description:
            - Number of vs_se_ping_fail.
            - Default value when not specified in API or module is interpreted by Avi Controller as 60.
            - Units(SEC).
    vs_se_vnic_fail:
        description:
            - Number of vs_se_vnic_fail.
            - Default value when not specified in API or module is interpreted by Avi Controller as 300.
            - Units(SEC).
    vs_se_vnic_ip_fail:
        description:
            - Number of vs_se_vnic_ip_fail.
            - Default value when not specified in API or module is interpreted by Avi Controller as 120.
            - Units(SEC).
    warmstart_se_reconnect_wait_time:
        description:
            - Number of warmstart_se_reconnect_wait_time.
            - Default value when not specified in API or module is interpreted by Avi Controller as 300.
            - Units(SEC).
extends_documentation_fragment:
    - avi
'''

EXAMPLES = """
- name: Example to create ControllerProperties object
  avi_controllerproperties:
    controller: 10.10.25.42
    username: admin
    password: something
    state: present
    name: sample_controllerproperties
"""

RETURN = '''
obj:
    description: ControllerProperties (api/controllerproperties) object
    returned: success, changed
    type: dict
'''

from ansible.module_utils.basic import AnsibleModule
try:
    from ansible.module_utils.network.avi.avi import (
        avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:
    HAS_AVI = False

def main():
    argument_specs = dict(
        state=dict(default='present',
                   choices=['absent', 'present']),
        avi_api_update_method=dict(default='put',
                                   choices=['put', 'patch']),
        avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
        allow_ip_forwarding=dict(type='bool',),
        allow_unauthenticated_apis=dict(type='bool',),
        allow_unauthenticated_nodes=dict(type='bool',),
        api_idle_timeout=dict(type='int',),
        appviewx_compat_mode=dict(type='bool',),
        attach_ip_retry_interval=dict(type='int',),
        attach_ip_retry_limit=dict(type='int',),
        bm_use_ansible=dict(type='bool',),
        cluster_ip_gratuitous_arp_period=dict(type='int',),
        crashed_se_reboot=dict(type='int',),
        dead_se_detection_timer=dict(type='int',),
        dns_refresh_period=dict(type='int',),
        dummy=dict(type='int',),
        enable_memory_balancer=dict(type='bool',),
        fatal_error_lease_time=dict(type='int',),
        max_dead_se_in_grp=dict(type='int',),
        max_pcap_per_tenant=dict(type='int',),
        max_seq_attach_ip_failures=dict(type='int',),
        max_seq_vnic_failures=dict(type='int',),
        persistence_key_rotate_period=dict(type='int',),
        portal_token=dict(type='str', no_log=True,),
        query_host_fail=dict(type='int',),
        safenet_hsm_version=dict(type='str',),
        se_create_timeout=dict(type='int',),
        se_failover_attempt_interval=dict(type='int',),
        se_offline_del=dict(type='int',),
        se_vnic_cooldown=dict(type='int',),
        secure_channel_cleanup_timeout=dict(type='int',),
        secure_channel_controller_token_timeout=dict(type='int',),
        secure_channel_se_token_timeout=dict(type='int',),
        seupgrade_fabric_pool_size=dict(type='int',),
        seupgrade_segroup_min_dead_timeout=dict(type='int',),
        ssl_certificate_expiry_warning_days=dict(type='list',),
        unresponsive_se_reboot=dict(type='int',),
        upgrade_dns_ttl=dict(type='int',),
        upgrade_lease_time=dict(type='int',),
        url=dict(type='str',),
        uuid=dict(type='str',),
        vnic_op_fail_time=dict(type='int',),
        vs_apic_scaleout_timeout=dict(type='int',),
        vs_awaiting_se_timeout=dict(type='int',),
        vs_key_rotate_period=dict(type='int',),
        vs_se_attach_ip_fail=dict(type='int',),
        vs_se_bootup_fail=dict(type='int',),
        vs_se_create_fail=dict(type='int',),
        vs_se_ping_fail=dict(type='int',),
        vs_se_vnic_fail=dict(type='int',),
        vs_se_vnic_ip_fail=dict(type='int',),
        warmstart_se_reconnect_wait_time=dict(type='int',),
    )
    argument_specs.update(avi_common_argument_spec())
    module = AnsibleModule(
        argument_spec=argument_specs, supports_check_mode=True)
    if not HAS_AVI:
        return module.fail_json(msg=(
            'Avi python API SDK (avisdk>=17.1) is not installed. '
            'For more details visit https://github.com/avinetworks/sdk.'))
    return avi_ansible_api(module, 'controllerproperties',
                           set(['portal_token']))

if __name__ == '__main__':
    main()


text:
class CBlockIndex;

namespace GRC {

class Claim;
class Cpid;
class Magnitude;
class MiningId;
class QuorumHash;
class Superblock;
class SuperblockPtr;

//!
//! \brief A CPID's project magnitude record produced from scraper statistics.
//!
class ExplainMagnitudeProject
{
public:
    std::string m_name; //!< Project name.
    double m_rac;       //!< CPID's recent average credit for the project.
    double m_magnitude; //!< CPID's magnitude for the project.

    //!
    //! \brief Initialize a new project magnitude record.
    //!
    //! \param name      Project name.
    //! \param rac       CPID's recent average credit for the project.
    //! \param magnitude CPID's magnitude for the project.
    //!
    ExplainMagnitudeProject(std::string name, double rac, double magnitude)
        : m_name(std::move(name))
        , m_rac(rac)
        , m_magnitude(magnitude)
    {
    }
}; // ExplainMagnitudeProject

//!
//! \brief Produces, stores, and validates superblocks.
//!
//! The quorum system enables the Gridcoin network to arrive at a consensus on
//! the daily superblocks. The legacy strategy for historical blocks follows a
//! protocol wherein nodes vote for superblocks. After switching to version 11
//! blocks, nodes create and validate superblocks from scraper convergences.
//!
//! This class is designed as a facade that provides an interface for the rest
//! of the application. It consumes information from newly-connected blocks to
//! update the superblock data for research reward calculations.
//!
//! THREAD SAFETY: The quorum system interacts closely with pointers to blocks
//! in the chain index. Always lock cs_main before calling its methods.
//!
class Quorum
{
public:
    //!
    //! \brief Determine whether the provided address participates in the
    //! quorum consensus at the specified time.
    //!
    //! \param address Default wallet address of a node in the network.
    //! \param time    Timestamp to check participation at.
    //!
    //! \return \c true if the address matches the subset of addresses that
    //! particpate in the quorum on the day of the year of \p time.
    //!
    static bool Participating(const std::string& address, const int64_t time);

    //!
    //! \brief Get the hash of the pending superblock with the greatest vote
    //! weight.
    //!
    //! \param pindex Provides context about the chain tip used to calculate
    //! quorum vote weights.
    //!
    //! \return Quorum hash of the most popular superblock or an invalid hash
    //! when no nodes voted in the current superblock cycle.
    //!
    static QuorumHash FindPopularHash(const CBlockIndex* const pindex);

    //!
    //! \brief Store a node's vote for a pending superblock in the cache.
    //!
    //! \param quorum_hash Hash of the superblock the node voted for.
    //! \param grc_address Default wallet address of the node.
    //! \param pindex      The block that contains the vote to store.
    //!
    static void RecordVote(
        const QuorumHash quorum_hash,
        const std::string& grc_address,
        const CBlockIndex* const pindex);

    //!
    //! \brief Remove a node's vote for a pending superblock from the cache.
    //!
    //! \param pindex The block that contains the vote to remove.
    //!
    static void ForgetVote(const CBlockIndex* const pindex);

    //!
    //! \brief Validate a superblock published to the network for the day.
    //!
    //! \param claim      Contains the superblock data staked in a block.
    //! \param superblock The claim's superblock to validate.
    //! \param pindex     Provides context for the block containing the superblock.
    //!
    static bool ValidateSuperblockClaim(
        const Claim& claim,
        const SuperblockPtr& superblock,
        const CBlockIndex* const pindex);

    //!
    //! \brief Validate the supplied superblock by comparing it to the node's
    //! local manifest data.
    //!
    //! \param superblock The superblock to validate.
    //! \param use_cache  If \c false, skip validation with the scraper cache.
    //! \param hint_bits  For testing by-project fallback validation.
    //!
    //! \return \c true if local manifest data produces a matching superblock.
    //!
    static bool ValidateSuperblock(
        const SuperblockPtr& superblock,
        const bool use_cache = true,
        const size_t hint_bits = 32);

    //!
    //! \brief Get the current magnitude for the specified CPID.
    //!
    //! \param cpid The CPID to fetch the magnitude for.
    //!
    //! \return Magnitude as of the last tallied superblock.
    //!
    static Magnitude GetMagnitude(const Cpid cpid);

    //!
    //! \brief Get the current magnitude for the specified mining ID.
    //!
    //! \param cpid May contain a CPID to fetch the magnitude for.
    //!
    //! \return Magnitude as of the last tallied superblock or zero if the
    //! mining ID represents an investor.
    //!
    static Magnitude GetMagnitude(const MiningId mining_id);

    //!
    //! \brief Generate a report from scraper statistics that contains the
    //! project-level magnitude and recent average credit for a CPID.
    //!
    //! \param cpid CPID to generate the report for.
    //!
    //! \return A set of records with statistics for each project.
    //!
    static std::vector<ExplainMagnitudeProject> ExplainMagnitude(const Cpid cpid);

    //!
    //! \brief Get a reference to the current active superblock.
    //!
    //! \return The most recent superblock applied by the tally.
    //!
    static SuperblockPtr CurrentSuperblock();

    //!
    //! \brief Get a reference to the upcoming superblock.
    //!
    //! After a node receives a new superblock, the tally must commit it before
    //! it becomes active.
    //!
    //! \return A superblock pending activation if one exists. Returns an empty
    //! superblock when the tally already activated the latest superblock.
    //!
    static SuperblockPtr PendingSuperblock();

    //!
    //! \brief Determine whether any superblocks are pending activation.
    //!
    //! \return \c true if the index contains a superblock loaded at a height
    //! above the last tally window.
    //!
    static bool HasPendingSuperblock();

    //!
    //! \brief Determine whether the network expects a new superblock.
    //!
    //! \param now Timestamp to consider as the current time.
    //!
    //! \return \c true if the age of the current superblock exceeds the
    //! protocol's superblock spacing parameter.
    //!
    static bool SuperblockNeeded(const int64_t now);

    //!
    //! \brief Initialize the tally's superblock context.
    //!
    //! \param pindexLast The most recent block to begin loading backward from.
    //!
    static void LoadSuperblockIndex(const CBlockIndex* pindexLast);

    //!
    //! \brief Create a new superblock from scraper convergence data.
    //!
    //! \return A new superblock to publish to the network.
    //!
    static Superblock CreateSuperblock();

    //!
    //! \brief Push a new superblock into the tally.
    //!
    //! \param superblock Contains the superblock data to load.
    //!
    static void PushSuperblock(SuperblockPtr superblock);

    //!
    //! \brief Drop the last superblock loaded into the tally.
    //!
    //! \param pindex Represents the block that contains the superblock to drop.
    //!
    static void PopSuperblock(const CBlockIndex* const pindex);

    //!
    //! \brief Activate the superblock received at or below the specified
    //! height.
    //!
    //! \param height The maximum height to activate superblocks up to.
    //!
    //! \return \c true if a superblock at or below the specified height was
    //! activated.
    //!
    static bool CommitSuperblock(const uint32_t height);
};
}

#endif // GRIDCOIN_QUORUM_H


text:
/*
 By Osvaldas Valutis, www.osvaldas.info
 Available for use under the MIT License
 */

'use strict';

;( function ( document, window, index )
{
    var div = document.querySelector( '.form-group.place_logo' );

    var label	 = div.nextElementSibling;
    var labelVal = label.innerHTML;

    var fileInput = document.getElementById("logo");
    console.log(fileInput);
    fileInput.addEventListener( 'change', function( e )
    {
        console.log("change");
        var fileName = '';
        console.log(this.files);
        console.log(this.files.length);

        if( this.files && this.files.length > 1 )
            fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
        else
            fileName = e.target.value.split( '\\' ).pop();

        if( fileName )
            label.querySelector( 'span' ).innerHTML = fileName;
        else
            label.innerHTML = labelVal;
    });

    // Firefox bug fix
    fileInput.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); });
    fileInput.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); });

}( document, window, 0 ));

/*
 By Osvaldas Valutis, www.osvaldas.info
 Available for use under the MIT License
 */
//
//'use strict';
//
//;( function( $, window, document, undefined )
//{
//    $( '.form-group.place_logo' ).each( function()
//    {
//        var $div	 = $( this ),
//            $label	 = $div.next( 'label' ),
//            labelVal = $label.html(),
//            $input = $('.file.form-control');
//        console.log($input);
//        $input.on( 'change', function( e )
//        {
//            console.log('change');
//            var fileName = '';
//
//            if( this.files && this.files.length > 1 )
//                fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
//            else if( e.target.value )
//                fileName = e.target.value.split( '\\' ).pop();
//
//            if( fileName )
//                $label.find( 'span' ).html( fileName );
//            else
//                $label.html( labelVal );
//        });
//
//        // Firefox bug fix
//        $input
//            .on( 'focus', function(){ $input.addClass( 'has-focus' ); })
//            .on( 'blur', function(){ $input.removeClass( 'has-focus' ); });
//    });
//})( jQuery, window, document );


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require(APPPATH.'libraries/api/T_API_Controller.php');

/**
 *
 * The Settings Controller/Endpoint
 *
 * @uses 			API Controller
 * @package        	CodeIgniter
 * @subpackage    	Libraries
 * @category    	Libraries
 * @author        	Bo Thomsen
 * @version 		1.0
 */
class API_Settings extends T_API_Controller {

	/**
	 * This function is called on any request send to this endpoint,
	 * it loads up all the needed files
	 * @since 1.0
	 * @access public
	 */
	public function __construct () {
		parent::__construct();
	}

	/**
	 *    Empties all the system databases
	 *
	 */
	public function empty_get () {
		$databases = array(
			"errors",
			"scraper_runs",
			"history",
			"scrape_statistics",
			"tweet_words",
			"tweets",
			"tweet_hashtags",
			"tweet_alert_strings",
			"tweet_mentions",
			"tweet_urls",
			"tweet_media"
		);

		$this->load->model("cleanup_model");

		$this->cleanup_model->empty_databases($databases);
	}

	/**
	 * Updates the twitter account information
	 */
	public function twitter_post () {
		$this->load->model("settings_model");

		if ( ! $this->post("twitter") ) {
			$this->response(array(
				"status" => false,
				"error_messages" => array(
					$this->lang->line("admin_missing_post_data")
				)
			), 400);
		}

		if ( ! $this->settings_model->save_twitter($this->post("twitter"))  ) {
			$this->response(array(
				"status" => false,
				"error_messages" => array(
					$this->lang->line("admin_post_data_error")
				)
			), 400);
		} else {
			$this->response(array(
				"status" => true
			), 200);
		}
	}

	/**
	 * Removes a twitter account
	 */
	public function remove_twitter_get () {
		if ( ! $this->get("account") ) {
			$this->response(array(
				"status" => false,
				"error_messages" => array(
					$this->lang->line("admin_missing_account_id")
				)
			), 400);
		}

		$this->load->model("settings_model");

		$this->settings_model->delete_twitter_account($this->get("account"));

		$this->response(array(
			"status" => true
		), 200);
	}

	/**
	 * Batch insert/update settings
	 */
	public function settings_post () {
		if ( ! $this->post("keys") ) {
			$this->response(array(
				"status" => false,
				"error_messages" => array(
					$this->lang->line("admin_missing_post_data")
				)
			), 400);
		}

		$this->load->model("settings_model");

		foreach ( $this->post("keys") as $key) {
			$type = "text";

			if ( isset($key["type"]) ) {
				$type = $key["type"];
			}

			$this->settings_model->set_setting($key["key"], $key["value"], $key["section"], $type);
		}

		$this->response(array(
			"status" => true
		), 200);
	}

	/**
	 * Removes a settings key
	 */
	public function setting_delete () {
		if ( ! $this->get("key") ) {
			$this->response(array(
				"status" => false,
				"error_messages" => array(
					$this->lang->line("admin_missing_key_name")
				)
			), 400);
		}

		$this->load->model("settings_model");

		$this->settings_model->delete_setting($this->get("key"));

		$this->response(array(
			"status" => true
		), 200);
	}

	/**
	 * Retrieves a settings value
	 */
	public function setting_get () {
		if ( ! $this->get("key") ) {
			$this->response(array(
				"status" => false,
				"error_messages" => array(
					$this->lang->line("admin_missing_key_name")
				)
			), 400);
		}

		$this->load->model("settings_model");

		$this->settings_model->get_setting($this->get("key"));

		$this->response(array(
			"status" => true
		), 200);
	}

	/**
	 * Updates a setting
	 */
	public function setting_post () {
		if ( ! $this->get("key") || ! $this->post("value") ) {
			$this->response(array(
				"status" => false,
				"error_messages" => array(
					$this->lang->line("admin_missing_key_name")
				)
			), 400);
		}

		$this->load->model("settings_model");

		$type = "text";

		if ( $this->post("type") ) {
			$type = $this->post("type");
		}

		$this->settings_model->set_setting($this->get("key"), $this->post("value"), $this->post("section"), $type);

		$this->response(array(
			"status" => true
		), 200);
	}
}


text:
#import "TempVController.h"

@interface TempVController ()

// Initialization property and global variable

@end

@implementation TempVController

#pragma mark - Initialization

#pragma mark - Getter

#pragma mark - Setter

#pragma mark - Public Method

#pragma mark - Private Method

#pragma mark - Life Cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    NSLog(@"parentViewController --- %@",self.parentViewController);
}

#pragma mark - All Delegate

@end


text:
<?php

namespace Oro\Bundle\ImapBundle\Tests\Unit\Entity;

use Oro\Bundle\EmailBundle\Tests\Unit\ReflectionUtil;
use Oro\Bundle\ImapBundle\Entity\UserEmailOrigin;

/**
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
 */
class UserEmailOriginTest extends \PHPUnit\Framework\TestCase
{
    public function testGetId()
    {
        $origin = new UserEmailOrigin();
        ReflectionUtil::setId($origin, 123);
        $this->assertEquals(123, $origin->getId());
    }

    public function testImapHostGetterAndSetter()
    {
        $origin = new UserEmailOrigin();
        $this->assertNull($origin->getImapHost());
        $origin->setImapHost('test');
        $this->assertEquals('test', $origin->getImapHost());
    }

    public function testImapPortGetterAndSetter()
    {
        $origin = new UserEmailOrigin();
        $this->assertEquals(null, $origin->getImapPort());
        $origin->setImapPort(123);
        $this->assertEquals(123, $origin->getImapPort());
    }

    public function testSslGetterAndSetter()
    {
        $origin = new UserEmailOrigin();
        $this->assertNull($origin->getImapEncryption());
        $origin->setImapEncryption('test');
        $this->assertEquals('test', $origin->getImapEncryption());
    }

    public function testUserGetterAndSetter()
    {
        $origin = new UserEmailOrigin();
        $this->assertNull($origin->getUser());
        $origin->setUser('test');
        $this->assertEquals('test', $origin->getUser());
    }

    public function testPasswordGetterAndSetter()
    {
        $origin = new UserEmailOrigin();
        $this->assertNull($origin->getPassword());
        $origin->setPassword('test');
        $this->assertEquals('test', $origin->getPassword());
    }

    public function testSmtpHostGetterAndSetter()
    {
        $origin = new UserEmailOrigin();
        $this->assertNull($origin->getSmtpHost());
        $origin->setSmtpHost('test');
        $this->assertEquals('test', $origin->getSmtpHost());
    }

    public function testSmtpPortGetterAndSetter()
    {
        $origin = new UserEmailOrigin();
        $this->assertEquals(null, $origin->getSmtpPort());
        $origin->setSmtpPort(123);
        $this->assertEquals(123, $origin->getSmtpPort());
    }

    /**
     * @param string $password
     * @param string $accessToken
     *
     * @dataProvider setDataProviderSmtpConfiguredSuccess
     */
    public function testIsSmtpConfiguredSuccess($password, $accessToken)
    {
        $origin = new UserEmailOrigin();
        $origin->setSmtpHost('host');
        $origin->setSmtpPort(25);
        $origin->setUser('test');
        $origin->setPassword($password);
        $origin->setAccessToken($accessToken);
        $origin->setSmtpEncryption('ssl');

        $this->assertTrue($origin->isSmtpConfigured());
    }

    /**
     * @return array
     */
    public function setDataProviderSmtpConfiguredSuccess()
    {
        return [
            'empty token' => [
                'password' => 'password',
                'accessToken' => ''
            ],
            'empty password' => [
                'password' => '',
                'accessToken' => 'token'
            ]
        ];
    }

    public function testIsSmtpConfiguredFailure()
    {
        $origin = new UserEmailOrigin();
        $origin->setSmtpHost('');
        $origin->setSmtpPort('');
        $origin->setUser('');
        $origin->setPassword('');
        $origin->setSmtpEncryption('');

        $this->assertFalse($origin->isSmtpConfigured());
    }

    /**
     * @param string $host
     * @param int $port
     * @param string $user
     * @param string $password
     * @param string $accessToken
     * @param bool $expectedResult
     *
     * @dataProvider setDataProviderImapConfigured
     */
    public function testIsImapConfigured($host, $port, $user, $password, $accessToken, $expectedResult)
    {
        $origin = new UserEmailOrigin();
        $origin->setImapHost($host);
        $origin->setImapPort($port);
        $origin->setUser($user);
        $origin->setPassword($password);
        $origin->setAccessToken($accessToken);
        $origin->setSmtpEncryption('ssl');

        $this->assertEquals($expectedResult, $origin->isImapConfigured());
    }

    /**
     * @return array
     */
    public function setDataProviderImapConfigured()
    {
        return [
            'empty host' => [
                'host' => null,
                'port' => 25,
                'user' => 'test',
                'password' => 'password',
                'accessToken' => 'token',
                'expectedResult' => false
            ],
            'empty port' => [
                'host' => 'host',
                'port' => null,
                'user' => 'test',
                'password' => 'password',
                'accessToken' => 'token',
                'expectedResult' => false
            ],
            'empty user' => [
                'host' => 'host',
                'port' => 25,
                'user' => null,
                'password' => 'password',
                'accessToken' => 'token',
                'expectedResult' => false
            ],
            'empty password and token' => [
                'host' => 'host',
                'port' => 25,
                'user' => 'test',
                'password' => '',
                'accessToken' => '',
                'expectedResult' => false
            ],
            'success with password' => [
                'host' => 'host',
                'port' => 25,
                'user' => 'test',
                'password' => 'password',
                'accessToken' => '',
                'expectedResult' => true
            ],
            'success with token' => [
                'host' => 'host',
                'port' => 25,
                'user' => 'test',
                'password' => '',
                'accessToken' => 'token',
                'expectedResult' => true
            ]
        ];
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class JobAnalysis extends CI_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->model('JobAnalysis_model');
	}

	public function getAnalysis() {
		$result = $this->JobAnalysis_model->getAnalysis();
		if ($result) {
			$response["result"] = "success";
			$response["message"] = urlencode("获取职位分析成功");
			$response["getAnalysis"] = $result;
			return urldecode(json_encode($response));
		}
		else {
			$response["result"] = "failure";
			$response["message"] = urlencode("获取职位分析失败");
			return urldecode(json_encode($response));
		}
	}

	/**
	 * Gets the message parameter not empty.
	 *
	 * @return     <json>  The message parameter not empty.
	 */
	public function getMsgParamNotEmpty() {
		$response["result"] = "failure";
		$response["message"] = urlencode("输入不能为空");
		return urldecode(json_encode($response));
	}

	/**
	 * Gets the message invalid parameter.
	 *
	 * @return     <json>  The message invalid parameter.
	 */
	public function getMsgInvalidParam() {
		$response["result"] = "failure";
		$response["message"] = urlencode("格式不正确");
		return urldecode(json_encode($response));
	}
}

$fun = new JobAnalysis();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	$data = json_decode(file_get_contents("php://input"));
	if (isset($data->operation)) {
		$operation = $data->operation;
		if (!empty($operation)) {
			if ($operation == 'getAnalysis') {
					echo $fun->getAnalysis();
					exit;
				}
				else {
					echo $fun->getMsgInvalidParam();
					exit;
				}
			}
		else {
			echo $fun->getMsgParamNotEmpty();
			exit;
		}
	}
	else {
		echo $fun->getMsgInvalidParam();
		exit;
	}
}
else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
	echo "职位分析";
	exit;
}


text:
// Modified work
// Copyright (c) 2016 The HellBender Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef HB_CORE_METAOBJECT_H
#define HB_CORE_METAOBJECT_H

#include "AbstractMetaObject.h"

#include <memory>
#include <string>

namespace hellbender {

template <class Derived, class Base>
class MetaObject :
  public AbstractMetaObject<Base>
{
public:
    MetaObject(const std::string& className, const std::string& baseClassName) :
      AbstractMetaObject<Base>(className, baseClassName)
    {
    }

    std::shared_ptr<Base> create() const override
    {
        return std::make_shared<Derived>();
    }
};

}

#endif


text:
namespace caf::detail {

void log_cstring_error(const char* cstring) {
  CAF_IGNORE_UNUSED(cstring);
  CAF_LOG_ERROR(cstring);
}

} // namespace caf::detail


text: import falcon


text:
package main;
/**
 * Class to demonstrate request handling / matching of parameters.
 *
 * @author Rocco Schulz
 */

import org.vertx.java.busmods.BusModBase;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.core.http.ServerWebSocket;
import org.vertx.java.core.json.DecodeException;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;

public class Server extends BusModBase {
	private String webRoot;
	private int port;
	private EventBus eBus;
	private Logger logger;

	private Handler<ServerWebSocket> socketHandler = new Handler<ServerWebSocket>() {
	    public void handle(final ServerWebSocket ws) {
	    	ws.dataHandler(new Handler<Buffer>() {
	            public void handle(Buffer buffer) {
	            	logger.info("socketHandler:");
	            	logger.info(buffer.toString());
	                ws.writeBuffer(buffer);
	            }
	        });
	}};

    /**
     * Registers client in an address room.
     */
    private Handler<Message> formCreateHandler = new Handler<Message>() {
        public void handle(Message message) {
            //TODO: assign "room" for communication / register client in room
        	logger.info("not yet implemented");
        	logger.info(message.body);
        }
    };

    /**
     * Forwards form data to the websocket clients.
     */
    private Handler<Message> formDataHandler = new Handler<Message>() {
        public void handle(Message message) {
        	logger.info("message body: " +  message.body);
        	JsonObject json = new JsonObject(message.body.toString());
        	String address = "form.data.client." + json.getString("formid");
        	logger.info("Address: " + address);
        	eBus.publish(address, json);
        }
    };

	/**
	 * Triggers the fee calculation based on the given form data.
	 */
	private Handler<HttpServerRequest> calcHandler = new Handler<HttpServerRequest>() {
		public void handle(final HttpServerRequest req) {
			// read body of request
			req.bodyHandler(new Handler<Buffer>() {
				@Override
				public void handle(Buffer buff) {
					JsonObject form;
					try{
						form = new JsonObject(buff.toString());
					} catch(DecodeException ex){
						form = new JsonObject();
					}

					// trigger calculation in worker verticle
					eBus.send("form.calculate", form,
							new Handler<Message<JsonObject>>() {
								public void handle(Message<JsonObject> message) {
									req.response.headers().put("Content-Type", "application/json; charset=utf-8");
									req.response.end(message.body.encode());
								}
							});
				}
			});

		}
	};

	/**
	 * Triggers the evaluation of the form instance.
	 */
	private Handler<HttpServerRequest> formHandler = new Handler<HttpServerRequest>() {
		public void handle(final HttpServerRequest req) {
			// read body of request
			req.bodyHandler(new Handler<Buffer>() {
				@Override
				public void handle(Buffer buff) {
					JsonArray form = new JsonArray(buff.toString());
					// trigger calculation in worker verticle
					eBus.send("form.submit", form,
							new Handler<Message<JsonArray>>() {
								public void handle(Message<JsonArray> message) {
									req.response.end(message.body.encode());
								}
							});
				}
			});

		}
	};

	/**
	 * Interprets the request path as file request and returns the file if present in the UI folder.
	 */
    private Handler<HttpServerRequest> fileHandler = new Handler<HttpServerRequest>() {
        public void handle(HttpServerRequest req) {
        	if (req.path.equals("/")) {
                req.response.sendFile(webRoot + "index.html");
              } else {
                //FIXME: This is clearly a security issue.
            	//		 Kept simple for demonstration purposes.
                req.response.sendFile(webRoot + req.path);
              }
        }
    };

    public void start() {
    	logger = container.getLogger();
    	eBus = vertx.eventBus();
        RouteMatcher rm = new RouteMatcher();
        EventBus eb = vertx.eventBus();

        //read configuration file if present
         port = 8080;//getOptionalIntConfig("port", 8080);
         webRoot = "../UI";//getOptionalStringConfig("web_root", "web");

        //normal HTTP handlers
        rm.post("/pricecalculation", calcHandler);
        rm.post("/insurances", formHandler);
        rm.noMatch(fileHandler);

        eb.registerHandler("form.create", this.formCreateHandler);
        eb.registerHandler("form.data", this.formDataHandler);

        HttpServer server = vertx.createHttpServer()
        .requestHandler(rm)
        .websocketHandler(socketHandler);
        //for SSL uncomment lines below
        //.setSSL(true)
        //.setKeyStorePath("/path/to/your/keystore/server-keystore.jks")
        //.setKeyStorePassword("password")

        JsonObject bridgeConfig = new JsonObject().putString("prefix", "/eventbus");

        JsonArray inboundPermitted = new JsonArray();
        JsonArray outboundPermitted = new JsonArray();
        // Let through any messages related to form creation and updates
        JsonObject addressData = new JsonObject().putString("address", "form.data");
        JsonObject addressCreate = new JsonObject().putString("address", "form.create");
        inboundPermitted.add(addressData);
        inboundPermitted.add(addressCreate);
        outboundPermitted.add(new JsonObject().putString("address_re", "form.data.client\\.\\d+"));
        //all allowed: new JsonArray().add(new JsonObject()
        vertx.createSockJSServer(server).bridge(bridgeConfig, inboundPermitted,  outboundPermitted);
        server.listen(port, "127.0.0.1");
    }
}


text:
cask "dcp-o-matic-playlist-editor" do
  version "2.16.24"
  sha256 "d31c2c7d79cf177b7ebb3f9a18833d8963a7d571e9fd954ed97de678cef7f758"

  url "https://dcpomatic.com/dl.php?id=osx-10.10-playlist&version=#{version}"
  name "DCP-o-matic Playlist Editor"
  desc "Convert video, audio and subtitles into DCP (Digital Cinema Democratized)"
  homepage "https://dcpomatic.com/"

  livecheck do
    cask "dcp-o-matic"
  end

  app "DCP-o-matic #{version.major} Playlist Editor.app"

  # No zap stanza required
end


text:
package org.rfcx.cellmapping.model;

public class Poi {

    private String sid, guid;
    private double lat, lng, accuracy;
    private int signalstrenth, evoDbm, cdmaDbm;
    private String name;

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public double getLng() {
        return lng;
    }

    public void setLng(double lng) {
        this.lng = lng;
    }

    public int getSignalstrenth() {
        return signalstrenth;
    }

    public void setSignalstrenth(int signalstrenth) {
        this.signalstrenth = signalstrenth;
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public String getGuid() {
        return guid;
    }

    public void setGuid(String guid) {
        this.guid = guid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getEvoDbm() {
        return evoDbm;
    }

    public void setEvoDbm(int evoDbm) {
        this.evoDbm = evoDbm;
    }

    public int getCdmaDbm() {
        return cdmaDbm;
    }

    public void setCdmaDbm(int cdmaDbm) {
        this.cdmaDbm = cdmaDbm;
    }

    public double getAccuracy() {
        return accuracy;
    }

    public void setAccuracy(double accuracy) {
        this.accuracy = accuracy;
    }
}


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="fpbe.basic_domain_manager.class">FP\BEBundle\Services\DomainManagers\BasicDomainManager</parameter>
        <parameter key="fpbe.basic_form_handler.class">FP\BEBundle\Services\FormHandlers\BasicFormHandler</parameter>
        <parameter key="fpbe.form_type.ckeditor_custom.class">FP\BEBundle\Form\Types\CKEditorType</parameter>
    </parameters>

    <services>
        <service id="fpbe.basic_domain_manager" class="%fpbe.basic_domain_manager.class%">
            <argument type="service" id="doctrine.orm.entity_manager"/>
        </service>

        <service id="fpbe.basic_form_handler" class="%fpbe.basic_form_handler.class%">
            <argument type="service" id="fpbe.basic_domain_manager"/>
            <argument type="service" id="form.factory"/>
        </service>

        <service id="fpbe.form_type.ckeditor_custom" class="%fpbe.form_type.ckeditor_custom.class%">
            <tag name="form.type" alias="ckeditor_custom" />
        </service>
    </services>
</container>


text:
class ChangeDescriptionTypeInSignUpTopics < ActiveRecord::Migration
  def change
    change_column :sign_up_topics, :description, :text
  end
end


text:
set -x

flink_home=$FLINK_HOME
bigdl_home=$BIGDL_HOME
flink_job_manager_ip=$FLINK_JOB_MANAGER_IP
flink_job_manager_port=$FLINK_JOB_MANAGER_REST_PORT

echo "### Launching Cluster Serving Job ###"

export FLINK_CONF_DIR=${flink_home}/conf && \
    ${flink_home}/bin/flink run \
    -c com.intel.analytics.bigdl.serving.ClusterServing -p 1 -m $flink_job_manager_ip:$flink_job_manager_port \
    ${bigdl_home}/bigdl-serving-jar-with-dependencies.jar | tee ./cluster-serving-job-sgx.log


text:
package net.bluemix.newsaggregator.api;

import com.wordnik.swagger.annotations.ApiModelProperty;

public class ResponseAddOrUpdateFeedDTO {

	public ResponseAddOrUpdateFeedDTO() {
	}

	private String feedId;

	@ApiModelProperty(value = "ID of the feed", required=true)
	public String getFeedId() {
		return feedId;
	}

	public void setFeedId(String feedId) {
		this.feedId = feedId;
	}

}


text:
module Twitter
  class Client
    # @private
    module Utils
      private

      # Returns the configured screen name or the screen name of the authenticated user
      #
      # @return [String]
      def get_screen_name
        @screen_name ||= self.verify_credentials.screen_name
      end

      # Remove @ signs from screen names
      #
      # @param screen_name [String] A Twitter screen name.
      # @return [String] The Twitter screen name minus the @ sign.
      def clean_screen_name!(screen_name)
        screen_name.gsub!(/[@@]/, '') if screen_name
      end

      # Take a single user ID or screen name and merge it into an options hash with the correct key
      #
      # @param user_id_or_screen_name [Integer, String] A Twitter user ID or screen_name.
      # @param options [Hash] A customizable set of options.
      # @return [Hash]
      def merge_user_into_options!(user_id_or_screen_name, options={})
        case user_id_or_screen_name
        when Fixnum
          options[:user_id] = user_id_or_screen_name
        when String
          clean_screen_name!(user_id_or_screen_name)
          options[:screen_name] = user_id_or_screen_name
        end
        options
      end

      # Take a multiple user IDs and screen names and merge them into an options hash with the correct keys
      #
      # @param users_id_or_screen_names [Array] An array of Twitter user IDs or screen_names.
      # @param options [Hash] A customizable set of options.
      # @return [Hash]
      def merge_users_into_options!(user_ids_or_screen_names, options={})
        user_ids, screen_names = [], []
        user_ids_or_screen_names.flatten.each do |user_id_or_screen_name|
          case user_id_or_screen_name
          when Fixnum
            user_ids << user_id_or_screen_name
          when String
            clean_screen_name!(user_id_or_screen_name)
            screen_names << user_id_or_screen_name
          end
        end
        options[:user_id] = user_ids.join(',') unless user_ids.empty?
        options[:screen_name] = screen_names.join(',') unless screen_names.empty?
        options
      end
    end
  end
end


text:
 class ComponentFactory {
    constructor() {
        this.componentsById = {}
        this.defaultComponents = {}
    }

    registerComponent(id, component) {
        this.componentsById[id] = component;
    }

    registerComponents( components) {
        this.componentsById = {...this.componentsById, ...components}
    }

    getComponent(id) {
        var component = this.componentsById[id];

        if (!component) {
            debugger
            throw `没有组件. Id: ${id}`;
        }
        return this.componentsById[id];
    }

    getComponents() {
        return this.componentsById
    }

    getDefaultComponent(type) {

        if (!type) {
            debugger
            throw 'type没有值';
        }
        if (this.defaultComponents[type])
            return this.getComponent(this.defaultComponents[type]);
        debugger
        throw new Error(`没有组件. Type: ${type}`);
    }

    setDefaultComponents(components) {
        this.defaultComponents = components;
    }

}

export default new ComponentFactory()


text:
package com.glaf.setup.conf;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAuthenticator extends Authenticator {
	private String username;

	private String password;

	public MailAuthenticator(String username, String password) {
		this.username = username;
		this.password = password;
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, password);
	}

}


text:
package nl.homeserver.energie.energycontract;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Sort;

import java.time.LocalDate;
import java.util.List;

import static java.time.Month.JANUARY;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class EnergyContractToDateRecalculatorTest {

    @InjectMocks
    EnergyContractToDateRecalculator energyContractToDateRecalculator;

    @Mock
    EnergyContractRepository energyContractRepository;

    @Test
    void givenMultipleEnergiecontractsWithoutValidToWhenRecalculateThenSetAndSaved() {
        final EnergyContract energyContract1 = new EnergyContract();
        energyContract1.setValidFrom(LocalDate.of(2017, JANUARY, 1));

        final EnergyContract energyContract2 = new EnergyContract();
        energyContract2.setValidFrom(LocalDate.of(2017, JANUARY, 6));

        final EnergyContract energyContract3 = new EnergyContract();
        energyContract3.setValidFrom(LocalDate.of(2017, JANUARY, 12));

        when(energyContractRepository.findAll(any(Sort.class))).thenReturn(List.of(energyContract1, energyContract2, energyContract3));

        energyContractToDateRecalculator.recalculate();

        assertThat(energyContract1.getValidTo()).isEqualTo(energyContract2.getValidFrom());
        assertThat(energyContract2.getValidTo()).isEqualTo(energyContract3.getValidFrom());
        assertThat(energyContract3.getValidTo()).isNull();

        verify(energyContractRepository).save(energyContract1);
        verify(energyContractRepository).save(energyContract2);
    }

    @Test
    void givenValidToAreAlreadyValidWhenRecalculateThenNothingSaved() {
        final EnergyContract energyContract1 = new EnergyContract();
        energyContract1.setValidFrom(LocalDate.of(2017, JANUARY, 1));
        energyContract1.setValidTo(LocalDate.of(2017, JANUARY, 5));

        final EnergyContract energyContract2 = new EnergyContract();
        energyContract2.setValidFrom(energyContract1.getValidTo());
        energyContract2.setValidTo(LocalDate.of(2017, JANUARY, 14));

        final EnergyContract energyContract3 = new EnergyContract();
        energyContract3.setValidFrom(energyContract2.getValidTo());
        energyContract3.setValidTo(null);

        when(energyContractRepository.findAll(any(Sort.class))).thenReturn(List.of(energyContract1, energyContract2, energyContract3));

        energyContractToDateRecalculator.recalculate();

        assertThat(energyContract1.getValidTo()).isEqualTo(LocalDate.of(2017, JANUARY, 5));
        assertThat(energyContract2.getValidTo()).isEqualTo(LocalDate.of(2017, JANUARY, 14));
        assertThat(energyContract3.getValidTo()).isNull();

        verify(energyContractRepository, never()).save(any(EnergyContract.class));
    }

    @Test
    void givenSingleEnergiecontractsWithValidToDateWhenRecalculateThenValidToIsClearedAndSaved() {
        final EnergyContract energyContract = new EnergyContract();
        energyContract.setValidTo(LocalDate.of(2017, JANUARY, 1));

        when(energyContractRepository.findAll(any(Sort.class))).thenReturn(List.of(energyContract));

        energyContractToDateRecalculator.recalculate();

        assertThat(energyContract.getValidTo()).isNull();

        verify(energyContractRepository).save(energyContract);
    }
}


text:
package org.apache.hadoop.hbase;

import java.io.IOException;

import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;

/**
 * Thrown during flush if the possibility snapshot content was not properly
 * persisted into store files.  Response should include replay of wal content.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public class DroppedSnapshotException extends IOException {

  private static final long serialVersionUID = -5463156580831677374L;

  /**
   * @param msg
   */
  public DroppedSnapshotException(String msg) {
    super(msg);
  }

  /**
   * default constructor
   */
  public DroppedSnapshotException() {
    super();
  }
}


text:
package com.netflix.astyanax.shallows;

import org.joda.time.DateTime;

import com.netflix.astyanax.connectionpool.NodeDiscovery;

public class EmptyNodeDiscoveryImpl implements NodeDiscovery {

    private static final EmptyNodeDiscoveryImpl instance = new EmptyNodeDiscoveryImpl();

    private EmptyNodeDiscoveryImpl() {

    }

    public static EmptyNodeDiscoveryImpl get() {
        return instance;
    }

    @Override
    public void start() {
    }

    @Override
    public void shutdown() {
    }

    @Override
    public DateTime getLastRefreshTime() {
        return null;
    }

    @Override
    public long getRefreshCount() {
        return 0;
    }

    @Override
    public long getErrorCount() {
        return 0;
    }

    @Override
    public Exception getLastException() {
        return null;
    }

    @Override
    public String getRawHostList() {
        return "";
    }

    public String toString() {
        return "EmptyNodeDiscovery";
    }

}


text:
import { LightningElement, api } from 'lwc';
import { isEmpty } from 'c/utilCommon';

export default class geModalPrompt extends LightningElement {

    @api variant = '';
    @api title;
    @api message;
    @api buttons = [];

    get titleSectionComputedClass() {

        let allowedVariants = ['warning', 'shade', 'inverse', 'alt-inverse',
            'success', 'info', 'error', 'offline', 'default'];

        let baseClass = ['slds-box', 'slds-theme_alert-texture', 'slds-box_extension'];

        if (isEmpty(this.variant) || !allowedVariants.includes(this.variant)) {
            baseClass.push('slds-theme_default');
            return baseClass.join(' ');
        }

        baseClass.push('slds-theme_'+ this.variant);
        return baseClass.join(' ');
    }
}


text:
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////

#import "RMSAudioUnit.h"

@interface RMSAudioUnitConverter : RMSAudioUnit

+ (instancetype)instanceWithSource:(RMSSource *)source;

@end


text:
elementOpen("div");
elementClose("div");


text:
function random_number(inner, outer) {
    var delta = Math.abs(outer - inner);
    if (inner < outer) {
	return (inner + delta * randomTool.genrand_real3());
    } else {
	return (outer + delta * randomTool.genrand_real3());
    }
};

/*----------------------------------------------------------------------*/
/* This function returns a value within a certain variation of the */
/* exact value given it in 'value'. */
/*----------------------------------------------------------------------*/
function about(value, variation) {
    var inner = value - variation;
    return (inner + 2.0 * variation * randomTool.genrand_real3());
};

function random_eccentricity() {
    return (1.0 - Math.pow((randomTool.genrand_real3()), ECCENTRICITY_COEFF));
};


text:
namespace ash::quick_start {

namespace {

TargetDeviceBootstrapController::QRCodePixelData GenerateQRCode(
    std::vector<uint8_t> blob) {
  QRCodeGenerator qr_generator;
  auto generated_code = qr_generator.Generate(
      base::as_bytes(base::make_span(blob.data(), blob.size())));
  CHECK(generated_code.has_value());
  auto res = TargetDeviceBootstrapController::QRCodePixelData{
      generated_code->data.begin(), generated_code->data.end()};
  CHECK_EQ(res.size(), static_cast<size_t>(generated_code->qr_size *
                                           generated_code->qr_size));
  return res;
}

}  // namespace

TargetDeviceBootstrapController::TargetDeviceBootstrapController() {
  connection_broker_ = TargetDeviceConnectionBrokerFactory::Create();
}

TargetDeviceBootstrapController::~TargetDeviceBootstrapController() = default;

TargetDeviceBootstrapController::Status::Status() = default;
TargetDeviceBootstrapController::Status::~Status() = default;

void TargetDeviceBootstrapController::AddObserver(Observer* obs) {
  observers_.AddObserver(obs);
}

void TargetDeviceBootstrapController::RemoveObserver(Observer* obs) {
  observers_.RemoveObserver(obs);
}

void TargetDeviceBootstrapController::GetFeatureSupportStatusAsync(
    TargetDeviceConnectionBroker::FeatureSupportStatusCallback callback) {
  connection_broker_->GetFeatureSupportStatusAsync(std::move(callback));
}

base::WeakPtr<TargetDeviceBootstrapController>
TargetDeviceBootstrapController::GetAsWeakPtrForClient() {
  // Only one client at a time should have a pointer.
  DCHECK(!weak_ptr_factory_for_clients_.HasWeakPtrs());
  return weak_ptr_factory_for_clients_.GetWeakPtr();
}

void TargetDeviceBootstrapController::StartAdvertising() {
  DCHECK(connection_broker_->GetFeatureSupportStatus() ==
         TargetDeviceConnectionBroker::FeatureSupportStatus::kSupported);
  DCHECK_EQ(status_.step, Step::NONE);

  // No pending requests.
  DCHECK(!weak_ptr_factory_.HasWeakPtrs());

  status_.step = Step::ADVERTISING;
  connection_broker_->StartAdvertising(
      this,
      base::BindOnce(&TargetDeviceBootstrapController::OnStartAdvertisingResult,
                     weak_ptr_factory_.GetWeakPtr()));
  NotifyObservers();
}

void TargetDeviceBootstrapController::StopAdvertising() {
  DCHECK_EQ(status_.step, Step::ADVERTISING);

  // No pending requests.
  DCHECK(!weak_ptr_factory_.HasWeakPtrs());

  connection_broker_->StopAdvertising(
      base::BindOnce(&TargetDeviceBootstrapController::OnStopAdvertising,
                     weak_ptr_factory_.GetWeakPtr()));
}

void TargetDeviceBootstrapController::OnIncomingConnectionInitiated(
    const std::string& source_device_id,
    base::WeakPtr<IncomingConnection> connection) {
  constexpr Step kPossibleSteps[] = {Step::ADVERTISING,
                                     Step::QR_CODE_VERIFICATION};
  DCHECK(base::Contains(kPossibleSteps, status_.step));
  if (status_.step == Step::QR_CODE_VERIFICATION) {
    // New connection came. It should be a different device.
    DCHECK_NE(source_device_id_, source_device_id);
  }
  source_device_id_ = source_device_id;
  incoming_connection_ = std::move(connection);
  auto qr_code = GenerateQRCode(incoming_connection_->GetQrCodeData());
  status_.step = Step::QR_CODE_VERIFICATION;
  status_.payload.emplace<QRCodePixelData>(std::move(qr_code));
  NotifyObservers();
}

void TargetDeviceBootstrapController::OnConnectionAuthenticated(
    const std::string& source_device_id,
    base::WeakPtr<AuthenticatedConnection> connection) {
  DCHECK_EQ(source_device_id_, source_device_id);
  constexpr Step kPossibleSteps[] = {Step::QR_CODE_VERIFICATION};
  DCHECK(base::Contains(kPossibleSteps, status_.step));
  DCHECK(incoming_connection_.WasInvalidated());

  status_.step = Step::CONNECTED;
  status_.payload.emplace<absl::monostate>();
  NotifyObservers();
}

void TargetDeviceBootstrapController::OnConnectionRejected(
    const std::string& source_device_id) {
  DCHECK_EQ(source_device_id_, source_device_id);
  status_.step = Step::ERROR;
  status_.payload = ErrorCode::CONNECTION_REJECTED;
  NotifyObservers();
}

void TargetDeviceBootstrapController::OnConnectionClosed(
    const std::string& source_device_id) {
  DCHECK_EQ(source_device_id_, source_device_id);
  status_.step = Step::ERROR;
  status_.payload = ErrorCode::CONNECTION_CLOSED;
  NotifyObservers();
}

void TargetDeviceBootstrapController::NotifyObservers() {
  for (auto& obs : observers_) {
    obs.OnStatusChanged(status_);
  }
}

void TargetDeviceBootstrapController::OnStartAdvertisingResult(bool success) {
  DCHECK_EQ(status_.step, Step::ADVERTISING);
  if (success)
    return;
  status_.step = Step::ERROR;
  status_.payload = ErrorCode::START_ADVERTISING_FAILED;
  NotifyObservers();
}

void TargetDeviceBootstrapController::OnStopAdvertising() {
  DCHECK_EQ(status_.step, Step::ADVERTISING);

  status_.step = Step::NONE;
  status_.payload.emplace<absl::monostate>();
  NotifyObservers();
}

}  // namespace ash::quick_start


text:
title: Control before growth
layout: post
---

For four years now, part of my life has been the running of [Bitesize Irish Gaelic](http://www.bitesizeirishgaelic.com/).

Life has changed over that time. The feeling of falling behind on things that "must be done" has only increased with time.

The feeling didn't even improve with working full-time on the project for six months, [funded by the Irish state](http://www.enterprise-ireland.com/en/Start-a-Business-in-Ireland/Supports-for-High-Potential-Start-Ups/New-Frontiers-Entrepreneur-Development-Programme.html).

To improve and build a project, there's always pressure from different sides: market it, build new features, keep up with email, track its accounts, develop new content.

## Customers being ignored

Tim Conly, an internet marketing consultant, recently made the point that businesses work so hard to grow that [they run out of time](http://foolishadventure.com/audio/foolish-guide-getting-time-income-mobility-fa174/) to take care of their customers. Customers leave because they've been ignored.

My management of Bitesize Irish Gaelic goes through phases, but I'm currently in one of those tough spots on falling behind.

Customers have emails in my inbox that I haven't replied to in two weeks. We have a [forum](http://www.bitesizeirishgaelic.com/forum/f2/) that I usually don't get to participate in. A bug for new members was live for about 10 days while I knew of it, and it was fixed for a week before I went live with it. The company's accounts of the past 10 months are only getting processed now.

Tim's answer is to systematise your processes. Scott Adams of Dilbert fame [is of the same opinion](http://online.wsj.com/news/articles/SB10001424052702304626104579121813075903866).

Before growing, Tim says you need to first get a hold of how effective your current business practices are. If you don't have the bandwidth to be in control of your current business, there's not much point in jumping onto new approaches.

## Control before growth, robustness before anti-fragility

Nassim Taleb's book Antifragile formalised this thought for me.

He says that there is a linear progression between fragility (where volatility will harm you), to robustness, and finaly to anti-fragility (where you will benefit from volatility, at least to a point).

For a business or project to be robust, I see that there needs to be control.

You can't grow into wild success without being first in control. You can't be a thriving business without first being robust. You probably won't acheive sustainable growth if you're regularly fragile.


text:
package org.perfcake.idea.run;

import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import org.jetbrains.annotations.NotNull;
import org.perfcake.idea.util.Constants;

import javax.swing.*;

/**
 * Created by miron on 4.2.2014.
 * @see super
 */
public class PerfCakeConfigurationType implements ConfigurationType {
    private static final Logger log = Logger.getInstance(PerfCakeConfigurationType.class);

    private final PerfCakeConfigurationFactory myFactory = new PerfCakeConfigurationFactory(this);

    public static PerfCakeConfigurationType getInstance() {
        for (ConfigurationType configType : Extensions.getExtensions(CONFIGURATION_TYPE_EP)) {
            if (configType instanceof PerfCakeConfigurationType) {
                return (PerfCakeConfigurationType) configType;
            }
        }
        log.error("Unexpected Idea Error: Could not find instance of PerfCakeConfigurationType");
        assert false;
        return null;
    }

    @Override
    public String getDisplayName() {
        return "PerfCake";
    }

    @Override
    public String getConfigurationTypeDescription() {
        return "PerfCake Run Configuration";
    }

    @Override
    public Icon getIcon() {
        return Constants.ICON_16P;
    }

    @NotNull
    @Override
    public String getId() {
        return "PerfCakeConfigurationType";
    }

    @Override
    public ConfigurationFactory[] getConfigurationFactories() {
        return new ConfigurationFactory[]{myFactory};
    }
}


text:
class ApplicationController < ActionController::Base
  protect_from_forgery

  helper RequirejsHelper

  def index
  end
end


text:
import { Component, OnInit, OnDestroy, Inject, ComponentFactoryResolver, Injector, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { Router, NavigationStart, RouterEvent } from '@angular/router';
import { Subject } from 'rxjs';
import { takeUntil, filter, map, switchMap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';

import {
    NewUrlStateNotificationService,
    UrlRouteManagerService,
    WebAppSettingDataService,
    AnalyticsService,
    TRACKED_EVENT_LIST,
    DynamicPopupService,
    MessageQueueService,
    MESSAGE_TO
} from 'app/shared/services';
import { UrlPathId } from 'app/shared/models';
import { EndTime } from 'app/core/models';
import { SERVER_MAP_TYPE, ServerMapType, NodeGroup, ServerMapData } from 'app/core/components/server-map/class';
import { ServerMapDataService } from './server-map-data.service';
import { LinkContextPopupContainerComponent } from 'app/core/components/link-context-popup/link-context-popup-container.component';
import { ServerMapContextPopupContainerComponent } from 'app/core/components/server-map-context-popup/server-map-context-popup-container.component';
import { ServerErrorPopupContainerComponent } from 'app/core/components/server-error-popup/server-error-popup-container.component';

@Component({
    selector: 'pp-server-map-container',
    templateUrl: './server-map-container.component.html',
    styleUrls: ['./server-map-container.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ServerMapContainerComponent implements OnInit, OnDestroy {
    private unsubscribe = new Subject<void>();

    i18nText: { [key: string]: string } = {
        NO_AGENTS: ''
    };
    mapData: ServerMapData;
    funcServerMapImagePath: Function;
    baseApplicationKey: string;
    showLoading = true;
    useDisable = true;
    isEmpty: boolean;
    endTime: string;
    period: string;

    constructor(
        private router: Router,
        private injector: Injector,
        private componentFactoryResolver: ComponentFactoryResolver,
        private translateService: TranslateService,
        private urlRouteManagerService: UrlRouteManagerService,
        private newUrlStateNotificationService: NewUrlStateNotificationService,
        private serverMapDataService: ServerMapDataService,
        private webAppSettingDataService: WebAppSettingDataService,
        private dynamicPopupService: DynamicPopupService,
        private analyticsService: AnalyticsService,
        private cd: ChangeDetectorRef,
        private messageQueueService: MessageQueueService,
        @Inject(SERVER_MAP_TYPE) public type: ServerMapType
    ) {}

    ngOnInit() {
        this.funcServerMapImagePath = this.webAppSettingDataService.getServerMapIconPathMakeFunc();
        this.addPageLoadingHandler();
        this.getI18NText();

        this.messageQueueService.receiveMessage(this.unsubscribe, MESSAGE_TO.SERVER_MAP_DISABLE).subscribe((disable: boolean) => {
            this.useDisable = disable;
            this.cd.detectChanges();
        });

        this.newUrlStateNotificationService.onUrlStateChange$.pipe(
            takeUntil(this.unsubscribe),
            map((urlService: NewUrlStateNotificationService) => {
                if (urlService.isRealTimeMode()) {
                    const endTime = urlService.getUrlServerTimeData();
                    const period = this.webAppSettingDataService.getSystemDefaultPeriod();

                    this.initVarBeforeDataLoad(
                        EndTime.formatDate(endTime),
                        period.getValueWithTime(),
                        urlService.getPathValue(UrlPathId.APPLICATION)
                    );

                    return [endTime - period.getMiliSeconds(), endTime];
                } else {
                    this.initVarBeforeDataLoad(
                        urlService.getPathValue(UrlPathId.END_TIME).getEndTime(),
                        urlService.getPathValue(UrlPathId.PERIOD).getValueWithTime(),
                        urlService.getPathValue(UrlPathId.APPLICATION)
                    );

                    return [urlService.getStartTimeToNumber(), urlService.getEndTimeToNumber()];
                }
            }),
            switchMap((range: number[]) => this.serverMapDataService.getData(range))
        ).subscribe((res: IServerMapInfo) => {
            this.mapData = new ServerMapData(res.applicationMapData.nodeDataArray, res.applicationMapData.linkDataArray);
            this.isEmpty = this.mapData.getNodeCount() === 0;
            this.messageQueueService.sendMessage({
                to: MESSAGE_TO.SERVER_MAP_DATA_UPDATE,
                param: this.mapData
            });
            if (this.isEmpty) {
                this.showLoading = false;
            }

            this.cd.detectChanges();
        }, (error: IServerErrorFormat) => {
            this.dynamicPopupService.openPopup({
                data: {
                    title: 'Server Error',
                    contents: error
                },
                component: ServerErrorPopupContainerComponent,
                onCloseCallback: () => {
                    this.urlRouteManagerService.move({
                        url: [
                            this.newUrlStateNotificationService.getStartPath()
                        ],
                        needServerTimeRequest: false
                    });
                }
            }, {
                resolver: this.componentFactoryResolver,
                injector: this.injector
            });
        });
    }

    ngOnDestroy() {
        this.unsubscribe.next();
        this.unsubscribe.complete();
    }

    private addPageLoadingHandler(): void {
        this.router.events.pipe(
            takeUntil(this.unsubscribe),
            filter((e: RouterEvent) => e instanceof NavigationStart)
        ).subscribe(() => {
            this.showLoading = true;
            this.useDisable = true;
            this.cd.detectChanges();
        });
    }

    private getI18NText(): void {
        this.translateService.get('COMMON.NO_AGENTS').subscribe((i18n: string) => {
            this.i18nText['NO_AGENTS'] = i18n;
        });
    }

    private initVarBeforeDataLoad(endTime: string, period: string, application: IApplication): void {
        this.endTime = endTime;
        this.period = period;
        this.showLoading = true;
        this.useDisable = true;
        this.baseApplicationKey = application.getKeyStr();
    }

    onRenderCompleted(): void {
        this.showLoading = false;
        this.useDisable = false;
        this.cd.detectChanges();
    }

    onClickNode(nodeData: any): void {
        this.analyticsService.trackEvent(TRACKED_EVENT_LIST.CLICK_NODE);
        let payload: any;
        if (NodeGroup.isGroupKey(nodeData.key)) {
            this.analyticsService.trackEvent(TRACKED_EVENT_LIST.SHOW_GROUPED_NODE_VIEW);
            payload = {
                period: this.period,
                endTime: this.endTime,
                isAuthorized: true,
                isNode: true,
                isLink: false,
                isMerged: true,
                isWAS: nodeData.isWas,
                node: nodeData.mergedNodes.map((nodeInfo: any) => {
                    return nodeInfo.key;
                })
            };
            if (nodeData.mergedSourceNodes) {
                payload.groupedNode = nodeData.mergedSourceNodes.map((nodeInfo: any) => {
                    return nodeInfo.applicationName;
                });
            }
        } else {
            payload = {
                period: this.period,
                endTime: this.endTime,
                isAuthorized: nodeData.isAuthorized,
                isNode: true,
                isLink: false,
                isMerged: false,
                isWAS: nodeData.isWas,
                node: [nodeData.key],
                hasServerList: nodeData.instanceCount > 0 ? true : false
            };
        }
        this.messageQueueService.sendMessage({
            to: MESSAGE_TO.SERVER_MAP_TARGET_SELECT,
            param: payload
        });
    }

    onClickLink(linkData: any): void {
        this.analyticsService.trackEvent(TRACKED_EVENT_LIST.CLICK_LINK);
        let payload;
        if (NodeGroup.isGroupKey(linkData.key)) {
            this.analyticsService.trackEvent(TRACKED_EVENT_LIST.SHOW_GROUPED_LINK_VIEW);
            payload = {
                period: this.period,
                endTime: this.endTime,
                isAuthorized: true,
                isNode: false,
                isLink: true,
                isMerged: true,
                isSourceMerge: NodeGroup.isGroupKey(linkData.from),
                isWAS: false,
                node: [linkData.from],
                link: linkData.targetInfo.map((linkInfo: any) => {
                    return linkInfo.key;
                }),
                hasServerList: false
            };
        } else {
            payload = {
                period: this.period,
                endTime: this.endTime,
                isAuthorized: this.mapData.getNodeData(linkData.from).isAuthorized,
                isNode: false,
                isLink: true,
                isMerged: false,
                isWAS: false,
                node: [linkData.from],
                link: [linkData.key],
                hasServerList: false
            };
        }
        this.messageQueueService.sendMessage({
            to: MESSAGE_TO.SERVER_MAP_TARGET_SELECT,
            param: payload
        });
    }

    onContextClickBackground(coord: ICoordinate): void {
        this.dynamicPopupService.openPopup({
            data: this.mapData,
            coord,
            component: ServerMapContextPopupContainerComponent
        }, {
            resolver: this.componentFactoryResolver,
            injector: this.injector
        });
    }

    onContextClickLink({key, coord}: {key: string, coord: ICoordinate}): void {
        this.dynamicPopupService.openPopup({
            data: this.mapData.getLinkData(key),
            coord,
            component: LinkContextPopupContainerComponent
        }, {
            resolver: this.componentFactoryResolver,
            injector: this.injector
        });
    }
}


text:
require 'truss/router'

describe Truss::Router do
    let(:app) { ->(env){[200, {'Content-Type' => 'text/plain'}, ["Hello World"]]} }
    subject { described_class }
    before(:each) { subject.reset! }
    it "requires a block to be passed to #draw" do
        expect {
            subject.draw
        }.to raise_error(ArgumentError)
    end

    context "drawing routes" do
        context "triggers the right route builder" do
            let(:map) { ->(m){
                    m.get("/home", app)
                    m.post("/home", app)
                    m.put("/home", app)
                    m.patch("/home", app)
                    m.options("/home", app)
                    m.head("/home", app)
                    m.delete("/home", app)
                }
            }

            it { subject.should_receive(:get).with("/home", app);        subject.draw(&map) }
            it { subject.should_receive(:post).with("/home", app);       subject.draw(&map) }
            it { subject.should_receive(:put).with("/home", app);        subject.draw(&map) }
            it { subject.should_receive(:patch).with("/home", app);      subject.draw(&map) }
            it { subject.should_receive(:head).with("/home", app);       subject.draw(&map) }
            it { subject.should_receive(:options).with("/home", app);    subject.draw(&map) }
            it { subject.should_receive(:delete).with("/home", app);     subject.draw(&map) }
        end

        context "populates the routeset" do
            let(:map) { ->(m){
                    m.get("/home", app)
                    m.post("/home", app)
                }
            }
            before(:each) do
                subject.draw(&map)
            end
            it "should have two route" do
                subject.routeset.total_nodes.should eq(3)
            end
            it "should have a Get routeset with one member" do
                subject.routeset.nodes_for("GET").length.should eq(1)
            end
            it "should have an Head routeset with one member" do
                subject.routeset.nodes_for("HEAD").length.should eq(1)
            end
            it "should have a Post routeset with one member" do
                subject.routeset.nodes_for("POST").length.should eq(1)
            end
        end
    end
end


text:
var db = require('../helpers/models');
var review = require('../helpers/manager').review;

function users(socket, cb) {
  review(
    { req: { params: { token: socket.token } }, res: {} },
    ((err, opt) => db.users.Find({}, ((err, rsp) => cb(err, rsp))))
  );
}

function roles(socket, cb) {
  db.roles.Find({}, ((err, rsp) => cb(err, rsp)));
}

module.exports.users = users;
module.exports.roles = roles;


text:
package com.microsoft.azure.management.compute.v2019_11_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The TerminateNotificationProfile model.
 */
public class TerminateNotificationProfile {
    /**
     * Configurable length of time a Virtual Machine being deleted will have to
     * potentially approve the Terminate Scheduled Event before the event is
     * auto approved (timed out). The configuration must be specified in ISO
     * 8601 format, the default value is 5 minutes (PT5M).
     */
    @JsonProperty(value = "notBeforeTimeout")
    private String notBeforeTimeout;

    /**
     * Specifies whether the Terminate Scheduled event is enabled or disabled.
     */
    @JsonProperty(value = "enable")
    private Boolean enable;

    /**
     * Get configurable length of time a Virtual Machine being deleted will have to potentially approve the Terminate Scheduled Event before the event is auto approved (timed out). The configuration must be specified in ISO 8601 format, the default value is 5 minutes (PT5M).
     *
     * @return the notBeforeTimeout value
     */
    public String notBeforeTimeout() {
        return this.notBeforeTimeout;
    }

    /**
     * Set configurable length of time a Virtual Machine being deleted will have to potentially approve the Terminate Scheduled Event before the event is auto approved (timed out). The configuration must be specified in ISO 8601 format, the default value is 5 minutes (PT5M).
     *
     * @param notBeforeTimeout the notBeforeTimeout value to set
     * @return the TerminateNotificationProfile object itself.
     */
    public TerminateNotificationProfile withNotBeforeTimeout(String notBeforeTimeout) {
        this.notBeforeTimeout = notBeforeTimeout;
        return this;
    }

    /**
     * Get specifies whether the Terminate Scheduled event is enabled or disabled.
     *
     * @return the enable value
     */
    public Boolean enable() {
        return this.enable;
    }

    /**
     * Set specifies whether the Terminate Scheduled event is enabled or disabled.
     *
     * @param enable the enable value to set
     * @return the TerminateNotificationProfile object itself.
     */
    public TerminateNotificationProfile withEnable(Boolean enable) {
        this.enable = enable;
        return this;
    }

}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('topic-selector', 'Integration | Component | topic selector', {
  integration: true
});

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{topic-selector}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#topic-selector}}
      template block text
    {{/topic-selector}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});


text:
	We gave the website a small makeover! A cool presentation of Spincast and its features has been added to the
	home page. We also added a new section: Demos / Tutorials.

	Finally, we implemented redirection rules.
	You can now easily specify that a route must be redirected to another one. This is useful,
	for example, when you change the URL of a resource but don't want the existing links to break.