text:
/* ----------------------------------------------------------------------------------
 * Hint: This is a derived (generated) file. Changes should be done in the underlying
 * source files only (*.control, *.js) or they will be lost after the next generation.
 * ---------------------------------------------------------------------------------- */

// Provides control sap.suite.ui.commons.ThingCollection.
jQuery.sap.declare("sap.suite.ui.commons.ThingCollection");
jQuery.sap.require("sap.suite.ui.commons.library");
jQuery.sap.require("sap.ui.core.Control");

/**
 * Constructor for a new ThingCollection.
 *
 * Accepts an object literal mSettings that defines initial
 * property values, aggregated and associated objects as well as event handlers.
 *
 * If the name of a setting is ambiguous (e.g. a property has the same name as an event),
 * then the framework assumes property, aggregation, association, event in that order.
 * To override this automatic resolution, one of the prefixes "aggregation:", "association:"
 * or "event:" can be added to the name of the setting (such a prefixed name must be
 * enclosed in single or double quotes).
 *
 * The supported settings are:
 *

 *
Properties
 *

 *
{@link #getWidth width} : sap.ui.core.CSSSize (default: '100%')

 *
{@link #getHeight height} : sap.ui.core.CSSSize (default: '100%')

 *
{@link #getMinWidth minWidth} : sap.ui.core.CSSSize

 *
{@link #getMinHeight minHeight} : sap.ui.core.CSSSize

 *

 *
Aggregations
 *

 *
{@link #getContent content} : sap.ui.ux3.ThingViewer[]

 *

 *
Associations
 *

 *

 *
Events
 *

 *

 *

 *
 * @param {string} [sId] id for the new control, generated automatically if no id is given
 * @param {object} [mSettings] initial settings for the new control
 *
 * @class
 * This control contains a collection of the sap.ui.ux3.ThingViewer controls or descendants of sap.ui.ux3.ThingViewer. It allows you to navigate through them as well as delete them from the collection.
 * @extends sap.ui.core.Control
 * @version 1.30.8
 *
 * @constructor
 * @public
 * @name sap.suite.ui.commons.ThingCollection
 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
 */
sap.ui.core.Control.extend("sap.suite.ui.commons.ThingCollection", { metadata : {

	publicMethods : [
		// methods
		"shiftPrev", "shiftNext", "addNextContent"
	],
	library : "sap.suite.ui.commons",
	properties : {
		"width" : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : '100%'},
		"height" : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : '100%'},
		"minWidth" : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : null},
		"minHeight" : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : null}
	},
	aggregations : {
		"content" : {type : "sap.ui.ux3.ThingViewer", multiple : true, singularName : "content"}
	}
}});

/**
 * Creates a new subclass of class sap.suite.ui.commons.ThingCollection with name sClassName
 * and enriches it with the information contained in oClassInfo.
 *
 * oClassInfo might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}.
 *
 * @param {string} sClassName name of the class to be created
 * @param {object} [oClassInfo] object literal with informations about the class
 * @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata.
 * @return {function} the created class / constructor function
 * @public
 * @static
 * @name sap.suite.ui.commons.ThingCollection.extend
 * @function
 */

/**
 * Getter for property width.
 * The width of the control.
 *
 * Default value is 100%
 *
 * @return {sap.ui.core.CSSSize} the value of property width
 * @public
 * @name sap.suite.ui.commons.ThingCollection#getWidth
 * @function
 */

/**
 * Setter for property width.
 *
 * Default value is 100%
 *
 * @param {sap.ui.core.CSSSize} sWidth  new value for property width
 * @return {sap.suite.ui.commons.ThingCollection} this to allow method chaining
 * @public
 * @name sap.suite.ui.commons.ThingCollection#setWidth
 * @function
 */

/**
 * Getter for property height.
 * The height of the control.
 *
 * Default value is 100%
 *
 * @return {sap.ui.core.CSSSize} the value of property height
 * @public
 * @name sap.suite.ui.commons.ThingCollection#getHeight
 * @function
 */

/**
 * Setter for property height.
 *
 * Default value is 100%
 *
 * @param {sap.ui.core.CSSSize} sHeight  new value for property height
 * @return {sap.suite.ui.commons.ThingCollection} this to allow method chaining
 * @public
 * @name sap.suite.ui.commons.ThingCollection#setHeight
 * @function
 */

/**
 * Getter for property minWidth.
 * The minimal width of the control.
 *
 * Default value is empty/undefined
 *
 * @return {sap.ui.core.CSSSize} the value of property minWidth
 * @public
 * @name sap.suite.ui.commons.ThingCollection#getMinWidth
 * @function
 */

/**
 * Setter for property minWidth.
 *
 * Default value is empty/undefined
 *
 * @param {sap.ui.core.CSSSize} sMinWidth  new value for property minWidth
 * @return {sap.suite.ui.commons.ThingCollection} this to allow method chaining
 * @public
 * @name sap.suite.ui.commons.ThingCollection#setMinWidth
 * @function
 */

/**
 * Getter for property minHeight.
 * The minimal height of the control.
 *
 * Default value is empty/undefined
 *
 * @return {sap.ui.core.CSSSize} the value of property minHeight
 * @public
 * @name sap.suite.ui.commons.ThingCollection#getMinHeight
 * @function
 */

/**
 * Setter for property minHeight.
 *
 * Default value is empty/undefined
 *
 * @param {sap.ui.core.CSSSize} sMinHeight  new value for property minHeight
 * @return {sap.suite.ui.commons.ThingCollection} this to allow method chaining
 * @public
 * @name sap.suite.ui.commons.ThingCollection#setMinHeight
 * @function
 */

/**
 * Getter for aggregation content.

 * Contains a collection of sap.ui.ux3.ThingViewer controls or descendants of sap.ui.ux3.ThingViewer.
 *
 * @return {sap.ui.ux3.ThingViewer[]}
 * @public
 * @name sap.suite.ui.commons.ThingCollection#getContent
 * @function
 */

/**
 * Inserts a content into the aggregation named content.
 *
 * @param {sap.ui.ux3.ThingViewer}
 *          oContent the content to insert; if empty, nothing is inserted
 * @param {int}
 *             iIndex the 0-based index the content should be inserted at; for
 *             a negative value of iIndex, the content is inserted at position 0; for a value
 *             greater than the current size of the aggregation, the content is inserted at
 *             the last position
 * @return {sap.suite.ui.commons.ThingCollection} this to allow method chaining
 * @public
 * @name sap.suite.ui.commons.ThingCollection#insertContent
 * @function
 */

/**
 * Adds some content oContent
 * to the aggregation named content.
 *
 * @param {sap.ui.ux3.ThingViewer}
 *            oContent the content to add; if empty, nothing is inserted
 * @return {sap.suite.ui.commons.ThingCollection} this to allow method chaining
 * @public
 * @name sap.suite.ui.commons.ThingCollection#addContent
 * @function
 */

/**
 * Removes an content from the aggregation named content.
 *
 * @param {int | string | sap.ui.ux3.ThingViewer} vContent the content to remove or its index or id
 * @return {sap.ui.ux3.ThingViewer} the removed content or null
 * @public
 * @name sap.suite.ui.commons.ThingCollection#removeContent
 * @function
 */

/**
 * Removes all the controls in the aggregation named content.

 * Additionally unregisters them from the hosting UIArea.
 * @return {sap.ui.ux3.ThingViewer[]} an array of the removed elements (might be empty)
 * @public
 * @name sap.suite.ui.commons.ThingCollection#removeAllContent
 * @function
 */

/**
 * Checks for the provided sap.ui.ux3.ThingViewer in the aggregation named content
 * and returns its index if found or -1 otherwise.
 *
 * @param {sap.ui.ux3.ThingViewer}
 *            oContent the content whose index is looked for.
 * @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
 * @public
 * @name sap.suite.ui.commons.ThingCollection#indexOfContent
 * @function
 */

/**
 * Destroys all the content in the aggregation
 * named content.
 * @return {sap.suite.ui.commons.ThingCollection} this to allow method chaining
 * @public
 * @name sap.suite.ui.commons.ThingCollection#destroyContent
 * @function
 */

/**
 * Displays a previous item in the collection.
 *
 * @name sap.suite.ui.commons.ThingCollection#shiftPrev
 * @function
 * @type void
 * @public
 * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
 */

/**
 * Displays the next item in the collection.
 *
 * @name sap.suite.ui.commons.ThingCollection#shiftNext
 * @function
 * @type void
 * @public
 * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
 */

/**
 * Inserts an element into the next display position.
 *
 * @name sap.suite.ui.commons.ThingCollection#addNextContent
 * @function
 * @param {sap.ui.ux3.ThingViewer} oOContent
 *         An instance of ThingViewer or an instance of its descendant.
 * @type sap.suite.ui.commons.ThingCollection
 * @public
 * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
 */

// Start of sap/suite/ui/commons/ThingCollection.js
///**
// * This file defines behavior for the control,
// */
sap.suite.ui.commons.ThingCollection.prototype.init = function() {
	this._iCenterNum = 0;
    this._bScrollDisabled = false;
    var that = this;
    this._rb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.commons");

    this._oRemoveButton = new sap.ui.commons.Link({
        id: this.getId() + "-remove-button",
        tooltip: this._rb.getText("THINGCOLLECTION_BUTTON_REMOVE_TOOLTIP"),
        press: function() {
            that._removeCenterContent();
        }
    });
    this._oRemoveButton.addStyleClass("sapUiUx3OverlayCloseButton");

    this._initTouchEvents();
};

sap.suite.ui.commons.ThingCollection.prototype.exit = function() {
	this._oRemoveButton.destroy();
};

sap.suite.ui.commons.ThingCollection.prototype.onBeforeRendering = function() {
    this._oCenterControl = this.getContent()[this._iCenterNum] || null;
};

sap.suite.ui.commons.ThingCollection.prototype.onAfterRendering = function() {
    var that = this;

    jQuery.sap.byId(this.getId() + "-nav-prev").bind("click", function() { that.shiftPrev(); });
    jQuery.sap.byId(this.getId() + "-nav-next").bind("click", function() { that.shiftNext(); });

    this._updateArrows();

    if(this.getContent().length <= 1) {
        this._hideRemoveButton();
    }

    jQuery.sap.byId(this._oRemoveButton.getId()).attr("role", "button");
    jQuery.sap.byId(this._oRemoveButton.getId()).attr("aria-disabled", "false");
};

