text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/common/plat/pegasus/prdfP8Mcs.C $           */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2015                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/** @file  prdfP8Mcs.C
 *  @brief Contains all the plugin code for the PRD P8 MCS
 */

// Framework includes
#include <iipServiceDataCollector.h>
#include <iipSystem.h>
#include <prdfExtensibleChip.H>
#include <prdfGlobal.H>
#include <prdfPluginMap.H>
#include <UtilHash.H>

// Pegasus includes
#include <prdfCalloutUtil.H>
#include <prdfCenMbaCaptureData.H>
#include <prdfCenMembufDataBundle.H>
#include <prdfLaneRepair.H>
#include <prdfP8McsDataBundle.H>
#include <prdfCenMemUtils.H>

#include <prdfP8McsExtraSig.H>

//##############################################################################
//
//                             Special plugins
//
//##############################################################################

namespace PRDF
{

using namespace PlatServices;
using namespace TARGETING;

namespace Mcs
{

/**
 * @brief  Plugin that initializes the MCS data bundle.
 * @param  i_mcsChip An MCS chip.
 * @return SUCCESS
 */
int32_t Initialize( ExtensibleChip * i_mcsChip )
{
    i_mcsChip->getDataBundle() = new P8McsDataBundle( i_mcsChip );
    return SUCCESS;
}
PRDF_PLUGIN_DEFINE( Mcs, Initialize );

/**
 * @brief Analysis code that is called before the main analyze() function.
 * @param i_mcsChip An MCS chip.
 * @param i_sc Step Code Data structure
 * @param o_analyzed TRUE if analysis has been done on this chip
 * @return failure or success
 */
int32_t PreAnalysis( ExtensibleChip * i_mcsChip, STEP_CODE_DATA_STRUCT & i_sc,
                     bool & o_analyzed )
{
    o_analyzed = false;

    // Get memory capture data.
    CaptureData & cd = i_sc.service_data->GetCaptureData();
    P8McsDataBundle * mcsdb = getMcsDataBundle( i_mcsChip );
    ExtensibleChip * membChip = mcsdb->getMembChip();
    if ( NULL != membChip )
    {
        membChip->CaptureErrorData( cd, Util::hashString("FirRegs") );
        membChip->CaptureErrorData( cd, Util::hashString("CerrRegs") );

        CenMbaCaptureData::addMemChipletFirRegs( membChip, cd );
    }

    // Check for a Centaur Checkstop
    int32_t o_rc = MemUtils::checkMcsChannelFail( i_mcsChip, i_sc );
    if ( SUCCESS != o_rc )
    {
        PRDF_ERR( "[Mcs::PreAnalysis] MemUtils::checkMcsChannelFail() failed" );
    }

    return o_rc;
}
PRDF_PLUGIN_DEFINE( Mcs, PreAnalysis );

/**
 * @brief  Plugin function called after analysis is complete but before PRD
 *         exits.
 * @param  i_mcsChip MCS chip
 * @param  i_sc      The step code data struct.
 * @note   This is especially useful for any analysis that still needs to be
 *         done after the framework clears the FIR bits that were at attention.
 * @return SUCCESS.
 */
int32_t PostAnalysis( ExtensibleChip * i_mcsChip,
                      STEP_CODE_DATA_STRUCT & i_sc )
{
    #define PRDF_FUNC "[Mcs::PostAnalysis] "
    int32_t l_rc = SUCCESS;

    P8McsDataBundle * mcsdb = getMcsDataBundle( i_mcsChip );
    ExtensibleChip * membChip = mcsdb->getMembChip();
    if ( NULL != membChip )
    {
        l_rc = MemUtils::chnlCsCleanup( membChip, i_sc );
        if( SUCCESS != l_rc )
        {
            PRDF_ERR( PRDF_FUNC "ChnlCsCleanup() failed for Membuf:0x%08X",
                      membChip->GetId() );
        }
    }

    return SUCCESS;
    #undef PRDF_FUNC
}
PRDF_PLUGIN_DEFINE( Mcs, PostAnalysis );

/**
 * @brief  Checks if spare deployed bit for DMI bus for this MCS is set.
 * @param  i_mcsChip MCS chip
 * @param  i_sc      The step code data struct.
 * @return SUCCESS if bit is on, FAIL otherwise.
 */
int32_t checkSpareBit( ExtensibleChip * i_mcsChip,
                       STEP_CODE_DATA_STRUCT & i_sc )
{
    using namespace LaneRepair;

    int32_t l_rc = FAIL; // Default is to handle the attention (via rule code).

    ExtensibleChip * mbChip = getMcsDataBundle( i_mcsChip )->getMembChip();

    if ( isSpareBitOnDMIBus(i_mcsChip, mbChip) )
    {
        // Ignore attention and do not commit the error log.
        i_sc.service_data->setDontCommitErrl();
        l_rc = SUCCESS;
    }

    return l_rc;
}
PRDF_PLUGIN_DEFINE( Mcs, checkSpareBit );

/**
 * @fn ClearMbsSecondaryBits
 * @brief Clears MBS secondary Fir bits which may come up because of MCIFIR
 * @param  i_chip       The Mcs chip.
 * @param  i_sc         ServiceDataColector.
 * @return SUCCESS.

 */
int32_t ClearMbsSecondaryBits( ExtensibleChip * i_chip,
                               STEP_CODE_DATA_STRUCT & i_sc  )
{
    #define PRDF_FUNC "[ClearMbsSecondaryBits] "

    int32_t l_rc = SUCCESS;
    do
    {
        P8McsDataBundle * mcsdb = getMcsDataBundle( i_chip );
        ExtensibleChip * membChip = mcsdb->getMembChip();

        if ( NULL == membChip ) break;

        // Not checking if MBSFIR bits are set or not.
        // Clearing them blindly as it will give better performance.
        SCAN_COMM_REGISTER_CLASS * mbsAndFir =
                                membChip->getRegister("MBSFIR_AND");

        if( NULL == mbsAndFir )
        {
            PRDF_ERR( PRDF_FUNC "Can not find MBSFIR_AND "
                       "for 0x%08x", membChip->GetId());
            break;
        }
        mbsAndFir->setAllBits();

        mbsAndFir->ClearBit(3);
        mbsAndFir->ClearBit(4);
        l_rc = mbsAndFir->Write();
        if ( SUCCESS != l_rc )
        {
            PRDF_ERR( PRDF_FUNC "MBSFIR_AND write failed"
                       "for 0x%08x", membChip->GetId());
            break;
        }
    }while( 0 );
    return SUCCESS;

    #undef PRDF_FUNC
} PRDF_PLUGIN_DEFINE( Mcs, ClearMbsSecondaryBits );

//------------------------------------------------------------------------------

/**
 * @brief   When not in MNFG mode, clear the service call flag so that
 *          thresholding will still be done, but no visible error log committed.
 * @param   i_chip MCS chip
 * @param   i_sc   Step code data struct
 * @returns SUCCESS always
 */
int32_t ClearServiceCallFlag( ExtensibleChip * i_chip,
                              STEP_CODE_DATA_STRUCT & i_sc )
{
    if ( i_sc.service_data->IsAtThreshold() && !mfgMode() &&
         (CHECK_STOP != i_sc.service_data->getPrimaryAttnType()) &&
         (!i_sc.service_data->queryFlag(ServiceDataCollector::UNIT_CS)) )
    {
        i_sc.service_data->clearServiceCall();
    }

    return SUCCESS;
}
PRDF_PLUGIN_DEFINE( Mcs, ClearServiceCallFlag );

/**
 * @brief   Checks if the parent proc chip is either a Murano at DD least 2.0
 *          or a Venice. If neither, implements the DD1 actions
 *          of MBSFIR for the specified bit.
 * @param   i_mcsChip MCS chip
 * @param   i_sc      Step code data struct
 * @return  FAIL if MuranoDD2Plus or Venice, SUCCESS otherwise
 */
int32_t dd1mcifirBit(ExtensibleChip * i_mcsChip,
                     STEP_CODE_DATA_STRUCT & i_sc,
                     uint32_t i_bitNum )
{
    int32_t l_rc = SUCCESS;
    bool isMuranoDD2Plus = false;
    bool isVenice = false;
    TargetHandle_t l_mcsTrgt = i_mcsChip->GetChipHandle();
    TargetHandle_t l_proc  = getParentChip( l_mcsTrgt );
    uint8_t l_chipLevel = getChipLevel(l_proc);
    MODEL l_model = getProcModel(l_proc);

    if( MODEL_VENICE == l_model )
        isVenice = true;
    else if( (0x20 <= l_chipLevel) && (MODEL_MURANO == l_model) )
        isMuranoDD2Plus = true;

    if(isMuranoDD2Plus || isVenice)
    {
        l_rc = FAIL;
    }
    else
    {
        i_sc.service_data->SetCallout(l_mcsTrgt, MRU_MED);
        ClearServiceCallFlag(i_mcsChip, i_sc);
        if(48 == i_bitNum)
            i_sc.service_data->SetErrorSig( PRDFSIG_MciFir_48_DD1Signature );
        else if(49 == i_bitNum)
            i_sc.service_data->SetErrorSig( PRDFSIG_MciFir_49_DD1Signature );
    }

    return l_rc;
}

#define PLUGIN_MCIFIR_DD1_CHECK( BITNUM )                     \
int32_t dd1mcifirBit##BITNUM (ExtensibleChip * i_mcsChip,     \
                              STEP_CODE_DATA_STRUCT & i_sc )  \
{                                                             \
    return dd1mcifirBit( i_mcsChip, i_sc, BITNUM );           \
}                                                             \
PRDF_PLUGIN_DEFINE( Mcs, dd1mcifirBit##BITNUM );

PLUGIN_MCIFIR_DD1_CHECK( 48 )
PLUGIN_MCIFIR_DD1_CHECK( 49 )

//------------------------------------------------------------------------------

/**
 * @brief   Handles a memory mirror action event.
 * @param   i_mcsChip An MCS chip.
 * @param   i_sc      The step code data struct
 * @returns SUCCESS always
 */
int32_t handleMirrorAction( ExtensibleChip * i_mcsChip,
                            STEP_CODE_DATA_STRUCT & i_sc )
{
    #define PRDF_FUNC "[handleMirrorAction] "

    int32_t l_rc = SUCCESS;

    do
    {
        // Get the primary MCS of the mirrored pair.
        P8McsDataBundle * mcsdb = getMcsDataBundle( i_mcsChip );
        ExtensibleChip * primcs = mcsdb->getPrimaryMirroredMcs();
        if ( NULL == primcs )
        {
            PRDF_ERR( PRDF_FUNC "getPrimaryMirroredMcs() failed: "
                      "i_mcsChip=0x%08x", i_mcsChip->GetId() );
            break;
        }

        // Manually capture the registers needed from the primary MCS.
        CaptureData & cd = i_sc.service_data->GetCaptureData();
        primcs->CaptureErrorData( cd, Util::hashString("MirrorRegs") );

        SCAN_COMM_REGISTER_CLASS * reg = primcs->getRegister("MCHWFM");
        l_rc = reg->Read();
        if ( SUCCESS != l_rc )
        {
            PRDF_ERR( PRDF_FUNC "Read() failed on MCHWFM: primcs=0x%08x",
                      primcs->GetId() );
            break;
        }

        if ( i_sc.service_data->IsAtThreshold() )
        {
            if ( reg->IsBitSet(1) ) // Mirror disabled.
            {
                // Error log will be predictive.
                i_sc.service_data->SetErrorSig( PRDFSIG_MirrorActionTH );
            }
            else // Mirror still enabled but getting a flood of attentions.
            {
                // Just submit the error log as hidden.
                i_sc.service_data->clearLogging();
            }
        }
        else // Under threshold
        {
            // Re-enable the mirror.
            reg->ClearBit(1);
            reg->ClearBit(2);
            reg->ClearBit(3);

            l_rc = reg->Write();
            if ( SUCCESS != l_rc )
            {
                PRDF_ERR( PRDF_FUNC "Write() failed on MCHWFM: primcs=0x%08x",
                          primcs->GetId() );
                break;
            }
        }

    } while (0);

    return SUCCESS;

    #undef PRDF_FUNC
}
PRDF_PLUGIN_DEFINE( Mcs, handleMirrorAction );

//------------------------------------------------------------------------------

int32_t calloutInterface_dmi( ExtensibleChip * i_mcsChip,
                              STEP_CODE_DATA_STRUCT & io_sc )
{
    CalloutUtil::calloutBusInterface( i_mcsChip, MRU_LOW );
    return SUCCESS;
}
PRDF_PLUGIN_DEFINE( Mcs, calloutInterface_dmi );

} // end namespace Mcs
} // end namespace PRDF


