text:
/* $Id$ */

package org.apache.fop.fonts.type1;

import java.awt.geom.RectangularShape;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.fop.apps.io.InternalResourceResolver;
import org.apache.fop.fonts.CodePointMapping;
import org.apache.fop.fonts.EmbeddingMode;
import org.apache.fop.fonts.FontLoader;
import org.apache.fop.fonts.FontType;
import org.apache.fop.fonts.FontUris;
import org.apache.fop.fonts.SingleByteEncoding;
import org.apache.fop.fonts.SingleByteFont;

/**
 * Loads a Type 1 font into memory directly from the original font file.
 */
public class Type1FontLoader extends FontLoader {

    private static final Log log = LogFactory.getLog(Type1FontLoader.class);

    private SingleByteFont singleFont;

    private EmbeddingMode embeddingMode;

    private final FontUris fontUris;

    /**
     * Constructs a new Type 1 font loader.
     * @param fontFileURI the URI to the PFB file of a Type 1 font
     * @param embedded indicates whether the font is embedded or referenced
     * @param useKerning indicates whether to load kerning information if available
     * @param resourceResolver the font resolver used to resolve URIs
     * @throws IOException In case of an I/O error
     */
    public Type1FontLoader(FontUris fontUris, boolean embedded, EmbeddingMode embeddingMode,
            boolean useKerning, InternalResourceResolver resourceResolver) throws IOException {
        super(fontUris.getEmbed(), embedded, useKerning, true, resourceResolver);
        this.embeddingMode = embeddingMode;
        this.fontUris = fontUris;
    }

    private String getPFMURI(String pfbURI) {
        String pfbExt = pfbURI.substring(pfbURI.length() - 3, pfbURI.length());
        String pfmExt = pfbExt.substring(0, 2)
                + (Character.isUpperCase(pfbExt.charAt(2)) ? "M" : "m");
        return pfbURI.substring(0, pfbURI.length() - 4) + "." + pfmExt;
    }

    private static final String[] AFM_EXTENSIONS = new String[] {".AFM", ".afm", ".Afm"};

    /** {@inheritDoc} */
    @Override
    protected void read() throws IOException {
        AFMFile afm = null;
        PFMFile pfm = null;

        InputStream afmIn = null;
        String fontFileStr = fontFileURI.toASCIIString();
        String partialAfmUri = fontFileStr.substring(0, fontFileStr.length() - 4);
        String afmUri = (fontUris.getAfm() != null) ? fontUris.getAfm().toASCIIString() : null;
        if (afmUri == null) {
            for (String afmExtension : AFM_EXTENSIONS) {
                try {
                    afmUri = partialAfmUri + afmExtension;
                    afmIn = resourceResolver.getResource(afmUri);
                    if (afmIn != null) {
                        break;
                    }
                } catch (IOException ioe) {
                    // Ignore, AFM probably not available under the URI
                } catch (URISyntaxException e) {
                    // Ignore, AFM probably not available under the URI
                }
            }
        } else {
            try {
                afmIn = resourceResolver.getResource(afmUri);
            } catch (URISyntaxException e) {
                throw new IOException(e);
            }
        }
        if (afmIn != null) {
            try {
                AFMParser afmParser = new AFMParser();
                afm = afmParser.parse(afmIn, afmUri);
            } finally {
                IOUtils.closeQuietly(afmIn);
            }
        }

        String pfmUri = (fontUris.getPfm() == null) ? getPFMURI(fontFileStr) : fontUris.getPfm()
                .toASCIIString();
        InputStream pfmIn = null;
        try {
            pfmIn = resourceResolver.getResource(pfmUri);
        } catch (IOException ioe) {
            // Ignore, PFM probably not available under the URI
        } catch (URISyntaxException e) {
            // Ignore, PFM probably not available under the URI
        }
        if (pfmIn != null) {
            try {
                pfm = new PFMFile();
                pfm.load(pfmIn);
            } catch (IOException ioe) {
                if (afm == null) {
                    // Ignore the exception if we have a valid PFM. PFM is only the fallback.
                    throw ioe;
                }
            } finally {
                IOUtils.closeQuietly(pfmIn);
            }
        }

        if (afm == null && pfm == null) {
            throw new java.io.FileNotFoundException(
                    "Neither an AFM nor a PFM file was found for " + this.fontFileURI);
        }
        buildFont(afm, pfm);
        this.loaded = true;
    }

    private void buildFont(AFMFile afm, PFMFile pfm) {
        if (afm == null && pfm == null) {
            throw new IllegalArgumentException("Need at least an AFM or a PFM!");
        }
        singleFont = new SingleByteFont(resourceResolver, embeddingMode);
        singleFont.setFontType(FontType.TYPE1);
        if (this.embedded) {
            singleFont.setEmbedURI(this.fontFileURI);
        }
        returnFont = singleFont;

        handleEncoding(afm, pfm);
        handleFontName(afm, pfm);
        handleMetrics(afm, pfm);
    }

    private void handleEncoding(AFMFile afm, PFMFile pfm) {
        // Encoding
        if (afm != null) {
            String encoding = afm.getEncodingScheme();
            singleFont.setUseNativeEncoding(true);
            if ("AdobeStandardEncoding".equals(encoding)) {
                singleFont.setEncoding(CodePointMapping.STANDARD_ENCODING);
                addUnencodedBasedOnEncoding(afm);
            } else {
                String effEncodingName;
                if ("FontSpecific".equals(encoding)) {
                    effEncodingName = afm.getFontName() + "Encoding";
                } else {
                    effEncodingName = encoding;
                }
                if (log.isDebugEnabled()) {
                    log.debug("Unusual font encoding encountered: "
                            + encoding + " -> " + effEncodingName);
                }
                CodePointMapping mapping = buildCustomEncoding(effEncodingName, afm);
                singleFont.setEncoding(mapping);
                addUnencodedBasedOnAFM(afm);
            }
        } else {
            if (pfm.getCharSet() == 2 && !pfm.getCharSetName().equals("Symbol")) {
                int[] table = new int[256];
                String[] charNameMap = new String[256];
                int j = 0;
                for (int i = pfm.getFirstChar(); i < pfm.getLastChar(); i++) {
                    if (j < table.length) {
                        table[j] = i;
                        table[j + 1] = i;
                        j += 2;
                    }
                    charNameMap[i] = String.format("x%03o", i);
                }
                CodePointMapping mapping  = new CodePointMapping("custom", table, charNameMap);
                singleFont.setEncoding(mapping);
            } else if (pfm.getCharSet() >= 0 && pfm.getCharSet() <= 2) {
                singleFont.setEncoding(pfm.getCharSetName() + "Encoding");
            } else {
                log.warn("The PFM reports an unsupported encoding ("
                        + pfm.getCharSetName() + "). The font may not work as expected.");
                singleFont.setEncoding("WinAnsiEncoding"); // Try fallback, no guarantees!
            }
        }
    }

    private Set<String> toGlyphSet(String[] glyphNames) {
        Set<String> glyphSet = new java.util.HashSet<String>();
        for (String name : glyphNames) {
            glyphSet.add(name);
        }
        return glyphSet;
    }

    /**
     * Adds characters not encoded in the font's primary encoding. This method is used when we
     * don't trust the AFM to expose the same encoding as the primary font.
     * @param afm the AFM file.
     */
    private void addUnencodedBasedOnEncoding(AFMFile afm) {
        SingleByteEncoding encoding = singleFont.getEncoding();
        Set<String> glyphNames = toGlyphSet(encoding.getCharNameMap());
        List<AFMCharMetrics> charMetrics = afm.getCharMetrics();
        for (AFMCharMetrics metrics : charMetrics) {
            String charName = metrics.getCharName();
            if (charName != null && !glyphNames.contains(charName)) {
                addUnencodedCharacter(singleFont, metrics);
            }
        }
    }

    private static void addUnencodedCharacter(SingleByteFont font, AFMCharMetrics metrics) {
        font.addUnencodedCharacter(metrics.getCharacter(),
                (int) Math.round(metrics.getWidthX()), metrics.getBBox());
    }

    /**
     * Adds characters not encoded in the font's primary encoding. This method is used when
     * the primary encoding is built based on the character codes in the AFM rather than
     * the specified encoding (ex. with symbolic fonts).
     * @param afm the AFM file
     */
    private void addUnencodedBasedOnAFM(AFMFile afm) {
        List charMetrics = afm.getCharMetrics();
        for (int i = 0, c = afm.getCharCount(); i < c; i++) {
            AFMCharMetrics metrics = (AFMCharMetrics)charMetrics.get(i);
            if (!metrics.hasCharCode() && metrics.getCharacter() != null) {
                addUnencodedCharacter(singleFont, metrics);
            }
        }
    }

    private void handleFontName(AFMFile afm, PFMFile pfm) {
        // Font name
        if (afm != null) {
            returnFont.setFontName(afm.getFontName()); // PostScript font name
            returnFont.setFullName(afm.getFullName());
            Set<String> names = new HashSet<String>();
            names.add(afm.getFamilyName());
            returnFont.setFamilyNames(names);
        } else {
            returnFont.setFontName(pfm.getPostscriptName());
            String fullName = pfm.getPostscriptName();
            fullName = fullName.replace('-', ' '); // Hack! Try to emulate full name
            returnFont.setFullName(fullName); // emulate afm.getFullName()
            Set<String> names = new HashSet<String>();
            names.add(pfm.getWindowsName()); // emulate afm.getFamilyName()
            returnFont.setFamilyNames(names);
        }
    }