sap.suite.ui.commons.ThingCollection.prototype.addContent = function(oContent) {
    this.addAggregation("content", oContent, true);
    this._updateArrows();
    this._showRemoveButton();
    return this;
};

sap.suite.ui.commons.ThingCollection.prototype.addNextContent = function(oContent) {
    this.insertAggregation("content", oContent, this._iCenterNum + 1, true);
    this._updateArrows();
    this._showRemoveButton();
    return this;
};

sap.suite.ui.commons.ThingCollection.prototype.shiftPrev = function() {
    if (this._isShiftPrevForbidden()) {
        return;
    }

    var that = this;
    this._hideRemoveButton();
    this._bScrollDisabled = true;

    var sContainerId = "#" + this.getId() + "-container";
    var oPrevPanel = jQuery(sContainerId + ">.sapSuiteTcPrev");
    var oCenterPanel = jQuery(sContainerId + ">.sapSuiteTcCenter");
    var oNextPanel = jQuery(sContainerId + ">.sapSuiteTcNext");

    var oRm = sap.ui.getCore().createRenderManager();

    var sDirection = sap.ui.getCore().getConfiguration().getRTL() ? "right" : "left";
    this._iCenterNum--;
    var oDirection = {};
    oDirection[sDirection] = "+=110%";

    this._renderPrevPanel(oRm, this.getContent()[this._iCenterNum]);

    oCenterPanel.animate(oDirection, 800);

    oPrevPanel.animate(oDirection, 800, function() {
        oNextPanel.css(sDirection, "-110%");

        that._renderNextPanel(oRm);        // clear next panel
        oRm.destroy();

        that._bScrollDisabled = false;
        that._updateArrows();
        that._showRemoveButton();
        jQuery(sContainerId).focus();
        oCenterPanel.show();                // restore center panel if it was hidden on removing content
    });

    oPrevPanel.removeClass("sapSuiteTcPrev").addClass("sapSuiteTcCenter").attr("aria-hidden", "false");
    oCenterPanel.removeClass("sapSuiteTcCenter").addClass("sapSuiteTcNext").attr("aria-hidden", "true");
    oNextPanel.removeClass("sapSuiteTcNext").addClass("sapSuiteTcPrev");
};

sap.suite.ui.commons.ThingCollection.prototype.shiftNext = function() {
    if (this._isShiftNextForbidden()) {
        return;
    }

    var that = this;
    this._hideRemoveButton();
    this._bScrollDisabled = true;

    var sContainerId = "#" + this.getId() + "-container";
    var oPrevPanel = jQuery(sContainerId + ">.sapSuiteTcPrev");
    var oCenterPanel = jQuery(sContainerId + ">.sapSuiteTcCenter");
    var oNextPanel = jQuery(sContainerId + ">.sapSuiteTcNext");

    var oRm = sap.ui.getCore().createRenderManager();

    var sDirection = sap.ui.getCore().getConfiguration().getRTL() ? "right" : "left";
    this._iCenterNum++;

    var oDirection = {};
    oDirection[sDirection] = "-=110%";

    this._renderNextPanel(oRm, this.getContent()[this._iCenterNum]);

    oCenterPanel.animate(oDirection, 800);

    oNextPanel.animate(oDirection, 800, function() {
        oPrevPanel.css(sDirection, "110%");

        that._renderPrevPanel(oRm);     // clear previous panel
        oRm.destroy();

        that._bScrollDisabled = false;
        that._updateArrows();
        that._showRemoveButton();
        jQuery(sContainerId).focus();
        oCenterPanel.show();            // restore center panel if it was hidden on removing content
    });

    oPrevPanel.removeClass("sapSuiteTcPrev").addClass("sapSuiteTcNext");
    oCenterPanel.removeClass("sapSuiteTcCenter").addClass("sapSuiteTcPrev").attr("aria-hidden", "true");
    oNextPanel.removeClass("sapSuiteTcNext").addClass("sapSuiteTcCenter").attr("aria-hidden", "false");
};

sap.suite.ui.commons.ThingCollection.prototype.onsapprevious = function(oEvent) {
    this.shiftPrev();
    oEvent.preventDefault();
};

sap.suite.ui.commons.ThingCollection.prototype.onsapnext = function(oEvent) {
    this.shiftNext();
    oEvent.preventDefault();
};

sap.suite.ui.commons.ThingCollection.prototype._initTouchEvents = function() {
    if (jQuery.sap.touchEventMode != "OFF") {
        var that = this;

        this.onswipeleft = function(oEvent) {
            oEvent.preventDefault();
            that.shiftNext();
        };
        this.onswiperight = function(oEvent) {
            oEvent.preventDefault();
            that.shiftPrev();
        };
    }
};

sap.suite.ui.commons.ThingCollection.prototype._removeCenterContent = function() {
    this._hideRemoveButton();           // hide remove button immediately to prevent double click
    this.removeAggregation("content", this.getContent()[this._iCenterNum], true);

    var that = this;
    var iContentLength = this.getContent().length;

    var oCenterPanel = jQuery("#" + this.getId() + "-container>.sapSuiteTcCenter");
    oCenterPanel.hide(600);

    if (that._iCenterNum >= iContentLength) {
        that._iCenterNum = iContentLength;
        that.shiftPrev();
    } else {
        that._iCenterNum -= 1;
        that.shiftNext();
    }
};

sap.suite.ui.commons.ThingCollection.prototype._showRemoveButton = function() {
    if (this.getContent().length > 1) {
        jQuery.sap.byId(this.getId() + "-remove-button").show();
    }
};

sap.suite.ui.commons.ThingCollection.prototype._hideRemoveButton = function() {
    jQuery.sap.byId(this.getId() + "-remove-button").hide();
};

sap.suite.ui.commons.ThingCollection.prototype._updateArrows = function() {
    var oNavPrev = jQuery.sap.byId(this.getId() + "-nav-prev");
    var oNavNext = jQuery.sap.byId(this.getId() + "-nav-next");
    var sPrevTooltip = "";
    var sNextTooltip = "";

	if (this._isShiftPrevForbidden()) {
        oNavPrev.removeClass("sapSuiteTcNavPrevArrow");
    } else {
        oNavPrev.addClass("sapSuiteTcNavPrevArrow");
        sPrevTooltip = this._rb.getText("THINGCOLLECTION_BUTTON_PREVIOUS_TOOLTIP");
    }
	oNavPrev.attr("title", sPrevTooltip);

    if (this._isShiftNextForbidden()) {
        oNavNext.removeClass("sapSuiteTcNavNextArrow");
    } else {
        oNavNext.addClass("sapSuiteTcNavNextArrow");
        sNextTooltip = this._rb.getText("THINGCOLLECTION_BUTTON_NEXT_TOOLTIP");
    }
    oNavNext.attr("title", sNextTooltip);
};

sap.suite.ui.commons.ThingCollection.prototype._isShiftPrevForbidden = function() {
	return this._bScrollDisabled || (this._iCenterNum <= 0);
};

sap.suite.ui.commons.ThingCollection.prototype._isShiftNextForbidden = function() {
	return this._bScrollDisabled || (this._iCenterNum >= this.getContent().length - 1);
};

sap.suite.ui.commons.ThingCollection.prototype._renderPrevPanel = function(oRm, oControl) {
	this._renderPanel(oRm, oControl, true);
};

sap.suite.ui.commons.ThingCollection.prototype._renderNextPanel = function(oRm, oControl) {
	this._renderPanel(oRm, oControl, false);
};

sap.suite.ui.commons.ThingCollection.prototype._renderPanel = function(oRm, oControl, bLeft) {
    var sPanelSelector = "#" + this.getId() + "-container>" + (bLeft ? ".sapSuiteTcPrev" : ".sapSuiteTcNext");
    var oPanel = jQuery(sPanelSelector);

    if (oPanel.length > 0) {

        if (oControl) {
            oRm.renderControl(oControl);
        } else {
            oRm.write("");
        }

        oRm.flush(oPanel[0]);
    }
};


text:
Python wrapper around the Stanford Named Entity Recognizer (NER) Server and the Part-Of-Speech (POS) Tagger Server.

# Stanford Named Entity Recognizer Project