text:
<?php

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="Application\Repository\IssueRepository"))
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="`issue`")
 */
class Issue extends EntityAbstract
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Project")
     * @ORM\JoinColumn(name="project_id", referencedColumnName="id")
     */
    protected $project;

    /** task's name**/
    /** @ORM\Column(type="string", length=128) */
    protected $summary;

    /** @ORM\Column(type="string", length=1024) */
    protected $description;

    /**
     * @ORM\ManyToOne(targetEntity="IssueType")
     * @ORM\JoinColumn(name="type_id", referencedColumnName="id")
     */
    protected $type;

    /** sequence number of elements in column */
    /** @ORM\Column(type="string", length=128) */
    protected $sequence_number=0;

    /**
     * @ORM\ManyToOne(targetEntity="IssuePriority")
     * @ORM\JoinColumn(name="priority_id", referencedColumnName="id")
     */
    protected $priority;

    /**
     * Who working with task now
     *
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumn(name="user_to_assignee", referencedColumnName="id")
     */
    protected $assignee;

    /**
     * @ORM\ManyToOne(targetEntity="Status")
     * @ORM\JoinColumn(name="status_id", referencedColumnName="id")
     */
    protected $status;

    /**
     * @ORM\ManyToOne(targetEntity="Sprint")
     * @ORM\JoinColumn(name="sprint_id", referencedColumnName="id", nullable=true)
     */
    protected $sprint;