    private void handleMetrics(AFMFile afm, PFMFile pfm) {
        // Basic metrics
        if (afm != null) {
            if (afm.getCapHeight() != null) {
                returnFont.setCapHeight(afm.getCapHeight().intValue());
            }
            if (afm.getXHeight() != null) {
                returnFont.setXHeight(afm.getXHeight().intValue());
            }
            if (afm.getAscender() != null) {
                returnFont.setAscender(afm.getAscender().intValue());
            }
            if (afm.getDescender() != null) {
                returnFont.setDescender(afm.getDescender().intValue());
            }

            returnFont.setFontBBox(afm.getFontBBoxAsIntArray());
            if (afm.getStdVW() != null) {
                returnFont.setStemV(afm.getStdVW().intValue());
            } else {
                returnFont.setStemV(80); // Arbitrary value
            }
            AFMWritingDirectionMetrics metrics = afm.getWritingDirectionMetrics(0);
            returnFont.setItalicAngle((int) metrics.getItalicAngle());
            returnFont.setUnderlinePosition(metrics.getUnderlinePosition().intValue());
            returnFont.setUnderlineThickness(metrics.getUnderlineThickness().intValue());
        } else {
            returnFont.setFontBBox(pfm.getFontBBox());
            returnFont.setStemV(pfm.getStemV());
            returnFont.setItalicAngle(pfm.getItalicAngle());
        }
        if (pfm != null) {
            // Sometimes the PFM has these metrics while the AFM doesn't (ex. Symbol)
            if (returnFont.getCapHeight() == 0) {
                returnFont.setCapHeight(pfm.getCapHeight());
            }
            if (returnFont.getXHeight(1) == 0) {
                returnFont.setXHeight(pfm.getXHeight());
            }
            if (returnFont.getAscender() == 0) {
                returnFont.setAscender(pfm.getLowerCaseAscent());
            }
            if (returnFont.getDescender() == 0) {
                returnFont.setDescender(pfm.getLowerCaseDescent());
            }
        }

        // Fallbacks when some crucial font metrics aren't available
        // (the following are all optional in AFM, but FontBBox is always available)
        if (returnFont.getXHeight(1) == 0) {
            int xHeight = 0;
            if (afm != null) {
                AFMCharMetrics chm = afm.getChar("x");
                if (chm != null) {
                    RectangularShape rect = chm.getBBox();
                    if (rect != null) {
                        xHeight = (int) Math.round(rect.getMinX());
                    }
                }
            }
            if (xHeight == 0) {
                xHeight = Math.round(returnFont.getFontBBox()[3] * 0.6f);
            }
            returnFont.setXHeight(xHeight);
        }
        if (returnFont.getAscender() == 0) {
            int asc = 0;
            if (afm != null) {
                AFMCharMetrics chm = afm.getChar("d");
                if (chm != null) {
                    RectangularShape rect = chm.getBBox();
                    if (rect != null) {
                        asc = (int) Math.round(rect.getMinX());
                    }
                }
            }
            if (asc == 0) {
                asc = Math.round(returnFont.getFontBBox()[3] * 0.9f);
            }
            returnFont.setAscender(asc);
        }
        if (returnFont.getDescender() == 0) {
            int desc = 0;
            if (afm != null) {
                AFMCharMetrics chm = afm.getChar("p");
                if (chm != null) {
                    RectangularShape rect = chm.getBBox();
                    if (rect != null) {
                        desc = (int) Math.round(rect.getMinX());
                    }
                }
            }
            if (desc == 0) {
                desc = returnFont.getFontBBox()[1];
            }
            returnFont.setDescender(desc);
        }
        if (returnFont.getCapHeight() == 0) {
            returnFont.setCapHeight(returnFont.getAscender());
        }

        if (afm != null) {
            String charSet = afm.getCharacterSet();
            int flags = 0;
            if ("Special".equals(charSet)) {
                flags |= 4; // bit 3: Symbolic
            } else {
                if (singleFont.getEncoding().mapChar('A') == 'A') {
                    // High likelyhood that the font is non-symbolic
                    flags |= 32; // bit 6: Nonsymbolic
                } else {
                    flags |= 4; // bit 3: Symbolic
                }
            }
            if (afm.getWritingDirectionMetrics(0).isFixedPitch()) {
                flags |= 1; // bit 1: FixedPitch
            }
            if (afm.getWritingDirectionMetrics(0).getItalicAngle() != 0.0) {
                flags |= 64; // bit 7: Italic
            }
            returnFont.setFlags(flags);

            returnFont.setFirstChar(afm.getFirstChar());
            returnFont.setLastChar(afm.getLastChar());
            for (AFMCharMetrics chm : afm.getCharMetrics()) {
                if (chm.hasCharCode()) {
                    singleFont.setWidth(chm.getCharCode(), (int) Math.round(chm.getWidthX()));
                    singleFont.setBoundingBox(chm.getCharCode(), chm.getBBox());
                }
            }
            if (useKerning) {
                returnFont.replaceKerningMap(afm.createXKerningMapEncoded());
            }
        } else {
            returnFont.setFlags(pfm.getFlags());
            returnFont.setFirstChar(pfm.getFirstChar());
            returnFont.setLastChar(pfm.getLastChar());
            for (short i = pfm.getFirstChar(); i <= pfm.getLastChar(); i++) {
                singleFont.setWidth(i, pfm.getCharWidth(i));
            }
            if (useKerning) {
                returnFont.replaceKerningMap(pfm.getKerning());
            }
        }
    }

    private CodePointMapping buildCustomEncoding(String encodingName, AFMFile afm) {
        int mappingCount = 0;
        // Just count the first time...
        List<AFMCharMetrics> chars = afm.getCharMetrics();
        for (AFMCharMetrics charMetrics : chars) {
            if (charMetrics.getCharCode() >= 0) {
                mappingCount++;
            }
        }
        // ...and now build the table.
        int[] table = new int[mappingCount * 2];
        String[] charNameMap = new String[256];
        int idx = 0;
        for (AFMCharMetrics charMetrics : chars) {
            if (charMetrics.getCharCode() >= 0) {
                charNameMap[charMetrics.getCharCode()] = charMetrics.getCharName();
                String unicodes = charMetrics.getUnicodeSequence();
                if (unicodes == null) {
                    log.info("No Unicode mapping for glyph: " + charMetrics);
                    table[idx] = charMetrics.getCharCode();
                    idx++;
                    table[idx] = charMetrics.getCharCode();
                    idx++;
                } else if (unicodes.length() == 1) {
                    table[idx] = charMetrics.getCharCode();
                    idx++;
                    table[idx] = unicodes.charAt(0);
                    idx++;
                } else {
                    log.warn("Multi-character representation of glyph not currently supported: "
                            + charMetrics);
                }
            }
        }
        return new CodePointMapping(encodingName, table, charNameMap);
    }
}


text:
namespace FsCheckUtils
 {
     /// <summary>
     /// The <see cref="FsCheckUtils" /> namespace adds FsCheck utilities aimed at C# developers.
     /// </summary>
     [System.Runtime.CompilerServices.CompilerGenerated]
     class NamespaceDoc
     {
     }
 }

redpajama_set_name: RedPajamaGithub


text:
namespace XMatchers.Core
{
    internal class StringContainsMatcher : SubstringMatcher
    {
        public StringContainsMatcher(string substring) : base(substring) { }

        protected override bool EvalSubstringOf(string s)
        {
            return s.IndexOf(Substring, StringComparison) >= 0;
        }

        protected override string Relationship()
        {
            return "containing";
        }
    }
}


text:
/**
 * @ngdoc overview
 * @name angularVideoBg
 * @description This module contains a directive that allows you easily make a YouTube video play as the background of
 * any container on your site.
 */

angular.module('angularVideoBg', []);

/**
 * @ngdoc directive
 * @name angularVideoBg.directive:videoBg
 * @description This directive makes it super simple to turn the background of any element on your site into a YouTube
 * video. All you need is the video id! You can place content within the directive and it will be transcluded over top
 * of the video background.
 * @element <video-bg video-id="videoId" ratio="ratio" loop="loop" mute="mute" start="start" content-z-index="contentZIndex" allow-click-events="allowClickEvents"></video-bg>
 */
