text:
<?php

/**
 * User form base class.
 *
 * @method User getObject() Returns the current form's model object
 *
 * @package    symfony12
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 24171 2009-11-19 16:37:50Z Kris.Wallsmith $
 */
abstract class BaseUserForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'               => new sfWidgetFormInputHidden(),
      'username'         => new sfWidgetFormInputText(),
      'password'         => new sfWidgetFormInputText(),
      'test'             => new sfWidgetFormInputText(),
      'groups_list'      => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'Group')),
      'permissions_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'Permission')),
    ));

    $this->setValidators(array(
      'id'               => new sfValidatorDoctrineChoice(array('model' => $this->getModelName(), 'column' => 'id', 'required' => false)),
      'username'         => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'password'         => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'test'             => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'groups_list'      => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'Group', 'required' => false)),
      'permissions_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'Permission', 'required' => false)),
    ));

    $this->validatorSchema->setPostValidator(
      new sfValidatorDoctrineUnique(array('model' => 'User', 'column' => array('username')))
    );

    $this->widgetSchema->setNameFormat('user[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'User';
  }

  public function updateDefaultsFromObject()
  {
    parent::updateDefaultsFromObject();

    if (isset($this->widgetSchema['groups_list']))
    {
      $this->setDefault('groups_list', $this->object->Groups->getPrimaryKeys());
    }

    if (isset($this->widgetSchema['permissions_list']))
    {
      $this->setDefault('permissions_list', $this->object->Permissions->getPrimaryKeys());
    }

  }

  protected function doSave($con = null)
  {
    $this->saveGroupsList($con);
    $this->savePermissionsList($con);

    parent::doSave($con);
  }

  public function saveGroupsList($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (!isset($this->widgetSchema['groups_list']))
    {
      // somebody has unset this widget
      return;
    }

    if (null === $con)
    {
      $con = $this->getConnection();
    }

    $existing = $this->object->Groups->getPrimaryKeys();
    $values = $this->getValue('groups_list');
    if (!is_array($values))
    {
      $values = array();
    }

    $unlink = array_diff($existing, $values);
    if (count($unlink))
    {
      $this->object->unlink('Groups', array_values($unlink));
    }

    $link = array_diff($values, $existing);
    if (count($link))
    {
      $this->object->link('Groups', array_values($link));
    }
  }

  public function savePermissionsList($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (!isset($this->widgetSchema['permissions_list']))
    {
      // somebody has unset this widget
      return;
    }

    if (null === $con)
    {
      $con = $this->getConnection();
    }

    $existing = $this->object->Permissions->getPrimaryKeys();
    $values = $this->getValue('permissions_list');
    if (!is_array($values))
    {
      $values = array();
    }

    $unlink = array_diff($existing, $values);
    if (count($unlink))
    {
      $this->object->unlink('Permissions', array_values($unlink));
    }

    $link = array_diff($values, $existing);
    if (count($link))
    {
      $this->object->link('Permissions', array_values($link));
    }
  }

}


text:
from ._abstract import AbstractScraper

class WatchWhatUEat(AbstractScraper):
    @classmethod
    def host(cls):
        return "watchwhatueat.com"

    def title(self):
        return self.schema.title()

    def total_time(self):
        return self.schema.total_time()

    def yields(self):
        return self.schema.yields()

    def image(self):
        return self.schema.image()

    def ingredients(self):
        return self.schema.ingredients()

    def instructions(self):
        return self.schema.instructions()

    def ratings(self):
        return self.schema.ratings()

redpajama_set_name: RedPajamaGithub


text:
package xlsx

import (
	"bytes"
	"encoding/xml"
	. "gopkg.in/check.v1"
)

type WorksheetSuite struct{}

var _ = Suite(&WorksheetSuite{})

// Test we can succesfully unmarshal the sheetN.xml files within and
// XLSX file into an xlsxWorksheet struct (and it's related children).
func (w *WorksheetSuite) TestUnmarshallWorksheet(c *C) {
	var sheetxml = bytes.NewBufferString(
		`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
                   xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
          <sheetPr filterMode="false">
            <pageSetUpPr fitToPage="false"/>
          </sheetPr>
          <dimension ref="A1:B2"/>
          <sheetViews>
            <sheetView colorId="64"
                       defaultGridColor="true"
                       rightToLeft="false"
                       showFormulas="false"
                       showGridLines="true"
                       showOutlineSymbols="true"
                       showRowColHeaders="true"
                       showZeros="true"
                       tabSelected="true"
                       topLeftCell="A1"
                       view="normal"
                       windowProtection="false"
                       workbookViewId="0"
                       zoomScale="100"
                       zoomScaleNormal="100"
                       zoomScalePageLayoutView="100">
              <selection activeCell="B2"
                         activeCellId="0"
                         pane="topLeft"
                         sqref="B2"/>
            </sheetView>
          </sheetViews>
          <sheetFormatPr defaultRowHeight="15">
          </sheetFormatPr>
          <cols>
            <col collapsed="false"
                 hidden="false"
                 max="1025"
                 min="1"
                 style="0"
                 width="10.5748987854251"/>
          </cols>
          <sheetData>
            <row collapsed="false"
                 customFormat="false"
                 customHeight="false"
                 hidden="false"
                 ht="14.9"
                 outlineLevel="0"
                 r="1">
              <c r="A1"
                 s="1"
                 t="s">
                <v>0</v>
              </c>
              <c r="B1"
                 s="0"
                 t="s">
                <v>1</v>
              </c>
            </row>
            <row collapsed="false"
                 customFormat="false"
                 customHeight="false"
                 hidden="false"
                 ht="14.9"
                 outlineLevel="0"
                 r="2">
              <c r="A2"
                 s="0"
                 t="s">
                <v>2</v>
              </c>
              <c r="B2"
                 s="2"
                 t="s">
                <v>3</v>
              </c>
            </row>
          </sheetData>
          <printOptions headings="false"
                        gridLines="false"
                        gridLinesSet="true"
                        horizontalCentered="false"
                        verticalCentered="false"/>
          <pageMargins left="0.7"
                       right="0.7"
                       top="0.7875"
                       bottom="0.7875"
                       header="0.511805555555555"
                       footer="0.511805555555555"/>
          <pageSetup blackAndWhite="false"
                     cellComments="none"
                     copies="1"
                     draft="false"
                     firstPageNumber="0"
                     fitToHeight="1"
                     fitToWidth="1"
                     horizontalDpi="300"
                     orientation="portrait"
                     pageOrder="downThenOver"
                     paperSize="9"
                     scale="100"
                     useFirstPageNumber="false"
                     usePrinterDefaults="false"
                     verticalDpi="300"/>
          <headerFooter differentFirst="false"
                        differentOddEven="false">
            <oddHeader>
            </oddHeader>
            <oddFooter>
            </oddFooter>
          </headerFooter>
        </worksheet>`)
	worksheet := new(xlsxWorksheet)
	err := xml.NewDecoder(sheetxml).Decode(worksheet)
	c.Assert(err, IsNil)
	c.Assert(worksheet.Dimension.Ref, Equals, "A1:B2")
	c.Assert(worksheet.SheetData.Row, HasLen, 2)
	row := worksheet.SheetData.Row[0]
	c.Assert(row.R, Equals, 1)
	c.Assert(row.C, HasLen, 2)
	cell := row.C[0]
	c.Assert(cell.R, Equals, "A1")
	c.Assert(cell.T, Equals, "s")
	c.Assert(cell.V, Equals, "0")
}


text:
package jp.gr.java_conf.jyukon.camerapreview;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.Surface;

public class AdjustedCoordinateFragment extends CompassFragment {
    private static final String TAG = AdjustedCoordinateFragment.class.getSimpleName();
    private float[] outR = new float[16];

    @Override
    protected void startSensor() {
        Sensor accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        Sensor magneticField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mSensorManager.registerListener(myEventListener, accelerometer,
                SensorManager.SENSOR_DELAY_UI);
        mSensorManager.registerListener(myEventListener, magneticField,
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void stopSensor() {
        mSensorManager.unregisterListener(myEventListener);
    }

    private final SensorEventListener myEventListener = new SensorEventListener() {
        private float[] accelerometerValues;
        private float[] geomagneticMatrix;

        @Override
        public void onSensorChanged(SensorEvent event) {
            switch (event.sensor.getType()) {
                case Sensor.TYPE_ACCELEROMETER:
                    accelerometerValues = AdaptiveFilter.apply(accelerometerValues,
                            event.values.clone());
                    break;
                case Sensor.TYPE_MAGNETIC_FIELD:
                    geomagneticMatrix = AdaptiveFilter.apply(geomagneticMatrix,
                            event.values.clone());
                    break;
                default:
                    return;
            }

            if (accelerometerValues == null || geomagneticMatrix == null) {
                Log.i(TAG, "no sensor values");
                return;
            }
            SensorManager.getRotationMatrix(mR, null, accelerometerValues, geomagneticMatrix);

            int x = SensorManager.AXIS_X;
            int y = SensorManager.AXIS_Y;

            switch (mRotation) {
                case Surface.ROTATION_0:
                    break;
                case Surface.ROTATION_90:
                    x = SensorManager.AXIS_Y;
                    y = SensorManager.AXIS_MINUS_X;
                    break;
                case Surface.ROTATION_180:
                    x = SensorManager.AXIS_MINUS_X;
                    y = SensorManager.AXIS_MINUS_Y;
                    break;
                case Surface.ROTATION_270:
                    x = SensorManager.AXIS_MINUS_Y;
                    y = SensorManager.AXIS_X;
                    break;
            }
            SensorManager.remapCoordinateSystem(mR, x, y, outR);
            mGLView.setR(outR);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };
}


text:
#include "../base.h"
#include "testing.h"
#include "test_utf8.h"

#include "../utf8.h"

#include "../unicode.h"
#include "../util.h"

int test_utf8_cli(int argc, char **argv)
{
  return run_test_suite(utf8_test);
}

/* ---------------------------------------------------------------- */

/* utf8 tests. */
unit_test_t utf8_test =
  {  test_utf8_run
  , "test_utf8"
  , "utf8 tests."
  };

/* Array of utf8 tests. */
unit_test_t *utf8_tests[] =
  { &utf8_encode_one_equalities_test
  , &utf8_encode_one_edge_cases_test

  , &utf8_encode_equalities_test
  , &utf8_encode_edge_cases_test

  , &utf8_decode_one_equalities_test
  , &utf8_decode_one_edge_cases_test

  , &utf8_decode_equalities_test
  /* TODO
  , &utf8_decode_edge_cases_test
  */

  , NULL
  };

unit_test_result_t test_utf8_run(unit_test_context_t *context)
{
  return run_tests(context, utf8_tests);
}

/* ---------------------------------------------------------------- */

static const struct utf8_codepoint_pair_s
{
  codepoint_t codepoint;

  unsigned char buf[4];
  size_t        utf8_size;
} utf8_codepoint_pairs[] =
  { { 0x0037, {0x37, 0x00, 0x00, 0x00}, 1}  /*  U+0037: DIGIT SEVEN       */
  , { 0x02DA, {0xCB, 0x9A, 0x00, 0x00}, 2}  /*  U+02DA: RING ABOVE        */
  , { 0x2665, {0xE2, 0x99, 0xA5, 0x00}, 3}  /*  U+2665: BLACK HEART SUIT  */
  , {0x1D31D, {0xF0, 0x9D, 0x8C, 0x9D}, 4}  /* U+1D31D: TETRAGRAM FOR JOY */
  , {0x1F48C, {0xF0, 0x9F, 0x92, 0x8C}, 4}  /* U+1F48C: LOVE LETTER       */
  };
static const size_t utf8_codepoint_pairs_size = sizeof(utf8_codepoint_pairs) / sizeof(utf8_codepoint_pairs[0]);

/* ---------------------------------------------------------------- */
/* utf8_encode_one tests                                            */
/* ---------------------------------------------------------------- */

unit_test_t utf8_encode_one_equalities_test =
  {  utf8_encode_one_equalities_test_run
  , "utf8_encode_one_equalities_test"
  , "utf8_encode_one: equality tests."
  };

unit_test_result_t utf8_encode_one_equalities_test_run(unit_test_context_t *context)
{
  char tag[DEFAULT_TAG_SIZE];

  int i;
  unit_test_result_t result;

  const struct utf8_codepoint_pair_s *pair;

  result = assert_success(context);

  for(i = 0; i < utf8_codepoint_pairs_size; ++i)
  {
    unsigned char buf[4] = { 0x00, 0x00, 0x00, 0x00 };
    size_t        utf8_size;

    pair = &utf8_codepoint_pairs[i];

    utf8_size = utf8_encode_one(buf, pair->codepoint);

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "width %d", i);
    result |=
      assert_inteq (context, NULL, tag, (int)          utf8_size, (int)          pair->utf8_size);
    if (is_test_result_aborting(result)) break;

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "buf mem %d", i);
    result |=
      assert_memeq (context, NULL, tag, (void *)       buf,       (void *)       pair->buf,       4);
    /* if (is_test_result_aborting(result)) break; */

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "buf str %d", i);
    result |=
      assert_streqn(context, NULL, tag, (const char *) buf,       (const char *) pair->buf,       4);
    if (is_test_result_aborting(result)) break;
  }

