text:
<?php

/**
 * zerif functions and definitions
 *
 * @package zerif
 */

/**
 * Set the content width based on the theme's design and stylesheet.

 */

/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.

 */

function zerif_setup()
{
    global $content_width;
    if (!isset($content_width)) {

        $content_width = 640;

    }

    /*

     * Make theme available for translation.

     * Translations can be filed in the /languages/ directory.

     * If you're building a theme based on zerif, use a find and replace

     * to change 'zerif-lite' to the name of your theme in all the template files

     */

    load_theme_textdomain('zerif-lite', get_template_directory() . '/languages');

    // Add default posts and comments RSS feed links to head.

    add_theme_support('automatic-feed-links');

    /*

     * Enable support for Post Thumbnails on posts and pages.

     *

     * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails

     */

    add_theme_support('post-thumbnails');

    /* Set the image size by cropping the image */

    add_image_size('post-thumbnail', 250, 250, true);
    add_image_size( 'post-thumbnail-large', 750, 500, true ); /* blog thumbnail */
    add_image_size( 'post-thumbnail-large-table', 600, 300, true ); /* blog thumbnail for table */
    add_image_size( 'post-thumbnail-large-mobile', 400, 200, true ); /* blog thumbnail for mobile */

    // This theme uses wp_nav_menu() in one location.

    register_nav_menus(array(

        'primary' => __('Primary Menu', 'zerif-lite'),

    ));

    // Enable support for Post Formats.

    add_theme_support('post-formats', array('aside', 'image', 'video', 'quote', 'link'));

    // Setup the WordPress core custom background feature.

    add_theme_support('custom-background', apply_filters('zerif_custom_background_args', array(

        'default-color' => 'ffffff',

        'default-image' => get_stylesheet_directory_uri() . "/images/bg.jpg",

    )));

    // Enable support for HTML5 markup.

    add_theme_support('html5', array(

        'comment-list',

        'search-form',

        'comment-form',

        'gallery',

    ));

		/**
		 * Custom template tags for this theme.

		 */

		require get_template_directory() . '/inc/template-tags.php';

		/**
		 * Custom functions that act independently of the theme templates.

		 */

		require get_template_directory() . '/inc/extras.php';

		/**
		 * Customizer additions.

		 */

		require get_template_directory() . '/inc/customizer.php';

		require get_template_directory() . '/inc/category-dropdown-custom-control.php';

		/* tgm-plugin-activation */
        require_once get_template_directory() . '/class-tgm-plugin-activation.php';

        add_image_size('zerif_project_photo', 285, 214, true);

        add_image_size('zerif_our_team_photo', 174, 174, true);

		/* woocommerce support */
		add_theme_support( 'woocommerce' );

}

add_action('after_setup_theme', 'zerif_setup');

/**
 * Register widgetized area and update sidebar with default widgets.

 */

function zerif_widgets_init()
{

    register_sidebar(array(

        'name' => __('Sidebar', 'zerif-lite'),

        'id' => 'sidebar-1',

        'before_widget' => '',

        'after_widget' => '',

        'before_title' => '
',

        'after_title' => '
',

    ));

    register_sidebar(array(

        'name' => __('Our focus section', 'zerif-lite'),

        'id' => 'sidebar-ourfocus',

        'before_widget' => '',

        'after_widget' => '',

        'before_title' => '
',

        'after_title' => '
',

    ));

    register_sidebar(array(

        'name' => __('Testimonials section', 'zerif-lite'),

        'id' => 'sidebar-testimonials',

        'before_widget' => '',

        'after_widget' => '',

        'before_title' => '
',

        'after_title' => '
',

    ));

    register_sidebar(array(

        'name' => __('About us section', 'zerif-lite'),

        'id' => 'sidebar-aboutus',

        'before_widget' => '',

        'after_widget' => '',

        'before_title' => '
',

        'after_title' => '
',

    ));

    register_sidebar(array(

        'name' => __('Our team section', 'zerif-lite'),

        'id' => 'sidebar-ourteam',

        'before_widget' => '',

        'after_widget' => '',

        'before_title' => '
',

        'after_title' => '
',

    ));

}

add_action('widgets_init', 'zerif_widgets_init');

function zerif_slug_fonts_url() {
    $fonts_url = '';

    /* Translators: If there are characters in your language that are not
    * supported by Lora, translate this to 'off'. Do not translate
    * into your own language.
    */
    $lato = _x( 'on', 'Lato font: on or off', 'zerif-lite' );
    $homemade = _x( 'on', 'Homemade font: on or off', 'zerif-lite' );
    /* Translators: If there are characters in your language that are not
    * supported by Open Sans, translate this to 'off'. Do not translate
    * into your own language.
    */
    $monserrat = _x( 'on', 'Monserrat font: on or off', 'zerif-lite' );

    if ( 'off' !== $lato || 'off' !== $monserrat|| 'off' !== $homemade ) {
        $font_families = array();

        if ( 'off' !== $lato ) {
            $font_families[] = 'Lato:300,400,700,400italic';
        }

        if ( 'off' !== $monserrat ) {
            $font_families[] = 'Montserrat:700';
        }

        if ( 'off' !== $homemade ) {
            $font_families[] = 'Homemade Apple';
        }

        $query_args = array(
            'family' => urlencode( implode( '|', $font_families ) ),
            'subset' => urlencode( 'latin,latin-ext' ),
        );

        $fonts_url = add_query_arg( $query_args, '//fonts.googleapis.com/css' );
    }

    return $fonts_url;
}

/**
 * Enqueue scripts and styles.

 */

function zerif_scripts()
{

    wp_enqueue_style('zerif_font', zerif_slug_fonts_url(), array(), null );

    wp_enqueue_style( 'zerif_font_all', '//fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600italic,600,700,700italic,800,800italic');

    wp_enqueue_style('zerif_bootstrap_style', get_template_directory_uri() . '/css/bootstrap.css');
    wp_style_add_data( 'zerif_bootstrap_style', 'rtl', 'replace' );

    wp_enqueue_style('zerif_fontawesome', get_template_directory_uri() . '/css/font-awesome.min.css', array(), 'v1');

    wp_enqueue_style('zerif_pixeden_style', get_template_directory_uri() . '/css/pixeden-icons.css', array('zerif_fontawesome'), 'v1');

    wp_enqueue_style('zerif_style', get_stylesheet_uri(), array('zerif_pixeden_style'), 'v1');

    wp_enqueue_style('zerif_responsive_style', get_template_directory_uri() . '/css/responsive.css', array('zerif_style'), 'v1');

    if ( wp_is_mobile() ){

        wp_enqueue_style( 'zerif_style_mobile', get_template_directory_uri() . '/css/style-mobile.css', array('zerif_bootstrap_style', 'zerif_style'),'v1' );

    }

    wp_enqueue_script('jquery');

    /* Bootstrap script */
    wp_enqueue_script('zerif_bootstrap_script', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '20120206', true);

    /* Knob script */
    wp_enqueue_script('zerif_knob_nav', get_template_directory_uri() . '/js/jquery.knob.js', array("jquery"), '20120206', true);

    /* Smootscroll script */

    $zerif_disable_smooth_scroll = get_theme_mod('zerif_disable_smooth_scroll');
    if( isset($zerif_disable_smooth_scroll) && ($zerif_disable_smooth_scroll != 1)):
        wp_enqueue_script('zerif_smoothscroll', get_template_directory_uri() . '/js/smoothscroll.js', array("jquery"), '20120206', true);
    endif;

	/* scrollReveal script */
	if ( !wp_is_mobile() ){
		wp_enqueue_script( 'zerif_scrollReveal_script', get_template_directory_uri() . '/js/scrollReveal.js', array("jquery"), '20120206', true  );
	}

    /* zerif script */

    wp_enqueue_script('zerif_script', get_template_directory_uri() . '/js/zerif.js', array("jquery", "zerif_knob_nav"), '20120206', true);

    if (is_singular() && comments_open() && get_option('thread_comments')) {

        wp_enqueue_script('comment-reply');

    }

	add_editor_style('/css/custom-editor-style.css');
}

add_action('wp_enqueue_scripts', 'zerif_scripts');

add_action('tgmpa_register', 'zerif_register_required_plugins');

function zerif_register_required_plugins()
{

	$wp_version_nr = get_bloginfo('version');

	if( $wp_version_nr < 3.9 ):

		$plugins = array(

			array(

				'name' => 'Widget customizer',

				'slug' => 'widget-customizer',

				'required' => false

			),

			array(

				'name'      => 'Login customizer',

				'slug'      => 'login-customizer',

				'required'  => false,

			),

			array(

				'name'      => 'Revive Old Post (Former Tweet Old Post)',

				'slug'      => 'tweet-old-post',

				'required'  => false,

			)

		);

	else:

		$plugins = array(

			array(

				'name'      => 'Login customizer',

				'slug'      => 'login-customizer',

				'required'  => false,

			),

			array(

				'name'      => 'Revive Old Post (Former Tweet Old Post)',

				'slug'      => 'tweet-old-post',

				'required'  => false,

			)

		);

	endif;

    $config = array(

        'default_path' => '',

        'menu' => 'tgmpa-install-plugins',

        'has_notices' => true,

        'dismissable' => true,

        'dismiss_msg' => '',

        'is_automatic' => false,

        'message' => '',

        'strings' => array(

            'page_title' => __('Install Required Plugins', 'zerif-lite'),

            'menu_title' => __('Install Plugins', 'zerif-lite'),

            'installing' => __('Installing Plugin: %s', 'zerif-lite'),

            'oops' => __('Something went wrong with the plugin API.', 'zerif-lite'),

            'notice_can_install_required' => _n_noop('This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.','zerif-lite'),

            'notice_can_install_recommended' => _n_noop('This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.','zerif-lite'),

            'notice_cannot_install' => _n_noop('Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.','zerif-lite'),

            'notice_can_activate_required' => _n_noop('The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.','zerif-lite'),

            'notice_can_activate_recommended' => _n_noop('The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.','zerif-lite'),

            'notice_cannot_activate' => _n_noop('Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.','zerif-lite'),

            'notice_ask_to_update' => _n_noop('The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.','zerif-lite'),

            'notice_cannot_update' => _n_noop('Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.','zerif-lite'),

            'install_link' => _n_noop('Begin installing plugin', 'Begin installing plugins','zerif-lite'),

            'activate_link' => _n_noop('Begin activating plugin', 'Begin activating plugins','zerif-lite'),

            'return' => __('Return to Required Plugins Installer', 'zerif-lite'),

            'plugin_activated' => __('Plugin activated successfully.', 'zerif-lite'),

            'complete' => __('All plugins installed and activated successfully. %s', 'zerif-lite'),

            'nag_type' => 'updated'

        )

    );

    tgmpa($plugins, $config);

}

/**
 * Load Jetpack compatibility file.

 */

require get_template_directory() . '/inc/jetpack.php';

function zerif_wp_page_menu()
{

    echo '
';

    wp_list_pages(array('title_li' => '', 'depth' => 1));

    echo '
';

}

add_filter('the_title', 'cwp_default_title');

function cwp_default_title($title)
{

    if ($title == '')

        $title = __("Default title",'zerif-lite');

    return $title;

}

