text:
(function() {
  var $, ResultsModel, WorkspaceView, path, waitsForPromise, _ref;

  path = require('path');

  _ref = require('atom'), $ = _ref.$, WorkspaceView = _ref.WorkspaceView;

  ResultsModel = require('../lib/project/results-model');

  waitsForPromise = function(fn) {
    return window.waitsForPromise({
      timeout: 30000
    }, fn);
  };

  describe('ResultsModel', function() {
    var editSession, resultsModel, searchPromise, _ref1;
    _ref1 = [], editSession = _ref1[0], searchPromise = _ref1[1], resultsModel = _ref1[2], searchPromise = _ref1[3];
    beforeEach(function() {
      var editor;
      atom.workspaceView = new WorkspaceView();
      atom.project.setPath(path.join(__dirname, 'fixtures'));
      atom.workspaceView.openSync('sample.js');
      atom.workspaceView.attachToDom();
      editor = atom.workspaceView.getActiveView();
      editSession = editor.editor;
      return resultsModel = new ResultsModel();
    });
    describe("searching for a pattern", function() {
      beforeEach(function() {});
      it("populates the model with all the results, and updates in response to changes in the buffer", function() {
        var resultAddedSpy, resultRemovedSpy;
        resultAddedSpy = jasmine.createSpy();
        resultRemovedSpy = jasmine.createSpy();
        runs(function() {
          resultsModel.on('result-added', resultAddedSpy);
          resultsModel.on('result-removed', resultRemovedSpy);
          return searchPromise = resultsModel.search('items', ['*.js'], '');
        });
        waitsForPromise(function() {
          return searchPromise;
        });
        return runs(function() {
          var result;
          expect(resultAddedSpy).toHaveBeenCalled();
          expect(resultAddedSpy.callCount).toBe(1);
          result = resultsModel.getResult(editSession.getPath());
          expect(result.matches.length).toBe(6);
          expect(resultsModel.getPathCount()).toBe(1);
          expect(resultsModel.getMatchCount()).toBe(6);
          expect(resultsModel.getPaths()).toEqual([editSession.getPath()]);
          editSession.setText('there are some items in here');
          editSession.buffer.emit('contents-modified');
          expect(resultAddedSpy.callCount).toBe(2);
          result = resultsModel.getResult(editSession.getPath());
          expect(result.matches.length).toBe(1);
          expect(resultsModel.getPathCount()).toBe(1);
          expect(resultsModel.getMatchCount()).toBe(1);
          expect(resultsModel.getPaths()).toEqual([editSession.getPath()]);
          expect(result.matches[0].lineText).toBe('there are some items in here');
          editSession.setText('no matches in here');
          editSession.buffer.emit('contents-modified');
          expect(resultAddedSpy.callCount).toBe(2);
          expect(resultRemovedSpy.callCount).toBe(1);
          result = resultsModel.getResult(editSession.getPath());
          expect(result).not.toBeDefined();
          expect(resultsModel.getPathCount()).toBe(0);
          expect(resultsModel.getMatchCount()).toBe(0);
          resultsModel.clear();
          spyOn(editSession, 'scan').andCallThrough();
          editSession.setText('no matches in here');
          editSession.buffer.emit('contents-modified');
          expect(editSession.scan).not.toHaveBeenCalled();
          expect(resultsModel.getPathCount()).toBe(0);
          return expect(resultsModel.getMatchCount()).toBe(0);
        });
      });
      return it("ignores changes in untitled buffers", function() {
        var resultAddedSpy, resultRemovedSpy;
        resultAddedSpy = jasmine.createSpy();
        resultRemovedSpy = jasmine.createSpy();
        waitsForPromise(function() {
          return atom.workspaceView.open();
        });
        runs(function() {
          resultsModel.on('result-added', resultAddedSpy);
          resultsModel.on('result-removed', resultRemovedSpy);
          return searchPromise = resultsModel.search('items', ['*.js'], '');
        });
        waitsForPromise(function() {
          return searchPromise;
        });
        return runs(function() {
          editSession = atom.workspaceView.getActiveView().editor;
          editSession.setText('items\nitems');
          spyOn(editSession, 'scan').andCallThrough();
          editSession.buffer.emit('contents-modified');
          return expect(editSession.scan).not.toHaveBeenCalled();
        });
      });
    });
    return describe("cancelling a search", function() {
      var cancelledSpy;
      cancelledSpy = null;
      beforeEach(function() {
        cancelledSpy = jasmine.createSpy();
        return resultsModel.on('cancelled-searching', cancelledSpy);
      });
      it("populates the model with all the results, and updates in response to changes in the buffer", function() {
        runs(function() {
          searchPromise = resultsModel.search('items', ['*.js'], '');
          expect(resultsModel.inProgressSearchPromise).toBeTruthy();
          resultsModel.clear();
          return expect(resultsModel.inProgressSearchPromise).toBeFalsy();
        });
        waitsForPromise(function() {
          return searchPromise;
        });
        return runs(function() {
          return expect(cancelledSpy).toHaveBeenCalled();
        });
      });
      return it("populates the model with all the results, and updates in response to changes in the buffer", function() {
        runs(function() {
          searchPromise = resultsModel.search('items', ['*.js'], '');
          return searchPromise = resultsModel.search('sort', ['*.js'], '');
        });
        waitsForPromise(function() {
          return searchPromise;
        });
        return runs(function() {
          expect(cancelledSpy).toHaveBeenCalled();
          expect(resultsModel.getPathCount()).toBe(1);
          return expect(resultsModel.getMatchCount()).toBe(5);
        });
      });
    });
  });

}).call(this);


text:
module.exports = function(gulp, config) {

	return function(done) {
		if(!config.sprites) return done()
		var c = require('better-console')
		c.info('~ sprites')

		var path = require('path')
		var plumber = require('gulp-plumber')
		var svgSprite = require('gulp-svg-sprite')
		var merge = require('merge-stream')

		var tasks = merge()

		for(var i = 0; i < config.sprites.length; i++) {
			(function() {
			var prefix = config.sprites[i].name
			var generator = (function(name) {
				var namePath = name.split(path.sep)
				var fileName = namePath[namePath.length - 1].split('.')
				fileName.pop() // Remove file extension
				var id = 'shape-' + (prefix ? prefix + '-' : '') + fileName.join('.')
				return id

			}).bind(prefix)
			var filename = config.sprites[i].filename || 'shapes' + (config.sprites[i].name ? '-' + config.sprites[i].name : '')
			var task = gulp.src(config.sprites[i].path, { base: config.src_folder, cwd: config.dir, allowEmpty: true })
				.pipe(svgSprite({
					svg: {
						rootAttributes: {
							'xmlns': 'http://www.w3.org/2000/svg',
							'xmlns:xlink': 'http://www.w3.org/1999/xlink'
						}
					},
					shape: {
						id: {
							generator: generator
						}
					},
					mode: {
						symbol: {
							inline: true,
							dest: 'sprites',
							sprite: filename
						}
					}
				}))

				if(config.devmode){
					task = task.pipe(plumber({ errorHandler: require('../helpers/error_handler') }))
				}
				tasks.add(task.pipe(gulp.dest(config.dist_persistent_folder)))
				})()
		}

		return tasks
	}
}

redpajama_set_name: RedPajamaGithub


text: Attempts at BASH (Bourne Again SHell) scripts by me


text:
name 'zookeeper_server'
description 'runs a zookeeper and hbase-master in fully-distributed mode. There should be exactly one of these per cluster.'

run_list %w[
  zookeeper::server
]


text:
public class CommandErrorNotification extends Event {
	private static final long serialVersionUID = 1L;

	public enum Type{
		REGISTER_CLIENT
	}

	Type mType;

	public CommandErrorNotification(Type type) {
		super(Event.Type.COMMAND_ERROR);
		mType = type;
	}

	public Type getErrorType(){
		return mType;
	}

	public void setType(Type type){
		mType = type;
	}
}


text:
const express = require('express')
const router = express.Router()
const http = require('http')
const fs = require('fs')
const jwt = require('jsonwebtoken')
const download = require('image-downloader')

router.get('/', function(req, res, next) {
    let token = req.cookies.access_token
    let secretKey = config.key
    jwt.verify(token, secretKey, function(err, decoded) {
        if (err) {
            logger.debug('Session Logged out')
            res.status(401).redirect('/')
        } else {
            var render_url = req.query.url
            logger.silly('Image URL', render_url)
            let options = {
                url: render_url,
                dest: './public/images/google.png'
            }
            /**
             * Will be used in order to store the image at a particular location and after saving will render the image.
             * @param {object} options - have 2 parameters url of the image and destination to be stored at
                  {string}    url- url of the image
                  {string}    dest-  destination where the image is to be stored
            */
            download.image(options)
                .then(({ filename, image }) => {
                    logger.info('image saved to', filename)
                    logger.info('GET /image')
                    res.render('image')
                }).catch((err) => {
                    logger.error(err)
                    logger.warn('Redirecting to welcome page')
                    res.status(404).redirect('welcome')
                })
        }
    })
})

module.exports = router


text:
<?php
/**
 * Pictorico functions and definitions
 *
 * @package Pictorico
 */

/**
 * Set the content width based on the theme's design and stylesheet.
 */
if ( ! isset( $content_width ) ) {
	$content_width = 1180; /* pixels */
}

if ( ! function_exists( 'pictorico_setup' ) ) :
/**
 * 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 pictorico_setup() {

	/*
	 * Make theme available for translation.
	 * Translations can be filed in the /languages/ directory.
	 * If you're building a theme based on Pictorico, use a find and replace
	 * to change 'pictorico' to the name of your theme in all the template files
	 */
	load_theme_textdomain( 'pictorico', get_template_directory() . '/languages' );

	// Add default posts and comments RSS feed links to head.
	add_theme_support( 'automatic-feed-links' );

	/**
	 * Editor styles
	 */
	add_editor_style( 'editor-style.css' );

	/*
	 * 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' );
	add_image_size( 'pictorico-home', '590', '590', true );
	add_image_size( 'pictorico-slider', '1180', '525', true );
	add_image_size( 'pictorico-single', '1500', '525', true );

	// This theme uses wp_nav_menu() in one location.
	register_nav_menus( array(
		'primary' => __( 'Primary Menu', 'pictorico' ),
	) );

	// Enable support for Post Formats.
	add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', 'gallery', 'audio' ) );

	// Setup the WordPress core custom background feature.
	add_theme_support( 'custom-background', apply_filters( 'pictorico_custom_background_args', array(
		'default-color' => 'e7f2f8',
		'default-image' => '',
	) ) );

	// Enable support for HTML5 markup.
	add_theme_support( 'html5', array(
		'comment-list',
		'search-form',
		'comment-form',
		'gallery',
	) );
}
endif; // pictorico_setup
add_action( 'after_setup_theme', 'pictorico_setup' );

/**
 * Register widget area.
 *
 * @link http://codex.wordpress.org/Function_Reference/register_sidebar
 */
