text:
#include "Camera.h"

#include <ecamadvsettings.h>
#include <fbs.h>

#include "Logger.h"

CDigitalCamera* CDigitalCamera::NewL(MObserver& aObserver)
{
    CDigitalCamera* self = new(ELeave) CDigitalCamera(aObserver);
    CleanupStack::PushL(self);
    self->ConstructL();
    CleanupStack::Pop(self);

    return self;
}

CDigitalCamera::~CDigitalCamera()
{
    delete iCameraSetting;
    delete iCamera;
}

CDigitalCamera::CDigitalCamera(MObserver& aObserver)
    : iObserver(aObserver), iViewportSize(KMaxTInt, KMaxTInt)
{}

void CDigitalCamera::ConstructL()
{
    TInt cameraCount = CCamera::CamerasAvailable();

    LOGARG("Camera count is %d", cameraCount);

    // Use main camera (index 0)
    iCamera = CCamera::New2L(*this, 0, 0);
    iCameraSetting = CCamera::CCameraAdvancedSettings::NewL(*iCamera);

    TCameraInfo cameraInfo;
    iCamera->CameraInfo(cameraInfo);

    LOGTXT("Camera capture sizes supported:");

    for (TInt i = 0; i < cameraInfo.iNumImageSizesSupported; ++i)
    {
        TSize size;
        iCamera->EnumerateCaptureSizes(size, i, CCamera::EFormatExif);

        if (iViewportSize.iWidth > size.iWidth && iViewportSize.iHeight > size.iHeight)
            iViewportSize = size;

        LOGARG("Index %d Size %d x %d", i, size.iWidth, size.iHeight);
    }

    LOGARG("Using smallest viewport: %d x %d", iViewportSize.iWidth, iViewportSize.iHeight);
}

void CDigitalCamera::Start()
{
    iCamera->Reserve();
}

void CDigitalCamera::Stop()
{
    iCamera->Release();
}

void CDigitalCamera::StartFocus()
{
    iCameraSetting->SetAutoFocusType(CCamera::CCameraAdvancedSettings::EAutoFocusTypeSingle);
}

void CDigitalCamera::ReserveComplete(TInt aError)
{
    if (aError)
    {
        LOGARG("Camera reserve complete error %d", aError);
        iObserver.CameraReady(aError);
    }
    else
        iCamera->PowerOn();
}

void CDigitalCamera::PowerOnComplete(TInt aError)
{
    TCameraInfo cameraInfo;
    iCamera->CameraInfo(cameraInfo);

    if ((aError == KErrNone) &&
        (cameraInfo.iOptionsSupported & TCameraInfo::EViewFinderBitmapsSupported) &&
        (cameraInfo.iOrientation == TCameraInfo::EOrientationOutwards))
    {
        TSize requestSize(iViewportSize);

        LOGARG("Requesting viewfinder size %d x %d", requestSize.iWidth, requestSize.iHeight);
        TRAPD(error, iCamera->StartViewFinderL(CCamera::EFormatFbsBitmapColor16MU, requestSize));
        LOGARG("Obtaining viewfinder size %d x %d", requestSize.iWidth, requestSize.iHeight);

        iObserver.CameraReady(error);
    }
    else
    {
        // Either power complete error or viewfinder bitmap unsupported
        iObserver.CameraReady(KErrNotSupported);
    }
}

void CDigitalCamera::ViewFinderFrameReady(CFbsBitmap& aFrame)
{
    iObserver.CameraFrame(aFrame);
}

void CDigitalCamera::ImageReady(CFbsBitmap* /*aBitmap*/, HBufC8* /*aData*/, TInt /*aError*/)
{}

void CDigitalCamera::FrameBufferReady(MFrameBuffer* /*aFrameBuffer*/, TInt /*aError*/)
{}

void CDigitalCamera::HandleEvent(const TECAMEvent& aEvent)
{
    if (aEvent.iEventType == KUidECamEventReserveComplete)
        ReserveComplete(aEvent.iErrorCode);
    else if (aEvent.iEventType == KUidECamEventPowerOnComplete)
        PowerOnComplete(aEvent.iErrorCode);
    else if (aEvent.iEventType == KUidECamEventCameraSettingFocusRange ||
            aEvent.iEventType == KUidECamEventCameraSettingFocusRange2)
        ;
    else if (aEvent.iEventType == KUidECamEventCameraSettingAutoFocusType ||
            aEvent.iEventType == KUidECamEventCameraSettingAutoFocusType2)
        ;
    else if (aEvent.iEventType == KUidECamEventCameraSettingsOptimalFocus)
        iObserver.FocusReady(aEvent.iErrorCode);

    LOGARG("Camera event %x (error %d)", aEvent.iEventType, aEvent.iErrorCode);
}

void CDigitalCamera::ViewFinderReady(MCameraBuffer& aCameraBuffer, TInt /*aError*/)
{
    CFbsBitmap& bitmap = aCameraBuffer.BitmapL(0);
    ViewFinderFrameReady(bitmap);
    aCameraBuffer.Release();
}

void CDigitalCamera::ImageBufferReady(MCameraBuffer& /*aCameraBuffer*/, TInt /*aError*/)
{}

void CDigitalCamera::VideoBufferReady(MCameraBuffer& /*aCameraBuffer*/, TInt /*aError*/)
{}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Object methods</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="index.html" title="GObject Reference Manual">
<link rel="up" href="howto-gobject.html" title="How to define and implement a new GObject">
<link rel="prev" href="howto-gobject-destruction.html" title="Object Destruction">
<link rel="next" href="howto-gobject-chainup.html" title="Chaining up">
<meta name="generator" content="GTK-Doc V1.15 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GObject Reference Manual

Object methods

      Just as with C++, there are many different ways to define object
      methods and extend them: the following list and sections draw on
      C++ vocabulary. (Readers are expected to know basic C++ buzzwords.
      Those who have not had to write C++ code recently can refer to e.g.
      http://www.cplusplus.com/doc/tutorial/ to refresh
      their memories.)

            non-virtual public methods,

            virtual public methods and

            virtual private methods

Non-virtual public methods

        These are the simplest: you want to provide a simple method which
        can act on your object. All you need to do is to provide a function
        prototype in the header and an implementation of that prototype
        in the source file.

/* declaration in the header. */
void maman_bar_do_action (MamanBar *self, /* parameters */);

/* implementation in the source file */
void
maman_bar_do_action (MamanBar *self, /* parameters */)
{
  g_return_if_fail (MAMAN_IS_BAR (self));

  /* do stuff here. */
}

There is really nothing scary about this.

Virtual public methods

        This is the preferred way to create polymorphic GObjects. All you
        need to do is to define the common method and its class function in
        the public header, implement the common method in the source file
        and re-implement the class function in each object which inherits
        from you.

/* declaration in maman-bar.h. */
struct _MamanBarClass
{
  GObjectClass parent_class;

  /* stuff */
  void (*do_action) (MamanBar *self, /* parameters */);
};

void maman_bar_do_action (MamanBar *self, /* parameters */);