//    /**  */
//   /** @ORM\Column(type="string", length=256) */
//    protected $labels;

    /** @ORM\Column(type="datetime") */
    protected $created;

    /** @ORM\Column(type="datetime", nullable=true) */
    protected $updated;

    /**
     * @ORM\PrePersist
     */
    public function prePersist()
    {
        $this->created = new \DateTime();
    }

    /**
     * @ORM\PreUpdate
     */
    public function preUpdate()
    {
        $this->updated = new \DateTime();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
include_once('httpful.phar');
  // Client.php
  // Utility class to perform http requests
  // For more info visit https://api.relateiq.com/#/php

class Client {
  private static $key;
  private static $secret;
  private static $endpoint;
  private static $headers = array("Content-type" => "application/json", "Accept" => "application/json");
  private static $cache = array ();

  # Hybrids
  public static function key($value=null) {
    self::$key = $value ?: self::$key;
    return self::$key;
  }

  public static function secret($value=null) {
    self::$secret = $value ?: self::$secret;
    return self::$secret;
  }

  public static function endpoint($value=null) {
    self::$endpoint = $value ?: self::$endpoint;
    return self::$endpoint;
  }

  public static function headers($value=null) {
    self::$headers = $value ?: self::$headers;
    return self::$headers;
  }

  public static function relateIQ($key, $secret, $endpoint=null) {
    $endpoint = $endpoint ?: "https://api.relateiq.com/v2/";
    self::key($key);
    self::secret($secret);
    self::endpoint($endpoint);
  }

  public function cache($endpoint, $value = null) {
    if ($value != null) {
      self::$cache[$endpoint] = $value;
    }

    return array_key_exists($endpoint, self::$cache) ? self::$cache[$endpoint] : "";
  }

  public function get($endpoint, $options=[])
  {
    $uri = Client::endpoint().$endpoint.Client::getUriOptions($options);
    $response = \Httpful\Request::get($uri)->authenticateWith(Client::key(), Client::secret())
      ->addHeaders(Client::headers())->send();
    return $response;
  }

  public function post($endpoint, $data, $options=[])
  {
    $uri = Client::endpoint().$endpoint.Client::getUriOptions($options);
    $data = json_encode($data);
    $response = \Httpful\Request::post($uri)->authenticateWith(Client::key(), Client::secret())
      ->addHeaders(Client::headers())->body($data)->send();
      return $response;
  }

  public function put($endpoint, $data, $options=[])
  {
    $uri = Client::endpoint().$endpoint.Client::getUriOptions($options);
    $data = json_encode($data);
    $response = \Httpful\Request::put($uri)->sendsJson()->authenticateWith(Client::key(), Client::secret())
      ->addHeaders(Client::headers())->body($data)->send();
      return $response;
  }

  public function delete($endpoint, $options=[])
  {
    $uri = Client::endpoint().$endpoint.Client::getUriOptions($options);
    $response = \Httpful\Request::delete($uri)->authenticateWith(Client::key(), Client::secret())
      ->addHeaders(Client::headers())->send();
    return $response;
  }

  public function getUriOptions($options=[])
  {
    $qyery = '';
    if(count($options) > 0)
    {
      if (count($options) == 1) {
        $query = $query. current($options);
      } else {
        $query = '?';
        foreach ($options as $key => $value) {
          $query = $query.$key.'='.$value.'&';
        }
        $pos = strrpos($query, '&');
        $query = substr($query, 0, $pos);
      }
    }
    return $query;
  }

  public function fetch($endpoint,$options=[])
  {
    try {

      $data = Client::get($endpoint);
      if ($data->code == 200) {
        return $data;
      } elseif ($data->code == 404) {
        return [];
      }else{
        throw new Exception ($data->body->errorMessage);
      }
    } catch (Exception $e) {
      if ($e->getCode() == 404) {
        return [];
      }
      throw new Exception ($e);
    }
  }
}

?>


text:
#ifndef MTFILE_H
#define MTFILE_H

#include "GiSTstore.h"

//	MTfile is a simple storage class for GiSTs to work over
//	UNIX/NT files. It is a copy of the GiSTfile class.

class MTfile: public GiSTstore {
public:
	MTfile(): GiSTstore() {}

	void Create(const char *filename);
	void Open(const char *filename);
	void Close();

	void Read(GiSTpage page, char *buf);
	void Write(GiSTpage page, const char *buf);
	GiSTpage Allocate();
	void Deallocate(GiSTpage page);
	void Sync() {}
//	int PageSize() const { return 65536; }
	int PageSize() const { return 4096; }

private:
	int fileHandle;
};

#endif


text:
YUI.add('mojitB-tests', function(Y) {

    var suite = new YUITest.TestSuite('mojitB-tests'),
        controller = null,
        A = YUITest.Assert;

    suite.add(new YUITest.TestCase({

        name: 'mojitB user tests',

        setUp: function() {
            controller = Y.mojito.controllers.mojitB;
        },
        tearDown: function() {
            controller = null;
        },

        'test mojit': function() {
            var ac,
                modelData,
                assetsResults,
                doneResults;
            modelData = { x:'y' };
            ac = {
                assets: {
                    addCss: function(css) {
                        assetsResults = css;
                    }
                },
                models: {
                    mojitBModelFoo: {
                        getData: function(cb) {
                            cb(null, modelData);
                        }
                    }
                },
                done: function(data) {
                    doneResults = data;
                }
            };

            A.isNotNull(controller);
            A.isFunction(controller.index);
            controller.index(ac);
            A.areSame('./index.css', assetsResults);
            A.isObject(doneResults);
            A.areSame('Mojito is working.', doneResults.status);
            A.areSame('{"x":"y"}', doneResults.data);

        }

    }));

    YUITest.TestRunner.add(suite);

}, '0.0.1', {requires: ['mojito-test', 'mojitB']});


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Baked Squash Casserole</title>
      <categories>
        <cat>Vegetables</cat>
        <cat>Casserole</cat>
        <cat>Vegetarian</cat></categories>
      <yield>10</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>5</qty>
          <unit>pounds</unit></amt>
        <item>Yellow squash</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>teaspoons</unit></amt>
        <item>Ener-G Egg Replacer</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>tablespoons</unit></amt>
        <item>Onion, chopped</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Green pepper, diced</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Light Whole Wheat Roll, crumb</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Dash of pepper</item></ing>
      <ing>
        <amt>
          <qty>1/3</qty>
          <unit>cups</unit></amt>
        <item>Brown Sugar</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Salt, as desired</item></ing></ingredients>
    <directions>
      <step>  Directions: Cut off tips of squash, cut each squash into 3-4 pieces. Drop
  squash into a large saucepan with enough boiling water to cover. Return to
  a boil, reduce heat and cook until tender. Mash, reserving liquid. Combine
  squash and liquid with egg replacer, bread crumbs, sugar, salt, onion and
  pepper.  Turn into a 3 quart casserole that has been lightly greased or
  sprayed with non-stick vegetable spray. Cover with a light layer of crumbs.
  Bake at 350 degrees until lightly browned. Makes 10 servings. Files of
  Alice in Houston, update old Family Recipe 5/11/93

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>


text:
import com.jogamp.opengl.GL;
import org.joml.Vector4f;
import util.IVertexData;
import util.PolygonMesh;

import java.util.*;

/**
 * Created by mspringer on 9/28/16.
 */
public class Tower {
    private float BASE_DIMENSION = 10f;
    private int id;
    public Stack<Disk> disks;
    public List<Disk> diskList;
    public List<PolygonMesh> mesh;
    public List<Map<String, String>> shaderToVertexAttribute;

    public Tower(int id) {
        this.id = id + 1;
        generateMesh();
    }

    public int getId() {
        return this.id;
    }

    public Disk getTopDisk() {
        return this.disks.peek();
    }

    public void popTopDisk() {
        try {
            this.disks.pop();
        }
        catch (EmptyStackException e) {
            e.printStackTrace();
        }
    }

    public void addNewDisk(Disk d) {
        disks.push(d);
    }

    public void addNewDiskToList(Disk d) {
        this.diskList.add(d);
    }

    private void generateMesh() {
        List<Vector4f> colors = new ArrayList<Vector4f>();

        colors.add(new Vector4f(1, 0, 0, 1)); //red
        colors.add(new Vector4f(0, 1, 0, 1)); //green
        colors.add(new Vector4f(0, 0, 1, 1)); //blue
        colors.add(new Vector4f(0, 0, 0, 1)); //black

        List<Vector4f> positions = new ArrayList<Vector4f>();

        /** BASE **/
        // bottom left
        positions.add(new Vector4f(-BASE_DIMENSION, -BASE_DIMENSION, 0, 1.0f));
        // bottom right
        positions.add(new Vector4f(BASE_DIMENSION, -BASE_DIMENSION, 0, 1.0f));
        // top right
        positions.add(new Vector4f(BASE_DIMENSION, BASE_DIMENSION, 0, 1.0f));
        // top left
        positions.add(new Vector4f(-BASE_DIMENSION, BASE_DIMENSION, 0, 1.0f));

        List<IVertexData> vertexData = new ArrayList<IVertexData>();
        VertexAttribWithColorProducer producer = new VertexAttribWithColorProducer();
        for (int i = 0; i < positions.size(); i++) {
            IVertexData v = producer.produce();
            v.setData("position", new float[]{positions.get(i).x,
                    positions.get(i).y,
                    positions.get(i).z,
                    positions.get(i).w});
            v.setData("color", new float[]{colors.get(this.id % colors.size()).x,
                    colors.get(this.id % colors.size()).y,
                    colors.get(this.id % colors.size()).z,
                    colors.get(this.id % colors.size()).w});
            vertexData.add(v);
        }

                /*
                We now generate a series of indices.
                These indices will be for the above list
                of vertices. For example we want to use
                the above list to draw triangles.
                The first triangle will be created from
                vertex numbers 0, 1 and 2 in the list above
                (indices begin at 0 like arrays). The second
                triangle will be created from vertex numbers
                0, 2 and 3. Therefore we will create a list
                of indices {0,1,2,0,2,3}.

                What is the advantage of having a second
                list? Vertices are often shared between
                triangles, and having a separate list of
                indices avoids duplication of vertex data
                 */
        List<Integer> indices = new ArrayList<Integer>();
        indices.add(0);
        indices.add(1);
        indices.add(2);

        indices.add(0);
        indices.add(2);
        indices.add(3);

        //now we create a polygon mesh object
        for (int i = 0; i < 2; i++) {
            PolygonMesh mesh = new PolygonMesh();

            mesh.setVertexData(vertexData);
            mesh.setPrimitives(indices);

                /*
                It turns out, there are several ways of
                reading the list of indices and interpreting
                them as triangles.

                The first, simplest (and the one we have
                assumed above) is to just read the list of
                indices 3 at a time, and use them as triangles.
                In OpenGL, this is the GL_TRIANGLES mode.

                If we wanted to draw lines by reading the indices
                two at a time, we would specify GL_LINES.

                In any case, this "mode" and the actual list of
                indices are related. That is, decide which mode
                you want to use, and accordingly build the list
                of indices.
                 */

            mesh.setPrimitiveType(GL.GL_TRIANGLES);
            mesh.setPrimitiveSize(3);

                /*
                now we create an ObjectInstance for it
                The ObjectInstance encapsulates a lot of the
                 OpenGL-specific code to draw this object
                 */

                /* so in the mesh, we have some attributes for each vertex. In the shader
                we have variables for each vertex attribute. We have to provide a mapping
                between attribute name in the mesh and corresponding shader variable name.
                This will allow us to use PolygonMesh with any shader program, without
                assuming that the attribute names in the mesh and the names of shader variables
                will be the same.

                We create such a shader variable -> vertex attribute mapping now
                 */
            Map<String, String> shaderVertexAttr = new HashMap<String, String>();

            //currently there are two per-vertex attributes: position and color
            shaderVertexAttr.put("vPosition", "position");
            shaderVertexAttr.put("vColor", "color");

            this.mesh.add(mesh);
            this.shaderToVertexAttribute.add(shaderVertexAttr);
        }
    }
}


text:
#include "tommath_private.h"
#ifdef BN_REVERSE_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis
 *
 * LibTomMath is a library that provides multiple-precision
 * integer arithmetic as well as number theoretic functionality.
 *
 * The library was designed directly after the MPI library by
 * Michael Fromberger but has been written from scratch with
 * additional optimizations in place.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 */

/* reverse an array, used for radix code */
void bn_reverse(unsigned char *s, int len)
{
   int     ix, iy;
   unsigned char t;

   ix = 0;
   iy = len - 1;
   while (ix < iy) {
      t     = s[ix];
      s[ix] = s[iy];
      s[iy] = t;
      ++ix;
      --iy;
   }
}
#endif

/* ref:         HEAD -> develop */
/* git commit:  8b9f98baa16b21e1612ac6746273febb74150a6f */
/* commit time: 2018-09-23 21:37:58 +0200 */


text:
package org.cidrz.project.zeprs.report.valueobject;

import java.sql.Date;
import java.util.List;

/**
 * @author Chris Kelley
 *         Date: Oct 30, 2007
 *         Time: 2:06:12 PM
 */
public class FixedCostIncentive {

    private int id;
	private int newANCClient;
    private int totalANCAttendees;
    private int expectedDeliveries;
    private int hivTested;
    private int hivPositive;
    private int hivNegative;
    private int hivIndeterminate;
    private int maternalNVP;
    private int infantNVP;

    private int revisits;
    private int counselledNew;
    private int counselledRevisits;
    private int referredArt;
    private int maternalAztNewStart;
    private int maternalAztRefills;
    private int noRoutineAnteVisit;
    private List noRoutineAnteVisitList;
    private int noInitialVisit;
    private List noInitialVisitList;
    private int noSafeMotherhoodForm;
    private List noSafeMotherhoodFormList;
    private int hivTestedNewAnc;
    private int hivTestedRevisit;
    private List noNewbornEvalVisitList;
    private int siteId;
    private Date dateVisit;
    private int hivTestedInLabourWard;
    private int routineUterotonicGiven;
    private int deliveries;

    public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getSiteId() {
		return siteId;
	}

	public void setSiteId(int siteId) {
		this.siteId = siteId;
	}

	public Date getDateVisit() {
		return dateVisit;
	}

	public void setDateVisit(Date dateVisit) {
		this.dateVisit = dateVisit;
	}

	public int getNewANCClient() {
        return newANCClient;
    }

    public void setNewANCClient(int newANCClient) {
        this.newANCClient = newANCClient;
    }

    public int getTotalANCAttendees() {
        return totalANCAttendees;
    }

    public void setTotalANCAttendees(int totalANCAttendees) {
        this.totalANCAttendees = totalANCAttendees;
    }

    public int getExpectedDeliveries() {
        return expectedDeliveries;
    }

    public void setExpectedDeliveries(int expectedDeliveries) {
        this.expectedDeliveries = expectedDeliveries;
    }

    public int getHivTested() {
        return hivTested;
    }

    public void setHivTested(int hivTested) {
        this.hivTested = hivTested;
    }

    public int getHivPositive() {
        return hivPositive;
    }

    public void setHivPositive(int hivPositive) {
        this.hivPositive = hivPositive;
    }

    public int getHivNegative() {
        return hivNegative;
    }

    public void setHivNegative(int hivNegative) {
        this.hivNegative = hivNegative;
    }

    public int getHivIndeterminate() {
        return hivIndeterminate;
    }

    public void setHivIndeterminate(int hivIndeterminate) {
        this.hivIndeterminate = hivIndeterminate;
    }

    public int getMaternalNVP() {
        return maternalNVP;
    }

    public void setMaternalNVP(int maternalNVP) {
        this.maternalNVP = maternalNVP;
    }

    public int getInfantNVP() {
        return infantNVP;
    }

    public void setInfantNVP(int infantNVP) {
        this.infantNVP = infantNVP;
    }

    public int getRevisits() {
        return revisits;
    }

    public void setRevisits(int revisits) {
        this.revisits = revisits;
    }

    public int getCounselledNew() {
        return counselledNew;
    }

    public void setCounselledNew(int counselledNew) {
        this.counselledNew = counselledNew;
    }

    public int getCounselledRevisits() {
        return counselledRevisits;
    }

    public void setCounselledRevisits(int counselledRevisits) {
        this.counselledRevisits = counselledRevisits;
    }

    public int getReferredArt() {
        return referredArt;
    }

    public void setReferredArt(int referredArt) {
        this.referredArt = referredArt;
    }

    public int getMaternalAztNewStart() {
		return maternalAztNewStart;
	}

	public void setMaternalAztNewStart(int maternalAztNewStart) {
		this.maternalAztNewStart = maternalAztNewStart;
	}

	public int getMaternalAztRefills() {
		return maternalAztRefills;
	}

	public void setMaternalAztRefills(int maternalAztRefills) {
		this.maternalAztRefills = maternalAztRefills;
	}

	public int getNoRoutineAnteVisit() {
        return noRoutineAnteVisit;
    }

    public void setNoRoutineAnteVisit(int noRoutineAnteVisit) {
        this.noRoutineAnteVisit = noRoutineAnteVisit;
    }

    public List getNoRoutineAnteVisitList() {
        return noRoutineAnteVisitList;
    }

    public void setNoRoutineAnteVisitList(List noRoutineAnteVisitList) {
        this.noRoutineAnteVisitList = noRoutineAnteVisitList;
    }

    public int getNoInitialVisit() {
        return noInitialVisit;
    }

    public void setNoInitialVisit(int noInitialVisit) {
        this.noInitialVisit = noInitialVisit;
    }

    public List getNoInitialVisitList() {
        return noInitialVisitList;
    }

    public void setNoInitialVisitList(List noInitialVisitList) {
        this.noInitialVisitList = noInitialVisitList;
    }

    public int getNoSafeMotherhoodForm() {
        return noSafeMotherhoodForm;
    }

    public void setNoSafeMotherhoodForm(int noSafeMotherhoodForm) {
        this.noSafeMotherhoodForm = noSafeMotherhoodForm;
    }

    public List getNoSafeMotherhoodFormList() {
        return noSafeMotherhoodFormList;
    }

    public void setNoSafeMotherhoodFormList(List noSafeMotherhoodFormList) {
        this.noSafeMotherhoodFormList = noSafeMotherhoodFormList;
    }

    public int getHivTestedNewAnc() {
        return hivTestedNewAnc;
    }

    public void setHivTestedNewAnc(int hivTestedNewAnc) {
        this.hivTestedNewAnc = hivTestedNewAnc;
    }

    public int getHivTestedRevisit() {
        return hivTestedRevisit;
    }

    public void setHivTestedRevisit(int hivTestedRevisit) {
        this.hivTestedRevisit = hivTestedRevisit;
    }

    public List getNoNewbornEvalVisitList() {
        return noNewbornEvalVisitList;
    }

    public void setNoNewbornEvalVisitList(List noNewbornEvalVisitList) {
        this.noNewbornEvalVisitList = noNewbornEvalVisitList;
    }

	public int getHivTestedInLabourWard() {
		return hivTestedInLabourWard;
	}

	public void setHivTestedInLabourWard(int hivTestedInLabourWard) {
		this.hivTestedInLabourWard = hivTestedInLabourWard;
	}

	public int getRoutineUterotonicGiven() {
		return routineUterotonicGiven;
	}

	public void setRoutineUterotonicGiven(int routineUterotonicGiven) {
		this.routineUterotonicGiven = routineUterotonicGiven;
	}

	public int getDeliveries() {
		return deliveries;
	}

	public void setDeliveries(int deliveries) {
		this.deliveries = deliveries;
	}

}


text:
package com.sequenceiq.environment.credential.v1.converter;

import static com.sequenceiq.cloudbreak.util.NullUtil.doIfNotNull;

import java.io.IOException;
import java.util.UUID;

import javax.inject.Inject;

import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.sequenceiq.cloudbreak.common.json.Json;
import com.sequenceiq.cloudbreak.common.json.JsonUtil;
import com.sequenceiq.environment.api.v1.credential.model.request.EditCredentialRequest;
import com.sequenceiq.environment.credential.attributes.CredentialAttributes;
import com.sequenceiq.environment.credential.domain.Credential;
import com.sequenceiq.environment.credential.v1.converter.aws.AwsCredentialV1ParametersToAwsCredentialAttributesConverter;
import com.sequenceiq.environment.credential.v1.converter.azure.AzureCredentialRequestParametersToAzureCredentialAttributesConverter;
import com.sequenceiq.environment.credential.v1.converter.gcp.GcpCredentialV1ParametersToGcpCredentialAttributesConverter;
import com.sequenceiq.environment.credential.v1.converter.mock.MockCredentialV1ParametersToMockCredentialAttributesConverter;
import com.sequenceiq.environment.credential.v1.converter.yarn.YarnCredentialV1ParametersToAwsYarnAttributesConverter;

@Component
public class EditCredentialRequestToCredentialConverter {

    @Inject
    private AwsCredentialV1ParametersToAwsCredentialAttributesConverter awsConverter;

    @Inject
    private AzureCredentialRequestParametersToAzureCredentialAttributesConverter azureConverter;

    @Inject
    private GcpCredentialV1ParametersToGcpCredentialAttributesConverter gcpConverter;

    @Inject
    private MockCredentialV1ParametersToMockCredentialAttributesConverter mockConverter;

    @Inject
    private YarnCredentialV1ParametersToAwsYarnAttributesConverter yarnConverter;

    public Credential convert(EditCredentialRequest editCredentialRequest, Credential originalCredential) {
        if (editCredentialRequest == null) {
            return null;
        }
        Credential credential = new Credential();
        credential.setName(Strings.isNullOrEmpty(editCredentialRequest.getName()) ? UUID.randomUUID().toString() : editCredentialRequest.getName());
        credential.setDescription(editCredentialRequest.getDescription());
        credential.setCloudPlatform(editCredentialRequest.getCloudPlatform());
        credential.setVerificationStatusText(editCredentialRequest.getVerificationStatusText());
        credential.setVerifyPermissions(editCredentialRequest.isVerifyPermissions());
        convertAttributes(editCredentialRequest, credential, originalCredential);
        if (editCredentialRequest.getAws() != null) {
            credential.setGovCloud(editCredentialRequest.getAws().getGovCloud());
        }
        return credential;
    }

    private void convertAttributes(EditCredentialRequest source, Credential targetCredential, Credential originalCredential) {
        CredentialAttributes credentialAttributes = new CredentialAttributes();
        doIfNotNull(source.getAws(), params -> credentialAttributes.setAws(awsConverter.convert(params)));
        try {
            if (source.getAzure() != null) {
                CredentialAttributes originalCredentialAttributes = null;
                if (originalCredential != null) {
                    originalCredentialAttributes = JsonUtil.readValue(originalCredential.getAttributes(), CredentialAttributes.class);
                }
                credentialAttributes.setAzure(azureConverter.convertModify(source.getAzure(), originalCredentialAttributes));
            }
        } catch (IOException e) {
            throw new RuntimeException("We were unable to parse the stored credential, therefore editing is not possible", e);
        }
        doIfNotNull(source.getGcp(), params -> credentialAttributes.setGcp(gcpConverter.convert(params)));
        doIfNotNull(source.getMock(), params -> credentialAttributes.setMock(mockConverter.convert(params)));
        doIfNotNull(source.getYarn(), params -> credentialAttributes.setYarn(yarnConverter.convert(params)));
        targetCredential.setAttributes(new Json(credentialAttributes).getValue());
    }
}


text:
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Return;

namespace {

// Used to confirm OneClickSigninHelper does not trigger redirect when there is
// a pending navigation.
class MockWebContentsDelegate : public content::WebContentsDelegate {
 public:
   MOCK_METHOD2(OpenURLFromTab,
                content::WebContents*(content::WebContents* source,
                                      const content::OpenURLParams& params));
};

class SigninManagerMock : public FakeSigninManager {
 public:
  explicit SigninManagerMock(Profile* profile) : FakeSigninManager(profile) {
    Initialize(NULL);
  }
  MOCK_CONST_METHOD1(IsAllowedUsername, bool(const std::string& username));
};

static KeyedService* BuildSigninManagerMock(content::BrowserContext* profile) {
  return new SigninManagerMock(static_cast<Profile*>(profile));
}

class TestProfileIOData : public ProfileIOData {
 public:
  TestProfileIOData(Profile::ProfileType profile_type,
                    PrefService* pref_service, PrefService* local_state,
                    CookieSettings* cookie_settings)
      : ProfileIOData(profile_type) {
    // Initialize the IO members required for these tests, but keep them on
    // this thread since we don't use a background thread here.
    google_services_username()->Init(prefs::kGoogleServicesUsername,
                                     pref_service);
    reverse_autologin_enabled()->Init(prefs::kReverseAutologinEnabled,
                                      pref_service);
    one_click_signin_rejected_email_list()->Init(
        prefs::kReverseAutologinRejectedEmailList, pref_service);

    google_services_username_pattern()->Init(
        prefs::kGoogleServicesUsernamePattern, local_state);

    sync_disabled()->Init(sync_driver::prefs::kSyncManaged, pref_service);

    signin_allowed()->Init(prefs::kSigninAllowed, pref_service);

    set_signin_names_for_testing(new SigninNamesOnIOThread());
    SetCookieSettingsForTesting(cookie_settings);
  }

  virtual ~TestProfileIOData() {
    signin_names()->ReleaseResourcesOnUIThread();
  }

  // ProfileIOData overrides:
  virtual void InitializeInternal(
      ProfileParams* profile_params,
      content::ProtocolHandlerMap* protocol_handlers,
      content::URLRequestInterceptorScopedVector request_interceptors)
      const OVERRIDE {
    NOTREACHED();
  }
  virtual void InitializeExtensionsRequestContext(
      ProfileParams* profile_params) const OVERRIDE {
    NOTREACHED();
  }
  virtual ChromeURLRequestContext* InitializeAppRequestContext(
      ChromeURLRequestContext* main_context,
      const StoragePartitionDescriptor& details,
      scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
          protocol_handler_interceptor,
      content::ProtocolHandlerMap* protocol_handlers,
      content::URLRequestInterceptorScopedVector request_interceptors)
      const OVERRIDE {
    NOTREACHED();
    return NULL;
  }
  virtual ChromeURLRequestContext* InitializeMediaRequestContext(
      ChromeURLRequestContext* original_context,
      const StoragePartitionDescriptor& details) const OVERRIDE {
    NOTREACHED();
    return NULL;
  }
  virtual ChromeURLRequestContext*
      AcquireMediaRequestContext() const OVERRIDE {
    NOTREACHED();
    return NULL;
  }
  virtual ChromeURLRequestContext* AcquireIsolatedAppRequestContext(
      ChromeURLRequestContext* main_context,
      const StoragePartitionDescriptor& partition_descriptor,
      scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
          protocol_handler_interceptor,
      content::ProtocolHandlerMap* protocol_handlers,
      content::URLRequestInterceptorScopedVector request_interceptors)
      const OVERRIDE {
    NOTREACHED();
    return NULL;
  }
  virtual ChromeURLRequestContext*
      AcquireIsolatedMediaRequestContext(
          ChromeURLRequestContext* app_context,
          const StoragePartitionDescriptor& partition_descriptor)
          const OVERRIDE {
    NOTREACHED();
    return NULL;
  }
};

class TestURLRequest : public base::SupportsUserData {
public:
  TestURLRequest() {}
  virtual ~TestURLRequest() {}
};

class OneClickTestProfileSyncService : public TestProfileSyncService {
 public:
  virtual ~OneClickTestProfileSyncService() {}

  // Helper routine to be used in conjunction with
  // BrowserContextKeyedServiceFactory::SetTestingFactory().
  static KeyedService* Build(content::BrowserContext* profile) {
    return new OneClickTestProfileSyncService(static_cast<Profile*>(profile));
  }

  // Need to control this for certain tests.
  virtual bool FirstSetupInProgress() const OVERRIDE {
    return first_setup_in_progress_;
  }

  virtual bool sync_initialized() const OVERRIDE { return sync_initialized_; }

  // Controls return value of FirstSetupInProgress. Because some bits
  // of UI depend on that value, it's useful to control it separately
  // from the internal work and components that are triggered (such as
  // ReconfigureDataTypeManager) to facilitate unit tests.
  void set_first_setup_in_progress(bool in_progress) {
    first_setup_in_progress_ = in_progress;
  }

  void set_sync_initialized(bool initialized) {
    sync_initialized_ = initialized;
  }

 private:
  explicit OneClickTestProfileSyncService(Profile* profile)
      : TestProfileSyncService(
          NULL,
          profile,
          SigninManagerFactory::GetForProfile(profile),
          ProfileOAuth2TokenServiceFactory::GetForProfile(profile),
          browser_sync::MANUAL_START),
        first_setup_in_progress_(false),
        sync_initialized_(false) {}

  bool first_setup_in_progress_;
  bool sync_initialized_;
};

}  // namespace

class OneClickSigninHelperTest : public ChromeRenderViewHostTestHarness {
 public:
  OneClickSigninHelperTest();

  virtual void SetUp() OVERRIDE;
  virtual void TearDown() OVERRIDE;

  // Sets up the sign-in manager for tests.  If |username| is
  // is not empty, the profile of the mock WebContents will be connected to
  // the given account.
  void SetUpSigninManager(const std::string& username);

  // Set the ID of the signin process that the test will assume to be the
  // only process allowed to sign the user in to Chrome.
  void SetTrustedSigninProcessID(int id);

  void AddEmailToOneClickRejectedList(const std::string& email);
  void EnableOneClick(bool enable);
  void AllowSigninCookies(bool enable);
  void SetAllowedUsernamePattern(const std::string& pattern);
  void SubmitGAIAPassword(OneClickSigninHelper* helper);

  SigninManagerMock* signin_manager_;
  FakeProfileOAuth2TokenService* fake_oauth2_token_service_;

 protected:
  GoogleServiceAuthError no_error_;

 private:
  // ChromeRenderViewHostTestHarness overrides:
  virtual content::BrowserContext* CreateBrowserContext() OVERRIDE;

  // The ID of the signin process the test will assume to be trusted.
  // By default, set to the test RenderProcessHost's process ID, but
  // overridden by SetTrustedSigninProcessID.
  int trusted_signin_process_id_;

  DISALLOW_COPY_AND_ASSIGN(OneClickSigninHelperTest);
};

OneClickSigninHelperTest::OneClickSigninHelperTest()
    : signin_manager_(NULL),
      fake_oauth2_token_service_(NULL),
      no_error_(GoogleServiceAuthError::NONE),
      trusted_signin_process_id_(-1) {
}

void OneClickSigninHelperTest::SetUp() {
  signin::ForceWebBasedSigninFlowForTesting(true);
  content::RenderViewHostTestHarness::SetUp();
  SetTrustedSigninProcessID(process()->GetID());
}

void OneClickSigninHelperTest::TearDown() {
  signin::ForceWebBasedSigninFlowForTesting(false);
  content::RenderViewHostTestHarness::TearDown();
}

void OneClickSigninHelperTest::SetTrustedSigninProcessID(int id) {
  trusted_signin_process_id_ = id;
}

void OneClickSigninHelperTest::SetUpSigninManager(const std::string& username) {
  SigninClient* signin_client =
      ChromeSigninClientFactory::GetForProfile(profile());
  if (signin_client)
    signin_client->SetSigninProcess(trusted_signin_process_id_);

  signin_manager_ = static_cast<SigninManagerMock*>(
      SigninManagerFactory::GetForProfile(profile()));
  if (!username.empty()) {
    ASSERT_TRUE(signin_manager_);
    signin_manager_->SetAuthenticatedUsername(username);
  }
}

void OneClickSigninHelperTest::EnableOneClick(bool enable) {
  PrefService* pref_service = profile()->GetPrefs();
  pref_service->SetBoolean(prefs::kReverseAutologinEnabled, enable);
}

void OneClickSigninHelperTest::AddEmailToOneClickRejectedList(
    const std::string& email) {
  PrefService* pref_service = profile()->GetPrefs();
  ListPrefUpdate updater(pref_service,
                         prefs::kReverseAutologinRejectedEmailList);
  updater->AppendIfNotPresent(new base::StringValue(email));
}

void OneClickSigninHelperTest::AllowSigninCookies(bool enable) {
  CookieSettings* cookie_settings =
      CookieSettings::Factory::GetForProfile(profile()).get();
  cookie_settings->SetDefaultCookieSetting(enable ? CONTENT_SETTING_ALLOW
                                                  : CONTENT_SETTING_BLOCK);
}

void OneClickSigninHelperTest::SetAllowedUsernamePattern(
    const std::string& pattern) {
  PrefService* local_state = g_browser_process->local_state();
  local_state->SetString(prefs::kGoogleServicesUsernamePattern, pattern);
}

void OneClickSigninHelperTest::SubmitGAIAPassword(
    OneClickSigninHelper* helper) {
  autofill::PasswordForm password_form;
  password_form.origin = GURL("https://accounts.google.com");
  password_form.signon_realm = "https://accounts.google.com";
  password_form.password_value = base::UTF8ToUTF16("password");
  helper->PasswordSubmitted(password_form);
}

content::BrowserContext* OneClickSigninHelperTest::CreateBrowserContext() {
  TestingProfile::Builder builder;
  builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
                            BuildFakeProfileOAuth2TokenService);
  builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
                            BuildSigninManagerMock);
  scoped_ptr<TestingProfile> profile = builder.Build();

  fake_oauth2_token_service_ =
      static_cast<FakeProfileOAuth2TokenService*>(
          ProfileOAuth2TokenServiceFactory::GetForProfile(profile.get()));

  return profile.release();
}

