text:
package org.apache.activemq.shiro.authz;

import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.broker.StubBroker;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.DestinationInfo;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.shiro.subject.SubjectAdapter;
import org.apache.activemq.shiro.subject.SubjectConnectionReference;
import org.apache.activemq.shiro.subject.SubjectSecurityContext;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.env.Environment;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

import java.util.Collection;

import static org.junit.Assert.*;

/**
 * @since 5.10.0
 */
public class AuthorizationFilterTest {

    private AuthorizationFilter filter;
    private StubBroker nextBroker;

    @Before
    public void setUp() {
        filter = new AuthorizationFilter();
        nextBroker = new StubBroker();
        filter.setNext(nextBroker);
    }

    @Test
    public void testDefaults() {
        ActionPermissionResolver resolver = filter.getActionPermissionResolver();
        assertNotNull(resolver);
        assertTrue(resolver instanceof DestinationActionPermissionResolver);
    }

    @Test
    public void testSetActionPermissionResolver() {
        ActionPermissionResolver resolver = new DestinationActionPermissionResolver();
        filter.setActionPermissionResolver(resolver);
        assertSame(resolver, filter.getActionPermissionResolver());
    }

    private ConnectionContext createContext(Subject subject) {
        ConnectionContext ctx = new ConnectionContext();
        ConnectionInfo info = new ConnectionInfo();
        Environment environment = new Environment() {
            @Override
            public org.apache.shiro.mgt.SecurityManager getSecurityManager() {
                return null; //not needed in this test.
            }
        };
        SubjectConnectionReference ref = new SubjectConnectionReference(ctx, info, environment, subject);
        SubjectSecurityContext secCtx = new SubjectSecurityContext(ref);
        ctx.setSecurityContext(secCtx);
        return ctx;
    }

    @Test
    public void testSubjectToString() {
        Subject subject = new PermsSubject() {
            @Override
            public PrincipalCollection getPrincipals() {
                return null;
            }
        };
        String string = filter.toString(subject);
        assertEquals("", string);
    }