* [Home Page](https://nlp.stanford.edu/software/CRF-NER.shtml)
* [Running NER as a Server](https://nlp.stanford.edu/software/crf-faq.shtml#cc)

# Stanford Part-Of-Speech Tagger Project

* [Home Page](https://nlp.stanford.edu/software/tagger.shtml)
* [Running POS as a Server](https://nlp.stanford.edu/software/pos-tagger-faq.html#e)

# Installation
```
pip install sner
```
or

```
python setup install
```

# Start
## NER Client
Run the following commands to start the NER server

```
cd your_stanford_ner_dir
java -Djava.ext.dirs=./lib -cp stanford-ner.jar edu.stanford.nlp.ie.NERServer -port 9199 -loadClassifier ./classifiers/english.all.3class.distsim.crf.ser.gz  -tokenizerFactory edu.stanford.nlp.process.WhitespaceTokenizer -tokenizerOptions tokenizeNLs=false
```
Use the following in Python to access the NER server

```
from sner import Ner

test_string = "Alice went to the Museum of Natural History."
tagger = Ner(host='localhost',port=9199)
print(tagger.get_entities(test_string))

```
The following results are expected

```
[('Alice', 'PERSON'),
 ('went', 'O'),
 ('to', 'O'),
 ('the', 'O'),
 ('Museum', 'ORGANIZATION'),
 ('of', 'ORGANIZATION'),
 ('Natural', 'ORGANIZATION'),
 ('History', 'ORGANIZATION'),
 ('.', 'O')]
```

## POS Client
Run the following commands to start the POS server

```
cd your_stanford_pos_dir
java -cp stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTaggerServer -port 9198 -model models/english-bidirectional-distsim.tagger
```
Use the following in Python to access the POS server

```
from sner import POSClient

test_string = "Alice went to the Museum of Natural History."
tagger = POSClient(host='localhost', port=9198)
print(tagger.tag(test_string))
```
The following results are expected

```python
[('Alice', 'NNP'),
 ('went', 'VBD'),
 ('to', 'TO'),
 ('the', 'DT'),
 ('Museum', 'NNP'),
 ('of', 'IN'),
 ('Natural', 'NNP'),
 ('History', 'NN'),
 ('.', '.')]
```

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace App\DataFixtures;

use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

/**
 * Creates a user to be assigned as the maintainer of packages.
 */
class UserFixtures extends Fixture
{
    public const PACKAGE_MAINTAINER = 'package-maintainer';

    public function __construct(private UserPasswordHasherInterface $passwordHasher)
    {
    }

    public function load(ObjectManager $manager): void
    {
        $dev = new User;
        $dev->setEmail('dev@example.org');
        $dev->setUsername('dev');
        $dev->setPassword($this->passwordHasher->hashPassword($dev, 'dev'));
        $dev->setEnabled(true);
        $dev->setRoles(['ROLE_SUPERADMIN']);
        $dev->initializeApiToken();

        $manager->persist($dev);

        $user = new User;
        $user->setEmail('user@example.org');
        $user->setUsername('user');
        $user->setPassword($this->passwordHasher->hashPassword($user, 'user'));
        $user->setEnabled(true);
        $user->setRoles([]);
        $user->initializeApiToken();

        $manager->persist($user);
        $manager->flush();

        $this->addReference(self::PACKAGE_MAINTAINER, $dev);
    }
}


text:
import { EventEmitter } from 'events';
import { StreamReader } from './StreamReader';
import http from 'http';
import https from 'https';

export interface ParserOptions {
  autoUpdate: boolean
  emptyInterval: number
  errorInterval: number
  keepListen: boolean
  metadataInterval: number
  notifyOnChangeOnly: boolean
  url: string
  userAgent: string
}

export interface ParserEvents {
  'empty': () => void
  'end': () => void
  'error': (error: Error) => void
  'metadata': (metadata: Map<string, string>) => void
  'stream': (stream: StreamReader) => void
}

export declare interface Parser {
  emit: <T extends keyof ParserEvents>(event: T, ...args: Parameters<ParserEvents[T]>) => boolean
  on: <T extends keyof ParserEvents>(event: T, listener: ParserEvents[T]) => this
}

export class Parser extends EventEmitter {
  private previousMetadata: Map<string, string> = new Map<string, string>();
  private readonly options: ParserOptions = {
    autoUpdate: true,
    emptyInterval: 5 * 60,
    errorInterval: 10 * 60,
    keepListen: false,
    metadataInterval: 5,
    notifyOnChangeOnly: false,
    url: '',
    userAgent: 'icecast-parser',
  };

  public constructor (options: Partial<ParserOptions>) {
    super();

    this.options = { ...this.options, ...options };
    this.queueRequest();
  }

  protected onRequestResponse (response: http.IncomingMessage): void {
    const icyMetaInt = response.headers['icy-metaint'];

    if (typeof icyMetaInt === 'undefined') {
      this.destroyResponse(response);
      this.queueNextRequest(this.options.emptyInterval);
      this.emit('empty');
    } else {
      const reader = new StreamReader(Array.isArray(icyMetaInt) ? Number(icyMetaInt[0]) : Number(icyMetaInt));

      reader.on('metadata', (metadata: Map<string, string>) => {
        this.destroyResponse(response);
        this.queueNextRequest(this.options.metadataInterval);

        if (this.options.notifyOnChangeOnly && this.isMetadataChanged(metadata)) {
          this.previousMetadata = metadata;
          this.emit('metadata', metadata);
        } else if (!this.options.notifyOnChangeOnly) {
          this.emit('metadata', metadata);
        }
      });

      response.pipe(reader);
      this.emit('stream', reader);
    }
  }

  protected onRequestError (error: Error): void {
    this.queueNextRequest(this.options.errorInterval);
    this.emit('error', error);
  }

  protected onSocketEnd (): void {
    if (this.options.keepListen) {
      this.emit('end');
    }
  }

  protected makeRequest (): void {
    const request = this.options.url.startsWith('https://')
      ? https.request(this.options.url)
      : http.request(this.options.url);

    request.setHeader('Icy-MetaData', '1');
    request.setHeader('User-Agent', this.options.userAgent);
    request.once('socket', (socket) => socket.once('end', this.onSocketEnd.bind(this)));
    request.once('response', this.onRequestResponse.bind(this));
    request.once('error', this.onRequestError.bind(this));
    request.end();
  }

  protected destroyResponse (response: http.IncomingMessage): void {
    if (!this.options.keepListen) {
      response.destroy();
    }
  }

  protected queueNextRequest (timeout: number): void {
    if (this.options.autoUpdate && !this.options.keepListen) {
      this.queueRequest(timeout);
    }
  }

  protected queueRequest (timeout = 0): void {
    setTimeout(this.makeRequest.bind(this), timeout * 1000);
  }

  protected isMetadataChanged (metadata: Map<string, string>): boolean {
    for (const [key, value] of metadata.entries()) {
      if (this.previousMetadata.get(key) !== value) {
        return true;
      }
    }

    return false;
  }
}


text:
<!doctype html>

    <title>Code coverage report for cd-messenger/src</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      All files cd-messenger/src

        35.9%
        Statements
        14/39

        0%
        Branches
        0/6

        21.43%
        Functions
        3/14

        40.63%
        Lines
        13/32

   File

   Statements

   Branches

   Functions

   Lines

	messenger-node.js

	35.9%
	14/39
	0%
	0/6
	21.43%
	3/14
	40.63%
	13/32

  Code coverage
  generated by istanbul at Fri Mar 10 2017 16:03:16 GMT-0800 (PST)


text:
package plugin

import "github.com/vito/booklit"

func init() {
	booklit.RegisterPlugin("set-partials", NewPlugin)
}

func NewPlugin(section *booklit.Section) booklit.Plugin {
	return Plugin{
		section: section,
	}
}

type Plugin struct {
	section *booklit.Section
}

func (plugin Plugin) SetThePartial() {
	plugin.section.SetPartial("FooBar", booklit.Paragraph{
		booklit.String("I'm a partial!"),
	})
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// IPC messages for drag and drop.
// Multiply-included message file, hence no include guard.

#include "content/common/drag_event_source_info.h"
#include "content/public/common/common_param_traits.h"
#include "content/public/common/drop_data.h"
#include "ipc/ipc_message_macros.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/WebKit/public/web/WebDragOperation.h"
#include "ui/gfx/point.h"
#include "ui/gfx/vector2d.h"

#define IPC_MESSAGE_START DragMsgStart

// Messages sent from the browser to the renderer.

IPC_MESSAGE_ROUTED5(DragMsg_TargetDragEnter,
                    content::DropData /* drop_data */,
                    gfx::Point /* client_pt */,
                    gfx::Point /* screen_pt */,
                    blink::WebDragOperationsMask /* ops_allowed */,
                    int /* key_modifiers */)

IPC_MESSAGE_ROUTED4(DragMsg_TargetDragOver,
                    gfx::Point /* client_pt */,
                    gfx::Point /* screen_pt */,
                    blink::WebDragOperationsMask /* ops_allowed */,
                    int /* key_modifiers */)

IPC_MESSAGE_ROUTED0(DragMsg_TargetDragLeave)

IPC_MESSAGE_ROUTED3(DragMsg_TargetDrop,
                    gfx::Point /* client_pt */,
                    gfx::Point /* screen_pt */,
                    int /* key_modifiers */)

// Notifies the renderer when and where the mouse-drag ended.
IPC_MESSAGE_ROUTED3(DragMsg_SourceEnded,
                    gfx::Point /* client_pt */,
                    gfx::Point /* screen_pt */,
                    blink::WebDragOperation /* drag_operation */)

// Notifies the renderer that the system DoDragDrop call has ended.
IPC_MESSAGE_ROUTED0(DragMsg_SourceSystemDragEnded)

// Messages sent from the renderer to the browser.

// Used to tell the parent the user started dragging in the content area. The
// DropData struct contains contextual information about the pieces of the
// page the user dragged. The parent uses this notification to initiate a
// drag session at the OS level.
IPC_MESSAGE_ROUTED5(DragHostMsg_StartDragging,
                    content::DropData /* drop_data */,
                    blink::WebDragOperationsMask /* ops_allowed */,
                    SkBitmap /* image */,
                    gfx::Vector2d /* image_offset */,
                    content::DragEventSourceInfo /* event_info */)

// The page wants to update the mouse cursor during a drag & drop operation.
// |is_drop_target| is true if the mouse is over a valid drop target.
IPC_MESSAGE_ROUTED1(DragHostMsg_UpdateDragCursor,
                    blink::WebDragOperation /* drag_operation */)

// Notifies the host that the renderer finished a drop operation.
IPC_MESSAGE_ROUTED0(DragHostMsg_TargetDrop_ACK)


text:
<?php

namespace TypiCMS\Modules\Files\Http\Requests;

use TypiCMS\Modules\Core\Http\Requests\AbstractFormRequest;

class FormRequest extends AbstractFormRequest
{
    public function rules()
    {
        $rules = [
            '*.alt_attribute' => 'max:255',
        ];
        if ($this->hasFile('file')) {
            $rules['file'] = 'mimes:jpeg,gif,png,bmp,tiff,pdf,eps,rtf,txt,md,doc,xls,ppt,docx,xlsx,ppsx,pptx,sldx|max:'.config('typicms.max_file_upload_size', 2000);
        }

        return $rules;
    }
}


text:
package org.auraframework.impl.clientlibrary;

import java.io.IOException;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.auraframework.builder.ClientLibraryDefBuilder;
import org.auraframework.def.ClientLibraryDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.RootDefinition;
import org.auraframework.impl.system.DefinitionImpl;
import org.auraframework.system.AuraContext;
import org.auraframework.throwable.quickfix.InvalidDefinitionException;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.util.json.Json;

/**
 * Client Library Definition: Specifies name, url, type, and modes of client library
 */
public final class ClientLibraryDefImpl extends DefinitionImpl<ClientLibraryDef> implements ClientLibraryDef {

    private static final long serialVersionUID = -1342087284192933971L;
    private final DefDescriptor<? extends RootDefinition> parentDescriptor;
    private final String name;
    private final Type type;
    private final Set<AuraContext.Mode> modes;
    private final int myHashCode;

    protected ClientLibraryDefImpl(Builder builder) {
        super(builder);
        this.parentDescriptor = builder.parentDescriptor;
        this.type = builder.type;
        this.name = builder.name;
        this.modes = builder.modes;

        int val = 0;

        if (name != null) {
            val += name.hashCode();
        }
        if (modes != null) {
            for (AuraContext.Mode mode : modes) {
                val += mode.hashCode();
            }
        }
        this.myHashCode = val;
    }

    @Override
    public DefDescriptor<? extends RootDefinition> getParentDescriptor() {
        return this.parentDescriptor;
    }

    /**
     * Client library must have name, type, and parent descriptor.
     *
     * @throws QuickFixException quick fix
     */
    @Override
    public void validateDefinition() throws QuickFixException {
        if (StringUtils.isBlank(this.name)) {
            throw new InvalidDefinitionException("Must have a name", getLocation());
        }
        if (this.type == null) {
            throw new InvalidDefinitionException("Missing required type", getLocation());
        }
        if (this.parentDescriptor == null) {
            throw new InvalidDefinitionException("No parent for ClientLibraryDef", getLocation());
        }
    }

    @Override
    public void validateReferences() throws QuickFixException {
        super.validateReferences();
    }

    @Override
    public Type getType() {
        return this.type;
    }

    @Override
    public String getLibraryName() {
        return this.name;
    }

    @Override
    public Set<AuraContext.Mode> getModes() {
        return this.modes;
    }

    @Override
    public void serialize(Json json) throws IOException {
    }

    /**
     * Determines whether client library should be included based on mode and type
     *
     * @param mode aura mode
     * @param type CSS or JS
     * @return true if should be included
     */
    @Override
    public boolean shouldInclude(AuraContext.Mode mode, Type type) {
        return this.type == type && shouldInclude(mode);
    }

    /**
     * Determines whether client library should be included based on mode
     *
     * @param mode aura mode
     * @return true if should be included
     */
    @Override
    public boolean shouldInclude(AuraContext.Mode mode) {
        return (this.modes == null || (this.modes != null && (this.modes.isEmpty() || this.modes.contains(mode))));
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("type: ").append(this.type).append(", name: ").append(this.name);
        return sb.toString();
    }

    @Override
    public boolean equalsIgnoreModes(ClientLibraryDef c) {
        return c.getLibraryName().equals(this.getLibraryName()) && c.getType() == this.getType();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof ClientLibraryDef) {
            ClientLibraryDef c = (ClientLibraryDef) obj;

            // equals if (same name and no url) or (same url and not blank url) and same type and same modes
            return  equalsIgnoreModes(c) && (this.getModes().isEmpty() ||
                    this.getModes().containsAll(c.getModes()));

        }
        return false;
    }

    @Override
    public int hashCode() {
        return myHashCode;
    }

    public static class Builder extends DefinitionImpl.BuilderImpl<ClientLibraryDef>
            implements ClientLibraryDefBuilder {

        private DefDescriptor<? extends RootDefinition> parentDescriptor;
        private String name;
        private Type type;
        private Set<AuraContext.Mode> modes;

        public Builder() {
            super(ClientLibraryDef.class);
        }

        @Override
        public ClientLibraryDefBuilder setParentDescriptor(DefDescriptor<? extends RootDefinition> parentDescriptor) {
            this.parentDescriptor = parentDescriptor;
            return this;
        }

        @Override
        public ClientLibraryDefBuilder setName(String name) {
            this.name = name;
            return this;
        }

        @Override
        public ClientLibraryDefBuilder setType(Type type) {
            this.type = type;
            return this;
        }

        @Override
        public ClientLibraryDefBuilder setModes(Set<AuraContext.Mode> modes) {
            this.modes = modes;
            return this;
        }

        @Override
        public ClientLibraryDef build() {
            return new ClientLibraryDefImpl(this);
        }
    }
}


text:
Ads::Banner.create name: 'big_one', width: 600, height: 200
Ads::Banner.create name: 'small_one', width: 250, height: 120


text: I announce the fact that the current cell value of a tape has changed.


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Mercy Benzaquen</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
      <link href="https://fonts.googleapis.com/css?family=Bungee+Inline" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>

Back to all projects

            <button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas">Toggle nav</button>

 BECOME YUUUUGE IN 5 YEARS

 How to break the Intenet Donad-Trump-style (Yuuugeness measured in Google searches)


text:
using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using AspNet.Security.OAuth.Validation;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using HiddenSound.API.Configuration;
using HiddenSound.API.Identity;
using HiddenSound.API.Swagger;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.EntityFrameworkCore;
using Swashbuckle.AspNetCore.Swagger;
using AspNet.Security.OpenIdConnect.Primitives;
using HiddenSound.API.OpenIddict;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;

namespace HiddenSound.API
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
#pragma warning disable 618
                builder.AddUserSecrets();
#pragma warning restore 618
            }

            Configuration = builder.Build();
            CurrentEnvironment = env;
        }

        public IContainer ApplicationContainer { get; private set; }

        public IConfigurationRoot Configuration { get; }

        private IHostingEnvironment CurrentEnvironment { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<SendGridConfig>(Configuration.GetSection("ThirdParty:SendGrid"));
            services.Configure<AppSettingsConfig>(Configuration.GetSection("AppSettings"));
            services.Configure<DatabaseSeedConfig>(Configuration.GetSection("DatabaseSeed"));

            var connectionString = Configuration.GetConnectionString("HiddenSoundDatabase");
            services.AddDbContext<HiddenSoundDbContext>(options =>
            {
                options.UseSqlServer(connectionString);

                options.UseOpenIddict<HSOpenIddictApplication, HSOpenIddictAuthorization, HSOpenIddictScope, HSOpenIddictToken, Guid>();
            });

            services.AddMemoryCache();
            services.AddOptions();

            services.AddSignalR(options =>
            {
                options.Hubs.EnableDetailedErrors = true;
            });

            services.AddCors(options =>
            {
                options.AddPolicy("AnyOrigin", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
                options.AddPolicy("Application", p => p.WithOrigins(Configuration["AppSettings:WebUri"], Configuration["AppSettings:ApiUri"]).AllowAnyMethod().AllowAnyHeader());
            });

            services.AddIdentity<HiddenSoundUser, HiddenSoundRole>(options =>
                {
                    options.Password.RequireDigit = true;
                    options.Password.RequireLowercase = true;
                    options.Password.RequireNonAlphanumeric = true;
                    options.Password.RequireUppercase = true;
                    options.Password.RequiredLength = 6;

                    options.SignIn.RequireConfirmedEmail = true;
                })
                .AddEntityFrameworkStores<HiddenSoundDbContext, Guid>()
                .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            });

            services.AddOpenIddict<HSOpenIddictApplication, HSOpenIddictAuthorization, HSOpenIddictScope, HSOpenIddictToken>()
                .AddEntityFrameworkCoreStores<HiddenSoundDbContext>()
                .AddMvcBinders()
                .EnableAuthorizationEndpoint("/OAuth/Authorize")
                .EnableTokenEndpoint($"/{OAuthConstants.ControllerRoute}/{OAuthConstants.TokenRoute}")
                .EnableLogoutEndpoint("/OAuth/Logout")
                .EnableUserinfoEndpoint($"/{OAuthConstants.ControllerRoute}/{OAuthConstants.UserInfoRoute}")
                .AllowAuthorizationCodeFlow()
                .AllowPasswordFlow()
                .AllowRefreshTokenFlow()
                .EnableRequestCaching()

                .DisableHttpsRequirement();

            services.AddAuthorization(c =>
            {
                c.AddPolicy("Application", b => b.RequireClaim("application"));
                c.AddPolicy("Api", b => b.RequireClaim("api"));
            });

            services.AddMvc(options =>
                {

                })
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "HiddenSound API", Version = "v1" });

                c.OperationFilter<ReplaceTagOperationFilter>();

                if (CurrentEnvironment.IsProduction())
                {
                    c.DocumentFilter<HideOperationFilter>();
                }

                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "password",
                    TokenUrl = $"{Configuration["AppSettings:ApiUri"]}/{OAuthConstants.ControllerRoute}/{OAuthConstants.TokenRoute}"
                });
            });

            services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());

            var builder = new ContainerBuilder();
            var manager = new ApplicationPartManager();

            manager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).GetTypeInfo().Assembly));
            manager.FeatureProviders.Add(new ControllerFeatureProvider());

            var feature = new ControllerFeature();
            manager.PopulateFeature(feature);

            builder.RegisterType<ApplicationPartManager>().AsSelf().SingleInstance(); // not sure if actually needed any more
            builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired();

            builder.RegisterModule<Module>();

            builder.Populate(services);

            ApplicationContainer = builder.Build();

            return ApplicationContainer.Resolve<IServiceProvider>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
            IApplicationLifetime appLifetime)
        {
            var sslPort = 0;

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (!env.IsProduction())
            {
                app.UseDeveloperExceptionPage();
            }

            if (env.IsDevelopment())
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile(@"Properties/launchSettings.json", optional: false, reloadOnChange: true);

                var launchConfig = builder.Build();
                sslPort = launchConfig.GetValue<int>("iisSettings:iisExpress:sslPort");
            }

            app.Use(async (ctx, next) =>
            {
                if (ctx.Request.IsHttps)
                {
                    await next();
                }
                else
                {
                    var sslPortStr = sslPort == 0 || sslPort == 443 ? string.Empty : $":{sslPort}";
                    var httpsUrl = $"https://{ctx.Request.Host.Host}{sslPortStr}{ctx.Request.Path}";
                    ctx.Response.Redirect(httpsUrl);
                }
            });

            app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/Application"), branch =>
            {
                branch.UseCors("Application");
            });

            app.UseWhen(ctx => new[] { "/.well-known", "/Api", "/Mobile", "/OAuth" }.Any(p => ctx.Request.Path.StartsWithSegments(p)), branch =>
            {
                branch.UseCors("AnyOrigin");
            });

            app.UseOAuthValidation(options =>
            {
                options.Events = new OAuthValidationEvents
                {
                    OnRetrieveToken = context =>
                    {
                        if (context.Request.Query.ContainsKey("access_token"))
                        {
                            context.Token = context.Request.Query["access_token"];
                        }

                        return Task.FromResult(0);
                    }
                };
            });

            app.UseOpenIddict();

            app.UseSignalR("/Api/Authorization/signalr");

            app.UseMvc(routes =>
            {
                routes.MapRoute("areaRoute", "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "HiddenSound v1");
                c.DocExpansion("none");
            });

            appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());

            app.ApplicationServices.GetService<HiddenSoundDbContext>().EnsureSeedData(app.ApplicationServices, CancellationToken.None).GetAwaiter().GetResult();
        }
    }
}