class OneClickSigninHelperIOTest : public OneClickSigninHelperTest {
 public:
  OneClickSigninHelperIOTest();

  virtual void SetUp() OVERRIDE;

  TestProfileIOData* CreateTestProfileIOData(Profile::ProfileType profile_type);

 protected:
  TestingProfileManager testing_profile_manager_;
  TestURLRequest request_;
  const GURL valid_gaia_url_;

 private:
  DISALLOW_COPY_AND_ASSIGN(OneClickSigninHelperIOTest);
};

OneClickSigninHelperIOTest::OneClickSigninHelperIOTest()
    : testing_profile_manager_(
          TestingBrowserProcess::GetGlobal()),
      valid_gaia_url_("https://accounts.google.com/") {
}

void OneClickSigninHelperIOTest::SetUp() {
  OneClickSigninHelperTest::SetUp();
  ASSERT_TRUE(testing_profile_manager_.SetUp());
}

TestProfileIOData* OneClickSigninHelperIOTest::CreateTestProfileIOData(
    Profile::ProfileType profile_type) {
  PrefService* pref_service = profile()->GetPrefs();
  PrefService* local_state = g_browser_process->local_state();
  CookieSettings* cookie_settings =
      CookieSettings::Factory::GetForProfile(profile()).get();
  TestProfileIOData* io_data = new TestProfileIOData(
      profile_type, pref_service, local_state, cookie_settings);
  io_data->set_reverse_autologin_pending_email("user@gmail.com");
  return io_data;
}

