text:
// Copyright 2021 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.fonts;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.SystemClock;

import androidx.core.content.res.ResourcesCompat;
import androidx.core.content.res.ResourcesCompat.FontCallback;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.LooperMode.Mode;
import org.robolectric.annotation.Resetter;
import org.robolectric.shadows.ShadowSystemClock;

import org.chromium.base.metrics.test.ShadowRecordHistogram;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.chrome.browser.fonts.FontPreloaderUnitTest.ShadowResourcesCompat;

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

/**
 * Unit tests for {@link FontPreloader}.
 */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE,
        shadows = {ShadowSystemClock.class, ShadowResourcesCompat.class,
                ShadowRecordHistogram.class})
@LooperMode(Mode.PAUSED)
public class FontPreloaderUnitTest {
    private static final Integer[] FONTS = {org.chromium.chrome.R.font.chrome_google_sans,
            org.chromium.chrome.R.font.chrome_google_sans_medium,
            org.chromium.chrome.R.font.chrome_google_sans_bold};
    private static final String AFTER_ON_CREATE =
            "Android.Fonts.TimeToRetrieveDownloadableFontsAfterOnCreate";
    private static final String AFTER_INFLATION =
            "Android.Fonts.TimeDownloadableFontsRetrievedAfterPostInflationStartup";
    private static final String BEFORE_INFLATION =
            "Android.Fonts.TimeDownloadableFontsRetrievedBeforePostInflationStartup";
    private static final String FRE = ".FirstRunActivity";
    private static final String TABBED = ".ChromeTabbedActivity";
    private static final String CUSTOM_TAB = ".CustomTabActivity";
    private static final int INITIAL_TIME = 1000;

    @Mock
    private Context mContext;

    private FontPreloader mFontPreloader;

    @Implements(ResourcesCompat.class)
    static class ShadowResourcesCompat {
        private static final List<Integer> sFontsRequested = new ArrayList<>();
        private static FontCallback sFontCallback;

        @Resetter
        public static void reset() {
            sFontsRequested.clear();
            sFontCallback = null;
        }

        @Implementation
        public static void getFont(
                Context context, int id, FontCallback fontCallback, Handler handler) {
            sFontCallback = fontCallback;
            sFontsRequested.add(id);
        }

        public static void loadFont() {
            sFontCallback.onFontRetrieved(Typeface.DEFAULT);
        }
    }

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        SystemClock.setCurrentTimeMillis(INITIAL_TIME);
        ShadowRecordHistogram.reset();
        ShadowResourcesCompat.reset();
        when(mContext.getApplicationContext()).thenReturn(mContext);
        mFontPreloader = new FontPreloader(FONTS);
        mFontPreloader.load(mContext);
    }

    @Test
    public void testGetFontCalledForAllFontsInArray() {
        assertThat(ShadowResourcesCompat.sFontsRequested, containsInAnyOrder(FONTS));
    }

    @Test
    public void testAllFontsRetrievedAfterOnPostInflationStartup_FRE() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 100);
        mFontPreloader.onPostInflationStartupFre();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 228);
        fakeLoadAllFonts();

        assertHistogramRecorded(AFTER_ON_CREATE, 228);
        assertHistogramRecorded(AFTER_INFLATION + FRE, 128);
        assertHistogramNotRecorded(BEFORE_INFLATION + FRE);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
        assertHistogramNotRecorded(AFTER_INFLATION + TABBED);
        assertHistogramNotRecorded(BEFORE_INFLATION + CUSTOM_TAB);
        assertHistogramNotRecorded(AFTER_INFLATION + CUSTOM_TAB);
    }

    @Test
    public void testAllFontsRetrievedAfterOnPostInflationStartup_Tabbed() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 100);
        mFontPreloader.onPostInflationStartupTabbedActivity();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 200);
        fakeLoadAllFonts();

        assertHistogramRecorded(AFTER_ON_CREATE, 200);
        assertHistogramRecorded(AFTER_INFLATION + TABBED, 100);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
        assertHistogramNotRecorded(BEFORE_INFLATION + FRE);
        assertHistogramNotRecorded(AFTER_INFLATION + FRE);
        assertHistogramNotRecorded(BEFORE_INFLATION + CUSTOM_TAB);
        assertHistogramNotRecorded(AFTER_INFLATION + CUSTOM_TAB);
    }

    @Test
    public void testAllFontsRetrievedAfterOnPostInflationStartup_CustomTab() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 100);
        mFontPreloader.onPostInflationStartupCustomTabActivity();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 150);
        fakeLoadAllFonts();

        assertHistogramRecorded(AFTER_ON_CREATE, 150);
        assertHistogramRecorded(AFTER_INFLATION + CUSTOM_TAB, 50);
        assertHistogramNotRecorded(BEFORE_INFLATION + CUSTOM_TAB);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
        assertHistogramNotRecorded(AFTER_INFLATION + TABBED);
        assertHistogramNotRecorded(BEFORE_INFLATION + FRE);
        assertHistogramNotRecorded(AFTER_INFLATION + FRE);
    }

    @Test
    public void testAllFontsRetrievedBeforeOnPostInflationStartup_FRE() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 150);
        fakeLoadAllFonts();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 200);
        mFontPreloader.onPostInflationStartupFre();

        assertHistogramRecorded(AFTER_ON_CREATE, 150);
        assertHistogramRecorded(BEFORE_INFLATION + FRE, 50);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
        assertHistogramNotRecorded(AFTER_INFLATION + TABBED);
        assertHistogramNotRecorded(AFTER_INFLATION + FRE);
        assertHistogramNotRecorded(BEFORE_INFLATION + CUSTOM_TAB);
        assertHistogramNotRecorded(AFTER_INFLATION + CUSTOM_TAB);
    }

    @Test
    public void testAllFontsRetrievedBeforeOnPostInflationStartup_Tabbed() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 5);
        fakeLoadAllFonts();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 555);
        mFontPreloader.onPostInflationStartupTabbedActivity();

        assertHistogramRecorded(AFTER_ON_CREATE, 5);
        assertHistogramRecorded(BEFORE_INFLATION + TABBED, 550);
        assertHistogramNotRecorded(AFTER_INFLATION + TABBED);
        assertHistogramNotRecorded(BEFORE_INFLATION + FRE);
        assertHistogramNotRecorded(AFTER_INFLATION + FRE);
        assertHistogramNotRecorded(BEFORE_INFLATION + CUSTOM_TAB);
        assertHistogramNotRecorded(AFTER_INFLATION + CUSTOM_TAB);
    }

    @Test
    public void testAllFontsRetrievedBeforeOnPostInflationStartup_CustomTab() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 123);
        fakeLoadAllFonts();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 234);
        mFontPreloader.onPostInflationStartupCustomTabActivity();

        assertHistogramRecorded(AFTER_ON_CREATE, 123);
        assertHistogramRecorded(BEFORE_INFLATION + CUSTOM_TAB, 111);
        assertHistogramNotRecorded(AFTER_INFLATION + CUSTOM_TAB);
        assertHistogramNotRecorded(BEFORE_INFLATION + FRE);
        assertHistogramNotRecorded(AFTER_INFLATION + FRE);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
        assertHistogramNotRecorded(AFTER_INFLATION + TABBED);
    }

    @Test
    public void testHistogramsNotRecordedBeforeAllFontsLoaded() {
        ShadowResourcesCompat.loadFont();
        ShadowResourcesCompat.loadFont();

        assertHistogramNotRecorded(AFTER_ON_CREATE);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
        assertHistogramNotRecorded(AFTER_INFLATION + TABBED);
        assertHistogramNotRecorded(BEFORE_INFLATION + FRE);
        assertHistogramNotRecorded(AFTER_INFLATION + FRE);
        assertHistogramNotRecorded(BEFORE_INFLATION + CUSTOM_TAB);
        assertHistogramNotRecorded(AFTER_INFLATION + CUSTOM_TAB);

        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 500);
        ShadowResourcesCompat.loadFont();

        assertHistogramRecorded(AFTER_ON_CREATE, 500);
    }

    @Test
    public void testHistogramRecordedForOnlyOneActivity_BeforeFREInflation() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 10);
        fakeLoadAllFonts();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 20);
        mFontPreloader.onPostInflationStartupFre();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 30);
        mFontPreloader.onPostInflationStartupTabbedActivity();

        assertHistogramRecorded(BEFORE_INFLATION + FRE, 10);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
    }

    @Test
    public void testHistogramRecordedForOnlyOneActivity_AfterFREInflation() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 64);
        mFontPreloader.onPostInflationStartupFre();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 96);
        fakeLoadAllFonts();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 128);
        mFontPreloader.onPostInflationStartupTabbedActivity();

        assertHistogramRecorded(AFTER_INFLATION + FRE, 32);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
    }

    @Test
    public void testHistogramRecordedForOnlyOneActivity_BeforeCCTInflation() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 1);
        fakeLoadAllFonts();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 11);
        mFontPreloader.onPostInflationStartupCustomTabActivity();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 111);
        mFontPreloader.onPostInflationStartupTabbedActivity();

        assertHistogramRecorded(BEFORE_INFLATION + CUSTOM_TAB, 10);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
    }

    @Test
    public void testHistogramRecordedForOnlyOneActivity_AfterCCTInflation() {
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 32);
        mFontPreloader.onPostInflationStartupCustomTabActivity();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 64);
        fakeLoadAllFonts();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 128);
        mFontPreloader.onPostInflationStartupTabbedActivity();

        assertHistogramRecorded(AFTER_INFLATION + CUSTOM_TAB, 32);
        assertHistogramNotRecorded(BEFORE_INFLATION + TABBED);
    }

    @Test
    public void testHistogramNotOverEmittedForExtraFontLoads() {
        mFontPreloader.onPostInflationStartupTabbedActivity();
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 10);
        fakeLoadAllFonts();

        assertHistogramRecorded(AFTER_ON_CREATE, 10);
        assertHistogramRecorded(AFTER_INFLATION + TABBED, 10);

        // Load an extra font
        ShadowResourcesCompat.loadFont();
        // Still should have only 1 record.
        SystemClock.setCurrentTimeMillis(INITIAL_TIME + 10);
        assertHistogramRecorded(AFTER_INFLATION + TABBED, 10);
    }

    private void fakeLoadAllFonts() {
        for (int i = 0; i < 3; i++) {
            ShadowResourcesCompat.loadFont();
        }
    }

    /**
     * @param histogram Histogram name to assert.
     * @param expectedValue The expected value to be recorded.
     */
    private void assertHistogramRecorded(String histogram, int expectedValue) {
        assertEquals(histogram + " isn't recorded correctly.", 1,
                ShadowRecordHistogram.getHistogramValueCountForTesting(histogram, expectedValue));
    }

    /**
     * @param histogram Histogram name to assert.
     */
    private void assertHistogramNotRecorded(String histogram) {
        assertEquals(histogram + " shouldn't be recorded.", 0,
                ShadowRecordHistogram.getHistogramTotalCountForTesting(histogram));
    }
}


