text:
package com.graphhopper.routing.util;

import com.graphhopper.reader.ReaderRelation;
import com.graphhopper.reader.ReaderWay;
import com.graphhopper.routing.weighting.PriorityWeighting;
import com.graphhopper.util.Helper;
import com.graphhopper.util.InstructionAnnotation;
import com.graphhopper.util.Translation;

import java.util.*;

import static com.graphhopper.routing.util.PriorityCode.*;

/**
 * Defines bit layout of bicycles (not motorcycles) for speed, access and relations (network).
 *

 *
 * @author Peter Karich
 * @author Nop
 * @author ratrun
 */
public class BikeCommonFlagEncoder extends AbstractFlagEncoder {
    /**
     * Reports whether this edge is unpaved.
     */
    public static final int K_UNPAVED = 100;
    protected static final int PUSHING_SECTION_SPEED = 4;
    // Pushing section heighways are parts where you need to get off your bike and push it (German: Schiebestrecke)
    protected final HashSet<String> pushingSectionsHighways = new HashSet<String>();
    protected final HashSet<String> oppositeLanes = new HashSet<String>();
    protected final Set<String> preferHighwayTags = new HashSet<String>();
    protected final Set<String> avoidHighwayTags = new HashSet<String>();
    protected final Set<String> unpavedSurfaceTags = new HashSet<String>();
    private final Map<String, Integer> trackTypeSpeeds = new HashMap<String, Integer>();
    private final Map<String, Integer> surfaceSpeeds = new HashMap<String, Integer>();
    private final Set<String> roadValues = new HashSet<String>();
    private final Map<String, Integer> highwaySpeeds = new HashMap<String, Integer>();
    // convert network tag of bicycle routes into a way route code
    private final Map<String, Integer> bikeNetworkToCode = new HashMap<String, Integer>();
    protected EncodedValue relationCodeEncoder;
    EncodedValue priorityWayEncoder;
    private long unpavedBit = 0;
    private EncodedValue wayTypeEncoder;
    // Car speed limit which switches the preference from UNCHANGED to AVOID_IF_POSSIBLE
    private int avoidSpeedLimit;

    // This is the specific bicycle class
    private String classBicycleKey;