/*****************************************/

/******          WIDGETS     *************/

/*****************************************/

add_action('widgets_init', 'zerif_register_widgets');

function zerif_register_widgets()
{

    register_widget('zerif_ourfocus');

    register_widget('zerif_testimonial_widget');

    register_widget('zerif_clients_widget');

    register_widget('zerif_team_widget');

}

/**************************/

/****** our focus widget */

/************************/

add_action('customize_controls_print_scripts', 'zerif_ourfocus_widget_scripts');

function zerif_ourfocus_widget_scripts()
{

    wp_enqueue_media();

    wp_enqueue_script('zerif_our_focus_widget_script', get_template_directory_uri() . '/js/widget.js', false, '1.0', true);

}

class zerif_ourfocus extends WP_Widget
{

    function zerif_ourfocus()
    {

        $widget_ops = array('classname' => 'ctUp-ads');

        $this->WP_Widget('ctUp-ads-widget', 'Zerif - Our focus widget', $widget_ops);

    }

    function widget($args, $instance)
    {

        extract($args);

        echo $before_widget;

        ?>

			<?php if( !empty($instance['image_uri']) ): ?>

				<?php if( !empty($instance['link']) ): ?>

					<a href="<?php echo $instance['link']; ?>"><i class="pixeden" style="background:url(<?php echo esc_url($instance['image_uri']); ?>) no-repeat center;width:100%; height:100%;">

				<?php else: ?>

					<i class="pixeden" style="background:url(<?php echo esc_url($instance['image_uri']); ?>) no-repeat center;width:100%; height:100%;">

				<?php endif; ?>

			<?php endif; ?>

<?php if( !empty($instance['title']) ): echo apply_filters('widget_title', $instance['title']); endif; ?>

			<?php
				if( !empty($instance['text']) ):

					echo '
';
						echo htmlspecialchars_decode(apply_filters('widget_title', $instance['text']));
					echo '
';
				endif;
			?>

        <?php

        echo $after_widget;

    }

    function update($new_instance, $old_instance)
    {

        $instance = $old_instance;

        $instance['text'] = wp_filter_post_kses($new_instance['text']);

        $instance['title'] = strip_tags($new_instance['title']);

		$instance['link'] = strip_tags( $new_instance['link'] );

        $instance['image_uri'] = strip_tags($new_instance['image_uri']);

        return $instance;

    }

    function form($instance)
    {

        ?>

            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('title'); ?>"
                   id="<?php echo $this->get_field_id('title'); ?>" value="<?php if( !empty($instance['title']) ): echo $instance['title']; endif; ?>"
                   class="widefat"/>

            <label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Text', 'zerif-lite'); ?>

            <textarea class="widefat" rows="8" cols="20" name="<?php echo $this->get_field_name('text'); ?>"
                      id="<?php echo $this->get_field_id('text'); ?>"><?php
                        if( !empty($instance['text']) ): echo htmlspecialchars_decode($instance['text']); endif;
            ?></textarea>

			<label for="<?php echo $this->get_field_id('link'); ?>"><?php _e('Link','zerif'); ?>

			<input type="text" name="<?php echo $this->get_field_name('link'); ?>" id="<?php echo $this->get_field_id('link'); ?>" value="<?php if( !empty($instance['link']) ): echo $instance['link']; endif; ?>" class="widefat" />

            <label for="<?php echo $this->get_field_id('image_uri'); ?>"><?php _e('Image', 'zerif-lite'); ?>

            <?php

            if ( !empty($instance['image_uri']) ) :

                echo '
';

            endif;

            ?>

            <input type="text" class="widefat custom_media_url" name="<?php echo $this->get_field_name('image_uri'); ?>"
                   id="<?php echo $this->get_field_id('image_uri'); ?>" value="<?php if( !empty($instance['image_uri']) ): echo $instance['image_uri']; endif; ?>"
                   style="margin-top:5px;">

            <input type="button" class="button button-primary custom_media_button" id="custom_media_button"
                   name="<?php echo $this->get_field_name('image_uri'); ?>" value="<?php _e('Upload Image','zerif-lite'); ?>"
                   style="margin-top:5px;"/>

    <?php

    }

}

/****************************/

/****** testimonial widget **/

/***************************/

add_action('customize_controls_print_scripts', 'zerif_testimonial_widget_scripts');

function zerif_testimonial_widget_scripts()
{

    wp_enqueue_media();

    wp_enqueue_script('zerif_testimonial_widget_script', get_template_directory_uri() . '/js/widget-testimonials.js', false, '1.0', true);

}

class zerif_testimonial_widget extends WP_Widget
{

    function zerif_testimonial_widget()
    {

        $widget_ops = array('classname' => 'zerif_testim');

        $this->WP_Widget('zerif_testim-widget', 'Zerif - Testimonial widget', $widget_ops);

    }

    function widget($args, $instance)
    {

        extract($args);

        echo $before_widget;

        ?>

			<?php if( !empty($instance['text']) ): ?>

					<?php echo htmlspecialchars_decode(apply_filters('widget_title', $instance['text'])); ?>

			<?php endif; ?>

					<a class="client-name" target="_blank" <?php if( !empty($instance['link']) ): echo 'href="'.esc_url($instance['link']).'"'; endif; ?>><?php if( !empty($instance['title']) ): echo apply_filters('widget_title', $instance['title'] ); endif; ?>

					<?php if( !empty($instance['details']) ): ?>

                        <?php echo apply_filters('widget_title', $instance['details']); ?>

					<?php endif; ?>

                <?php

				if( !empty($instance['image_uri']) ):

					echo '
';

					echo '';

					echo '
';
				endif;

                ?>

        <?php

        echo $after_widget;

    }

    function update($new_instance, $old_instance)
    {

        $instance = $old_instance;

        $instance['text'] = $new_instance['text'];

        $instance['title'] = strip_tags($new_instance['title']);

        $instance['details'] = strip_tags($new_instance['details']);

        $instance['image_uri'] = strip_tags($new_instance['image_uri']);

		$instance['link'] = strip_tags( $new_instance['link'] );

        return $instance;

    }

    function form($instance)
    {

        ?>

            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Author', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('title'); ?>"
                   id="<?php echo $this->get_field_id('title'); ?>" value="<?php if( !empty($instance['title']) ): echo $instance['title']; endif; ?>"
                   class="widefat"/>

			<label for="<?php echo $this->get_field_id('link'); ?>"><?php _e('Author link','zerif'); ?>

			<input type="text" name="<?php echo $this->get_field_name('link'); ?>" id="<?php echo $this->get_field_id('link'); ?>" value="<?php if( !empty($instance['link']) ): echo $instance['link']; endif; ?>" class="widefat" />

            <label for="<?php echo $this->get_field_id('details'); ?>"><?php _e('Author details', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('details'); ?>"
                   id="<?php echo $this->get_field_id('details'); ?>" value="<?php if( !empty($instance['details']) ): echo $instance['details']; endif; ?>"
                   class="widefat"/>

            <label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Text', 'zerif-lite'); ?>

            <textarea class="widefat" rows="8" cols="20" name="<?php echo $this->get_field_name('text'); ?>"
                      id="<?php echo $this->get_field_id('text'); ?>"><?php
                if( !empty($instance['text']) ): echo htmlspecialchars_decode($instance['text']); endif;
            ?></textarea>

            <label for="<?php echo $this->get_field_id('image_uri'); ?>"><?php _e('Image', 'zerif-lite'); ?>

            <?php

            if ( !empty($instance['image_uri']) ) :

                echo '
';

            endif;

            ?>

            <input type="text" class="widefat custom_media_url_testimonial"
                   name="<?php echo $this->get_field_name('image_uri'); ?>"
                   id="<?php echo $this->get_field_id('image_uri'); ?>" value="<?php if( !empty($instance['image_uri']) ): echo $instance['image_uri']; endif; ?>"
                   style="margin-top:5px;">

            <input type="button" class="button button-primary custom_media_button_testimonial"
                   id="custom_media_button_testimonial" name="<?php echo $this->get_field_name('image_uri'); ?>"
                   value="<?php _e('Upload Image','zerif-lite'); ?>" style="margin-top:5px;"/>

    <?php

    }

}

/****************************/

/****** clients widget **/

/***************************/

add_action('customize_controls_print_scripts', 'zerif_clients_widget_scripts');

function zerif_clients_widget_scripts()
{

    wp_enqueue_media();

    wp_enqueue_script('zerif_clients_widget_script', get_template_directory_uri() . '/js/widget-clients.js', false, '1.0', true);

}

class zerif_clients_widget extends WP_Widget
{

    function zerif_clients_widget()
    {

        $widget_ops = array('classname' => 'zerif_clients');

        $this->WP_Widget('zerif_clients-widget', 'Zerif - Clients widget', $widget_ops);

    }

    function widget($args, $instance)
    {

        extract($args);

        echo $before_widget;

        ?>

        <a href="<?php if( !empty($instance['link']) ): echo apply_filters('widget_title', $instance['link']); endif; ?>"><img
                src="<?php if( !empty($instance['image_uri']) ): echo esc_url($instance['image_uri']); endif; ?>" alt="Client">

        <?php

        echo $after_widget;

    }

    function update($new_instance, $old_instance)
    {

        $instance = $old_instance;

        $instance['link'] = strip_tags($new_instance['link']);

        $instance['image_uri'] = strip_tags($new_instance['image_uri']);

        return $instance;

    }

    function form($instance)
    {

        ?>

            <label for="<?php echo $this->get_field_id('link'); ?>"><?php _e('Link', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('link'); ?>"
                   id="<?php echo $this->get_field_id('link'); ?>" value="<?php if( !empty($instance['link']) ): echo $instance['link']; endif; ?>"
                   class="widefat"/>

            <label for="<?php echo $this->get_field_id('image_uri'); ?>"><?php _e('Image', 'zerif-lite'); ?>

            <?php

            if ( !empty($instance['image_uri']) ) :

                echo '
';

            endif;

            ?>

            <input type="text" class="widefat custom_media_url_clients"
                   name="<?php echo $this->get_field_name('image_uri'); ?>"
                   id="<?php echo $this->get_field_id('image_uri'); ?>" value="<?php if( !empty($instance['image_uri']) ): echo $instance['image_uri']; endif; ?>"
                   style="margin-top:5px;">

            <input type="button" class="button button-primary custom_media_button_clients"
                   id="custom_media_button_clients" name="<?php echo $this->get_field_name('image_uri'); ?>"
                   value="<?php _e('Upload Image','zerif-lite'); ?>" style="margin-top:5px;"/>

    <?php

    }

}

/****************************/

/****** team member widget **/

/***************************/

add_action('customize_controls_print_scripts', 'zerif_team_widget_scripts');

function zerif_team_widget_scripts()
{

    wp_enqueue_media();

    wp_enqueue_script('zerif_team_widget_script', get_template_directory_uri() . '/js/widget-team.js', false, '1.0', true);

}

class zerif_team_widget extends WP_Widget
{

    function zerif_team_widget()
    {

        $widget_ops = array('classname' => 'zerif_team');

        $this->WP_Widget('zerif_team-widget', 'Zerif - Team member widget', $widget_ops);

    }

