text:
package it.geosolutions.jaiext.bandmerge;

import java.awt.image.DataBuffer;
import java.awt.image.RenderedImage;
import java.util.Vector;
import javax.media.jai.JAI;
import javax.media.jai.ParameterBlockJAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;
import javax.media.jai.TiledImage;

import org.junit.BeforeClass;
import org.junit.Test;

import it.geosolutions.jaiext.JAIExt;
import it.geosolutions.jaiext.range.Range;
import it.geosolutions.jaiext.range.RangeFactory;
import it.geosolutions.jaiext.testclasses.TestBase;

/**
 * This test class is used for compare the timing between the new BandMerge operation and the its old Jai version. NoData range can be used by setting
 * to true the JAI.Ext.RangeUsed JVM boolean parameters. If the user wants to change the number of the benchmark cycles or of the not benchmark
 * cycles, should only pass the new values to the JAI.Ext.BenchmarkCycles or JAI.Ext.NotBenchmarkCycles parameters.If the user want to use the Jai
 * BandMerge operation must pass to the JVM the JAI.Ext.OldDescriptor parameter set to true. For selecting a specific data type the user must set the
 * JAI.Ext.TestSelector JVM integer parameter to a number between 0 and 5 (where 0 means byte, 1 Ushort, 2 Short, 3 Integer, 4 Float and 5 Double).
 * The test is made on a group of 4 images.
 */
public class ComparisonTest extends TestBase {

    /** Number of benchmark iterations (Default 1) */
    private final static Integer BENCHMARK_ITERATION = Integer.getInteger(
            "JAI.Ext.BenchmarkCycles", 1);

    /** Number of not benchmark iterations (Default 0) */
    private final static int NOT_BENCHMARK_ITERATION = Integer.getInteger(
            "JAI.Ext.NotBenchmarkCycles", 0);

    /** Boolean indicating if the old descriptor must be used */
    private final static boolean OLD_DESCRIPTOR = Boolean.getBoolean("JAI.Ext.OldDescriptor");

    /** Boolean indicating if a No Data Range must be used */
    private final static boolean RANGE_USED = Boolean.getBoolean("JAI.Ext.RangeUsed");

    /** Final image band number */
    private static final int BAND_NUMBER = 4;

    /** Source test image */
    private static RenderedImage[] testImage;

    /** No Data Range for Byte */
    private static Range[] rangeND;

    /** Destination No Data value */
    private static double destNoData;

    // Initial static method for preparing all the test data
    @BeforeClass
    public static void initialSetup() {
        // Setting of the image filler parameter to true for a better image creation
        IMAGE_FILLER = true;
        // Images initialization values
        byte noDataB = 100;
        short noDataUS = 100;
        short noDataS = 100;
        int noDataI = 100;
        float noDataF = 100;
        double noDataD = 100;

        RenderedImage image;

        testImage = new RenderedImage[BAND_NUMBER];

        // Image creations
        switch (TEST_SELECTOR) {
        case DataBuffer.TYPE_BYTE:
            image = createTestImage(DataBuffer.TYPE_BYTE, DEFAULT_WIDTH, DEFAULT_HEIGHT, noDataB,
                    false, 1);
            for (int i = 0; i < BAND_NUMBER; i++) {
                testImage[i] = image;
            }
            break;
        case DataBuffer.TYPE_USHORT:
            image = createTestImage(DataBuffer.TYPE_USHORT, DEFAULT_WIDTH, DEFAULT_HEIGHT,
                    noDataUS, false, 1);
            for (int i = 0; i < BAND_NUMBER; i++) {
                testImage[i] = image;
            }
            break;
        case DataBuffer.TYPE_SHORT:
            image = createTestImage(DataBuffer.TYPE_SHORT, DEFAULT_WIDTH, DEFAULT_HEIGHT, noDataS,
                    false, 1);
            for (int i = 0; i < BAND_NUMBER; i++) {
                testImage[i] = image;
            }
            break;
        case DataBuffer.TYPE_INT:
            image = createTestImage(DataBuffer.TYPE_INT, DEFAULT_WIDTH, DEFAULT_HEIGHT, noDataI,
                    false, 1);
            for (int i = 0; i < BAND_NUMBER; i++) {
                testImage[i] = image;
            }
            break;
        case DataBuffer.TYPE_FLOAT:
            image = createTestImage(DataBuffer.TYPE_FLOAT, DEFAULT_WIDTH, DEFAULT_HEIGHT, noDataF,
                    false, 1);
            for (int i = 0; i < BAND_NUMBER; i++) {
                testImage[i] = image;
            }
            break;
        case DataBuffer.TYPE_DOUBLE:
            image = createTestImage(DataBuffer.TYPE_DOUBLE, DEFAULT_WIDTH, DEFAULT_HEIGHT, noDataD,
                    false, 1);
            for (int i = 0; i < BAND_NUMBER; i++) {
                testImage[i] = image;
            }
            break;
        default:
            throw new IllegalArgumentException("Wrong data type");
        }
        // Image filler must be reset
        IMAGE_FILLER = false;

        // Range creation if selected
        if (RANGE_USED) {
            switch (TEST_SELECTOR) {
            case DataBuffer.TYPE_BYTE:
                rangeND = new Range[] { RangeFactory.create(noDataB, true, noDataB, true) };
                break;
            case DataBuffer.TYPE_USHORT:
                rangeND = new Range[] { RangeFactory.createU(noDataUS, true, noDataUS, true) };
                break;
            case DataBuffer.TYPE_SHORT:
                rangeND = new Range[] { RangeFactory.create(noDataS, true, noDataS, true) };
                break;
            case DataBuffer.TYPE_INT:
                rangeND = new Range[] { RangeFactory.create(noDataI, true, noDataI, true) };
                break;
            case DataBuffer.TYPE_FLOAT:
                rangeND = new Range[] { RangeFactory.create(noDataF, true, noDataF, true, true) };
                break;
            case DataBuffer.TYPE_DOUBLE:
                rangeND = new Range[] { RangeFactory.create(noDataD, true, noDataD, true, true) };
                break;
            default:
                throw new IllegalArgumentException("Wrong data type");
            }
        }

        // Destination No Data
        destNoData = 50d;

    }

    // General method for showing calculation time of the 2 ZonalStats operators
    @Test
    public void testBandMergeDescriptor() {
        // Image data types
        int dataType = TEST_SELECTOR;

        // Descriptor string
        String description = "\n ";
        // String for final output
        String stat = "BandMerge";

        if (OLD_DESCRIPTOR) {
            description = "Old " + stat;
        } else {
            description = "New " + stat;
        }

        // Data type string
        String dataTypeString = "";

        switch (dataType) {
        case DataBuffer.TYPE_BYTE:
            dataTypeString += "Byte";
            break;
        case DataBuffer.TYPE_USHORT:
            dataTypeString += "UShort";
            break;
        case DataBuffer.TYPE_SHORT:
            dataTypeString += "Short";
            break;
        case DataBuffer.TYPE_INT:
            dataTypeString += "Integer";
            break;
        case DataBuffer.TYPE_FLOAT:
            dataTypeString += "Float";
            break;
        case DataBuffer.TYPE_DOUBLE:
            dataTypeString += "Double";
            break;
        default:
            throw new IllegalArgumentException("Wrong data type");
        }

        // Total cycles number
        int totalCycles = BENCHMARK_ITERATION + NOT_BENCHMARK_ITERATION;
        // PlanarImage
        PlanarImage imageMerged = null;
        // Initialization of the statistics
        long mean = 0;
        long max = Long.MIN_VALUE;
        long min = Long.MAX_VALUE;

        // Vector of sources (used for Old BandMerge operation)
        Vector vec = new Vector(testImage.length);

        for (RenderedImage img : testImage) {
            vec.add(img);
        }

        ParameterBlockJAI pbj = new ParameterBlockJAI("bandmerge");
        pbj.setSources(vec);

        // Cycle for calculating the mean, maximum and minimum calculation time
        for (int i = 0; i < totalCycles; i++) {

            // creation of the image with the selected descriptor

            if (OLD_DESCRIPTOR) {
                JAIExt.registerJAIDescriptor("bandmerge");
                // Old descriptor calculations
                imageMerged = JAI.create("bandmerge", pbj, null);
            } else {
                // New descriptor calculations
                imageMerged = BandMergeDescriptor.create(rangeND, destNoData, false, null, testImage);
            }

            // Total statistic calculation time
            long start;
            long end;
            start = System.nanoTime();
            imageMerged.getTiles();
            end = System.nanoTime() - start;

            // If the the first NOT_BENCHMARK_ITERATION cycles has been done, then the mean, maximum and minimum values are stored
            if (i > NOT_BENCHMARK_ITERATION - 1) {
                if (i == NOT_BENCHMARK_ITERATION) {
                    mean = end;
                } else {
                    mean = mean + end;
                }

                if (end > max) {
                    max = end;
                }

                if (end < min) {
                    min = end;
                }
            }
            // For every cycle the cache is flushed such that all the tiles must be recalculated
            JAI.getDefaultInstance().getTileCache().flush();
        }
        // Mean values
        double meanValue = mean / BENCHMARK_ITERATION * 1E-6;

        // Max and Min values stored as double
        double maxD = max * 1E-6;
        double minD = min * 1E-6;
        // Comparison between the mean times
        System.out.println(dataTypeString);
        // Output print
        System.out.println("\nMean value for " + description + "Descriptor : " + meanValue
                + " msec.");
        System.out.println("Maximum value for " + description + "Descriptor : " + maxD + " msec.");
        System.out.println("Minimum value for " + description + "Descriptor : " + minD + " msec.");
        // Final Image disposal
        if (imageMerged instanceof RenderedOp) {
            ((RenderedOp) imageMerged).dispose();
        }

        for (int band = 0; band < BAND_NUMBER; band++) {
            ((TiledImage) testImage[band]).dispose();
        }

    }

}


text:
require 'singleton'
require 'ostruct'
require 'yaml'
require 'logger'
require 'pstore'

module FeedTorrents
  def self.configuration
    Configuration.instance
  end

  def self.logger
    configuration.logger
  end

  class Configuration
    include Singleton

    def yaml_from_file(file)
      set_config YAML.load_file(File.expand_path(file))
      nil
    end

    def set_config(hash)
      @source = OpenStruct.new(hash)
    end

    def logger
      @logger ||= create_logger
    end

    def method_missing(method, *args, &block)
      @source.send(method, *args, &block)
    end

    def filter_testing=(value)
      @filter_testing = !!value
    end

    def filter_testing?
      @filter_testing
    end

    private

    def source
      @source ||= OpenStruct.new
    end

    def create_logger
      if self.log && self.log[:out] == 'STDOUT' || filter_testing?
        obj = Logger.new(STDOUT)
      else
        obj = Logger.new(File.expand_path(self.log[:out]), self.log[:rotate], self.log[:size])
        obj.level = Logger.const_get(self.log[:level])
        obj.datetime_format = self.log[:format]
      end

      obj
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
from traductor.translators.base import BaseTranslator

class VolumesFrom(BaseTranslator):
    """

    """
    def translate(self, value):
        """
        :param value:
        :return:
        """
        if type(value) is not list:
            return ""

        return "--volumes-from=%s" % " --volumes-from=".join(value)


text:
<?php

/*
 * Example PHP implementation for the client-side table formatting example.
 * This is basically the same as the 'fieldTypes' example, but in this case
 * note that there is no server-side formatting of the 'done' field - rather it
 * is done in the DataTable in this example
 */

// DataTables PHP library
include( "../../php/DataTables.php" );

// Alias Editor classes so they are easy to use
use
	DataTables\Editor,
	DataTables\Editor\Field,
	DataTables\Editor\Format,
	DataTables\Editor\Join,
	DataTables\Editor\Upload,
	DataTables\Editor\Validate;

// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'todo' )
	->fields(
		Field::inst( 'item' ),
		Field::inst( 'done' ),
		Field::inst( 'priority' )
	)
	->process( $_POST )
	->json();


text:
<?php

/**
 * @see Zend_Filter_Encrypt
 */
require_once 'Zend/Filter/Encrypt.php';

/**
 * Decrypts a given string
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Decrypt extends Zend_Filter_Encrypt
{
    /**
     * Defined by Zend_Filter_Interface
     *
     * Decrypts the content $value with the defined settings
     *
     * @param  string $value Content to decrypt
     * @return string The decrypted content
     */
    public function filter($value)
    {
        return $this->_adapter->decrypt($value);
    }
}


text:
package com.yl.merchat.module.main;

import com.yl.merchat.model.vo.bean.NoticeBean;
import com.yl.core.component.mvp.view.BaseMvpView;

import java.util.List;

/**
 * Created by zm on 2018/9/10.
 */
public interface IMainView extends BaseMvpView{
    void showToast(String message);
    void showNotices(List<NoticeBean> noticeBeans);
}


text:
<md-content flex>

    <md-card>
        <md-toolbar class="md-table-toolbar md-default"
                    ng-hide="vm.selectedUsers.length">

                <md-icon class="material-icons">search</md-icon>
                <form name="vm.filterForm" flex>
                    <input type="text" flex
                           ng-model="vm.query.filter"
                           ng-model-options="vm.filterOptions"
                           placeholder="{{ 'SEARCH' | translate}}">
                </form>
                <md-button class="md-icon-button" ng-show="vm.query.filter" ng-click="vm.clearFilter()">
                    <md-tooltip>{{ 'CLEAR' | translate }}</md-tooltip>
                    <md-icon>close</md-icon>
                </md-button>
                <md-button class="md-icon-button" ng-click="vm.refresh()">
                    <md-tooltip>{{ 'REFRESH' | translate }}</md-tooltip>
                    <md-icon>refresh</md-icon>
                </md-button>

        </md-toolbar>

        <md-toolbar class="md-table-toolbar alternate"
                    ng-show="vm.options.rowSelection && vm.selectedUsers.length">

                {{vm.selectedUsers.length}}

                <md-button class="md-icon-button" aria-label="Delete"
                           ng-click="vm.deleteItems()">
                    <md-tooltip>{{ 'BUTTON_DELETE' | translate }}</md-tooltip>
                    <md-icon ng-if="vm.selectedUsers.length == 1">delete</md-icon>
                    <md-icon ng-if="vm.selectedUsers.length > 1">delete_sweep</md-icon>
                </md-button>

        </md-toolbar>

        <md-table-container>

                        <span translate="TARGET_WEEKLY_DISTANCE"

                        {{user.email}}
                        {{user.name}}
                        {{ user.admin ? 'Administrator' : user.manager ? 'User Manager' : 'User' }}
                        {{user.targetWeeklyDistance}}

        </md-table-container>

        <md-table-pagination md-limit="vm.query.limit"
                             md-limit-options="vm.options.limitSelect"
                             md-page-select="vm.options.pageSelect"
                             md-page="vm.query.page"
                             md-total="{{vm.users.length}}"
                             md-boundary-links="vm.options.boundaryLinks"
                             md-on-paginate></md-table-pagination>

    </md-card>
</md-content>


text:
<?php

namespace Lunr\Spark\Contentful;

/**
 * Low level Contentful Preview API methods for Spark
 */
class PreviewApi extends DeliveryApi
{

    /**
     * Content Preview API URL.
     * @var String
     */
    const URL = 'https://preview.contentful.com/spaces/';

    /**
     * Constructor.
     *
     * @param \Lunr\Spark\CentralAuthenticationStore $cas    Shared instance of the credentials store
     * @param \Psr\Log\LoggerInterface               $logger Shared instance of a Logger class.
     * @param \Requests_Session                      $http   Shared instance of the Requests_Session class.
     */
    public function __construct($cas, $logger, $http)
    {
        parent::__construct($cas, $logger, $http);
    }

    /**
     * Destructor.
     */
    public function __destruct()
    {
        parent::__destruct();
    }

}

?>


text:
<?php

namespace Magento\NewRelicReporting\Test\Unit\Model\Observer;

use Magento\NewRelicReporting\Model\Observer\ReportConcurrentUsers;

/**
 * Class ReportConcurrentUsersTest
 */
class ReportConcurrentUsersTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ReportConcurrentUsers
     */
    protected $model;

    /**
     * @var \Magento\NewRelicReporting\Model\Config|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $config;

    /**
     * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $customerSession;

    /**
     * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $customerRepository;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $storeManager;

    /**
     * @var \Magento\NewRelicReporting\Model\UsersFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $usersFactory;

    /**
     * @var \Magento\NewRelicReporting\Model\Users|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $usersModel;

    /**
     * @var \Magento\Framework\Json\EncoderInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $jsonEncoder;

    /**
     * Setup
     *
     * @return void
     */
    protected function setUp()
    {
        $this->config = $this->getMockBuilder('Magento\NewRelicReporting\Model\Config')
            ->disableOriginalConstructor()
            ->setMethods(['isNewRelicEnabled'])
            ->getMock();
        $this->customerSession = $this->getMockBuilder('Magento\Customer\Model\Session')
            ->disableOriginalConstructor()
            ->setMethods(['isLoggedIn', 'getCustomerId'])
            ->getMock();
        $this->customerRepository = $this->getMockBuilder('Magento\Customer\Api\CustomerRepositoryInterface')
            ->getMock();
        $this->storeManager = $this->getMockBuilder('Magento\Store\Model\StoreManagerInterface')
            ->getMock();
        $this->usersFactory = $this->getMockBuilder('Magento\NewRelicReporting\Model\UsersFactory')
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();
        $this->usersModel = $this->getMockBuilder('Magento\NewRelicReporting\Model\Users')
            ->disableOriginalConstructor()
            ->getMock();
        $this->jsonEncoder = $this->getMockBuilder('Magento\Framework\Json\EncoderInterface')
            ->getMock();

        $this->usersFactory->expects($this->any())
            ->method('create')
            ->willReturn($this->usersModel);

        $this->model = new ReportConcurrentUsers(
            $this->config,
            $this->customerSession,
            $this->customerRepository,
            $this->storeManager,
            $this->usersFactory,
            $this->jsonEncoder
        );
    }

    /**
     * Test case when module is disabled in config
     *
     * @return void
     */
    public function testReportConcurrentUsersModuleDisabledFromConfig()
    {
        /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */
        $eventObserver = $this->getMockBuilder('Magento\Framework\Event\Observer')
            ->disableOriginalConstructor()
            ->getMock();

        $this->config->expects($this->once())
            ->method('isNewRelicEnabled')
            ->willReturn(false);

        $this->model->execute($eventObserver);
    }

    /**
     * Test case when user is not logged in
     *
     * @return void
     */
    public function testReportConcurrentUsersUserIsNotLoggedIn()
    {
        /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */
        $eventObserver = $this->getMockBuilder('Magento\Framework\Event\Observer')
            ->disableOriginalConstructor()
            ->getMock();

        $this->config->expects($this->once())
            ->method('isNewRelicEnabled')
            ->willReturn(true);
        $this->customerSession->expects($this->once())
            ->method('isLoggedIn')
            ->willReturn(false);

        $this->model->execute($eventObserver);
    }

    /**
     * Test case when module is enabled and user is logged in
     *
     * @return void
     */
    public function testReportConcurrentUsers()
    {
        $testCustomerId = 1;
        $testAction = 'JSON string';

        /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */
        $eventObserver = $this->getMockBuilder('Magento\Framework\Event\Observer')
            ->disableOriginalConstructor()
            ->getMock();

        $this->config->expects($this->once())
            ->method('isNewRelicEnabled')
            ->willReturn(true);
        $this->customerSession->expects($this->once())
            ->method('isLoggedIn')
            ->willReturn(true);
        $this->customerSession->expects($this->once())
            ->method('getCustomerId')
            ->willReturn($testCustomerId);
        $customerMock = $this->getMockBuilder('Magento\Customer\Api\Data\CustomerInterface')->getMock();
        $this->customerRepository->expects($this->once())
            ->method('getById')
            ->willReturn($customerMock);
        $storeMock = $this->getMockBuilder('Magento\Store\Model\Store')->disableOriginalConstructor()->getMock();
        $this->storeManager->expects($this->once())
            ->method('getStore')
            ->willReturn($storeMock);
        $websiteMock = $this->getMockBuilder('Magento\Store\Model\Website')->disableOriginalConstructor()->getMock();
        $this->storeManager->expects($this->once())
            ->method('getWebsite')
            ->willReturn($websiteMock);
        $this->jsonEncoder->expects($this->once())
            ->method('encode')
            ->willReturn($testAction);
        $this->usersModel->expects($this->once())
            ->method('setData')
            ->with(['type' => 'user_action', 'action' => $testAction])
            ->willReturnSelf();
        $this->usersModel->expects($this->once())
            ->method('save');

        $this->model->execute($eventObserver);
    }
}


text:
#pragma once
#include <aws/applicationcostprofiler/ApplicationCostProfiler_EXPORTS.h>
#include <aws/applicationcostprofiler/ApplicationCostProfilerRequest.h>
#include <aws/applicationcostprofiler/model/SourceS3Location.h>
#include <utility>

namespace Aws
{
namespace ApplicationCostProfiler
{
namespace Model
{

  /**
   */
  class AWS_APPLICATIONCOSTPROFILER_API ImportApplicationUsageRequest : public ApplicationCostProfilerRequest
  {
  public:
    ImportApplicationUsageRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ImportApplicationUsage"; }

    Aws::String SerializePayload() const override;

    /**
     *
Amazon S3 location to import application usage data from.

     */
    inline const SourceS3Location& GetSourceS3Location() const{ return m_sourceS3Location; }

    /**
     *
Amazon S3 location to import application usage data from.

     */
    inline bool SourceS3LocationHasBeenSet() const { return m_sourceS3LocationHasBeenSet; }

    /**
     *
Amazon S3 location to import application usage data from.

     */
    inline void SetSourceS3Location(const SourceS3Location& value) { m_sourceS3LocationHasBeenSet = true; m_sourceS3Location = value; }

    /**
     *
Amazon S3 location to import application usage data from.

     */
    inline void SetSourceS3Location(SourceS3Location&& value) { m_sourceS3LocationHasBeenSet = true; m_sourceS3Location = std::move(value); }

    /**
     *
Amazon S3 location to import application usage data from.

     */
    inline ImportApplicationUsageRequest& WithSourceS3Location(const SourceS3Location& value) { SetSourceS3Location(value); return *this;}

    /**
     *
Amazon S3 location to import application usage data from.

     */
    inline ImportApplicationUsageRequest& WithSourceS3Location(SourceS3Location&& value) { SetSourceS3Location(std::move(value)); return *this;}

  private:

    SourceS3Location m_sourceS3Location;
    bool m_sourceS3LocationHasBeenSet;
  };

} // namespace Model
} // namespace ApplicationCostProfiler
} // namespace Aws


text:
use std::ops::RangeInclusive;

use clap::{arg, command};

fn main() {
    let matches = command!()
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .validator(port_in_range),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    let port: usize = matches
        .value_of_t("PORT")
        .expect("'PORT' is required and parsing will fail if its missing");
    println!("PORT = {}", port);
}

const PORT_RANGE: RangeInclusive<usize> = 1..=65535;