text:
from __future__ import division

import numpy as np
np.set_printoptions(precision=3, suppress=True)

import scipy as sci
import scipy.interpolate

from vehicle_core.path import trajectory_tools as tt
from vehicle_core.util import conversions as cnv

# default config
DEFAULT_TOLERANCES = np.array([
    1.0,                # meters
    1.0,                # meters
    1.0,                # meters
    np.deg2rad(45),     # radians
    np.deg2rad(45),     # radians
    np.deg2rad(6)       # radians
])

FAST_SPEED = 1.0        # m/s
FAST_LOOKAHEAD = 5.0    # meters
LINE_SPACING = 10       # meters

class PathStrategy(object):
    """PathStrategy is the base class for any path navigation strategies. It implements all the common features required
    by other modes, like initialization of waypoint lists, total and cumulative distances, tolerances and status.

    This class shouldn't be used directly as it doesn't provide any form of navigation capability.
    """

    def __init__(self, points, position, **kwargs):
        # internal status
        self.cnt = 1                    # start always from one (default to first requested waypoint)
        self.des_pos = position         # initialize with current position
        self.des_vel = np.ones(6)       # initialize with normalized speeds
        self.dis_axis = np.zeros(6)     # initialize with empty disable mask

        # keep track of trajectory
        #   - add the current waypoint (last known position)
        #   - (optimize) remove possible duplicates
        #   - (safety) wrap angle
        self.points = np.concatenate((position.reshape(1, 6), points), axis=0)
        self.points = tt.remove_repeated_points(self.points)
        self.points[:, 3:6] = cnv.wrap_pi(self.points[:, 3:6])

        # calculate distances
        self.cum_distances = tt.cumulative_distance(self.points, spacing_dim=3)
        self.total_distance = self.cum_distances[-1]

        # NOTE: position tolerances should be passed as a numpy array (or single scalar)
        #   thus it should be parsed by upper modules and not provided directly from the ROS messages/services as strings
        self.tolerances = kwargs.get('tolerances', DEFAULT_TOLERANCES)

        # path status
        self.path_completed = False

    def distance_left(self, position=None):
        return self.cum_distances[-1] - self.distance_completed(position)

    def distance_completed(self, position=None):
        """Calculate the distance along the trajectory covered so far. The distance between the last point (A)
        and current position (B) is calculated by projecting the displacement vector (A-B) on vector representing
        the distance between last point (A) and target point (C). The maximum of this distance is |AC|. Then
        distance from the start of the path to point A is added.

        :param position: numpy array of shape (6)
        :return: float - distance in meters
        """
        current_wp = self.points[self.cnt - 1]
        prev_wp = self.points[self.cnt - 2]
        added_distance = 0

        if position is not None:
            vehicle_direction = (position[0:3] - prev_wp[0:3])
            trajectory_direction = (current_wp[0:3] - prev_wp[0:3])

            if np.linalg.norm(trajectory_direction) != 0:
                added_distance = np.dot(vehicle_direction, trajectory_direction) / np.linalg.norm(trajectory_direction)

        return self.cum_distances[self.cnt - 2] + added_distance

    def calculate_position_error(self, current_position, desired_position):
        error = current_position - desired_position
        error[3:6] = cnv.wrap_pi(error[3:6])
        return error

    def update(self, position, velocity):
        pass

    def __str__(self):
        pass

class SimpleStrategy(PathStrategy):
    """SimpleStrategy provides the basic navigation functionality where the vehicle is requested to adjust its attitude as soon
    as the following waypoint is requested. If these are close enough this mode can help in maintaining sensor pointing.

    This mode is useful for its precise positioning. However it lacks efficiency thus its use is limited to precise manoeuvring
    during inspection tasks or short position changes.
    """

    def __init__(self, points, position, **kwargs):
        super(SimpleStrategy, self).__init__(points, position, **kwargs)

        # set disable axis mask (simple mode is using all dofs)
        self.dis_axis = np.zeros(6)

    def update(self, position, velocity):
        if self.cnt >= len(self.points):
            self.des_pos = self.points[-1]
            return

        self.des_pos = self.points[self.cnt]
        self.error_position = self.calculate_position_error(position, self.des_pos)

        if np.all(np.abs(self.error_position) < self.tolerances):
            self.cnt += 1

            if self.cnt < len(self.points):
                # print 'WP reached, moving to the next one'
                pass
            else:
                self.path_completed = True
                self.des_pos = self.points[-1]

class LineStrategy(PathStrategy):
    """LineStrategy provides a line-of-sight navigation mode where the vehicle visit all the path waypoint achieving the
    requested attitude (RPY) but travelling using forward navigation among them, thus implementing a rotate-first approach.

    This mode is useful for its good trade-off between precise positioning and efficient navigation due to
    forward navigation. It make use of the concept of waypoint proximity to adjust the requested attitude when close to
    each requested waypoint.
    """

    def __init__(self, points, position, **kwargs):
        super(LineStrategy, self).__init__(points, position, **kwargs)

        # config
        self.spacing = float(kwargs.get('spacing', LINE_SPACING))
        self.points = tt.interpolate_trajectory(self.points, self.spacing, face_goal=True)
        self.proximity = False

        # calculate distances (after interpolating the points)
        self.cum_distances = tt.cumulative_distance(self.points, spacing_dim=3)
        self.total_distance = self.cum_distances[-1]

        # set disable axis mask (lines mode is using some dofs)
        self.dis_axis = np.zeros(6)

    def update(self, position, velocity):
        if self.cnt >= len(self.points):
            self.des_pos = self.points[-1]
            return

        # select next waypoint
        self.des_pos = self.points[self.cnt]
        self.dis_axis[1] = 1

        # calculate the error using the point in the trajectory list
        error_position = self.calculate_position_error(position, self.des_pos)

        # check if proximity condition (within two tolerances) is reached and latched:
        #   once proximity is triggered the vehicle will adjust for the final yaw
        #   until reaching the requested waypoint (this takes into account disturbances)
        if np.all(np.abs(error_position[0:2]) < 2 * self.tolerances[0:2]):
            self.proximity = True
            self.dis_axis = np.zeros(6)

            # when close to the last waypoint enable full dof control
            #if self.cnt == len(self.points) - 1:
            #   self.dis_axis = np.zeros(6)

        # if waypoint is far adjust vehicle orientation towards the next waypoint
        if not self.proximity:
            self.des_pos[5] = tt.calculate_orientation(position, self.des_pos)

        # if waypoint is reached also reset proximity flag (re-enable yaw adjustments)
        if np.all(np.abs(error_position) < self.tolerances):
            self.cnt += 1
            self.proximity = False

            if self.cnt >= len(self.points):
                self.des_pos = self.points[-1]
                self.path_completed = True
                # print('Path completed')

class FastTimeStrategy(PathStrategy):
    """FastTimeStrategy provides a rapid navigation mode by interpolating the trajectory between requested waypoint.

    This mode use the notion of time along the trajectory to request a position further ahead in the path in order to maintain
    the requested target speed. Its behaviour can be tuned using the constructor's keyword arguments like:

        - target_speed: the ideal navigation speed, waypoint requests will try to meet this requirement

    If the vehicle is to far from the requested waypoint some external effects, like real sea effects, disturbances or
    user input (cooperative control), the internal navigation timer can drift away and a compensation is needed. This effect
    is governed by two parameters:

        - distance_threshold: maximum distance between current position and requested position before adjusting the time
        - time_adjust: seconds to adjust in the navigation timer to slow give the vehicle more time to complete the current leg

    """

    def __init__(self, points, position, **kwargs):
        super(FastTimeStrategy, self).__init__(points, position, **kwargs)

        # mode config:
        #   - set a target speed for the path navigation
        #   - adjust the time if vehicle is far away from the point
        self.look_ahead = float(kwargs.get('look_ahead', FAST_LOOKAHEAD))
        self.target_speed = float(kwargs.get('target_speed', FAST_SPEED))
        self.kind = kwargs.get('interpolation_method', 'linear')

        # trajectory time
        self.n = 0.0
        self.dt = 0.2
        self.a = 0.2
        self.v = 0.0
        self.t_interp = self.cum_distances / self.target_speed      # time at the end of each leg
        self.t_end = self.t_interp[-1]

        # interpolating assuming constant speed
        self.fc = [
            sci.interpolate.interp1d(self.t_interp, self.points[:, 0], kind=self.kind),
            sci.interpolate.interp1d(self.t_interp, self.points[:, 1], kind=self.kind),
            sci.interpolate.interp1d(self.t_interp, self.points[:, 2], kind=self.kind),
            sci.interpolate.interp1d(self.t_interp, self.points[:, 3], kind=self.kind),
            sci.interpolate.interp1d(self.t_interp, self.points[:, 4], kind=self.kind),
            sci.interpolate.interp1d(self.t_interp, self.points[:, 5], kind=self.kind)
        ]

        # set disable axis mask (fast mode is using few dofs)
        self.dis_axis = np.zeros(6)

    def update(self, position, velocity):
        # calculate the distance to the next virtual wps
        curr_error = self.calculate_position_error(position, self.des_pos)

        # fast motion doesn't require all dofs
        self.dis_axis[1] = 1

        # use real vehicle speed to initialize the virtual speed (this takes into account the previous path inertia)
        if self.v == 0 and velocity[0] > 0.0:
            self.v = velocity[0]

        if self.v <= self.target_speed:
            self.n = self.n + self.v * self.dt + 0.5 * self.a * self.dt**2
            self.v = self.v + self.a * self.dt
        else:
            self.n = self.n + self.v * self.dt

        # TODO: evaluate if it is worth reintroducing this
        # # close enough to next point?
        # if np.linalg.norm(curr_error[0:3]) < self.look_ahead:
        #     # compute next time for the interpolation
        #     self.n += self.look_ahead / self.target_speed

        if self.n < self.t_end:
            self.des_pos[0] = self.fc[0](self.n)
            self.des_pos[1] = self.fc[1](self.n)
            self.des_pos[2] = self.fc[2](self.n)
            self.des_pos[3] = self.fc[3](self.n)
            self.des_pos[4] = self.fc[4](self.n)
            self.des_pos[5] = self.fc[5](self.n)

            # adjust yaw towards next waypoint
            self.des_pos[5] = tt.calculate_orientation(position, self.des_pos)
        else:
            self.des_pos = self.points[-1]
            self.des_pos[5] = tt.calculate_orientation(position, self.des_pos)

            error_position = self.calculate_position_error(position, self.points[self.cnt, :])
            error_position = error_position.flatten()

            # final condition only on surge, sway and heave
            if np.all(np.abs(error_position[0:3]) < self.tolerances[0:3]):
                self.des_pos = self.points[-1]      # keep sending the last point
                self.dis_axis = np.zeros(6)         # terminal state (use all dofs for fine approach)

                self.path_completed = True
                # print('Path completed')

        # update waypoint counter
        try:
            # do not allow the counter to move back
            self.cnt = np.maximum(np.argwhere(self.t_interp > self.n)[0], self.cnt)
        except:
            self.cnt = len(self.points) - 1