    function widget($args, $instance)
    {

        extract($args);

        echo $before_widget;

        ?>

				<?php if( !empty($instance['image_uri']) ): ?>

						<img src="<?php echo esc_url($instance['image_uri']); ?>" alt="">

				<?php endif; ?>

					<?php if( !empty($instance['name']) ): ?>

<?php echo apply_filters('widget_title', $instance['name']); ?>

					<?php endif; ?>

					<?php if( !empty($instance['position']) ): ?>

<?php echo apply_filters('widget_title', $instance['position']); ?>

					<?php endif; ?>

                        <?php if ( !empty($instance['fb_link']) ): ?>

<a href="<?php echo apply_filters('widget_title', $instance['fb_link']); ?>">

                        <?php endif; ?>

                        <?php if ( !empty($instance['tw_link']) ): ?>

<a href="<?php echo apply_filters('widget_title', $instance['tw_link']); ?>">

                        <?php endif; ?>

                        <?php if ( !empty($instance['bh_link']) ): ?>

<a href="<?php echo apply_filters('widget_title', $instance['bh_link']); ?>">

                        <?php endif; ?>

                        <?php if ( !empty($instance['db_link']) ): ?>

<a href="<?php echo apply_filters('widget_title', $instance['db_link']); ?>">

                        <?php endif; ?>

						<?php if ( !empty($instance['ln_link']) ): ?>

<a href="<?php echo apply_filters('widget_title', $instance['ln_link']); ?>">

                        <?php endif; ?>

				<?php if( !empty($instance['description']) ): ?>

                    <?php echo htmlspecialchars_decode(apply_filters('widget_title', $instance['description'])); ?>

				<?php endif; ?>

        <?php

        echo $after_widget;

    }

    function update($new_instance, $old_instance)
    {

        $instance = $old_instance;

        $instance['name'] = strip_tags($new_instance['name']);

        $instance['position'] = wp_filter_post_kses($new_instance['position']);

        $instance['description'] = wp_filter_post_kses($new_instance['description']);

        $instance['fb_link'] = strip_tags($new_instance['fb_link']);

        $instance['tw_link'] = strip_tags($new_instance['tw_link']);

        $instance['bh_link'] = strip_tags($new_instance['bh_link']);

        $instance['db_link'] = strip_tags($new_instance['db_link']);

		$instance['ln_link'] = strip_tags($new_instance['ln_link']);

        $instance['image_uri'] = strip_tags($new_instance['image_uri']);

        return $instance;

    }

