text:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Project: Loop                                                                 '
' Description: Python program for flipkart - API using beautiful soup V4.3.1    '
' Version : V 0.0.1 build 00002                                                 '
' Date : 21/11/14                                                               '
' Author: Tejasvi T                                                             '
'                                                                               '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

from bs4 import BeautifulSoup
import urllib2
from datetime import datetime

class FlipKart:

    #Global values for ID,Token and URL
    global BaseURL,FK_Affiliate_ID,FK_Affiliate_Token,productDict

    FK_Affiliate_ID    = '' //Enter your affiliate ID
    FK_Affiliate_Token = '' //Enter your affiliate token
    BaseURL            = 'https://affiliate-api.flipkart.net/affiliate/api/'
    productDict        = {}

    #Function to Extract the categories and their respective urls
    def BasicURLExtraction():

        #Request for product category xml
        request = urllib2.urlopen(BaseURL+FK_Affiliate_ID+'.xml').read()
        soup = BeautifulSoup(request)

        #Looking for apilistings tag in the category xml file
        soup_Contents = soup.apigroups.entry.value.apilistings

        #Extraction of each child tag as a parent tag
        for child in soup_Contents:

            #Checking for value tag in each parent tag
            if child.entry.value:

                Value = child.entry.value

                #Check for URL for the category and storing that into Catagory_URL variable
                if Value.find_all("get"):
                    Catagory_URL = Value.find_all("get")[0].string.strip()
                else:
                    Catagory_URL = "NA"

                #Check for the respective Category type for that url
                if Value.resourcename:
                    Catagory = Value.resourcename.string
                    Catagory = Catagory.replace("_", " ")
                else:
                    Catagory = "NA"

                #Storing the values of category and URL in a dictionary for further user
                if not Catagory_URL == "NA":
                    if not Catagory == "NA":
                        productDict[Catagory]=Catagory_URL
                    else:
                        pass
                else:
                    pass

            else:
                print "Parsing Error: Please check the parsing algorithm in BasicURLExtraction Function"

    #Function to take user input and route them to respective urls stored in product dictionaries
    def BasicProductURLExtraction():

        #Printing each category name on the screen and to wait for the user input
        for key,value in productDict.items():
            print key

        product = raw_input("Enter product name: ")

        #Checking for the user input entered for error
        if product in productDict:

            #Extracting the url and storing into productURL, flag entry for the user input error
            global productURL,userInputKey
            userInputKey = True
            productURL = productDict[product]
            print "ProductURL: ",productURL

        #When there is an error in the user input
        else:
            print "Please check the product entered and try again, thank you"
            userInputKey = False

    #Product Extraction for the xml of each Category
    def BasicLaptopExtraction(productURL,numberRun):

        #Requesting for the category page
        productRequest = urllib2.Request(productURL , headers= {"Fk-Affiliate-Id":FK_Affiliate_ID,"Fk-Affiliate-Token":FK_Affiliate_Token})
        productContent = urllib2.urlopen(productRequest).read()

        productSoup = BeautifulSoup(productContent)

        #Check for nexturl tag in the xml
        global flagNextURL, nextURL
        if productSoup.nexturl:
            flagNextURL = True
            nextURL = productSoup.nexturl.string

        #When no nexturl tag is not present
        else:
            flagNextURL = False

        #looking for products tag present in the xml
        ProductSoupContent = productSoup.products
        itemNumber   = 0
        numLaptop    = 0
        numNA        = 0

        #Extracting child tags from the parent tag
        for tags in ProductSoupContent:
            itemNumber += 1
            itemNewNumber = itemNumber + numberRun

            #To Extract Category and SubCategory of the product to store in DataBase
            if tags.categorypaths.categorypath.find_all("item"):
                itemDetails     = tags.categorypaths.categorypath.find_all("item")
                itemCategory    = itemDetails[0]
                itemSubCategory = itemDetails[1]
                itemCategory    = itemCategory.title.string
                itemSubCategory = itemSubCategory.title.string
            else:
                itemCategory    = "NA"
                itemSubCategory = "NA"

            #To Extract ProductID and store it into itemID
            if tags.productid:
                itemID = tags.productid.string
            else:
                itemID = "NA"

            #To Extract Cash-On-Delivery status and store in itemCOD
            if tags.codavailable:
                itemCOD = tags.codavailable.string
            else:
                itemCOD = "NA"

            #To Extract Color and store in itemColor
            if tags.color:
                itemColor = tags.color.string
            else:
                itemColor = "NA"

            #To Extract EMI status and store in itemEMI
            if tags.emiavailable:
                itemEMI = tags.emiavailable.string
            else:
                itemEMI = "NA"

            #To Extract In-Stock status and store in itemInStock
            if tags.instock:
                itemInStock = tags.instock.string
            else:
                itemInStock = "NA"

            #To Extract productBrand and store in itemBrand
            if tags.productbrand:
                itemBrand = tags.productbrand.string
            else:
                itemBrand = "NA"

            #To Extract productURL and store in itemURL
            if tags.producturl:
                itemURL = tags.producturl.string
            else:
                itemURL = "NA"

            #To Extract title and store in itemTitle
            if tags.find_all("title"):
                itemTitle = tags.find_all("title")
                if len(itemTitle) == 4:
                    itemTitle = itemTitle[3].string
                elif len(itemTitle) == 5:
                    itemTitle = itemTitle[4].string

            else:
                itemTitle = "NA"

            #To Extract MRP amount and store in itemMRPAmount
            if tags.maximumretailprice.amount:
                itemMRPAmount = tags.maximumretailprice.amount.string
            else:
                itemMRPAmount = "NA"

            #To Extract MRP currency and store in itemMRPCurrency
            if tags.maximumretailprice.currency:
                itemMRPCurrency = tags.maximumretailprice.currency.string
            else:
                itemMRPCurrency = "NA"

            #To Extract Selling amount and store in itemSellingAmount
            if tags.sellingprice.amount:
                itemSellingAmount = tags.sellingprice.amount.string
            else:
                itemSellingAmount = "NA"

            #To Extract MRP amount and store in itemMRPAmount
            if tags.sellingprice.currency:
                itemSellingCurrency = tags.sellingprice.currency.string
            else:
                itemSellingCurrency = "NA"

            #To Extract sizeVariants and store in itemSizeVariants
            if tags.sizevariants:
                itemSizeVariants = tags.sizevariants.string
            else:
                itemSizeVariants = "NA"

            #To Extract colorvariants and store in itemColorVariants
            if tags.colorvariants:
                itemColorVariants = tags.colorvariants.string
            else:
                itemColorVariants = "NA"

            #To Extract ImageURLS and store in itemImageDict dictionary
            if tags.imageurls.find_all("entry"):
                itemImageEntry = tags.imageurls.find_all("entry")
                itemImageDict  = {}
                for subtags in itemImageEntry:

                    #To Extract imagekey and store in itemimagekey
                    if subtags.key:
                        itemImageKey = subtags.key.string
                    else:
                        itemImageKey = "NA"

                    #To Extract imagevalue and store in itemimagevalue
                    if subtags.value:
                        itemImageValue = subtags.value.string
                    else:
                        itemImageValue = "NA"

                    itemImageDict[itemImageKey] = itemImageValue

            else:
                itemImageDict = {}

            #To Extract productDescription and store in itemDescription
            if tags.productdescription:
                itemDescription = tags.productdescription.string
            else:
                itemDescription = "NA"

            #To Extract size and store in itemSize
            if tags.size:
                itemSize = tags.size.string
            else:
                itemSize = "NA"

            #To Extract sizeunit and store in itemSizeUnit
            if tags.sizeunit:
                itemSizeUnit = tags.sizeunit.string
            else:
                itemSizeUnit = "NA"

            #Calculation of Discount
            if not itemMRPAmount == "NA":
                if not itemSellingAmount == "NA":
                    if float(itemSellingAmount) < float(itemMRPAmount):
                        itemDiscount = (((float(itemMRPAmount) - float(itemSellingAmount))/float(itemSellingAmount)) * 100 )
                    else:
                        itemDiscount = "0"
                else:
                    itemDiscount = "0"
            else:
                itemDiscount = "0"

            #To Seperate each value present in the Title
            itemSubDiv = itemTitle
            itemSubDiv = itemSubDiv.split(' ')
            numitemSubDiv = 0

            #To Check for the Laptop present in the Title String
            if "Laptop" in itemSubDiv or "Sleekbook" in itemSubDiv or "Netbook" in itemSubDiv or "Ultrabook" in itemSubDiv or "netbook" in itemSubDiv or "ProBook" in itemSubDiv or "Probook" in itemSubDiv or "Notebook" in itemSubDiv or "VivoBook" in itemSubDiv or "Chromebook" in itemSubDiv or "PC" in itemSubDiv or "Slatebook" in itemSubDiv or "ChromebookSamsung" in itemSubDiv or "MacBook" in itemSubDiv:

                #Initilization of few Variables
                numLaptop    += 1
                placeNumber   = 0
                processNumber = 0
                count1        = 0
                OSFlag        = False
                HardDiskFlag  = False
                RAMFlag       = False
                DoNotEnterFlag= False
                foundFewFlag  = False
                itemTouch     = False
                itemRetina    = False
                itemProcessor = "NA"
                itemGraphics  = "NA"
                itemRAM       = "NA"
                itemHardDisk  = "NA"
                itemOS        = "NA"

                #Dividing the title into subDiv's and checking for each term
                for subDiv in itemSubDiv:

                    #To get the Location of string "Laptop" in an array
                    if subDiv == "Laptop" or subDiv == "Sleekbook" or subDiv == "Netbook" or subDiv == "Ultrabook" or subDiv == "netbook" or subDiv == "ProBook" or subDiv == "Probook" or subDiv == "Notebook" or subDiv == "VivoBook" or subDiv == "Chromebook" or subDiv == "PC" or subDiv == "Slatebook" or subDiv == "ChromebookSamsung" or subDiv == "MacBook":

                        placeNumber = numitemSubDiv

                    #To Identify string with "/"
                    if "/" in subDiv and placeNumber < numitemSubDiv and placeNumber > 0:

                        #To get the position of first forward slash and get the processer position
                        if count1 == 0:
                            processNumber = numitemSubDiv
                            count1 += 1

                        #To get the position of secong forward slash and get the RAM position
                        elif count1 == 1:
                            RAMFlag   = True
                            numRAM    = numitemSubDiv
                            itemRAM   = itemSubDiv[numitemSubDiv]
                            itemRAM   = itemRAM.replace('/','')
                            count1 += 1

                        #To get the position of third forward slash and get the Hard disk position
                        elif count1 == 2:
                            numHardDisk  = numitemSubDiv
                            itemHardDisk = itemSubDiv[numitemSubDiv]
                            itemHardDisk = itemHardDisk.replace('/','')
                            count1 += 1
                            HardDiskFlag = True
                            #When there is SSD or TB or something with two tags for memory then store the two values
                            if itemHardDisk == "SSD" or itemHardDisk == "TB" or itemHardDisk == "Flash":
                                itemHardDisk = itemSubDiv[numitemSubDiv - 1]+" "+itemSubDiv[numitemSubDiv]
                                itemHardDisk = itemHardDisk.replace('/','')
                            else:
                                pass

                        #To get the position of fourth forward slash and get the OS position
                        elif count1 == 3:
                            numOS   = numitemSubDiv
                            itemOS  = itemSubDiv[numitemSubDiv]
                            itemOS  = itemOS.replace('/','')
                            count1 += 1
                            OSFlag  = True
                            if itemOS == "HB":
                                itemOS = itemSubDiv[numitemSubDiv - 1]+" "+itemSubDiv[numitemSubDiv]
                            elif itemOS == "Lion":
                                itemOS = itemSubDiv[numitemSubDiv - 4]+" "+itemSubDiv[numitemSubDiv - 3]+" "+itemSubDiv[numitemSubDiv - 2]+" "+itemSubDiv[numitemSubDiv - 1]+" "+itemSubDiv[numitemSubDiv]
                                itemOS = itemOS.replace('/','')
                            else:
                                pass

                    #When fourth forward slash is not present and to retrieve OS
                    if HardDiskFlag:
                        if not OSFlag:
                            itemOS = itemSubDiv[numHardDisk + 1]

                    #When fourth slash is present go for Laptop Graphics tag
                    if HardDiskFlag:
                        if OSFlag:
                            itemGraphics = itemSubDiv[numOS + 1]
                            if itemGraphics == "Touch":
                                itemGraphics = "NA"
                                itemTouch    = True
                            elif itemGraphics == "Retina":
                                itemGraphics = "NA"
                                itemRetina   = True
                        else:
                            itemGraphics = "NA"

                    numitemSubDiv += 1

                #Storing ItemModel number based on the position of laptop tag in an array
                itemModel  = itemSubDiv[placeNumber - 1]

                #Storing ItemSerial Number based on the position of laptop tag in an array when position is 3 there won't be child for ItemSeries
                if placeNumber == 3:
                    itemSeriesParent = itemSubDiv[placeNumber - 2]
                    itemSeriesChild  = "NA"

                #Storing ItemSerial Number based on the position of laptop tag in an array when position is 4 there will be child for ItemSeries
                elif placeNumber == 4:
                    itemSeriesParent = itemSubDiv[placeNumber - 3]
                    itemSeriesChild  = itemSubDiv[placeNumber - 2]

                #When other options comes to business store NA tags in ItemSeries Parent and Child
                else:
                    itemSeriesParent = "NA"
                    itemSeriesChild  = "NA"

                if not count1 == 1:
                    #Storing the processor specifications
                    if not processNumber == 0:
                        #Calculation of difference between location of first forward slash and the location of laptop tag
                        calNumber = processNumber - placeNumber
                        numb = 0
                        itemProcessor = []
                        #Running the code to store processor specification grabbed from different variables in an array named ITEMSUBDIV
                        while numb < calNumber:
                            numb += 1
                            if not itemSubDiv[(processNumber - calNumber) + numb] == "Pro":
                                itemProcessor.append(itemSubDiv[(processNumber - calNumber) + numb])
                            else:
                                itemSeriesChild = itemSubDiv[(processNumber - calNumber) + numb]
                                itemSeriesParent = "Macbook"
                    #When Processor or first forward slash is not present store itemprocessor with an empty array
                    else:
                        itemProcessor = []

                #When there is only one value in an array with forward slash then make all the specification as NA and make DoNotEnterFlag as True
                else:
                    itemProcessor = "NA"
                    itemGraphics  = "NA"
                    itemRAM       = "NA"
                    itemHardDisk  = "NA"
                    itemOS        = "NA"
                    DoNotEnterFlag= True

                #Join different variables in an array seperated by a space
                itemProcessor = ' '.join(itemProcessor)
                itemProcessor = itemProcessor.replace('/','')

                #When there is no third forward slash store itemHardDisk as NA
                if not HardDiskFlag:
                    itemHardDisk = "NA"

                #When there is no Second forward slash store itemRAM as NA
                if not  RAMFlag:
                    itemRAM = "NA"

                #When there are exceptional cases of extracting data from the title
                if "," in itemTitle:
                    subitemSubDiv = itemTitle.split(',')
                    itemSize      = subitemSubDiv[0]
                    itemSize      = itemSize.split('-')
                    if len(itemSize) == 2:
                        itemS          = itemSize[1]
                        itemD          = itemSize[0]
                        itemD          = itemD.split(' ')
                        itemModel      = itemD[1]
                        if len(itemD) > 3:
                            itemSeriesParent = itemD[2]
                            itemSeriesChild  = itemD[3]
                        else:
                            itemSeriesParent = itemD[2]
                            itemSeriesChild  = "NA"

                    elif len(itemSize) == 3:
                        itemS         = itemSize[2]
                        itemD         = itemSize[0]+"-"+itemSize[1]
                        itemD         = itemD.split(' ')
                        itemModel     = itemD[1]
                        itemSeriesParent = itemD[2]
                        itemSeriesChild  = itemD[3]

                    itemHardDisk  = subitemSubDiv[1]

                    itemRAM       = subitemSubDiv[2]
                    itemRAM       = itemRAM.split('Laptop')
                    itemRAM       = itemRAM[0]
                    itemSize      = itemS

                    if itemRAM[0] == " ":
                        itemRAM = itemRAM[1:len(itemRAM)]

                    if itemHardDisk[0] == " ":
                        itemHardDisk = itemHardDisk[1:len(itemHardDisk)]

                    if itemSize[0] == " ":
                        itemSize = itemSize[1:len(itemSize)]

                    if "i5" in itemTitle:
                        itemProcessor = "Intel Core i5"
                    elif "i7" in itemTitle:
                        itemProcessor = "Intel Core i7"

                #Printing of all the values that are extracted
                print "Item No               :", itemNewNumber
                print "Item ID               :", itemID
                print "Item Title            :", itemTitle
                print "Item Brand            :", itemBrand
                print "Item URL              :", itemURL
                print "Item Available        :", itemInStock
                print "Item SeriesParent     :", itemSeriesParent
                print "Item SeriesChild      :", itemSeriesChild
                print "Item Processor        :", itemProcessor
                print "Item RAM              :", itemRAM
                print "Item HardDisk         :", itemHardDisk
                print "Item OS               :", itemOS
                print "Item Graphics         :", itemGraphics
                print "Item Touch            :", itemTouch
                if "MacBook" in itemSubDiv:
                    print "Item Retina           :", itemRetina
                else:
                    pass
                print "Item Model            :", itemModel
                print "Item COD Status       :", itemCOD
                print "Item MRP Amount       :", itemMRPAmount
                print "Item MRP Currency     :", itemMRPCurrency
                print "Item Selling Amount   :", itemSellingAmount
                print "Item Selling Currency :", itemSellingCurrency
                print "Item Discount         :", str(itemDiscount)+"%"
                print "Item EMI Status       :", itemEMI
                print "Item Description      :", itemDescription
                print "Item Size             :", itemSize
                print "Item Size Unit        :", itemSizeUnit
                print "Item Color            :", itemColor
                print "Item Color Variants   :", itemColorVariants
                print "Item Size Variants    :", itemSizeVariants

                for keys,values in itemImageDict.items():
                    print "Item Image Size       :", keys
                    print "Item Image URL        :", values

                print "***********************************************************"

            else:
                numNA += 1

        #Printing the nextURL that need to be accessed at the end
        print nextURL
        print productURL

    if __name__ == "__main__":

        #Calling BasicURLExtraction() Function
        BasicURLExtraction()
        #Calling BasicProductURLExtraction() Function
        BasicProductURLExtraction()

        #When User input has an Error Calling BaiscProductURLExtraction() Once Again
        while not userInputKey:
            BasicProductURLExtraction()

        #Start the Time function to start calculating the time taken to extract
        startTime = datetime.now()
        print "Start Time:",startTime
        BasicProductExtraction(productURL, 0)
        #Increase or Reduce the number to choose number of XML pages to be extracted
        z = 10
        i = 1
        while i < z:
            if flagNextURL:
                productURL = nextURL
                numberRun = i * 500
                BasicLaptopExtraction(productURL, numberRun)
            else:
                i = i + (z - i)
            i += 1
            print i

        #Print the End time after the complition of all the processes
        endTime = datetime.now()
        print "End Time:",endTime

        #Calculating TotalTime taken from startTime and endTime
        totalTimeMicroseconds = endTime.microsecond - startTime.microsecond
        totalTimeSeconds      = endTime.second      - startTime.second
        totalTimeMinutes      = endTime.minute      - startTime.minute
        totalTimeHours        = endTime.hour        - startTime.hour

        #When TotalHours Value is negative
        if totalTimeHours < 0:
            totalTimeHours = 24 + totalTimeHours

        #When TotalMinutes Value is negative
        if totalTimeMinutes < 0:
            totalTimeMinutes = 60 + totalTimeMinutes
            totalTimeHours -= 1

        #When TotalSeconds Value is negative
        if totalTimeSeconds < 0:
            totalTimeSeconds = 60 + totalTimeSeconds
            totalTimeMinutes -= 1

        #When TotalMicroSeconds Value is negative
        if totalTimeMicroseconds < 0:
            totalTimeMicroseconds = 1000000 + totalTimeMicroseconds
            totalTimeSeconds -= 1

        #Converting MicroSeconds into MilliSeconds
        totalTimeMilliseconds = totalTimeMicroseconds/1000

        #Printing of TotalTime taken at the end of the program
        print "Total Time:",totalTimeHours,"H:",totalTimeMinutes,"M:",totalTimeSeconds,"S.",totalTimeMilliseconds,"ms"