    protected BikeCommonFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts) {
        super(speedBits, speedFactor, maxTurnCosts);
        // strict set, usually vehicle and agricultural/forestry are ignored by cyclists
        restrictions.addAll(Arrays.asList("bicycle", "vehicle", "access"));
        restrictedValues.add("private");
        restrictedValues.add("no");
        restrictedValues.add("restricted");
        restrictedValues.add("military");
        restrictedValues.add("emergency");

        intendedValues.add("yes");
        intendedValues.add("designated");
        intendedValues.add("official");
        intendedValues.add("permissive");

        oppositeLanes.add("opposite");
        oppositeLanes.add("opposite_lane");
        oppositeLanes.add("opposite_track");

        setBlockByDefault(false);
        potentialBarriers.add("gate");
        // potentialBarriers.add("lift_gate");
        potentialBarriers.add("swing_gate");

        absoluteBarriers.add("stile");
        absoluteBarriers.add("turnstile");

        unpavedSurfaceTags.add("unpaved");
        unpavedSurfaceTags.add("gravel");
        unpavedSurfaceTags.add("ground");
        unpavedSurfaceTags.add("dirt");
        unpavedSurfaceTags.add("grass");
        unpavedSurfaceTags.add("compacted");
        unpavedSurfaceTags.add("earth");
        unpavedSurfaceTags.add("fine_gravel");
        unpavedSurfaceTags.add("grass_paver");
        unpavedSurfaceTags.add("ice");
        unpavedSurfaceTags.add("mud");
        unpavedSurfaceTags.add("salt");
        unpavedSurfaceTags.add("sand");
        unpavedSurfaceTags.add("wood");

        roadValues.add("living_street");
        roadValues.add("road");
        roadValues.add("service");
        roadValues.add("unclassified");
        roadValues.add("residential");
        roadValues.add("trunk");
        roadValues.add("trunk_link");
        roadValues.add("primary");
        roadValues.add("primary_link");
        roadValues.add("secondary");
        roadValues.add("secondary_link");
        roadValues.add("tertiary");
        roadValues.add("tertiary_link");

        maxPossibleSpeed = 30;

        setTrackTypeSpeed("grade1", 18); // paved
        setTrackTypeSpeed("grade2", 12); // now unpaved ...
        setTrackTypeSpeed("grade3", 8);
        setTrackTypeSpeed("grade4", 6);
        setTrackTypeSpeed("grade5", 4); // like sand/grass

        setSurfaceSpeed("paved", 18);
        setSurfaceSpeed("asphalt", 18);
        setSurfaceSpeed("cobblestone", 8);
        setSurfaceSpeed("cobblestone:flattened", 10);
        setSurfaceSpeed("sett", 10);
        setSurfaceSpeed("concrete", 18);
        setSurfaceSpeed("concrete:lanes", 16);
        setSurfaceSpeed("concrete:plates", 16);
        setSurfaceSpeed("paving_stones", 12);
        setSurfaceSpeed("paving_stones:30", 12);
        setSurfaceSpeed("unpaved", 14);
        setSurfaceSpeed("compacted", 16);
        setSurfaceSpeed("dirt", 10);
        setSurfaceSpeed("earth", 12);
        setSurfaceSpeed("fine_gravel", 18);
        setSurfaceSpeed("grass", 8);
        setSurfaceSpeed("grass_paver", 8);
        setSurfaceSpeed("gravel", 12);
        setSurfaceSpeed("ground", 12);
        setSurfaceSpeed("ice", PUSHING_SECTION_SPEED / 2);
        setSurfaceSpeed("metal", 10);
        setSurfaceSpeed("mud", 10);
        setSurfaceSpeed("pebblestone", 16);
        setSurfaceSpeed("salt", 6);
        setSurfaceSpeed("sand", 6);
        setSurfaceSpeed("wood", 6);

        setHighwaySpeed("living_street", 6);
        setHighwaySpeed("steps", PUSHING_SECTION_SPEED / 2);

        final int CYCLEWAY_SPEED = 18;  // Make sure cycleway and path use same speed value, see #634
        setHighwaySpeed("cycleway", CYCLEWAY_SPEED);
        setHighwaySpeed("path", 10);
        setHighwaySpeed("footway", 6);
        setHighwaySpeed("pedestrian", 6);
        setHighwaySpeed("track", 12);
        setHighwaySpeed("service", 14);
        setHighwaySpeed("residential", 18);
        // no other highway applies:
        setHighwaySpeed("unclassified", 16);
        // unknown road:
        setHighwaySpeed("road", 12);

        setHighwaySpeed("trunk", 18);
        setHighwaySpeed("trunk_link", 18);
        setHighwaySpeed("primary", 18);
        setHighwaySpeed("primary_link", 18);
        setHighwaySpeed("secondary", 18);
        setHighwaySpeed("secondary_link", 18);
        setHighwaySpeed("tertiary", 18);
        setHighwaySpeed("tertiary_link", 18);

        // special case see tests and #191
        setHighwaySpeed("motorway", 18);
        setHighwaySpeed("motorway_link", 18);
        avoidHighwayTags.add("motorway");
        avoidHighwayTags.add("motorway_link");

        setCyclingNetworkPreference("icn", BEST.getValue());
        setCyclingNetworkPreference("ncn", BEST.getValue());
        setCyclingNetworkPreference("rcn", VERY_NICE.getValue());
        setCyclingNetworkPreference("lcn", PREFER.getValue());
        setCyclingNetworkPreference("mtb", UNCHANGED.getValue());

        setCyclingNetworkPreference("deprecated", AVOID_AT_ALL_COSTS.getValue());

        setAvoidSpeedLimit(71);
    }

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

    @Override
    public int defineWayBits(int index, int shift) {
        // first two bits are reserved for route handling in superclass
        shift = super.defineWayBits(index, shift);
        speedEncoder = new EncodedDoubleValue("Speed", shift, speedBits, speedFactor, highwaySpeeds.get("cycleway"),
                maxPossibleSpeed);
        shift += speedEncoder.getBits();

        unpavedBit = 1L << shift++;
        // 2 bits
        wayTypeEncoder = new EncodedValue("WayType", shift, 2, 1, 0, 3, true);
        shift += wayTypeEncoder.getBits();

        priorityWayEncoder = new EncodedValue("PreferWay", shift, 3, 1, 0, 7);
        shift += priorityWayEncoder.getBits();

        return shift;
    }

    @Override
    public int defineRelationBits(int index, int shift) {
        relationCodeEncoder = new EncodedValue("RelationCode", shift, 3, 1, 0, 7);
        return shift + relationCodeEncoder.getBits();
    }

    @Override
    public long acceptWay(ReaderWay way) {
        String highwayValue = way.getTag("highway");
        if (highwayValue == null) {
            if (way.hasTag("route", ferries)) {
                // if bike is NOT explicitly tagged allow bike but only if foot is not specified
                String bikeTag = way.getTag("bicycle");
                if (bikeTag == null && !way.hasTag("foot") || "yes".equals(bikeTag))
                    return acceptBit | ferryBit;
            }

            // special case not for all acceptedRailways, only platform
            if (way.hasTag("railway", "platform"))
                return acceptBit;

            return 0;
        }

        if (!highwaySpeeds.containsKey(highwayValue))
            return 0;

        String sacScale = way.getTag("sac_scale");
        if (sacScale != null) {
            if ((way.hasTag("highway", "cycleway"))
                    && (way.hasTag("sac_scale", "hiking")))
                return acceptBit;
            if (!isSacScaleAllowed(sacScale))
                return 0;
        }

        // use the way if it is tagged for bikes
        if (way.hasTag("bicycle", intendedValues) ||
            way.hasTag("bicycle", "dismount") ||
            way.hasTag("highway", "cycleway"))
            return acceptBit;

        // accept only if explicitly tagged for bike usage
        if ("motorway".equals(highwayValue) || "motorway_link".equals(highwayValue))
            return 0;

        if (way.hasTag("motorroad", "yes"))
            return 0;

        // do not use fords with normal bikes, flagged fords are in included above
        if (isBlockFords() && (way.hasTag("highway", "ford") || way.hasTag("ford")))
            return 0;

        // check access restrictions
        if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way))
            return 0;

        if (getConditionalTagInspector().isPermittedWayConditionallyRestricted(way))
            return 0;
        else
            return acceptBit;
    }

    boolean isSacScaleAllowed(String sacScale) {
        // other scales are nearly impossible by an ordinary bike, see http://wiki.openstreetmap.org/wiki/Key:sac_scale
        return "hiking".equals(sacScale);
    }

    @Override
    public long handleRelationTags(ReaderRelation relation, long oldRelationFlags) {
        int code = 0;
        if (relation.hasTag("route", "bicycle")) {
            Integer val = bikeNetworkToCode.get(relation.getTag("network"));
            if (val != null)
                code = val;
            else
                code = PriorityCode.PREFER.getValue();  // Assume priority of network "lcn" as bicycle route default
        } else if (relation.hasTag("route", "ferry")) {
            code = AVOID_IF_POSSIBLE.getValue();
        }

        int oldCode = (int) relationCodeEncoder.getValue(oldRelationFlags);
        if (oldCode < code)
            return relationCodeEncoder.setValue(0, code);
        return oldRelationFlags;
    }

    /**
     * Apply maxspeed: In contrast to the implementation of the AbstractFlagEncoder, we assume that
     * we can reach the maxspeed for bicycles in case that the road type speed is higher and not
     * just only 90%.
     *

     *
     * @param way:   needed to retrieve tags
     * @param speed: speed guessed e.g. from the road type or other tags
     * @return The assumed avererage speed.
     */
    @Override
    protected double applyMaxSpeed(ReaderWay way, double speed) {
        double maxSpeed = getMaxSpeed(way);
        if (maxSpeed >= 0) {
            // We strictly obay speed limits, see #600
            if (maxSpeed < speed) {
                return maxSpeed;
            }
        }
        return speed;
    }

    @Override
    public long handleWayTags(ReaderWay way, long allowed, long relationFlags) {
        if (!isAccept(allowed))
            return 0;

        long flags = 0;
        double wayTypeSpeed = getSpeed(way);
        if (!isFerry(allowed)) {
            wayTypeSpeed = applyMaxSpeed(way, wayTypeSpeed);
            flags = handleSpeed(way, wayTypeSpeed, flags);
            flags = handleBikeRelated(way, flags, relationFlags > UNCHANGED.getValue());

            boolean isRoundabout = way.hasTag("junction", "roundabout");
            if (isRoundabout) {
                flags = setBool(flags, K_ROUNDABOUT, true);
            }

        } else {
            double ferrySpeed = getFerrySpeed(way,
                    highwaySpeeds.get("living_street"),
                    highwaySpeeds.get("track"),
                    highwaySpeeds.get("primary"));
            flags = handleSpeed(way, ferrySpeed, flags);
            flags |= directionBitMask;
        }
        int priorityFromRelation = 0;
        if (relationFlags != 0)
            priorityFromRelation = (int) relationCodeEncoder.getValue(relationFlags);

        flags = priorityWayEncoder.setValue(flags, handlePriority(way, wayTypeSpeed, priorityFromRelation));
        return flags;
    }

    int getSpeed(ReaderWay way) {
        int speed = PUSHING_SECTION_SPEED;
        String highwayTag = way.getTag("highway");
        Integer highwaySpeed = highwaySpeeds.get(highwayTag);

        // Under certain conditions we need to increase the speed of pushing sections to the speed of a "highway=cycleway"
        if (way.hasTag("highway", pushingSectionsHighways)
                && ((way.hasTag("foot", "yes") && way.hasTag("segregated", "yes"))
                || way.hasTag("bicycle", "designated") || way.hasTag("bicycle", "official")))
            highwaySpeed = getHighwaySpeed("cycleway");

        String s = way.getTag("surface");
        if (!Helper.isEmpty(s)) {
            Integer surfaceSpeed = surfaceSpeeds.get(s);
            if (surfaceSpeed != null) {
                speed = surfaceSpeed;
                // boost handling for good surfaces but avoid boosting if pushing section
                if (highwaySpeed != null && surfaceSpeed > highwaySpeed) {
                    if (pushingSectionsHighways.contains(highwayTag))
                        speed = highwaySpeed;
                    else
                        speed = surfaceSpeed;
                }
            }
        } else {
            String tt = way.getTag("tracktype");
            if (!Helper.isEmpty(tt)) {
                Integer tInt = trackTypeSpeeds.get(tt);
                if (tInt != null)
                    speed = tInt;
            } else if (highwaySpeed != null) {
                if (!way.hasTag("service"))
                    speed = highwaySpeed;
                else
                    speed = highwaySpeeds.get("living_street");
            }
        }

        // Until now we assumed that the way is no pushing section
        // Now we check that, but only in case that our speed is bigger compared to the PUSHING_SECTION_SPEED
        if (speed > PUSHING_SECTION_SPEED
                && (way.hasTag("highway", pushingSectionsHighways) || way.hasTag("bicycle", "dismount"))) {
            if (!way.hasTag("bicycle", intendedValues)) {
                // Here we set the speed for pushing sections and set speed for steps as even lower:
                if (way.hasTag("highway", "steps"))
                    speed = PUSHING_SECTION_SPEED / 2;
                else
                    speed = PUSHING_SECTION_SPEED;
            } else if (way.hasTag("bicycle", "designated") || way.hasTag("bicycle", "official")) {
                // Here we handle the cases where the OSM tagging results in something similar to "highway=cycleway"
                speed = highwaySpeeds.get("cycleway");
            } else {
                speed = PUSHING_SECTION_SPEED;
            }
            // Increase speed in case of segregated
            if (speed <= PUSHING_SECTION_SPEED && way.hasTag("segregated", "yes"))
                speed = PUSHING_SECTION_SPEED * 2;
        }

        return speed;
    }

    @Override
    public InstructionAnnotation getAnnotation(long flags, Translation tr) {
        int paveType = 0; // paved
        if (isBool(flags, K_UNPAVED))
            paveType = 1; // unpaved

        int wayType = (int) wayTypeEncoder.getValue(flags);
        String wayName = getWayName(paveType, wayType, tr);
        return new InstructionAnnotation(0, wayName);
    }

    String getWayName(int pavementType, int wayType, Translation tr) {
        String pavementName = "";
        if (pavementType == 1)
            pavementName = tr.tr("unpaved");

        String wayTypeName = "";
        switch (wayType) {
            case 0:
                wayTypeName = "";
                break;
            case 1:
                wayTypeName = tr.tr("off_bike");
                break;
            case 2:
                wayTypeName = tr.tr("cycleway");
                break;
            case 3:
                wayTypeName = tr.tr("small_way");
                break;
        }

        if (pavementName.isEmpty()) {
            if (wayType == 0 || wayType == 3)
                return "";
            return wayTypeName;
        } else if (wayTypeName.isEmpty())
            return pavementName;
        else
            return wayTypeName + ", " + pavementName;
    }

    /**
     * In this method we prefer cycleways or roads with designated bike access and avoid big roads
     * or roads with trams or pedestrian.
     *

     *
     * @return new priority based on priorityFromRelation and on the tags in ReaderWay.
     */
    protected int handlePriority(ReaderWay way, double wayTypeSpeed, int priorityFromRelation) {
        TreeMap<Double, Integer> weightToPrioMap = new TreeMap<Double, Integer>();
        if (priorityFromRelation == 0)
            weightToPrioMap.put(0d, UNCHANGED.getValue());
        else
            weightToPrioMap.put(110d, priorityFromRelation);

        collect(way, wayTypeSpeed, weightToPrioMap);

        // pick priority with biggest order value
        return weightToPrioMap.lastEntry().getValue();
    }

    // Conversion of class value to priority. See http://wiki.openstreetmap.org/wiki/Class:bicycle
    private PriorityCode convertClassValueToPriority(String tagvalue) {
        int classvalue;
        try {
            classvalue = Integer.parseInt(tagvalue);
        } catch (NumberFormatException e) {
            return UNCHANGED;
        }

        switch (classvalue) {
            case 3:
                return BEST;
            case 2:
                return VERY_NICE;
            case 1:
                return PREFER;
            case 0:
                return UNCHANGED;
            case -1:
                return AVOID_IF_POSSIBLE;
            case -2:
                return REACH_DEST;
            case -3:
                return AVOID_AT_ALL_COSTS;
            default:
                return UNCHANGED;
        }
    }

    /**
     * @param weightToPrioMap associate a weight with every priority. This sorted map allows
     *                        subclasses to 'insert' more important priorities as well as overwrite determined priorities.
     */
    void collect(ReaderWay way, double wayTypeSpeed, TreeMap<Double, Integer> weightToPrioMap) {
        String service = way.getTag("service");
        String highway = way.getTag("highway");
        if (way.hasTag("bicycle", "designated") || way.hasTag("bicycle", "official")) {
            if ("path".equals(highway))
                weightToPrioMap.put(100d, VERY_NICE.getValue());
            else
                weightToPrioMap.put(100d, PREFER.getValue());
        }

        if ("cycleway".equals(highway)) {
            if (way.hasTag("foot", intendedValues) && !way.hasTag("segregated", "yes"))
                weightToPrioMap.put(100d, PREFER.getValue());
            else
                weightToPrioMap.put(100d, VERY_NICE.getValue());
        }

        double maxSpeed = getMaxSpeed(way);
        if (preferHighwayTags.contains(highway) || maxSpeed > 0 && maxSpeed <= 30) {
            if (maxSpeed < avoidSpeedLimit) {
                weightToPrioMap.put(40d, PREFER.getValue());
                if (way.hasTag("tunnel", intendedValues))
                    weightToPrioMap.put(40d, UNCHANGED.getValue());
            }
        } else if (avoidHighwayTags.contains(highway)
                || maxSpeed >= avoidSpeedLimit && !"track".equals(highway)) {
            weightToPrioMap.put(50d, REACH_DEST.getValue());
            if (way.hasTag("tunnel", intendedValues))
                weightToPrioMap.put(50d, AVOID_AT_ALL_COSTS.getValue());
        }

        if (pushingSectionsHighways.contains(highway)
                || way.hasTag("bicycle", "use_sidepath")
                || "parking_aisle".equals(service)) {
            int pushingSectionPrio = AVOID_IF_POSSIBLE.getValue();
            if (way.hasTag("bicycle", "yes") || way.hasTag("bicycle", "permissive"))
                pushingSectionPrio = PREFER.getValue();
            if (way.hasTag("bicycle", "designated") || way.hasTag("bicycle", "official"))
                pushingSectionPrio = VERY_NICE.getValue();
            if (way.hasTag("foot", "yes")) {
                pushingSectionPrio = Math.max(pushingSectionPrio - 1, WORST.getValue());
                if (way.hasTag("segregated", "yes"))
                    pushingSectionPrio = Math.min(pushingSectionPrio + 1, BEST.getValue());
            }
            weightToPrioMap.put(100d, pushingSectionPrio);
        }

        if (way.hasTag("railway", "tram"))
            weightToPrioMap.put(50d, AVOID_AT_ALL_COSTS.getValue());

        String classBicycleValue = way.getTag(classBicycleKey);
        if (classBicycleValue != null) {
            // We assume that humans are better in classifying preferences compared to our algorithm above -> weight = 100
            weightToPrioMap.put(100d, convertClassValueToPriority(classBicycleValue).getValue());
        } else {
            String classBicycle = way.getTag("class:bicycle");
            if (classBicycle != null)
                weightToPrioMap.put(100d, convertClassValueToPriority(classBicycle).getValue());
        }

        // Increase the priority for scenic routes or in case that maxspeed limits our average speed as compensation. See #630
        if (way.hasTag("scenic", "yes") || maxSpeed > 0 && maxSpeed < wayTypeSpeed) {
            if (weightToPrioMap.lastEntry().getValue() < BEST.getValue())
                // Increase the prio by one step
                weightToPrioMap.put(110d, weightToPrioMap.lastEntry().getValue() + 1);
        }
    }

    /**
     * Handle surface and wayType encoding
     */
    long handleBikeRelated(ReaderWay way, long encoded, boolean partOfCycleRelation) {
        String surfaceTag = way.getTag("surface");
        String highway = way.getTag("highway");
        String trackType = way.getTag("tracktype");

        // Populate unpavedBit
        if ("track".equals(highway) && (trackType == null || !"grade1".equals(trackType))
                || "path".equals(highway) && surfaceTag == null
                || unpavedSurfaceTags.contains(surfaceTag)) {
            encoded = setBool(encoded, K_UNPAVED, true);
        }

        WayType wayType;
        if (roadValues.contains(highway))
            wayType = WayType.ROAD;
        else
            wayType = WayType.OTHER_SMALL_WAY;

        boolean isPushingSection = isPushingSection(way);
        if (isPushingSection && !partOfCycleRelation || "steps".equals(highway))
            wayType = WayType.PUSHING_SECTION;

        if (way.hasTag("bicycle", intendedValues)) {
            if (isPushingSection && !way.hasTag("bicycle", "designated"))
                wayType = WayType.OTHER_SMALL_WAY;
            else if (wayType == WayType.OTHER_SMALL_WAY || wayType == WayType.PUSHING_SECTION)
                wayType = WayType.CYCLEWAY;
        } else if ("cycleway".equals(highway))
            wayType = WayType.CYCLEWAY;

        return wayTypeEncoder.setValue(encoded, wayType.getValue());
    }

    @Override
    public long setBool(long flags, int key, boolean value) {
        switch (key) {
            case K_UNPAVED:
                return value ? flags | unpavedBit : flags & ~unpavedBit;
            default:
                return super.setBool(flags, key, value);
        }
    }

    @Override
    public boolean isBool(long flags, int key) {
        switch (key) {
            case K_UNPAVED:
                return (flags & unpavedBit) != 0;
            default:
                return super.isBool(flags, key);
        }
    }

    @Override
    public double getDouble(long flags, int key) {
        switch (key) {
            case PriorityWeighting.KEY:
                return (double) priorityWayEncoder.getValue(flags) / BEST.getValue();
            default:
                return super.getDouble(flags, key);
        }
    }

    boolean isPushingSection(ReaderWay way) {
        return way.hasTag("highway", pushingSectionsHighways) || way.hasTag("railway", "platform") || way.hasTag("bicycle", "dismount");
    }

    protected long handleSpeed(ReaderWay way, double speed, long encoded) {
        encoded = setSpeed(encoded, speed);

        // handle oneways
        boolean isOneway = way.hasTag("oneway", oneways)
                || way.hasTag("oneway:bicycle", oneways)
                || way.hasTag("vehicle:backward")
                || way.hasTag("vehicle:forward")
                || way.hasTag("bicycle:forward");

        if ((isOneway || way.hasTag("junction", "roundabout"))
                && !way.hasTag("oneway:bicycle", "no")
                && !way.hasTag("bicycle:backward")
                && !way.hasTag("cycleway", oppositeLanes)
                && !way.hasTag("cycleway:left", oppositeLanes)
                && !way.hasTag("cycleway:right", oppositeLanes)) {
            boolean isBackward = way.hasTag("oneway", "-1")
                    || way.hasTag("oneway:bicycle", "-1")
                    || way.hasTag("vehicle:forward", "no")
                    || way.hasTag("bicycle:forward", "no");
            if (isBackward)
                encoded |= backwardBit;
            else
                encoded |= forwardBit;

        } else {
            encoded |= directionBitMask;
        }
        return encoded;
    }

    protected void setHighwaySpeed(String highway, int speed) {
        highwaySpeeds.put(highway, speed);
    }

    protected int getHighwaySpeed(String key) {
        return highwaySpeeds.get(key);
    }

    void setTrackTypeSpeed(String tracktype, int speed) {
        trackTypeSpeeds.put(tracktype, speed);
    }

    void setSurfaceSpeed(String surface, int speed) {
        surfaceSpeeds.put(surface, speed);
    }

    void setCyclingNetworkPreference(String network, int code) {
        bikeNetworkToCode.put(network, code);
    }

    void addPushingSection(String highway) {
        pushingSectionsHighways.add(highway);
    }

    @Override
    public boolean supports(Class<?> feature) {
        if (super.supports(feature))
            return true;

        return PriorityWeighting.class.isAssignableFrom(feature);
    }

    public void setAvoidSpeedLimit(int limit) {
        avoidSpeedLimit = limit;
    }

    protected void setSpecificClassBicycle(String subkey) {
        classBicycleKey = "class:bicycle:" + subkey;
    }

    private enum WayType {
        ROAD(0),
        PUSHING_SECTION(1),
        CYCLEWAY(2),
        OTHER_SMALL_WAY(3);

        private final int value;

        private WayType(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }
}


