text:
package io.gravitee.am.repository.jdbc.management.api.spring.organization;

import io.gravitee.am.repository.jdbc.management.api.model.JdbcOrganization;
import io.reactivex.Flowable;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.repository.reactive.RxJava2CrudRepository;
import org.springframework.stereotype.Repository;

/**
 * @author Eric LELEU (eric.leleu at graviteesource.com)
 * @author GraviteeSource Team
 */
@Repository
public interface SpringOrganizationDomainRestrictionRepository extends RxJava2CrudRepository<JdbcOrganization.DomainRestriction, String> {
    @Query("select * from organization_domain_restrictions c where c.organization_id = :organizationId")
    Flowable<JdbcOrganization.DomainRestriction> findAllByOrganizationId(String organizationId);
}


text:
namespace PyCuDNN {
	typedef cudnnSamplerType_t SamplerType;
} // PyCuDNN

#endif // PYCUDNN_SAMPLER_TYPE_HPP

redpajama_set_name: RedPajamaGithub


text:
class DirectoryEntryLimitless : public DirectoryEntryLimited
{
public:
   DirectoryEntryLimitless(SInt32 max_hw_sharers, SInt32 max_num_sharers);
   ~DirectoryEntryLimitless();

   bool hasSharer(tile_id_t sharer_id);
   bool addSharer(tile_id_t sharer_id);
   void removeSharer(tile_id_t sharer_id, bool reply_expected);

   bool getSharersList(vector<tile_id_t>& sharers_list);
   SInt32 getNumSharers();

   UInt32 getLatency();

private:
   // Software Sharers
   BitVector* _software_sharers;

   // Max Num Sharers - For Software Trap
   SInt32 _max_num_sharers;

   // Software Trap Variables
   bool _software_trap_enabled;
   static UInt32 _software_trap_penalty;
   static bool _software_trap_penalty_initialized;
};


text:
/**
 * Photo resource
 */

var express = require("express"),
    router = express.Router(),
    multer = require("multer"),
    mime = require("mime-magic"),
    im = require("imagemagick"),
    async = require("async"),
    path = require("path"),
    fs = require("fs"),
    libs = require("../libs"),
    models = require("../models");

router.get("/", function (req, res) {
  var photo_stream = {
    status: "ok",
    my_photos: null,
    photos: null
  };

  // 投稿者が自分の写真を取得
  models.Photo.find({contributor: req.user})
  .populate("viewers")
  .sort({created_at: -1})
  .exec()
  .then(function (my_photos) {
    photo_stream.my_photos = my_photos;
    // User model -> Twitter model
    return models.Twitter.findOne({id: req.user.id}).exec();
  })
  .then(function (account) {
    // 自分に共有されている写真を取得
    return models.Photo.find({viewers: account})
    .populate("contributor")
    .sort({created_at: -1})
    .exec();
  })
  .then(function (photos) {
    // success
    photo_stream.photos = photos;
    res.json(photo_stream);
  }, function (err) {
    // error
    res.status(500).json({
      status: "ng",
      error: "DB error"
    });
    console.error(err);
  });
});

// upload dir
var temp_dir = path.resolve(__dirname, "../temp");
var photo_dir = path.resolve(__dirname, "../public/photos");
var thumbs_dir = path.resolve(__dirname, "../public/thumbs");

// cleanup temp dir
fs.readdirSync(temp_dir).forEach(function (filename) {
  if (filename[0] === ".") {
    return;
  }

  fs.unlinkSync(path.join(temp_dir, filename));
});

// 写真の削除
function unlinkFile(filename) {
  fs.unlink(filename, function (err) {
    if (err) {
      console.error(err);
    }
  });
}
// 写真の保存
function saveFile(file, callback) {
  var req = this,
      error = null;

  libs.genid(function (err, id) {
    // id の存在確認
    models.Photo.findOne({id: id}, function (err, photo) {
      if (err) {
        unlinkFile(file.path);
        return callback(err);
      }

      // id が既に使われている場合は再度 id 生成
      if (photo !== null) {
        return saveFile.call(req, file, callback);
      }

      // JPEG 確認
      mime(file.path, function (err, type) {
        if (err) {
          unlinkFile(file.path);
          return callback(err);
        }

        // JPEG 以外の場合はエラー
        if (type !== "image/jpeg") {
          unlinkFile(file.path);
          error = new Error("invalid mime type");
          error.statusCode = 400;
          return callback(error);
        }

        // EXIF Data の取得
        im.readMetadata(file.path, function (err, metadata) {
          if (err) {
            console.error(err);
          }

          // DB へ保存
          models.Photo.create({
            id: id,
            name: file.originalname,
            size: file.size,
            contributor: req.user,
            viewers: req.body.viewers,
            exif: metadata && metadata.exif
          }, function (err) {
            if (err) {
              return callback(err);
            }

            // thumbnail の生成
            im.resize({
              srcPath: file.path,
              dstPath: path.join(thumbs_dir, id + ".jpg"),
              quality: 0.8,
              format: "jpg",
              progressive: true,
              width: 480
            }, function (err, stdout, stderr) {
              if (err) {
                console.error(stderr);
                return callback(err);
              }

              // photo dir へ移動
              fs.rename(file.path, path.join(photo_dir, id + ".jpg"), callback);
            });
          });
        });
      });
    });
  });
}

// upload photo (multiple)
router.post("/", multer({dest: temp_dir}));
router.post("/", function (req, res) {
  var photos = req.files.photo;
  var data = req.body;

  if (! photos || ! data.viewers) {
    return res.status(400).json({
      status: "ng",
      error: "Bad Request"
    });
  }

  // cast to Array
  if (! Array.isArray(data.viewers)) {
    data.viewers = [data.viewers];
  }

  // cast to Array
  if (! Array.isArray(photos)) {
    photos = [photos];
  }

  // override filename
  if (data.filename != null) {
    // cast to Array
    if (! Array.isArray(data.filename)) {
      data.filename = [data.filename];
    }

    photos = photos.map(function (photo, index) {
      photo.originalname = data.filename[index];
      return photo;
    });
  }

  if (data.viewers.length === 0) {
    return res.status(400).json({
      status: "ng",
      error: "Bad Request"
    });
  }

  // remove duplicate element from viewers
  data.viewers = data.viewers.filter(function (viewer, index, viewers) {
    return viewers.indexOf(viewer) === index;
  });

  libs.twitter.screenNameToId({
    key: req.user.key,
    secret: req.user.secret
  }, data.viewers, function (err, accounts) {
    if (err) {
      res.status(err.statusCode || 500).json({
        status: "ng",
        error: err.statusCode ? "twitter access error" : "DB error"
      });
      return console.error(err);
    }

    data.viewers = accounts;

    async.parallel(photos.map(function (file) {
      return saveFile.bind(req, file);
    }), function (err) {
      if (err) {
        var message = "save image error";
        if (err.message === "invalid mime type") {
          message = err.message;
        }
        res.status(err.statusCode || 500).json({
          status: "ng",
          error: message
        });
        return console.error(err);
      }

      res.json({status: "ok"});
    });
  });
});