text:
A basic geometry calculator.

## Compilation:
To compile the TypeScript files install the development dependencies, and then run `npm run build`.

```bash
$ npm install
$ npm run build
```

## Tests:
To run the tests run `npm run test`.

```bash
$ npm run test
```

## Example:
```js
"use strict";

const assert = require("assert");

const {
    calculateTotalArea,
    Rectangle,
    Triangle
} = require("geometry-calculator");

let rectangle = new Rectangle(10, 20);

assert(rectangle.area() == 200);

assert(rectangle.perimeter() == 60);

let triangle = new Triangle(3, 4, 5);

assert(triangle.area() == 6);

assert(triangle.perimeter() == 12);

assert(calculateTotalArea([
    rectangle,
    triangle
]) == 206);
```

## Class: Circle
The Circle class represents circles.

### Circle.Circle(radius)

Creates an instance of Circle.

**Parameters**

**radius**: `number`, the radius

### Circle.area()

Returns the area of the Circle.

**Returns**: `number`, the area

### Circle.circumference()

Returns the circumference/perimeter of the Circle.

**Returns**: `number`, the circumference/perimeter

### Circle.perimeter()

Returns the perimeter of the Circle.

**Returns**: `number`, the perimeter

## Class: Rectangle
The Rectangle class represents rectangles.

### Rectangle.Rectangle(length, width)

Creates an instance of Rectangle.

**Parameters**

**length**: `number`, the length

**width**: `number`, the width

### Rectangle.area()

Returns the area of the Rectangle.

**Returns**: `number`, the area

### Rectangle.perimeter()

Returns the perimeter of the Rectangle.