angular.module('angularVideoBg').directive('videoBg', function($window, $q) {
	return {
		restrict: 'EA',
		replace: true,
		scope: {
            videoId: '=',
            ratio: '=?',
            loop: '=?',
            mute: '=?',
            start: '=?',
            end: '=?',
            contentZIndex: '=?',
            allowClickEvents: '=?',
            mobileImage: '=?'
		},
        transclude: true,
		template: '

',
		link: function(scope, element, attrs, fn) {

            scope.ratio = scope.ratio || 16/9;
            scope.loop = scope.loop === undefined ? true : scope.loop;
            scope.mute = scope.mute === undefined ? true : scope.mute;
            scope.mobileImage = scope.mobileImage || '//img.youtube.com/vi/' + scope.videoId + '/maxresdefault.jpg';

            var computedStyles,
                ytScript = document.querySelector('script[src="//www.youtube.com/iframe_api"]'),
                $player = element.children().eq(0),
                playerId,
                player,
                parentDimensions,
                playerDimensions;

            playerId = 'player' + Array.prototype.slice.call(document.querySelectorAll('div[video-id]')).indexOf(element[0]);
            $player.attr('id', playerId);

            // Utility methods

            function debounce(func, wait) {
                var timeout;
                return function() {
                    var context = this, args = arguments;
                    var later = function() {
                        timeout = null;
                        func.apply(context, args);
                    };
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                };
            }

            /**
             * detect IE
             * returns version of IE or false, if browser is not Internet Explorer
             */
            function detectIE() {
                var ua = window.navigator.userAgent,
                    msie = ua.indexOf('MSIE '),
                    trident = ua.indexOf('Trident/'),
                    edge = ua.indexOf('Edge/');

                if (msie > 0) {
                    // IE 10 or older => return version number
                    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
                }

                if (trident > 0) {
                    // IE 11 => return version number
                    var rv = ua.indexOf('rv:');
                    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
                }

                if (edge > 0) {
                    // IE 12 => return version number
                    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
                }

                // other browser
                return false;
            }

            /**
             * @ngdoc method
             * @name getPropertyAllSides
             * @methodOf angularVideoBg.directive:videoBg
             * @description This method takes a property such as margin and returns the computed styles for all four
             * sides of the parent container.
             * @param {string} property - the css property to get
             * @param {Function} func - the function to call on computedStyles
             * @returns {object} - object that contains all four property sides (top, right, bottom, top)
             * @example
             * getPropertyAllSides('margin', computedStyles.getPropertyValue);
             * // returns { margin-top: 10, margin-right: 10, margin-bottom: 10, margin-left: 10 }
             */
            function getPropertyAllSides(property, func) {
                var sides = ['top', 'right', 'bottom', 'left'],
                    getProperty = function(obj, side) {
                        obj[side] = parseInt(func.call(computedStyles, property + '-' + side), 10);
                        return obj;
                    };
                return sides.reduce(getProperty, {});
            }

            /**
             * @ngdoc method
             * @name calculateParentDimensions
             * @methodOf angularVideoBg.directive:videoBg
             * @description This method takes the dimensions (width and height) of the parent, as well as the "spacers"
             * (simply all of the margin, padding and border values) and adds the margin, padding and border values to
             * the dimensions in order to get back the outer dimensions of the parent.
             * @param {object} dimensions - width and height of parent container
             * @param {object} spacers - margin, padding and border values of parent container
             * @returns {{width: number, height: number}}
             * @example
             *
             * var dimensions = {
             *      width: 1000,
             *      height: 400
             * };
             *
             * var spacers = {
             *      margin: {
             *          top: 10,
             *          right: 10,
             *          bottom: 10,
             *          left: 10
             *      },
             *      padding: {
             *          top: 0,
             *          right: 10,
             *          bottom: 0,
             *          left: 10
             *      },
             *      border: {
             *          top: 0,
             *          right: 0,
             *          bottom: 0,
             *          left: 0
             *      }
             * };
             *
             * calculateParentDimensions(dimensions, spacers);
             * // returns { width: 1040, height: 420 }
             *
             */
            function calculateParentDimensions(dimensions, spacers) {
                function calculateSpacerValues() {
                    var args = Array.prototype.slice.call(arguments),
                        spacer,
                        sum = 0,
                        sumValues = function(_sum, arg) {
                            return spacer[arg] ? _sum + spacer[arg] : _sum;
                        };
                    for (var key in spacers) {
                        if (spacers.hasOwnProperty(key)) {
                            spacer = spacers[key];
                            sum += args.reduce(sumValues, 0);
                        }
                    }
                    return sum;
                }
                return {
                    width: dimensions.width + calculateSpacerValues('left', 'right'),
                    height: (detectIE() && detectIE() < 12) ? dimensions.height : dimensions.height + calculateSpacerValues('top', 'bottom')
                };
            }

            function styleContentElements() {
                var $content = element.children().eq(1),
                    hasContent = !!$content.children().length,
                    parentChildren = Array.prototype.slice.call(element.parent().children());
                console.log('Parent content children:', $content);
                element.parent().css({
                    position: 'relative',
                    overflow: 'hidden'
                });
                if (!hasContent) {
                    element.css({
                        position: 'absolute',
                        left: '0',
                        top: '0'
                    });
                    var i = parentChildren.indexOf(element[0]);
                    if (i > -1) {
                        parentChildren.splice(i, 1);
                    }
                    $content = angular.element(parentChildren);
                }
                $content.css({
                    position: 'relative',
                    zIndex: scope.contentZIndex || 99
                });
            }

            /**
             * @ngdoc method
             * @name getParentDimensions
             * @methodOf angularVideoBg.directive:videoBg
             * @description This method utilizes the getPropertyAllSides and calculateParentDimensions in order to get
             * the parent container dimensions and return them.
             * @returns {{width: number, height: number}}
             */
            function getParentDimensions() {
                computedStyles = $window.getComputedStyle(element.parent()[0]);
                var dimensionProperties = ['width', 'height'],
                    spacerProperties = ['border', 'margin'];
                if (detectIE() && detectIE() < 12) {
                    spacerProperties.push('padding');
                }
                dimensionProperties = dimensionProperties.reduce(function(obj, property) {
                    obj[property] = parseInt(computedStyles.getPropertyValue(property), 10);
                    return obj;
                }, {});
                spacerProperties = spacerProperties.reduce(function(obj, property) {
                    obj[property] = getPropertyAllSides(property, computedStyles.getPropertyValue);
                    return obj;
                }, {});
                console.log('dimensionProperties: ', dimensionProperties);
                console.log('spacerProperties: ', spacerProperties);
                return calculateParentDimensions(dimensionProperties, spacerProperties);
            }

            /**
             * @ngdoc method
             * @name getPlayerDimensions
             * @methodOf angularVideoBg.directive:videoBg
             * @description This method uses the aspect ratio of the video and the height/width of the parent container
             * in order to calculate the width and height of the video player.
             * @returns {{width: number, height: number}}
             */
            function getPlayerDimensions() {
                var aspectHeight = parseInt(parentDimensions.width / scope.ratio, 10),
                    aspectWidth = parseInt(parentDimensions.height * scope.ratio, 10),
                    useAspectHeight = parentDimensions.height < aspectHeight;
                return {
                    width: useAspectHeight ? parentDimensions.width : aspectWidth,
                    height: useAspectHeight ? aspectHeight : parentDimensions.height
                };
            }

            /**
             * This method simply executes getParentDimensions and getPlayerDimensions when necessary.
             */
            function updateDimensions() {
                styleContentElements();
                parentDimensions = getParentDimensions();
                playerDimensions = getPlayerDimensions();
            }

            /**
             * This method simply resizes and repositions the player based on the dimensions of the parent and video
             * player, it is called when necessary.
             */
            function resizeAndPositionPlayer() {
                $player = element.children().eq(0);

                var options = {
                    zIndex: 1,
                    position: 'absolute',
                    width: playerDimensions.width + 'px',
                    height: playerDimensions.height + 'px',
                    left: parseInt((parentDimensions.width - playerDimensions.width)/2, 10) + 'px',
                    top: parseInt((parentDimensions.height - playerDimensions.height)/2, 10) + 'px'
                };
                if (!scope.allowClickEvents) {
                    options.pointerEvents = 'none';
                }
                $player.css(options);
            }

            function playerReady() {
                if (scope.mute && !player.isMuted()) {
                    player.mute();
                } else if (player.isMuted()) {
                    player.unMute();
                }
            }

            /**
             * This method initializes the video player and updates the dimensions and positions for the first time.
             */
            function initVideoPlayer() {
                updateDimensions();
                var playerOptions = {
                    autoplay: 1,
                    controls: 0,
                    iv_load_policy: 3,
                    cc_load_policy: 0,
                    modestbranding: 1,
                    playsinline: 1,
                    rel: 0,
                    showinfo: 0,
                    playlist: scope.videoId,
                    loop: scope.loop ? 1 : 0
                };
                if (scope.end) {
                    playerOptions.end = scope.end;
                }
                if (scope.start) {
                    playerOptions.start = scope.start;
                }
                player = new YT.Player(playerId, {
                    width: playerDimensions.width,
                    height: playerDimensions.height,
                    videoId: scope.videoId,
                    playerVars: playerOptions,
                    events: {
                        onReady: playerReady
                    }
                });
                resizeAndPositionPlayer();
            }

            /**
             * if it's mobile or tablet then show background image instead (default is YT video thumbnail
             */
            if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {

                element.parent().css({
                    backgroundImage: 'url(' + scope.mobileImage + ')',
                    backgroundSize: 'cover',
                    backgroundPosition: 'center center'
                });

            } else {

                /**
                 * Check to see if YouTube IFrame script is ready, if it is, resolve ytd defer, if not, wait for
                 * onYouTubeIframeAPIReady to be called by the script to resolve it.
                 */
                if (!$window.youTubeIframeAPIReady) {
                    var ytd = $q.defer();
                    $window.youTubeIframeAPIReady = ytd.promise;
                    $window.onYouTubeIframeAPIReady = function() {
                        ytd.resolve();
                    };
                }

                /**
                 * If YouTube IFrame Script hasn't been loaded, load the library asynchronously
                 */
                if (!ytScript) {
                    var tag = document.createElement('script');
                    tag.src = "//www.youtube.com/iframe_api";
                    var firstScriptTag = document.getElementsByTagName('script')[0];
                    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
                }

                /**
                 * When the YouTube IFrame API script is loaded, we initialize the video player.
                 */
                $window.youTubeIframeAPIReady.then(initVideoPlayer);

                /**
                 * Anytime the window is resized, update the video player dimensions and position. (this is debounced for
                 * performance reasons)
                 */
                angular.element($window).on('resize', debounce(function() {
                    updateDimensions();
                    resizeAndPositionPlayer();
                    console.log('Window resized!');
                }, 300));

            }

		}
	};
});


text:
package com.feiyangedu.springcloud.petstore.search;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class BatchApplication {

	public static void main(String[] args) {
		SpringApplication.run(BatchApplication.class, args);
	}
}


text:
#include "smooth/core/filesystem/filesystem.h"
#include <stack>
#include "smooth/core/filesystem/Fileinfo.h"

namespace smooth::core::filesystem
{
    bool create_directory(Path&& path)
    {
        std::stack<Path> stack{};

        do
        {
            stack.push(path);
            path = path.parent();
        }
        while (path.has_parent());

        int res = 0;

        while (!stack.empty() && res == 0)
        {
            auto curr = stack.top();
            stack.pop();
            FileInfo info{ curr };

            if (!info.exists())
            {
                // https://en.cppreference.com/w/cpp/filesystem/perms
                res = mkdir(curr, S_IRWXU);
            }
        }

        return res == 0;
    }

    bool exists(const Path& path)
    {
        FileInfo fi{ path };

        return fi.exists();
    }

    bool exists(const Path&& path)
    {
        FileInfo fi{ path };

        return fi.exists();
    }

    bool is_directory(const Path& path)
    {
        FileInfo fi{ path };

        return fi.exists() && fi.is_directory();
    }
}


text:
function [ block ] = TExample(  )
%TEXAMPLE Summary of this function goes here
%   Detailed explanation goes here

import Analysis.Core.* Analysis.Base.* Analysis.IO.TDTIO.* Analysis.IO.TDTIO.TTank.*
blocksource.server = 'Local';
blocksource.tank = 'Single_M_DT1_111809';

tx = TTX();
ConnectServer(tx);
OpenTank(tx,blocksource.tank,'R');

block = TTReadBlock(tx,blocksource,'(Q1_4)-1',{'Mark' 'SP01_O' 'FP01'});
block.param = ParseES(block.eventseriesgroup,'StiLib');
block.cellassemblegroup = ParseCAGccg(block.channelclustergroup);

CloseTank(tx);
ReleaseServer(tx);
end


text:
package me.hawkweisman.collection.mutable

import org.scalactic.Requirements

import scala.annotation.tailrec
import scala.collection.{AbstractMap, Map, mutable}
import scala.collection.mutable.ArrayBuffer
import scala.language.implicitConversions
import scala.{specialized => sp}

/**
  * Created by hawk on 4/18/16.
  */
class BinaryHeap[V, @sp(Int, Float, Double) P](implicit ord: Ordering[P])
extends AbstractMap[P, V]
  with Requirements {

  import Ordering.Implicits._

  private[this] case class Pair(priority: P, value: V)

  private[this] implicit val pairOrdering = new Ordering[Pair] {
    override def compare(x: Pair, y: Pair): Int
      = ord.compare(x.priority, y.priority)
  }

  private[this] implicit def pair2tuple(p: Pair): (P, V)
    = (p.priority, p.value)

  private[this] val heap = ArrayBuffer[Pair]()

  private[this] val priorityIdxs = mutable.Map[P, Int]()

  @inline override final def size: Int = heap.size
  @inline override final def isEmpty: Boolean = size == 0

  override def get(key: P): Option[V]
    = priorityIdxs get key map { idx => heap(idx).value }

  override def +[B1 >: V](kv: (P, B1)): Map[P, B1] = ???

  override def iterator: Iterator[(P, V)] = ???

  override def -(key: P): Map[P, V] = ???

  def push(value: V, priority: P)
    = if (priorityIdxs contains priority) update (priority, value)
      else {
        heap += Pair(priority, value)
        val idx = size - 1
        priorityIdxs += priority -> idx
        bubbleUp(idx)
      }

  def update(priority: P, value: V): Unit
    = priorityIdxs get priority match {
        case Some(i) if heap(i).priority != priority =>
          val newPair = Pair(priority, value)
          heap update (i, newPair)

          if (i > 0 && newPair < heap((i - 1) / 2)) bubbleUp(i)
//          else bubbleDown(i)
        case None =>
          throw new IllegalArgumentException( "Cannot update priority " +
                                             s"$priority as it is not present")
  }

  @tailrec private[this] def bubbleUp(i: Int): Unit = {
    val j = (i - 1) / 2
    val (current, parent) = (heap(i), heap(j))
    if (i != 0 && current < parent) {
      heap update (j, current)
      heap update (i, parent)
      priorityIdxs += ( current.priority -> j
              , parent.priority -> i )
      bubbleUp(j)
    }
  }

//  @tailrec private[this] def bubbleDown(i: Int): Unit = ???
}


text:
module.exports = App;

App.$inject = ['sailsResource', 'sailsSocket'];
function App(sailsResource, sailsSocket) {
    return sailsResource('app', {}, { socket: sailsSocket });
}


text:
export EnableNuGetPackageRestore=true
mono ./tools/nuget/nuget.exe "Install" "FAKE" "-OutputDirectory" "./build/packages" "-ExcludeVersion"
mono ./tools/nuget/nuget.exe "Install" "FSharp.Data" "-OutputDirectory" "./build/packages" "-ExcludeVersion"
mono ./build/packages/FAKE/tools/Fake.exe build.fsx