  return result;
}

/* ---------------------------------------------------------------- */

unit_test_t utf8_encode_one_edge_cases_test =
  {  utf8_encode_one_edge_cases_test_run
  , "utf8_encode_one_edge_cases_test"
  , "utf8_encode_one: edge case tests."
  };

unit_test_result_t utf8_encode_one_edge_cases_test_run(unit_test_context_t *context)
{
  size_t                              utf8_size;
  unit_test_result_t                  result;

  const struct utf8_codepoint_pair_s *pair;

  result = assert_success(context);

  pair = &utf8_codepoint_pairs[0];

  /* Test NULL arguments for optional parameters. */
  utf8_size = utf8_encode_one(NULL, pair->codepoint);

  result |=
    assert_inteq (context, NULL, "width", (int) utf8_size, (int) pair->utf8_size);
  if (is_test_result_aborting(result)) return result;

  return result;
}

/* ---------------------------------------------------------------- */
/* utf8_encode tests                                                */
/* ---------------------------------------------------------------- */

unit_test_t utf8_encode_equalities_test =
  {  utf8_encode_equalities_test_run
  , "utf8_encode_equalities_test"
  , "utf8_encode: equality tests."
  };

static const codepoint_t utf8_codepoints[] =
  { 0x2665  /* BLACK HEART SUIT                    */
  , 0x2665  /* BLACK HEART SUIT                    */
  , 0x2665  /* BLACK HEART SUIT                    */
  , 0x03B1  /* GREEK SMALL LETTER ALPHA            */
  , 0x03B3  /* GREEK SMALL LETTER GAMMA            */
  , 0x03B1  /* GREEK SMALL LETTER ALPHA            */
  , 0x03C0  /* GREEK SMALL LETTER PI               */
  , 0x03CE  /* GREEK SMALL LETTER OMEGA WITH TONOS */
  , 0x2665  /* BLACK HEART SUIT                    */
  };
static const size_t utf8_codepoints_size = sizeof(utf8_codepoints) / sizeof(utf8_codepoints[0]);

static const codepoint_t utf8_codepoints_replace_last[] =
  { 0x2665  /* BLACK HEART SUIT                    */
  , 0x2665  /* BLACK HEART SUIT                    */
  , 0x2665  /* BLACK HEART SUIT                    */
  , 0x03B1  /* GREEK SMALL LETTER ALPHA            */
  , 0x03B3  /* GREEK SMALL LETTER GAMMA            */
  , 0x03B1  /* GREEK SMALL LETTER ALPHA            */
  , 0x03C0  /* GREEK SMALL LETTER PI               */
  , 0x03CE  /* GREEK SMALL LETTER OMEGA WITH TONOS */
  , 0xFFFD  /* REPLACEMENT CHARACTER               */
  };
static const size_t utf8_codepoints_replace_last_size = sizeof(utf8_codepoints_replace_last) / sizeof(utf8_codepoints_replace_last[0]);

static const unsigned char utf8_codepoints_encoding[] =
  { 0xE2, 0x99, 0xA5  /* U+2665: BLACK HEART SUIT                    */
  , 0xE2, 0x99, 0xA5  /* U+2665: BLACK HEART SUIT                    */
  , 0xE2, 0x99, 0xA5  /* U+2665: BLACK HEART SUIT                    */
  , 0xCE, 0xB1        /* U+03B1: GREEK SMALL LETTER ALPHA            */
  , 0xCE, 0xB3        /* U+03B1: GREEK SMALL LETTER GAMMA            */
  , 0xCE, 0xB1        /* U+03B1: GREEK SMALL LETTER ALPHA            */
  , 0xCF, 0x80        /* U+03B1: GREEK SMALL LETTER PI               */
  , 0xCF, 0x8E        /* U+03B1: GREEK SMALL LETTER OMEGA WITH TONOS */
  , 0xE2, 0x99, 0xA5  /* U+2665: BLACK HEART SUIT                    */
  };
static const size_t utf8_codepoints_encoding_size = sizeof(utf8_codepoints_encoding) / sizeof(utf8_codepoints_encoding[0]);

/* Number of bytes to encode last symbol in utf8_codepoints_encoding.
 * Used in the unit test "".
 */
static const size_t utf8_encoding_last_width = 3;

unit_test_result_t utf8_encode_equalities_test_run(unit_test_context_t *context)
{
  unit_test_result_t result;

  unsigned char      buf[sizeof(utf8_codepoints_encoding) / sizeof(utf8_codepoints_encoding[0])];
  size_t             buf_written;
  size_t             num_encoded;

  result = assert_success(context);

  buf_written = utf8_encode(buf, utf8_codepoints_encoding_size, utf8_codepoints, utf8_codepoints_size, &num_encoded);

  result |=
    assert_inteq (context, NULL, "num_written", (int)          buf_written, (int)          utf8_codepoints_encoding_size);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "num_encoded", (int)          num_encoded, (int)          utf8_codepoints_size);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_memeq (context, NULL, "buf mem",     (void *)       buf,         (void *)       utf8_codepoints_encoding,      utf8_codepoints_encoding_size);
  /* if (is_test_result_aborting(result)) return result; */

  result |=
    assert_streqn(context, NULL, "buf str",     (const char *) buf,         (const char *) utf8_codepoints_encoding,      utf8_codepoints_encoding_size);
  if (is_test_result_aborting(result)) return result;

  return result;
}

/* ---------------------------------------------------------------- */

unit_test_t utf8_encode_edge_cases_test =
  {  utf8_encode_edge_cases_test_run
  , "utf8_encode_edge_cases_test"
  , "utf8_encode: edge case tests."
  };

unit_test_result_t utf8_encode_edge_cases_test_run(unit_test_context_t *context)
{
  unit_test_result_t result;

  unsigned char      buf[sizeof(utf8_codepoints_encoding) / sizeof(utf8_codepoints_encoding[0])];
  size_t             buf_written;
  size_t             num_encoded;

  result = assert_success(context);

  /* Test NULL arguments for optional parameters. */
  buf_written = utf8_encode(buf, utf8_codepoints_encoding_size, utf8_codepoints, utf8_codepoints_size, NULL);

  result |=
    assert_inteq (context, NULL, "num_written",       (int)          buf_written, (int)          utf8_codepoints_encoding_size);
  if (is_test_result_aborting(result)) return result;

  /* Test smaller buf limit. */
  buf_written = utf8_encode(buf, utf8_codepoints_encoding_size - 1, utf8_codepoints, utf8_codepoints_size, &num_encoded);

  result |=
    assert_inteq (context, NULL, "small num_written", (int)          buf_written, (int)          utf8_codepoints_encoding_size - utf8_encoding_last_width);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "small num_encoded", (int)          num_encoded, (int)          utf8_codepoints_size - 1);
  if (is_test_result_aborting(result)) return result;

  return result;
}

/* ---------------------------------------------------------------- */
/* utf8_decode_one tests                                            */
/* ---------------------------------------------------------------- */

unit_test_t utf8_decode_one_equalities_test =
  {  utf8_decode_one_equalities_test_run
  , "utf8_decode_one_equalities_test"
  , "utf8_decode_one: equality tests."
  };

unit_test_result_t utf8_decode_one_equalities_test_run(unit_test_context_t *context)
{
  char tag[DEFAULT_TAG_SIZE];

  int i;
  unit_test_result_t result;

  const struct utf8_codepoint_pair_s *pair;

  result = assert_success(context);

  for(i = 0; i < utf8_codepoint_pairs_size; ++i)
  {
    codepoint_t                codepoint;
    size_t                     width;
    utf8_decode_error_status_t error_status;

    pair = &utf8_codepoint_pairs[i];

    codepoint = utf8_decode_one(pair->buf, pair->utf8_size, utf8_default_decode_error_behaviour, &width, &error_status);

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "codepoint %d", i);
    result |=
      assert_inteq (context, NULL, tag, (int) codepoint,      (int) pair->codepoint);
    if (is_test_result_aborting(result)) break;

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "width %d", i);
    result |=
      assert_inteq (context, NULL, tag, (int) width,          (int) pair->utf8_size);
    if (is_test_result_aborting(result)) break;

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "error_status %d", i);
    result |=
      assert_inteq (context, NULL, tag, (int) error_status,   (int) utf8_decode_no_error);
    if (is_test_result_aborting(result)) break;
  }

  return result;
}

/* ---------------------------------------------------------------- */