fn port_in_range(s: &str) -> Result<(), String> {
    let port: usize = s
        .parse()
        .map_err(|_| format!("`{}` isn't a port number", s))?;
    if PORT_RANGE.contains(&port) {
        Ok(())
    } else {
        Err(format!(
            "Port not in range {}-{}",
            PORT_RANGE.start(),
            PORT_RANGE.end()
        ))
    }
}


text:
require 'rails_helper'

describe 'shared/_breadcrumb.html.haml' do
  let(:crumb) do
    { title: 'A title', url: '/a/path/' }
  end
  let(:children) { '!!! CHILD CODE GOES HERE !!!' }
  let(:root) { true }

  before do
    render partial: 'shared/breadcrumb',
           locals: {
             crumb: crumb,
             children: children,
             root: root
           }
  end

  context 'as root' do
    it 'does not include the itemprop="child" attribute' do
      expect(rendered).not_to match(/itemprop='child'/)
    end
  end

  context 'not root' do
    let(:root) { false }

    it 'renders the data-root tas as false' do
      expect(rendered).to match(/itemprop='child'/)
    end
  end

  it 'renders child code' do
    expect(rendered).to match(/#{children}/)
  end
end


text:
Useful builders and related utilities to access the features of the `HttpClient` in more reusable and fluent manner.

## `Request`

Light wrapper for building HTTP requests in similar fashion as Jersey HTTP client.

```java
// build the request
Request request = new Request(httpClient,
            "http://www.example.org",
            ImmutableMultimap.of("header", "value"),
            ImmutableMultimap.of("param", "value"),
            null);
// call a method which matches the HTTP request method you want to execute
// remember to use try-with-resources
try (Request request : request.get()) {
    Response response = request.get();
    // and so on and so forth
}
```

## `RequestBuilder`

Build `Request` instances and reuse the builder.

```java
// request list of numbers from example API
RequestBuilder listOfNumbers = new RequestBuilder(httpClient)
        .withUrl("http://example.org/numbers");

try (Response numbersResponse : listOfNumbers.build().get()) {
    List<Integer> numbers = deserialize(numbersRequest.getResponseBody());
    // for each number reuse original builder with extended URL path and added parameter
    // note that the params do not stack as each builder instance is unique
    RequestBuilder translateNumber = listOfNumbers.withUrl("http://example.org/translate"
    for (Integer n : numbers) {
        Request numberRequest = translateNumber
                .withParams(params -> params.put("n", n.toString())
                .build();
        // this will HTTP GET http://example.org/translate?n={n}
        try (Response numberResponse : numberRequest.get()) {
            // and so on and so forth
        }
    }
}
```


text:
<?php

class Google_Service_ContainerAnalysis_ListScanConfigsResponse extends Google_Collection
{
  protected $collection_key = 'scanConfigs';
  public $nextPageToken;
  protected $scanConfigsType = 'Google_Service_ContainerAnalysis_ScanConfig';
  protected $scanConfigsDataType = 'array';

  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
  /**
   * @param Google_Service_ContainerAnalysis_ScanConfig
   */
  public function setScanConfigs($scanConfigs)
  {
    $this->scanConfigs = $scanConfigs;
  }
  /**
   * @return Google_Service_ContainerAnalysis_ScanConfig
   */
  public function getScanConfigs()
  {
    return $this->scanConfigs;
  }
}


text:
<?php

/* @SRVDVServer/Registration/register_content.html.twig */
class __TwigTemplate_c914caf63b24a0beb350cc46f29d2f0e95556bbffbe860feb8d04d96acb3775c extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 2
        echo "
";
        // line 3
        $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->setTheme((isset($context["form"]) ? $context["form"] : null), array(0 => ":FormTemplate:bootstrap.html.twig"));
        // line 4
        echo "<form action=\"";
        echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("fos_user_registration_register");
        echo "\" ";
        echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : null), 'enctype');
        echo " method=\"POST\" class=\"fos_user_registration_register\"   >
    ";
        // line 5
        echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : null), 'widget');
        echo "
    </br>
    <div>
        <input type=\"submit\" value=\"";
        // line 8
        echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("registration.submit", array(), "FOSUserBundle"), "html", null, true);
        echo "\" class=\"btn btn-success\"/>
    </div>
</form>
";
    }

    public function getTemplateName()
    {
        return "@SRVDVServer/Registration/register_content.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  37 => 8,  31 => 5,  24 => 4,  22 => 3,  19 => 2,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("", "@SRVDVServer/Registration/register_content.html.twig", "C:\\wamp64\\www\\serveurDeVoeuxOmar\\src\\SRVDV\\ServerBundle\\Resources\\views\\Registration\\register_content.html.twig");
    }
}


text:
#include <sedml/SedTask.h>
#include <sedml/SedTypes.h>
#include <sbml/xml/XMLInputStream.h>

using namespace std;

LIBSEDML_CPP_NAMESPACE_BEGIN

/*
 * Creates a new SedTask with the given level, version, and package version.
 */
SedTask::SedTask(unsigned int level, unsigned int version)
  : SedBase(level, version)
  , mId("")
  , mName("")
  , mModelReference("")
  , mSimulationReference("")

{
  // set an SedNamespaces derived object of this package
  setSedNamespacesAndOwn(new SedNamespaces(level, version));

  // connect to child objects
  connectToChild();
}

/*
 * Creates a new SedTask with the given SedNamespaces object.
 */
SedTask::SedTask(SedNamespaces* sedns)
  : SedBase(sedns)
  , mId("")
  , mName("")
  , mModelReference("")
  , mSimulationReference("")

{
  // set the element namespace of this object
  setElementNamespace(sedns->getURI());

  // connect to child objects
  connectToChild();
}

/*
 * Copy constructor for SedTask.
 */
SedTask::SedTask(const SedTask& orig)
  : SedBase(orig)
{
  mId  = orig.mId;
  mName  = orig.mName;
  mModelReference  = orig.mModelReference;
  mSimulationReference  = orig.mSimulationReference;

  // connect to child objects
  connectToChild();
}

/*
 * Assignment for SedTask.
 */
SedTask&
SedTask::operator=(const SedTask& rhs)
{
  if (&rhs != this)
    {
      SedBase::operator=(rhs);
      mId  = rhs.mId;
      mName  = rhs.mName;
      mModelReference  = rhs.mModelReference;
      mSimulationReference  = rhs.mSimulationReference;

      // connect to child objects
      connectToChild();
    }

  return *this;
}

/*
 * Clone for SedTask.
 */
SedTask*
SedTask::clone() const
{
  return new SedTask(*this);
}

/*
 * Destructor for SedTask.
 */
SedTask::~SedTask()
{
}

/*
 * Returns the value of the "id" attribute of this SedTask.
 */
const std::string&
SedTask::getId() const
{
  return mId;
}

/*
 * Returns the value of the "name" attribute of this SedTask.
 */
const std::string&
SedTask::getName() const
{
  return mName;
}

/*
 * Returns the value of the "modelReference" attribute of this SedTask.
 */
const std::string&
SedTask::getModelReference() const
{
  return mModelReference;
}

/*
 * Returns the value of the "simulationReference" attribute of this SedTask.
 */
const std::string&
SedTask::getSimulationReference() const
{
  return mSimulationReference;
}

/*
 * Returns true/false if id is set.
 */
bool
SedTask::isSetId() const
{
  return (mId.empty() == false);
}

/*
 * Returns true/false if name is set.
 */
bool
SedTask::isSetName() const
{
  return (mName.empty() == false);
}

/*
 * Returns true/false if modelReference is set.
 */
bool
SedTask::isSetModelReference() const
{
  return (mModelReference.empty() == false);
}

/*
 * Returns true/false if simulationReference is set.
 */
bool
SedTask::isSetSimulationReference() const
{
  return (mSimulationReference.empty() == false);
}

/*
 * Sets id and returns value indicating success.
 */
int
SedTask::setId(const std::string& id)
{
  return SyntaxChecker::checkAndSetSId(id, mId);
}

/*
 * Sets name and returns value indicating success.
 */
int
SedTask::setName(const std::string& name)
{
  {
    mName = name;
    return LIBSEDML_OPERATION_SUCCESS;
  }
}

/*
 * Sets modelReference and returns value indicating success.
 */
int
SedTask::setModelReference(const std::string& modelReference)
{
  if (!(SyntaxChecker::isValidInternalSId(modelReference)))
    {
      return LIBSEDML_INVALID_ATTRIBUTE_VALUE;
    }
  else
    {
      mModelReference = modelReference;
      return LIBSEDML_OPERATION_SUCCESS;
    }
}

/*
 * Sets simulationReference and returns value indicating success.
 */
int
SedTask::setSimulationReference(const std::string& simulationReference)
{
  if (!(SyntaxChecker::isValidInternalSId(simulationReference)))
    {
      return LIBSEDML_INVALID_ATTRIBUTE_VALUE;
    }
  else
    {
      mSimulationReference = simulationReference;
      return LIBSEDML_OPERATION_SUCCESS;
    }
}

/*
 * Unsets id and returns value indicating success.
 */
int
SedTask::unsetId()
{
  mId.erase();

  if (mId.empty() == true)
    {
      return LIBSEDML_OPERATION_SUCCESS;
    }
  else
    {
      return LIBSEDML_OPERATION_FAILED;
    }
}

/*
 * Unsets name and returns value indicating success.
 */
int
SedTask::unsetName()
{
  mName.erase();

  if (mName.empty() == true)
    {
      return LIBSEDML_OPERATION_SUCCESS;
    }
  else
    {
      return LIBSEDML_OPERATION_FAILED;
    }
}

/*
 * Unsets modelReference and returns value indicating success.
 */
int
SedTask::unsetModelReference()
{
  mModelReference.erase();

  if (mModelReference.empty() == true)
    {
      return LIBSEDML_OPERATION_SUCCESS;
    }
  else
    {
      return LIBSEDML_OPERATION_FAILED;
    }
}

/*
 * Unsets simulationReference and returns value indicating success.
 */
int
SedTask::unsetSimulationReference()
{
  mSimulationReference.erase();

  if (mSimulationReference.empty() == true)
    {
      return LIBSEDML_OPERATION_SUCCESS;
    }
  else
    {
      return LIBSEDML_OPERATION_FAILED;
    }
}

/*
 * Returns the XML element name of this object
 */
const std::string&
SedTask::getElementName() const
{
  static const string name = "task";
  return name;
}

/**
 * return the SEDML object corresponding to next XMLToken.
 */
SedBase*
SedTask::createObject(XMLInputStream& stream)
{
  SedBase* object = NULL;

  const string& name   = stream.peek().getName();

  connectToChild();

  return object;
}

/*
 * Read values from the given XMLAttributes set into their specific fields.
 */
void
SedTask::connectToChild()
{
  SedBase::connectToChild();

}

/*
 * Returns the libSEDML type code for this SEDML object.
 */
int
SedTask::getTypeCode() const
{
  return SEDML_TASK;
}

/*
 * check if all the required attributes are set
 */
bool
SedTask::hasRequiredAttributes() const
{
  bool allPresent = true;

  if (isSetId() == false)
    allPresent = false;

  return allPresent;
}

/*
 * check if all the required elements are set
 */
bool
SedTask::hasRequiredElements() const
{
  bool allPresent = true;

  return allPresent;
}

/** @cond doxygen-libsedml-internal */

/*
 * write contained elements
 */
void
SedTask::writeElements(XMLOutputStream& stream) const
{
  SedBase::writeElements(stream);
}

/** @endcond doxygen-libsedml-internal */

/** @cond doxygen-libsedml-internal */

/*
 * Accepts the given SedVisitor.
 */
bool
SedTask::accept(SedVisitor& v) const
{
  return false;

}

/** @endcond doxygen-libsedml-internal */

/** @cond doxygen-libsedml-internal */