text:
declare module 'gettext-parser' {

    interface IGetTextParserResult {
        translations: any
    }

    interface IGetTextParserPO {
        parse: (input: string) => IGetTextParserResult;
    }

    class GetTextParser {

        static po: IGetTextParserPO;

    }

    export = GetTextParser;

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

require('../../app/support/setup');
var helperLocation = '../../../src/helpers/translate';
var translateHelper = require(helperLocation).Translator;
var fixture = require('../../fixtures/translate/translate.json');

describe('Translate Helper', function() {

	beforeEach(function() {
		this.channel = Radio.channel('global');
	});

	describe('Methods', function() {

		it('should expose a getLocale method', function() {
			expect(translateHelper.getLocale).to.be.a('function');
		});

		it('should expose a addLocale method', function() {
			expect(translateHelper.addLocale).to.be.a('function');
		});

		it('should expose a translate method', function() {
			expect(translateHelper.translate).to.be.a('function');
		});

	});

	describe('getLocale()', function() {

		describe('Default state', function() {

			it('should default to en-GB', function() {
				expect(translateHelper.getLocale()).to.eql('en-GB');
			});
		});

		describe('Config Response - Locale German', function() {

			beforeEach(function() {
				this.channel.reply('config', function () { return fixture.configDE });
			});

			it('should return de-DE', function() {
				expect(translateHelper.getLocale()).to.eql('de-DE');
			});

		});

		describe('Config Response - Locale undefined', function() {

			beforeEach(function() {
				this.channel.reply('config', function () { return fixture.configNA });
			});

			it('should return en-GB', function() {
				expect(translateHelper.getLocale()).to.eql('en-GB');
			});

		});

		describe('Config Response - App undefined', function() {

			beforeEach(function() {
				this.channel.reply('config', function () { return {} });
			});

			it('should return en-GB', function() {
				expect(translateHelper.getLocale()).to.eql('en-GB');
			});

		});

	});

	describe('translate() && addLocale()', function() {

		beforeEach(function() {
			translateHelper.addLocale('en-GB', fixture.lang);
		});

		it('should translate il8Key correctly', function() {
			expect(translateHelper.translate('helloWorld')).to.eql('Hello World!');
		});

		it('should translate i18key with value containing colons correctly', function() {
			expect(translateHelper.translate('error_message')).to.eql('There was a problem: could not connect');
		});

		it('should translate i18Key correctly with the count number supplied', function() {
			expect(translateHelper.translate('day', {count: 2})).to.eql('days');
		});

		it('should translate i18Key correctly with the count number supplied', function() {
			expect(translateHelper.translate('day', {count: 1})).to.eql('day');
		});

		it('should subsitute number into translated text', function() {
			expect(translateHelper.translate('buyNTickets', [2])).to.eql('Buy 2 tickets?');
		});

	});

});


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BerkeleyDB;
using Dccelerator.DataAccess.Infrastructure;
using Dccelerator.UnFastReflection;
using JetBrains.Annotations;

namespace Dccelerator.DataAccess.BerkeleyDb.Implementation {
    public class BDbSchema : IBDbSchema {
        readonly string _environmentPath;
        readonly string _dbPath;
        string _password;