function pictorico_widgets_init() {
	register_sidebar( array(
		'name'          => __( 'Footer Sidebar 1', 'pictorico' ),
		'id'            => 'sidebar-1',
		'description'   => '',
		'before_widget' => '',
		'after_widget'  => '',
		'before_title'  => '
',
		'after_title'   => '
',
	) );
	register_sidebar( array(
		'name'          => __( 'Footer Sidebar 2', 'pictorico' ),
		'id'            => 'sidebar-2',
		'description'   => '',
		'before_widget' => '',
		'after_widget'  => '',
		'before_title'  => '
',
		'after_title'   => '
',
	) );
	register_sidebar( array(
		'name'          => __( 'Footer Sidebar 3', 'pictorico' ),
		'id'            => 'sidebar-3',
		'description'   => '',
		'before_widget' => '',
		'after_widget'  => '',
		'before_title'  => '
',
		'after_title'   => '
',
	) );
	register_sidebar( array(
		'name'          => __( 'Footer Sidebar 4', 'pictorico' ),
		'id'            => 'sidebar-4',
		'description'   => '',
		'before_widget' => '',
		'after_widget'  => '',
		'before_title'  => '
',
		'after_title'   => '
',
	) );
}
add_action( 'widgets_init', 'pictorico_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function pictorico_scripts() {
	wp_enqueue_style( 'pictorico-style', get_stylesheet_uri() );

	wp_enqueue_style( 'genericons', get_template_directory_uri() . '/genericons/genericons.css', array(), '3.0.3' );

	wp_enqueue_style( 'pictorico-open-sans-condensed' );
	wp_enqueue_style( 'pictorico-pt-serif' );

	wp_enqueue_script( 'pictorico-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );

	wp_enqueue_script( 'pictorico-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}

	if ( pictorico_has_featured_posts( 1 ) ) {
	    wp_enqueue_script( 'pictorico-slider-script', get_template_directory_uri() . '/js/jquery.flexslider.js', array( 'jquery' ) );
	    wp_enqueue_script( 'pictorico-script', get_template_directory_uri() . '/js/pictorico.js', array( 'pictorico-slider-script' ) );
	}
}
add_action( 'wp_enqueue_scripts', 'pictorico_scripts' );

/**
 * Register Google Fonts
 */
function pictorico_google_fonts() {

	$protocol = is_ssl() ? 'https' : 'http';

	/*	translators: If there are characters in your language that are not supported
		by Open Sans Condensed, translate this to 'off'. Do not translate into your own language. */

	if ( 'off' !== _x( 'on', 'Open Sans Condensed font: on or off', 'pictorico' ) ) {

		wp_register_style( 'pictorico-open-sans-condensed', "$protocol://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700&subset=latin,latin-ext" );

	}

	/*	translators: If there are characters in your language that are not supported
		by PT Serif, translate this to 'off'. Do not translate into your own language. */

	if ( 'off' !== _x( 'on', 'PT Serif font: on or off', 'pictorico' ) ) {

		wp_register_style( 'pictorico-pt-serif', "$protocol://fonts.googleapis.com/css?family=PT+Serif:400,700,400italic,700italic" );

	}

}
add_action( 'init', 'pictorico_google_fonts' );

/**
 * Enqueue Google Fonts for custom headers
 */
function pictorico_admin_scripts( $hook_suffix ) {

	if ( 'appearance_page_custom-header' != $hook_suffix )
		return;

	wp_enqueue_style( 'pictorico-open-sans-condensed' );
	wp_enqueue_style( 'pictorico-pt-serif' );

}
add_action( 'admin_enqueue_scripts', 'pictorico_admin_scripts' );

/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/inc/custom-header.php';

/**
 * 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';

/**
 * Load Jetpack compatibility file.
 */
require get_template_directory() . '/inc/jetpack.php';


text:
try {
    var Spooky = require('spooky');
} catch (e) {
    var Spooky = require('../lib/spooky');
}

var fs = require('fs');

var addTransactionsToSpreadsheet = require('./GoogleSpreadsheetHelper.js');

var username = process.env.CARD_USERNAME;
var password = process.env.CARD_PASSWORD;
var googleusername = process.env.GMAIL_USERNAME;
var googlepassword = process.env.GMAIL_PASSWORD;

var spooky = new Spooky({
        child: {
            transport: 'http',
            'ignore-ssl-errors': 'yes',
            'ssl-protocol': 'tlsv1'
        },
        casper: {
            logLevel: 'error',
            verbose: true
        }
    }, function (err) {
        if (err) {
            e = new Error('Failed to initialize SpookyJS');
            e.details = err;
            throw e;
        }

        if(process.argv[2] === 'local')
        {
            spooky.start();
            spooky.then(function() {
                this.emit('processJson', null);
            });
        }
        else
        {
            spooky.start('https://www.barclaycardus.com');
            spooky.then(function () {
                this.echo(this.getTitle());
            });

            // pass params by value into the casper context
            spooky.then([{username: username}, function() {
                this.echo('Entering username');
                this.sendKeys('#username', username);
                this.click('#loginButton-button');
            }]);

            spooky.then(function(){
                this.echo('Waiting for password page to load');
                this.waitForSelector('#password');
            })

            spooky.then([{password: password}, function() {
                this.echo('Entering password');
                this.sendKeys('#password', password);
                this.click('#loginButton-button');
            }]);

            spooky.then(function(){
                this.echo('Waiting for activities and statements to load');
                this.waitForSelector('div.tabAction.floatLeft.mHide');
            })

            spooky.then(function() {
                this.echo('View Activity and Statements');
                this.click('div.tabAction.floatLeft.mHide');
                this.page.evaluate(function() {
                  (function(open) {
                    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
                      this.addEventListener('readystatechange', function() {
                        if (this.readyState === 4) {
                          window.request = this.responseText;
                        }
                      }, false);
                      open.call(this, method, url, async, user, pass);
                    };
                  })(XMLHttpRequest.prototype.open);
                  return 1;
                });
            });

            spooky.then(function() {
                this.echo(this.getTitle());
            });

            spooky.then(function() {
                this.wait(1500);
            });

            spooky.then(function() {
                var json = JSON.parse(this.page.evaluate(function() {
                    return window.request;
                }));
                this.emit('processJson', json);
            });
        }

        spooky.run();
    });

spooky.on('error', function (e, stack) {
    console.error(e);

    if (stack) {
        console.log(stack);
    }
});

// Uncomment this block to see all of the things Casper has to say.
// There are a lot.
// He has opinions.
spooky.on('console', function (line) {
    console.log(line);
});

// spooky.on('hello', function (greeting) {
//     console.log(greeting);
// });

spooky.on('log', function (log) {
    if (log.space === 'remote') {
        console.log(log.message.replace(/ \- .*/, ''));
    }
});

spooky.on('processJson', function(json) {

    // Write the JSON to a file with the first line
    // as the field names
    var outputStr = 'Date\tDescription\tAmount\n';

    if(!json) {
        console.log('Reading from input.json');
        var fileContents = fs.readFileSync('input.json');

        if(fileContents) {
            json = JSON.parse(fileContents);
        }
    }

    if(json) {
        json.filter(function(it) {
            return it.purchaserFirstname === 'Asha';
        })
        .reverse()
        .forEach(function(it) {
        if (it.type === 'CREDIT') {
                outputStr += it.transactionDate + '\t' + it.description + '\t' + '-' + it.amount.amount + '\n';
            } else {
                outputStr += (it.transactionDate + '\t' + it.description + '\t' + it.amount.amount + '\n');
            }
        });

        fs.writeFile('output.txt', outputStr, function(err){
            if (err) throw err;
            console.log('Wrote output.txt');

            addTransactionsToSpreadsheet(googleusername, googlepassword);
        });
    } else {
        console.log("No data to process");
    }
});


text:
package org.asynchttpclient.providers.grizzly.bodyhandler;

import static org.asynchttpclient.util.MiscUtils.isNonEmpty;

import org.asynchttpclient.Body;
import org.asynchttpclient.Request;
import org.asynchttpclient.multipart.MultipartBody;
import org.asynchttpclient.multipart.MultipartUtils;
import org.asynchttpclient.multipart.Part;
import org.asynchttpclient.providers.grizzly.FeedableBodyGenerator;
import org.asynchttpclient.providers.grizzly.GrizzlyAsyncHttpProvider;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.http.HttpRequestPacket;
import org.glassfish.grizzly.memory.Buffers;
import org.glassfish.grizzly.memory.MemoryManager;

import java.io.IOException;
import java.util.List;

public final class PartsBodyHandler extends BodyHandler {

    // -------------------------------------------- Methods from BodyHandler

    public boolean handlesBodyType(final Request request) {
        return isNonEmpty(request.getParts());
    }

    public boolean doHandle(final FilterChainContext ctx, final Request request, final HttpRequestPacket requestPacket) throws IOException {

        final List<Part> parts = request.getParts();
        final MultipartBody multipartBody = MultipartUtils.newMultipartBody(parts, request.getHeaders());
        requestPacket.setContentLengthLong(multipartBody.getContentLength());
        requestPacket.setContentType(multipartBody.getContentType());
        if (GrizzlyAsyncHttpProvider.LOGGER.isDebugEnabled()) {
            GrizzlyAsyncHttpProvider.LOGGER.debug("REQUEST(modified): contentLength={}, contentType={}",
                    new Object[] { requestPacket.getContentLength(), requestPacket.getContentType() });
        }

        final FeedableBodyGenerator generator = new FeedableBodyGenerator() {
            @Override
            public Body createBody() throws IOException {
                return multipartBody;
            }
        };
        generator.setFeeder(new FeedableBodyGenerator.BaseFeeder(generator) {
            @Override
            public void flush() throws IOException {
                final Body bodyLocal = feedableBodyGenerator.createBody();
                try {
                    final MemoryManager mm = ctx.getMemoryManager();
                    boolean last = false;
                    while (!last) {
                        Buffer buffer = mm.allocate(BodyHandler.MAX_CHUNK_SIZE);
                        buffer.allowBufferDispose(true);
                        final long readBytes = bodyLocal.read(buffer.toByteBuffer());
                        if (readBytes > 0) {
                            buffer.position((int) readBytes);
                            buffer.trim();
                        } else {
                            buffer.dispose();
                            if (readBytes < 0) {
                                last = true;
                                buffer = Buffers.EMPTY_BUFFER;
                            } else {
                                throw new IllegalStateException("MultipartBody unexpectedly returned 0 bytes available");
                            }
                        }
                        feed(buffer, last);
                    }
                } finally {
                    if (bodyLocal != null) {
                        try {
                            bodyLocal.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            }
        });
        generator.initializeAsynchronousTransfer(ctx, requestPacket);
        return false;
    }
} // END PartsBodyHandler


text:
<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    private $name;
    private $email;
    private $password;

	protected $table = 'users';

    public $timestamps = true;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}


text:
/*global AWPCP*/
AWPCP.define( 'awpcp/file-manager', [ 'jquery', 'knockout', 'awpcp/file', 'awpcp/settings' ],
function( $, ko, File, settings ) {
    var FileManager = function( nonce, files, options ) {
        var self = this;

        self.files = ko.observableArray( [] );
        self.images = ko.observableArray( [] );
        self.attachments = ko.observableArray( [] );

        self.imagesAllowed = ko.observable( options.imagesAllowed );
        self.imagesUploaded = ko.observable( options.imagesUploaded );

        self.primaryImageId = ko.observable( options.primaryImageId );

        self.setImageAsPrimary = function( file ) {
            self.showLoadingSpinner( file );

            $.post( settings.get( 'ajaxurl' ), {
                nonce: nonce,
                action: 'awpcp-set-image-as-primary',
                listing_id: file.listing_id,
                file_id: file.id
            }, function( response ) {
                if ( response.status === 'ok' ) {
                    self.primaryImageId( file.id );
                    self.hideLoadingSpinner( file );
                }
            } );
        };

        self.showLoadingSpinner = function( file ) {
            $( '#file-' + file.id ).find( '.image-actions .spinner' ).removeClass( 'spinner-hidden' );
        };

        self.hideLoadingSpinner = function( file ) {
            $( '#file-' + file.id ).find( '.image-actions .spinner' ).addClass( 'spinner-hidden' );
        };

        self.updateFileEnabledStatus = function( new_status ) {
            var file = this;

            if ( file.locked ) {
                return;
            }

            self.showLoadingSpinner( file );
            file.locked = true;

            $.post( settings.get( 'ajaxurl' ), {
                nonce: nonce,
                action: 'awpcp-update-file-enabled-status',
                listing_id: file.listing_id,
                file_id: file.id,
                new_status: new_status
            }, function( response ) {
                if ( response.status !== 'ok' ) {
                    file.enabled( ! new_status );
                }
                self.hideLoadingSpinner( file );
                file.locked = false;
            } );
        };

        self.deleteFile = function( file ) {
            self.showLoadingSpinner( file );

            $.post( settings.get( 'ajaxurl' ), {
                nonce: nonce,
                action: 'awpcp-delete-file',
                listing_id: file.listing_id,
                file_id: file.id
            }, function( response ) {
                if ( response.status === 'ok' ) {
                    self.files.remove(file);
                    if ( file.isImage ) {
                        self.images.remove( file );
                    } else {
                        self.attachments.remove( file );
                    }
                    self.hideLoadingSpinner( file );
                }
            } );
        };

        self.prepareFiles( nonce, files );
        self.defineComputedProperties();
    };

    $.extend( FileManager.prototype, {
        prepareFiles: function( nonce, files ) {
            var self = this;

            $.each( files, function( index, file ) {
                var model = new File( file, self.primaryImageId );

                model.enabled.subscribe( self.updateFileEnabledStatus, model );

                self[ file.isImage ? 'images' : 'attachments' ].push( model );
                self.files.push( model );
            } );
        },

        defineComputedProperties: function() {
            var self = this;

            self.haveFiles = ko.computed( function() {
                return self.files().length > 0;
            } );

            self.haveImages = ko.computed( function() {
                return self.images().length > 0;
            } );

            self.haveAttachments = ko.computed( function() {
                return self.attachments().length > 0;
            } );

            self.canUploadImages = ko.computed( function() {
                return self.imagesAllowed() > self.images().length;
            } );
        }
    } );

    return FileManager;
} );


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="user-scalable=no, width=device-width" />

      <canvas id="canvas" width="980" height="1000" style="margin: 0; background-color: rgb(245,245,245);">
          Votre navigateur ne supporte pas les canvas.
      </canvas>


text:
OpenStack Haproxy Server
########################
:tags: openstack, galera, haproxy, cloud, ansible
:category: \*nix

Role for the installation and setup of haproxy

.. code-block:: yaml

    - name: Install haproxy
      hosts: haproxy
      user: root
      roles:
        - { role: "haproxy_server", tags: [ "haproxy-server" ] }
      vars:
        haproxy_service_configs:
          - service:
              hap_service_name: group_name
              hap_backend_nodes: "{{ groups['group_name'][0] }}"
              hap_backup_nodes: "{{ groups['group_name'][1:] }}"
              hap_port: 80
              hap_balance_type: http
              hap_backend_options:
                - "forwardfor"
                - "httpchk"
                - "httplog"


text:
package org.fcrepo.server.search;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import java.util.Date;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import org.fcrepo.server.errors.ObjectIntegrityException;
import org.fcrepo.server.errors.RepositoryConfigurationException;
import org.fcrepo.server.errors.StreamIOException;
import org.fcrepo.server.errors.UnrecognizedFieldException;
import org.fcrepo.server.utilities.DCField;
import org.fcrepo.server.utilities.DCFields;
import org.fcrepo.utilities.DateUtility;
import org.fcrepo.utilities.XmlTransformUtility;

/**
 * @author Chris Wilper
 */
public class ObjectFields
        extends DCFields {

    private String m_pid;

    private String m_label;

    private String m_state;

    private String m_ownerId;

    private Date m_cDate;

    private Date m_mDate;

    private Date m_dcmDate;

    private List<DCField> m_relObj = new ArrayList<DCField>();

    private List<DCField> m_relPredObj = new ArrayList<DCField>();

    private List<DCField> m_relSysPredObj = new ArrayList<DCField>();

    private StringBuffer m_currentContent;

    private final boolean[] m_want = new boolean[27];

    public final static int PID = 0;

    public final static int LABEL = 1;

    public final static int STATE = 4;

    public final static int OWNERID = 5;

    public final static int CDATE = 6;

    public final static int MDATE = 7;

    public final static int TITLE = 8;

    public final static int CREATOR = 9;

    public final static int SUBJECT = 10;

    public final static int DESCRIPTION = 11;

    public final static int PUBLISHER = 12;

    public final static int CONTRIBUTOR = 13;

    public final static int DATE = 14;

    public final static int TYPE = 15;

    public final static int FORMAT = 16;

    public final static int IDENTIFIER = 17;

    public final static int SOURCE = 18;

    public final static int LANGUAGE = 19;

    public final static int RELATION = 20;

    public final static int COVERAGE = 21;

    public final static int RIGHTS = 22;

    public final static int DCMDATE = 23;

    public final static int RELOBJ = 24;

    public final static int RELPREDOBJ = 25;

    public final static int RELSYSPREDOBJ = 26;

    public ObjectFields() {
    }

    public ObjectFields(String[] fieldNames)
            throws UnrecognizedFieldException {
        for (String s : fieldNames) {
            if (s.equalsIgnoreCase("pid")) {
                m_want[PID] = true;
            } else if (s.equalsIgnoreCase("label")) {
                m_want[LABEL] = true;
            } else if (s.equalsIgnoreCase("state")) {
                m_want[STATE] = true;
            } else if (s.equalsIgnoreCase("ownerId")) {
                m_want[OWNERID] = true;
            } else if (s.equalsIgnoreCase("cDate")) {
                m_want[CDATE] = true;
            } else if (s.equalsIgnoreCase("mDate")) {
                m_want[MDATE] = true;
            } else if (s.equalsIgnoreCase("title")) {
                m_want[TITLE] = true;
            } else if (s.equalsIgnoreCase("creator")) {
                m_want[CREATOR] = true;
            } else if (s.equalsIgnoreCase("subject")) {
                m_want[SUBJECT] = true;
            } else if (s.equalsIgnoreCase("description")) {
                m_want[DESCRIPTION] = true;
            } else if (s.equalsIgnoreCase("publisher")) {
                m_want[PUBLISHER] = true;
            } else if (s.equalsIgnoreCase("contributor")) {
                m_want[CONTRIBUTOR] = true;
            } else if (s.equalsIgnoreCase("date")) {
                m_want[DATE] = true;
            } else if (s.equalsIgnoreCase("type")) {
                m_want[TYPE] = true;
            } else if (s.equalsIgnoreCase("format")) {
                m_want[FORMAT] = true;
            } else if (s.equalsIgnoreCase("identifier")) {
                m_want[IDENTIFIER] = true;
            } else if (s.equalsIgnoreCase("source")) {
                m_want[SOURCE] = true;
            } else if (s.equalsIgnoreCase("language")) {
                m_want[LANGUAGE] = true;
            } else if (s.equalsIgnoreCase("relation")) {
                m_want[RELATION] = true;
            } else if (s.equalsIgnoreCase("coverage")) {
                m_want[COVERAGE] = true;
            } else if (s.equalsIgnoreCase("rights")) {
                m_want[RIGHTS] = true;
            } else if (s.equalsIgnoreCase("dcmDate")) {
                m_want[DCMDATE] = true;
            } else if (s.equalsIgnoreCase("relObj")) {
                m_want[RELOBJ] = true;
            } else if (s.equalsIgnoreCase("relPredObj")) {
                m_want[RELPREDOBJ] = true;
            } else if (s.equalsIgnoreCase("relSysPredObj")) {
                m_want[RELSYSPREDOBJ] = true;
            } else {
                throw new UnrecognizedFieldException("Unrecognized field: '"
                        + s + "'");
            }
        }
    }

    public ObjectFields(String[] fieldNames, InputStream in)
            throws UnrecognizedFieldException,
            RepositoryConfigurationException, ObjectIntegrityException,
            StreamIOException {
        this(fieldNames);
        try {
            XmlTransformUtility.parseWithoutValidating(in, this);
        } catch (SAXException saxe) {
            throw new ObjectIntegrityException("Parse error parsing ObjectFields: "
                    + saxe.getMessage());
        } catch (IOException ioe) {
            throw new StreamIOException("Stream error parsing ObjectFields: "
                    + ioe.getMessage());
        }
    }

    @Override
    public void startElement(String uri,
                             String localName,
                             String qName,
                             Attributes attrs) {
        m_currentContent = new StringBuffer();
    }

    @Override
    public void characters(char[] ch, int start, int length) {
        m_currentContent.append(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName) {
        if (m_want[PID] && localName.equals("pid")) {
            setPid(m_currentContent.toString());
        } else if (m_want[LABEL] && localName.equals("label")) {
            setLabel(m_currentContent.toString());
        } else if (m_want[STATE] && localName.equals("state")) {
            setState(m_currentContent.toString());
        } else if (m_want[OWNERID] && localName.equals("ownerId")) {
            setOwnerId(m_currentContent.toString());
        } else if (m_want[CDATE] && localName.equals("cDate")) {
            setCDate(DateUtility.convertStringToDate(m_currentContent
                    .toString()));
        } else if (m_want[MDATE] && localName.equals("mDate")) {
            setMDate(DateUtility.convertStringToDate(m_currentContent
                    .toString()));
        } else if (m_want[DCMDATE] && localName.equals("dcmDate")) {
            setDCMDate(DateUtility.convertStringToDate(m_currentContent
                    .toString()));
        } else if (m_want[RELOBJ] && localName.equals("relObj")) {
            relObjs().add(new DCField(m_currentContent.toString()));
        } else if (m_want[RELPREDOBJ] && localName.equals("relPredObj")) {
            relPredObjs().add(new DCField(m_currentContent.toString()));
        } else if (m_want[RELSYSPREDOBJ] && localName.equals("relSysPredObj")) {
            relSysPredObjs().add(new DCField(m_currentContent.toString()));
        } else if (m_want[TITLE] && localName.equals("title")) {
            titles().add(new DCField(m_currentContent.toString()));
        } else if (m_want[CREATOR] && localName.equals("creator")) {
            creators().add(new DCField(m_currentContent.toString()));
        } else if (m_want[SUBJECT] && localName.equals("subject")) {
            subjects().add(new DCField(m_currentContent.toString()));
        } else if (m_want[DESCRIPTION] && localName.equals("description")) {
            descriptions().add(new DCField(m_currentContent.toString()));
        } else if (m_want[PUBLISHER] && localName.equals("publisher")) {
            publishers().add(new DCField(m_currentContent.toString()));
        } else if (m_want[CONTRIBUTOR] && localName.equals("contributor")) {
            contributors().add(new DCField(m_currentContent.toString()));
        } else if (m_want[DATE] && localName.equals("date")) {
            dates().add(new DCField(m_currentContent.toString()));
        } else if (m_want[TYPE] && localName.equals("type")) {
            types().add(new DCField(m_currentContent.toString()));
        } else if (m_want[FORMAT] && localName.equals("format")) {
            formats().add(new DCField(m_currentContent.toString()));
        } else if (m_want[IDENTIFIER] && localName.equals("identifier")) {
            identifiers().add(new DCField(m_currentContent.toString()));
        } else if (m_want[SOURCE] && localName.equals("source")) {
            sources().add(new DCField(m_currentContent.toString()));
        } else if (m_want[LANGUAGE] && localName.equals("language")) {
            languages().add(new DCField(m_currentContent.toString()));
        } else if (m_want[RELATION] && localName.equals("relation")) {
            relations().add(new DCField(m_currentContent.toString()));
        } else if (m_want[COVERAGE] && localName.equals("coverage")) {
            coverages().add(new DCField(m_currentContent.toString()));
        } else if (m_want[RIGHTS] && localName.equals("rights")) {
            rights().add(new DCField(m_currentContent.toString()));
        }
    }

    public void setPid(String pid) {
        m_pid = pid;
    }

    public String getPid() {
        return m_pid;
    }

    public void setLabel(String label) {
        m_label = label;
    }

    public String getLabel() {
        return m_label;
    }

    public void setState(String state) {
        m_state = state;
    }

    public String getState() {
        return m_state;
    }

    public void setOwnerId(String ownerId) {
        m_ownerId = ownerId;
    }

    public String getOwnerId() {
        return m_ownerId;
    }

    public void setCDate(Date cDate) {
        m_cDate = cDate;
    }

    public Date getCDate() {
        return m_cDate;
    }

    public void setMDate(Date mDate) {
        m_mDate = mDate;
    }

    public Date getMDate() {
        return m_mDate;
    }

    public void setDCMDate(Date dcmDate) {
        m_dcmDate = dcmDate;
    }

    public Date getDCMDate() {
        return m_dcmDate;
    }

    public List<DCField> relObjs() {
        return m_relObj;
    }

    public List<DCField> relPredObjs() {
        return m_relPredObj;
    }

    public List<DCField> relSysPredObjs() {
        return m_relSysPredObj;
    }

}


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

<title>ProductBaseRate</title>
<meta name="date" content="2013-12-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.api.ads.dfp.v201308

Class ProductBaseRate

java.lang.Object

com.google.api.ads.dfp.v201308.BaseRate

com.google.api.ads.dfp.v201308.ProductBaseRate

All Implemented Interfaces:

java.io.Serializable

public class ProductBaseRate
extends BaseRate
implements java.io.Serializable

A base rate applied to a Product.

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

ProductBaseRate()

ProductBaseRate(java.lang.Long rateCardId,
               java.lang.Long id,
               BaseRateStatus status,
               java.lang.String baseRateType,
               java.lang.String productId,
               Money rate)

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object obj)

static org.apache.axis.encoding.Deserializer
getDeserializer(java.lang.String mechType,
               java.lang.Class _javaType,
               javax.xml.namespace.QName _xmlType)

Get Custom Deserializer

java.lang.String
getProductId()

Gets the productId value for this ProductBaseRate.

Money
getRate()

Gets the rate value for this ProductBaseRate.

static org.apache.axis.encoding.Serializer
getSerializer(java.lang.String mechType,
             java.lang.Class _javaType,
             javax.xml.namespace.QName _xmlType)

Get Custom Serializer

static org.apache.axis.description.TypeDesc
getTypeDesc()

Return type metadata object

int
hashCode()

void
setProductId(java.lang.String productId)

Sets the productId value for this ProductBaseRate.

void
setRate(Money rate)

Sets the rate value for this ProductBaseRate.

Methods inherited from class com.google.api.ads.dfp.v201308.BaseRate

getBaseRateType, getId, getRateCardId, getStatus, setBaseRateType, setId, setRateCardId, setStatus

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ProductBaseRate

public ProductBaseRate()

ProductBaseRate

public ProductBaseRate(java.lang.Long rateCardId,
               java.lang.Long id,
               BaseRateStatus status,
               java.lang.String baseRateType,
               java.lang.String productId,
               Money rate)

Method Detail

getProductId

public java.lang.String getProductId()

Gets the productId value for this ProductBaseRate.

Returns:

productId   * The ID of Product this base rate is applied to.

                     This attribute is required and cannot be changed
 after creation.

setProductId

public void setProductId(java.lang.String productId)

Sets the productId value for this ProductBaseRate.

Parameters:

productId - * The ID of Product this base rate is applied to.

                     This attribute is required and cannot be changed
 after creation.

getRate

public Money getRate()

Gets the rate value for this ProductBaseRate.

Returns:

rate   * The rate value to override the rate on the product template.

                     This attribute is required. If null, the
 product is not associated
                     with this rate card.
                     The currency code is read-only.

setRate

public void setRate(Money rate)

Sets the rate value for this ProductBaseRate.

Parameters:

rate - * The rate value to override the rate on the product template.

                     This attribute is required. If null, the
 product is not associated
                     with this rate card.
                     The currency code is read-only.

equals

public boolean equals(java.lang.Object obj)

Overrides:

equals in class BaseRate

hashCode

public int hashCode()

Overrides:

hashCode in class BaseRate

getTypeDesc

public static org.apache.axis.description.TypeDesc getTypeDesc()

Return type metadata object

getSerializer

public static org.apache.axis.encoding.Serializer getSerializer(java.lang.String mechType,
                                                java.lang.Class _javaType,
                                                javax.xml.namespace.QName _xmlType)

Get Custom Serializer

getDeserializer

public static org.apache.axis.encoding.Deserializer getDeserializer(java.lang.String mechType,
                                                    java.lang.Class _javaType,
                                                    javax.xml.namespace.QName _xmlType)

Get Custom Deserializer

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var isPlainObject = require( '@stdlib/assert/is-plain-object' );
var isArray = require( '@stdlib/assert/is-array' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var dataset = require( './../lib' );

// VARIABLES //

var opts = {
	'skip': IS_BROWSER
};

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof dataset, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns an object containing arrays', opts, function test( t ) {
	var data = dataset();

	t.equal( isPlainObject( data ), true, 'is an object' );

	t.equal( hasOwnProp( data, 'black' ), true, 'has property' );
	t.equal( hasOwnProp( data, 'white' ), true, 'has property' );

	t.equal( isArray( data.black ), true, 'returns expected value' );
	t.equal( data.black.length > 0, true, 'is not empty' );

	t.equal( isArray( data.white ), true, 'returns expected value' );
	t.equal( data.white.length > 0, true, 'is not empty' );
	t.end();
});

tape( 'the function returns a copy', opts, function test( t ) {
	var l1;
	var l2;

	l1 = dataset();
	l2 = dataset();

	t.notEqual( l1, l2, 'different references' );

	l1.black[ 5 ] = 'beep';

	t.equal( l1.black[ 5 ], 'beep', 'expected element' );
	t.notEqual( l1.black[ 5 ], l2.black[ 5 ], 'no shared state' );

	t.end();
});


text:
function repeat(operation, num) {
  // modify this so it can be interrupted
  if (num <= 0) return
  operation()

  if (num % 15 === 0) {
     setTimeout(function() {
       repeat(operation, --num)
     })
   } else {
     repeat(operation, --num)
   }
}

module.exports = repeat


text:
package org.owasp.dependencycheck.xml.pom;

import org.owasp.dependencycheck.xml.pom.PomUtils;
import java.io.File;
import javax.xml.transform.sax.SAXSource;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.xml.pom.Model;

/**
 *
 * @author jeremy
 */
public class PomUtilsTest {

    public PomUtilsTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of readPom method, of class PomUtils.
     */
    @Test
    public void testReadPom_File() throws Exception {
        File file = BaseTest.getResourceAsFile(this, "dwr-pom.xml");
        String expResult = "Direct Web Remoting";
        Model result = PomUtils.readPom(file);
        assertEquals(expResult, result.getName());
    }

}


text:
VERSION := $(shell cat VERSION)
OSS := linux darwin windows

deps:
	glide -q install

test: deps
	go test `glide nv`

build: test
	@for OS in $(OSS); do \
		echo "Building $$OS..."; \
		export OUTFILE=coldbrew; if [ ! "$$OS" != "windows" ]; then export OUTFILE=coldbrew.exe; fi; \
		GOOS=$$OS GOARCH=amd64 CGO_ENABLED=0 go build -tags production -ldflags "-X main.appVersion=$(VERSION)" -o bin/$$OS/amd64/v$(VERSION)/$$OUTFILE; \
		(cd bin/$$OS/amd64/v$(VERSION); tar -cvzf coldbrew.tar.gz $$OUTFILE; rm $$OUTFILE); \
		GOOS=$$OS GOARCH=386 CGO_ENABLED=0 go build -tags production -ldflags "-X main.appVersion=$(VERSION)" -o bin/$$OS/386/v$(VERSION)/$$OUTFILE; \
		(cd bin/$$OS/386/v$(VERSION); tar -cvzf coldbrew.tar.gz $$OUTFILE; rm $$OUTFILE); \
		mkdir -p bin/$$OS/amd64/latest/; cp bin/$$OS/amd64/v$(VERSION)/* bin/$$OS/amd64/latest/; \
		mkdir -p bin/$$OS/386/latest/; cp bin/$$OS/386/v$(VERSION)/* bin/$$OS/386/latest/; \
	done

.PHONY: deps test build


text:
package net.johnewart.gearman.server.util;

import net.johnewart.gearman.engine.queue.JobQueue;
import net.johnewart.shuzai.DifferentialTimeSeries;
import net.johnewart.shuzai.Frequency;
import net.johnewart.shuzai.SampleMethod;
import net.johnewart.shuzai.TimeSeries;
import org.joda.time.DateTime;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class JobQueueMetrics {
    public final TimeSeries queued, failed, completed, exceptions,
                            highJobs, midJobs, lowJobs, futureJobs;

    public JobQueueMetrics() {
        this.highJobs = new TimeSeries();
        this.midJobs = new TimeSeries();
        this.lowJobs = new TimeSeries();
        this.futureJobs = new TimeSeries();
        this.queued = new DifferentialTimeSeries();
        this.failed = new DifferentialTimeSeries();
        this.completed = new DifferentialTimeSeries();
        this.exceptions = new DifferentialTimeSeries();
    }

    public JobQueueMetrics(TimeSeries queued, TimeSeries failed,
                           TimeSeries completed, TimeSeries exceptions,
                           TimeSeries highJobs, TimeSeries midJobs,
                           TimeSeries lowJobs, TimeSeries futureJobs) {
        this.queued = queued;
        this.failed = failed;
        this.completed = completed;
        this.exceptions = exceptions;
        this.highJobs = highJobs;
        this.midJobs = midJobs;
        this.lowJobs = lowJobs;
        this.futureJobs = futureJobs;
    }

    public JobQueueMetrics compact() {
        return new JobQueueMetrics(
                compactTimeSeries(queued, SampleMethod.MEAN),
                compactTimeSeries(failed, SampleMethod.SUM),
                compactTimeSeries(completed, SampleMethod.SUM),
                compactTimeSeries(exceptions, SampleMethod.SUM),
                compactTimeSeries(highJobs, SampleMethod.MEAN),
                compactTimeSeries(midJobs, SampleMethod.MEAN),
                compactTimeSeries(lowJobs, SampleMethod.MEAN),
                compactTimeSeries(futureJobs, SampleMethod.MEAN)
        );
    }

    private TimeSeries compactTimeSeries(TimeSeries original, SampleMethod method) {
        TimeSeries ts = original.downSample(Frequency.of(5, TimeUnit.MINUTES),
                method);
        DateTime start = ts.index().last();
        DateTime end = original.index().last();

        if (start != null && end != null) {
            for (Map.Entry<DateTime, BigDecimal> entry : ts.dataWindow(start, end).entrySet()) {
                ts.add(entry.getKey(), entry.getValue());
            }
        }

        return ts;
    }
}


text:
import numpy
from fframework import asfunction, OpFunction

__all__ = ['ScalarProduct']

class ScalarProduct(OpFunction):
    """Calculates the scalar product of the mesh points with a given vector
    Function."""

    def __init__(self, vector, mesh=None):
        """*mesh* is the mesh Function, *vector* the vector Function."""

        self.vector = asfunction(vector)
        self.mesh = asfunction(mesh)

    def __call__(self, ps):
        """Calculates the dot product of each mesh vector and the
        ``.vector()``.  The spacial coordinates are in the last dimension of
        the mesh and the vector array."""

        vector = self.vector(ps)
        mesh = self.mesh(ps)

        return numpy.tensorproduct(mesh, vector, (-1, -1))


text:
package com.cyphercove.lwptools.android.prefs;

import android.view.View;

public interface OnColorChangedListener {
	void onColorChanged(int newColor, View source);
}


text:
from __future__ import division
import numpy as np

class UncertaintyTrapEcon(object):

    def __init__(self,
                a=1.5,          # Risk aversion
                gx=0.5,         # Production shock precision
                rho=0.99,       # Correlation coefficient for theta
                sig_theta=0.5,  # Std dev of theta shock
                num_firms=100,  # Number of firms
                sig_F=1.5,      # Std dev of fixed costs
                c=-420,         # External opportunity cost
                mu_init=0,      # Initial value for mu
                gamma_init=4,   # Initial value for gamma
                theta_init=0):  # Initial value for theta

        # == Record values == #
        self.a, self.gx, self.rho, self.sig_theta = a, gx, rho, sig_theta
        self.num_firms, self.sig_F, self.c, = num_firms, sig_F, c
        self.sd_x = np.sqrt(1/ gx)

        # == Initialize states == #
        self.gamma, self.mu, self.theta =  gamma_init, mu_init, theta_init

    def psi(self, F):
        temp1 = -self.a * (self.mu - F)
        temp2 = self.a**2 * (1/self.gamma + 1/self.gx) / 2
        return (1 / self.a) * (1 - np.exp(temp1 + temp2)) - self.c

    def update_beliefs(self, X, M):
        """
        Update beliefs (mu, gamma) based on aggregates X and M.
        """
        # Simplify names
        gx, rho, sig_theta = self.gx, self.rho, self.sig_theta
        # Update mu
        temp1 = rho * (self.gamma * self.mu + M * gx * X)
        temp2 = self.gamma + M * gx
        self.mu =  temp1 / temp2
        # Update gamma
        self.gamma = 1 / (rho**2 / (self.gamma + M * gx) + sig_theta**2)

    def update_theta(self, w):
        """
        Update the fundamental state theta given shock w.
        """
        self.theta = self.rho * self.theta + self.sig_theta * w

    def gen_aggregates(self):
        """
        Generate aggregates based on current beliefs (mu, gamma).  This
        is a simulation step that depends on the draws for F.
        """
        F_vals = self.sig_F * np.random.randn(self.num_firms)
        M = np.sum(self.psi(F_vals) > 0)  # Counts number of active firms
        if M > 0:
            x_vals = self.theta + self.sd_x * np.random.randn(M)
            X = x_vals.mean()
        else:
            X = 0
        return X, M


text:
@interface LaptimesViewController : UITableViewController

@property (nonatomic, strong) Lap *lap;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *startBarButton;

-(IBAction)startTimer;

@end


text:
from model.contact import Contact
import random

def test_modify_first_contact(app, db):
    if app.contact.count() == 0:
        app.contact.create(Contact(first_name="test", last_name="test"))
    old_contacts = db.get_contact_list()
    old_contact = random.choice(old_contacts)
    contact = Contact(first_name="test2", last_name="test2")
    contact.id = old_contact.id
    app.contact.modify_contact_by_id(old_contact.id, contact)
    new_contacts = db.get_contact_list()
    assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)


text:
require 'spec_helper'

describe 'kmod', :type => :class do

  on_supported_os.each do |os, facts|
    context "on #{os} with augeas 0.8.9" do
      let(:facts) do facts.merge({:augeasversion => '0.8.9'}) end
      it do
        expect {
          should compile
        }.to raise_error(/Augeas 0.10.0 or higher required/)
      end
    end
    context "on #{os}" do
      let(:facts) do
        facts.merge(  { :augeasversion => '1.2.0' } )
      end

      it { should contain_class('kmod') }
      it { should contain_file('/etc/modprobe.d').with({ 'ensure' => 'directory' }) }
      ['modprobe.conf','aliases.conf','blacklist.conf'].each do |file|
        it { should contain_file("/etc/modprobe.d/#{file}").with({ 'ensure' => 'file' }) }
      end
    end
  end
end


text:
user_admin = User.create!(
  name: 'Admin',
  login:'admin',
  email: 'admin@test.com',
  password:'12345678',
  role: 'admin',
  thumbnail: 'logo.png',
  medium_image: 'logo.png',
  large_image: 'logo.png',
  admin: true
)

user_system = User.create!(
  name: 'System',
  login:'system',
  email: 'system@test.com',
  password:'12345678',
  role: 'user',
  admin: false
)

user_scott = User.create!(
  name: 'Scott Miller',
  login: 'scott',
  email: 'scott+demo@helpy.io',
  password: '12345678',
  role: 'user',
  admin: false,
  bio: 'I am the creator of Helpy.io, the open source helpdesk alternative. Welcome to the system!',
  linkedin: 'http://www.linkedin.com/in/optimizeit',
  thumbnail: '14369.jpg',
  medium_image: '14369.jpg',
  large_image: '14369.jpg',
  company: ''
)

# Forums
Forum.create(
  name: "Private Tickets",
  description: "Private Messages to Support",
  private: true
)
Forum.create(
  name: "Trash",
  description: "Deleted discussions go here",
  private: true
)
Forum.create(
  name: "Doc comments",
  description: "Contains comments to docs",
  private: true
)
Forum.create(
  name: "Questions and Answers",
  description: "Answers to how to do common things",
  layout: 'qna',
  allow_topic_voting: true,
  allow_post_voting: true
)
Forum.create(
  name: "Feature Requests",
  description: "Suggest and vote on what features we should add next!",
  allow_topic_voting: true
)
Forum.create(
  name: "Idea Board",
  description: "Submit Ideas for HR to consider",
  allow_topic_voting: true,
  allow_post_voting: true,
  layout: 'grid'
)
Forum.create(
  name: "Bugs and Issues",
  description: "Report Bugs here!"
)

# Knowledgebase Categories
Category.create(name:'Common Replies', title_tag: 'Common Agent Replies', meta_description: 'Common replies to questions (Visible only to agents)', front_page: false, active: false)
Category.create(name:'Email templates', title_tag: 'Email Templates',  meta_description: 'Emails used by the system (Not implemented)', front_page: false, active: false)
Category.create(name:'Getting Started',icon: 'eye-open', title_tag: 'Getting Started',meta_description:'Learn how to get started with our solution', front_page: true)
Category.create(name:'Top Issues',icon: 'exclamation-sign', title_tag: 'Solutions to Top Issues',meta_description:'Answers to our most frequent issues', front_page: true)
Category.create(name:'General Questions', icon: 'question-sign', title_tag: 'Answers General Questions',meta_description:'If you have a question of a more general nature, you might find the answer here', front_page: true)
Category.create(name:'Troubleshooting', icon: 'ok-circle', title_tag: 'Troubleshooting',meta_description:'Got a problem? Start here to learn more about solving it', front_page: true)

# Create first example tickets
topic = Forum.first.topics.create(
  name: 'Welcome to Helpy',
  private: true,
  assigned_user_id: user_admin.id,
  user_id: user_scott.id,
  current_status: 'pending'
)

topic.posts.create(
  body: 'I am the creator of Helpy, and I wanted to take a moment to welcome you to the system.  I am very interested in your feedback, so please visit http://support.helpy.io/ and leave your thoughts there.',
  user_id: user_scott.id,
  kind: 'first'
)

topic.posts.create(
  body: 'Helpy is largely a project of passion, and represents many hours of time spent coding, researching, developing ideas, documenting features, writing translations and helping to spread the word. This is all contributed for free by a community devoted to building a great customer support helpdesk, and viable alternative to commericial options like Zendesk and Desk.com.

Despite all the gains thus far, we still need YOUR help. If you can do one of the following, please do so to help support the cause. The bigger we can grow the community, the better it will become:

1. Help Spread the Word: If you like what we are doing, please SHARE, TWEET, POST, BLOG and tell all your friends about Helpy. Seriously, this is still a fairly young and little known project. Helping us spread the word is our number one request!

2. Help with I18n: We have had some great translations contributed already. If you translate Helpy to you language and we don't have it yet, please please please send us a pull request or gist of the yml file.

Thanks in advance for helping us out!',
  user_id: user_scott.id,
  kind: 'reply'
)


text:
#include <geos/planargraph/PlanarGraph.h>
#include <geos/planargraph/Edge.h>
#include <geos/planargraph/NodeMap.h>
#include <geos/planargraph/Node.h>
#include <geos/planargraph/DirectedEdge.h>

#include <vector>
#include <map>

using namespace std;

namespace geos {
namespace planargraph {

/*
 * Adds the Edge and its DirectedEdges with this PlanarGraph.
 * Assumes that the Edge has already been created with its associated
 * DirectEdges.
 * Only subclasses can add Edges, to ensure the edges added are of
 * the right class.
 */
void
PlanarGraph::add(Edge *edge)
{
	edges.push_back(edge);
	add(edge->getDirEdge(0));
	add(edge->getDirEdge(1));
}

/*
 * Removes an Edge and its associated DirectedEdges from their from-Nodes and
 * from this PlanarGraph. Note: This method does not remove the Nodes associated
 * with the Edge, even if the removal of the Edge reduces the degree of a
 * Node to zero.
 */
void
PlanarGraph::remove(Edge *edge)
{
	remove(edge->getDirEdge(0));
	remove(edge->getDirEdge(1));
	for(unsigned int i=0; i<edges.size();++i)
	{
		if(edges[i]==edge) {
			edges.erase(edges.begin()+i);
			--i;
		}
	}
}

/*
 * Removes DirectedEdge from its from-Node and from this PlanarGraph. Note:
 * This method does not remove the Nodes associated with the DirectedEdge,
 * even if the removal of the DirectedEdge reduces the degree of a Node to
 * zero.
 */
void
PlanarGraph::remove(DirectedEdge *de)
{
	DirectedEdge *sym = de->getSym();
	if (sym!=NULL) sym->setSym(NULL);
	de->getFromNode()->getOutEdges()->remove(de);
	for(unsigned int i=0; i<dirEdges.size(); ++i) {
		if(dirEdges[i]==de) {
			dirEdges.erase(dirEdges.begin()+i);
			--i;
		}
	}
}

/*
 * Removes a node from the graph, along with any associated
 * DirectedEdges and Edges.
 */
void
PlanarGraph::remove(Node *node)
{
	// unhook all directed edges
	vector<DirectedEdge*> &outEdges=node->getOutEdges()->getEdges();
	for(unsigned int i=0; i<outEdges.size(); ++i) {
		DirectedEdge *de =outEdges[i];
		DirectedEdge *sym = de->getSym();
		// remove the diredge that points to this node
		if (sym!=NULL) remove(sym);
		// remove this diredge from the graph collection
		for(unsigned int j=0; j<dirEdges.size(); ++j) {
			if (dirEdges[j]==de) {
				dirEdges.erase(dirEdges.begin()+j);
				--j;
			}
		}
		Edge *edge=de->getEdge();
		if (edge!=NULL) {
			for(unsigned int k=0; k<edges.size(); ++k) {
				if(edges[k]==edge) {
					edges.erase(edges.begin()+k);
					--k;
				}
			}
		}
	}
	// remove the node from the graph
	nodeMap.remove(node->getCoordinate());
	//nodes.remove(node);
}

/*public*/
vector<Node*>*
PlanarGraph::findNodesOfDegree(size_t degree)
{
	vector<Node*> *nodesFound=new vector<Node*>();
	findNodesOfDegree(degree, *nodesFound);
	return nodesFound;
}

/*public*/
void
PlanarGraph::findNodesOfDegree(size_t degree, vector<Node*>& nodesFound)
{
	NodeMap::container &nm=nodeMap.getNodeMap();
	for (NodeMap::container::iterator it=nm.begin(), itEnd=nm.end();
			it!=itEnd; ++it)
	{
		Node *node=it->second;
		if (node->getDegree()==degree) nodesFound.push_back(node);
	}
}

} // namespace planargraph
} // namespace geos

