text:
package org.apache.asterix.external.dataflow;

import java.io.IOException;

import org.apache.asterix.external.api.ITupleForwarder;
import org.apache.asterix.external.util.DataflowUtils;
import org.apache.asterix.external.util.FeedLogManager;
import org.apache.hyracks.api.comm.IFrame;
import org.apache.hyracks.api.comm.IFrameWriter;
import org.apache.hyracks.api.comm.VSizeFrame;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.util.HyracksConstants;
import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;
import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender;
import org.apache.hyracks.dataflow.common.comm.util.FrameUtils;
import org.apache.hyracks.dataflow.common.io.MessagingFrameTupleAppender;
import org.apache.hyracks.dataflow.common.utils.TaskUtil;

public class FeedTupleForwarder implements ITupleForwarder {

    private final FeedLogManager feedLogManager;
    private FrameTupleAppender appender;
    private IFrame frame;
    private IFrameWriter writer;
    private boolean paused = false;
    private boolean initialized;

    public FeedTupleForwarder(FeedLogManager feedLogManager) {
        this.feedLogManager = feedLogManager;
    }

    public FeedLogManager getFeedLogManager() {
        return feedLogManager;
    }

    @Override
    public void initialize(IHyracksTaskContext ctx, IFrameWriter writer) throws HyracksDataException {
        if (!initialized) {
            this.frame = new VSizeFrame(ctx);
            this.writer = writer;
            this.appender = new FrameTupleAppender(frame);
            // Set null feed message
            VSizeFrame message = TaskUtil.<VSizeFrame> get(HyracksConstants.KEY_MESSAGE, ctx);
            // a null message
            message.getBuffer().put(MessagingFrameTupleAppender.NULL_FEED_MESSAGE);
            message.getBuffer().flip();
            initialized = true;
        }
    }

    @Override
    public void addTuple(ArrayTupleBuilder tb) throws HyracksDataException {
        if (paused) {
            synchronized (this) {
                while (paused) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        throw new HyracksDataException(e);
                    }
                }
            }
        }
        DataflowUtils.addTupleToFrame(appender, tb, writer);
    }

    public void pause() {
        paused = true;
    }

    public synchronized void resume() {
        paused = false;
        notifyAll();
    }

    @Override
    public void close() throws HyracksDataException {
        Throwable throwable = null;
        try {
            if (appender.getTupleCount() > 0) {
                FrameUtils.flushFrame(frame.getBuffer(), writer);
            }
        } catch (Throwable th) {
            throwable = th;
            throw th;
        } finally {
            try {
                feedLogManager.close();
            } catch (IOException e) {
                if (throwable != null) {
                    throwable.addSuppressed(e);
                } else {
                    throw new HyracksDataException(e);
                }
            } catch (Throwable th) {
                if (throwable != null) {
                    throwable.addSuppressed(th);
                } else {
                    throw th;
                }
            }
        }
    }

    public void flush() throws HyracksDataException {
        appender.flush(writer);
    }
}