redpajama_set_name: RedPajamaGithub


text:
var bower = require('./bower.json');
var pkg = require('./package.json');

module.exports = {
    bower: bower,
    buildFonts: true, // or false. Set to false if you are doing your own thing in the fonts directory
    buildTool: 'gulp', // grunt not yet available
    buildStyles: 'sass', // less not yet available
    buildHTML: 'html-concat', // moustache or assemble or jekyll not yet available
    buildScripts: 'browserify', // or requirejs not yet available
    release: false, /// or 'aws',
    releaseConfig: { //add you release config here... this is for AWS
        bucket: process.env.AWS_SKYGLOBAL_BUCKET,
        key: process.env.AWS_ACCESS_KEY_ID,
        secret: process.env.AWS_SECRET_ACCESS_KEY,
        region: process.env.AWS_REGION,
        directoryPrefix: 'components/' //prefix your target release destination
    },
    test: false,
    serve: '_site', // can be a node app like below
                    //{   script : 'src/app/server.js',
                    //    host: 'http://localhost:3000',
                    //    port: 3001,
                    //    env: { NODE_ENV: 'local'}
                    //}, // or serve static folders '_site' or ['_site','bower_component']
    paths: {
        /*
        All paths also have `script`, `styles`, `fonts`, `icons` and `images` properties
        Feel free to specify a custom path i.e. `scripts: './src/js'`
        */
        "bower": {
            root: './bower_components',
            fonts: './bower_components/*/dist/fonts'
        },
        source: { //source files to build your component / site
            root: "./src"
        },
        "demo": { // files used to demo the source code or an accompanying site.
                  // not files you would want to distribute.
            root: "./demo"
        },
        dist : { // Compiled source code to be redistributed i.e. via bower
            root: "./dist"
        },
        "site": { // Compiled demo code + Compiled source code.
                  // Final build code pushed to your chosen release cloud i.e. AWS
            root: './_site'
        }
    },
    pkg: pkg
};


text:
from django.test import TestCase
from permabots.validators import validate_telegram_keyboard
from django.core.exceptions import ValidationError

class TestValidateTelegramKeyboard(TestCase):

    def test_valid_no_template(self):
        keyboard_template = "[['a','b']]"
        validate_telegram_keyboard(keyboard_template)

    def test_not_valid_no_template(self):
        keyboard_template = "[['a','b']"
        self.assertRaises(ValidationError, validate_telegram_keyboard, keyboard_template)

    def test_valid_with_template_inside(self):
        keyboard_template = "[['{{response.value}}','{% if pattern.condition %}{{ pattern.condition }}{% else %}back{% endif %}']]"
        validate_telegram_keyboard(keyboard_template)

    def test_not_valid_with_template_inside(self):
        keyboard_template = "[['{{response.value}}','{% if pattern.condition %}{{ pattern.condition }}{% else %}back{% endif %}']"
        self.assertRaises(ValidationError, validate_telegram_keyboard, keyboard_template)

    def test_valid_with_template_outside(self):
        keyboard_template = "{% if response.status == 400 %}[['a','b']]{% else %}[['b', 'c']]{% endif %}"
        validate_telegram_keyboard(keyboard_template)

    def test_not_valid_with_template_outside(self):
        keyboard_template = "{% if response.status == 400 %}[['a','b']]{% else %}[['b', 'c']{% endif %}"
        self.assertRaises(ValidationError, validate_telegram_keyboard, keyboard_template)

    def test_valid_with_template_outside_rendered_as_none(self):
        keyboard_template = "{% if response.status == 200 %}[['Repos', 'Starred'],['Back']]{% endif %}"
        validate_telegram_keyboard(keyboard_template)

    def test_valid_template_with_state_context(self):
        keyboard_template = """[['Back']{% for repo in state_context.user_detail.response.data %}{% if loop.first %},{% endif %}
                            ['{{repo.full_name}}']{% if not loop.last %},{% endif %}{% endfor%}]"""
        validate_telegram_keyboard(keyboard_template)

    def test_valid_template_with_time(self):
        keyboard_template = """[['Back'],['{% now 'local' %}']]"""
        validate_telegram_keyboard(keyboard_template)

    def test_valid_template_with_data_for_hook(self):
        keyboard_template = """[['Back'],['{{ data.element }}']]"""
        validate_telegram_keyboard(keyboard_template)

#     #TODO: this case is not covered. When rendering the bad pattern is not validated
#     def test_not_valid_with_template_outside_not_generated(self):
#         keyboard_template = "{% if response.status == 400 %}[['a','b']{% else %}[['b', 'c']]{% endif %}"
#         self.assertRaises(ValidationError, validate_telegram_keyboard, keyboard_template)


text:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using Meridian.Domain;
using Meridian.Services;
using Meridian.ViewModel;
using Application = System.Windows.Application;

namespace Meridian.Helpers
{
    public sealed class HotKey : IDisposable
    {
        public event Action<HotKey> HotKeyPressed;

        private readonly int _id;
        private bool _isKeyRegistered;
        readonly IntPtr _handle;

        public HotKey(ModifierKeys modifierKeys, Key key, Window window)
            : this(modifierKeys, key, new WindowInteropHelper(window))
        {

        }

        public HotKey(ModifierKeys modifierKeys, Key key, WindowInteropHelper window)
            : this(modifierKeys, key, window.Handle)
        {

        }

        public HotKey(ModifierKeys modifierKeys, Key key, IntPtr windowHandle)
        {
            Key = key;
            KeyModifier = modifierKeys;
            _id = GetHashCode();
            _handle = windowHandle;
            RegisterHotKey();
            ComponentDispatcher.ThreadPreprocessMessage += ThreadPreprocessMessageMethod;
        }

        ~HotKey()
        {
            Dispose();
        }

        public Key Key { get; private set; }

        public ModifierKeys KeyModifier { get; private set; }

        public void RegisterHotKey()
        {
            if (Key == Key.None)
                return;
            if (_isKeyRegistered)
                UnregisterHotKey();
            _isKeyRegistered = NativeMethods.RegisterHotKey(_handle, _id, KeyModifier, KeyInterop.VirtualKeyFromKey(Key));
        }

        public void UnregisterHotKey()
        {
            _isKeyRegistered = !NativeMethods.UnregisterHotKey(_handle, _id);
        }

        public void Dispose()
        {
            if (_isKeyRegistered)
            {
                try
                {
                    ComponentDispatcher.ThreadPreprocessMessage -= ThreadPreprocessMessageMethod;
                }
                catch
                {

                }

                UnregisterHotKey();
            }
        }

        private void ThreadPreprocessMessageMethod(ref MSG msg, ref bool handled)
        {
            if (!handled)
            {
                if (msg.message == NativeMethods.WM_HOTKEY
                    && (int)(msg.wParam) == _id)
                {
                    OnHotKeyPressed();
                    handled = true;
                }
            }
        }

        private void OnHotKeyPressed()
        {
            if (HotKeyPressed != null)
                HotKeyPressed(this);
        }
    }

    public class HotKeyManager : IDisposable
    {
        private readonly IntPtr handle;
        private List<HotKey> hotKeys;

        public HotKeyManager(IntPtr handle)
        {
            this.handle = handle;

            RegisterHotkey(ModifierKeys.None, Key.MediaPlayPause);
            RegisterHotkey(ModifierKeys.None, Key.MediaNextTrack);
            RegisterHotkey(ModifierKeys.None, Key.MediaPreviousTrack);
            RegisterHotkey(ModifierKeys.None, Key.MediaStop);
            RegisterHotkey(ModifierKeys.None, Key.Play);
            RegisterHotkey(ModifierKeys.None, Key.Pause);
            RegisterHotkey(ModifierKeys.None, Key.SelectMedia);
        }

        public void RegisterHotkey(ModifierKeys modifier, Key key)
        {
            if (key == Key.None)
                return;

            if (hotKeys == null)
                hotKeys = new List<HotKey>();
            var hotkey = new HotKey(modifier, key, handle);
            hotkey.HotKeyPressed += HotKeyPressed;

            hotKeys.Add(hotkey);
        }

        public void RegisterHotkey(ModifierKeys modifier, Key key, Action<HotKey> action)
        {
            if (key == Key.None)
                return;
            if (hotKeys == null)
                hotKeys = new List<HotKey>();
            var hotkey = new HotKey(modifier, key, handle);
            hotkey.HotKeyPressed += action;

            hotKeys.Add(hotkey);
        }

        public void UnregisterHotkey(ModifierKeys modifier, Key key)
        {
            if (key == Key.None)
                return;
            foreach (var hotKey in hotKeys)
            {
                if (hotKey.Key == key && hotKey.KeyModifier == modifier)
                {
                    hotKey.HotKeyPressed -= HotKeyPressed;
                    hotKey.Dispose();
                    hotKeys.Remove(hotKey);
                    break;
                }
            }
        }

        public bool IsRegistered(ModifierKeys modifier, Key key)
        {
            if (key == Key.None)
                return false;
            foreach (var hotKey in hotKeys)
            {
                if (hotKey.Key == key && hotKey.KeyModifier == modifier)
                {
                    return true;
                }
            }

            return false;
        }

        public void InitializeHotkeys()
        {
            RegisterHotkey(Settings.Instance.NextHotKeyModifier, Settings.Instance.NextHotKey, h => AudioService.SkipNext());
            RegisterHotkey(Settings.Instance.PrevHotKeyModifier, Settings.Instance.PrevHotKey, h => AudioService.Prev());
            RegisterHotkey(Settings.Instance.PlayPauseHotKeyModifier, Settings.Instance.PlayPauseHotKey, h =>
            {
                if (AudioService.IsPlaying)
                    AudioService.Pause();
                else
                    AudioService.Play();
            });

            RegisterHotkey(Settings.Instance.LikeDislikeHotKeyModifier, Settings.Instance.LikeDislikeHotKey, h =>
            {
                ViewModelLocator.Main.AddRemoveAudioCommand.Execute(ViewModelLocator.Main.CurrentAudio);
            });

            RegisterHotkey(Settings.Instance.ShuffleHotKeyModifier, Settings.Instance.ShuffleHotKey, h => ViewModelLocator.Main.Shuffle = !ViewModelLocator.Main.Shuffle);
            RegisterHotkey(Settings.Instance.RepeatHotKeyModifier, Settings.Instance.RepeatHotKey, h => ViewModelLocator.Main.Repeat = !ViewModelLocator.Main.Repeat);
            RegisterHotkey(Settings.Instance.IncreaseVolumeHotKeyModifier, Settings.Instance.IncreaseVolumeHotKey, h => ViewModelLocator.Main.Volume += 5);
            RegisterHotkey(Settings.Instance.DecreaseVolumeHotKeyModifier, Settings.Instance.DecreaseVolumeHotKey, h => ViewModelLocator.Main.Volume -= 5);

            RegisterHotkey(Settings.Instance.ShowHideHotKeyModifier, Settings.Instance.ShowHideHotKey, h =>
            {
                if (Application.Current.MainWindow.WindowState != WindowState.Minimized)
                    Application.Current.MainWindow.WindowState = WindowState.Minimized;
                else
                    Application.Current.MainWindow.WindowState = WindowState.Normal;
            });

            RegisterHotkey(Settings.Instance.FastForwardHotKeyModifier, Settings.Instance.FastForwardHotKey, h => AudioService.FastForward(7));

            RegisterHotkey(Settings.Instance.RewindHotKeyModifier, Settings.Instance.RewindHotKey, h => AudioService.Rewind(7));
        }

