text:
// ==UserScript==
// @name            Search the first tweet
// @name:ja         最初のツイート検索
// @namespace       https://furyutei.work
// @license         MIT
// @version         0.2.11
// @description     Search the first tweet related to a specific keyword in search timeline of Twitter
// @description:ja  Twitterの検索タイムラインにおいて指定したキーワードに関する最初のツイートを検索
// @author          furyu
// @match           https://twitter.com/*
// @match           https://mobile.twitter.com/*
// @noframes
// @grant           none
// @require         https://greasyfork.org/scripts/410119-twittertimeline/code/TwitterTimeline.js?version=911467
// @compatible      chrome
// @compatible      firefox
// @supportURL      https://github.com/furyutei/twSearchFirstTweet/issues
// @contributionURL https://memo.furyutei.work/about#send_donation
// ==/UserScript==

( async () => {
'use strict';

const
    SCRIPT_NAME = 'twSearchFirstTweet',
    DEBUG = false,

    SEARCH_BUTTON_CLASS = SCRIPT_NAME + '-search-button',
    CSS_STYLE_CLASS = SCRIPT_NAME + '-css-rule',

    ENABLE_NEW_WINDOW_OPEN = false, // TODO: 検索後に新しいウィンドウを開こうとするとポップアップブロックに引っかかってしまう
    EXCLUDE_RETWEETS = true, // true: リツイートは除外して検索
    TIME_TO_REASSESS_USER_FIRST_TWEET_MSEC = 3 * 60 * 60 * 1000, // ユーザーの最初のツイートを再評価するまでの時間(ミリ秒)

    TwitterTimeline = ( ( TwitterTimeline ) => {
        TwitterTimeline.debug_mode = DEBUG;
        TwitterTimeline.logged_script_name = SCRIPT_NAME;
        // デフォルトでは Rate Limit 回避用にディレイが入るので、これを無効化
        TwitterTimeline.TWITTER_API.API_DEFINITIONS[ TwitterTimeline.TIMELINE_TYPE.user ].min_delay_ms = 1;
        TwitterTimeline.TWITTER_API.API_DEFINITIONS[ TwitterTimeline.TIMELINE_TYPE.search ].min_delay_ms = 1;
        return TwitterTimeline;
    } )( window.TwitterTimeline ),

    {
        log_debug,
        log,
        log_info,
        log_error,
        TWITTER_API,
        TIMELINE_TYPE,
        REACTION_TYPE,
        CLASS_TIMELINE_SET,
    } = TwitterTimeline,

    ClassUserTimeline = CLASS_TIMELINE_SET[ TIMELINE_TYPE.user ],
    ClassSearchTimeline = CLASS_TIMELINE_SET[ TIMELINE_TYPE.search ],

    SEARCH_BUTTON_HELP_TEXT = 'Search for the first tweet that contains a given keyword',
    SEARCH_BUTTON_USER_HELP_TEXT = 'Search for the first tweet by this user',
    SEARCHING_HELP_TEXT = 'Searching ...',

    search_button_icon_svg = '<svg version="1.1" viewBox="0 0 96 96" xmlns="http://www.w3.org/2000/svg"><g transform="translate(0 -271.6)"><g transform="matrix(1.0127 0 0 .94178 5.2473 -23.213)" aria-label="1" fill="currentColor"><path d="m60.319 382.71h-36.204v-6.2296h14.175v-46.768h-14.175v-5.5074q8.3062-0.0451 11.872-2.3474 3.5663-2.3474 4.0177-7.4034h6.4102v62.026h13.904z"/></g><g fill="currentColor"><path d="m40.125 291.81a32.75 32.75 0 0 0-24.875 31.789 32.75 32.75 0 0 0 32.75 32.75 32.75 32.75 0 0 0 32.75-32.75 32.75 32.75 0 0 0-24.875-31.789v11.859a21 21.5 0 0 1 13.125 19.93 21 21.5 0 0 1-0.9082 6.25h2.9961v8.75h-8.0449a21 21.5 0 0 1-15.043 6.5 21 21.5 0 0 1-15.043-6.5h-8.0449v-8.75h2.9941a21 21.5 0 0 1-0.90625-6.25 21 21.5 0 0 1 13.125-19.932z" style="paint-order:normal"/><rect transform="matrix(.66428 -.74748 .74998 .66146 0 0)" x="-217.91" y="280.73" width="10.664" height="29.006" ry="0" style="paint-order:normal"/></g></g></svg>',

    searching_icon_svg = '<svg version="1.1" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" fill="none" r="10" stroke-width="4" style="stroke: currentColor; opacity: 0.4;"></circle><path d="M 12,2 a 10 10 -90 0 1 9,5.6" fill="none" stroke="currentColor" stroke-width="4" />',

    get_query_datetime = time_sec => new Date( time_sec * 1000 ).toISOString().replace( /T/, '_' ).replace( /(\.\d*)?Z$/, '_GMT' ),

    get_search_input_element = () => document.querySelector( 'div[data-testid="primaryColumn"] form[role="search"] input[data-testid="SearchBox_Search_Input"]' ),

    get_screen_name_from_url = ( url ) => new URL( url || location.href ).pathname.split( '/', 2 )[ 1 ],

    is_night_mode = () => ( getComputedStyle( document.body ).backgroundColor != 'rgb(255, 255, 255)' ),

    save_value = async ( name, value ) => {
        localStorage.setItem( SCRIPT_NAME + '-' + name, value );
    }, // end of save_value()

    load_value = async ( name ) => {
        return localStorage.getItem( SCRIPT_NAME + '-' + name );
    }, // end of load_value()

    load_user_tweet_info_map = async () => {
        try {
            let user_tweet_info_map_string = await load_value( 'UserTweetInfoMap' );

            if ( ! user_tweet_info_map_string ) return {};

            let user_tweet_info_map = JSON.parse( user_tweet_info_map_string );

            log_debug( 'load_user_tweet_info_map() user_tweet_info_map:', user_tweet_info_map );

            return user_tweet_info_map;
        }
        catch ( error ) {
            log_error( 'load_user_tweet_info_map() error:', error );
            return {};
        }
    }, // end of load_user_tweet_info_map()

    save_user_tweet_info_map = async ( user_tweet_info_map ) => {
        try {
            let user_tweet_info_map_string = JSON.stringify( user_tweet_info_map );

            await save_value( 'UserTweetInfoMap', user_tweet_info_map_string );
        }
        catch ( error ) {
            log_error( 'save_user_tweet_info_map() error:', error );
        }
    }, // end of save_user_tweet_info_map()

    user_tweet_info_map = await load_user_tweet_info_map() || {}, // Twitterのユーザーの情報のうち、変化しないユーザーID(id_str)をキーに情報を保存

    search_result_map = {},

    divide_period = ( period, min_period_length_sec = 180 ) => {
        period = period || {};

        if ( ! period.from_time_sec ) period.from_time_sec = new Date( '2006-03-01T00:00:00Z' ).getTime() / 1000;
        if ( ! period.to_time_sec ) period.to_time_sec = Date.now() / 1000;

        let from_time_sec = Math.floor( period.from_time_sec ),
            to_time_sec = Math.floor( period.to_time_sec );

        if ( to_time_sec - min_period_length_sec <= from_time_sec ) {
            return null;
        }

        let middle_time_sec = Math.floor( from_time_sec + ( to_time_sec - from_time_sec ) / 2 );

        if ( ( middle_time_sec <= from_time_sec ) || ( to_time_sec <= middle_time_sec ) ) {
            return null;
        }

        return {
            first_period : {
                from_time_sec : from_time_sec,
                to_time_sec : middle_time_sec,
            },
            second_period : {
                from_time_sec : middle_time_sec,
                to_time_sec : to_time_sec,
            },
        }
    }, // end of divide_period()

    search_first_tweet = async ( parameters ) => {
        parameters = parameters || {};

        const
            { specified_query, screen_name } = parameters,
            ClassTimeline = screen_name ? ClassUserTimeline : ( specified_query ? ClassSearchTimeline : null );

        if ( ! ClassTimeline ) {
            return null;
        }

        let user_info = screen_name ? await TWITTER_API.get_user_info( { screen_name } ) : {},
            user_id = screen_name ? user_info.id_str : null;

        if ( screen_name && ( ! user_id ) ) {
            return null;
        }

        const
            get_valid_tweet_info = async ( SearchTimeline ) => {
                let tweet_info;

                while ( true ) {
                    tweet_info = await SearchTimeline.fetch_tweet_info();
                    if ( ! tweet_info ) break;
                    if ( ! EXCLUDE_RETWEETS ) break;
                    if ( tweet_info.reacted_info && ( tweet_info.reacted_info.type == REACTION_TYPE.retweet ) ) {
                        continue; // RTの場合は読み飛ばす
                    }
                    break;
                }
                return tweet_info;
            };

        let user_tweet_info = user_id ? ( user_tweet_info_map[ user_id ] || {} ) : {},

            period_info = ( () => {
                if ( ! user_id ) {
                    return divide_period();
                }

                if ( ! user_tweet_info.first_tweet_url ) {
                    return divide_period( {
                        from_time_sec : new Date( user_info.created_at ).getTime() / 1000,
                    } );
                }

                let current_timestamp_ms = Date.now();

                try {
                    if ( ( ! user_tweet_info.reassess_timstamp_ms ) || ( user_tweet_info.reassess_timstamp_ms < current_timestamp_ms ) ) {
                        // 一定期間経過後は、ツイートを再チェック
                        user_tweet_info.reassess_timstamp_ms = null;

                        return {
                            first_period : {
                                from_time_sec : Math.floor( new Date( user_info.created_at ).getTime() / 1000 ),
                                to_time_sec : user_tweet_info.period.to_time_sec,
                            },
                            second_period : {
                                from_time_sec : user_tweet_info.period.to_time_sec,
                                to_time_sec : Math.floor( current_timestamp_ms / 1000 ),
                           }
                        };
                    }
                    else {
                        // キャッシュ時間内は保存された period を使用
                        return {
                            first_period : user_tweet_info.period,
                            second_period : {
                                from_time_sec : user_tweet_info.period.to_time_sec,
                                to_time_sec : Math.floor( current_timestamp_ms / 1000 ),
                           }
                        };
                   }
                }
                catch ( error ) {
                    log_error( 'Illegal format in user_tweet_info:', user_tweet_info, error );

                    return divide_period( {
                        from_time_sec : new Date( user_info.created_at ).getTime() / 1000,
                    } );
                }
            } )(),
            next_period_info,
            try_counter = 0,
            hit_tweet_info = null,
            hit_period = null,
            HitSearchTimeline,
            query_base = specified_query;

        while ( period_info ) {
            try_counter ++;

            let period_length = period_info.first_period.to_time_sec - period_info.first_period.from_time_sec;

            log_debug(
                'try_counter:', try_counter,
                'period length(sec):', period_length,
                'period_info:', period_info,
                'until:', new Date( period_info.first_period.to_time_sec * 1000 ).toISOString()
            );

            let SearchTimeline = new ClassTimeline( {
                    screen_name,
                    specified_query,
                    max_timestamp_ms : period_info.first_period.to_time_sec * 1000 + 1,
                    keep_since : true,
                } );

            query_base = SearchTimeline.query_base;

            if ( ! query_base ) return null;

            let tweet_info = await get_valid_tweet_info( SearchTimeline );

            log_debug( ( tweet_info || {} ).datetime, tweet_info );

            if ( tweet_info ) {
                hit_tweet_info = tweet_info;
                hit_period = period_info.first_period;
                HitSearchTimeline = SearchTimeline;
                next_period_info = divide_period( period_info.first_period );

                log_debug( '[in this period]', period_info.first_period, 'period_length:', period_length, '(sec) => found ! tweet_info:', tweet_info, 'next_period_info:', next_period_info, 'SearchTimeline:', SearchTimeline );
            }
            else {
                next_period_info = divide_period( period_info.second_period );

                log_debug( '[in this period]', period_info.first_period, 'period_length:', period_length, '(sec) => no tweet ... next_period_info:', next_period_info, 'SearchTimeline:', SearchTimeline );
            }

            if ( ! next_period_info ) {
                if ( HitSearchTimeline ) {
                    SearchTimeline = HitSearchTimeline;
                }
                else {
                    hit_period = period_info.second_period;
                    SearchTimeline = new ClassTimeline( {
                        screen_name,
                        specified_query,
                        max_timestamp_ms : hit_period.to_time_sec * 1000 + 1,
                        keep_since : true,
                    } );
                }

                while ( true ) {
                    tweet_info = await get_valid_tweet_info( SearchTimeline );

                    if ( ! tweet_info ) break;

                    hit_tweet_info = tweet_info;
                }

                if ( hit_tweet_info ) {
                    hit_period.from_time_sec = Math.floor( hit_tweet_info.timestamp_ms / 1000 );
                }
                else {
                    hit_period = null;
                }
                break;
            }
            period_info = next_period_info;
        }

        let result = {
                first_tweet_info : hit_tweet_info,
                period : hit_period,
                screen_name,
                user_id,
                specified_query,
                query_base,
            };

        if ( user_id ) {
            user_tweet_info_map[ user_id ] = {
                user_id,
                screen_name,
                first_tweet_url : ( hit_tweet_info || {} ).tweet_url,
                first_tweet_timestamp_ms : ( hit_tweet_info || {} ).timestamp_ms,
                period : hit_period,
                reassess_timstamp_ms : user_tweet_info.reassess_timstamp_ms || ( Date.now() + TIME_TO_REASSESS_USER_FIRST_TWEET_MSEC ),
            }
            await save_user_tweet_info_map( user_tweet_info_map );

            log_debug( 'updated user_tweet_info_map:', user_tweet_info_map );
        }
        log_debug( 'result:', result );

        return result;
    },  // end of search_first_tweet()

    check_page_transition = () => {
        let search_button = document.querySelector( '.' + SEARCH_BUTTON_CLASS );

        if ( search_button ) {
            if ( is_night_mode() ) {
                search_button.classList.add( 'night-mode' );
            }
            else {
                search_button.classList.remove( 'night-mode' );
            }

            let br = search_button.parentNode.querySelector( '.before-linefeed' ),
                previous_element = search_button.previousSibling;

            if ( ( ! br ) || ( ! previous_element ) ) return;
            if ( previous_element.previousSibling && previous_element.previousSibling.classList.contains( 'before-linefeed' ) ) return;

            log_debug( 're-insert br.before-linefeed' );
            previous_element.before( br );
            return;
        }

        const
            search_form = ( () => {
                const
                    search_input = get_search_input_element();
                if ( ! search_input ) return null;
                return search_input.closest( 'form[role="search"]' );
            } )(),

            search_option_button = document.querySelector('div[data-testid="primaryColumn"] [role="button"][data-testid="searchBoxOverflowButton"]'),

            is_search_timeline = !! ( search_form || search_option_button ),

            user_profile_header_items_container = document.querySelector( 'div[data-testid="primaryColumn"] [data-testid="UserProfileHeader_Items"]' ),

            base_container = search_option_button || search_form || ( user_profile_header_items_container || {} ).lastChild;

        if ( ! base_container ) return;

        search_button = document.createElement( 'div' );
        search_button.classList.add( SEARCH_BUTTON_CLASS );

        if ( is_search_timeline ) {
            search_button.classList.add( 'search-timeline' );
            search_button.title = SEARCH_BUTTON_HELP_TEXT;
        }
        else {
            search_button.classList.add( 'user-timeline' );
            search_button.title = SEARCH_BUTTON_USER_HELP_TEXT;
        }

        if ( is_night_mode() ) {
            search_button.classList.add( 'night-mode' );
        }

        let search_button_icon,
            searching_icon;

        search_button.insertAdjacentHTML( 'beforeend', searching_icon_svg );
        searching_icon = search_button.firstChild;
        searching_icon.remove();
        search_button.insertAdjacentHTML( 'beforeend', search_button_icon_svg );
        search_button_icon = search_button.firstChild;

        const
            do_page_transition = ( url ) => {
                if ( ! url ) return;

                if ( ENABLE_NEW_WINDOW_OPEN ) {
                    window.open( url );
                }
                else {
                    //location.href = url;
                    // TODO: ページ読み込みを発生させないために pushState を使用しているが、Twitter側で state の構造(特に key)が変わってしまうとうまく動かなくなる
                    // TODO: Firefox79.0 (64 ビット)+Violentmonkey 2.12.7の場合、Twitter側のスクリプト(main*.js)にてエラーが発生する(Uncaught Error: Permission denied to access property "key")
                    // →とりあえず、Tampermonkey 4.11.6117 なら動作する模様
                    let state = {
                            key : 'r80bpk',
                            state : {
                                fromApp : true,
                                previousPath : location.pathname,
                            },
                        },
                        pop_state_event = new PopStateEvent( 'popstate', { state : state } );

                    try {
                        history.pushState( state, '', new URL( url ).pathname );
                        dispatchEvent( pop_state_event );
                    }
                    catch ( error ) {
                        location.href = url;
                    }
                }
            };

        let is_searching = false;

        search_button.addEventListener( 'click', async ( event ) => {
            event.preventDefault();
            event.stopPropagation();

            if ( is_searching ) return;

            let screen_name = is_search_timeline ? null : get_screen_name_from_url(),
                specified_query = is_search_timeline ? ( ( get_search_input_element() || {} ).value || ( Array.from( new URL( location.href ).searchParams ).filter( p => p[ 0 ] == 'q' )[ 0 ] || [] )[ 1 ] || '' ) : 'from:' + screen_name;

            if ( ! specified_query ) {
                return;
            }

            if ( search_result_map[ specified_query ] ) {
                do_page_transition( ( search_result_map[ specified_query ].first_tweet_info || {} ).tweet_url );
                return;
            }

            is_searching = true;
            search_button_icon.remove();
            search_button.appendChild( searching_icon );
            search_button.classList.add( 'searching' );
            search_button.title = SEARCHING_HELP_TEXT;

            let result = await search_first_tweet( { specified_query, screen_name } ) || {};
            log_debug( 'search_first_tweet() result:', result );

            search_result_map[ specified_query ] = result;

            if ( result && result.first_tweet_info ) {
                do_page_transition( ( result.first_tweet_info || {} ).tweet_url );
            }

            is_searching = false;
            searching_icon.remove();
            search_button.appendChild( search_button_icon );
            search_button.classList.remove( 'searching' );
            search_button.title = SEARCH_BUTTON_HELP_TEXT;
        } );

        base_container.after( search_button );

        if ( user_profile_header_items_container ) {
            // 「xxxx年xx月からTwitterを利用しています」の前に改行を挿入
            let br = document.createElement( 'br' );
            br.classList.add( 'before-linefeed' );
            ( search_button.previousSibling || search_button ).before( br );
        }
    }, // end of check_page_transition()

    insert_css_rule = () => {
        const
            button_selector = '.' + SEARCH_BUTTON_CLASS,
            css_rule_text = `
                ${button_selector} {
                    display: inline-block;
                    width: 28px;
                    height: 28px;
                    background: transparent;
                    color: #8899a6;
                    cursor: pointer;
                }

                ${button_selector}.search-timeline {
                    position: absolute;
                    /*bottom: 2px;*/
                    /*right: -28px;*/
                    right: 28px;
                }

                ${button_selector}.user-timeline {
                    position: relative;
                    top: 8px;
                    left: 8px;
                }

                ${button_selector}:hover {
                    color: #17bf63;
                }

                ${button_selector}.searching svg {
                    animation: searching 1.5s linear infinite;
                }

                @keyframes searching {
                    0% {transform: rotate(0deg);}
                    100% {transform: rotate(360deg);}
                }

                ${button_selector}.night-mode {
                }

                br.before-linefeed:first-child {
                    display: none;
                }
            `;

        let css_style = document.querySelector( '.' + CSS_STYLE_CLASS );

        if ( css_style ) css_style.remove();

        css_style = document.createElement( 'style' );
        css_style.classList.add( CSS_STYLE_CLASS );
        css_style.textContent = css_rule_text;

        document.querySelector( 'head' ).appendChild( css_style );
    }, // end of insert_css_rule()

    observer = new MutationObserver( ( records ) => {
        try {
            stop_observe();
            check_page_transition();
        }
        finally {
            start_observe();
        }
    } ),
    start_observe = () => observer.observe( document.body, { childList : true, subtree : true } ),
    stop_observe = () => observer.disconnect();

insert_css_rule();
start_observe();

} )();