static const struct utf8_decode_one_pair_s
{
  /* Input. */
  unsigned char                 buf[4];
  size_t                        utf8_size;

  utf8_decode_error_behaviour_t error_behaviour;

  /* Output. */
  codepoint_t                   codepoint;

  size_t                        width;
  size_t                        error_status;
} utf8_decode_one_pairs[] =
  {
    /* Valid input. */
    { {0x37, 0x00, 0x00, 0x00}, 1,  utf8_default_decode_error_behaviour  /*  U+0037: DIGIT SEVEN       */
    ,  0x0037, 1, utf8_decode_no_error
    }
  , { {0xCB, 0x9A, 0x00, 0x00}, 2,  utf8_default_decode_error_behaviour  /*  U+02DA: RING ABOVE        */
    ,  0x02DA, 2, utf8_decode_no_error
    }
  , { {0xE2, 0x99, 0xA5, 0x00}, 3,  utf8_default_decode_error_behaviour  /*  U+2665: BLACK HEART SUIT  */
    ,  0x2665, 3, utf8_decode_no_error
    }
  , { {0xF0, 0x9D, 0x8C, 0x9D}, 4,  utf8_default_decode_error_behaviour  /* U+1D31D: TETRAGRAM FOR JOY */
    , 0x1D31D, 4, utf8_decode_no_error
    }
  , { {0xF0, 0x9F, 0x92, 0x8C}, 4,  utf8_default_decode_error_behaviour  /* U+1F48C: LOVE LETTER       */
    , 0x1F48C, 4, utf8_decode_no_error
    }

    /* Testing different behaviours on unexpected continuation bytes. */
  , { {0x8C, 0x9F, 0x92, 0x8C}, 4,  utf8_replacement_character_uFFFD_behaviour
    ,  0xFFFD, 1, utf8_decode_unexpected_continuation_byte
    }
  , { {0x8C, 0x9F, 0x92, 0x8C}, 4,  utf8_invalid_character_uDCxx_behaviour
    ,  0xDC8C, 1, utf8_decode_unexpected_continuation_byte
    }
  , { {0x8C, 0x9F, 0x92, 0x8C}, 4,  utf8_codepoint_u00xx_behaviour
    ,  0x008C, 1, utf8_decode_unexpected_continuation_byte
    }

    /* Testing other errors. */
  , { {0xF0, 0x9F, 0x92, 0x00}, 3,  utf8_replacement_character_uFFFD_behaviour
    ,  0xFFFD, 1, utf8_decode_insufficient_continuation_bytes_eof
    }
  , { {0xF0, 0x9F, 0x92, 0x37}, 4,  utf8_replacement_character_uFFFD_behaviour
    ,  0xFFFD, 1, utf8_decode_insufficient_continuation_bytes_sufficient_input
    }
  , { {0xF8, 0x9F, 0x92, 0x8C}, 4,  utf8_replacement_character_uFFFD_behaviour
    ,  0xFFFD, 1, utf8_decode_out_of_bounds
    }

    /* Testing overlong encoding errors. */

    /* '7' in 2 bytes */
    /* xxxx xxxx = 0011 0111 = 0x37 */
    /* 110x xxxx  10xx xxxx */
    /* 1100 0000  1011 0111 */
    /* 0xC0      0xB7      */
  , { {0xC0, 0xB7, 0x00, 0x00}, 2,  utf8_replacement_character_uFFFD_behaviour
    ,  0xFFFD, 1, utf8_decode_overlong_encoding
    }
  , { {0xC0, 0xB7, 0x00, 0x00}, 2,  utf8_po_replacement_character_uFFFD_behaviour
    ,  0x0037, 2, utf8_decode_overlong_encoding
    }

    /* 'G' in 2 bytes */
    /* xxxx xxxx = 0100 0111 = 0x47 */
    /* 110x xxxx  10xx xxxx */
    /* 1100 0001  1000 0111 */
    /* 0xC1       0x87      */
  , { {0xC1, 0x87, 0x00, 0x00}, 2,  utf8_replacement_character_uFFFD_behaviour
    ,  0xFFFD, 1, utf8_decode_overlong_encoding
    }
  , { {0xC1, 0x87, 0x00, 0x00}, 2,  utf8_po_replacement_character_uFFFD_behaviour
    ,  0x0047, 2, utf8_decode_overlong_encoding
    }
  };
static const size_t utf8_decode_one_pairs_size = sizeof(utf8_decode_one_pairs) / sizeof(utf8_decode_one_pairs[0]);

/* ---------------------------------------------------------------- */

unit_test_t utf8_decode_one_edge_cases_test =
  {  utf8_decode_one_edge_cases_test_run
  , "utf8_decode_one_edge_cases_test"
  , "utf8_decode_one: edge case tests."
  };

unit_test_result_t utf8_decode_one_edge_cases_test_run(unit_test_context_t *context)
{
  char tag[DEFAULT_TAG_SIZE];

  int i;
  unit_test_result_t result;

  const struct utf8_decode_one_pair_s *pair;

  result = assert_success(context);

  for(i = 0; i < utf8_decode_one_pairs_size; ++i)
  {
    codepoint_t                codepoint;
    size_t                     width;
    utf8_decode_error_status_t error_status;

    pair = &utf8_decode_one_pairs[i];

    codepoint = utf8_decode_one(pair->buf, pair->utf8_size, pair->error_behaviour, &width, &error_status);

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "error_status %d", i);
    result |=
      assert_inteq (context, NULL, tag, (int) error_status,   (int) pair->error_status);
    if (is_test_result_aborting(result)) break;

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "codepoint %d", i);
    result |=
      assert_inteq (context, NULL, tag, (int) codepoint,      (int) pair->codepoint);
    if (is_test_result_aborting(result)) break;

    snprintf(tag, sizeof(tag) / sizeof(tag[0]), "width %d", i);
    result |=
      assert_inteq (context, NULL, tag, (int) width,          (int) pair->width);
    if (is_test_result_aborting(result)) break;
  }

  return result;
}

/* ---------------------------------------------------------------- */
/* utf8_decode tests                                                */
/* ---------------------------------------------------------------- */

unit_test_t utf8_decode_equalities_test =
  {  utf8_decode_equalities_test_run
  , "utf8_decode_equalities_test"
  , "utf8_decode: equality tests."
  };

unit_test_result_t utf8_decode_equalities_test_run(unit_test_context_t *context)
{
  unit_test_result_t result;

  size_t                     num_codepoints;
  codepoint_t                codepoints[sizeof(utf8_codepoints) / sizeof(utf8_codepoints[0])];
  size_t                     bytes_read;
  size_t                     num_trailing_bytes;
  utf8_decode_error_status_t error_status;

  result = assert_success(context);

  num_codepoints =
    utf8_decode
      ( codepoints, utf8_codepoints_size, utf8_codepoints_encoding
      , utf8_codepoints_encoding_size, 0, utf8_default_decode_error_behaviour
      , &bytes_read, &num_trailing_bytes, &error_status
      );

  result |=
    assert_inteq (context, NULL, "num_codepoints",     (int)    num_codepoints,     (int)    utf8_codepoints_size);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "bytes_read",         (int)    bytes_read,         (int)    utf8_codepoints_encoding_size);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "num_trailing_bytes", (int)    num_trailing_bytes, (int)    0);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "error_status",       (int)    error_status,       (int)    utf8_decode_no_error);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_memeq (context, NULL, "buf mem",            (void *) codepoints,         (void *) utf8_codepoints, sizeof(utf8_codepoints));
  if (is_test_result_aborting(result)) return result;

  return result;
}

/* ---------------------------------------------------------------- */

unit_test_t utf8_decode_edge_cases_test =
  {  utf8_decode_edge_cases_test_run
  , "utf8_decode_edge_cases_test"
  , "utf8_decode: edge case tests."
  };

static unit_test_result_t utf8_decode_edge_cases_trailing_test_run(unit_test_context_t *context)
{
  unit_test_result_t result;

  int                        allow_trailing_bytes;

  size_t                     num_codepoints;
  codepoint_t                codepoints[sizeof(utf8_codepoints) / sizeof(utf8_codepoints[0])];
  size_t                     bytes_read;
  size_t                     num_trailing_bytes;
  utf8_decode_error_status_t error_status;

  result = assert_success(context);

  /* Allow trailing bytes. */
  allow_trailing_bytes = 1;

  num_codepoints =
    utf8_decode
      ( codepoints, utf8_codepoints_size, utf8_codepoints_encoding
      , utf8_codepoints_encoding_size - 1, allow_trailing_bytes, utf8_default_decode_error_behaviour
      , &bytes_read, &num_trailing_bytes, &error_status
      );

  result |=
    assert_inteq (context, NULL, "num_codepoints",     (int)    num_codepoints,     (int)    utf8_codepoints_size);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "bytes_read",         (int)    bytes_read,         (int)    utf8_codepoints_encoding_size - utf8_encoding_last_width);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "num_trailing_bytes", (int)    num_trailing_bytes, (int)    utf8_encoding_last_width);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "error_status",       (int)    error_status,       (int)    utf8_decode_no_error);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_memeq (context, NULL, "buf mem",            (void *) codepoints,         (void *) utf8_codepoints, sizeof(utf8_codepoints));
  if (is_test_result_aborting(result)) return result;

  /* Disallow trailing bytes. */
  allow_trailing_bytes = 0;

  num_codepoints =
    utf8_decode
      ( codepoints, utf8_codepoints_size, utf8_codepoints_encoding
      , utf8_codepoints_encoding_size - 1, allow_trailing_bytes, utf8_default_decode_error_behaviour
      , &bytes_read, &num_trailing_bytes, &error_status
      );

  result |=
    assert_inteq (context, NULL, "num_codepoints",     (int)    num_codepoints,     (int)    utf8_codepoints_size - 1);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "bytes_read",         (int)    bytes_read,         (int)    utf8_codepoints_encoding_size - utf8_encoding_last_width + 1);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "num_trailing_bytes", (int)    num_trailing_bytes, (int)    0);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_inteq (context, NULL, "error_status",       (int)    error_status,       (int)    utf8_decode_insufficient_continuation_bytes_eof);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_memeq (context, NULL, "buf mem",            (void *) codepoints,         (void *) utf8_codepoints_replace_last, sizeof(utf8_codepoints_replace_last));
  if (is_test_result_aborting(result)) return result;

  return result;
}
static unit_test_result_t utf8_decode_edge_cases_null_outs_test_run(unit_test_context_t *context)
{
  unit_test_result_t result;

  size_t                     num_codepoints;
  codepoint_t                codepoints[sizeof(utf8_codepoints) / sizeof(utf8_codepoints[0])];

  result = assert_success(context);

  num_codepoints =
    utf8_decode
      ( codepoints, utf8_codepoints_size, utf8_codepoints_encoding
      , utf8_codepoints_encoding_size, 0, utf8_default_decode_error_behaviour
      , NULL, NULL, NULL
      );

  result |=
    assert_inteq (context, NULL, "num_codepoints",     (int)    num_codepoints,     (int)    utf8_codepoints_size);
  if (is_test_result_aborting(result)) return result;

  result |=
    assert_memeq (context, NULL, "buf mem",            (void *) codepoints,         (void *) utf8_codepoints, sizeof(utf8_codepoints));
  if (is_test_result_aborting(result)) return result;

  return result;
}
static unit_test_t
  utf8_decode_edge_cases_trailing_test =
  {  utf8_decode_edge_cases_trailing_test_run
  , "utf8_decode_edge_cases_trailing_test"
  , "utf8_decode: trailing bytes tests."
  },
  utf8_decode_edge_cases_null_outs_test =
  {  utf8_decode_edge_cases_null_outs_test_run
  , "utf8_decode_edge_cases_null_outs_test"
  , "utf8_decode: optional parameters tests."
  };

/* Array of utf8_decode edge tests. */
static unit_test_t *utf8_edge_cases_tests[] =
  { &utf8_decode_edge_cases_trailing_test
  , &utf8_decode_edge_cases_null_outs_test

  , NULL
  };