    @Test(expected=UnauthorizedException.class)
    public void testAddDestinationInfoNotAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);
        DestinationInfo info = new DestinationInfo(null, DestinationInfo.ADD_OPERATION_TYPE, dest);

        Subject subject = new PermsSubject();
        ConnectionContext context = createContext(subject);

        filter.addDestinationInfo(context, info);
    }

    @Test
    public void testAddDestinationInfoAuthorized() throws Exception {

        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);
        DestinationInfo info = new DestinationInfo(null, DestinationInfo.ADD_OPERATION_TYPE, dest);

        Subject subject = new PermsSubject() {
            @Override
            public boolean isPermitted(Permission toCheck) {
                Permission assigned = createPerm("topic:myTopic:create");
                assertEquals(assigned.toString(), toCheck.toString());
                return assigned.implies(toCheck);
            }
        };

        ConnectionContext context = createContext(subject);

        filter.addDestinationInfo(context, info);
    }

    @Test(expected=UnauthorizedException.class)
    public void testAddDestinationNotAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);

        Subject subject = new PermsSubject();
        ConnectionContext context = createContext(subject);

        filter.addDestination(context, dest, true);
    }

    @Test
    public void testAddDestinationAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);

        Subject subject = new PermsSubject() {
            @Override
            public boolean isPermitted(Permission toCheck) {
                Permission assigned = createPerm("topic:myTopic:create");
                assertEquals(assigned.toString(), toCheck.toString());
                return assigned.implies(toCheck);
            }
        };

        ConnectionContext context = createContext(subject);

        filter.addDestination(context, dest, true);
    }

    @Test(expected=UnauthorizedException.class)
    public void testRemoveDestinationInfoNotAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);
        DestinationInfo info = new DestinationInfo(null, DestinationInfo.REMOVE_OPERATION_TYPE, dest);

        Subject subject = new PermsSubject();
        ConnectionContext context = createContext(subject);

        filter.removeDestinationInfo(context, info);
    }

    @Test
    public void testRemoveDestinationInfoAuthorized() throws Exception {

        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);
        DestinationInfo info = new DestinationInfo(null, DestinationInfo.REMOVE_OPERATION_TYPE, dest);

        Subject subject = new PermsSubject() {
            @Override
            public boolean isPermitted(Permission toCheck) {
                Permission assigned = createPerm("topic:myTopic:remove");
                assertEquals(assigned.toString(), toCheck.toString());
                return assigned.implies(toCheck);
            }
        };

        ConnectionContext context = createContext(subject);

        filter.removeDestinationInfo(context, info);
    }

    @Test(expected=UnauthorizedException.class)
    public void testRemoveDestinationNotAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);

        Subject subject = new PermsSubject();
        ConnectionContext context = createContext(subject);

        filter.removeDestination(context, dest, 1000);
    }

    @Test
    public void testRemoveDestinationAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);

        Subject subject = new PermsSubject() {
            @Override
            public boolean isPermitted(Permission toCheck) {
                Permission assigned = createPerm("topic:myTopic:remove");
                assertEquals(assigned.toString(), toCheck.toString());
                return assigned.implies(toCheck);
            }
        };

        ConnectionContext context = createContext(subject);

        filter.removeDestination(context, dest, 1000);
    }

    @Test(expected=UnauthorizedException.class)
    public void testAddConsumerNotAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);

        Subject subject = new PermsSubject();
        ConnectionContext context = createContext(subject);
        ConsumerInfo info = new ConsumerInfo(null);
        info.setDestination(dest);

        filter.addConsumer(context, info);
    }

    @Test
    public void testAddConsumerAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);

        Subject subject = new PermsSubject() {
            @Override
            public boolean isPermitted(Permission toCheck) {
                Permission assigned = createPerm("topic:myTopic:read");
                assertEquals(assigned.toString(), toCheck.toString());
                return assigned.implies(toCheck);
            }
        };

        ConnectionContext context = createContext(subject);
        ConsumerInfo info = new ConsumerInfo(null);
        info.setDestination(dest);

        filter.addConsumer(context, info);
    }

    @Test
    public void testAddProducerWithoutDestination() throws Exception {
        Subject subject = new PermsSubject();
        ConnectionContext context = createContext(subject);
        ProducerInfo info = new ProducerInfo(null);
        filter.addProducer(context, info);
    }

    @Test(expected=UnauthorizedException.class)
    public void testAddProducerNotAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);

        Subject subject = new PermsSubject();
        ConnectionContext context = createContext(subject);
        ProducerInfo info = new ProducerInfo(null);
        info.setDestination(dest);

        filter.addProducer(context, info);
    }

    @Test
    public void testAddProducerAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);

        Subject subject = new PermsSubject() {
            @Override
            public boolean isPermitted(Permission toCheck) {
                Permission assigned = createPerm("topic:myTopic:write");
                assertEquals(assigned.toString(), toCheck.toString());
                return assigned.implies(toCheck);
            }
        };

        ConnectionContext context = createContext(subject);
        ProducerInfo info = new ProducerInfo(null);
        info.setDestination(dest);

        filter.addProducer(context, info);
    }

    @Test(expected=UnauthorizedException.class)
    public void testBrokerExchangeSendNotAuthorized() throws Exception {
        String name = "myTopic";

        ActiveMQDestination dest = new ActiveMQTopic(name);
        ActiveMQTextMessage message = new ActiveMQTextMessage();
        message.setDestination(dest);
        message.setText("Hello, world!");

        Subject subject = new PermsSubject();
        ConnectionContext context = createContext(subject);
        ProducerBrokerExchange exchange = new ProducerBrokerExchange();
        exchange.setConnectionContext(context);

        filter.send(exchange, message);
    }

    @Test
    public void testBrokerExchangeSendAuthorized() throws Exception {
        String name = "myTopic";
        ActiveMQDestination dest = new ActiveMQTopic(name);
        ActiveMQTextMessage message = new ActiveMQTextMessage();
        message.setDestination(dest);
        message.setText("Hello, world!");

        Subject subject = new PermsSubject() {
            @Override
            public boolean isPermitted(Permission toCheck) {
                Permission assigned = createPerm("topic:myTopic:write");
                assertEquals(assigned.toString(), toCheck.toString());
                return assigned.implies(toCheck);
            }
        };

        ConnectionContext context = createContext(subject);
        ProducerBrokerExchange exchange = new ProducerBrokerExchange();
        exchange.setConnectionContext(context);

        filter.send(exchange, message);
    }

    protected Permission createPerm(String perm) {
        return new DestinationActionPermissionResolver().createPermission(perm);
    }

    private static class PermsSubject extends SubjectAdapter {

        @Override
        public PrincipalCollection getPrincipals() {
            return new SimplePrincipalCollection("foo", "someRealm");
        }

        @Override
        public boolean isPermittedAll(Collection<Permission> permissions) {
            assertNotNull(permissions);
            assertEquals(1, permissions.size());
            return isPermitted(permissions.iterator().next());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Swaggy Jenkins
 *
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 * Generated by: https://github.com/openapitools/openapi-generator.git
 */

using Xunit;

using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Api;
using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;

namespace Org.OpenAPITools.Test.Model
{
    /// <summary>
    ///  Class for testing PipelineRunImpllinks
    /// </summary>
    /// <remarks>
    /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
    /// Please update the test case below to test the model.
    /// </remarks>
    public class PipelineRunImpllinksTests : IDisposable
    {
        // TODO uncomment below to declare an instance variable for PipelineRunImpllinks
        //private PipelineRunImpllinks instance;

        public PipelineRunImpllinksTests()
        {
            // TODO uncomment below to create an instance of PipelineRunImpllinks
            //instance = new PipelineRunImpllinks();
        }

        public void Dispose()
        {
            // Cleanup when everything is done.
        }

        /// <summary>
        /// Test an instance of PipelineRunImpllinks
        /// </summary>
        [Fact]
        public void PipelineRunImpllinksInstanceTest()
        {
            // TODO uncomment below to test "IsType" PipelineRunImpllinks
            //Assert.IsType<PipelineRunImpllinks>(instance);
        }

        /// <summary>
        /// Test the property 'Nodes'
        /// </summary>
        [Fact]
        public void NodesTest()
        {
            // TODO unit test for the property 'Nodes'
        }
        /// <summary>
        /// Test the property 'Log'
        /// </summary>
        [Fact]
        public void LogTest()
        {
            // TODO unit test for the property 'Log'
        }
        /// <summary>
        /// Test the property 'Self'
        /// </summary>
        [Fact]
        public void SelfTest()
        {
            // TODO unit test for the property 'Self'
        }
        /// <summary>
        /// Test the property 'Actions'
        /// </summary>
        [Fact]
        public void ActionsTest()
        {
            // TODO unit test for the property 'Actions'
        }
        /// <summary>
        /// Test the property 'Steps'
        /// </summary>
        [Fact]
        public void StepsTest()
        {
            // TODO unit test for the property 'Steps'
        }
        /// <summary>
        /// Test the property 'Class'
        /// </summary>
        [Fact]
        public void ClassTest()
        {
            // TODO unit test for the property 'Class'
        }

    }

}


text:
var PJS, PJSEditor, expect, testData;

expect = require("chai").expect;

PJS = require("../../src/js/propertiesJS");

PJSEditor = require("../../src/js/modules/editor");

testData = require("../test-data");

describe("Test abstract editor", function() {
  var objs, pe, pjs, schema;
  pjs = null;
  objs = null;
  schema = null;
  pe = null;
  before(function() {
    testData.createDivs(this.test.parent.title);
    return pe = $(".propertyEditor");
  });
  beforeEach(function() {
    var ref;
    return ref = testData.clone(), objs = ref[0], schema = ref[1], ref;
  });
  return describe("Test abstract editor", function() {
    it("check abstract Editor functions", function() {
      var editor, settings, tr;
      schema.editors = testData.getEditors(schema.editors, ["name"]);
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      expect(pjs.objectHandler.objs).to.be.length(1);
      expect(pjs.schema).to.be.equal(schema);
      expect(pjs.editors).to.be.length(1);
      editor = pjs.editors[0];
      tr = pe.find("tbody tr:eq(0)");
      expect(editor.changed).to.be.False;
      expect(editor.errors).to.be.length(0);
      expect(editor.lastValue).to.be.unDefined;
      expect(editor.fieldName).to.be.equal(schema.editors[0].field);
      expect(editor.on).to.be.exist;
      expect(editor.off).to.be.exist;
      settings = editor.settings;
      expect(settings).to.be.equal(schema.editors[0]);
      expect(tr.find("td:eq(0)").text()).to.be.equal(editor.settings.title);
      expect(tr.hasClass("required")).to.be["true"];
      expect(tr.hasClass("featured")).to.be["true"];
      expect(tr.hasClass(settings.type)).to.be["true"];
      expect(tr.attr("data-field")).to.be.equal(settings.field);
      expect(editor.isEnabled()).to.be["true"];
      expect(editor.disable()).to.be.equal(editor);
      expect(editor.isEnabled()).to.be["false"];
      expect(editor.input.attr("disabled")).to.be.equal("disabled");
      expect(tr.hasClass("disabled")).to.be["true"];
      expect(editor.enable()).to.be.equal(editor);
      expect(editor.isEnabled()).to.be["true"];
      expect(editor.input.attr("disabled")).to.be.unDefined;
      expect(tr.hasClass("disabled")).to.be["false"];
      editor.setInputValue("123");
      expect(editor.lastValue).to.be.equal("123");
      expect(pjs.workObject[editor.fieldName]).to.be.equal(objs[0][settings.field]);
      editor.valueChanged("555");
      expect(pjs.workObject[editor.fieldName]).to.be.equal("555");
      editor.changeValue("888", false);
      expect(editor.lastValue).to.be.equal("888");
      expect(pjs.workObject[editor.fieldName]).to.be.equal(objs[0][settings.field]);
      editor.changeValue("999", true);
      expect(editor.lastValue).to.be.equal("999");
      return expect(pjs.workObject[editor.fieldName]).to.be.equal("999");
    });
    it("check editor abstract methods", function() {
      var editor;
      editor = new PJSEditor(null, schema);
      expect(function() {
        return editor.createInput();
      }).to["throw"](/Abstract/);
      return expect(function() {
        return editor.getInputValue();
      }).to["throw"](/Abstract/);
    });
    it("check schema disabled property", function() {
      var editor, tr;
      schema.editors = testData.getEditors(schema.editors, ["name"]);
      schema.editors[0].disabled = true;
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      editor = pjs.editors[0];
      tr = pe.find("tbody tr:eq(0)");
      expect(editor.isEnabled()).to.be["false"];
      expect(editor.input.attr("disabled")).to.be.equal("disabled");
      return expect(tr.hasClass("disabled")).to.be["true"];
    });
    it("check editor onChanged event", function(done) {
      var editor;
      schema.editors = testData.getEditors(schema.editors, ["name"]);
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      editor = pjs.editors[0];
      schema.editors[0].onChanged = function(_editor, _newValue, _obj) {
        expect(_editor).to.be.equal(editor);
        expect(_newValue).to.be.equal("111");
        expect(_obj).to.be.exist;
        expect(pjs.getObject()).to.be.equal(_obj);
        expect(_obj[editor.fieldName]).to.be.equal("111");
        return done();
      };
      return editor.valueChanged("111");
    });
    it("check schema onChanged event", function(done) {
      var editor;
      schema.editors = testData.getEditors(schema.editors, ["name"]);
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      editor = pjs.editors[0];
      schema.onChanged = function(_editor, _newValue, _obj) {
        expect(_editor).to.be.equal(editor);
        expect(_newValue).to.be.equal("123");
        expect(_obj[_editor.fieldName]).to.be.equal("123");
        return done();
      };
      return editor.valueChanged("123");
    });
    it("check editor event-emitter", function(done) {
      var editor;
      schema.editors = testData.getEditors(schema.editors, ["name"]);
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      editor = pjs.editors[0];
      editor.on("changed", function(_editor, _newValue, _obj) {
        expect(_editor).to.be.equal(editor);
        expect(_newValue).to.be.equal("234");
        expect(_obj[_editor.fieldName]).to.be.equal("234");
        return done();
      });
      return editor.valueChanged("234");
    });
    it("check PJS event-emitter", function(done) {
      var editor;
      schema.editors = testData.getEditors(schema.editors, ["name"]);
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      editor = pjs.editors[0];
      pjs.on("changed", function(_editor, _newValue, _obj) {
        expect(_editor).to.be.equal(editor);
        expect(_newValue).to.be.equal("345");
        expect(_obj[_editor.fieldName]).to.be.equal("345");
        return done();
      });
      return editor.valueChanged("345");
    });
    it("check PJS field-changed event-emitter", function(done) {
      var editor;
      schema.editors = testData.getEditors(schema.editors, ["name"]);
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      editor = pjs.editors[0];
      pjs.on(editor.fieldName + "-changed", function(_editor, _newValue, _obj) {
        expect(_editor).to.be.equal(editor);
        expect(_newValue).to.be.equal("555");
        expect(_obj[_editor.fieldName]).to.be.equal("555");
        return done();
      });
      return editor.valueChanged("555");
    });
    it("check PJS auto disable/enable editors", function() {
      var editorActive, editorAge;
      schema.editors = testData.getEditors(schema.editors, ["age", "active"]);
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      editorAge = pjs.editors[0];
      editorActive = pjs.editors[1];
      expect(editorActive.getInputValue()).to.be["true"];
      expect(editorAge.isEnabled()).to.be["false"];
      editorActive.valueChanged(false);
      expect(editorAge.isEnabled()).to.be["true"];
      editorActive.valueChanged(true);
      return expect(editorAge.isEnabled()).to.be["false"];
    });
    return it("check PJS editor formatter", function() {
      var editor, input, settings, tr;
      schema.editors = testData.getEditors(schema.editors, ["distance"]);
      pjs = new PJS(".propertyEditor", schema, objs[0]);
      editor = pjs.editors[0];
      settings = editor.settings;
      tr = pe.find("tbody tr:eq(0)");
      input = tr.find("input");
      editor.settings.formatter = function(value, e) {
        expect(value).to.be.equal(1230);
        expect(e).to.be.equal(editor);
        return "1km 230m";
      };
      editor.setInputValue(1230);
      return expect(input.val()).to.be.equal("1km 230m");
    });
  });
});


text:
import Image, tempfile, math

from os.path import abspath, dirname, join

from opencv.highgui import cvCreateFileCapture, cvQueryFrame
from opencv.cv import cvClearMemStorage, cvCopy, cvCreateImage, cvCvtColor, \
                      cvEqualizeHist, cvHaarDetectObjects, \
                      cvLoadHaarClassifierCascade, cvResize, cvRound, cvSize, \
                      CV_HAAR_DO_CANNY_PRUNING, CV_INTER_LINEAR, CV_BGR2GRAY, \
                      IPL_DEPTH_8U, cvCreateMemStorage

CASCADES_DIR   = dirname(abspath(__file__))
CASCADES_NAMES = ['haarcascade_frontalface_alt_tree.xml']
CASCADES = [ join(CASCADES_DIR, name) for name in CASCADES_NAMES ]

MIN_SIZE             = cvSize(100, 100)
IMAGE_SCALE          = 1.3
MIN_NEIGHBORS        = 3
HAAR_SCALE           = 1.3
HAAR_FLAGS           = CV_HAAR_DO_CANNY_PRUNING
DEFAULT_ROTATE_ANGLE = 45
COPY_DEPTH           = 8
COPY_CHANNELS        = 1
STORAGE              = cvCreateMemStorage(0)

def _detect(image):
    """ Detects faces on `image`
    Parameters:
        @image: image file path

    Returns:
        [((x1, y1), (x2, y2)), ...] List of coordenates for top-left
                                    and bottom-right corner
    """
    # the OpenCV API says this function is obsolete, but we can't
    # cast the output of cvLoad to a HaarClassifierCascade, so use
    # this anyways the size parameter is ignored
    capture = cvCreateFileCapture(image)

    if not capture:
        return []

    frame = cvQueryFrame(capture)
    if not frame:
        return []

    img = cvCreateImage(cvSize(frame.width, frame.height),
                        IPL_DEPTH_8U, frame.nChannels)
    cvCopy(frame, img)

    # allocate temporary images
    gray          = cvCreateImage((img.width, img.height),
                                  COPY_DEPTH, COPY_CHANNELS)
    width, height = (cvRound(img.width / IMAGE_SCALE),
                     cvRound(img.height / IMAGE_SCALE))
    small_img     = cvCreateImage((width, height), COPY_DEPTH, COPY_CHANNELS)

    # convert color input image to grayscale
    cvCvtColor(img, gray, CV_BGR2GRAY)

    # scale input image for faster processing
    cvResize(gray, small_img, CV_INTER_LINEAR)
    cvEqualizeHist(small_img, small_img)
    cvClearMemStorage(STORAGE)

    coords = []
    for haar_file in CASCADES:
        cascade = cvLoadHaarClassifierCascade(haar_file, cvSize(1, 1))
        if cascade:
            faces = cvHaarDetectObjects(small_img, cascade, STORAGE, HAAR_SCALE,
                                        MIN_NEIGHBORS, HAAR_FLAGS, MIN_SIZE) or []
            for face_rect in faces:
                # the input to cvHaarDetectObjects was resized, so scale the
                # bounding box of each face and convert it to two CvPoints
                x, y = face_rect.x, face_rect.y
                pt1 = (int(x * IMAGE_SCALE), int(y * IMAGE_SCALE))
                pt2 = (int((x + face_rect.width) * IMAGE_SCALE),
                       int((y + face_rect.height) * IMAGE_SCALE))
                coords.append((pt1, pt2))
    return coords

def detect(image):
    """ Aims to detect faces in `image`. If no faces are detected,
    the image is rotated DEFAULT_ROTATE_ANGLE left and right trying to
    get potentially inclined faces.

    Parameters:
        @image: image path

    Returns:
        [((x1, y1), (x2, y2)), ...] List of coordenates for top-left
                                    and bottom-right corner

    Rotated coordinates are rotated back to original image position.
    """
    coords = _detect(image) or []

    if not coords:
        img = Image.open(image)

        for degree in (-DEFAULT_ROTATE_ANGLE, DEFAULT_ROTATE_ANGLE):
            tmp = tempfile.NamedTemporaryFile(suffix='.' + image.split('.')[-1])
            img.rotate(degree).save(tmp)
            coords += [rotate(-1 * degree, box) for box in _detect(tmp.name)]
            tmp.close()
    return coords

def rotate(degree, box):
    """ Rotates `degree` the coords on `box` using the `box`
    center as the rotate axis.

    Parameters:
        @degree: Degrees to rotate back the box
        @box: Tuple with top-left and bottom-right coordinates

    Returns:
        [(x1, y1), (x2, y2)]: Rotated top-left and bottom-right
                              coordinats
    """
    (x1, y1), (x2, y2) = box
    orig_x, orig_y = int((x2 - x1)/2), int((y2 - y1)/2)

    x0 = x1 - orig_x
    y0 = y1 - orig_y

    rad = math.radians(degree) # conver to radians
    cos_rad = math.cos(rad)
    sin_rad = math.sin(rad)

    new_x = int((x0 * cos_rad) - (y0 * sin_rad))
    new_y = int((x0 * sin_rad) + (y0 * cos_rad))

    return [(new_x + orig_x, new_y + orig_y),
            (new_x + orig_x + x2 - x1, new_y + orig_y + y2 - y1)]


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pezicula brenckleana Seaver

### Remarks
null


text:
package org.normandra.orientdb.data;

import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import org.apache.commons.lang.NullArgumentException;
import org.normandra.EntitySession;
import org.normandra.NormandraException;
import org.normandra.association.ElementIdentity;
import org.normandra.meta.EntityMeta;

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

/**
 * Date: 9/23/14
 */
public class OrientElementIdentity<T> implements ElementIdentity<T> {
    private final EntityMeta entity;

    public OrientElementIdentity(final EntityMeta entity) {
        if (null == entity) {
            throw new NullArgumentException("entity context");
        }
        this.entity = entity;
    }

    @Override
    public ORID fromKey(final EntitySession session, final Object key) {
        if (null == key) {
            return null;
        }
        final OrientDatabaseSession orientdb = (OrientDatabaseSession) session;
        final OIdentifiable rid = orientdb.findIdByKey(this.entity, key);
        return rid != null ? rid.getIdentity() : null;
    }

    @Override
    public ORID fromEntity(final EntitySession session, final T value) {
        if (null == value) {
            return null;
        }
        final Object key = this.entity.getId().fromEntity(value);
        return this.fromKey(session, key);
    }

    @Override
    public List<?> fromEntities(final EntitySession session, final T... values) {
        if (null == values || values.length <= 0) {
            return Collections.emptyList();
        }
        final List<ORID> list = new ArrayList<>(values.length);
        for (final Object value : values) {
            final Object key = this.entity.getId().fromEntity(value);
            final ORID rid = this.fromKey(session, key);
            if (rid != null) {
                list.add(rid);
            }
        }
        return Collections.unmodifiableList(list);
    }

    @Override
    public T toEntity(final EntitySession session, final Object value) throws NormandraException {
        return (T) session.get(this.entity, value);
    }

    @Override
    public List toEntities(final EntitySession session, final Object... values) throws NormandraException {
        return session.get(this.entity, values);
    }
}


text:
package org.apache.flink.table.runtime.arrow.readers;

import org.apache.flink.annotation.Internal;

import org.apache.arrow.vector.VarBinaryVector;

/**
 * {@link ArrowFieldReader} for VarBinary.
 */
@Internal
public final class VarBinaryFieldReader extends ArrowFieldReader<byte[]> {

	public VarBinaryFieldReader(VarBinaryVector varBinaryVector) {
		super(varBinaryVector);
	}

	@Override
	public byte[] read(int index) {
		return ((VarBinaryVector) getValueVector()).get(index);
	}
}


text:
@interface JOYFullReportElement : JOYElement<NSCopying>
- (instancetype)initWithDevice:(IOHIDDeviceRef) device reportID:(unsigned)reportID;
- (void)updateValue:(NSData *)value;
@end


text:
/**
 * C hash table type used to implement Map<T>
 *
 * @author colin.gordon
 */
package com.samsung.sjs.backend.asts.c.types;

public final class CHashTable extends CType {
    private CType elemType;
    public CHashTable(CType elem) {
        super(1);
        this.elemType = elem;
    }
    @Override
    public String toSource() { return "map_t*"; }
}


text:
package org.teachingkidsprogramming.section02methods.Variations;

import org.teachingextensions.logo.Tortoise;
import org.teachingextensions.logo.utils.ColorUtils.PenColors.Reds;

public class Houses_Pointy
{
  public static void main(String[] args)
  {
    Tortoise.show();
    Tortoise.setSpeed(10);
    Tortoise.setX(200);
    int Height = 40;
    drawHouseFlatRoof(Height);
    drawHouseFlatRoof(120);
    drawHouseFlatRoof(90);
    drawHouseFlatRoof(20);
    drawHousePointyRoof(Height);
    drawHousePointyRoof(120);
    // drawHousePointyRoof(90);
    // drawHousePointyRoof(20);
    drawHouseTrapezoidRoof(Height);
    drawHouseTrapezoidRoof(120);
    //  drawHouseTrapezoidRoof(90);
    //drawHouseTrapezoidRoof(20);
  }
  private static void drawHouseFlatRoof(int Height)
  {
    Tortoise.setPenColor(Reds.Red);
    Tortoise.setPenWidth(3);
    Tortoise.move(Height);
    drawFlatRoof();
    Tortoise.move(Height);
    Tortoise.turn(-90);
    Tortoise.move(20);
    Tortoise.turn(-90);
  }
  private static void drawHouseTrapezoidRoof(int Height)
  {
    Tortoise.setPenColor(Reds.Red);
    Tortoise.setPenWidth(3);
    Tortoise.move(Height);
    drawTrapezoidRoof();
    Tortoise.move(Height);
    Tortoise.turn(-90);
    Tortoise.move(20);
    Tortoise.turn(-90);
  }
  private static void drawHousePointyRoof(int Height)
  {
    Tortoise.setPenColor(Reds.Red);
    Tortoise.setPenWidth(3);
    Tortoise.move(Height);
    drawPointyRoof();
    Tortoise.move(Height);
    Tortoise.turn(-90);
    Tortoise.move(20);
    Tortoise.turn(-90);
  }
  private static void drawFlatRoof()
  {
    Tortoise.turn(90);
    Tortoise.move(30);
    Tortoise.turn(90);
  }
  private static void drawTrapezoidRoof()
  {
    Tortoise.turn(30);
    Tortoise.move(15);
    Tortoise.turn(60);
    Tortoise.move(15);
    Tortoise.turn(50);
    Tortoise.move(15);
    Tortoise.turn(40);
  }
  private static void drawPointyRoof()
  {
    Tortoise.turn(45);
    Tortoise.move(15);
    Tortoise.turn(90);
    Tortoise.move(15);
    Tortoise.turn(45);
  }
}


text:
#character-display-container {
  position: absolute;
  top: 200px;
  width: 100%; }
  #character-display-container #character-two-container {
    text-align: right; }