text:
package com.stratio.deep.commons.extractor.client.codecs;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.stratio.deep.commons.extractor.actions.Action;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class ActionEncoder extends MessageToByteEncoder<Action> {

    private static final Logger LOG = LoggerFactory.getLogger(ActionEncoder.class);

    protected void encode(ChannelHandlerContext ctx, Action action, ByteBuf out) {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput outObj = null;

        try {
            outObj = new ObjectOutputStream(bos);
            outObj.writeObject(action);
        } catch (IOException e) {
            LOG.error(e.getMessage());
        } finally {
            try {
                if (outObj != null) {
                    outObj.close();
                }
            } catch (IOException ex) {
                // ignore close exception
            }
            try {
                bos.close();
            } catch (IOException ex) {
                // ignore close exception
            }
        }

        byte[] encodedObj = bos.toByteArray();
        int dataLength = encodedObj.length;
        out.writeInt(dataLength);
        out.writeBytes(encodedObj);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import {
  assert, expect
} from 'chai';
import {
  ADAPTER_VERSION,
  DOMAIN,
  DOMAIN_DEVELOPMENT,
  DOMAIN_STAGING,
  domain,
  BIDDER_PATH,
  bidderUrl,
  buildRequests,
  conformBidRequest,
  DEFAULT_ENV,
  DEVELOPMENT,
  EVENTS_PATH,
  eventsUrl,
  getDeviceDimensions,
  getDeviceInfo,
  getDocumentDimensions,
  getUserSyncs,
  getViewDimensions,
  interpretResponse,
  isBidRequestValid,
  isWebGLEnabled,
  ON_ADAPTER_CALLED,
  ON_BID_WON,
  ON_BIDDER_TIMEOUT,
  onBidWon,
  onAdapterCalled,
  onTimeout,
  PRODUCTION,
  requestsPayload,
  resolveDebug,
  resolveEnv,
  spec,
  STAGING,
  USER_SYNC_IFRAME_PATH,
  USER_SYNC_IMAGE_PATH,
  userSyncIframeUrl,
  userSyncImageUrl,
} from 'modules/emoteevBidAdapter';
import * as url from '../../../src/url';
import * as utils from '../../../src/utils';
import * as pubCommonId from '../../../modules/pubCommonId';
import {config} from '../../../src/config';

const cannedValidBidRequests = [{
  adUnitCode: '/19968336/header-bid-tag-1',
  auctionId: 'fcbf2b27-a951-496f-b5bb-1324ce7c0558',
  bidId: '2b8de6572e8193',
  bidRequestsCount: 1,
  bidder: 'emoteev',
  bidderRequestId: '1203b39fecc6a5',
  crumbs: {pubcid: 'f3371d16-4e8b-42b5-a770-7e5be1fdf03d'},
  params: {adSpaceId: 5084},
  sizes: [[300, 250], [250, 300], [300, 600]],
  transactionId: '58dbd732-7a39-45f1-b23e-1c24051a941c',
}];
const cannedBidderRequest = {
  auctionId: 'fcbf2b27-a951-496f-b5bb-1324ce7c0558',
  auctionStart: 1544200122837,
  bidderCode: 'emoteev',
  bidderRequestId: '1203b39fecc6a5',
  doneCbCallCount: 0,
  refererInfo: {
    canonicalUrl: undefined,
    numIframes: 0,
    reachedTop: true,
    referer: 'http://localhost:9999/integrationExamples/gpt/hello_world_emoteev.html',
    stack: ['http://localhost:9999/integrationExamples/gpt/hello_world_emoteev.html']
  },
  start: 1544200012839,
  timeout: 3000,
  gdprConsent: {
    gdprApplies: true,
    consentString: 'my consentString'
  }
};
const serverResponse =
  {
    body: [
      {
        requestId: cannedValidBidRequests[0].bidId,
        cpm: 1,
        width: cannedValidBidRequests[0].sizes[0][0],
        height: cannedValidBidRequests[0].sizes[0][1],
        ad: '

',
        ttl: 360,
        creativeId: 123,
        netRevenue: false,
        currency: 'EUR',
      }
    ]
  };

describe('emoteevBidAdapter', function () {
  describe('isBidRequestValid', function () {
    it('should return true when valid', function () {
      const validBid = {
        bidder: 'emoteev',
        bidId: '23a45b4e3',
        params: {
          adSpaceId: 12345,
        },
        mediaTypes: {
          banner: {
            sizes: [[750, 200]]
          }
        },
      };
      expect(isBidRequestValid(validBid)).to.equal(true);

      expect(spec.isBidRequestValid(validBid)).to.exist.and.to.be.a('boolean');
      expect(spec.isBidRequestValid({})).to.exist.and.to.be.a('boolean');
    });

    it('should return false when required params are invalid', function () {
      expect(isBidRequestValid({
        bidder: '', // invalid bidder
        params: {
          adSpaceId: 12345,
        },
        mediaTypes: {
          banner: {
            sizes: [[750, 200]]
          }
        },
      })).to.equal(false);
      expect(isBidRequestValid({
        bidder: 'emoteev',
        params: {
          adSpaceId: '', // invalid adSpaceId
        },
        mediaTypes: {
          banner: {
            sizes: [[750, 200]]
          }
        },
      })).to.equal(false);
      expect(isBidRequestValid({
        bidder: 'emoteev',
        params: {
          adSpaceId: 12345,
        },
        mediaTypes: {
          banner: {
            sizes: [[750]] // invalid size
          }
        },
      })).to.equal(false);
    });
  });

  describe('buildRequests', function () {
    const
      env = DEFAULT_ENV,
      debug = true,
      currency = 'EUR',
      request = buildRequests(env, debug, currency, cannedValidBidRequests, cannedBidderRequest);

    expect(request).to.exist.and.have.all.keys(
      'method',
      'url',
      'data',
    );

    expect(request.method).to.equal('POST');
    expect(request.url).to.equal(bidderUrl(env));

    expect(spec.buildRequests(cannedValidBidRequests, cannedBidderRequest)).to.exist.and.to.be.an('object');
  });

  describe('interpretResponse', function () {
    it('bid objects from response', function () {
      const bidResponses = interpretResponse(serverResponse);
      expect(bidResponses).to.be.an('array').that.is.not.empty;
      expect(bidResponses[0]).to.have.property('requestId', cannedValidBidRequests[0].bidId);
      expect(bidResponses[0]).to.have.property('cpm', serverResponse.body[0].cpm);
      expect(bidResponses[0]).to.have.property('width', serverResponse.body[0].width);
      expect(bidResponses[0]).to.have.property('height', serverResponse.body[0].height);
      expect(bidResponses[0]).to.have.property('ad', serverResponse.body[0].ad);
      expect(bidResponses[0]).to.have.property('ttl', serverResponse.body[0].ttl);
      expect(bidResponses[0]).to.have.property('creativeId', serverResponse.body[0].creativeId);
      expect(bidResponses[0]).to.have.property('netRevenue', serverResponse.body[0].netRevenue);
      expect(bidResponses[0]).to.have.property('currency', serverResponse.body[0].currency);
    });
  });

  describe('onAdapterCalled', function () {
    const
      bidRequest = cannedValidBidRequests[0],
      url = onAdapterCalled(DEFAULT_ENV, bidRequest);

    expect(url).to.have.property('protocol');
    expect(url).to.have.property('hostname');
    expect(url).to.have.property('pathname', EVENTS_PATH);
    expect(url).to.have.nested.property('search.eventName', ON_ADAPTER_CALLED);
    expect(url).to.have.nested.property('search.pubcId', bidRequest.crumbs.pubcid);
    expect(url).to.have.nested.property('search.bidId', bidRequest.bidId);
    expect(url).to.have.nested.property('search.adSpaceId', bidRequest.params.adSpaceId);
    expect(url).to.have.nested.property('search.cache_buster');
  });

  describe('onBidWon', function () {
    const
      pubcId = cannedValidBidRequests[0].crumbs.pubcid,
      bidObject = serverResponse.body[0],
      url = onBidWon(DEFAULT_ENV, pubcId, bidObject);

    expect(url).to.have.property('protocol');
    expect(url).to.have.property('hostname');
    expect(url).to.have.property('pathname', EVENTS_PATH);
    expect(url).to.have.nested.property('search.eventName', ON_BID_WON);
    expect(url).to.have.nested.property('search.pubcId', pubcId);
    expect(url).to.have.nested.property('search.bidId', bidObject.requestId);
    expect(url).to.have.nested.property('search.cache_buster');
  });

  describe('onTimeout', function () {
    const
      data = {
        ...cannedValidBidRequests[0],
        timeout: 123,
      },
      url = onTimeout(DEFAULT_ENV, data);

    expect(url).to.have.property('protocol');
    expect(url).to.have.property('hostname');
    expect(url).to.have.property('pathname', EVENTS_PATH);
    expect(url).to.have.nested.property('search.eventName', ON_BIDDER_TIMEOUT);
    expect(url).to.have.nested.property('search.bidId', data.bidId);
    expect(url).to.have.nested.property('search.pubcId', data.crumbs.pubcid);
    expect(url).to.have.nested.property('search.adSpaceId', data.params.adSpaceId);
    expect(url).to.have.nested.property('search.timeout', data.timeout);
    expect(url).to.have.nested.property('search.cache_buster');
  });

  describe('getUserSyncs', function () {
    expect(getUserSyncs(
      DEFAULT_ENV,
      {
        iframeEnabled: false,
        pixelEnabled: false
      })).to.deep.equal([]);
    expect(getUserSyncs(
      PRODUCTION,
      {
        iframeEnabled: false,
        pixelEnabled: true
      })).to.deep.equal([{
      type: 'image',
      url: userSyncImageUrl(PRODUCTION)
    }]);
    expect(getUserSyncs(
      STAGING,
      {
        iframeEnabled: true,
        pixelEnabled: false
      })).to.deep.equal([{
      type: 'iframe',
      url: userSyncIframeUrl(STAGING)
    }]);
    expect(getUserSyncs(
      DEVELOPMENT,
      {
        iframeEnabled: true,
        pixelEnabled: true
      })).to.deep.equal([{
      type: 'image',
      url: userSyncImageUrl(DEVELOPMENT)
    }, {
      type: 'iframe',
      url: userSyncIframeUrl(DEVELOPMENT)
    }]);
  });

  describe('domain', function () {
    expect(domain(null)).to.deep.equal(DOMAIN);
    expect(domain('anything')).to.deep.equal(DOMAIN);
    expect(domain(PRODUCTION)).to.deep.equal(DOMAIN);
    expect(domain(STAGING)).to.deep.equal(DOMAIN_STAGING);
    expect(domain(DEVELOPMENT)).to.deep.equal(DOMAIN_DEVELOPMENT);
  });

  describe('eventsUrl', function () {
    expect(eventsUrl(null)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(DEFAULT_ENV),
      pathname: EVENTS_PATH
    }));
    expect(eventsUrl('anything')).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(DEFAULT_ENV),
      pathname: EVENTS_PATH
    }));
    expect(eventsUrl(PRODUCTION)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(PRODUCTION),
      pathname: EVENTS_PATH
    }));
    expect(eventsUrl(STAGING)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(STAGING),
      pathname: EVENTS_PATH
    }));
    expect(eventsUrl(DEVELOPMENT)).to.deep.equal(url.format({
      hostname: domain(DEVELOPMENT),
      pathname: EVENTS_PATH
    }));
  });

  describe('bidderUrl', function () {
    expect(bidderUrl(null)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(DEFAULT_ENV),
      pathname: BIDDER_PATH
    }));
    expect(bidderUrl('anything')).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(DEFAULT_ENV),
      pathname: BIDDER_PATH
    }));
    expect(bidderUrl(PRODUCTION)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(PRODUCTION),
      pathname: BIDDER_PATH
    }));
    expect(bidderUrl(STAGING)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(STAGING),
      pathname: BIDDER_PATH
    }));
    expect(bidderUrl(DEVELOPMENT)).to.deep.equal(url.format({
      hostname: domain(DEVELOPMENT),
      pathname: BIDDER_PATH
    }));
  });

  describe('userSyncIframeUrl', function () {
    expect(userSyncIframeUrl(null)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(DEFAULT_ENV),
      pathname: USER_SYNC_IFRAME_PATH
    }));
    expect(userSyncIframeUrl('anything')).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(DEFAULT_ENV),
      pathname: USER_SYNC_IFRAME_PATH
    }));
    expect(userSyncIframeUrl(PRODUCTION)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(PRODUCTION),
      pathname: USER_SYNC_IFRAME_PATH
    }));
    expect(userSyncIframeUrl(STAGING)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(STAGING),
      pathname: USER_SYNC_IFRAME_PATH
    }));
    expect(userSyncIframeUrl(DEVELOPMENT)).to.deep.equal(url.format({
      hostname: domain(DEVELOPMENT),
      pathname: USER_SYNC_IFRAME_PATH
    }));
  });

  describe('userSyncImageUrl', function () {
    expect(userSyncImageUrl(null)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(DEFAULT_ENV),
      pathname: USER_SYNC_IMAGE_PATH
    }));
    expect(userSyncImageUrl('anything')).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(DEFAULT_ENV),
      pathname: USER_SYNC_IMAGE_PATH
    }));
    expect(userSyncImageUrl(PRODUCTION)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(PRODUCTION),
      pathname: USER_SYNC_IMAGE_PATH
    }));
    expect(userSyncImageUrl(STAGING)).to.deep.equal(url.format({
      protocol: 'https',
      hostname: domain(STAGING),
      pathname: USER_SYNC_IMAGE_PATH
    }));
    expect(userSyncImageUrl(DEVELOPMENT)).to.deep.equal(url.format({
      hostname: domain(DEVELOPMENT),
      pathname: USER_SYNC_IMAGE_PATH
    }));
  });

  describe('conformBidRequest', function () {
    expect(conformBidRequest(cannedValidBidRequests[0])).to.deep.equal({
      params: cannedValidBidRequests[0].params,
      crumbs: cannedValidBidRequests[0].crumbs,
      sizes: cannedValidBidRequests[0].sizes,
      bidId: cannedValidBidRequests[0].bidId,
      bidderRequestId: cannedValidBidRequests[0].bidderRequestId,
    });
  });

  describe('requestsPayload', function () {
    const
      currency = 'EUR',
      debug = true;

    const payload = requestsPayload(debug, currency, cannedValidBidRequests, cannedBidderRequest);

    expect(payload).to.exist.and.have.all.keys(
      'akPbjsVersion',
      'bidRequests',
      'currency',
      'debug',
      'language',
      'refererInfo',
      'deviceInfo',
      'userAgent',
      'gdprApplies',
      'gdprConsent'
    );

    expect(payload.bidRequests[0]).to.exist.and.have.all.keys(
      'params',
      'crumbs',
      'sizes',
      'bidId',
      'bidderRequestId',
    );

    expect(payload.akPbjsVersion).to.deep.equal(ADAPTER_VERSION);
    expect(payload.bidRequests[0].params).to.deep.equal(cannedValidBidRequests[0].params);
    expect(payload.bidRequests[0].crumbs).to.deep.equal(cannedValidBidRequests[0].crumbs);
    expect(payload.bidRequests[0].mediaTypes).to.deep.equal(cannedValidBidRequests[0].mediaTypes);
    expect(payload.bidRequests[0].bidId).to.deep.equal(cannedValidBidRequests[0].bidId);
    expect(payload.bidRequests[0].bidderRequestId).to.deep.equal(cannedValidBidRequests[0].bidderRequestId);
    expect(payload.currency).to.deep.equal(currency);
    expect(payload.debug).to.deep.equal(debug);
    expect(payload.language).to.deep.equal(navigator.language);
    expect(payload.deviceInfo).to.exist.and.have.all.keys(
      'browserWidth',
      'browserHeight',
      'deviceWidth',
      'deviceHeight',
      'documentWidth',
      'documentHeight',
      'webGL',
    );
    expect(payload.userAgent).to.deep.equal(navigator.userAgent);
    expect(payload.gdprApplies).to.deep.equal(cannedBidderRequest.gdprConsent.gdprApplies);
    expect(payload.gdprConsent).to.deep.equal(cannedBidderRequest.gdprConsent.consentString);
  });

  describe('getViewDimensions', function () {
    const window = {
      innerWidth: 1024,
      innerHeight: 768
    };
    const documentWithElement = {
      documentElement:
        {
          clientWidth: 512,
          clientHeight: 384
        }
    };
    const documentWithBody = {
      body:
        {
          clientWidth: 512,
          clientHeight: 384
        }
    };
    expect(getViewDimensions(window, documentWithElement)).to.deep.equal({
      width: 1024,
      height: 768
    });
    expect(getViewDimensions(window, documentWithBody)).to.deep.equal({width: 1024, height: 768});
    expect(getViewDimensions(window, documentWithElement)).to.deep.equal({
      width: 1024,
      height: 768
    });
    expect(getViewDimensions(window, documentWithBody)).to.deep.equal({width: 1024, height: 768});
    expect(getViewDimensions({}, documentWithElement)).to.deep.equal({width: 512, height: 384});
    expect(getViewDimensions({}, documentWithBody)).to.deep.equal({width: 512, height: 384});
  });

  describe('getDeviceDimensions', function () {
    const window = {screen: {width: 1024, height: 768}};
    expect(getDeviceDimensions(window)).to.deep.equal({width: 1024, height: 768});
    expect(getDeviceDimensions({})).to.deep.equal({width: '', height: ''});
  });

  describe('getDocumentDimensions', function () {
    expect(getDocumentDimensions({
      documentElement: {
        clientWidth: 1,
        clientHeight: 1,
        offsetWidth: 0,
        offsetHeight: 0,
        scrollWidth: 0,
        scrollHeight: 0,
      },
    })).to.deep.equal({width: 1, height: 1});

    expect(getDocumentDimensions({
      documentElement: {
        clientWidth: 1,
        clientHeight: 1,
        offsetWidth: 0,
        offsetHeight: 0,
        scrollWidth: 0,
        scrollHeight: 0,
      },
      body: {
        scrollHeight: 0,
        offsetHeight: 0,
      }
    })).to.deep.equal({width: 1, height: 1});

    expect(getDocumentDimensions({
      documentElement: {
        clientWidth: 0,
        clientHeight: 0,
        offsetWidth: 1,
        offsetHeight: 1,
        scrollWidth: 0,
        scrollHeight: 0,
      },
      body: {
        scrollHeight: 0,
        offsetHeight: 0,
      }
    })).to.deep.equal({width: 1, height: 1});

    expect(getDocumentDimensions({
      documentElement: {
        clientWidth: 0,
        clientHeight: 0,
        offsetWidth: 0,
        offsetHeight: 0,
        scrollWidth: 1,
        scrollHeight: 1,
      },
      body: {
        scrollHeight: 0,
        offsetHeight: 0,
      }
    })).to.deep.equal({width: 1, height: 1});

    expect(getDocumentDimensions({
      documentElement: {
        clientWidth: undefined,
        clientHeight: undefined,
        offsetWidth: undefined,
        offsetHeight: undefined,
        scrollWidth: undefined,
        scrollHeight: undefined,
      },
      body: {
        scrollHeight: undefined,
        offsetHeight: undefined,
      }
    })).to.deep.equal({width: '', height: ''});
  });

  // describe('isWebGLEnabled', function () {
  //   it('handles no webgl', function () {
  //     const
  //       document = new Document(),
  //       canvas = sinon.createStubInstance(HTMLCanvasElement);
  //     sinon.stub(document, 'createElement').withArgs('canvas').returns(canvas);
  //     canvas.getContext.withArgs('webgl').returns(undefined);
  //     canvas.getContext.withArgs('experimental-webgl').returns(undefined);
  //     expect(isWebGLEnabled(document)).to.equal(false);
  //   });
  //
  //   it('handles webgl exception', function () {
  //     const
  //       document = new Document(),
  //       canvas = sinon.createStubInstance(HTMLCanvasElement);
  //     sinon.stub(document, 'createElement').withArgs('canvas').returns(canvas);
  //     canvas.getContext.withArgs('webgl').throws(DOMException);
  //     expect(isWebGLEnabled(document)).to.equal(false);
  //   });
  //
  //   it('handles experimental webgl', function () {
  //     const
  //       document = new Document(),
  //       canvas = sinon.createStubInstance(HTMLCanvasElement);
  //     sinon.stub(document, 'createElement').withArgs('canvas').returns(canvas);
  //     canvas.getContext.withArgs('webgl').returns(undefined);
  //     canvas.getContext.withArgs('experimental-webgl').returns(true);
  //     expect(isWebGLEnabled(document)).to.equal(true);
  //   });
  //
  //   it('handles experimental webgl exception', function () {
  //     const
  //       document = new Document(),
  //       canvas = sinon.createStubInstance(HTMLCanvasElement);
  //     sinon.stub(document, 'createElement').withArgs('canvas').returns(canvas);
  //     canvas.getContext.withArgs('webgl').returns(undefined);
  //     canvas.getContext.withArgs('experimental-webgl').throws(DOMException);
  //     expect(isWebGLEnabled(document)).to.equal(false);
  //   });
  //
  //   it('handles webgl', function () {
  //     const
  //       document = new Document(),
  //       canvas = sinon.createStubInstance(HTMLCanvasElement);
  //     sinon.stub(document, 'createElement').withArgs('canvas').returns(canvas);
  //     canvas.getContext.withArgs('webgl').returns(true);
  //     expect(isWebGLEnabled(document)).to.equal(true);
  //   });
  // });

  describe('getDeviceInfo', function () {
    expect(getDeviceInfo(
      {width: 1, height: 2},
      {width: 3, height: 4},
      {width: 5, height: 6},
      true
    )).to.deep.equal({
      deviceWidth: 1,
      deviceHeight: 2,
      browserWidth: 3,
      browserHeight: 4,
      documentWidth: 5,
      documentHeight: 6,
      webGL: true
    });
  });

  describe('resolveEnv', function () {
    it('defaults to production', function () {
      expect(resolveEnv({}, null)).to.deep.equal(DEFAULT_ENV);
    });
    expect(resolveEnv({}, PRODUCTION)).to.deep.equal(PRODUCTION);
    expect(resolveEnv({}, STAGING)).to.deep.equal(STAGING);
    expect(resolveEnv({}, DEVELOPMENT)).to.deep.equal(DEVELOPMENT);
    expect(resolveEnv({emoteev: {env: PRODUCTION}}, null)).to.deep.equal(PRODUCTION);
    expect(resolveEnv({emoteev: {env: STAGING}}, null)).to.deep.equal(STAGING);
    expect(resolveEnv({emoteev: {env: DEVELOPMENT}}, null)).to.deep.equal(DEVELOPMENT);
    it('prioritizes parameter over configuration', function () {
      expect(resolveEnv({emoteev: {env: STAGING}}, DEVELOPMENT)).to.deep.equal(DEVELOPMENT);
    });
  });

  describe('resolveDebug', function () {
    it('defaults to production', function () {
      expect(resolveDebug({}, null)).to.deep.equal(false);
    });
    expect(resolveDebug({}, 'false')).to.deep.equal(false);
    expect(resolveDebug({}, 'true')).to.deep.equal(true);
    expect(resolveDebug({debug: true}, null)).to.deep.equal(true);
    it('prioritizes parameter over configuration', function () {
      expect(resolveDebug({debug: true}, 'false')).to.deep.equal(false);
    });
  });

  describe('side effects', function () {
    let triggerPixelSpy;
    let getCookieSpy;
    let getConfigSpy;
    let getParameterByNameSpy;
    beforeEach(function () {
      triggerPixelSpy = sinon.spy(utils, 'triggerPixel');
      getCookieSpy = sinon.spy(pubCommonId, 'getCookie');
      getConfigSpy = sinon.spy(config, 'getConfig');
      getParameterByNameSpy = sinon.spy(utils, 'getParameterByName');
    });
    afterEach(function () {
      triggerPixelSpy.restore();
      getCookieSpy.restore();
      getConfigSpy.restore();
      getParameterByNameSpy.restore();
    });

    describe('isBidRequestValid', function () {
      it('has intended side-effects', function () {
        const validBidRequest = {
          bidder: 'emoteev',
          bidId: '23a45b4e3',
          params: {
            adSpaceId: 12345,
          },
          mediaTypes: {
            banner: {
              sizes: [[750, 200]]
            }
          },
        };
        spec.isBidRequestValid(validBidRequest);
        sinon.assert.notCalled(utils.triggerPixel);
        sinon.assert.notCalled(pubCommonId.getCookie);
        sinon.assert.notCalled(config.getConfig);
        sinon.assert.notCalled(utils.getParameterByName);
      });
      it('has intended side-effects', function () {
        const invalidBidRequest = {};
        spec.isBidRequestValid(invalidBidRequest);
        sinon.assert.notCalled(utils.triggerPixel);
        sinon.assert.notCalled(pubCommonId.getCookie);
        sinon.assert.notCalled(config.getConfig);
        sinon.assert.notCalled(utils.getParameterByName);
      });
    });
    describe('buildRequests', function () {
      it('has intended side-effects', function () {
        spec.buildRequests(cannedValidBidRequests, cannedBidderRequest);
        sinon.assert.notCalled(utils.triggerPixel);
        sinon.assert.notCalled(pubCommonId.getCookie);
        sinon.assert.callCount(config.getConfig, 3);
        sinon.assert.callCount(utils.getParameterByName, 2);
      });
    });
    describe('interpretResponse', function () {
      it('has intended side-effects', function () {
        spec.interpretResponse(serverResponse);
        sinon.assert.notCalled(utils.triggerPixel);
        sinon.assert.notCalled(pubCommonId.getCookie);
        sinon.assert.notCalled(config.getConfig);
        sinon.assert.notCalled(utils.getParameterByName);
      });
    });
    describe('onBidWon', function () {
      it('has intended side-effects', function () {
        const bidObject = serverResponse.body[0];
        spec.onBidWon(bidObject);
        sinon.assert.calledOnce(utils.triggerPixel);
        sinon.assert.calledOnce(pubCommonId.getCookie);
        sinon.assert.calledOnce(config.getConfig);
        sinon.assert.calledOnce(utils.getParameterByName);
      });
    });
    describe('onTimeout', function () {
      it('has intended side-effects', function () {
        spec.onTimeout(cannedValidBidRequests[0]);
        sinon.assert.calledOnce(utils.triggerPixel);
        sinon.assert.notCalled(pubCommonId.getCookie);
        sinon.assert.calledOnce(config.getConfig);
        sinon.assert.calledOnce(utils.getParameterByName);
      });
    });
    describe('getUserSyncs', function () {
      it('has intended side-effects', function () {
        spec.getUserSyncs({});
        sinon.assert.notCalled(utils.triggerPixel);
        sinon.assert.notCalled(pubCommonId.getCookie);
        sinon.assert.calledOnce(config.getConfig);
        sinon.assert.calledOnce(utils.getParameterByName);
      });
    });
  });
});