// update photo data
router.put("/:id", function (req, res) {
  var data = req.body;

  if (! data.name && ! data.viewers) {
    return res.status(400).json({
      status: "ng",
      error: "Bad Request"
    });
  }

  // cast to Array
  if (! Array.isArray(data.viewers)) {
    data.viewers = [data.viewers];
  }

  if (data.viewers.length === 0) {
    return res.status(400).json({
      status: "ng",
      error: "Bad Request"
    });
  }

  // remove duplicate element from viewers
  data.viewers = data.viewers.filter(function (viewer, index, viewers) {
    return viewers.indexOf(viewer) === index;
  });

  libs.twitter.screenNameToId({
    key: req.user.key,
    secret: req.user.secret
  }, data.viewers, function (err, accounts) {
    if (err) {
      res.status(err.statusCode || 500).json({
        status: "ng",
        error: err.statusCode ? "twitter access error" : "DB error"
      });
      return console.error(err);
    }

    data.viewers = accounts;

    models.Photo.findOne({id: req.params.id})
    .populate("contributor")
    .exec()
    .then(function (photo) {
      // success

      if (req.user.id !== photo.contributor.id) {
        return res.status(403).json({
          status: "ng",
          error: "Forbidden"
        });
      }

      // update photo data
      data.name && (photo.name = data.name);
      data.viewers && (photo.viewers = data.viewers);
      photo.save(function (err) {
        if (err) {
          res.status(500).json({
            status: "ng",
            error: "update error"
          });
          return console.error(err);
        }

        res.json({
          status: "ok"
        });
      });
    }, function (err) {
      // error
      res.status(500).json({
        status: "ng",
        error: "DB error"
      });
      console.error(err);
    });
  });
});

// delete photo
router.delete("/:id", function (req, res) {
  models.Photo.findOne({id: req.params.id})
  .populate("contributor")
  .exec()
  .then(function (photo) {
    // success

    // id check
    if (req.user.id !== photo.contributor.id) {
      return res.status(403).json({
        status: "ng",
        error: "Forbidden"
      });
    }

    photo.remove(function (err) {
      if (err) {
        res.status(500).json({
          status: "ng",
          error: "remove error"
        });
        return console.error(err);
      }

      unlinkFile(path.join(photo_dir, req.params.id + ".jpg"));
      unlinkFile(path.join(thumbs_dir, req.params.id + ".jpg"));

      res.json({
        status: "ok"
      });
    });
  }, function (err) {
    // error
    res.status(500).json({
      status: "ng",
      error: "DB error"
    });
    console.error(err);
  });
});

module.exports = router;


text:
<!DOCTYPE html>

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

    <title>Owin.ApiGateway</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

Owin.ApiGateway

Configuration API

Get current configuration (GET)

Override current configuration (POST)

Add service instance (POST)

Remove service instance (DEL)

Update service instance (PUT)

Examples