text:
#pragma once

/**
 * Helper function for writing the contents of a Texture object into a file
 * and loading them from a file.
 */

#include <ACGL/ACGL.hh>
#include <ACGL/OpenGL/Data/ColorSpace.hh>
#include <ACGL/OpenGL/Objects/Texture.hh>

#include <string>

namespace ACGL{
namespace OpenGL{

//! loads the texture and creates mip maps
SharedTexture2D loadTexture2D(const std::string& _filename, ColorSpace _colorSpace = COLOR_SPACE_AUTO_DETECT);

//! loads the texture including mipmaps from a DDS file
//! supports DXT1, DXT3 and DXT5 compression
SharedTexture2D      loadTexture2DFromDDS     (const std::string& _filename, ColorSpace _colorSpace = COLOR_SPACE_AUTO_DETECT);
SharedTexture3D      loadTexture3DFromDDS     (const std::string& _filename, ColorSpace _colorSpace = COLOR_SPACE_AUTO_DETECT);
SharedTextureCubeMap loadTextureCubeMapFromDDS(const std::string& _filename, ColorSpace _colorSpace = COLOR_SPACE_AUTO_DETECT);

}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magwel\DispatcherBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('magwel_dispatcher', 'array');

        $this->addPrefixSection($rootNode);
        $this->addViewsSection($rootNode);
        $this->addApplicationSection($rootNode);