/**********************************************************************
 * $Log$
 * Revision 1.4  2006/06/12 10:49:43  strk
 * unsigned int => size_t
 *
 * Revision 1.3  2006/03/21 21:42:54  strk
 * planargraph.h header split, planargraph:: classes renamed to match JTS symbols
 *
 **********************************************************************/


text:
Write a program to determine the sum of the first 1000 prime numbers.

##INPUT SAMPLE:

There is no input for this program.

##OUTPUT SAMPLE:

Your program should print the sum on stdout, i.e.

3682913


text:
require_relative "die"

class CrapsDie < Die
  def initialize
    @sides = 6
  end
end


text:
<?php

require_once dirname(__FILE__) . '/ASTNodeTest.php';

/**
 * Test case for the {@link PHP_Depend_Code_ASTListExpression} class.
 *
 * @category   PHP
 * @package    PHP_Depend
 * @subpackage Code
 * @author     Manuel Pichler <mapi@pdepend.org>
 * @author     Joey Mazzarelli
 * @copyright  2008-2012 Manuel Pichler. All rights reserved.
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://www.pdepend.org/
 *
 * @covers PHP_Depend_Parser
 * @covers PHP_Depend_Code_ASTListExpression
 * @group pdepend
 * @group pdepend::ast
 * @group unittest
 */
