text:
;(function(){
    if ( typeof define === "function" && define.amd ) {
        define( 'GNavVer', ['require', 'jquery'], function(require) {
            return factory(require('jquery'));
        } );
    }else if ( typeof module === "object" && typeof module.exports === "object" ) {
        module.exports = factory(require('jquery'))
    }else{
        window.GNavVer = factory(window.jQuery);
    }
    function factory($){
        var defaultConfig = {
            content: [],
            fixedNav: { position: 'left', distance: '0'}
        };
        var NavVer = function(el, conf){
            this.el = el;
            this.conf = $.extend({}, defaultConfig, conf);
            this.init();
        };
        NavVer.prototype = {
            _render: function(){
                var el = this.el;
                var conf = this.conf;
                $(el).append('

');
                var navListHtml ='';
                $.each(conf.content, function(index, item){
                    var navSubList ='';
                    var navSubListHtml ='';
                    if(item.sub){
                        $.each(item.sub, function(i, itemSub){
                            navSubList += '
'+itemSub.title+'
'
                        });
                        navSubListHtml = '
'+navSubList+'
';
                    }
                    navListHtml += '
'+item.title+''+navSubListHtml+'
';
                });
                $(el).find('.nav-list').append(navListHtml);
            },
            init: function(el, conf){
                this._render();
                this._renderStyle();
                this._rePosition();
            },
            _renderStyle: function(){
                var conf = this.conf;
                var el = this.el;
                $(el).find('.nav-list').css('position','fixed');
                $(el).find('.nav-list-container').css('position','relative');
                if(conf.fixedNav.position == 'right'){
                    $(el).find('.nav-list-container').append('

');
                    $(el).find('.nav-list').css('right', conf.fixedNav.distance+'px');
                    $(el).css('float', 'right');
                    $(el).find('.support-block-right').css('float', 'right');
                }else{
                    $(el).find('.nav-list-container').append('

');
                    $(el).find('.nav-list').css('left', conf.fixedNav.distance+'px');
                    $(el).css('float', 'left');
                }
                $(el).find('[class^=support-block]').width($(el).find('.nav-list').width()+parseInt(conf.fixedNav.distance));
                $(el).find('[class^=support-block]').height($(el).find('.nav-list').height());
            },
            _rePosition: function(){
                var el = this.el;
                $(window).on('resize', function(){
                    $(el).find('.nav-list').css('position', $(el).find('.nav-list').height()>$(window).height() ? 'absolute':'fixed');
                 });
                 $(window).trigger('resize');
            }
        };
        return NavVer;
    }
})();


text:
.button {
  line-height: 1;
  font-size: 1em;
  padding: calc(var(--baseline) * 0.5px) calc(var(--grid-padding) * 1px);
  margin: calc(var(--baseline) * 0.5px) calc(var(--grid-padding) * -1px);
  box-shadow: 0 0 0 2px;
  background-image: none;
  background-color: transparent;
  text-decoration: none;
  color: currentcolor;
  float: right;

  &:hover {
    box-shadow: 0 0 0 2px var(--theme-text-color);
    color: var(--theme-color);
    background-color: var(--theme-text-color);
  }
}

redpajama_set_name: RedPajamaGithub


text:
describe('collectionview - emptyView', function() {
  'use strict';

  beforeEach(function() {
    this.ItemView = Backbone.Marionette.ItemView.extend({
      tagName: 'span',
      template: _.template('<%= foo %>')
    });

    this.EmptyView = Backbone.Marionette.ItemView.extend({
      tagName: 'span',
      template: _.template('empty')
    });

    this.EmptyCollectionView = Backbone.Marionette.CollectionView.extend({
      childView: this.ItemView,
      emptyView: this.EmptyView
    });
  });

  describe('when rendering a collection view with an empty collection', function() {
    beforeEach(function() {
      this.collection = new Backbone.Collection();
      this.collectionView = new this.EmptyCollectionView({
        collection: this.collection
      });

      this.collectionView.render();
    });

    it('should append the html for the emptyView', function() {
      expect(this.collectionView.$el).to.have.$html('empty');
    });

    it('should reference each of the rendered view items', function() {
      expect(this.collectionView.children).to.have.lengthOf(1);
    });

    describe('and then adding an item to the collection', function() {
      beforeEach(function() {
        this.destroySpy = this.sinon.spy(this.EmptyView.prototype, 'destroy');
        this.collection.add({foo: 'wut'});
      });

      it('should destroy the emptyView', function() {
        expect(this.destroySpy).to.have.been.called;
      });

      it('should show the new item', function() {
        expect(this.collectionView.$el).to.have.$text('wut');
      });
    });
  });

  describe('when the emptyView has been rendered for an empty collection and then collection reset, receiving some values. Then adding an item to the collection', function() {
    beforeEach(function() {
      this.collection = new Backbone.Collection();
      this.collectionView = new this.EmptyCollectionView({
        collection: this.collection
      });

      this.destroySpy = this.sinon.spy(this.EmptyView.prototype, 'destroy');

      this.collectionView.render();
      this.collection.reset([{foo: 'bar'}, {foo: 'baz'}]);
      this.collection.add({foo: 'wut'});
    });

    it('should destroy the emptyView', function() {
      expect(this.destroySpy).to.have.been.called;
    });

    it('should show all three items without empty view', function() {
      expect(this.collectionView.$el).to.have.$html('barbazwut');
    });
  });

  describe('when the last item is removed from a collection', function() {
    beforeEach(function() {
      this.collection = new Backbone.Collection([{foo: 'wut'}]);
      this.collectionView = new this.EmptyCollectionView({
        collection: this.collection
      });

      this.collectionView.render();
      this.collection.remove(this.collection.at(0));
    });

    it('should append the html for the emptyView', function() {
      expect(this.collectionView.$el).to.have.$html('empty');
    });

    it('should reference each of the rendered view items', function() {
      expect(this.collectionView.children).to.have.lengthOf(1);
    });
  });

  describe('when the collection is reset multiple times', function() {
    beforeEach(function() {
      this.population = [{foo: 1}, {foo: 2}, {foo: 3}];
      this.collection = new Backbone.Collection();
      this.collectionView = new this.EmptyCollectionView({
        collection: this.collection
      });
      this.collectionView.render();
    });

    it('should remove all EmptyView', function() {
      this.collection.reset();
      this.collection.reset(this.population);
      expect(this.collectionView.$el).not.to.have.$html('empty');
    });

    it('should have only one emptyView open', function() {
      this.collection.reset(this.population);
      this.collection.reset();
      expect(this.collectionView.$el).to.have.$html('empty');
    });
  });

  describe('when a collection is reset with empty data after the view is loaded', function() {
    beforeEach(function() {
      this.data = [{foo: 'bar'}, {foo: 'baz'}];
      this.collection = new Backbone.Collection(this.data);

      this.collectionView = new this.EmptyCollectionView({
        collection: this.collection,
        emptyView: this.EmptyView
      });

      this.collectionView.render();
      this.collection.reset();
    });

    it('should have 1 child view (empty view)', function() {
      expect(this.collectionView.children).to.have.lengthOf(1);
    });

    it('should append the html for the emptyView', function() {
      expect(this.collectionView.$el).to.have.$html('empty');
    });

    it('should not have the empty child view after resetting with data', function() {
      this.collection.reset(this.data);
      expect(this.collectionView.$el).to.have.$html('barbaz');
    });
  });

  describe('when emptyView is specified with getEmptyView option', function() {
    beforeEach(function() {
      this.getEmptyViewStub = this.sinon.stub();
      this.OtherEmptyView = Backbone.Marionette.ItemView.extend();

      this.CollectionView = Backbone.Marionette.CollectionView.extend({
        childView: this.ItemView,
        getEmptyView: this.getEmptyViewStub
      });
    });

    describe('when rendering a collection view with an empty collection', function() {
      beforeEach(function() {
        this.collection = new Backbone.Collection();
        this.collectionView = new this.CollectionView({
          collection: this.collection
        });

        this.collectionView.render();
      });

      it('renders other empty view instance', function() {
        expect(this.getEmptyViewStub).to.have.been.calledWith(this.collectionView.children.first());
      });
    });
  });

  describe('isEmpty', function() {
    beforeEach(function() {
      this.collection = new Backbone.Collection();
      this.collectionView = new this.EmptyCollectionView({
        collection: this.collection
      });

      this.collectionView.render();
    });

    it('should return true when the collection is empty', function() {
      expect(this.collectionView.isEmpty()).to.be.true;
    });

    it('should return false when the collection is not empty', function() {
      this.collectionView.collection.add({foo: 'wut'});
      expect(this.collectionView.isEmpty()).to.be.false;
    });

    describe('when overriding with a populated collection', function() {
      beforeEach(function() {
        this.isEmptyStub = this.sinon.stub().returns(true);

        this.collection = new Backbone.Collection([{foo: 'wut'}, {foo: 'wat'}]);
        this.OverriddenIsEmptyCollectionView = this.EmptyCollectionView.extend({
          isEmpty: this.isEmptyStub
        });
        this.collectionView = new this.OverriddenIsEmptyCollectionView({
          collection: this.collection
        });

        this.collectionView.render();
      });

      it('should append the html for the emptyView', function() {
        expect(this.collectionView.$el).to.have.$html('empty');
      });

      it('should reference each of the rendered view items', function() {
        expect(this.collectionView.children).to.have.lengthOf(1);
      });

      it('should pass the collection as an argument to isEmpty', function() {
        expect(this.isEmptyStub).to.have.been.calledWith(this.collection);
      });
    });
  });

  describe('when rendering and an "emptyViewOptions" is provided', function() {
    beforeEach(function() {
      this.collection = new Backbone.Collection();
      this.collectionView = new this.EmptyCollectionView({
        collection: this.collection,
        emptyViewOptions: {
          foo: 'bar',
          tagName: 'p'
        }
      });

      this.collectionView.render();
      this.view = this.collectionView.children.findByIndex(0);
    });

    it('should pass the options to the empty view instance', function() {
      expect(this.view.options).to.have.property('foo', 'bar');
    });

    it('overrides options of emptyView class', function() {
      expect(this.collectionView.$el).to.have.$html('
empty
');
    });

    describe('when "emptyViewOptions" is provided as a fuction', function() {
      beforeEach(function() {
        this.collection = new Backbone.Collection();
        this.collectionView = new this.EmptyCollectionView({
          collection: this.collection,
          emptyViewOptions: function() {
            return {
              foo: 'bar',
              collection: this.collection
            };
          }
        });

        this.collectionView.render();
        this.view = this.collectionView.children.findByIndex(0);
      });

      it('should pass the options to the empty view instance', function() {
        expect(this.view.options).to.be.have.property('foo', 'bar');
      });

      it('should pass the collectionView as the context', function() {
        expect(this.view.options).to.have.property('collection', this.collection);
      });
    });

    describe('when "childViewOptions" are also provided', function() {
      beforeEach(function() {
        this.collection = new Backbone.Collection();
        this.collectionView = new this.EmptyCollectionView({
          collection: this.collection,
          childViewOptions: { foo: 'bar' },
          emptyViewOptions: { foo: 'baz' }
        });

        this.collectionView.render();
        this.view = this.collectionView.children.findByIndex(0);
      });

      it('passes the options to the empty view instance correctly', function() {
        expect(this.view.options).to.have.property('foo', 'baz');
      });
    });
  });

  describe('when rendering and only "childViewOptions" are provided', function() {
    beforeEach(function() {
      this.collection = new Backbone.Collection();
      this.collectionView = new this.EmptyCollectionView({
        collection: this.collection,
        childViewOptions: { foo: 'bar' }
      });

      this.collectionView.render();
      this.view = this.collectionView.children.findByIndex(0);
    });

    it('passes the options to the empty view instance', function() {
      expect(this.view.options).to.have.property('foo', 'bar');
    });
  });
});


text:
namespace remoting {
namespace test {

std::string MakeFormattedStringForReleasedHost(
    const std::string& application_id,
    const std::string& host_id) {
  return application_id + "::" + host_id;
}

FakeAppRemotingReportIssueRequest::FakeAppRemotingReportIssueRequest()
    : fail_start_request_(false) {
}

FakeAppRemotingReportIssueRequest::~FakeAppRemotingReportIssueRequest() {
}

bool FakeAppRemotingReportIssueRequest::Start(
    const std::string& application_id,
    const std::string& host_id,
    const std::string& access_token,
    ServiceEnvironment service_environment,
    bool abandon_host,
    base::Closure done_callback) {
  if (fail_start_request_) {
    done_callback.Run();
    return false;
  }

  if (abandon_host) {
    std::string host_id_string(application_id + "::" + host_id);
    host_ids_released_.push_back(MakeFormattedStringForReleasedHost(
      application_id, host_id));
  }

  scoped_refptr<base::SingleThreadTaskRunner> task_runner =
      base::ThreadTaskRunnerHandle::Get();
  task_runner->PostTask(FROM_HERE, done_callback);

  return true;
}

}  // namespace test
}  // namespace remoting


text:
require "rubygems"
require "bundler/setup"
require "simplecov"
require "with_model"
require 'celluloid/test'
require "cellgraph"

SimpleCov.start do
  add_filter "spec"
  add_filter "vendor"
end

$: << File.join(File.dirname(__FILE__), "..", "lib")

config_json = File.open(File.join("spec", "config", "database.json")).read
ActiveRecord::Base.establish_connection(JSON.parse(config_json, :symbolize_keys => true))

logfile = File.open(File.expand_path("../../log/test.log", __FILE__), 'a')
logfile.sync = true

Celluloid.logger = Logger.new(logfile)
Celluloid.shutdown_timeout = 1
$CELLULOID_DEBUG = true

RSpec.configure do |config|
  config.extend WithModel

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.warnings = true

  if config.files_to_run.one?
    config.default_formatter = 'doc'
  end

  config.order = :random

  config.before(:each) do
    Cellgraph.reset
  end

  Kernel.srand config.seed
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Summa veg. Scand. (Stockholm), Section Post. 380 (1849)

#### Original name
Dichaenaceae Fr.

### Remarks
null


text:
namespace GraphQLTemplate.IntegrationTest.Models
{
    using System.Collections.Generic;

    public class GraphQLError
    {
        public string Message { get; set; }

        public List<GraphQLErrorLocation> Locations { get; set; }

        public GraphQLErrorExtensions Extensions { get; set; }
    }
}


text:
<?php

namespace Entertainment\Bundle\GuideToTheStarsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Component\HttpFoundation\Session\Session;

use Entertainment\Bundle\GuideToTheStarsBundle\Entity\GTSstar;
use Entertainment\Bundle\GuideToTheStarsBundle\Entity\GTSvideo;
use Entertainment\Bundle\GuideToTheStarsBundle\Entity\GTSimage;
use Entertainment\Bundle\GuideToTheStarsBundle\Entity\GTSquote;
use Entertainment\Bundle\GuideToTheStarsBundle\Entity\GTSfunfact;

class StarController extends Controller
{

    /**
    * @Route("/stars/index/{eventId}")
    */
    public function indexAction($eventId)
    {

        $event = $this->getDoctrine()
            ->getRepository('EntertainmentRedCarpetBundle:Event')
            ->find($eventId);

        $repository = $this->getDoctrine()
             ->getRepository('EntertainmentGuideToTheStarsBundle:GTSstar');

        $stars = $repository->findAll();

        return $this->render(
            'EntertainmentGuideToTheStarsBundle:Star:index.html.twig',
            array('event' => $event, 'stars' => $stars)
        );

    }

    /**
     * @Route("/stars/create/{eventId}")
    */
    public function createAction($eventId)
    {

        $request = $this->get('request');
        if ($request->isMethod('POST')) {
            $em = $this->getDoctrine()->getManager();
            $star = new GTSstar();
            $star->setStarName($request->request->get('star-name'));
            $star->setStarDescription($request->request->get('star-description'));

            ## Handle uploaded Files
            $tmpImageBubble = $request->files->get('star-bubble');
            $tmpImageLarge = $request->files->get('star-large');
            $bubbleFileName = $_FILES['star-bubble']['name'];
            $largeFileName = $_FILES['star-large']['name'];
            $basePath = $this->get('kernel')->getRootDir();

            move_uploaded_file($tmpImageBubble, $basePath."/gts-images/".$bubbleFileName);
            move_uploaded_file($tmpImageLarge, $basePath."/gts-images/".$largeFileName);
            $star->setImageBubbleName($bubbleFileName);
            $star->setImageLargeName($largeFileName);
            $em->persist($star);
            $em->flush();
            $session = new Session();
            $session->getFlashBag()->add('notice', 'Success! The star has been created.');

            ## get the ID that was just inserted
            $starId = $star->getId();

            $categories = $request->request->get('category-check');
            if(isset($categories)) {
                foreach($categories as $key => $categoryId) {
                    $conn = $this->get('database_connection');
                    ## JOIN TABLE INSERT
                    $sql = "
                        INSERT INTO star_category
                        VALUES(" . $starId . ", " . $categoryId . ")"
                        ;
                    $numRowsEffected = $conn->exec($sql);
                }
            }
        }

        $event = $this->getDoctrine()
           ->getRepository('EntertainmentRedCarpetBundle:Event')
           ->find($eventId);

        ## get all categories that are associated with the event
        $categories = $event->getCategory();

        return $this->render(
            'EntertainmentGuideToTheStarsBundle:Star:create.html.twig',
            array('event' => $event, 'categories' => $categories)
        );

    }

     /**
     * @Route("/stars/{eventId}/update/{starId}")
     */
    public function updateAction($eventId, $starId)
    {

        $event = $this->getDoctrine()
            ->getRepository('EntertainmentRedCarpetBundle:Event')
            ->find($eventId);

        $categories = $this->getDoctrine()
            ->getRepository('EntertainmentGuideToTheStarsBundle:GTScategory')
            ->findBy(array('eventId' => $eventId));

        $star = $this->getDoctrine()
            ->getRepository('EntertainmentGuideToTheStarsBundle:GTSstar')
            ->find(array('id' => $starId));

        ## TODO: put in model
        $conn = $this->get('database_connection');
        $sql = "
            SELECT category_id
            FROM star_category
            WHERE star_id = " . $starId
            ;

        $dbCategories= $conn->fetchAll($sql);
        $selectedCategories = array();
        foreach ($dbCategories as $category) {
            $val = $category['category_id'];
            array_push($selectedCategories, $val);
        }

        $request = $this->get('request');
        if ($request->isMethod('POST')) {
            $em = $this->getDoctrine()->getManager();
            $star->setStarName($request->request->get('star-name'));
            $star->setStarDescription($request->request->get('star-description'));
            $getCategories = $request->request->get('category-check');

            if(isset($getCategories)) {
                ## delete old categories
                $sql = "
                        DELETE FROM star_category
                        WHERE star_id = " . $starId;
                $numRowsEffected = $conn->exec($sql);

                ## add new categories from updated form
                foreach($getCategories as $key => $categoryId) {
                    $conn = $this->get('database_connection');
                    $sql = "
                        INSERT INTO star_category
                        VALUES(" . $starId . ", " . $categoryId . ")"
                        ;
                    $numRowsEffected = $conn->exec($sql);
                }
            }

            $em->flush();
            $session = new Session();
            $session->getFlashBag()->add('notice', 'Success! The star information has been updated.');

            ## query for updated categories
            $conn = $this->get('database_connection');
            $sql = "
                SELECT category_id
                FROM star_category
                WHERE star_id = " . $starId
                ;
            $dbCategories= $conn->fetchAll($sql);
            $selectedCategories = array();
            foreach ($dbCategories as $category) {
                $val = $category['category_id'];
                array_push($selectedCategories, $val);
            }
        }

        return $this->render(
            'EntertainmentGuideToTheStarsBundle:Star:update.html.twig',
            array('event' => $event, 'categories' => $categories, 'star' => $star, 'selectedcat' => $selectedCategories)
        );

    }

    /**
    * @Route("/stars/{eventId}/content/{starId}")
    */
    public function addContentAction($eventId, $starId) {
        $event = $this->getDoctrine()
            ->getRepository('EntertainmentRedCarpetBundle:Event')
            ->find($eventId);

        $star = $this->getDoctrine()
             ->getRepository('EntertainmentGuideToTheStarsBundle:GTSstar')
             ->find(array('id' => $starId));

        $position = $this->nextPosition($starId);
        $request = $this->get('request');
        $session = $this->container->get('session');

        if(empty($session)) {
            $session = new Session();
            $session->set('order', '0');
        }

        if ($request->isMethod('POST')) {

            $ajaxOrdering = $session->get('order');
            if(!$ajaxOrdering) {
                $session->set('order', '0');
                $contentType = $request->request->get('submit');
                $em = $this->getDoctrine()->getManager();
                switch ($contentType) {
                    case 'video-submit':
                        $asset = new GTSvideo();
                        $videoId = $request->request->get('video-id');
                        $videoEmbed = $request->request->get('video-embed');

                        $asset->setVideoId($videoId);
                        $asset->setVideoEmbed($videoEmbed);

                        break;
                    case 'image-submit':
                        $asset = new GTSimage();
                        $title = $request->request->get('image-title');
                        $url = $request->request->get('image-url');
                        $caption = $request->request->get('image-caption');
                        $credit = $request->request->get('image-credit');

                        ## image asset
                        $tmpFileName = $request->files->get('image-name');
                        $userFileName = $_FILES['image-name']['name'];
                        $basePath = $this->get('kernel')->getRootDir();
                        move_uploaded_file($tmpFileName, $basePath."/event-images/".$userFileName);

                        $asset->setImageTitle($title);
                        $asset->setImageName($userFileName);
                        $asset->setImageUrl($url);
                        $asset->setImageCaption($caption);
                        $asset->setImageCredit($credit);

                        break;
                    case 'quote-submit':
                        $asset = new GTSquote();
                        $credit = $request->request->get('quote-credit');
                        $quote = $request->request->get('quote');

                        ## image asset
                        $tmpFileName = $request->files->get('quote-image');
                        $userFileName = $_FILES['quote-image']['name'];
                        $basePath = $this->get('kernel')->getRootDir();
                        move_uploaded_file($tmpFileName, $basePath."/event-images/".$userFileName);

                        $asset->setQuoteCredit($credit);
                        $asset->setQuoteText($quote);
                        $asset->setQuoteImage($userFileName);

                        break;
                    case 'fact-submit':
                        $asset = new GTSfunfact();
                        $fact = $request->request->get('fact-content');
                        $asset->setFunFact($fact);
                        break;
                }

                if(!empty($asset)) {
                    $asset->setTitle($request->request->get('title'));
                    $asset->setType($request->request->get('type'));
                    $asset->setStar($star);
                    $asset->setPosition($position);
                    $em->persist($asset);
                    $em->flush();
                }

            }

        }

        $session->set('order', '0');

        $videos = $star->getGtsVideos();
        $images = $star->getGtsImages();
        $facts = $star->getGtsFacts();
        $quotes = $star->getGtsQuotes();

        $assets = array();

        foreach($videos as $video) {
            $position = $video->getPosition();
            $assets[$position] = $video;
        }

        foreach($images as $image) {
            $position = $image->getPosition();
            $assets[$position] = $image;
        }

        foreach($facts as $fact) {
            $position = $fact->getPosition();
            $assets[$position] = $fact;
        }

        foreach($quotes as $quote) {
            $position = $quote->getPosition();
            $assets[$position] = $quote;
        }

        krsort($assets);

        return $this->render(
            'EntertainmentGuideToTheStarsBundle:Star:content.html.twig',
            array('event' => $event, 'star' => $star, 'assets' => $assets)
        );

    }

   /**
     * @Route("/stars/ajax-order")
     * @Template()
    */
    public function ajaxOrderAction()
    {
        $logger = $this->get('logger');
        $logger->info("I AM HERE IN AJAXPOSITION ACTION");

        $orderArray = $_REQUEST['starsArr'];
        $totalPositions = count($orderArray);
        $logger->info(var_export($orderArray, true));

        $em = $this->getDoctrine()->getManager();

        foreach($orderArray as $key => $value) {
            $logger->info("Content Data = " . $value);
            $data = explode("_", $value);
            $contentType = $data[0];
            $contentId = $data[1];

            $logger->info("Content Type = " . $contentType);
            $logger->info("Content Id = " . $contentId);

            switch ($contentType) {
              case "video":
                  $asset = $this->getDoctrine()
                    ->getRepository('EntertainmentGuideToTheStarsBundle:GTSvideo')
                    ->find($contentId);

                  break;
              case "quote":
                  $asset = $this->getDoctrine()
                    ->getRepository('EntertainmentGuideToTheStarsBundle:GTSquote')
                    ->find($contentId);

                  break;
              case "image":
                  $asset = $this->getDoctrine()
                    ->getRepository('EntertainmentGuideToTheStarsBundle:GTSimage')
                    ->find($contentId);
                   break;
              case "fact":
                  $asset = $this->getDoctrine()
                    ->getRepository('EntertainmentGuideToTheStarsBundle:GTSfunfact')
                    ->find($contentId);
                   break;

            }

            $asset->setPosition($totalPositions);
            $em->flush();
            $totalPositions--;

        }

        $session = new Session();
        $session->getFlashBag()->add('notice', 'Success! The Arrivlas ordering has been updated.');
        $session->set('order', '1');

        return new Response("positions updated");
    }

    public function nextPosition($starId)
    {

         ## Refactor to one query
         $conn = $this->get('database_connection');
         $sql = "SELECT COUNT(*) AS videoTotal FROM GTSvideo WHERE star_id = " . $starId;
         $videoArr = $conn->fetchAll($sql);
         $videoTotal = $videoArr[0]['videoTotal'];

         $sql = "SELECT COUNT(*) AS quoteTotal FROM GTSquote WHERE star_id = " . $starId;
         $quoteArr = $conn->fetchAll($sql);
         $quoteTotal = $quoteArr[0]['quoteTotal'];

         $sql = "SELECT COUNT(*) AS factTotal FROM GTSfunfact WHERE star_id = " . $starId;
         $factArr = $conn->fetchAll($sql);
         $factTotal = $factArr[0]['factTotal'];

         $sql = "SELECT COUNT(*) AS imageTotal FROM GTSimage WHERE star_id = " . $starId;
         $imageArr = $conn->fetchAll($sql);
         $imageTotal = $imageArr[0]['imageTotal'];

         $totalAssets = $videoTotal + $quoteTotal + $factTotal + $imageTotal;
         $position = $totalAssets + 1;

         return $position;

    }

    /**
     * @Route("/stars/json-test")
     * @Template()
    */

    public function contentJSONAction () {
        $name = array('foo' => 'bar');
        $response = new Response(json_encode(array('name' => $name)));
        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

}


text:
var TABLETOPCMS_DEFAULT_CONFIG = {
    ng_app: "myWebsite",
    module_paths: ['../lib/tabletopcms/modules/website.js'],
    module_names: ['tabletopcms.website']
};

//custom merge the two objects
TABLETOPCMS_DEFAULT_CONFIG = (function(tabletopcms_config,tabletopcms_default_config){
    if (tabletopcms_config) {
        function uniqueFilter(array) {
            var a = array.concat();
            for(var i=0; i<a.length; ++i) {
                for(var j=i+1; j<a.length; ++j) {
                    if(a[i] === a[j])
                        a.splice(j--, 1);
                }
            }

            return a;
        }

        for (var key in tabletopcms_config) {
            switch(key) {
                case "ng_app" :
                    tabletopcms_default_config[key] = tabletopcms_config[key];
                    break;
                case "module_paths" :
                case "module_names" :
                    if (tabletopcms_default_config.hasOwnProperty(key)) {
                        tabletopcms_default_config[key] = uniqueFilter(tabletopcms_default_config[key].concat(tabletopcms_config[key]));
                    } else {
                        tabletopcms_default_config[key] = tabletopcms_config[key];
                    }
            }
        }
    }

    return tabletopcms_default_config;
})(TABLETOPCMS_CONFIG,TABLETOPCMS_DEFAULT_CONFIG);

$script(TABLETOPCMS_DEFAULT_CONFIG.module_paths, function() {
    // when all is done, start the angular application
    angular.module(TABLETOPCMS_DEFAULT_CONFIG.ng_app,TABLETOPCMS_DEFAULT_CONFIG.module_names);
});


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dim.server.handler;

import com.dim.server.data.DBTool;
import com.dim.server.msg.LoginResponse;
import com.dim.server.msg.Message;

/**
 *
 * @author yanming_dai
 */
public class LoginHandler{

    public LoginResponse handle(Message message) {
        return DBTool.login((LoginResponse)message);
    }
}


text:
<meta http-equiv="Content-Language" content="en-us"/>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css"/>
<title>Apache Ant User Manual</title>
<base target="mainFrame"/>

Table of Contents

Apache Ant Tasks

Overview of Ant Tasks

List of Tasks

Library Dependencies


text:
exports.definition = {
	config: {
		columns: {
		    "ids": "integer",
		    "title": "string",
		    "description": "string"
		},
		adapter: {
			type: "sql",
			collection_name: "currentsuggestion"
		}
	},
	extendModel: function(Model) {
		_.extend(Model.prototype, {
			// extended functions and properties go here
		});

		return Model;
	},
	extendCollection: function(Collection) {
		_.extend(Collection.prototype, {
			// extended functions and properties go here
		});

		return Collection;
	}
};


text:
/*
  D3.js GrepgoGraphs
*/

d3.grepgoGraph = function module() {
  "use strict";

  // Public variables width default settings
  var type = 'bar',
      width = 300;

  // Private variables

  function grepgoGraph(selection) {
    var graph;
    if (type == 'bar') {
      graph = d3.grepgoGraphBar();
    } else if (type == 'circle') {
      graph = d3.grepgoGraphCircle();
    } else if (type == 'table') {
      graph = d3.grepgoGraphTable();
    }

    graph = graph.width(width);

    selection
      .call(graph);
  }

  // Getter/setter functions
  grepgoGraph.type = function(_) {
    if (!arguments.length) return type;
    type = _;
    return grepgoGraph;
  };

  grepgoGraph.width = function(_) {
    if (!arguments.length) return width;
    width = _;
    return grepgoGraph;
  };

  return grepgoGraph;

};


text:
/// <reference path="fourslash.ts" />

////class A {
////    foo(nu/**/: number) {
////    }
////}

// Completion list shouldn't be present in argument name position
verify.completions({ marker: "", exact: undefined });


text:
var CleverCat = CleverCat || {};

CleverCat.LevelPlay = function(){
  this.cat = null;
  this.platforms = null;
  this.topbar = null;
  this.cursors = null;
  this.score = 0;
  this.scoreText = null;
  this.blocks = null;
  this.storeBlocks = null;
  this.draggingBlocks = null;
  this.dragShadowBlocks = null;

  // Refers to the sprite currently being dragged, if any
  this.draggingSprite = null;
  // The "shadow" of that block for snapping to a valid placement position
  this.draggingSpriteShadow = null;
  this.dragOffset = null; // Pointer-Sprite when dragging starts
};

CleverCat.LevelPlay.prototype = {
  init: function () {
    this.game.world.setBounds(0, 0, 640, 480);
    this.game.physics.startSystem(Phaser.Physics.ARCADE);
    this.game.physics.arcade.gravity.y = 200;
  },

  create: function () {

    //  We're going to be using physics, so enable the Arcade Physics system
    this.game.physics.startSystem(Phaser.Physics.ARCADE);

    //  A simple background for our game
    this.add.sprite(0, 0, 'sky');

    //  The platforms group contains the ground and the cliff
    this.platforms = this.add.group();
    this.platforms.enableBody = true;
    var ground = this.platforms.create(0, this.game.world.height - 64, 'ground');
    ground.scale.setTo(2, 2); //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
    ground.body.immovable = true;
    var cliff = this.platforms.create(this.game.world.width/2, 1*this.game.world.height/3, 'cliff');
    cliff.scale.setTo(3.3, 2);
    cliff.body.setSize(cliff.body.width, cliff.body.height-25, 0, 25);
    cliff.body.immovable = true;

    this.cat = new Cat(this);

    // the bar at the top of the game
    this.topbar = this.add.sprite(0, -13, 'topbar');
    this.topbar.scale.setTo(10, 0.3);

    this.blockManager = new BlockManager(this);

    this.milk = new Milk(this);

    // Timer
    this.startTimer = this.add.text(550,05,'01:30',{font: '400 30px Open Sans', fill: '#000', align: 'right'});
    this.timer = this.time.create(false);
    this.countdownTimer = this.timer.add(Phaser.Timer.MINUTE * 0 + Phaser.Timer.SECOND * 30, this.endTimer, this);
    this.timer.start();
    this.levelOver = false;

    this.cursors = this.input.keyboard.createCursorKeys();

  },

  /* Test whether the group being dragged overlaps with platforms,
   * active blocks, or the player
   */
  overlapsWithActiveObjects: function(group) {
    //what is this function supposed to be doing?
  },

  spritesOverlap: function(sprite1, sprite2) {
    // Checks if the bounding boxes of two sprites overlap
    var left1 = sprite1.x,
      left2 = sprite2.x,
      right1 = sprite1.x + sprite1.width,
      right2 = sprite2.x + sprite2.width,
      top1 = sprite1.y,
      top2 = sprite2.y,
      bottom1 = sprite1.y + sprite1.height,
      bottom2 = sprite2.y + sprite2.height;

    var overlapHorizontally = ((left1 < left2 && right1 >= left2) ||
                               (left1 >= left2 && right2 > left1));
    var overlapVertically = ((top1 < top2 && bottom1 >= bottom2) ||
                             (top1 >= top2 && bottom2 > bottom1));
    return overlapHorizontally && overlapVertically;
  },

  draggingSpriteOverlaps: function() {
      return this.overlapsWithActiveObjects(this.dragShadowBlocks);
  },

  draggingSpriteShadowOverlaps: function() {
    // return this.overlapsWithActiveObjects(this.draggingBlocks);
    // Phaser doesn't respond to recent changes in position. That is,
    // if we change a sprite's position and then immediately check if it
    // overlaps, it still uses the old position. so let's do this manually.
    var opposingGroups = [this.platforms, this.activeBlocks];
    for (var i = 0; i < opposingGroups.length; i++) {
        for (var c = 0; c < opposingGroups[i].children.length; c++) {
            if (this.spritesOverlap(this.draggingSpriteShadow, opposingGroups[i].children[c])) {
                return false;
            }
        }
    }
    if (this.spritesOverlap(this.draggingSpriteShadow, this.cat.sprite)) {
        return false;
    } else {
        return true;
    }
  },

  /*  Countdown Timer */
    render : function () {
        if (this.timer.running){
            this.game.world.remove(this.startTimer);
            this.startTimer = this.game.add.text(550,05,this.formatTime(Math.round((this.countdownTimer.delay - this.timer.ms) / 1000)),
                               { font: '400 30px Open Sans', fill: '#000', align: 'right' } );
        } else {
            this.game.world.remove(this.startTimer);
            if(!this.levelOver){
                this.game.add.text(220,200,"Game Over!",{font: '400 40px Open Sans', fill: '#000', align: 'middle'});
                //disable further movement
                this.cat.sprite.kill();
            }
        }
    },

   drinkMilk: function (player,sprite) {
      sprite.kill();
      player.kill();
      this.timer.stop();
      this.world.remove(this.startTimer);
      this.add.text(190,200,"Congratulations!",{font: '400 40px Open Sans', fill: '#000', align: 'middle'});
      //Setting the indicator of whether player gets the milk to true
      this.levelOver = true;
      var restartText = this.add.text(500, 350, 'Restart', { font: "400 30px Open Sans", fill: "#ff0044", align: "center" });
      restartText.events.onInputDown.add(this.restartTextOnClick, this);

    },

    restartTextOnClick : function() {
        this.state.start('LevelIntro');
    },

    endTimer : function() {
        this.timer.stop();
    },

    formatTime: function(s) {
        var minutes = "0" + Math.floor(s / 60);
        var seconds = "0" + (s - minutes * 60);
        return minutes.substr(-2) + ":" + seconds.substr(-2);
    },

  /**
   * Core update loop. Handles collision checks and player input.
   *
   * @method update
   */
  update: function () {

    this.game.physics.arcade.collide(this.cat.sprite, this.platforms);
    this.game.physics.arcade.collide(this.cat.sprite, this.blockManager.activeBlocks);
    this.game.physics.arcade.collide(this.platforms, this.blockManager.activeBlocks);
    this.game.physics.arcade.collide(this.blockManager.activeBlocks, this.blockManager.activeBlocks);
    this.game.physics.arcade.collide(this.milk.sprite, this.platforms);
    this.game.physics.arcade.collide(this.milk.sprite, this.blockManager.activeBlocks);
    this.game.physics.arcade.overlap(this.cat.sprite, this.milk.sprite, this.drinkMilk, null, this);
    this.game.physics.arcade.collide(this.draggingBlocks, this.blockManager.activeBlocks);

    // Handle overlaps of sprites
    if (this.draggingSprite !== null) {
        if (this.draggingSpriteOverlaps()) {
            this.displayDraggingShadow();
        } else {
            this.hideDraggingShadow();
        }
    }
    this.cat.handleArrowKeys(this.cursors);
  }
};


text:
Zen.Hash is a class that can be used to parse and generate shebang/hash bang
URLs. Parsing is done using ``Zen.Hash#parse`` and generating URLs using
``Zen.Hash#getHash``.

Parsing a URL is relatively simple and the end output is similar to how you'd
parse URLs with query string parameters. First create a new instance of this
class:

    var hash = new Zen.Hash('#!/users/active?limit=10');

The supplied string will be parsed straight away and the result can be
retrieved from two attributes:

* segments
* params

The first attribute contains an array with all the URL segments, the second
one is an object containing all the query string parameters. In case of the
above example that would lead to the following data being stored in these
attributes:

    console.log(hash.segments); // => ["users", "active"]
    console.log(hash.params);   // => {limit: '10'}

Keep in mind that calling ``Zen.Hash#parse`` will overwrite existing segments
and parameters.

Generating a full shebang URL is pretty straight forward as well and can be done
by calling ``getHash()``. This method returns a string containing the shebang
URL including the prefix:

    hash.getHash(); // => "#!/users/active?limit=10"


text:
package submit.server;

import submit.shared.Manifest;
import submit.shared.Registration;
import submit.shared.Encryption;
import submit.shared.Response;

import static submit.shared.FileInfo.makePathNetwork;
import static submit.shared.FileInfo.format;

import submit.server.Parameters;

import java.io.*;

import java.util.Date;
import java.util.Set;
import java.util.jar.*;

import javax.crypto.*;

class Download {

   private static String semesterx, coursex, projectx;

   public static void download (final Parameters args, Response resp,
      final ObjectInputStream ois, final ObjectOutputStream oos) throws ClassNotFoundException, IOException {

      final String course = args.getCourseName();   // cleaned-up a bit
      if (course==null) resp.failBecause ("Missing course information.");

      final String project = args.getProjectName(); // cleaned-up a bit
      if (project==null) resp.failBecause ("Missing project information.");

      if (course==null || project==null) return;

      final File course_directory = SubmitServer.getRealCourseDirectory (course);
      if (!course_directory.isDirectory()) {
         resp.failBecause (String.format ("Course %s not found.", CreateProject.infoCourse (course, args)));
         return;
      }
      coursex=course;
      projectx=project;
      semesterx= CreateProject.getSemester (course_directory);

      final boolean authorized = CreateProject.isAuthorized (args, course_directory);
      if (!authorized) {
         resp.failBecause ("Not authorized.");
         return;
      }

      final File project_directory = SubmitServer.getProjectDirectory (course_directory, project);

      resp.success = true;
      resp.add_line ("Internal protocol message: ready to send jar");
      oos.writeObject (resp);   // 2.  OK to transfer?
      oos.flush();
      ois.readObject(); // Protocol; discard input

      final Encryption e = new Encryption (CreateProject.getPassword (course_directory));

      if (SubmitServer.VERBOSE>4) System.out.format ("Download: encrypted using password='%s'%n", CreateProject.getPassword (course_directory));
      final OutputStream out = new CipherOutputStream (oos, e.getCipher (true));

      jar2jar (project_directory, out);
      oos.flush();
   }

   private static final byte[] buffer = new byte[8_000];
   private static void copyStream (InputStream in, OutputStream out) throws IOException {
      for (;;) {
         final int len = in.read(buffer);
         if (len < 0) break;
         out.write (buffer, 0, len);
      }
   }

   private static void copyStream (final byte[] a, OutputStream out) throws IOException {
      copyStream (new ByteArrayInputStream (a), out);
   }

   private static void copyStream (final String x, OutputStream out) throws IOException {
      copyStream (x.getBytes(), out);
   }

   public static void jar2jar (final File dir, OutputStream out) throws ClassNotFoundException, IOException {
      final String top = String.format ("%s_%s_%s", semesterx, coursex, projectx);
      if (SubmitServer.VERBOSE>4) System.out.format ("jar2jar: dir=%s; top=%s%n", dir, top);

      final JarOutputStream jos = new JarOutputStream (out);
      jos.setMethod (JarEntry.DEFLATED);

      /*
        Include in the jar from some general meta information about the download.
      */

      final JarEntry ije =new JarEntry(makePathNetwork (top,"INFO"));
      jos.putNextEntry (ije);
      final String info = String.format ("copied=%s, semester=%s, course=%s, project=%s%n", format.format(new Date()), semesterx, coursex, projectx);
      copyStream (info, jos);
      jos.closeEntry();

      // JSON info about the projects (JSON info about the submission comes later)
      final JarEntry ijej =new JarEntry(makePathNetwork (top,"info.json"));
      jos.putNextEntry (ijej);
      final String iformat = "{%n\"copied\":\"%s\", \"semester\":\"%s\", \"course\":\"%s\", \"project\":\"%s\"%n}%n";
      final String infoj = String.format (iformat, format.format(new Date()), semesterx, coursex, projectx);
      copyStream (infoj, jos);
      jos.closeEntry();

      final Set<File> students = Latest.lsd (dir);

      for (File student: students) {
         // The latest submission for this student
         final File jar = Latest.latestSubmission (student);
         // In the rare event student directory exists, but no submission
         if (jar==null) continue;

         final Manifest man = Manifest.loadFromJar (jar);  // The submission manifest (not the Jar manifest)

         final String submitter_directory;
         if (man==null) {
            // This is not good.
            if (SubmitServer.VERBOSE>4) System.out.format ("The manifest for '%s' is missing.%n", student.toString());
            submitter_directory = makePathNetwork (top, student.getName());
         } else {
            submitter_directory = makePathNetwork (top, man.getNameAsDirectory());
         }

         if (man!=null) {
            final JarEntry xje = new JarEntry(makePathNetwork (submitter_directory, "INFO"));
            jos.putNextEntry (xje);
            final ByteArrayOutputStream x = new ByteArrayOutputStream ();
            man.print (new PrintStream (x));
            x.close();
            copyStream (new ByteArrayInputStream (x.toByteArray()), jos);
            jos.closeEntry();

            final JarEntry xjej =new JarEntry(makePathNetwork (submitter_directory, "info.json"));
            jos.putNextEntry (xjej);

            final String name    = man.getRegistration().fullName();
            final String first   = man.getRegistration().firstName();
            final String last    = man.getRegistration().lastName();
            final String control = man.getRegistration().getControl();
            final String email   = man.getRegistration().getEMail();
            final String time    = man.formatLocalTimeStamp();  // time of submission
            final String xformat = "{%n\"name\":\"%s\", \"last\":\"%s\", \"first\":\"%s\", \"control\":\"%s\", \"email\":\"%s\", \"time\":\"%s\", \"project\":\"%s\"%n}%n";
            final String xinfoj   = String.format (xformat, name, last, first, control, email, time, projectx);
            copyStream (xinfoj, jos);
            jos.closeEntry();
         }

         final String submissions_directory = makePathNetwork (submitter_directory, "submission");

         try (
              final JarInputStream jis = new JarInputStream (new FileInputStream(jar))
         ) {

               while (true) {
                  final JarEntry je = jis.getNextJarEntry();
                  if (je==null) break;
                  if (je.getName().equals (Manifest.FILENAME)) continue;  // cf INFO; plain text
                  final JarEntry sje =new JarEntry (makePathNetwork (submissions_directory,je.getName()));
                  if (SubmitServer.VERBOSE>5) System.out.format ("Copying from '%s' to '%s'.%n", je, sje);
                  jos.putNextEntry (sje);
                  copyStream (jis, jos);
                  jos.closeEntry();
               }
         }
      }
      jos.close();
   }
}


text:
package moveRefactoring.container

import moveRefactoring.bar.O.m1

object ObjUser {
  def main(args: Array[String]) {
    m1()
  }
}


text:
package com.paipeng.rest;

import java.util.List;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.paipeng.jms.MessageSender;
import com.paipeng.jpa.model.Lotto;
import com.paipeng.jpa.service.LottoService;

@RequestScoped
@Path("")
public class TestRest {

	@Inject
	protected Logger log;

	@Inject
	protected LottoService lottoService;

	@Inject
	protected MessageSender messageSender;

	@PostConstruct
	public void postConstruct() {
		log.info("postConstruct");
	}

	@Path("/echo")
	@Produces("application/json")
	@GET
	@POST
	public Response echo(@QueryParam("echo") String echo) {
		log.info("echo: " + echo);
		return Response.ok(echo).build();
	}

	@Path("/lottos")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	@GET
	@POST
	public List<Lotto> lottos() {
		log.info("lottos");
		List<Lotto> lottoList = lottoService.getLottos();
		return lottoList;
	}

	@Path("/newLotto")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	@GET
	@POST
	public Lotto newLotto() {
		log.info("newLotto");
		Lotto lotto = lottoService.getLastLotto();
		return lotto;
	}

	@Path("/jms/")
	@Produces({MediaType.APPLICATION_JSON})
	@GET
	@POST
	public Response sendJMS(@QueryParam("message") String message) {
		log.info("sendJMS " + message);

		messageSender.sendMessage(message);
		return Response.ok(message).build();
	}

	@Path("/jmsRemote/")
	@Produces({MediaType.APPLICATION_JSON})
	@GET
	@POST
	public Response sendRemoteJMS(@QueryParam("message") String message) {
		log.info("jmsRemote " + message);

		try {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Response.ok(message).build();
	}

}


text:
=begin
#ARTIK Cloud API

#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)

OpenAPI spec version: 2.0.0

Generated by: https://github.com/swagger-api/swagger-codegen.git

=end

require 'spec_helper'
require 'json'

# Unit tests for ArtikCloud::MonetizationApi
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'MonetizationApi' do
  before do
    # run before each test
    @instance = ArtikCloud::MonetizationApi.new
  end

  after do
    # run after each test
  end

  describe 'test an instance of MonetizationApi' do
    it 'should create an instact of MonetizationApi' do
      expect(@instance).to be_instance_of(ArtikCloud::MonetizationApi)
    end
  end

  # unit tests for create_pricing_tiers
  # Define devicetype's pricing tiers.
  # Define devicetype's pricing tiers.
  # @param dtid DeviceType ID
  # @param pricing_tier_info Pricing tier info
  # @param [Hash] opts the optional parameters
  # @return [DeviceTypePricingTier]
  describe 'create_pricing_tiers test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for get_pricing_tiers
  # Get a device's pricing tiers
  # Get a device's pricing tiers
  # @param did Device ID
  # @param [Hash] opts the optional parameters
  # @option opts [BOOLEAN] :active Filter by active
  # @return [DevicePricingTiersEnvelope]
  describe 'get_pricing_tiers test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for get_the__pricing_tiers
  # Get devicetype's pricing tiers.
  # Get devicetype's pricing tiers.
  # @param dtid DeviceType ID
  # @param version Version
  # @param [Hash] opts the optional parameters
  # @return [DeviceTypePricingTiersEnvelope]
  describe 'get_the__pricing_tiers test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for get_upgrade_path
  # Get upgrade path
  # Get upgrade path
  # @param did Device ID
  # @param action Action to perform
  # @param [Hash] opts the optional parameters
  # @return [UpgradePathEnvelope]
  describe 'get_upgrade_path test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for set_pricing_tier
  # Set a device's pricing tier
  # Set a device's pricing tier
  # @param did Device ID
  # @param pricing_tier Pricing tier
  # @param [Hash] opts the optional parameters
  # @return [DevicePricingTierEnvelope]
  describe 'set_pricing_tier test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

end


text:
#include <boost/algorithm/string.hpp>

#include <osquery/logger.h>
#include <osquery/sql.h>
#include <osquery/system.h>
#include <osquery/tables.h>

#include "osquery/core/conversions.h"
#include "osquery/core/windows/wmi.h"

namespace osquery {
namespace tables {

QueryData genVideoInfo(QueryContext& context) {
  Row r;
  QueryData results;

  const WmiRequest wmiSystemReq("SELECT * FROM Win32_VideoController");
  const std::vector<WmiResultItem>& wmiResults = wmiSystemReq.results();
  if (wmiResults.empty()) {
    LOG(WARNING) << "Failed to retrieve video information";
    return {};
  } else {
    long bitsPerPixel = 0;
    wmiResults[0].GetLong("CurrentBitsPerPixel", bitsPerPixel);
    r["color_depth"] = INTEGER(bitsPerPixel);
    wmiResults[0].GetString("InstalledDisplayDrivers", r["driver"]);
    wmiResults[0].GetString("DriverDate", r["driver_date"]);
    wmiResults[0].GetString("DriverVersion", r["driver_version"]);
    wmiResults[0].GetString("AdapterCompatibility", r["manufacturer"]);
    wmiResults[0].GetString("VideoProcessor", r["model"]);
    wmiResults[0].GetString("Name", r["series"]);
    wmiResults[0].GetString("VideoModeDescription", r["video_mode"]);
  }

  results.push_back(r);
  return results;
}
} // namespace tables
} // namespace osquery


text:
/* @flow */
import { extractSupportQuery } from 'fela-utils'

import rehydrateRules from './rehydrateRules'

import type DOMRenderer from '../../../../../flowtypes/DOMRenderer'

const SUPPORT_REGEX = /@supports[^{]+\{([\s\S]+?})\s*}/g

export default function rehydrateSupportRules(
  renderer: DOMRenderer,
  css: string,
  media: string = ''
): Object {
  const supportCache = {}
  let ruleCss = css

  let decl

  while ((decl = SUPPORT_REGEX.exec(css))) {
    const [ruleSet, rules] = decl

    const support = extractSupportQuery(ruleSet)
    ruleCss = ruleCss.replace(ruleSet, '')

    rehydrateRules(renderer, supportCache, rules, media, support)
  }

  return { ruleCss, supportCache }
}


text:
title: Compilers
---
## Compilers

### Programming
At its heart, a barebones computer (aka a stored program computer) is nothing but a machine which knows how to read steps written in a fixed instruction set and execute the same. The set of instructions a computer understands is very specific to it. This is also known as machine language (**opcodes**). Machine Language is often referred to as Binary Code.

Humans interact with computers using **Programs**. A program is simply a sequence of opcodes provided to the computer along with data that is necessary for executing the opcodes.

For example,
```
ADD 10, 20  // ADD is the Opcode
            // and 10, 20 are the two operands(data)
            // needed for the ADD instruction to be executed successfully
```
Humans develop programs to solve complex problems. Looking at how simple opcodes are, if we try to develop programs using opcodes alone, it will be very cumbersome and difficult to debug. To solve this problem, high level languages like C/C++, Python, Java, Javascript, etc were developed.

Now, high level languages aren't suitable for execution by computers. Hence, the need arose for a translator that can digest the high-level language programs and convert them to machine language instructions suitable for execution by a computer.

#### [HUMANS] -> [Highlevel language programs] -> [Translator] -> [Machine Language] -> [Computer]

A **compiler** is a type of translator program, that translates high level languages into binary code, which is nothing but 1s and 0s. When you run your source code, a compiler translates all the code first, then produces the binary code. Then the computer takes the binary code and runs it.

If there are errors in your source code, the compiler detects and flags them. This stops the compilation process. Once all errors are fixed, the compiler converts the code and generates an executable program.

## Parts of a compiler
Most compilers break down into three primary stages: Parsing, Transformation, and Code Generation

1. *Parsing* is taking raw code and turning it into a more abstract representation of the code.
2. *Transformation* takes this abstract representation and manipulates to do whatever the compiler wants it to.
3. *Code Generation* takes the transformed representation of the code and turns it into new code.

#### Parsing
Parsing typically gets broken down into two phases: **Lexical Analysis** and **Syntactic Analysis**.

*Lexical Analysis* takes the raw code and splits it apart into these things called tokens by a thing called a tokenizer (or lexer).
```
Tokens are an array of tiny little objects that describe an isolated piece of the syntax.
They could be numbers, labels, punctuation, operators, etc.
```

*Syntactic Analysis* takes the tokens and reformats them into a representation that describes each part of the syntax
and their relation to one another. This is known as an intermediate representation or Abstract Syntax Tree.
```
An Abstract Syntax Tree, or AST for short, is a deeply nested object.
It represents code in a way that is both easy to work with and tells us a lot of information.
```
#### Transformation
The next type of stage for a compiler is transformation. Again, this just takes the AST from the last step and makes changes to it.
It can manipulate the AST in the same language or it can translate it into an entirely new language.

#### Code Generation
The final phase of a compiler is code generation. Sometimes compilers will do things that overlap with transformation, but for the most part code generation just takes the AST and converts it to binary code.

All compilers need to perform these steps. Most modern compilers also carry out other steps such as checking for type errors and optimizing the resulting compiled code.

#### More Information:
Matt Adesanya's "A Gentler Introduction to Programming" covers compilers vs. interpreters, along with other basic programming concepts.


text:
var Watcher = require("../lib/watcher").Watcher;
var BuildContext = require("../lib/context").BuildContext;
var ModuleReader = require("../lib/reader").ModuleReader;
var ReadFileCache = require("../lib/cache").ReadFileCache;
var grepP = require("../lib/grep");
var util = require("../lib/util");
var fs = require("fs");
var Q = require("q");

var path = require("path");
var sourceDir = path.resolve(__dirname, "source");
var outputDir = path.resolve(__dirname, "output");

try {
    fs.mkdirSync(outputDir);
} catch (exists) {
    // pass
}

var watcher = new Watcher(new ReadFileCache(sourceDir), false);

var debugContext = new BuildContext({
    config: { debug: true },
    sourceDir: sourceDir
}, new ReadFileCache(sourceDir));

var releaseContext = new BuildContext({
    config: { debug: false },
    sourceDir: sourceDir
}, new ReadFileCache(sourceDir));

debugContext.setCacheDirectory(path.join(
    outputDir, ".debug-module-cache"));

releaseContext.setCacheDirectory(path.join(
    outputDir, ".release-module-cache"));

debugContext.setRelativize(true);
releaseContext.setRelativize(true);

function getProvidedP(id) {
    var context = this;
    return context.getProvidedP().then(function(idToPath) {
        if (idToPath.hasOwnProperty(id))
            return context.readFileP(idToPath[id]);
    });
}

function getSourceP(id) {
    return this.readModuleP(id);
}

function waitForHelpers(t, helperP) {
    Q.all([
        helperP(debugContext),
        helperP(releaseContext)
    ]).done(t.finish.bind(t));
}

function checkHome(assert, home) {
    return Q.resolve(home).then(function(home) {
        assert.strictEqual(home.id, "home");
        assert.strictEqual(typeof home.source, "string");
        assert.notEqual(home.source.indexOf("exports"), -1);
        assert.strictEqual(home.source.indexOf('require("./assert");'), 0);
        return home;
    }).invoke("getRequiredP").then(function(reqs) {
        assert.strictEqual(reqs.length, 1);
        assert.strictEqual(reqs[0].id, "assert");
    });
}

exports.testModuleReader = function(t, assert) {
    var reader = new ModuleReader(debugContext, [getSourceP], []);
    var homeP = reader.readModuleP("home");
    checkHome(assert, homeP).done(t.finish.bind(t));
};

exports.testMissingModuleWarning = function(t, assert) {
    function helperP(context) {
        var reader = new ModuleReader(context, [getSourceP], []);
        var id = "this/module/should/not/exist";
        return reader.readModuleP(id).then(function(module) {
            assert.strictEqual(module.id, id);
            assert.notEqual(module.source.indexOf("throw new Error"), -1);
        });
    }

    waitForHelpers(t, helperP);
};

exports.testSkipFailingResolvers = function(t, assert) {
    var reader = new ModuleReader(debugContext, [function(id) {
        return this.makePromise(function(callback) {
            process.nextTick(function() {
                callback(new Error("bad thing happen"));
            });
        });
    }, function(id) {
        throw new Error("superbad situation");
    }, getSourceP], []);

    var homeP = reader.readModuleP("home");
    checkHome(assert, homeP).done(t.finish.bind(t));
};

exports.testReaderCaching = function(t, assert) {
    var reader = new ModuleReader(debugContext, [getSourceP], []);

    var homes = [
        reader.readModuleP("home"),
        reader.readModuleP("home"),
        reader.readModuleP.originalFn.call(reader, "home")
    ];

    assert.strictEqual(homes[0], homes[1]);
    assert.notStrictEqual(homes[0], homes[2]);
    assert.notStrictEqual(homes[1], homes[2]);

    Q.all(homes).spread(function(h0, h1, h2) {
        assert.strictEqual(h0, h1);
        assert.strictEqual(h0, h2);
        assert.strictEqual(h1, h2);

        assert.strictEqual(h0.hash, h1.hash);
        assert.strictEqual(h1.hash, h2.hash);
    }).done(t.finish.bind(t));
};

exports.testMultipleFileOutput = function(t, assert) {
    var mfSource = [
        "function multiFile(foo) {",
        "  console.log(foo);",
        "}"
    ].join("\n");

    var pkg = require("../package.json");

    function getSourceP(id) {
        assert.strictEqual(id, "multi-file");
        return Q.resolve(mfSource);
    }

    function processP1(id, source) {
        assert.strictEqual(source, mfSource);
        return {
            ".js": source,
            ".json": util.readJsonFileP(
                path.join(__dirname, "..", "package.json")
            )
        };
    }

    function processP2(id, input) {
        assert.strictEqual(input[".js"], mfSource);

        var json = input[".json"];
        assert.deepEqual(json, pkg);

        input[".json"] = util.makePromise(function(callback) {
            process.nextTick(function() {
                callback(null, JSON.stringify(json));
            });
        });

        return input;
    }

    function processP3(id, input) {
        assert.strictEqual(input[".js"], mfSource);
        assert.strictEqual(typeof input[".json"], "string");
        assert.deepEqual(JSON.parse(input[".json"]), pkg);

        return input;
    }

    var reader = new ModuleReader(
        debugContext,
        [getSourceP],
        [processP1, processP2, processP3]
    );

    reader.readModuleP("multi-file").then(function(mf) {
        assert.strictEqual(mf.id, "multi-file");
        assert.strictEqual(mf.source, mfSource);
        assert.deepEqual(JSON.parse(mf.output[".json"]), pkg);
    }).done(t.finish.bind(t));
};

exports.testGrepP = function(t, assert) {
    Q.all([
        grepP("@providesModule\\s+\\S+", sourceDir),
        debugContext.getProvidedP()
    ]).spread(function(pathToMatch, valueToPath) {
        assert.deepEqual(pathToMatch, {
            "widget/share.js": "@providesModule WidgetShare",
            "widget/.bogus.js": "@providesModule WidgetShare",
            "widget/bogus.js~": "@providesModule WidgetShare"
        });
        assert.deepEqual(valueToPath, {
            "WidgetShare": "widget/share.js"
        });
    }).done(t.finish.bind(t));
};

exports.testProvidesModule = function(t, assert) {
    var code = arguments.callee.toString();

    /**
     * Look, Ma! A test function that uses itself as input!
     * @providesModule
     * @providesModule foo/bar
     */

    assert.strictEqual(
        code.split("@provides" + "Module").length,
        4);

    assert.strictEqual(
        debugContext.getProvidedId(code),
        "foo/bar");

    assert.strictEqual(
        debugContext.getProvidedId(
            "no at-providesModule, here"),
        null);

    /**
     * Just to make sure we only pay attention to the first one.
     * @providesModule ignored
     */

    function helper(context) {
        var reader = new ModuleReader(context, [
            getProvidedP,
            getSourceP
        ], []);

        return Q.all([
            Q.all([
                reader.readModuleP("widget/share"),
                reader.readModuleP("WidgetShare")
            ]).spread(function(ws1, ws2) {
                assert.strictEqual(ws1.id, ws2.id);
                assert.strictEqual(ws1.id, "WidgetShare");
                assert.strictEqual(ws1, ws2);
            }),

            reader.readMultiP([
                "widget/share",
                "WidgetShare"
            ]).then(function(modules) {
                assert.strictEqual(modules.length, 1);
                assert.strictEqual(modules[0].id, "WidgetShare");
            }),

            reader.readModuleP(
                "widget/gallery"
            ).then(function(gallery) {
                return gallery.getRequiredP();
            }).then(function(deps) {
                assert.strictEqual(deps.length, 1);
                assert.strictEqual(deps[0].id, "WidgetShare");
            }),

            Q.all([
                reader.getSourceP("widget/share"),
                reader.getSourceP("WidgetShare")
            ]).spread(function(source1, source2) {
                assert.strictEqual(source1, source2);
            })
        ]);
    }

    waitForHelpers(t, helper);
};

exports.testMakePromise = function(t, assert) {
    var error = new Error("test");

    function helperP(context) {
        return context.makePromise(function(callback) {
            process.nextTick(function() {
                callback(error, "asdf");
            });
        }).then(function() {
            assert.ok(false, "should have thrown an error");
        }, function(err) {
            assert.strictEqual(err, error);

            return context.makePromise(function(callback) {
                process.nextTick(function() {
                    callback(null, "success");
                });
            }).then(function(result) {
                assert.strictEqual(result, "success");
            });
        })
    }

    waitForHelpers(t, helperP);
};

exports.testRelativize = function(t, assert) {
    var moduleId = "some/deeply/nested/module";
    var processor = require("../lib/relative").getProcessor(null);

    function makeSource(id) {
        var str = JSON.stringify(id);
        return "require(" + str + ");\n" +
            "require(function(){require(" + str + ")}())";
    }

    function helperP(requiredId, expected) {
        assert.strictEqual(
            util.relativize(moduleId, requiredId),
            expected);

        return processor(
            moduleId,
            makeSource(requiredId)
        ).then(function(output) {
            assert.deepEqual(output, {
                ".js": makeSource(expected)
            });
        });
    }

    Q.all([
        helperP("another/nested/module",
                "../../../another/nested/module"),
        helperP("../../buried/module/./file",
                "../../buried/module/file"),
        helperP("../../buried/module/../file",
                "../../buried/file"),
        helperP("./same/level",
                "./same/level"),
        helperP("./same/./level",
                "./same/level"),
        helperP("./same/../level",
                "./level"),
        helperP("some/deeply/buried/treasure",
                "../buried/treasure"),
        helperP("./file", "./file"),
        helperP("./file/../../../module",
                "../../module"),
        helperP("./file/../../module",
                "../module")
    ]).done(t.finish.bind(t));
};

exports.testGetCanonicalId = function(t, assert) {
    function helperP(context) {
        var reader = new ModuleReader(context, [
            getProvidedP,
            getSourceP
        ], []);

        return Q.all([
            reader.getCanonicalIdP("widget/share"),
            reader.getCanonicalIdP("WidgetShare"),
            reader.readModuleP("widget/share").get("id"),
            reader.readModuleP("WidgetShare").get("id")
        ]).spread(function(ws1, ws2, ws3, ws4) {
            assert.strictEqual(ws1, "WidgetShare");
            assert.strictEqual(ws2, "WidgetShare");
            assert.strictEqual(ws3, "WidgetShare");
            assert.strictEqual(ws4, "WidgetShare");
        });
    }

    waitForHelpers(t, helperP);
};

exports.testCanonicalRequires = function(t, assert) {
    function helperP(context) {
        assert.strictEqual(context.ignoreDependencies, false);

        var reader = new ModuleReader(context, [
            getProvidedP,
            getSourceP
        ], []);

        return reader.readModuleP("widget/follow").then(function(follow) {
            assert.strictEqual(follow.source.indexOf("widget/share"), -1);

            assert.strictEqual(strCount(
                'require("../WidgetShare")',
                follow.source
            ), 4);

            assert.strictEqual(strCount(
                'require("./gallery")',
                follow.source
            ), 2);

            assert.strictEqual(strCount(
                'require("../assert")',
                follow.source
            ), 2);
        });
    }

    waitForHelpers(t, helperP);
};

function strCount(substring, string) {
    return string.split(substring).length - 1;
}

exports.testFlatten = function(t, assert) {
    function check(input, expected) {
        var flat = util.flatten(input);
        assert.deepEqual(flat, expected);
    }

    check(1, 1);
    check([[],,[],1, 2], [1, 2]);
    check([[[[[[]]]]]], []);
    check([[1,[[[[2]]],3]]], [1, 2, 3]);
    check([[1],[[2]],[[[3]]]], [1, 2, 3]);
    check([,,,], []);

    t.finish();
};

exports.testWriteFd = function(t, assert) {
    var file = path.join(outputDir, "writeFdP.test.txt");

    function check(content) {
        function afterUnlink(err) {
            return util.openExclusiveP(file).then(function(fd) {
                return util.writeFdP(fd, content).then(function(written) {
                    assert.strictEqual(content, written);
                });
            });
        }

        return function() {
            return util.unlinkP(file).then(afterUnlink, afterUnlink);
        };
    }

    Q.resolve("ignored")
        .then(check("x"))
        .then(check("x\ny"))
        .then(check("x\r\ny"))
        .then(check("\t\nx\t"))
        .then(check("\ufeff")) // zero-width non-breaking space
        .then(check("\u2603")) // snowman
        .then(check("\ud83d\udc19")) // octopus
        .fin(function() {
            return util.unlinkP(file);
        })
        .done(t.finish.bind(t));
};

exports.testWatcherBasic = function(t, assert) {
    var watcher = new Watcher(new ReadFileCache(sourceDir), false);
    var dummy = "dummy.js";
    var dummyFile = path.join(sourceDir, dummy);

    function waitForChangeP() {
        return util.makePromise(function(callback) {
            watcher.on("changed", function(path) {
                callback(null, path);
            });
        });
    }

    util.unlinkP(dummyFile).then(function() {
        return util.openExclusiveP(dummyFile).then(function(fd) {
            return util.writeFdP(fd, "dummy");
        });
    }).then(function() {
        return Q.all([
            watcher.readFileP("home.js"),
            watcher.readFileP(dummy)
        ]);
    }).then(function() {
        return Q.all([
            util.unlinkP(dummyFile),
            waitForChangeP()
        ]);
    }).done(function() {
        watcher.close();
        t.finish();
    });
};

exports.testWatchDirectory = function(t, assert) {
    var watcher = new Watcher(new ReadFileCache(sourceDir), false);
    var watchMe = "watchMe.js";
    var fullPath = path.join(sourceDir, watchMe);

    function waitForChangeP() {
        return util.makePromise(function(callback) {
            watcher.once("changed", function(path) {
                callback(null, path);
            });
        });
    }

    function write(content) {
        return util.openFileP(fullPath).then(function(fd) {
            var promise = waitForChangeP();
            util.writeFdP(fd, content);
            return promise;
        });
    }

    util.unlinkP(fullPath).then(function() {
        return watcher.readFileP(watchMe).then(function(source) {
            assert.ok(false, "readFileP should have failed");
        }, function(err) {
            assert.strictEqual(err.code, "ENOENT");
        });
    }).then(function() {
        return write("first");
    }).then(function() {
        return write("second");
    }).then(function() {
        var promise = waitForChangeP();
        util.unlinkP(fullPath);
        return promise;
    }).then(function() {
        return write("third");
    }).fin(function() {
        return util.unlinkP(fullPath);
    }).done(function() {
        watcher.close();
        t.finish();
    });
};


text:
The environment variable `MALLOC_ARENA_MAX` will now default to `2` for Ruby applications. This environment variable was
previously unset. This change will only affect new applications on the platform, to update an existing application please
run:

```
$ heroku config:set MALLOC_ARENA_MAX=2
```

The goal of setting this value is to decrease memory usage for the majority of Ruby applications that are using threads
such as apps that use Sidekiq or Puma. To understand more about the relationship between this value and memory please see
the following external resources:

- https://www.speedshop.co/2017/12/04/malloc-doubles-ruby-memory.html
- https://www.mikeperham.com/2018/04/25/taming-rails-memory-bloat/

We also maintain our own [documentation on tuning the memory behavior of glibc by setting this environment variable](https://devcenter.heroku.com/articles/tuning-glibc-memory-behavior).

If a your application is not memory bound and would prefer slightly faster execution over the decreased memory use,
you can set their `MALLOC_ARENA_MAX` to a higher value. The default as specified by the [linux man page](http://man7.org/linux/man-pages/man3/mallopt.3.html)
is 8 times the number of cores on the system.

## Jemalloc

Another popular alternative memory allocator is jemalloc. At this time Heroku does not maintain a supported version of this memory allocator,
but you can use it in your application with a 3rd party [jemalloc buildpack](https://elements.heroku.com/buildpacks/mojodna/heroku-buildpack-jemalloc).

If you are using jemalloc, setting `MALLOC_ARENA_MAX` will have no impact on memory or performance. For more information on
how jemalloc interacts with Ruby applications see this external post:

- https://www.speedshop.co/2017/12/04/malloc-doubles-ruby-memory.html#fix-2-use-jemalloc


text:
package org.iwethey.forums.web.filter;

/**
 * Handler for internally generated intermediate anchor tags.
 *

 * $Id: InternalLinkHandler.java 55 2004-12-07 21:53:42Z anderson $
 *

 * @author Scott Anderson (scott@iwethey.org)
 */
public class InternalLinkHandler
{
	/**
	 * Empty constructor for bean use.
	 *

	 */
	public InternalLinkHandler() {}
}


text:
from django.urls import path

from . import views

app_name = 'pages'
urlpatterns = [
    path('', view=views.homepage, name='homepage'),

]


text:
default: clean test

test:
	jbuilder runtest

clean:
	jbuilder clean

.PHONY: clean


text:
package org.scalatra

class ScalatraException(message: String) extends Exception(message)


text:
var baseCallback = require('../internal/baseCallback'),
    baseWhile = require('../internal/baseWhile');

/**
 * Creates a slice of `array` excluding elements dropped from the end.
 * Elements are dropped until `predicate` returns falsey. The predicate is
 * bound to `thisArg` and invoked with three arguments: (value, index, array).
 *
 * If a property name is provided for `predicate` the created `_.property`
 * style callback returns the property value of the given element.
 *
 * If a value is also provided for `thisArg` the created `_.matchesProperty`
 * style callback returns `true` for elements that have a matching property
 * value, else `false`.
 *
 * If an object is provided for `predicate` the created `_.matches` style
 * callback returns `true` for elements that match the properties of the given
 * object, else `false`.
 *
 * @static
 * @memberOf _
 * @category Array
 * @param {Array} array The array to query.
 * @param {Function|Object|string} [predicate=_.identity] The function invoked
 *  per iteration.
 * @param {*} [thisArg] The `this` binding of `predicate`.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * _.dropRightWhile([1, 2, 3], function(n) {
 *   return n > 1;
 * });
 * // => [1]
 *
 * var users = [
 *   { 'user': 'barney',  'active': true },
 *   { 'user': 'fred',    'active': false },
 *   { 'user': 'pebbles', 'active': false }
 * ];
 *
 * // using the `_.matches` callback shorthand
 * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
 * // => ['barney', 'fred']
 *
 * // using the `_.matchesProperty` callback shorthand
 * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
 * // => ['barney']
 *
 * // using the `_.property` callback shorthand
 * _.pluck(_.dropRightWhile(users, 'active'), 'user');
 * // => ['barney', 'fred', 'pebbles']
 */
function dropRightWhile(array, predicate, thisArg) {
    return (array && array.length)
        ? baseWhile(array, baseCallback(predicate, thisArg, 3), true, true)
        : [];
}

module.exports = dropRightWhile;


text:
namespace bubblefs {
namespace mymars {

class Mutex {
  public:
    typedef pthread_mutex_t handle_type;
    Mutex(bool _recursive = false)
        : magic_(reinterpret_cast<uintptr_t>(this)), mutex_(), attr_() {
        //禁止重复加锁
        int ret = pthread_mutexattr_init(&attr_);

        if (ENOMEM == ret) ASSERT(0 == ENOMEM);
        else if (0 != ret) ASSERT(0 == ret);

        ret = pthread_mutexattr_settype(&attr_, _recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_ERRORCHECK);

        if (EINVAL == ret) ASSERT(0 == EINVAL);
        else if (0 != ret) ASSERT(0 == ret);

        ret = pthread_mutex_init(&mutex_, &attr_);

        if (EAGAIN == ret) ASSERT(0 == EAGAIN);
        else if (ENOMEM == ret) ASSERT(0 == ENOMEM);
        else if (EPERM == ret) ASSERT(0 == EPERM);
        else if (EBUSY == ret) ASSERT(0 == EBUSY);
        else if (EINVAL == ret) ASSERT(0 == EINVAL);
        else if (0 != ret) ASSERT(0 == ret);
    }

    ~Mutex() {
        magic_ = 0;
        int ret = pthread_mutex_destroy(&mutex_);

        if (EBUSY == ret) ASSERT(0 == EBUSY);
        else if (EINVAL == ret) ASSERT(0 == EINVAL);
        else if (0 != ret) ASSERT(0 == ret);

        ret = pthread_mutexattr_destroy(&attr_);

        if (EINVAL == ret) ASSERT(0 == EINVAL);
        else if (0 != ret) ASSERT(0 == ret);
    }

    bool lock() {
        // 成功返回0,失败返回错误码
        ASSERT(reinterpret_cast<uintptr_t>(this) == magic_ && 0 != magic_); // "this:%p != mageic:%p", this, (void*)magic_);

        if (reinterpret_cast<uintptr_t>(this) != magic_) return false;

        int ret = pthread_mutex_lock(&mutex_);

        if (EINVAL == ret) ASSERT(0 == EINVAL);
        else if (EAGAIN == ret) ASSERT(0 == EAGAIN);
        else if (EDEADLK == ret) ASSERT(0 == EDEADLK);
        else if (0 != ret) ASSERT(0 == ret);

        return 0 == ret;
    }

    bool unlock() {
        ASSERT(reinterpret_cast<uintptr_t>(this) == magic_ && 0 != magic_); // "this:%p != mageic:%p", this, (void*)magic_);
        //        if (reinterpret_cast<uintptr_t>(this)!=m_magic) return false;

        int ret = pthread_mutex_unlock(&mutex_);

        if (EINVAL == ret) ASSERT(0 == EINVAL);
        else if (EAGAIN == ret) ASSERT(0 == EAGAIN);
        else if (EPERM == ret) ASSERT(0 == EPERM);
        else if (0 != ret) ASSERT(0 == ret);

        return 0 == ret;
    }

    bool trylock() {
        ASSERT(reinterpret_cast<uintptr_t>(this) == magic_ && 0 != magic_); // "this:%p != mageic:%p", this, (void*)magic_);

        if (reinterpret_cast<uintptr_t>(this) != magic_) return false;

        int ret = pthread_mutex_trylock(&mutex_);

        if (EBUSY == ret) return false;

        if (EINVAL == ret) ASSERT(0 == EINVAL);
        else if (EAGAIN == ret) ASSERT(0 == EAGAIN);
        else if (EDEADLK == ret) ASSERT(0 == EDEADLK);
        else if (0 != ret) ASSERT(0 == ret);

        return 0 == ret;
    }

    bool timedlock(long _millisecond) {
        ASSERT(reinterpret_cast<uintptr_t>(this) == magic_ && 0 != magic_); // "this:%p != mageic:%p", this, (void*)magic_);

        if (reinterpret_cast<uintptr_t>(this) != magic_) return false;

        struct timespec ts;
        MakeTimeout(&ts, _millisecond);

        int ret = pthread_mutex_timedlock(&mutex_, &ts);

        switch (ret) {
        case 0: return true;

        case ETIMEDOUT: return false;

        case EAGAIN: ASSERT(false); return false;

        case EDEADLK: ASSERT("EDEADLK"); return false;

        case EINVAL: ASSERT("EINVAL"); return false;

        default: ASSERT(false); return false;
        }

        return false;
    }

    bool islocked() {
        ASSERT(reinterpret_cast<uintptr_t>(this) == magic_);

        int ret = pthread_mutex_trylock(&mutex_);

        if (0 == ret) unlock();

        return 0 != ret;
    }

    handle_type& internal() { return mutex_; }

  private:
    Mutex(const Mutex&);
    Mutex& operator = (const Mutex&);

  private:
    static void MakeTimeout(struct timespec* pts, long millisecond) {
        struct timeval tv;
        gettimeofday(&tv, 0);
        pts->tv_sec = millisecond / 1000 + tv.tv_sec;
        pts->tv_nsec = (millisecond % 1000) * 1000 * 1000 + tv.tv_usec * 1000;

        pts->tv_sec += pts->tv_nsec / (1000 * 1000 * 1000);
        pts->tv_nsec = pts->tv_nsec % (1000 * 1000 * 1000);
    }

  private:
    uintptr_t    magic_;  // Dangling pointer will dead lock, so check it!!!
    pthread_mutex_t mutex_;
    pthread_mutexattr_t attr_;
};

} // namespace mymars
} // namespace bubblefs

#endif // BUBBLEFS_PLATFORM_MARS_MUTEX_H_


text:
#ifndef IMAGEPROCESSINGSETTINGSDIALOG_H
#define IMAGEPROCESSINGSETTINGSDIALOG_H

// Qt
#include <QDialog>
#include <QAbstractButton>
// Local
#include "Structures.h"
#include "Config.h"

namespace Ui {
class ImageProcessingSettingsDialog;
}

//! Image processing dialog class
/*!
    Dialog to set specifc parameters which will be applied on the displayed image.
*/
class ImageProcessingSettingsDialog : public QDialog
{
    Q_OBJECT

    public:
        //! Constructor of the dialog  to set up the UI from the Qt file.
        /*!
        \param parent an QWidget argument. If no parameter is give parent = 0.
        */
        explicit ImageProcessingSettingsDialog(QWidget *parent = 0);
        //! Destructor of the dialog  to delete the created UI.
        /*!
        */
        ~ImageProcessingSettingsDialog();
        //! Function which updates the dialog settings from the stored ones.
        /*!
        */
        void updateDialogSettingsFromStored();

		//simple image functions
        //! Function to get actual ImageProcessingSettings struct.
        /*!
        \return ImageProcessingSettings struct which contains the acutal settings.
        */
		ImageProcessingSettings getImgProcSettingsForImg();
        //! Function to get actual ImageProcessingFlags struct.
        /*!
        \return ImageProcessingFlags struct which contains the acutal flags.
        */
		ImageProcessingFlags ImgProcFlagsForImg();

    private:
        //! ImageProcessingSettingsDialog UI pointer.
        /*!
        Pointer the the user interface file of the dialog.
        */
        Ui::ImageProcessingSettingsDialog *ui;
        //! ImageProcessingSettings struct.
        /*!
        Structure of several settings.
        */
        ImageProcessingSettings imageProcessingSettings;

    public slots:
        //! Public slot to updated the stored settings from the dialog ones.
        /*!
        Public slot to connect with a specific action in program that should call this function
        */
        void updateStoredSettingsFromDialog();

    private slots:
        //! Private slot to reset the display settings.
        /*!
        Private slot tocall function to reset settings. Value from Config.h are used.
        */
        void resetOverlays();

    signals:
        //! Signal: New ImageProcessingSettings are set.
        /*!
        \param p_settings ImageProcessingSettings struct as argument.
        */
        void newImageProcessingSettings(struct ImageProcessingSettings p_settings);
};

#endif // IMAGEPROCESSINGSETTINGSDIALOG_H


text:
namespace pcl
{

  namespace proctor
  {

    class ScanningModelSource : public ModelSource {
      public:
        ScanningModelSource(std::string name, std::string dir) : ModelSource(name, dir)
        {
          rng_.seed(0);

          resetTestGenerator();
        }

        IndicesPtr
        randomSubset(int n, int r);

        void
        pickUniqueModels(std::vector<int>& ids);

        virtual void
        loadModels();

        virtual void
        getModelIDs(std::vector<std::string> &output);

        virtual
        PointCloud<PointNormal>::Ptr getTrainingModel(std::string model_id);

        virtual
        PointCloud<PointNormal>::Ptr getTestModel(std::string model_id);

        void resetTestGenerator();

      protected:
        std::map<std::string, Model> models_;
        boost::mt19937 rng_;
        boost::uniform_real<float> theta_u;
        boost::uniform_real<float> phi_u;

        boost::variate_generator<boost::mt19937&, boost::uniform_real<float> >* theta_gen;
        boost::variate_generator<boost::mt19937&, boost::uniform_real<float> >* phi_gen;
    };

  }
}

#endif


text:
  The content in this example was included from
  a separate file. 🤯

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
  aliqua. Lectus vestibulum mattis ullamcorper velit sed ullamcorper morbi. Fringilla urna porttitor rhoncus dolor purus
  non enim. Nullam vehicula ipsum a arcu cursus vitae congue mauris. Gravida in fermentum et sollicitudin.

  Cursus sit amet dictum sit amet justo donec enim. Sed id semper risus in hendrerit gravida. Viverra accumsan in nisl
  nisi scelerisque eu ultrices vitae. Et molestie ac feugiat sed lectus vestibulum mattis ullamcorper velit. Nec
  ullamcorper sit amet risus nullam. Et egestas quis ipsum suspendisse ultrices gravida dictum. Lorem donec massa sapien
  faucibus et molestie. A cras semper auctor neque vitae.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII" />
    <title>NumberConcept - SeqAn API Documentation</title>

      <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.css" type="text/css" media="screen" charset="utf-8" />

      <link rel="stylesheet" href="lib/bootstrap-multiselect/css/bootstrap-multiselect.css" type="text/css" media="screen" charset="utf-8" />

      <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />
      <link rel="stylesheet" href="css/common.less.css" type="text/css" media="screen" charset="utf-8" />

  Concept NumberConcept

Concept for numbers.

    Defined in

      <seqan/basic.h>

    Signature

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Dox Sources

/*!
 * @concept NumberConcept
 *
 * @headerfile <seqan/basic.h>
 *
 * @brief Concept for numbers.
 */

        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>


text:
package shotgun

import (
	"fmt"
	"github.com/romanoff/fsmonitor"
	"io"
	"log"
	"net/http"
	"net/url"
	"time"
)

type Shotgun struct {
	addr, cmdAddr string
	runner        *Runner
	path          string
	timeout       time.Duration
}

func New(srcPort, cmdPort uint, cmds []string, path string) (*Shotgun, error) {
	runner, err := NewRunner(cmds)
	if err != nil {
		return nil, err
	}

	return &Shotgun{
		addr:    fmt.Sprintf(":%d", srcPort),
		cmdAddr: fmt.Sprintf("127.0.0.1:%d", cmdPort),
		runner:  runner,
		path:    path,
		timeout: 10 * time.Second,
	}, nil
}

func (s *Shotgun) SetTimeout(timeout time.Duration) {
	s.timeout = timeout
}

func (s *Shotgun) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var message string
	u := new(url.URL)
	*u = *(r.URL)
	u.Host = s.cmdAddr
	u.Scheme = "http"

	err := s.runner.CheckRestart()
	if err != nil {
		message = fmt.Sprintf("restart failed: %v", err)
		log.Println(message)
		http.Error(w, message, http.StatusBadGateway)
		return
	}

	req, err := http.NewRequest(r.Method, u.String(), r.Body)
	if err != nil {
		message = fmt.Sprintf("new request failed: %v", err)
		log.Println(message)
		http.Error(w, message, http.StatusBadGateway)
		return
	}
	req.Header = r.Header

	type Result struct {
		response *http.Response
		error    error
	}

	timeout := time.After(s.timeout)
	result := make(chan *Result)

	go func() {
		var last_error error
		for {
			select {
			case <-timeout:
				result <- &Result{nil, last_error}
				return
			default:
			}

			res, err := http.DefaultClient.Do(req)
			if err != nil {
				last_error = err
				time.Sleep(time.Millisecond * 10)
				continue
			}

			result <- &Result{res, nil}
		}
	}()

	res := <-result

	if res.response == nil {
		message = fmt.Sprintf(res.error.Error())
		log.Println(message)
		http.Error(w, message, http.StatusBadGateway)
		return
	}

	defer res.response.Body.Close()

	for k, v := range res.response.Header {
		for _, p := range v {
			w.Header().Add(k, p)
		}
	}
	w.WriteHeader(res.response.StatusCode)
	io.Copy(w, res.response.Body)
}

func (s *Shotgun) Run() error {
	w, err := fsmonitor.NewWatcher()
	if err != nil {
		return err
	}

	w.Watch(s.path)

	go func() {
		for {
			select {
			case <-w.Event:
				s.runner.SetNeedRestart()
			case err := <-w.Error:
				log.Printf("fs error: %s\n", err)
			}
		}
	}()

	return http.ListenAndServe(s.addr, s)
}


text:
// --------- This code has been automatically generated !!! Sat Mar 21 2015 21:52:41 GMT+0100 (Paris, Madrid)
/**
 * @module node-opcua-address-space.types
 */
const util = require("util");
const { assert } = require("node-opcua-assert");
const schema_helpers = require("node-opcua-factory/src/factories_schema_helpers");
const { check_options_correctness_against_schema, resolve_schema_field_types, initialize_field } = schema_helpers;
const { _defaultTypeMap } = require("node-opcua-factory/src/factories_builtin_types");
const { makeExpandedNodeId } = require("node-opcua-nodeid");
const _enumerations = require("node-opcua-factory/src/factories_enumerations")._private._enumerations;
const { BaseUAObject, generate_new_id } = require("node-opcua-factory");
const schema = require("../../schemas/Variant_schema").Variant_Schema;

/**
 * @class Variant
 * @constructor
 * @extends BaseUAObject
 */
function Variant(options) {
    options = options || {};
    check_options_correctness_against_schema(this, schema, options);
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    const self = this;
    assert(this instanceof BaseUAObject); //  ' keyword "new" is required for constructor call')
    resolve_schema_field_types(schema);

    //construction hook
    options = schema.construct_hook(options);
    BaseUAObject.call(this, options);

    /**
     * the variant type.
     * @property dataType
     * @type {DataType}
     * @default  0
     */
    //## Define special behavior for Enumeration
    Object.defineProperties(this, {
        dataType: {
            hidden: false,
            enumerable: true,
            configurable: true,
            get: function () {
                return this.__dataType;
            },
            set: function (value) {
                const coercedValue = _enumerations.DataType.typedEnum.get(value);
                if (coercedValue === undefined || coercedValue === null) {
                    throw new Error("value cannot be coerced to DataType: " + value);
                }
                this.__dataType = coercedValue;
            }
        },
        __dataType: {
            hidden: true,
            writable: true,
            enumerable: false
        }
    });
    self.dataType = initialize_field(schema.fields[0], options.dataType);

    /**
     * @property arrayType
     * @type {VariantArrayType}
     * @default  0
     */
    //## Define special behavior for Enumeration
    Object.defineProperties(this, {
        arrayType: {
            hidden: false,
            enumerable: true,
            configurable: true,
            get: function () {
                return this.__arrayType;
            },
            set: function (value) {
                const coercedValue = _enumerations.VariantArrayType.typedEnum.get(value);
                if (coercedValue === undefined || coercedValue === null) {
                    throw new Error("value cannot be coerced to VariantArrayType: " + value);
                }
                this.__arrayType = coercedValue;
            }
        },
        __arrayType: {
            hidden: true,
            writable: true,
            enumerable: false
        }
    });
    self.arrayType = initialize_field(schema.fields[1], options.arrayType);

    /**
     * @property value
     * @type {Any}
     * @default  null
     */
    self.value = initialize_field(schema.fields[2], options.value);

    // Object.preventExtensions(self);
}
util.inherits(Variant, BaseUAObject);
schema.id = generate_new_id();
Variant.prototype.encodingDefaultBinary = makeExpandedNodeId(schema.id);
Variant.prototype._schema = schema;

const encode_DataType = _enumerations.DataType.encode;
const decode_DataType = _enumerations.DataType.decode;
const encode_VariantArrayType = _enumerations.VariantArrayType.encode;
const decode_VariantArrayType = _enumerations.VariantArrayType.decode;
const encode_Any = _defaultTypeMap.Any.encode;
const decode_Any = _defaultTypeMap.Any.decode;
Variant.prototype.encode = function (stream, options) {
    schema.encode(this, stream, options);
};
/**
 * decode the object from a binary stream
 * @method decode
 *
 * @param stream {BinaryStream}
 * @param [option] {object}
 */
Variant.prototype.decode = function (stream, options) {
    schema.decode(this, stream, options);
};
Variant.prototype.decodeDebug = function (stream, options) {
    schema.decodeDebug(this, stream, options);
};
/**
 *
 * verify that all object attributes values are valid according to schema
 * @method isValid
 * @return {Boolean}
 */
Variant.prototype.isValid = function () {
    return schema.isValid(this);
};
Variant.possibleFields = (function () {
    return ["dataType", "arrayType", "value"];
})();

exports.Variant = Variant;


text:
<?php

namespace LIN3S\CMSKernel\Domain\Model\Menu;

use LIN3S\SharedKernel\Exception\Exception;

/**
 * @author Beñat Espiña <benatespina@gmail.com>
 */
class EmptyMenuItemOrderException extends Exception
{
    public function __construct()
    {
        parent::__construct('Order must not be empty');
    }
}