    function form($instance)
    {

        ?>

            <label for="<?php echo $this->get_field_id('name'); ?>"><?php _e('Name', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('name'); ?>"
                   id="<?php echo $this->get_field_id('name'); ?>" value="<?php if( !empty($instance['name']) ): echo $instance['name']; endif; ?>"
                   class="widefat"/>

            <label for="<?php echo $this->get_field_id('position'); ?>"><?php _e('Position', 'zerif-lite'); ?>

            <textarea class="widefat" rows="8" cols="20" name="<?php echo $this->get_field_name('position'); ?>"
                      id="<?php echo $this->get_field_id('position'); ?>"><?php
                if( !empty($instance['position']) ): echo htmlspecialchars_decode($instance['position']); endif;
            ?></textarea>

            <label
                for="<?php echo $this->get_field_id('description'); ?>"><?php _e('Description', 'zerif-lite'); ?>

            <textarea class="widefat" rows="8" cols="20" name="<?php echo $this->get_field_name('description'); ?>"
                      id="<?php echo $this->get_field_id('description'); ?>"><?php
                if( !empty($instance['description']) ): echo htmlspecialchars_decode($instance['description']); endif;
            ?></textarea>

            <label
                for="<?php echo $this->get_field_id('fb_link'); ?>"><?php _e('Facebook link', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('fb_link'); ?>"
                   id="<?php echo $this->get_field_id('fb_link'); ?>" value="<?php if( !empty($instance['fb_link']) ): echo $instance['fb_link']; endif; ?>"
                   class="widefat"/>

            <label
                for="<?php echo $this->get_field_id('tw_link'); ?>"><?php _e('Twitter link', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('tw_link'); ?>"
                   id="<?php echo $this->get_field_id('tw_link'); ?>" value="<?php if( !empty($instance['tw_link']) ): echo $instance['tw_link']; endif; ?>"
                   class="widefat"/>

            <label
                for="<?php echo $this->get_field_id('bh_link'); ?>"><?php _e('Behance link', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('bh_link'); ?>"
                   id="<?php echo $this->get_field_id('bh_link'); ?>" value="<?php if( !empty($instance['bh_link']) ): echo $instance['bh_link']; endif; ?>"
                   class="widefat"/>

            <label
                for="<?php echo $this->get_field_id('db_link'); ?>"><?php _e('Dribble link', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('db_link'); ?>"
                   id="<?php echo $this->get_field_id('db_link'); ?>" value="<?php if( !empty($instance['db_link']) ): echo $instance['db_link']; endif; ?>"
                   class="widefat"/>

            <label
                for="<?php echo $this->get_field_id('ln_link'); ?>"><?php _e('Linkedin link', 'zerif-lite'); ?>

            <input type="text" name="<?php echo $this->get_field_name('ln_link'); ?>"
                   id="<?php echo $this->get_field_id('ln_link'); ?>" value="<?php if( !empty($instance['ln_link']) ): echo $instance['ln_link']; endif; ?>"
                   class="widefat"/>

            <label for="<?php echo $this->get_field_id('image_uri'); ?>"><?php _e('Image', 'zerif-lite'); ?>

            <?php

            if ( !empty($instance['image_uri']) ) :

                echo '
';

            endif;

            ?>

            <input type="text" class="widefat custom_media_url_team"
                   name="<?php echo $this->get_field_name('image_uri'); ?>"
                   id="<?php echo $this->get_field_id('image_uri'); ?>" value="<?php if( !empty($instance['image_uri']) ): echo $instance['image_uri']; endif; ?>"
                   style="margin-top:5px;">

            <input type="button" class="button button-primary custom_media_button_team" id="custom_media_button_clients"
                   name="<?php echo $this->get_field_name('image_uri'); ?>" value="<?php _e('Upload Image','zerif-lite'); ?>"
                   style="margin-top:5px;"/>

    <?php

    }

}

function zerif_customizer_custom_css()
{

    wp_register_style('zerif_customizer_custom_css', get_template_directory_uri() . '/css/zerif_customizer_custom_css.css');

    wp_enqueue_style('zerif_customizer_custom_css');
}

add_action('customize_controls_print_styles', 'zerif_customizer_custom_css');

function zerif_excerpt_more( $more ) {
	return '[...]';
}
add_filter('excerpt_more', 'zerif_excerpt_more');

/**************************/
/**** More themes *********/
/**************************/

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// Add stylesheet and JS for upsell page.
function zerif_upsell_style() {
	wp_enqueue_style( 'upsell-style', get_template_directory_uri() . '/css/upsell.css');
}

// Add upsell page to the menu.
function zerif_lite_add_upsell() {
	$page = add_theme_page(
		__( 'More Themes', 'zerif-lite' ),
		__( 'More Themes', 'zerif-lite' ),
		'administrator',
		'zerif-lite-themes',
		'zerif_lite_display_upsell'
	);

	add_action( 'admin_print_styles-' . $page, 'zerif_upsell_style' );
}
add_action( 'admin_menu', 'zerif_lite_add_upsell', 11 );

// Define markup for the upsell page.
function zerif_lite_display_upsell() {

	// Set template directory uri
	$directory_uri = get_template_directory_uri();
	?>

								<img src="<?php echo get_template_directory_uri(); ?>/images/logo-themeisle.png"/>

<?php _e( 'Simple and effective products, no complex frameworks, no drag & drop builders.', 'zerif-lite' ); ?>

					<?php
					// Set the argument array with author name.
					$args = array(
						'author' => 'codeinwp',
					);

					// Set the $request array.
					$request = array(
						'body' => array(
							'action'  => 'query_themes',
							'request' => serialize( (object)$args )
						)
					);
					$themes = zerif_get_themes( $request );
					$active_theme = wp_get_theme()->get( 'Name' );
					$counter = 1;

					// For currently active theme.
					foreach ( $themes->themes as $theme ) {
						if( $active_theme == $theme->name ) {?>

							<div id="<?php echo $theme->slug; ?>" class="theme-container col-md-6 col-lg-4">

									<img class="theme-screenshot" src="<?php echo $theme->screenshot_url ?>"/>

<?php echo $theme->description; ?>

									<?php echo $theme->name . ':' . __( 'Current theme', 'zerif-lite' ); ?>
									<a class="button button-secondary customize right" target="_blank" href="<?php echo get_site_url(). '/wp-admin/customize.php' ?>">Customize

						<?php
						$counter++;
						break;
						}
					}

					// For all other themes.
					foreach ( $themes->themes as $theme ) {
						if( $active_theme != $theme->name ) {

							// Set the argument array with author name.
							$args = array(
								'slug' => $theme->slug,
							);

							// Set the $request array.
							$request = array(
								'body' => array(
									'action'  => 'theme_information',
									'request' => serialize( (object)$args )
								)
							);

							$theme_details = zerif_get_themes( $request );
							?>

							<div id="<?php echo $theme->slug; ?>" class="theme-container col-md-6 col-lg-4 <?php echo $counter % 3 == 1 ? 'no-left-megin' : ""; ?>">

									<img class="theme-screenshot" src="<?php echo $theme->screenshot_url ?>"/>

<?php echo $theme->description; ?>

									<?php echo $theme->name; ?>

									<?php if( wp_get_theme( $theme->slug )->exists() ) { ?>

										<img data-toggle="tooltip" title="<?php _e( 'Already installed', 'zerif-lite' ); ?>" data-placement="bottom" class="theme-exists" src="<?php echo $directory_uri ?>/core/images/tick.png"/>

										<a  class="button button-primary activate right"
											href="<?php echo wp_nonce_url( admin_url( 'themes.php?action=activate&stylesheet=' . urlencode( $theme->slug ) ), 'switch-theme_' . $theme->slug );?>" >Activate
									<?php }
									else {

										// Set the install url for the theme.
										$install_url = add_query_arg( array(
												'action' => 'install-theme',
												'theme'  => $theme->slug,
											), self_admin_url( 'update.php' ) );
									?>

										<a data-toggle="tooltip" data-placement="bottom" title="<?php echo 'Downloaded ' . number_format( $theme_details->downloaded ) . ' times'; ?>" class="button button-primary install right" href="<?php echo esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ); ?>" ><?php _e( 'Install Now', 'zerif-lite' ); ?>
									<?php } ?>

									<a class="button button-secondary preview right" target="_blank" href="<?php echo $theme->preview_url; ?>"><?php _e( 'Live Preview', 'zerif-lite' ); ?>

							<?php
							$counter++;
						}
					}?>

<?php
}

// Get all themeisle themes by using API.
function zerif_get_themes( $request ) {

	// Generate a cache key that would hold the response for this request:
	$key = 'zerif-lite_' . md5( serialize( $request ) );

	// Check transient. If it's there - use that, if not re fetch the theme
	if ( false === ( $themes = get_transient( $key ) ) ) {

		// Transient expired/does not exist. Send request to the API.
		$response = wp_remote_post( 'http://api.wordpress.org/themes/info/1.0/', $request );

		// Check for the error.
		if ( !is_wp_error( $response ) ) {

			$themes = unserialize( wp_remote_retrieve_body( $response ) );

			if ( !is_object( $themes ) && !is_array( $themes ) ) {

				// Response body does not contain an object/array
				return new WP_Error( 'theme_api_error', 'An unexpected error has occurred' );
			}

			// Set transient for next time... keep it for 24 hours should be good
			set_transient( $key, $themes, 60 * 60 * 24 );
		}
		else {
			// Error object returned
			return $response;
		}
	}

	return $themes;
}

/* Enqueue Google reCAPTCHA scripts */
add_action( 'wp_enqueue_scripts', 'recaptcha_scripts' );

function recaptcha_scripts() {

    if ( is_home() ):
        $zerif_contactus_sitekey = get_theme_mod('zerif_contactus_sitekey');
        $zerif_contactus_secretkey = get_theme_mod('zerif_contactus_secretkey');
        $zerif_contactus_recaptcha_show = get_theme_mod('zerif_contactus_recaptcha_show');
        if( isset($zerif_contactus_recaptcha_show) && $zerif_contactus_recaptcha_show != 1 && !empty($zerif_contactus_sitekey) && !empty($zerif_contactus_secretkey) ) :
            wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js' );
        endif;
    endif;

}

/* remove custom-background from body_class() */
add_filter( 'body_class', 'remove_class_function' );
function remove_class_function( $classes ) {

    if ( !is_home() ) {
        // index of custom-background
        $key = array_search('custom-background', $classes);
        // remove class
        unset($classes[$key]);
    }
    return $classes;

}


text:
using System;
using System.Linq;
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
using RohlikAPI.Model.JsonDeserialization;

namespace RohlikAPITests
{
    [TestClass]
    public class AuthenticatedRohlikApiTests
    {
        [TestMethod]
        public void RohlikApiLogin_FailsToLoginWithWrongPassword()
        {
            try
            {
                var authenticatedApiClient = new AuthenticatedRohlikApi("testemail@testemail.com", "TestPassword");
                authenticatedApiClient.GetOrderHistory();
            }
            catch (WebException ex)
            {
                Assert.IsTrue(ex.Message.Contains("Failed to login"),
                    $"Unexpected exception message: {ex.Message}");
                return;
            }

            Assert.Fail("Login with fake credentials did not throw an exception");
        }

        private string[] GetCredentials()
        {
            var credentialsString = Environment.GetEnvironmentVariable("TEST_CREDENTIALS");

            if (credentialsString == null)
            {
                throw new ArgumentException(
                    "Test needs credentials. Set environment variable 'TEST_CREDENTIALS=username@email.com:yourPassword'");
            }

            return credentialsString.Split(':');
        }

        private void CheckOrderHistoryItem(Order order)
        {
            Assert.IsTrue(order.Id > 0);
            Assert.IsNotNull(order.Date);
        }

        [TestMethod, TestCategory("Authenticated")]
        public void OrderHistory_RetrievesAllHistory()
        {
            var login = GetCredentials();
            var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
            var result = rohlikApi.GetOrderHistory().ToList();
            Assert.IsTrue(result.Any(), "Failed to get any orders");

            result.ForEach(CheckOrderHistoryItem);
        }

        [TestMethod, TestCategory("Authenticated")]
        public void RunRohlikovac()
        {
            var login = GetCredentials();
            var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
            var result = rohlikApi.RunRohlikovac();

            Assert.IsTrue(result.Status == 200);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.siyeh.ig.controlflow;

import com.intellij.codeInspection.InspectionProfileEntry;
import com.siyeh.ig.LightJavaInspectionTestCase;
import org.jetbrains.annotations.Nullable;

/**
 * @author Danila Ponomarenko
 */
public class PointlessBooleanExpressionInspectionTest extends LightJavaInspectionTestCase {

  public void testPointlessBooleanExpression() {
    doTest();
  }

  @Nullable
  @Override
  protected InspectionProfileEntry getInspection() {
    final PointlessBooleanExpressionInspection inspection = new PointlessBooleanExpressionInspection();
    inspection.m_ignoreExpressionsContainingConstants = true;
    return inspection;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Overview (JGraphT : a free Java graph library)
</TITLE>

<META NAME="date" CONTENT="2013-12-17">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

    Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

JGraphT - Parent 0.9.0 API

Packages

org.jgrapht
The front-end API's interfaces and classes, including Graph,
DirectedGraph and UndirectedGraph.

org.jgrapht.alg
Algorithms provided with JGraphT.

org.jgrapht.alg.cycle
Algorithms for enumeration of simple cycles in graphs.

org.jgrapht.alg.interfaces

org.jgrapht.alg.util
Utilities used by JGraphT algorithms.

org.jgrapht.demo
Demo programs that help to get started with JGraphT.

org.jgrapht.event
Event classes and listener interfaces, used to provide a change
notification mechanism on graph modification events.

org.jgrapht.experimental
A package that contains experimental work or work-in-progress that
is not yet ready to be included in a release.

org.jgrapht.experimental.alg

org.jgrapht.experimental.alg.color

org.jgrapht.experimental.dag

org.jgrapht.experimental.equivalence
Classes which enable working with Equivalence Sets.

org.jgrapht.experimental.isomorphism
Algorithms which provide isomorphism check between two graphs.

org.jgrapht.experimental.permutation
Classes to provide all the possible permutations of arrays or sets.

org.jgrapht.ext

Extensions and integration means to other products.

org.jgrapht.generate
Generators for graphs of various topologies.

org.jgrapht.graph
Implementations of various graphs.

org.jgrapht.traverse
Graph traversal means.

org.jgrapht.util
Non-graph-specific data structures, algorithms, and utilities used by
JGraphT.

    Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2013. All rights reserved.


text:
Leaflet.snogylop
================

Leaflet.snogylop is a [Leaflet][] plugin that inverts polygons.

Why? you ask. Sometimes you want to highlight a region of a map by
de-emphasizing the rest of the map. Using this plugin you can set a relatively
high opacity in order to de-emphasize everything outside of a polygon or
multipolygon.

## Demos

An inverted [polygon][].

An inverted [multipolygon][].

Custom [worldLatLngs][], eg for polygons near the antimeridian.

## Usage

Include `leaflet.snogylop.js` on your page, set the options on your GeoJSON
layer as specified below.

Leaflet.snogylop is tested on Leaflet version 0.7 and 1.x with L.GeoJSON
layers. It may work with older Leaflets and should work with other layers. Pull
requests in this direction are welcome.

AMD compatible.

Available through [bower][]: `bower install --save leaflet.snogylop`

### Options

Define the following option in the vector options when creating a layer (eg,
an `L.GeoJSON`):

 - **invert**: (boolean) True to invert. False by default.
 - **worldLatLngs**: (coordinate array) Optional, the coordinates of the outer
   ring of the inverted polygon that will be created.

### Examples

Create a GeoJSON layer, set `invert` to `true`:

```javascript
L.geoJson(data, {
    invert: true
}).addTo(map);
```

The default worldLatLngs can be overriden by using the `worldLatLngs` option:

```javascript
L.geoJson(data, {
    invert: true,
    worldLatLngs: [
        L.latLng([90, 360]),
        L.latLng([90, -180]),
        L.latLng([-90, -180]),
        L.latLng([-90, 360])
    ]
}).addTo(map);
```

### FAQs

**Is there any way to avoid the delay in drawing the polygon when panning and zooming?**

Yes, with Leaflet 1.* you can use the `renderer` option as described in [this issue](https://github.com/ebrelsford/Leaflet.snogylop/issues/1#issuecomment-487265696) to add padding around the polygon. For example:

```javascript
L.geoJson(data, {
    invert: true,
    renderer: L.svg({ padding: 1 })
}).addTo(map);
```

## License

Leaflet.snogylop is free software, and may be redistributed under the MIT
License.

 [Leaflet]: https://github.com/Leaflet/Leaflet
 [polygon]: http://ebrelsford.github.io/Leaflet.snogylop/examples/polygon.html
 [multipolygon]: http://ebrelsford.github.io/Leaflet.snogylop/examples/multipolygon.html
 [worldLatLngs]: http://ebrelsford.github.io/Leaflet.snogylop/examples/custom_world.html
 [bower]: https://github.com/bower/bower


text:
Changes:
* Fixed a wallet.dat compatibility problem if you downgraded from 0.3.17 and then upgraded again
* IsStandard() check to only include known transaction types in blocks
* Jgarzik's optimisation to speed up the initial block download a little

The main addition in this release is the Accounts-Based JSON-RPC commands that Gavin's been working on (more details at http://www.digibyte.org/smf/index.php?topic=1886.0).
* getaccountaddress
* sendfrom
* move
* getbalance
* listtransactions


text:
qc::format_timestamp_rel_age
============================

part of [Docs](../index.md)

Usage
-----
`qc::format_timestamp_rel_age args`

Description
-----------
Return the approximate relative age of a timestamp

Examples
--------
```tcl

% qc::format_timestamp_rel_age "2009-10-12 12:12:12"
5 years
% qc::format_timestamp_rel_age -long "2009-10-12 12:12:12"
5 years ago
```

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"


text:
<?php

/**
 * @class MediaFiles
 * =================
 *
 * Provides static functions for deleting media files.
 *
 * Ryff API <http://www.github.com/RyffProject/ryff-api>
 * Released under the Apache License 2.0.
 */
class MediaFiles {
    /**
     * Deletes the avatar from the given user.
     *
     * @param int $user_id
     */
    public static function delete_user_image($user_id) {
        $media_dir = TEST_MODE ? TEST_MEDIA_ABSOLUTE_PATH : MEDIA_ABSOLUTE_PATH;
        $avatar_path = "$media_dir/avatars/$user_id.png";
        $avatar_small_path = "$media_dir/avatars/small/$user_id.jpg";
        if (file_exists($avatar_path)) {
            unlink($avatar_path);
        }
        if (file_exists($avatar_small_path)) {
            unlink($avatar_small_path);
        }
    }

    /**
     * Deletes all media files associated with the given post.
     *
     * @param int $post_id
     * @return boolean
     */
    public static function delete_from_post($post_id) {
        $media_dir = TEST_MODE ? TEST_MEDIA_ABSOLUTE_PATH : MEDIA_ABSOLUTE_PATH;
        $paths = array(
            "$media_dir/posts/$post_id.png",
            "$media_dir/posts/medium/$post_id.jpg",
            "$media_dir/posts/small/$post_id.jpg",
            "$media_dir/riffs/$post_id.mp3",
            "$media_dir/riffs/hq/$post_id.mp3",
            "$media_dir/riffs/raw/$post_id.mp3"
        );
        foreach ($paths as $path) {
            if (file_exists($path) && !unlink($path)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Deletes all media files associated with the given user.
     *
     * @global NestedPDO $dbh
     * @global User $CURRENT_USER
     * @param int $user_id [optional] Defaults to the current user.
     */
    public static function delete_from_user($user_id = null) {
        global $dbh, $CURRENT_USER;

        if ($user_id === null && $CURRENT_USER) {
            $user_id = $CURRENT_USER->id;
        }

        $post_ids_query = "
            SELECT `post_id` FROM `posts`
            WHERE `user_id` = :user_id";
        $post_ids_sth = $dbh->prepare($post_ids_query);
        $post_ids_sth->bindValue('user_id', $user_id);
        if ($post_ids_sth->execute()) {
            while ($row = $post_ids_sth->fetch(PDO::FETCH_ASSOC)) {
                MediaFiles::delete_from_post((int)$row['post_id']);
            }
        }

        MediaFiles::delete_user_image($user_id);
    }

    /**
     * Returns a GD image resource if the given file is a valid
     * GIF, JPEG, or PNG, or false on failure.
     *
     * @param string $path
     * @return resource|false
     */
    protected static function get_image_resource($path) {
        $info = @getimagesize($path);
        if (!$info || !$info[0] || !$info[1]) {
            return false;
        }

        switch ($info[2]) {
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($path);
                break;
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($path);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($path);
                break;
            default:
                return false;
        }

        return $image;
    }

    /**
     * Saves the image from $source_path to the file given by $dest_path, as
     * either a JPEG or PNG depending on $image_type. If $width and $height are
     * set, the source image is scaled and cropped to the given size. If saving
     * a JPEG, $quality can be from 0 to 100.
     *
     * @param string $source_path
     * @param string $dest_path
     * @param int $image_type Must be IMAGETYPE_JPEG or IMAGETYPE_PNG.
     * @param int $width [optional]
     * @param int $height [optional]
     * @param int $quality [optional] Defaults to 100.
     * @return boolean
     */
    public static function save_image($source_path, $dest_path, $image_type,
            $width = null, $height = null, $quality = 100) {
        if (!in_array($image_type, array(IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
            return false;
        }

        $source_image = static::get_image_resource($source_path);
        if (!$source_image) {
            return false;
        }

        if ((int)$width <= 0 || (int)$height <= 0) {
            $dest_image = $source_image;
        } else {
            $dest_image = imagecreatetruecolor($width, $height);
            if ($image_type === IMAGETYPE_JPEG) {
                $white = imagecolorallocate($dest_image, 255, 255, 255);
                imagefill($dest_image, 0, 0, $white);
            } else if ($image_type === IMAGETYPE_PNG) {
                imagealphablending($dest_image, false);
                imagesavealpha($dest_image, true);
            }
            $original_width = imagesx($source_image);
            $original_height = imagesy($source_image);
            $scale_factor = max((double)$width / $original_width, (double)$height / $original_height);
            imagecopyresampled($dest_image, $source_image,
                ($width - ($original_width * $scale_factor)) / 2,
                ($height - ($original_height * $scale_factor)) / 2,
                0, 0,
                $scale_factor * $original_width, $scale_factor * $original_height,
                $original_width, $original_height
            );
        }

        if ($image_type === IMAGETYPE_JPEG) {
            return imagejpeg($dest_image, $dest_path, $quality);
        } else if ($image_type === IMAGETYPE_PNG) {
            return imagepng($dest_image, $dest_path);
        }
    }

    /**
     * Saves an avatar image as a full size 800x800 .png and a 100x100 .jpg
     * thumbnail.
     *
     * @param string $avatar_source_path
     * @param int $user_id
     * @return boolean
     */
    public static function save_avatar($avatar_source_path, $user_id) {
        $media_dir = TEST_MODE ? TEST_MEDIA_ABSOLUTE_PATH : MEDIA_ABSOLUTE_PATH;
        $avatar_dest_path = "$media_dir/avatars/$user_id.png";
        $avatar_dest_small_path = "$media_dir/avatars/small/$user_id.jpg";

        if (!static::save_image($avatar_source_path, $avatar_dest_path,
                IMAGETYPE_PNG, 800, 800)) {
            return false;
        } else if (!static::save_image($avatar_source_path, $avatar_dest_small_path,
                IMAGETYPE_JPEG, 100, 100, 80)) {
            return false;
        }

        return true;
    }

    /**
     * Saves a post image as a full size 800x600 .png, a 400x400 .jpg medium
     * thumbnail, and a 100x100 .jpg small thumbnail.
     *
     * @param string $post_image_source_path
     * @param int $post_id
     * @return boolean
     */
    public static function save_post_image($post_image_source_path, $post_id) {
        $media_dir = TEST_MODE ? TEST_MEDIA_ABSOLUTE_PATH : MEDIA_ABSOLUTE_PATH;
        $post_image_dest_path = "$media_dir/posts/$post_id.png";
        $post_image_medium_dest_path = "$media_dir/posts/medium/$post_id.jpg";
        $post_image_small_dest_path = "$media_dir/posts/small/$post_id.jpg";

        if (!static::save_image($post_image_source_path, $post_image_dest_path,
                IMAGETYPE_PNG, 800, 600)) {
            return false;
        } else if (!static::save_image($post_image_source_path, $post_image_medium_dest_path,
                IMAGETYPE_JPEG, 400, 400, 80)) {
            return false;
        } else if (!static::save_image($post_image_source_path, $post_image_small_dest_path,
                IMAGETYPE_JPEG, 100, 100, 80)) {
            return false;
        }

        return true;
    }

    /**
     * Uses ffprobe or avconv (set in AUDIO_INFO_COMMAND) to get audio codec
     * information as JSON, which it then decodes. Returns information on
     * codec name, number of channels, duration, bitrate, etc. If the command
     * fails or the file is not a recognized audio file with a single stream,
     * this function returns null.
     *
     * @param string $audio_path
     * @return array|null
     */
    public static function get_audio_info($audio_path) {
        if (!(fileperms($audio_path) & 0x0004)) {
            if (!chmod($audio_path, 0644)) {
                return null;
            }
        }

        $command = sprintf(AUDIO_INFO_COMMAND, escapeshellarg($audio_path));
        exec($command, $output_array, $return_var);
        if ($return_var) {
            return null;
        }
        $output = json_decode(implode("", $output_array), true);
        if (!$output || !isset($output["streams"]) ||
                !is_array($output["streams"]) || count($output["streams"]) !== 1 ||
                !isset($output["streams"][0]["codec_type"]) ||
                $output["streams"][0]["codec_type"] !== "audio") {
            return null;
        }

        $interesting_data = array(
            "codec_name", "codec_long_name", "channels",
            "channel_layout", "duration", "bit_rate"
        );
        $info = array();
        foreach ($interesting_data as $key) {
            if (isset($output["streams"][0][$key])) {
                $info[$key] = $output["streams"][0][$key];
            } else {
                $info[$key] = "";
            }
        }
        return $info;
    }

    /**
     * Attempts to convert audio from $source_path and save it as an MP3
     * file for the given $post_id, using ffmpeg. Saves as either 256k if
     * $is_hq is true or $128k otherwise. Returns true if the conversion
     * succeeded or false on failure.
     *
     * @param string $source_path
     * @param int $post_id
     * @param boolean $hq
     * @return boolean
     */
    public static function save_audio($source_path, $post_id, $hq) {
        if (!file_exists($source_path)) {
            return false;
        }

        $media_dir = TEST_MODE ? TEST_MEDIA_ABSOLUTE_PATH : MEDIA_ABSOLUTE_PATH;
        if ($hq) {
            $riff_dest_path = "$media_dir/riffs/hq/$post_id.mp3";
        } else {
            $riff_dest_path = "$media_dir/riffs/$post_id.mp3";
        }
        $bitrate = $hq ? "256k" : "128k";

        $command = FFMPEG_COMMAND." -y -i ".escapeshellarg($source_path).
                " -c:a ".FFMPEG_CODEC." -b:a $bitrate ".escapeshellarg($riff_dest_path).
                " > /dev/null 2>&1";
        exec($command, $output, $return_var);
        if ($return_var) {
            if (file_exists($riff_dest_path)) {
                unlink($riff_dest_path);
            }
            return false;
        }

        return true;
    }

    /**
     * Gets the audio info from $source_path, then if it is in mp3 format and
     * in the right bitrate it will be copied to media/riffs/hq, otherwise
     * it will be copied to media/riffs/raw. Also sets the post as active if
     * the audio is available for listening.
     *
     * @global NestedPDO $dbh
     * @param string $source_path
     * @param int $post_id
     * @return boolean
     */
    public static function save_riff($source_path, $post_id) {
        global $dbh;

        $dbh->beginTransaction();

        $audio_info = static::get_audio_info($source_path);
        if (!$audio_info) {
            $dbh->rollBack();
            return false;
        } else if (!Post::set_duration($post_id, ceil((double)$audio_info['duration']))) {
            $dbh->rollBack();
            return false;
        } else if (!Post::set_filesize($post_id, filesize($source_path))) {
            $dbh->rollBack();
            return false;
        }

        $copy_func = is_uploaded_file($source_path) ? "move_uploaded_file" : "copy";
        $media_dir = TEST_MODE ? TEST_MEDIA_ABSOLUTE_PATH : MEDIA_ABSOLUTE_PATH;
        $dest_hq_path = "$media_dir/riffs/hq/$post_id.mp3";
        $dest_raw_path = "$media_dir/riffs/raw/$post_id.mp3";
        if ($audio_info['codec_name'] === "mp3") {
            if ((int)$audio_info['bit_rate'] >= 192000 && (int)$audio_info['bit_rate'] <= 320000) {
                if (!$copy_func($source_path, $dest_hq_path) || !Post::set_active($post_id, true) ||
                        !Post::set_converted($post_id, true, true)) {
                    $dbh->rollBack();
                    return false;
                }
            } else if (!$copy_func($source_path, $dest_raw_path) || !Post::set_active($post_id, true)) {
                $dbh->rollBack();
                return false;
            }
        } else if (!$copy_func($source_path, $dest_raw_path)) {
            $dbh->rollBack();
            return false;
        }

        $dbh->commit();
        return true;
    }
}


text:
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
  inject,
  async,
  TestBed,
  ComponentFixture
} from '@angular/core/testing';

// Load the implementations that should be tested
import { App } from './app.component';
import { GlobalState } from './global.state';
import { BaImageLoaderService, BaThemeSpinner } from './theme/services';
import { BaThemeConfigProvider } from './theme/theme.configProvider';
import { BaThemeConfig } from './theme/theme.config';

describe(`App`, () => {
  let comp: App;
  let fixture: ComponentFixture<App>;

  // async beforeEach
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ App ],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [GlobalState, BaImageLoaderService, BaThemeSpinner, BaThemeConfigProvider, BaThemeConfig]
    })
    .compileComponents(); // compile template and css
  }));

  // synchronous beforeEach
  beforeEach(() => {
    fixture = TestBed.createComponent(App);
    comp    = fixture.componentInstance;

    fixture.detectChanges(); // trigger initial data binding
  });

  it(`should be readly initialized`, () => {
    expect(fixture).toBeDefined();
    expect(comp).toBeDefined();
  });
});


text:
export interface BaseService {
}


text:
// Type definitions for scratch-vm (extension environment) 3.0
// Project: https://github.com/LLK/scratch-vm#readme
// Definitions by: Richie Bendall <https://github.com/Richienb>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.9

type ValueOf<ObjectType> = ObjectType[keyof ObjectType];

/** All the metadata needed to register an extension. */
interface ExtensionMetadata {
    /** A unique alphanumeric identifier for this extension. No special characters allowed. */
    id: string;

    /** The human-readable name of this extension. */
    name?: string | undefined;

    /** URI for an image to be placed on each block in this extension. Data URI ok. */
    blockIconURI?: string | undefined;

    /** URI for an image to be placed on this extension's category menu item. Data URI ok. */
    menuIconURI?: string | undefined;

    /** Link to documentation content for this extension. */
    docsURI?: string | undefined;

    /** The blocks provided by this extension and the separators. */
    blocks: Array<ExtensionBlockMetadata | string>;

    /** Map of menu name to metadata for each of this extension's menus. */
    menus?: Record<string, ExtensionMenuMetadata> | undefined;
}

/** All the metadata needed to register an extension block. */
interface ExtensionBlockMetadata {
    /** A unique alphanumeric identifier for this block. No special characters allowed. */
    opcode: string;

    /** The name of the function implementing this block. Can be shared by other blocks/opcodes. */
    func?: string | undefined;

    /** The type of block (command, reporter, etc.) being described. */
    blockType: ValueOf<Scratch.BlockType>;

    /** The text on the block, with [PLACEHOLDERS] for arguments. */
    text: string;

    /** Whether this block should not appear in the block palette. */
    hideFromPalette?: boolean | undefined;

    /** Whether the block ends a stack - no blocks can be connected after it. */
    isTerminal?: boolean | undefined;

    /** Whether this block is a reporter but should not allow a monitor. */
    disableMonitor?: boolean | undefined;

    /** If this block is a reporter, this is the scope/context for its value. */
    reporterScope?: ReporterScope | undefined;

    /** Whether a hat block is edge-activated. */
    isEdgeActivated?: boolean | undefined;

    /** Whether a hat/event block should restart existing threads. */
    shouldRestartExistingThreads?: boolean | undefined;

    /** For flow control blocks, the number of branches/substacks for this block. */
    branchCount?: number | undefined;

    /** Map of argument placeholder to metadata about each arg. */
    arguments?: Record<string, ExtensionArgumentMetadata> | undefined;
}

/** All the metadata needed to register an argument for an extension block. */
interface ExtensionArgumentMetadata {
    /** The type of the argument (number, string, etc.) */
    type: ValueOf<Scratch.ArgumentType>;

    /** The default value of this argument. */
    defaultValue?: any;

    /** The name of the menu to use for this argument, if any. */
    menu?: string | undefined;
}

/** All the metadata needed to register an extension drop-down menu. */
type ExtensionMenuMetadata = ExtensionDynamicMenu | ExtensionMenuItems;

/** The string name of a function which returns menu items. */
type ExtensionDynamicMenu = string;

/** Items in an extension menu. */
type ExtensionMenuItems = Array<ExtensionMenuItemSimple | ExtensionMenuItemComplex>;

/** A menu item for which the label and value are identical strings. */
type ExtensionMenuItemSimple = string;

/** A menu item for which the label and value can differ. */
interface ExtensionMenuItemComplex {
    /** The value of the block argument when this menu item is selected. */
    value: any;

    /** The human-readable label of this menu item in the menu. */
    text: string;
}

declare class ScratchExtension {
    /** Returns data about the extension. */
    getInfo(): ExtensionMetadata;
}

/** Indicate the scope for a reporter's value. */
declare enum ReporterScope {
    /** This reporter's value is global and does not depend on context. */
    GLOBAL = "global",

    /**
     * This reporter's value is specific to a particular target/sprite.
     * Another target may have a different value or may not even have a value.
     */
    TARGET = "target"
}

declare namespace Scratch {
    namespace extensions {
        /** Register an extension. */
        function register(extension: ScratchExtension): void;
    }

    /** Block argument types. */
    enum ArgumentType {
        /** Numeric value with angle picker. */
        ANGLE = "angle",

        /** Boolean value with hexagonal placeholder. */
        BOOLEAN = "Boolean",

        /** Numeric value with color picker. */
        COLOR = "color",

        /** Numeric value with text field. */
        NUMBER = "number",

        /** String value with text field. */
        STRING = "string",

        /** String value with matrix field. */
        MATRIX = "matrix",

        /** MIDI note number with note picker (piano) field. */
        NOTE = "note",

        /** Inline image on block (as part of the label). */
        IMAGE = "image"
    }

    /** Types of blocks. */
    enum BlockType {
        /** Boolean reporter with hexagonal shape. */
        BOOLEAN = "Boolean",

        /** A button (not an actual block) for some special action, like making a variable. */
        BUTTON = "button",

        /** Command block. */
        COMMAND = "command",

        /**
         * Specialized command block which may or may not run a child branch.
         * The thread continues with the next block whether or not a child branch ran.
         */
        CONDITIONAL = "conditional",

        /**
         * Specialized hat block with no implementation function.
         * This stack only runs if the corresponding event is emitted by other code.
         */
        EVENT = "event",

        /** Hat block which conditionally starts a block stack. */
        HAT = "hat",

        /**
         * Specialized command block which may or may not run a child branch.
         * If a child branch runs, the thread evaluates the loop block again.
         */
        LOOP = "loop",

        /** General reporter with numeric or string value. */
        REPORTER = "reporter"
    }

    /** Default types of target supported by the VM. */
    enum TargetType {
        /** Rendered target which can move, change costumes, etc. */
        SPRITE = "sprite",

        /** Rendered target which cannot move but can change backdrops. */
        STAGE = "stage"
    }
}


text:
package com.intellij.ide;

import javax.annotation.Nonnull;

import java.util.Collection;

/**
 * @author Gregory.Shrago
 */
public interface CompositeSelectInTarget extends SelectInTarget{
  @Nonnull
  Collection<SelectInTarget> getSubTargets(SelectInContext context);
}


text: load File.expand_path('../tasks/delayed_job.rake', __FILE__)


text:
package net.schmizz.sshj.transport.mac;

import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;

import java.nio.charset.Charset;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

public class HMACSHA2512Test {
    private static final Charset CHARSET = Charset.forName("US-ASCII");
    private static final byte[] PLAIN_TEXT = "Hello World".getBytes(CHARSET);
    private static final String EXPECTED_HMAC = "28929cffc903039ef18cbc9cea6fd5f1420763af297a470d731236ed1f5a4c61d64dfccf6529265205bec932f2f7850c8ae4de1dc1a5259dc5b1fd85d8e62c04";

    @Test
    public void testUpdateWithDoFinal() {
        HMACSHA2512 hmac = initHmac();
        hmac.update(PLAIN_TEXT);
        assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
    }

    @Test
    public void testDoFinalWithInput() {
        HMACSHA2512 hmac = initHmac();
        assertThat(Hex.toHexString(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
    }

    @Test
    public void testUpdateWithDoFinalWithResultBuffer() {
        HMACSHA2512 hmac = initHmac();
        byte[] resultBuf = new byte[64];
        hmac.update(PLAIN_TEXT);
        hmac.doFinal(resultBuf, 0);
        assertThat(Hex.toHexString(resultBuf), is(EXPECTED_HMAC));
    }

    private HMACSHA2512 initHmac() {
        HMACSHA2512 hmac = new HMACSHA2512();
        hmac.init("paishiengu1jaeTie5OoTu2eib7Kohqueicie7ahLohfoothahpeivi5weik1EiB".getBytes(CHARSET));
        return hmac;
    }
}


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Portal.CMS.Entities.Entities
{
    public class MenuItemRole
    {
        [Key]
        public int MenuItemRoleId { get; set; }

        [ForeignKey("MenuItem")]
        public int MenuItemId { get; set; }

        public virtual MenuItem MenuItem { get; set; }

        [ForeignKey("Role")]
        public int RoleId { get; set; }

        public virtual Role Role { get; set; }
    }
}


text:
from struct import pack, unpack, calcsize

class Structure:
    """ sublcasses can define commonHdr and/or structure.
        each of them is an tuple of either two: (fieldName, format) or three: (fieldName, ':', class) fields.
        [it can't be a dictionary, because order is important]

        where format specifies how the data in the field will be converted to/from bytes (string)
        class is the class to use when unpacking ':' fields.

        each field can only contain one value (or an array of values for *)
           i.e. struct.pack('Hl',1,2) is valid, but format specifier 'Hl' is not (you must use 2 dfferent fields)

        format specifiers:
          specifiers from module pack can be used with the same format
          see struct.__doc__ (pack/unpack is finally called)
            x       [padding byte]
            c       [character]
            b       [signed byte]
            B       [unsigned byte]
            h       [signed short]
            H       [unsigned short]
            l       [signed long]
            L       [unsigned long]
            i       [signed integer]
            I       [unsigned integer]
            q       [signed long long (quad)]
            Q       [unsigned long long (quad)]
            s       [string (array of chars), must be preceded with length in format specifier, padded with zeros]
            p       [pascal string (includes byte count), must be preceded with length in format specifier, padded with zeros]
            f       [float]
            d       [double]
            =       [native byte ordering, size and alignment]
            @       [native byte ordering, standard size and alignment]
            !       [network byte ordering]
            <       [little endian]
            >       [big endian]

          usual printf like specifiers can be used (if started with %)
          [not recommeneded, there is no why to unpack this]

            %08x    will output an 8 bytes hex
            %s      will output a string
            %s\\x00  will output a NUL terminated string
            %d%d    will output 2 decimal digits (against the very same specification of Structure)
            ...

          some additional format specifiers:
            :       just copy the bytes from the field into the output string (input may be string, other structure, or anything responding to __str__()) (for unpacking, all what's left is returned)
            z       same as :, but adds a NUL byte at the end (asciiz) (for unpacking the first NUL byte is used as terminator)  [asciiz string]
            u       same as z, but adds two NUL bytes at the end (after padding to an even size with NULs). (same for unpacking) [unicode string]
            w       DCE-RPC/NDR string (it's a macro for [  '<L=(len(field)+1)/2','"\\x00\\x00\\x00\\x00','<L=(len(field)+1)/2',':' ]
            ?-field length of field named 'field', formated as specified with ? ('?' may be '!H' for example). The input value overrides the real length
            ?1*?2   array of elements. Each formated as '?2', the number of elements in the array is stored as specified by '?1' (?1 is optional, or can also be a constant (number), for unpacking)
            'xxxx   literal xxxx (field's value doesn't change the output. quotes must not be closed or escaped)
            "xxxx   literal xxxx (field's value doesn't change the output. quotes must not be closed or escaped)
            _       will not pack the field. Accepts a third argument, which is an unpack code. See _Test_UnpackCode for an example
            ?=packcode  will evaluate packcode in the context of the structure, and pack the result as specified by ?. Unpacking is made plain
            ?&fieldname "Address of field fieldname".
                        For packing it will simply pack the id() of fieldname. Or use 0 if fieldname doesn't exists.
                        For unpacking, it's used to know weather fieldname has to be unpacked or not, i.e. by adding a & field you turn another field (fieldname) in an optional field.

    """
    commonHdr = ()
    structure = ()
    debug = 0

    def __init__(self, data = None, alignment = 0):
        if not hasattr(self, 'alignment'):
            self.alignment = alignment

        self.fields    = {}
        self.rawData   = data
        if data is not None:
            self.fromString(data)
        else:
            self.data = None

    @classmethod
    def fromFile(self, file):
        answer = self()
        answer.fromString(file.read(len(answer)))
        return answer

    def setAlignment(self, alignment):
        self.alignment = alignment

    def setData(self, data):
        self.data = data

    def packField(self, fieldName, format = None):
        if self.debug:
            print "packField( %s | %s )" % (fieldName, format)

        if format is None:
            format = self.formatForField(fieldName)

        if self.fields.has_key(fieldName):
            ans = self.pack(format, self.fields[fieldName], field = fieldName)
        else:
            ans = self.pack(format, None, field = fieldName)

        if self.debug:
            print "\tanswer %r" % ans

        return ans

    def getData(self):
        if self.data is not None:
            return self.data
        data = ''
        for field in self.commonHdr+self.structure:
            try:
                data += self.packField(field[0], field[1])
            except Exception, e:
                if self.fields.has_key(field[0]):
                    e.args += ("When packing field '%s | %s | %r' in %s" % (field[0], field[1], self[field[0]], self.__class__),)
                else:
                    e.args += ("When packing field '%s | %s' in %s" % (field[0], field[1], self.__class__),)
                raise
            if self.alignment:
                if len(data) % self.alignment:
                    data += ('\x00'*self.alignment)[:-(len(data) % self.alignment)]

        #if len(data) % self.alignment: data += ('\x00'*self.alignment)[:-(len(data) % self.alignment)]
        return data

    def fromString(self, data):
        self.rawData = data
        for field in self.commonHdr+self.structure:
            if self.debug:
                print "fromString( %s | %s | %r )" % (field[0], field[1], data)
            size = self.calcUnpackSize(field[1], data, field[0])
            if self.debug:
                print "  size = %d" % size
            dataClassOrCode = str
            if len(field) > 2:
                dataClassOrCode = field[2]
            try:
                self[field[0]] = self.unpack(field[1], data[:size], dataClassOrCode = dataClassOrCode, field = field[0])
            except Exception,e:
                e.args += ("When unpacking field '%s | %s | %r[:%d]'" % (field[0], field[1], data, size),)
                raise

            size = self.calcPackSize(field[1], self[field[0]], field[0])
            if self.alignment and size % self.alignment:
                size += self.alignment - (size % self.alignment)
            data = data[size:]

        return self

    def __setitem__(self, key, value):
        self.fields[key] = value
        self.data = None        # force recompute

    def __getitem__(self, key):
        return self.fields[key]

    def __delitem__(self, key):
        del self.fields[key]

    def __str__(self):
        return self.getData()

    def __len__(self):
        # XXX: improve
        return len(self.getData())

    def pack(self, format, data, field = None):
        if self.debug:
            print "  pack( %s | %r | %s)" %  (format, data, field)

        if field:
            addressField = self.findAddressFieldFor(field)
            if (addressField is not None) and (data is None):
                return ''

        # void specifier
        if format[:1] == '_':
            return ''

        # quote specifier
        if format[:1] == "'" or format[:1] == '"':
            return format[1:]

        # code specifier
        two = format.split('=')
        if len(two) >= 2:
            try:
                return self.pack(two[0], data)
            except:
                fields = {'self':self}
                fields.update(self.fields)
                return self.pack(two[0], eval(two[1], {}, fields))

        # address specifier
        two = format.split('&')
        if len(two) == 2:
            try:
                return self.pack(two[0], data)
            except:
                if (self.fields.has_key(two[1])) and (self[two[1]] is not None):
                    return self.pack(two[0], id(self[two[1]]) & ((1<<(calcsize(two[0])*8))-1) )
                else:
                    return self.pack(two[0], 0)

        # length specifier
        two = format.split('-')
        if len(two) == 2:
            try:
                return self.pack(two[0],data)
            except:
                return self.pack(two[0], self.calcPackFieldSize(two[1]))

        # array specifier
        two = format.split('*')
        if len(two) == 2:
            answer = ''
            for each in data:
                answer += self.pack(two[1], each)
            if two[0]:
                if two[0].isdigit():
                    if int(two[0]) != len(data):
                        raise Exception, "Array field has a constant size, and it doesn't match the actual value"
                else:
                    return self.pack(two[0], len(data))+answer
            return answer

        # "printf" string specifier
        if format[:1] == '%':
            # format string like specifier
            return format % data

        # asciiz specifier
        if format[:1] == 'z':
            return str(data)+'\0'

        # unicode specifier
        if format[:1] == 'u':
            return str(data)+'\0\0' + (len(data) & 1 and '\0' or '')

        # DCE-RPC/NDR string specifier
        if format[:1] == 'w':
            if len(data) == 0:
                data = '\0\0'
            elif len(data) % 2:
                data += '\0'
            l = pack('<L', len(data)/2)
            return '%s\0\0\0\0%s%s' % (l,l,data)

        if data is None:
            raise Exception, "Trying to pack None"

        # literal specifier
        if format[:1] == ':':
            return str(data)

        # struct like specifier
        return pack(format, data)

    def unpack(self, format, data, dataClassOrCode = str, field = None):
        if self.debug:
            print "  unpack( %s | %r )" %  (format, data)

        if field:
            addressField = self.findAddressFieldFor(field)
            if addressField is not None:
                if not self[addressField]:
                    return

        # void specifier
        if format[:1] == '_':
            if dataClassOrCode != str:
                fields = {'self':self, 'inputDataLeft':data}
                fields.update(self.fields)
                return eval(dataClassOrCode, {}, fields)
            else:
                return None

        # quote specifier
        if format[:1] == "'" or format[:1] == '"':
            answer = format[1:]
            if answer != data:
                raise Exception, "Unpacked data doesn't match constant value '%r' should be '%r'" % (data, answer)
            return answer

        # address specifier
        two = format.split('&')
        if len(two) == 2:
            return self.unpack(two[0],data)

        # code specifier
        two = format.split('=')
        if len(two) >= 2:
            return self.unpack(two[0],data)

        # length specifier
        two = format.split('-')
        if len(two) == 2:
            return self.unpack(two[0],data)

        # array specifier
        two = format.split('*')
        if len(two) == 2:
            answer = []
            sofar = 0
            if two[0].isdigit():
                number = int(two[0])
            elif two[0]:
                sofar += self.calcUnpackSize(two[0], data)
                number = self.unpack(two[0], data[:sofar])
            else:
                number = -1

            while number and sofar < len(data):
                nsofar = sofar + self.calcUnpackSize(two[1],data[sofar:])
                answer.append(self.unpack(two[1], data[sofar:nsofar], dataClassOrCode))
                number -= 1
                sofar = nsofar
            return answer

        # "printf" string specifier
        if format[:1] == '%':
            # format string like specifier
            return format % data

        # asciiz specifier
        if format == 'z':
            if data[-1] != '\x00':
                raise Exception, ("%s 'z' field is not NUL terminated: %r" % (field, data))
            return data[:-1] # remove trailing NUL

        # unicode specifier
        if format == 'u':
            if data[-2:] != '\x00\x00':
                raise Exception, ("%s 'u' field is not NUL-NUL terminated: %r" % (field, data))
            return data[:-2] # remove trailing NUL

        # DCE-RPC/NDR string specifier
        if format == 'w':
            l = unpack('<L', data[:4])[0]
            return data[12:12+l*2]

        # literal specifier
        if format == ':':
            return dataClassOrCode(data)

        # struct like specifier
        return unpack(format, data)[0]

    def calcPackSize(self, format, data, field = None):
#        # print "  calcPackSize  %s:%r" %  (format, data)
        if field:
            addressField = self.findAddressFieldFor(field)
            if addressField is not None:
                if not self[addressField]:
                    return 0

        # void specifier
        if format[:1] == '_':
            return 0

        # quote specifier
        if format[:1] == "'" or format[:1] == '"':
            return len(format)-1

        # address specifier
        two = format.split('&')
        if len(two) == 2:
            return self.calcPackSize(two[0], data)

        # code specifier
        two = format.split('=')
        if len(two) >= 2:
            return self.calcPackSize(two[0], data)

        # length specifier
        two = format.split('-')
        if len(two) == 2:
            return self.calcPackSize(two[0], data)

        # array specifier
        two = format.split('*')
        if len(two) == 2:
            answer = 0
            if two[0].isdigit():
                    if int(two[0]) != len(data):
                        raise Exception, "Array field has a constant size, and it doesn't match the actual value"
            elif two[0]:
                answer += self.calcPackSize(two[0], len(data))

            for each in data:
                answer += self.calcPackSize(two[1], each)
            return answer

        # "printf" string specifier
        if format[:1] == '%':
            # format string like specifier
            return len(format % data)

        # asciiz specifier
        if format[:1] == 'z':
            return len(data)+1

        # asciiz specifier
        if format[:1] == 'u':
            l = len(data)
            return l + (l & 1 and 3 or 2)

        # DCE-RPC/NDR string specifier
        if format[:1] == 'w':
            l = len(data)
            return 12+l+l % 2

        # literal specifier
        if format[:1] == ':':
            return len(data)

        # struct like specifier
        return calcsize(format)

    def calcUnpackSize(self, format, data, field = None):
        if self.debug:
            print "  calcUnpackSize( %s | %s | %r)" %  (field, format, data)

        # void specifier
        if format[:1] == '_':
            return 0

        addressField = self.findAddressFieldFor(field)
        if addressField is not None:
            if not self[addressField]:
                return 0

        try:
            lengthField = self.findLengthFieldFor(field)
            return self[lengthField]
        except:
            pass

        # XXX: Try to match to actual values, raise if no match

        # quote specifier
        if format[:1] == "'" or format[:1] == '"':
            return len(format)-1

        # address specifier
        two = format.split('&')
        if len(two) == 2:
            return self.calcUnpackSize(two[0], data)

        # code specifier
        two = format.split('=')
        if len(two) >= 2:
            return self.calcUnpackSize(two[0], data)

        # length specifier
        two = format.split('-')
        if len(two) == 2:
            return self.calcUnpackSize(two[0], data)

        # array specifier
        two = format.split('*')
        if len(two) == 2:
            answer = 0
            if two[0]:
                if two[0].isdigit():
                    number = int(two[0])
                else:
                    answer += self.calcUnpackSize(two[0], data)
                    number = self.unpack(two[0], data[:answer])

                while number:
                    number -= 1
                    answer += self.calcUnpackSize(two[1], data[answer:])
            else:
                while answer < len(data):
                    answer += self.calcUnpackSize(two[1], data[answer:])
            return answer

        # "printf" string specifier
        if format[:1] == '%':
            raise Exception, "Can't guess the size of a printf like specifier for unpacking"

        # asciiz specifier
        if format[:1] == 'z':
            return data.index('\x00')+1

        # asciiz specifier
        if format[:1] == 'u':
            l = data.index('\x00\x00')
            return l + (l & 1 and 3 or 2)

        # DCE-RPC/NDR string specifier
        if format[:1] == 'w':
            l = unpack('<L', data[:4])[0]
            return 12+l*2

        # literal specifier
        if format[:1] == ':':
            return len(data)

        # struct like specifier
        return calcsize(format)

    def calcPackFieldSize(self, fieldName, format = None):
        if format is None:
            format = self.formatForField(fieldName)

        return self.calcPackSize(format, self[fieldName])

    def formatForField(self, fieldName):
        for field in self.commonHdr+self.structure:
            if field[0] == fieldName:
                return field[1]
        raise Exception, ("Field %s not found" % fieldName)

    def findAddressFieldFor(self, fieldName):
        descriptor = '&%s' % fieldName
        l = len(descriptor)
        for field in self.commonHdr+self.structure:
            if field[1][-l:] == descriptor:
                return field[0]
        return None

    def findLengthFieldFor(self, fieldName):
        descriptor = '-%s' % fieldName
        l = len(descriptor)
        for field in self.commonHdr+self.structure:
            if field[1][-l:] == descriptor:
                return field[0]
        return None

    def zeroValue(self, format):
        two = format.split('*')
        if len(two) == 2:
            if two[0].isdigit():
                return (self.zeroValue(two[1]),)*int(two[0])

        if not format.find('*') == -1: return ()
        if 's' in format: return ''
        if format in ['z',':','u']: return ''
        if format == 'w': return '\x00\x00'

        return 0

    def clear(self):
        for field in self.commonHdr + self.structure:
            self[field[0]] = self.zeroValue(field[1])

    def dump(self, msg = None, indent = 0):
        if msg is None: msg = self.__class__.__name__
        ind = ' '*indent
        print "\n%s" % msg
        fixedFields = []
        for field in self.commonHdr+self.structure:
            i = field[0]
            if i in self.fields:
                fixedFields.append(i)
                if isinstance(self[i], Structure):
                    self[i].dump('%s%s:{' % (ind,i), indent = indent + 4)
                    print "%s}" % ind
                else:
                    print "%s%s: {%r}" % (ind,i,self[i])
        # Do we have remaining fields not defined in the structures? let's
        # print them
        remainingFields = list(set(self.fields) - set(fixedFields))
        for i in remainingFields:
            if isinstance(self[i], Structure):
                self[i].dump('%s%s:{' % (ind,i), indent = indent + 4)
                print "%s}" % ind
            else:
                print "%s%s: {%r}" % (ind,i,self[i])

class _StructureTest:
    alignment = 0
    def create(self,data = None):
        if data is not None:
            return self.theClass(data, alignment = self.alignment)
        else:
            return self.theClass(alignment = self.alignment)

    def run(self):
        print
        print "-"*70
        testName = self.__class__.__name__
        print "starting test: %s....." % testName
        a = self.create()
        self.populate(a)
        a.dump("packing.....")
        a_str = str(a)
        print "packed: %r" % a_str
        print "unpacking....."
        b = self.create(a_str)
        b.dump("unpacked.....")
        print "repacking....."
        b_str = str(b)
        if b_str != a_str:
            print "ERROR: original packed and repacked don't match"
            print "packed: %r" % b_str

class _Test_simple(_StructureTest):
    class theClass(Structure):
        commonHdr = ()
        structure = (
                ('int1', '!L'),
                ('len1','!L-z1'),
                ('arr1','B*<L'),
                ('z1', 'z'),
                ('u1','u'),
                ('', '"COCA'),
                ('len2','!H-:1'),
                ('', '"COCA'),
                (':1', ':'),
                ('int3','>L'),
                ('code1','>L=len(arr1)*2+0x1000'),
                )

    def populate(self, a):
        a['default'] = 'hola'
        a['int1'] = 0x3131
        a['int3'] = 0x45444342
        a['z1']   = 'hola'
        a['u1']   = 'hola'.encode('utf_16_le')
        a[':1']   = ':1234:'
        a['arr1'] = (0x12341234,0x88990077,0x41414141)
        # a['len1'] = 0x42424242

class _Test_fixedLength(_Test_simple):
    def populate(self, a):
        _Test_simple.populate(self, a)
        a['len1'] = 0x42424242

class _Test_simple_aligned4(_Test_simple):
    alignment = 4

class _Test_nested(_StructureTest):
    class theClass(Structure):
        class _Inner(Structure):
            structure = (('data', 'z'),)

        structure = (
            ('nest1', ':', _Inner),
            ('nest2', ':', _Inner),
            ('int', '<L'),
        )

    def populate(self, a):
        a['nest1'] = _Test_nested.theClass._Inner()
        a['nest2'] = _Test_nested.theClass._Inner()
        a['nest1']['data'] = 'hola manola'
        a['nest2']['data'] = 'chau loco'
        a['int'] = 0x12345678

class _Test_Optional(_StructureTest):
    class theClass(Structure):
        structure = (
                ('pName','<L&Name'),
                ('pList','<L&List'),
                ('Name','w'),
                ('List','<H*<L'),
            )

    def populate(self, a):
        a['Name'] = 'Optional test'
        a['List'] = (1,2,3,4)

class _Test_Optional_sparse(_Test_Optional):
    def populate(self, a):
        _Test_Optional.populate(self, a)
        del a['Name']

class _Test_AsciiZArray(_StructureTest):
    class theClass(Structure):
        structure = (
            ('head','<L'),
            ('array','B*z'),
            ('tail','<L'),
        )

    def populate(self, a):
        a['head'] = 0x1234
        a['tail'] = 0xabcd
        a['array'] = ('hola','manola','te traje')

class _Test_UnpackCode(_StructureTest):
    class theClass(Structure):
        structure = (
            ('leni','<L=len(uno)*2'),
            ('cuchi','_-uno','leni/2'),
            ('uno',':'),
            ('dos',':'),
        )

    def populate(self, a):
        a['uno'] = 'soy un loco!'
        a['dos'] = 'que haces fiera'

class _Test_AAA(_StructureTest):
    class theClass(Structure):
        commonHdr = ()
        structure = (
          ('iv', '!L=((init_vector & 0xFFFFFF) << 8) | ((pad & 0x3f) << 2) | (keyid & 3)'),
          ('init_vector',   '_','(iv >> 8)'),
          ('pad',           '_','((iv >>2) & 0x3F)'),
          ('keyid',         '_','( iv & 0x03 )'),
          ('dataLen',       '_-data', 'len(inputDataLeft)-4'),
          ('data',':'),
          ('icv','>L'),
        )

    def populate(self, a):
        a['init_vector']=0x01020304
        #a['pad']=int('01010101',2)
        a['pad']=int('010101',2)
        a['keyid']=0x07
        a['data']="\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9"
        a['icv'] = 0x05060708
        #a['iv'] = 0x01020304

if __name__ == '__main__':
    _Test_simple().run()

    try:
        _Test_fixedLength().run()
    except:
        print "cannot repack because length is bogus"

    _Test_simple_aligned4().run()
    _Test_nested().run()
    _Test_Optional().run()
    _Test_Optional_sparse().run()
    _Test_AsciiZArray().run()
    _Test_UnpackCode().run()
    _Test_AAA().run()


text:
const Promise = require('bluebird');
const logging = require('../../../../../shared/logging');

// settings with new groups
const typeGroupMapping = [{
    keys: [
        'members_public_key',
        'members_private_key',
        'members_email_auth_secret'
    ],
    from: 'members',
    to: 'core'
}, {
    keys: [
        'title',
        'description',
        'logo',
        'cover_image',
        'icon',
        'accent_color',
        'lang',
        'timezone',
        'codeinjection_head',
        'codeinjection_foot',
        'facebook',
        'twitter',
        'navigation',
        'secondary_navigation',
        'meta_title',
        'meta_description',
        'og_image',
        'og_title',
        'og_description',
        'twitter_image',
        'twitter_title',
        'twitter_description'

    ],
    from: 'blog',
    to: 'site'
}, {
    keys: ['amp'],
    from: 'blog',
    to: 'amp'
}, {
    keys: ['labs'],
    from: 'blog',
    to: 'labs'
}, {
    keys: ['slack'],
    from: 'blog',
    to: 'slack'
}, {
    keys: ['unsplash'],
    from: 'blog',
    to: 'unsplash'
}, {
    keys: ['shared_views'],
    from: 'blog',
    to: 'views'
}, {
    keys: ['bulk_email_settings'],
    from: 'bulk_email',
    to: 'email'
}];

// settings with the same groups
const groupMapping = [{
    group: 'core',
    keys: [
        'db_hash',
        'next_update_check',
        'notifications',
        'session_secret',
        'theme_session_secret',
        'ghost_public_key',
        'ghost_private_key'
    ]
}, {
    group: 'theme',
    keys: ['active_theme']
}, {
    group: 'private',
    keys: [
        'is_private',
        'password',
        'public_hash'
    ]
}, {
    group: 'members',
    keys: [
        'default_content_visibility',
        'members_subscription_settings',
        'stripe_connect_integration'
    ]
}, {
    group: 'portal',
    keys: [
        'portal_name',
        'portal_button',
        'portal_plans'
    ]
}];

// flags to be added to settings
const flagMapping = [{
    key: 'title',
    flags: 'PUBLIC'
}, {
    key: 'description',
    flags: 'PUBLIC'
}, {
    key: 'logo',
    flags: 'PUBLIC'
}, {
    key: 'accent_color',
    flags: 'PUBLIC'
}, {
    key: 'active_theme',
    flags: 'RO'
}];

module.exports = {
    config: {
        transaction: true
    },

    async up(options) {
        // set the new group for each changed setting and rename type
        await Promise.map(typeGroupMapping, async (typeGroupMap) => {
            return await Promise.map(typeGroupMap.keys, async (key) => {
                logging.info(`Moving setting ${key} from ${typeGroupMap.from} to ${typeGroupMap.to}`);

                return await options
                    .transacting('settings')
                    .where('key', key)
                    .update({
                        group: typeGroupMap.to,
                        type: typeGroupMap.to
                    });
            });
        });

        // set the correct group value settings which aren't changing type
        await Promise.map(groupMapping, async (groupMap) => {
            return await Promise.map(groupMap.keys, async (key) => {
                logging.info(`Adding setting ${key} to ${groupMap.group}`);

                return await options
                    .transacting('settings')
                    .where('key', key)
                    .update({
                        group: groupMap.group
                    });
            });
        });

        return await Promise.map(flagMapping, async (flagMap) => {
            logging.info(`Adding ${flagMap.flags} flag to ${flagMap.key} setting`);

            return await options
                .transacting('settings')
                .where('key', flagMap.key)
                .update({
                    flags: flagMap.flags
                });
        });
    },

    async down(options) {
        // clear all flags values
        logging.info('Clearing all settings flags values');
        await options
            .transacting('settings')
            .update({
                flags: null
            });

        // put type values back but leave all group values as-is because we
        // didn't change them from anything specific in `up`
        return await Promise.map(typeGroupMapping, async (typeGroupMap) => {
            return await Promise.map(typeGroupMap.keys, async (key) => {
                logging.info(`Moving setting ${key} from ${typeGroupMap.from} to ${typeGroupMap.to}`);

                return await options
                    .transacting('settings')
                    .where('key', key)
                    .update({
                        type: typeGroupMap.from
                    });
            });
        });
    }
};


text: Google is fast .