class PHP_Depend_Code_ASTListExpressionTest extends PHP_Depend_Code_ASTNodeTest
{
    /**
     * testListExpression
     *
     * @return PHP_Depend_Code_ASTListExpression
     * @since 1.0.2
     */
    public function testListExpression()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $this->assertInstanceOf(PHP_Depend_Code_ASTListExpression::CLAZZ, $expr);

        return $expr;
    }

    /**
     * Tests the start line value.
     *
     * @param PHP_Depend_Code_ASTListExpression $expr
     *
     * @return void
     * @depends testListExpression
     */
    public function testListExpressionHasExpectedStartLine($expr)
    {
        $this->assertEquals(4, $expr->getStartLine());
    }

    /**
     * Tests the start column value.
     *
     * @param PHP_Depend_Code_ASTListExpression $expr
     *
     * @return void
     * @depends testListExpression
     */
    public function testListExpressionHasExpectedStartColumn($expr)
    {
        $this->assertEquals(5, $expr->getStartColumn());
    }

    /**
     * Tests the end line value.
     *
     * @param PHP_Depend_Code_ASTListExpression $expr
     *
     * @return void
     * @depends testListExpression
     */
    public function testListExpressionHasExpectedEndLine($expr)
    {
        $this->assertEquals(4, $expr->getEndLine());
    }

    /**
     * Tests the end column value.
     *
     * @param PHP_Depend_Code_ASTListExpression $expr
     *
     * @return void
     * @depends testListExpression
     */
    public function testListExpressionHasExpectedEndColumn($expr)
    {
        $this->assertEquals(16, $expr->getEndColumn());
    }

    /**
     * testListExpressionWithNestedList
     *
     * @return PHP_Depend_Code_ASTListExpression
     * @since 1.0.2
     */
    public function testListExpressionWithNestedList()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $this->assertInstanceOf(PHP_Depend_Code_ASTListExpression::CLAZZ, $expr);

        return $expr;
    }

    /**
     * testListExpressionWithNestedListHasExpectedStartLine
     *
     * @param PHP_Depend_Code_ASTListExpression $expr
     *
     * @return void
     * @since 1.0.2
     * @depends testListExpressionWithNestedList
     */
    public function testListExpressionWithNestedListHasExpectedStartLine($expr)
    {
        $this->assertEquals(4, $expr->getStartLine());
    }

    /**
     * testListExpressionWithNestedListHasExpectedStartColumn
     *
     * @param PHP_Depend_Code_ASTListExpression $expr
     *
     * @return void
     * @since 1.0.2
     * @depends testListExpressionWithNestedList
     */
    public function testListExpressionWithNestedListHasExpectedStartColumn($expr)
    {
        $this->assertEquals(5, $expr->getStartColumn());
    }

    /**
     * testListExpressionWithNestedListHasExpectedEndLine
     *
     * @param PHP_Depend_Code_ASTListExpression $expr
     *
     * @return void
     * @since 1.0.2
     * @depends testListExpressionWithNestedList
     */
    public function testListExpressionWithNestedListHasExpectedEndLine($expr)
    {
        $this->assertEquals(4, $expr->getEndLine());
    }

    /**
     * testListExpressionWithNestedListHasExpectedEndColumn
     *
     * @param PHP_Depend_Code_ASTListExpression $expr
     *
     * @return void
     * @since 1.0.2
     * @depends testListExpressionWithNestedList
     */
    public function testListExpressionWithNestedListHasExpectedEndColumn($expr)
    {
        $this->assertEquals(42, $expr->getEndColumn());
    }

    /**
     * Tests the list supports many variables in it
     *
     * @return void
     */
    public function testListExpressionSupportsManyVariables()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $vars = $expr->getChildren();
        $this->assertEquals(3, count($vars));
    }

    /**
     * Tests the list supports a single variable
     *
     * @return void
     */
    public function testListExpressionSupportsSingleVariable()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $vars = $expr->getChildren();
        $this->assertEquals(1, count($vars));
    }

    /**
     * Tests the list supports commas without variables
     *
     * @return void
     */
    public function testListExpressionSupportsExtraCommas()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $vars = $expr->getChildren();
        $this->assertEquals(3, count($vars));
    }

    /**
     * testListExpressionWithComments
     *
     * @return void
     */
    public function testListExpressionWithComments()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $vars = $expr->getChildren();
        $this->assertEquals(3, count($vars));
    }

    /**
     * testListExpressionWithoutChildExpression
     *
     * @return void
     */
    public function testListExpressionWithoutChildExpression()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $vars = $expr->getChildren();
        $this->assertEquals(0, count($vars));
    }

    /**
     * testListExpressionWithVariableVariable
     *
     * @return void
     */
    public function testListExpressionWithVariableVariable()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $var  = $expr->getChild(0);

        $this->assertInstanceOf(PHP_Depend_Code_ASTVariableVariable::CLAZZ, $var);
    }

    /**
     * testListExpressionWithCompoundVariable
     *
     * @return void
     */
    public function testListExpressionWithCompoundVariable()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $var  = $expr->getChild(0);

        $this->assertInstanceOf(PHP_Depend_Code_ASTCompoundVariable::CLAZZ, $var);
    }

    /**
     * testListExpressionWithArrayElement
     *
     * @return void
     */
    public function testListExpressionWithArrayElement()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $var  = $expr->getChild(0);

        $this->assertInstanceOf(PHP_Depend_Code_ASTArrayIndexExpression::CLAZZ, $var);
    }

    /**
     * testListExpressionWithObjectProperty
     *
     * @return void
     */
    public function testListExpressionWithObjectProperty()
    {
        $expr = $this->_getFirstListExpressionInFunction();
        $var  = $expr->getChild(0);

        $this->assertInstanceOf(PHP_Depend_Code_ASTMemberPrimaryPrefix::CLAZZ, $var);
    }

    /**
     * Returns a node instance for the currently executed test case.
     *
     * @return PHP_Depend_Code_ASTListExpression
     */
    private function _getFirstListExpressionInFunction()
    {
        return $this->getFirstNodeOfTypeInFunction(
            $this->getCallingTestMethod(),
            PHP_Depend_Code_ASTListExpression::CLAZZ
        );
    }
}