text:
import joi from 'joi';
import ValidationModel from './ValidationModel';

const schema = joi.object().keys({
    number: joi.string().required()
});

class CallerIdRequest extends ValidationModel {
  constructor(obj){
    super(obj, schema);
  }
}

export default CallerIdRequest;


text:
define(function(require) {
  'use strict';

  var module = require('../module');
  require('../resources/search');

  module.controller('<%= helpers.capitalize( name ) %>SearchCtrl', <%= helpers.capitalize( name ) %>SearchCtrl);

  //---

  <%= helpers.capitalize( name ) %>SearchCtrl.$inject = [
    '$scope', '<%= helpers.capitalize( name ) %>SearchResource',
    'PaginationFactory', 'InputFocusFactory',
    '$log'
  ];

  function <%= helpers.capitalize( name ) %>SearchCtrl(
    $scope, resource, pagination, input, console
  ) {

    var ctrlName = '<%= helpers.capitalize( name ) %>SearchCtrl';
    input = input.get(ctrlName);
    pagination = pagination.get(ctrlName);

    /*
    console.debug(ctrlName);
    console.debug(input);
    console.debug(pagination);
    */

    //---

    var config = {
      pageMinSize: 2,
      pageMaxSize: 50,
      showFilterBtnMinlength: 5
    };

    //---

    var vm = this;

    vm.result = undefined;

      //--- options

    vm.showOptions = false;

    vm.optionsBtnLabel = 'Show Options';

    vm.showOptionsBtnClick = showOptionsBtnClick;

      //--- filter

    vm.filter = { search: '' };
    vm.showFilter = false;

    vm.showFilterBtn = false;
    vm.showFilterBtnActive = false;

    vm.filterBtnLabel = 'Show filter';

    vm.showFilterBtnClick = showFilterBtnClick;

    vm.clearFilter = clearFilter;

      //--- pagination

    vm.showPagination = true;
    vm.pageSize = pagination.getPageSize();
    vm.pageMinSize = config.pageMinSize;
    vm.pageMaxSize = config.pageMaxSize;

    vm.paginationItemsSize = 5;
    vm.paginationPageSize = pagination.getPageSize();

    vm.currentPage = 1;
    vm.pageChanged = PageChanged;

    vm.updatePageSizeInvalid = updatePageSizeInvalid;

    vm.updatePageSize = updatePageSize;

    vm.updatePageSizeFormSubmit = updatePageSizeFormSubmit;

      //--- search

    vm.doSearch = doSearch;

    //---

    input.config(
      $scope,
      [
        'focusSearchInput',
        'focusPageSizeInput',
        'focusFilterSearchInput'
      ]);

    input.setFocus('focusSearchInput', 200);

    //---

    function stringEmpty(str) {
      var pattern = /^\s*$/;
      return (str === null || pattern.test(str));
    }

    //---

    function updateInterface() {
      vm.clearFilter();

      // check if filter is visible
      if(vm.showOptions) vm.showOptionsBtnClick();
      if(vm.showFilter || vm.showFilterBtnActive) vm.showFilterBtnClick();

      // check if filter is needed
      vm.showFilterBtn = checkShowfilterBtn();

      vm.showPagination = true;
      vm.showFilter = false;
      vm.showFilterBtnActive = false;

      input.setFocus('focusSearchInput');
    }

    //---

    function loadData(page) {
      if(!stringEmpty(vm.searchName)) {
        resource.get(
          {
            name: vm.searchName,
            page: page,
            size: pagination.getPageSize()
          },
          function(result) {

            //console.debug(result);

            vm.result = result;

            vm.currentPage = result.page;

            pagination.updateMetainf(
              result.count,
              result.data.length,
              result.page,
              result.pages
            );

            updateInterface();
          }
        );
      }
    }

    //---
    // @begin: options

    function showOptionsBtnClick() {
      vm.showOptions = !vm.showOptions;
      vm.optionsBtnLabel = (vm.showOptions ? 'Hide' : 'Show') + ' Options';

      if(vm.showOptions) {
        vm.showFilter = vm.showFilterBtnActive;

        if(vm.showFilter) input.setFocus('focusFilterSearchInput');
        else input.setFocus('focusPageSizeInput');
      } else {
        if(vm.showFilter && stringEmpty(vm.filter.search)) vm.showFilterBtnClick();
        vm.showFilter = false;

        input.setFocus('focusSearchInput');
      }
    }

    // @end: options
    //---
    // @begin: filter

    function checkShowfilterBtn() {
      return (
        (pagination.getPageSize() >= config.showFilterBtnMinlength) &&
        (pagination.metainf.lastPageSize >= config.showFilterBtnMinlength)
      );
    }

    function showFilterBtnClick() {
      vm.showFilter = vm.showFilterBtnActive = !vm.showFilter;
      vm.filterBtnLabel = (vm.showFilter ? 'Hide' : 'Show') + ' filter';
      if(!vm.showFilter) vm.clearFilter();
      vm.showPagination = !vm.showFilter;

      // change input field focus
      if(vm.showFilter) input.setFocus('focusFilterSearchInput');
      else input.setFocus('focusPageSizeInput');
    }

    function clearFilter() {
      vm.filter = { search: '' };
    }

    // @end: filter
    //---
    // @begin: pagination

    function PageChanged() {
      if(vm.currentPage != vm.result.page) {
        pagination.setNextPage(vm.currentPage);
        loadData(pagination.getNextPage());
      }
    }

    function updatePageSizeInvalid(pageSize) {
      var flag = false;

      flag = (
        pageSize === undefined ||
        pageSize === null ||
        pageSize === pagination.getPageSize() ||
        pageSize < vm.pageMinSize ||
        pageSize > vm.pageMaxSize
      );

      return flag;
    }

    function updatePageSize() {
      // check if filter is visible
      if(vm.showFilter) vm.showFilterBtnClick();

      pagination.resetPageSize(vm.pageSize);
      vm.paginationPageSize = pagination.getPageSize();

      loadData(pagination.getNextPage());
    }

    function updatePageSizeFormSubmit() {
      if(!vm.updatePageSizeInvalid(vm.pageSize)) {
        vm.updatePageSize();
      }
    }

    // @end: pagination
    //---

    function doSearch() {
      pagination.resetPageSize(vm.pageSize);

      loadData(pagination.getNextPage());
    }

  }

});