/*
 * Sets the parent SedDocument.
 */
void
SedTask::setSedDocument(SedDocument* d)
{
  SedBase::setSedDocument(d);
}

/** @endcond doxygen-libsedml-internal */

/** @cond doxygen-libsedml-internal */

/*
 * Get the list of expected attributes for this element.
 */
void
SedTask::addExpectedAttributes(ExpectedAttributes& attributes)
{
  SedBase::addExpectedAttributes(attributes);

  attributes.add("id");
  attributes.add("name");
  attributes.add("modelReference");
  attributes.add("simulationReference");
}

/** @endcond doxygen-libsedml-internal */

/** @cond doxygen-libsedml-internal */

/*
 * Read values from the given XMLAttributes set into their specific fields.
 */
void
SedTask::readAttributes(const XMLAttributes& attributes,
                        const ExpectedAttributes& expectedAttributes)
{
  SedBase::readAttributes(attributes, expectedAttributes);

  bool assigned = false;

  //
  // id SId  ( use = "required" )
  //
  assigned = attributes.readInto("id", mId, getErrorLog(), true);

  if (assigned == true)
    {
      // check string is not empty and correct syntax

      if (mId.empty() == true)
        {
          logEmptyString(mId, getLevel(), getVersion(), "<SedTask>");
        }
      else if (SyntaxChecker::isValidSBMLSId(mId) == false)
        {
          logError(SedInvalidIdSyntax);
        }
    }

  //
  // name string   ( use = "optional" )
  //
  assigned = attributes.readInto("name", mName, getErrorLog(), false);

  if (assigned == true)
    {
      // check string is not empty

      if (mName.empty() == true)
        {
          logEmptyString(mName, getLevel(), getVersion(), "<SedTask>");
        }
    }

  //
  // modelReference SIdRef   ( use = "optional" )
  //
  assigned = attributes.readInto("modelReference", mModelReference, getErrorLog(), false);

  if (assigned == true)
    {
      // check string is not empty and correct syntax

      if (mModelReference.empty() == true)
        {
          logEmptyString(mModelReference, getLevel(), getVersion(), "<SedTask>");
        }
      else if (SyntaxChecker::isValidSBMLSId(mModelReference) == false)
        {
          logError(SedInvalidIdSyntax);
        }
    }

  //
  // simulationReference SIdRef   ( use = "optional" )
  //
  assigned = attributes.readInto("simulationReference", mSimulationReference, getErrorLog(), false);

  if (assigned == true)
    {
      // check string is not empty and correct syntax

      if (mSimulationReference.empty() == true)
        {
          logEmptyString(mSimulationReference, getLevel(), getVersion(), "<SedTask>");
        }
      else if (SyntaxChecker::isValidSBMLSId(mSimulationReference) == false)
        {
          logError(SedInvalidIdSyntax);
        }
    }

}

/** @endcond doxygen-libsedml-internal */

/** @cond doxygen-libsedml-internal */

/*
 * Write values of XMLAttributes to the output stream.
 */
void
SedTask::writeAttributes(XMLOutputStream& stream) const
{
  SedBase::writeAttributes(stream);

  if (isSetId() == true)
    stream.writeAttribute("id", getPrefix(), mId);

  if (isSetName() == true)
    stream.writeAttribute("name", getPrefix(), mName);

  if (isSetModelReference() == true)
    stream.writeAttribute("modelReference", getPrefix(), mModelReference);

  if (isSetSimulationReference() == true)
    stream.writeAttribute("simulationReference", getPrefix(), mSimulationReference);

}

/** @endcond doxygen-libsedml-internal */

/*
 * Constructor
 */
SedListOfTasks::SedListOfTasks(unsigned int level,
                               unsigned int version)
  : SedListOf(level, version)
{
  setSedNamespacesAndOwn(new SedNamespaces(level, version));
}

/*
 * Constructor
 */
SedListOfTasks::SedListOfTasks(SedNamespaces* sedns)
  : SedListOf(sedns)
{
  setElementNamespace(sedns->getURI());
}

/*
 * Returns a deep copy of this SedListOfTasks
 */
SedListOfTasks*
SedListOfTasks::clone() const
{
  return new SedListOfTasks(*this);
}

/*
 * Get a Task from the SedListOfTasks by index.
*/
SedTask*
SedListOfTasks::get(unsigned int n)
{
  return static_cast<SedTask*>(SedListOf::get(n));
}

/*
 * Get a Task from the SedListOfTasks by index.
 */
const SedTask*
SedListOfTasks::get(unsigned int n) const
{
  return static_cast<const SedTask*>(SedListOf::get(n));
}

/*
 * Get a Task from the SedListOfTasks by id.
 */
SedTask*
SedListOfTasks::get(const std::string& sid)
{
  return const_cast<SedTask*>(
           static_cast<const SedListOfTasks&>(*this).get(sid));
}

/*
 * Get a Task from the SedListOfTasks by id.
 */
const SedTask*
SedListOfTasks::get(const std::string& sid) const
{
  vector<SedBase*>::const_iterator result;

  result = find_if(mItems.begin(), mItems.end(), SedIdEq<SedTask>(sid));
  return (result == mItems.end()) ? 0 : static_cast <SedTask*>(*result);
}

/**
 * Adds a copy the given "SedTask" to this SedListOfTasks.
 *
 * @param st; the SedTask object to add
 *
 * @return integer value indicating success/failure of the
 * function.  @if clike The value is drawn from the
 * enumeration #OperationReturnValues_t. @endif The possible values
 * returned by this function are:
 * @li LIBSEDML_OPERATION_SUCCESS
 * @li LIBSEDML_INVALID_ATTRIBUTE_VALUE
 */
int
SedListOfTasks::addTask(const SedTask* st)
{
  if (st == NULL) return LIBSEDML_INVALID_ATTRIBUTE_VALUE;

  append(st);
  return LIBSEDML_OPERATION_SUCCESS;
}

/**
 * Get the number of SedTask objects in this SedListOfTasks.
 *
 * @return the number of SedTask objects in this SedListOfTasks
 */
unsigned int
SedListOfTasks::getNumTasks() const
{
  return size();
}

/**
 * Creates a new SedTask object, adds it to this SedListOfTasks
 * task and returns the SedTask object created.
 *
 * @return a new SedTask object instance
 *
 * @see addTask(const SedTask* st)
 */
SedTask*
SedListOfTasks::createTask()
{
  SedTask *temp = new SedTask();

  if (temp != NULL) appendAndOwn(temp);

  return temp;
}

/**
 * Creates a new SedRepeatedTask object, adds it to this SedListOfTasks
 * repeatedTask and returns the SedRepeatedTask object created.
 *
 * @return a new SedRepeatedTask object instance
 *
 * @see addRepeatedTask(const SedTask* st)
 */
SedRepeatedTask*
SedListOfTasks::createRepeatedTask()
{
  SedRepeatedTask *temp = new SedRepeatedTask();

  if (temp != NULL) appendAndOwn(temp);

  return temp;
}

/*
 * Removes the nth Task from this SedListOfTasks
 */
SedTask*
SedListOfTasks::remove(unsigned int n)
{
  return static_cast<SedTask*>(SedListOf::remove(n));
}

/*
 * Removes the Task from this SedListOfTasks with the given identifier
 */
SedTask*
SedListOfTasks::remove(const std::string& sid)
{
  SedBase* item = NULL;
  vector<SedBase*>::iterator result;

  result = find_if(mItems.begin(), mItems.end(), SedIdEq<SedTask>(sid));

  if (result != mItems.end())
    {
      item = *result;
      mItems.erase(result);
    }

  return static_cast <SedTask*>(item);
}

/*
 * Returns the XML element name of this object
 */
const std::string&
SedListOfTasks::getElementName() const
{
  static const string name = "listOfTasks";
  return name;
}

/*
 * Returns the libSEDML type code for this SEDML object.
 */
int
SedListOfTasks::getTypeCode() const
{
  return SEDML_LIST_OF;
}

/*
 * Returns the libSEDML type code for the objects in this LIST_OF.
 */
int
SedListOfTasks::getItemTypeCode() const
{
  return SEDML_TASK;
}

/** @cond doxygen-libsedml-internal */

/*
 * Creates a new SedTask in this SedListOfTasks
 */
SedBase*
SedListOfTasks::createObject(XMLInputStream& stream)
{
  const std::string& name   = stream.peek().getName();
  SedBase* object = NULL;

  if (name == "task")
    {
      object = new SedTask(getSedNamespaces());
      appendAndOwn(object);
    }

  if (name == "repeatedTask")
    {
      object = new SedRepeatedTask(getSedNamespaces());
      appendAndOwn(object);
    }

  return object;
}

/** @endcond doxygen-libsedml-internal */

/** @cond doxygen-libsedml-internal */

/*
 * Write the namespace for the Sed package.
 */
void
SedListOfTasks::writeXMLNS(XMLOutputStream& stream) const
{
  XMLNamespaces xmlns;

  std::string prefix = getPrefix();

  if (prefix.empty())
    {
      if (getNamespaces() != NULL && !getNamespaces()->hasURI(SEDML_XMLNS_L1) && !getNamespaces()->hasURI(SEDML_XMLNS_L1V2) && !getNamespaces()->hasURI(SEDML_XMLNS_L1V3))
        {
          if (getVersion() == 2) xmlns.add(SEDML_XMLNS_L1V2, prefix);
          else if (getVersion() == 3) xmlns.add(SEDML_XMLNS_L1V3, prefix);
          else xmlns.add(SEDML_XMLNS_L1V2, prefix);
        }
    }

  stream << xmlns;
}

/** @endcond doxygen-libsedml-internal */

/**
 * write comments
 */
LIBSEDML_EXTERN
SedTask_t *
SedTask_create(unsigned int level, unsigned int version)
{
  return new SedTask(level, version);
}

/**
 * write comments
 */