**Returns**: `number`, the perimeter

## Class: Square
The Square class represents squares.

### Square.Square(length)

Creates an instance of Square.

**Parameters**

**length**: `number`, the length

### Square.area()

Returns the area of the Square.

**Returns**: `number`, the area

### Square.perimeter()

Returns the perimeter of the Square.

**Returns**: `number`, the perimeter

## Class: Triangle
The Triangle class represents triangles.

### Triangle.Triangle(a, b, c)

Creates an instance of Triangle.

**Parameters**

**a**: `number`, the first side of the Triangle

**b**: `number`, the second side of the Triangle

**c**: `number`, the third side of the Triangle

### Triangle.area()

Returns the area of the Triangle.
The area is calculated with Heron's formula (https://en.wikipedia.org/wiki/Heron's_formula).

**Returns**: `number`, the area

### Triangle.perimeter()

Returns the perimeter of the Triangle.

**Returns**: `number`, the perimeter

### Triangle.semiperimeter()

Returns the semiperimeter of the Triangle.
The semiperimeter is half of the shape's perimeter.

**Returns**: `number`, the semiperimeter

### calculateTotalArea(array)

Returns the total area of multiple IGeometricShapes.

**Parameters**

**array**: `Array<IGeometricShape>`, the array of IGeometricShapes

**Returns**: `number`, the area

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.msf4j.internal.entitywriter;

import org.wso2.carbon.messaging.CarbonCallback;
import org.wso2.carbon.messaging.CarbonMessage;

/**
 * Interface that provides the capability of writing an entity type to
 * a carbon message.
 *
 * @param <T> type of the entity
 */
public interface EntityWriter<T> {

    String CHUNKED = "chunked";

    /**
     * Provide supported entity type.
     *
     * @return entity type
     */
    Class<T> getType();

    /**
     * Write the entity object to the carbon message by considering the
     * provided chunk size and media type.
     *
     * @param carbonMessage response message
     * @param entity    object
     * @param mediaType user defined media type
     * @param chunkSize user defined chunk size
     *                  0 to signify none chunked response
     *                  -1 to signify default chunk size of the EntityWriter
     * @param cb        callback method that should be called to start sending the response payload
     */
    void writeData(CarbonMessage carbonMessage, T entity, String mediaType,
                   int chunkSize, CarbonCallback cb);

}


text:
var myChart = [];
var domCode = $("[md='sidebar-code']");
var domGraphic = $("[md='graphic']");
var domMain = $("[md='main']");
var domMessage = $("[md='wrong-message']");
var iconResize = $("[md='icon-resize']");
var needRefresh = false;

function findIdxFromEvent(event) {
    event = event || window.event;
    return findIdx(event.target || event.srcElement);
}
function findIdx(d) {
    var p = d;
    while (p.className != 'container-fluid') {
        p = p.parentElement;
    }
    return $(p).attr('idx');
}
var idx;
function autoResize(event) {
    idx = findIdxFromEvent(event);
    if (iconResize[idx].className == 'icon-resize-full') {
        focusCode();
        iconResize[idx].className = 'icon-resize-small';
    }
    else {
        focusGraphic();
        iconResize[idx].className = 'icon-resize-full';
    }
}

function focusCode() {
    domCode[idx].className = 'span8 ani';
    domGraphic[idx].className = 'span4 ani';
}

function focusGraphic() {
    domCode[idx].className = 'span4 ani';
    domGraphic[idx].className = 'span8 ani';
    if (needRefresh) {
        myChart[idx].showLoading();
        setTimeout(refresh, 1000);
    }
}

var domTextarea = $("[md='code']");
var editor = [];
for (var i = 0, l = domTextarea.length; i < l; i++) {
    editor[i] = CodeMirror.fromTextArea(
        domTextarea[i],
        { lineNumbers: true }
    );
    editor[i].setOption("theme", 'monokai');
    editor[i].on('change', function (){needRefresh = true;});
}

function refresh(isBtnRefresh, idd){
    if (isBtnRefresh) {
        idx = idd;
        needRefresh = true;
        focusGraphic();
        return;
    }
    needRefresh = false;
    if (myChart[idx] && myChart[idx].dispose) {
        myChart[idx].dispose();
    }
    myChart[idx] = echarts.init(domMain[idx]);
    (new Function (editor[idx].doc.getValue().replace(
        'option', 'option[' + idx + ']'))
    )()
    myChart[idx].setOption(option[idx], true);
    domMessage[idx].innerHTML = '';
}

function refreshAll() {
    for (var i = 0, l = myChart.length; i < l; i++) {
        (new Function (editor[i].doc.getValue().replace(
            'option', 'option[' + i + ']'))
        )();
        myChart[i].setOption(option[i], true);
        domMessage[i].innerHTML = '';
    }
}

var developMode = false;
if (developMode) {
    window.esl = null;
    window.define = null;
    window.require = null;
    (function () {
        var script = document.createElement('script');
        script.async = true;

        script.src = '../../doc/asset/js/esl/esl.js';
        if (script.readyState) {
            script.onreadystatechange = fireLoad;
        }
        else {
            script.onload = fireLoad;
        }
        (document.getElementsByTagName('head')[0] || document.body).appendChild(script);

        function fireLoad() {
            script.onload = script.onreadystatechange = null;
            setTimeout(loadedListener,100);
        }
        function loadedListener() {
            // for develop
            require.config({
                packages: [
                    {
                        name: 'echarts',
                        location: '../../src',
                        main: 'echarts'
                    },
                    {
                        name: 'zrender',
                        //location: 'http://ecomfe.github.io/zrender/src',
                        location: '../../../zrender/src',
                        main: 'zrender'
                    }
                ]
            });
            launchExample();
        }
    })();
}
else {
    // for echarts online home page
    require.config({
        paths:{
            echarts: '../../build/dist'
        }
    });
    launchExample();
}

var isExampleLaunched;
function launchExample() {
    if (isExampleLaunched) {
        return;
    }

    // 按需加载
    isExampleLaunched = 1;
    require(
        [
            'echarts',
            'echarts/chart/line',
            'echarts/chart/bar',
            'echarts/chart/scatter',
            'echarts/chart/k',
            'echarts/chart/pie',
            'echarts/chart/radar',
            'echarts/chart/force',
            'echarts/chart/chord',
            'echarts/chart/map',
            'echarts/chart/gauge',
            'echarts/chart/funnel',
            'echarts/chart/eventRiver'
        ],
        requireCallback
    );
}

var echarts;
var option = {};
function requireCallback (ec) {
    echarts = ec;
    if (myChart.length > 0) {
        for (var i = 0, l = myChart.length; i < l; i++) {
            myChart[i].dispose && myChart[i].dispose();
        }
    }
    myChart = [];
    for (var i = 0, l = domMain.length; i < l; i++) {
        myChart[i] = echarts.init(domMain[i]);
    }
    refreshAll();

    window.onresize = function (){
        for (var i = 0, l = myChart.length; i < l; i++) {
            myChart[i].resize && myChart[i].resize();
        }
    };
}


text:
<?php
namespace HyperBookBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Util\LegacyFormHelper;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\EmailType'), [
                'label' => 'Your email address',
                'translation_domain' => 'FOSUserBundle',
                'attr' => [
                    'class' => 'form-control'
                ]
            ])
            ->add('username', null, [
                'label' => 'Username',
                'translation_domain' => 'FOSUserBundle',
                'attr' => [
                    'class' => 'form-control'
                ]
            ])
            ->add('plainPassword', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\RepeatedType'), [
                'type' => LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\PasswordType'),
                'options' => array('translation_domain' => 'FOSUserBundle'),
                'first_options' => [
                    'label' => 'Password',
                    'attr' => [
                        'class' => 'form-control'
                    ]
                ],
                'second_options' => [
                    'label' => 'Confirm Password',
                    'attr' => [
                        'class' => 'form-control'
                    ]
                ],
                'invalid_message' => 'fos_user.password.mismatch',
            ]);
    }

    public function getParent()
    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';
    }

    public function getBlockPrefix()
    {
        return 'app_user_registration';
    }

    public function getName()
    {
        return $this->getBlockPrefix();
    }
}


text:
import * as os from 'os';
import * as _ from 'underscore';
import { betterSetInterval, betterClearInterval } from 'apify-shared/utilities';
import { ACTOR_EVENT_NAMES, ENV_VARS } from 'apify-shared/consts';
import { checkParamOrThrow } from 'apify-client/build/utils';
import { getMemoryInfo, isAtHome, apifyClient } from '../utils';
import log from '../utils_log';
import events from '../events';

const DEFAULT_OPTIONS = {
    eventLoopSnapshotIntervalSecs: 0.5,
    maxBlockedMillis: 50, // 0.05
    memorySnapshotIntervalSecs: 1,
    clientSnapshotIntervalSecs: 1,
    cpuSnapshotIntervalSecs: 1,
    maxUsedMemoryRatio: 0.7,
    maxUsedCpuRatio: 0.95,
    snapshotHistorySecs: 30,
    maxClientErrors: 3,
};
const RESERVE_MEMORY_RATIO = 0.5;
const CLIENT_RATE_LIMIT_ERROR_RETRY_COUNT = 2;
const CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS = 10000;

/**
 * @typedef SnapshotterOptions
 * @property {number} [eventLoopSnapshotIntervalSecs=0.5]
 *   Defines the interval of measuring the event loop response time.
 * @property {number} [clientSnapshotIntervalSecs=1]
 *   Defines the interval of checking the current state
 *   of the remote API client.
 * @property {number} [maxBlockedMillis=50]
 *   Maximum allowed delay of the event loop in milliseconds.
 *   Exceeding this limit overloads the event loop.
 * @property {number} [cpuSnapshotIntervalSecs=1]
 *   Defines the interval of measuring CPU usage.
 *   This is only used when running locally. On the Apify platform,
 *   the statistics are provided externally at a fixed interval.
 * @property {number} [maxUsedCpuRatio=0.95]
 *   Defines the maximum usage of CPU.
 *   Exceeding this limit overloads the CPU.
 * @property {number} [memorySnapshotIntervalSecs=1]
 *   Defines the interval of measuring memory consumption.
 *   This is only used when running locally. On the Apify platform,
 *   the statistics are provided externally at a fixed interval.
 *   The measurement itself is resource intensive (25 - 50ms async).
 *   Therefore, setting this interval below 1 second is not recommended.
 * @property {number} [maxUsedMemoryRatio=0.7]
 *   Defines the maximum ratio of total memory that can be used.
 *   Exceeding this limit overloads the memory.
 * @property {number} [maxClientErrors=1]
 *   Defines the maximum number of new rate limit errors within
 *   the given interval.
 * @property {number} [snapshotHistorySecs=60]
 *   Sets the interval in seconds for which a history of resource snapshots
 *   will be kept. Increasing this to very high numbers will affect performance.
 */