class OneClickSigninHelperIncognitoTest : public OneClickSigninHelperTest {
 protected:
  // content::RenderViewHostTestHarness.
  virtual content::BrowserContext* CreateBrowserContext() OVERRIDE;
};

content::BrowserContext*
OneClickSigninHelperIncognitoTest::CreateBrowserContext() {
  // Builds an incognito profile to run this test.
  TestingProfile::Builder builder;
  builder.SetIncognito();
  return builder.Build().release();
}

TEST_F(OneClickSigninHelperTest, CanOfferNoContents) {
  std::string error_message;
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      NULL, OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "user@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      NULL, OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      NULL,
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      std::string(),
      &error_message));
  EXPECT_EQ("", error_message);
}

TEST_F(OneClickSigninHelperTest, CanOffer) {
  SetUpSigninManager(std::string());

  EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
        WillRepeatedly(Return(true));

  EnableOneClick(true);
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "user@gmail.com", NULL));
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", NULL));
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      std::string(),
      NULL));

  EnableOneClick(false);

  std::string error_message;
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "user@gmail.com", &error_message));
  EXPECT_EQ("", error_message);

  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", &error_message));
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      std::string(),
      &error_message));
  EXPECT_EQ("", error_message);
}

TEST_F(OneClickSigninHelperTest, CanOfferFirstSetup) {
  SetUpSigninManager(std::string());

  EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
        WillRepeatedly(Return(true));

  // Invoke OneClickTestProfileSyncService factory function and grab result.
  OneClickTestProfileSyncService* sync =
      static_cast<OneClickTestProfileSyncService*>(
          ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
              profile(), OneClickTestProfileSyncService::Build));
  sync->set_sync_initialized(false);
  sync->Initialize();
  sync->set_sync_initialized(true);
  sync->set_first_setup_in_progress(true);

  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "foo@gmail.com", NULL));
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "foo@gmail.com", NULL));
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      std::string(),
      NULL));
}

TEST_F(OneClickSigninHelperTest, CanOfferProfileConnected) {
  SetUpSigninManager("foo@gmail.com");

  EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
      WillRepeatedly(Return(true));

  std::string error_message;
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "foo@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "foo", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "user@gmail.com", &error_message));
  EXPECT_EQ(l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL,
                                      base::UTF8ToUTF16("foo@gmail.com")),
            error_message);
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "foo@gmail.com", &error_message));
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "foo", &error_message));
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", &error_message));
  EXPECT_EQ(l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL,
                                      base::UTF8ToUTF16("foo@gmail.com")),
            error_message);
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      std::string(),
      &error_message));
}

TEST_F(OneClickSigninHelperTest, CanOfferUsernameNotAllowed) {
  SetUpSigninManager(std::string());

  EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
      WillRepeatedly(Return(false));

  std::string error_message;
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "foo@gmail.com", &error_message));
  EXPECT_EQ(l10n_util::GetStringUTF8(IDS_SYNC_LOGIN_NAME_PROHIBITED),
            error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "foo@gmail.com", &error_message));
  EXPECT_EQ(l10n_util::GetStringUTF8(IDS_SYNC_LOGIN_NAME_PROHIBITED),
            error_message);
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      std::string(),
      &error_message));
}

TEST_F(OneClickSigninHelperTest, CanOfferWithRejectedEmail) {
  SetUpSigninManager(std::string());

  EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
        WillRepeatedly(Return(true));

  AddEmailToOneClickRejectedList("foo@gmail.com");
  AddEmailToOneClickRejectedList("user@gmail.com");

  std::string error_message;
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "foo@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "user@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "foo@gmail.com", &error_message));
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", &error_message));
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "john@gmail.com", &error_message));
}

TEST_F(OneClickSigninHelperIncognitoTest, CanOfferIncognito) {
  SetUpSigninManager(std::string());

  std::string error_message;
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "user@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      std::string(),
      &error_message));
  EXPECT_EQ("", error_message);
}

TEST_F(OneClickSigninHelperTest, CanOfferNoSigninCookies) {
  SetUpSigninManager(std::string());
  AllowSigninCookies(false);

  EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
        WillRepeatedly(Return(true));

  std::string error_message;
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      "user@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", &error_message));
  EXPECT_EQ("", error_message);
  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(),
      OneClickSigninHelper::CAN_OFFER_FOR_INTERSTITAL_ONLY,
      std::string(),
      &error_message));
  EXPECT_EQ("", error_message);
}