        void HotKeyPressed(HotKey obj)
        {
            switch (obj.Key)
            {
                case Key.MediaPlayPause:
                    if (AudioService.IsPlaying)
                        AudioService.Pause();
                    else
                        AudioService.Play();
                    break;
                case Key.MediaNextTrack:
                    AudioService.SkipNext();
                    break;
                case Key.MediaPreviousTrack:
                    AudioService.Prev();
                    break;
                case Key.MediaStop:
                    AudioService.Stop();
                    break;
                case Key.SelectMedia:
                    if (Application.Current.MainWindow.WindowState == WindowState.Minimized)
                        Application.Current.MainWindow.WindowState = WindowState.Normal;
                    else if (Application.Current.MainWindow.IsActive)
                        Application.Current.MainWindow.WindowState = WindowState.Minimized;
                    else
                    {
                        Application.Current.MainWindow.Show();
                        Application.Current.MainWindow.Activate();
                    }
                    break;
            }
        }

        public void Dispose()
        {
            foreach (var hotKey in hotKeys)
            {
                hotKey.HotKeyPressed -= HotKeyPressed;
                hotKey.Dispose();
                break;
            }

            hotKeys.Clear();
        }
    }
}


text:
package org.teavm.classlib.java.lang;

import java.io.IOException;
import org.teavm.codegen.SourceWriter;
import org.teavm.javascript.spi.Generator;
import org.teavm.javascript.spi.GeneratorContext;
import org.teavm.model.MethodReference;

/**
 *
 * @author Alexey Andreev
 */
public class MathNativeGenerator implements Generator {
    @Override
    public void generate(GeneratorContext context, SourceWriter writer, MethodReference methodRef) throws IOException {
        function(context, writer, "Math." + methodRef.getName(), methodRef.parameterCount());
    }

    private void function(GeneratorContext context, SourceWriter writer, String name, int paramCount)
            throws IOException {
        writer.append("return ").append(name).append("(");
        for (int i = 0; i < paramCount; ++i) {
            if (i > 0) {
                writer.append(",").ws();
            }
            writer.append(context.getParameterName(i + 1));
        }
        writer.append(");").softNewLine();
    }
}


text:
'use strict';

import invariant from 'fbjs/lib/invariant';
import NativeModules from '../../../exports/NativeModules';
import NativeEventEmitter from '../NativeEventEmitter';
var NativeAnimatedModule = NativeModules.NativeAnimatedModule;
var __nativeAnimatedNodeTagCount = 1;
/* used for animated nodes */

var __nativeAnimationIdCount = 1;
/* used for started animations */

var nativeEventEmitter;
/**
 * Simple wrappers around NativeAnimatedModule to provide flow and autocmplete support for
 * the native module methods
 */

var API = {
  createAnimatedNode: function createAnimatedNode(tag, config) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.createAnimatedNode(tag, config);
  },
  startListeningToAnimatedNodeValue: function startListeningToAnimatedNodeValue(tag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.startListeningToAnimatedNodeValue(tag);
  },
  stopListeningToAnimatedNodeValue: function stopListeningToAnimatedNodeValue(tag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.stopListeningToAnimatedNodeValue(tag);
  },
  connectAnimatedNodes: function connectAnimatedNodes(parentTag, childTag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.connectAnimatedNodes(parentTag, childTag);
  },
  disconnectAnimatedNodes: function disconnectAnimatedNodes(parentTag, childTag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.disconnectAnimatedNodes(parentTag, childTag);
  },
  startAnimatingNode: function startAnimatingNode(animationId, nodeTag, config, endCallback) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.startAnimatingNode(animationId, nodeTag, config, endCallback);
  },
  stopAnimation: function stopAnimation(animationId) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.stopAnimation(animationId);
  },
  setAnimatedNodeValue: function setAnimatedNodeValue(nodeTag, value) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.setAnimatedNodeValue(nodeTag, value);
  },
  setAnimatedNodeOffset: function setAnimatedNodeOffset(nodeTag, offset) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.setAnimatedNodeOffset(nodeTag, offset);
  },
  flattenAnimatedNodeOffset: function flattenAnimatedNodeOffset(nodeTag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.flattenAnimatedNodeOffset(nodeTag);
  },
  extractAnimatedNodeOffset: function extractAnimatedNodeOffset(nodeTag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.extractAnimatedNodeOffset(nodeTag);
  },
  connectAnimatedNodeToView: function connectAnimatedNodeToView(nodeTag, viewTag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.connectAnimatedNodeToView(nodeTag, viewTag);
  },
  disconnectAnimatedNodeFromView: function disconnectAnimatedNodeFromView(nodeTag, viewTag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.disconnectAnimatedNodeFromView(nodeTag, viewTag);
  },
  dropAnimatedNode: function dropAnimatedNode(tag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.dropAnimatedNode(tag);
  },
  addAnimatedEventToView: function addAnimatedEventToView(viewTag, eventName, eventMapping) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.addAnimatedEventToView(viewTag, eventName, eventMapping);
  },
  removeAnimatedEventFromView: function removeAnimatedEventFromView(viewTag, eventName, animatedNodeTag) {
    assertNativeAnimatedModule();
    NativeAnimatedModule.removeAnimatedEventFromView(viewTag, eventName, animatedNodeTag);
  }
};
/**
 * Styles allowed by the native animated implementation.
 *
 * In general native animated implementation should support any numeric property that doesn't need
 * to be updated through the shadow view hierarchy (all non-layout properties).
 */

var STYLES_WHITELIST = {
  opacity: true,
  transform: true,

  /* ios styles */
  shadowOpacity: true,
  shadowRadius: true,

  /* legacy android transform properties */
  scaleX: true,
  scaleY: true,
  translateX: true,
  translateY: true
};
var TRANSFORM_WHITELIST = {
  translateX: true,
  translateY: true,
  scale: true,
  scaleX: true,
  scaleY: true,
  rotate: true,
  rotateX: true,
  rotateY: true,
  perspective: true
};
var SUPPORTED_INTERPOLATION_PARAMS = {
  inputRange: true,
  outputRange: true,
  extrapolate: true,
  extrapolateRight: true,
  extrapolateLeft: true
};

function addWhitelistedStyleProp(prop) {
  STYLES_WHITELIST[prop] = true;
}

function addWhitelistedTransformProp(prop) {
  TRANSFORM_WHITELIST[prop] = true;
}

function addWhitelistedInterpolationParam(param) {
  SUPPORTED_INTERPOLATION_PARAMS[param] = true;
}

function validateTransform(configs) {
  configs.forEach(function (config) {
    if (!TRANSFORM_WHITELIST.hasOwnProperty(config.property)) {
      throw new Error("Property '" + config.property + "' is not supported by native animated module");
    }
  });
}

function validateStyles(styles) {
  for (var key in styles) {
    if (!STYLES_WHITELIST.hasOwnProperty(key)) {
      throw new Error("Style property '" + key + "' is not supported by native animated module");
    }
  }
}

function validateInterpolation(config) {
  for (var key in config) {
    if (!SUPPORTED_INTERPOLATION_PARAMS.hasOwnProperty(key)) {
      throw new Error("Interpolation property '" + key + "' is not supported by native animated module");
    }
  }
}

function generateNewNodeTag() {
  return __nativeAnimatedNodeTagCount++;
}

function generateNewAnimationId() {
  return __nativeAnimationIdCount++;
}

function assertNativeAnimatedModule() {
  invariant(NativeAnimatedModule, 'Native animated module is not available');
}

var _warnedMissingNativeAnimated = false;

function shouldUseNativeDriver(config) {
  if (config.useNativeDriver && !NativeAnimatedModule) {
    if (!_warnedMissingNativeAnimated) {
      console.warn('Animated: `useNativeDriver` is not supported because the native ' + 'animated module is missing. Falling back to JS-based animation. To ' + 'resolve this, add `RCTAnimation` module to this app, or remove ' + '`useNativeDriver`. ' + 'More info: https://github.com/facebook/react-native/issues/11094#issuecomment-263240420');
      _warnedMissingNativeAnimated = true;
    }

    return false;
  }

  return config.useNativeDriver || false;
}

var NativeAnimatedHelper = {
  API: API,
  addWhitelistedStyleProp: addWhitelistedStyleProp,
  addWhitelistedTransformProp: addWhitelistedTransformProp,
  addWhitelistedInterpolationParam: addWhitelistedInterpolationParam,
  validateStyles: validateStyles,
  validateTransform: validateTransform,
  validateInterpolation: validateInterpolation,
  generateNewNodeTag: generateNewNodeTag,
  generateNewAnimationId: generateNewAnimationId,
  assertNativeAnimatedModule: assertNativeAnimatedModule,
  shouldUseNativeDriver: shouldUseNativeDriver,

  get nativeEventEmitter() {
    if (!nativeEventEmitter) {
      nativeEventEmitter = new NativeEventEmitter(NativeAnimatedModule);
    }

    return nativeEventEmitter;
  }

};
export { API, addWhitelistedStyleProp, addWhitelistedTransformProp, addWhitelistedInterpolationParam, validateStyles, validateTransform, validateInterpolation, generateNewNodeTag, generateNewAnimationId, assertNativeAnimatedModule, shouldUseNativeDriver };
export default NativeAnimatedHelper;


text:
"""python-colorlog example."""

import logging
from colorlog import ColoredFormatter

def setup_logger():
    """Return a logger with a default ColoredFormatter."""
    formatter = ColoredFormatter(
        "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
        datefmt=None,
        reset=True,
        log_colors={
            "DEBUG": "cyan",
            "INFO": "green",
            "WARNING": "yellow",
            "ERROR": "red",
            "CRITICAL": "red",
        },
    )

    logger = logging.getLogger("example")
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)

    return logger

def main():
    """Create and use a logger."""
    logger = setup_logger()

    logger.debug("a debug message")
    logger.info("an info message")
    logger.warning("a warning message")
    logger.error("an error message")
    logger.critical("a critical message")

if __name__ == "__main__":
    main()