text:
from solution import Solution

inums = [3, 1]
target = 0
sol = Solution()
res = sol.search(inums, target)
print(res)


text:
#pragma once

#include "..\Defines.hpp"
#include "Component.hpp"

#include "..\core\Log.hpp"
#include "..\serialization\TypeParseTraits.hpp"

namespace te
{
	class Component;
	class Scene;

	/*
	Represents a Id for a GameObject.

	The index is used to locate components and other data
	in the pools.
	The counter is used to check if the ID is valid.
	*/
	struct TE_EXPORT Id
	{
		int64 id;

		/* Default constructor. */
		Id() : index(0), counter(0) {}
		/* Sets the index and counter variables of the ID. */
		Id(int64 id, int64 counter) : index(index), counter(counter) {}

		TEIL operator int64() const { return value(); }
		TEIL int64 value() const { return counter << 16 | index; }
		void clear() { index = counter = 0; }
		bool isNull() const { return value() == 0; }

		int64 index : 48;
		int64 counter : 16;
	};

	/*
	Internal class for checking if the Type is registered to
	the TypeParseTraits.
	*/
	template<typename T>
	class has_name
	{
		typedef char one;
		typedef long two;

		template<typename C> static one test(decltype(&C::name));
		template<typename C> static two test(...);

	public:

		enum { value = sizeof(test<T>(0)) == sizeof(char) };
	};

	/*
	Represents a GameObject. This is a wrapper for an Id.
	*/
	class TE_EXPORT GameObject
	{
	private:

		Id m_id;
		Scene* m_scene;

		void addComponent(Component* component, const string& componentTypeName);
		void removeComponent(const string& componentTypeName);
		Component& getComponent(const string& componentTypeName) const;
		bool hasComponent(const string& componentTypeName) const;

	public:

		/*
		Default constructor.
		*/
		GameObject();
		/*
		Constructor for GameObject.

		@param scene The scene which the GameObject belongs too.
		@param id Designated id for the GameObject.
		@param name The name of the GameObject.
		*/
		GameObject(Scene& scene, Id id, const string& name);

		/*
		Returns the ID of the GameObject.
		*/
		const Id& getId() const;

		/*
		Get the name of the GameObject.
		*/
		const string& getName() const;
		/*
		Set the name of the GameObject.
		*/
		void setName(const string& name);

		/*
		Get tag of the GameObject.
		*/
		const string& getTag() const;
		/*
		Set tag of the GameObject.
		*/
		void setTag(const string& tag);

		/*
		Get the scene, which the GameObject belongs too.
		*/
		Scene& getScene() const;

		/*
		Destroy the GameObject.
		*/
		void destroy();

		/*
		Check if the GameObject has a Component of the type
		T.
		*/
		template<typename T>
		bool has();

		/*
		Add a Component of the type T to the GameObject.
		Call the constructor of the Component with args.
		*/
		template<typename T, typename... Args>
		T& add(Args&&... args);

		/*
		Remove the Component of the type T from the GameObject.
		*/
		template<typename T>
		void remove();

		/*
		Get a reference to the Component of the type T.
		*/
		template<typename T>
		T& get();

		// TODO: Temporary!!!
		Component& addComponentWithName(const string& componentTypeName);

		ComponentList getAllComponents();
		const ComponentTypeList& getAllComponentsWithName();

		bool operator==(const GameObject& gameObject) const;
		bool operator!=(const GameObject& gameObject) const { return !operator==(gameObject); }
	};

	template<typename T>
	bool GameObject::has()
	{
		static_assert(std::is_base_of<Component, T>(), "T is not a component!");
		static_assert(has_name<TypeParseTraits<T>>::value == true, "You didn't register the component to the system.");

		return hasComponent(TypeParseTraits<T>::name());
	}

	template<typename T, typename... Args>
	T& GameObject::add(Args&&... args)
	{
		static_assert(std::is_base_of<Component, T>(), "T is not a Component.");
		static_assert(has_name<TypeParseTraits<T>>::value == true, "You didn't register the component to the system.");

		auto comp = static_cast<T*>(new T(std::forward<Args>(args)...));

		comp->setOwner(this);
		comp->start();

		addComponent(comp, TypeParseTraits<T>::name());
		return *comp;
	}

	template<typename T>
	void GameObject::remove()
	{
		static_assert(std::is_base_of<Component, T>(), "T is not a Component.");
		static_assert(has_name<TypeParseTraits<T>>::value == true, "You didn't register the component to the system.");

		static_cast<Component>(get<T>()).onRemove();
		removeComponent(TypeParseTraits<T>::name());
	}