TEST_F(OneClickSigninHelperTest, CanOfferDisabledByPolicy) {
  SetUpSigninManager(std::string());

  EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
        WillRepeatedly(Return(true));

  EnableOneClick(true);
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", NULL));

  // Simulate a policy disabling signin by writing kSigninAllowed directly.
  profile()->GetTestingPrefService()->SetManagedPref(
      prefs::kSigninAllowed, base::Value::CreateBooleanValue(false));

  EXPECT_FALSE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", NULL));

  // Reset the preference value to true.
  profile()->GetTestingPrefService()->SetManagedPref(
      prefs::kSigninAllowed, base::Value::CreateBooleanValue(true));

  // Simulate a policy disabling sync by writing kSyncManaged directly.
  profile()->GetTestingPrefService()->SetManagedPref(
      sync_driver::prefs::kSyncManaged, base::Value::CreateBooleanValue(true));

  // Should still offer even if sync is disabled by policy.
  EXPECT_TRUE(OneClickSigninHelper::CanOffer(
      web_contents(), OneClickSigninHelper::CAN_OFFER_FOR_ALL,
      "user@gmail.com", NULL));
}

// Should not crash if a helper instance is not associated with an incognito
// web contents.
TEST_F(OneClickSigninHelperIncognitoTest, ShowInfoBarUIThreadIncognito) {
  SetUpSigninManager(std::string());
  OneClickSigninHelper* helper =
      OneClickSigninHelper::FromWebContents(web_contents());
  EXPECT_EQ(NULL, helper);

  OneClickSigninHelper::ShowInfoBarUIThread(
      "session_index", "email", OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED,
      signin::SOURCE_UNKNOWN, GURL(), process()->GetID(),
      rvh()->GetRoutingID());
}

// If Chrome signin is triggered from a webstore install, and user chooses to
// config sync, then Chrome should redirect immediately to sync settings page,
// and upon successful setup, redirect back to webstore.
TEST_F(OneClickSigninHelperTest, SigninFromWebstoreWithConfigSyncfirst) {
  SetUpSigninManager(std::string());
  EXPECT_CALL(*signin_manager_, IsAllowedUsername(_))
      .WillRepeatedly(Return(true));

  OneClickTestProfileSyncService* sync_service =
      static_cast<OneClickTestProfileSyncService*>(
          ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
              profile(), OneClickTestProfileSyncService::Build));
  sync_service->set_sync_initialized(true);

  content::WebContents* contents = web_contents();

  OneClickSigninHelper::CreateForWebContentsWithPasswordManager(contents, NULL);
  OneClickSigninHelper* helper =
      OneClickSigninHelper::FromWebContents(contents);
  helper->SetDoNotClearPendingEmailForTesting();
  helper->set_do_not_start_sync_for_testing();

  GURL continueUrl("https://chrome.google.com/webstore?source=5");
  OneClickSigninHelper::ShowInfoBarUIThread(
      "session_index", "user@gmail.com",
      OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT,
      signin::SOURCE_WEBSTORE_INSTALL,
      continueUrl, process()->GetID(), rvh()->GetRoutingID());

  SubmitGAIAPassword(helper);

  NavigateAndCommit(GURL("https://chrome.google.com/webstore?source=3"));
  helper->DidStopLoading(rvh());
  sync_service->NotifyObservers();
  EXPECT_EQ(GURL(continueUrl), contents->GetVisibleURL());
}

// Checks that the state of OneClickSigninHelper is cleaned when there is a
// navigation away from the sign in flow that is not triggered by the
// web contents.
TEST_F(OneClickSigninHelperTest, CleanTransientStateOnNavigate) {
  content::WebContents* contents = web_contents();

  OneClickSigninHelper::CreateForWebContentsWithPasswordManager(contents, NULL);
  OneClickSigninHelper* helper =
      OneClickSigninHelper::FromWebContents(contents);
  helper->SetDoNotClearPendingEmailForTesting();
  helper->auto_accept_ = OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT;

  content::LoadCommittedDetails details;
  content::FrameNavigateParams params;
  params.url = GURL("http://crbug.com");
  params.transition = content::PAGE_TRANSITION_TYPED;
  helper->DidNavigateMainFrame(details, params);

  EXPECT_EQ(OneClickSigninHelper::AUTO_ACCEPT_NONE, helper->auto_accept_);
}

TEST_F(OneClickSigninHelperTest, NoRedirectToNTPWithPendingEntry) {
  content::NavigationController& controller = web_contents()->GetController();
  EXPECT_FALSE(controller.GetPendingEntry());

  const GURL fooWebUIURL("chrome://foo");
  controller.LoadURL(fooWebUIURL, content::Referrer(),
                     content::PAGE_TRANSITION_TYPED, std::string());
  EXPECT_EQ(fooWebUIURL, controller.GetPendingEntry()->GetURL());

  MockWebContentsDelegate delegate;
  EXPECT_CALL(delegate, OpenURLFromTab(_, _)).Times(0);
  web_contents()->SetDelegate(&delegate);
  OneClickSigninHelper::RedirectToNtpOrAppsPage(
      web_contents(), signin::SOURCE_UNKNOWN);

  EXPECT_EQ(fooWebUIURL, controller.GetPendingEntry()->GetURL());
}

// I/O thread tests

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThread) {
  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::CAN_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadIncognito) {
  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::INCOGNITO_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadNoIOData) {
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, NULL));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadBadURL) {
  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(
      OneClickSigninHelper::IGNORE_REQUEST,
      OneClickSigninHelper::CanOfferOnIOThreadImpl(
          GURL("https://foo.com/"), &request_, io_data.get()));
  EXPECT_EQ(OneClickSigninHelper::IGNORE_REQUEST,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                GURL("http://accounts.google.com/"),
                &request_,
                io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadDisabled) {
  EnableOneClick(false);
  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadSignedIn) {
  PrefService* pref_service = profile()->GetPrefs();
  pref_service->SetString(prefs::kGoogleServicesUsername, "user@gmail.com");

  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadEmailNotAllowed) {
  SetAllowedUsernamePattern("*@example.com");
  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_,  &request_, io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadEmailAlreadyUsed) {
  ProfileInfoCache* cache = testing_profile_manager_.profile_info_cache();
  const base::FilePath& user_data_dir = cache->GetUserDataDir();
  cache->AddProfileToCache(user_data_dir.Append(FILE_PATH_LITERAL("user")),
                           base::UTF8ToUTF16("user"),
                           base::UTF8ToUTF16("user@gmail.com"), 0,
                           std::string());

  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadWithRejectedEmail) {
  AddEmailToOneClickRejectedList("user@gmail.com");
  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadNoSigninCookies) {
  AllowSigninCookies(false);
  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));
}

TEST_F(OneClickSigninHelperIOTest, CanOfferOnIOThreadDisabledByPolicy) {
  scoped_ptr<TestProfileIOData> io_data(
      CreateTestProfileIOData(Profile::REGULAR_PROFILE));
  EXPECT_EQ(OneClickSigninHelper::CAN_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));

  // Simulate a policy disabling signin by writing kSigninAllowed directly.
  // We should not offer to sign in the browser.
  profile()->GetTestingPrefService()->SetManagedPref(
      prefs::kSigninAllowed, base::Value::CreateBooleanValue(false));
  EXPECT_EQ(OneClickSigninHelper::DONT_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));

  // Reset the preference.
  profile()->GetTestingPrefService()->SetManagedPref(
      prefs::kSigninAllowed, base::Value::CreateBooleanValue(true));

  // Simulate a policy disabling sync by writing kSyncManaged directly.
  // We should still offer to sign in the browser.
  profile()->GetTestingPrefService()->SetManagedPref(
      sync_driver::prefs::kSyncManaged, base::Value::CreateBooleanValue(true));
  EXPECT_EQ(OneClickSigninHelper::CAN_OFFER,
            OneClickSigninHelper::CanOfferOnIOThreadImpl(
                valid_gaia_url_, &request_, io_data.get()));
}

class MockStarterWrapper
    : public testing::StrictMock<OneClickSigninHelper::SyncStarterWrapper> {
 public:
  MockStarterWrapper(
      const OneClickSigninHelper::StartSyncArgs& args,
      OneClickSigninSyncStarter::StartSyncMode start_mode);

  MOCK_METHOD1(DisplayErrorBubble, void(const std::string& error_message));
  MOCK_METHOD0(StartSigninOAuthHelper, void());
  MOCK_METHOD2(StartOneClickSigninSyncStarter,
               void(const std::string& email,
                    const std::string& refresh_token));
};

MockStarterWrapper::MockStarterWrapper(
    const OneClickSigninHelper::StartSyncArgs& args,
    OneClickSigninSyncStarter::StartSyncMode start_mode)
    : testing::StrictMock<OneClickSigninHelper::SyncStarterWrapper>(
          args, start_mode) {
}

class OneClickSyncStarterWrapperTest : public testing::Test {
 public:
  virtual void SetUp() OVERRIDE {
    TestingProfile::Builder builder;
    profile_ = builder.Build();
  }

  virtual void TearDown() OVERRIDE {
    // Let the SyncStarterWrapper delete itself.
    base::RunLoop().RunUntilIdle();
  }

  void SetCookie(const std::string& value) {
    // Set a valid LSID cookie in the test cookie store.
    scoped_refptr<net::CookieMonster> cookie_monster =
        profile()->GetCookieMonster();
    net::CookieOptions options;
    options.set_include_httponly();
    cookie_monster->SetCookieWithOptionsAsync(
          GURL("https://accounts.google.com"),
          value, options,
          net::CookieMonster::SetCookiesCallback());
  }

  void SimulateRefreshTokenFetched(
      SigninOAuthHelper::Consumer* consumer,
      const std::string& email,
      const std::string& display_email,
      const std::string& refresh_token) {
    consumer->OnSigninOAuthInformationAvailable(
        email, display_email, refresh_token);
  }

  TestingProfile* profile() { return profile_.get(); }

 private:
  content::TestBrowserThreadBundle thread_bundle_;
  scoped_ptr<TestingProfile> profile_;
};

TEST_F(OneClickSyncStarterWrapperTest, SignInWithRefreshToken) {
  OneClickSigninHelper::StartSyncArgs args;
  args.email = "foo@gmail.com";
  args.password = "password";
  args.refresh_token = "refresh_token";
  MockStarterWrapper* wrapper = new MockStarterWrapper(
      args, OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS);

  EXPECT_CALL(*wrapper,
              StartOneClickSigninSyncStarter("foo@gmail.com",
                                             "refresh_token"));
  wrapper->Start();
}

TEST_F(OneClickSyncStarterWrapperTest, SignInWithPasswordNoRefreshToken) {
  OneClickSigninHelper::StartSyncArgs args;
  args.email = "foo@gmail.com";
  args.password = "password";
  MockStarterWrapper* wrapper = new MockStarterWrapper(
      args, OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS);

  EXPECT_CALL(*wrapper, StartSigninOAuthHelper());
  EXPECT_CALL(*wrapper,
              StartOneClickSigninSyncStarter("foo@gmail.com",
                                             "refresh_token"));
  wrapper->Start();
  SimulateRefreshTokenFetched(wrapper, "foo@gmail.com", "foo@gmail.com",
                              "refresh_token");
}