        readonly ConcurrentDictionary<string, Database> _primaryDbs = new ConcurrentDictionary<string, Database>();
        readonly ConcurrentDictionary<string, SecondaryDatabase> _secondaryDbs = new ConcurrentDictionary<string, SecondaryDatabase>();
        readonly HashSet<string> _transactionPreparedEntities = new HashSet<string>();

        public bool IsEncrypted { get; private set; }

        public bool IsFreeThreaded { get; private set; }

        public virtual DatabaseEnvironment Environment {
            get {
                if (_environment != null)
                    return _environment;

                _environment = OpenEnvironment(_environmentPath, _dbPath, _password);
                _password = null;

                IsEncrypted = _environment.EncryptAlgorithm == EncryptionAlgorithm.AES;
                IsFreeThreaded = _environment.FreeThreaded;

                return _environment;
            }
        }

        DatabaseEnvironment _environment;

        public BDbSchema(string environmentPath, string dbPath) : this(environmentPath, dbPath, null) { }

        /// <exception cref="InvalidOperationException">Can't create environment directory.</exception>
        /// <exception cref="ArgumentException">BerkeleyDb file name is an absolute or relative path, but should be just file name (with or without extension).</exception>
        public BDbSchema(string environmentPath, string dbPath, string password) {
            _environmentPath = environmentPath;
            _dbPath = dbPath;
            _password = password;

            if (Path.GetFileName(_dbPath) != _dbPath) {
                var msg = $"BerkeleyDb file name '{dbPath}' is an absolute or relative path, but should be just file name (with or without extension)";
                Log.TraceEvent(TraceEventType.Error, msg);
                throw new ArgumentException(msg, nameof(dbPath));
            }

            if (!Directory.Exists(_environmentPath)) {
                try {
                    Directory.CreateDirectory(_environmentPath);
                }
                catch (Exception e) {
                    var msg = $"Can't create environment directory {environmentPath}";
                    Log.TraceEvent(TraceEventType.Error, msg);
                    throw new InvalidOperationException(msg, e);
                }
            }
        }

        public virtual Database GetPrimaryDb(string dbName) {
            Database database;
            if (_primaryDbs.TryGetValue(dbName, out database))
                return database;

            database = OpenDatabase(dbName);
            if (_primaryDbs.TryAdd(dbName, database))
                return database;

            database.Close();
            database = _primaryDbs[dbName];
            return database;
        }

        public virtual SecondaryDatabase GetSecondaryDb(Database primaryDb, SecondaryKeyAttribute secondaryKey, Database foreignDb = null) {
            var dbName = SecondaryKeyDbName(primaryDb, secondaryKey);

            SecondaryDatabase database;

            if (_secondaryDbs.TryGetValue(dbName, out database))
                return database;

            database = OpenWritableSecondaryDatabase(primaryDb, secondaryKey, dbName, foreignDb);

            if (_secondaryDbs.TryAdd(dbName, database))
                return database;

            database.Close();
            database = _secondaryDbs[dbName];
            return database;
        }

        public virtual Transaction BeginTransactionFor(ICollection<IBDbEntityInfo> entityInfos) {
            var needToPrepare = new List<IBDbEntityInfo>();

            lock (_transactionPreparedEntities) {
                needToPrepare.AddRange(entityInfos.Where(info => !_transactionPreparedEntities.Contains(info.EntityName)));
            }

            foreach (var info in needToPrepare) {
                var primaryDb = GetPrimaryDb(info.EntityName);

                foreach (var keyMapping in info.ForeignKeys.Values) {
                    var foreignDb = GetPrimaryDb(keyMapping.ForeignEntityName);
                    GetSecondaryDb(primaryDb, keyMapping, foreignDb);
                }

                foreach (var keyMapping in info.SecondaryKeys.Where(x => !info.ForeignKeys.ContainsKey(x.Key)).Select(x => x.Value)) {
                    GetSecondaryDb(primaryDb, keyMapping);
                }

                lock (_transactionPreparedEntities) {
                    _transactionPreparedEntities.Add(info.EntityName);
                }
            }

            return Environment.BeginTransaction();
        }

        protected virtual SecondaryDatabase OpenWritableSecondaryDatabase(Database primaryDb,SecondaryKeyAttribute secondaryForeingKey, string dbName, [CanBeNull] Database foreignDb = null) {
            var config = new SecondaryBTreeDatabaseConfig(primaryDb, GetForeignKeyGenerator(secondaryForeingKey)) {
                Env = Environment,
                Encrypted = IsEncrypted,
                Duplicates = (BerkeleyDB.DuplicatesPolicy)secondaryForeingKey.DuplicatesPolicy,
                Creation = CreatePolicy.IF_NEEDED,
                ReadUncommitted = true,
                FreeThreaded = IsFreeThreaded,
                AutoCommit = true,
            };

            if (foreignDb != null)
                config.SetForeignKeyConstraint(foreignDb, ForeignKeyDeleteAction.ABORT);

            return SecondaryBTreeDatabase.Open(_dbPath, dbName, config);
        }

        protected virtual string SecondaryKeyDbName(Database primaryDb, SecondaryKeyAttribute secondaryKey) {
            return $"{primaryDb.DatabaseName}-->{secondaryKey.Name}";
        }

        protected virtual DatabaseEnvironment OpenEnvironment(string environmentPath, string dbPath, string password) {
            try {
                var environmentConfig = GetDefaultEnvironmentConfig();
                if (!string.IsNullOrWhiteSpace(password)) {
                    environmentConfig.SetEncryption(_password, EncryptionAlgorithm.AES);
                }
                var environment = DatabaseEnvironment.Open(_environmentPath, environmentConfig);

/*
                Task.Factory.StartNew(() => {
                    while (true) {
                        environment.DetectDeadlocks(DeadlockPolicy.MIN_WRITE);
                        Thread.Sleep(10);
                    }
                }, TaskCreationOptions.LongRunning);
*/

                return environment;
            }
            catch (RunRecoveryException) {
                try {
                    var environmentConfig = GetDefaultEnvironmentConfig();
                    environmentConfig.RunRecovery = true;
                    if (!string.IsNullOrWhiteSpace(password)) {
                        environmentConfig.SetEncryption(_password, EncryptionAlgorithm.AES);
                    }
                    return DatabaseEnvironment.Open(_environmentPath, environmentConfig);
                }
                catch (RunRecoveryException) {
                    try {
                        var environmentConfig = GetDefaultEnvironmentConfig();
                        environmentConfig.RunFatalRecovery = true;
                        if (!string.IsNullOrWhiteSpace(password)) {
                            environmentConfig.SetEncryption(_password, EncryptionAlgorithm.AES);
                        }
                        return DatabaseEnvironment.Open(_environmentPath, environmentConfig);
                    }
                    catch (Exception ex) {
                        throw new InvalidOperationException("Can't open environment even with recovery!", ex);
                    }
                }
            }
        }

        protected virtual DatabaseEnvironmentConfig GetDefaultEnvironmentConfig() {
            var environmentConfig = new DatabaseEnvironmentConfig {
                Create = true,
                UseMPool = true,
                Private = false,
                UseLogging = true,
                UseLocking = true,
                FreeThreaded = true,
                UseTxns = true,
                ForceFlush = true,
                LockSystemCfg = GetLockingConfig(),
                LogSystemCfg = GetLogsConfig(),
                MPoolSystemCfg = GetMPoolConfig(),
                MutexSystemCfg = GetMutexesConfig(),
            };

            return environmentConfig;
        }

        protected virtual MutexConfig GetMutexesConfig() {
            return new MutexConfig {
                InitMutexes = 0,
                MaxMutexes = 0,
                Increment = 0
            };
        }

        protected virtual LockingConfig GetLockingConfig() {
            return new LockingConfig {
                DeadlockResolution = DeadlockPolicy.MIN_WRITE,
            };
        }

        protected virtual MPoolConfig GetMPoolConfig() {
            return new MPoolConfig {
                CacheSize = new CacheInfo(0, 500 * 1024 * 1024, 2)
            };
        }

        protected virtual LogConfig GetLogsConfig() {
            return new LogConfig {
                InMemory = false,
                BufferSize = 50 * 1024 * 1024
            };
        }

        protected virtual Database OpenDatabase(string dbName) {
            return BTreeDatabase.Open(_dbPath, dbName, new BTreeDatabaseConfig {
                Env = Environment,
                Encrypted = IsEncrypted,
                Creation = CreatePolicy.IF_NEEDED,
                FreeThreaded = IsFreeThreaded,
                AutoCommit = true,
                ReadUncommitted = true
            });
        }

        protected virtual SecondaryKeyGenDelegate GetForeignKeyGenerator(SecondaryKeyAttribute secondaryKey) {
            return (pKey, pData) => {
                var entity = pData.Data.FromBytes();

                object foreingKey;
                if (!entity.TryGet(secondaryKey.Name, out foreingKey))
                    throw new InvalidOperationException();

                return new DatabaseEntry(foreingKey.ToBinnary());
            };
        }

        #region Implementation of IDisposable

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose() {

            foreach (var db in _secondaryDbs) {
                db.Value.Close(true);
                db.Value.Dispose();
            }

            foreach (var db in _primaryDbs) {
                db.Value.Close(true);
                db.Value.Dispose();
            }

            Environment.Close();
        }

        #endregion
    }
}


text:
from logging import getLogger

from dependency_injector.containers import DeclarativeContainer
from dependency_injector.providers import Configuration, DependenciesContainer, Singleton

from .anilist import Anilist
from .botadmin import BotAdmin
from .channels import Channels
from .jisho import Jisho
from .moderation import Moderation
from .mute import Mute
from .newbie import Newbies
from .notifications import Notifications
from .roles import Roles
from .saucenao import SauceNAO
from .stop import Stop
from .whitelist import Whitelisting

logger = getLogger(__name__)
cog_names = (
    'anilist',
    'botadmin',
    'channels',
    'jisho',
    'moderation',
    'mute',
    'newbie',
    'notifications',
    'roles',
    'saucenao',
    'stop',
    'whitelist'
)

class CogsContainer(DeclarativeContainer):
    root = DependenciesContainer()
    # Accessing a Configuration through a DependenciesContainer does not work, so do it manually
    config = Configuration('config.cogs')