/*# sourceMappingURL=character-display.css.map */


text:
package converter

import "github.com/cbguder/unc/models"

type Importer interface {
	Import(string) ([]models.Note, error)
}


text:
BASERULEDIR=/var/lib/yara-rules
INDEXFILE=$BASERULEDIR/rules.yara
REPORULEDIR=$BASERULEDIR/rules/
RULESTODEPLOY=(malware_index.yar CVE_Rules_index.yar Crypto_index.yar Antidebug_AntiVM_index.yar Exploit-Kits_index.yar Malicious_Documents_index.yar Webshells_index.yar)

# first check for the ruledir, if its not there clone and update permissions
if ! [ -d $REPORULEDIR ]; then
  cd /var/lib/yara-rules && git clone https://github.com/yara-rules/rules.git
  chown -R fsf:fsf $REPORULEDIR
  chmod -R 744 $REPORULEDIR
fi

# next update the rules if there be updates to be had
cd $REPORULEDIR

if [[ $(git status --branch --porcelain | grep 'behind') = *behind* ]]; then
  git pull -f
fi

# next make sure the appropriate yara-rules/rules/*_index.yar are in the $INDEXFILE
if ! [[ $(grep 'yara-rules/rules' $INDEXFILE) = *yara-rules/rules* ]]; then
# Add the header
  sed -i -e "\$a\/\/yara-rules/rules" $INDEXFILE
  # add the rules we care about
  for RULE in ${RULESTODEPLOY[@]}; do
    sed -i -e "\$ainclude\ \"$REPORULEDIR$RULE\"" $INDEXFILE
  done