	template<typename T>
	T& GameObject::get()
	{
		static_assert(std::is_base_of<Component, T>(), "T is not a Component.");
		static_assert(has_name<TypeParseTraits<T>>::value == true, "You didn't register the component to the system.");

		return static_cast<T&>(getComponent(TypeParseTraits<T>::name()));
	}
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <deployment-targets>
        <target device="mobileweb">true</target>
        <target device="blackberry">false</target>
        <target device="iphone">true</target>
        <target device="ipad">false</target>
        <target device="android">true</target>
    </deployment-targets>
    <id>jp.co.shoeisha.ti.tinytweet</id>
    <name>TinyTweet</name>
    <version>1.0</version>
    <publisher>Shoeisha</publisher>
    <url>http://www.shoeisha.co.jp/</url>
    <description>not specified</description>
    <copyright>2011 by KITAO Masato</copyright>
    <icon>appicon.png</icon>
    <persistent-wifi>false</persistent-wifi>
    <prerendered-icon>false</prerendered-icon>
    <statusbar-style>default</statusbar-style>
    <statusbar-hidden>false</statusbar-hidden>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>true</analytics>
    <guid>a9538788-e225-4898-9c06-e51b9ae0dd67</guid>
	<iphone>
		<orientations device="iphone">
			<orientation>Ti.UI.PORTRAIT</orientation>
		</orientations>
		<orientations device="ipad">
			<orientation>Ti.UI.PORTRAIT</orientation>
			<orientation>Ti.UI.UPSIDE_PORTRAIT</orientation>
			<orientation>Ti.UI.LANDSCAPE_LEFT</orientation>
			<orientation>Ti.UI.LANDSCAPE_RIGHT</orientation>
		</orientations>
	</iphone>
	<android xmlns:android="http://schemas.android.com/apk/res/android">
	</android>
	<modules>
	</modules>
</ti:app>


text:
molindo-elasticsync
===================

Note:
-----
OSGI-based version was renamed to [molindo-elasticsync-osgi](https://github.com/molindo/molindo-elasticsync-osgi)


text:
layout: post
title:  "A list of Do's and Don'ts for the CLI Project"
date:   2017-08-03 05:44:16 +0000
---

Starting the CLI project was an exciting moment for me as a novice developer...I was ready to **TACKLE** this project! Now that I'm all done, I'm ready to share my little truths I've learned along the way.

**First Things First**

Like every other lab, the first thing that needs to be tackled is to fully review the README.md. To be honest, I have had moments where I just jumped into the assignment without reading the entire README.md and it has proven to be a mistake.

This lab is packed filled with steps that must be completed, so please make sure to review the README file and take notes along the way. I created a seperate NOTES.md file to start brainstorming on project ideas and lay out my steps.

**Walkthrough Videos, Student Examples, and Study Groups**

There are a couple of Walkthrough Videos within the Final section. I HIGHLY recommend that you watch them and then watch them again! They are there to help guide you through this project and give you a good idea on how to tackle it.

The other resource available are the student examples. I enjoyed reviewing these because it gave me a peak into how other students create their own code.

Last but not least, my all time favorite - Study Groups. The Learn Instructors set up study groups  that are specific to this project and they are *extremely * useful. The instructors go over the lab and answer any and all questions you may have. For example, if you're stuck on what idea you'd like to pursue for the lab, they are there to help!

Inspiration overload...

**Idea and Take Off**

The idea I chose for my CLI was to provide the user with the Top 20 Companies to Work for, based off of Fortune.com.

The user experience I wanted to create was to provide the names of the companies and their respective ranks. From there, the user could select what company they wanted more information on.

After the pseudocode for the CLI has been created, it's time to make some magic and build the actual interface!

**Project is a GO**

With all of the resources and your knowledge....you are ready to go! To summarize all this awesomeness:

**DO**
1. Read through the entire README.md file.
2. Take notes on the specific requirements that you have to complete to pass the project.
3. Watch all walkthrough videos (2x if necessary!)
4. Clone and review the previous student examples.
5. Attend Study Groups for this project.

**DON'T**
1. Rush through this project and miss some requirements. The requirements are there to help you get 100% from this assignment.
2. Copy word for word from the previous students' assignments. This is your opportunity to learn a little bit more!
3. Be afraid to ask for help. The Learn instructors are there to help you brainstorm and work through your project; reach out to them if you are stuck.

And always remember that this is a project to help you continue in your learning process as a beginner. Don't be too hard on yourself if this takes longer than expected.

**Extra Gold Nugget: **

This quote helped me to remember to *be kind* to myself as a beginner. Hopefully it will help you too:

"Learning to program is hard, as is learning to do anything worthwhile when you're just starting out. Freaking out about not knowing anything is totally normal, and every budding programmer feels overwhelmed by the sheer magnitude of all that they don't know."

<3
Catherine Cordova


text:
<!DOCTYPE html>

<title>demo widget</title>

<link rel="stylesheet" href="http://yui.yahooapis.com/3.0.0b1/build/cssfonts/fonts-min.css">


text:
struct GenericException;
struct ParseException;

struct GenericException: public std::exception
{
	GenericException() : std::exception() {}
	virtual const char* what() const throw()
	{
		return "Exception while parsing json.";
	}
};

#define RAPIDJSON_HAS_STDSTRING 0
#define RAPIDJSON_HAS_CXX11_NOEXCEPT 0
#define RAPIDJSON_ASSERT(x) do {if (!(x)) throw GenericException(); } while(0);
#define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \
	throw ParseException(parseErrorCode, #parseErrorCode, offset)

#include "rapidjson/error/error.h"
struct ParseException: public std::runtime_error, public rapidjson::ParseResult
{
	ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset) : std::runtime_error(msg),
		ParseResult(code, offset) {}
};

#include "rapidjson/error/en.h"
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"

#if defined(__GNUC__) && __GNUC__ >= 8
#pragma GCC diagnostic pop
#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:useLevel="true">

    <solid android:color="@color/grayTrasnparent" ></solid>

    <padding android:bottom="2dp"
        android:left="2dp"
        android:right="2dp"
        android:top="2dp"></padding>

    <corners android:radius="5dp"></corners>

</shape>


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

// clang-format off
import {sendWithPromise} from 'chrome://resources/js/cr.m.js';
// clang-format on

export interface ResetBrowserProxy {
  /**
   * @param sendSettings Whether the user gave consent to upload broken settings
   *     to Google for analysis.
   * @param requestOrigin The origin of the reset request.
   * @return A promise firing once resetting has completed.
   */
  performResetProfileSettings(sendSettings: boolean, requestOrigin: string):
      Promise<void>;

  /**
   * A method to be called when the reset profile dialog is hidden.
   */
  onHideResetProfileDialog(): void;

  /**
   * A method to be called when the reset profile banner is hidden.
   */
  onHideResetProfileBanner(): void;

  /**
   * A method to be called when the reset profile dialog is shown.
   */
  onShowResetProfileDialog(): void;

  /**
   * Shows the settings that are about to be reset and which will be reported
   * to Google for analysis, in a new tab.
   */
  showReportedSettings(): void;

  /**
   * Retrieves the triggered reset tool name.
   * @return A promise firing with the tool name, once it has been retrieved.
   */
  getTriggeredResetToolName(): Promise<string>;
}

export class ResetBrowserProxyImpl implements ResetBrowserProxy {
  performResetProfileSettings(sendSettings: boolean, requestOrigin: string) {
    return sendWithPromise(
        'performResetProfileSettings', sendSettings, requestOrigin);
  }

  onHideResetProfileDialog() {
    chrome.send('onHideResetProfileDialog');
  }

  onHideResetProfileBanner() {
    chrome.send('onHideResetProfileBanner');
  }

  onShowResetProfileDialog() {
    chrome.send('onShowResetProfileDialog');
  }

  showReportedSettings() {
    sendWithPromise('getReportedSettings')
        .then(function(settings: Array<{key: string, value: string}>) {
          const output = settings.map(function(entry) {
            return entry.key + ': ' + entry.value.replace(/\n/g, ', ');
          });
          const win = window.open('about:blank')!;
          const div = win.document.createElement('div');
          div.textContent = output.join('\n');
          div.style.whiteSpace = 'pre';
          win.document.body.appendChild(div);
        });
  }

  getTriggeredResetToolName(): Promise<string> {
    return sendWithPromise('getTriggeredResetToolName');
  }

  static getInstance(): ResetBrowserProxy {
    return instance || (instance = new ResetBrowserProxyImpl());
  }

  static setInstance(obj: ResetBrowserProxy) {
    instance = obj;
  }
}

let instance: ResetBrowserProxy|null = null;


text:
This is a personal project. This program will be a command-line to-do list manager. I'm experimenting with both sqlite integration/file writing. I'll update as I go.

# Hello there!


text:
static VALUE hallo_welt_hello(VALUE self) {
  VALUE string = rb_str_new2("Hello World!");
  return rb_funcall(self, rb_intern("print"), 1, string);
}

static VALUE hallo_welt_print(VALUE self, VALUE obj) {
  VALUE printable = rb_funcall(obj, rb_intern("to_s"), 0);
  switch (TYPE(printable)) {
    case T_STRING:
      printf("%s\n", RSTRING_PTR(printable));
      break;
    default:
      rb_raise(rb_eTypeError, "Could not obtain a valid String!");
      break;
  }
  return Qnil;
}

void Init_hallo_welt(void) {
  VALUE cHalloWelt;

  cHalloWelt = rb_const_get(rb_cObject, rb_intern("HalloWelt"));
  rb_define_method(cHalloWelt, "hello", hallo_welt_hello, 0);
  rb_define_method(cHalloWelt, "print", hallo_welt_print, 1);
}


text:
using System;

namespace Azure.Management.Compute.Models
{
    internal static class OperatingSystemTypesExtensions
    {
        public static string ToSerialString(this OperatingSystemTypes value) => value switch
        {
            OperatingSystemTypes.Windows => "Windows",
            OperatingSystemTypes.Linux => "Linux",
            _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown OperatingSystemTypes value.")
        };

        public static OperatingSystemTypes ToOperatingSystemTypes(this string value)
        {
            if (string.Equals(value, "Windows", StringComparison.InvariantCultureIgnoreCase)) return OperatingSystemTypes.Windows;
            if (string.Equals(value, "Linux", StringComparison.InvariantCultureIgnoreCase)) return OperatingSystemTypes.Linux;
            throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown OperatingSystemTypes value.");
        }
    }
}


text:
#import "AWSRequest.h"

@class NSString, NSNumber;

@interface AWSKinesisCreateStreamInput : AWSRequest {
	NSNumber* _shardCount;
	NSString* _streamName;
}
@property(retain, nonatomic) NSNumber* shardCount;
@property(retain, nonatomic) NSString* streamName;
+ (id)JSONKeyPathsByPropertyKey;
- (void).cxx_destruct;
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<!-- Information -->
	<groupId>jeo</groupId>
	<artifactId>jeo</artifactId>
	<version>1.8.0</version>
	<packaging>pom</packaging>
	<name>Jeo</name>
	<description>Java libraries containing generic structures and matrix operations (extending JAMA)</description>
	<url>https://github.com/barrasflorian/jeo</url>
	<!-- License -->
	<licenses>
		<license>
			<name>MIT License</name>
			<url>https://github.com/barrasflorian/jeo/blob/master/LICENSE</url>
		</license>
	</licenses>
	<!-- Modules -->
	<modules>
		<module>Android</module>
		<module>Common</module>
		<module>Games</module>
		<module>Graphics</module>
		<module>GUI</module>
		<module>MachineLearning</module>
		<module>Math</module>
		<module>Network</module>
	</modules>
	<!-- Properties -->
	<properties>
		<!-- Project -->
		<project.build.source>1.8</project.build.source>
		<project.build.target>1.8</project.build.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- Maven -->
		<maven.version>2.2.1</maven.version>
		<maven.compiler.version>2.5.1</maven.compiler.version>
		<maven.javadoc.version>2.10.3</maven.javadoc.version>
		<!-- Default goal -->
		<default.goal>install</default.goal>
		<!-- Structure -->
		<structure.source.folder>src</structure.source.folder>
		<structure.output.folder>out</structure.output.folder>
		<structure.resources.folder>res</structure.resources.folder>
		<!-- Final name -->
		<final.name>${project.groupId}-${project.artifactId}-${project.version}</final.name>
	</properties>
	<!-- Dependencies -->
	<dependencies>
		<!-- Maven -->
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-artifact</artifactId>
			<version>${maven.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-project</artifactId>
			<version>${maven.version}</version>
		</dependency>
	</dependencies>
	<!-- Build -->
	<build>
		<!-- Final name -->
		<finalName>${final.name}</finalName>
		<!-- Structure -->
		<sourceDirectory>${structure.source.folder}</sourceDirectory>
		<directory>${structure.output.folder}</directory>
		<outputDirectory>${structure.output.folder}/classes</outputDirectory>
		<resources>
			<resource>
				<directory>${structure.resources.folder}</directory>
			</resource>
		</resources>
		<!-- Default goal -->
		<defaultGoal>${default.goal}</defaultGoal>
		<!-- Plugins -->
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${maven.compiler.version}</version>
				<configuration>
					<source>${project.build.source}</source>
					<target>${project.build.target}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<!-- Reporting -->
	<reporting>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>${maven.javadoc.version}</version>
				<configuration>
					<overview>${basedir}/overview.html</overview>
				</configuration>
			</plugin>
		</plugins>
	</reporting>
</project>


text:
cask 'cuda' do
  version '8.0.47'
  sha256 '6866465217e88f7d0c17c202c4aa21281bd56671b863d810efa870d2bbed0a54'

  url "https://developer.nvidia.com/compute/cuda/#{version.major_minor}/Prod/local_installers/cuda_#{version}_mac-dmg"
  name 'Nvidia CUDA'
  homepage 'https://developer.nvidia.com/cuda-zone'

  installer script: 'CUDAMacOSXInstaller.app/Contents/MacOS/CUDAMacOSXInstaller',
            args:   ['--accept-eula', '--silent']

  uninstall script: "/Developer/NVIDIA/CUDA-#{version.major_minor}/bin/uninstall_cuda_#{version.major_minor}.pl"
end


text:
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Spell_Untraceable extends Spell
{

	@Override
	public String ID()
	{
		return "Spell_Untraceable";
	}

	private final static String	localizedName	= CMLib.lang().L("Untraceable");

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

	private final static String	localizedStaticDisplay	= CMLib.lang().L("(Untraceable)");

	@Override
	public String displayText()
	{
		return canBeUninvoked() ? localizedStaticDisplay : "";
	}

	@Override
	public int abstractQuality()
	{
		return Ability.QUALITY_OK_SELF;
	}

	@Override
	protected int canAffectCode()
	{
		return CAN_MOBS;
	}

	@Override
	public int classificationCode()
	{
		return Ability.ACODE_SPELL | Ability.DOMAIN_ABJURATION;
	}

	@Override
	public void unInvoke()
	{
		if(!(affected instanceof MOB))
			return;
		final MOB mob=(MOB)affected;

		super.unInvoke();
		if(canBeUninvoked())
			mob.tell(L("You are no longer untraceable."));
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!(affected instanceof MOB))
			return super.okMessage(myHost,msg);

		final MOB mob=(MOB)affected;
		if((!msg.amISource(mob))
		&&(msg.target()==mob)
		&&((msg.source().location()!=mob.location())
			||(!CMLib.flags().canBeSeenBy(mob, msg.source())))
		&&(msg.tool() instanceof Ability)
		&&(proficiencyCheck(mob,0,false))
		&&(msg.sourceMinor()!=CMMsg.TYP_TEACH)
		&&((CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_TRACKING))
			||(CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_TRANSPORTING))
			||(((Ability)msg.tool()).classificationCode()==(Ability.ACODE_SPELL | Ability.DOMAIN_DIVINATION))))
		{
			msg.source().tell(L("You can't get a bead on @x1.",mob.charStats().himher()));
			super.helpProficiency(mob, 0);
			return false;
		}
		return super.okMessage(myHost,msg);
	}

	@Override
	public void executeMsg(final Environmental myHost, final CMMsg msg)
	{
		super.executeMsg(myHost, msg);
	}

	@Override
	public void affectCharStats(final MOB affected, final CharStats affectableStats)
	{
		super.affectCharStats(affected,affectableStats);
	}

	@Override
	public void affectPhyStats(final Physical affected, final PhyStats affectableStats)
	{
		super.affectPhyStats(affected,affectableStats);
	}

	@Override
	public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
	{
		MOB target=mob;
		if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
			target=(MOB)givenTarget;
		if(target.fetchEffect(this.ID())!=null)
		{
			failureTell(mob,target,auto,L("<S-NAME> <S-IS-ARE> already untraceable."));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> become(s) untraceable!"):L("^S<S-NAME> incant(s) obscurely, invoking untraceability!^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				beneficialAffect(mob,target,asLevel,0);
			}
		}
		else
			beneficialVisualFizzle(mob,null,L("<S-NAME> incant(s) obscurely, but the spell fizzles."));

		return success;
	}
}


text:
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

    <title>PHPXRef 0.7.1 : Unnamed Project : /application/config/constants.php source</title>
    <link rel="stylesheet" href="../../sample.css" type="text/css">
    <link rel="stylesheet" href="../../sample-print.css" type="text/css" media="print">

    <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">

            [ Index ]

PHP Cross Reference of Unnamed Project

[ Show Explorer ]
[ Hide Navbar ]

title

Body

[close]

/application/config/ -> constants.php (source)