text:
module.exports = (error, code, args) => {
  if (error.status) {
    this.statusCode = error.response.res.statusCode;
    this.statusMessage = error.response.res.statusMessage;
    this.code = error.response.body.code;
    this.message = error.response.body.message;
    return this;
  }
  this.code = code || null;
  if (this.code === 1) this.args = args;
  this.message = error;
  this.stack = error.stack || null;
  return this;
};


text:
from django.core.urlresolvers import reverse
from django.test import TestCase

from model_mommy import mommy

from .. import models

class GroupViewMixin(object):
    """Mixin for testing group related views."""

    url_name = ''

    def setUp(self):
        self.group = mommy.make('TenantGroup')
        self.user = mommy.make('User')
        self.user.set_password('test')
        self.user.save()
        self.client.login(username=self.user.username, password='test')
        super(GroupViewMixin, self).setUp()

    def url(self, **kwargs):
        return reverse(self.url_name, kwargs=kwargs)

class TenantViewMixin(GroupViewMixin):
    """Extension to handle tenant related views."""

    def setUp(self):
        super(TenantViewMixin, self).setUp()
        self.tenant = mommy.make('Tenant', group=self.group)

class GroupLandingViewTestCase(GroupViewMixin, TestCase):
    """Selection page for users with multiple groups."""

    url_name = 'group-landing'

    def assertGroupsEqual(self, response, expected):
        """Assert groups in the response context."""
        self.assertEqual(response.status_code, 200)
        expected = sorted(expected, key=lambda x: x.pk)
        found = sorted(response.context['groups'], key=lambda x: x.pk)
        self.assertEqual(found, expected)

    def test_get_page(self):
        """Users with multiple groups can get the page to pick an group."""
        mommy.make('TenantRole',
                   group=self.group, user=self.user,
                   role=models.TenantRole.ROLE_GROUP_MANAGER)
        other = mommy.make('TenantGroup')
        mommy.make('TenantRole',
                   group=other, user=self.user,
                   role=models.TenantRole.ROLE_GROUP_MANAGER)
        # Create group with no relation to the user
        mommy.make('TenantGroup')
        with self.assertTemplateUsed('multitenancy/group-landing.html'):
            response = self.client.get(self.url())
            self.assertGroupsEqual(response, [self.group, other])

    def test_superuser_get_page(self):
        """Super users will see all groups."""
        self.user.is_staff = True
        self.user.is_superuser = True
        self.user.save(update_fields=('is_staff', 'is_superuser'))
        other = mommy.make('TenantGroup')
        with self.assertTemplateUsed('multitenancy/group-landing.html'):
            response = self.client.get(self.url())
            self.assertGroupsEqual(response, [self.group, other])

    def test_inactive_user_get_page(self):
        """Inactive users will see no groups."""
        self.user.is_active = False
        self.user.save(update_fields=('is_active', ))
        with self.assertTemplateUsed('multitenancy/group-landing.html'):
            response = self.client.get(self.url())
            self.assertGroupsEqual(response, [])
            self.assertContains(response, 'do not have permissions to manage any groups')

    def test_single_group_get_page(self):
        """Redirect user to group if there is only one."""
        mommy.make('TenantRole',
                   group=self.group, user=self.user,
                   role=models.TenantRole.ROLE_GROUP_MANAGER)
        response = self.client.get(self.url())
        self.assertRedirects(response, self.group.get_absolute_url())

    def test_mixed_roles_get_page(self):
        """Users with roles on two groups need to select groups."""
        mommy.make('TenantRole',
                   group=self.group, user=self.user,
                   role=models.TenantRole.ROLE_GROUP_MANAGER)
        other = mommy.make('TenantGroup')
        other_tenant = mommy.make('Tenant', group=other)
        mommy.make('TenantRole',
                   group=other, tenant=other_tenant, user=self.user,
                   role=models.TenantRole.ROLE_TENANT_MANAGER)
        with self.assertTemplateUsed('multitenancy/group-landing.html'):
            response = self.client.get(self.url())
            self.assertGroupsEqual(response, [self.group, other])

    def test_no_groups_get_page(self):
        """Users with no groups will be shown an error message."""
        with self.assertTemplateUsed('multitenancy/group-landing.html'):
            response = self.client.get(self.url())
            self.assertContains(response, 'do not have permissions to manage any groups')