        return $treeBuilder;
    }

    /**
     * @param ArrayNodeDefinition $node
     */
    private function addPrefixSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->scalarNode('prefix')->defaultValue('/')->end()
            ->end();
    }

    /**
     * @param ArrayNodeDefinition $node
     */
    private function addViewsSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('views')
                    ->requiresAtLeastOneElement()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('package')->isRequired()->end()
                            ->scalarNode('parent')->defaultValue('')->end()
                            ->scalarNode('preserve')->defaultValue(false)->end()
                            ->scalarNode('classname')->isRequired()->end()
                            ->scalarNode('route')->defaultValue('')->end()
                        ->end()
                    ->end()
                ->end()
            ->end();
    }

    /**
     * @param ArrayNodeDefinition $node
     */
    private function addApplicationSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('applications')
                    ->requiresAtLeastOneElement()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('package')->isRequired()->end()
                            ->scalarNode('classname')->isRequired()->end()
                            ->scalarNode('route')->defaultValue('')->end()
                        ->end()
                    ->end()
                ->end()
            ->end();
    }
}


text:
package com.intellij.application.options.emmet;

import com.intellij.codeInsight.template.emmet.filters.ZenCodingFilter;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBTextField;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.XmlBundle;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.*;

public class XmlEmmetConfigurable implements SearchableConfigurable, Disposable, Configurable.NoScroll {
  private JPanel myPanel;
  private JBCheckBox myEnableEmmetJBCheckBox;
  private JBCheckBox myEnablePreviewJBCheckBox;
  private JPanel myFiltersListPanel;
  private JBCheckBox myEnableHrefAutodetectJBCheckBox;
  private JBCheckBox myAddEditPointAtTheEndOfTemplateJBCheckBox;
  private JBTextField myBemElementSeparatorTextField;
  private JBTextField myBemModifierSeparatorTextField;
  private JBTextField myBemShortElementPrefixTextField;
  private JPanel myBemPanel;

  private Map<String, JBCheckBox> myFilterCheckboxes = new HashMap<>();

  public XmlEmmetConfigurable() {
    myEnableEmmetJBCheckBox.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        boolean selected = myEnableEmmetJBCheckBox.isSelected();
        myEnablePreviewJBCheckBox.setEnabled(selected);
        myFiltersListPanel.setEnabled(selected);
        myEnableHrefAutodetectJBCheckBox.setEnabled(selected);
        myAddEditPointAtTheEndOfTemplateJBCheckBox.setEnabled(selected);
        UIUtil.setEnabled(myBemPanel, selected, true);
        for (JBCheckBox checkBox : myFilterCheckboxes.values()) {
          checkBox.setEnabled(selected);
        }
      }
    });
    myFiltersListPanel.setBorder(IdeBorderFactory.createTitledBorder(XmlBundle.message("emmet.filters.enabled.by.default")));
    myBemPanel.setBorder(IdeBorderFactory.createTitledBorder(XmlBundle.message("emmet.bem.title")));
    createFiltersCheckboxes();

  }

  public void createFiltersCheckboxes() {
    final List<ZenCodingFilter> filters = ZenCodingFilter.getInstances();
    final GridBagLayout layoutManager = new GridBagLayout();
    final GridBagConstraints constraints = new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                                                  JBUI.emptyInsets(), 0, 0);
    myFiltersListPanel.setLayout(layoutManager);
    int added = 0;
    for (ZenCodingFilter filter : filters) {
      if (myFilterCheckboxes.containsKey(filter.getSuffix())) continue;
      final JBCheckBox checkBox = new JBCheckBox(filter.getDisplayName());
      myFilterCheckboxes.put(filter.getSuffix(), checkBox);
      constraints.gridy = added;
      myFiltersListPanel.add(checkBox, constraints);
      added++;
    }
    myFiltersListPanel.revalidate();
  }

  @Override
  public void dispose() {
    myFilterCheckboxes.clear();
    myFilterCheckboxes = null;
  }

  @Nullable
  @Override
  public JComponent createComponent() {
    return myPanel;
  }

  @Override
  public boolean isModified() {
    EmmetOptions emmetOptions = EmmetOptions.getInstance();
    return emmetOptions.isEmmetEnabled() != myEnableEmmetJBCheckBox.isSelected() ||
           emmetOptions.isPreviewEnabled() != myEnablePreviewJBCheckBox.isSelected() ||
           emmetOptions.isHrefAutoDetectEnabled() != myEnableHrefAutodetectJBCheckBox.isSelected() ||
           emmetOptions.isAddEditPointAtTheEndOfTemplate() != myAddEditPointAtTheEndOfTemplateJBCheckBox.isSelected() ||
           !emmetOptions.getFiltersEnabledByDefault().equals(enabledFilters()) ||
           !emmetOptions.getBemElementSeparator().equals(myBemElementSeparatorTextField.getText()) ||
           !emmetOptions.getBemModifierSeparator().equals(myBemModifierSeparatorTextField.getText()) ||
           !emmetOptions.getBemShortElementPrefix().equals(myBemShortElementPrefixTextField.getText());
  }

  @Override
  public void apply() throws ConfigurationException {
    EmmetOptions emmetOptions = EmmetOptions.getInstance();
    emmetOptions.setEmmetEnabled(myEnableEmmetJBCheckBox.isSelected());
    emmetOptions.setPreviewEnabled(myEnablePreviewJBCheckBox.isSelected());
    emmetOptions.setHrefAutoDetectEnabled(myEnableHrefAutodetectJBCheckBox.isSelected());
    emmetOptions.setAddEditPointAtTheEndOfTemplate(myAddEditPointAtTheEndOfTemplateJBCheckBox.isSelected());
    emmetOptions.setFiltersEnabledByDefault(enabledFilters());
    emmetOptions.setBemElementSeparator(myBemElementSeparatorTextField.getText());
    emmetOptions.setBemModifierSeparator(myBemModifierSeparatorTextField.getText());
    emmetOptions.setBemShortElementPrefix(myBemShortElementPrefixTextField.getText());
  }

  @Override
  public void reset() {
    EmmetOptions emmetOptions = EmmetOptions.getInstance();
    myEnableEmmetJBCheckBox.setSelected(emmetOptions.isEmmetEnabled());
    myEnablePreviewJBCheckBox.setEnabled(emmetOptions.isEmmetEnabled());
    myEnablePreviewJBCheckBox.setSelected(emmetOptions.isPreviewEnabled());
    myEnableHrefAutodetectJBCheckBox.setEnabled(emmetOptions.isEmmetEnabled());
    myEnableHrefAutodetectJBCheckBox.setSelected(emmetOptions.isHrefAutoDetectEnabled());
    myAddEditPointAtTheEndOfTemplateJBCheckBox.setEnabled(emmetOptions.isEmmetEnabled());
    myAddEditPointAtTheEndOfTemplateJBCheckBox.setSelected(emmetOptions.isAddEditPointAtTheEndOfTemplate());

    myBemElementSeparatorTextField.setText(emmetOptions.getBemElementSeparator());
    myBemModifierSeparatorTextField.setText(emmetOptions.getBemModifierSeparator());
    myBemShortElementPrefixTextField.setText(emmetOptions.getBemShortElementPrefix());

    Set<String> enabledByDefault = emmetOptions.getFiltersEnabledByDefault();
    for (ZenCodingFilter filter : ZenCodingFilter.getInstances()) {
      final String filterSuffix = filter.getSuffix();
      final JBCheckBox checkBox = myFilterCheckboxes.get(filterSuffix);
      if (checkBox != null) {
        checkBox.setEnabled(emmetOptions.isEmmetEnabled());
        checkBox.setSelected(enabledByDefault.contains(filterSuffix));
      }
    }
  }

  @Override
  public void disposeUIResources() {
    Disposer.dispose(this);
  }

  @NotNull
  private Set<String> enabledFilters() {
    Set<String> result = new HashSet<>();
    for (Map.Entry<String, JBCheckBox> checkbox : myFilterCheckboxes.entrySet()) {
      if (checkbox.getValue().isSelected()) {
        result.add(checkbox.getKey());
      }
    }
    return result;
  }

  @Nls
  @Override
  public String getDisplayName() {
    return XmlBundle.message("configurable.XmlEmmetConfigurable.display.name");
  }

  @Nullable
  @Override
  public String getHelpTopic() {
    return getId();
  }

  @NotNull
  @Override
  public String getId() {
    return "reference.idesettings.emmet.xml";
  }
}


text:
Unknown Resource Requested

Unable to locate the resource you are looking for.


text:
%include "x86-helpers.asm"

nasm_util_assert_boilerplate
thunk_boilerplate

; branch notes
;
; The BTB seems to have a 32-byte granularity and only the first taken
; branch in a 32-byte region gets a "fast" back-to-back prediction, of
; 1 cycle
; the second branch in a 32-byte region appears to take at least 2 cycles
; sometimes longer, exhibiting patterns such as 5.0, 5.67 or 6.33 cycles for
; two such branches for the *same* benchmark, from run to run
; an lfence inside the loop appears to remove the variance (only the
; fastest timing shows).
; The "second" determination is based on the IP, not frequency: even if the
; second branch is jumped to 2x as often, the first branch retains the fast
; behavior.
; an lfence before the benchmark but outside the loop seems to reduce
; the variance
;
;
; indirect branches
;
; indirect seem to have a best-case throughput of 1 per 2 cycles,
; regardless of spacing

; fill the given number of bytes with nop3, using
; plain nop for the 0-2 odd bytes at the end
%macro fillnop3 1-2 2
times ((%1 - %2) / 3) nop3
times ((%1 - %2) % 3) nop
%endmacro