[Summary view]
[Print]
[Text view]

   1  <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
   2
   3  /*
   4  |--------------------------------------------------------------------------
   5  | File and Directory Modes
   6  |--------------------------------------------------------------------------
   7  |
   8  | These prefs are used when checking and setting modes when working
   9  | with the file system.  The defaults are fine on servers with proper
  10  | security, but you may wish (or even need) to change the values in
  11  | certain environments (Apache running a separate process for each
  12  | user, PHP under CGI with Apache suEXEC, etc.).  Octal values should
  13  | always be used to set the mode correctly.
  14  |
  15  */
  16  define('FILE_READ_MODE', 0644);
  17  define('FILE_WRITE_MODE', 0666);
  18  define('DIR_READ_MODE', 0755);
  19  define('DIR_WRITE_MODE', 0777);
  20
  21  /*
  22  |--------------------------------------------------------------------------
  23  | File Stream Modes
  24  |--------------------------------------------------------------------------
  25  |
  26  | These modes are used when working with fopen()/popen()
  27  |
  28  */
  29
  30  define('FOPEN_READ',                            'rb');
  31  define('FOPEN_READ_WRITE',                        'r+b');
  32  define('FOPEN_WRITE_CREATE_DESTRUCTIVE',        'wb'); // truncates existing file data, use with care
  33  define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE',    'w+b'); // truncates existing file data, use with care
  34  define('FOPEN_WRITE_CREATE',                    'ab');
  35  define('FOPEN_READ_WRITE_CREATE',                'a+b');
  36  define('FOPEN_WRITE_CREATE_STRICT',                'xb');
  37  define('FOPEN_READ_WRITE_CREATE_STRICT',        'x+b');
  38
  39
  40  /* End of file constants.php */
  41  /* Location: ./application/config/constants.php */

title

Description

Body

title

Description

Body

title

Description

Body

title

Body

Generated: Thu Oct 23 19:31:09 2014
	Cross-referenced by PHPXref 0.7.1


text:
@implementation DBChooserResult

- (id)initWithDictionary:(NSDictionary*)dictionary
{
    self = [super init];
    if (self) {
        _link = [NSURL URLWithString:dictionary[@"link"]];
        _name = dictionary[@"name"];
        _size = [dictionary[@"bytes"] longLongValue];
        _iconURL = [NSURL URLWithString:dictionary[@"icon"]];

        NSDictionary *thumbnailsStringDict = dictionary[@"thumbnails"];
        NSMutableDictionary *thumbnailsDict = [NSMutableDictionary dictionaryWithCapacity:[thumbnailsStringDict count]];
        [thumbnailsStringDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            thumbnailsDict[key] = [NSURL URLWithString:obj];
        }];
        _thumbnails = thumbnailsDict;
    }
    return self;
}

@end


text:
import { html } from 'haunted';
import { ifDefined } from 'lit-html/directives/if-defined.js';
import { triangle } from '../icons';

export const render = ({ column, on, descending, setOn, setDescending }) => {
	const { name, title } = column ?? {};
	return html`<button
		class="sg"
		title=${title}
		data-on=${ifDefined(
			(name === on && (descending ? 'desc' : 'asc')) || undefined
		)}
		@click=${(e) => {
			const on = e.currentTarget?.dataset.on;
			if (!on) {
				setOn(name);
				setDescending(false);
			}
			if (on === 'asc') {
				setDescending(true);
			} else if (on === 'desc') {
				setOn();
				setDescending(false);
			}
		}}
	>
		<span>${title}</span> ${triangle}
	</button>`;
};

export const renderAll = ({ columns, ...thru }) =>
	columns?.map((column) => render({ column, ...thru }));

export const group = () => html`
	<sort-and-group-consumer
		class="sgs"
		.render=${({
			columns,
			groupOn: on,
			setGroupOn: setOn,
			groupOnDescending: descending,
			setGroupOnDescending: setDescending,
		} = {}) =>
			renderAll({
				columns: columns?.filter?.((c) => c['groupOn']),
				on,
				setOn,
				descending,
				setDescending,
			})}
	>
	</sort-and-group-consumer>
`;

export const sort = () => html`
	<sort-and-group-consumer
		class="sgs"
		.render=${({
			columns,
			sortOn: on,
			setSortOn: setOn,
			descending,
			setDescending,
		} = {}) =>
			renderAll({
				columns: columns?.filter?.((c) => c['sortOn']),
				on,
				setOn,
				descending,
				setDescending,
			})}
	>
	</sort-and-group-consumer>
`;


text:
<?php

namespace Drupal\bootstrap\Plugin\Process;

use Drupal\bootstrap\Utility\Element;
use Drupal\Core\Form\FormStateInterface;

/**
 * Processes the "managed_file" element.
 *
 * @ingroup plugins_process
 *
 * @BootstrapProcess("managed_file")
 */
class ManagedFile extends ProcessBase implements ProcessInterface {

  /**
   * {@inheritdoc}
   */
  public static function processElement(Element $element, FormStateInterface $form_state, array &$complete_form) {
    $ajax_wrapper_id = $element->upload_button->getProperty('ajax')['wrapper'];
    if ($prefix = $element->getProperty('prefix')) {
      $prefix = preg_replace('/
/', '
', $prefix);
      $element->setProperty('prefix', $prefix);
    }
  }

}


text: await operation();


text:
<?php

namespace Acme\MainBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * CompanyRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CompanyRepository extends EntityRepository
{

	/**
	 * @param bool|integer $id
	 * @param bool|integer $limit
	 * @param null|City $city
	 * @return array
	 */
    public function getTop($id = false, $limit = false, $city = null)
    {
		$query = $this->createQueryBuilder('c')
			->where('c.status = :status')
			->setParameter('status', Company::STATUS_ON)

			->orderBy('c.rating', 'DESC')
			->addOrderBy('c.id', 'DESC')
		;

        if ($id) {
			$query
				->where('c.id != :cId')
				->setParameter('cId', $id)
			;
		}

        if ($city) {
            $query
				->join('c.city', 'city')
                ->where('city.id = :cityId')
                ->setParameter('cityId', $city->getId())
			;
        }

        if ($limit)
            $query->setMaxResults($limit);

        return $query->getQuery()->getResult();
    }

	/**
	 * @param City $city
	 * @param int $limit
	 * @return array
	 */
	public function getPopularByCity(City $city, $limit = 4)
	{
		$query = $this->createQueryBuilder('com')
			->join('com.city', 'city')

			->where('city.id = :cityId AND com.status = :status')
			->setParameter('cityId', $city->getId())
//			->andWhere('com.status = :status')
			->setParameter('status', Company::STATUS_ON)

			->orderBy('com.rating', 'DESC')

			->setMaxResults($limit)
			;

		return $query->getQuery()->getResult();
    }
}


text:
namespace tests
{

    const bond::Metadata Foo::Schema::metadata
        = Foo::Schema::GetMetadata();

    const bond::Metadata Foo::Schema::s_o_metadata
        = bond::reflection::MetadataInit("o");

    const bond::Metadata Foo::Schema::s_r_metadata
        = bond::reflection::MetadataInit("r", bond::reflection::required_field_modifier::value,
            bond::reflection::Attributes());

    const bond::Metadata Foo::Schema::s_ro_metadata
        = bond::reflection::MetadataInit("ro", bond::reflection::required_optional_field_modifier::value,
            bond::reflection::Attributes());

} // namespace tests


text:
#include "ctkModuleDescriptionConverter.h"

ctkModuleDescriptionConverter::ctkModuleDescriptionConverter()
{

}

ctkModuleDescriptionConverter::~ctkModuleDescriptionConverter()
{

}

void ctkModuleDescriptionConverter::setModuleDescription( const ctkModuleDescription &val )
{
  this->ModuleDescription = val;
}


text:
import asyncio
import discord
from   discord.ext import commands
from   Cogs import Settings
from   Cogs import DisplayName
from   Cogs import Nullify

# This is the Face module. It sends faces.

class Face:

	# Init with the bot reference, and a reference to the settings var
	def __init__(self, bot, settings):
		self.bot = bot
		self.settings = settings

	@commands.command(pass_context=True)
	async def lenny(self, ctx, *, message : str = None):
		"""Give me some Lenny."""

		# Check if we're suppressing @here and @everyone mentions
		if self.settings.getServerStat(ctx.message.server, "SuppressMentions").lower() == "yes":
			suppress = True
		else:
			suppress = False

		# Log the user
		self.settings.setServerStat(ctx.message.server, "LastLenny", ctx.message.author.id)

		msg = "( ͡° ͜ʖ ͡°)"
		if message:
			msg += "\n{}".format(message)
		# Check for suppress
		if suppress:
			msg = Nullify.clean(msg)
		# Send new message first, then delete original
		await self.bot.send_message(ctx.message.channel, msg)
		# Remove original message
		await self.bot.delete_message(ctx.message)

	@commands.command(pass_context=True)
	async def lastlenny(self, ctx):
		"""Who Lenny'ed last?"""
		lastLen = self.settings.getServerStat(ctx.message.server, "LastLenny")
		msg = 'No one has Lenny\'ed on my watch yet...'
		if lastLen:
			# Got someone
			memberName = DisplayName.name(DisplayName.memberForID(lastLen, ctx.message.server))
			if memberName:
				msg = '*{}* was the last person to use the `{}lenny` command.'.format(memberName, ctx.prefix)
			else:
				msg = 'The user that last used the `{}lenny` command is no longer on this server.'.format(ctx.prefix)
		await self.bot.send_message(ctx.message.channel, msg)

	@commands.command(pass_context=True)
	async def shrug(self, ctx, *, message : str = None):
		"""Shrug it off."""

		# Check if we're suppressing @here and @everyone mentions
		if self.settings.getServerStat(ctx.message.server, "SuppressMentions").lower() == "yes":
			suppress = True
		else:
			suppress = False

		# Log the user
		self.settings.setServerStat(ctx.message.server, "LastShrug", ctx.message.author.id)

		msg = "¯\_(ツ)_/¯"
		if message:
			msg += "\n{}".format(message)
		# Check for suppress
		if suppress:
			msg = Nullify.clean(msg)
		# Send new message first, then delete original
		await self.bot.send_message(ctx.message.channel, msg)
		# Remove original message
		await self.bot.delete_message(ctx.message)