class GroupDetailViewTestCase(GroupViewMixin, TestCase):
    """Group detail and tenant listing page."""

    url_name = 'group-detail'

    def assertTenantsEqual(self, response, expected):
        """Assert tenants in the response context."""
        self.assertEqual(response.status_code, 200)
        expected = sorted(expected, key=lambda x: x.pk)
        found = sorted(response.context['tenants'], key=lambda x: x.pk)
        self.assertEqual(found, expected)

    def test_get_page(self):
        """Group managers will see all the tenants for the group."""
        mommy.make('TenantRole',
                   group=self.group, user=self.user,
                   role=models.TenantRole.ROLE_GROUP_MANAGER)
        tenant = mommy.make('Tenant', group=self.group)
        other = mommy.make('Tenant', group=self.group)
        # Create tenant with no relation to the user
        mommy.make('Tenant')
        with self.assertTemplateUsed('multitenancy/group-detail.html'):
            response = self.client.get(self.url(group_slug=self.group.slug))
            self.assertTenantsEqual(response, [tenant, other])

    def test_no_group_permission(self):
        """This page with 404 if the user is not associated with the group."""
        response = self.client.get(self.url(group_slug=self.group.slug))
        self.assertEqual(response.status_code, 404)

    def test_superuser_get_page(self):
        """Super users will see all tenants for the group."""
        self.user.is_staff = True
        self.user.is_superuser = True
        self.user.save(update_fields=('is_staff', 'is_superuser'))
        tenant = mommy.make('Tenant', group=self.group)
        other = mommy.make('Tenant', group=self.group)
        with self.assertTemplateUsed('multitenancy/group-detail.html'):
            response = self.client.get(self.url(group_slug=self.group.slug))
            self.assertTenantsEqual(response, [tenant, other])

    def test_tenant_manager_single(self):
        """A user managing a single tenant will be directed to the tenant page."""
        tenant = mommy.make('Tenant', group=self.group)
        mommy.make('TenantRole',
                   group=self.group, tenant=tenant, user=self.user,
                   role=models.TenantRole.ROLE_TENANT_MANAGER)
        response = self.client.get(self.url(group_slug=self.group.slug))
        self.assertRedirects(response, tenant.get_absolute_url())

    def test_tenant_manager_multiple(self):
        """A user managing a multiples tenants will see their tenants."""
        tenant = mommy.make('Tenant', group=self.group)
        other = mommy.make('Tenant', group=self.group)
        mommy.make('TenantRole',
                   group=self.group, tenant=tenant, user=self.user,
                   role=models.TenantRole.ROLE_TENANT_MANAGER)
        mommy.make('TenantRole',
                   group=self.group, tenant=other, user=self.user,
                   role=models.TenantRole.ROLE_TENANT_MANAGER)
        with self.assertTemplateUsed('multitenancy/group-detail.html'):
            response = self.client.get(self.url(group_slug=self.group.slug))
            self.assertTenantsEqual(response, [tenant, other])

class TenantDetailViewTestCase(TenantViewMixin, TestCase):
    """Tenant detail page."""

    url_name = 'tenant-detail'

    def test_tenant_manager_get_page(self):
        """Tenant managers will use this page to manage their tenants."""
        mommy.make('TenantRole',
                   group=self.group, tenant=self.tenant, user=self.user,
                   role=models.TenantRole.ROLE_TENANT_MANAGER)
        with self.assertTemplateUsed('multitenancy/tenant-detail.html'):
            response = self.client.get(self.url(group_slug=self.group.slug, tenant_slug=self.tenant.slug))
            self.assertEqual(response.status_code, 200)

    def test_group_manager_get_page(self):
        """Group managers also have access to their tenant pages."""
        mommy.make('TenantRole',
                   group=self.group, user=self.user,
                   role=models.TenantRole.ROLE_GROUP_MANAGER)
        with self.assertTemplateUsed('multitenancy/tenant-detail.html'):
            response = self.client.get(self.url(group_slug=self.group.slug, tenant_slug=self.tenant.slug))
            self.assertEqual(response.status_code, 200)

    def test_superuser_get_page(self):
        """Super users have access to all tenant pages."""
        self.user.is_staff = True
        self.user.is_superuser = True
        self.user.save(update_fields=('is_staff', 'is_superuser'))
        with self.assertTemplateUsed('multitenancy/tenant-detail.html'):
            response = self.client.get(self.url(group_slug=self.group.slug, tenant_slug=self.tenant.slug))
            self.assertEqual(response.status_code, 200)

    def test_wrong_group(self):
        """Users which don't have access to the group will see a 404."""
        mommy.make('TenantRole',
                   user=self.user,
                   role=models.TenantRole.ROLE_GROUP_MANAGER)
        response = self.client.get(self.url(group_slug=self.group.slug, tenant_slug=self.tenant.slug))
        self.assertEqual(response.status_code, 404)

    def test_wrong_tenant(self):
        """Users which don't have access to the tenant will see a 404."""
        other = mommy.make('Tenant', group=self.group)
        mommy.make('TenantRole',
                   group=self.group, tenant=other, user=self.user,
                   role=models.TenantRole.ROLE_TENANT_MANAGER)
        response = self.client.get(self.url(group_slug=self.group.slug, tenant_slug=self.tenant.slug))
        self.assertEqual(response.status_code, 404)