LIBSEDML_EXTERN
void
SedTask_free(SedTask_t * st)
{
  if (st != NULL)
    delete st;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
SedTask_t *
SedTask_clone(SedTask_t * st)
{
  if (st != NULL)
    {
      return static_cast<SedTask_t*>(st->clone());
    }
  else
    {
      return NULL;
    }
}

/**
 * write comments
 */
LIBSEDML_EXTERN
char *
SedTask_getId(SedTask_t * st)
{
  if (st == NULL)
    return NULL;

  return st->getId().empty() ? NULL : safe_strdup(st->getId().c_str());
}

/**
 * write comments
 */
LIBSEDML_EXTERN
char *
SedTask_getName(SedTask_t * st)
{
  if (st == NULL)
    return NULL;

  return st->getName().empty() ? NULL : safe_strdup(st->getName().c_str());
}

/**
 * write comments
 */
LIBSEDML_EXTERN
char *
SedTask_getModelReference(SedTask_t * st)
{
  if (st == NULL)
    return NULL;

  return st->getModelReference().empty() ? NULL : safe_strdup(st->getModelReference().c_str());
}

/**
 * write comments
 */
LIBSEDML_EXTERN
char *
SedTask_getSimulationReference(SedTask_t * st)
{
  if (st == NULL)
    return NULL;

  return st->getSimulationReference().empty() ? NULL : safe_strdup(st->getSimulationReference().c_str());
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_isSetId(SedTask_t * st)
{
  return (st != NULL) ? static_cast<int>(st->isSetId()) : 0;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_isSetName(SedTask_t * st)
{
  return (st != NULL) ? static_cast<int>(st->isSetName()) : 0;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_isSetModelReference(SedTask_t * st)
{
  return (st != NULL) ? static_cast<int>(st->isSetModelReference()) : 0;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_isSetSimulationReference(SedTask_t * st)
{
  return (st != NULL) ? static_cast<int>(st->isSetSimulationReference()) : 0;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_setId(SedTask_t * st, const char * id)
{
  return (st != NULL) ? st->setId(id) : LIBSEDML_INVALID_OBJECT;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_setName(SedTask_t * st, const char * name)
{
  return (st != NULL) ? st->setName(name) : LIBSEDML_INVALID_OBJECT;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_setModelReference(SedTask_t * st, const char * modelReference)
{
  return (st != NULL) ? st->setModelReference(modelReference) : LIBSEDML_INVALID_OBJECT;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_setSimulationReference(SedTask_t * st, const char * simulationReference)
{
  return (st != NULL) ? st->setSimulationReference(simulationReference) : LIBSEDML_INVALID_OBJECT;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_unsetId(SedTask_t * st)
{
  return (st != NULL) ? st->unsetId() : LIBSEDML_INVALID_OBJECT;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_unsetName(SedTask_t * st)
{
  return (st != NULL) ? st->unsetName() : LIBSEDML_INVALID_OBJECT;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_unsetModelReference(SedTask_t * st)
{
  return (st != NULL) ? st->unsetModelReference() : LIBSEDML_INVALID_OBJECT;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_unsetSimulationReference(SedTask_t * st)
{
  return (st != NULL) ? st->unsetSimulationReference() : LIBSEDML_INVALID_OBJECT;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_hasRequiredAttributes(SedTask_t * st)
{
  return (st != NULL) ? static_cast<int>(st->hasRequiredAttributes()) : 0;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
int
SedTask_hasRequiredElements(SedTask_t * st)
{
  return (st != NULL) ? static_cast<int>(st->hasRequiredElements()) : 0;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
SedTask_t *
SedListOfTasks_getById(SedListOf_t * lo, const char * sid)
{
  if (lo == NULL)
    return NULL;

  return (sid != NULL) ? static_cast <SedListOfTasks *>(lo)->get(sid) : NULL;
}

/**
 * write comments
 */
LIBSEDML_EXTERN
SedTask_t *
SedListOfTasks_removeById(SedListOf_t * lo, const char * sid)
{
  if (lo == NULL)
    return NULL;

  return (sid != NULL) ? static_cast <SedListOfTasks *>(lo)->remove(sid) : NULL;
}

LIBSEDML_CPP_NAMESPACE_END


text:
steal("benchmark", function(){

	var suite = new Benchmark.Suite;

	suite.on('cycle', function(event) {
	  console.log(String(event.target));
	});

	var benchmarks =  {
		add: function(name, setup, benchmark, teardown){
			if(!benchmark){
				benchmark = setup;
				setup = undefined
			}
			suite.add(name, benchmark, {
				setup: setup,
				teardown: teardown
			});
			return this;
		},
		run: function(){
			suite.run({ 'async': true, 'queued': true });
		},
		suite: suite,
		on: function(){
			return suite.on.apply(this, arguments)
		}
	};

	steal().done().then(function(){
		benchmarks.run();
	});

	return benchmarks;
});


text:
<?php
	session_unset();
	session_destroy();
	echo "<script>document.location='./'</script>";
?>


text:
<?php

class SpotCache {
	protected $_db;

	const SpotImage			= 1;
	const SpotNzb			= 2;
	const Web				= 3;
	const Statistics		= 4;
	const StatisticsData	= 5;

	function __construct(SpotDb $db) {
		$this->_db = $db;
	} # ctor

	function isCached($resourceid, $cachetype) {
		return $this->_db->isCached($resourceid, $cachetype);
	} # isCached

	function getCache($resourceid, $cachetype) {
		SpotTiming::start(__FUNCTION__);
		$data = $this->_db->getCache($resourceid, $cachetype);
		SpotTiming::stop(__FUNCTION__, array($data));

		if ($data) {
			return $data;
		} else {
			return false;
		} # else
	} # getCache

	function saveCache($resourceid, $cachetype, $metadata, $content) {
		SpotTiming::start(__FUNCTION__);
		$this->_db->saveCache($resourceid, $cachetype, $metadata, $content);
		SpotTiming::stop(__FUNCTION__, array($resourceid, $cachetype, $metadata, $content));
	} # saveCache

	function updateCacheStamp($resourceid, $cachetype) {
		SpotTiming::start(__FUNCTION__);
		$this->_db->updateCacheStamp($resourceid, $cachetype);
		SpotTiming::stop(__FUNCTION__, array($resourceid, $cachetype));
	} # updateCacheStamp

} # class SpotCache


text:
class SystemStat < ActiveRecord::Base
  has_paper_trail
end


text:
from ..common import SummaryBase

class CADoublePointSyntheticProvider(SummaryBase.SummaryBaseSyntheticProvider):
    """
    Class representing CADoublePoint structure.
    """
    # struct CADoublePoint {
    #     double x;
    #     double y;
    # };
    def __init__(self, value_obj, internal_dict):
        super(CADoublePointSyntheticProvider, self).__init__(value_obj, internal_dict)

        self.register_child_value("x", ivar_name="x", type_name="double", offset=0,
                                  primitive_value_function=SummaryBase.get_float_value,
                                  summary_function=self.get_x_summary)
        self.register_child_value("y", ivar_name="y", type_name="double", offset=8,
                                  primitive_value_function=SummaryBase.get_float_value,
                                  summary_function=self.get_y_summary)

    @staticmethod
    def get_x_summary(value):
        return "x={}".format(SummaryBase.formatted_float(value))

    @staticmethod
    def get_y_summary(value):
        return "y={}".format(SummaryBase.formatted_float(value))

    def summary(self):
        summary = "({}, {})".format(self.x_summary, self.y_summary)
        return summary


text:
// Code generated by injection-gen. DO NOT EDIT.

package fake

import (
	context "context"

	fake "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/fake"
	pipeline "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1/pipeline"
	controller "knative.dev/pkg/controller"
	injection "knative.dev/pkg/injection"
)

var Get = pipeline.Get

func init() {
	injection.Fake.RegisterInformer(withInformer)
}

func withInformer(ctx context.Context) (context.Context, controller.Informer) {
	f := fake.Get(ctx)
	inf := f.Tekton().V1().Pipelines()
	return context.WithValue(ctx, pipeline.Key{}, inf), inf.Informer()
}


text:
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { Color } from 'vs/base/common/color';
import { IDisposable } from 'vs/base/common/lifecycle';
import { ViewPart } from 'vs/editor/browser/view/viewPart';
import { Position } from 'vs/editor/common/core/position';
import { IConfiguration } from 'vs/editor/common/editorCommon';
import { TokenizationRegistry } from 'vs/editor/common/modes';
import { editorCursorForeground, editorOverviewRulerBorder } from 'vs/editor/common/view/editorColorRegistry';
import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext';
import { ViewContext } from 'vs/editor/common/view/viewContext';
import * as viewEvents from 'vs/editor/common/view/viewEvents';
import { ITheme } from 'vs/platform/theme/common/themeService';

class Settings {

	public readonly lineHeight: number;
	public readonly pixelRatio: number;
	public readonly overviewRulerLanes: number;

	public readonly renderBorder: boolean;
	public readonly borderColor: string | null;

	public readonly hideCursor: boolean;
	public readonly cursorColor: string | null;

	public readonly themeType: 'light' | 'dark' | 'hc';
	public readonly backgroundColor: string | null;

	public readonly top: number;
	public readonly right: number;
	public readonly domWidth: number;
	public readonly domHeight: number;
	public readonly canvasWidth: number;
	public readonly canvasHeight: number;

	public readonly x: number[];
	public readonly w: number[];

	constructor(config: IConfiguration, theme: ITheme) {
		this.lineHeight = config.editor.lineHeight;
		this.pixelRatio = config.editor.pixelRatio;
		this.overviewRulerLanes = config.editor.viewInfo.overviewRulerLanes;

		this.renderBorder = config.editor.viewInfo.overviewRulerBorder;
		const borderColor = theme.getColor(editorOverviewRulerBorder);
		this.borderColor = borderColor ? borderColor.toString() : null;

		this.hideCursor = config.editor.viewInfo.hideCursorInOverviewRuler;
		const cursorColor = theme.getColor(editorCursorForeground);
		this.cursorColor = cursorColor ? cursorColor.transparent(0.7).toString() : null;

		this.themeType = theme.type;

		const minimapEnabled = config.editor.viewInfo.minimap.enabled;
		const minimapSide = config.editor.viewInfo.minimap.side;
		const backgroundColor = (minimapEnabled ? TokenizationRegistry.getDefaultBackground() : null);
		if (backgroundColor === null || minimapSide === 'left') {
			this.backgroundColor = null;
		} else {
			this.backgroundColor = Color.Format.CSS.formatHex(backgroundColor);
		}

		const position = config.editor.layoutInfo.overviewRuler;
		this.top = position.top;
		this.right = position.right;
		this.domWidth = position.width;
		this.domHeight = position.height;
		this.canvasWidth = (this.domWidth * this.pixelRatio) | 0;
		this.canvasHeight = (this.domHeight * this.pixelRatio) | 0;

		const [x, w] = this._initLanes(1, this.canvasWidth, this.overviewRulerLanes);
		this.x = x;
		this.w = w;
	}

	private _initLanes(canvasLeftOffset: number, canvasWidth: number, laneCount: number): [number[], number[]] {
		const remainingWidth = canvasWidth - canvasLeftOffset;

		if (laneCount >= 3) {
			const leftWidth = Math.floor(remainingWidth / 3);
			const rightWidth = Math.floor(remainingWidth / 3);
			const centerWidth = remainingWidth - leftWidth - rightWidth;
			const leftOffset = canvasLeftOffset;
			const centerOffset = leftOffset + leftWidth;
			const rightOffset = leftOffset + leftWidth + centerWidth;

			return [
				[
					0,
					leftOffset, // Left
					centerOffset, // Center
					leftOffset, // Left | Center
					rightOffset, // Right
					leftOffset, // Left | Right
					centerOffset, // Center | Right
					leftOffset, // Left | Center | Right
				], [
					0,
					leftWidth, // Left
					centerWidth, // Center
					leftWidth + centerWidth, // Left | Center
					rightWidth, // Right
					leftWidth + centerWidth + rightWidth, // Left | Right
					centerWidth + rightWidth, // Center | Right
					leftWidth + centerWidth + rightWidth, // Left | Center | Right
				]
			];
		} else if (laneCount === 2) {
			const leftWidth = Math.floor(remainingWidth / 2);
			const rightWidth = remainingWidth - leftWidth;
			const leftOffset = canvasLeftOffset;
			const rightOffset = leftOffset + leftWidth;

			return [
				[
					0,
					leftOffset, // Left
					leftOffset, // Center
					leftOffset, // Left | Center
					rightOffset, // Right
					leftOffset, // Left | Right
					leftOffset, // Center | Right
					leftOffset, // Left | Center | Right
				], [
					0,
					leftWidth, // Left
					leftWidth, // Center
					leftWidth, // Left | Center
					rightWidth, // Right
					leftWidth + rightWidth, // Left | Right
					leftWidth + rightWidth, // Center | Right
					leftWidth + rightWidth, // Left | Center | Right
				]
			];
		} else {
			const offset = canvasLeftOffset;
			const width = remainingWidth;

			return [
				[
					0,
					offset, // Left
					offset, // Center
					offset, // Left | Center
					offset, // Right
					offset, // Left | Right
					offset, // Center | Right
					offset, // Left | Center | Right
				], [
					0,
					width, // Left
					width, // Center
					width, // Left | Center
					width, // Right
					width, // Left | Right
					width, // Center | Right
					width, // Left | Center | Right
				]
			];
		}
	}

	public equals(other: Settings): boolean {
		return (
			this.lineHeight === other.lineHeight
			&& this.pixelRatio === other.pixelRatio
			&& this.overviewRulerLanes === other.overviewRulerLanes
			&& this.renderBorder === other.renderBorder
			&& this.borderColor === other.borderColor
			&& this.hideCursor === other.hideCursor
			&& this.cursorColor === other.cursorColor
			&& this.themeType === other.themeType
			&& this.backgroundColor === other.backgroundColor
			&& this.top === other.top
			&& this.right === other.right
			&& this.domWidth === other.domWidth
			&& this.domHeight === other.domHeight
			&& this.canvasWidth === other.canvasWidth
			&& this.canvasHeight === other.canvasHeight
		);
	}
}

const enum Constants {
	MIN_DECORATION_HEIGHT = 6
}

const enum OverviewRulerLane {
	Left = 1,
	Center = 2,
	Right = 4,
	Full = 7
}

export class DecorationsOverviewRuler extends ViewPart {

	private readonly _tokensColorTrackerListener: IDisposable;
	private readonly _domNode: FastDomNode<HTMLCanvasElement>;
	private _settings: Settings;
	private _cursorPositions: Position[];

	constructor(context: ViewContext) {
		super(context);

		this._domNode = createFastDomNode(document.createElement('canvas'));
		this._domNode.setClassName('decorationsOverviewRuler');
		this._domNode.setPosition('absolute');
		this._domNode.setLayerHinting(true);
		this._domNode.setAttribute('aria-hidden', 'true');

		this._updateSettings(false);

		this._tokensColorTrackerListener = TokenizationRegistry.onDidChange((e) => {
			if (e.changedColorMap) {
				this._updateSettings(true);
			}
		});

		this._cursorPositions = [];
	}

	public dispose(): void {
		super.dispose();
		this._tokensColorTrackerListener.dispose();
	}

	private _updateSettings(renderNow: boolean): boolean {
		const newSettings = new Settings(this._context.configuration, this._context.theme);
		if (this._settings && this._settings.equals(newSettings)) {
			// nothing to do
			return false;
		}

		this._settings = newSettings;

		this._domNode.setTop(this._settings.top);
		this._domNode.setRight(this._settings.right);
		this._domNode.setWidth(this._settings.domWidth);
		this._domNode.setHeight(this._settings.domHeight);
		this._domNode.domNode.width = this._settings.canvasWidth;
		this._domNode.domNode.height = this._settings.canvasHeight;

		if (renderNow) {
			this._render();
		}

		return true;
	}

	// ---- begin view event handlers

	public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
		return this._updateSettings(false);
	}
	public onCursorStateChanged(e: viewEvents.ViewCursorStateChangedEvent): boolean {
		this._cursorPositions = [];
		for (let i = 0, len = e.selections.length; i < len; i++) {
			this._cursorPositions[i] = e.selections[i].getPosition();
		}
		this._cursorPositions.sort(Position.compare);
		return true;
	}
	public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean {
		return true;
	}
	public onFlushed(e: viewEvents.ViewFlushedEvent): boolean {
		return true;
	}
	public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
		return e.scrollHeightChanged;
	}
	public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {
		return true;
	}
	public onThemeChanged(e: viewEvents.ViewThemeChangedEvent): boolean {
		// invalidate color cache
		this._context.model.invalidateOverviewRulerColorCache();
		return this._updateSettings(false);
	}

	// ---- end view event handlers

	public getDomNode(): HTMLElement {
		return this._domNode.domNode;
	}

	public prepareRender(ctx: RenderingContext): void {
		// Nothing to read
	}

	public render(editorCtx: RestrictedRenderingContext): void {
		this._render();
	}

	private _render(): void {
		const canvasWidth = this._settings.canvasWidth;
		const canvasHeight = this._settings.canvasHeight;
		const lineHeight = this._settings.lineHeight;
		const viewLayout = this._context.viewLayout;
		const outerHeight = this._context.viewLayout.getScrollHeight();
		const heightRatio = canvasHeight / outerHeight;
		const decorations = this._context.model.getAllOverviewRulerDecorations(this._context.theme);

		const minDecorationHeight = (Constants.MIN_DECORATION_HEIGHT * this._settings.pixelRatio) | 0;
		const halfMinDecorationHeight = (minDecorationHeight / 2) | 0;

		const canvasCtx = this._domNode.domNode.getContext('2d')!;
		if (this._settings.backgroundColor === null) {
			canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
		} else {
			canvasCtx.fillStyle = this._settings.backgroundColor;
			canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
		}

		const x = this._settings.x;
		const w = this._settings.w;
		// Avoid flickering by always rendering the colors in the same order
		// colors that don't use transparency will be sorted last (they start with #)
		const colors = Object.keys(decorations);
		colors.sort();
		for (let cIndex = 0, cLen = colors.length; cIndex < cLen; cIndex++) {
			const color = colors[cIndex];

			const colorDecorations = decorations[color];

			canvasCtx.fillStyle = color;

			let prevLane = 0;
			let prevY1 = 0;
			let prevY2 = 0;
			for (let i = 0, len = colorDecorations.length; i < len; i++) {
				const lane = colorDecorations[3 * i];
				const startLineNumber = colorDecorations[3 * i + 1];
				const endLineNumber = colorDecorations[3 * i + 2];

				let y1 = (viewLayout.getVerticalOffsetForLineNumber(startLineNumber) * heightRatio) | 0;
				let y2 = ((viewLayout.getVerticalOffsetForLineNumber(endLineNumber) + lineHeight) * heightRatio) | 0;
				let height = y2 - y1;
				if (height < minDecorationHeight) {
					let yCenter = ((y1 + y2) / 2) | 0;
					if (yCenter < halfMinDecorationHeight) {
						yCenter = halfMinDecorationHeight;
					} else if (yCenter + halfMinDecorationHeight > canvasHeight) {
						yCenter = canvasHeight - halfMinDecorationHeight;
					}
					y1 = yCenter - halfMinDecorationHeight;
					y2 = yCenter + halfMinDecorationHeight;
				}

				if (y1 > prevY2 + 1 || lane !== prevLane) {
					// flush prev
					if (i !== 0) {
						canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
					}
					prevLane = lane;
					prevY1 = y1;
					prevY2 = y2;
				} else {
					// merge into prev
					if (y2 > prevY2) {
						prevY2 = y2;
					}
				}
			}
			canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
		}

		// Draw cursors
		if (!this._settings.hideCursor && this._settings.cursorColor) {
			const cursorHeight = (2 * this._settings.pixelRatio) | 0;
			const halfCursorHeight = (cursorHeight / 2) | 0;
			const cursorX = this._settings.x[OverviewRulerLane.Full];
			const cursorW = this._settings.w[OverviewRulerLane.Full];
			canvasCtx.fillStyle = this._settings.cursorColor;

			let prevY1 = -100;
			let prevY2 = -100;
			for (let i = 0, len = this._cursorPositions.length; i < len; i++) {
				const cursor = this._cursorPositions[i];

				let yCenter = (viewLayout.getVerticalOffsetForLineNumber(cursor.lineNumber) * heightRatio) | 0;
				if (yCenter < halfCursorHeight) {
					yCenter = halfCursorHeight;
				} else if (yCenter + halfCursorHeight > canvasHeight) {
					yCenter = canvasHeight - halfCursorHeight;
				}
				const y1 = yCenter - halfCursorHeight;
				const y2 = y1 + cursorHeight;

				if (y1 > prevY2 + 1) {
					// flush prev
					if (i !== 0) {
						canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
					}
					prevY1 = y1;
					prevY2 = y2;
				} else {
					// merge into prev
					if (y2 > prevY2) {
						prevY2 = y2;
					}
				}
			}
			canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
		}

		if (this._settings.renderBorder && this._settings.borderColor && this._settings.overviewRulerLanes > 0) {
			canvasCtx.beginPath();
			canvasCtx.lineWidth = 1;
			canvasCtx.strokeStyle = this._settings.borderColor;
			canvasCtx.moveTo(0, 0);
			canvasCtx.lineTo(0, canvasHeight);
			canvasCtx.stroke();

			canvasCtx.moveTo(0, 0);
			canvasCtx.lineTo(canvasWidth, 0);
			canvasCtx.stroke();
		}
	}
}


text:
layout: post
title: "[Algorithm]Interval overlap merging"
description: ""
category:
tags: [Algorithm,C++]
---
# A Solution for interval overlap merging

### 题目描述

##### Input:   字符串,合法内容为"[A,B] [C,D] [E,F]",A,B,C,D,E,F为int类型,它们所表示的intervals都为闭区间。

##### Output:  将输入的首个interval看为一个集合,其余的intervals为另一个集合,查询第二个集合中和首个interval overlap的部分,并输出可能的intervals,升序并merge重合的部分。如果没有符合条件的interval,输出"Empty"

##### Example: "[2,9] [3,12] [-12,1]" 的输出为 "[3,9]"

### 解决思路
* 需要对输入字符串的输入进行合法性验证

#### 1. 声明下面的函数

{% highlight c++ %}
//Test
void TestIntervalFilter(void);
//finite closed interval struct
struct Interval
{
	Interval(const int &s, const int &e) : start(s), end(e){}
	int start;
	int end;
};
void CheckAndMergeIntervals(vector<Interval> &intervals);
bool ValidateAndGetIntervals(const string &input, Interval &seedInterval, vector<Interval> &intervals);
//Function entry for question two
void IntervalFilter(const string &input);
{% endhighlight %}

#### 2. TDD推荐首先设计单元测试用例

{% highlight c++ %}
void TestIntervalFilter(void)
{
	IntervalFilter("[6,27] [5,7] [21,34] [13,25]");
	IntervalFilter("[24,35] [3,20] [-2,9] [37,40]");

	//below test will output error message
	IntervalFilter("");
	IntervalFilter("[");
	IntervalFilter(" ");
	IntervalFilter("[]");
	IntervalFilter("[1,2]");
	IntervalFilter("[1,test]");
	IntervalFilter("[1,5] [2,10] ");

}
{% endhighlight %}

#### 3. 输入合法性验证的实现

{% highlight c++ %}
bool ValidateAndGetIntervals(const string &input, Interval &seedInterval, vector<Interval> &intervals)
{
	if(input.empty() || input[0] != '[' || input[input.length() - 1] != ']')
	{
		printf("invalid\n");
		return false;
	}

	string dataStr = input;
	int spaceIndex = dataStr.find_first_of(" ");
	if(spaceIndex <= 0)
	{
		printf("invalid\n");
		return false;
	}

	bool alreadyGetSeedInterval = false;
	while(spaceIndex > 0)
	{
		spaceIndex = dataStr.find_first_of(" ");
		string intervalStr = dataStr.substr(0, spaceIndex);
		if(intervalStr.length() < 3 || intervalStr[0] != '[' || intervalStr[intervalStr.length() - 1] != ']')
		{
			printf("invalid\n");
			return false;
		}
		int commaIndex = intervalStr.find(',');
		if(commaIndex <= 1)
		{
			printf("invalid\n");
			return false;
		}
		int start = atoi(intervalStr.substr(1,commaIndex).c_str());
		int end = atoi(intervalStr.substr(commaIndex + 1, intervalStr.length() - commaIndex - 1).c_str());
		if(start != 0 && end != 0 && start < end)
		{
			Interval currentInterval(start, end);
			if(!alreadyGetSeedInterval)
			{
				seedInterval = currentInterval;
				alreadyGetSeedInterval = true;
			}
			else
				intervals.push_back(currentInterval);
		}
		else
		{
			printf("invalid\n");
			return false;
		}

		if(spaceIndex < dataStr.length() - 1)
		{
			dataStr = dataStr.substr(spaceIndex + 1);
		}
		else
			break;
	}

	return true;
}
{% endhighlight %}

#### 4. 定义sort函数的比较算法

{% highlight c++ %}
bool Compare(Interval i1, Interval i2)
{
	return (i1.start < i2.start)? true: false;
}
{% endhighlight %}

#### 5. 对符合条件的intervals进行merge

{% highlight c++ %}
void CheckAndMergeIntervals(vector<Interval> &intervals)
{
	//Make sure the given intervals are not empty
	if (intervals.size() <= 0)
		return;

	vector<Interval> output;

	//Sort the given intervals according to their start number to asc order
	sort(intervals.begin(), intervals.end(), Compare);

	output.push_back(intervals[0]);

	for (unsigned int i = 1 ; i < intervals.size(); i++)
	{
		Interval last = output[output.size() - 1];

		//Add the current interval into the vector if it is not overlapping with the top last in it
		if (last.end < intervals[i].start)
		{
			output.push_back(intervals[i]);
		}

		//Update the last interval in the vector if necessary
		else if (last.end < intervals[i].end)
		{
			last.end = intervals[i].end;
			output[output.size() - 1] = last;
		}
	}

	for(vector<Interval>::const_iterator cit = output.begin(); cit != output.end(); ++cit)
	{
		Interval currInterval = *cit;
		printf("[%d,%d] ", currInterval.start, currInterval.end);
	}

	printf("\n");
}
{% endhighlight %}

#### 6. 解决问题的入口函数实现,从第二个intervals的集合中获取符合条件的intervals并调用上面的merge函数
{% highlight c++ %}
void IntervalFilter(const string &input)
{
	vector<Interval> intervals;
	Interval seedInterval(0,0);
	if(!ValidateAndGetIntervals(input, seedInterval, intervals))
		return;

	if(intervals.size() == 0)
		printf("invalid\n");

	vector<Interval> intervalsAfterSeedCompare;
	for(vector<Interval>::iterator it = intervals.begin(); it != intervals.end(); ++it)
	{
		Interval currentInterval = *it;

		if(currentInterval.end < seedInterval.start)
			continue;

		if(currentInterval.end == seedInterval.start)
		{
			currentInterval.start = currentInterval.end;
		}
		else if(currentInterval.end > seedInterval.start && currentInterval.end <= seedInterval.end)
		{
			if(currentInterval.start <= seedInterval.start)
				currentInterval.start = seedInterval.start;
		}
		else if(currentInterval.end > seedInterval.end)
		{
			if(currentInterval.start <= seedInterval.end)
			{
				currentInterval.end = seedInterval.end;
				if(currentInterval.start <= seedInterval.start)
					currentInterval.start = seedInterval.start;
			}
			else
				continue;
		}

		intervalsAfterSeedCompare.push_back(currentInterval);
	}

	if(intervalsAfterSeedCompare.size() > 0)
		CheckAndMergeIntervals(intervalsAfterSeedCompare);
	else
		printf("Empty\n");
}
{% endhighlight %}

#### 7. 在main函数中这样调用:

{% highlight c++ %}
int main()
{
	//Test question one
	TestIntervalFilter();

	return 0;
}
{% endhighlight %}

{% include JB/setup %}


text:
enum CollisionType
{
	PLAYER,
	PLAYER_ATTACK,
	ENEMY,
	ENEMY_ATTACK,
	WALL,
	NONE
};

extern bool ShouldColide[6][6];
// Example: lasers should not collide with lasers but should collider with walls
// enemy shots will collide with other enemies ? and against walls ?

class Entity;

struct Collider
{
	iRectangle3 rect = iRectangle3(0, 0, 0, 0, 0);
	bool to_delete = false;
	CollisionType type = NONE;

	Entity* attached = nullptr;

	Collider(iRectangle3 rectangle) : // expand this call if you need to
		rect(rectangle)
	{}

	void SetPos(int x, int y, int z)
	{
		rect.Position.x = x;
		rect.Position.y = y;
		rect.Position.z = z;
	}

	bool CheckCollision(const iRectangle3& r) const;
};

class ModuleCollision : public Module
{
public:

	ModuleCollision();
	~ModuleCollision();

	update_status PreUpdate();
	update_status Update();

	bool CleanUp();

	Collider* AddCollider(const iRectangle3& rect, Entity* attached);
	void DebugDraw();

private:

	std::list<Collider*> colliders;
	bool debug = false;
};

#endif // __ModuleCollision_H__


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Diagnostics;

namespace BulletSharp
{
    public class AlignedIndexedMeshArrayDebugView
    {
        private readonly AlignedIndexedMeshArray _array;

        public AlignedIndexedMeshArrayDebugView(AlignedIndexedMeshArray array)
        {
            _array = array;
        }

        [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
        public IndexedMesh[] Items
        {
            get
            {
                IndexedMesh[] array = new IndexedMesh[_array.Count];
                for (int i = 0; i < _array.Count; i++)
                {
                    array[i] = _array[i];
                }
                return array;
            }
        }
    }

    public class AlignedIndexedMeshArrayEnumerator : IEnumerator<IndexedMesh>
    {
        int _i;
        readonly int _count;
        readonly AlignedIndexedMeshArray _array;

        public AlignedIndexedMeshArrayEnumerator(AlignedIndexedMeshArray array)
        {
            _array = array;
            _count = array.Count;
            _i = -1;
        }

        public IndexedMesh Current
        {
            get { return _array[_i]; }
        }

        public void Dispose()
        {
        }

        object System.Collections.IEnumerator.Current
        {
            get { return _array[_i]; }
        }

        public bool MoveNext()
        {
            _i++;
            return _i != _count;
        }

        public void Reset()
        {
            _i = 0;
        }
    }

    [Serializable, DebuggerTypeProxy(typeof(AlignedIndexedMeshArrayDebugView)), DebuggerDisplay("Count = {Count}")]
    public class AlignedIndexedMeshArray : IList<IndexedMesh>
    {
        private IntPtr _native;

        internal AlignedIndexedMeshArray(IntPtr native)
        {
            _native = native;
        }

        public int IndexOf(IndexedMesh item)
        {
            throw new NotImplementedException();
        }

        public void Insert(int index, IndexedMesh item)
        {
            throw new NotImplementedException();
        }

        public void RemoveAt(int index)
        {
            throw new NotImplementedException();
        }

        public IndexedMesh this[int index]
        {
            get
            {
                if ((uint)index >= (uint)Count)
                {
                    throw new ArgumentOutOfRangeException("index");
                }
                return new IndexedMesh(btAlignedIndexedMeshArray_at(_native, index), true);
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void Add(IndexedMesh item)
        {
            btAlignedIndexedMeshArray_push_back(_native, item._native);
        }

        public void Clear()
        {
            btAlignedIndexedMeshArray_resizeNoInitialize(_native, 0);
        }

        public bool Contains(IndexedMesh item)
        {
            throw new NotImplementedException();
        }

        public void CopyTo(IndexedMesh[] array, int arrayIndex)
        {
            if (array == null)
                throw new ArgumentNullException("array");

            if (arrayIndex < 0)
                throw new ArgumentOutOfRangeException("array");

            int count = Count;
            if (arrayIndex + count > array.Length)
                throw new ArgumentException("Array too small.", "array");

            for (int i = 0; i < count; i++)
            {
                array[arrayIndex + i] = this[i];
            }
        }

        public int Count
        {
            get { return btAlignedIndexedMeshArray_size(_native); }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(IndexedMesh item)
        {
            throw new NotImplementedException();
        }

        public IEnumerator<IndexedMesh> GetEnumerator()
        {
            return new AlignedIndexedMeshArrayEnumerator(this);
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return new AlignedIndexedMeshArrayEnumerator(this);
        }

        [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
        static extern IntPtr btAlignedIndexedMeshArray_at(IntPtr obj, int n);
        [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
        static extern void btAlignedIndexedMeshArray_push_back(IntPtr obj, IntPtr val);
        [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
        static extern void btAlignedIndexedMeshArray_resizeNoInitialize(IntPtr obj, int newSize);
        [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
        static extern int btAlignedIndexedMeshArray_size(IntPtr obj);
    }
}


text:
<?php

class Google_Service_AndroidProvisioningPartner_ListCustomersResponse extends Google_Collection
{
  protected $collection_key = 'customers';
  protected $customersType = 'Google_Service_AndroidProvisioningPartner_Company';
  protected $customersDataType = 'array';

  /**
   * @param Google_Service_AndroidProvisioningPartner_Company
   */
  public function setCustomers($customers)
  {
    $this->customers = $customers;
  }
  /**
   * @return Google_Service_AndroidProvisioningPartner_Company
   */
  public function getCustomers()
  {
    return $this->customers;
  }
}


text:
import React from 'react';
import { Grid, Row, Col } from 'react-bootstrap';
import ShaderController from './shader-controller';
import MusicController from './music-controller';
import VolumeController from './volume-controller';

let ShaderPlayer = React.createClass({
  render() {
    return (
      <div>
        <MusicController {...this.props} />
        <VolumeController {...this.props} />
        <ShaderController {...this.props} />
      </div>
    );
  }
});

module.exports = ShaderPlayer;


text:
"""
This module provides various classes for specifying what a particular syntax
diagram (a.k.a. railroad diagram) should look like.

The actual drawing of diagrams created with classes in this module is left up
to other modules included with Parcon in order to allow railroad diagrams that
look different to be created. The main one of these is the submodule raildraw,
which is a from-scratch railroad diagram drawing engine that can take a
railroad diagram as specified by classes in this module and convert it to a PNG
image.

Here's a really simple example that uses raildraw to draw a syntax diagram:

from parcon import First
# Create a parser to draw
some_parser = "Hello, " + First("world", "all you people")
# Then draw a diagram of it.
some_parser.draw_railroad_to_png({}, "test.png")
"""

from itertools import chain
from parcon import ordered_dict

PRODUCTION = 1
TEXT = 2
ANYCASE = 3
DESCRIPTION = 4

class Component(object):
    def copy(self):
        raise NotImplementedError

    def optimize(self):
        pass

    def __repr__(self):
        return self.__str__()

class Nothing(Component):
    def copy(self):
        return Nothing()

    def __str__(self):
        return "Nothing()"

class Then(Component):
    def __init__(self, *constructs):
        self.constructs = list(constructs)

    def copy(self):
        return Then(*[c.copy() for c in self.constructs])

    def optimize(self):
        modified = True
        while modified:
            modified = False
            old_constructs = self.constructs
            new_constructs = list(chain(*[c.constructs if isinstance(c, Then) else [c] for c in old_constructs if not isinstance(c, Nothing)]))
            if old_constructs != new_constructs:
                modified = True
            self.constructs = new_constructs
        for construct in self.constructs:
            construct.optimize()

    def __str__(self):
        return "Then(%s)" % ", ".join([repr(c) for c in self.constructs])

class Or(Component):
    def __init__(self, *constructs):
        self.constructs = list(constructs)

    def copy(self):
        return Or(*[c.copy() for c in self.constructs])

    def optimize(self):
        modified = True
        while modified:
            modified = False
            old_constructs = self.constructs
            new_constructs = list(chain(*[c.constructs if isinstance(c, Or) else [c] for c in old_constructs]))
            if old_constructs != new_constructs:
                modified = True
            self.constructs = new_constructs
        for construct in self.constructs:
            construct.optimize()

    def __str__(self):
        return "Or(%s)" % ", ".join([repr(c) for c in self.constructs])

class Token(Component):
    def __init__(self, type, text):
        assert type >= 1 and type <= 4
        self.type = type
        self.text = text

    def copy(self):
        return Token(self.type, self.text)

    def __str__(self):
        return "Token(%s, %s)" % (repr(self.type), repr(self.text))

class Loop(Component):
    def __init__(self, component, delimiter):
        self.component = component
        self.delimiter = delimiter

    def copy(self):
        return Loop(self.component.copy(), self.delimiter.copy())

    def optimize(self):
        if isinstance(self.component, Loop):
            self.component, self.delimiter = self.component.component, Or(self.component.delimiter, self.delimiter)
            self.optimize()
            return
        self.component.optimize()
        self.delimiter.optimize()

    def __str__(self):
        return "Loop(%s, %s)" % (repr(self.component), repr(self.delimiter))

class Bullet(Component):
    def copy(self):
        return Bullet()

    def __str__(self):
        return "Bullet()"

class Railroadable(object):
    """
    A class representing an object that can be drawn as a railroad diagram.
    Most Parcon parsers subclass this class in addition to parcon.Parser.
    """
    railroad_children = []
    railroad_production_name = None
    railroad_production_delegate = None

    def create_railroad(self, options):
        raise NotImplementedError

    def get_productions(self):
        map = ordered_dict.OrderedDict()
        visited = set()
        self._list_productions(map, visited)
        # TODO: in the future, check that each possible result for a given
        # production generates a railroad that means syntactically the same
        # thing. For now, we're just going to use the first one in the list.
        return ordered_dict.OrderedDict([(k, v[0]) for k, v in map.items()])

    def _list_productions(self, map, visited):
        if self in visited: # Already visited this object
            return
        visited.add(self)
        if self.railroad_production_name is not None:
            the_list = map.get(self.name, None)
            if not the_list:
                the_list = []
                map[self.name] = the_list
            if self.railroad_production_delegate not in the_list:
                the_list.append(self.railroad_production_delegate)
        for r in self.railroad_children:
            ensure_railroadable(r)
            r._list_productions(map, visited)

    def draw_railroad_to_png(self, options, filename):
        """
        Draws a syntax diagram for this object to the specified .png image file
        using the specified options. For now, just pass {} (i.e. an empty
        dictionary) as options; I'll document what this actually does at a
        later date.
        """
        # raildraw /has/ to be imported here, not at the top of the module,
        # because it depends on us and circular dependency issues will arise
        # if the import is done at the top of this module
        from parcon.railroad import raildraw as _raildraw
        diagram = Then(Bullet(), self.create_railroad(options), Bullet())
        _raildraw.draw_to_png(diagram, options, filename)
        del _raildraw

    def draw_productions_to_png(self, options, filename, tail=[]):
        productions = self.get_productions()
        if len(productions) == 0:
            raise Exception("No named productions to generate")
        # Sort the specified tail productions to the end
        for name in tail:
            if name in productions:
                value = productions[name]
                del productions[name]
                productions[name] = value
        from parcon.railroad import raildraw as _raildraw
        _raildraw.draw_to_png(ordered_dict.OrderedDict([(k,
            Then(Bullet(), v.create_railroad(options), Bullet()))
            for k, v in productions.items()]), options, filename)
        del _raildraw

def ensure_railroadable(value):
    if not isinstance(value, Railroadable):
        raise Exception("Trying to create a railroad diagram for an object of "
                        "class " + str(type(value)) + " but that type is not a "
                        "subclass of Railroadable, so this is not allowed.")

def create_railroad(value, options):
    ensure_railroadable(value)
    return value.create_railroad(options)


text:
<!DOCTYPE html>

    <% include ../common/head.html %>

    <% include ../common/header.html %>

    <% include ../common/aside.html %>

                500 Error Page

 Home

Examples

500 error

500

 Oops! Something went wrong.

                        We will work on fixing that right away.
                        Meanwhile, you may return to dashboard or try using the search
                        form.

                    <form class="search-form">

                            <input type="text" name="search" class="form-control" placeholder="Search">

                                <button type="submit" name="submit" class="btn btn-danger btn-flat">
                                </button>

                    </form>

    <% include ../common/footer.html %>

    <% include ../common/right-aside.html %>

<% include ../common/script.html %>


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

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:textColor="@color/chocolate"
        android:layout_height="wrap_content"
        android:textSize="@dimen/ts_huge"/>

    <TextView
        android:id="@+id/tv_age"
        android:layout_width="wrap_content"
        android:textColor="@color/chocolate"
        android:layout_height="wrap_content"
        android:textSize="@dimen/ts_huge"/>

</LinearLayout>


text:
import { NgModule } from '@angular/core';
import { AuditLogComponent } from './audit-log.component';
import { SharedModule } from '../shared/shared.module';
import { AuditLogService } from './audit-log.service';
import { LogPageComponent } from './log-page.component';

@NgModule({
  imports: [SharedModule],
  declarations: [
    AuditLogComponent,
    LogPageComponent
  ],
  providers: [AuditLogService],
  exports: [
    AuditLogComponent,
    LogPageComponent]
})
export class LogModule { }


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

<TITLE>
ColumnData (Jemboss API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.emboss.jemboss.gui

Class  ColumnData

java.lang.Object
  |
  +--org.emboss.jemboss.gui.ColumnData

 class ColumnData
extends java.lang.Object

Content of each column in the DragJTable

Field Summary

protected  int
alignment

protected  java.lang.String
title

protected  int
width

Constructor Summary

ColumnData(java.lang.String title,
           int width,
           int alignment)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

title

protected java.lang.String title

width

protected int width

alignment

protected int alignment

Constructor Detail

ColumnData

public ColumnData(java.lang.String title,
                  int width,
                  int alignment)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
#region Licence

#endregion

using System;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Paramore.Brighter.Logging;

namespace Paramore.Brighter.Logging.Handlers
{
    /// <summary>
    /// Class AsyncRequestLoggingHandler.
    /// Logs a request to a <see cref="IHandleRequestsAsync"/> handler using the Common.Logging logger registered with the <see cref="CommandProcessor"/>
    /// The log shows the original <see cref="IRequest"/> properties as well as the timer handling.
    /// </summary>
    /// <typeparam name="TRequest">The type of the t request.</typeparam>
    public class RequestLoggingHandlerAsync<TRequest> : RequestHandlerAsync<TRequest> where TRequest : class, IRequest
    {
        private static readonly Lazy<ILog> _logger = new Lazy<ILog>(LogProvider.For<RequestLoggingHandlerAsync<TRequest>>);

        private HandlerTiming _timing;

        /// <summary>
        /// Initializes from attribute parameters.
        /// </summary>
        /// <param name="initializerList">The initializer list.</param>
        public override void InitializeFromAttributeParams(params object[] initializerList)
        {
            _timing = (HandlerTiming)initializerList[0];
        }

        /// <summary>
        /// Awaitably handles the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="cancellationToken">Allows the sender to cancel the request. Optional.</param>
        /// <returns>Awaitable <see cref="Task{TRequest}"/>.</returns>
        public override async Task<TRequest> HandleAsync(TRequest command, CancellationToken cancellationToken = default(CancellationToken))
        {
            LogCommand(command);
            return await base.HandleAsync(command, cancellationToken).ConfigureAwait(ContinueOnCapturedContext);
        }

        /// <summary>
        /// If a request cannot be completed by <see cref="RequestHandlerAsync{TRequest}.HandleAsync"/>, implementing the <see cref="RequestHandlerAsync{TRequest}.FallbackAsync"/> method provides an alternate code path that can be used
        /// This allows for graceful  degradation. Using the <see cref="AsyncFallbackPolicyAttribute"/> handler you can configure a policy to catch either all <see cref="Exception"/>'s or
        /// just <see cref="BrokenCircuitException"/> that occur later in the pipeline, and then call the <see cref="RequestHandler{TRequest}.Fallback"/> path.
        /// Note that the <see cref="AsyncFallbackPolicyAttribute"/> target handler might be 'beginning of chain' and need to pass through to actual handler that is end of chain.
        /// Because of this we need to call Fallback on the chain. Later step handlers don't know the context of failure so they cannot know if any operations they had,
        /// that could fail (such as DB access) were the cause of the failure chain being hit.
        /// Steps that don't know how to handle should pass through.
        /// Useful alternatives for Fallback are to try via the cache.
        /// Note that a Fallback handler implementation should not catch exceptions in the <see cref="RequestHandler{TRequest}.Fallback"/> chain to avoid an infinite loop.
        /// Call <see cref="RequestHandlerAsync{TRequest}.Successor"/>.<see cref="RequestHandlerAsync{TRequest}.HandleAsync"/> if having provided a Fallback you want the chain to return to the 'happy' path. Excerise caution here though
        /// as you do not know who generated the exception that caused the fallback chain.
        /// For this reason, the <see cref="AsyncFallbackPolicyHandler{TRequest}"/> puts the exception in the request context.
        /// When the <see cref="FallbackPolicyAttribute"/> is set on the <see cref="RequestHandler{TRequest}.Handle"/> method of a derived class
        /// The <see cref="AsyncFallbackPolicyHandler{TRequest}"/> will catch either all failures (backstop) or <see cref="AsyncBrokenCircuitException"/> depending on configuration
        /// and call the <see cref="RequestHandlerAsync{TRequest}"/>'s <see cref="RequestHandlerAsync{TRequest}.FallbackAsync"/> method
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="cancellationToken">Allows the sender to cancel the request. Optional.</param>
        /// <returns>TRequest.</returns>
        public override async Task<TRequest> FallbackAsync(TRequest command, CancellationToken cancellationToken = default(CancellationToken))
        {
            LogFailure(command);
            return await base.FallbackAsync(command, cancellationToken).ConfigureAwait(ContinueOnCapturedContext);
        }

        private void LogCommand(TRequest request)
        {
            //TODO: LibLog has no async support, so remains a blocking call for now
            _logger.Value.InfoFormat("Logging handler pipeline call. Pipeline timing {0} target, for {1} with values of {2} at: {3}", _timing.ToString(), typeof(TRequest), JsonConvert.SerializeObject(request), DateTime.UtcNow);
        }

        private void LogFailure(TRequest request)
        {
            //TODO: LibLog has no async support, so remains a blocking call for now
            _logger.Value.InfoFormat("Failure in pipeline call for {0} with values of {1} at: {2}", typeof(TRequest), JsonConvert.SerializeObject(request), DateTime.UtcNow);
        }
    }
}


text:
/**
 * @file mip-st-detail 组件
 * @author
 */

/* global MIP, m */
define(function (require) {
    'use strict';

    var customElement = require('customElement').create();

    var viewer = require('viewer');

    function getQuery(url) {
        url = url || location.href;
        var query = url.split('?')[1] || '';
        query = query.split('#')[0] || '';
        if (!query) {
            return {};
        }
        return query.split('&').reduce(function (obj, item) {
            var data = item.split('=');
            obj[data[0]] = decodeURIComponent(data[1]);
            return obj;
        }, {});
    }

    /**
     * 第一次进入可视区回调,只会执行一次
     */
    customElement.prototype.firstInviewCallback = function () {
        var element = this.element;
        var url = element.getAttribute('url');
        var productid = getQuery().product_id;
        var xzhid = getQuery().xzh_id;
        if (productid) {
            url += '?product_id=' + productid;
        }
        else if (xzhid) {
            url += '?xzh_id=' + xzhid;
        }
        if (m.currentTab) {
            url += '&spu_cate=' + m.currentTab;
        }
        fetch(url, {
        }).then(function (res) {
            return res.json();
        }).then(function (res) {
            res.data.list = res.data.list || [];
            MIP.setData({
                data: res.data
            });
            var url = location.href;
            if (!/tag=/.test(url)) {
                url = url.replace('?', '?tag=all&');
            }
            history.replaceState('', null, url);
            viewer.eventAction.execute('dataloaded', element, res.data);
        });
    };

    customElement.prototype.prerenderAllowed = function () {
        return true;
    };

    return customElement;
});