TEST_F(OneClickSyncStarterWrapperTest, SignInWithWrongEmail) {
  OneClickSigninHelper::StartSyncArgs args;
  args.email = "foo@gmail.com";
  args.password = "password";
  MockStarterWrapper* wrapper = new MockStarterWrapper(
      args, OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS);

  EXPECT_CALL(*wrapper, StartSigninOAuthHelper());
  EXPECT_CALL(*wrapper, DisplayErrorBubble(_));
  wrapper->Start();
  SimulateRefreshTokenFetched(wrapper, "bar@gmail.com", "bar@gmail.com",
                              "refresh_token");
}

TEST_F(OneClickSyncStarterWrapperTest, SignInWithEmptyPasswordValidCookie) {
  OneClickSigninHelper::StartSyncArgs args;
  args.email = "foo@gmail.com";
  args.profile = profile();
  MockStarterWrapper* wrapper = new MockStarterWrapper(
      args, OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS);
  SetCookie("LSID=1234; secure; httponly");

  EXPECT_CALL(*wrapper, StartSigninOAuthHelper());
  EXPECT_CALL(*wrapper,
              StartOneClickSigninSyncStarter("foo@gmail.com",
                                             "refresh_token"));
  wrapper->Start();
  base::RunLoop().RunUntilIdle();
  SimulateRefreshTokenFetched(wrapper, "foo@gmail.com", "foo@gmail.com",
                              "refresh_token");
}

TEST_F(OneClickSyncStarterWrapperTest, SignInWithEmptyPasswordNoCookie) {
  OneClickSigninHelper::StartSyncArgs args;
  args.email = "foo@gmail.com";
  args.profile = profile();
  MockStarterWrapper* wrapper = new MockStarterWrapper(
      args, OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS);

  EXPECT_CALL(*wrapper, DisplayErrorBubble(_));
  wrapper->Start();
  base::RunLoop().RunUntilIdle();
}

TEST_F(OneClickSyncStarterWrapperTest, SignInWithEmptyPasswordInvalidCookie) {
  OneClickSigninHelper::StartSyncArgs args;
  args.email = "foo@gmail.com";
  args.profile = profile();
  MockStarterWrapper* wrapper = new MockStarterWrapper(
      args, OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS);
  SetCookie("LSID=1234; domain=google.com; secure; httponly");

  EXPECT_CALL(*wrapper, DisplayErrorBubble(_));
  wrapper->Start();
  base::RunLoop().RunUntilIdle();
}


text:
<link rel="import" href="../quizjs-player-buzzer/quizjs-player-buzzer.html">
<link rel="import" href="../../bower_components/iron-icon/iron-icon.html">
<link rel="import" href="../../bower_components/iron-icons/av-icons.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/paper-toast/paper-toast.html">

<dom-module id="quizjs-player-interface">

	<template>
		<iron-signals id="signals"></iron-signals>
		<paper-spinner id="spinner" active alt="Connecting to the game"></paper-spinner>

		<quizjs-player-buzzer hidden id="buzzer" subscribed="{{subscribed}}"></quizjs-player-buzzer>
		<paper-material id="panelAnswer" class="panel" elevation="1" hidden>

You can answer!

				<paper-button raised>
					<iron-icon icon="av:mic"></iron-icon>
					Answer
				</paper-button>

		</paper-material>
		<paper-material id="panelWait" class="panel" elevation="1" hidden>

Too slow!

			You are in the waiting list. Let's hope their answer is wrong!
		</paper-material>

		<paper-toast id="newGameToast" text="A new game has started!"></paper-toast>
	</template>

</dom-module>


text:
package org.xsaas.xstat.dao.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.xsaas.xstat.dao.IReportTemplateInfoDao;
import org.xsaas.xstat.po.ReportTemplateInfo;

public class ReportTemplateInfoDao extends HibernateDaoSupport implements
		IReportTemplateInfoDao {

	@Override
	public void deleteReportTemplateInfo(ReportTemplateInfo data) {

		this.getHibernateTemplate().delete(data);
	}

	@Override
	public ReportTemplateInfo getReportTemplateInfo(Long templateID) {
		return (ReportTemplateInfo) this.getHibernateTemplate().get(ReportTemplateInfo.class,templateID);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<ReportTemplateInfo> getReportTemplateInfoList() {
		Criteria query = this.getSession().createCriteria(ReportTemplateInfo.class);
		query.add(Restrictions.eq("status", 1));
		query.setMaxResults(Integer.MAX_VALUE);
		return query.list();
	}

	@Override
	public void saveReportTemplateInfo(ReportTemplateInfo data) {

		this.getHibernateTemplate().save(data);
	}

	@Override
	public void updateReportTemplateInfo(ReportTemplateInfo data) {

		this.getHibernateTemplate().update(data);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<ReportTemplateInfo> findReportTemplateInfoByPage(final int firstResult,final int maxResult) {
		List<ReportTemplateInfo> list = this.getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session sess)throws HibernateException, SQLException {
				Criteria query = sess.createCriteria(ReportTemplateInfo.class);
				 query.add(Restrictions.eq("status", 1));
				query.addOrder(Order.desc("reportTemplateID"));
				query.setFirstResult(firstResult);
				query.setMaxResults(maxResult);
			return query.list();
			}

		});
		return list;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<ReportTemplateInfo> findPageByDelStatus(final int firstResult,final int maxResult) {
		List<ReportTemplateInfo> list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			 public Object doInHibernate(Session s) throws HibernateException, SQLException {
				 Criteria query = s.createCriteria(ReportTemplateInfo.class);
				 query.add(Restrictions.eq("status", 2));
				 query.addOrder(Order.desc("reportTemplateID"));
				 query.setFirstResult(firstResult);
				 query.setMaxResults(maxResult);
				 return query.list();
			 }
		});
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public int getTotalByDelStatus() {
		Criteria query = this.getSession().createCriteria(ReportTemplateInfo.class);
		query.add(Restrictions.eq("status", 2));
		query.setProjection(Projections.count("reportTemplateID"));
		query.setMaxResults(1);
		List list = query.list();
		int result = 0;
		if(list.size() > 0) {
			result = (Integer)list.get(0);
		}
		return result;
	}
	@Override
	@SuppressWarnings("unchecked")
	public int getReportTemplateInfoTotal() {
		Criteria query = this.getSession().createCriteria(ReportTemplateInfo.class);
		 query.add(Restrictions.eq("status", 1));
		query.setProjection(Projections.count("reportTemplateID"));
		query.setMaxResults(1);
		List list = query.list();
		int result = 0;
		if(list.size() > 0) {
			result = (Integer)list.get(0);
		}
		return result;
	}

}


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

<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<TITLE>
Uses of Class org.apache.commons.compress.archivers.zip.ZipShort (Commons Compress 1.1 API)
</TITLE>

<META NAME="date" CONTENT="2010-08-13">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.commons.compress.archivers.zip.ZipShort

Packages that use ZipShort

org.apache.commons.compress.archivers.zip
Provides stream classes for reading and writing archives using
      the ZIP format.

Uses of ZipShort in org.apache.commons.compress.archivers.zip

Fields in org.apache.commons.compress.archivers.zip declared as ZipShort

static ZipShort
UnicodeCommentExtraField.UCOM_ID

static ZipShort
UnicodePathExtraField.UPATH_ID

Methods in org.apache.commons.compress.archivers.zip that return ZipShort

 ZipShort
ZipExtraField.getCentralDirectoryLength()

          Length of the extra field in the central directory - without Header-ID or
 length specifier.

 ZipShort
UnrecognizedExtraField.getCentralDirectoryLength()

          Get the central data length.

 ZipShort
UnparseableExtraFieldData.getCentralDirectoryLength()

          Length of the complete extra field in the central directory.

 ZipShort
JarMarker.getCentralDirectoryLength()

          Length of the extra field in the central directory - without
 Header-ID or length specifier.

 ZipShort
AsiExtraField.getCentralDirectoryLength()

          Delegate to local file data.

 ZipShort
AbstractUnicodeExtraField.getCentralDirectoryLength()

          Length of the extra field in the central directory - without Header-ID or
 length specifier.

 ZipShort
ZipExtraField.getHeaderId()

          The Header-ID.

 ZipShort
UnrecognizedExtraField.getHeaderId()

          Get the header id.

 ZipShort
UnparseableExtraFieldData.getHeaderId()

          The Header-ID.

 ZipShort
UnicodePathExtraField.getHeaderId()

          The Header-ID.

 ZipShort
UnicodeCommentExtraField.getHeaderId()

          The Header-ID.

 ZipShort
JarMarker.getHeaderId()

          The Header-ID.

 ZipShort
AsiExtraField.getHeaderId()

          The Header-ID.

 ZipShort
ZipExtraField.getLocalFileDataLength()

          Length of the extra field in the local file data - without Header-ID or
 length specifier.

 ZipShort
UnrecognizedExtraField.getLocalFileDataLength()

          Get the length of the local data.

 ZipShort
UnparseableExtraFieldData.getLocalFileDataLength()

          Length of the complete extra field in the local file data.

 ZipShort
JarMarker.getLocalFileDataLength()

          Length of the extra field in the local file data - without
 Header-ID or length specifier.

 ZipShort
AsiExtraField.getLocalFileDataLength()

          Length of the extra field in the local file data - without
 Header-ID or length specifier.

 ZipShort
AbstractUnicodeExtraField.getLocalFileDataLength()

          Length of the extra field in the local file data - without Header-ID or
 length specifier.

Methods in org.apache.commons.compress.archivers.zip with parameters of type ZipShort

static ZipExtraField
ExtraFieldUtils.createExtraField(ZipShort headerId)

          Create an instance of the approriate ExtraField, falls back to
 UnrecognizedExtraField.

 ZipExtraField
ZipArchiveEntry.getExtraField(ZipShort type)

          Looks up an extra field by its header id.

 void
ZipArchiveEntry.removeExtraField(ZipShort type)

          Remove an extra field.

 void
UnrecognizedExtraField.setHeaderId(ZipShort headerId)

          Set the header id.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2010 The Apache Software Foundation. All Rights Reserved.


text:
package org.apereo.cas.support.saml.web.idp.profile.builders.response.artifact;

import org.apereo.cas.support.saml.SamlUtils;
import org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileBuilderContext;
import org.apereo.cas.support.saml.web.idp.profile.builders.response.SamlProfileSamlResponseBuilderConfigurationContext;
import org.apereo.cas.support.saml.web.idp.profile.builders.response.soap.SamlProfileSamlSoap11ResponseBuilder;
import org.apereo.cas.ticket.artifact.SamlArtifactTicket;