fi


text:
from fairseq.tasks.translation import TranslationTask
from fairseq.tasks.language_modeling import LanguageModelingTask
from fairseq import checkpoint_utils
import argparse
from fairseq.tasks import register_task
import torch

@register_task("noisy_channel_translation")
class NoisyChannelTranslation(TranslationTask):
    """
    Rescore the top k candidates from each beam using noisy channel modeling
    """

    @staticmethod
    def add_args(parser):
        """Add task-specific arguments to the parser."""
        TranslationTask.add_args(parser)
        # fmt: off
        parser.add_argument('--channel-model', metavar='FILE',
                            help='path to P(S|T) model. P(S|T) and P(T|S) must share source and target dictionaries.')
        parser.add_argument('--combine-method', default='lm_only',
                            choices=['lm_only', 'noisy_channel'],
                            help="""method for combining direct and channel model scores.
                                    lm_only: decode with P(T|S)P(T)
                                    noisy_channel: decode with 1/t P(T|S) + 1/s(P(S|T)P(T))""")
        parser.add_argument('--normalize-lm-scores-by-tgt-len', action='store_true', default=False,
                            help='normalize lm score by target length instead of source length')
        parser.add_argument('--channel-scoring-type', default='log_norm', choices=['unnormalized', 'log_norm', 'k2_separate', 'src_vocab', 'src_vocab_batched'],
                            help="Normalize bw scores with log softmax or return bw scores without log softmax")
        parser.add_argument('--top-k-vocab', default=0, type=int,
                            help='top k vocab IDs to use with `src_vocab` in channel model scoring')
        parser.add_argument('--k2', default=50, type=int,
                            help='the top k2 candidates to rescore with the noisy channel model for each beam')
        parser.add_argument('--ch-wt', default=1, type=float,
                            help='weight for the channel model')
        parser.add_argument('--lm-model', metavar='FILE',
                            help='path to lm model file, to model P(T). P(T) must share the same vocab as the direct model on the target side')
        parser.add_argument('--lm-data', metavar='FILE',
                            help='path to lm model training data for target language, used to properly load LM with correct dictionary')
        parser.add_argument('--lm-wt', default=1, type=float,
                            help='the weight of the lm in joint decoding')
        # fmt: on

    def build_generator(
        self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None
    ):
        if getattr(args, "score_reference", False):
            raise NotImplementedError()
        else:
            from .noisy_channel_sequence_generator import NoisyChannelSequenceGenerator
            use_cuda = torch.cuda.is_available() and not self.args.cpu
            assert self.args.lm_model is not None, '--lm-model required for noisy channel generation!'
            assert self.args.lm_data is not None, '--lm-data required for noisy channel generation to map between LM and bitext vocabs'
            if self.args.channel_model is not None:
                import copy
                ch_args_task = copy.deepcopy(self.args)
                tmp = ch_args_task.source_lang
                ch_args_task.source_lang = ch_args_task.target_lang
                ch_args_task.target_lang = tmp
                ch_args_task._name = 'translation'
                channel_task = TranslationTask.setup_task(ch_args_task)

            arg_dict = {}
            arg_dict['task'] = 'language_modeling'
            arg_dict['sample_break_mode'] = 'eos'
            arg_dict['data'] = self.args.lm_data
            arg_dict['output_dictionary_size'] = -1
            lm_args = argparse.Namespace(**arg_dict)
            lm_task = LanguageModelingTask.setup_task(lm_args)
            lm_dict = lm_task.output_dictionary

            if self.args.channel_model is not None:
                channel_models, _ = checkpoint_utils.load_model_ensemble(self.args.channel_model.split(':'), task=channel_task)

                for model in channel_models:
                    model.make_generation_fast_(
                        beamable_mm_beam_size=None if args.no_beamable_mm else args.beam,
                        need_attn=args.print_alignment,
                    )
                    if self.args.fp16:
                        model.half()
                    if use_cuda:
                        model.cuda()
            else:
                channel_models = None

            lm_models, _ = checkpoint_utils.load_model_ensemble(self.args.lm_model.split(':'), task=lm_task)

            for model in lm_models:
                model.make_generation_fast_(
                    beamable_mm_beam_size=None if args.no_beamable_mm else args.beam,
                    need_attn=args.print_alignment,
                )
                if self.args.fp16:
                    model.half()
                if use_cuda:
                    model.cuda()
            return NoisyChannelSequenceGenerator(
                combine_method=self.args.combine_method,
                tgt_dict=self.target_dictionary,
                src_dict=self.source_dictionary,
                beam_size=getattr(args, 'beam', 5),
                max_len_a=getattr(args, 'max_len_a', 0),
                max_len_b=getattr(args, 'max_len_b', 200),
                min_len=getattr(args, 'min_len', 1),
                len_penalty=getattr(args, 'lenpen', 1),
                unk_penalty=getattr(args, 'unkpen', 0),
                temperature=getattr(args, 'temperature', 1.),
                match_source_len=getattr(args, 'match_source_len', False),
                no_repeat_ngram_size=getattr(args, 'no_repeat_ngram_size', 0),
                normalize_scores=(not getattr(args, 'unnormalized', False)),
                channel_models=channel_models,
                k2=getattr(self.args, 'k2', 50),
                ch_weight=getattr(self.args, 'ch_wt', 1),
                channel_scoring_type=self.args.channel_scoring_type,
                top_k_vocab=self.args.top_k_vocab,
                lm_models=lm_models,
                lm_dict=lm_dict,
                lm_weight=getattr(self.args, 'lm_wt', 1),
                normalize_lm_scores_by_tgt_len=getattr(self.args, 'normalize_lm_scores_by_tgt_len', False),
            )