/* implementation in maman-bar.c */
void
maman_bar_do_action (MamanBar *self, /* parameters */)
{
  g_return_if_fail (MAMAN_IS_BAR (self));

  MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
}

        The code above simply redirects the do_action call to the relevant
        class function. Some users, concerned about performance, do not
        provide the maman_bar_do_action wrapper function
        and require users to dereference the class pointer themselves. This
        is not such a great idea in terms of encapsulation and makes it
        difficult to change the object's implementation afterwards, should
        this be needed.

        Other users, also concerned by performance issues, declare
        the maman_bar_do_action function inline in the
        header file. This, however, makes it difficult to change the
        object's implementation later (although easier than requiring users
        to directly dereference the class function) and is often difficult
        to write in a portable way (the inline keyword
        is part of the C99 standard but not every compiler supports it).

        In doubt, unless a user shows you hard numbers about the performance
        cost of the function call, just implement maman_bar_do_action
        in the source file.

        Please, note that it is possible for you to provide a default
        implementation for this class method in the object's
        class_init function: initialize the
        klass->do_action field to a pointer to the actual implementation.
        You can also make this class method pure virtual by initializing
        the klass->do_action field to NULL:

static void
maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
{
  /* Default implementation for the virtual method. */
}

static void
maman_bar_class_init (BarClass *klass)
{
  /* pure virtual method: mandates implementation in children. */
  klass->do_action_one = NULL;

  /* merely virtual method. */
  klass->do_action_two = maman_bar_real_do_action_two;
}

void
maman_bar_do_action_one (MamanBar *self, /* parameters */)
{
  g_return_if_fail (MAMAN_IS_BAR (self));

  MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
}

void
maman_bar_do_action_two (MamanBar *self, /* parameters */)
{
  g_return_if_fail (MAMAN_IS_BAR (self));

  MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
}

Virtual private Methods

        These are very similar to Virtual Public methods. They just don't
        have a public function to call the function directly. The header
        file contains only a declaration of the class function:

/* declaration in maman-bar.h. */
struct _MamanBarClass
{
  GObjectClass parent;

  /* stuff */
  void (* helper_do_specific_action) (MamanBar *self, /* parameters */);
};

void maman_bar_do_any_action (MamanBar *self, /* parameters */);

        These class functions are often used to delegate part of the job
        to child classes:

/* this accessor function is static: it is not exported outside of this file. */
static void
maman_bar_do_specific_action (MamanBar *self, /* parameters */)
{
  MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
}

void
maman_bar_do_any_action (MamanBar *self, /* parameters */)
{
  /* random code here */

  /*
   * Try to execute the requested action. Maybe the requested action
   * cannot be implemented here. So, we delegate its implementation
   * to the child class:
   */
  maman_bar_do_specific_action (self, /* parameters */);

  /* other random code here */
}

        Again, it is possible to provide a default implementation for this
        private virtual class function:

static void
maman_bar_class_init (MamanBarClass *klass)
{
  /* pure virtual method: mandates implementation in children. */
  klass->do_specific_action_one = NULL;

  /* merely virtual method. */
  klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
}

        Children can then implement the subclass with code such as:

static void
maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
{
  MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);

  /* implement pure virtual class function. */
  bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
}

          Generated by GTK-Doc V1.15

redpajama_set_name: RedPajamaGithub


text:
TARGET = rc_blink

include ../robotics.mk


text:
extern bool S3QueryIsAbortInProgress(void);

#endif


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "conf".
 *
 * @property integer $id
 * @property integer $user_id
 * @property string $name
 * @property string $conf
 * @property integer $level
 * @property integer $status
 * @property integer $at
 */
class DynamicConf extends \yii\db\ActiveRecord
{
    const K_ONLINE_VERSION = 'online_version';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'dynamic_conf';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'value'], 'required'],
            [['name', 'value'], 'string', 'max' => 30],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Name',
            'value' => 'value',
        ];
    }
}


text:
package multiconfig

import (
	"testing"
	"time"
)

type (
	Server struct {
		Name       string `required:"true"`
		Port       int    `default:"6060"`
		ID         int64
		Labels     []int
		Enabled    bool
		Users      []string
		Postgres   Postgres
		unexported string
		Interval   time.Duration
	}

	// Postgres holds Postgresql database related configuration
	Postgres struct {
		Enabled           bool
		Port              int      `required:"true" customRequired:"yes"`
		Hosts             []string `required:"true"`
		DBName            string   `default:"configdb"`
		AvailabilityRatio float64
		unexported        string
	}
)

type FlattenedServer struct {
	Postgres Postgres
}

type CamelCaseServer struct {
	AccessKey         string
	Normal            string
	DBName            string `default:"configdb"`
	AvailabilityRatio float64
}

var (
	testTOML = "testdata/config.toml"
	testJSON = "testdata/config.json"
)

func getDefaultServer() *Server {
	return &Server{
		Name:     "koding",
		Port:     6060,
		Enabled:  true,
		ID:       1234567890,
		Labels:   []int{123, 456},
		Users:    []string{"ankara", "istanbul"},
		Interval: 10 * time.Second,
		Postgres: Postgres{
			Enabled:           true,
			Port:              5432,
			Hosts:             []string{"192.168.2.1", "192.168.2.2", "192.168.2.3"},
			DBName:            "configdb",
			AvailabilityRatio: 8.23,
		},
	}
}

func getDefaultCamelCaseServer() *CamelCaseServer {
	return &CamelCaseServer{
		AccessKey:         "123456",
		Normal:            "normal",
		DBName:            "configdb",
		AvailabilityRatio: 8.23,
	}
}

func TestNewWithPath(t *testing.T) {
	var _ Loader = NewWithPath(testTOML)
}

func TestLoad(t *testing.T) {
	m := NewWithPath(testTOML)

	s := new(Server)
	if err := m.Load(s); err != nil {
		t.Error(err)
	}

	testStruct(t, s, getDefaultServer())
}

func TestDefaultLoader(t *testing.T) {
	m := New()

	s := new(Server)
	if err := m.Load(s); err != nil {
		t.Error(err)
	}

	if err := m.Validate(s); err != nil {
		t.Error(err)
	}
	testStruct(t, s, getDefaultServer())

	s.Name = ""
	if err := m.Validate(s); err == nil {
		t.Error("Name should be required")
	}
}

func testStruct(t *testing.T, s *Server, d *Server) {
	if s.Name != d.Name {
		t.Errorf("Name value is wrong: %s, want: %s", s.Name, d.Name)
	}

	if s.Port != d.Port {
		t.Errorf("Port value is wrong: %d, want: %d", s.Port, d.Port)
	}

	if s.Enabled != d.Enabled {
		t.Errorf("Enabled value is wrong: %t, want: %t", s.Enabled, d.Enabled)
	}

	if s.Interval != d.Interval {
		t.Errorf("Interval value is wrong: %v, want: %v", s.Interval, d.Interval)
	}

	if s.ID != d.ID {
		t.Errorf("ID value is wrong: %v, want: %v", s.ID, d.ID)
	}

	if len(s.Labels) != len(d.Labels) {
		t.Errorf("Labels value is wrong: %d, want: %d", len(s.Labels), len(d.Labels))
	} else {
		for i, label := range d.Labels {
			if s.Labels[i] != label {
				t.Errorf("Label is wrong for index: %d, label: %s, want: %s", i, s.Labels[i], label)
			}
		}
	}

	if len(s.Users) != len(d.Users) {
		t.Errorf("Users value is wrong: %d, want: %d", len(s.Users), len(d.Users))
	} else {
		for i, user := range d.Users {
			if s.Users[i] != user {
				t.Errorf("User is wrong for index: %d, user: %s, want: %s", i, s.Users[i], user)
			}
		}
	}

	// Explicitly state that Enabled should be true, no need to check
	// `x == true` infact.
	if s.Postgres.Enabled != d.Postgres.Enabled {
		t.Errorf("Postgres enabled is wrong %t, want: %t", s.Postgres.Enabled, d.Postgres.Enabled)
	}

	if s.Postgres.Port != d.Postgres.Port {
		t.Errorf("Postgres Port value is wrong: %d, want: %d", s.Postgres.Port, d.Postgres.Port)
	}

	if s.Postgres.DBName != d.Postgres.DBName {
		t.Errorf("DBName is wrong: %s, want: %s", s.Postgres.DBName, d.Postgres.DBName)
	}

	if s.Postgres.AvailabilityRatio != d.Postgres.AvailabilityRatio {
		t.Errorf("AvailabilityRatio is wrong: %f, want: %f", s.Postgres.AvailabilityRatio, d.Postgres.AvailabilityRatio)
	}

	if len(s.Postgres.Hosts) != len(d.Postgres.Hosts) {
		// do not continue testing if this fails, because others is depending on this test
		t.Fatalf("Hosts len is wrong: %v, want: %v", s.Postgres.Hosts, d.Postgres.Hosts)
	}

	for i, host := range d.Postgres.Hosts {
		if s.Postgres.Hosts[i] != host {
			t.Fatalf("Hosts number %d is wrong: %v, want: %v", i, s.Postgres.Hosts[i], host)
		}
	}
}