text:
module RSpec
  module Mocks
    class HaveReceived
      COUNT_CONSTRAINTS = %w(exactly at_least at_most times once twice)
      ARGS_CONSTRAINTS = %w(with)
      CONSTRAINTS = COUNT_CONSTRAINTS + ARGS_CONSTRAINTS

      def initialize(method_name)
        @method_name = method_name
        @constraints = []
      end

      def matches?(subject)
        @subject = subject
        @expectation = expect
        @expectation.expected_messages_received?
      end

      def does_not_match?(subject)
        @subject = subject
        ensure_count_unconstrained
        @expectation = expect.never
        @expectation.expected_messages_received?
      end

      def failure_message
        generate_failure_message
      end

      def negative_failure_message
        generate_failure_message
      end

      CONSTRAINTS.each do |expectation|
        define_method expectation do |*args|
          @constraints << [expectation, *args]
          self
        end
      end

      private

      def expect
        build_expectation do |expectation|
          apply_constraints_to expectation
        end
      end

      def apply_constraints_to(expectation)
        @constraints.each do |constraint|
          expectation.send(*constraint)
        end
      end

      def ensure_count_unconstrained
        if count_constraint
          raise RSpec::Mocks::MockExpectationError,
            "can't use #{count_constraint} when negative"
        end
      end

      def count_constraint
        @constraints.map(&:first).detect do |constraint|
          COUNT_CONSTRAINTS.include?(constraint)
        end
      end

      def generate_failure_message
        mock_proxy.check_for_unexpected_arguments(@expectation)
        @expectation.generate_error
      rescue RSpec::Mocks::MockExpectationError => error
        error.message
      end

      def build_expectation(&block)
        mock_proxy.build_expectation(@method_name, &block)
      end

      def mock_proxy
        RSpec::Mocks.proxy_for(@subject)
      end
    end
  end
end


text:
title: I Tag
localeTitle: Yo Etiqueta
---
## Yo Etiqueta

El elemento `<i>` se utiliza para denotar el texto que está separado de su texto circundante de alguna manera. De forma predeterminada, el texto rodeado de etiquetas `<i>` se mostrará en cursiva.

En las especificaciones HTML anteriores, la etiqueta `<i>` se usaba únicamente para denotar el texto en cursiva. Sin embargo, en el HTML semántico moderno, las etiquetas como `<em>` y `<strong>` deben usarse cuando sea apropiado. Puede usar el atributo "clase" del elemento `<i>` para indicar por qué el texto en las etiquetas es diferente del texto circundante. Es posible que desee mostrar que el texto o la frase es de un idioma diferente, como se muestra en el siguiente ejemplo.

```HTML
<p>The French phrase <i class="french">esprit de corps</i> is often
 used to describe a feeling of group cohesion and fellowship.</p>
```

#### Más información:

*   [El elemento HTML <i>: MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i)
*   [Etiqueta: w3schools](https://www.w3schools.com/tags/tag_i.asp)
*   [Etiqueta: htmlreference.io](http://htmlreference.io/element/i/)


text:
package com.navercorp.pinpoint.rpc.stream;

import com.navercorp.pinpoint.common.util.Assert;
import com.navercorp.pinpoint.rpc.packet.stream.StreamClosePacket;
import com.navercorp.pinpoint.rpc.packet.stream.StreamCode;
import com.navercorp.pinpoint.rpc.packet.stream.StreamCreatePacket;
import com.navercorp.pinpoint.rpc.packet.stream.StreamPacket;
import com.navercorp.pinpoint.rpc.packet.stream.StreamPingPacket;
import com.navercorp.pinpoint.rpc.packet.stream.StreamPongPacket;
import com.navercorp.pinpoint.rpc.packet.stream.StreamResponsePacket;

import org.jboss.netty.channel.Channel;

import java.net.SocketAddress;

/**
 * @author koo.taejin
 */
public class NettyClientStreamChannel extends AbstractStreamChannel implements ClientStreamChannel {

    private final Channel channel;
    private final ClientStreamChannelEventHandler streamChannelEventHandler;

    public NettyClientStreamChannel(Channel channel, int streamId, StreamChannelRepository streamChannelRepository, ClientStreamChannelEventHandler streamChannelEventHandler) {
        super(streamId, streamChannelRepository);
        this.channel = Assert.requireNonNull(channel, "channel");
        this.streamChannelEventHandler = Assert.requireNonNull(streamChannelEventHandler, "streamChannelEventHandler");
    }

    public void connect(byte[] payload, long timeout) throws StreamException {
        changeStateTo(StreamChannelStateCode.CONNECT_AWAIT, true);

        sendCreate(payload);

        boolean connected = awaitOpen(timeout);
        if (connected) {
            logger.info("Open streamChannel initialization completed. streamChannel:{} ", this);
        } else {
            throw new StreamException(StreamCode.CONNECTION_TIMEOUT);
        }
    }

    private void sendCreate(byte[] payload) {
        StreamCreatePacket packet = new StreamCreatePacket(getStreamId(), payload);
        write(StreamChannelStateCode.CONNECT_AWAIT, packet);
    }

    @Override
    public void sendPing(int requestId) {
        StreamPingPacket packet = new StreamPingPacket(getStreamId(), requestId);
        write(StreamChannelStateCode.CONNECTED, packet);
    }

    @Override
    public void sendPong(int requestId) {
        StreamPongPacket packet = new StreamPongPacket(getStreamId(), requestId);
        write(StreamChannelStateCode.CONNECTED, packet);
    }

    @Override
    public void close(StreamCode code) {
        clearStreamChannelResource();
        if (!StreamCode.isConnectionError(code)) {
            try {
                StreamClosePacket packet = new StreamClosePacket(getStreamId(), code);
                write(packet);
            } catch (Exception e) {
                // do nothing
            }
        }
    }

    private void write(StreamPacket packet) {
        write(null, packet);
    }

    private void write(StreamChannelStateCode expectedCode, StreamPacket packet) {
        if (expectedCode != null) {
            state.assertState(expectedCode);
        }
        channel.write(packet);
    }

    @Override
    public void handleStreamResponsePacket(StreamResponsePacket packet) throws StreamException {
        if (state.checkState(StreamChannelStateCode.CONNECTED)) {
            streamChannelEventHandler.handleStreamResponsePacket(this, packet);
        } else if (state.checkState(StreamChannelStateCode.CONNECT_AWAIT)) {
            // may happen in the timing
        } else {
            throw new StreamException(StreamCode.STATE_NOT_CONNECTED);
        }
    }

    @Override
    public void handleStreamClosePacket(StreamClosePacket packet) {
        streamChannelEventHandler.handleStreamClosePacket(this, packet);
        disconnect(packet.getCode());
    }

    @Override
    public SocketAddress getRemoteAddress() {
        return channel.getRemoteAddress();
    }

    @Override
    protected StreamChannelStateChangeEventHandler getStateChangeEventHandler() {
        return streamChannelEventHandler;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Capoeira Canberra</title>
	<atom:link href="http://www.capoeiracanberra.com.au/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.capoeiracanberra.com.au</link>
	<description>Capoeira Senzala Australia with Mestre Rodriguinho in Canberra</description>
	<lastBuildDate>Sat, 29 Apr 2017 08:05:22 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.5.1</generator>
</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using wincache
Database Caching using wincache
Object Caching 344/374 objects using wincache

 Served from: www.capoeiracanberra.com.au @ 2017-07-01 10:36:26 by W3 Total Cache -->


text:
package liquid.service;

import liquid.user.db.config.UserJpaConfig;
import liquid.user.domain.Group;
import liquid.user.service.UserService;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by Tao Ma on 3/18/15.
 */
public class UserServiceTest {

    @Test
    public void testFind() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(UserJpaConfig.class);
        context.register(UserService.class);
        context.refresh();

        UserService userService = (UserService) context.getBean(UserService.class);
        Group group = userService.find(2);
    }
}


text:
module Magaz
  class PropertyValue < ActiveRecord::Base
    belongs_to :property
    belongs_to :valuable, polymorphic: true

    scope :features, -> { joins(property: :property_kind).where('magaz_property_kinds' => { id: Magaz::PropertyKind::FEATURE.id }) }

    scoped_search on: :value

  end
end


text:
module Byebug
  module VarFunctions
    def var_list(ary, b = get_binding)
      ary.sort!
      for v in ary
        begin
          s = bb_eval(v.to_s, b).inspect
        rescue
          begin
            s = bb_eval(v.to_s, b).to_s
          rescue
            s = "*Error in evaluation*"
          end
        end
        s[Setting[:width]-3..-1] = "..." if s.size > Setting[:width]
        print "#{v} = #{s}\n"
      end
    end

    def var_class_self
      obj = bb_eval('self')
      var_list(obj.class.class_variables, get_binding)
    end

    def var_global
      var_list(global_variables.reject { |v| [:$=, :$KCODE, :$-K].include?(v) })
    end
  end

  # Implements byebug's 'var class' command
  class VarClassCommand < Command
    def regexp
      /^\s* v(?:ar)? \s+ cl(?:ass)? \s*/x
    end

    def execute
      unless @state.context
        errmsg "can't get class variables here.\n"
        return
      end
      var_class_self
    end

    class << self
      def names
        %w(var)
      end

      def description
        %{v[ar] cl[ass] \t\t\tshow class variables of self}
      end
    end
  end

  class VarConstantCommand < Command
    def regexp
      /^\s* v(?:ar)? \s+ co(?:nst(?:ant)?)? \s+/x
    end

    def execute
      obj = bb_eval(@match.post_match)
      if obj.kind_of? Module
        constants = bb_eval("#{@match.post_match}.constants")
        constants.sort!
        for c in constants
          next if c =~ /SCRIPT/
          value = obj.const_get(c) rescue "ERROR: #{$!}"
          print " %s => %p\n", c, value
        end
      else
        print "Should be Class/Module: #{@match.post_match}\n"
      end
    end

    class << self
      def names
        %w(var)
      end

      def description
        %{v[ar] co[nst] <object>\t\tshow constants of object}
      end
    end
  end

  class VarGlobalCommand < Command
    def regexp
      /^\s* v(?:ar)? \s+ g(?:lobal)? \s*$/x
    end

    def execute
      var_global
    end

    class << self
      def names
        %w(var)
      end

      def description
        %{v[ar] g[lobal]\t\t\tshow global variables}
      end
    end
  end

  class VarInstanceCommand < Command
    def regexp
      /^\s* v(?:ar)? \s+ ins(?:tance)? \s*/x
    end

    def execute
      obj = bb_eval(@match.post_match.empty? ? 'self' : @match.post_match)
      var_list(obj.instance_variables, obj.instance_eval{binding()})
    end

    class << self
      def names
        %w(var)
      end

      def description
        %{v[ar] i[nstance] <object>\tshow instance variables of object}
      end
    end
  end

  # Implements byebug's 'var local' command
  class VarLocalCommand < Command
    def regexp
      /^\s* v(?:ar)? \s+ l(?:ocal)? \s*$/x
    end

    def execute
      _self = @state.context.frame_self(@state.frame_pos)
      locals = @state.context.frame_locals
      locals.keys.sort.each do |name|
        print "  %s => %p\n", name, locals[name]
      end
    end

    class << self
      def names
        %w(var)
      end

      def description
        %{v[ar] l[ocal]\t\t\tshow local variables}
      end
    end
  end
end


text:
'use strict';

var fsapi       = require('desirae/lib/node-adapters').fsapi
  ;

module.exports.create = function (options) {
  var restful = {}
    ;

  //
  // Required for desirae
  //
  restful.walk = function (req, res, next) {
    if (!(/^GET$/i.test(req.method) || /^GET$/i.test(req.query._method))) {
      next();
      return;
    }

    var opts = {}
      , dirnames = req.query.dir && [req.query.dir] || (req.query.dirs && req.query.dirs.split(/,/g)) || req.body.dirs
      ;

    if (!dirnames || !dirnames.length) {
      res.send({ error: "please specify GET w/ req.query.dir or POST w/ _method=GET&dirs=path/to/thing,..." });
      return;
    }

    if (!dirnames.every(function (dirname) {
      return 'string' === typeof dirname;
    })) {
      res.send({ error: "malformed request: " + JSON.stringify(dirnames) });
      return;
    }

    /*
    if (req.query.excludes) {
      opts.excludes = req.query.excludes.split(',');
    }
    */

    if (req.query.extensions) {
      opts.extensions = req.query.extensions.split(/,/g);
    }

    if ('true' === req.query.dotfiles) {
      opts.dotfiles = true;
    }
    if ('false' === req.query.sha1sum) {
      opts.sha1sum = false;
    }
    if ('true' === req.query.contents) {
      opts.contents = true;
    }

    // TODO opts.contents?
    fsapi.walk.walkDirs(options.blogdir, dirnames, opts).then(function (stats) {
      if (!req.body.dirs && !req.query.dirs) {
        res.send(stats[dirnames[0]]);
      } else {
        res.send(stats);
      }
    });
  };

  restful.getFiles = function (req, res, next) {
    if (!(/^GET$/i.test(req.method) || /^GET$/i.test(req.query._method))) {
      next();
      return;
    }

    var filepaths = req.query.path && [req.query.path] || (req.query.paths && req.query.paths.split(/,/g)) || req.body.paths
      ;

    if (!filepaths || !filepaths.length) {
      res.send({ error: "please specify GET w/ req.query.path or POST _method=GET&paths=path/to/thing,..." });
      return;
    }

    return fsapi.getfs(options.blogdir, filepaths).then(function (files) {
      if (!req.body.paths && !req.query.paths) {
        res.send(files[0]);
      } else {
        res.send(files);
      }
    });
  };

  restful.putFiles = function (req, res, next) {
    if (!(/^POST|PUT$/i.test(req.method) || /^POST|PUT$/i.test(req.query._method))) {
      next();
      return;
    }

    var opts = {}
      , files = req.body.files
      ;

    if (!files || !files.length) {
      res.send({ error: "please specify POST w/ req.body.files" });
      return;
    }

    opts.tmpdir = options.tmpdir;
    return fsapi.putfs(options.blogdir, files, opts).then(function (results) {
      res.send(results);
    });
  };

  restful.copy = function (req, res, next) {
    if (!(/^POST|PUT$/i.test(req.method) || /^POST|PUT$/i.test(req.query._method))) {
      next();
      return;
    }

    var opts = {}
      , files = req.body.files
      ;

    if ('object' !== typeof files || !Object.keys(files).length) {
      res.send({ error: "please specify POST w/ req.body.files" });
      return;
    }

    return fsapi.copyfs(options.blogdir, files, opts).then(function (results) {
      res.send(results);
    });
  };
  //
  // end Desirae API
  //

  return restful;
};


text:
package com.iluwatar.event.aggregator;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.PrintStream;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;

/**
 * Date: 12/12/15 - 3:04 PM
 *
 * @author Jeroen Meulemeester
 */
public class KingJoffreyTest {

  /**
   * The mocked standard out {@link PrintStream}, required since {@link KingJoffrey} does nothing
   * except for writing to std-out using {@link System#out}
   */
  private final PrintStream stdOutMock = mock(PrintStream.class);

  /**
   * Keep the original std-out so it can be restored after the test
   */
  private final PrintStream stdOutOrig = System.out;

  /**
   * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
   */
  @Before
  public void setUp() {
    System.setOut(this.stdOutMock);
  }

  /**
   * Removed the mocked std-out {@link PrintStream} again from the {@link System} class
   */
  @After
  public void tearDown() {
    System.setOut(this.stdOutOrig);
  }

  /**
   * Test if {@link KingJoffrey} tells us what event he received
   */
  @Test
  public void testOnEvent() {
    final KingJoffrey kingJoffrey = new KingJoffrey();

    for (final Event event : Event.values()) {
      verifyZeroInteractions(this.stdOutMock);
      kingJoffrey.onEvent(event);

      final String expectedMessage = "Received event from the King's Hand: " + event.toString();
      verify(this.stdOutMock, times(1)).println(expectedMessage);
      verifyNoMoreInteractions(this.stdOutMock);
    }

  }

}


text:
(function () {

    "use-strict";

    angular.module('layout', []);
})();


text:
var phantom = require('phantom');
var webshot = require('webshot');
var width = 2048;
var height = 1536;

var utils = {
  scrapeFullImage: function (url, file, userId, callback) {
    console.log('url', url);
    console.log('file', file);
    console.log('folder', userId);

    webshot(url, '../client/assets/' + userId + '/' + file,
      {
        screenSize: {
          width: 2048,
          height: 1536
        },
        shotSize: {
          width: 2048,
          height: 'all'
        },
        defaultWhiteBackground: true,
        quality: 100,
        renderDelay: 50,
        zoomFactor: 2
      }, function(err) {
          // screenshot now saved to google.png// screenshot now saved to hello_world.png
          console.log('err from scrape.js ' + err);
          if (!err) {
            callback('success', 'assets/' + userId + '/' + file);
          } else {
            callback(403, 'error');
          }
      });
  }
};

module.exports = utils;


text:
package io.druid.client.selector;

import com.google.common.collect.Lists;
import io.druid.client.DirectDruidClient;
import io.druid.client.DruidServer;
import io.druid.timeline.DataSegment;
import io.druid.timeline.partition.NoneShardSpec;
import org.easymock.EasyMock;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class TierSelectorStrategyTest
{

  @Test
  public void testHighestPriorityTierSelectorStrategy()
  {
    DirectDruidClient client = EasyMock.createMock(DirectDruidClient.class);
    QueryableDruidServer lowPriority = new QueryableDruidServer(
        new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
        client
    );
    QueryableDruidServer highPriority = new QueryableDruidServer(
        new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 1),
        client
    );

    testTierSelectorStrategy(
        new HighestPriorityTierSelectorStrategy(new ConnectionCountServerSelectorStrategy()),
        Arrays.asList(lowPriority, highPriority),
        highPriority
    );
  }

  @Test
  public void testLowestPriorityTierSelectorStrategy()
  {
    DirectDruidClient client = EasyMock.createMock(DirectDruidClient.class);
    QueryableDruidServer lowPriority = new QueryableDruidServer(
        new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
        client
    );
    QueryableDruidServer highPriority = new QueryableDruidServer(
        new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 1),
        client
    );

    testTierSelectorStrategy(
        new LowestPriorityTierSelectorStrategy(new ConnectionCountServerSelectorStrategy()),
        Arrays.asList(lowPriority, highPriority),
        lowPriority
    );
  }

  @Test
  public void testCustomPriorityTierSelectorStrategy()
  {
    DirectDruidClient client = EasyMock.createMock(DirectDruidClient.class);
    QueryableDruidServer lowPriority = new QueryableDruidServer(
        new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, -1),
        client
    );
    QueryableDruidServer mediumPriority = new QueryableDruidServer(
        new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
        client
    );
    QueryableDruidServer highPriority = new QueryableDruidServer(
        new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 1),
        client
    );

    testTierSelectorStrategy(
        new CustomTierSelectorStrategy(
            new ConnectionCountServerSelectorStrategy(), new CustomTierSelectorStrategyConfig()
        {
          @Override
          public List<Integer> getPriorities()
          {
            return Arrays.asList(2, 0, -1, 1);
          }
        }
        ),
        Arrays.asList(lowPriority, mediumPriority, highPriority),
        mediumPriority
    );
  }

  private void testTierSelectorStrategy(
      TierSelectorStrategy tierSelectorStrategy,
      List<QueryableDruidServer> servers,
      QueryableDruidServer expectedSelection
  )
  {
    final ServerSelector serverSelector = new ServerSelector(
        new DataSegment(
            "test",
            new Interval("2013-01-01/2013-01-02"),
            new DateTime("2013-01-01").toString(),
            com.google.common.collect.Maps.<String, Object>newHashMap(),
            Lists.<String>newArrayList(),
            Lists.<String>newArrayList(),
            new NoneShardSpec(),
            0,
            0L
        ),
        tierSelectorStrategy
    );
    for (QueryableDruidServer server : servers) {
      serverSelector.addServer(server);
    }
    Assert.assertEquals(expectedSelection, serverSelector.pick());
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item
      android:id="@+id/recents"
      android:icon="@android:drawable/ic_dialog_info"
      android:title="message1" />

  <item
      android:id="@+id/favourites"
      android:icon="@android:drawable/ic_dialog_info"
      android:title="message2" />

  <item
      android:id="@+id/nearby"
      android:icon="@android:drawable/ic_dialog_info"
      android:title="message3" />
</menu>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.swingeasy</groupId>
	<artifactId>swing-easy</artifactId>
	<version>3.3-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>swing-easy</name>
	<description>Java Swing components</description>
	<url>https://github.com/jurgendl/swing-easy</url>
	<!--
	http://cemerick.com/2010/08/24/hosting-maven-repos-on-github/

	deploy snapshot:
	mvn -DaltDeploymentRepository=snapshot-repo::default::file:../mvn-repo/snapshots clean deploy
	release:
	mvn release:prepare
	mvn release:perform

	mvn release:prepare
	git checkout swing-easy-3.3
	set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_51
	mvn -DaltDeploymentRepository=repo::default::file:../mvn-repo/releases clean deploy
	git checkout master
	mvn versions:set -DnewVersion=3.4-SNAPSHOT
	delete pom.xml.releaseBackup & release.properties & pom.xml.releaseBackup & pom.xml.versionsBackup
	commit/push
	-->
	<properties>
		<targetJdk>1.7</targetJdk><!-- should be compatible with 1.6 and higher -->
		<project.build.sourceEncoding>utf-8</project.build.sourceEncoding><!-- fixed encoding -->
		<project.reporting.outputEncoding>${project.build.sourceEncoding}</project.reporting.outputEncoding>
		<maven.javadoc.skip>true</maven.javadoc.skip><!-- skip by default -->
		<!-- maven-site-plugin -->
		<maven.site.skip>false</maven.site.skip><!-- do not skip by default -->
		<!-- maven-compiler-plugin -->
		<maven.compiler.optimize>true</maven.compiler.optimize>
		<maven.compiler.fork>true</maven.compiler.fork>
		<maven.compiler.source>${targetJdk}</maven.compiler.source>
		<maven.compiler.target>${targetJdk}</maven.compiler.target>
		<maven.compiler.verbose>true</maven.compiler.verbose>
		<maven.compiler.debug>true</maven.compiler.debug>
		<maven.compiler.debuglevel>lines,vars,source</maven.compiler.debuglevel>
		<!-- maven-surefire-plugin -->
		<maven.test.failure.ignore>true</maven.test.failure.ignore>
		<!-- versions -->
		<version.glazedlists>1.9.1</version.glazedlists>
		<version.commons.lang3>3.4</version.commons.lang3>
		<version.miglayout>4.2</version.miglayout>
		<version.javassist>3.20.0-GA</version.javassist>
		<version.commons.beanutils>1.9.2</version.commons.beanutils>
		<version.xhtmlrenderer>9.0.8</version.xhtmlrenderer>
		<version.commons.codec>1.10</version.commons.codec>
		<version.poi>3.10-FINAL</version.poi>
		<version.slf4j>1.7.19</version.slf4j>
		<version.logback>1.1.6</version.logback>
		<version.junit>4.12</version.junit>
		<version.ostermiller>1.07.00</version.ostermiller>
	</properties>
	<!-- http://maven.apache.org/guides/introduction/introduction-to-profiles.html -->
	<profiles>
		<profile>
			<id>src</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-source-plugin</artifactId>
						<version>2.2.1</version>
						<executions>
							<execution>
								<id>attach-sources</id>
								<phase>verify</phase>
								<goals>
									<goal>jar-no-fork</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<!-- "mvn clean package -P nodebuginfo" wil create an optimized (without
				debugging info) jar: swing-easy-nodebug-{version}.jar "mvn clean package"
				wil create a jar without debugging info: swing-easy-{version}.jar -->
			<id>nodebuginfo</id>
			<build>
				<finalName>${project.artifactId}-nodebuginfo-${project.version}</finalName>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-compiler-plugin</artifactId>
						<version>3.1</version>
						<configuration>
							<fork>true</fork>
							<source>${targetJdk}</source>
							<target>${targetJdk}</target>
							<optimize>true</optimize>
							<verbose>false</verbose>
							<encoding>${project.build.sourceEncoding}</encoding>
							<debug>false</debug>
							<debuglevel>none</debuglevel><!-- lines, vars, and source or none -->
						</configuration>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
	<licenses>
		<license>
			<name>The MIT License (MIT)</name>
			<url>https://raw.githubusercontent.com/jurgendl/swing-easy/master/LICENSE.md</url>
		</license>
	</licenses>
	<issueManagement>
		<system>github</system>
		<url>https://github.com/jurgendl/swing-easy/issues</url>
	</issueManagement>
	<distributionManagement>
		<repository>
			<id>repo</id>
			<url>https://github.com/jurgendl/mvn-repo/raw/master/releases</url>
		</repository>
		<snapshotRepository>
			<id>snapshot-repo</id>
			<url>https://github.com/jurgendl/mvn-repo/raw/master/snapshots</url>
		</snapshotRepository>
	</distributionManagement>
	<inceptionYear>2011</inceptionYear>
	<developers>
		<developer>
			<id />
			<timezone>+1</timezone>
			<name>jurgendl</name>
			<roles>
				<role>Project owner</role>
			</roles>
		</developer>
	</developers>
	<contributors />
	<scm>
		<connection>scm:git:git@github.com:jurgendl/swing-easy.git</connection>
		<url>scm:git:git@github.com:jurgendl/swing-easy.git</url>
		<developerConnection>scm:git:git@github.com:jurgendl/swing-easy.git</developerConnection>
		<tag>HEAD</tag>
	</scm>
	<repositories>
		<repository>
			<id>github</id>
			<!-- <url>https://github.com/jurgendl/mvn-repo/raw/master/releases/</url> -->
			<url>https://raw.githubusercontent.com/jurgendl/mvn-repo/master/releases/</url>
		</repository>
	</repositories>
	<dependencies>
		<dependency>
			<groupId>net.java.dev.glazedlists</groupId>
			<artifactId>glazedlists_java15</artifactId>
			<version>${version.glazedlists}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>${version.commons.lang3}</version>
		</dependency>
		<dependency>
			<groupId>com.miglayout</groupId>
			<artifactId>miglayout-swing</artifactId>
			<version>${version.miglayout}</version>
		</dependency>
		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>${version.javassist}</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>${version.commons.beanutils}</version>
			<exclusions>
				<exclusion>
					<artifactId>commons-logging</artifactId>
					<groupId>commons-logging</groupId>
				</exclusion>
				<exclusion>
					<artifactId>commons-collections</artifactId>
					<groupId>commons-collections</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.xhtmlrenderer</groupId>
			<artifactId>flying-saucer-pdf-itext5</artifactId>
			<version>${version.xhtmlrenderer}</version>
		</dependency>
		<dependency><!-- must be place before poi -->
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>${version.commons.codec}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>${version.poi}</version>
			<exclusions>
				<exclusion>
					<artifactId>stax-api</artifactId>
					<groupId>stax</groupId>
				</exclusion>
				<exclusion>
					<artifactId>xml-apis</artifactId>
					<groupId>xml-apis</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.ostermiller</groupId>
			<artifactId>utils</artifactId>
			<version>${version.ostermiller}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${version.slf4j}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${version.slf4j}</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
			<version>${version.logback}</version>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${version.logback}</version>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${version.junit}</version>
			<scope>test</scope>
			<optional>true</optional>
		</dependency>
	</dependencies>
	<build>
		<extensions>
			<extension>
				<groupId>org.apache.maven.wagon</groupId>
				<artifactId>wagon-webdav-jackrabbit</artifactId>
				<version>1.0</version>
			</extension>
		</extensions>
		<plugins>
			<!-- http://stackoverflow.com/questions/4725668/how-to-deploy-snapshot-with-sources-and-javadoc -->
			<plugin>
			  <artifactId>maven-source-plugin</artifactId>
			  <executions>
				<execution>
				  <id>attach-sources</id>
				  <phase>deploy</phase>
				  <goals><goal>jar-no-fork</goal></goals>
				</execution>
			  </executions>
			</plugin>
			<plugin>
			  <!-- explicitly define maven-deploy-plugin after other to force exec order -->
			  <artifactId>maven-deploy-plugin</artifactId>
			  <executions>
				<execution>
				  <id>deploy</id>
				  <phase>deploy</phase>
				  <goals><goal>deploy</goal></goals>
				</execution>
			  </executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<useReleaseProfile>false</useReleaseProfile>
					<releaseProfiles>src</releaseProfiles>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-scm-plugin</artifactId>
				<version>1.9</version>
				<configuration>
					<connectionType>developerConnection</connectionType>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-site-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<locales>en</locales>
					<generateSitemap>true</generateSitemap>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.4</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<source>${targetJdk}</source>
					<target>${targetJdk}</target>
					<optimize>true</optimize>
					<verbose>false</verbose>
					<encoding>${project.build.sourceEncoding}</encoding>
					<debug>true</debug>
					<debuglevel>lines,vars,source</debuglevel>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.17</version>
				<configuration>
					<testFailureIgnore>true</testFailureIgnore>
					<argLine>-Xms128m -Xmx128m</argLine>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<version>2.4.0</version>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
						<Bundle-Version>${project.version}</Bundle-Version>
					</instructions>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
					<forceRecheck>true</forceRecheck>
					<buildOutputDirectory>target-eclipse</buildOutputDirectory>
					<charset>${project.build.sourceEncoding}</charset>
					<docencoding>${project.build.sourceEncoding}</docencoding>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<reporting>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.6</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-project-info-reports-plugin</artifactId>
				<version>2.7</version>
				<reportSets>
					<reportSet>
						<reports>
							<report>dependencies</report>
							<report>project-team</report>
							<report>mailing-list</report>
							<report>cim</report>
							<report>issue-tracking</report>
							<report>license</report>
							<report>scm</report>
							<report>dependency-convergence</report>
							<report>dependency-info</report>
							<report>dependency-management</report>
							<report>distribution-management</report>
							<report>index</report>
							<report>modules</report>
							<report>plugin-management</report>
							<report>plugins</report>
							<report>summary</report>
						</reports>
					</reportSet>
				</reportSets>
			</plugin>
			<plugin>
				<!--http://jeremylong.github.io/DependencyCheck/dependency-check-maven/usage.html-->
				<!--https://www.owasp.org/index.php/OWASP_Dependency_Check-->
				<!--https://www.owasp.org/index.php/Top_10_2013-A9-Using_Components_with_Known_Vulnerabilities-->
				<groupId>org.owasp</groupId>
				<artifactId>dependency-check-maven</artifactId>
				<version>1.2.11</version>
				<!-- in build/plugins -->
				<!--<configuration>
					<failBuildOnCVSS>8</failBuildOnCVSS>
				</configuration>-->
				<configuration>
					<externalReport>false</externalReport>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-changes-plugin</artifactId>
				<version>2.9</version>
				<reportSets>
					<reportSet>
						<reports>
							<report>changes-report</report>
						</reports>
					</reportSet>
				</reportSets>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<targetjdk>${targetJdk}</targetjdk>
					<format>xml</format>
					<linkXref>true</linkXref>
					<sourceEncoding>${project.build.sourceEncoding}</sourceEncoding>
					<minimumTokens>100</minimumTokens>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-clover-plugin</artifactId>
				<version>2.4</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-report-plugin</artifactId>
				<version>2.17</version>
				<configuration>
					<testFailureIgnore>true</testFailureIgnore>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>jdepend-maven-plugin</artifactId>
				<version>2.0</version>
				<configuration>
					<projectDirectory>${basedir}</projectDirectory>
					<classDirectory>${project.build.directory}/classes</classDirectory>
				</configuration>
			</plugin>
			<!-- makes site size very large -->
			<!--
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jxr-plugin</artifactId>
				<version>2.4</version>
			</plugin>
			-->
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>taglist-maven-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<multipleLineComments>true</multipleLineComments>
					<sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
					<tags>
						<tag>TODO</tag>
						<tag>FIXME</tag>
					</tags>
				</configuration>
			</plugin>
			<!-- makes site size very large -->
			<!--
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.9.1</version>
				<configuration>
					<links>
						<link>http://docs.oracle.com/javase/7/docs/api/</link>
					</links>
					<linksource>true</linksource>
					<source>${targetJdk}</source>
					<splitindex>true</splitindex>
					<use>true</use>
					<verbose>false</verbose>
					<version>true</version>
					<detectLinks>true</detectLinks>
				</configuration>
			</plugin>
			 -->
		</plugins>
	</reporting>
</project>


text:
use get_error;
use render::{Texture, TextureCreator};
use rwops::RWops;
use std::ffi::CString;
use std::os::raw::{c_char, c_int};
use std::path::Path;
use surface::Surface;
use sys;
use sys::image;
use version::Version;

bitflags! {
    /// InitFlags are passed to init() to control which subsystem
    /// functionality to load.
    pub struct InitFlag : u32 {
        const JPG  = image::IMG_InitFlags_IMG_INIT_JPG as u32;
        const PNG  = image::IMG_InitFlags_IMG_INIT_PNG as u32;
        const TIF  = image::IMG_InitFlags_IMG_INIT_TIF as u32;
        const WEBP = image::IMG_InitFlags_IMG_INIT_WEBP as u32;
    }
}

// This is used for error message for init
impl ::std::fmt::Display for InitFlag {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        if self.contains(InitFlag::JPG) {
            f.write_str("INIT_JPG ")?;
        }
        if self.contains(InitFlag::PNG) {
            f.write_str("INIT_PNG ")?;
        }
        if self.contains(InitFlag::TIF) {
            f.write_str("INIT_TIF ")?;
        }
        if self.contains(InitFlag::WEBP) {
            f.write_str("INIT_WEBP ")?;
        }
        Ok(())
    }
}