text:
<?php
/**
 * Holding a instance of CRama to enable use of $this in subclasses and provide some helpers.
 *
 * @package RamaCore
 */
class CObject {

	/**
	 * Members
	 */
	protected $ra;
	protected $config;
	protected $request;
	protected $data;
	protected $db;
	protected $views;
	protected $session;
	protected $user;

	/**
	 * Constructor, can be instantiated by sending in the $ra reference.
	 */
	protected function __construct($ra=null) {
	  if(!$ra) {
	    $ra = CRama::Instance();
	  }
	  $this->ly       = &$ra;
    $this->config   = &$ra->config;
    $this->request  = &$ra->request;
    $this->data     = &$ra->data;
    $this->db       = &$ra->db;
    $this->views    = &$ra->views;
    $this->session  = &$ra->session;
    $this->user     = &$ra->user;
	}

	/**
	 * Wrapper for same method in CRama. See there for documentation.
	 */
	protected function RedirectTo($urlOrController=null, $method=null, $arguments=null) {
    $this->ly->RedirectTo($urlOrController, $method, $arguments);
  }

	/**
	 * Wrapper for same method in CRama. See there for documentation.
	 */
	protected function RedirectToController($method=null, $arguments=null) {
    $this->ly->RedirectToController($method, $arguments);
  }