text:
#ifndef PHP_CAIRO_PATTERN_SURFACE_DEF
#define PHP_CAIRO_PATTERN_SURFACE_DEF

#include <cairo.h>
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "zend.h"
#include "zend_API.h"
#include "../commons/hub.h"
#include "exception.h"
#include "pattern.h"
#include "surface.h"

ZEND_BEGIN_ARG_INFO_EX(arginfo_pc_pattern_surface_construct, 0, 0, 1)
	ZEND_ARG_OBJ_INFO(0, x, PGGI\\Cairo\\Surface, 0)
ZEND_END_ARG_INFO()

#define PATTERN_SURFACE_SURFACE "surface"

/*****************************/
/* Class information getters */
/*****************************/

/*==========================================================================*/
/**
 * get the class entry
 */
zend_class_entry * pc_pattern_surface_get_class_entry(void);

/*==========================================================================*/
/**
 * get the object handler
 */
zend_object_handlers * pc_pattern_surface_get_object_handlers();

/***************/
/* PHP Methods */
/***************/

#define PATTERN_SURFACE_METHOD(name) \
PHP_METHOD(PatternSurface, name)

/* PatternSurface Functions */

/************************/
/* Class Initialization */
/************************/

/*==========================================================================*/
/**
 * init the class
 */
void pc_pattern_surface_init(int module_number);

#endif


text:
#ifndef _BRIDGE_SERVER_H_
#define _BRIDGE_SERVER_H_

#include <Bridge.h>
#include <Server.h>

class BridgeClient;

class BridgeServer : public Server {
  public:
    // Constructor with a user provided BridgeClass instance
    BridgeServer(uint16_t port = 5555, BridgeClass &_b = Bridge);

    void begin();
    BridgeClient accept();

    virtual size_t write(uint8_t c);

    void listenOnLocalhost()   {
      useLocalhost = true;
    }
    void noListenOnLocalhost() {
      useLocalhost = false;
    }

  private:
    BridgeClass &bridge;
    uint16_t port;
    bool listening;
    bool useLocalhost;
};

#endif // _BRIDGE_SERVER_H_


text:
package com.github.j5ik2o.forseti.domain.client

import scala.concurrent.{ExecutionContext, Future}
import scalaz.EitherT

trait ClientWriter {

  def store(entity: Client)(implicit ec: ExecutionContext): EitherT[Future, Exception, Unit]

  def deleteById(id: ClientId)(implicit ec: ExecutionContext): EitherT[Future, Exception, Unit]

  def deleteByKey(key: String)(implicit ec: ExecutionContext): EitherT[Future, Exception, Unit]

}


text:
function d = squared_chi(P, Q)
%DISTS.SQUARE_CHI   Squared Chi-Squared distance between two time series
%   SQUARE_CHI(S,Z) returns the Squared Chi-Squared distance between time
%   series S and Z.
%
%   The Squared Chi-Squared distance is a symmetrical variant of the
%   Pearsons's chi-squared test statistics. When used to test the distance
%   between time series, it is best if the series are normalized to the
%   interval [0,1] rather than being z-normalized.
%
%   The distance between observations P(t) and Q(t) is normalized by the
%   magnitude of P(t) and Q(t); when P(t) + Q(t) == 0, the distance between
%   P(t) and Q(t) is given by the difference between the terms. In other
%   words, if p and q are observations of P and Q at instance t, then
%
%       dist(p, q) = { (p - q)^2 / (p + q),  if p + q ~= 0
%                    { (p - q)^2,            otherwise
%
%   Disclaimer: this function is based on the work of Sung-Hyuk Cha.
%   "Comprehensive Survey on Distance/Similarity Measures between
%   Probability Density Functions". In: International Journal of
%   Mathematical Models and Methods in Applied Sciences. Issue 4, Volume 1,
%   pp 300-307 (2007).

%   This file is part of TimeBox. Copyright 2015-16 Rafael Giusti
%   Revision 1.0.0
PQsum = P + Q;
PQsum(PQsum == 0) = 1;
d = sum(((P - Q).^ 2) ./ PQsum);
end


text:
using System.Collections.Generic;
using System.Web.Mvc;
using TwitterBootstrapMVC.Controls;

namespace TwitterBootstrapMVC.ControlModels
{
    public class BootstrapRadioButtonTrueFalseModel
    {
        public BootstrapRadioButtonTrueFalseModel()
        {
            inputTrueValue = true;
            inputFalseValue = false;
            labelTrueText = "Yes";
            labelFalseText = "No";
            htmlAttributesInputTrue = new Dictionary<string, object>();
            htmlAttributesInputFalse = new Dictionary<string, object>();
            htmlAttributesLabelTrue = new Dictionary<string, object>();
            htmlAttributesLabelFalse = new Dictionary<string, object>();
        }

        public string htmlFieldName;
        public object inputTrueValue;
        public object inputFalseValue;
        public string labelTrueText;
        public string labelFalseText;
        public bool? selectedValue;
        public IDictionary<string, object> htmlAttributesInputTrue;
        public IDictionary<string, object> htmlAttributesInputFalse;
        public IDictionary<string, object> htmlAttributesLabelTrue;
        public IDictionary<string, object> htmlAttributesLabelFalse;
        public bool displayValidationMessage;
        public HelpTextStyle validationMessageStyle;
        public ModelMetadata metadata;
        public TooltipConfiguration tooltipConfiguration;
        public Tooltip tooltip;
        public BootstrapHelpText helpText;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button_write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Write"/>

    <Button
        android:id="@+id/button_smoketest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Smoke Test"/>

    <Button
        android:id="@+id/button_delete_all"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete All"/>

</LinearLayout>


text:
require File.join(File.dirname(__FILE__), "..", "..", "spec_helper")
require File.join(File.dirname(__FILE__), "controllers", "sessions")

# The Merb::Session module gets mixed into Merb::SessionContainer to allow
# app-level functionality (usually found in app/models/merb/session.rb)
module Merb
  module Session

    def awesome?
      self[:foo] == 'awesome'
    end

  end
end

describe "All session-store backends", :shared => true do

  it "should be instanciated using the 'generate' method" do
    @session_class.generate.should be_kind_of(@session_class)
  end

  it "should store the session_id" do
    @session.session_id.should match(/^[0-9a-f]{32}$/)
  end

  it "should have bracket accessors for setting data" do
    @session.should respond_to(:[]=)
    @session.should respond_to(:[])
    @session[:foo] = 'bar'
    @session[:foo].should == 'bar'
  end

end

describe "All session-stores mixed into Merb::Controller", :shared => true do

  before(:all) { @controller_klass = Merb::Test::Fixtures::Controllers::SessionsController }

  it "should represent the controller session" do
    with_cookies(@controller_klass) do
      controller = dispatch_to(@controller_klass, :index)
      controller.request.session.should be_kind_of(@session_class)
    end
  end

  it "should store session data" do
    session_store_type = @session_class.session_store_type.to_s
    with_cookies(@controller_klass) do
      controller = dispatch_to(@controller_klass, :index, :foo => session_store_type)
      controller.request.session[:foo].should == session_store_type
      cookie_header = controller.headers["Set-Cookie"].first
      cookie_header.should_not match(/expires/) # sessions expire when browser quits
    end
  end

  it "should retrieve session data" do
    session_store_type = @session_class.session_store_type.to_s
    with_cookies(@controller_klass) do
      controller = dispatch_to(@controller_klass, :index, :foo => session_store_type)
      controller = dispatch_to(@controller_klass, :retrieve)
      controller.request.session[:foo].should == session_store_type
    end
  end

  it "should allow regeneration of the session" do
    session_store_type = @session_class.session_store_type.to_s
    with_cookies(@controller_klass) do
      controller = dispatch_to(@controller_klass, :index, :foo => session_store_type)
      controller = dispatch_to(@controller_klass, :regenerate)
      controller = dispatch_to(@controller_klass, :retrieve)
      controller.request.session[:foo].should == session_store_type
    end
  end

  it "should allow the session to be destroyed" do
    session_store_type = @session_class.session_store_type.to_s
    with_cookies(@controller_klass) do
      controller = dispatch_to(@controller_klass, :index, :foo => session_store_type)
      controller = dispatch_to(@controller_klass, :retrieve)
      controller.request.session[:foo].should == session_store_type

      controller = dispatch_to(@controller_klass, :destroy)
      controller.request.session.should be_empty
      cookie_header = controller.headers["Set-Cookie"].first
      cookie_header.should match(/_session_id=;/)
      cookie_header.should match(/01-Jan-1970/)
    end
  end

  it "should not set the Set-Cookie header when the session(_id) didn't change" do
    session_store_type = @session_class.session_store_type.to_s
    with_cookies(@controller_klass) do
      controller = dispatch_to(@controller_klass, :index, :foo => session_store_type)
      controller.headers["Set-Cookie"].should_not be_blank
      controller = dispatch_to(@controller_klass, :retrieve)
      controller.headers["Set-Cookie"].should be_blank
    end
  end

  it "should have mixed in Merb::Session methods" do
    with_cookies(@controller_klass) do
      controller = dispatch_to(@controller_klass, :index, :foo => 'awesome')
      controller.request.session.should respond_to(:awesome?)
      controller.request.session.should be_awesome
    end
  end

end


text:
module.exports = function (config) {
  'use strict';

  config.set({
    // list of files / patterns to load in the browser
    files: [
      'node_modules/lodash/dist/lodash.js',
      'lib/index.js',
      'test/*.js'
    ],

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: [
      'mocha',
      'chai'
    ],

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: [
      'progress'
    ],

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
      'PhantomJS',
      'Chrome',
      'Firefox',
      'Safari',
      'IE'
    ],

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    sauceLabs: {
      testName: 'Storage',
      build: process.env.TRAVIS_JOB_ID,
      recordScreenshots: false
    },

    customLaunchers: {
      sauce_chrome: {
        base: 'SauceLabs',
        browserName: 'chrome',
        platform: 'Windows 7'
      },
      sauce_chrome_linux: {
        base: 'SauceLabs',
        browserName: 'chrome'
      },
      sauce_firefox: {
        base: 'SauceLabs',
        browserName: 'firefox',
        platform: 'Windows 7'
      },
      sauce_firefox_linux: {
        base: 'SauceLabs',
        browserName: 'firefox'
      },
      sauce_safari: {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'OS X 10.9'
      },
      sauce_ie_8: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows XP',
        version: '8'
      },
      sauce_ie_9: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '9'
      },
      sauce_ie_10: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '10'
      },
      sauce_ie_11: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
      }
    }
  });
};