import lombok.val;
import org.opensaml.saml.common.SAMLObject;
import org.opensaml.saml.saml2.core.Assertion;
import org.opensaml.saml.saml2.core.StatusCode;
import org.opensaml.saml.saml2.core.impl.ArtifactResponseBuilder;
import org.opensaml.soap.soap11.Body;
import org.opensaml.soap.soap11.Envelope;
import org.opensaml.soap.soap11.Header;

import java.io.Serial;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

/**
 * This is {@link SamlProfileArtifactResponseBuilder}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
public class SamlProfileArtifactResponseBuilder extends SamlProfileSamlSoap11ResponseBuilder {
    @Serial
    private static final long serialVersionUID = -5582616946993706815L;

    public SamlProfileArtifactResponseBuilder(final SamlProfileSamlResponseBuilderConfigurationContext ctx) {
        super(ctx);
    }

    @Override
    protected Envelope buildResponse(final Assertion assertion, final SamlProfileBuilderContext context) throws Exception {
        val ticket = (SamlArtifactTicket) context.getAuthenticatedAssertion().getAttributes().get("artifact");
        val artifactResponse = new ArtifactResponseBuilder().buildObject();
        artifactResponse.setIssueInstant(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
        artifactResponse.setIssuer(newIssuer(ticket.getIssuer()));
        artifactResponse.setInResponseTo(ticket.getRelyingPartyId());
        artifactResponse.setID(ticket.getId());
        artifactResponse.setStatus(newStatus(StatusCode.SUCCESS, "Success"));

        val samlResponse = SamlUtils.transformSamlObject(openSamlConfigBean, ticket.getObject(), SAMLObject.class);
        artifactResponse.setMessage(samlResponse);

        val header = SamlUtils.newSoapObject(Header.class);

        val body = SamlUtils.newSoapObject(Body.class);
        body.getUnknownXMLObjects().add(artifactResponse);

        val envelope = SamlUtils.newSoapObject(Envelope.class);
        envelope.setHeader(header);
        envelope.setBody(body);
        openSamlConfigBean.logObject(envelope);
        return envelope;
    }
}


text:
<?PHP
include ('common.php');
include ('session.php');
//global $session;
global $divelog;

if (isset ($_POST['action']) && strtoupper($_POST['action']) == "LOGIN") {
	header("Location: login.php");
	die('');
}
else if(isset ($_GET['action']) && strtoupper($_GET['action']) == "LOGOUT" ){
	header("Location: logout.php");
	die('');
}
else {

	$stpl = new Smarty_divelog();
	//do some testing to make sure the db stuff is on
	if ($db->error) {
		//echo "We have an error " . $db->error;
		$stpl->assign('errordb', true);
		$stpl->assign('errortext', $db->error);
	}
	if ($session->getAuthStatus()) {
		//I am logged in
		//get the name

		$uname = $db->queryRow("SELECT * FROM sel_user_from_sessid('". $session->getID() . "') AS (userid int, username text)" );
		$stpl->assign('name', $uname['username']);
		$stpl->assign('login', "Logout");
		$content = $stpl->fetch('index-in.html');
	}
	else {
		//I am new
		$stpl->assign('login', "Login");
		$content = $stpl->fetch('index.html'); //get and parse the main "content" of the page
	}

	$stpl->assign('title', "Divelog Login");
	$stpl->assign('content', $content); //this puts the "content" of the page into the main layout template
	$stpl->display('shell.html');
}
?>


text:
ENV['RAILS_ENV'] ||= 'test'
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)


text:
from sklearn import metrics
from sklearn.svm import SVC
import sklearn

""" Writing my first randomforest code.
Author : AstroDave
Date : 23rd September 2012
Revised: 15 April 2014
please see packages.python.org/milk/randomforests.html for more

"""
import pandas as pd
import numpy as np
import csv as csv
from sklearn.ensemble import RandomForestClassifier

# Data cleanup
# TRAIN DATA
train_df = pd.read_csv('train.csv', header=0)        # Load the train file into a dataframe

# I need to convert all strings to integer classifiers.
# I need to fill in the missing values of the data and make it complete.

# female = 0, Male = 1
train_df['Gender'] = train_df['Sex'].map( {'female': 0, 'male': 1} ).astype(int)

# Embarked from 'C', 'Q', 'S'
# Note this is not ideal: in translating categories to numbers, Port "2" is not 2 times greater than Port "1", etc.

# All missing Embarked -> just make them embark from most common place
if len(train_df.Embarked[ train_df.Embarked.isnull() ]) > 0:
    train_df.Embarked[ train_df.Embarked.isnull() ] = train_df.Embarked.dropna().mode().values

Ports = list(enumerate(np.unique(train_df['Embarked'])))    # determine all values of Embarked,
Ports_dict = { name : i for i, name in Ports }              # set up a dictionary in the form  Ports : index
train_df.Embarked = train_df.Embarked.map( lambda x: Ports_dict[x]).astype(int)     # Convert all Embark strings to int

# All the ages with no data -> make the median of all Ages
median_age = train_df['Age'].dropna().median()
if len(train_df.Age[ train_df.Age.isnull() ]) > 0:
    train_df.loc[ (train_df.Age.isnull()), 'Age'] = median_age

# Remove the Name column, Cabin, Ticket, and Sex (since I copied and filled it to Gender)
train_df = train_df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'PassengerId'], axis=1)

# TEST DATA
test_df = pd.read_csv('test.csv', header=0)        # Load the test file into a dataframe

# I need to do the same with the test data now, so that the columns are the same as the training data
# I need to convert all strings to integer classifiers:
# female = 0, Male = 1
test_df['Gender'] = test_df['Sex'].map( {'female': 0, 'male': 1} ).astype(int)

# Embarked from 'C', 'Q', 'S'
# All missing Embarked -> just make them embark from most common place
if len(test_df.Embarked[ test_df.Embarked.isnull() ]) > 0:
    test_df.Embarked[ test_df.Embarked.isnull() ] = test_df.Embarked.dropna().mode().values
# Again convert all Embarked strings to int
test_df.Embarked = test_df.Embarked.map( lambda x: Ports_dict[x]).astype(int)

# All the ages with no data -> make the median of all Ages
median_age = test_df['Age'].dropna().median()
if len(test_df.Age[ test_df.Age.isnull() ]) > 0:
    test_df.loc[ (test_df.Age.isnull()), 'Age'] = median_age

# All the missing Fares -> assume median of their respective class
if len(test_df.Fare[ test_df.Fare.isnull() ]) > 0:
    median_fare = np.zeros(3)
    for f in range(0,3):                                              # loop 0 to 2
        median_fare[f] = test_df[ test_df.Pclass == f+1 ]['Fare'].dropna().median()
    for f in range(0,3):                                              # loop 0 to 2
        test_df.loc[ (test_df.Fare.isnull()) & (test_df.Pclass == f+1 ), 'Fare'] = median_fare[f]

# Collect the test data's PassengerIds before dropping it
ids = test_df['PassengerId'].values
# Remove the Name column, Cabin, Ticket, and Sex (since I copied and filled it to Gender)
test_df = test_df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'PassengerId'], axis=1)

# The data is now ready to go. So lets fit to the train, then predict to the test!
# Convert back to a numpy array
train_data = train_df.values
test_data = test_df.values
#
train_normalize_data = train_data[0::,1::]
#train_normalize_data = sklearn.preprocessing.normalize( train_data[0::,1::],  norm='l2')

import pylab as P
mset = train_df[train_df.Survived == 1]
mset['Age'].dropna().hist(bins=32, range=(0,80), alpha = .5)
mset1 = train_df[train_df.Survived == 0]
mset1['Age'].dropna().hist(bins=32, range=(0,80), alpha = .5)
P.show()
print(train_df.columns.values)

#exit(0)
print 'Training...'
end_train = len(train_data)*0.8

model = SVC(kernel='linear')
model.fit(train_normalize_data[0:end_train:,3::], train_data[0:end_train:,0])
#model.fit(train_normalize_data[0::,0::], train_data[0::,0])

print 'Cross validation'
expected = train_data[end_train::,0]
predicted = model.predict(train_normalize_data[end_train::,3::])
#
# # summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))

#print train_data
#print 'Test'
#print train_data[0::,1::]

print 'Predicting...'
output = model.predict(test_data[0::,3::]).astype(int)

predictions_file = open("mysvm.csv", "wb")
open_file_object = csv.writer(predictions_file)
open_file_object.writerow(["PassengerId","Survived"])
open_file_object.writerows(zip(ids, output))
predictions_file.close()
print 'Done.'

# # fet a SVM model to the data

# print(model)
# # make predictions
#expected = y
#predicted = model.predict(X)
#
# # summarize the fit of the model
#print(metrics.classification_report(expected, predicted))
#print(metrics.confusion_matrix(expected, predicted))


text:
Robot Architecture

After working on the board's communication, is time to build the architecture.


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.base;

import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.MainDex;
import org.chromium.base.annotations.NativeMethods;

/** Time-related utilities. */
@JNINamespace("base::android")
@MainDex
public class TimeUtils {
    private TimeUtils() {}

    // For conversion from MILLISECONDS use {@android.text.format.DateUtils#*_IN_MILLIS}
    public static final int NANOSECONDS_PER_MILLISECOND = 1000000;
    public static final int SECONDS_PER_MINUTE = 60;
    public static final int SECONDS_PER_HOUR = 3600; // 60 sec * 60 min
    public static final int SECONDS_PER_DAY = 86400;

    @NativeMethods
    public interface Natives {
        // 60 sec * 60 min * 24 h

        /** Returns TimeTicks::Now() in microseconds. */
        long getTimeTicksNowUs();
    }
}


text:
<?php

namespace BAP\SimpleBTSBundle\Form\Type;

use BAP\SimpleBTSBundle\Entity\Issue;
use BAP\SimpleBTSBundle\Form\EventListener\IssueSubscriber;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class IssueType extends AbstractType
{
    /**
     * @var IssueSubscriber
     */
    protected $issueSubscriber;

    /**
     * @param IssueSubscriber $issueSubscriber
     */
    public function __construct(IssueSubscriber $issueSubscriber)
    {
        $this->issueSubscriber = $issueSubscriber;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('code')
            ->add('summary')
            ->add('description')
            ->add('priority', 'genemu_jqueryselect2_translatable_entity', [
                'class'     => 'BAP\SimpleBTSBundle\Entity\IssuePriority',
                'property'  => 'name',
            ])
            ->add('assignee', 'oro_jqueryselect2_hidden', [
                'autocomplete_alias' => 'users'
            ])
            ->add('tags', 'oro_tag_select', ['label' => 'oro.tag.entity_plural_label'])
            ->addEventSubscriber($this->issueSubscriber)
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'BAP\SimpleBTSBundle\Entity\Issue',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'bts_issue';
    }
}