%macro jmp_forward 1
%assign jump_bytes %1
%if %1 < 2
%error jump should be at least two bytes
%assign jump_bytes 2
%endif
    jmp %%target
    fillnop3 jump_bytes
%%target:
%undef jump_bytes
%endmacro

; make a benchmark that jumps forward by %1 bytes
; then by %2 bytes, repeated 10 times
;
; shows the important of jump spacing on BTB access
; and or prediction latency
;
; %1 first jump distance
; %2 second jump distance
%macro define_jmp_forward 2
define_bench jmp_forward_%1_%2
    xor eax, eax
    clc
    jmp .top

align 64
.top:

%rep 10
    jmp_forward %1
    jmp_forward %2
%endrep

    dec rdi
    jnz .top
    nop2
    ret
%endmacro

define_jmp_forward   8,   8
define_jmp_forward  16,  16
define_jmp_forward  32,  32
define_jmp_forward  64,  64
define_jmp_forward  96,  96
define_jmp_forward 128, 128

; This test consists of a series of forward jumps, two per "block", organized
; into two chains: a first chain whose jmp is always first in the block and
; targets the first jmp in the second block, and a second chain that is similar
; except using the second jump.
;
; We go though three chains every iteration, either 2 first and 1 second, or
; 2 second and 1 first chains. This test shows that the first jump in a block
; is resolved faster (1 cycle) by the BTB, since the variant with 2:1
; first:second jumps is faster by 1 cycle per jmp tham the 1:2 variant.
;
; %1 total gap (between first/second jump in one block and first/second
; %2 first gap (between first and second jump targets)
; jump in the next)
; %3: 0 means the second jump occurs in a 2:1 ratio with the first
;     1 means the second jump occurs in a 1:2 ratio with the first
; %4 offset of the first jump after the start of the block
%macro define_jmp_forward_dual 4
define_bench jmp_forward_dual_%1_%2_%3
    xor eax, eax
    jmp .first_1

align 64

%assign reps 10
%assign fill1 %2
%assign fill2 (%1 - %2 - %4)

%assign i 1
%rep (reps-1)
    %assign next (i+1)
    fillnop3 %4, 0
.first_%+i:
    jmp  .first_%+next
    fillnop3 fill1
.second_%+i:
    jmp .second_%+next
    fillnop3 fill2
%assign i (i+1)
%endrep

%if %3
%define target1 first
%define target2 second
%else
%define target1 second
%define target2 first
%endif

; the final iteration of the first pass jumps to
; the first target of the second pass, unconditionally
. %+ target1 %+ _ %+ reps:
    jmp     . %+ target2 %+ _1

; while the second iteration alternates between jumping again
; to the second pass and the first pass (in the latter case
; also checking for termination). So the first:second passes are
; executed in a 1:2 ratio
. %+ target2 %+ _ %+ reps:
    xor     eax, 1
    jnz      . %+ target2 %+ _1
    dec rdi
    jnz . %+ target1 %+ _1
    ret
%endmacro

define_jmp_forward_dual 32, 16, 0, 3
define_jmp_forward_dual 32,  6, 0, 3
define_jmp_forward_dual 64, 16, 0, 3
define_jmp_forward_dual 64, 48, 0, 3
define_jmp_forward_dual 32, 16, 1, 3
define_jmp_forward_dual 32,  6, 1, 3
define_jmp_forward_dual 64, 16, 1, 3
define_jmp_forward_dual 64, 48, 1, 3

struc jmp_loop_args
    .total  : resd 1
    .first  : resd 1
endstruc