/**
 * Creates snapshots of system resources at given intervals and marks the resource
 * as either overloaded or not during the last interval. Keeps a history of the snapshots.
 * It tracks the following resources: Memory, EventLoop, API and CPU.
 * The class is used by the {@link AutoscaledPool} class.
 *
 * When running on the Apify platform, the CPU and memory statistics are provided by the platform,
 * as collected from the running Docker container. When running locally, `Snapshotter`
 * makes its own statistics by querying the OS.
 *
 * CPU becomes overloaded locally when its current use exceeds the `maxUsedCpuRatio` option or
 * when Apify platform marks it as overloaded.
 *
 * Memory becomes overloaded if its current use exceeds the `maxUsedMemoryRatio` option.
 * It's computed using the total memory available to the container when running on
 * the Apify platform and a quarter of total system memory when running locally.
 * Max total memory when running locally may be overridden by using the `APIFY_MEMORY_MBYTES`
 * environment variable.
 *
 * Event loop becomes overloaded if it slows down by more than the `maxBlockedMillis` option.
 *
 * Client becomes overloaded when rate limit errors (429 - Too Many Requests),
 * typically received from the request queue, exceed the set limit within the set interval.
 */
class Snapshotter {
    /**
     * @param {SnapshotterOptions} [options] All `Snapshotter` configuration options.
     */
    constructor(options = {}) {
        const {
            eventLoopSnapshotIntervalSecs,
            cpuSnapshotIntervalSecs,
            memorySnapshotIntervalSecs,
            clientSnapshotIntervalSecs,
            snapshotHistorySecs,
            maxBlockedMillis,
            maxUsedMemoryRatio,
            maxUsedCpuRatio,
            maxClientErrors,
        } = _.defaults({}, options, DEFAULT_OPTIONS);

        checkParamOrThrow(eventLoopSnapshotIntervalSecs, 'options.eventLoopSnapshotIntervalSecs', 'Number');
        checkParamOrThrow(memorySnapshotIntervalSecs, 'options.memorySnapshotIntervalSecs', 'Number');
        checkParamOrThrow(cpuSnapshotIntervalSecs, 'options.cpuSnapshotIntervalSecs', 'Number');
        checkParamOrThrow(snapshotHistorySecs, 'options.snapshotHistorySecs', 'Number');
        checkParamOrThrow(clientSnapshotIntervalSecs, 'options.clientSnapshotIntervalSecs', 'Number');
        checkParamOrThrow(maxBlockedMillis, 'options.maxBlockedMillis', 'Number');
        checkParamOrThrow(maxUsedMemoryRatio, 'options.maxUsedMemoryRatio', 'Number');
        checkParamOrThrow(maxUsedCpuRatio, 'options.maxUsedCpuRatio', 'Number');
        checkParamOrThrow(maxClientErrors, 'options.maxClientErrors', 'Number');

        this.eventLoopSnapshotIntervalMillis = eventLoopSnapshotIntervalSecs * 1000;
        this.memorySnapshotIntervalMillis = memorySnapshotIntervalSecs * 1000;
        this.clientSnapshotIntervalMillis = clientSnapshotIntervalSecs * 1000;
        this.cpuSnapshotIntervalMillis = cpuSnapshotIntervalSecs * 1000;
        this.snapshotHistoryMillis = snapshotHistorySecs * 1000;
        this.maxBlockedMillis = maxBlockedMillis;
        this.maxUsedMemoryRatio = maxUsedMemoryRatio;
        this.maxUsedCpuRatio = maxUsedCpuRatio;
        this.maxClientErrors = maxClientErrors;
        this.maxMemoryBytes = (parseInt(process.env[ENV_VARS.MEMORY_MBYTES], 10) * 1024 * 1024) || null;

        this.cpuSnapshots = [];
        this.eventLoopSnapshots = [];
        this.memorySnapshots = [];
        this.clientSnapshots = [];

        this.eventLoopInterval = null;
        this.memoryInterval = null;
        this.clientInterval = null;
        this.cpuInterval = null;

        this.lastLoggedCriticalMemoryOverloadAt = null;

        // We need to pre-bind those functions to be able to successfully remove listeners.
        this._snapshotCpuOnPlatform = this._snapshotCpuOnPlatform.bind(this);
        this._snapshotMemoryOnPlatform = this._snapshotMemoryOnPlatform.bind(this);
    }

    /**
     * Starts capturing snapshots at configured intervals.
     * @return {Promise<void>}
     */
    async start() {
        await this._ensureCorrectMaxMemory();

        // Start snapshotting.
        this.eventLoopInterval = betterSetInterval(this._snapshotEventLoop.bind(this), this.eventLoopSnapshotIntervalMillis);
        this.clientInterval = betterSetInterval(this._snapshotClient.bind(this), this.clientSnapshotIntervalMillis);
        if (isAtHome()) {
            events.on(ACTOR_EVENT_NAMES.SYSTEM_INFO, this._snapshotCpuOnPlatform);
            events.on(ACTOR_EVENT_NAMES.SYSTEM_INFO, this._snapshotMemoryOnPlatform);
        } else {
            this.cpuInterval = betterSetInterval(this._snapshotCpuOnLocal.bind(this), this.cpuSnapshotIntervalMillis);
            this.memoryInterval = betterSetInterval(this._snapshotMemoryOnLocal.bind(this), this.memorySnapshotIntervalMillis);
        }
    }

    /**
     * Stops all resource capturing.
     * @return {Promise<void>}
     */
    async stop() {
        betterClearInterval(this.eventLoopInterval);
        betterClearInterval(this.memoryInterval);
        betterClearInterval(this.cpuInterval);
        betterClearInterval(this.clientInterval);
        events.removeListener(ACTOR_EVENT_NAMES.SYSTEM_INFO, this._snapshotCpuOnPlatform);
        events.removeListener(ACTOR_EVENT_NAMES.SYSTEM_INFO, this._snapshotMemoryOnPlatform);
        // Allow microtask queue to unwind before stop returns.
        await new Promise(resolve => setImmediate(resolve));
    }

    /**
     * Returns a sample of latest memory snapshots, with the size of the sample defined
     * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
     * @param {number} [sampleDurationMillis]
     * @return {Array<*>}
     */
    getMemorySample(sampleDurationMillis) {
        return this._getSample(this.memorySnapshots, sampleDurationMillis);
    }

    /**
     * Returns a sample of latest event loop snapshots, with the size of the sample defined
     * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
     * @param {number} [sampleDurationMillis]
     * @return {Array<*>}
     */
    getEventLoopSample(sampleDurationMillis) {
        return this._getSample(this.eventLoopSnapshots, sampleDurationMillis);
    }

    /**
     * Returns a sample of latest CPU snapshots, with the size of the sample defined
     * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
     * @param {number} [sampleDurationMillis]
     * @return {Array<*>}
     */
    getCpuSample(sampleDurationMillis) {
        return this._getSample(this.cpuSnapshots, sampleDurationMillis);
    }

    /**
     * Returns a sample of latest Client snapshots, with the size of the sample defined
     * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
     * @param {number} sampleDurationMillis
     * @return {Array<*>}
     */
    getClientSample(sampleDurationMillis) {
        return this._getSample(this.clientSnapshots, sampleDurationMillis);
    }

    /**
     * Finds the latest snapshots by sampleDurationMillis in the provided array.
     * @param {Array<*>} snapshots
     * @param {number} [sampleDurationMillis]
     * @return {Array<*>}
     * @ignore
     */
    _getSample(snapshots, sampleDurationMillis) { // eslint-disable-line class-methods-use-this
        if (!sampleDurationMillis) return snapshots;

        const sample = [];
        let idx = snapshots.length;
        if (!idx) return sample;

        const latestTime = snapshots[idx - 1].createdAt;
        while (idx--) {
            const snapshot = snapshots[idx];
            if (latestTime - snapshot.createdAt <= sampleDurationMillis) sample.unshift(snapshot);
            else break;
        }
        return sample;
    }

    /**
     * Creates a snapshot of current memory usage
     * using the Apify platform `systemInfo` event.
     * @param {*} systemInfo
     * @ignore
     */
    _snapshotMemoryOnPlatform(systemInfo) {
        const now = new Date();
        this._pruneSnapshots(this.memorySnapshots, now);
        const { memCurrentBytes } = systemInfo;
        const snapshot = {
            createdAt: now,
            isOverloaded: memCurrentBytes / this.maxMemoryBytes > this.maxUsedMemoryRatio,
            usedBytes: memCurrentBytes,
        };

        this.memorySnapshots.push(snapshot);
        this._memoryOverloadWarning(systemInfo);
    }

    /**
     * Creates a snapshot of current memory usage
     * using the Apify platform `systemInfo` event.
     * @param {Function} intervalCallback
     * @return {Promise<void>}
     * @ignore
     */
    async _snapshotMemoryOnLocal(intervalCallback) {
        try {
            const now = new Date();
            const memInfo = await getMemoryInfo();
            const { mainProcessBytes, childProcessesBytes } = memInfo;
            this._pruneSnapshots(this.memorySnapshots, now);

            const usedBytes = mainProcessBytes + childProcessesBytes;
            const snapshot = {
                createdAt: now,
                isOverloaded: usedBytes / this.maxMemoryBytes > this.maxUsedMemoryRatio,
                usedBytes,
            };

            this.memorySnapshots.push(snapshot);
        } catch (err) {
            log.exception(err, 'Snapshotter: Memory snapshot failed.');
        } finally {
            intervalCallback();
        }
    }

    /**
     * Checks for critical memory overload and logs it to the console.
     * @param {*} systemInfo
     * @ignore
     */
    _memoryOverloadWarning({ memCurrentBytes }) {
        const now = new Date();
        if (this.lastLoggedCriticalMemoryOverloadAt && now.getTime() < this.lastLoggedCriticalMemoryOverloadAt.getTime()
            + CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS) return;

        const maxDesiredMemoryBytes = this.maxUsedMemoryRatio * this.maxMemoryBytes;
        const reserveMemory = this.maxMemoryBytes * (1 - this.maxUsedMemoryRatio) * RESERVE_MEMORY_RATIO;
        const criticalOverloadBytes = maxDesiredMemoryBytes + reserveMemory;
        const isCriticalOverload = memCurrentBytes > criticalOverloadBytes;
        if (isCriticalOverload) {
            const usedPercentage = Math.round((memCurrentBytes / this.maxMemoryBytes) * 100);
            const toMb = bytes => Math.round(bytes / (1024 ** 2));
            log.warning('Memory is critically overloaded. '
                + `Using ${toMb(memCurrentBytes)} MB of ${toMb(this.maxMemoryBytes)} MB (${usedPercentage}%). Consider increasing the actor memory.`);
            this.lastLoggedCriticalMemoryOverloadAt = now;
        }
    }

    /**
     * Creates a snapshot of current event loop delay.
     * @param {Function} intervalCallback
     * @ignore
     */
    _snapshotEventLoop(intervalCallback) {
        const now = new Date();
        this._pruneSnapshots(this.eventLoopSnapshots, now);

        const snapshot = {
            createdAt: now,
            isOverloaded: false,
            exceededMillis: 0,
        };

        const previousSnapshot = this.eventLoopSnapshots[this.eventLoopSnapshots.length - 1];
        if (previousSnapshot) {
            const { createdAt } = previousSnapshot;
            const delta = now.getTime() - createdAt - this.eventLoopSnapshotIntervalMillis;

            if (delta > this.maxBlockedMillis) snapshot.isOverloaded = true;
            snapshot.exceededMillis = Math.max(delta - this.maxBlockedMillis, 0);
        }

        this.eventLoopSnapshots.push(snapshot);
        intervalCallback();
    }