unit_test_result_t utf8_decode_edge_cases_test_run(unit_test_context_t *context)
{
  return run_tests(context, utf8_edge_cases_tests);
}


text: google-site-verification: google4eede13f416d1a61.html


text:
namespace stratum {
namespace hal {
namespace phal {
namespace onlp {

using namespace google::protobuf::util;  // NOLINT

OnlpSfpConfigurator::OnlpSfpConfigurator(
    std::shared_ptr<OnlpSfpDataSource> datasource, AttributeGroup* sfp_group,
    OnlpOid oid)
    : OnlpEventCallback(oid),
      datasource_(ABSL_DIE_IF_NULL(datasource)),
      sfp_group_(ABSL_DIE_IF_NULL(sfp_group)) {
  // lock us so we can modify
  auto mutable_sfp = sfp_group_->AcquireMutable();

  // Ok, now go add the sfp attributes
  mutable_sfp->AddAttribute("id", datasource_->GetSfpId());
  mutable_sfp->AddAttribute("description", datasource_->GetSfpDesc());
  // Hardware state is not updated by the datasource, but by us in response to
  // the Onlp callback.
  mutable_sfp->AddAttribute(
      "hardware_state",
      FixedEnumDataSource::Make(HwState_descriptor(), HW_STATE_NOT_PRESENT)
          ->GetAttribute());
}

::util::StatusOr<std::unique_ptr<OnlpSfpConfigurator>>
OnlpSfpConfigurator::Make(std::shared_ptr<OnlpSfpDataSource> datasource,
                          AttributeGroup* sfp_group, OnlpOid oid) {
  return absl::WrapUnique(new OnlpSfpConfigurator(datasource, sfp_group, oid));
}

::util::Status OnlpSfpConfigurator::HandleOidStatusChange(
    const OidInfo& oid_info) {
  RET_CHECK(GetOid() == oid_info.GetHeader()->id)
      << "Status change event oid " << oid_info.GetHeader()->id
      << " does not match configurator oid: " << GetOid();

  return HandleEvent(oid_info.GetHardwareState());
}

::util::Status OnlpSfpConfigurator::HandleEvent(HwState state) {
  // Check SFP state
  switch (state) {
    // Add SFP attributes
    case HW_STATE_PRESENT:
      RETURN_IF_ERROR(AddSfp());
      break;

    // Remove SFP attributes
    case HW_STATE_NOT_PRESENT:
      RETURN_IF_ERROR(RemoveSfp());
      break;

    default:
      return MAKE_ERROR() << "Unknown SFP event state " << state << ".";
  }

  return ::util::OkStatus();
}

// Add an Sfp transceiver
::util::Status OnlpSfpConfigurator::AddSfp() {
  // Make sure we don't already have a SFP added to the DB
  absl::WriterMutexLock l(&config_lock_);

  if (initialized_) {
    VLOG(1) << "SFP " << datasource_->GetSfpId() << " already exists.";
    return ::util::OkStatus();
  }

  // lock us so we can modify
  auto mutable_sfp = sfp_group_->AcquireMutable();

  mutable_sfp->AddAttribute(
      "hardware_state",
      FixedEnumDataSource::Make(HwState_descriptor(), HW_STATE_PRESENT)
          ->GetAttribute());

  // TODO(max): Error checking
  mutable_sfp->AddAttribute("media_type", datasource_->GetSfpMediaType());
  mutable_sfp->AddAttribute("connector_type", datasource_->GetSfpType());
  mutable_sfp->AddAttribute("module_type", datasource_->GetSfpModuleType());
  mutable_sfp->AddAttribute("cable_length", datasource_->GetSfpCableLength());
  mutable_sfp->AddAttribute("cable_length_desc",
                            datasource_->GetSfpCableLengthDesc());
  mutable_sfp->AddAttribute("temperature", datasource_->GetSfpTemperature());
  mutable_sfp->AddAttribute("vcc", datasource_->GetSfpVoltage());
  mutable_sfp->AddAttribute("channel_count", datasource_->GetSfpChannelCount());

  {
    // Get HardwareInfo DB group
    ASSIGN_OR_RETURN(auto info, mutable_sfp->AddChildGroup("info"));
    auto mutable_info_group = info->AcquireMutable();
    // Ok, now go add the info attributes
    mutable_info_group->AddAttribute("mfg_name", datasource_->GetSfpVendor());
    mutable_info_group->AddAttribute("part_no", datasource_->GetSfpModel());
    mutable_info_group->AddAttribute("serial_no",
                                     datasource_->GetSfpSerialNumber());
  }

  {
    // Get SfpModuleCaps DB group
    ASSIGN_OR_RETURN(auto caps,
                     mutable_sfp->AddChildGroup("module_capabilities"));
    auto mutable_caps = caps->AcquireMutable();
    // Ok, now go remove the attributes
    mutable_caps->AddAttribute("f_100", datasource_->GetModCapF100());
    mutable_caps->AddAttribute("f_1g", datasource_->GetModCapF1G());
    mutable_caps->AddAttribute("f_10g", datasource_->GetModCapF10G());
    mutable_caps->AddAttribute("f_40g", datasource_->GetModCapF40G());
    mutable_caps->AddAttribute("f_100g", datasource_->GetModCapF100G());
  }

  // Add SFPChannel Attributes
  // note: use a 0-based index for both database and ONLP
  ASSIGN_OR_RETURN(auto sfp_channel_count,
                   datasource_->GetSfpChannelCount()->ReadValue<int>());
  for (int id = 0; id < sfp_channel_count; id++) {
    // Get a new channel
    ASSIGN_OR_RETURN(auto channel,
                     mutable_sfp->AddRepeatedChildGroup("channels"));
    auto mutable_channel = channel->AcquireMutable();
    // Now add the attributes
    mutable_channel->AddAttribute("rx_power", datasource_->GetSfpRxPower(id));
    mutable_channel->AddAttribute("tx_power", datasource_->GetSfpTxPower(id));
    mutable_channel->AddAttribute("tx_bias", datasource_->GetSfpTxBias(id));
  }

  // we're now initialized
  initialized_ = true;

  return ::util::OkStatus();
}

::util::Status OnlpSfpConfigurator::RemoveSfp() {
  // Make sure we have a been initialized
  absl::WriterMutexLock l(&config_lock_);
  if (!initialized_) {
    VLOG(1)
        << "Can't remove SFP "
        << sfp_group_->AcquireReadable()->ReadAttribute<int>("id").ValueOrDie()
        << " from attribute DB, because it does not exists.";
    return ::util::OkStatus();
  }

  // lock us so we can modify
  auto mutable_sfp = sfp_group_->AcquireMutable();

  mutable_sfp->AddAttribute(
      "hardware_state",
      FixedEnumDataSource::Make(HwState_descriptor(), HW_STATE_NOT_PRESENT)
          ->GetAttribute());

  // TODO(max): Error checking
  mutable_sfp->RemoveAttribute("media_type");
  mutable_sfp->RemoveAttribute("connector_type");
  mutable_sfp->RemoveAttribute("module_type");
  mutable_sfp->RemoveAttribute("cable_length");
  mutable_sfp->RemoveAttribute("cable_length_desc");
  mutable_sfp->RemoveAttribute("temperature");
  mutable_sfp->RemoveAttribute("vcc");

  {
    // Get HardwareInfo DB group
    ASSIGN_OR_RETURN(auto info, mutable_sfp->GetChildGroup("info"));
    auto mutable_info = info->AcquireMutable();
    mutable_info->RemoveAttribute("mfg_name");
    mutable_info->RemoveAttribute("part_no");
    mutable_info->RemoveAttribute("serial_no");
  }
  RETURN_IF_ERROR(mutable_sfp->RemoveChildGroup("info"));

  {
    // Get SfpModuleCaps DB group
    ASSIGN_OR_RETURN(auto caps,
                     mutable_sfp->GetChildGroup("module_capabilities"));
    auto mutable_caps = caps->AcquireMutable();
    mutable_caps->RemoveAttribute("f_100");
    mutable_caps->RemoveAttribute("f_1g");
    mutable_caps->RemoveAttribute("f_10g");
    mutable_caps->RemoveAttribute("f_40g");
    mutable_caps->RemoveAttribute("f_100g");
  }
  RETURN_IF_ERROR(mutable_sfp->RemoveChildGroup("module_capabilities"));

  // Remove SFPChannel Attributes
  // note: use a 0-based index for both database and ONLP
  ASSIGN_OR_RETURN(auto sfp_channel_count,
                   datasource_->GetSfpChannelCount()->ReadValue<int>())
  for (int id = 0; id < sfp_channel_count; id++) {
    // Get channel group
    ASSIGN_OR_RETURN(auto channel,
                     mutable_sfp->GetRepeatedChildGroup("channels", id));

    auto mutable_channel = channel->AcquireMutable();
    mutable_channel->RemoveAttribute("rx_power");
    mutable_channel->RemoveAttribute("tx_power");
    mutable_channel->RemoveAttribute("tx_bias");
  }
  // Remove all the channel groups
  RETURN_IF_ERROR(mutable_sfp->RemoveRepeatedChildGroup("channels"));

  // we're now not initialized
  initialized_ = false;

  return ::util::OkStatus();
}

}  // namespace onlp
}  // namespace phal
}  // namespace hal

}  // namespace stratum


text:
import datetime

from PyQt5.QtWidgets import QDialog

from ..core.graph import Graph
from ..gen_resources.member_uic import Ui_DialogMember
from ..tools.exceptions import MembershipNotFoundError

class MemberDialog(QDialog, Ui_DialogMember):
    """
    classdocs
    """

    def __init__(self, account, community, person):
        """
        Constructor
        """
        super().__init__()
        self.setupUi(self)
        self.community = community
        self.account = account
        self.person = person
        self.label_uid.setText(person.uid)

        try:
            join_date = self.person.get_join_date(self.community)
        except MembershipNotFoundError:
            join_date = None

        if join_date is None:
            join_date = self.tr('not a member')
        else:
            join_date = datetime.datetime.fromtimestamp(join_date).strftime("%d/%m/%Y %I:%M")

        # calculate path to account member
        graph = Graph(self.community)
        path = None
        # if selected member is not the account member...
        if person.pubkey != self.account.pubkey:
            # add path from selected member to account member
            path = graph.get_shortest_path_between_members(person, self.account.get_person())

        text = self.tr("""

{:}
	{:}

{:}
	{:}

            """).format(
                self.tr('Public key'),
                self.person.pubkey,
                self.tr('Join date'),
                join_date
            )

        if path:
            distance = len(path) - 1
            text += self.tr("""
{:}
	{:}
""".format(self.tr('Distance'), distance))
            if distance > 1:
                index = 0
                for node in path:
                    if index == 0:
                        text += self.tr("""
{:}
	{:}
""").format(self.tr('Path'), node['text'])
                    else:
                        text += self.tr("""
{:}
	{:}
""").format('', node['text'])
                    if index == distance and node['id'] != self.account.pubkey:
                        text += self.tr("""
{:}
	{:}
""").format('', self.account.name)
                    index += 1
        # close html text
        text += "
"

        # set text in label
        self.label_properties.setText(text)