; this is similar to the jmp_forward_dual test
; except that we execute the forward jump region
; 100x times in a loop, split in a configurable way
; between the first and second regions
;
; %1 total gap (between first/second jump in one block and first/second
; %2 first gap (between first and second jump targets)
%macro define_jmp_loop_generic 2
define_bench jmp_loop_generic_%1_%2
%define block_size  %1
%define gap         %2

    mov edx, [rsi + jmp_loop_args.total]
    mov ecx, [rsi + jmp_loop_args.first]

%define total_iters edx
%define first_iters ecx

    xor eax, eax
    jmp .bottom
    ud2

align 64

%assign reps 10
%assign fill1 gap
%assign fill2 (block_size - gap)

%assign i 1
%rep (reps-1)
    %assign next (i+1)
.first_%+i:
    jmp  .first_%+next
    fillnop3 fill1
.second_%+i:
    jmp .second_%+next
    fillnop3 fill2
%assign i (i+1)
%endrep

.first_%+i:
    nop
    nop
.second_%+i:

.bottom:
    inc eax
    cmp eax, first_iters
    jle .first_1
    cmp eax, total_iters
    jle .second_1

    xor eax, eax
    dec rdi
    jnz .bottom

.done:
    ret
%endmacro

define_jmp_loop_generic 32, 16

%macro indirect_forward 1
%%before:
    add rax, %%target - %%before
    jmp rax
%%after:

%assign rem (%1 - (%%after - %%before))
%if rem < 0
%error indirect jump bytes too small: smaller than lea/jmp pair
%endif
    times (rem / 3) nop3
    times (rem % 3) nop
%%target:

%undef rem
%endmacro

%macro define_indirect_forward 1
define_bench indirect_forward_%1
    xor eax, eax
    clc
    jmp .top

align 64
.top:
    lea rax, [.before]

.before:

%rep 20
    indirect_forward %1
%endrep

    dec rdi
    jnz .top
    nop2
    ret
%endmacro

define_indirect_forward  8
define_indirect_forward 16
define_indirect_forward 32
define_indirect_forward 64

%macro define_indirect_variable 1
define_bench define_indirect_variable
    xor eax, eax
    clc
    lea rax, [.nops]

    jmp .top
align 64
.top:

.before:

    mov rdx, rdi
    and rdx, 127
    lea rdx, [rax + rdx * 2]
    jmp rdx

.nops:
    times 128 nop2

    dec rdi
    jnz .top
    nop2
    ret
%endmacro

define_indirect_variable 0

; ALIGNMODE p6,nojmp

%define LAT_BODY_SIZE 64
%define LAT_BODY_COUNT_LG2 3
%define LAT_BODY_COUNT (1 << LAT_BODY_COUNT_LG2)

; %1 1st instruction
; %2 2nd instruction
%macro lat_body 2
    ; chaining instructions
    %1
    %2
    ; do the LCG
    imul    rdx, rax ; x*a
    add     rdx, rcx ; + c
    mov      r8, rdx
    shr      r8, 45  ; high bits have much longer cycles
    and     r8d, (LAT_BODY_COUNT - 1)
    imul     r8, LAT_BODY_SIZE
    lea      r8, [r8 + .top]
    dec     rdi
    cmovz    r8, r11 ; jump to end when rdi == 0
    jmp      r8
%endmacro

; %1 name suffix
; %2 fist payload instruction
; %3 fist payload instruction
%macro define_load_alloc 3
define_bench la_%1
    push 0
    xor r10d, r10d
    lea r11, [rel .end]
    mov rax, 6364136223846793005
    mov ecx, 1
    mov rdx, rax

    jmp .top

align 64
.top:
%rep LAT_BODY_COUNT
    lat_body {%2},{%3}
ALIGN 64
%endrep
.end:
    pop rax
    ret

%assign GAP (.end - .top)
%assign GAPPER (GAP / LAT_BODY_COUNT)
%if GAP != LAT_BODY_SIZE * LAT_BODY_COUNT
%error wrong LAT BODY SIZE (LAT_BODY_SIZE) vs GAPPER
%endif
%undef GAP
%undef GAPPER

%endmacro

; See this tweet from Rivet Amber
; https://twitter.com/rivet_amber/status/1312141314629148673
;
; The idea is that IACA shows that load instructions take an extra 3 cycles (4 total)
; from allocation until when they can be dispatched.
;
; We test this by setting up a test that jumps around randomly using indirect branches
; between 8 identical blocks. This will mispredict with a rate of 87.5% (7/8) and we
; use the misprediction to ensure that allocation starts fresh every time, and we put
; two 'payload' instrucitons as the first two in each block, and include them in the dep
; chain leading to the next branch mispredict. In particular, they modify (but don't
; actually change the value) of rdx which is contains the state of the rng and is used
; to calculate the next jump address.
;
; We have two variants of this test with differnet payload: one with a load+add and a nop,
; and one with two lea instructions. Nominally, both add 6 cycles to the latency chain (5
; cycles for the load + 1 for the add, and 3 + 3 for the two LEAs), so if the measured
; performacne is the same, we conclude that load don't have this additional allocation time.
;
; On Skylake, I find that both run in the same time, indicating no additional allocation time.
define_load_alloc load,{add rdx, [rsp + r10]},{nop5}
define_load_alloc lea,{lea rdx, [rdx + r10 - 1]},{lea rdx, [rdx + r10 + 1]}


text:
@interface Student : NSObject
{
    int studentNum;
    NSString *name;
    int age;
    NSString *sex;
}
-(int)getAge;
-(void)setAge:(int)Age;
-(void)setStudentNum:(int)studentNum;
-(void)showInfo;

- (id)initWithStudentNum:(int)s_num
                 stuName:(NSString *)s_name
                  stuAge:(int)s_age
               stuGender:(NSString *)s_sex;

@end


text: $('.dropdown').dropdown()


text:
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema AppCloudDB
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema AppCloudDB
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `AppCloudDB` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `AppCloudDB` ;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_APP_TYPE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_APP_TYPE` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `description` VARCHAR(1000) NULL,
  `buildable` int(1) DEFAULT '1',
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Populate Data to `AppCloudDB`.`AC_APP_TYPE`
-- -----------------------------------------------------
INSERT INTO `AC_APP_TYPE` (`id`, `name`, `description`) VALUES
(1, 'war', 'Allows you to create dynamic websites using Servlets and JSPs and deploy web services.'),
(2, 'mss', 'Allows you to create microservices in Java, using an annotation-based programming model. MSF4J stands for Microservices Framework for Java.'),
(3, 'php', 'Allows you to create dynamic web pages and complete server applications using PHP web applications.'),
(4, 'jaggery', 'Allows you to write all parts of web applications, services and APIs in a completely JavaScript way.'),
(5, 'wso2dataservice', 'Allows you to deploy a data service that is supported in WSO2 Data Services Server.'),
(6, 'wso2esb', 'Allows you to deploy a esb configuration that is supported in WSO2 Enterprise Service Bus');

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_RUNTIME`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_RUNTIME` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `repo_url` VARCHAR(250) NULL,
  `image_name` VARCHAR(100) NULL,
  `tag` VARCHAR(45) NOT NULL,
  `description` VARCHAR(1000) NULL,
  PRIMARY KEY (`id`, `name`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Populate Data to `AppCloudDB`.`ApplicationRuntime`
-- -----------------------------------------------------

INSERT INTO `AC_RUNTIME` (`id`, `name`, `repo_url`, `image_name`, `tag`, `description`) VALUES
(1, 'Apache Tomcat 8.0.28 / WSO2 Application Server 6.0.0-M1 - Deprecated (will work until 2016/09/30)', 'registry.docker.appfactory.private.wso2.com:5000', 'wso2as', '6.0.0-m1', 'OS:Debian, JAVA Version:8u72'),
(2, 'OpenJDK 8 + WSO2 MSF4J 1.0.0 - Deprecated Runtime (Will continue to work until 2016/9/30)', 'registry.docker.appfactory.private.wso2.com:5000', 'msf4j', '1.0.0', 'OS:Debian, JAVA Version:8u72'),
(3, 'Apache 2.4.10', 'registry.docker.appfactory.private.wso2.com:5000','php','5.6', 'OS:Debian, PHP Version:5.6.20'),
(4, 'Carbon 4.2.0', 'registry.docker.appfactory.private.wso2.com:5000','carbon','4.2.0', 'OS:Debian, Java Version:7u101'),
(5, 'Jaggery 0.11.0 - Deprecated Runtime (Will continue to work until 2016/9/30)', 'registry.docker.appfactory.private.wso2.com:5000', 'jaggery', '0.11.0', 'OS:Debian, Java Version:7u101'),
(6, 'Apache Tomcat 8.0.28 / WSO2 Application Server 6.0.0-M2', 'registry.docker.appfactory.private.wso2.com:5000', 'wso2as', '6.0.0-m2', 'OS:Debian, JAVA Version:8u72'),
(7, 'WSO2 Data Services Server - 3.5.0','registry.docker.appfactory.private.wso2.com:5000', 'wso2dataservice', '3.5.0', 'OS:Debian, Java Version:7u101'),
(8, 'OpenJDK 8 + WSO2 MSF4J 2.0.0', 'registry.docker.appfactory.private.wso2.com:5000', 'msf4j', '2.0.0', 'OS:Debian, JAVA Version:8u72'),
(9, 'WSO2 Enterprise Service Bus - 5.0.0','registry.docker.appfactory.private.wso2.com:5000', 'wso2esb', '5.0.0', 'OS:Debian, Java Version:7u101'),
(10, 'Apache Tomcat 8.0.28 / WSO2 Application Server 6.0.0-M3','registry.docker.appfactory.private.wso2.com:5000', 'wso2as', '6.0.0-m3', 'OS:Debian, JAVA Version:8u72');

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_APPLICATION`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_APPLICATION` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `hash_id` VARCHAR(24) NULL,
  `description` VARCHAR(1000) NULL,
  `tenant_id` INT NOT NULL,
  `default_version` varchar(24) DEFAULT NULL,
  `app_type_id` INT NULL,
  `custom_domain` VARCHAR(200) NULL,
  `cloud_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT uk_Application_NAME_TID_REV UNIQUE(`name`, `tenant_id`),
  CONSTRAINT `fk_Application_ApplicationType1`
    FOREIGN KEY (`app_type_id`)
    REFERENCES `AppCloudDB`.`AC_APP_TYPE` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT fk_Application_CloudType1
    FOREIGN KEY (cloud_id)
    REFERENCES AppCloudDB.AC_CLOUD (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_DEPLOYMENT`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_DEPLOYMENT` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NULL,
  `replicas` INT NULL,
  `tenant_id` INT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_VERSION`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_VERSION` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(13) NULL,
  `hash_id` VARCHAR(24) NULL,
  `application_id` INT NOT NULL,
  `runtime_id` INT NOT NULL,
  `status` VARCHAR(45) NULL,
  `deployment_id` INT NULL,
  `tenant_id` INT NULL,
  `con_spec_cpu` VARCHAR(10) NOT NULL,
  `con_spec_memory` VARCHAR(10) NOT NULL,
  `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `is_white_listed` TINYINT unsigned NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_AC_VERSION_AC_APPLICATION1`
    FOREIGN KEY (`application_id`)
    REFERENCES `AppCloudDB`.`AC_APPLICATION` (`id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_AC_VERSION_ApplicationRuntime1`
    FOREIGN KEY (`runtime_id`)
    REFERENCES `AppCloudDB`.`AC_RUNTIME` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_AC_VERSION_ApplicationDeployment1`
    FOREIGN KEY (`deployment_id`)
    REFERENCES `AppCloudDB`.`AC_DEPLOYMENT` (`id`)
    ON DELETE SET NULL
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_TAG`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_TAG` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `value` VARCHAR(100) NULL,
  `version_id` INT NOT NULL,
  `description` VARCHAR(1000) NULL,
  `tenant_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_AC_TAG_AC_VERSION1`
    FOREIGN KEY (`version_id`)
    REFERENCES `AppCloudDB`.`AC_VERSION` (`id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_RUNTIME_PROPERTY`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_RUNTIME_PROPERTY` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(200) NOT NULL,
  `value` VARCHAR(2000) NULL,
  `version_id` INT NOT NULL,
  `description` VARCHAR(1000) NULL,
  `tenant_id` INT NOT NULL,
  `is_secured` BIT(1) NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_AC_RUNTIME_PROPERTY_AC_VERSION1`
    FOREIGN KEY (`version_id`)
    REFERENCES `AppCloudDB`.`AC_VERSION` (`id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_TENANT_APP_TYPE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_TENANT_APP_TYPE` (
  `tenant_id` INT NOT NULL,
  `app_type_id` INT NOT NULL,
  CONSTRAINT `fk_TenantAppType_ApplicationType1`
    FOREIGN KEY (`app_type_id`)
    REFERENCES `AppCloudDB`.`AC_APP_TYPE` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_APP_TYPE_RUNTIME`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_APP_TYPE_RUNTIME` (
  `app_type_id` INT NOT NULL,
  `runtime_id` INT NOT NULL,
  CONSTRAINT `fk_ApplicationType_has_ApplicationRuntime_ApplicationType1`
    FOREIGN KEY (`app_type_id`)
    REFERENCES `AppCloudDB`.`AC_APP_TYPE` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_ApplicationType_has_ApplicationRuntime_ApplicationRuntime1`
    FOREIGN KEY (`runtime_id`)
    REFERENCES `AppCloudDB`.`AC_RUNTIME` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Populate Data to `AppCloudDB`.`ApplicationTypeRuntime`
-- -----------------------------------------------------
INSERT INTO `AC_APP_TYPE_RUNTIME` (`app_type_id`, `runtime_id`) VALUES
(1, 1),
(2, 2),
(3, 3),
(4, 5),
(1, 6),
(5, 7),
(2, 8),
(6, 9),
(1, 10),
(4, 10);

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_TENANT_RUNTIME`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_TENANT_RUNTIME` (
  `tenant_id` INT NOT NULL,
  `runtime_id` INT NOT NULL,
  CONSTRAINT `fk_TenanntRuntime_ApplicationRuntime1`
    FOREIGN KEY (`runtime_id`)
    REFERENCES `AppCloudDB`.`AC_RUNTIME` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_EVENT`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_EVENT` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  `status` VARCHAR(45) NULL,
  `version_id` INT NOT NULL,
  `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `description` VARCHAR(1000) NULL,
  `tenant_id` INT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_CONTAINER`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_CONTAINER` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NULL,
  `version` VARCHAR(45) NULL,
  `deployment_id` INT NOT NULL,
  `tenant_id` INT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_ApplicationContainer_ApplicationDeployment1`
    FOREIGN KEY (`deployment_id`)
    REFERENCES `AppCloudDB`.`AC_DEPLOYMENT` (`id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_CONTAINER_SERVICE_PROXY`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_CONTAINER_SERVICE_PROXY` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NULL,
  `protocol` VARCHAR(20) NULL,
  `port` INT NULL,
  `backend_port` VARCHAR(45) NULL,
  `container_id` INT NOT NULL,
  `tenant_id` INT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_ApplicationServiceProxy_ApplicationContainer1`
    FOREIGN KEY (`container_id`)
    REFERENCES `AppCloudDB`.`AC_CONTAINER` (`id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_APP_ICON`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_APP_ICON` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `icon` MEDIUMBLOB DEFAULT NULL,
  `application_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `application_id_UNIQUE` (`application_id` ASC),
  CONSTRAINT `fk_AC_APPLICATION_ICON_AC_APPLICATION1`
    FOREIGN KEY (`application_id`)
    REFERENCES `AppCloudDB`.`AC_APPLICATION` (`id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_TRANSPORT`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_TRANSPORT` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(20) NOT NULL,
  `port` INT NOT NULL,
  `protocol` VARCHAR(4) NOT NULL,
  `service_prefix` VARCHAR(3) NOT NULL,
  `description` VARCHAR(1000) NULL DEFAULT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_RUNTIME_TRANSPORT`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_RUNTIME_TRANSPORT` (
  `transport_id` INT NOT NULL,
  `runtime_id` INT NOT NULL,
  CONSTRAINT `fk_Service_id`
    FOREIGN KEY (`transport_id`)
    REFERENCES `AppCloudDB`.`AC_TRANSPORT` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_ApplicationRuntime_id`
    FOREIGN KEY (`runtime_id`)
    REFERENCES `AppCloudDB`.`AC_RUNTIME` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS AC_SUBSCRIPTION_PLANS (
    PLAN_ID	INTEGER NOT NULL AUTO_INCREMENT,
    PLAN_NAME   VARCHAR(200) NOT NULL,
    MAX_APPLICATIONS	INT NOT NULL,
    MAX_DATABASES INT NOT NULL,
    CLOUD_ID INT NOT NULL,
    PRIMARY KEY (PLAN_ID),
    CONSTRAINT fk_SubscriptionPlans_CloudType1 FOREIGN KEY (CLOUD_ID) REFERENCES AppCloudDB.AC_CLOUD (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT uk_SubscriptionPlans_PlanName_CloudId UNIQUE(PLAN_NAME, CLOUD_ID))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS AC_CONTAINER_SPECIFICATIONS (
    CON_SPEC_ID     INTEGER NOT NULL AUTO_INCREMENT,
    CON_SPEC_NAME   VARCHAR(200) NOT NULL,
    CPU              INT NOT NULL,
    MEMORY	     INT NOT NULL,
    COST_PER_HOUR    INT NOT NULL,
    PRIMARY KEY (CON_SPEC_ID))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS AC_RUNTIME_CONTAINER_SPECIFICATIONS (
  id int(11) NOT NULL,
  CON_SPEC_ID int(11) NOT NULL,
  PRIMARY KEY (id,CON_SPEC_ID),
  KEY CON_SPEC_ID (CON_SPEC_ID))
ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_WHITE_LISTED_TENANTS` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `tenant_id` INT NOT NULL,
  `max_app_count` INT(11) DEFAULT -1,
  `max_database_count` INT(11) DEFAULT -1,
  `cloud_id` INT NOT NULL,
  PRIMARY KEY (`id`, `tenant_id`),
  CONSTRAINT fk_WhiteListedTenants_CloudType1 FOREIGN KEY (cloud_id) REFERENCES AppCloudDB.AC_CLOUD (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT uk_WhiteListedTenants UNIQUE (tenant_id, cloud_id))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_APPLICAION_CONTEXTS` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `tenant_id` INT NOT NULL,
  `version_id` INT NOT NULL,
  `context` VARCHAR(200) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE (`version_id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Populate Data to `AppCloudDB`.`ApplicationRuntime`
-- -----------------------------------------------------

INSERT INTO `AC_TRANSPORT` (`id`, `name`, `port`, `protocol`, `service_prefix`, `description`) VALUES
(1, 'http', 80, 'TCP', 'htp', 'HTTP Protocol'),
(2, 'https', 443, 'TCP', 'hts', 'HTTPS Protocol'),
(3, 'http-alt', 8080, 'TCP', 'htp', 'HTTP Alternate Protocol'),
(4, 'https-alt', 8443, 'TCP', 'hts', 'HTTPS Alternate Protocol'),
(5, 'http', 9763, 'TCP', 'htp', 'HTTP servlet transport for carbon products'),
(6, 'https', 9443, 'TCP', 'hts', 'HTTPS servlet transport for carbon products'),
(7, 'http', 8280, 'TCP', 'htp', 'HTTP Protocol'),
(8, 'https', 8243, 'TCP', 'hts', 'HTTPS Protocol');

-- -----------------------------------------------------
-- Populate Data to `AppCloudDB`.`ApplicationRuntimeService`
-- -----------------------------------------------------
INSERT INTO `AC_RUNTIME_TRANSPORT` (`transport_id`, `runtime_id`) VALUES
(4, 1),
(4, 2),
(1, 3),
(4, 4),
(3, 1),
(3, 2),
(2, 3),
(3, 4),
(6, 5),
(5, 5),
(3, 6),
(4, 6),
(5, 7),
(6, 7),
(3, 8),
(4, 8),
(7, 9),
(8, 9),
(3, 10),
(4, 10);

INSERT INTO `AC_CONTAINER_SPECIFICATIONS` (`CON_SPEC_NAME`, `CPU`, `MEMORY`, `COST_PER_HOUR`) VALUES
('128MB RAM and 0.1x vCPU', 100, 128, 1),
('256MB RAM and 0.2x vCPU', 200, 256, 2),
('512MB RAM and 0.3x vCPU', 300, 512, 3),
('1024MB RAM and 0.5x vCPU', 500, 1024, 4);

INSERT INTO `AC_SUBSCRIPTION_PLANS` (`PLAN_ID`, `PLAN_NAME`, `MAX_APPLICATIONS`, `MAX_DATABASES`, `CLOUD_ID`) VALUES
(1, 'FREE', 3, 3, 1),
(2, 'PAID', 10, 6, 1),
(3, 'FREE', 3, 3, 2),
(4, 'PAID', 10, 6, 2);

INSERT INTO `AC_RUNTIME_CONTAINER_SPECIFICATIONS` (`id`, `CON_SPEC_ID`) VALUES
(1, 3),
(2, 2),
(2, 3),
(3, 1),
(3, 2),
(3, 3),
(5, 3),
(6, 3),
(7, 3),
(1, 4),
(7, 4),
(2, 4),
(8, 2),
(8, 3),
(8, 4),
(5, 4),
(6, 4),
(9, 3),
(9, 4),
(10, 3),
(10, 4);

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_CLOUD`
-- -----------------------------------------------------

CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_CLOUD` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE (`name`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Populate Data to `AppCloudDB`.`AC_CLOUD`
-- -----------------------------------------------------

INSERT INTO `AC_CLOUD` (`id`, `name`) VALUES
(1, 'app-cloud'),
(2, 'integration-cloud');

-- -----------------------------------------------------
-- Table `AppCloudDB`.`AC_CLOUD_APP_TYPE`
-- -----------------------------------------------------

CREATE TABLE IF NOT EXISTS `AppCloudDB`.`AC_CLOUD_APP_TYPE` (
  `cloud_id` INT NOT NULL,
  `app_type_id` INT NOT NULL,
  CONSTRAINT `fk_cloud_has_cloudAppType_cloud`
    FOREIGN KEY (`cloud_id`)
    REFERENCES `AppCloudDB`.`AC_CLOUD` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_cloud_has_cloudAppType_appType`
    FOREIGN KEY (`app_type_id`)
    REFERENCES `AppCloudDB`.`AC_APP_TYPE` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Populate Data to `AppCloudDB`.`AC_CLOUD_APP_TYPE`
-- -----------------------------------------------------

INSERT INTO `AC_CLOUD_APP_TYPE` (`cloud_id`, `app_type_id`) VALUES
(1, 1),
(1, 2),
(1, 3),
(1, 4),
(1, 5),
(2, 6);

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


text:
from distutils.core import setup

setup(name="Example",
      version="1.0",
      description="sample description",
      author="sample author",
      author_email="sample email",
      url="sample url",
      packages=[],
      package_dir={},
      requires=["Dependency1", "dependency2"],
      )


text:
<?php

defined('_JEXEC') or die;

jimport('joomla.application.component.controllerform');

class ContactControllerContact extends JControllerForm
{
	public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true))
	{
		return parent::getModel($name, $prefix, array('ignore_request' => false));
	}

	public function submit()
	{
		// Check for request forgeries.
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Initialise variables.
		$app    = JFactory::getApplication();
		$model  = $this->getModel('contact');
		$params = JComponentHelper::getParams('com_contact');
		$stub   = JRequest::getString('id');
		$id     = (int) $stub;

		// Get the data from POST
		$data = JRequest::getVar('jform', array(), 'post', 'array');

		$contact = $model->getItem($id);

		$params->merge($contact->params);

		// Check for a valid session cookie
		if ($params->get('validate_session', 0))
		{
			if (JFactory::getSession()->getState() != 'active')
			{
				JError::raiseWarning(403, JText::_('COM_CONTACT_SESSION_INVALID'));

				// Save the data in the session.
				$app->setUserState('com_contact.contact.data', $data);

				// Redirect back to the contact form.
				$this->setRedirect(JRoute::_('index.php?option=com_contact&view=contact&id=' . $stub, false));

				return false;
			}
		}

		// Contact plugins
		JPluginHelper::importPlugin('contact');
		$dispatcher = JDispatcher::getInstance();

		// Validate the posted data.
		$form = $model->getForm();

		if (!$form)
		{
			JError::raiseError(500, $model->getError());

			return false;
		}

		$validate = $model->validate($form, $data);

		if ($validate === false)
		{
			// Get the validation messages.
			$errors = $model->getErrors();

			// Push up to three validation messages out to the user.
			for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
			{
				if ($errors[$i] instanceof Exception)
				{
					$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
				}
				else
				{
					$app->enqueueMessage($errors[$i], 'warning');
				}
			}

			// Save the data in the session.
			$app->setUserState('com_contact.contact.data', $data);

			// Redirect back to the contact form.
			$this->setRedirect(JRoute::_('index.php?option=com_contact&view=contact&id=' . $stub, false));

			return false;
		}

		// Validation succeeded, continue with custom handlers
		$results = $dispatcher->trigger('onValidateContact', array(&$contact, &$data));

		foreach ($results as $result)
		{
			if ($result instanceof Exception)
			{
				return false;
			}
		}

		// Passed Validation: Process the contact plugins to integrate with other applications
		$results = $dispatcher->trigger('onSubmitContact', array(&$contact, &$data));

		// Send the email
		$sent = false;

		if (!$params->get('custom_reply'))
		{
			$sent = $this->_sendEmail($data, $contact, $params->get('show_email_copy'));
		}

		// Set the success message if it was a success
		if (!($sent instanceof Exception))
		{
			$msg = JText::_('COM_CONTACT_EMAIL_THANKS');
		}
		else
		{
			$msg = '';
		}

		// Flush the data from the session
		$app->setUserState('com_contact.contact.data', null);

		// Redirect if it is set in the parameters, otherwise redirect back to where we came from
		if ($contact->params->get('redirect'))
		{
			$this->setRedirect($contact->params->get('redirect'), $msg);
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_contact&view=contact&id=' . $stub, false), $msg);
		}

		return true;
	}

	private function _sendEmail($data, $contact, $copy_email_activated)
	{
		$app    = JFactory::getApplication();
		$params = JComponentHelper::getParams('com_contact');

		if ($contact->email_to == '' && $contact->user_id != 0)
		{
			$contact_user      = JUser::getInstance($contact->user_id);
			$contact->email_to = $contact_user->get('email');
		}

		$mailfrom = $app->getCfg('mailfrom');
		$fromname = $app->getCfg('fromname');
		$sitename = $app->getCfg('sitename');
		$copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename);

		$name    = $data['contact_name'];
		$email   = $data['contact_email'];
		$subject = $data['contact_subject'];
		$body    = $data['contact_message'];

		// Prepare email body
		$prefix = JText::sprintf('COM_CONTACT_ENQUIRY_TEXT', JURI::base());
		$body   = $prefix . "\n" . $name . ' <' . $email . '>' . "\r\n\r\n" . stripslashes($body);

		$mail = JFactory::getMailer();
		$mail->addRecipient($contact->email_to);
		$mail->addReplyTo(array($email, $name));
		$mail->setSender(array($mailfrom, $fromname));
		$mail->setSubject($sitename . ': ' . $subject);
		$mail->setBody($body);
		$sent = $mail->Send();

		// If we are supposed to copy the sender, do so.
		// Check whether email copy function activated
		if ($copy_email_activated == true && isset($data['contact_email_copy']))
		{
			$copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename);
			$copytext .= "\r\n\r\n" . $body;
			$copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);

			$mail = JFactory::getMailer();
			$mail->addRecipient($email);
			$mail->addReplyTo(array($email, $name));
			$mail->setSender(array($mailfrom, $fromname));
			$mail->setSubject($copysubject);
			$mail->setBody($copytext);
			$sent = $mail->Send();
		}

		return $sent;
	}
}


text:
package com.yammer.schedulizer.resources;

import com.yammer.schedulizer.auth.Authorize;
import com.yammer.schedulizer.auth.Role;
import com.yammer.schedulizer.entities.Employee;
import com.yammer.schedulizer.entities.Group;
import com.yammer.schedulizer.entities.User;
import com.yammer.schedulizer.managers.EmployeeManager;
import com.yammer.schedulizer.utils.ResourceUtils;
import io.dropwizard.hibernate.UnitOfWork;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Set;

@Path("/employees")
@Produces(MediaType.APPLICATION_JSON)
public class EmployeesResource {

    private EmployeeManager employeeManager;

    public EmployeesResource(EmployeeManager employeeManager) {
        this.employeeManager = employeeManager;
    }

    @GET
    @Path("/{employee_id}/groups")
    @UnitOfWork
    public Response getEmployeeGroups(
            @PathParam("employee_id") long employeeId) {

        Employee employee = employeeManager.getById(employeeId);
        Set<Group> groups = employee.getGroups();
        return Response.ok().entity(groups).build();
    }

    @GET
    @Path("/{employee_id}")
    @UnitOfWork
    public Response getEmployee(
            @PathParam("employee_id") long employeeId) {

        Employee employee = employeeManager.getById(employeeId);
        return Response.ok().entity(employee).build();
    }

    @POST
    @Path("/{employee_id}")
    @UnitOfWork
    public Response updateEmployee(
            @Authorize({Role.ADMIN, Role.MEMBER}) User user,
            @PathParam("employee_id") long employeeId,
            @FormParam("name") String name,
            @FormParam("imageUrlTemplate") String imageUrlTemplate) {

        ResourceUtils.checkConflictFree(user.getEmployee().getId() == employeeId, User.class);
        employeeManager.updateByEmployeeId(employeeId, (Employee e) -> {
            e.setName(name);
            e.setImageUrlTemplate(imageUrlTemplate);
        });
        return Response.ok().build();
    }
}


text:
from azure.identity import DefaultAzureCredential
from azure.mgmt.cosmosdb import CosmosDBManagementClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-cosmosdb
# USAGE
    python cosmos_db_database_account_create_min.py

    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""

def main():
    client = CosmosDBManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id="subid",
    )

    response = client.database_accounts.begin_create_or_update(
        resource_group_name="rg1",
        account_name="ddb1",
        create_update_parameters={
            "location": "westus",
            "properties": {
                "createMode": "Default",
                "databaseAccountOfferType": "Standard",
                "locations": [{"failoverPriority": 0, "isZoneRedundant": False, "locationName": "southcentralus"}],
            },
        },
    ).result()
    print(response)

# x-ms-original-file: specification/cosmos-db/resource-manager/Microsoft.DocumentDB/preview/2022-08-15-preview/examples/CosmosDBDatabaseAccountCreateMin.json
if __name__ == "__main__":
    main()


text:
source $setup

tar -xf $src
mv xcb-* util

mkdir build
cd build

PKG_CONFIG=pkg-config-cross \
../util/configure --prefix=$out $configure_flags

make

make install


text:
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>KML Layers</title>


text:
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.poll = {
        question: "",
        isMulti: 0,
        options: ["", "", ""]
    };

    console.log($scope.poll.options.length);

    $scope.addNewOption = function() {
        $scope.poll.options.push("");
    };

    var dialog = document.querySelector('dialog');

    $scope.createPoll = function() {
        if (!$scope.poll.question) {
            var toast = { message: 'Please enter a poll question!' };
            var snackbarContainer = document.querySelector('#demo-toast-example');
            snackbarContainer.MaterialSnackbar.showSnackbar(toast);
            return;
        }
        var count = 0;
        var flag = true;
        for (var idx in $scope.poll.options) {
            if ($scope.poll.options[idx] != "") {
                count++;
                flag = false;
            }
        }
        if (flag) {
            var toast = { message: 'Please enter at least two options!' };
            var snackbarContainer = document.querySelector('#demo-toast-example');
            snackbarContainer.MaterialSnackbar.showSnackbar(toast);
        }
        if (count < 2) {
            var toast = { message: 'Please enter at least two options!' };
            var snackbarContainer = document.querySelector('#demo-toast-example');
            snackbarContainer.MaterialSnackbar.showSnackbar(toast);
        }
        if (count >= 2) {
            $http.post('/createpoll', $scope.poll).
                success(function(data, status, headers, config) {
                    console.log(JSON.stringify(data));
                    $scope.poll = {
                        question: "",
                        isMulti: 0,
                        options: ["", "", ""]
                    };
                    layer.open({
                        type: 1,
                        shift: 2,
                        closeBtn: 0,
                        shadeClose: true,
                        title: "",
                        area: ['65%', '35%'],
                        content: '

您的投票已经被创建,地址如下:
' + data.addr + '
',
                        // btn: '复制到粘贴板',
                        // yes: function(index, layero) {
                        //     var clipboard = new Clipboard('.layui-layer-btn0', {
                        //         text: function() {
                        //             return data.addr;
                        //         }
                        //     });
                        //     clipboard.on('success', function(e) {
                        //         console.log(e);
                        //     });
                        //     clipboard.on('error', function(e) {
                        //         console.log(e);
                        //     });
                        // }
                    });
                }).
                error(function(data, status, headers, config) {
                    console.log(status);
                });
        }
    };

}])