text:
require "chiliproject_side_by_side_wiki_edit/version"

module ChiliprojectSideBySideWikiEdit
end


text:
package org.jetbrains.plugins.scala.settings

import com.intellij.openapi.options.{BeanConfigurable, SearchableConfigurable}
import com.intellij.util.ui.{JBUI, UI}
import org.jetbrains.plugins.scala.ScalaBundle
import org.jetbrains.plugins.scala.extensions.ObjectExt

import java.awt.GridLayout
import javax.swing._

class ScalaEditorSmartKeysConfigurable extends BeanConfigurable[ScalaApplicationSettings](ScalaApplicationSettings.getInstance) with SearchableConfigurable {
  override def getId: String = "ScalaSmartKeys"

  //noinspection ScalaExtractStringToBundle
  override def getDisplayName: String = "Scala"

  override def getHelpTopic: String = null

  override def enableSearch(option: String): Runnable = null

  override def disposeUIResources(): Unit = super.disposeUIResources()

  init()

  def init(): Unit = {
    val settings: ScalaApplicationSettings = getInstance()
    checkBox(ScalaBundle.message("indent.pasted.lines.at.caret"), () => settings.INDENT_PASTED_LINES_AT_CARET, settings.INDENT_PASTED_LINES_AT_CARET = _)
    checkBox(ScalaBundle.message("insert.pair.multiline.quotes"), () => settings.INSERT_MULTILINE_QUOTES, settings.INSERT_MULTILINE_QUOTES = _)
    checkBox(ScalaBundle.message("upgrade.to.interpolated"), () => settings.UPGRADE_TO_INTERPOLATED, settings.UPGRADE_TO_INTERPOLATED = _)
    checkBox(ScalaBundle.message("wrap.single.expression.body"), () => settings.WRAP_SINGLE_EXPRESSION_BODY, settings.WRAP_SINGLE_EXPRESSION_BODY = _)
    checkBox(ScalaBundle.message("delete.closing.brace"), () => settings.DELETE_CLOSING_BRACE, settings.DELETE_CLOSING_BRACE = _)

    // these checkboxes need special wrappers since they have tooltips
    val addBracesCheckbox = new JCheckBox(ScalaBundle.message("insert.block.braces.automatically.based.on.indentation"))
    component(
      UI.PanelFactory.panel(addBracesCheckbox).withTooltip(ScalaBundle.message("insert.block.braces.automatically.based.on.indentation.tooltip")).createPanel(),
      () => settings.HANDLE_BLOCK_BRACES_INSERTION_AUTOMATICALLY, settings.HANDLE_BLOCK_BRACES_INSERTION_AUTOMATICALLY = _: Boolean,
      () => addBracesCheckbox.isSelected, addBracesCheckbox.setSelected(_)
    )
    val removeBracesCheckbox = new JCheckBox(ScalaBundle.message("remove.block.braces.automatically.based.on.indentation"))
    component(
      UI.PanelFactory.panel(removeBracesCheckbox).withTooltip(ScalaBundle.message("remove.block.braces.automatically.based.on.indentation.tooltip")).createPanel(),
      () => settings.HANDLE_BLOCK_BRACES_REMOVAL_AUTOMATICALLY, settings.HANDLE_BLOCK_BRACES_REMOVAL_AUTOMATICALLY = _: Boolean,
      () => removeBracesCheckbox.isSelected, removeBracesCheckbox.setSelected(_)
    )
  }