	@commands.command(pass_context=True)
	async def lastshrug(self, ctx):
		"""Who shrugged last?"""
		lastLen = self.settings.getServerStat(ctx.message.server, "LastShrug")
		msg = 'No one has shrugged on my watch yet...'
		if lastLen:
			# Got someone
			memberName = DisplayName.name(DisplayName.memberForID(lastLen, ctx.message.server))
			if memberName:
				msg = '*{}* was the last person to use the `{}shrug` command.'.format(memberName, ctx.prefix)
			else:
				msg = 'The user that last used the `{}shrug` command is no longer on this server.'.format(ctx.prefix)
		await self.bot.send_message(ctx.message.channel, msg)


text:
#include "mitkDisplayInteractor.h"
#include "mitkBaseRenderer.h"
#include "mitkInteractionPositionEvent.h"
#include "mitkPropertyList.h"
#include <string.h>
// level window
#include "mitkStandaloneDataStorage.h"
#include "mitkNodePredicateDataType.h"
#include "mitkLevelWindowProperty.h"
#include "mitkLevelWindow.h"

void mitk::DisplayInteractor::Notify(InteractionEvent* interactionEvent, bool isHandled)
{
  // to use the state machine pattern,
  // the event is passed to the state machine interface to be handled
  if (!isHandled || m_AlwaysReact)
  {
    this->HandleEvent(interactionEvent, NULL);
  }
}

void mitk::DisplayInteractor::ConnectActionsAndFunctions()
{
  CONNECT_CONDITION( "check_position_event", CheckPositionEvent );

  CONNECT_FUNCTION("init", Init);
  CONNECT_FUNCTION("move", Move);
  CONNECT_FUNCTION("zoom", Zoom);
  CONNECT_FUNCTION("scroll", Scroll);
  CONNECT_FUNCTION("ScrollOneDown", ScrollOneDown);
  CONNECT_FUNCTION("ScrollOneUp", ScrollOneUp);
  CONNECT_FUNCTION("levelWindow", AdjustLevelWindow);
}

mitk::DisplayInteractor::DisplayInteractor()
: m_IndexToSliceModifier(4)
, m_AutoRepeat(false)
, m_InvertScrollDirection( false )
, m_InvertZoomDirection( false )
, m_InvertMoveDirection( false )
, m_InvertLevelWindowDirection( false )
, m_AlwaysReact(false)
, m_ZoomFactor(2)
{
  m_StartDisplayCoordinate.Fill(0);
  m_LastDisplayCoordinate.Fill(0);
  m_CurrentDisplayCoordinate.Fill(0);
}

mitk::DisplayInteractor::~DisplayInteractor()
{
}

bool mitk::DisplayInteractor::CheckPositionEvent( const InteractionEvent* interactionEvent )
{
  const InteractionPositionEvent* positionEvent = dynamic_cast<const InteractionPositionEvent*>(interactionEvent);
  if (positionEvent == NULL)
  {
    return false;
  }

  return true;
}

bool mitk::DisplayInteractor::Init(StateMachineAction*, InteractionEvent* interactionEvent)
{
  BaseRenderer* sender = interactionEvent->GetSender();
  InteractionPositionEvent* positionEvent = static_cast<InteractionPositionEvent*>(interactionEvent);

  Vector2D origin = sender->GetDisplayGeometry()->GetOriginInMM();
  double scaleFactorMMPerDisplayUnit = sender->GetDisplayGeometry()->GetScaleFactorMMPerDisplayUnit();
  m_StartDisplayCoordinate = positionEvent->GetPointerPositionOnScreen();
  m_LastDisplayCoordinate = positionEvent->GetPointerPositionOnScreen();
  m_CurrentDisplayCoordinate = positionEvent->GetPointerPositionOnScreen();
  m_StartCoordinateInMM = mitk::Point2D(
      (origin + m_StartDisplayCoordinate.GetVectorFromOrigin() * scaleFactorMMPerDisplayUnit).GetDataPointer());
  return true;
}

bool mitk::DisplayInteractor::Move(StateMachineAction*, InteractionEvent* interactionEvent)
{
  BaseRenderer* sender = interactionEvent->GetSender();
  InteractionPositionEvent* positionEvent = static_cast<InteractionPositionEvent*>(interactionEvent);

  float invertModifier = -1.0;
  if ( m_InvertMoveDirection )
  {
    invertModifier = 1.0;
  }

  // perform translation
  sender->GetDisplayGeometry()->MoveBy( (positionEvent->GetPointerPositionOnScreen() - m_LastDisplayCoordinate) * invertModifier );
  sender->GetRenderingManager()->RequestUpdate(sender->GetRenderWindow());
  m_LastDisplayCoordinate = positionEvent->GetPointerPositionOnScreen();
  return true;
}

bool mitk::DisplayInteractor::Zoom(StateMachineAction*, InteractionEvent* interactionEvent)
{
  const BaseRenderer::Pointer sender = interactionEvent->GetSender();
  InteractionPositionEvent* positionEvent = static_cast<InteractionPositionEvent*>(interactionEvent);

  float factor = 1.0;
  float distance = 0;

  if (m_ZoomDirection == "updown")
  {
    distance = m_CurrentDisplayCoordinate[1] - m_LastDisplayCoordinate[1];
  }
  else
  {
    distance = m_CurrentDisplayCoordinate[0] - m_LastDisplayCoordinate[0];
  }

  if ( m_InvertZoomDirection )
  {
    distance *= -1.0;
  }

  // set zooming speed
  if (distance < 0.0)
  {
    factor = 1.0 / m_ZoomFactor;
  }
  else if (distance > 0.0)
  {
    factor = 1.0 * m_ZoomFactor;
  }
  sender->GetDisplayGeometry()->ZoomWithFixedWorldCoordinates(factor, m_StartDisplayCoordinate, m_StartCoordinateInMM);
  sender->GetRenderingManager()->RequestUpdate(sender->GetRenderWindow());
  m_LastDisplayCoordinate = m_CurrentDisplayCoordinate;
  m_CurrentDisplayCoordinate = positionEvent->GetPointerPositionOnScreen();
  return true;
}

bool mitk::DisplayInteractor::Scroll(StateMachineAction*, InteractionEvent* interactionEvent)
{
  InteractionPositionEvent* positionEvent = static_cast<InteractionPositionEvent*>(interactionEvent);

  mitk::SliceNavigationController::Pointer sliceNaviController = interactionEvent->GetSender()->GetSliceNavigationController();
  if (sliceNaviController)
  {
    int delta = 0;
    // Scrolling direction
    if (m_ScrollDirection == "updown")
    {
      delta = static_cast<int>(m_LastDisplayCoordinate[1] - positionEvent->GetPointerPositionOnScreen()[1]);
    }
    else
    {
      delta = static_cast<int>(m_LastDisplayCoordinate[0] - positionEvent->GetPointerPositionOnScreen()[0]);
    }

    if ( m_InvertScrollDirection )
    {
      delta *= -1;
    }

    // Set how many pixels the mouse has to be moved to scroll one slice
    // if we moved less than 'm_IndexToSliceModifier' pixels slice ONE slice only
    if (delta > 0 && delta < m_IndexToSliceModifier)
    {
      delta = m_IndexToSliceModifier;
    }
    else if (delta < 0 && delta > -m_IndexToSliceModifier)
    {
      delta = -m_IndexToSliceModifier;
    }
    delta /= m_IndexToSliceModifier;

    int newPos = sliceNaviController->GetSlice()->GetPos() + delta;

    // if auto repeat is on, start at first slice if you reach the last slice and vice versa
    int maxSlices = sliceNaviController->GetSlice()->GetSteps();
    if (m_AutoRepeat)
    {
      while (newPos < 0)
      {
        newPos += maxSlices;
      }

      while (newPos >= maxSlices)
      {
        newPos -= maxSlices;
      }
    }
    else
    {
      // if the new slice is below 0 we still show slice 0
      // due to the stepper using unsigned int we have to do this ourselves
      if (newPos < 1)
      {
        newPos = 0;
      }
    }
    // set the new position
    sliceNaviController->GetSlice()->SetPos(newPos);
    m_LastDisplayCoordinate = m_CurrentDisplayCoordinate;
    m_CurrentDisplayCoordinate = positionEvent->GetPointerPositionOnScreen();
  }
  return true;
}

bool mitk::DisplayInteractor::ScrollOneDown(StateMachineAction*, InteractionEvent* interactionEvent)
{
  mitk::SliceNavigationController::Pointer sliceNaviController = interactionEvent->GetSender()->GetSliceNavigationController();
  if (!sliceNaviController->GetSliceLocked())
  {
    mitk::Stepper* stepper = sliceNaviController->GetSlice();
    if (stepper->GetSteps() <= 1)
    {
      stepper = sliceNaviController->GetTime();
    }
    stepper->Next();
  }
  return true;
}

bool mitk::DisplayInteractor::ScrollOneUp(StateMachineAction*, InteractionEvent* interactionEvent)
{
  mitk::SliceNavigationController::Pointer sliceNaviController = interactionEvent->GetSender()->GetSliceNavigationController();
  if (!sliceNaviController->GetSliceLocked())
  {
    mitk::Stepper* stepper = sliceNaviController->GetSlice();
    if (stepper->GetSteps() <= 1)
    {
      stepper = sliceNaviController->GetTime();
    }
    stepper->Previous();
    return true;
  }
  return false;
}

bool mitk::DisplayInteractor::AdjustLevelWindow(StateMachineAction*, InteractionEvent* interactionEvent)
{
  BaseRenderer::Pointer sender = interactionEvent->GetSender();
  InteractionPositionEvent* positionEvent = static_cast<InteractionPositionEvent*>(interactionEvent);

  m_LastDisplayCoordinate = m_CurrentDisplayCoordinate;
  m_CurrentDisplayCoordinate = positionEvent->GetPointerPositionOnScreen();
  // search for active image
  mitk::DataStorage::Pointer storage = sender->GetDataStorage();
  mitk::DataNode::Pointer node = NULL;
  mitk::DataStorage::SetOfObjects::ConstPointer allImageNodes = storage->GetSubset(mitk::NodePredicateDataType::New("Image"));
  for (unsigned int i = 0; i < allImageNodes->size(); i++)
  {
    bool isActiveImage = false;
    bool propFound = allImageNodes->at(i)->GetBoolProperty("imageForLevelWindow", isActiveImage);

    if (propFound && isActiveImage)
    {
      node = allImageNodes->at(i);
      continue;
    }
  }
  if (node.IsNull())
  {
    node = storage->GetNode(mitk::NodePredicateDataType::New("Image"));
  }
  if (node.IsNull())
  {
    return false;
  }

  mitk::LevelWindow lv = mitk::LevelWindow();
  node->GetLevelWindow(lv);
  ScalarType level = lv.GetLevel();
  ScalarType window = lv.GetWindow();

  int levelIndex = 0;
  int windowIndex = 1;

  if ( m_LevelDirection != "leftright" )
  {
    levelIndex = 1;
    windowIndex = 0;
  }

  int directionModifier = 1;
  if ( m_InvertLevelWindowDirection )
  {
    directionModifier = -1;
  }

  // calculate adjustments from mouse movements
  level += (m_CurrentDisplayCoordinate[levelIndex] - m_LastDisplayCoordinate[levelIndex]) * static_cast<ScalarType>(2) * directionModifier;
  window += (m_CurrentDisplayCoordinate[windowIndex] - m_LastDisplayCoordinate[windowIndex]) * static_cast<ScalarType>(2) * directionModifier;

  lv.SetLevelWindow(level, window);
  dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"))->SetLevelWindow(lv);

  sender->GetRenderingManager()->RequestUpdateAll();
  return true;
}

void mitk::DisplayInteractor::ConfigurationChanged()
{
  mitk::PropertyList::Pointer properties = GetAttributes();
  // auto repeat
  std::string strAutoRepeat = "";
  if (properties->GetStringProperty("autoRepeat", strAutoRepeat))
  {
    if (strAutoRepeat == "true")
    {
      m_AutoRepeat = true;
    }
    else
    {
      m_AutoRepeat = false;
    }
  }
  // pixel movement for scrolling one slice
  std::string strPixelPerSlice = "";
  if (properties->GetStringProperty("pixelPerSlice", strPixelPerSlice))
  {
    m_IndexToSliceModifier = atoi(strPixelPerSlice.c_str());
  }
  else
  {
    m_IndexToSliceModifier = 4;
  }
  // scroll direction
  if (!properties->GetStringProperty("scrollDirection", m_ScrollDirection))
  {
    m_ScrollDirection = "updown";
  }

  m_InvertScrollDirection = GetBoolProperty( properties, "invertScrollDirection", false );

  // zoom direction
  if (!properties->GetStringProperty("zoomDirection", m_ZoomDirection))
  {
    m_ZoomDirection = "updown";
  }

  m_InvertZoomDirection = GetBoolProperty( properties, "invertZoomDirection", false );

  m_InvertMoveDirection = GetBoolProperty( properties, "invertMoveDirection", false );

  if (!properties->GetStringProperty("levelWindowDirection", m_LevelDirection))
  {
    m_LevelDirection = "leftright";
  }

  m_InvertLevelWindowDirection = GetBoolProperty( properties, "invertLevelWindowDirection", false );

  // zoom factor
  std::string strZoomFactor = "";
  properties->GetStringProperty("zoomFactor", strZoomFactor);
  m_ZoomFactor = .05;
  if (atoi(strZoomFactor.c_str()) > 0)
  {
    m_ZoomFactor = 1.0 + (atoi(strZoomFactor.c_str()) / 100.0);
  }
  // allwaysReact
  std::string strAlwaysReact = "";
  if (properties->GetStringProperty("alwaysReact", strAlwaysReact))
  {
    if (strAlwaysReact == "true")
    {
      m_AlwaysReact = true;
    }
    else
    {
      m_AlwaysReact = false;
    }
  }
  else
  {
    m_AlwaysReact = false;
  }
}

bool mitk::DisplayInteractor::FilterEvents(InteractionEvent* /*interactionEvent*/, DataNode* /*dataNode*/)
{
  return true;
}

bool mitk::DisplayInteractor::GetBoolProperty( mitk::PropertyList::Pointer propertyList,
                                               const char* propertyName,
                                               bool defaultValue )
{
  std::string valueAsString;
  if ( !propertyList->GetStringProperty( propertyName, valueAsString ) )
  {
    return defaultValue;
  }
  else
  {
    if ( valueAsString == "true" )
    {
      return true;
    }
    else
    {
      return false;
    }
  }
}


text:
require 'set'
Rule_names = []
Rearrangements = []

Dir.glob(File.join(File.dirname(File.absolute_path(__FILE__)),"fragmentable", "*.rb")).map {|rfile| require rfile }

module Rubabel
  class Molecule
    module Fragmentable