text:
require 'rspec_helper'

unless `cat /etc/*-release` =~ /CentOS release 6/
  describe 'Chrome Grid' do
    before(:all) do
      @selenium = Selenium::WebDriver.for(:remote, desired_capabilities: :chrome)
    end

    after(:all) do
      @selenium.quit
    end

    it 'Should return display resolution of 1280x1024' do
      @selenium.get 'http://www.whatismyscreenresolution.com/'
      element = @selenium.find_element(:id, 'resolutionNumber')
      expect(element.text).to eq('1280 x 1024')
    end
  end
end


text:
namespace UnicornHack.Utils.MessagingECS;

public enum MessageProcessingResult
{
    StopProcessing,
    ContinueProcessing
}


text:
from __future__ import unicode_literals

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from mwparserfromhell.compat import str
from mwparserfromhell.nodes import Comment

from ._test_tree_equality import TreeEqualityTestCase

class TestComment(TreeEqualityTestCase):
    """Test cases for the Comment node."""

    def test_unicode(self):
        """test Comment.__unicode__()"""
        node = Comment("foobar")
        self.assertEqual("<!--foobar-->", str(node))

    def test_children(self):
        """test Comment.__children__()"""
        node = Comment("foobar")
        gen = node.__children__()
        self.assertRaises(StopIteration, next, gen)

    def test_strip(self):
        """test Comment.__strip__()"""
        node = Comment("foobar")
        for a in (True, False):
            for b in (True, False):
                self.assertIs(None, node.__strip__(a, b))

    def test_showtree(self):
        """test Comment.__showtree__()"""
        output = []
        node = Comment("foobar")
        node.__showtree__(output.append, None, None)
        self.assertEqual(["<!--foobar-->"], output)

    def test_contents(self):
        """test getter/setter for the contents attribute"""
        node = Comment("foobar")
        self.assertEqual("foobar", node.contents)
        node.contents = "barfoo"
        self.assertEqual("barfoo", node.contents)