text:
echo
echo -e "\e[91m+-------------------------------------------------------------------------+\e[0m"
echo -e "\e[91m|                                                                         |\e[0m"
echo -e "\e[91m|   !!! Attention !!! This file is intended for local development only!   |\e[0m"
echo -e "\e[91m|                                                                         |\e[0m"
echo -e "\e[91m+-------------------------------------------------------------------------+\e[0m"
echo

set -xeuo pipefail

BASE_DIR=$(dirname $(dirname $(readlink -e "$0")))

cd "$BASE_DIR/src/main"

rm -fr resources/linux-x64
mkdir -p resources/linux-x64

# *** Build libsass

make -C libsass clean
cd libsass
git reset --hard # hard reset
git clean -xdf # hard clean
cd ..

# We use:
# - BUILD="static" to make sure that we build a static library
BUILD="static" make -C libsass -j4

# *** Build libjsass

rm -fr c/build
mkdir -p c/build
cd c/build
cmake ../
make
cp libjsass.so ../../resources/linux-x64/libjsass.so

# *** Build libjsass_test

cd "$BASE_DIR/src/test"

rm -fr resources/linux-x64
mkdir -p resources/linux-x64

rm -fr c/build
mkdir -p c/build
cd c/build
cmake ../
make
cp libjsass_test.so ../../resources/linux-x64/libjsass_test.so