/// Static method extensions for creating Surfaces
pub trait LoadSurface: Sized {
    // Self is only returned here to type hint to the compiler.
    // The syntax for type hinting in this case is not yet defined.
    // The intended return value is Result<~Surface, String>.
    fn from_file<P: AsRef<Path>>(filename: P) -> Result<Self, String>;
    fn from_xpm_array(xpm: *const *const i8) -> Result<Self, String>;
}

/// Method extensions to Surface for saving to disk
pub trait SaveSurface {
    fn save<P: AsRef<Path>>(&self, filename: P) -> Result<(), String>;
    fn save_rw(&self, dst: &mut RWops) -> Result<(), String>;
}

impl<'a> LoadSurface for Surface<'a> {
    fn from_file<P: AsRef<Path>>(filename: P) -> Result<Surface<'a>, String> {
        //! Loads an SDL Surface from a file
        unsafe {
            let c_filename = CString::new(filename.as_ref().to_str().unwrap()).unwrap();
            let raw = image::IMG_Load(c_filename.as_ptr() as *const _);
            if (raw as *mut ()).is_null() {
                Err(get_error())
            } else {
                Ok(Surface::from_ll(raw))
            }
        }
    }

    fn from_xpm_array(xpm: *const *const i8) -> Result<Surface<'a>, String> {
        //! Loads an SDL Surface from XPM data
        unsafe {
            let raw = image::IMG_ReadXPMFromArray(xpm as *mut *mut c_char);
            if (raw as *mut ()).is_null() {
                Err(get_error())
            } else {
                Ok(Surface::from_ll(raw))
            }
        }
    }
}