func testFlattenedStruct(t *testing.T, s *FlattenedServer, d *Server) {
	// Explicitly state that Enabled should be true, no need to check
	// `x == true` infact.
	if s.Postgres.Enabled != d.Postgres.Enabled {
		t.Errorf("Postgres enabled is wrong %t, want: %t", s.Postgres.Enabled, d.Postgres.Enabled)
	}

	if s.Postgres.Port != d.Postgres.Port {
		t.Errorf("Postgres Port value is wrong: %d, want: %d", s.Postgres.Port, d.Postgres.Port)
	}

	if s.Postgres.DBName != d.Postgres.DBName {
		t.Errorf("DBName is wrong: %s, want: %s", s.Postgres.DBName, d.Postgres.DBName)
	}

	if s.Postgres.AvailabilityRatio != d.Postgres.AvailabilityRatio {
		t.Errorf("AvailabilityRatio is wrong: %f, want: %f", s.Postgres.AvailabilityRatio, d.Postgres.AvailabilityRatio)
	}

	if len(s.Postgres.Hosts) != len(d.Postgres.Hosts) {
		// do not continue testing if this fails, because others is depending on this test
		t.Fatalf("Hosts len is wrong: %v, want: %v", s.Postgres.Hosts, d.Postgres.Hosts)
	}

	for i, host := range d.Postgres.Hosts {
		if s.Postgres.Hosts[i] != host {
			t.Fatalf("Hosts number %d is wrong: %v, want: %v", i, s.Postgres.Hosts[i], host)
		}
	}
}

func testCamelcaseStruct(t *testing.T, s *CamelCaseServer, d *CamelCaseServer) {
	if s.AccessKey != d.AccessKey {
		t.Errorf("AccessKey is wrong: %s, want: %s", s.AccessKey, d.AccessKey)
	}

	if s.Normal != d.Normal {
		t.Errorf("Normal is wrong: %s, want: %s", s.Normal, d.Normal)
	}

	if s.DBName != d.DBName {
		t.Errorf("DBName is wrong: %s, want: %s", s.DBName, d.DBName)
	}

	if s.AvailabilityRatio != d.AvailabilityRatio {
		t.Errorf("AvailabilityRatio is wrong: %f, want: %f", s.AvailabilityRatio, d.AvailabilityRatio)
	}

}


text:
package org.apache.qpid.protonj2.types.messaging;

import org.apache.qpid.protonj2.types.Symbol;
import org.apache.qpid.protonj2.types.UnsignedLong;
import org.apache.qpid.protonj2.types.transport.DeliveryState;

public final class Accepted implements DeliveryState, Outcome {

    public static final UnsignedLong DESCRIPTOR_CODE = UnsignedLong.valueOf(0x0000000000000024L);
    public static final Symbol DESCRIPTOR_SYMBOL = Symbol.valueOf("amqp:accepted:list");

    private static final Accepted INSTANCE = new Accepted();

    private Accepted() {
    }

    @Override
    public String toString() {
        return "Accepted{}";
    }

    public static Accepted getInstance() {
        return INSTANCE;
    }

    @Override
    public DeliveryStateType getType() {
        return DeliveryStateType.Accepted;
    }
}


text:
import { Box } from '@rocket.chat/fuselage';
import React from 'react';

import Page from '../../../components/Page';
import RawText from '../../../components/RawText';
import TextCopy from '../../../components/TextCopy';
import { useSetting } from '../../../contexts/SettingsContext';
import { useTranslation } from '../../../contexts/TranslationContext';
import Wrapper from './Wrapper';

const Installation = () => {
	const t = useTranslation();

	const siteUrl = useSetting('Site_Url')?.replace(/\/$/, '');

	const installString = `<!-- Start of Rocket.Chat Livechat Script -->
	<script type="text/javascript">
	(function(w, d, s, u) {
		w.RocketChat = function(c) { w.RocketChat._.push(c) }; w.RocketChat._ = []; w.RocketChat.url = u;
		var h = d.getElementsByTagName(s)[0], j = d.createElement(s);
		j.async = true; j.src = '${siteUrl}/livechat/rocketchat-livechat.min.js?_=201903270000';
		h.parentNode.insertBefore(j, h);
	})(window, document, 'script', '${siteUrl}/livechat');
	</script>`;

	return (
		<Page>
			<Page.Header title={t('Installation')} />
			<Page.ScrollableContentWithShadow>
				<Box maxWidth='x600' alignSelf='center'>
					<p>
						<RawText>
							{t(
								'To_install_RocketChat_Livechat_in_your_website_copy_paste_this_code_above_the_last_body_tag_on_your_site',
							)}
						</RawText>
					</p>
					<TextCopy pi='none' text={installString} wrapper={Wrapper} />
				</Box>
			</Page.ScrollableContentWithShadow>
		</Page>
	);
};

export default Installation;


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

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Almond-Chocolate Chip Biscotti-From Vicki</title>
      <categories>
        <cat>Cookies</cat>
        <cat>Bars & squa</cat></categories>
      <yield>12</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1/3</qty>
          <unit>cups</unit></amt>
        <item>Slivered almonds; chopped</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Canola oil</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>cups</unit></amt>
        <item>Flour</item></ing>
      <ing>
        <amt>
          <qty>1 3/4</qty>
          <unit>teaspoons</unit></amt>
        <item>Baking powder</item></ing>
      <ing>
        <amt>
          <qty>1/4</qty>
          <unit>teaspoons</unit></amt>
        <item>Salt</item></ing>
      <ing>
        <amt>
          <qty>3/4</qty>
          <unit>cups</unit></amt>
        <item>Sugar</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Light corn syrup</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>large</unit></amt>
        <item>Egg whites</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>teaspoons</unit></amt>
        <item>Vanilla extract</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Almond extract</item></ing>
      <ing>
        <amt>
          <qty>1/3</qty>
          <unit>cups</unit></amt>
        <item>Chocolate chips; chopped</item></ing></ingredients>
    <directions>
      <step>  1) Preheat oven to 350F. Lightly oil a large baking sheet or coat with
  non-stick cooking spray.

  2) In a medium sauce pan, combine almonds and oil. Cook, stirring
  constantly, over medium-high heat, until golden brown, 1 to 2 minutes.
  Transfer to a small bowl and let cool.

  3) In a medium bowl, whisk flour, baking soda and baking powder.

  4) In a large mixing bowl, combine almonds, sugar and corn syrup. Beat with
  an electric blender at medium speed until well blended. Add egg whites and
  vanilla and almond extracts, beat until well blended. Reduce mixer speed to
  low and blend in half the flour mixture. Add chocolate chips and remaining
  flour mixture; beat until just blended. (the dough will be crumbly)

  5) Divide dough in half. Lightly oil your hands and work surface. Shape
  each portion into a smooth 2-by-10 inch log. Place on prepared baking
  sheet, 5 inches apart. Flatten tops slightly.

  6) Bake logs 20 to 25 minutes, or until lightly browned and cracked on top.
  Transfer baking sheet to a wire rack and let cool until barely warm. Set
  logs on a cutting board. With a serrated knife, cut on the diagonal into
  3/8-inch thick slices. Lay slices flat on baking sheet.

  7) Bake biscotti for 6 minutes, or until just beginning to brown on the
  bottom. Turn over and bake for 6 to 9 minutes more. (the longer the baking
  time, the cruchier the biscotti) Transfer to wire racks and let cool
  completely.

  (Biscotti will keep in an airtight container for up to 2 weeks. Freeze for
  longer storage) Makes about 2 1/2 dozen

  NOTES : Fat 2g per cookie.

  Recipe by: Vicki S.

  Posted to TNT Recipes Digest by mail from texi <perrys@airmail.net> on Mar
  05, 1998

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