    /**
     * Creates a snapshot of current CPU usage
     * using the Apify platform `systemInfo` event.
     * @param {Object} systemInfo
     * @ignore
     */
    _snapshotCpuOnPlatform(systemInfo) {
        const { cpuCurrentUsage, isCpuOverloaded } = systemInfo;
        const createdAt = (new Date(systemInfo.createdAt));
        this._pruneSnapshots(this.cpuSnapshots, createdAt);

        this.cpuSnapshots.push({
            createdAt,
            isOverloaded: isCpuOverloaded,
            usedRatio: Math.ceil(cpuCurrentUsage / 100),
        });
    }

    /**
     * Creates a snapshot of current CPU usage
     * using OS provided metrics.
     * @param {Function} intervalCallback
     * @ignore
     */
    _snapshotCpuOnLocal(intervalCallback) {
        const now = new Date();
        this._pruneSnapshots(this.eventLoopSnapshots, now);

        const ticks = this._getCurrentCpuTicks();
        const snapshot = {
            createdAt: now,
            isOverloaded: false,
            ticks,
            usedRatio: 0,
        };

        const previousSnapshot = this.cpuSnapshots[this.cpuSnapshots.length - 1];
        if (previousSnapshot) {
            const { ticks: prevTicks } = previousSnapshot;
            const idleTicksDelta = ticks.idle - prevTicks.idle;
            const totalTicksDelta = ticks.total - prevTicks.total;
            const usedCpuRatio = 1 - (idleTicksDelta / totalTicksDelta);

            if (usedCpuRatio > this.maxUsedCpuRatio) snapshot.isOverloaded = true;
            snapshot.usedRatio = Math.ceil(usedCpuRatio);
        }

        this.cpuSnapshots.push(snapshot);
        intervalCallback();
    }

    _getCurrentCpuTicks() { // eslint-disable-line class-methods-use-this
        const cpus = os.cpus();
        return cpus.reduce((acc, cpu) => {
            const cpuTimes = Object.values(cpu.times);
            return {
                idle: acc.idle + cpu.times.idle,
                total: acc.total + cpuTimes.reduce((sum, num) => sum + num),
            };
        }, { idle: 0, total: 0 });
    }

    /**
     * Creates a snapshot of current API state by checking for
     * rate limit errors. Only errors produced by a 2nd retry
     * of the API call are considered for snapshotting since
     * earlier errors may just be caused by a random spike in
     * number of requests and do not necessarily signify API
     * overloading.
     *
     * @param intervalCallback
     * @private
     */
    _snapshotClient(intervalCallback) {
        const now = new Date();
        this._pruneSnapshots(this.clientSnapshots, now);

        const allErrorCounts = apifyClient.stats.rateLimitErrors;
        const currentErrCount = allErrorCounts[CLIENT_RATE_LIMIT_ERROR_RETRY_COUNT] || 0;

        // Handle empty snapshots array
        const snapshot = {
            createdAt: now,
            isOverloaded: false,
            rateLimitErrorCount: currentErrCount,
        };
        const previousSnapshot = this.clientSnapshots[this.clientSnapshots.length - 1];
        if (previousSnapshot) {
            const { rateLimitErrorCount } = previousSnapshot;
            const delta = currentErrCount - rateLimitErrorCount;
            if (delta > this.maxClientErrors) snapshot.isOverloaded = true;
        }

        this.clientSnapshots.push(snapshot);
        intervalCallback();
    }

    /**
     * Removes snapshots that are older than the snapshotHistorySecs option
     * from the array (destructively - in place).
     * @param {Array<*>} snapshots
     * @param {Date} now
     * @ignore
     */
    _pruneSnapshots(snapshots, now) {
        let oldCount = 0;
        for (let i = 0; i < snapshots.length; i++) {
            const { createdAt } = snapshots[i];
            if (now.getTime() - createdAt > this.snapshotHistoryMillis) oldCount++;
            else break;
        }
        snapshots.splice(0, oldCount);
    }

    /**
     * Calculate max memory for platform or local usage.
     * @ignore
     */
    async _ensureCorrectMaxMemory() {
        if (this.maxMemoryBytes) return;
        const { totalBytes } = await getMemoryInfo();
        if (isAtHome()) {
            this.maxMemoryBytes = totalBytes;
        } else {
            this.maxMemoryBytes = Math.ceil(totalBytes / 4);
            // NOTE: Log as AutoscaledPool, so that users are not confused what "Snapshotter" is
            log.info(`AutoscaledPool: Setting max memory of this run to ${Math.round(this.maxMemoryBytes / 1024 / 1024)} MB. Use the ${ENV_VARS.MEMORY_MBYTES} environment variable to override it.`); // eslint-disable-line max-len
        }
    }
}

export default Snapshotter;


text:
'use strict';
// jshint -W124, -W106, -W101

/*
 * Dependencies
 */
import * as koa from 'koa';
import * as bodyParser from 'koa-bodyparser';
import * as render from 'koa-ejs';
import * as router from 'koa-router';
import * as request from 'co-request';
import * as chalk from 'chalk';
import {join} from 'path';
import {BitBucket, SemaphoreBadge} from './helper';

/*
 * Application
 */
var app = koa();
var port = (process.env.PORT) ? process.env.PORT : 8000;
render(app, {
  root: join(__dirname, '../views'),
  layout: false,
  viewExt: 'ejs',
  cache: true,
  debug: true
});

/*
 * Middlewares
 */
app.use(bodyParser());

var {BITBUCKET_USERNAME: bbUsername, BITBUCKET_PASSWORD: bbPassword} = process.env;
app.use(function*(next) {
  this.bitbucket = new BitBucket(bbUsername, bbPassword);
  yield next;
});

app.use(router(app));

/*
 * Routes
 */
app.get('/', function*() {
  yield this.render('index', {
    bbUsername: Boolean(bbUsername),
    bbPassword: Boolean(bbPassword),
    host: this.protocol + '://' + this.get('host'),
    isAuthenticated: yield this.bitbucket.isAuthenticated()
  });
});

app.post('/pull-request/:semaphoreProjectId/:semaphoreAuthToken', function*() {
  // Extract usefull values
  var pullRequest, pR = {}, sP = {};
  ({semaphoreProjectId: sP.projectId, semaphoreAuthToken: sP.authToken} = this.params);
  try {
    ({pullrequest_created: pullRequest} = this.request.body || {});
    ({id: pR.id,
      description: pR.description,
      source: {
        commit: {hash: pR.commitId},
        branch: {name: pR.branchName},
        repository: {full_name: pR.repoName}
      }
    } = pullRequest);
  } catch (error) {
    this.throw(400, 'Invalid Bitbucket hook data');
  }
  // If it doesn't already have Semaphore status at the start of the description, let's add it
  if (!pullRequest.description.contains('[![Semaphore Build Status')) {
    // Create Semaphore badge
    var badge = yield new SemaphoreBadge(sP.projectId, pR.branchName, pR.commitId, sP.authToken);
    pullRequest.description = `${badge}\r\n\r\n${pullRequest.description}`;
    // Post badge to BitBucket
    yield this.bitbucket.api(`/repositories/${pR.repoName}/pullrequests/${pR.id}`, 'PUT', pullRequest);
    this.status = 204;
  } else {
    this.status = 204;
  }
});

/*
 * Error handler
 */
app.on('error', function(error) {
  console.log(chalk.red(error.stack));
});

/*
 * Server
 */
var server = app.listen(port, function() {
  var host = server.address().address;
  console.log('Listening at http://%s:%s', host, port);
});


text:
title: Sponsor Flourish! 2014
slug: /sponsor/
---

#Sponsorship Information

Flourish is a free to attend conference and your donations
will help us a lot!

Thank you for your interest in sponsoring the Flourish! 2014 open source computing conference! The conference seeks to bring together some of the brightest developers and thinkers from the open source community to Chicago. We hope that through community-driven presentations, workshops, and other activities, we can all promote a feeling of interconnectedness and
inspire others.

The open source philosophy states that software source code should be free, easily shared, and available to anyone. This philosophy of openness has allowed for the creation of software such as the Linux operating system, the Firefox web browser, Wikipedia and the Apache web server. Presently, it has permeated almost every facet of the computing world, as well as attracted a variety of talented developers and progressive businesses into embracing the open source philosophy.

Started in 2006 by a group of computer hobbyists at the University of Illinois at Chicago, the Flourish! Conference was designed to fill a void in the open source community. For the past four years, the conference has attracted students, enthusiasts and the business community alike and has allowed them to connect, share ideas and discuss recent developments. This year, an even larger group of volunteers from all over the community has taken up the mantle to make the conference our best yet.

With your contribution, we can afford to create an amazing conference and, once again, bring together the vibrant Chicago open source community. As a sponsor, you'll be able to introduce yourself to the talent of the community and become a part of it.

We've included a guide of what you can expect with your donation along with this document. If you have questions or concerns, please contact the Flourish Organizers, by email at [info@flourishconf.com](mailto:info@flourishconf.com?Subject=Flourish%202014%20Sponsorship%20Information).

## What do I get with my donation?
We're glad you asked.  First of all, you will receive the gratitude and goodwill of the open source community, UIC students, and that warm fuzzy feeling that you've done something really really good.  But, of course, it doesn't stop there as we offer the following perks based on the amount of your generous donation.

### Bronze Level ($150 - $499)

- Logo is featured on the Flourish website
- You get a table on the conference mini expo floor to represent your organization
- Logo appears on conference program book in the back

### Silver Level ($500 - $999)

- Same as Bronze, plus:
- Your name and logo appear on all flyers, posters, t-shirts, and any other poromtional material

### Gold Level ($1000 - $1999)

- Same as Silver, plus:
- Approved material is placed at the registration table to be distributed to all attendees
- Half page advertisement in our program book

### Platinum Level ($2000 - $2999)

- Same as Gold, plus:
- A part of the conference will be sponsored by your company (For example: Lunch sponsored by [company])

### Diamond Level ($3000 and up)

- Same as Platinum, plus:
- Larger logo than lower sponsorship levels on all promotional materials

We will be happy to work with you in devising any "substitute" promotions if you find it in your company's best interest.

# Are you ready to sponsor Flourish?

<form action="sponsorship-proposal.php" method="GET">
<input type="submit" value="Submit a Sponsorship Proposal!"/>
</form>


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

/**
 * @author Guilherme Jacichen <gui_jaci@yahoo.com.br>
 */
public class Main {
    public static void main(String[] args) {
        List<Jogador> time = new ArrayList<>();

        Jogador achado;

        time.add(new Jogador(2, "Fulano"));
        time.add(new Jogador(7, "Beltrano"));
        time.add(new Jogador(14, "Ciclano"));
        time.add(new Jogador(5, "Peça"));
        time.add(new Jogador(16, "Escravo"));
        time.add(new Jogador(22, "Servo"));
        time.add(new Jogador(7, "Fugitivo"));
        time.add(new Jogador(19, "Mendigo"));

        for(Jogador jog : time)
            System.out.println(jog);

        System.out.println();
        time.sort(new JogadorComparator(true,false));

        for(Jogador jog : time)
            System.out.println(jog);

        achado = time.get(Collections.binarySearch(time, new Jogador(19, "Mendigo"), new JogadorComparator(true,false)));

        System.out.println(achado);
    }
}