    anilist = Singleton(Anilist, http=root.http)

    botadmin = Singleton(BotAdmin, http=root.http)

    channels = Singleton(Channels)

    jisho = Singleton(Jisho, http=root.http)

    moderation = Singleton(Moderation)

    mute = Singleton(
        Mute,
        bot=root.bot,
        loop=root.loop,
        scoped_session=root.scoped_session,
        sessionmaker=root.sessionmaker
    )

    newbie = Singleton(
        Newbies,
        bot=root.bot,
        loop=root.loop,
        scoped_session=root.scoped_session,
        sessionmaker=root.sessionmaker
    )

    notifications = Singleton(
        Notifications,
        scoped_session=root.scoped_session
    )

    roles = Singleton(Roles)

    saucenao = Singleton(SauceNAO, http=root.http, api_key=config.saucenao.api_key)

    stop = Singleton(Stop)

    whitelist = Singleton(Whitelisting)

def load_cogs(root):
    bot = root.bot()
    cogs = CogsContainer(root=root, config=root.config.cogs())

    for cog_name in cog_names:
        cog_provider = getattr(cogs, cog_name)
        bot.add_cog(cog_provider())


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>3443 Sieghartskirchen, Austria</formatted_address>
  <address_component>
   <long_name>Sieghartskirchen</long_name>
   <short_name>Sieghartskirchen</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Sieghartskirchen</long_name>
   <short_name>Gemeinde Sieghartskirchen</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Tulln District</long_name>
   <short_name>Tulln District</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Lower Austria</long_name>
   <short_name>Lower Austria</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>3443</long_name>
   <short_name>3443</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>48.2543134</lat>
    <lng>16.0137790</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>48.2391712</lat>
     <lng>16.0030998</lng>
    </southwest>
    <northeast>
     <lat>48.2624991</lat>
     <lng>16.0269512</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>48.2391712</lat>
     <lng>16.0030998</lng>
    </southwest>
    <northeast>
     <lat>48.2624991</lat>
     <lng>16.0269512</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJq-3MnOR1bUcRlRX6KCEwC2k</place_id>
 </result>
</GeocodeResponse>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var articleCtrl = angular.module('articleCtrl', []);

//================================================================================
//                  CONTROLEUR LIST
//================================================================================
articleCtrl.controller('articleCtrlList',
        ['$scope', 'ArticleFactory', '$location', '$http', '$rootScope', function
                    ($scope, ArticleFactory, $location, $http, $rootScope) {

                $http.get($rootScope.webservice + '/rest/article/get?id=1').success(function (data) {
                    $scope.mainArticle = data;
                });
//                        $scope.myarticles = ArticleFactory.query();
                ;

                $scope.edit = function (id) {
                    $location.path('/article-edit/'+id);
                }

            }
        ]);

//================================================================================
//                  CONTROLEUR EDIT
//================================================================================

workauthorCtrl.controller('articleCtrlEdit',
        ['$scope', 'ArticleFactory', '$location', '$http', '$rootScope', '$routeParams',
            function ($scope, ArticleFactory, $location, $http, $rootScope, $routeParams) {

                /***
                 * Récupération de l'article principal
                 */
                $http.get($rootScope.webservice + '/rest/article/get?id=' + $routeParams.articleId).success(function (data) {
                    $scope.article = data;
                });

                $scope.confirmForm = function (action) {
                    if (action === ACTION_EDIT) {
                        alert("EDITION " + $scope.article.id + " " + $scope.article)
                        ArticleFactory.update({'id': $scope.article.id}, $scope.article).$promise.then(function () {
                            $location.path('/home');
                        });
                    }
                    else if (action === ACTION_CREATE) {
                        ArticleFactory.create($scope.article).$promise.then(function () {
                            $location.path('/source');
                        });
                    }
                };

            }]);

//================================================================================
//                  CONTROLEUR VIEW
//================================================================================

workCtrl.controller('articleCtrlView', ['$scope', '$rootScope', 'WorkFactory', '$location', '$routeParams', '$http', function ($scope, $rootScope, WorkFactory, $location, $routeParams, $http) {

//alert("ID : " + $routeParams.articleId)

        $http.get($rootScope.webservice + '/rest/article/get?id=' + $routeParams.articleId).success(function (data) {
            $scope.article = data;
        });

    }
]
        );


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="script.module.dropbox"
       name="Dropbox API"
       version="9.4.0"
       provider-name="Dropbox">
  <requires>
    <import addon="xbmc.python" version="3.0.0"/>
    <import addon="script.module.requests" version="2.18.4"/>
    <import addon="script.module.six" version="1.11.0" />
  </requires>
  <extension point="xbmc.python.module" library="lib" /> <!-- entry to import this in other addons -->
  <extension point="xbmc.addon.metadata">
    <summary lang="en_GB">Dropbox API</summary>
    <description lang="en_GB">Provide Dropbox Python API support</description>
    <description lang="he">התוסף מספק תמיכה ב-API Python Dropbox</description>
    <platform>all</platform>
    <license>Apache2</license>
    <website>https://www.dropbox.com/developers/documentation/python</website>
    <source>https://github.com/dropbox/dropbox-sdk-python</source>
    <news>
v9.4.0 (2019-11-26)
- support for Python 3
v8.4.2 (2019-08-23)
- Fix Windows import errors (github.com/robweber)
- Make qrcode module an optional dependency (github.com/robweber)
v8.4.1 (2017-11-28)
- Update to API version 8.4.0
- Switch strings to po format
- Add Hebrew (github.com/Eng2Heb)
- Fix for UI lib issues (github.com/SchapplM)
    </news>
  </extension>
</addon>


text:
package com.theoryinpractice.testng;

import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.openapi.application.QueryExecutorBase;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.search.UsageSearchContext;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
import org.testng.annotations.DataProvider;

public class DataProviderSearcher extends QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters> {
  public DataProviderSearcher() {
    super(true);
  }