text:
using json = nlohmann::json;

int main()
{
    // create values of different floating-point types
    json::number_float_t v_ok = 3.141592653589793;
    json::number_float_t v_nan = NAN;
    json::number_float_t v_infinity = INFINITY;

    // create JSON numbers
    json j_ok(v_ok);
    json j_nan(v_nan);
    json j_infinity(v_infinity);

    // serialize the JSON numbers
    std::cout << j_ok << '\n';
    std::cout << j_nan << '\n';
    std::cout << j_infinity << '\n';
}


text:
typedef struct InputDeviceValues_s {
	//keys
  int esc[2];
  int space[2];
  int r[2];
  int z[2];
  int c[2];
  int plus[2];
  int minus[2];

  //mouse
  int leftClick[2];
  int rightClick[2];
  int scrollVal[2];
  int mouseMotionX[2];
  int mouseMotionY[2];
} InputDeviceValues_t;

void InitializeKeyPresses(InputDeviceValues_t *keys);
char CheckInput(InputDeviceValues_t *keys);
char HandleInput(ThreadedLifeContext_t *worldContext,
  LifeGameGraphicsContext_t *graphicsContext,
  InputDeviceValues_t * const keys);

#endif


text:
#import <iWorkImport/TSMTraceDecoder.h>

@interface TSMTraceDecoder (TSDrawables)
- (id)stringForTSDrawablesTraceRecord:(struct TSMTraceRecord_s *)arg1;
@end


text:
__author__ = 'Jeremy Emerson'

from core.domain import exp_domain
from core.domain import exp_services
from core.domain import rule_domain
from core.domain import stats_domain
from core.domain import stats_services

import test_utils

class EventHandlerUnitTests(test_utils.GenericTestBase):
    """Test the event handler methods."""

    DEFAULT_RULESPEC_STR = exp_domain.DEFAULT_RULESPEC_STR
    SUBMIT_HANDLER = stats_services.SUBMIT_HANDLER_NAME

    def test_record_state_hit(self):
        stats_services.EventHandler.record_state_hit('eid', 'sname', True)

        counter = stats_domain.StateCounter.get('eid', 'sname')
        self.assertEquals(counter.first_entry_count, 1)
        self.assertEquals(counter.subsequent_entries_count, 0)
        self.assertEquals(counter.resolved_answer_count, 0)
        self.assertEquals(counter.active_answer_count, 0)
        self.assertEquals(counter.total_entry_count, 1)
        self.assertEquals(counter.no_answer_count, 1)

        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR)
        self.assertEquals(answer_log.answers, {})

        stats_services.EventHandler.record_state_hit('eid', 'sname', False)

        counter = stats_domain.StateCounter.get('eid', 'sname')
        self.assertEquals(counter.first_entry_count, 1)
        self.assertEquals(counter.subsequent_entries_count, 1)
        self.assertEquals(counter.resolved_answer_count, 0)
        self.assertEquals(counter.active_answer_count, 0)
        self.assertEquals(counter.total_entry_count, 2)
        self.assertEquals(counter.no_answer_count, 2)

        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR)
        self.assertEquals(answer_log.answers, {})

    def test_record_answer_submitted(self):
        stats_services.EventHandler.record_state_hit('eid', 'sname', True)
        stats_services.EventHandler.record_answer_submitted(
            'eid', 'sname', self.SUBMIT_HANDLER, 'Rule', 'answer')

        counter = stats_domain.StateCounter.get('eid', 'sname')
        self.assertEquals(counter.first_entry_count, 1)
        self.assertEquals(counter.subsequent_entries_count, 0)
        self.assertEquals(counter.total_entry_count, 1)
        self.assertEquals(counter.resolved_answer_count, 0)
        self.assertEquals(counter.active_answer_count, 1)
        self.assertEquals(counter.no_answer_count, 0)

        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, 'Rule')
        self.assertEquals(answer_log.answers, {'answer': 1})

        stats_services.EventHandler.record_state_hit('eid', 'sname', False)
        stats_services.EventHandler.record_answer_submitted(
            'eid', 'sname', self.SUBMIT_HANDLER, 'Rule', 'answer')

        counter = stats_domain.StateCounter.get('eid', 'sname')
        self.assertEquals(counter.first_entry_count, 1)
        self.assertEquals(counter.subsequent_entries_count, 1)
        self.assertEquals(counter.total_entry_count, 2)
        self.assertEquals(counter.resolved_answer_count, 0)
        self.assertEquals(counter.active_answer_count, 2)
        self.assertEquals(counter.no_answer_count, 0)

        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, 'Rule')
        self.assertEquals(answer_log.answers, {'answer': 2})

        stats_services.EventHandler.record_state_hit('eid', 'sname', False)

        counter = stats_domain.StateCounter.get('eid', 'sname')
        self.assertEquals(counter.first_entry_count, 1)
        self.assertEquals(counter.subsequent_entries_count, 2)
        self.assertEquals(counter.total_entry_count, 3)
        self.assertEquals(counter.resolved_answer_count, 0)
        self.assertEquals(counter.active_answer_count, 2)
        self.assertEquals(counter.no_answer_count, 1)

        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, 'Rule')
        self.assertEquals(answer_log.answers, {'answer': 2})

    def test_resolve_answers_for_default_rule(self):
        stats_services.EventHandler.record_state_hit('eid', 'sname', True)

        # Submit three answers.
        stats_services.EventHandler.record_answer_submitted(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR,
            'a1')
        stats_services.EventHandler.record_answer_submitted(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR,
            'a2')
        stats_services.EventHandler.record_answer_submitted(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR,
            'a3')

        counter = stats_domain.StateCounter.get('eid', 'sname')
        self.assertEquals(counter.resolved_answer_count, 0)
        self.assertEquals(counter.active_answer_count, 3)

        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR)
        self.assertEquals(
            answer_log.answers, {'a1': 1, 'a2': 1, 'a3': 1})

        # Nothing changes if you try to resolve an invalid answer.
        stats_services.EventHandler.resolve_answers_for_default_rule(
            'eid', 'sname', self.SUBMIT_HANDLER, ['fake_answer'])
        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR)
        self.assertEquals(
            answer_log.answers, {'a1': 1, 'a2': 1, 'a3': 1})

        # Resolve two answers.
        stats_services.EventHandler.resolve_answers_for_default_rule(
            'eid', 'sname', self.SUBMIT_HANDLER, ['a1', 'a2'])

        counter = stats_domain.StateCounter.get('eid', 'sname')
        self.assertEquals(counter.resolved_answer_count, 2)
        self.assertEquals(counter.active_answer_count, 1)

        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR)
        self.assertEquals(answer_log.answers, {'a3': 1})

        # Nothing changes if you try to resolve an answer that has already
        # been resolved.
        stats_services.EventHandler.resolve_answers_for_default_rule(
            'eid', 'sname', self.SUBMIT_HANDLER, ['a1'])
        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR)
        self.assertEquals(answer_log.answers, {'a3': 1})

        # Resolve the last answer.
        stats_services.EventHandler.resolve_answers_for_default_rule(
            'eid', 'sname', self.SUBMIT_HANDLER, ['a3'])

        counter = stats_domain.StateCounter.get('eid', 'sname')
        self.assertEquals(counter.resolved_answer_count, 3)
        self.assertEquals(counter.active_answer_count, 0)

        answer_log = stats_domain.StateRuleAnswerLog.get(
            'eid', 'sname', self.SUBMIT_HANDLER, 'Rule')
        self.assertEquals(answer_log.answers, {})

class StatsServicesUnitTests(test_utils.GenericTestBase):
    """Test the statistics services."""

    DEFAULT_RULESPEC_STR = exp_domain.DEFAULT_RULESPEC_STR
    SUBMIT_HANDLER = stats_services.SUBMIT_HANDLER_NAME