text:
tailorSCAD
==========

A modest library to attempt to build SCAD based projects using configuration files.

A general overview is here

https://www.youtube.com/watch?v=XYstpSbyPak

The basic flow is

config A builds object A
config B uses object A when it builds Object B
config C uses A & B to build C etc.

You define a config file that allows your openscad files to be 'rendered' and then used elsewhere. Each config file also allows for optional parameters to be injected while you are rendering. This allows you to create small objects and then render them to STL using configurable parameters based on a defined config file. So, if you are using 3 different scad files in different repositories you can have a single config in one repository that will build STLs from the other repository and then make those stl's available to you in your repo, even if those files have conflicting variable names (an issue if you bring those scripts into your local project.


text:
import imaplib
import email
import email.header
import datetime
import re
import html_parse
import logging
log = logging.getLogger(__name__)

def navigate_content(content, level=0):
    ctype = content.get_content_type()
    cdispo = str(content.get('Content-Disposition'))
    log.info('{0} + {1} {2}'.format(' ' * level, ctype, cdispo))
    if content.is_multipart():
        for payload in content.get_payload():
            navigate_content(payload, level + 1)

def read_content(content):
    try:
        text = '++ No Content ++'
        if content.is_multipart():
            for part in content.walk():
                has_text, rtext = read_text(part)
                if has_text:
                    text = rtext
                    break
        else:
            has_text, rtext = read_text(content)
            if has_text:
                text = rtext
        return re.sub('[^\s!-~]', ' ', text.strip())
    except ImportWarning as err:
        log.warning(err.message)
        return '++ No HTML Parser Installed ++'
    except:
        log.exception('read_content')
        return '++ No Potatoes Error ++'

def read_text(content, prefer_plain_text = True):
    has_text = False
    text = ''
    ptype = content.get_content_type().split("/")
    if ptype[0] == 'text':
        bytes = content.get_payload(decode=True)
        charset = content.get_content_charset('iso-8859-1')
        text = bytes.decode(charset, 'replace')
        if ptype[1] == 'plain':
            has_text = True & prefer_plain_text
            if has_text:
                log.info('Read text/plain [' + charset + ']')
                log.debug(text)
        elif ptype[1] == 'html':
            has_text = False
            text = html_parse.parse(text)
            has_text = True
            log.info('Read text/html [' + charset + ']:\r\n')
            log.debug(text)
    return has_text, text

def read_subject(message):
    try:
        subject = email.header.decode_header(message['Subject'])[0]
        if subject[1] == None:
            actual_subject = unicode(subject[0])
        else:
            actual_subject = subject[0].decode(subject[1])
        return actual_subject
    except:
        log.exception('read_subject')
        return '++ Subject Error ++'

def read_date(message):
    try:
        date_tuple = email.utils.parsedate_tz(message['Date'])
        if date_tuple:
            local_date = datetime.datetime.fromtimestamp(
                email.utils.mktime_tz(date_tuple))
            return local_date.strftime('%a, %d %b %Y %H:%M:%S')
    except:
        return '++ Date Error ++'

def read_from(message):
    try:
        return str(email.header.make_header(email.header.decode_header(message['From'])))
    except:
        return ''

def read_message(mailbox, num, message_handler = None):
    response, data = mailbox.fetch(num, '(RFC822)')
    if response != 'OK':
        log.warning('Could not fetch message %s', num)
        return

    message = email.message_from_string(data[0][1])
    log.info('Message %s', num)
    log.info('Date: %s', message['Date'])
    log.info('Content:')
    navigate_content(message, 0)

    if message_handler != None:
        message_handler(
        read_from(message),
        read_date(message),
        read_subject(message),
        read_content(message))

def read_folder(mailbox, folder_name, message_handler = None):
    response, data = mailbox.select(folder_name)
    if response == 'OK':
        log.info('Processing %s folder...', folder_name)
        read_current_folder(mailbox, message_handler)
        mailbox.close()
        log.info('Processing complete')
    else:
        log.warning('Unable to open %s folder', folder_name)

def read_current_folder(mailbox, message_handler = None):

    response, data = mailbox.search(None, 'UNSEEN')
    if response != 'OK':
        log.warning('No messages found!')
        return

    for num in data[0].split():
        try:
            read_message(mailbox, num, message_handler)
        except:
            log.exception('Unable to read message %s', num)


text:
package com.opengamma.collect.id;

import static com.opengamma.collect.id.MockIdentifiable.MOCK1;
import static com.opengamma.collect.id.MockIdentifiable.MOCK1_RESOLVED_MOCK2;
import static com.opengamma.collect.id.MockIdentifiable.MOCK2;
import static com.opengamma.collect.id.MockIdentifiable.STANDARD_ID_2;
import static org.assertj.core.api.Assertions.assertThat;
import org.testng.annotations.Test;

import com.google.common.reflect.TypeToken;

/**
 * Tests for a link resolver.
 */
@Test
public class LinkResolverTest {

  private static final LinkResolver RESOLVER = new LinkResolver() {
    @SuppressWarnings("unchecked")
    @Override
    public <T extends IdentifiableBean> T resolve(StandardId identifier, TypeToken<T> targetType) {
      assertThat(identifier).isEqualTo(STANDARD_ID_2);
      assertThat(targetType).isEqualTo(TypeToken.of(MockIdentifiable.class));
      return (T) MOCK2;
    }
  };

  public void test_resolve_Class() {
    assertThat(RESOLVER.resolve(STANDARD_ID_2, MockIdentifiable.class)).isEqualTo(MOCK2);
  }

  public void test_resolve_TypeToken() {
    TypeToken<MockIdentifiable> token = TypeToken.of(MockIdentifiable.class);
    assertThat(RESOLVER.resolve(STANDARD_ID_2, token)).isSameAs(MOCK2);
  }

  public void test_resolveAll_notResolvable() {
    assertThat(RESOLVER.resolveLinksIn(MOCK1, "TargetIsNotResolvable", r -> r)).isSameAs(MOCK1);
  }

  public void test_resolveAll_targetIsResolvableAndNeedsResolving() {
    MockIdentifiable test = MockIdentifiable.MOCK1_LINKED_MOCK2.resolveLinks(RESOLVER);
    assertThat(test).isEqualTo(MOCK1_RESOLVED_MOCK2);
  }

  public void test_resolveAll_targetIsResolvableAndDoesNotNeedResolving() {
    MockIdentifiable test = MOCK1_RESOLVED_MOCK2.resolveLinks(RESOLVER);
    assertThat(test).isSameAs(MOCK1_RESOLVED_MOCK2);
  }

}


text:
'''
Created on 17 janv. 2014

@author: Alexandre Bonhomme
'''

'''
Basic agent which basically do : nothing
'''
class AgentBase(object):

    def __init__(self, x, y, sma):
        self.x = x
        self.y = y
        self.sma = sma
        self.age = 0

    def action(self):
        print("I'm a basic agent!")


text:
package freedomandy.exception

/**
  * Created by andy on 05/06/2017.
  */
case class BaseException(errorMsg: String) extends Exception(errorMsg) {
  def errorCode: String = "Interval Error"
  def httpStatusCode: Int = 500
}


text:
Overview
--------

The mod_wsgi package provides an Apache module that implements a WSGI
compliant interface for hosting Python based web applications on top of the
Apache web server.

The primary package for mod_wsgi is available on the Python package index
(PyPi) as ``mod_wsgi``. That package assumes that you have a suitable
version of Apache pre-installed on your target system, and if you don't,
installation of the package will fail.

If you are on a UNIX like system (Linux, macOS) and need a version of
Apache to be installed for you, you can use the ``mod_wsgi-standalone``
package on PyPi instead. When installing the ``mod_wsgi-standalone``
package it will first trigger the installation of the ``mod_wsgi-httpd``
package, which will result in a version of Apache being installed as
part of your Python installation. Next the ``mod_wsgi`` package will be
installed, with it using the version of Apache installed by the
``mod_wsgi-httpd`` package rather than any system package for Apache.

Note that this method of installation is only suitable for where you want
to use ``mod_wsgi-expres``. It cannot be used to build mod_wsgi for use
with your system Apache installation. This installation method will also
not work on Windows.

When installing mod_wsgi using this method, except that you will install
the ``mod_wsgi-standalone`` package instead of the ``mod_wsgi`` package,
you should follow installation and usage instructions outlined on the
PyPi page for the ``mod_wsgi`` package.


text:
package rx.internal.operators;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.observers.TestSubscriber;

public class OperatorIgnoreElementsTest {

    @Test
    public void testWithEmpty() {
        assertTrue(Observable.empty().ignoreElements().isEmpty().toBlocking().single());
    }

    @Test
    public void testWithNonEmpty() {
        assertTrue(Observable.just(1, 2, 3).ignoreElements().isEmpty().toBlocking().single());
    }

    @Test
    public void testUpstreamIsProcessedButIgnored() {
        final int num = 10;
        final AtomicInteger upstreamCount = new AtomicInteger();
        int count = Observable.range(1, num)
                .doOnNext(new Action1<Integer>() {
                    @Override
                    public void call(Integer t) {
                        upstreamCount.incrementAndGet();
                    }
                })
                .ignoreElements()
                .count().toBlocking().single();
        assertEquals(num, upstreamCount.get());
        assertEquals(0, count);
    }

    @Test
    public void testCompletedOk() {
        TestSubscriber<Object> ts = new TestSubscriber<Object>();
        Observable.range(1, 10).ignoreElements().subscribe(ts);
        ts.assertNoErrors();
        ts.assertReceivedOnNext(Arrays.asList());
        ts.assertTerminalEvent();
        ts.assertUnsubscribed();
    }

    @Test
    public void testErrorReceived() {
        TestSubscriber<Object> ts = new TestSubscriber<Object>();
        RuntimeException ex = new RuntimeException("boo");
        Observable.error(ex).ignoreElements().subscribe(ts);
        ts.assertReceivedOnNext(Arrays.asList());
        ts.assertTerminalEvent();
        ts.assertUnsubscribed();
        assertEquals(1, ts.getOnErrorEvents().size());
        assertEquals("boo", ts.getOnErrorEvents().get(0).getMessage());
    }

    @Test
    public void testUnsubscribesFromUpstream() {
        final AtomicBoolean unsub = new AtomicBoolean();
        Observable.range(1, 10).doOnUnsubscribe(new Action0() {
            @Override
            public void call() {
                unsub.set(true);
            }})
            .subscribe();
        assertTrue(unsub.get());
    }