text:
.slider .axis .axis-tick-mark, .slider .axis .axis-minor-tick-mark {
    -fx-fill: null;
    -fx-stroke: black;

}
.slider .axis {
    -fx-tick-label-fill: black;
}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
            new Crm\CaracteristicasBundle\CaracteristicasBundle(),
            new Crm\ClienteBundle\ClienteBundle(),
            new Crm\EmpresaBundle\EmpresaBundle(),
            new Crm\EquipoBundle\EquipoBundle(),
            new Crm\FabricanteBundle\FabricanteBundle(),
            new Crm\GeneralBundle\GeneralBundle(),
            new Crm\PersonalBundle\PersonalBundle(),
            new Crm\ProductoBundle\ProductoBundle(),
            new Crm\UsuariosBundle\UsuariosBundle(),
            new Crm\VentasBundle\VentasBundle(),
            new Crm\TicketBundle\TicketBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Templates on A Developer's Experience</title>
    <link>/tags/templates/</link>
    <description>Recent content in Templates on A Developer's Experience</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Sat, 10 Apr 2010 07:39:00 +0000</lastBuildDate><atom:link href="/tags/templates/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Quiz – (Journey through templates, SFINAE and specialization) !!!</title>
      <link>/2010/04/10/sfinae/</link>
      <pubDate>Sat, 10 Apr 2010 07:39:00 +0000</pubDate>

      <guid>/2010/04/10/sfinae/</guid>
      <description>template&lt;typename A, typename B&gt; class TClass { public: TClass() { } // Overload #1 public: std::string SomeMethod(A a, B b) { std::ostringstream ostr; ostr &lt;&lt; a &lt;&lt; &#34;-&#34; &lt;&lt; b; return ostr.</description>
    </item>

  </channel>
</rss>


text:
require 'redmine'

require 'issue_assignees_helper_patch'

ActiveRecord::Base.observers << :issue_observer

Redmine::Plugin.register :global_assignees do
  name 'Global Assignees plugin'
  author 'Michel Beloshitsky'
  description 'Allows to assign to issue any user not only project member.'
  version '0.2.1'
  url 'http://github.com/mbeloshitsky/global_assignees'
  author_url 'http://github.com/mbeloshitsky'

  requires_redmine :version_or_higher => '2.3.0'
end


text:
'use strict';
var gulp       = require('gulp'),
    requireDir = require('require-dir')('./gulp');

gulp.task('build',  ['build-js', 'lint-js', 'build-css']);
gulp.task('watch',  ['watch-js', 'watch-lint', 'watch-css']);
gulp.task('default',['serve', 'watch']);


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JavaScript Engine testing utilities.
 *
 * The Initial Developer of the Original Code is
 * Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Igor Bukanov
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

//-----------------------------------------------------------------------------
var BUGNUMBER = 347739;
var summary = 'generator_instance.close readonly and immune';
var actual = '';
var expect = '';

//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------

function test()
{
  enterFunc ('test');
  printBugNumber(BUGNUMBER);
  printStatus (summary);

  function gen_test(test_index)
  {
    try {
      yield 1;
    } finally {
      actual += "Inside finally: "+test_index + ' ';
    }
  }

  actual = '';
  expect = 'Inside finally: 1 Inside finally: 2 ';

  var iter1 = gen_test(1);
  iter1.next();
  iter1.close = null;
  iter1 = null;
  gc();

  var iter2 = gen_test(2);
  for (i in iter2)
    iter2.close = null;

  reportCompare(expect, actual, summary + ': 2');

  exitFunc ('test');
}


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_DISCRETE_DYNAMICS_WORLD_H
#define BT_DISCRETE_DYNAMICS_WORLD_H

#include "btDynamicsWorld.h"

class btDispatcher;
class btOverlappingPairCache;
class btConstraintSolver;
class btSimulationIslandManager;
class btTypedConstraint;
class btActionInterface;

class btIDebugDraw;
struct InplaceSolverIslandCallback;

#include "LinearMath/btAlignedObjectArray.h"

///btDiscreteDynamicsWorld provides discrete rigid body simulation
///those classes replace the obsolete CcdPhysicsEnvironment/CcdPhysicsController
class btDiscreteDynamicsWorld : public btDynamicsWorld
{
protected:
    btAlignedObjectArray<btTypedConstraint*> m_sortedConstraints;
    InplaceSolverIslandCallback* m_solverIslandCallback;

    btConstraintSolver* m_constraintSolver;

    btSimulationIslandManager* m_islandManager;

    btAlignedObjectArray<btTypedConstraint*> m_constraints;

    btAlignedObjectArray<btRigidBody*> m_nonStaticRigidBodies;

    btVector3 m_gravity;

    //for variable timesteps
    btScalar m_localTime;
    //for variable timesteps

    bool m_ownsIslandManager;
    bool m_ownsConstraintSolver;
    bool m_synchronizeAllMotionStates;

    btAlignedObjectArray<btActionInterface*> m_actions;

    int m_profileTimings;

    virtual void predictUnconstraintMotion(btScalar timeStep);

    virtual void integrateTransforms(btScalar timeStep);

    virtual void calculateSimulationIslands();

    virtual void solveConstraints(btContactSolverInfo& solverInfo);

    void updateActivationState(btScalar timeStep);

    void updateActions(btScalar timeStep);

    void startProfiling(btScalar timeStep);

    virtual void internalSingleStepSimulation(btScalar timeStep);

    virtual void saveKinematicState(btScalar timeStep);

    void serializeRigidBodies(btSerializer* serializer);

public:
    ///this btDiscreteDynamicsWorld constructor gets created objects from the user, and will not delete those
    btDiscreteDynamicsWorld(btDispatcher* dispatcher, btBroadphaseInterface* pairCache, btConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration);

    virtual ~btDiscreteDynamicsWorld();

    ///if maxSubSteps > 0, it will interpolate motion between fixedTimeStep's
    virtual int stepSimulation(btScalar timeStep, int maxSubSteps = 1, btScalar fixedTimeStep = btScalar(1.) / btScalar(60.));

    virtual void synchronizeMotionStates();

    ///this can be useful to synchronize a single rigid body -> graphics object
    void synchronizeSingleMotionState(btRigidBody* body);

    virtual void addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies = false);

    virtual void removeConstraint(btTypedConstraint* constraint);

    virtual void addAction(btActionInterface*);

    virtual void removeAction(btActionInterface*);

    btSimulationIslandManager* getSimulationIslandManager()
    {
        return m_islandManager;
    }

    const btSimulationIslandManager* getSimulationIslandManager() const
    {
        return m_islandManager;
    }

    btCollisionWorld* getCollisionWorld()
    {
        return this;
    }

    virtual void setGravity(const btVector3& gravity);

    virtual btVector3 getGravity() const;

    virtual void addCollisionObject(btCollisionObject* collisionObject, short int collisionFilterGroup = btBroadphaseProxy::StaticFilter, short int collisionFilterMask = btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);

    virtual void addRigidBody(btRigidBody* body);

    virtual void addRigidBody(btRigidBody* body, short group, short mask);

    virtual void removeRigidBody(btRigidBody* body);

    ///removeCollisionObject will first check if it is a rigid body, if so call removeRigidBody otherwise call btCollisionWorld::removeCollisionObject
    virtual void removeCollisionObject(btCollisionObject* collisionObject);

    void debugDrawConstraint(btTypedConstraint* constraint);

    virtual void debugDrawWorld();

    virtual void setConstraintSolver(btConstraintSolver* solver);

    virtual btConstraintSolver* getConstraintSolver();

    virtual int getNumConstraints() const;

    virtual btTypedConstraint* getConstraint(int index);

    virtual const btTypedConstraint* getConstraint(int index) const;

    virtual btDynamicsWorldType getWorldType() const
    {
        return BT_DISCRETE_DYNAMICS_WORLD;
    }

    ///the forces on each rigidbody is accumulating together with gravity. clear this after each timestep.
    virtual void clearForces();

    ///apply gravity, call this once per timestep
    virtual void applyGravity();

    virtual void setNumTasks(int numTasks)
    {
        (void)numTasks;
    }

    ///obsolete, use updateActions instead
    virtual void updateVehicles(btScalar timeStep)
    {
        updateActions(timeStep);
    }

    ///obsolete, use addAction instead
    virtual void addVehicle(btActionInterface* vehicle);
    ///obsolete, use removeAction instead
    virtual void removeVehicle(btActionInterface* vehicle);
    ///obsolete, use addAction instead
    virtual void addCharacter(btActionInterface* character);
    ///obsolete, use removeAction instead
    virtual void removeCharacter(btActionInterface* character);

    void setSynchronizeAllMotionStates(bool synchronizeAll)
    {
        m_synchronizeAllMotionStates = synchronizeAll;
    }
    bool getSynchronizeAllMotionStates() const
    {
        return m_synchronizeAllMotionStates;
    }

    ///Preliminary serialization test for Bullet 2.76. Loading those files requires a separate parser (see Bullet/Demos/SerializeDemo)
    virtual void serialize(btSerializer* serializer);
};

#endif //BT_DISCRETE_DYNAMICS_WORLD_H


text:
#pragma once

class StkObject
{
private:
	class Impl;
	Impl* pImpl;

public:
	static const int STKOBJECT_UNKNOWN = 0;
	static const int STKOBJECT_UNKW_INT = 1;
	static const int STKOBJECT_UNKW_FLOAT = 2;
	static const int STKOBJECT_UNKW_STRING = 3;
	static const int STKOBJECT_ATTRIBUTE = 10;
	static const int STKOBJECT_ATTR_INT = 11;
	static const int STKOBJECT_ATTR_FLOAT = 12;
	static const int STKOBJECT_ATTR_STRING = 13;
	static const int STKOBJECT_ELEMENT = 20;
	static const int STKOBJECT_ELEM_INT = 21;
	static const int STKOBJECT_ELEM_FLOAT = 22;
	static const int STKOBJECT_ELEM_STRING = 23;