      #RULES = Set[:cod, :codoo, :oxe, :oxepd, :oxh]
      #RULES = Set[:cod, :codoo, :oxe, :oxepd, :oxh, :oxhpd, :paoc, :nc] # :paoc is Phosphate Attack On Carbonyl Carbon
      @@rules = Set[*Rule_names]
      @@rearrangements = Set[*Rearrangements]
      def rules
        @@rules
      end
      RULES = @@rules
      REARRANGEMENTS = @@rearrangements

      DEFAULT_OPTIONS = {
        rules: @@rules - @@rearrangements,
        errors: :remove,
        # return only the set of unique fragments
        uniq: false,
        fragment_adduct_state: :as_published
      }

      # molecules and fragments should all have hydrogens added (add_h!)
      # before calling this method
      #
      # For instance, water loss with double bond formation is not allowable
      # for NCC(O)CC => CCC=C[NH2+], presumably because of the lone pair and
      # double bond resonance.
      def allowable_fragmentation?(frags)
        self.num_atoms(true) == frags.reduce(0) {|cnt,fr| cnt + fr.num_atoms(true) }
      end

      # returns the duplicated molecule and the equivalent atoms
      def dup_molecule(atoms=[])
        nmol = self.dup
        [nmol, atoms.map {|old_atom| nmol.atom(old_atom.id) }]
      end

      # An API for determining if a fragmentation rule should occur given configurable
      # parameters.  This takes into account adducts, charge state, instrument type... etc
      # Rubabel::FragmentationConditions?
      def instrument_configuration(rules, rearrangements)
      end

      # An API to select rules based upon the chemistry of the given molecule... ?  Maybe...
      def select_rules_by_molecule
      end

      # an empty array is returned if there are no fragments generated.
      # Hydrogens are added at a pH of 7.4, unless they have already been
      # added.
      #
      #     :rules => queryable by :include? set of rules
      #     :uniq => false
      #     :errors => :remove | :fix | :ignore  (default is :remove)
      #     :fragment_adduct_state => :force_adducts, :as_published (default), :no_adducts, :all (doubles fragment list size)
      def fragment(rules: @@rules- @@rearrangements, errors: :ignore, uniq: false, rearrange: true, fragment_adduct_state: DEFAULT_OPTIONS[:fragment_adduct_state], add_rule_names: false)
        only_uniqs = true # Option is currently ignored.
        # opts = DEFAULT_OPTIONS.merge(opts)
        rules.each do |rule|
          raise ArgumentError, "bad rule: #{rule}\nThe allowed rules are #{@@rules.entries.join(", ")}" unless @@rules.include?(rule)
        end

        had_hydrogens = self.h_added?
        self.correct_for_ph!(7.4) unless had_hydrogens
        self.remove_h!

        fragment_sets = {}
        fragments = []
        # call on API for selection rules from given experimental conditions
        #
        #
        # Fxn call to select rules...

        # Call all rules for now...
        rules.map do |rule|
          rule_fragments = self.send(rule, only_uniqs: only_uniqs, fragment_adduct_state: fragment_adduct_state)
          #binding.pry if rule_fragments.nil?
          rule_fragments = rule_fragments.flatten.compact
          if self.adducts?
          #  rule_fragments.map {|m| m.adducts = self.adducts }  # TODO THIS IS BAD, it doesn't allow for rules which don't produce adduct added fragments.  I was wrong and need to refactor the rules to account for this.
          end
          fragment_sets[rule] = rule_fragments.flatten.compact
          fragments << rule_fragments
        end

        if rearrange
          ::Rearrangements.map do |rule|
          #(::Rearrangements+::Rule_names).map do |rule|
            fragments.flatten.map do |fragment|
              rule_fragments = fragment.send(rule)
              if fragment_sets[rule]
                fragment_sets[rule] = (fragment_sets[rule] + rule_fragments).flatten
              else
                fragment_sets[rule] = rule_fragments
              end
              fragments << rule_fragments
            end
          end
        end

        # Error handling
        case :errors
        when :remove
          # This can't work like it used to, as I've already flattened away the meaning of the set
          puts "This is like ignore right now"
          #fragments.select! {|set| allowable_fragmentation?(set) }
        when :fix
          raise NotImplementedError
        when :ignore  # do nothing
        end

        self.remove_h!
        if uniq
          # TODO: implement properly
          raise NotImplementedError
          #fragment_sets = fragment_sets.uniq_by(&:csmiles)
        end

        if add_rule_names
          fragment_sets # Hash of fragments by rule
        else
          fragments.select {|a| not a.empty? } #Array of all fragments
        end
      end
      def rearrange(rules: @@rearrangements, errors: :remove, uniq: false)
        only_uniqs = uniq
        had_hydrogens = self.h_added?
        self.correct_for_ph!(7.4) unless had_hydrogens
        self.remove_h!
        fragment_sets = Hash.new {|h,k| h[k] = [] }
        fragments = []
        rules.map do |rule|
          rule_fragments = self.send(rule)
          fragment_sets[rule] << rule_fragments.flatten.compact
          fragments << rule_fragments
        end
        fragment_sets.each {|k, v| fragment_sets[k] = v.flatten }
        fragments
      end #rearrange
      def rearrange_but_return_sets(rules: @@rearrangements, errors: :remove, uniq: false)
        only_uniqs = uniq
        had_hydrogens = self.h_added?
        self.correct_for_ph!(7.4) unless had_hydrogens
        self.remove_h!
        fragment_sets = Hash.new {|h,k| h[k] = [] }
        fragments = []
        rules.map do |rule|
          rule_fragments = self.send(rule)
          fragment_sets[rule] << rule_fragments.flatten.compact
          fragments << rule_fragments
        end
        fragment_sets
      end #rearrange
    end
    include Fragmentable
  end
end # Rubabel


text:
DROP TABLE IF EXISTS books;
CREATE TABLE IF NOT EXISTS books(
  id SERIAL PRIMARY KEY,
  title VARCHAR(512),
  description TEXT,
  large_image_url VARCHAR(512),
  thumbnail_image_url VARCHAR(512) DEFAULT 'http://www.aobc.com/images/astd/no_book_image.gif',
  buy_link VARCHAR(512) DEFAULT 'https://www.amazon.com/Coding-Dummies-Computers-Nikhil-Abraham/dp/1118951301',
  average_rating DECIMAL DEFAULT 2.5,
  ratings_count INTEGER DEFAULT 0,
  list_price DECIMAL DEFAULT 0,
  published_at VARCHAR(32),
  page_count INTEGER DEFAULT 0
);

DROP TABLE IF EXISTS authors;
CREATE TABLE IF NOT EXISTS authors(
  id SERIAL PRIMARY KEY,
  name VARCHAR(256) NOT NULL UNIQUE
);

DROP TABLE IF EXISTS genres;
CREATE TABLE IF NOT EXISTS genres(
  id SERIAL PRIMARY KEY,
  name VARCHAR(256) NOT NULL UNIQUE
);

DROP TABLE IF EXISTS book_authors;
CREATE TABLE IF NOT EXISTS book_authors(
  book_id INTEGER REFERENCES books ON DELETE CASCADE,
  author_id INTEGER REFERENCES authors ON DELETE CASCADE
);

DROP TABLE IF EXISTS book_genres;
CREATE TABLE IF NOT EXISTS book_genres(
  book_id INTEGER REFERENCES books ON DELETE CASCADE,
  genre_id INTEGER REFERENCES genres ON DELETE CASCADE
);


text:
package model

import "gopkg.in/mgo.v2/bson"

type User struct {
	ID             bson.ObjectId `bson:"_id,omitempty" json:"id"`
	Name           string        `bson:"name" json:"name"`
	Email          string        `bson:"email" json:"email"`
	EmailVerified  bool          `bson:"email_verified" json:"email_verified"`
	Password       []byte        `bson:"password" json:"-"`
	ActivationCode string        `bson:"activation_code,omitempty" json:"activation_code,omitempty"`
	RecoveryCode   string        `bson:"recovery_code,omitempty" json:"recovery_code,omitempty"`
	Roles          []string      `bson:"roles" json:"roles"`
}

func (u *User) AddRole(role string) {
	u.Roles = append(u.Roles, role)
}

func (u *User) RemoveRole(role string) {
	var roles []string
	for _, v := range u.Roles {
		if v == role {
			continue
		} else {
			roles = append(roles, v)
		}
	}
	u.Roles = roles
}