impl<'a> SaveSurface for Surface<'a> {
    fn save<P: AsRef<Path>>(&self, filename: P) -> Result<(), String> {
        //! Saves an SDL Surface to a file
        unsafe {
            let c_filename = CString::new(filename.as_ref().to_str().unwrap()).unwrap();
            let status = image::IMG_SavePNG(self.raw(), c_filename.as_ptr() as *const _);
            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }

    fn save_rw(&self, dst: &mut RWops) -> Result<(), String> {
        //! Saves an SDL Surface to an RWops
        unsafe {
            let status = image::IMG_SavePNG_RW(self.raw(), dst.raw(), 0);

            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }
}

/// Method extensions for creating Textures from a `TextureCreator`
pub trait LoadTexture {
    fn load_texture<P: AsRef<Path>>(&self, filename: P) -> Result<Texture, String>;
    fn load_texture_bytes(&self, buf: &[u8]) -> Result<Texture, String>;
}

impl<T> LoadTexture for TextureCreator<T> {
    fn load_texture<P: AsRef<Path>>(&self, filename: P) -> Result<Texture, String> {
        //! Loads an SDL Texture from a file
        unsafe {
            let c_filename = CString::new(filename.as_ref().to_str().unwrap()).unwrap();
            let raw = image::IMG_LoadTexture(self.raw(), c_filename.as_ptr() as *const _);
            if (raw as *mut ()).is_null() {
                Err(get_error())
            } else {
                Ok(self.raw_create_texture(raw))
            }
        }
    }

    #[doc(alias = "IMG_LoadTexture")]
    fn load_texture_bytes(&self, buf: &[u8]) -> Result<Texture, String> {
        //! Loads an SDL Texture from a buffer that the format must be something supported by SDL2_image (png, jpeg, ect, but NOT RGBA8888 bytes for instance)
        unsafe {
            let buf = sdl2_sys::SDL_RWFromMem(buf.as_ptr() as *mut libc::c_void, buf.len() as i32);
            let raw = image::IMG_LoadTexture_RW(self.raw(), buf, 1); // close(free) buff after load
            if (raw as *mut ()).is_null() {
                Err(get_error())
            } else {
                Ok(self.raw_create_texture(raw))
            }
        }
    }
}

/// Context manager for `sdl2_image` to manage quitting. Can't do much with it but
/// keep it alive while you are using it.
pub struct Sdl2ImageContext;

impl Drop for Sdl2ImageContext {
    fn drop(&mut self) {
        unsafe {
            image::IMG_Quit();
        }
    }
}

/// Initializes `SDL2_image` with `InitFlags`.
/// If not every flag is set it returns an error
pub fn init(flags: InitFlag) -> Result<Sdl2ImageContext, String> {
    let return_flags = unsafe {
        let used = image::IMG_Init(flags.bits() as c_int);
        InitFlag::from_bits_truncate(used as u32)
    };
    if !flags.intersects(return_flags) {
        // According to docs, error message text is not always set
        let mut error = get_error();
        if error.is_empty() {
            let un_init_flags = return_flags ^ flags;
            error = format!("Could not init: {}", un_init_flags);
            let _ = ::set_error(&error);
        }
        Err(error)
    } else {
        Ok(Sdl2ImageContext)
    }
}

/// Returns the version of the dynamically linked `SDL_image` library
pub fn get_linked_version() -> Version {
    unsafe { Version::from_ll(*image::IMG_Linked_Version()) }
}

#[inline]
fn to_surface_result<'a>(raw: *mut sys::SDL_Surface) -> Result<Surface<'a>, String> {
    if (raw as *mut ()).is_null() {
        Err(get_error())
    } else {
        unsafe { Ok(Surface::from_ll(raw)) }
    }
}

pub trait ImageRWops {
    /// load as a surface. except TGA
    fn load(&self) -> Result<Surface<'static>, String>;
    /// load as a surface. This can load all supported image formats.
    fn load_typed(&self, _type: &str) -> Result<Surface<'static>, String>;

    fn load_cur(&self) -> Result<Surface<'static>, String>;
    fn load_ico(&self) -> Result<Surface<'static>, String>;
    fn load_bmp(&self) -> Result<Surface<'static>, String>;
    fn load_pnm(&self) -> Result<Surface<'static>, String>;
    fn load_xpm(&self) -> Result<Surface<'static>, String>;
    fn load_xcf(&self) -> Result<Surface<'static>, String>;
    fn load_pcx(&self) -> Result<Surface<'static>, String>;
    fn load_gif(&self) -> Result<Surface<'static>, String>;
    fn load_jpg(&self) -> Result<Surface<'static>, String>;
    fn load_tif(&self) -> Result<Surface<'static>, String>;
    fn load_png(&self) -> Result<Surface<'static>, String>;
    fn load_tga(&self) -> Result<Surface<'static>, String>;
    fn load_lbm(&self) -> Result<Surface<'static>, String>;
    fn load_xv(&self) -> Result<Surface<'static>, String>;
    fn load_webp(&self) -> Result<Surface<'static>, String>;

    fn is_cur(&self) -> bool;
    fn is_ico(&self) -> bool;
    fn is_bmp(&self) -> bool;
    fn is_pnm(&self) -> bool;
    fn is_xpm(&self) -> bool;
    fn is_xcf(&self) -> bool;
    fn is_pcx(&self) -> bool;
    fn is_gif(&self) -> bool;
    fn is_jpg(&self) -> bool;
    fn is_tif(&self) -> bool;
    fn is_png(&self) -> bool;
    fn is_lbm(&self) -> bool;
    fn is_xv(&self) -> bool;
    fn is_webp(&self) -> bool;
}

impl<'a> ImageRWops for RWops<'a> {
    fn load(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_Load_RW(self.raw(), 0) };
        to_surface_result(raw)
    }
    fn load_typed(&self, _type: &str) -> Result<Surface<'static>, String> {
        let raw = unsafe {
            let c_type = CString::new(_type.as_bytes()).unwrap();
            image::IMG_LoadTyped_RW(self.raw(), 0, c_type.as_ptr() as *const _)
        };
        to_surface_result(raw)
    }

    fn load_cur(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadCUR_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_ico(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadICO_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_bmp(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadBMP_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_pnm(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadPNM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xpm(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadXPM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xcf(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadXCF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_pcx(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadPCX_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_gif(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadGIF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_jpg(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadJPG_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_tif(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadTIF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_png(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadPNG_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_tga(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadTGA_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_lbm(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadLBM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xv(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadXV_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_webp(&self) -> Result<Surface<'static>, String> {
        let raw = unsafe { image::IMG_LoadWEBP_RW(self.raw()) };
        to_surface_result(raw)
    }

    fn is_cur(&self) -> bool {
        unsafe { image::IMG_isCUR(self.raw()) == 1 }
    }
    fn is_ico(&self) -> bool {
        unsafe { image::IMG_isICO(self.raw()) == 1 }
    }
    fn is_bmp(&self) -> bool {
        unsafe { image::IMG_isBMP(self.raw()) == 1 }
    }
    fn is_pnm(&self) -> bool {
        unsafe { image::IMG_isPNM(self.raw()) == 1 }
    }
    fn is_xpm(&self) -> bool {
        unsafe { image::IMG_isXPM(self.raw()) == 1 }
    }
    fn is_xcf(&self) -> bool {
        unsafe { image::IMG_isXCF(self.raw()) == 1 }
    }
    fn is_pcx(&self) -> bool {
        unsafe { image::IMG_isPCX(self.raw()) == 1 }
    }
    fn is_gif(&self) -> bool {
        unsafe { image::IMG_isGIF(self.raw()) == 1 }
    }
    fn is_jpg(&self) -> bool {
        unsafe { image::IMG_isJPG(self.raw()) == 1 }
    }
    fn is_tif(&self) -> bool {
        unsafe { image::IMG_isTIF(self.raw()) == 1 }
    }
    fn is_png(&self) -> bool {
        unsafe { image::IMG_isPNG(self.raw()) == 1 }
    }
    fn is_lbm(&self) -> bool {
        unsafe { image::IMG_isLBM(self.raw()) == 1 }
    }
    fn is_xv(&self) -> bool {
        unsafe { image::IMG_isXV(self.raw()) == 1 }
    }
    fn is_webp(&self) -> bool {
        unsafe { image::IMG_isWEBP(self.raw()) == 1 }
    }
}


text:
exports.pow = function () {
	return function (valueA, valueB) {
		if (arguments.length < 3) {
			throw new Error('Handlebars Helper "pow" needs 2 parameters minimum');
		}

		return Math.pow(valueA, valueB);
	};
};