text:
/* ex: set ts=4 et: */

#ifndef IMGMIN_H
#define IMGMIN_H

/* ImageMagick */
#include <wand/MagickWand.h>

struct imgmin_options
{
    double   error_threshold,
             color_density_ratio;
    unsigned min_unique_colors,
             quality_out_max,
             quality_out_min,
             quality_in_min,
             max_steps,
             show_progress;
};

int imgmin_options_init(struct imgmin_options *opt);
void imgmin_opt_set_error_threshold(struct imgmin_options *opt, const char *arg);

MagickWand * search_quality(MagickWand *mw,
                            const char *dst,
                            const struct imgmin_options *opt);

#endif


text:
static NSString *DescriptionPlaceholder = @"Description";

static void *UploadStateContext = &UploadStateContext;
static void *UploadProgressContext = &UploadProgressContext;

@interface MetadataViewController () <UITextFieldDelegate, UITextViewDelegate>

@property (nonatomic, strong, readwrite) VIMVideoAsset *videoAsset;
@property (nonatomic, strong, readwrite) VIMVideoMetadata *videoMetadata;

@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic, weak) IBOutlet AnimatedLoadingBar *uploadStateView;
@property (nonatomic, weak) IBOutlet UILabel *uploadStateLabel;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *uploadProgressTrailingConstraint;

@property (nonatomic, weak) IBOutlet UITextField *titleTextField;
@property (nonatomic, weak) IBOutlet UITextView *descriptionTextView;

@property (nonatomic, assign) BOOL didRegisterObservers;

@end

@implementation MetadataViewController

- (void)dealloc
{
    if (self.didRegisterObservers)
    {
        [self removeObservers];
    }
}

- (instancetype)initWithVideoAsset:(VIMVideoAsset *)videoAsset
{
    self = [super init];
    if (self)
    {
        _videoAsset = videoAsset;
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSAssert(self.videoAsset != nil, @"Use designated initializer to set videoAsset");

    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.title = @"Video Metadata";

    [self setupBarButtonItem];
    [self setupProgressViews];

    self.descriptionTextView.text = DescriptionPlaceholder;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self uploadProgressDidChange];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Setup

- (void)setupBarButtonItem
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(didTapDone:)];
    [self.navigationItem setRightBarButtonItem:item];
}

- (void)setupProgressViews
{
    if (self.videoAsset.uploadState == VIMUploadState_None)
    {
        [self.containerView removeFromSuperview];
    }
    else
    {
        [self.uploadStateView startAnimating];

        [self uploadStateDidChange];

        [self addObservers];
    }
}

#pragma mark - Actions

- (void)didTapDone:(id)sender
{
    VIMVideoMetadata *videoMetadata = [[VIMVideoMetadata alloc] init];
    videoMetadata.videoTitle = self.titleTextField.text;
    videoMetadata.videoDescription = self.descriptionTextView.text;
    videoMetadata.videoPrivacy = (NSString *)VIMPrivacy_Private;
    videoMetadata.tags = @[@"surfing", @"cats"];

    self.videoMetadata = videoMetadata;

    if (self.delegate && [self.delegate respondsToSelector:@selector(metadataViewControlerDidFinish:)])
    {
        [self.delegate metadataViewControlerDidFinish:self];
    }
}

#pragma mark - Observers

- (void)addObservers
{
    [self.videoAsset addObserver:self forKeyPath:NSStringFromSelector(@selector(uploadState)) options:NSKeyValueObservingOptionNew context:UploadStateContext];

    [self.videoAsset addObserver:self forKeyPath:NSStringFromSelector(@selector(uploadProgressFraction)) options:NSKeyValueObservingOptionNew context:UploadProgressContext];

    self.didRegisterObservers = YES;
}

- (void)removeObservers
{
    @try
    {
        [self.videoAsset removeObserver:self forKeyPath:NSStringFromSelector(@selector(uploadState)) context:UploadStateContext];
    }
    @catch (NSException *exception)
    {
        NSLog(@"Exception removing observer: %@", exception);
    }

    @try
    {
        [self.videoAsset removeObserver:self forKeyPath:NSStringFromSelector(@selector(uploadProgressFraction)) context:UploadProgressContext];
    }
    @catch (NSException *exception)
    {
        NSLog(@"Exception removing observer: %@", exception);
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (context == UploadStateContext)
    {
        if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadState))])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self uploadStateDidChange];
            });
        }
    }
    else if (context == UploadProgressContext)
    {
        if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadProgressFraction))])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self uploadProgressDidChange];
            });
        }
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)uploadStateDidChange
{
    switch (self.videoAsset.uploadState)
    {
        case VIMUploadState_None:
            self.uploadStateLabel.text = @"";
            break;

        case VIMUploadState_Enqueued:
            self.uploadStateLabel.text = @"Enqueued";
            break;

        case VIMUploadState_CreatingRecord:
            self.uploadStateLabel.text = @"Creating Record";
            break;

        case VIMUploadState_UploadingFile:
            self.uploadStateLabel.text = @"Uploading File";
            break;

        case VIMUploadState_ActivatingRecord:
            self.uploadStateLabel.text = @"Activating Record";
            break;

        case VIMUploadState_AddingMetadata:
            self.uploadStateLabel.text = @"Adding Metadata";
            break;

        case VIMUploadState_Succeeded:
            self.uploadStateLabel.text = @"Succeeded";
            [self.uploadStateView stopAnimating];
            break;

        case VIMUploadState_Failed:
            self.uploadStateLabel.text = @"Failed";
            [self.uploadStateView stopAnimating];
            break;

        default:
            break;
    }

    self.uploadStateView.hidden = NO;
}

- (void)uploadProgressDidChange
{
    CGFloat constant = self.view.frame.size.width * (1.0f - self.videoAsset.uploadProgressFraction);

    self.uploadProgressTrailingConstraint.constant = constant;
}

#pragma mark - UITextField Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.descriptionTextView becomeFirstResponder];

    return YES;
}

#pragma mark - UITextView Delegate

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:DescriptionPlaceholder])
    {
        textView.text = nil;
    }
}