    @Test(timeout = 10000)
    public void testDoesNotHangAndProcessesAllUsingBackpressure() {
        final AtomicInteger upstreamCount = new AtomicInteger();
        final AtomicInteger count = new AtomicInteger(0);
        int num = 10;
        Observable.range(1, num)
        //
                .doOnNext(new Action1<Integer>() {
                    @Override
                    public void call(Integer t) {
                        upstreamCount.incrementAndGet();
                    }
                })
                //
                .ignoreElements()
                //
                .doOnNext(new Action1<Integer>() {

                    @Override
                    public void call(Integer t) {
                        upstreamCount.incrementAndGet();
                    }
                })
                //
                .subscribe(new Subscriber<Integer>() {

                    @Override
                    public void onStart() {
                        request(1);
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Integer t) {
                        count.incrementAndGet();
                    }
                });
        assertEquals(num, upstreamCount.get());
        assertEquals(0, count.get());
    }

}


text:
#ifndef __VX_CONVOLUTION_H__
#define __VX_CONVOLUTION_H__

#include "vxParameter.h"
#include "vxParamHelper.h"
#include "vxUtils.h"

class CVxParamConvolution : public CVxParameter
{
public:
	CVxParamConvolution();
	virtual ~CVxParamConvolution();
	virtual int Initialize(vx_context context, vx_graph graph, const char * desc);
	virtual int InitializeIO(vx_context context, vx_graph graph, vx_reference ref, const char * io_params);
	virtual int Finalize();
	virtual int ReadFrame(int frameNumber);
	virtual int WriteFrame(int frameNumber);
	virtual int CompareFrame(int frameNumber);
	virtual int Shutdown();

private:
	// vx configuration
	vx_size m_columns;
	vx_size m_rows;
	vx_uint32 m_scale;
	// I/O configuration
	bool m_readFileIsBinary;
	bool m_writeFileIsBinary;
	bool m_compareFileIsBinary;
	bool m_readFileWithScale;
	bool m_writeFileWithScale;
	bool m_compareFileWithScale;
	int m_compareCountMatches;
	int m_compareCountMismatches;
	vx_int16 * m_bufForAccess;
	// vx object
	vx_convolution m_convolution;
};

#endif /* __VX_CONVOLUTION_H__ */


text:
require 'dfp_api'

def get_all_creatives(dfp)
  # Get the CreativeService.
  creative_service = dfp.service(:CreativeService, API_VERSION)

  # Create a statement to select creatives.
  statement = dfp.new_statement_builder()

  # Retrieve a small amount of creatives at a time, paging
  # through until all creatives have been retrieved.
  page = {:total_result_set_size => 0}
  begin
    page = creative_service.get_creatives_by_statement(
        statement.to_statement()
    )

    # Print out some information for each creative.
    unless page[:results].nil?
      page[:results].each_with_index do |creative, index|
        puts '%d) Creative with ID %d and name "%s" was found.' %
            [index + statement.offset, creative[:id], creative[:name]]
      end
    end

    # Increase the statement offset by the page size to get the next page.
    statement.offset += statement.limit
  end while statement.offset < page[:total_result_set_size]

  puts 'Total number of creatives: %d' % page[:total_result_set_size]
end

if __FILE__ == $0
  API_VERSION = :v201802

  # Get DfpApi instance and load configuration from ~/dfp_api.yml.
  dfp = DfpApi::Api.new

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # dfp.logger = Logger.new('dfp_xml.log')

  begin
    get_all_creatives(dfp)

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue DfpApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end


text:
#ifndef ZC_GESCL3D_H
#define ZC_GESCL3D_H

#include "zadesk.h"
#include "zgegbl.h"
#pragma pack (push, 8)

class ZcGeMatrix3d;

class
GE_DLLEXPIMPORT
ZcGeScale3d
{
public:
    ZcGeScale3d();
    ZcGeScale3d(const ZcGeScale3d& src);
    ZcGeScale3d(double factor);
    ZcGeScale3d(double xFact, double yFact, double zFact);

    static const   ZcGeScale3d kIdentity;

    ZcGeScale3d    operator *  (const ZcGeScale3d& sclVec) const;
    ZcGeScale3d&   operator *= (const ZcGeScale3d& scl);
    ZcGeScale3d&   preMultBy   (const ZcGeScale3d& leftSide);
    ZcGeScale3d&   postMultBy  (const ZcGeScale3d& rightSide);
    ZcGeScale3d&   setToProduct(const ZcGeScale3d& sclVec1, const ZcGeScale3d& sclVec2);
    ZcGeScale3d    operator *  (double s) const;
    ZcGeScale3d&   operator *= (double s);
    ZcGeScale3d&   setToProduct(const ZcGeScale3d& sclVec, double s);
    friend
GE_DLLEXPIMPORT
    ZcGeScale3d    operator *  (double, const ZcGeScale3d& scl);

    ZcGeScale3d    inverse        () const;
    ZcGeScale3d&   invert         ();

    ZSoft::Boolean isProportional(const ZcGeTol& tol = ZcGeContext::gTol) const;

    bool operator == (const ZcGeScale3d& sclVec) const;
    bool operator != (const ZcGeScale3d& sclVec) const;
    bool isEqualTo   (const ZcGeScale3d& scaleVec,
                                const ZcGeTol& tol = ZcGeContext::gTol) const;

    double         operator [] (unsigned int i) const;
    double&        operator [] (unsigned int i);
    ZcGeScale3d&   set         (double sc0, double sc1, double sc2);

    operator       ZcGeMatrix3d   () const;
    void getMatrix(ZcGeMatrix3d& mat) const;
    ZcGeScale3d&   extractScale   ( const ZcGeMatrix3d& mat );
    ZcGeScale3d&   removeScale    ( ZcGeMatrix3d& mat );

    double         sx, sy, sz;
};

__forceinline bool
ZcGeScale3d::operator == (const ZcGeScale3d& s) const
{
    return this->isEqualTo(s);
}

__forceinline bool
ZcGeScale3d::operator != (const ZcGeScale3d& s) const
{
    return !(this->isEqualTo(s));
}

__forceinline double
ZcGeScale3d::operator [] (unsigned int i) const
{
    return *(&sx+i);
}

__forceinline double&
ZcGeScale3d::operator [] (unsigned int i)
{
    return *(&sx+i);
}

#pragma pack (pop)
#endif


text:
/**
 * @constructor
 * @implements {WebInspector.CSSSourceMapping}
 * @param {!WebInspector.CSSModel} cssModel
 * @param {!WebInspector.NetworkMapping} networkMapping
 * @param {!WebInspector.NetworkProject} networkProject
 */
WebInspector.SASSSourceMapping = function(cssModel, networkMapping, networkProject)
{
    this._cssModel = cssModel;
    this._networkProject = networkProject;
    this._networkMapping = networkMapping;
    this._cssModel.addEventListener(WebInspector.CSSModel.Events.SourceMapAttached, this._sourceMapAttached, this);
    this._cssModel.addEventListener(WebInspector.CSSModel.Events.SourceMapDetached, this._sourceMapDetached, this);
    this._cssModel.addEventListener(WebInspector.CSSModel.Events.SourceMapChanged, this._sourceMapChanged, this);
}