	/**
	 * Wrapper for same method in CRama. See there for documentation.
	 */
	protected function RedirectToControllerMethod($controller=null, $method=null, $arguments=null) {
    $this->ly->RedirectToControllerMethod($controller, $method, $arguments);
  }

	/**
	 * Wrapper for same method in CRama. See there for documentation.
	 */
  protected function AddMessage($type, $message, $alternative=null) {
    return $this->ly->AddMessage($type, $message, $alternative);
  }

	/**
	 * Wrapper for same method in CRama. See there for documentation.
	 */
	protected function CreateUrl($urlOrController=null, $method=null, $arguments=null) {
    return $this->ly->CreateUrl($urlOrController, $method, $arguments);
  }

}


text:
#import "SPXTableViewCell.h"

@implementation SPXTableViewCell

@end


text:
bootstrap-fileinput
====================

An enhanced HTML 5 file input for Bootstrap 3.x with file preview for images and text, multiple selection, and more. This plugin is inspired by [this blog article](http://www.abeautifulsite.net/blog/2013/08/whipping-file-inputs-into-shape-with-bootstrap-3/) and [Jasny's File Input plugin](http://jasny.github.io/bootstrap/javascript/#fileinput). The plugin enhances these concepts and simplifies the widget initialization with simple HTML markup on a file input. It also offers support for multiple file preview and previewing both images and text types.

![File Input Screenshot](https://lh6.googleusercontent.com/-2niyujIaat0/UyqzA_78OQI/AAAAAAAAADE/f6IJkr11uA8/w666-h418-no/fileinput-screenshot.jpg)

> NOTE: The latest version of the plugin v1.5.0 has been released. Refer the [CHANGE LOG](https://github.com/kartik-v/bootstrap-fileinput/blob/master/CHANGE.md) for details.

## Features

1. The plugin will convert a simple HTML file input to an advanced file picker control. Will help fallback to a normal HTML file input for browsers not supporting JQuery or Javascript.
2. The file input consists of the following three sections with options and templates to control the display:
   - file caption section: to display a brief information of the file(s) selected
   - file action buttons section: to browse, remove, and upload files.
   - file preview section: to display the selected files on client for preview (supports images and text file types). Other file types will be displayed as normal thumbnails.
3. The plugin automatically converts an input with `type = file` to an advanced file picker input if you set its `class = file`. All options to the input can be passed as HTML5 `data` attributes.
4. Ability to select and preview multiple files. Uses HTML 5 File reader API to read and preview files. Displays the progress of files being being loaded onto the preview zone, in case many files are chosen.
5. Offers predefined templates and CSS classes which can be changed to style your file-input display as per your needs.
6. With **v1.5.0**, you can now configure the plugin to show an **initial preview of images/files** with **initial caption**
   (more useful for record update scenarios). Refer the [`initialPreview`](https://github.com/kartik-v/bootstrap-fileinput/blob/master/README.md#initialpreview)
   and [`initialCaption`](https://github.com/kartik-v/bootstrap-fileinput/blob/master/README.md#initialcaption) properties in the plugin options
   section for configuring this.
7. Option to show/hide any or all of the following:
   - caption section
   - preview section
   - upload button
   - remove button
8. Customise the location of the target container elements to display the entire plugin, the caption container, the caption text, the preview container, preview image, and preview status.
9. For text file previews, autowrap the text to the thumbnail width, and show a wrap indicator link to display complete text on hover. You can customize the wrap indicator (which defaults to …).
10. Customise the messages for preview, progress, and files selected.
11. Upload action defaults to form submit. Supports an upload route/server action parameter for custom ajax based upload.
12. Triggers JQuery events for advanced development. Events currently available are `filereset` and `fileclear`.
13. Disabled and readonly file input support.
14. Size of the entire plugin is less than 11KB (about 9KB for the minified JS and 2KB for the minified CSS).

## Demo

View the [plugin documentation](http://plugins.krajee.com/file-input) and [plugin demos](http://plugins.krajee.com/file-input/demo) at Krajee JQuery plugins.

## Pre-requisites

1. [Bootstrap 3.x](http://getbootstrap.com/)
2. Latest [JQuery](http://jquery.com/)
3. Most modern browsers supporting HTML5 file inputs and FileReader API including CSS3 & JQuery. For Internet Explorer, one must use IE versions 10 and above. IE9 and below will work as a normal file input, and will not support multiple file selection or the HTML 5 FileReader API.

## Restrictions
The plugin supports only file input and preview at client level. It does not actually process the upload of the files to the server.

## Installation

### Using Bower
You can use the `bower` package manager to install. Run:

    bower install bootstrap-fileinput

### Using Composer
You can use the `composer` package manager to install. Either run:

    $ php composer.phar require kartik-v/bootstrap-fileinput "dev-master"

or add:

    "kartik-v/bootstrap-fileinput": "dev-master"

to your composer.json file

### Manual Install

You can also manually install the plugin easily to your project. Just download the source [ZIP](https://github.com/kartik-v/bootstrap-fileinput/zipball/master) or [TAR ball](https://github.com/kartik-v/bootstrap-fileinput/tarball/master) and extract the plugin assets (css and js folders) into your project.

## Usage

Step 1: Load the following assets in your header.

```html
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link href="path/to/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="path/to/js/fileinput.min.js" type="text/javascript"></script>
```

If you noticed, you need to load the `jquery.min.js` and `bootstrap.min.css` in addition to the `fileinput.min.css` and `fileinput.min.js`.

Step 2: Initialize the plugin on your page. For example,

```js
// initialize with defaults
$("#input-id").fileinput();

// with plugin options
$("#input-id").fileinput({'showUpload':false, 'previewFileType':'any'});
```

The `#input-id` is the identifier for the input (e.g. `type = file`) on your page, which is hidden automatically by the plugin.

Alternatively, you can directly call the plugin options by setting data attributes to your input field.

```html
<input id="input-id" type="file" class="file" data-preview-file-type="text" >
```

## Documentation

### Plugin Options
The plugin supports these following options:

#### showCaption
_boolean_ whether to display the file caption. Defaults to `true`.

#### showPreview
_boolean_ whether to display the file preview. Defaults to `true`.

#### showRemove
_boolean_ whether to display the file remove/clear button. Defaults to `true`.

#### showUpload
_boolean_ whether to display the file upload button. Defaults to `true`. This will default to a form submit button, unless the uploadUrl is specified.

#### captionClass
_string_ any additional CSS class to append to the caption container.

#### previewClass
_string_ any additional CSS class to append to the preview container.

#### mainClass
_string_ any additional CSS class to append to the main plugin container.

#### mainTemplate
_string_ the template used to render the widget. The following template variables will be parsed:

- `{class}`: any additional CSS class to append to the main widget container.
- `{preview}`: the content parsed by the `previewTemplate` and will be displayed only if `showPreview` is `true`.
- `{caption}`: the content parsed by the `captionTemplate` and will be displayed only if `showCaption` is `true`.
- `{remove}`: the file remove/clear button and will be displayed only if `showRemove` is `true`.
- `{upload}`: the file upload button and will be displayed only if `showUpload` is `true`.
- `{browse}`: the main file browse button to select your files for input.

The `mainTemplate` if not passed, will be automatically set based on `showCaption` settings.

- If `showCaption` is set to `true`, the `mainTemplate` will default to:
```html
{preview}
<div class="input-group {class}">
   {caption}
   <div class="input-group-btn">
       {remove}
       {upload}
       {browse}
   </div>
</div>
```

- If `showCaption` is set to `false`, the `mainTemplate` will default to:
```html
{preview}\n{remove}\n{upload}\n{browse}\n
```

#### initialPreview

_string | array_ the initial preview content to be displayed. You can pass the minimal HTML markup for displaying your image, text, or file.
If set as a string, this will display a single file in the initial preview. If set as an array, it will display all files in the array as an
initial preview (useful for multiple file upload scenarios).

The following CSS classes will need to be added for displaying each file type as per the plugin style theme:

- **image files:** Include CSS class `file-preview-image`
- **text files:** Include CSS class `file-preview-text`
- **other files:** Include CSS class `file-preview-other`

Examples of how you can setup various files for initial preview:

```js
// for image files
initialPreview: [
    "<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>",
    "<img src='/images/jellyfish.jpg' class='file-preview-image' alt='Jelly Fish' title='Jelly Fish'>",
],

// for text files
initialPreview: "<div class='file-preview-text' title='NOTES.txt'>" +
    "This is the sample text file content upto wrapTextLength of 250 characters" +
    "<span class='wrap-indicator' onclick='$(\"#show-detailed-text\").modal(\"show\")' title='NOTES.txt'>[…]</span>" +
    "</div>"

// for other files
initialPreview: "<div class='file-preview-text'>" +
    "<h2><i class='glyphicon glyphicon-file'></i></h2>" +
    "Filename.xlsx" + "</div>"
```

#### initialCaption

_string_ the initial preview caption text to be displayed. If you do not set a value here and `initialPreview` is set to
`true` this will default to `"{preview-file-count} files selected"`, where `{preview-file-count}` is the count of the
files passed in `initialPreview`.

#### captionTemplate
_string_ the template used to render the caption. The following template variables will be parsed:

- `{class}`: any additional CSS class to append to the caption container.

The `captionTemplate` if not set will default to:
```html
<div class="form-control file-caption {class}">
   <span class="glyphicon glyphicon-file"></span> <span class="file-caption-name"></span>
</div>
```

#### previewTemplate
_string_ the template used to render the preview. The following template variables will be parsed:

- `{class}`: any additional CSS class to append to the preview container.

The `previewTemplate` if not set will default to:
```html
<div class="file-preview {class}">
   <div class="file-preview-status text-center text-success"></div>
   <div class="close fileinput-remove text-right">×</div>
   <div class="file-preview-thumbnails"></div>
   <div class="clearfix"></div> +
</div>
```

#### browseLabel
_string_ the label to display for the file picker/browse button. Defaults to `Browse …`.

#### browseIcon
_string_ the icon to display before the label for the file picker/browse button. Defaults to `<i class="glyphicon glyphicon-folder-open"></i>  `.

#### browseClass
_string_ the CSS class for the file picker/browse button. Defaults to `btn btn-primary`.

#### removeLabel
_string_ the label to display for the file remove button. Defaults to `Remove`.

#### removeIcon
_string_ the icon to display before the label for the file picker/remove button. Defaults to `<i class="glyphicon glyphicon-ban-circle"></i>  `.

#### removeClass
_string_ the CSS class for the file remove button. Defaults to `btn btn-default`.

#### uploadLabel
_string_ the label to display for the file upload button. Defaults to `Upload`.

#### uploadIcon
_string_ the icon to display before the label for the file upload button. Defaults to `<i class="glyphicon glyphicon-upload"></i>  `.

#### uploadClass
_string_ the CSS class for the file upload button. Defaults to `btn btn-default`.

#### uploadUrl
_string_ the URL for the upload processing action (typically for ajax based processing). Defaults to `null`. If this is not set or `null`, then the upload button action will default to form submission.

#### msgLoading
_string_ the message displayed when the files are getting read and loaded for preview. Defaults to `Loading …`.

#### msgProgress
_string_ the progress message displayed as each file is loaded for preview. Defaults to `Loaded {percent}% of {file}`. The following variables will be replaced:

- `{percent}`: the percentage of file read and loaded.
- `{file}`: the name of the file being loaded.

#### msgSelected
_string_ the progress message displayed in caption window when multiple (more than one) files are selected. Defaults to `{n} files selected`. The following variables will be replaced:

- `{n}`: the number of files selected.

#### previewFileType
_string_ the type of files that are to be displayed in the preview window. Defaults to `image`. Can be one of the following:

- `image`: Only `image` type files will be shown in preview.
- `text`:  Only `text` type files will be shown in preview.
- `any`: Both `image` and `text` files content will be shown in preview.

Files other than `image` or `text` will be displayed as a thumbnail with the filename in the preview window.

#### wrapTextLength
_integer_ the number of characters after which the content will be stripped/wrapped for text preview. Defaults to `250`.

#### wrapIndicator
_string_ the type of files that are to be displayed in the preview window. Defaults to ` <span class="wrap-indicator" title="{title}">[…]</span>`.  The following variables will be replaced:

- `{title}`: the content of the entire text file that will be displayed as a span title element.

#### elCaptionContainer
_string_ the identifier for the container element containing the caption (e.g. `'#id'`). If not set, will default to the container with CSS class `file-caption` inside the main plugin container.

#### elCaptionText
_string_ the identifier for the container element containing the caption text (e.g. `'#id'`). If not set, will default to the container with CSS class `file-caption-name` inside the main plugin container.

#### elPreviewContainer
_string_ the identifier for the container element containing the preview (e.g. `'#id'`). If not set, will default to the container with CSS class `file-preview` inside the main plugin container.

#### elPreviewImage
_string_ the identifier for the element containing the preview image thumbnails (e.g. `'#id'`). If not set, will default to the container with CSS class `file-preview-thumbnails` inside the main plugin container.

#### elPreviewStatus
_string_ the identifier for the element containing the preview progress status (e.g. `'#id'`). If not set, will default to the container with CSS class `file-preview-status` inside the main plugin container.

### Plugin Events
The plugin supports these events:

#### fileclear
This event is triggered when the file input is cleared with the remove button.

**Example:**
```js
$('#input-id').on('fileclear', function(event) {
    console.log("fileclear");
});
```

#### filereset
This event is triggered when the file input is reset to initial value.

**Example:**
```js
$('#input-id').on('filereset', function(event) {
    console.log("filereset");
});
```

### Plugin Methods
The plugin supports these methods:

#### reset
Reset the file input.
```js
$('#input-id').fileinput('reset');
```

#### clear
Clear the file input.
```js
$('#input-id').fileinput('clear');
```

## License

**bootstrap-fileinput** is released under the BSD 3-Clause License. See the bundled `LICENSE.md` for details.