@end


text:
MOCK_BASE_CLASS(ClassifierMock, Classifier)
{
	MOCK_METHOD_EXT(doSetInputData, 1, void(const ClassDescriptionBase&), doSetInputData);
	MOCK_METHOD_EXT(doMakeBuilder, 0, Classifier::Builder*(void), doMakeBuilder);
	MOCK_METHOD_EXT(doRun, 0, void(void), doRun);
	MOCK_METHOD_EXT(doStop, 0, void(void), doStop);
	MOCK_METHOD_EXT(doCalculation, 1, ClassifierResults(const ObjectDescription&), doCalculation);
	MOCK_METHOD_EXT(doClassification, 1, ClassName(const ClassifierResults&), doClassification);
};

MOCK_BASE_CLASS(ClassifierBuilderMock, Classifier::Builder)
{
	MOCK_METHOD_EXT(build, 0, Classifier*(), buildDefault);
	MOCK_METHOD_EXT(build, 1, Classifier*(const XMLNode&), buildXMLNode);
	MOCK_METHOD_EXT(build, 1, Classifier*(const std::string&), buildString);
	MOCK_METHOD_EXT(dismantleToXML, 1, std::unique_ptr<XMLNode>(std::shared_ptr<Classifier>), dismantleToXML);
	MOCK_METHOD_EXT(dismantleToText, 1, std::string(std::shared_ptr<Classifier>), dismantleToText);
};


text:
% Copyright (c) Aranyx. All rights reserved.
% Licensed under the Apache License, Version 2.0 (the "License"). See LICENSE.md
% for full license information.

%% standalone script to create a database with appropriate resolution

%% new session
clc;
clear;

%% declare variable
DATABASE_PATH = 'res/oven';
WIDTH = 92;
HEIGHT = 112;

%% load database
faceDatabase = imageSet(DATABASE_PATH);

%% crop the face
for j = 1:faceDatabase.Count
    img = read(faceDatabase, j);
    img = rgb2gray(img);

    % detect face
    faceDetector = vision.CascadeObjectDetector;
    face_boundary = step(faceDetector, img);

    % crop face
    for i = 1:size(face_boundary, 1)
        bb_x = face_boundary(i,1)
        bb_y = face_boundary(i,2)
        bb_width = face_boundary(i,3)
        bb_height = face_boundary(i,4)

        new_bb_height = uint32(bb_height*(HEIGHT / WIDTH));
        y_offset = uint32((new_bb_height - bb_height) / 2);
        bb_y = bb_y - y_offset;

        face = imcrop(img, [bb_x, bb_y, bb_width, new_bb_height]);
        face = imresize(face, [HEIGHT, WIDTH]);
        imwrite(face, strcat('res/cooked/', num2str(j), num2str(i), '.png'));
    end

end


text: Personal utility to get disk size information from remote computers.


text:
``LabelPropagation``
============================================================================

.. autoclass:: ibex.sklearn.semi_supervised.LabelPropagation
    :members:
    :special-members:
    :show-inheritance:


text:
package eu.ydp.empiria.player.client.controller.variables.processor.global.transformation;

import com.google.common.base.Function;
import eu.ydp.empiria.player.client.controller.variables.objects.response.Response;
import eu.ydp.empiria.player.client.module.expression.model.ExpressionBean;

import javax.annotation.Nullable;

public class ResponseToExpressionBeanTransformation implements Function<Response, ExpressionBean> {

    @Override
    @Nullable
    public ExpressionBean apply(@Nullable Response input) {
        return input.getExpression();
    }

}


text:
namespace gc {

class BaseObject;

class RefSweep : private Chaos::UnCopyable {
  std::vector<BaseObject*> roots_;
  std::list<BaseObject*> objects_;
  std::stack<BaseObject*> inc_objects_;
  std::stack<BaseObject*> dec_objects_;
  static constexpr std::size_t kMaxObjects = 1024;

  RefSweep(void) = default;
  ~RefSweep(void) = default;

  void inc(BaseObject* ref);
  void dec(BaseObject* ref);
  void write(BaseObject* p, BaseObject* obj, bool is_first = true);
  void apply_increments(void);
  void scan_counting(void);
  void sweep_counting(void);
public:
  static RefSweep& get_instance(void);

  void collect_counting(void);
  BaseObject* put_in(int value);
  BaseObject* put_in(BaseObject* first = nullptr, BaseObject* second = nullptr);
  BaseObject* fetch_out(void);
};

}


text:
- Troubleshoot PCR.

Hypothesis: the primers do not work.

How will we know? If we run the PCR reaction with regular MyTaq Red, then if the primers work, we will get the expected 1.6 and 0.8 kb bands. If they don't work, then I will re-order new primers for amplification.

Note to self: in the future, must test the primers before going running them with expensive mutagenesis primers!

## Key Protocol Steps and Results

### PCR

**Samples:**
- Template: Victoria PB2
  - Part 1:
    - Fw primer: EM-11, 64ºC
    - Re primer: EM-10, 62ºC
    - 1586 bp product size
  - Part 2:
    - Fw primer: EM-3, 63ºC
    - Re primer: EM-2, 62ºC
    - 806 bp product size
- PCR tube samples:
  - P1: Part 1
  - P2: Part 2
  - W: Water-only control
  - T: Template-only control

**Master Mix:**

Reaction volume: 50 µL

Reagent       | 1 rxn (µL)     | MM x4.4 (µL)
--------------|----------------|-------------
MyTaq Red Mix | 25             | 110
Water         | 22             | 96.8
Fw Primer     | 1              | N/A
Re Primer     | 1              | N/A
Template      | 1              | N/A
**Total:**    | **50**         | **206.8**

Note how the primer pairs are matched up:

Sample   | Fw   | Re   | Template
---------|------|------|----------
P1       | EM11 | EM10 | VicPB2
P2       | EM3  | EM2  | VicPB2
W        | H2O  | H2O  | H2O
T        | H2O  | H2O  | VicPB2

**PCR Protocol:**

Temperature (ºC)  |  Time (min, sec)  | Cycles
------------------|-------------------|--------
95                | 1, 00             | 1
95                | 0, 15             | repeat
57                | 0, 15             | 35
72                | 1, 00             | cycles
72                | 10, 00            | 1
4                 | hold              | 1

Note: MyTaq Red uses 30s/kb. The longest PCR product is 1.6 kb, so we go for 1 min.

Let the PCR reaction go overnight.

**Gel:**

Date: 2016-08-16

30 min, 150V, 1% (w/v), EtBr.

Sample Order:
- 1 kb ladder
- P1 (part 1)
- P2 (part 2)
- W (water-only control)
- T (template-only control)

![gel](./20160816-pb2-primer-test.jpg)

As we can see from the gel, the template-only control exhibits the same banding pattern as the two samples P1 and P2. Luckily, the water-only control does not show any banding pattern.

This indicates to me that the banding pattern in the two samples comes from the template, and that there is a failed amplicon in P2 (which is supposed to be 806 bp).

I will re-order a few new primer sets to get the mutagenesis done.


text:
CustomControllers
=================

I want to create CustomControllers easy to use for iOS;


text:
Populating the database
=======================

Data install or update
----------------------

Populate your database with command::

    ./manage.py cities_light

By default, this command attempts to do the least work possible, update what is
necessary only. If you want to disable all these optimisations/skips, use --force-all.

This command is well documented, consult the help with::

    ./manage.py help cities_light

Using fixtures
--------------