WebInspector.SASSSourceMapping.prototype = {
    /**
     * @param {!WebInspector.Event} event
     */
    _sourceMapAttached: function(event)
    {
        var header = /** @type {!WebInspector.CSSStyleSheetHeader} */ (event.data);
        var sourceMap = this._cssModel.sourceMapForHeader(header);
        for (var sassURL of sourceMap.sourceURLs()) {
            if (!this._networkMapping.hasMappingForNetworkURL(sassURL)) {
                var contentProvider = sourceMap.sourceContentProvider(sassURL, WebInspector.resourceTypes.SourceMapStyleSheet);
                this._networkProject.addFile(contentProvider, WebInspector.ResourceTreeFrame.fromStyleSheet(header));
            }
        }
        WebInspector.cssWorkspaceBinding.updateLocations(header);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _sourceMapDetached: function(event)
    {
        var header = /** @type {!WebInspector.CSSStyleSheetHeader} */(event.data);
        WebInspector.cssWorkspaceBinding.updateLocations(header);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _sourceMapChanged: function(event)
    {
        var sourceMap = /** @type {!WebInspector.SourceMap} */(event.data.sourceMap);
        var newSources = /** @type {!Map<string, string>} */(event.data.newSources);
        var headers = this._cssModel.headersForSourceMap(sourceMap);
        var handledUISourceCodes = new Set();
        for (var header of headers) {
            WebInspector.cssWorkspaceBinding.updateLocations(header);
            for (var sourceURL of newSources.keys()) {
                var uiSourceCode = this._networkMapping.uiSourceCodeForStyleURL(sourceURL, header);
                if (!uiSourceCode) {
                    console.error("Failed to update source for " + sourceURL);
                    continue;
                }
                if (handledUISourceCodes.has(uiSourceCode))
                    continue;
                handledUISourceCodes.add(uiSourceCode);
                var sassText = /** @type {string} */(newSources.get(sourceURL));
                uiSourceCode.setWorkingCopy(sassText);
            }
        }
    },

    /**
     * @param {!WebInspector.CSSStyleSheetHeader} header
     */
    addHeader: function(header)
    {
        if (!header.sourceMapURL)
            return;
        WebInspector.cssWorkspaceBinding.pushSourceMapping(header, this);
    },

    /**
     * @param {!WebInspector.CSSStyleSheetHeader} header
     */
    removeHeader: function(header)
    {
        if (!header.sourceMapURL)
            return;
        WebInspector.cssWorkspaceBinding.updateLocations(header);
    },

    /**
     * @override
     * @param {!WebInspector.CSSLocation} rawLocation
     * @return {?WebInspector.UILocation}
     */
    rawLocationToUILocation: function(rawLocation)
    {
        var sourceMap = this._cssModel.sourceMapForHeader(rawLocation.header());
        if (!sourceMap)
            return null;
        var entry = sourceMap.findEntry(rawLocation.lineNumber, rawLocation.columnNumber);
        if (!entry || !entry.sourceURL)
            return null;
        var uiSourceCode = this._networkMapping.uiSourceCodeForStyleURL(entry.sourceURL, rawLocation.header());
        if (!uiSourceCode)
            return null;
        return uiSourceCode.uiLocation(entry.sourceLineNumber || 0, entry.sourceColumnNumber);
    },

    /**
     * @override
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @param {number} columnNumber
     * @return {?WebInspector.CSSLocation}
     */
    uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber)
    {
        return null;
    },

    /**
     * @override
     * @return {boolean}
     */
    isIdentity: function()
    {
        return false;
    },

    /**
     * @override
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @return {boolean}
     */
    uiLineHasMapping: function(uiSourceCode, lineNumber)
    {
        return true;
    },

    /**
     * @return {!WebInspector.Target}
     */
    target: function()
    {
        return this._cssModel.target();
    }
}


text:
package com.cw.jerrbase.util.form;

import android.content.Context;
import android.widget.EditText;
import android.widget.Toast;

import com.andreabaccega.widget.FormEditText;
import com.cw.jerrbase.util.QMUtil;

import java.util.regex.Pattern;

/**
 * @version V1.0
 * @ClassName: ${CLASS_NAME}
 * @Description: (表单验证)
 * @create by: chenwei
 * @date 2016/10/11 11:51
 */
public class FormUtils {

    /**
     * 验证所有表单
     *
     * @param formEditTexts
     * @return
     */
    public static boolean validate(FormEditText... formEditTexts) {
        boolean allValid = true;
        for (FormEditText fet : formEditTexts) {
            allValid = fet.testValidity() && allValid;
        }
        return allValid;
    }

    /**
     * 验证所有表单是否为空
     *
     * @param mContext
     * @param errors    错误信息
     * @param editTexts 要验证的EditText
     * @return 有一个为空返回true,全都不为空返回false
     */
    public static boolean validate(Context mContext, String[] errors, EditText... editTexts) {
        for (int i = 0; i < editTexts.length; i++) {
            EditText et = editTexts[i];
            if (QMUtil.isEmpty(et.getText().toString().trim())) {
                Toast.makeText(mContext, errors[i] + "不能为空", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;
    }

    /**
     * 正则表达式验证所有表单(提示信息为 "错误信息"+ "格式不正确")
     *
     * @param mContext
     * @param regexs    正则表达式
     * @param errors    错误信息
     * @param editTexts 要验证的EditText
     * @return 有一个验证失败返回true,全都都验证成功返回false
     */
    public static boolean validate(Context mContext, String[] regexs, String[] errors, EditText... editTexts) {
        for (int i = 0; i < editTexts.length; i++) {
            EditText et = editTexts[i];
            if (!Pattern.matches(regexs[i], et.getText().toString().trim())) {
                Toast.makeText(mContext, errors[i] + "格式不正确", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;
    }

    /**
     * 正则表达式验证所有表单(提示信息为 "错误信息")
     *
     * @param mContext
     * @param regexs    正则表达式
     * @param errors    错误信息
     * @param editTexts 要验证的EditText
     * @return 有一个验证失败返回true,全都都验证成功返回false
     */
    public static boolean validateAll(Context mContext, String[] regexs, String[] errors, EditText... editTexts) {
        for (int i = 0; i < editTexts.length; i++) {
            EditText et = editTexts[i];
            if (!Pattern.matches(regexs[i], et.getText().toString().trim())) {
                Toast.makeText(mContext, errors[i], Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;
    }
}


text:
Welcome to the 6th exercise in the **React Native Track** of this Apollo Client Tutorial!

## Goal

The **goal** of this exercise is to add the possibility to update and delete existing pokemons:

![](../images/react-native-exercise-06-pokemonpage.png)

This will both let you increase your understanding of mutations as well as show you how you can add multiple mutations to the same component.

## Introduction

Change to the 6th exercise and install the dependencies from your console:

```sh
cd pokedex-react/exercise-06
yarn install # or npm install
```

## Updating and deleting pokemons

Let's use what we learned about mutations in the last exercise to start using the `updatePokemon` and `deletePokemon` mutations.
You will add an update and a delete button to the `PokemonCard` component that call the according mutation when clicked. Let's get started then!

### Changes to `PokemonCard`

We already prepared some changes to the `PokemonCard` component and updated `PokemonPage` accordingly. Let's have a closer look at `PokemonCard`. First of all, we introduced `name` and `url` as part of the component's state:

```js
state = {
  name: this.props.pokemon.name,
  url: this.props.pokemon.url,
}
```

The state gets initialized with the passed props and `onChangeText` events for the two new `TextInput` elements update the according part of the state:

```js
<View>
  <TextInput
    style={{
      padding: 20,
      height: 60,
      fontFamily: 'HelveticaNeue-Light',
    }}
    onChangeText={(name) => this.setState({name})}
    value={this.state.name}
    placeholder='Type a name...'
  />
  <TextInput
    style={{
      padding: 20,
      height: 60,
      fontFamily: 'HelveticaNeue-Light',
    }}
    onChangeText={(url) => this.setState({url})}
    value={this.state.url}
    placeholder='Image Url'
  />
</View>
```

The update and delete buttons were added:

```js
<View
  style={{
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 12
  }}
>
  <Button
    title='Delete'
    onPress={this.handleDelete}
    color='red'
  />
  {updateButton}
</View>
```

The `updateButton` is only shown if the input fields have updated values:

```js
let updateButton = null
if (this.canUpdate()) {
  updateButton = <Button
    title='Update'
    onPress={this.handleUpdate}
  />
}
```

However, you have to implement the `handleUpdate` and `handleDelete` methods yourself. Before that, let us define the required mutations together. As both mutations need the `id` of the pokemon, we have to update the `pokemon` fragment in the `PokemonCard` by adding the `id`:

```js@components/PokemonCard.js
static fragments = {
  pokemon: gql`
    fragment PokemonCardPokemon on Pokemon {
      id
      url
      name
    }
  `
}
```

### The `updatePokemon` mutation

We want to be able to update pokemon names and image URLs. That's why we make use of `updatePokemon` and its arguments `name` and `url`. Add this mutation to the `PokemonCard`:

```js@components/PokemonCard.js
const updatePokemon = gql`
  mutation updatePokemon($id: ID!, $name: String!, $url: String!) {
    updatePokemon(id: $id, name: $name, url: $url) {
      id
      name
      url
    }
  }
`
```

You can also use fragments in mutations the same way you do in queries. We could write the `updatePokemon` mutation like this as well:

```js
const updatePokemon = gql`
  mutation updatePokemon($id: ID!, $name: String!, $url: String!) {
    updatePokemon(id: $id, name: $name, url: $url) {
      id
      ... PokemonCardPokemon
    }
  }
  ${PokemonCard.fragments.pokemon}
`
```

We included the `id` in the query selection for good measure, even though it is already included in the `PokemonCardPokemon` fragment.

Let's now think about the `deletePokemon` mutation before we will use both mutations and inject them to `PokemonCard`.

### The `deletePokemon` mutation

The `deletePokemon` mutation only needs the `id` pokemon to delete it. Add it to `PokemonCard` as well:

```js@components/PokemonCard.js
const deletePokemon = gql`
  mutation deletePokemon($id: ID!) {
    deletePokemon(id: $id) {
      id
    }
  }
`
```

### Combining multiple mutations when wrapping components

Now it's time for you to inject these mutations to `PokemonCard`. By default, injected mutations are accessible with `this.props.mutate`. But how can we inject multiple mutations? We simply provide a `name` option:

```js@components/PokemonCard.js
const PokemonCardWithMutations =  graphql(deletePokemon, {name : 'deletePokemon'})(
  graphql(updatePokemon, {name: 'updatePokemon'})(PokemonCard)
)

export default PokemonCardWithMutations
```

This results in the two new props `updatePokemon` and `deletePokemon`, so let's reflect that when defining the `propTypes`:

```js@components/PokemonCard.js
static propTypes = {
  pokemon: propType(pokemonCardFragments.pokemon).isRequired,
  updatePokemon: React.PropTypes.func.isRequired,
  deletePokemon: React.PropTypes.func.isRequired,
}
```

### Connect the buttons with the mutations

Finally, you can now call the mutations from within the `onClick` of the buttons:

```js@components/PokemonCard.js
handleUpdate = async () => {
  await this.props.updatePokemon({variables: { id: this.props.pokemon.id, name: this.state.name, url: this.state.url }})

  Actions.pokedex()
}

handleDelete = async () => {
  await this.props.deletePokemon({variables: { id: this.props.pokemon.id }})

  Actions.pokedex()
}
```

Again, we are making use of the promise returned by the mutations to call another function after the mutation results came in.

Check if you got everthing right by running the app:

```sh
yarn start
```

Click on an existing pokemon button. Update one of its attributes and click the update button. You should get back to the updated pokemon list. Repeat the same but this time delete the pokemon.

## Force fetching for a consistent UI

If you played around a bit with deleting pokemons, you will notice that it is only reflected in our UI after we refresh the page.
We already saw this issue in the last exercise with the creation of pokemons and fixed it by telling the Apollo Store how to uniquely identify objects in our application, namely by their `id` field. We also included the `Trainer` object in the mutation response of `createPokemon`:

```js
const createPokemonMutation = gql`
  mutation createPokemon($name: String!, $url: String!, $trainerId: ID) {
    createPokemon(name: $name, url: $url, trainerId: $trainerId) {
      trainer {
        id
        ownedPokemons {
          id
        }
      }
    }
  }
`
```

What this does, is telling Apollo Client to refetch the trainer object and all its related pokemons whenever we create a new pokemon. Apollo Store identifies the trainer object by its `id` and it basically merges the known pokemons with all the pokemons in the mutation response. Even though this is highly inefficient, this works in our example.

Now the question is, if we can use the same logic for the deletion of pokemons. What if we changed the `deleteMutation` to also query the trainer and all its pokemons after the deletion of a pokemon?

```js
const deletePokemon = gql`
  mutation deletePokemon($id: ID!) {
    deletePokemon(id: $id) {
      trainer {
        id
        ownedPokemons {
          id
        }
      }
    }
  }
`
```

As before, Apollo Client will merge the previously known pokemons with the pokemons in this mutation response. As the previous known pokemons already contain the now deleted pokemons, the pokemon will still be in the Apollo's store after this deletion. As things like filters on fields exist, there is no way for Apollo to know that in our case, we are fetching all the pokemon ids there are and not only a subset. A quick fix to make things work, is to force fetch the trainer object whenever the pokedex is being rendered. The `fetchPolicy: 'cache-and-network'` option tells Apollo to first return the result from cache (if it exists), and then return the network result once it's available.

To do this, head over to the `Pokedex` component in `components/Pokedex.js` again and add the `fetchPolicy: 'cache-and-network'` option to the options of the query:

```js@components/Pokedex.js
const PokedexWithData = graphql(TrainerQuery, {
  options: {
    variables: {
      name: '__NAME__'
    },
    fetchPolicy: 'cache-and-network',
  }
})(Pokedex)

export default PokedexWithData
```

Now we can also get rid of fetching the trainer object in `AddPokemonCard` in `components/AddPokemonCard.js` after creating a new pokemon:

```js@components/AddPokemonCard.js
const createPokemonMutation = gql`
  mutation createPokemon($name: String!, $url: String!, $trainerId: ID) {
    createPokemon(name: $name, url: $url, trainerId: $trainerId) {
      id
    }
  }
`
```

To learn more about handling the Apollo Store and get to know more efficient ways of handling situations like these, check out [the excursion on managing Apollo store](/excursions/excursion-02).

## Recap

* We saw how we can **update and delete** pokemons using mutations
* **Injecting multiple mutations** is possible by using the `name` option
* We learned a bit about how **caching** works with Apollo Client and used **force fetching** for a consistent but inefficient UI when creating or deleting nodes


text:
layout: page
title: "Philip Matthew Pendergast"
comments: true
description: "blanks"
keywords: "Philip Matthew Pendergast,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: SOCY 2061, SOCY 4084

#### SOCY 2061: Introduction to Social Statistics

**Terms taught**: Spring 2015

**Instructor rating**: 5.58

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.28

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.45

**Standard deviation in workload** (raw): 0.0

#### SOCY 4084: Punishment, Law and Society

**Terms taught**: Fall 2015, Spring 2016

**Instructor rating**: 5.6

**Standard deviation in instructor rating**: 0.21

**Average grade** (4.0 scale): 3.15

**Standard deviation in grades** (4.0 scale): 0.11

**Average workload** (raw): 2.59

**Standard deviation in workload** (raw): 0.15