text:
package org.assertj.core.api;

import java.util.List;

/**
 * Assertion methods for {@link List}s.
 *

 * To create an instance of this class, invoke {@link Assertions#assertThat(List)}.
 *

 * @param <T> the type of elements of the "actual" value.
 *
 * @author Yvonne Wang
 * @author Alex Ruiz
 * @author Joel Costigliola
 * @author Mikhail Mazursky
 */
public class ListAssert<T> extends AbstractListAssert<ListAssert<T>, List<T>, T> {

  protected ListAssert(List<T> actual) {
    super(actual, ListAssert.class);
  }
}


text:
package ds_proj;

/**
 * @author xavier Source: http://codigolibre.weebly.com/blog/pilas-en-java
 */
public class Node {

    // Variables to save value and link the following nodes
    private int value;
    Node next;

    //Constructor that initializes the value of the variables
    public void Node() {
        this.value = 0;
        this.next = null;
    }

    // Methods get and set for the attributes.
    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}


text:
package org.neo4j.visualization.graphviz;

import java.io.IOException;
import java.util.Iterator;

import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.visualization.PropertyType;

class DefaultNodeStyle implements NodeStyle
{
    protected final DefaultStyleConfiguration config;

    DefaultNodeStyle( DefaultStyleConfiguration configuration )
    {
        this.config = configuration;
    }