  override def createComponent: JComponent = {
    val result = super.createComponent
    assert(result != null, "ScalaEditorSmartKeysConfigurable panel was not created")

    // Group the auto-brace options by padding them to the right and adding a caption
    val isAutoBraceOptionTitle = Set(
      ScalaBundle.message("insert.block.braces.automatically.based.on.indentation"),
      ScalaBundle.message("remove.block.braces.automatically.based.on.indentation"),
    )

    for {
      // get the panel
      panel <- result.getComponent(0).asOptionOf[JComponent]

      // get the auto-brace options
      panelComponents = panel.getComponents
      autoBraceOptions = panelComponents.collect {
        case jpanel: JPanel if jpanel.getComponent(0).asOptionOf[JPanel].exists(
          checkboxPanel => checkboxPanel.getComponent(0).asOptionOf[JCheckBox].exists(
            checkbox => isAutoBraceOptionTitle(checkbox.getText)))
        => jpanel
      }

      if autoBraceOptions.nonEmpty
      gridLayout <- panel.getLayout.asOptionOf[GridLayout]
    } {
      // add a label above the auto-brace options
      gridLayout.setRows(gridLayout.getRows + 1)
      val groupCaptionPosition = panelComponents.indexOf(autoBraceOptions.head)
      panel.add(new JLabel(ScalaBundle.message("control.curly.braces.based.on.line.indents")), groupCaptionPosition)

      // add a left margin
      autoBraceOptions.foreach(_.setBorder(JBUI.Borders.emptyLeft(16)))
    }

    result
  }
}