if __name__ == "__main__":
    unittest.main(verbosity=2)


text:
layout: page
title: Solis - Willis Wedding
date: 2016-05-24
author: Andrew Reyes
tags: weekly links, java
status: published
summary: Sed rutrum, ante eu interdum convallis, augue mi.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 03/14/2017
  endDate: 03/16/2017
  ctyhocn: RICMVHX
  groupCode: SWW
published: true
---
Sed sollicitudin commodo ipsum eget porttitor. Donec auctor ipsum et odio pulvinar imperdiet. Proin varius, nunc et suscipit scelerisque, ante turpis consectetur est, a rutrum quam sem vestibulum mauris. Aliquam ut elit nec mi sagittis accumsan et ut sapien. Duis risus urna, suscipit sit amet semper ac, blandit in sapien. Maecenas at urna purus. Vivamus tristique, sapien varius commodo ultrices, nunc eros suscipit ipsum, a ultricies nunc nibh eu mauris. Etiam consectetur mi vel scelerisque tempor.
Cras tincidunt, ipsum sed euismod tincidunt, augue lectus viverra tortor, ac ultrices urna sem quis eros. Ut eget tincidunt purus. Nam dignissim quam quis rutrum rutrum. Quisque venenatis mi nec aliquet fringilla. Aenean molestie eu arcu vel posuere. Duis cursus leo felis, eget feugiat erat ornare ut. Phasellus condimentum sapien ac velit porta commodo sed vel urna. Maecenas suscipit ut ex sit amet mattis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec varius dui vel purus rutrum aliquet. Praesent semper facilisis elit quis imperdiet. Maecenas sollicitudin felis id turpis rhoncus, at euismod ante fermentum. Quisque ullamcorper ligula ac mauris luctus, id posuere arcu vestibulum.

* Nunc et tellus ullamcorper, scelerisque leo eget, lobortis dui
* Etiam venenatis odio a quam hendrerit, a egestas diam consequat
* Ut eu orci molestie, blandit est ultricies, porta est.

Mauris vulputate dignissim arcu at tincidunt. Quisque ultrices lacus vel auctor vulputate. Etiam laoreet, velit sit amet volutpat lobortis, lectus enim mollis ante, a viverra lorem libero in orci. Nulla pulvinar consequat ligula. Morbi cursus leo vel nulla sollicitudin aliquam. Suspendisse potenti. Vivamus eget nisl quis tellus pulvinar aliquet.


text:
import re

from core.actionModule import actionModule
from core.keystore import KeyStore as kb
from core.mymsf import myMsf
from core.utils import Utils