    @Override
    public void emitNodeStart( Appendable stream, Node node )
            throws IOException
    {
        stream.append( "  N" + node.getId() + " [\n" );
        config.emit( node, stream );
        stream.append( "    label = \"{"
                       + config.escapeLabel( config.getTitle( node ) ) );
        Iterator<Label> labels = node.getLabels().iterator();
        if ( labels.hasNext() )
        {
            if ( labels.hasNext() )
            {
                stream.append( ": " );
                while ( labels.hasNext() )
                {
                    stream.append( labels.next()
                            .name() );
                    if ( labels.hasNext() )
                    {
                        stream.append( ", " );
                    }
                }
            }
        }
        stream.append( "|" );
    }

    @Override
    public void emitEnd( Appendable stream ) throws IOException
    {
        stream.append( "}\"\n  ]\n" );
    }

    @Override
    public void emitProperty( Appendable stream, String key, Object value )
            throws IOException
    {
        if ( config.acceptNodeProperty( key ) )
        {
            PropertyType type = PropertyType.getTypeOf( value );
            config.emitNodeProperty( stream, key, type, value );
        }
    }
}


text:
const program = [
  {
    time: '8:00',
    kind: 'checkin',
    title: 'Check-in',
  },
  {
    time: '9:00',
    kind: 'opening',
    title: 'Abertura Oficial',
  },
  {
    time: '9:10',
    kind: 'talk',
    title: 'Um menino chamado JavaScripto',
    speaker: 'Juliana Negreiros',
    description:
      'Vamos fazer uma imersão na mente do javascripto e entender um pouco melhor o porquê de suas ações e, principalmente, como ter uma vida saudável com ele.',
  },
  {
    time: '9:50',
    kind: 'coffee',
    title: 'Coffee-break',
  },
  {
    time: '10:20',
    kind: 'talk',
    title: 'Tem um tipo no meu JavaScript',
    speaker: 'Matias Leidemer',
    description:
      'Com o advento das SPA (single page apps), o uso do Javascript não se limita apenas a validação de forms e chamadas ajax. Codificar regras de negócio complexas já faz parte do dia a dia de grande parte dos desenvolvedores JS. Mas, à medida que as linhas de código aumentam, como garantir que tudo está funcionando perfeitamente? Nesta talk falarei sobre tipagem estática em Javascript e como ela pode ajudar na diminuição de erros de runtime e na definição tipos específicos de negócio.',
  },
  {
    time: '11:00',
    kind: 'talk',
    title: 'CSS Animations under the hood',
    speaker: 'Rafael Dantas',
    description:
      'Tenho feito estudos profundos sobre animações com CSS e como o navegador trabalha para renderizar tudo na tela. Com uma linguagem simples e mais didática quero compartilhar minhas experiências e pretendo mostrar como o navegador entende as propriedades CSS que fazem as animações acontecerem, além disso vou falar do Composite Layer e Implicit Composite, a razão deles serem fundamentais e como isso tem impacto direto na performance das animações nos mais diferentes dispositivos. Quero também mostrar como fazer de uma maneira performática aproveitando o máximo dos navegadores, mas fazendo eles trabalharem menos, resultando em animações mais suaves e que rodam em dispositivos com menos poder computacional. Quero desmistificar as animações em CSS e mostrar que não é tão complicado e que é possível encontrar um equilíbrio entre sites/aplicações animadas e interativas com dispositivos menos potentes ou mais antigos. ',
  },
  {
    time: '12:00',
    kind: 'lunch',
    title: 'Almoço',
  },
  {
    time: '14:00',
    kind: 'talk',
    title: 'Primeiros passos com testes com Cypress',
    speaker: 'Thaiane Braga e Luine Gallois',
    description: `Uma das dores comuns em front é desenvolver testes para javascript. O Cypress é uma ferramenta que possibilita escrever testes unitários, integração e end-to-end de forma simples, rápida e legível`,
  },
  {
    time: '14:40',
    kind: 'talk',
    title: 'Design de Interfaces, entre a hibridez, os métodos e as práticas',
    speaker: 'Débora Gasparetto',
    description: `O design de interfaces é um campo interdisciplinar, que proporciona uma hibridez de profissionais, pesquisas, métodos e projetos. A proposta é abordar esse espaço comum por meio do método de projetação de interfaces 5I's, que parte do design centrado no usuário para proporcionar usabilidade, acessibilidade e adequadas experiências de usuário.`,
  },
  {
    time: '15:20',
    kind: 'talk',
    title: 'Estendendo CSS: uma intro a Houdini',
    speaker: 'Luiza Hagemann',
    description:
      'Uma talk expositiva sobre o novo conjunto de APIs do Houdini, mostrando um pouco da magia de finalmente poder interagir com a engine de renderização do browser.',
  },
  {
    time: '16:00',
    kind: 'coffee',
    title: 'Coffee-break',
  },
  {
    time: '16:30',
    kind: 'talk',
    title: 'Server Side Rendering @ globoplay',
    speaker: 'Isadora Possebon',
    description:
      'Uma talk que aborda os conceitos de Server Side Rendering vs Client Side Rendering. Vamos explorar esses pontos usando o Globoplay como caso de uso, explorando como funciona a arquitetura da famosa ferramenta de streaming de vídeos.',
  },
  {
    time: '17:10',
    kind: 'talk',
    title: 'Guia Prático para Desenvolver um Frontend Saudável',
    speaker: 'Igor Brandão',
    description:
      'O mundo todo sabe da genialidade e capacidade de improviso do povo brasileiro, e esse fato não é diferente com software - especialmente frontend - e isso é uma faca de dois gumes. Com orientação, resulta em soluções simples e elegantes; mas sem direcionamento, consolida aberrações difíceis de manter. A fim de complementar a saúde do desenvolvimento de frontend da galera, discuto nessa talk conceitos como padrões de projeto, técnicas comumente desprezadas e até mentalidades que trazem resultados positivos na prática e outros que possuem o efeito contrário (como over-engineering e code jealousy). Portanto e independente do nível técnico pessoal, chega mais que certamente há algo de produtivo para todos, de júnior a sênior.',
  },
  {
    time: '17:50',
    kind: 'closing',
    title: 'Encerramento',
  },
  {
    time: '19:00',
    kind: 'happyhour',
    title: 'Happy Hour!',
  },
]

export default program


text:
#include "radlib.h"
#include "radlib_private.h"

#ifndef PHP_RADIUS_H
#define PHP_RADIUS_H

#define phpext_radius_ptr &radius_module_entry

#define PHP_RADIUS_VERSION "1.3.0"

#ifdef PHP_WIN32
#define PHP_RADIUS_API __declspec(dllexport)
#else
#define PHP_RADIUS_API
#endif

#ifdef ZTS
#include "TSRM.h"
#endif

extern zend_module_entry radius_module_entry;

typedef struct {
	int id;
	struct rad_handle *radh;
} radius_descriptor;

PHP_MINIT_FUNCTION(radius);
PHP_MSHUTDOWN_FUNCTION(radius);
PHP_MINFO_FUNCTION(radius);

PHP_FUNCTION(radius_auth_open);
PHP_FUNCTION(radius_acct_open);
PHP_FUNCTION(radius_close);
PHP_FUNCTION(radius_strerror);
PHP_FUNCTION(radius_config);
PHP_FUNCTION(radius_add_server);
PHP_FUNCTION(radius_create_request);
PHP_FUNCTION(radius_put_string);
PHP_FUNCTION(radius_put_int);
PHP_FUNCTION(radius_put_attr);
PHP_FUNCTION(radius_put_addr);
PHP_FUNCTION(radius_put_vendor_string);
PHP_FUNCTION(radius_put_vendor_int);
PHP_FUNCTION(radius_put_vendor_attr);
PHP_FUNCTION(radius_put_vendor_addr);
PHP_FUNCTION(radius_send_request);
PHP_FUNCTION(radius_get_attr);
PHP_FUNCTION(radius_get_tagged_attr_data);
PHP_FUNCTION(radius_get_tagged_attr_tag);
PHP_FUNCTION(radius_get_vendor_attr);
PHP_FUNCTION(radius_cvt_addr);
PHP_FUNCTION(radius_cvt_int);
PHP_FUNCTION(radius_cvt_string);
PHP_FUNCTION(radius_salt_encrypt_attr);
PHP_FUNCTION(radius_request_authenticator);
PHP_FUNCTION(radius_server_secret);
PHP_FUNCTION(radius_demangle);
PHP_FUNCTION(radius_demangle_mppe_key);

#ifdef ZTS
#define RADIUS_G(v) TSRMG(radius_globals_id, zend_radius_globals *, v)
#else
#define RADIUS_G(v) (radius_globals.v)
#endif

#define RADIUS_OPTION_NONE	RAD_OPTION_NONE
#define RADIUS_OPTION_TAGGED	RAD_OPTION_TAG
#define RADIUS_OPTION_SALT	RAD_OPTION_SALT

#endif	/* PHP_RADIUS_H */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * indent-tabs-mode: t
 * End:
 */

/* vim: set ts=8 sw=8 noet: */


text:
Object include some methods witch difficult to type,
for resolve this problem I recommend you call these methods with
new schema type!

### 2.1) [object().camelCase()](https://github.com/jquense/yup/#objectcamelcase-schema)

```js
object({ a_aa_a: string() }).camelCase<{ aAaA: string }>()
```

### 2.2) [object().constantCase()](https://github.com/jquense/yup/#objectconstantcase-schema)

```js
object({ a_aa_a: string() }).constantCase<{ A_AA_A: string }>()
```

### 2.3) [object().from('from','to', false)](https://github.com/jquense/yup/#objectfromfromkey-string-tokey-string-alias-boolean--false-schema)

```js
object({ a: string() }).from<{ a2: string }>('a', 'a2');
```

## 3) `ref<T>('key')` not throw error

Example with mistake:

```js
const schema = object({
  a: object({
    b: number(),
  }),
  refB: ref<boolean>('a.b'), // here must be `number`
});

(schema: Schema<{ a: { b: number }, refB: boolean }, any>);
```

In example above I called `ref` with `boolean` type,
but it is wrong, because `a.b` declared as `number`

!! You should be very carefully when you change something


text:
A place to test out the various Google analytics code implementations

This project is designed to provide a basis to be able to implement the Transaction Code that is being sent by your platform to Google Analytics.

The code base attached includes the following tagging types:

### Enhanced Ecommerce Google Tag Manager Purchase and Refund Transactions

to use:

1. Update your Google Tag reference in the snippet below the opening Body tag
2. Review the sample code for each Purchase / Refund Transaction and compare to the code that is being outputted by the relevant platform.


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.autofill_assistant.header;

import android.content.Context;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;

import org.chromium.base.task.PostTask;
import org.chromium.chrome.autofill_assistant.R;
import org.chromium.chrome.browser.autofill_assistant.AssistantTagsForTesting;
import org.chromium.chrome.browser.autofill_assistant.AssistantTextUtils;
import org.chromium.chrome.browser.autofill_assistant.AutofillAssistantPreferenceFragment;
import org.chromium.chrome.browser.autofill_assistant.carousel.AssistantChipAdapter;
import org.chromium.chrome.browser.settings.SettingsLauncherImpl;
import org.chromium.components.browser_ui.settings.SettingsLauncher;
import org.chromium.components.browser_ui.widget.textbubble.TextBubble;
import org.chromium.content_public.browser.UiThreadTaskTraits;
import org.chromium.ui.modelutil.PropertyKey;
import org.chromium.ui.modelutil.PropertyModelChangeProcessor;
import org.chromium.ui.util.AccessibilityUtil;
import org.chromium.ui.widget.ViewRectProvider;