class TopImprovableStatesUnitTests(test_utils.GenericTestBase):
    """Test the get_top_improvable_states() function."""

    DEFAULT_RULESPEC_STR = exp_domain.DEFAULT_RULESPEC_STR
    SUBMIT_HANDLER = stats_services.SUBMIT_HANDLER_NAME

    def test_get_top_improvable_states(self):
        exp = exp_domain.Exploration.create_default_exploration(
            'eid', 'A title', 'A category')
        exp_services.save_new_exploration('fake@user.com', exp)
        state_name = exp.init_state_name

        for _ in range(5):
            stats_services.EventHandler.record_state_hit(
                'eid', state_name, True)

        stats_services.EventHandler.record_answer_submitted(
            'eid', state_name, self.SUBMIT_HANDLER,
            self.DEFAULT_RULESPEC_STR, '1')
        for _ in range(2):
            stats_services.EventHandler.record_answer_submitted(
                'eid', state_name, self.SUBMIT_HANDLER,
                self.DEFAULT_RULESPEC_STR, '2')

        expected_top_state = {
            'exp_id': 'eid', 'type': 'default', 'rank': 3,
            'state_name': exp.init_state_name
        }

        states = stats_services.get_top_improvable_states(['eid'], 10)
        self.assertEquals(len(states), 1)
        self.assertDictContainsSubset(expected_top_state, states[0])

    def test_single_default_rule_hit(self):
        exp = exp_domain.Exploration.create_default_exploration(
            'eid', 'A title', 'A category')
        exp_services.save_new_exploration('fake@user.com', exp)
        state_name = exp.init_state_name

        stats_services.EventHandler.record_state_hit('eid', state_name, True)
        stats_services.EventHandler.record_answer_submitted(
            'eid', state_name, self.SUBMIT_HANDLER,
            self.DEFAULT_RULESPEC_STR, '1')

        expected_top_state = {
            'exp_id': 'eid', 'type': 'default', 'rank': 1,
            'state_name': exp.init_state_name
        }

        states = stats_services.get_top_improvable_states(['eid'], 2)
        self.assertEquals(len(states), 1)
        self.assertDictContainsSubset(expected_top_state, states[0])

    def test_no_improvement_flag_hit(self):
        exp = exp_domain.Exploration.create_default_exploration(
            'eid', 'A title', 'A category')
        exp_services.save_new_exploration('fake@user.com', exp)

        not_default_rule_spec = exp_domain.RuleSpec({
            'rule_type': rule_domain.ATOMIC_RULE_TYPE,
            'name': 'NotDefault',
            'inputs': {},
            'subject': 'answer'
        }, exp.init_state_name, [], [])
        exp.init_state.widget.handlers[0].rule_specs = [
            not_default_rule_spec, exp_domain.DEFAULT_RULESPEC
        ]
        exp_services._save_exploration('fake@user.com', exp, '', [])

        stats_services.EventHandler.record_state_hit(
            'eid', exp.init_state_name, True)
        stats_services.EventHandler.record_answer_submitted(
            'eid', exp.init_state_name, self.SUBMIT_HANDLER,
            str(not_default_rule_spec), '1')

        states = stats_services.get_top_improvable_states(['eid'], 1)
        self.assertEquals(len(states), 0)

    def test_incomplete_and_default_flags(self):
        exp = exp_domain.Exploration.create_default_exploration(
            'eid', 'A title', 'A category')
        exp_services.save_new_exploration('fake@user.com', exp)

        state_name = exp.init_state_name

        # Hit the default rule once, and fail to answer twice. The result
        # should be classified as incomplete.

        for _ in range(3):
            stats_services.EventHandler.record_state_hit(
                'eid', state_name, True)

        stats_services.EventHandler.record_answer_submitted(
            'eid', state_name, self.SUBMIT_HANDLER,
            self.DEFAULT_RULESPEC_STR, '1')

        states = stats_services.get_top_improvable_states(['eid'], 2)
        self.assertEquals(len(states), 1)
        self.assertEquals(states[0]['rank'], 2)
        self.assertEquals(states[0]['type'], 'incomplete')

        # Now hit the default two more times. The result should be classified
        # as default.

        for i in range(2):
            stats_services.EventHandler.record_state_hit(
                'eid', state_name, True)
            stats_services.EventHandler.record_answer_submitted(
                'eid', state_name, self.SUBMIT_HANDLER,
                self.DEFAULT_RULESPEC_STR, '1')

        states = stats_services.get_top_improvable_states(['eid'], 2)
        self.assertEquals(len(states), 1)
        self.assertEquals(states[0]['rank'], 3)
        self.assertEquals(states[0]['type'], 'default')

    def test_two_state_default_hit(self):
        exp = exp_domain.Exploration.create_default_exploration(
            'eid', 'A title', 'A category')
        exp_services.save_new_exploration('fake@user.com', exp)

        FIRST_STATE_NAME = exp.init_state_name
        SECOND_STATE_NAME = 'State 2'
        exp.add_states([SECOND_STATE_NAME])
        exp_services._save_exploration('fake@user.com', exp, '', [])

        # Hit the default rule of state 1 once, and the default rule of state 2
        # twice.
        stats_services.EventHandler.record_state_hit(
            'eid', FIRST_STATE_NAME, True)
        stats_services.EventHandler.record_answer_submitted(
            'eid', FIRST_STATE_NAME, self.SUBMIT_HANDLER,
            self.DEFAULT_RULESPEC_STR, '1')

        for i in range(2):
            stats_services.EventHandler.record_state_hit(
                'eid', SECOND_STATE_NAME, True)
            stats_services.EventHandler.record_answer_submitted(
                'eid', SECOND_STATE_NAME, self.SUBMIT_HANDLER,
                self.DEFAULT_RULESPEC_STR, '1')

        states = stats_services.get_top_improvable_states(['eid'], 5)
        self.assertEquals(len(states), 2)
        self.assertDictContainsSubset({
            'rank': 2,
            'type': 'default',
            'state_name': SECOND_STATE_NAME
        }, states[0])
        self.assertDictContainsSubset({
            'rank': 1,
            'type': 'default',
            'state_name': FIRST_STATE_NAME
        }, states[1])

        # Hit the default rule of state 1 two more times.

        for i in range(2):
            stats_services.EventHandler.record_state_hit(
                'eid', FIRST_STATE_NAME, True)
            stats_services.EventHandler.record_answer_submitted(
                'eid', FIRST_STATE_NAME, self.SUBMIT_HANDLER,
                self.DEFAULT_RULESPEC_STR, '1')

        states = stats_services.get_top_improvable_states(['eid'], 5)
        self.assertEquals(len(states), 2)
        self.assertDictContainsSubset({
            'rank': 3,
            'type': 'default',
            'state_name': FIRST_STATE_NAME
        }, states[0])
        self.assertDictContainsSubset({
            'rank': 2,
            'type': 'default',
            'state_name': SECOND_STATE_NAME
        }, states[1])

        # Try getting just the top improvable state.
        states = stats_services.get_top_improvable_states(['eid'], 1)
        self.assertEquals(len(states), 1)
        self.assertDictContainsSubset({
            'rank': 3,
            'type': 'default',
            'state_name': FIRST_STATE_NAME
        }, states[0])

class UnresolvedAnswersTests(test_utils.GenericTestBase):
    """Test the unresolved answers methods."""

    DEFAULT_RULESPEC_STR = exp_domain.DEFAULT_RULESPEC_STR
    SUBMIT_HANDLER = stats_services.SUBMIT_HANDLER_NAME

    def test_get_unresolved_answers(self):
        self.assertEquals(
            stats_services.get_unresolved_answers_for_default_rule(
                'eid', 'sid'), {})

        stats_services.EventHandler.record_answer_submitted(
            'eid', 'sid', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR, 'a1')
        self.assertEquals(
            stats_services.get_unresolved_answers_for_default_rule(
                'eid', 'sid'), {'a1': 1})

        stats_services.EventHandler.record_answer_submitted(
            'eid', 'sid', self.SUBMIT_HANDLER, self.DEFAULT_RULESPEC_STR, 'a1')
        self.assertEquals(
            stats_services.get_unresolved_answers_for_default_rule(
                'eid', 'sid'), {'a1': 2})

        stats_services.EventHandler.resolve_answers_for_default_rule(
            'eid', 'sid', self.SUBMIT_HANDLER, ['a1'])
        self.assertEquals(
            stats_services.get_unresolved_answers_for_default_rule(
                'eid', 'sid'), {})


text:
<template>

basic

		<ssv-select
			options.bind="options"
			selected.bind="optionSelected"
			placeholder="select game"></ssv-select>

<ssv-select options.bind="options"
	selected.bind="optionSelected"
	placeholder="select game">
</ssv-select>

const options = [
	{ text: "League of Legends", value: "lol", type: "MOBA" },
	{ text: "World Of Warcraft", value: "wow", type: "MMO" },
	{ text: "Heroes of the Storm", value: "hots", type: "MOBA" }
];

simple list

		<ssv-select options.bind="fruits"
			placeholder="select fruit"
			selected.bind="selectedFruit"
			color="danger"></ssv-select>

<ssv-select options.bind="fruits"
	placeholder="select fruit"
	selected.bind="selectedFruit"
	color="danger">
</ssv-select>

const fruits = ["banana", "strawberry", "melon"];

Specify text and value properties

		<ssv-select options.bind="heroes"
		 	text-field="name"
			value-field="id"
			selected.bind="heroSelected"
			filter-placeholder="search game"
			no-options="no games found"
			placeholder="select hero"></ssv-select>

<ssv-select options.bind="heroes"
	text-field="name"
	value-field="id"
	selected.bind="heroSelected"
	filter-placeholder="search game"
	no-options="no games found"
	placeholder="select hero">
</ssv-select>

const heroes = [
	{ id: 1, name: "thor", strength: 20 },
	{ id: 2, name: "iron man", strength: 11 },
	{ id: 3, name: "batman", strength: 7 }
];

group by

		<ssv-select options.bind="options"
			groupby="type"
			selected.bind="optionSelected"
			placeholder="select game"></ssv-select>

<ssv-select options.bind="options"
	groupby="type"
	selected.bind="optionSelected"
	placeholder="select game">
</ssv-select>

const options = [
	{ text: "League of Legends", value: "lol", type: "MOBA" },
	{ text: "World Of Warcraft", value: "wow", type: "MMO" },
	{ text: "Heroes of the Storm", value: "hots", type: "MOBA" }
];

multi select

		<button ssv-button click.delegate="addGame()">Add game</button>
		<ssv-select options.bind="options"
			type="multi"
			auto-close="false"
			max-selections="3"
			placeholder="select game"
			selected.bind="optionsSelected"
			color="primary"></ssv-select>

		selected text:

${item.text}

<ssv-select options.bind="options"
	type="multi"
	auto-close="false"
	max-selections="3"
	placeholder="select game"
	selected.bind="optionsSelected"
	color="primary">
</ssv-select>

event: change

		*note: select an item and check console.
		<ssv-select options.bind="options"
			placeholder="select game"
			change.delegate="onChange($event)"></ssv-select>

<ssv-select options.bind="options"
	placeholder="select game"
	change.delegate="onChange($event)">
</ssv-select>

onChange(event: CustomEvent) {
	this.logger.debug("onChange", "triggered", {
		previous: event.detail.previous,
		value: event.detail.value
	});
}

disabled

		<ssv-select options.bind="options"
			disabled
			selected.bind="optionSelected"
			placeholder="select game"></ssv-select>

<ssv-select
	options.bind="options"
	disabled
	selected.bind="optionSelected"
	placeholder="select game">
</ssv-select>

		<ssv-select options.bind="options"
			type="multi"
			disabled.bind="isDisabled"
			placeholder="select game"
			selected.bind="optionsSelected"
			color="success"></ssv-select>
		<button ssv-button click.delegate="toggleDisable()">${isDisabled ? "enable" : "disable"}</button>

<ssv-select options.bind="options"
	type="multi"
	disabled.bind="isDisabled"
	placeholder="select game"
	selected.bind="optionSelected"
	color="success">
</ssv-select>

variants

type single

		<template repeat.for="color of colors">

			<ssv-select options.bind="options"
				selected.bind="optionSelected"
				placeholder="select game"
				color.bind="color"></ssv-select>
		</template>

type multi

		<template repeat.for="color of colors">
			<ssv-select options.bind="options" type="multi"
				placeholder="select game"
				selected.bind="optionsSelected"
				color.bind="color"></ssv-select>
		</template>

</template>


text:
<form name="deleteForm" ng-submit="vm.confirmDelete(vm.effort.id)">

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                ng-click="vm.clear()">×</button>

Confirm delete operation

        <jhi-alert-error></jhi-alert-error>

Are you sure you want to delete this Effort?

        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.clear()">
             Cancel
        </button>
        <button type="submit" ng-disabled="deleteForm.$invalid" class="btn btn-danger">
             Delete
        </button>

</form>


text:
class GURL;
class Profile;
class TrustedSourcesManager;

namespace content {
class BrowserContext;
class DownloadManager;
}

namespace download {
class DownloadItem;
}

namespace policy {
class URLBlacklist;
}

namespace user_prefs {
class PrefRegistrySyncable;
}

// Stores all download-related preferences.
class DownloadPrefs {
 public:
  enum class DownloadRestriction {
    NONE = 0,
    DANGEROUS_FILES = 1,
    POTENTIALLY_DANGEROUS_FILES = 2,
    ALL_FILES = 3,
    // MALICIOUS_FILES has a stricter definition of harmful file than
    // DANGEROUS_FILES and does not block based on file extension.
    MALICIOUS_FILES = 4,
  };
  explicit DownloadPrefs(Profile* profile);
  ~DownloadPrefs();