	// XMS decoding error code
	static const int ERROR_XML_ELEMENT_END_NOT_FOUND = -100;
	static const int ERROR_XML_EQUAL_FOUND_WITHOUT_ATTRIBUTE_NAME = -101;
	static const int ERROR_XML_INVALID_ELEMENT_START_FOUND = -102;
	static const int ERROR_XML_INVALID_QUOT_FOUND = -103;
	static const int ERROR_XML_INVALID_ELEMENT_END_FOUND = -104;
	static const int ERROR_XML_SLASH_FOUND_WITHOUT_ELEMENT_END = -105;
	static const int ERROR_XML_CANNOT_HANDLE = -106;
	static const int ERROR_XML_NO_ELEMENT_FOUND = -107;
	static const int ERROR_XML_INVALID_SLASH_FOUND = -108;
	static const int ERROR_XML_SLASH_FOUND_WITHOUT_ELEMENT = -109;

	// JSON decoding error code
	static const int ERROR_JSON_NO_ELEMENT_FOUND = -200;
	static const int ERROR_JSON_INVALID_QUOT_FOUND = -201;
	static const int ERROR_JSON_INVALID_COLON_FOUND = -202;
	static const int ERROR_JSON_INVALID_STRUCTURE = -203;
	static const int ERROR_JSON_INVALID_COMMA = -204;
	static const int ERROR_JSON_CANNOT_HANDLE = -205;
	static const int ERROR_JSON_INVALID_ARRAY_STRUCTURE = -206;
	static const int ERROR_JSON_NO_ROOT_ELEMENT = -207;

	StkObject(const wchar_t*);
	StkObject(const wchar_t*, int);
	StkObject(const wchar_t*, float);
	StkObject(const wchar_t*, const wchar_t*);
	virtual ~StkObject();

	StkObject* Clone();
	bool Equals(StkObject*);
	StkObject* Contains(StkObject*);
	int GetArrayLength();
	int GetChildElementCount();
	int GetAttributeCount();

	wchar_t* GetName();
	int GetType();
	void SetType(int); // DO NOT USE THIS API.

	int GetIntValue();
	float GetFloatValue();
	wchar_t* GetStringValue();
	void SetIntValue(int);
	void SetFloatValue(float);
	void SetStringValue(const wchar_t*);

	StkObject* GetFirstChildElement();
	StkObject* GetLastChildElement();
	StkObject* GetFirstAttribute();
	StkObject* GetLastAttribute();
	StkObject* GetNext();

	void AppendChildElement(StkObject*);
	void AppendAttribute(StkObject*);
	void SetNext(StkObject*); // DO NOT USE THIS API. USE Append* API INSTEAD.

	void ToXml(wchar_t*, int, int Indent = 0); // DO NOT SPECIFY 3RD PARAMETER.
	int ToJson(wchar_t*, int, int Indent = 0, bool ArrayFlag = false); // DO NOT SPECIFY 3RD AND 4TH PARAMETERS.

	static int Analyze(const wchar_t*);
	static StkObject* CreateObjectFromXml(const wchar_t*, int*);
	static StkObject* CreateObjectFromJson(const wchar_t*, int*, StkObject* Obj = 0); // DO NOT SPECIFY 3RD PARAMETER.
};


text:
for test in *_test.rb; do
    ./jtest.sh $test
done

#jruby.sh -I connections/native_jdbc_mysql -e 'Dir.foreach(".") { |file| require file if file =~ /_test.rb$/ }' | tee all.log


text:
terraform-riak allows you to provision a Riak KV or a Riak TS cluster on AWS with a single Terraform command. You can also provision a separate instance pre-configured with the Python, Java and Erlang clients.

## Setup

### Configure AWS Access