Geonames.org is updated on daily basis and its full import is quite slow, so
if you want to import the same data multiple times (for example on different
servers) it is convenient to use fixtures. It is also ten times faster than
normal import. Storing these fixtures in VCS along with your project's source
code is suboptimal due to large size and unwieldy diffs, so this command is
able to fetch fixtures both from local filesystem and HTTP server.

After initial import (using cities_light command) you can dump the data into
set of fixtures using the following command::

    ./manage.py cities_light_fixtures dump

They will be stored in `DATA_DIR/fixtures/` folder in the following files::

    cities_light_country.json.bz2
    cities_light_region.json.bz2
    cities_light_city.json.bz2

To load them back use the following command::

    ./manage.py cities_light_fixtures load

By default it reads fixtures from the same `DATA_DIR/fixtures/` directory, but
you can customize their location via `settings.CITIES_LIGHT_FIXTURES_BASE_URL`
setting or `--base-url` command line argument. It should always be a folder
(end with a trailing slash). For example::

    ./manage.py cities_light_fixtures load --base-url http://example.com/fixtures/

    ./manage.py cities_light_fixtures load --base-url file:///tmp/folder/

This command attempts to cache fixtures in the `DATA_DIR/fixtures/` directory, but
you may want to force download by using `--force-all`.

.. _signals:

Signals
-------

.. automodule:: cities_light.signals
   :members:

.. automodule:: cities_light.exceptions
   :members:

Configure logging
-----------------

This command is made to be compatible with background usage like from cron, to
keep the database fresh. So it doesn't do direct output. To get output from
this command, simply configure a handler and formatter for `cities_light`
logger. For example::

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'simple': {
                'format': '%(levelname)s %(message)s'
            },
        },
        'handlers': {
            'console':{
                'level':'DEBUG',
                'class':'logging.StreamHandler',
                'formatter': 'simple'
            },
        },
        'loggers': {
            'cities_light': {
                'handlers':['console'],
                'propagate': True,
                'level':'DEBUG',
            },
            # also use this one to see SQL queries
            'django': {
                'handlers':['console'],
                'propagate': True,
                'level':'DEBUG',
            },
        }
    }


text:
package com.diffplug.spotless;

import java.util.Set;
import java.util.TreeSet;

/**
 * A policy for handling exceptions in the format.  Any exceptions will
 * halt the build except for a specifically excluded path or step.
 */
public class FormatExceptionPolicyStrict extends NoLambda.EqualityBasedOnSerialization implements FormatExceptionPolicy {
	private static final long serialVersionUID = 1L;

	private final Set<String> excludeSteps = new TreeSet<>();
	private final Set<String> excludePaths = new TreeSet<>();

	/** Adds a step name to exclude. */
	public void excludeStep(String stepName) {
		excludeSteps.add(stepName);
	}

	/** Adds a realtive pathx to exclude. */
	public void excludePath(String relativePath) {
		excludePaths.add(relativePath);
	}

	@Override
	public void handleError(Throwable e, FormatterStep step, String relativePath) {
		if (excludeSteps.contains(step.getName())) {
			FormatExceptionPolicyLegacy.warning(e, step, relativePath);
		} else {
			if (excludePaths.contains(relativePath)) {
				FormatExceptionPolicyLegacy.warning(e, step, relativePath);
			} else {
				FormatExceptionPolicyLegacy.error(e, step, relativePath);
				throw ThrowingEx.asRuntimeRethrowError(e);
			}
		}
	}
}


text:
package com.google.errorprone.bugpatterns.apidiff;

import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** {@link AndroidJdkLibsChecker}Test. */
@RunWith(JUnit4.class)
public class AndroidJdkLibsCheckerTest extends Java7ApiCheckerTest {

  private final CompilationTestHelper allowJava8Helper =
      CompilationTestHelper.newInstance(AndroidJdkLibsChecker.class, getClass())
          .setArgs(ImmutableList.of("-XepOpt:Android:Java8Libs"));

  public AndroidJdkLibsCheckerTest() {
    super(AndroidJdkLibsChecker.class);
  }