  static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);

  // Returns the default download directory.
  static const base::FilePath& GetDefaultDownloadDirectory();

  // Returns the default download directory for the current profile.
  base::FilePath GetDefaultDownloadDirectoryForProfile() const;

  // Returns the DownloadPrefs corresponding to the given DownloadManager
  // or BrowserContext.
  static DownloadPrefs* FromDownloadManager(
      content::DownloadManager* download_manager);
  static DownloadPrefs* FromBrowserContext(
      content::BrowserContext* browser_context);

  // Identify whether the downloaded item was downloaded from a trusted source.
  bool IsFromTrustedSource(const download::DownloadItem& item);

  base::FilePath DownloadPath() const;
  void SetDownloadPath(const base::FilePath& path);
  base::FilePath SaveFilePath() const;
  void SetSaveFilePath(const base::FilePath& path);
  int save_file_type() const { return *save_file_type_; }
  void SetSaveFileType(int type);
  DownloadRestriction download_restriction() const {
    return static_cast<DownloadRestriction>(*download_restriction_);
  }
  bool safebrowsing_for_trusted_sources_enabled() const {
    return *safebrowsing_for_trusted_sources_enabled_;
  }

  // Returns true if the prompt_for_download preference has been set and the
  // download location is not managed (which means the user shouldn't be able
  // to choose another download location).
  bool PromptForDownload() const;

  // Returns true if the download path preference is managed.
  bool IsDownloadPathManaged() const;

  // Returns true if there is at least one file extension registered
  // by the user for auto-open.
  bool IsAutoOpenByUserUsed() const;

  // Returns true if |path| should be opened automatically.
  bool IsAutoOpenEnabled(const GURL& url, const base::FilePath& path) const;

  // Returns true if |path| should be opened automatically by policy.
  bool IsAutoOpenByPolicy(const GURL& url, const base::FilePath& path) const;

  // Enables automatically opening all downloads with the same file type as
  // |file_name|. Returns true on success. The call may fail if |file_name|
  // either doesn't have an extension (hence the file type cannot be
  // determined), or if the file type is one that is disallowed from being
  // opened automatically. See IsAllowedToOpenAutomatically() for details on the
  // latter.
  bool EnableAutoOpenByUserBasedOnExtension(const base::FilePath& file_name);

  // Disables auto-open based on file extension.
  void DisableAutoOpenByUserBasedOnExtension(const base::FilePath& file_name);

#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_MACOSX)
  // Store the user preference to disk. If |should_open| is true, also disable
  // the built-in PDF plugin. If |should_open| is false, enable the PDF plugin.
  void SetShouldOpenPdfInSystemReader(bool should_open);

  // Return whether the user prefers to open PDF downloads in the platform's
  // default reader.
  bool ShouldOpenPdfInSystemReader() const;
#endif

  void ResetAutoOpenByUser();

  // If this is called, the download target path will not be sanitized going
  // forward - whatever has been passed to SetDownloadPath will be used.
  void SkipSanitizeDownloadTargetPathForTesting();

 private:
  void SaveAutoOpenState();

  // Checks whether |path| is a valid download target path. If it is, returns
  // it as is. If it isn't returns the default download directory.
  base::FilePath SanitizeDownloadTargetPath(const base::FilePath& path) const;

  void UpdateAutoOpenByPolicy();

  void UpdateAllowedURLsForOpenByPolicy();

  Profile* profile_;

  BooleanPrefMember prompt_for_download_;
#if defined(OS_ANDROID)
  IntegerPrefMember prompt_for_download_android_;
#endif

  FilePathPrefMember download_path_;
  FilePathPrefMember save_file_path_;
  IntegerPrefMember save_file_type_;
  IntegerPrefMember download_restriction_;
  BooleanPrefMember safebrowsing_for_trusted_sources_enabled_;

  PrefChangeRegistrar pref_change_registrar_;

  // To identify if a download URL is from a trusted source.
  std::unique_ptr<TrustedSourcesManager> trusted_sources_manager_;

  // Set of file extensions to open at download completion.
  struct AutoOpenCompareFunctor {
    bool operator()(const base::FilePath::StringType& a,
                    const base::FilePath::StringType& b) const;
  };
  typedef std::set<base::FilePath::StringType,
                   AutoOpenCompareFunctor> AutoOpenSet;
  AutoOpenSet auto_open_by_user_;
  AutoOpenSet auto_open_by_policy_;

  std::unique_ptr<policy::URLBlacklist> auto_open_allowed_by_urls_;

#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_MACOSX)
  bool should_open_pdf_in_system_reader_;
#endif

  // If this is true, SanitizeDownloadTargetPath will always return the passed
  // path verbatim.
  bool skip_sanitize_download_target_path_for_testing_ = false;

  DISALLOW_COPY_AND_ASSIGN(DownloadPrefs);
};

#endif  // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_PREFS_H_


text:
package com.sitescout.dsp.api.model.dto;

import org.joda.time.DateTime;

public class CreativeAssetDTO {
    private String assetUrl;
    private Integer width;
    private Integer height;
    private DateTime created;

    public String getAssetUrl() {
        return assetUrl;
    }

    public void setAssetUrl(String assetUrl) {
        this.assetUrl = assetUrl;
    }

    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    public DateTime getCreated() {
        return created;
    }

    public void setCreated(DateTime created) {
        this.created = created;
    }
}


text:
'use strict';

/**
 * Setup file for the Scenario.
 * Must be first in the compilation/bootstrap list.
 */

// Public namespace
angular.scenario = angular.scenario || {};

/**
 * Expose jQuery (e.g. for custom dsl extensions).
 */
angular.scenario.jQuery = _jQuery;

/**
 * Defines a new output format.
 *
 * @param {string} name the name of the new output format
 * @param {function()} fn function(context, runner) that generates the output
 */
angular.scenario.output = angular.scenario.output || function(name, fn) {
  angular.scenario.output[name] = fn;
};

/**
 * Defines a new DSL statement. If your factory function returns a Future
 * it's returned, otherwise the result is assumed to be a map of functions
 * for chaining. Chained functions are subject to the same rules.
 *
 * Note: All functions on the chain are bound to the chain scope so values
 *   set on "this" in your statement function are available in the chained
 *   functions.
 *
 * @param {string} name The name of the statement
 * @param {function()} fn Factory function(), return a function for
 *  the statement.
 */
angular.scenario.dsl = angular.scenario.dsl || function(name, fn) {
  angular.scenario.dsl[name] = function() {
    /* jshint -W040 *//* The dsl binds `this` for us when calling chained functions */
    function executeStatement(statement, args) {
      var result = statement.apply(this, args);
      if (angular.isFunction(result) || result instanceof angular.scenario.Future) {
        return result;
      }
      var self = this;
      var chain = angular.extend({}, result);
      angular.forEach(chain, function(value, name) {
        if (angular.isFunction(value)) {
          chain[name] = function() {
            return executeStatement.call(self, value, arguments);
          };
        } else {
          chain[name] = value;
        }
      });
      return chain;
    }
    var statement = fn.apply(this, arguments);
    return function() {
      return executeStatement.call(this, statement, arguments);
    };
  };
};

/**
 * Defines a new matcher for use with the expects() statement. The value
 * this.actual (like in Jasmine) is available in your matcher to compare
 * against. Your function should return a boolean. The future is automatically
 * created for you.
 *
 * @param {string} name The name of the matcher
 * @param {function()} fn The matching function(expected).
 */
angular.scenario.matcher = angular.scenario.matcher || function(name, fn) {
  angular.scenario.matcher[name] = function(expected) {
    var description = this.future.name +
                      (this.inverse ? ' not ' : ' ') + name +
                      ' ' + angular.toJson(expected);
    var self = this;
    this.addFuture('expect ' + description,
      function(done) {
        var error;
        self.actual = self.future.value;
        if ((self.inverse && fn.call(self, expected)) ||
            (!self.inverse && !fn.call(self, expected))) {
          error = 'expected ' + description +
            ' but was ' + angular.toJson(self.actual);
        }
        done(error);
    });
  };
};

/**
 * Initialize the scenario runner and run !
 *
 * Access global window and document object
 * Access $runner through closure
 *
 * @param {Object=} config Config options
 */