You will need to create an [AWS SSH key pair](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) as well as a set of [access keys](http://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html). Please note that AWS SSH keys are region-specific, and that `terraform-riak` defaults to the `US-East (N. Virginia)` region.

Set the following environment variables accordingly:

```bash
$ export KEY_PATH=[PATH_TO_AWS_SSH_KEY]
$ export AWS_ACCESS_KEY=[AWS_ACCESS_KEY]
$ export AWS_SECRET_KEY=[AWS_SECRET_KEY]
```

For example:

```bash
$ export KEY_PATH=$HOME/.ssh/aws-us-east.pem
$ export AWS_ACCESS_KEY=AKIAI3MEITMDDTB00000
$ export AWS_SECRET_KEY=b/keH4gFgERz12K3Eai7Q+zGZG8PJ1f4Oy100000
```

### Check your user and instance configuration on AWS

Terraform swallows error messages - so you get something like "doesn't work, meh" so it is best to ensure that your AWS user and security stuff is correct and lets you connect to boxes before trying to use terraform.

You need to set up a user:
![User Setup](./images/User_setup.png)

Give that user access to do stuff on the box with a security policy - AmazonEC2FullAccess is the brute force one:
![Policy Access](./images/PolicyAccess-to-images.png)

But you also need to 'wire up' the instances to make them visible to the outside world via Security Groups:
![Security Groups](./images/SecurityGroup-to-run-instances-in.png)

### Vagrant local environment

The repo includes a Vagrantfile for your convenience. The OS used by Vagrant can be set using the `VAGRANT_OS` environment variable (set to `UBUNTU` or `CENTOS`).

```bash
$ git clone https://github.com/basho-labs/terraform-riak.git
$ cd terraform-riak
$ export VAGRANT_OS=UBUNTU
$ vagrant plugin install vagrant-env
$ vagrant up
$ vagrant ssh
```

Verify that your AWS credentials and access keys have been properly set in `aws/global.tf` (scroll to the bottom).

### Non-Vagrant local environment

Use the relevant bootstrap script as a reference for the required dependencies or just run it as-is:

```bash
$ git clone https://github.com/basho-labs/terraform-riak.git
$ cd terraform-riak
$ bash bootstrap-ubuntu.sh
$ PATH=$PATH:$PWD
```

If you opt *not* to run one of the bootstrap scripts directly, you will need to populate the AWS configs in `aws/global.tf` directly.

## Usage

Create `working` subdirectories for your cluster and client(s)

```bash
$ mkdir -p working/cluster working/clients
```

### Provision Riak

The `terraform apply` command takes the following variables for a Riak cluster config:

* `product_version` (default: ts-1.3; options: ts-1.3, ts-1.2, kv-2.1.3, kv-2.0.6)
* `platform` (default: ubuntu14; options: rhel6, rhel7, ubuntu12, ubuntu14, debian7)
* `nodes` (default: 5; options: must be >= 3)
* `instance_type` (default: t2.medium; options: any AWS instance type)

The following command uses the default settings to provision a 5-node Riak TS 1.3 cluster using the Ubuntu 14 package:

```bash
$ cd working/cluster
$ terraform apply ../../aws/riak
```

To provision a Riak KV 2.1.3 cluster using the RHEL 6 package:

```bash
$ terraform apply -var 'product_version=kv-2.1.3' -var 'platform=rhel6' ../../aws/riak
```

### Provision a client

To provision a client instance, first change to the `clients` working subdirectory:

```bash
$ cd working/clients
$ terraform apply ../../aws/clients
```

You can provision multiple client instances with a single command by adding the `count` variable:

```bash
$ cd working/clients
$ terraform apply -var 'count=2' ../../aws/clients
```

Take note of the IPs printed to the console at the end of each process.

### Destroy infrastructure

To destroy provisioned infrastructure, simply replace `apply` with `destroy` in the commands above. Run the command from the relevant `working` subdirectory. For example:

```bash
$ cd working/cluster
$ terraform destroy ../../aws/riak

$ cd working/clients
$ terraform destroy ../../aws/clients
```

## Riak TS sample data & queries

The Riak client config downloads a sample time series data file (containing traffic data), and includes example Python scripts to both load and query the data. To run the examples, first SSH in to your client instance:

```bash
$ ssh -i [PATH_TO_AWS_SSH_KEY] ubuntu@[CLIENT_IP]
```

Then, run:

```bash
$ export RIAK_IP=[RIAK_PRIVATE_IP]
$ export TABLE=table1
$ python examples/load.py $RIAK_IP $TABLE
$ python examples/query.py $RIAK_IP $TABLE
```

You can get a `RIAK_PRIVATE_IP` from the output of the relevant `terraform apply` command. The table name `table1` is arbitrary.

## Remote command execution with Ansible

Ansible can be used to remotely execute ad-hoc commands against a client or the Riak cluster. Ansible is pre-installed, but requires activation:

```bash
$ source ansible/hacking/env-setup
$ ssh-agent bash
$ ssh-add [PATH_TO_AWS_SSH_KEY]
```

Command example:

```bash
$ RIAK_IP=[RIAK_PUBLIC_IP]
$ ansible all -i "$RIAK_IP," -u "ubuntu" -m shell -a "sudo riak ping"
$ ansible all -i "$RIAK_IP," -u "ubuntu" -m shell -a "sudo riak-admin member_status"
```

Ansible ad-hoc commands require the target host's Linux user name (`-u` parameter above). Use `ubuntu` for Ubuntu-based instances, `ec2-user` for RHEL-based instances and `admin` for Debian-based instances.


text:
namespace blink {

EventSourceParser::EventSourceParser(const AtomicString& last_event_id,
                                     Client* client)
    : id_(last_event_id),
      last_event_id_(last_event_id),
      client_(client),
      codec_(NewTextCodec(UTF8Encoding())) {}

void EventSourceParser::AddBytes(const char* bytes, uint32_t size) {
  // A line consists of |m_line| followed by
  // |bytes[start..(next line break)]|.
  uint32_t start = 0;
  const unsigned char kBOM[] = {0xef, 0xbb, 0xbf};
  for (uint32_t i = 0; i < size && !is_stopped_; ++i) {
    // As kBOM contains neither CR nor LF, we can think BOM and the line
    // break separately.
    if (is_recognizing_bom_ && line_.size() + (i - start) == std::size(kBOM)) {
      Vector<char> line = line_;
      line.Append(&bytes[start], i - start);
      DCHECK_EQ(line.size(), std::size(kBOM));
      is_recognizing_bom_ = false;
      if (memcmp(line.data(), kBOM, sizeof(kBOM)) == 0) {
        start = i;
        line_.clear();
        continue;
      }
    }
    if (is_recognizing_crlf_ && bytes[i] == '\n') {
      // This is the latter part of "\r\n".
      is_recognizing_crlf_ = false;
      ++start;
      continue;
    }
    is_recognizing_crlf_ = false;
    if (bytes[i] == '\r' || bytes[i] == '\n') {
      line_.Append(&bytes[start], i - start);
      ParseLine();
      line_.clear();
      start = i + 1;
      is_recognizing_crlf_ = bytes[i] == '\r';
      is_recognizing_bom_ = false;
    }
  }
  if (is_stopped_)
    return;
  line_.Append(&bytes[start], size - start);
}

void EventSourceParser::ParseLine() {
  if (line_.size() == 0) {
    last_event_id_ = id_;
    // We dispatch an event when seeing an empty line.
    if (!data_.IsEmpty()) {
      DCHECK_EQ(data_[data_.size() - 1], '\n');
      String data = FromUTF8(data_.data(), data_.size() - 1);
      client_->OnMessageEvent(
          event_type_.IsEmpty() ? event_type_names::kMessage : event_type_,
          data, last_event_id_);
      data_.clear();
    }
    event_type_ = g_null_atom;
    return;
  }
  wtf_size_t field_name_end = line_.Find(':');
  wtf_size_t field_value_start;
  if (field_name_end == WTF::kNotFound) {
    field_name_end = line_.size();
    field_value_start = field_name_end;
  } else {
    field_value_start = field_name_end + 1;
    if (field_value_start < line_.size() && line_[field_value_start] == ' ') {
      ++field_value_start;
    }
  }
  wtf_size_t field_value_size = line_.size() - field_value_start;
  String field_name = FromUTF8(line_.data(), field_name_end);
  if (field_name == "event") {
    event_type_ = AtomicString(
        FromUTF8(line_.data() + field_value_start, field_value_size));
    return;
  }
  if (field_name == "data") {
    data_.Append(line_.data() + field_value_start, field_value_size);
    data_.push_back('\n');
    return;
  }
  if (field_name == "id") {
    if (!memchr(line_.data() + field_value_start, '\0', field_value_size)) {
      id_ = AtomicString(
          FromUTF8(line_.data() + field_value_start, field_value_size));
    }
    return;
  }
  if (field_name == "retry") {
    bool has_only_digits = true;
    for (wtf_size_t i = field_value_start; i < line_.size() && has_only_digits;
         ++i)
      has_only_digits = IsASCIIDigit(line_[i]);
    if (field_value_start == line_.size()) {
      client_->OnReconnectionTimeSet(EventSource::kDefaultReconnectDelay);
    } else if (has_only_digits) {
      bool ok;
      auto reconnection_time =
          FromUTF8(line_.data() + field_value_start, field_value_size)
              .ToUInt64Strict(&ok);
      if (ok)
        client_->OnReconnectionTimeSet(reconnection_time);
    }
    return;
  }
  // Unrecognized field name. Ignore!
}

String EventSourceParser::FromUTF8(const char* bytes, uint32_t size) {
  return codec_->Decode(bytes, size, WTF::FlushBehavior::kDataEOF);
}

void EventSourceParser::Trace(Visitor* visitor) const {
  visitor->Trace(client_);
}

}  // namespace blink


text:
"""Incremental Principal Components Analysis."""

# Author: Kyle Kastner <kastnerkyle@gmail.com>
#         Giorgio Patrini
# License: BSD 3 clause

import numpy as np
from scipy import linalg, sparse

from ._base import _BasePCA
from ..utils import gen_batches
from ..utils.extmath import svd_flip, _incremental_mean_and_var

class IncrementalPCA(_BasePCA):
    """Incremental principal components analysis (IPCA).

    Linear dimensionality reduction using Singular Value Decomposition of
    the data, keeping only the most significant singular vectors to
    project the data to a lower dimensional space. The input data is centered
    but not scaled for each feature before applying the SVD.

    Depending on the size of the input data, this algorithm can be much more
    memory efficient than a PCA, and allows sparse input.

    This algorithm has constant memory complexity, on the order
    of ``batch_size * n_features``, enabling use of np.memmap files without
    loading the entire file into memory. For sparse matrices, the input
    is converted to dense in batches (in order to be able to subtract the
    mean) which avoids storing the entire dense matrix at any one time.

    The computational overhead of each SVD is
    ``O(batch_size * n_features ** 2)``, but only 2 * batch_size samples
    remain in memory at a time. There will be ``n_samples / batch_size`` SVD
    computations to get the principal components, versus 1 large SVD of
    complexity ``O(n_samples * n_features ** 2)`` for PCA.

    Read more in the :ref:`User Guide <IncrementalPCA>`.

    .. versionadded:: 0.16

    Parameters
    ----------
    n_components : int, default=None
        Number of components to keep. If ``n_components`` is ``None``,
        then ``n_components`` is set to ``min(n_samples, n_features)``.

    whiten : bool, default=False
        When True (False by default) the ``components_`` vectors are divided
        by ``n_samples`` times ``components_`` to ensure uncorrelated outputs
        with unit component-wise variances.

        Whitening will remove some information from the transformed signal
        (the relative variance scales of the components) but can sometimes
        improve the predictive accuracy of the downstream estimators by
        making data respect some hard-wired assumptions.

    copy : bool, default=True
        If False, X will be overwritten. ``copy=False`` can be used to
        save memory but is unsafe for general use.

    batch_size : int, default=None
        The number of samples to use for each batch. Only used when calling
        ``fit``. If ``batch_size`` is ``None``, then ``batch_size``
        is inferred from the data and set to ``5 * n_features``, to provide a
        balance between approximation accuracy and memory consumption.

    Attributes
    ----------
    components_ : ndarray of shape (n_components, n_features)
        Components with maximum variance.

    explained_variance_ : ndarray of shape (n_components,)
        Variance explained by each of the selected components.

    explained_variance_ratio_ : ndarray of shape (n_components,)
        Percentage of variance explained by each of the selected components.
        If all components are stored, the sum of explained variances is equal
        to 1.0.

    singular_values_ : ndarray of shape (n_components,)
        The singular values corresponding to each of the selected components.
        The singular values are equal to the 2-norms of the ``n_components``
        variables in the lower-dimensional space.

    mean_ : ndarray of shape (n_features,)
        Per-feature empirical mean, aggregate over calls to ``partial_fit``.

    var_ : ndarray of shape (n_features,)
        Per-feature empirical variance, aggregate over calls to
        ``partial_fit``.

    noise_variance_ : float
        The estimated noise covariance following the Probabilistic PCA model
        from Tipping and Bishop 1999. See "Pattern Recognition and
        Machine Learning" by C. Bishop, 12.2.1 p. 574 or
        http://www.miketipping.com/papers/met-mppca.pdf.

    n_components_ : int
        The estimated number of components. Relevant when
        ``n_components=None``.

    n_samples_seen_ : int
        The number of samples processed by the estimator. Will be reset on
        new calls to fit, but increments across ``partial_fit`` calls.

    batch_size_ : int
        Inferred batch size from ``batch_size``.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    Examples
    --------
    >>> from sklearn.datasets import load_digits
    >>> from sklearn.decomposition import IncrementalPCA
    >>> from scipy import sparse
    >>> X, _ = load_digits(return_X_y=True)
    >>> transformer = IncrementalPCA(n_components=7, batch_size=200)
    >>> # either partially fit on smaller batches of data
    >>> transformer.partial_fit(X[:100, :])
    IncrementalPCA(batch_size=200, n_components=7)
    >>> # or let the fit function itself divide the data into batches
    >>> X_sparse = sparse.csr_matrix(X)
    >>> X_transformed = transformer.fit_transform(X_sparse)
    >>> X_transformed.shape
    (1797, 7)

    Notes
    -----
    Implements the incremental PCA model from:
    *D. Ross, J. Lim, R. Lin, M. Yang, Incremental Learning for Robust Visual
    Tracking, International Journal of Computer Vision, Volume 77, Issue 1-3,
    pp. 125-141, May 2008.*
    See https://www.cs.toronto.edu/~dross/ivt/RossLimLinYang_ijcv.pdf

    This model is an extension of the Sequential Karhunen-Loeve Transform from:
    *A. Levy and M. Lindenbaum, Sequential Karhunen-Loeve Basis Extraction and
    its Application to Images, IEEE Transactions on Image Processing, Volume 9,
    Number 8, pp. 1371-1374, August 2000.*
    See https://www.cs.technion.ac.il/~mic/doc/skl-ip.pdf

    We have specifically abstained from an optimization used by authors of both
    papers, a QR decomposition used in specific situations to reduce the
    algorithmic complexity of the SVD. The source for this technique is
    *Matrix Computations, Third Edition, G. Holub and C. Van Loan, Chapter 5,
    section 5.4.4, pp 252-253.*. This technique has been omitted because it is
    advantageous only when decomposing a matrix with ``n_samples`` (rows)
    >= 5/3 * ``n_features`` (columns), and hurts the readability of the
    implemented algorithm. This would be a good opportunity for future
    optimization, if it is deemed necessary.

    References
    ----------
    D. Ross, J. Lim, R. Lin, M. Yang. Incremental Learning for Robust Visual
    Tracking, International Journal of Computer Vision, Volume 77,
    Issue 1-3, pp. 125-141, May 2008.

    G. Golub and C. Van Loan. Matrix Computations, Third Edition, Chapter 5,
    Section 5.4.4, pp. 252-253.

    See Also
    --------
    PCA
    KernelPCA
    SparsePCA
    TruncatedSVD
    """
    def __init__(self, n_components=None, *, whiten=False, copy=True,
                 batch_size=None):
        self.n_components = n_components
        self.whiten = whiten
        self.copy = copy
        self.batch_size = batch_size

    def fit(self, X, y=None):
        """Fit the model with X, using minibatches of size batch_size.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training data, where n_samples is the number of samples and
            n_features is the number of features.

        y : Ignored

        Returns
        -------
        self : object
            Returns the instance itself.
        """
        self.components_ = None
        self.n_samples_seen_ = 0
        self.mean_ = .0
        self.var_ = .0
        self.singular_values_ = None
        self.explained_variance_ = None
        self.explained_variance_ratio_ = None
        self.noise_variance_ = None

        X = self._validate_data(X, accept_sparse=['csr', 'csc', 'lil'],
                                copy=self.copy, dtype=[np.float64, np.float32])
        n_samples, n_features = X.shape

        if self.batch_size is None:
            self.batch_size_ = 5 * n_features
        else:
            self.batch_size_ = self.batch_size

        for batch in gen_batches(n_samples, self.batch_size_,
                                 min_batch_size=self.n_components or 0):
            X_batch = X[batch]
            if sparse.issparse(X_batch):
                X_batch = X_batch.toarray()
            self.partial_fit(X_batch, check_input=False)

        return self

    def partial_fit(self, X, y=None, check_input=True):
        """Incremental fit with X. All of X is processed as a single batch.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Training data, where n_samples is the number of samples and
            n_features is the number of features.

        check_input : bool, default=True
            Run check_array on X.

        y : Ignored

        Returns
        -------
        self : object
            Returns the instance itself.
        """
        first_pass = not hasattr(self, "components_")
        if check_input:
            if sparse.issparse(X):
                raise TypeError(
                    "IncrementalPCA.partial_fit does not support "
                    "sparse input. Either convert data to dense "
                    "or use IncrementalPCA.fit to do so in batches.")
            X = self._validate_data(
                X, copy=self.copy, dtype=[np.float64, np.float32],
                reset=first_pass)
        n_samples, n_features = X.shape
        if first_pass:
            self.components_ = None

        if self.n_components is None:
            if self.components_ is None:
                self.n_components_ = min(n_samples, n_features)
            else:
                self.n_components_ = self.components_.shape[0]
        elif not 1 <= self.n_components <= n_features:
            raise ValueError("n_components=%r invalid for n_features=%d, need "
                             "more rows than columns for IncrementalPCA "
                             "processing" % (self.n_components, n_features))
        elif not self.n_components <= n_samples:
            raise ValueError("n_components=%r must be less or equal to "
                             "the batch number of samples "
                             "%d." % (self.n_components, n_samples))
        else:
            self.n_components_ = self.n_components

        if (self.components_ is not None) and (self.components_.shape[0] !=
                                               self.n_components_):
            raise ValueError("Number of input features has changed from %i "
                             "to %i between calls to partial_fit! Try "
                             "setting n_components to a fixed value." %
                             (self.components_.shape[0], self.n_components_))

        # This is the first partial_fit
        if not hasattr(self, 'n_samples_seen_'):
            self.n_samples_seen_ = 0
            self.mean_ = .0
            self.var_ = .0

        # Update stats - they are 0 if this is the first step
        col_mean, col_var, n_total_samples = \
            _incremental_mean_and_var(
                X, last_mean=self.mean_, last_variance=self.var_,
                last_sample_count=np.repeat(self.n_samples_seen_, X.shape[1]))
        n_total_samples = n_total_samples[0]

        # Whitening
        if self.n_samples_seen_ == 0:
            # If it is the first step, simply whiten X
            X -= col_mean
        else:
            col_batch_mean = np.mean(X, axis=0)
            X -= col_batch_mean
            # Build matrix of combined previous basis and new data
            mean_correction = \
                np.sqrt((self.n_samples_seen_ / n_total_samples) *
                        n_samples) * (self.mean_ - col_batch_mean)
            X = np.vstack((self.singular_values_.reshape((-1, 1)) *
                           self.components_, X, mean_correction))

        U, S, Vt = linalg.svd(X, full_matrices=False, check_finite=False)
        U, Vt = svd_flip(U, Vt, u_based_decision=False)
        explained_variance = S ** 2 / (n_total_samples - 1)
        explained_variance_ratio = S ** 2 / np.sum(col_var * n_total_samples)

        self.n_samples_seen_ = n_total_samples
        self.components_ = Vt[:self.n_components_]
        self.singular_values_ = S[:self.n_components_]
        self.mean_ = col_mean
        self.var_ = col_var
        self.explained_variance_ = explained_variance[:self.n_components_]
        self.explained_variance_ratio_ = \
            explained_variance_ratio[:self.n_components_]
        if self.n_components_ < n_features:
            self.noise_variance_ = \
                explained_variance[self.n_components_:].mean()
        else:
            self.noise_variance_ = 0.
        return self

    def transform(self, X):
        """Apply dimensionality reduction to X.

        X is projected on the first principal components previously extracted
        from a training set, using minibatches of size batch_size if X is
        sparse.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            New data, where n_samples is the number of samples
            and n_features is the number of features.

        Returns
        -------
        X_new : ndarray of shape (n_samples, n_components)

        Examples
        --------

        >>> import numpy as np
        >>> from sklearn.decomposition import IncrementalPCA
        >>> X = np.array([[-1, -1], [-2, -1], [-3, -2],
        ...               [1, 1], [2, 1], [3, 2]])
        >>> ipca = IncrementalPCA(n_components=2, batch_size=3)
        >>> ipca.fit(X)
        IncrementalPCA(batch_size=3, n_components=2)
        >>> ipca.transform(X) # doctest: +SKIP
        """
        if sparse.issparse(X):
            n_samples = X.shape[0]
            output = []
            for batch in gen_batches(n_samples, self.batch_size_,
                                     min_batch_size=self.n_components or 0):
                output.append(super().transform(X[batch].toarray()))
            return np.vstack(output)
        else:
            return super().transform(X)


text:
import React, { useContext } from "react"
import { PageOwnerType } from "@artsy/cohesion"

export interface AnalyticsContextProps {
  contextPageOwnerId?: string
  contextPageOwnerSlug?: string
  contextPageOwnerType?: PageOwnerType
}

export const AnalyticsContext = React.createContext<{
  contextPageOwnerId?: string
  contextPageOwnerSlug?: string
  contextPageOwnerType?: PageOwnerType
  children?: any
}>({})

export const useAnalyticsContext = () => {
  const analyticsContext = useContext(AnalyticsContext)
  return analyticsContext
}

export const withAnalyticsContext = Component => {
  return props => {
    return (
      <AnalyticsContext.Consumer>
        {contextValues => {
          return <Component {...contextValues} {...props} />
        }}
      </AnalyticsContext.Consumer>
    )
  }
}


text:
package gamecontrollers.rules.palacerules;

import gamecontrollers.Message;
import gamecontrollers.commandcreator.PalaceCommandCreator;
import gamecontrollers.turn.TurnController;

/**
 * Created by kevinnieman on 4/20/14.
 */
public class CityIsLargeEnough extends PalaceRule {
    private PalaceCommandCreator creator;
    private TurnController controller;
    private Message message;

    public CityIsLargeEnough(PalaceCommandCreator creator, TurnController controller){
        this.creator = creator;
        this.controller = controller;
    }
    @Override
    public void update() {
        if(creator.getCurrentLevel() <= creator.getCitySize()){
            message = new Message("Necesito un palace-o mas grande", true);
            setValidity(false);
        }
        else{
            message = new Message("This palace is juuuuuust right", false);
            setValidity(true);
        }
    }

    @Override
    public Message getErrorMessage() {
        return message;
    }
}


text:
/**
 * A collection that holds a set of organization groups
 */
cdb.admin.OrganizationGroups = Backbone.Collection.extend({

  model: cdb.admin.Group,

  url: function(method) {
    var version = cdb.config.urlVersion('organizationGroups', method);
    return '/api/' + version + '/organization/' + this.organization.id + '/groups';
  },

  initialize: function(models, opts) {
    if (!opts.organization) throw new Error('organization is required');
    this.organization = opts.organization;
  },

  parse: function(response) {
    this.total_entries = response.total_entries;
    return response.groups;
  },

  // @return {Object} A instance of cdb.admin.Group. If group wasn't already present a new model with id and collection
  //  set will be returned, i.e. group.fetch() will be required to get the data or handle the err case (e.g. non-existing)
  newGroupById: function(id) {
    var group = this.get(id);
    if (!group) {
      group = new this.model({
        id: id
      });
      // collection set on model, but not added to collection yet
      group.collection = this;
    }
    return group;
  },

  // @return {Number, undefined} may be undefined until a first fetch is done
  totalCount: function() {
    return this.total_entries;
  }

});


text:
const assert = require('assert');

const Account     = require('../Contents/Scripts/account.js').Account;
const PullRequest = require('../Contents/Scripts/pull-request.js').PullRequest;
const Repository  = require('../Contents/Scripts/repository.js').Repository;

describe('PullRequest', function() {
  let number = '42';
  let title  = 'Fix off by one bug';

  let owner       = new Account('obama');
  let repo        = new Repository(owner, 'whitehouse.gov', 'My blog.');
  let pullRequest = new PullRequest(repo, number, title);

  describe('#url', function() {
    it('returns the URL of the pull request', function() {
      assert.equal('https://github.com/obama/whitehouse.gov/pull/42', pullRequest.url);
    });
  });

  describe('#shortURL', function() {
    it('returns the short URL of the pull request', function() {
      assert.equal('obama/whitehouse.gov#42', pullRequest.shortURL);
    });
  });

  describe('#toMenuItem()', function() {
    it('returns a JSON formatted menu item for LaunchBar', function() {
      assert.deepEqual({
        title: 'Fix off by one bug',
        subtitle: 'obama/whitehouse.gov#42',
        alwaysShowsSubtitle: true,
        icon: 'pullRequestTemplate.png',
        url: 'https://github.com/obama/whitehouse.gov/pull/42',
      }, pullRequest.toMenuItem());
    });
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentRegistration.Infrastructure;
using Microsoft.Extensions.DependencyInjection;

namespace FluentRegistration.Internal;

public abstract class AbstractTypeSelector :
    ITypeSelector,
    IRegister
{
    private readonly List<Func<ITypeFilter, bool>> _wherePredicates = new List<Func<ITypeFilter, bool>>();
    private readonly List<Func<ITypeFilter, bool>> _exceptPredicates = new List<Func<ITypeFilter, bool>>();
    private ServiceTypeSelector _serviceTypeSelector = new ServiceTypeSelector();

    protected abstract IEnumerable<Type> Types { get; }

    public ITypeSelector Where(Func<ITypeFilter, bool> predicate)
    {
        GuardAgainst.Null(predicate);

        _wherePredicates.Add(predicate);
        return this;
    }

    public ITypeSelector Except(Func<ITypeFilter, bool> predicate)
    {
        GuardAgainst.Null(predicate);

        _exceptPredicates.Add(predicate);
        return this;
    }

    public IEnumerable<Type> FilteredTypes
    {
        get
        {
            return Types
                .Where(type =>
                {
                    var typeInfo = type.GetTypeInfo();
                    return typeInfo.IsClass && !typeInfo.IsAbstract;
                })
                .Where(type => _wherePredicates.Count == 0 || _wherePredicates.Any(filter => filter(new TypeFilter(type))))
                .Where(type => _exceptPredicates.Count == 0 || _exceptPredicates.None(filter => filter(new TypeFilter(type))));
        }
    }

    public IServiceSelector WithServices
    {
        get
        {
            return _serviceTypeSelector;
        }
    }

    public void Register(IServiceCollection services)
    {
        var filteredTypes = FilteredTypes;

        foreach (var type in filteredTypes)
        {
            var serviceTypes = _serviceTypeSelector.GetServicesFor(type);
            var serviceLifetimeSelector = _serviceTypeSelector.GetLifetimeSelector();

            var componentRegistration = new ComponentImplementedByRegistration<object, object>(serviceTypes, type, serviceLifetimeSelector);
            componentRegistration.Register(services);
        }
    }
}


text:
<?php

namespace App\Http\Requests;

use App\Flyer;
use App\Http\Requests\Request;

class AddPhotoRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Flyer::where([
                'zip'=> $this->zip,
                'street'=> $this->street,
                'user_id'=> $this->user()->id
            ])->exists();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'photo'=>'required|mimes:jpg,jpeg,png,bmp'
        ];
    }
}