text:
from __future__ import unicode_literals
"""build query for doclistview and return results"""

import frappe, json
import frappe.permissions
from frappe.model.db_query import DatabaseQuery
from frappe import _

@frappe.whitelist()
def get():
	return compress(execute(**get_form_params()))

def execute(doctype, *args, **kwargs):
	return DatabaseQuery(doctype).execute(*args, **kwargs)

def get_form_params():
	"""Stringify GET request parameters."""
	data = frappe._dict(frappe.local.form_dict)

	del data["cmd"]

	if isinstance(data.get("filters"), basestring):
		data["filters"] = json.loads(data["filters"])
	if isinstance(data.get("fields"), basestring):
		data["fields"] = json.loads(data["fields"])
	if isinstance(data.get("docstatus"), basestring):
		data["docstatus"] = json.loads(data["docstatus"])

	# queries must always be server side
	data.query = None

	return data

def compress(data):
	"""separate keys and values"""
	if not data: return data
	values = []
	keys = data[0].keys()
	for row in data:
		new_row = []
		for key in keys:
			new_row.append(row[key])
		values.append(new_row)

	return {
		"keys": keys,
		"values": values
	}

@frappe.whitelist()
def save_report():
	"""save report"""

	data = frappe.local.form_dict
	if frappe.db.exists('Report', data['name']):
		d = frappe.get_doc('Report', data['name'])
	else:
		d = frappe.new_doc('Report')
		d.report_name = data['name']
		d.ref_doctype = data['doctype']

	d.report_type = "Report Builder"
	d.json = data['json']
	frappe.get_doc(d).save()
	frappe.msgprint(_("{0} is saved").format(d.name))
	return d.name

@frappe.whitelist()
def export_query():
	"""export from report builder"""
	form_params = get_form_params()
	form_params["limit_page_length"] = None
	form_params["as_list"] = True
	doctype = form_params.doctype
	del form_params["doctype"]

	frappe.permissions.can_export(doctype, raise_exception=True)

	db_query = DatabaseQuery(doctype)
	ret = db_query.execute(**form_params)

	data = [['Sr'] + get_labels(db_query.fields, doctype)]
	for i, row in enumerate(ret):
		data.append([i+1] + list(row))

	# convert to csv
	from cStringIO import StringIO
	import csv

	f = StringIO()
	writer = csv.writer(f)
	for r in data:
		# encode only unicode type strings and not int, floats etc.
		writer.writerow(map(lambda v: isinstance(v, unicode) and v.encode('utf-8') or v, r))

	f.seek(0)
	frappe.response['result'] = unicode(f.read(), 'utf-8')
	frappe.response['type'] = 'csv'
	frappe.response['doctype'] = doctype

def get_labels(fields, doctype):
	"""get column labels based on column names"""
	labels = []
	for key in fields:
		key = key.split(" as ")[0]

		if "." in key:
			parenttype, fieldname = key.split(".")[0][4:-1], key.split(".")[1].strip("`")
		else:
			parenttype = doctype
			fieldname = fieldname.strip("`")

		df = frappe.get_meta(parenttype).get_field(fieldname)
		label = df.label if df else fieldname.title()
		if label in labels:
			label = doctype + ": " + label
		labels.append(label)

	return labels

@frappe.whitelist()
def delete_items():
	"""delete selected items"""
	import json

	il = json.loads(frappe.form_dict.get('items'))
	doctype = frappe.form_dict.get('doctype')

	for d in il:
		frappe.delete_doc(doctype, d)

@frappe.whitelist()
def get_tag_catagories(doctype):
	cat_tags = frappe.db.sql("""select tag.parent as category, tag.tag_name as tag
		from `tabTag Doc Category` as docCat
		INNER JOIN  tabTag as tag on tag.parent = docCat.parent
		where docCat.tagdoc=%s
		ORDER BY tag.parent asc,tag.idx""",doctype,as_dict=1)

	return cat_tags

@frappe.whitelist()
def get_stats(stats, doctype,filters=[]):
	"""get tag info"""
	import json
	tags = json.loads(stats)
	if filters:
		filters = json.loads(filters)
	stats = {}

	columns = frappe.db.get_table_columns(doctype)
	for tag in tags:
		if not tag in columns: continue
		tagcount = execute(doctype, fields=[tag, "count(*)"],
			#filters=["ifnull(`%s`,'')!=''" % tag], group_by=tag, as_list=True)
			filters = filters + ["ifnull(`%s`,'')!=''" % tag], group_by = tag, as_list = True)

		if tag=='_user_tags':
			stats[tag] = scrub_user_tags(tagcount)
			stats[tag].append(["No Tags",execute(doctype, fields=[tag, "count(*)"], filters=filters +["({0} = ',' or {0} is null)".format(tag)],  as_list=True)[0][1]])
		else:
			stats[tag] = tagcount

	return stats

@frappe.whitelist()
def get_dash(stats, doctype,filters=[]):
	"""get tag info"""
	import json
	tags = json.loads(stats)
	if filters:
		filters = json.loads(filters)
	stats = {}

	columns = frappe.db.get_table_columns(doctype)
	for tag in tags:
		if not tag["name"] in columns: continue
		tagcount = []
		if tag["type"] not in ['Date', 'Datetime']:
			tagcount = execute(doctype, fields=[tag["name"], "count(*)"],
				filters = filters + ["ifnull(`%s`,'')!=''" % tag["name"]], group_by = tag["name"], as_list = True)

		if tag["type"] not in ['Check','Select','Date','Datetime']:
			stats[tag["name"]] = list(tagcount)
			if stats[tag["name"]]:
				data =["No Data",execute(doctype, fields=[tag["name"], "count(*)"], filters=filters + ["({0} = '' or {0} is null)".format(tag["name"])],  as_list=True)[0][1]]
				if data and data[1]!=0:

					stats[tag["name"]].append(data)
		else:
			stats[tag["name"]] = tagcount

	return stats

def scrub_user_tags(tagcount):
	"""rebuild tag list for tags"""
	rdict = {}
	tagdict = dict(tagcount)
	for t in tagdict:
		if not t:
			continue
		alltags = t.split(',')
		for tag in alltags:
			if tag:
				if not tag in rdict:
					rdict[tag] = 0

				rdict[tag] += tagdict[t]

	rlist = []
	for tag in rdict:
		rlist.append([tag, rdict[tag]])

	return rlist

# used in building query in queries.py
def get_match_cond(doctype):
	cond = DatabaseQuery(doctype).build_match_conditions()
	return ((' and ' + cond) if cond else "").replace("%", "%%")

def build_match_conditions(doctype, as_condition=True):
	match_conditions =  DatabaseQuery(doctype).build_match_conditions(as_condition=as_condition)
	if as_condition:
		return match_conditions.replace("%", "%%")
	else:
		return match_conditions


text:
package chapter4.recipe4;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.protocol.http.server.HttpServer;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;

import java.nio.charset.Charset;

public class NettyRxJavaServer {
    public static void main(String... args) throws InterruptedException {
        HttpServer<ByteBuf, ByteBuf> server = RxNetty.createHttpServer(8080,
        		(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) -> {
            System.out.println("Server => Request: " + request.getPath());
            try {
                if ("/error".equals(request.getPath())) {
                    throw new RuntimeException("forced error");
                }
                response.setStatus(HttpResponseStatus.OK);
                response.writeString("Path Requested =>: " + request.getPath() + '\n');
                return response.close();
            } catch (Throwable e) {
                System.err.println("Server => Error [" + request.getPath() + "] => " + e);
                response.setStatus(HttpResponseStatus.BAD_REQUEST);
                response.writeString("Error 500: Bad Request\n");
                return response.close();
            }
        });

        server.start();

        RxNetty.createHttpGet("http://localhost:8080/")
               .flatMap(response -> response.getContent())
               .map(data -> "Client => " + data.toString(Charset.defaultCharset()))
               .toBlocking().forEach(System.out::println);

        RxNetty.createHttpGet("http://localhost:8080/error")
               .flatMap(response -> response.getContent())
               .map(data -> "Client => " + data.toString(Charset.defaultCharset()))
               .toBlocking().forEach(System.out::println);

        RxNetty.createHttpGet("http://localhost:8080/data")
               .flatMap(response -> response.getContent())
               .map(data -> "Client => " + data.toString(Charset.defaultCharset()))
               .toBlocking().forEach(System.out::println);

        Thread.sleep(Integer.MAX_VALUE);

        server.shutdown();
    }
}


text:
using FluentNHibernate.Mapping;
using LNF.Impl.Repository.Data;