text:
def add_native_methods(clazz):
    def ShellExecute__java_lang_String__java_lang_String__(a0, a1, a2):
        raise NotImplementedError()

    clazz.ShellExecute__java_lang_String__java_lang_String__ = staticmethod(ShellExecute__java_lang_String__java_lang_String__)


text:
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">

Georeferencing Maps with Map Warper

@MaptimePGH | 27 April 2016

Follow along at

  maptime.io /pittsburgh /presentations /2016-04-27-mapwarper

Find that link at maptime.io/pittsburgh: Look for Map Warper under the MaptimePGH Resources sidebar.

What is Maptime?

A time for learning about maps

Hands-on

Beginner-focused

Emphasis on open source, programming, and web-mapping

Events / blog n'at: maptime.io/pittsburgh

Code: github.com/maptime/pittsburgh

PLEASE interrupt if you have questions!

Today we're going to talk about
Map Warper
mapwarper.net

and the process of putting images of maps into a digital geographic context:

Georeferencing

Why might you want to do this?

You may not have access to the data used to make the map, but want to see the map in the context of other geographic data.

Historic maps - what used to be here?

Photos of non-current political district maps...snap a photo of that old map you see in a public building

Maps from community development corporations, from old hand drawn annual reports and the like

Zoning maps from small municipalities that don't have a GIS department