  @Override
  public void processQuery(@NotNull MethodReferencesSearch.SearchParameters queryParameters, @NotNull Processor<PsiReference> consumer) {
    final PsiMethod method = queryParameters.getMethod();

    final PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, DataProvider.class.getName());
    if (annotation == null) return;
    PsiNameValuePair[] values = annotation.getParameterList().getAttributes();
    for (PsiNameValuePair value : values) {
      if ("name".equals(value.getName())) {
        final PsiAnnotationMemberValue dataProviderMethodName = value.getValue();
        if (dataProviderMethodName != null) {
          final String providerName = StringUtil.unquoteString(dataProviderMethodName.getText());
          queryParameters.getOptimizer().searchWord(providerName, queryParameters.getScope(), UsageSearchContext.IN_STRINGS, true, method);
        }
      }
    }
  }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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>com.nuodb.samples.mule</groupId>
    <artifactId>rest-subscribers</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>mule</packaging>
    <name>Mule rest-subscribers Application</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <mule.version>3.6.0</mule.version>
        <mule.tools.version>1.0</mule.tools.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mule.tools.maven</groupId>
                <artifactId>mule-app-maven-plugin</artifactId>
                <version>${mule.tools.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <copyToAppsDirectory>true</copyToAppsDirectory>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2.1</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>project</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <id>add-resource</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>add-resource</goal>
                        </goals>
                        <configuration>
                            <resources>
                                <resource>
                                    <directory>src/main/app/</directory>
                                </resource>
                                <resource>
                                    <directory>mappings/</directory>
                                </resource>
                                <resource>
                                    <directory>src/main/api/</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!--Install clover-plugins -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>copy-clover-plugins</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <overWriteReleases>true</overWriteReleases>
                            <overWriteSnapshots>true</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                            <stripVersion>true</stripVersion>

                            <outputDirectory>${project.build.testOutputDirectory}</outputDirectory>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>com.cloveretl</groupId>
                                    <artifactId>cloveretl-engine</artifactId>
                                    <version>${mule.version}</version>
                                    <type>zip</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <configuration>
                            <tasks>
                                <!-- Using an ant task to deflate cloveretl-engine.zip -->
                                <unzip dest="${project.build.testOutputDirectory}"
                                       src="${project.build.testOutputDirectory}/cloveretl-engine.zip"/>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <!-- Mule Dependencies -->
    <dependencies>
        <!-- Xml configuration -->
        <dependency>
            <groupId>com.mulesoft.muleesb</groupId>
            <artifactId>mule-core-ee</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Xml configuration -->
        <dependency>
            <groupId>com.mulesoft.muleesb.modules</groupId>
            <artifactId>mule-module-spring-config-ee</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Mule Transports -->
        <dependency>
            <groupId>org.mule.transports</groupId>
            <artifactId>mule-transport-file</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.transports</groupId>
            <artifactId>mule-transport-http</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.mulesoft.muleesb.transports</groupId>
            <artifactId>mule-transport-jdbc-ee</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.mulesoft.muleesb.transports</groupId>
            <artifactId>mule-transport-jms-ee</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.transports</groupId>
            <artifactId>mule-transport-vm</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Mule Modules -->
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-scripting</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-xml</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- for testing -->
        <dependency>
            <groupId>org.mule.tests</groupId>
            <artifactId>mule-tests-functional</artifactId>
            <version>${mule.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.cloveretl</groupId>
            <artifactId>cloveretl-engine</artifactId>
            <version>${mule.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-http</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-jersey</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-spring-config</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-json</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.nuodb.jdbc</groupId>
            <artifactId>nuodb-jdbc</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-db</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>Central</id>
            <name>Central</name>
            <url>http://repo1.maven.org/maven2/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Releases Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>mulesoft-snapshots</id>
            <name>MuleSoft Snapshots Repository</name>
            <url>http://repository.mulesoft.org/snapshots/</url>
            <layout>default</layout>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>mulesoft-release</id>
            <name>mulesoft release repository</name>
            <layout>default</layout>
            <url>http://repository.mulesoft.org/releases/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>


text:
require 'digest/sha1'

class Gateway::PaybynetController < Spree::BaseController
  skip_before_filter :verify_authenticity_token, :only => [:comeback, :complete]

  # Show form Dotpay for pay
  def show
    if session[:idbank]
      @idbank = session[:idbank]
      session[:idbank] = nil
    end
    @order = Spree::Order.find(params[:order_id])
    @gateway = @order.available_payment_methods.find{|x| x.id == params[:gateway_id].to_i }
    @order.payments.destroy_all
    payment = @order.payments.create!(:amount => 0, :payment_method_id => @gateway.id)

    if @order.blank? || @gateway.blank?
      flash[:error] = I18n.t("invalid_arguments")
      redirect_to :back
    else
      @bill_address, @ship_address = @order.bill_address, (@order.ship_address || @order.bill_address)
    end
    @hashtrans = hashtrans(@order, @gateway)
    render(:layout => false)
  end

  def notify

  end

  def complete
    @order = Spree::Order.find(session[:order_id])
    session[:order_id] = nil
    @order.update_attributes({:state => "complete", :completed_at => Time.now}, :without_protection => true)
    redirect_to order_url(@order, {:checkout_complete => true, :order_token => @order.token}), :notice => "Paybynet correct"
  end

  def reject
    @order = Spree::Order.find(session[:order_id])
    redirect_to order_url(@order, {:checkout_complete => true}), :notice => "Paybynet not correct"
  end

  def comeback
    newStatus = params[:newStatus] #status transakcji
    transAmount = params[:transAmount]
    paymentId = params[:paymentId] #identyfikator transakcji przekazane ze sklepu.
    hash = params[:hash] #skrót SHA1 z połączenia : newStatus + transAmount + paymentId + password

    @order = Spree::Order.find_by_number(paymentId)
    gateway = @order && @order.payments.first.payment_method

    check = Digest::SHA1.hexdigest(newStatus + transAmount + paymentId + gateway.preferred_password)

    if check==hash
      if newStatus=='2203' || newStatus=='2303'
          paybynet_payment_success(transAmount.to_f,@order)
          render :text => "OK", :layout => false
      elsif newStatus=='2202' || newStatus=='2302'
          paybynet_payment_fail(params,@order)
          render :text => "OK", :layout => false
      else
          render :text => "OK", :layout => false
      end
    else
      render :text => "FAIL", :layout => false
    end
  end

  def hashtrans(order, gateway)
    time = Time.new + 3.days

    xml = "<id_client>"+gateway.preferred_id_client+"</id_client>"
    xml += "<id_trans>"+order.number+"</id_trans>"
    xml += "<date_valid>"+time.strftime("%d-%m-%Y %H:%M:%S")+"</date_valid>"
    xml += "<amount>"+order.total.to_s.sub!(".", ",")+"</amount><currency>PLN</currency>"
    xml += "<email>"+order.user.try(:email)+"</email>"
    xml += "<account>"+gateway.preferred_account+"</account>"
    xml += "<accname>"+gateway.preferred_accname+"^NM^"+gateway.preferred_postcode+"^ZP^"+gateway.preferred_city+"^CI^"+gateway.preferred_street+"^ST^"+gateway.preferred_country+"^CT^</accname>"
    xml += "<backpage>"+main_app.gateway_paybynet_complete_url(@order.number)+"</backpage>"
    xml += "<backpagereject>"+main_app.gateway_paybynet_reject_url(@order.number)+"</backpagereject>"

    hash = Digest::SHA1.hexdigest(xml + "<password>"+gateway.preferred_password+"</password>")

    xml += "<hash>"+hash+"</hash>"

    @xm = xml

    ActiveSupport::Base64.encode64(xml)

  end

  private

  # Completed payment process
  def paybynet_payment_success(price, order)
      sleep(10)
    if order.payment_state != 'paid'
      order.payments.first.started_processing!
      cash = order.payments.first
      cash.amount = price
      cash.save
      order.payments.first.complete
      order.payment_state = 'paid'

      order.finalize!
      order.next
      order.next
      order.save
    end
  end

  def paybynet_payment_fail(params, order)
      order.payments.first.complete
      order.payment_state = 'fail'
      order.save
  end

end


text:
package org.datagr4m.monitors;

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

import org.datagr4m.datastructures.pairs.Pair;

public class TimeMonitor implements ITimeMonitor{
    protected long start;
    protected List<Pair<Date,Double>> measurements = new ArrayList<Pair<Date,Double>>();
    protected static double TEN_POWER_9 = 1000000000.0;
    protected String name;
    protected Object monitored;
    protected boolean enabled;

    public TimeMonitor(Object o) {
        this(o, o.getClass().getSimpleName(), false);
    }

    public TimeMonitor(String name) {
        this(name, name, false);
    }

    /*public TimeMonitor(String name, boolean enabled) {
        this(null, name, enabled);
    }*/

    public TimeMonitor(Object monitored, String name, boolean enabled) {
        this.monitored = monitored;
        this.name = name;
        this.enabled = enabled;
    }

    @Override
    public void startMonitor() {
        if(isEnabled())
            start = System.nanoTime();
    }

    @Override
    public void stopMonitor() {
        if(isEnabled()){
            long elapsedNano = System.nanoTime() - start;
            double elapsedSecons = elapsedNano / TEN_POWER_9;
            measurements.add(new Pair<Date,Double>(new Date(), elapsedSecons));
        }
    }

    @Override
    public List<Pair<Date,Double>> getMeasurements() {
        return measurements;
    }

    @Override
    public Unit getUnit() {
        return Unit.SECONDS;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    @Override
    public void enable(boolean status) {
        this.enabled = status;
    }

    @Override
    public Object getMonitored() {
        return monitored;
    }

    @Override
    public Double getMean() {
        if(measurements.size()==0)
            return Double.NaN;
        else{
            double mean = 0;
            int k = 0;
            for(Pair<Date,Double> m: measurements){
                mean += m.b;
                k++;
            }
            return mean/k;
        }
    }

    @Override
    public int getSize() {
        // TODO Auto-generated method stub
        return 0;
    }
}


text:
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.PortableUI.Common;

namespace MonoGame.PortableUI.Controls
{
    public class TextBlock : Control
    {
        private TextAlignment _textAlignment;
        protected SpriteFont Font;
        private string _text = "";
        private int _textSize;
        private Color _textColor;

        public TextAlignment TextAlignment
        {
            get { return _textAlignment; }
            set
            {
                _textAlignment = value;
                InvalidateLayout(false);
            }
        }

        public Color TextColor
        {
            get { return _textColor; }
            set
            {
                _textColor = value;
                InvalidateLayout(false);
            }
        }
        public Vector2 MeasuredText { get; private set; }

        public string Text
        {
            get { return _text; }
            set
            {
                _text = value ?? "";
                MeasuredText = Font.MeasureString(_text);
                InvalidateLayout(true);
            }
        }

        public int TextSize
        {
            get { return _textSize; }
            set
            {
                _textSize = value;
                InvalidateLayout(true);
            }
        }

        public override Size MeasureLayout()
        {
            var size = base.MeasureLayout();

            var vector2 = Font.MeasureString(Text);
            size.Width = Width.IsFixed() ? Width : vector2.X;
            if (vector2.Y > size.Height)
                size.Height = vector2.Y;
            //size.Height = Height;

            return size;
        }

        public TextBlock()
        {
            Font = FontManager.DefaultFont;
            TextColor = Color.Black;
            TextAlignment = TextAlignment.Left;
        }

        protected internal override void OnDraw(SpriteBatch spriteBatch, Rect rect)
        {
            base.OnDraw(spriteBatch, rect);
            var offset = rect.Offset;
            offset.Y += (rect.Height - MeasuredText.Y) / 2;

            switch (TextAlignment)
            {
                case TextAlignment.Left:
                    break;
                case TextAlignment.Center:
                    offset.X += (rect.Width - MeasuredText.X) / 2;
                    break;
                case TextAlignment.Right:
                    offset.X += rect.Width - MeasuredText.X;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if (SnapToPixel)
                offset = offset.ToInts();
            spriteBatch.DrawString(Font, Text, offset, TextColor);
        }
    }
}


text:
package com.alibaba.fastjson.serializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.DateDeserializer;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;

public class CalendarCodec implements ObjectSerializer, ObjectDeserializer {

    public final static CalendarCodec instance = new CalendarCodec();

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        Calendar calendar = (Calendar) object;
        Date date = calendar.getTime();
        serializer.write(date);
    }

    @SuppressWarnings("unchecked")
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        Object value = DateDeserializer.instance.deserialze(parser, type, fieldName);

        if (value instanceof Calendar) {
            return (T) value;
        }

        Date date = (Date) value;
        if (date == null) {
            return null;
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return (T) calendar;
    }

    public int getFastMatchToken() {
        return JSONToken.LITERAL_INT;
    }
}


text:
using MagicalLifeAPI.Asset;
using MagicalLifeAPI.Filing;
using MagicalLifeGUIWindows.GUI.Reusable;
using MagicalLifeGUIWindows.Rendering.Text;
using Microsoft.Xna.Framework;
using System;

namespace MagicalLifeGUIWindows.GUI.Settings_Menu.InputBoxes
{
    public class MasterVolumeInputBox : MonoInputBox
    {
        public MasterVolumeInputBox() :
           base(TextureLoader.GUIInputBox100x50, TextureLoader.GUICursorCarrot, GetInitialLocation(), int.MaxValue, TextureLoader.FontMainMenuFont12x,
               false, SimpleTextRenderer.Alignment.Left, true)
        {
            TextChanged += UpdateAudio;
        }

        /// <summary>
        /// Updates the audio.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="args">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void UpdateAudio(Object obj, EventArgs args)
        {
            if (int.TryParse(this.Text, out int volume) && volume >= 0 && volume <= 100)
            {
                SettingsManager.AudioSettings.Settings.MasterVolume = volume;
                SettingsManager.AudioSettings.Save();
            }
        }

        private static Rectangle GetInitialLocation()
        {
            int x = SettingsMenuLayout.MasterVolumeInputBoxX;
            int y = SettingsMenuLayout.MasterVolumeInputBoxY;
            int width = SettingsMenuLayout.MasterVolumeInputBoxWidth;
            int height = SettingsMenuLayout.MasterVolumeInputBoxHeight;

            return new Rectangle(x, y, width, height);
        }
    }
}


text:
using System;

namespace Elephanet.Tests.Entities
{
    public class EntityWithDateTime
    {
        public DateTime CreatedAt { get; set; }
    }
}


text:
package dataStructures.goods;

import dataStructures.building.Building;
import dataStructures.city.City;
import dataStructures.exceptions.CapacityOverflowException;
import dataStructures.person.Person;

public class DemandFactory {
	public static Demand calculateDemandDailyForPerson(Person person) {
		Demand demand = new Demand();

		try {
			demand.getGoodDemand().addGood(Good.Fish, 0.5);
			demand.getGoodDemand().addGood(Good.Potato, 0.5);
			demand.getGoodDemand().addGood(Good.Corn, 0.5);
			demand.getGoodDemand().addGood(Good.Wood, 0.25);
		} catch (CapacityOverflowException e) {
			e.printStackTrace();
		}

		return demand;
	}

	public static Demand calculateDemandDailyForBuilding(Building building) {
		Demand demand = new Demand();

		if (building.getPersonsInvolved() != null)
			for (Person p : building.getPersonsInvolved()) {
				Demand d = building.predictDemandDaily(p);
				for (Good good : d.getGoodDemand().getStock().keySet())
					try {
						demand.getGoodDemand().addGood(good, demand.getGoodDemand().getStock(good) + d.getGoodDemand().getStock(good));
					} catch (CapacityOverflowException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}

		return demand;
	}

	public static Demand calculateDemandDailyForCity(City city) {

		Demand demand = new Demand();

		for (Person p : city.getPersons()) {
			Demand d = calculateDemandDailyForPerson(p);
			for (Good good : d.getGoodDemand().getStock().keySet())
				try {
					demand.getGoodDemand().addGood(good, demand.getGoodDemand().getStock(good) + d.getGoodDemand().getStock(good));
				} catch (CapacityOverflowException e) {
					e.printStackTrace();
				}
		}

		for (Building b : city.getBuildings()) {
			Demand d = calculateDemandDailyForBuilding(b);
			for (Good good : d.getGoodDemand().getStock().keySet())
				try {
					demand.getGoodDemand().addGood(good, demand.getGoodDemand().getStock(good) + d.getGoodDemand().getStock(good));
				} catch (CapacityOverflowException e) {
					e.printStackTrace();
				}
		}

		return demand;
	}
}


text:
package com.navercorp.pinpoint.test.plugin;

import java.util.List;

/**
 * @author Jongho Moon
 */
public class PluginTestContext {

    private final String agentJar;
    private final String profile;
    private final String configFile;
    private final String logLocationConfig;

    private final List<String> requiredLibraries;
    private final List<String> mavenDependencyLibraries;
    private final List<String> repositoryUrls;
    private final Class<?> testClass;
    private final String testClassLocation;

    private final List<String> jvmArguments;
    private final boolean debug;

    private final int jvmVersion;
    private final String javaExecutable;

    private final List<String> importPluginIds;

    public PluginTestContext(String agentJar, String profile, String configFile, String logLocationConfig,
                             List<String> requiredLibraries, List<String> mavenDependencyLibraries, List<String> repositoryUrls,
                             Class<?> testClass, String testClassLocation, List<String> jvmArguments,
                             boolean debug, int jvmVersion,
                             String javaExecutable, List<String> importPluginIds) {
        this.agentJar = agentJar;
        this.profile = profile;
        this.configFile = configFile;
        this.logLocationConfig = logLocationConfig;
        this.requiredLibraries = requiredLibraries;
        this.mavenDependencyLibraries = mavenDependencyLibraries;
        this.repositoryUrls = repositoryUrls;
        this.testClass = testClass;
        this.testClassLocation = testClassLocation;
        this.jvmArguments = jvmArguments;
        this.debug = debug;
        this.jvmVersion = jvmVersion;
        this.javaExecutable = javaExecutable;
        this.importPluginIds = importPluginIds;
    }

    public List<String> getRequiredLibraries() {
        return requiredLibraries;
    }

    public List<String> getMavenDependencyLibraries() {
        return mavenDependencyLibraries;
    }

    public List<String> getRepositoryUrls() { return repositoryUrls; }

    public String getTestClassLocation() {
        return testClassLocation;
    }

    public String getAgentJar() {
        return agentJar;
    }

    public String getProfile() {
        return profile;
    }

    public String getConfigFile() {
        return configFile;
    }

    public String getLogLocationConfig() {
        return logLocationConfig;
    }

    public List<String> getJvmArguments() {
        return jvmArguments;
    }

    public int getJvmVersion() {
        return jvmVersion;
    }

    public boolean isDebug() {
        return debug;
    }

    public Class<?> getTestClass() {
        return testClass;
    }

    public String getJavaExecutable() {
        return javaExecutable;
    }

    public List<String> getImportPluginIds() {
        return importPluginIds;
    }

    @Override
    public String toString() {
        return "PinpointPluginTestContext{" +
                "agentJar='" + agentJar + '\'' +
                ", profile='" + profile + '\'' +
                ", configFile='" + configFile + '\'' +
                ", logLocationConfig='" + logLocationConfig + '\'' +
                ", requiredLibraries=" + requiredLibraries +
                ", mavenDependencyLibraries=" + mavenDependencyLibraries +
                ", repositoryUrls=" + repositoryUrls +
                ", testClass=" + testClass +
                ", testClassLocation='" + testClassLocation + '\'' +
                ", jvmArguments=" + jvmArguments +
                ", debug=" + debug +
                ", jvmVersion=" + jvmVersion +
                ", javaExecutable='" + javaExecutable + '\'' +
                ", importPluginIds=" + importPluginIds +
                '}';
    }

}


text:
from nose.tools import eq_, ok_
from nose.plugins.skip import SkipTest

# Skip test on PY3
from flask.ext.admin._compat import PY2, as_unicode
if not PY2:
    raise SkipTest('MongoEngine is not Python 3 compatible')

from wtforms import fields

from flask.ext.admin import form
from flask.ext.admin.contrib.mongoengine import ModelView

from . import setup

class CustomModelView(ModelView):
    def __init__(self, model,
                 name=None, category=None, endpoint=None, url=None,
                 **kwargs):
        for k, v in kwargs.iteritems():
            setattr(self, k, v)

        super(CustomModelView, self).__init__(model,
                                              name, category,
                                              endpoint, url)

def create_models(db):
    class Model1(db.Document):
        test1 = db.StringField(max_length=20)
        test2 = db.StringField(max_length=20)
        test3 = db.StringField()
        test4 = db.StringField()

    class Model2(db.Document):
        int_field = db.IntField()
        bool_field = db.BooleanField()

    Model1.objects.delete()
    Model2.objects.delete()

    return Model1, Model2

def test_model():
    app, db, admin = setup()

    Model1, Model2 = create_models(db)

    view = CustomModelView(Model1)
    admin.add_view(view)

    eq_(view.model, Model1)
    eq_(view.name, 'Model1')
    eq_(view.endpoint, 'model1view')

    eq_(view._primary_key, 'id')

    ok_('test1' in view._sortable_columns)
    ok_('test2' in view._sortable_columns)
    ok_('test3' in view._sortable_columns)
    ok_('test4' in view._sortable_columns)

    ok_(view._create_form_class is not None)
    ok_(view._edit_form_class is not None)
    eq_(view._search_supported, False)
    eq_(view._filters, None)

    # Verify form
    # TODO: Figure out why there's inconsistency
    try:
        eq_(view._create_form_class.test1.field_class, fields.TextField)
        eq_(view._create_form_class.test2.field_class, fields.TextField)
    except AssertionError:
        eq_(view._create_form_class.test1.field_class, fields.StringField)
        eq_(view._create_form_class.test2.field_class, fields.StringField)

    eq_(view._create_form_class.test3.field_class, fields.TextAreaField)
    eq_(view._create_form_class.test4.field_class, fields.TextAreaField)

    # Make some test clients
    client = app.test_client()

    rv = client.get('/admin/model1view/')
    eq_(rv.status_code, 200)

    rv = client.get('/admin/model1view/new/')
    eq_(rv.status_code, 200)

    rv = client.post('/admin/model1view/new/',
                     data=dict(test1='test1large', test2='test2'))
    eq_(rv.status_code, 302)

    model = Model1.objects.first()
    eq_(model.test1, 'test1large')
    eq_(model.test2, 'test2')
    eq_(model.test3, '')
    eq_(model.test4, '')

    rv = client.get('/admin/model1view/')
    eq_(rv.status_code, 200)
    ok_('test1large' in rv.data)

    url = '/admin/model1view/edit/?id=%s' % model.id
    rv = client.get(url)
    eq_(rv.status_code, 200)

    rv = client.post(url,
                     data=dict(test1='test1small', test2='test2large'))
    eq_(rv.status_code, 302)

    model = Model1.objects.first()
    eq_(model.test1, 'test1small')
    eq_(model.test2, 'test2large')
    eq_(model.test3, '')
    eq_(model.test4, '')

    url = '/admin/model1view/delete/?id=%s' % model.id
    rv = client.post(url)
    eq_(rv.status_code, 302)
    eq_(Model1.objects.count(), 0)

def test_default_sort():
    app, db, admin = setup()
    M1, _ = create_models(db)

    M1(test1='c').save()
    M1(test1='b').save()
    M1(test1='a').save()

    eq_(M1.objects.count(), 3)

    view = CustomModelView(M1, column_default_sort='test1')
    admin.add_view(view)

    _, data = view.get_list(0, None, None, None, None)

    eq_(data[0].test1, 'a')
    eq_(data[1].test1, 'b')
    eq_(data[2].test1, 'c')

def test_extra_fields():
    app, db, admin = setup()

    Model1, _ = create_models(db)

    view = CustomModelView(
        Model1,
        form_extra_fields={
            'extra_field': fields.TextField('Extra Field')
        }
    )
    admin.add_view(view)

    client = app.test_client()

    rv = client.get('/admin/model1view/new/')
    eq_(rv.status_code, 200)

    # Check presence and order
    data = rv.data.decode('utf-8')
    ok_('Extra Field' in data)
    pos1 = data.find('Extra Field')
    pos2 = data.find('Test1')
    ok_(pos2 < pos1)

def test_extra_field_order():
    app, db, admin = setup()

    Model1, _ = create_models(db)

    view = CustomModelView(
        Model1,
        form_columns=('extra_field', 'test1'),
        form_extra_fields={
            'extra_field': fields.TextField('Extra Field')
        }
    )
    admin.add_view(view)

    client = app.test_client()

    rv = client.get('/admin/model1view/new/')
    eq_(rv.status_code, 200)

    # Check presence and order
    data = rv.data.decode('utf-8')
    pos1 = data.find('Extra Field')
    pos2 = data.find('Test1')
    ok_(pos2 > pos1)

def test_custom_form_base():
    app, db, admin = setup()

    class TestForm(form.BaseForm):
        pass

    Model1, _ = create_models(db)

    view = CustomModelView(
        Model1,
        form_base_class=TestForm
    )
    admin.add_view(view)

    ok_(hasattr(view._create_form_class, 'test1'))

    create_form = view.create_form()
    ok_(isinstance(create_form, TestForm))

def test_subdocument_config():
    app, db, admin = setup()

    class Comment(db.EmbeddedDocument):
        name = db.StringField(max_length=20, required=True)
        value = db.StringField(max_length=20)

    class Model1(db.Document):
        test1 = db.StringField(max_length=20)
        subdoc = db.EmbeddedDocumentField(Comment)

    # Check only
    view1 = CustomModelView(
        Model1,
        form_subdocuments = {
            'subdoc': {
                'form_columns': ('name',)
            }
        }
    )

    ok_(hasattr(view1._create_form_class, 'subdoc'))

    form = view1.create_form()
    ok_('name' in dir(form.subdoc.form))
    ok_('value' not in dir(form.subdoc.form))

    # Check exclude
    view2 = CustomModelView(
        Model1,
        form_subdocuments = {
            'subdoc': {
                'form_excluded_columns': ('value',)
            }
        }
    )

    form = view2.create_form()
    ok_('name' in dir(form.subdoc.form))
    ok_('value' not in dir(form.subdoc.form))

def test_subdocument_class_config():
    app, db, admin = setup()

    from flask.ext.admin.contrib.mongoengine import EmbeddedForm

    class Comment(db.EmbeddedDocument):
        name = db.StringField(max_length=20, required=True)
        value = db.StringField(max_length=20)

    class Model1(db.Document):
        test1 = db.StringField(max_length=20)
        subdoc = db.EmbeddedDocumentField(Comment)

    class EmbeddedConfig(EmbeddedForm):
        form_columns = ('name',)

    # Check only
    view1 = CustomModelView(
        Model1,
        form_subdocuments = {
            'subdoc': EmbeddedConfig()
        }
    )

    form = view1.create_form()
    ok_('name' in dir(form.subdoc.form))
    ok_('value' not in dir(form.subdoc.form))

def test_nested_subdocument_config():
    app, db, admin = setup()

    # Check recursive
    class Comment(db.EmbeddedDocument):
        name = db.StringField(max_length=20, required=True)
        value = db.StringField(max_length=20)

    class Nested(db.EmbeddedDocument):
        name = db.StringField(max_length=20, required=True)
        comment = db.EmbeddedDocumentField(Comment)

    class Model1(db.Document):
        test1 = db.StringField(max_length=20)
        nested = db.EmbeddedDocumentField(Nested)

    view1 = CustomModelView(
        Model1,
        form_subdocuments = {
            'nested': {
                'form_subdocuments': {
                    'comment': {
                        'form_columns': ('name',)
                    }
                }
            }
        }
    )

    form = view1.create_form()
    ok_('name' in dir(form.nested.form.comment.form))
    ok_('value' not in dir(form.nested.form.comment.form))

def test_nested_list_subdocument():
    app, db, admin = setup()

    class Comment(db.EmbeddedDocument):
        name = db.StringField(max_length=20, required=True)
        value = db.StringField(max_length=20)

    class Model1(db.Document):
        test1 = db.StringField(max_length=20)
        subdoc = db.ListField(db.EmbeddedDocumentField(Comment))

    # Check only
    view1 = CustomModelView(
        Model1,
        form_subdocuments = {
            'subdoc': {
                'form_subdocuments': {
                    None: {
                        'form_columns': ('name',)
                    }
                }

            }
        }
    )

    form = view1.create_form()
    inline_form = form.subdoc.unbound_field.args[2]

    ok_('name' in dir(inline_form))
    ok_('value' not in dir(inline_form))

def test_ajax_fk():
    app, db, admin = setup()

    class Model1(db.Document):
        test1 = db.StringField(max_length=20)
        test2 = db.StringField(max_length=20)

        def __str__(self):
            return self.test1

    class Model2(db.Document):
        int_field = db.IntField()
        bool_field = db.BooleanField()

        model1 = db.ReferenceField(Model1)

    Model1.objects.delete()
    Model2.objects.delete()

    view = CustomModelView(
        Model2,
        url='view',
        form_ajax_refs={
            'model1': {
                'fields': ('test1', 'test2')
            }
        }
    )
    admin.add_view(view)

    ok_(u'model1' in view._form_ajax_refs)

    model = Model1(test1=u'first')
    model.save()
    model2 = Model1(test1=u'foo', test2=u'bar').save()

    # Check loader
    loader = view._form_ajax_refs[u'model1']
    mdl = loader.get_one(model.id)
    eq_(mdl.test1, model.test1)

    items = loader.get_list(u'fir')
    eq_(len(items), 1)
    eq_(items[0].id, model.id)

    items = loader.get_list(u'bar')
    eq_(len(items), 1)
    eq_(items[0].test1, u'foo')

    # Check form generation
    form = view.create_form()
    eq_(form.model1.__class__.__name__, u'AjaxSelectField')

    with app.test_request_context('/admin/view/'):
        ok_(u'value=""' not in form.model1())

        form.model1.data = model
        needle = u'data-json="["%s", "first"]"' % as_unicode(model.id)
        ok_(needle in form.model1())
        ok_(u'value="%s"' % as_unicode(model.id) in form.model1())

    # Check querying
    client = app.test_client()

    req = client.get(u'/admin/view/ajax/lookup/?name=model1&query=foo')
    eq_(req.data, u'[["%s", "foo"]]' % model2.id)

    # Check submitting
    client.post('/admin/view/new/', data={u'model1': as_unicode(model.id)})
    mdl = Model2.objects.first()

    ok_(mdl is not None)
    ok_(mdl.model1 is not None)
    eq_(mdl.model1.id, model.id)
    eq_(mdl.model1.test1, u'first')

def test_nested_ajax_refs():
    app, db, admin = setup()

    # Check recursive
    class Comment(db.Document):
        name = db.StringField(max_length=20, required=True)
        value = db.StringField(max_length=20)

    class Nested(db.EmbeddedDocument):
        name = db.StringField(max_length=20, required=True)
        comment = db.ReferenceField(Comment)

    class Model1(db.Document):
        test1 = db.StringField(max_length=20)
        nested = db.EmbeddedDocumentField(Nested)

    view1 = CustomModelView(
        Model1,
        form_subdocuments = {
            'nested': {
                'form_ajax_refs': {
                    'comment': {
                        'fields': ['name']
                    }
                }
            }
        }
    )

    form = view1.create_form()
    eq_(type(form.nested.form.comment).__name__, 'AjaxSelectField')
    ok_('nested-comment' in view1._form_ajax_refs)

def test_form_flat_choices():
    app, db, admin = setup()

    class Model(db.Document):
        name = db.StringField(max_length=20, choices=('a', 'b', 'c'))

    view = CustomModelView(Model)
    admin.add_view(view)

    form = view.create_form()
    eq_(form.name.choices, [('a', 'a'), ('b', 'b'), ('c', 'c')])


text:
from sys import exit

def slide_printer(result_key, data, option_value=None):
    for slide in data:
        print slide
        key = raw_input()

        if key == 'q':
            exit(0)


text:
Titulo

		1. Tipografía
		2. Colores
		3. Botones
		4. Iconos
		5. Acordeones
		6. Formularios
		7. Sidebars
		8. Bloques


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Selectmenu - Default functionality</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    <form action="#">

        <fieldset>
            Select a speed
            <select name="speed" id="speed">
                <option>Slower</option>
                <option>Slow</option>
                <option selected="selected">Medium</option>
                <option>Fast</option>
                <option>Faster</option>
            </select>

            Select a file
            <select name="files" id="files">
                <optgroup label="Scripts">
                    <option value="jquery">jQuery.js</option>
                    <option value="jqueryui">ui.jQuery.js</option>
                </optgroup>
                <optgroup label="Other files">
                    <option value="somefile">Some unknown file</option>
                    <option value="someotherfile">Some other file with a very long option text</option>
                </optgroup>
            </select>

            Select a number
            <select name="number" id="number">
                <option>1</option>
                <option selected="selected">2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
                <option>6</option>
                <option>7</option>
                <option>8</option>
                <option>9</option>
                <option>10</option>
                <option>11</option>
                <option>12</option>
                <option>13</option>
                <option>14</option>
                <option>15</option>
                <option>16</option>
                <option>17</option>
                <option>18</option>
                <option>19</option>
            </select>

            Select a title
            <select name="salutation" id="salutation">
                <option disabled selected>Please pick one</option>
                <option>Mr.</option>
                <option>Mrs.</option>
                <option>Dr.</option>
                <option>Prof.</option>
                <option>Other</option>
            </select>
        </fieldset>

    </form>


text:
Note the placeholder. The format should match it.

ESPN Url: <input class="espn_url" type="text" placeholder="http://scores.espn.go.com/ncf/boxscore?gameId=400548402" style="width: 400px">

/r/<input class="subreddit_name" type="text" placeholder="THIS IS OPTIONAL" style="width: 400px">

<button class="get_results">Generate Reddit Post</button>

message/bitch at/appreciate/xoxo/gild/wink at/praise/fire creator