text:
import base64
import logging
import werkzeug

from openerp.addons.web import http
from openerp.exceptions import AccessError, UserError
from openerp.http import request
from openerp.tools.translate import _

_logger = logging.getLogger(__name__)

class website_slides(http.Controller):
    _slides_per_page = 12
    _slides_per_list = 20
    _order_by_criterion = {
        'date': 'date_published desc',
        'view': 'total_views desc',
        'vote': 'likes desc',
    }

    def _set_viewed_slide(self, slide, view_mode):
        slide_key = '%s_%s' % (view_mode, request.session_id)
        viewed_slides = request.session.setdefault(slide_key, list())
        if slide.id not in viewed_slides:
            if view_mode == 'slide':
                slide.sudo().slide_views += 1
            elif view_mode == 'embed':
                slide.sudo().embed_views += 1
            viewed_slides.append(slide.id)
            request.session[slide_key] = viewed_slides
        return True

    def _get_slide_detail(self, slide):
        most_viewed_slides = slide.get_most_viewed_slides(self._slides_per_list)
        related_slides = slide.get_related_slides(self._slides_per_list)
        return {
            'slide': slide,
            'most_viewed_slides': most_viewed_slides,
            'related_slides': related_slides,
            'user': request.env.user,
            'is_public_user': request.env.user == request.website.user_id,
            'comments': slide.channel_id.can_see_full and slide.website_message_ids or [],
            'private': not slide.channel_id.can_see_full,
        }

    # --------------------------------------------------
    # MAIN / SEARCH
    # --------------------------------------------------

    @http.route('/slides', type='http', auth="public", website=True)
    def slides_index(self, *args, **post):
        """ Returns a list of available channels: if only one is available,
            redirects directly to its slides
        """
        channels = request.env['slide.channel'].search([], order='sequence, id')
        if not channels:
            return request.website.render("website_slides.channel_not_found")
        elif len(channels) == 1:
            return request.redirect("/slides/%s" % channels.id)
        return request.website.render('website_slides.channels', {
            'channels': channels,
            'user': request.env.user,
            'is_public_user': request.env.user == request.website.user_id
        })

    @http.route([
        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>''',
        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/page/<int:page>''',

        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/<string:slide_type>''',
        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/<string:slide_type>/page/<int:page>''',

        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/tag/<model("slide.tag"):tag>''',
        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/tag/<model("slide.tag"):tag>/page/<int:page>''',

        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/category/<model("slide.category"):category>''',
        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/category/<model("slide.category"):category>/page/<int:page>''',

        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/category/<model("slide.category"):category>/<string:slide_type>''',
        '''/slides/<model("slide.channel", "[('can_see', '=', True)]"):channel>/category/<model("slide.category"):category>/<string:slide_type>/page/<int:page>'''],
        type='http', auth="public", website=True)
    def channel(self, channel, category=None, tag=None, page=1, slide_type=None, sorting='creation', search=None, **kw):
        user = request.env.user
        Slide = request.env['slide.slide']
        domain = [('channel_id', '=', channel.id)]
        pager_url = "/slides/%s" % (channel.id)
        pager_args = {}

        if search:
            domain += [
                '|', '|',
                ('name', 'ilike', search),
                ('description', 'ilike', search),
                ('index_content', 'ilike', search)]
            pager_args['search'] = search
        else:
            if category:
                domain += [('category_id', '=', category.id)]
                pager_url += "/category/%s" % category.id
            elif tag:
                domain += [('tag_ids.id', '=', tag.id)]
                pager_url += "/tag/%s" % tag.id
            if slide_type:
                domain += [('slide_type', '=', slide_type)]
                pager_url += "/%s" % slide_type

        if not sorting or sorting not in self._order_by_criterion:
            sorting = 'date'
        order = self._order_by_criterion[sorting]
        pager_args['sorting'] = sorting

        pager_count = Slide.search_count(domain)
        pager = request.website.pager(url=pager_url, total=pager_count, page=page,
                                      step=self._slides_per_page, scope=self._slides_per_page,
                                      url_args=pager_args)

        slides = Slide.search(domain, limit=self._slides_per_page, offset=pager['offset'], order=order)
        values = {
            'channel': channel,
            'category': category,
            'slides': slides,
            'tag': tag,
            'slide_type': slide_type,
            'sorting': sorting,
            'user': user,
            'pager': pager,
            'is_public_user': user == request.website.user_id,
            'display_channel_settings': not request.httprequest.cookies.get('slides_channel_%s' % (channel.id), False) and channel.can_see_full,
        }
        if search:
            values['search'] = search
            return request.website.render('website_slides.slides_search', values)

        # Display uncategorized slides
        if not slide_type and not category:
            category_datas = []
            for category in Slide.read_group(domain, ['category_id'], ['category_id']):
                category_id, name = category.get('category_id') or (False, _('Uncategorized'))
                category_datas.append({
                    'id': category_id,
                    'name': name,
                    'total': category['category_id_count'],
                    'slides': Slide.search(category['__domain'], limit=4, offset=0, order=order)
                })
            values.update({
                'category_datas': category_datas,
            })
        return request.website.render('website_slides.home', values)

    # --------------------------------------------------
    # SLIDE.SLIDE CONTOLLERS
    # --------------------------------------------------

    @http.route('''/slides/slide/<model("slide.slide", "[('channel_id.can_see', '=', True)]"):slide>''', type='http', auth="public", website=True)
    def slide_view(self, slide, **kwargs):
        values = self._get_slide_detail(slide)
        if not values.get('private'):
            self._set_viewed_slide(slide, 'slide')
        return request.website.render('website_slides.slide_detail_view', values)

    @http.route('''/slides/slide/<model("slide.slide", "[('channel_id.can_see', '=', True), ('datas', '!=', False), ('slide_type', '=', 'presentation')]"):slide>/pdf_content''', type='http', auth="public", website=True)
    def slide_get_pdf_content(self, slide):
        response = werkzeug.wrappers.Response()
        response.data = slide.datas and slide.datas.decode('base64') or ''
        response.mimetype = 'application/pdf'
        return response

    @http.route('''/slides/slide/<model("slide.slide", "[('channel_id.can_see', '=', True)]"):slide>/comment''', type='http', auth="public", methods=['POST'], website=True)
    def slide_comment(self, slide, **post):
        """ Controller for message_post. Public user can post; their name and
        email is used to find or create a partner and post as admin with the
        right partner. Their comments are not published by default. Logged
        users can post as usual. """
        # TDE TODO :
        # - subscribe partner instead of user writing the message ?
        # - public user -> cannot create mail.message ?
        if not post.get('comment'):
            return werkzeug.utils.redirect(request.httprequest.referrer + "#discuss")
        # public user: check or find author based on email, do not subscribe public user
        # and do not publish their comments by default to avoid direct spam
        if request.uid == request.website.user_id.id:
            if not post.get('email'):
                return werkzeug.utils.redirect(request.httprequest.referrer + "#discuss")
            # TDE FIXME: public user has no right to create mail.message, should
            # be investigated - using SUPERUSER_ID meanwhile
            contextual_slide = slide.sudo().with_context(mail_create_nosubcribe=True)
            # TDE FIXME: check in mail_thread, find partner from emails should maybe work as public user
            partner_id = slide.sudo()._find_partner_from_emails([post.get('email')])[0]
            if partner_id:
                partner = request.env['res.partner'].sudo().browse(partner_id)
            else:
                partner = request.env['res.partner'].sudo().create({
                    'name': post.get('name', post['email']),
                    'email': post['email']
                })
            post_kwargs = {
                'author_id': partner.id,
                'website_published': False,
                'email_from': partner.email,
            }
        # logged user: as usual, published by default
        else:
            contextual_slide = slide
            post_kwargs = {}

        contextual_slide.message_post(
            body=post['comment'],
            message_type='comment',
            subtype='mt_comment',
            **post_kwargs
        )
        return werkzeug.utils.redirect(request.httprequest.referrer + "#discuss")

    @http.route('''/slides/slide/<model("slide.slide", "[('channel_id.can_see', '=', True), ('download_security', '=', 'public')]"):slide>/download''', type='http', auth="public", website=True)
    def slide_download(self, slide):
        if slide.download_security == 'public' or (slide.download_security == 'user' and request.session.uid):
            filecontent = base64.b64decode(slide.datas)
            disposition = 'attachment; filename=%s.pdf' % werkzeug.urls.url_quote(slide.name)
            return request.make_response(
                filecontent,
                [('Content-Type', 'application/pdf'),
                 ('Content-Length', len(filecontent)),
                 ('Content-Disposition', disposition)])
        elif not request.session.uid and slide.download_security == 'user':
            return werkzeug.utils.redirect('/web?redirect=/slides/slide/%s' % (slide.id))
        return request.website.render("website.403")

    @http.route('''/slides/slide/<model("slide.slide"):slide>/promote''', type='http', auth='user', website=True)
    def slide_set_promoted(self, slide):
        slide.channel_id.promoted_slide_id = slide.id
        return request.redirect("/slides/%s" % slide.channel_id.id)

    # JSONRPC
    @http.route('/slides/slide/like', type='json', auth="user", website=True)
    def slide_like(self, slide_id):
        slide = request.env['slide.slide'].browse(int(slide_id))
        slide.likes += 1
        return slide.likes

    @http.route('/slides/slide/dislike', type='json', auth="user", website=True)
    def slide_dislike(self, slide_id):
        slide = request.env['slide.slide'].browse(int(slide_id))
        slide.dislikes += 1
        return slide.dislikes

    @http.route(['/slides/slide/send_share_email'], type='json', auth='user', website=True)
    def slide_send_share_email(self, slide_id, email):
        slide = request.env['slide.slide'].browse(int(slide_id))
        result = slide.send_share_email(email)
        return result

    @http.route('/slides/slide/overlay', type='json', auth="public", website=True)
    def slide_get_next_slides(self, slide_id):
        slide = request.env['slide.slide'].browse(int(slide_id))
        slides_to_suggest = 9

        def slide_mapped_dict(slide):
            return {
                'img_src': '/web/image/slide.slide/%s/image_thumb' % (slide.id),
                'caption': slide.name,
                'url': slide.website_url
            }
        vals = map(slide_mapped_dict, slide.get_related_slides(slides_to_suggest))
        add_more_slide = slides_to_suggest - len(vals)
        if max(add_more_slide, 0):
            vals += map(slide_mapped_dict, slide.get_most_viewed_slides(add_more_slide))
        return vals

    # --------------------------------------------------
    # TOOLS
    # --------------------------------------------------

    @http.route(['/slides/dialog_preview'], type='json', auth='user', methods=['POST'], website=True)
    def dialog_preview(self, **data):
        Slide = request.env['slide.slide']
        document_type, document_id = Slide._find_document_data_from_url(data['url'])
        preview = {}
        if not document_id:
            preview['error'] = _('Please enter valid youtube or google doc url')
            return preview
        existing_slide = Slide.search([('channel_id', '=', int(data['channel_id'])), ('document_id', '=', document_id)], limit=1)
        if existing_slide:
            preview['error'] = _('This video already exists in this channel <a target="_blank" href="/slides/slide/%s">click here to view it </a>') % existing_slide.id
            return preview
        values = Slide._parse_document_url(data['url'], only_preview_fields=True)
        if values.get('error'):
            preview['error'] = _('Could not fetch data from url. Document or access right not available.\nHere is the received response: %s') % values['error']
            return preview
        return values

    @http.route(['/slides/add_slide'], type='json', auth='user', methods=['POST'], website=True)
    def create_slide(self, *args, **post):
        payload = request.httprequest.content_length
        # payload is total request content size so it's not exact size of file.
        # already add client validation this is for double check if client alter.
        if (payload / 1024 / 1024 > 25):
            return {'error': _('File is too big. File size cannot exceed 25MB')}

        values = dict((fname, post[fname]) for fname in [
            'name', 'url', 'tag_ids', 'slide_type', 'channel_id',
            'mime_type', 'datas', 'description', 'image', 'index_content', 'website_published'] if post.get(fname))
        if post.get('category_id'):
            if post['category_id'][0] == 0:
                values['category_id'] = request.env['slide.category'].create({
                    'name': post['category_id'][1]['name'],
                    'channel_id': values.get('channel_id')}).id
            else:
                values['category_id'] = post['category_id'][0]

        # handle exception during creation of slide and sent error notification to the client
        # otherwise client slide create dialog box continue processing even server fail to create a slide.
        try:
            slide_id = request.env['slide.slide'].create(values)
        except (UserError, AccessError) as e:
            _logger.error(e)
            return {'error': e.name}
        except Exception as e:
            _logger.error(e)
            return {'error': _('Internal server error, please try again later or contact administrator.\nHere is the error message: %s') % e.message}
        return {'url': "/slides/slide/%s" % (slide_id.id)}

    # --------------------------------------------------
    # EMBED IN THIRD PARTY WEBSITES
    # --------------------------------------------------
    @http.route('/slides/embed/<int:slide_id>', type='http', auth='public', website=True)
    def slides_embed(self, slide_id, page="1", **kw):
        # Note : don't use the 'model' in the route (use 'slide_id'), otherwise if public cannot access the embedded
        # slide, the error will be the website.403 page instead of the one of the website_slides.embed_slide.
        # Do not forget the rendering here will be displayed in the embedded iframe

        # determine if it is embedded from external web page
        referrer_url = request.httprequest.headers.get('Referer', '')
        base_url = request.env['ir.config_parameter'].get_param('web.base.url')
        is_embedded = referrer_url and not bool(base_url in referrer_url) or False
        # try accessing slide, and display to corresponding template
        try:
            slide = request.env['slide.slide'].browse(slide_id)
            if is_embedded:
                request.env['slide.embed'].sudo().add_embed_url(slide.id, referrer_url)
            values = self._get_slide_detail(slide)
            values['page'] = page
            values['is_embedded'] = is_embedded
            if not values.get('private'):
                self._set_viewed_slide(slide, 'embed')
            return request.website.render('website_slides.embed_slide', values)
        except AccessError: # TODO : please, make it clean one day, or find another secure way to detect
                            # if the slide can be embedded, and properly display the error message.
            slide = request.env['slide.slide'].sudo().browse(slide_id)
            return request.website.render('website_slides.embed_slide_forbidden', {'slide': slide})


text:
package ru.job4j.tracker;

/**
 * Интерфейс ввода.
 */
public interface Input {

    /**
     * Структура запроса.
     * @param question - вопроса
     * @return - возврат
     */
    String ask(String question);

    /**
     * Сложная структура запроса.
     * @param question - вопрос
     * @param range - область ответа
     * @return - возращаемое значение
     */
    int ask(String question, int[] range);
}

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package de.fu_berlin.agdb.crepe.algebra.dsl;

import java.util.ArrayList;
import java.util.List;

import de.fu_berlin.agdb.crepe.algebra.Operator;
import de.fu_berlin.agdb.crepe.algebra.Profile;
import de.fu_berlin.agdb.crepe.algebra.notifications.Notification;
import de.fu_berlin.agdb.crepe.algebra.windows.EndlessWindow;
import de.fu_berlin.agdb.crepe.algebra.windows.IWindow;

/**
 * DSL for profiles.
 * @author Ralf Oechsner
 *
 */
public class ProfileBuilder {

	private static List<Profile> profileList;
	private static IWindow currentWindow;

	/**
	 * Starts block with profiles. Is used in profile files automatically by
	 * the ProfileLoader. Shouldn't be used by the user!
	 */
	public static void beginProfiles() {

		profileList = new ArrayList<Profile>();
		currentWindow = new EndlessWindow(); // default window - can be overwritten by user
	}

	/**
	 * Ends a block with profiles. Is used in profile files automatically by
	 * the ProfileLoader. Shouldn't be used by the user!
	 * @return list with profiles
	 */
	public static List<Profile> endProfiles() {

		// profile list is automatically emptied with the next beginProfiles
		// can't be emptied before because the list is still needed
		return profileList;
	}

	/**
	 * Creates a profile, which is automatically added to the algebra (if the function
	 * is used in a profile file which is loaded with ProfileLoader).
	 * @param rule rule of the profile
	 * @param notifications notification that is thrown when the rule matches
	 */
	public static void profile(Operator rule, Notification ... notifications) {

		Profile profile = new Profile(rule, currentWindow.newInstance(), notifications);

		profileList.add(profile);
	}

	/**
	 * Sets the window that used for the next profiles until the window is changed again or
	 * the profile file ends. Every profile file starts with an endless window as default.
	 * @param window window for profiles
	 */
	public static void setWindow(IWindow window) {

		currentWindow = window;
	}
}


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

<title>Uses of Class com.google.publicalerts.cap.Reasons.Builder (CAP Library)</title>
<meta name="date" content="2014-11-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.google.publicalerts.cap.Reasons.Builder

Packages that use Reasons.Builder

Package
Description

com.google.publicalerts.cap

This package contains the core classes that encode the CAP protocol as
 well as classes that can parse and write CAP messages from a variety of
 wire formats.

com.google.publicalerts.cap.feed

This package contains classes to parse and write feeds (Atom, RSS, and more)
 enclosing CAP messages.

com.google.publicalerts.cap.profile

This package contains classes that handle specific CAP profiles, which
 specify a set of extra constraints on the CAP format.

Uses of Reasons.Builder in com.google.publicalerts.cap

Methods in com.google.publicalerts.cap that return Reasons.Builder

Modifier and Type
Method and Description

Reasons.Builder
Reasons.Builder.add(Reason reason)

Adds a Reason object to the collection.

Reasons.Builder
Reasons.Builder.add(java.lang.String xPath,
   Reason.Type type,
   java.lang.Object... messageParams)

Adds a Reason object to the collection.

Reasons.Builder
Reasons.Builder.addAll(java.lang.Iterable<Reason> reasons)

Adds Reason objects to the collection.

static Reasons.Builder
Reasons.newBuilder()

Creates an object of type Reasons.Builder.

Methods in com.google.publicalerts.cap with parameters of type Reasons.Builder

Modifier and Type
Method and Description

Alert
CapXmlParser.parseFrom(org.xml.sax.InputSource is,
         Reasons.Builder reasons)

Parse the given alert.

Alert
CapXmlParser.parseFrom(java.io.Reader reader,
         Reasons.Builder reasons)

Parse the given alert.

Alert
CapXmlParser.parseFrom(java.lang.String str,
         Reasons.Builder reasons)

Parse the given alert.

protected Alert
CapXmlParser.parseFromInternal(CachedSaxInputSource is,
                 Reasons.Builder reasons)

Uses of Reasons.Builder in com.google.publicalerts.cap.feed

Methods in com.google.publicalerts.cap.feed with parameters of type Reasons.Builder

Modifier and Type
Method and Description

Alert
CapFeedParser.parseAlert(SyndEntry entry,
          Reasons.Builder reasons)

Parses the CAP alert assumed to be in the body of the first <content>
 entry.

Uses of Reasons.Builder in com.google.publicalerts.cap.profile

Methods in com.google.publicalerts.cap.profile with parameters of type Reasons.Builder

Modifier and Type
Method and Description

protected void
AbstractCapProfile.checkZeroTimezone(Reasons.Builder reasons,
                 java.lang.String dateStr,
                 java.lang.String xpath,
                 Reason.Type type)

Checks if the timezone on the given dateStr is zero.

protected Alert
AbstractCapProfile.parseFromInternal(CachedSaxInputSource is,
                 Reasons.Builder reasons)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
(function(exports)
{

// Strict mode by default
"use strict";

var request = require('request');

exports.Jiraffe = function(link, user, password)
{
    return {
        ctx:
        {
            link: link,
            user: user,
            password: password,
            timeout: 10000,
            api:  '/rest/api/latest/',
            auth: '/rest/auth/1/'
        },
        Initialize: function()
        {
            return this;
        },
        Terminate: function()
        {
            return this;
        },
        DoRequest: function(options, cbCommon, cbLogicOK, cbLogicFail)
        {
            var that = this,
                data = {};

            console.log('Jiraffe.DoRequest() URI:', options.uri);

            request(options, function(error, response, body)
            {
                if ( !error && response.statusCode === 200 )
                {
                    if ( typeof cbLogicOK === 'function' )
                    {
                        cbLogicOK.call(that, error, response, body);
                    }

                    data = body;
                }
                else
                {
                    var err = response && response.statusCode ? response.statusCode :
                                    error && error.errno ? error.errno : 'unknown';
                    console.log('Jiraffe.DoRequest() Error:', err);

                    if ( typeof cbLogicFail === 'function' )
                    {
                        cbLogicFail.call(that, error, response, body);
                    }
                }

                if ( typeof cbCommon === 'function' )
                {
                    cbCommon.call(that, data);
                }
            });
        },
        Login: function(cb)
        {
            var that = this,
                uri =
                [
                    this.ctx.link,
                    this.ctx.auth,
                    'session'
                ].join(''),
                options =
                {
                    timeout: this.ctx.timeout,
                    uri: uri,
                    method: 'POST',
                    json: true,
                    body:
                    {
                        'username': this.ctx.user,
                        'password': this.ctx.password
                    }
                };

            this.ctx.logged = false;

            this.DoRequest(options, cb,
                function OK(error, response, body)
                {
                    that.ctx.logged = true;
                    console.log('Jiraffe.Login() OK.');
                },
                function Failed(error, response, body)
                {
                    that.ctx.logged = false;
                    console.log('Jiraffe.Login() Error:', 'Failed.');
                }
            );

            return this;
        },
        Logout: function()
        {
            this.ctx.logged = false;
        },
        IsLoggedin: function()
        {
            return this.ctx.logged;
        },
        GetServerInfo: function(cb)
        {
            var that = this,
                uri =
                [
                    this.ctx.link,
                    this.ctx.api,
                    'serverInfo',
                ].join(''),
                options =
                {
                    timeout: this.ctx.timeout,
                    uri: uri,
                    method: 'GET',
                    json: true
                };

            if ( this.IsLoggedin() )
            {
                this.DoRequest(options, cb,
                    function OK(error, response, body)
                    {
                        console.log('Jiraffe.GetServerInfo() OK.');
                    },
                    function Failed(error, response, body)
                    {
                        console.log('Jiraffe.GetServerInfo() Error:', 'Failed.');
                    }
                );
            }

            return this;
        },
        GetUnresolvedIssueCountFor: function(id, cb)
        {
            var that = this,
                uri =
                [
                    this.ctx.link,
                    this.ctx.api,
                    'version',
                    '/', id, '/',
                    'unresolvedIssueCount'
                ].join(''),
                options =
                {
                    timeout: this.ctx.timeout,
                    uri: uri,
                    method: 'GET',
                    json: true
                };

            if ( this.IsLoggedin() )
            {
                this.DoRequest(options, cb,
                    function OK(error, response, body)
                    {
                        console.log('Jiraffe.GetUnresolvedIssueCountFor() OK.');
                    },
                    function Failed(error, response, body)
                    {
                        console.log('Jiraffe.GetUnresolvedIssueCountFor() Error:', 'Failed.');
                    }
                );
            }

            return this;
        },
        GetRelatedIssueCountFor: function(id, cb)
        {
            var that = this,
                uri =
                [
                    this.ctx.link,
                    this.ctx.api,
                    'version',
                    '/', id ,'/',
                    'relatedIssueCounts'
                ].join(''),
                options =
                {
                    timeout: this.ctx.timeout,
                    uri: uri,
                    method: 'GET',
                    json: true
                };

            if ( this.IsLoggedin() )
            {
                this.DoRequest(options, cb,
                    function OK(error, response, body)
                    {
                        console.log('Jiraffe.GetRelatedIssueCountFor() OK.');
                    },
                    function Failed(error, response, body)
                    {
                        console.log('Jiraffe.GetRelatedIssueCountFor() Error:', 'Failed.');
                    }
                );
            }

            return this;
        },
        GetIssue: function(id, cb)
        {
            var that = this,
                uri =
                [
                    this.ctx.link,
                    this.ctx.api,
                    'issue',
                    '/', id
                ].join(''),
                options =
                {
                    timeout: this.ctx.timeout,
                    uri: uri,
                    method: 'GET',
                    json: true
                };

            if ( this.IsLoggedin() )
            {
                this.DoRequest(options, cb,
                    function OK(error, response, body)
                    {
                        console.log('Jiraffe.GetIssue() OK.');
                    },
                    function Failed(error, response, body)
                    {
                        console.log('Jiraffe.GetIssue() Error:', 'Failed.');
                    }
                );
            }

            return this;
        },
        SearchWithJql: function(jql, start, max)
        {
            var jql = jql || '',
                start = start || 0,
                max = max || 100;
                that = this,
                uri =
                [
                    this.ctx.link,
                    this.ctx.api,
                    'search'
                ].join(''),
                options =
                {
                    timeout: this.ctx.timeout,
                    uri: uri,
                    method: 'POST',
                    json: true,
                    body:
                    {
                        'jql': jql,
                        'startAt': start,
                        'maxResults': max
                    }
                };

            if ( this.IsLoggedin() )
            {
                this.DoRequest(options, cb,
                    function OK(error, response, body)
                    {
                        console.log('Jiraffe.SearchWithJql() OK.');
                    },
                    function Failed(error, response, body)
                    {
                        console.log('Jiraffe.SearchWithJql() Error:', 'Failed.');
                    }
                );
            }

            return this;
        }
    };
};

})((typeof exports !== 'undefined' ? exports : this));


text:
package speakman.whatsshakingnz.ui.viewmodel;

import android.support.v7.widget.RecyclerView;
import android.view.View;

import speakman.whatsshakingnz.databinding.RowEarthquakeBinding;
import speakman.whatsshakingnz.databinding.RowEarthquakeBindingImpl;
import speakman.whatsshakingnz.databinding.RowEarthquakeBindingLandImpl;
import speakman.whatsshakingnz.model.Earthquake;
import timber.log.Timber;

/**
 * Created by Adam on 11/29/2015.
 */
@SuppressWarnings("unused")
public class EarthquakeListViewModel extends EarthquakeOverviewViewModel {

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public interface OnClickListener {
            void onEarthquakeClick(View v, Earthquake earthquake);
        }

        public final RowEarthquakeBinding binding;
        private final OnClickListener clickListener;
        public ViewHolder(RowEarthquakeBinding binding, OnClickListener clickListener) {
            super(binding.getRoot());
            this.binding = binding;
            this.clickListener = clickListener;
            this.itemView.setOnClickListener(this);
        }

        public void onClick(View v) {
            /*
            http://developer.android.com/tools/data-binding/guide.html
            "When there are different layout files for various configurations (e.g. landscape or
            portrait), the variables will be combined. There must not be conflicting variable
            definitions between these layout files."
            Turns out the DataBinding library (at least the version included in 23.1.1 support libs)
            forgets to generate a getter for the models in the binding abstract base class. It
            generates two impl files - one for each resource variant I've defined - but only the
            setter is accessible from the base class. For that reason, we figure out what type it
            is and then cast it appropriately so we can get access to the method.
             */
            Earthquake earthquake = null;
            if (this.binding instanceof RowEarthquakeBindingImpl) {
                earthquake = ((RowEarthquakeBindingImpl) this.binding).getEarthquakeModel().getEarthquake();
            } else if (this.binding instanceof RowEarthquakeBindingLandImpl) {
                earthquake = ((RowEarthquakeBindingLandImpl) this.binding).getEarthquakeModel().getEarthquake();
            }
            if (earthquake == null) {
                Timber.w("Unexpected view binding class {{ %s }}, list view item clicks will not work!", this.binding.getClass().getCanonicalName());
            } else {
                this.clickListener.onEarthquakeClick(v, earthquake);
            }
        }
    }

    public EarthquakeListViewModel(Earthquake earthquake) {
        super(earthquake);
    }
}


text:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';

import { UsefulLinksService } from './useful-links.service';

@Component({
  selector: 'useful-links',
  templateUrl: 'useful-links.html',
  styleUrls: ['useful-links.css'],
  encapsulation: ViewEncapsulation.None
})
export class UsefulLinksComponent implements OnInit {
  public nativeWindow: any;
  public currentUrl = window.location;
  public formVisitSearchUrl = '';

  public _links = [
    {
      url:
        'https://wiki.ampath.or.ke/display/POC/Versions+Of+POC+Troubleshooting+Manual',
      title: 'POC General Troubleshooting Manual (PDF)'
    },
    {
      url:
        'https://wiki.ampath.or.ke/display/ACPS/AMPATH+Clinical+Protocols+and+SOPs',
      title: 'AMPATH Clinical Protocols and SOPs'
    },
    {
      url: 'https://wiki.ampath.or.ke/display/ATG/AMPATH+TB+Guidelines+Home',
      title: 'TB Guidelines '
    },
    {
      url: 'https://wiki.ampath.or.ke/display/POC/POC+Release+Notes',
      title: 'POC Release Notes '
    },
    {
      url:
        'https://wiki.ampath.or.ke/display/POC/AMPATHPlus+Master+Facility+List+-+MFL',
      title: 'MFL Wiki'
    }
  ];
  constructor(private linksService: UsefulLinksService) {
    this.nativeWindow = linksService.getNativeWindow();
  }

  public ngOnInit() {
    this.getFormVisitSearchUrl();
  }

  public goToLink(link: string) {
    const newWindow = this.nativeWindow.open('/');
    newWindow.location.href = link;
  }

  public getFormVisitSearchUrl() {
    this.formVisitSearchUrl =
      this.currentUrl.href.split('useful-links')[0] + 'form-visit-search';

    this._links.push({
      url: this.formVisitSearchUrl + '',
      title: 'Information on Forms / Visit Type'
    });

    console.log('formvisiturl', this.formVisitSearchUrl);
  }

  public goBack() {
    this.nativeWindow.history.back();
  }

  public getexternalLinks(): Array<any> {
    return this._links;
  }
}


text:
package org.jbpm.workbench.cm.client.stages;

import com.google.common.collect.Lists;
import org.jbpm.workbench.cm.client.util.AbstractCaseInstancePresenterTest;
import org.jbpm.workbench.cm.util.CaseStageStatus;
import org.jbpm.workbench.cm.model.CaseDefinitionSummary;
import org.jbpm.workbench.cm.model.CaseInstanceSummary;
import org.jbpm.workbench.cm.model.CaseStageSummary;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.mocks.CallerMock;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class CaseStagesPresenterTest extends AbstractCaseInstancePresenterTest {

    @Mock
    CaseStagesPresenter.CaseStagesView caseStagesView;

    @InjectMocks
    CaseStagesPresenter presenter;

    @Override
    public CaseStagesPresenter getPresenter() {
        return presenter;
    }

    CaseInstanceSummary cis;
    final static String serverTemplateId = "serverTemplateId",
            containerId = "containerId",
            caseDefId ="caseDefinitionId",
            caseId = "caseId";

    private static CaseStageSummary createCaseStageSummary() {
        return CaseStageSummary.builder()
                .identifier("stage1")
                .name("stageName")
                .status(CaseStageStatus.AVAILABLE.getStatus())
                .build();
    }

    private static CaseInstanceSummary createCaseInstance() {
        return CaseInstanceSummary.builder()
                .caseId(caseId)
                .caseDefinitionId(caseDefId)
                .description("description")
                .status(1)
                .containerId(containerId)
                .stages(Lists.newArrayList(createCaseStageSummary()))
                .build();
    }

    @Before
    public void init() {
        cis = createCaseInstance();
        caseService = new CallerMock<>(caseManagementService);

        presenter.setCaseService(caseService);

        cis = CaseInstanceSummary.builder().containerId(containerId).caseId(caseId).caseDefinitionId(caseDefId).build();
        final CaseDefinitionSummary cds = CaseDefinitionSummary.builder().id(caseDefId).build();

        when(caseManagementService.getCaseDefinition(serverTemplateId, cis.getContainerId(), cis.getCaseDefinitionId())).thenReturn(cds);
        when(caseManagementService.getCaseInstance(serverTemplateId,containerId,caseId)).thenReturn(cis);
    }

    @Test
    public void testClearCaseInstance() {
        presenter.clearCaseInstance();

        verifyClearCaseInstance();
    }

    private void verifyClearCaseInstance() {
        verify(caseStagesView).removeAllStages();
    }

    @Test
    public void testLoadCaseInstance() {
        setupCaseInstance(cis, serverTemplateId);

        verifyClearCaseInstance();
        verify(caseStagesView).setCaseStagesList(cis.getStages());
    }

}


text:
from __future__ import print_function
from setuptools import setup

# Version
# N.B., this is versioned separately from rcomp clients
MAJOR = 0
MINOR = 1
MICRO = 0

rcomp_version = '{major}.{minor}.{micro}'.format(major=MAJOR, minor=MINOR, micro=MICRO)

with open('rcompserv/_version.py', 'w') as f:
    f.write("""# Automatically generated by setup.py of rcompserv. Do not edit.
version = '{version}'""".format(version=rcomp_version))

setup(name='rcompserv',
      version=rcomp_version,
      author='Scott C. Livingston',
      author_email='slivingston@cds.caltech.edu',
      url='https://github.com/slivingston/rcomp',
      license='BSD',
      description='',
      packages=['rcompserv'],
      install_requires=['aiohttp', 'redis'],
      entry_points={'console_scripts': ['rcompserv = rcompserv.cli:main']},
      classifiers=['Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.5']
      )


text:
package com.android.sdklib.devices;

import com.android.annotations.NonNull;

public class Camera {
    @NonNull
    private CameraLocation mLocation;
    private boolean mAutofocus;
    private boolean mFlash;

    /**
     * Creates a {@link Camera} with reasonable defaults.
     *
     * The resulting {@link Camera} with be on the {@link CameraLocation#BACK} with both autofocus
     * and flash.
     */
    public Camera() {
        this(CameraLocation.BACK, true, true);
    }

    /**
     * Creates a new {@link Camera} which describes an on device camera and it's features.
     * @param location The location of the {@link Camera} on the device. Either
     * {@link CameraLocation#FRONT} or {@link CameraLocation#BACK}.
     * @param autofocus Whether the {@link Camera} can auto-focus.
     * @param flash Whether the {@link Camera} has flash.
     */
    public Camera(@NonNull CameraLocation location, boolean autofocus, boolean flash) {
        mLocation = location;
        mAutofocus = autofocus;
        mFlash = flash;
    }

    @NonNull
    public CameraLocation getLocation() {
        return mLocation;
    }

    public void setLocation(@NonNull CameraLocation location) {
        mLocation = location;
    }

    public boolean hasAutofocus() {
        return mAutofocus;
    }

    public void setAutofocus(boolean hasAutofocus) {
        mAutofocus = hasAutofocus;
    }

    public boolean hasFlash() {
        return mFlash;
    }

    public void setFlash(boolean flash) {
        mFlash = flash;
    }

    /**
     * Returns a copy of the object that shares no state with it,
     * but is initialized to equivalent values.
     *
     * @return A copy of the object.
     */
    @NonNull
    public Camera deepCopy() {
        Camera c = new Camera();
        c.mLocation = mLocation;
        c.mAutofocus = mAutofocus;
        c.mFlash = mFlash;
        return c;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (!(o instanceof Camera)) {
            return false;
        }
        Camera c = (Camera) o;
        return mLocation == c.mLocation
                && mAutofocus == c.hasAutofocus()
                && mFlash == c.hasFlash();
    }

    @Override
    public int hashCode() {
        int hash = 17;
        hash = 31 * hash + mLocation.ordinal();
        hash = 31 * hash + (mAutofocus ? 1 : 0);
        hash = 31 * hash + (mFlash ? 1 : 0);
        return hash;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Camera <mLocation=");
        sb.append(mLocation);
        sb.append(", mAutofocus=");
        sb.append(mAutofocus);
        sb.append(", mFlash=");
        sb.append(mFlash);
        sb.append(">");
        return sb.toString();
    }

}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Rikrop.Core.Dataflow.Build;
using Rikrop.Core.Framework;
using Rikrop.Core.Framework.Exceptions;
using NUnit.Framework;
using Telerik.JustMock;

namespace Rikrop.Core.Dataflow.Tests
{
    [TestFixture, Ignore]
    public class TestScheduler
    {
        [Test]
        public void TestMethod2()
        {
            var exceptionHandler = Mock.Create<IExceptionHandler>();
            Mock.Arrange(() => exceptionHandler.Handle(null)).IgnoreArguments().Returns<Exception>(o =>
                                                                                {
                                                                                Console.WriteLine(o);
                                                                                return true;
                                                                                });

            var itemStore = new ItemStore();
            var uniqueQueue = new ItemsQueueContainer<ItemWithDate>();
            var infinityPipe = new InfinityPipe<ItemWithDate>(uniqueQueue);

            var dataflow = DataflowBuilder
                .StartFrom(infinityPipe)
                .ConvertItemsTo(o => new ScheduledTransmitterItem<int>(o.DateTime, o.Num, stopSchedule: o.Count == 4))
                .TransmitWith(o => o.ScheduledTransmitter(new DateTimeProvider(), exceptionHandler))
                .Transform(itemStore.GetItem)
                .BroadcastTo(t1 => t1.SendToTarget(new LoggingTarget<ItemWithDate>()),
                             t2 => t2.Transform(o =>
                                                    {
                                                        o.Count++;
                                                        o.DateTime = DateTime.Now.AddSeconds(o.Num + 1);
                                                        return o;
                                                    })
                                     .RouteTo(condition => condition.Case(o => o.Count == 4)
                                                                    .BroadcastTo(t21 => t21.SendToTarget(new DeleteTarget(itemStore)),
                                                                                t22 => t22.SendToTarget(infinityPipe)),

                                              condition => condition.Default()
                                                                    .BroadcastTo(t21 => t21.SendToTarget(new UpdateTarget(itemStore)),
                                                                                t22 => t22.SendToTarget(infinityPipe))))
                .Build();

            dataflow.Start();

            var items = itemStore.Load();
            foreach (var item in items)
            {
                infinityPipe.SendAsync(item).Wait();
            }

            Task.Delay(10000).Wait();
        }

    }

    public class UpdateTarget : ITarget<ItemWithDate>
    {
        private readonly ItemStore _itemStore;

        public UpdateTarget(ItemStore itemStore)
        {
            _itemStore = itemStore;
        }

        public Task SendAsync(ItemWithDate item)
        {
            return _itemStore.Update(item);
        }
    }

    public class DeleteTarget : ITarget<ItemWithDate>
    {
        private readonly ItemStore _itemStore;

        public DeleteTarget(ItemStore itemStore)
        {
            _itemStore = itemStore;
        }

        public Task SendAsync(ItemWithDate item)
        {
            return _itemStore.Delete(item);
        }
    }

    public class ItemStore
    {
        private readonly ConcurrentDictionary<int, ItemWithDate> _items = new ConcurrentDictionary<int, ItemWithDate>();

        public IReadOnlyCollection<ItemWithDate> Load()
        {
            foreach (var num in Enumerable.Range(0, 10))
            {
                _items.TryAdd(num, new ItemWithDate(num));
            }

            return _items.Values.ToArray();
        }

        public ItemWithDate GetItem(int num)
        {
            ItemWithDate item;
            if (_items.TryGetValue(num, out item))
            {
                return item;
            }

            throw new InvalidOperationException("!!!");
        }

        public Task Update(ItemWithDate item)
        {
            _items[item.Num] = item;
            return Task.FromResult(true);
        }

        public Task Delete(ItemWithDate item)
        {
            ItemWithDate temp;
            _items.TryRemove(item.Num, out temp);
            return Task.FromResult(true);
        }
    }

    public class DatabaseTarget : ITarget<ItemWithDate>
    {
        public Task SendAsync(ItemWithDate item)
        {
            return Task.FromResult(true);
        }
    }

    //public class ScheduledPipe<TItem> : IPipe<TItem>
    //{
    //    private readonly ITarget<TItem> _target;
    //    private readonly IPipe<TItem> _pipe;

    //    public ScheduledPipe(ITarget<TItem> target, IPipe<TItem> pipe)
    //    {
    //        _target = target;
    //        _pipe = pipe;
    //    }

    //    public Task<TItem> ReceiveAsync()
    //    {
    //        return _pipe.ReceiveAsync();
    //    }

    //    public Task SendAsync(TItem item)
    //    {
    //        _target.SendAsync(item);
    //        _pipe.SendAsync(item);
    //    }

    //    async Task<ScheduledTransmitterItem<TItem>> ISource<ScheduledTransmitterItem<TItem>>.ReceiveAsync()
    //    {
    //        var item = await ReceiveAsync();

    //        return new ScheduledTransmitterItem<TItem>(_dateExtractor.GetKey(item), item);
    //    }
    //}

    public class SchedulerSource : ISource<ItemWithDate>
    {
        private int _count;
        public Task<ItemWithDate> ReceiveAsync()
        {
            if (_count == 10)
            {
                return Task.FromResult<ItemWithDate>(null);
            }
            _count++;

            return Task.FromResult(new ItemWithDate(_count, DateTime.Now));
        }
    }

    public class ItemWithDate
    {
        private readonly int _num;
        private DateTime _dateTime;

        public ItemWithDate(int num)
        {
            _num = num;
            _dateTime = DateTime.Now.AddSeconds(num + 1);
        }

        public ItemWithDate(int num, DateTime dateTime)
        {
            _num = num;
            _dateTime = dateTime;
        }

        public DateTime DateTime
        {
            get { return _dateTime; }
        set { _dateTime = value; }
        }

        public int Num
        {
            get { return _num; }
        }

        public int Count { get; set; }

        public override string ToString()
        {
            return Num.ToString();
        }
    }
}


text:
title: "A website that doesn't exit"
layout: redirect
sitemap: false
permalink: "/2016-07-16-Golbat-Build-Log"
redirect_to:  "/keyboards/2016-07-16-Golbat-Build-Log"
---


text:
from aysncio import coroutine

from isperdal import Node as u
from isperdal.websocket import WebSocket

app = u('/')

@app.all()
class Ws(WebSocket):
    @coroutine
    def on_message(self, message):
        self.send(message)

app.run()


text:
package com.haulmont.cuba.web.widgets.client.fieldgroup;

import com.haulmont.cuba.web.widgets.client.groupbox.CubaGroupBoxState;

public class CubaFieldGroupState extends CubaGroupBoxState {
    {
        primaryStyleName = "c-fieldgroup";
    }

    public boolean borderVisible = false;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Pass: (1401) Species 's' is not defined. -->
<sbml xmlns="http://www.sbml.org/sbml/level2/version2" level="2" version="2">
	<model>
		<listOfCompartments>
			<compartment id="c"/>
		</listOfCompartments>
		<listOfSpecies>
			<species id="s" compartment="c"/>
		</listOfSpecies>
		<listOfReactions>
			<reaction id="r">
				<listOfReactants>
					<speciesReference species="s"/>
				</listOfReactants>
			</reaction>
		</listOfReactions>
	</model>
</sbml>


text:
namespace AngleSharp.Css.Tests.Parsing
{
    using AngleSharp.Css.Parser;
    using NUnit.Framework;
    using System.Threading.Tasks;

    [TestFixture]
    public class StyleSheet
    {
        [Test]
        public async Task ParseEmptySheet_Issue42()
        {
            var sheetCode = "";
            var parser = new CssParser();
            var sheet = await parser.ParseStyleSheetAsync(sheetCode);
            Assert.IsNotNull(sheet);
        }

        [Test]
        public async Task ParseStyleSheetAndBack_Issue82()
        {
            var css = @"
    .root {
        position: absolute;
        top: 0;
        left: 0;
        width: calc(100% - 10px);
        height: calc(100% - 10px);
        padding: 5px;
    }

    .container {
        width: 100%;
        height: 100%;
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-template-rows: 240px calc(100% - 360px) 100px;
        grid-template-areas: 'header info' 'quantity info' 'footerOk footerCancel';
        row-gap: 10px;
        font-size: 26px;
    }

    .destination {
        grid-area: header;
        width: calc(100% - 20px);
        height: calc(100% - 20px);
        margin: 10px;
        display: grid;
        grid-template-columns: auto auto auto;
        grid-template-rows: 150px 50px;
        grid-template-areas:
            ""sourcerp image destrp""
            ""sourcele image destle"";
    }

    .quantitygrid {
        width: 100%;
        height: 100%;
        display: grid;
        grid-template-columns: auto auto auto;
        grid-template-rows: 150px 100px;
        grid-template-areas: 'minus number plus';
    }

    .headergrid {
        width: 100%;
        height: 100%;
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-template-rows: 1fr 1fr;
        grid-template-areas: 'sourceplace space destinationplace' 'sourcelc space destinationlc';
    }

    #info td + td {
        font-size: 24px;
    }

    input {
        animation-duration: 2s;
        font-family: inherit;
        background-color: white;
    }

    td {
        padding: 5px;
    }

    paper-button {
        padding: 0;
        background-color: var(--kx-dark);
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        /*font-weight: bolder;*/
    }

    @keyframes errorAnimation {
        0% {
            background-color: white;
        }

        1% {
            background-color: red;
        }

        100% {
            background-color: white;
        }
    }

    input:invalid {
        color: red;
    }
";
            var parser = new CssParser();
            var formatter = new MinifyStyleFormatter();
            var ss = await parser.ParseStyleSheetAsync(css);
            var newCss = ss.ToCss(formatter);
            Assert.IsNotNull(newCss);
        }

        [Test]
        public async Task CastingException_Issue83()
        {
            var css = @"
 	.kardex-wrapper {
		height: 100vh;
		width: 100vw;
		display: grid;
		grid-template-rows: var(--header-height) 10px 1fr;
		grid-template-columns: var(--nav-width) 1fr;
		grid-template-areas: ""navheader header"" ""navheader content"" ""nav content"";
	}

	header {
		grid-area: header;
		font-family: KardexMOT-Light, sans-serif;
		background-color: var(--kx-bg);
		color: var(--kx-text-light);
		display: grid;
		grid-template-rows: var(--header-height);
		grid-template-columns: 1fr 1fr 1fr;
	}
";
            var parser = new CssParser();
            var formatter = new MinifyStyleFormatter();
            var ss = await parser.ParseStyleSheetAsync(css);
            var newCss = ss.ToCss(formatter);
            Assert.IsNotNull(newCss);
        }
    }
}


text:
package com.hannesdorfmann.mosby.retrofit.mock;

import retrofit.Callback;

/**
 * @author Hannes Dorfmann
 */
public interface TestApi {

  public void loadData(Callback<Object> callback);
}


text:
package brainslug.jpa;

import brainslug.jpa.migration.DatabaseMigration;
import brainslug.jpa.spring.SpringDatabaseConfiguration;
import brainslug.jpa.spring.SpringDatabaseMigrationConfiguration;
import brainslug.jpa.spring.SpringHibernateConfiguration;
import brainslug.spring.SpringBrainslugConfiguration;
import brainslug.util.IdGenerator;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import static org.mockito.Mockito.mock;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
  TestDataSourceConfiguration.class,
  SpringHibernateConfiguration.class,
  SpringDatabaseConfiguration.class,
  SpringDatabaseMigrationConfiguration.class,
  SpringBrainslugConfiguration.class
})
@Transactional
public abstract class AbstractDatabaseTest {

  @Autowired
  Database database;

  @Autowired
  DatabaseMigration databaseMigration;

  IdGenerator idGeneratorMock = mock(IdGenerator.class);
}


text:
package org.apache.qpid.jms.transports;

import io.netty.buffer.ByteBuf;

/**
 * Listener interface that should be implemented by users of the various
 * QpidJMS Transport classes.
 */
public interface TransportListener {

    /**
     * Called when new incoming data has become available.
     *
     * @param incoming
     *        the next incoming packet of data.
     */
    void onData(ByteBuf incoming);

    /**
     * Called if the connection state becomes closed.
     */
    void onTransportClosed();

    /**
     * Called when an error occurs during normal Transport operations.
     *
     * @param cause
     *        the error that triggered this event.
     */
    void onTransportError(Throwable cause);

}


text:
<!DOCTYPE html>
{% load media cms blog google_cse google_analytics %}

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>{% block title %}{% endblock %} | {{ site_name }}</title>
    {% block blogfeeds %}
      {% blog_feeds %}
    {% endblock %}
    {% block css %}
      {% include_media 'main.css' %}
    {% endblock %}

    {% block preload_js %}
      {% google_analytics_code %}
    {% endblock %}

    {% block extra-head %}{% endblock %}

      {% google_search_form %}

        {% show_menu %}

        {% block content-header %}
          {% if error %}
{{ error }}
{% endif %}
          {% if info %}
{{ info }}
{% endif %}
          {% if messages %}
            {% for message in messages %}

{{ message }}

            {% endfor %}
          {% endif %}
        {% endblock %}

        {% block content %}{% endblock %}

        {% block sidebar %}
          {% show_block 'sidebar' %}
        {% endblock %}

        Copyright {% now "Y" %} {{ site_copyright }}

        Powered by Django-nonrel,
        App Engine, and
        All Buttons Pressed

    {% block js %}
    {% endblock %}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the HubKit package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace HubKit\Tests\Unit\Helper;

use HubKit\Helper\BranchAliasResolver;
use HubKit\Service\Git\GitConfig;
use HubKit\Tests\Handler\SymfonyStyleTrait;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;

/**
 * @internal
 */
final class BranchAliasResolverTest extends TestCase
{
    use ProphecyTrait;
    use SymfonyStyleTrait;

    public const FIXTURES_DIR = __DIR__ . '/../../Fixtures';

    /** @var string */
    public $outputString = '';

    /** @test */
    public function it_get_alias_from_composer(): void
    {
        $style = $this->createStyle();
        $git = $this->givenGitAliasIsNotCalled();

        $resolver = new BranchAliasResolver($style, $git, self::FIXTURES_DIR . '/project_with_composer_alias');

        self::assertEquals('1.0-dev', $resolver->getAlias());
        self::assertEquals('composer.json "extra.branch-alias.dev-master"', $resolver->getDetectedBy());
        $this->assertNoOutput();
    }

    private function givenGitAliasIsNotCalled(): GitConfig
    {
        $gitProphecy = $this->prophesize(GitConfig::class);
        $gitProphecy->getGitConfig('branch.master.alias')->shouldNotBeCalled();

        return $gitProphecy->reveal();
    }

    /** @test */
    public function it_get_alias_as_stable_when_alias_is_pre_release(): void
    {
        $style = $this->createStyle();
        $git = $this->givenGitAliasIsNotCalled();

        $resolver = new BranchAliasResolver($style, $git, self::FIXTURES_DIR . '/project_with_composer_unstable_alias');

        self::assertEquals('1.0-dev', $resolver->getAlias());
        self::assertEquals('composer.json "extra.branch-alias.dev-master"', $resolver->getDetectedBy());
        $this->assertNoOutput();
    }

    /** @test */
    public function it_get_alias_from_git(): void
    {
        $style = $this->createStyle();
        $git = $this->givenGitAliasIs('2.0-dev');

        $resolver = new BranchAliasResolver($style, $git, self::FIXTURES_DIR);

        self::assertEquals('2.0-dev', $resolver->getAlias());
        self::assertEquals('Git config "branch.master.alias"', $resolver->getDetectedBy());
        $this->assertNoOutput();
    }

    /** @test */
    public function it_get_alias_from_git_if_composer_alias_is_absent(): void
    {
        $style = $this->createStyle();
        $git = $this->givenGitAliasIs('2.0-dev');

        $resolver = new BranchAliasResolver($style, $git, self::FIXTURES_DIR . '/project_with_composer');

        self::assertEquals('2.0-dev', $resolver->getAlias());
        self::assertEquals('Git config "branch.master.alias"', $resolver->getDetectedBy());
    }

    private function givenGitAliasIs(string $alias): GitConfig
    {
        $gitProphecy = $this->prophesize(GitConfig::class);
        $gitProphecy->getGitConfig('branch.master.alias')->willReturn($alias);

        return $gitProphecy->reveal();
    }

    /** @test */
    public function it_sets_alias_for_git(): void
    {
        $style = $this->createStyle(['3.0']);
        $git = $this->createGitConfigSpy();

        $resolver = new BranchAliasResolver($style, $git, self::FIXTURES_DIR);

        self::assertEquals('3.0-dev', $resolver->getAlias());
        self::assertEquals('Git config "branch.master.alias"', $resolver->getDetectedBy());
        self::assertEquals(['branch.master.alias' => '3.0-dev'], $git->configsSet);
    }

    private function createGitConfigSpy()
    {
        $git = new class() extends GitConfig {
            public $configsSet = [];

            public function __construct()
            {
                // Overwritten
            }

            public function getGitConfig(string $config, string $section = 'local', bool $all = false): string
            {
                Assert::assertEquals('branch.master.alias', $config);

                return '';
            }

            public function setGitConfig(string $config, $value, bool $overwrite = false, string $section = 'local'): void
            {
                $this->configsSet[$config] = $value;
            }
        };

        return $git;
    }

    /** @test */
    public function it_validates_alias_for_git(): void
    {
        $style = $this->createStyle(['stable', '4.0']);
        $git = $this->createGitConfigSpy();

        $resolver = new BranchAliasResolver($style, $git, self::FIXTURES_DIR);

        self::assertEquals('4.0-dev', $resolver->getAlias());
        self::assertEquals('Git config "branch.master.alias"', $resolver->getDetectedBy());
        self::assertEquals(['branch.master.alias' => '4.0-dev'], $git->configsSet);

        $this->assertOutputMatches('A branch alias consists of major and minor version without any prefix or suffix. like: 1.2');
    }
}


text:
layout: article
title: "Buenavista"
subtitle: "Rivas, Costa Rica"
categories: episode travel
excerpt: ""
author: matthey
tags: []
youtube_id: "WQpd8Q9BSMI"
image:
  cover: travel/buenavista-cover.jpg
comments: true
---


text:
module SpaceFrame
  module Generators
    class SectionGenerator < SpaceFrame::Generators::NamedBase
      source_root File.expand_path('templates', File.dirname(__FILE__))

      attr_reader   :controller_name,
                    :view_name,
                    :model_name

      def initialize(*args)
        super(*args)
        @logger = Logger.new STDOUT

        if @name == @name.pluralize && !options[:force_plural]
          @logger.info "You selected a plural resource name. It's best to use the singular version. Override with --force-plural"
          @name = @name.singularize
        end

        @controller_name = plural_table_name
        @view_name = plural_table_name
        @model_name = singular_table_name
      end

      def generate_section
        directory "app", "app/assets/javascripts/app"

        insert_into_file "app/assets/javascripts/app/main.coffee",
                         "    @#{@controller_name} = new App.#{@controller_name.camelize}.Section()",
                         :after =>"super\n"

        gsub_file "app/assets/javascripts/app/main.coffee", /\@sections = \[(.*)\]/ do |match|
          puts match.to_s
          match = /\@sections = \[(.*)\]/.match(match.to_s)
          puts "match: #{match[1]}"

          if match == "sections = []"
            "@sections = [@#{@controller_name}]"
          else
            sections = match[1].split(",")
            sections << "@#{@controller_name}" unless sections.include?("@#{@controller_name}")
            "@sections = [#{sections.join(',')}]"
          end
        end

        #process other templates
      end

      def add_root_route
        route(%Q{root :to => "#{@controller_name}#index"})
      end

    end
  end
end


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Nytt Mag. Natur. 7: 229 (1853)

#### Original name
Trachyderma Norman

### Remarks
null


text:
module Hanami
  module Utils
    # Class utilities
    # @since 0.1.0
    class Class
      # Loads a class for the given name.
      #
      # @param name [String, Class] the specific class name
      # @param namespace [Class, Module] the Ruby namespace where we want to perform the lookup.
      # @return [Class, Module] the found Ruby constant.
      #
      # @raise [NameError] if no constant can be found.
      #
      # @since 0.1.0
      #
      # @example
      #   require 'hanami/utils/class'
      #
      #   module App
      #     module Service
      #       class Endpoint
      #       end
      #     end
      #
      #     class ServiceEndpoint
      #     end
      #   end
      #
      #   # basic usage
      #   Hanami::Utils::Class.load!('App::Service') # => App::Service
      #   Hanami::Utils::Class.load!(App::Service)   # => App::Service
      #
      #   # with explicit namespace
      #   Hanami::Utils::Class.load!('Service', App) # => App::Service
      #
      #   # with missing constant
      #   Hanami::Utils::Class.load!('Unknown') # => raises NameError
      def self.load!(name, namespace = Object)
        namespace.const_get(name.to_s, false)
      end

      # Loads a class for the given name, only if it's defined.
      #
      # @param name [String, Class] the specific class name
      # @param namespace [Class, Module] the Ruby namespace where we want to perform the lookup.
      # @return [Class, Module, NilClass] the Ruby constant, or nil if not found.
      #
      # @since 0.8.0
      #
      # @example
      #   require 'hanami/utils/class'
      #
      #   module App
      #     module Service
      #       class Endpoint
      #       end
      #     end
      #
      #     class ServiceEndpoint
      #     end
      #   end
      #
      #   # basic usage
      #   Hanami::Utils::Class.load('App::Service') # => App::Service
      #   Hanami::Utils::Class.load(App::Service)   # => App::Service
      #
      #   # with explicit namespace
      #   Hanami::Utils::Class.load('Service', App) # => App::Service
      def self.load(name, namespace = Object)
        load!(name, namespace) if namespace.const_defined?(name.to_s, false)
      end
    end
  end
end


text:
package net.bytebuddy.instrumentation.attribute.annotation;

import net.bytebuddy.instrumentation.type.TypeDescription;
import net.bytebuddy.matcher.FilterableList;

import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * Defines a list of annotation instances.
 */
public interface AnnotationList extends FilterableList<AnnotationDescription, AnnotationList> {

    /**
     * Checks if this list contains an annotation of the given type.
     *
     * @param annotationType The type to find in the list.
     * @return {@code true} if the list contains the annotation type.
     */
    boolean isAnnotationPresent(Class<? extends Annotation> annotationType);

    /**
     * Checks if this list contains an annotation of the given type.
     *
     * @param annotationType The type to find in the list.
     * @return {@code true} if the list contains the annotation type.
     */
    boolean isAnnotationPresent(TypeDescription annotationType);

    /**
     * Finds the first annotation of the given type and returns it.
     *
     * @param annotationType The type to be found in the list.
     * @param <T>            The annotation type.
     * @return The annotation value or {@code null} if no such annotation was found.
     */
    <T extends Annotation> AnnotationDescription.Loadable<T> ofType(Class<T> annotationType);

    /**
     * Returns only annotations that are marked as {@link java.lang.annotation.Inherited} as long as they are not
     * contained by the set of ignored annotation types.
     *
     * @param ignoredTypes A list of annotation types to be ignored from the lookup.
     * @return A list of all inherited annotations besides of the given ignored types.
     */
    AnnotationList inherited(Set<? extends TypeDescription> ignoredTypes);

    /**
     * Describes an array of loaded {@link java.lang.annotation.Annotation}s as an annotatoon list.
     */
    class ForLoadedAnnotation extends AbstractBase<AnnotationDescription, AnnotationList> implements AnnotationList {

        /**
         * The represented annotations.
         */
        private final Annotation[] annotation;

        /**
         * Creates a new list of loaded annotations.
         *
         * @param annotation The represented annotations.
         */
        public ForLoadedAnnotation(Annotation... annotation) {
            this.annotation = annotation;
        }

        /**
         * Creates a list of annotation lists representing the given loaded annotations.
         *
         * @param annotations The annotations to represent where each dimension is converted into a list.
         * @return A list of annotation lists representing the given annotations.
         */
        public static List<AnnotationList> asList(Annotation[][] annotations) {
            List<AnnotationList> result = new ArrayList<AnnotationList>(annotations.length);
            for (Annotation[] annotation : annotations) {
                result.add(new ForLoadedAnnotation(annotation));
            }
            return result;
        }

        @Override
        public AnnotationDescription get(int index) {
            return AnnotationDescription.ForLoadedAnnotation.of(annotation[index]);
        }

        @Override
        public int size() {
            return annotation.length;
        }

        @Override
        public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
            for (Annotation anAnnotation : annotation) {
                if (anAnnotation.annotationType().equals(annotationType)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean isAnnotationPresent(TypeDescription annotationType) {
            for (Annotation anAnnotation : annotation) {
                if (annotationType.represents(anAnnotation.getClass())) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public <T extends Annotation> AnnotationDescription.Loadable<T> ofType(Class<T> annotationType) {
            for (Annotation anAnnotation : annotation) {
                if (anAnnotation.annotationType().equals(annotationType)) {
                    return AnnotationDescription.ForLoadedAnnotation.of(annotationType.cast(anAnnotation));
                }
            }
            return null;
        }

        @Override
        public AnnotationList inherited(Set<? extends TypeDescription> ignoredTypes) {
            List<Annotation> inherited = new LinkedList<Annotation>();
            for (Annotation annotation : this.annotation) {
                if (!ignoredTypes.contains(new TypeDescription.ForLoadedType(annotation.annotationType()))
                        && annotation.annotationType().isAnnotationPresent(Inherited.class)) {
                    inherited.add(annotation);
                }
            }
            return new ForLoadedAnnotation(inherited.toArray(new Annotation[inherited.size()]));
        }

        @Override
        protected AnnotationList wrap(List<AnnotationDescription> values) {
            return new Explicit(values);
        }
    }

    /**
     * Represents a list of explicitly provided annotation descriptions.
     */
    class Explicit extends AbstractBase<AnnotationDescription, AnnotationList> implements AnnotationList {

        /**
         * The list of represented annotation descriptions.
         */
        private final List<? extends AnnotationDescription> annotationDescriptions;

        /**
         * Creates a new list of annotation descriptions.
         *
         * @param annotationDescriptions The list of represented annotation descriptions.
         */
        public Explicit(List<? extends AnnotationDescription> annotationDescriptions) {
            this.annotationDescriptions = annotationDescriptions;
        }

        /**
         * Creates a list of annotation lists for a given multidimensional list of annotation descriptions.
         *
         * @param annotations The list of annotations to represent as a list of annotation lists.
         * @return The list of annotation lists.
         */
        public static List<AnnotationList> asList(List<? extends List<? extends AnnotationDescription>> annotations) {
            List<AnnotationList> result = new ArrayList<AnnotationList>(annotations.size());
            for (List<? extends AnnotationDescription> annotation : annotations) {
                result.add(new Explicit(annotation));
            }
            return result;
        }

        @Override
        public AnnotationDescription get(int index) {
            return annotationDescriptions.get(index);
        }

        @Override
        public int size() {
            return annotationDescriptions.size();
        }

        @Override
        public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
            for (AnnotationDescription annotationDescription : annotationDescriptions) {
                if (annotationDescription.getAnnotationType().represents(annotationType)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean isAnnotationPresent(TypeDescription annotationType) {
            for (AnnotationDescription annotationDescription : annotationDescriptions) {
                if (annotationDescription.getAnnotationType().equals(annotationType)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public <T extends Annotation> AnnotationDescription.Loadable<T> ofType(Class<T> annotationType) {
            for (AnnotationDescription annotationDescription : annotationDescriptions) {
                if (annotationDescription.getAnnotationType().represents(annotationType)) {
                    return annotationDescription.prepare(annotationType);
                }
            }
            return null;
        }

        @Override
        public AnnotationList inherited(Set<? extends TypeDescription> ignoredTypes) {
            List<AnnotationDescription> inherited = new LinkedList<AnnotationDescription>();
            for (AnnotationDescription annotation : annotationDescriptions) {
                TypeDescription annotationType = annotation.getAnnotationType();
                if (!ignoredTypes.contains(annotationType) && annotationType.getDeclaredAnnotations().isAnnotationPresent(Inherited.class)) {
                    inherited.add(annotation);
                }
            }
            return new Explicit(new ArrayList<AnnotationDescription>(inherited));
        }

        @Override
        protected AnnotationList wrap(List<AnnotationDescription> values) {
            return new Explicit(values);
        }
    }

    /**
     * Represents an empty annotation list.
     */
    class Empty extends FilterableList.Empty<AnnotationDescription, AnnotationList> implements AnnotationList {

        /**
         * Creates a list of empty annotation lists of the given dimension.
         *
         * @param length The length of the list.
         * @return A list of empty annotation lists of the given length.
         */
        public static List<AnnotationList> asList(int length) {
            List<AnnotationList> result = new ArrayList<AnnotationList>(length);
            for (int i = 0; i < length; i++) {
                result.add(new AnnotationList.Empty());
            }
            return result;
        }

        @Override
        public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
            return false;
        }

        @Override
        public boolean isAnnotationPresent(TypeDescription annotationType) {
            return false;
        }

        @Override
        public <T extends Annotation> AnnotationDescription.Loadable<T> ofType(Class<T> annotationType) {
            return null;
        }

        @Override
        public AnnotationList inherited(Set<? extends TypeDescription> ignoredTypes) {
            return this;
        }
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe ThorLogger do
  context "after module is included" do
    subject{VanillaTest}
    it {subject.class_options.keys.should include(:color)}
    it {subject.class_options.keys.should include(:logfile)}
    it {subject.class_options.keys.should include(:loglevel)}
    it {subject.class_options.keys.should include(:silent)}
    it {subject.class_options.keys.should include(:quiet)}
    it {subject.class_options.keys.should include(:verbose)}
    it {subject.class_options.keys.should include(:debug)}
  end

  context "instance has methods from module" do
    subject{VanillaTest.new}
    it {should respond_to(:logger)}
    it {should respond_to(:setup_logger)}
  end

end


text:
package tamaized.aov.common.core.abilities.druid;

import net.minecraft.client.resources.I18n;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.util.DamageSource;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import tamaized.aov.AoV;
import tamaized.aov.common.capabilities.CapabilityList;
import tamaized.aov.common.capabilities.aov.IAoVCapability;
import tamaized.aov.common.capabilities.polymorph.IPolymorphCapability;
import tamaized.aov.common.core.abilities.Ability;
import tamaized.aov.common.core.abilities.AbilityBase;
import tamaized.aov.common.core.abilities.IAura;
import tamaized.aov.registry.AoVParticles;
import tamaized.aov.registry.ParticleRegistry;
import tamaized.aov.registry.SoundEvents;

import javax.annotation.Nullable;
import java.util.List;

public class ElementalEmpowerment extends AbilityBase implements IAura {

	private static final String UNLOC = "aov.spells.elementalempowerment";
	private static final float DAMAGE = 1F;
	private static final float RANGE = 4F;
	private static final int CHARGES = 2;

	private static final ResourceLocation ICON = new ResourceLocation(AoV.MODID, "textures/spells/elementalempowerment.png");

	public ElementalEmpowerment() {
		super(

				new TranslationTextComponent(UNLOC.concat(".name")),

				new TranslationTextComponent(""),

				new TranslationTextComponent("aov.spells.global.charges", CHARGES),

				new TranslationTextComponent("aov.spells.global.range", RANGE),

				new TranslationTextComponent("aov.spells.global.damage", DAMAGE),

				new TranslationTextComponent(""),

				new TranslationTextComponent(UNLOC.concat(".desc"))

		);
	}

	@Override
	@OnlyIn(Dist.CLIENT)
	public String getName() {
		return I18n.format(UNLOC.concat(".name"));
	}

	@Override
	public int getMaxCharges() {
		return CHARGES;
	}

	@Override
	public int getChargeCost() {
		return 1;
	}

	@Override
	public double getMaxDistance() {
		return RANGE;
	}

	@Override
	public int getCoolDown() {
		return 90;
	}

	@Override
	public boolean usesInvoke() {
		return false;
	}

	@Override
	public boolean isCastOnTarget(PlayerEntity caster, IAoVCapability cap, LivingEntity target) {
		return false;
	}

	@Override
	public boolean shouldDisable(@Nullable PlayerEntity caster, IAoVCapability cap) {
		IPolymorphCapability poly = CapabilityList.getCap(caster, CapabilityList.POLYMORPH);
		return poly == null || (poly.getMorph() != IPolymorphCapability.Morph.FireElemental && poly.getMorph() != IPolymorphCapability.Morph.WaterElemental);
	}

	@Override
	public boolean cast(Ability ability, PlayerEntity caster, LivingEntity target) {
		IAoVCapability cap = CapabilityList.getCap(caster, CapabilityList.AOV);
		if (cap == null)
			return false;
		IPolymorphCapability poly = CapabilityList.getCap(caster, CapabilityList.POLYMORPH);
		if (poly != null) {
			switch (poly.getMorph()) {
				case WaterElemental:
				case FireElemental:
					cap.addAura(createAura(ability));
					SoundEvents.playMovingSoundOnServer(SoundEvents.aura, caster);
					return true;
				default:
					return false;
			}
		}
		return false;
	}

	@Override
	public ResourceLocation getIcon() {
		return ICON;
	}

	@Override
	public void castAsAura(PlayerEntity caster, IAoVCapability cap, int life) {
		IPolymorphCapability poly = CapabilityList.getCap(caster, CapabilityList.POLYMORPH);
		if (poly != null) {
			switch (poly.getMorph()) {
				case WaterElemental:
					ParticleRegistry.spawnFromServer(caster.world, AoVParticles.SNOW, caster.posX + caster.world.rand.nextDouble() * 1.5F - 0.75F, caster.posY + caster.getEyeHeight() - 0.25F + caster.world.rand.nextDouble() * 1.5F - 0.75F, caster.posZ + caster.world.rand.nextDouble() * 1.5F - 0.75F, 0, -0.03F, 0);
					break;
				case FireElemental:
					caster.world.addParticle(ParticleTypes.FLAME, caster.posX + caster.world.rand.nextDouble() * 1.5F - 0.75F, caster.posY + caster.getEyeHeight() - 0.25F + caster.world.rand.nextDouble() * 1.5F - 0.75F, caster.posZ + caster.world.rand.nextDouble() * 1.5F - 0.75F, 0, 0, 0);
					float damage = DAMAGE * (1F + (cap.getSpellPower() / 100F));
					if (life > 0 && life % (3 * 20) == 0) {
						List<LivingEntity> list = caster.world.getEntitiesWithinAABB(LivingEntity.class, new AxisAlignedBB(caster.getPosition().add(-RANGE, -RANGE, -RANGE), caster.getPosition().add(RANGE, RANGE, RANGE)));
						for (LivingEntity entity : list) {
							if (IAoVCapability.selectiveTarget(caster, cap, entity) && entity.attackEntityFrom(DamageSource.IN_FIRE, damage)) {
								entity.setFire(5);
								cap.addExp(caster, 20, this);
							}
						}
					}
					break;
				default:
					break;
			}
		}
	}

	@Override
	public int getLife() {
		return 45;
	}
}


text:
// checking for references to static symbols in template

static int static_function (int i) { return i; }
static int static_function (double d) { return int (d); }

template <class T>
int foo (T t)
{
    // check whether static functions can be called from
    // a function template ( EDG eccp in strict mode or
    // SunPro do not allow it -- see PR #25961)
    return static_function (t);
}

int main ()
{
    foo (0);
    foo (0.0);
}


text: An IRC bot that searches baka-updates and batoto, among other sources


text:
var express   = require('express'),
    http      = require('http'),
    engine    = require('ejs-locals'),
    request   = require('request'),
    futures   = require('futures'),
    http      = require('http'),
    fs        = require('fs'),
    colors    = require('colors'),
    config    = require('config'),
    utilities = require('./utilities');

var app = express();

var requirements = {
    futures: futures,
    request: request
};

var urlHelper = {
    meal: function (id) {
        return '/meal/' + id;
    }
};

utilities.moment = require('moment');
utilities.moment.lang('de');

utilities.url = urlHelper;

app.set('config', config);
app.set('utilities', utilities);
app.set('requirements', requirements);

process.on('uncaughtException', function (error) {
    utilities.handleError(error);
});

/**
 * Request alive status
 *
 * Lets check if the app is already running
 */

request({
    uri     :  config.api.uri + '/alive',
    method  : 'GET'
}, function (error, response) {
    if(typeof response === 'undefined' || response.statusCode !== 418) {
        console.log();
        console.error('Please start the API app. "cd ../../ && node app"'.red);
        console.log();
        process.exit();
    }
});

// controllers - setup
// ----------------------------------------------------------------------

var controllers = {
    user    : require('./controllers/user.js')(app),
    order   : require('./controllers/order.js')(app),
    meal    : require('./controllers/meal.js')(app)
};

app.set('controllers', controllers);

// routes - setup
// ----------------------------------------------------------------------

var routes  = {
    user    : require('./routes/user.js')(app),
    order   : require('./routes/order.js')(app),
    meal    : require('./routes/meal.js')(app)
};

// express - config
// ----------------------------------------------------------------------

app.configure(function(){

    app.engine('ejs', engine);
    app.set('port', config.port);

    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');

    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser('dawuH27)"&e2g769dshw'));
    app.use(express.session());
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

app.configure('development', function () {
    app.use(express.errorHandler());
});

// app locals
// ----------------------------------------------------------------------

app.locals.config      = config;
app.locals.utilities   = utilities;

app.locals.global = {};

var updateInterval = function () {

    controllers.meal.getMeals(function (meals) {
        app.locals.global.meals = meals;
    });

    controllers.meal.getVotes(function (votes) {
        app.locals.global.votes = votes;
    });

    console.log(utilities.moment().format('HH:ss') + ' – Updated: max votes, meal search index');
};

updateInterval();

setInterval(updateInterval, 20000);

// routes - user
// ----------------------------------------------------------------------

app.post('/login', routes.user.login);
app.get('/login', routes.user.renderLogin);
app.get('/logout', routes.user.logout);

// routes - order
// ----------------------------------------------------------------------

app.get('/account/orders/?:page?', routes.user.checkLogin, routes.order.renderOrdersByUser);
app.get('/orders/?:date?/', routes.user.checkLogin, routes.order.renderOrders);

// routes - meal
// ----------------------------------------------------------------------

app.get('/meal/:id', routes.user.checkLogin, routes.meal.renderMeal);
app.get('/meals/?:page?', routes.user.checkLogin, function (req, res, next) {
    if (typeof req.param('page') == 'string') {
        req.filter = req.param('page');
    }
    next();
}, routes.meal.renderMeals);
app.get('/meals/:filter/:value/:page?', routes.user.checkLogin, routes.meal.renderMeals);

// routes - general
// ----------------------------------------------------------------------

app.get('/faq', function (req, res) {
    res.render('faq', {
        session : req.session
    });
});

app.get('/', routes.user.checkLogin, function (req, res, next) {

    var seq = new futures.sequence();

    seq

    .then(function (next, user_orders) {

        request({
            uri     : config.api.uri + '/meals/',
            method  : 'GET',
            qs      : {
                sort: 'votes',
                order: 'desc',
                limit: 5
            }
        }, function (error, response, body) {

            if(error) utilities.handleError(error);

            var meals_trending = JSON.parse(body) || [];

            console.log(meals_trending);

            next(user_orders, meals_trending);

        });
    })

    .then(function (next, user_orders, meals_trending) {

        request({
            uri     : config.api.uri + '/orders/',
            method  : 'GET',
            qs      : {
                limit: 5,
                order: 'desc'
            }
        }, function (error, response, body) {

            if(error) utilities.handleError(error);

            var orders_last = JSON.parse(body) || [];

            next(user_orders, meals_trending, orders_last);
        });
    })

    .then(function (next, user_orders, meals_trending, orders_last, meals_trending_maxvotes) {

        res.render('index', {
            session   : req.session,

            user_orders     : user_orders,
            meals_trending  : meals_trending,
            orders_last     : orders_last
        });
    });
});

app.use(function (req, res) {

    res.status(404);

    if (req.accepts('html')) {
        res.render('404', {
            session : req.session
        });
        return;
    }

    if (req.accepts('json')) {
        res.send({ error: 'Not found' });
        return;
    }

    // default to plain-text. send()
    res.type('txt').send('Not found');
});

http.createServer(app).listen(app.get('port'), function(){
  console.log("HTTP: " + app.get('port'));
});