Community plan drafts handed out at public meetings (likely created in CAD/GIS, but without easy access to the consultant, etc.)

First, Let's find some images of maps!

University of Pittsburgh's Historic Pittsburgh Maps Collection: digital.library.pitt.edu/maps

Explore their catalog - very cool stuff!

Full-Image and Description

See An Example

Full-Image provides a little image-viewer. Zoom and pan around.

Description provides important metadata: Title, Date, Creator, etc. Also, read the Rights and download a copy.

Important!

Pitt's maps themselves (which we will use for our examples tonight), and many historic maps are in the public domain.

However, always be cognizant of copyright and license when using the work of others.

New York Public Library (NYPL) Digital Collection: digitalcollections.nypl.org

NYPL includes some maps outside NYC. Search for "pennsylvania map" and check the "search only public domain" to see some great stuff! (and you can filter down by "place" once you are in the main search area.)

Also see buildinginspector.nypl.org and spacetime.nypl.org for some interesting historic mapping projects from the NYPL.

Penn State Digital Sanborn Maps: www.libraries.psu.edu/psul/digital/sanborn.html

Great collection, and Sanborn maps are relatively easy to georeference due to the map projection (a little more on that later).

All the maps maps on these sites are stored as image files.

The files themselves contain no machine-readable geographic information.