namespace LNF.Impl.Mappings.Data
{
    internal class OrgTypeMap : ClassMap<OrgType>
    {
        internal OrgTypeMap()
        {
            Schema("sselData.dbo");
            Id(x => x.OrgTypeID);
            Map(x => x.OrgTypeName, "OrgType");
            References(x => x.ChargeType, "ChargeTypeID");
        }
    }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\IFD0;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class XPosition extends AbstractTag
{

    protected $Id = 286;

    protected $Name = 'XPosition';

    protected $FullName = 'Exif::Main';

    protected $GroupName = 'IFD0';

    protected $g0 = 'EXIF';

    protected $g1 = 'IFD0';

    protected $g2 = 'Image';

    protected $Type = 'rational64u';

    protected $Writable = true;

    protected $Description = 'X Position';

}


text:
all:
	echo Nothing to do...

ctags:
	ctags --recurse --options=ctags.rust --languages=Rust

docs:
	cargo doc
	in-dir ./target/doc fix-perms
	rscp ./target/doc/* gopher:~/www/burntsushi.net/rustdoc/

push:
	git push origin master
	git push github master


text:
namespace qtpacket {

TreeNumbering::TreeNumbering(int branching_factor, int depth,
                             bool mangle_second_row)
    : depth_(depth),
      branching_factor_(branching_factor) {
  // Precompute the number of nodes at each level
  nodes_at_levels_ = new int[depth_ + 1];
  PrecomputeNodesAtLevels();

  // Compute number of nodes in the tree
  num_nodes_ = NodesAtLevels(depth);
  nodes_ = new NodeInfo[num_nodes_];

  // The second row only affects the inorder <-> subindex conversions.
  // We precompute this conversion table here.
  if (mangle_second_row) {
    // Special-case the nasty second row of subindex numbering
    if (depth > 0) {
      nodes_[0].subindex_to_inorder = 0;
      nodes_[0].inorder_to_level = 0;
      if (depth > 1) {
        int num = 1;
        // Inorder traversal of each child of the second row
        for (int i = 0; i < branching_factor; ++i)
          PrecomputeSubindexToInorder(num, 1, 0, 0, &num);
      }
    }
  } else {
    int num = 0;
    PrecomputeSubindexToInorder(0, 0, 0, 0, &num);
  }

  // Reverse the table
  for (int i = 0; i < num_nodes_; ++i)
    nodes_[nodes_[i].subindex_to_inorder].inorder_to_subindex = i;

  PrecomputeInorderToParent();
}

TreeNumbering::~TreeNumbering() {
  delete [] nodes_;
  delete [] nodes_at_levels_;
}

int TreeNumbering::TraversalPathToInorder(const QuadtreePath path) const {
  assert(static_cast<int>(path.Level()) < depth_);

  int index = 0;
  for (std::uint32_t i = 0; i < path.Level(); ++i) {
    assert(path[i] < QuadtreePath::kChildCount);

    index += 1 + path[i] * NodesAtLevels(depth_ - i - 1);
  }
  return index;
}

int TreeNumbering::TraversalPathToSubindex(const QuadtreePath path) const {
  return InorderToSubindex(TraversalPathToInorder(path));
}

QuadtreePath TreeNumbering::InorderToTraversalPath(int inorder) const {
  assert(InRange(inorder));

  // Walk down the tree, subtracting off the size of the child subtree
  // at each step.
  QuadtreePath path;
  int level = 1;
  while (inorder > 0) {
    int nodes_below = NodesAtLevels(depth_ - level);
    int step = (inorder - 1) / nodes_below;
    path = path.Child(step);
    inorder = inorder - step * nodes_below - 1;
    ++level;
  }

  return path;
}

QuadtreePath TreeNumbering::SubindexToTraversalPath(int subindex) const {
  return InorderToTraversalPath(SubindexToInorder(subindex));
}

bool TreeNumbering::GetChildrenSubindex(int subindex, int *indices) const {
  if (!GetChildrenInorder(SubindexToInorder(subindex), indices))
    return false;

  // Convert children to subindex
  for (int i = 0; i < branching_factor_; ++i)
    indices[i] = InorderToSubindex(indices[i]);
  return true;
}

bool TreeNumbering::GetChildrenInorder(int inorder, int *indices) const {
  assert(InRange(inorder));

  // At a leaf node?
  int level = GetLevelInorder(inorder);
  if (level == depth_ - 1)
    return false;

  // First child is inorder + 1.  The others differ by the number of
  // nodes in the subtree rooted at a child.
  int num_nodes_in_subtree = NodesAtLevels(depth_ - level - 1);

  for (int i = 0; i < branching_factor_; ++i)
    indices[i] = inorder + 1 + i * num_nodes_in_subtree;
  return true;
}

int TreeNumbering::GetParentSubindex(int subindex) const {
  int parent = GetParentInorder(SubindexToInorder(subindex));
  if (-1 == parent)
    return parent;

  return InorderToSubindex(parent);
}

int TreeNumbering::GetParentInorder(int inorder) const {
  assert(InRange(inorder));
  return nodes_[inorder].inorder_to_parent;
}

void TreeNumbering::PrecomputeSubindexToInorder(int base,
                                                int level, int offset,
                                                int left_index, int *num) {
  nodes_[base + left_index + offset].subindex_to_inorder = *num;
  nodes_[*num].inorder_to_level = level;
  *num = *num + 1;
  // Descend to children?
  if (level < depth_ - 1) {
    for (int i = 0; i < branching_factor_; ++i)
      PrecomputeSubindexToInorder(base,
                                  level + 1,
                                  offset * branching_factor_ + i,
                                  left_index * branching_factor_ + 1,
                                  num);
  }
}

void TreeNumbering::PrecomputeInorderToParent() {
  // Deal with root
  if (num_nodes_ > 0)
    nodes_[0].inorder_to_parent = -1;

  for (int i = 1; i < num_nodes_; ++i) {
    QuadtreePath path = InorderToTraversalPath(i);
    nodes_[i].inorder_to_parent =
      TraversalPathToInorder(path.Parent());
  }
}

void TreeNumbering::PrecomputeNodesAtLevels() {
  int i = 0;
  int num = 0;
  int num_at_bottom = 1;
  do {
    nodes_at_levels_[i] = num;
    num += num_at_bottom;
    num_at_bottom *= branching_factor_;
    ++i;
  } while (i <= depth_);
}

int TreeNumbering::NodesAtLevels(int level) const {
  return nodes_at_levels_[level];
}

}  // namespace qtpacket


text:
file(REMOVE_RECURSE
  "CMakeFiles/age.dir/Core_types.cpp.o"
  "CMakeFiles/age.dir/assets/ConfigAsset.cpp.o"
  "CMakeFiles/age.dir/assets/ConfigHandler.cpp.o"
  "CMakeFiles/age.dir/assets/FontAsset.cpp.o"
  "CMakeFiles/age.dir/assets/FontHandler.cpp.o"
  "CMakeFiles/age.dir/assets/ImageAsset.cpp.o"
  "CMakeFiles/age.dir/assets/ImageHandler.cpp.o"
  "CMakeFiles/age.dir/assets/MusicAsset.cpp.o"
  "CMakeFiles/age.dir/assets/MusicHandler.cpp.o"
  "CMakeFiles/age.dir/assets/SoundAsset.cpp.o"
  "CMakeFiles/age.dir/assets/SoundHandler.cpp.o"
  "CMakeFiles/age.dir/classes/AssetManager.cpp.o"
  "CMakeFiles/age.dir/classes/ConfigReader.cpp.o"
  "CMakeFiles/age.dir/classes/EventManager.cpp.o"
  "CMakeFiles/age.dir/classes/PropertyManager.cpp.o"
  "CMakeFiles/age.dir/classes/StatManager.cpp.o"
  "CMakeFiles/age.dir/classes/StateManager.cpp.o"
  "CMakeFiles/age.dir/interfaces/Game.cpp.o"
  "CMakeFiles/age.dir/interfaces/IAssetHandler.cpp.o"
  "CMakeFiles/age.dir/interfaces/IEvent.cpp.o"
  "CMakeFiles/age.dir/interfaces/ILogger.cpp.o"
  "CMakeFiles/age.dir/interfaces/IProperty.cpp.o"
  "CMakeFiles/age.dir/interfaces/IState.cpp.o"
  "CMakeFiles/age.dir/loggers/FatalLogger.cpp.o"
  "CMakeFiles/age.dir/loggers/FileLogger.cpp.o"
  "CMakeFiles/age.dir/loggers/ScopeLogger.cpp.o"
  "CMakeFiles/age.dir/loggers/StringLogger.cpp.o"
  "CMakeFiles/age.dir/states/SplashState.cpp.o"
  "CMakeFiles/age.dir/utils/StringUtil.cpp.o"
  "../../../lib/libage.pdb"
  "../../../lib/libage.so"
  "../../../lib/libage.so.0.1.0"
  "../../../lib/libage.so.0.1"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/age.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
  <!--
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="嵌套第二层已经很不要脸,如果设计要你嵌套三层,请反手给他一巴掌,就说我让你打的" />
  -->

  <ImageView
      android:id="@+id/nestIv"
      android:layout_width="100dp"
      android:layout_height="100dp" />
</LinearLayout>


text:
package org.apache.shindig.gadgets.oauth2.handler;

import org.apache.shindig.gadgets.http.HttpRequest;
import org.apache.shindig.gadgets.oauth2.OAuth2Accessor;
import org.apache.shindig.gadgets.oauth2.OAuth2Error;
import org.apache.shindig.gadgets.oauth2.OAuth2Message;

import org.apache.commons.codec.binary.Base64;

/**
 *
 * See {@link ClientAuthenticationHandler}
 *
 * Handler for Basic Authentication
 *
 */
public class BasicAuthenticationHandler implements ClientAuthenticationHandler {
  private static final OAuth2Error ERROR = OAuth2Error.AUTHENTICATION_PROBLEM;

  public OAuth2HandlerError addOAuth2Authentication(final HttpRequest request,
          final OAuth2Accessor accessor) {
    try {
      if (request == null) {
        return BasicAuthenticationHandler.getError("request is null");
      }

      if (accessor == null || !accessor.isValid() || accessor.isErrorResponse()) {
        return BasicAuthenticationHandler.getError("accessor is invalid " + accessor);
      }

      final String clientId = accessor.getClientId();

      if (clientId == null) {
        return BasicAuthenticationHandler.getError("client_id is null");
      }

      final byte[] secretBytes = accessor.getClientSecret();

      if (secretBytes == null) {
        return BasicAuthenticationHandler.getError("client_secret is secret");
      }

      final String secret = new String(secretBytes, "UTF-8");

      final String authString = clientId + ':' + secret;
      final byte[] authBytes = Base64.encodeBase64(authString.getBytes());
      request.setHeader(OAuth2Message.AUTHORIZATION_HEADER, "Basic: " + new String(authBytes));

      return null;
    } catch (final Exception e) {
      return BasicAuthenticationHandler.getError("Exception adding basic auth headers", e);
    }
  }

  public String geClientAuthenticationType() {
    return OAuth2Message.BASIC_AUTH_TYPE;
  }

  private static OAuth2HandlerError getError(final String contextMessage) {
    return BasicAuthenticationHandler.getError(contextMessage, null);
  }

  private static OAuth2HandlerError getError(final String contextMessage, final Exception e) {
    return new OAuth2HandlerError(BasicAuthenticationHandler.ERROR, contextMessage, e);
  }
}