angular.scenario.setUpAndRun = function(config) {
  var href = window.location.href;
  var body = _jQuery(window.document.body);
  var output = [];
  var objModel = new angular.scenario.ObjectModel($runner);

  if (config && config.scenario_output) {
    output = config.scenario_output.split(',');
  }

  angular.forEach(angular.scenario.output, function(fn, name) {
    if (!output.length || output.indexOf(name) != -1) {
      var context = body.append('

').find('div:last');
      context.attr('id', name);
      fn.call({}, context, $runner, objModel);
    }
  });

  if (!/^http/.test(href) && !/^https/.test(href)) {
    body.append('

');
    body.find('#system-error').text(
      'Scenario runner must be run using http or https. The protocol ' +
      href.split(':')[0] + ':// is not supported.'
    );
    return;
  }

  var appFrame = body.append('

').find('#application');
  var application = new angular.scenario.Application(appFrame);

  $runner.on('RunnerEnd', function() {
    appFrame.css('display', 'none');
    appFrame.find('iframe').attr('src', 'about:blank');
  });

  $runner.on('RunnerError', function(error) {
    if (window.console) {
      console.log(formatException(error));
    } else {
      // Do something for IE
      alert(error);
    }
  });

  $runner.run(application);
};

/**
 * Iterates through list with iterator function that must call the
 * continueFunction to continue iterating.
 *
 * @param {Array} list list to iterate over
 * @param {function()} iterator Callback function(value, continueFunction)
 * @param {function()} done Callback function(error, result) called when
 *   iteration finishes or an error occurs.
 */
function asyncForEach(list, iterator, done) {
  var i = 0;
  function loop(error, index) {
    if (index && index > i) {
      i = index;
    }
    if (error || i >= list.length) {
      done(error);
    } else {
      try {
        iterator(list[i++], loop);
      } catch (e) {
        done(e);
      }
    }
  }
  loop();
}

/**
 * Formats an exception into a string with the stack trace, but limits
 * to a specific line length.
 *
 * @param {Object} error The exception to format, can be anything throwable
 * @param {Number=} [maxStackLines=5] max lines of the stack trace to include
 *  default is 5.
 */
function formatException(error, maxStackLines) {
  maxStackLines = maxStackLines || 5;
  var message = error.toString();
  if (error.stack) {
    var stack = error.stack.split('\n');
    if (stack[0].indexOf(message) === -1) {
      maxStackLines++;
      stack.unshift(error.message);
    }
    message = stack.slice(0, maxStackLines).join('\n');
  }
  return message;
}

/**
 * Returns a function that gets the file name and line number from a
 * location in the stack if available based on the call site.
 *
 * Note: this returns another function because accessing .stack is very
 * expensive in Chrome.
 *
 * @param {Number} offset Number of stack lines to skip
 */
function callerFile(offset) {
  var error = new Error();

  return function() {
    var line = (error.stack || '').split('\n')[offset];

    // Clean up the stack trace line
    if (line) {
      if (line.indexOf('@') !== -1) {
        // Firefox
        line = line.substring(line.indexOf('@') + 1);
      } else {
        // Chrome
        line = line.substring(line.indexOf('(') + 1).replace(')', '');
      }
    }

    return line || '';
  };
}

/**
 * Don't use the jQuery trigger method since it works incorrectly.
 *
 * jQuery notifies listeners and then changes the state of a checkbox and
 * does not create a real browser event. A real click changes the state of
 * the checkbox and then notifies listeners.
 *
 * To work around this we instead use our own handler that fires a real event.
 */
(function(fn) {
  // We need a handle to the original trigger function for input tests.
  var parentTrigger = fn._originalTrigger = fn.trigger;
  fn.trigger = function(type) {
    if (/(click|change|keydown|blur|input|mousedown|mouseup)/.test(type)) {
      var processDefaults = [];
      this.each(function(index, node) {
        processDefaults.push(browserTrigger(node, type));
      });

      // this is not compatible with jQuery - we return an array of returned values,
      // so that scenario runner know whether JS code has preventDefault() of the event or not...
      return processDefaults;
    }
    return parentTrigger.apply(this, arguments);
  };
})(_jQuery.fn);

/**
 * Finds all bindings with the substring match of name and returns an
 * array of their values.
 *
 * @param {string} bindExp The name to match
 * @return {Array.<string>} String of binding values
 */
_jQuery.fn.bindings = function(windowJquery, bindExp) {
  var result = [], match,
      bindSelector = '.ng-binding:visible';
  if (angular.isString(bindExp)) {
    bindExp = bindExp.replace(/\s/g, '');
    match = function(actualExp) {
      if (actualExp) {
        actualExp = actualExp.replace(/\s/g, '');
        if (actualExp == bindExp) return true;
        if (actualExp.indexOf(bindExp) === 0) {
          return actualExp.charAt(bindExp.length) == '|';
        }
      }
    };
  } else if (bindExp) {
    match = function(actualExp) {
      return actualExp && bindExp.exec(actualExp);
    };
  } else {
    match = function(actualExp) {
      return !!actualExp;
    };
  }
  var selection = this.find(bindSelector);
  if (this.is(bindSelector)) {
    selection = selection.add(this);
  }

  function push(value) {
    if (angular.isUndefined(value)) {
      value = '';
    } else if (typeof value !== 'string') {
      value = angular.toJson(value);
    }
    result.push('' + value);
  }

  selection.each(function() {
    var element = windowJquery(this),
        bindings;
    if (bindings = element.data('$binding')) {
      for (var expressions = [], binding, j=0, jj=bindings.length; j < jj; j++) {
        binding = bindings[j];

        if (binding.expressions) {
          expressions = binding.expressions;
        } else {
          expressions = [binding];
        }
        for (var scope, expression, i = 0, ii = expressions.length; i < ii; i++) {
          expression = expressions[i];
          if (match(expression)) {
            scope = scope || element.scope();
            push(scope.$eval(expression));
          }
        }
      }
    }
  });
  return result;
};


text:
This extension will label (classify) from any `jpg` or `png` images uploaded to Cloud Storage and write the labels to Firestore.

# Billing

This extension uses other Firebase or Google Cloud Platform services which may have associated charges:

<!-- List all products the extension interacts with -->

- Cloud Functions
- Cloud Vision API
- Cloud Storage
- Cloud Firestore

When you use Firebase Extensions, you're only charged for the underlying resources that you use. A paid-tier (Blaze) billing plan is required because the extension uses Cloud Vision API.


text:
package com.facebook.react.testing;

import android.content.Context;

import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.NativeModule;

public interface ReactTestFactory {
  public static interface ReactInstanceEasyBuilder {
    ReactInstanceEasyBuilder setContext(Context context);
    ReactInstanceEasyBuilder addNativeModule(NativeModule module);
    CatalystInstance build();
  }

  ReactInstanceEasyBuilder getCatalystInstanceBuilder();
  ReactInstanceManagerBuilder getReactInstanceManagerBuilder();
}


text:
void searchPrimesBasicOMP(unsigned long long max, unsigned long long *isPrime);

#define PRIME_OMP_H

#endif //PRIME_OMP_H


text:
package com.sabertazimi.tao.virtualMachine;

import com.sabertazimi.tao.intermediatecode.CodeChunk;

import java.util.EnumMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Value {

    public enum Type {
        Integer, Number, Boolean, String, Object, Null,
    }

    private static final Map<CodeChunk.ImmediateType, Type> typeMap = new EnumMap<CodeChunk.ImmediateType, Type>(CodeChunk.ImmediateType.class) {{
        put(CodeChunk.ImmediateType.Integer, Type.Integer);
        put(CodeChunk.ImmediateType.Number, Type.Number);
        put(CodeChunk.ImmediateType.Boolean, Type.Boolean);
        put(CodeChunk.ImmediateType.String, Type.String);
        put(CodeChunk.ImmediateType.Null, Type.Null);
    }};

    public static final Value NULL = new Value(Type.Null, 0, 0.0, false, null, null);

    public final Type type;
    public final int intValue;
    public final double numValue;
    public final boolean bolValue;
    public final String strValue;
    public final TaolanObject objValue;

    private Value(Type type, int intValue, double numValue, boolean bolValue, String strValue, TaolanObject objValue) {
        this.type = type;
        this.intValue = intValue;
        this.numValue = numValue;
        this.bolValue = bolValue;
        this.strValue = strValue;
        this.objValue = objValue;
    }

    public Value(CodeChunk.ImmediateNumber immediateNumber) {
        this(typeMap.get(immediateNumber.getType()), immediateNumber.getIntegerValue(),
             immediateNumber.getNumberValue(), immediateNumber.isBooleanValue(), immediateNumber.getStringValue(), null);
    }

    public Value(int value) {
        this(Type.Integer, value, 0.0, false, null, null);
    }

    public Value(double value) {
        this(Type.Number, 0, value, false, null, null);
    }

    public Value(boolean value) {
        this(Type.Boolean, 0, 0.0, value, null, null);
    }

    public Value(String str) {
        this(str == null? Type.Null: Type.String, 0, 0.0, false, str, null);
    }

    public Value(TaolanObject objValue) { this(Type.Object, 0, 0.0, false, null, objValue); }

    public boolean convertToBoolean() {
        return this.type == Type.Boolean? bolValue: this.type != Type.Null;
    }

    public boolean isInstanceOf(Value other) {
        if (this.type != Type.Object || other.type != Type.Object) {
            return false;
        }
        TaolanObject thisObj = this.objValue;
        TaolanObject otherObj = other.objValue;

        while (thisObj != null) {
            if (thisObj == otherObj) {
                return true;
            }
            thisObj = thisObj.getPrototype();
        }
        return false;
    }

    public boolean isSameTypeOf(Value other) {
        if (this.type != Type.Object || other.type != Type.Object) {
            return false;
        }
        TaolanObject thisObj = this.objValue;
        TaolanObject otherObj = other.objValue;

        return thisObj.getConstructor() == otherObj;
    }

    public static Value add(Value v1, Value v2) {
        if (v1.type == Type.String) {
            return new Value(v1.strValue + v2.toString());
        }
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue + v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue + v2.numValue);
            }
        }
        return null;
    }

    public static Value sub(Value v1, Value v2) {
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue - v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue - v2.numValue);
            }
        }
        return null;
    }

    public static Value mul(Value v1, Value v2) {
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue * v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue * v2.numValue);
            }
        }
        return null;
    }

    public static Value div(Value v1, Value v2) {
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue / v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue / v2.numValue);
            }
        }
        return null;
    }

    public static Value gt(Value v1, Value v2) {
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue > v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue > v2.numValue);
            }
        }
        return null;
    }

    public static Value lt(Value v1, Value v2) {
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue < v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue < v2.numValue);
            }
        }
        return null;
    }

    public static Value gte(Value v1, Value v2) {
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue >= v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue >= v2.numValue);
            }
        }
        return null;
    }

    public static Value lte(Value v1, Value v2) {
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue <= v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue <= v2.numValue);
            }
        }
        return null;
    }

    public static Value checkEquals(Value v1, Value v2) {
        v1 = convertNumberToHeightTypeLevel(v1, v2);
        v2 = convertNumberToHeightTypeLevel(v2, v1);

        if (v1.type == v2.type) {
            if (v1.type == Type.Integer) {
                return new Value(v1.intValue == v2.intValue);
            } else if (v1.type == Type.Number) {
                return new Value(v1.numValue == v2.numValue);
            } else if (v1.type == Type.Boolean) {
                return new Value(v1.bolValue == v2.bolValue);
            } else if (v1.type == Type.String) {
                return new Value(v1.strValue.equals(v2.strValue));
            } else if (v1.type == Type.Object) {
                List<Value> params = new LinkedList<>();
                params.add(v2);
                return NativeFunction.Equals.invoke(v1.objValue, params);
            } else if (v1.type == Type.Null) {
                return new Value(true);
            }
        } else {
            return new Value(false);
        }
        return null;
    }

    public static Value checkNotEquals(Value v1, Value v2) {
        return new Value(!checkEquals(v1, v2).bolValue);
    }

    public static Value convertNumberToHeightTypeLevel(Value convertedValue, Value comparedValue) {
        if (convertedValue.type == Type.Integer && comparedValue.type == Type.Number) {
            convertedValue = new Value((double)convertedValue.intValue);
        }
        return convertedValue;
    }

    @Override
    public String toString() {
        if (type == Type.Integer) {
            return String.valueOf(intValue);
        } else if (type == Type.Number) {
            return String.valueOf(numValue);
        } else if (type == Type.Boolean) {
            return String.valueOf(bolValue);
        } else if (type == Type.String) {
            return strValue;
        } else if (type == Type.Object) {
            return objValue.toString();
        } else if (type == Type.Null) {
            return "NULL";
        }
        throw new RuntimeException();
    }
}


text:
[![Join the chat at https://gitter.im/enricolucia/what-2-nite](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/enricolucia/what-2-nite?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
![alt tag](logo.jpg)

[![Build Status](https://travis-ci.org/enricolucia/what-2-nite.svg)](https://travis-ci.org/enricolucia/what-2-nite)
[![Code Climate](https://codeclimate.com/github/enricolucia/what-2-nite/badges/gpa.svg)](https://codeclimate.com/github/enricolucia/what-2-nite)

A single page application with restful API from [themoviedb.org] and AngularJs.
It lets you search and browse for your favourite movies based on your preferences, provindig tips for best movies to watch as well.

Live on heroku here: [what-2-nite.herokuapp.com]
### Structure
  - Gulp task management implemented for build, watch and test tasks (e2e, unit-test)
  - Bower integration
  - Karma and Protractor implemented
  - Continuos Integration with Travis
  - Continuos Deployment with Heroku

### Configure
```sh
$ npm install
```
Install npm and bower dependencies
```sh
$ gulp
```
Starts the express server, plus creating the main 'app' folder where to serve all contents and watch changes
```sh
$ gulp test
```
Starts karma testings
```sh
$ gulp protractor
```
Starts protractor testings

### Todo's
 - e2e testings
 - unit testings
 - enhance mobile view
 - improve modules
 - add related movies to movie page

Any suggestions or bug reports is more than welcome!

### Tech

What-2-Nite use the following tools and libraries:

* Google Fonts 'Open Sans'
* Karma
* Protractor
* Bootstrap html/less
* Bower
* Node Express
* Selenium
* PhantomJS

### Compatibilities

Tested on latest Chrome and Firefox.

### Angular dependencies

What-2-Nite use the following angular dependencies:

* [ngAnimate]
* [ngRoute]
* [ngResource]

### Thanks to

I would like to thank again [themoviedb.org] for providing this API end point!

### License

MIT

**Free Software, Hell Yeah!**
[what-2-nite.herokuapp.com]:http://what-2-nite.herokuapp.com/
[themoviedb.org]:http://themoviedb.org/
[ngRoute]:https://docs.angularjs.org/api/ngRoute
[ngAnimate]:https://docs.angularjs.org/api/ngAnimate
[ngResource]:https://docs.angularjs.org/api/ngResource


text:
function proxy_path() {
	return window.cep_node.require('path')
}

module.exports = proxy_path()