If we want to view these maps in a geographic context, with other geographic data...

 we need to georeference them

What does it mean to georeference an image?

First, let's talk about the basics of images on computers and maps.

RASTER

A raster stores data in pixels

On maps, pixels are powerful.

In Geographic Information Systems (GIS) software, the pixels of a raster can represent color, height, slope, direction...and many other classifications or gradients.

Geographically-referenced raster data is commonly encountered in:

satellite imagery

weather data

digital elevation model

Such rasters contain geographic reference information that describes where the pixels exist on the globe.

This info typically includes the coordinate system and some information about the raster's dimensions, in a standard format.

The historic images do not (yet) have this information.

Some references on coordinate systems:

MaptimeHQ: The Wild World of Geodesy

		MaptimePGH: Geo101

mapschool.io

Raster as a text file (ascii) with geo info:

Georeferencing

the process of giving non-geographic data the geographic attributes it needs to be shown in the correct location on a digital map

Read Esri's Fundamentals for georeferencing a raster dataset for a good conceptual overview

Download a map from the University of Pittsburgh's Historic Pittsburgh Maps Collection that you'd like to georeference

digital.library.pitt.edu/maps

Some maps will be easier to georeference than others.

Find one with a lot of detail. For your first map, try to avoid broad-scale or conceptual maps.

Map Warper
mapwarper.net

"It's a free to use, open source map warper / map georectifier, and image georeferencer tool. Developed, hosted and maintained by Tim Waters. This project is supported by Topomancy LLC and the New York Public Library".

Examples

				1912 Flood Map, Pittsburgh South Side

Pittsburgh HOLC Redlining Map

How do I georeference an image using Map Warper?

Sign-Up

Upload map and enter metadata (really, really important!)

Georeference (Rectify, Crop, Align)

View!

Export to a file or reference as a web service

(make fixes)

Upload

Make sure to copy metadata from your source!!!

Be thorough! Give credit!

(you can add more later if you need to)

Rectify using Control Points

Image Space,
Coordinate Space

our map image at left,
our web map at right

Identify Control Points

A little bit of art
 to the science...

Find clearly-defined points of reference,
 like buildings or intersections.

Avoid using "soft" references,
 like shorelines.

Rectify

Save the image to coordinate space

Technically...

		source

Stretch that map!

	source

Crop and Align

Crop lets you cut off portions of the image. Useful if you scan has extra white space. But please avoid cropping any info that might help identify the map.

Align lets you specify other maps you've uploaded to Map Warper

Preview Map

Now that I've georefernced this map...what do I do with it?

EXPORT

Download a georeferenced image file for use in geographic information systems (GIS) software

Get the KML version and view/share it with Google Maps

Build a web map and reference the map service hosted for you by MapWarper

Work Session!

(tag your maps with MaptimePGH)

Share Your Work!

Q/A + Troubleshooting

Did anyone have a map didn't work?

Thanks!

Carnegie Library of Pittsburgh

OpenPGH, Pittsburgh's Code for America Brigade

Maptime HQ and the other Maptime chapters for providing great resource material

Our next event will be announced soon, for end of May / beginning of June.

additional MaptimePGH resources

Web Mapping + CartoDB

Geo 102 & Web Mapping (for the 2015 National Day of Civic Hacking)

Geo 101 & Open Street Map

Maptime HQ resources page

Presentation pulled together by  @GassChristianB and @eleanortutt

Presentation made with Stack.

Stack is made by Mike Bostock and is available

on GitHub under the BSD license.


text:
- order: 5

选择框的不可用状态。

---

````jsx
var Datepicker = antd.Datepicker;

React.render(
  <Datepicker value="2015-06-06" disabled={true} />
, document.getElementById('components-datepicker-demo-disabled'));
````


text:
import { API } from '../api';
import { getStatistics, getLastStatistics } from '../../../statistics/server';

API.v1.addRoute('statistics', { authRequired: true }, {
	get() {
		const { refresh } = this.requestParams();
		return API.v1.success(Promise.await(getLastStatistics({
			userId: this.userId,
			refresh: refresh && refresh === 'true',
		})));
	},
});

API.v1.addRoute('statistics.list', { authRequired: true }, {
	get() {
		const { offset, count } = this.getPaginationItems();
		const { sort, fields, query } = this.parseJsonQuery();

		return API.v1.success(Promise.await(getStatistics({
			userId: this.userId,
			query,
			pagination: {
				offset,
				count,
				sort,
				fields,
			},
		})));
	},
});


text:
'use strict';

module.exports = function (context) {
  return {
    Function(node) {
      if (!node.generator) {
        return;
      }
      context.report({
        node,
        message: 'Generator functions are foribdden.',
      });
    },
  };
};


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _SimpleRule = require('../rules/SimpleRule');

var _SimpleRule2 = _interopRequireDefault(_SimpleRule);

var _KeyframesRule = require('../rules/KeyframesRule');

var _KeyframesRule2 = _interopRequireDefault(_KeyframesRule);

var _ConditionalRule = require('../rules/ConditionalRule');

var _ConditionalRule2 = _interopRequireDefault(_ConditionalRule);

var _FontFaceRule = require('../rules/FontFaceRule');

var _FontFaceRule2 = _interopRequireDefault(_FontFaceRule);

var _ViewportRule = require('../rules/ViewportRule');

var _ViewportRule2 = _interopRequireDefault(_ViewportRule);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var classes = {
  '@charset': _SimpleRule2['default'],
  '@import': _SimpleRule2['default'],
  '@namespace': _SimpleRule2['default'],
  '@keyframes': _KeyframesRule2['default'],
  '@media': _ConditionalRule2['default'],
  '@supports': _ConditionalRule2['default'],
  '@font-face': _FontFaceRule2['default'],
  '@viewport': _ViewportRule2['default'],
  '@-ms-viewport': _ViewportRule2['default']

  /**
   * Generate plugins which will register all rules.
   */
};
exports['default'] = Object.keys(classes).map(function (key) {
  // https://jsperf.com/indexof-vs-substr-vs-regex-at-the-beginning-3
  var re = new RegExp('^' + key);
  var onCreateRule = function onCreateRule(name, decl, options) {
    return re.test(name) ? new classes[key](name, decl, options) : null;
  };
  return { onCreateRule: onCreateRule };
});