/**
 * This class is responsible for pushing updates to the Autofill Assistant header view. These
 * updates are pulled from the {@link AssistantHeaderModel} when a notification of an update is
 * received.
 */
class AssistantHeaderViewBinder
        implements PropertyModelChangeProcessor.ViewBinder<AssistantHeaderModel,
                AssistantHeaderViewBinder.ViewHolder, PropertyKey> {
    /** The amount of space to put between the top of the sheet and the bottom of the bubble.*/
    private static final int TEXT_BUBBLE_PIXELS_ABOVE_SHEET = 4;

    private final AccessibilityUtil mAccessibilityUtil;

    public AssistantHeaderViewBinder(AccessibilityUtil accessibilityUtil) {
        mAccessibilityUtil = accessibilityUtil;
    }

    /**
     * A wrapper class that holds the different views of the header.
     */
    static class ViewHolder {
        final Context mContext;
        final AnimatedPoodle mPoodle;
        final ViewGroup mHeader;
        final TextView mStatusMessage;
        final AssistantStepProgressBar mStepProgressBar;
        final ImageView mTtsButton;
        final View mProfileIconView;
        final PopupMenu mProfileIconMenu;
        final MenuItem mProfileIconMenuSettingsMessage;
        final MenuItem mProfileIconMenuSendFeedbackMessage;
        final RecyclerView mChipsContainer;
        @Nullable
        TextBubble mTextBubble;

        ViewHolder(Context context, ViewGroup headerView, AnimatedPoodle poodle,
                RecyclerView chipsContainer) {
            mContext = context;
            mPoodle = poodle;
            mHeader = headerView;
            mStatusMessage = headerView.findViewById(R.id.status_message);
            mStepProgressBar =
                    new AssistantStepProgressBar(headerView.findViewById(R.id.step_progress_bar));
            mTtsButton = (ImageView) headerView.findViewById(R.id.tts_button);
            mProfileIconView = headerView.findViewById(R.id.profile_image);
            mProfileIconMenu = new PopupMenu(context, mProfileIconView);
            mProfileIconMenu.inflate(R.menu.profile_icon_menu);
            mProfileIconMenuSettingsMessage = mProfileIconMenu.getMenu().findItem(R.id.settings);
            mProfileIconMenuSendFeedbackMessage =
                    mProfileIconMenu.getMenu().findItem(R.id.send_feedback);
            mProfileIconView.setOnClickListener(unusedView -> mProfileIconMenu.show());
            mChipsContainer = chipsContainer;
        }

        void disableAnimations(boolean disable) {
            mStepProgressBar.disableAnimations(disable);
            // Hiding the animated poodle seems to be the easiest way to disable its animation since
            // {@link LogoView#setAnimationEnabled(boolean)} is private.
            mPoodle.getView().setVisibility(View.INVISIBLE);
            ((DefaultItemAnimator) mChipsContainer.getItemAnimator())
                    .setSupportsChangeAnimations(!disable);
        }

        void updateProgressBarVisibility(boolean visible) {
            mStepProgressBar.setVisible(visible);
        }
    }

    @Override
    public void bind(AssistantHeaderModel model, ViewHolder view, PropertyKey propertyKey) {
        if (AssistantHeaderModel.STATUS_MESSAGE == propertyKey) {
            String message = model.get(AssistantHeaderModel.STATUS_MESSAGE);
            AssistantTextUtils.applyVisualAppearanceTags(view.mStatusMessage, message, null);
            view.mStatusMessage.announceForAccessibility(view.mStatusMessage.getText());
        } else if (AssistantHeaderModel.PROFILE_ICON_MENU_SETTINGS_MESSAGE == propertyKey) {
            view.mProfileIconMenuSettingsMessage.setTitle(
                    model.get(AssistantHeaderModel.PROFILE_ICON_MENU_SETTINGS_MESSAGE));
        } else if (AssistantHeaderModel.PROFILE_ICON_MENU_SEND_FEEDBACK_MESSAGE == propertyKey) {
            view.mProfileIconMenuSendFeedbackMessage.setTitle(
                    model.get(AssistantHeaderModel.PROFILE_ICON_MENU_SEND_FEEDBACK_MESSAGE));
        } else if (AssistantHeaderModel.PROGRESS_ACTIVE_STEP == propertyKey) {
            int activeStep = model.get(AssistantHeaderModel.PROGRESS_ACTIVE_STEP);
            if (activeStep >= 0) {
                view.mStepProgressBar.setActiveStep(activeStep);
            }
        } else if (AssistantHeaderModel.PROGRESS_BAR_ERROR == propertyKey) {
            view.mStepProgressBar.setError(model.get(AssistantHeaderModel.PROGRESS_BAR_ERROR));
        } else if (AssistantHeaderModel.PROGRESS_VISIBLE == propertyKey) {
            view.updateProgressBarVisibility(model.get(AssistantHeaderModel.PROGRESS_VISIBLE));
        } else if (AssistantHeaderModel.STEP_PROGRESS_BAR_ICONS == propertyKey) {
            view.mStepProgressBar.setSteps(model.get(AssistantHeaderModel.STEP_PROGRESS_BAR_ICONS));
            view.mStepProgressBar.disableAnimations(
                    model.get(AssistantHeaderModel.DISABLE_ANIMATIONS_FOR_TESTING));
        } else if (AssistantHeaderModel.SPIN_POODLE == propertyKey) {
            view.mPoodle.setSpinEnabled(model.get(AssistantHeaderModel.SPIN_POODLE));
        } else if (AssistantHeaderModel.FEEDBACK_BUTTON_CALLBACK == propertyKey) {
            setProfileMenuListener(view, model.get(AssistantHeaderModel.FEEDBACK_BUTTON_CALLBACK));
        } else if (AssistantHeaderModel.CHIPS == propertyKey) {
            view.mChipsContainer.invalidateItemDecorations();
            ((AssistantChipAdapter) view.mChipsContainer.getAdapter())
                    .setChips(model.get(AssistantHeaderModel.CHIPS));
            maybeShowChips(model, view);
        } else if (AssistantHeaderModel.CHIPS_VISIBLE == propertyKey) {
            maybeShowChips(model, view);
        } else if (AssistantHeaderModel.BUBBLE_MESSAGE == propertyKey) {
            showOrDismissBubble(model, view);
        } else if (AssistantHeaderModel.TTS_BUTTON_VISIBLE == propertyKey) {
            showOrHideTtsButton(model, view);
        } else if (AssistantHeaderModel.TTS_BUTTON_STATE == propertyKey) {
            setTtsButtonState(view, model.get(AssistantHeaderModel.TTS_BUTTON_STATE));
        } else if (AssistantHeaderModel.TTS_BUTTON_CALLBACK == propertyKey) {
            setTtsButtonClickListener(view, model.get(AssistantHeaderModel.TTS_BUTTON_CALLBACK));
        } else if (AssistantHeaderModel.DISABLE_ANIMATIONS_FOR_TESTING == propertyKey) {
            view.disableAnimations(model.get(AssistantHeaderModel.DISABLE_ANIMATIONS_FOR_TESTING));
        } else {
            assert false : "Unhandled property detected in AssistantHeaderViewBinder!";
        }
    }

    private void maybeShowChips(AssistantHeaderModel model, ViewHolder view) {
        // The PostTask is necessary as a workaround for the sticky button occasionally not showing,
        // this makes sure that the change happens after any possibly clashing animation currently
        // happening.
        // TODO(b/164389932): Figure out a better fix that doesn't require issuing the change in the
        // following UI iteration.
        PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> {
            if (model.get(AssistantHeaderModel.CHIPS_VISIBLE)
                    && !model.get(AssistantHeaderModel.CHIPS).isEmpty()) {
                view.mChipsContainer.setVisibility(View.VISIBLE);
                view.mProfileIconView.setVisibility(View.GONE);
            } else {
                view.mChipsContainer.setVisibility(View.GONE);
                view.mProfileIconView.setVisibility(View.VISIBLE);
            }
        });
    }

    private void setProfileMenuListener(ViewHolder view, @Nullable Runnable feedbackCallback) {
        view.mProfileIconMenu.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.settings) {
                SettingsLauncher settingsLauncher = new SettingsLauncherImpl();
                settingsLauncher.launchSettingsActivity(
                        view.mHeader.getContext(), AutofillAssistantPreferenceFragment.class);
                return true;
            } else if (itemId == R.id.send_feedback) {
                if (feedbackCallback != null) {
                    feedbackCallback.run();
                }
                return true;
            }

            return false;
        });
    }

    private void showOrDismissBubble(AssistantHeaderModel model, ViewHolder view) {
        String message = model.get(AssistantHeaderModel.BUBBLE_MESSAGE);
        if (message.isEmpty() && view.mTextBubble == null) {
            return;
        }
        if (message.isEmpty() && view.mTextBubble != null) {
            view.mTextBubble.dismiss();
            view.mTextBubble = null;
            return;
        }
        View poodle = view.mPoodle.getView();
        ViewRectProvider anchorRectProvider = new ViewRectProvider(poodle);
        int topOffset = view.mContext.getResources().getDimensionPixelSize(
                                R.dimen.autofill_assistant_root_view_top_padding)
                + TEXT_BUBBLE_PIXELS_ABOVE_SHEET;
        anchorRectProvider.setInsetPx(0, -topOffset, 0, 0);
        view.mTextBubble = new TextBubble(
                /*context = */ view.mContext, /*rootView = */ poodle, /*contentString = */ message,
                /*accessibilityString = */ message, /*showArrow = */ true,
                /*anchorRectProvider = */ anchorRectProvider,
                mAccessibilityUtil.isAccessibilityEnabled());
        view.mTextBubble.setDismissOnTouchInteraction(true);
        view.mTextBubble.show();
    }

    private void showOrHideTtsButton(AssistantHeaderModel model, ViewHolder view) {
        if (model.get(AssistantHeaderModel.TTS_BUTTON_VISIBLE)) {
            view.mTtsButton.setVisibility(View.VISIBLE);
        } else {
            view.mTtsButton.setVisibility(View.GONE);
        }
    }

    private void setTtsButtonClickListener(ViewHolder view, @Nullable Runnable ttsButtonCallback) {
        view.mTtsButton.setOnClickListener(unusedView -> {
            if (ttsButtonCallback != null) {
                ttsButtonCallback.run();
            }
        });
    }

    private void setTtsButtonState(ViewHolder view, @AssistantTtsButtonState int state) {
        switch (state) {
            case AssistantTtsButtonState.DEFAULT:
                view.mTtsButton.setImageResource(R.drawable.ic_volume_on_white_24dp);
                view.mTtsButton.setTag(AssistantTagsForTesting.TTS_ENABLED_ICON_TAG);
                break;
            case AssistantTtsButtonState.PLAYING:
                view.mTtsButton.setImageResource(R.drawable.ic_volume_on_white_24dp);
                view.mTtsButton.setTag(AssistantTagsForTesting.TTS_PLAYING_ICON_TAG);
                break;
            case AssistantTtsButtonState.DISABLED:
                view.mTtsButton.setImageResource(R.drawable.ic_volume_off_white_24dp);
                view.mTtsButton.setTag(AssistantTagsForTesting.TTS_DISABLED_ICON_TAG);
                break;
        }
    }
}