class scan_msf_snmplogin(actionModule):
    def __init__(self, config, display, lock):
        super(scan_msf_snmplogin, self).__init__(config, display, lock)
        self.triggers = ["newPort_tcp_161"]
        self.requirements = ["msfconsole"]
        self.title = "Attempt Login Using Common Community Strings"
        self.shortName = "MSFSNMPLogin"
        self.description = "execute [auxiliary/scanner/snmp/snmp_login] on each target"
        self.safeLevel = 5

    def getTargets(self):
        # we are interested only in the hosts that have UDP 161 open
        self.targets = kb.get('port/udp/161')

    def process(self):
        # load any targets we are interested in
        self.getTargets()

        if len(self.targets) > 0:
            # connect to msfrpc
            msf = myMsf(host=self.config['msfhost'], port=int(self.config['msfport']), user=self.config['msfuser'],
                        password=self.config['msfpass'])

            if not msf.isAuthenticated():
                return

            # If any results are succesful, this will become true and Fire will be called in the end
            callFire = False
            # loop over each target
            for t in self.targets:
                # verify we have not tested this host before
                if not self.seentarget(t):
                    # add the new IP to the already seen list
                    self.addseentarget(t)
                    myMsf.lock.acquire()
                    self.display.verbose(self.shortName + " - Connecting to " + t)
                    msf.execute("use auxiliary/scanner/snmp/snmp_login\n")
                    msf.execute("set RHOSTS %s\n" % t)
                    msf.execute("set VERSION 2c\n")
                    msf.execute("exploit\n")
                    msf.sleep(int(self.config['msfexploitdelay']))
                    result = msf.getResult()
                    while (re.search(".*execution completed.*", result) is None):
                        result = result + msf.getResult()
                    myMsf.lock.release()

                    outfile = self.config["proofsDir"] + self.shortName + "_" + t + "_" + Utils.getRandStr(10)
                    Utils.writeFile(result, outfile)

                    parts = re.findall(".*LOGIN SUCCESSFUL.*", result)
                    for part in parts:
                        callFire = True
                        # Add all relevant details
                        p = part.split()
                        comString = p[p.index("SUCCESSFUL:") + 1]
                        self.addVuln(t, "snmpCred", {"port": "161", "message": str(part), "communityString": comString,
                                                     "output": outfile.replace("/", "%2F")})

            if callFire:
                self.fire("snmpCred")

            # clean up after ourselves
            result = msf.cleanup()

        return


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.jellytools.ide/3">
    <module_version install_time="1360797707505" last="true" origin="installer" specification_version="3.17.1.1">
        <file crc="3504672906" name="config/Modules/org-netbeans-modules-jellytools-ide.xml"/>
        <file crc="1776890358" name="modules/locale/org-netbeans-modules-jellytools-ide_ja.jar"/>
        <file crc="1288229171" name="modules/locale/org-netbeans-modules-jellytools-ide_pt_BR.jar"/>
        <file crc="3332682175" name="modules/locale/org-netbeans-modules-jellytools-ide_ru.jar"/>
        <file crc="4009693346" name="modules/locale/org-netbeans-modules-jellytools-ide_zh_CN.jar"/>
        <file crc="2089832611" name="modules/org-netbeans-modules-jellytools-ide.jar"/>
    </module_version>
</module>


text:
import { Optional } from '@ephox/katamari';

export interface WordScope {
  readonly word: string;
  readonly left: Optional<string>;
  readonly right: Optional<string>;
}

export const WordScope = (word: string, left: Optional<string>, right: Optional<string>): WordScope => ({
  word,
  left,
  right
});


text:
var baseUrl = (function () {
  var paths = window.location.pathname.split('/');
  paths.pop();
  return window.location.protocol + '//' + window.location.host + paths.join('/');
})();

var xtuple = angular.module("Xtuple", [
  "ngResource", "ngCookies", "ngRoute", "anguFixedHeaderTable"
]);

xtuple.config(["$routeProvider", function ($routeProvider) {
  $routeProvider
    .when("/signIn", {
      templateUrl: "modules/entrance/signIn.html",
      controller: "entranceSignInController"
    })
    .when("/signOut", {
      templateUrl: "modules/entrance/signIn.html",
      controller: "entranceSignOutController"
    })
    .when("/company/registration", {
      templateUrl: "modules/company/registration.html",
      controller: "companyRegistrationController"
    })
    .when("/company/registration-konsole", {
      templateUrl: "modules/company/registration-konsole.html",
      controller: "companyKonsoleController"
    })
    .when("/entrance/setting", {
      templateUrl: "modules/entrance/setting.html",
      controller: "entranceSettingController"
    })
    .when("/company/list", {
      templateUrl: "modules/company/list.html",
      controller: "companyListController"
    })
    .otherwise({
      redirectTo: "/company/list"
    });
}]);

xtuple.run(function (connectionFactory, $rootScope, $location) {
  $(".leftMenu > li").click(function (e) {
    $(".leftMenu > li").removeClass("active");
    $(e.currentTarget).addClass("active");
  });
  connectionFactory.reconnect();

  $rootScope.$on('$routeChangeSuccess', function (event, next, current) {
    if (!/\/signIn\//i.test($location.path())) {
      if ($rootScope.userInfo === undefined) {
        $location.path("/signIn");
      }
    }
    else if ($rootScope.userInfo !== undefined) {
      $location.path("/");
    }

    //console.log(event, next, current);
    //
    //$(".leftMenu > li").removeClass("active");
    //if (!/\/company\/registration\//i.test($location.path())) {
    //  $($(".leftMenu > li")[1]).addClass("active");
    //}
    //else if (!/\/company\/list\//i.test($location.path())) {
    //  $($(".leftMenu > li")[0]).addClass("active");
    //}
    //else if (!/\/company\/registration-konsole\//i.test($location.path())) {
    //  $($(".leftMenu > li")[2]).addClass("active");
    //}
    //else if (!/\/entrance\/setting\//i.test($location.path())) {
    //  $($(".leftMenu > li")[3]).addClass("active");
    //}
  });
});


text:
Convert [Grana](https://play.google.com/store/apps/details?id=com.renanferrari.grana) backup to [Financius] (https://play.google.com/store/apps/details?id=com.code44.finance) backup

You decided to change your financial tracking software from [Grana](https://play.google.com/store/apps/details?id=com.renanferrari.grana) to [Financius] (https://play.google.com/store/apps/details?id=com.code44.finance) (both are Android apps)? You are on good place. This is quick & dirty script to take your data with you.

Usage
=====
`./grana2financius.py grana_backup_file [-o fanancius_backup_file] [-h]`


text:
package gov.hhs.fha.nhinc.direct;

import static gov.hhs.fha.nhinc.direct.DirectUnitTestUtil.getSampleMimeMessage;
import gov.hhs.fha.nhinc.direct.event.DirectEventLogger;
import gov.hhs.fha.nhinc.mail.MailClientException;
import gov.hhs.fha.nhinc.mail.MailSender;
import gov.hhs.fha.nhinc.mail.MessageHandler;
import java.net.URL;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.junit.Test;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.nhindirect.gateway.smtp.MessageProcessResult;
import org.nhindirect.gateway.smtp.SmtpAgent;
import org.nhindirect.stagent.NHINDAddress;
import org.nhindirect.stagent.NHINDAddressCollection;

/**
 * Test {@link OutboundMessageHandler}.
 */
public class DirectOutboundMsgHandlerTest extends DirectBaseTest {

    private SmtpAgent mockSmtpAgent;
    private MessageProcessResult mockResult;
    private MailSender mockExtMailSender;
    private DirectSender directSender;
    private MessageHandler testOutboundMsgHandler;
    private DirectAdapter directAdapter;

    /**
     * Verify that the Outbound Message Handler will use the external direct mail client to directify the message. The
     * internal direct mail client passed in will be ignored.
     *
     * @throws MailClientException
     * @throws MessagingException
     */
    @Test
    public void canHandleOutboundMsg() throws MailClientException, MessagingException {

        mockSmtpAgent = mock(SmtpAgent.class);
        mockResult = DirectUnitTestUtil.getMockMessageProcessResult(1);
        directAdapter = mock(DirectAdapter.class);
        when(directAdapter.getSmtpAgent()).thenReturn(mockSmtpAgent);
        when(mockSmtpAgent.processMessage(any(MimeMessage.class), any(NHINDAddressCollection.class),
            any(NHINDAddress.class))).thenReturn(mockResult);

        mockExtMailSender = mock(MailSender.class);
        directSender = new DirectSenderImpl(mockExtMailSender, DirectEventLogger.getInstance()) {
            //igonre it for now. Need to come up with better unit tests for this
            @Override
            protected void addOutgoingMessage(MimeMessage message, boolean failed, String errorMessage) {
            }

            @Override
            protected SmtpAgent getSmtpAgent(URL url) {
                return mockSmtpAgent;
            }
        };
        testOutboundMsgHandler = new DirectOutboundMsgHandler(directSender);

        MimeMessage mimeMessage = getSampleMimeMessage();
        testOutboundMsgHandler.handleMessage(mimeMessage);

        verify(mockExtMailSender).send(any(Address[].class), any(MimeMessage.class));
    }
}


text:
package org.gradle.internal.component.model;

import org.gradle.internal.component.external.model.ModuleComponentArtifactMetadata;

/**
 * Represents a module descriptor artifact.
 */
public interface ModuleDescriptorArtifactMetadata extends ModuleComponentArtifactMetadata {
}


text:
package tdanford.ideals.numerics;

import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import tdanford.ideals.Polynomial;
import tdanford.ideals.PolynomialTesting;
import tdanford.ideals.Rational;
import tdanford.ideals.Rationals;

public class NewtonRaphsonTest extends PolynomialTesting {

  /**
   * Example taken from
   * http://www3.ul.ie/~mlc/support/CompMaths2/files/NewtonExample.pdf
   */
  @Test
  public void testNewtonRaphsonExample() {

    final Polynomial<Rational, Rationals> poly = kxPoly("x^3 - x - 1");

    final RootFinder<Rational, Rationals> roots = new RootFinder<>(poly, Rationals::liftInteger);

    final Rational eps = new Rational(1, 100000L);

    final Rational root = roots.newtonRaphson(
      new Rational(3, 2),
      (r1, r2) -> r1.sum(r2.negative()).abs().lessThan(eps),
      1000
      );

    assertThat(root.doubleValue()).isEqualTo(1.3247179572447898);
  }
}


text:
package org.apache.poi.sl.draw.geom;

import java.awt.geom.Path2D;

/**
 * Date: 10/25/11
 *
 * @author Yegor Kozlov
 */
public class ClosePathCommand implements PathCommand {

    ClosePathCommand(){
    }

    public void execute(Path2D.Double path, Context ctx){
        path.closePath();
    }
}