  @Test
  public void repeatedAnnotationAllowed() {
    compilationHelper
        .addSourceLines(
            "Test.java",
            "import java.lang.annotation.Repeatable;",
            "@Repeatable(Test.Container.class)",
            "public @interface Test {",
            "  public @interface Container {",
            "    Test[] value();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void typeAnnotationAllowed() {
    compilationHelper
        .addSourceLines(
            "Test.java",
            "import java.lang.annotation.Target;",
            "import java.lang.annotation.ElementType;",
            "@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})",
            "public @interface Test {",
            "}")
        .doTest();
  }

  @Test
  public void defaultMethod() {
    compilationHelper
        .addSourceLines(
            "Test.java",
            "import java.util.Map;",
            "public class Test {",
            "  abstract static class A implements Map<Object, Object> {}",
            "  abstract static class B implements Map<Object, Object> {",
            "    @Override",
            "    public Object getOrDefault(Object key, Object defaultValue) {",
            "      return null;",
            "    }",
            "  }",
            "  void f(A a, B b) {",
            "    // BUG: Diagnostic contains: java.util.Map#getOrDefault(java.lang.Object,V)"
                + " is not available in Test.A",
            "    a.getOrDefault(null, null);",
            "    b.getOrDefault(null, null); // OK: overrides getOrDefault",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void typeKind() {
    compilationHelper
        .addSourceLines(
            "Test.java",
            "public class Test {",
            "  // BUG: Diagnostic contains:",
            "  javax.lang.model.type.TypeKind tk;",
            "}")
        .doTest();
  }

  @Test
  public void stopwatchElapsed() {
    compilationHelper
        .addSourceLines(
            "Test.java",
            "import com.google.common.base.Stopwatch;",
            "import java.util.concurrent.TimeUnit;",
            "public class Test {",
            "  void o() {",
            "    // BUG: Diagnostic contains:",
            "    Stopwatch.createStarted().elapsed();",
            "    Stopwatch.createStarted().elapsed(TimeUnit.MILLISECONDS);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void allowJava8Flag_packageAllowed() {
    allowJava8Helper
        .addSourceLines(
            "Test.java",
            "import java.time.Duration;",
            "import java.util.stream.Stream;",
            "import com.google.common.base.Predicates;",
            "import java.util.Arrays;",
            "public class Test {",
            "  Duration d = Duration.ofSeconds(10);",
            "  public static void test(Stream s) {",
            "    s.forEach(i -> {});",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void allowJava8Flag_memberAllowed() {
    allowJava8Helper
        .addSourceLines(
            "Test.java",
            "import java.util.Arrays;",
            "public class Test {",
            "  public static void main(String... args) {",
            "    Arrays.stream(args);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void allowJava8Flag_memberBanned() {
    allowJava8Helper
        .addSourceLines(
            "Test.java",
            "import java.util.stream.Stream;",
            "public class Test {",
            "  public static void test(Stream s) {",
            "    // BUG: Diagnostic contains: parallel",
            "    s.parallel();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void allowJava8Flag_getTimeZone() {
    allowJava8Helper
        .addSourceLines(
            "Test.java",
            "import java.time.ZoneId;",
            "import java.util.TimeZone;",
            "public class Test {",
            "  public static void test() {",
            "    TimeZone.getTimeZone(\"a\");",
            "    TimeZone.getTimeZone(ZoneId.of(\"a\"));",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void allowJava8Flag_explicitNestedClass() {
    allowJava8Helper
        .addSourceLines(
            "Test.java",
            "import java.util.Spliterator;",
            "public abstract class Test implements Spliterator.OfInt {",
            "}")
        .doTest();
  }

  @Test
  public void forEach() {
    compilationHelper
        .addSourceLines(
            "Test.java",
            "import java.util.Collection;",
            "class T {",
            "  void f(Iterable<?> i, Collection<?> c) {",
            "    // BUG: Diagnostic contains: java.lang.Iterable#forEach",
            "    i.forEach(System.err::println);",
            "    // BUG: Diagnostic contains: java.lang.Iterable#forEach",
            "    c.forEach(System.err::println);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void allowJava8Flag_forEach() {
    allowJava8Helper
        .addSourceLines(
            "Test.java",
            "import java.util.Collection;",
            "class T {",
            "  void f(Iterable<?> i, Collection<?> c) {",
            "    i.forEach(System.err::println);",
            "    c.forEach(System.err::println);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void moduleInfo() {
    compilationHelper
        .addSourceLines(
            "module-info.java", //
            "module testmodule {",
            "  requires java.base;",
            "}")
        .doTest();
  }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\BoxesSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'title') ?>

    <?= $form->field($model, 'sort_value') ?>

        <?= Html::submitButton(Yii::t('backend', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('backend', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
import os
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext
import sys

# CUDA specific config
# nvcc is assumed to be in user's PATH
nvcc_compile_args = ['-O', '--ptxas-options=-v', '--compiler-options',
                     "'-fPIC'"]
nvcc_compile_args = os.environ.get('NVCCFLAGS', '').split() + nvcc_compile_args
cuda_libs = ['cublas']

cudamat_ext = Extension('cudamat.libcudamat',
                        sources=['cudamat/cudamat.cu',
                                 'cudamat/cudamat_kernels.cu'],
                        libraries=cuda_libs,
                        extra_compile_args=nvcc_compile_args)
cudalearn_ext = Extension('cudamat.libcudalearn',
                          sources=['cudamat/learn.cu',
                                   'cudamat/learn_kernels.cu'],
                          libraries=cuda_libs,
                          extra_compile_args=nvcc_compile_args)

class CUDA_build_ext(build_ext):
    """
    Custom build_ext command that compiles CUDA files.
    Note that all extension source files will be processed with this compiler.
    """
    def build_extensions(self):
        self.compiler.src_extensions.append('.cu')
        self.compiler.set_executable('compiler_so', 'nvcc')
        self.compiler.set_executable('linker_so', 'nvcc --shared')
        build_ext.build_extensions(self)

setup(name="cudamat",
      version="0.3",
      description="Performs linear algebra computation on the GPU via CUDA",
      ext_modules=[cudamat_ext, cudalearn_ext],
      packages=find_packages(exclude=['examples', 'test']),
      include_package_data=True,
      package_data={'cudamat': ['rnd_multipliers_32bit.txt']},
      author="Volodymyr Mnih",
      url="https://github.com/cudamat/cudamat",
      cmdclass={'build_ext': CUDA_build_ext})


text:
<?php

namespace Itsup\Api\EndPoint;

use Itsup\Api\Model\AbstractModel;
use Itsup\Api\Model\Follower;

/**
 * @author Alex VASIC <alex@quantox.com>
 */
abstract class AbstractNoteFollowerEndPoint extends AbstractNoteEndPoint
{
    /**
     * Add a note to an object using the API.
     *
     * @param AbstractModel $object
     * @param Follower      $follower
     *
     * @return bool|AbstractModel
     */
    public function addFollower(AbstractModel $object, Follower $follower)
    {
        return $this->handleRequest(
            'POST',
            $this->getRoute().'/'.$object->getId().'/follower/'.$follower->getId(),
            ['context' => $follower->getContext()]
        );
    }

    /**
     * Remove a note from an object using the API.
     *
     * @param AbstractModel $object
     * @param Follower      $follower
     *
     * @return bool|AbstractModel
     */
    public function removeFollower(AbstractModel $object, Follower $follower)
    {
        return $this->handleRequest(
            'DELETE',
            $this->getRoute().'/'.$object->getId().'/follower/'.$follower->getId()
        );
    }
}


text:
package io.material.catalog.slider;

import io.material.catalog.R;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
import com.google.android.material.slider.Slider;
import io.material.catalog.feature.DemoFragment;

/**
 * A fragment that displays a list of {@link Slider} inside a ScrollView to showcase how touch
 * events are handled.
 */
public class SliderScrollContainerDemoFragment extends DemoFragment {

  @Override
  public View onCreateDemoView(
      LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) {
    View view =
        layoutInflater.inflate(
            R.layout.cat_slider_demo_scroll, viewGroup, false /* attachToRoot */);
    LinearLayout sliderContainer = view.findViewById(R.id.sliderContainer);
    for (int i = 0; i < 50; i++) {
      sliderContainer.addView(
          new Slider(layoutInflater.getContext()),
          ViewGroup.LayoutParams.MATCH_PARENT,
          ViewGroup.LayoutParams.WRAP_CONTENT);
    }
    return view;
  }
}


text:
'use strict';

var should = require('should'),
  request = require('supertest'),
  path = require('path'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  Church = mongoose.model('Church'),
  express = require(path.resolve('./config/lib/express'));

/**
 * Globals
 */
var app,
  agent,
  credentials,
  user,
  church;

/**
 * Church routes tests
 */
describe('Church CRUD tests', function () {

  before(function (done) {
    // Get application
    app = express.init(mongoose);
    agent = request.agent(app);

    done();
  });

  beforeEach(function (done) {
    // Create user credentials
    credentials = {
      username: 'username',
      password: 'M3@n.jsI$Aw3$0m3'
    };

    // Create a new user
    user = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'test@test.com',
      username: credentials.username,
      password: credentials.password,
      provider: 'local'
    });

    // Save a user to the test db and create new Church
    user.save(function () {
      church = {
        name: 'Church name'
      };

      done();
    });
  });

  it('should be able to save a Church if logged in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Church
        agent.post('/api/churches')
          .send(church)
          .expect(200)
          .end(function (churchSaveErr, churchSaveRes) {
            // Handle Church save error
            if (churchSaveErr) {
              return done(churchSaveErr);
            }

            // Get a list of Churches
            agent.get('/api/churches')
              .end(function (churchesGetErr, churchesGetRes) {
                // Handle Churches save error
                if (churchesGetErr) {
                  return done(churchesGetErr);
                }

                // Get Churches list
                var churches = churchesGetRes.body;

                // Set assertions
                (churches[0].user._id).should.equal(userId);
                (churches[0].name).should.match('Church name');

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should not be able to save an Church if not logged in', function (done) {
    agent.post('/api/churches')
      .send(church)
      .expect(403)
      .end(function (churchSaveErr, churchSaveRes) {
        // Call the assertion callback
        done(churchSaveErr);
      });
  });

  it('should not be able to save an Church if no name is provided', function (done) {
    // Invalidate name field
    church.name = '';

    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Church
        agent.post('/api/churches')
          .send(church)
          .expect(400)
          .end(function (churchSaveErr, churchSaveRes) {
            // Set message assertion
            (churchSaveRes.body.message).should.match('Please fill Church name');

            // Handle Church save error
            done(churchSaveErr);
          });
      });
  });

  it('should be able to update an Church if signed in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Church
        agent.post('/api/churches')
          .send(church)
          .expect(200)
          .end(function (churchSaveErr, churchSaveRes) {
            // Handle Church save error
            if (churchSaveErr) {
              return done(churchSaveErr);
            }

            // Update Church name
            church.name = 'WHY YOU GOTTA BE SO MEAN?';

            // Update an existing Church
            agent.put('/api/churches/' + churchSaveRes.body._id)
              .send(church)
              .expect(200)
              .end(function (churchUpdateErr, churchUpdateRes) {
                // Handle Church update error
                if (churchUpdateErr) {
                  return done(churchUpdateErr);
                }

                // Set assertions
                (churchUpdateRes.body._id).should.equal(churchSaveRes.body._id);
                (churchUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should be able to get a list of Churches if not signed in', function (done) {
    // Create new Church model instance
    var churchObj = new Church(church);

    // Save the church
    churchObj.save(function () {
      // Request Churches
      request(app).get('/api/churches')
        .end(function (req, res) {
          // Set assertion
          res.body.should.be.instanceof(Array).and.have.lengthOf(1);

          // Call the assertion callback
          done();
        });

    });
  });

  it('should be able to get a single Church if not signed in', function (done) {
    // Create new Church model instance
    var churchObj = new Church(church);

    // Save the Church
    churchObj.save(function () {
      request(app).get('/api/churches/' + churchObj._id)
        .end(function (req, res) {
          // Set assertion
          res.body.should.be.instanceof(Object).and.have.property('name', church.name);

          // Call the assertion callback
          done();
        });
    });
  });

  it('should return proper error for single Church with an invalid Id, if not signed in', function (done) {
    // test is not a valid mongoose Id
    request(app).get('/api/churches/test')
      .end(function (req, res) {
        // Set assertion
        res.body.should.be.instanceof(Object).and.have.property('message', 'Church is invalid');

        // Call the assertion callback
        done();
      });
  });

  it('should return proper error for single Church which doesnt exist, if not signed in', function (done) {
    // This is a valid mongoose Id but a non-existent Church
    request(app).get('/api/churches/559e9cd815f80b4c256a8f41')
      .end(function (req, res) {
        // Set assertion
        res.body.should.be.instanceof(Object).and.have.property('message', 'No Church with that identifier has been found');

        // Call the assertion callback
        done();
      });
  });

  it('should be able to delete an Church if signed in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Church
        agent.post('/api/churches')
          .send(church)
          .expect(200)
          .end(function (churchSaveErr, churchSaveRes) {
            // Handle Church save error
            if (churchSaveErr) {
              return done(churchSaveErr);
            }

            // Delete an existing Church
            agent.delete('/api/churches/' + churchSaveRes.body._id)
              .send(church)
              .expect(200)
              .end(function (churchDeleteErr, churchDeleteRes) {
                // Handle church error error
                if (churchDeleteErr) {
                  return done(churchDeleteErr);
                }

                // Set assertions
                (churchDeleteRes.body._id).should.equal(churchSaveRes.body._id);

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should not be able to delete an Church if not signed in', function (done) {
    // Set Church user
    church.user = user;

    // Create new Church model instance
    var churchObj = new Church(church);

    // Save the Church
    churchObj.save(function () {
      // Try deleting Church
      request(app).delete('/api/churches/' + churchObj._id)
        .expect(403)
        .end(function (churchDeleteErr, churchDeleteRes) {
          // Set message assertion
          (churchDeleteRes.body.message).should.match('User is not authorized');

          // Handle Church error error
          done(churchDeleteErr);
        });

    });
  });

  it('should be able to get a single Church that has an orphaned user reference', function (done) {
    // Create orphan user creds
    var _creds = {
      username: 'orphan',
      password: 'M3@n.jsI$Aw3$0m3'
    };

    // Create orphan user
    var _orphan = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'orphan@test.com',
      username: _creds.username,
      password: _creds.password,
      provider: 'local'
    });

    _orphan.save(function (err, orphan) {
      // Handle save error
      if (err) {
        return done(err);
      }

      agent.post('/api/auth/signin')
        .send(_creds)
        .expect(200)
        .end(function (signinErr, signinRes) {
          // Handle signin error
          if (signinErr) {
            return done(signinErr);
          }

          // Get the userId
          var orphanId = orphan._id;

          // Save a new Church
          agent.post('/api/churches')
            .send(church)
            .expect(200)
            .end(function (churchSaveErr, churchSaveRes) {
              // Handle Church save error
              if (churchSaveErr) {
                return done(churchSaveErr);
              }

              // Set assertions on new Church
              (churchSaveRes.body.name).should.equal(church.name);
              should.exist(churchSaveRes.body.user);
              should.equal(churchSaveRes.body.user._id, orphanId);

              // force the Church to have an orphaned user reference
              orphan.remove(function () {
                // now signin with valid user
                agent.post('/api/auth/signin')
                  .send(credentials)
                  .expect(200)
                  .end(function (err, res) {
                    // Handle signin error
                    if (err) {
                      return done(err);
                    }

                    // Get the Church
                    agent.get('/api/churches/' + churchSaveRes.body._id)
                      .expect(200)
                      .end(function (churchInfoErr, churchInfoRes) {
                        // Handle Church error
                        if (churchInfoErr) {
                          return done(churchInfoErr);
                        }

                        // Set assertions
                        (churchInfoRes.body._id).should.equal(churchSaveRes.body._id);
                        (churchInfoRes.body.name).should.equal(church.name);
                        should.equal(churchInfoRes.body.user, undefined);

                        // Call the assertion callback
                        done();
                      });
                  });
              });
            });
        });
    });
  });

  afterEach(function (done) {
    User.remove().exec(function () {
      Church.remove().exec(done);
    });
  });
});


text:
import React, {PureComponent} from 'react'
import _ from 'lodash'

// Components
import {Dropdown} from '@influxdata/clockface'

// Types
import {IconFont, ComponentColor} from '@influxdata/clockface'

interface OwnProps {
  onSelectAllAccess: () => void
  onSelectReadWrite: () => void
}

type Props = OwnProps

export default class GenerateTokenDropdown extends PureComponent<Props> {
  public render() {
    return (
      <Dropdown
        testID="dropdown--gen-token"
        widthPixels={160}
        button={(active, onClick) => (
          <Dropdown.Button
            active={active}
            onClick={onClick}
            icon={IconFont.Plus}
            color={ComponentColor.Primary}
            testID="dropdown-button--gen-token"
          >
            Generate
          </Dropdown.Button>
        )}
        menu={onCollapse => (
          <Dropdown.Menu onCollapse={onCollapse}>
            {this.optionItems}
          </Dropdown.Menu>
        )}
      />
    )
  }

  private get optionItems(): JSX.Element[] {
    return [
      <Dropdown.Item
        testID="dropdown-item generate-token--read-write"
        id={this.bucketReadWriteOption}
        key={this.bucketReadWriteOption}
        value={this.bucketReadWriteOption}
        onClick={this.handleSelect}
      >
        {this.bucketReadWriteOption}
      </Dropdown.Item>,
      <Dropdown.Item
        testID="dropdown-item generate-token--all-access"
        id={this.allAccessOption}
        key={this.allAccessOption}
        value={this.allAccessOption}
        onClick={this.handleSelect}
      >
        {this.allAccessOption}
      </Dropdown.Item>,
    ]
  }

  private get bucketReadWriteOption(): string {
    return 'Read/Write Token'
  }

  private get allAccessOption(): string {
    return 'All Access Token'
  }

  private handleSelect = (selection: string): void => {
    if (selection === this.allAccessOption) {
      this.props.onSelectAllAccess()
    } else if (selection === this.bucketReadWriteOption) {
      this.props.onSelectReadWrite()
    }
  }
}