text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package io.botcoin.UI;

import io.botcoin.global.Global;
import io.botcoin.global.Settings;
import io.botcoin.strategy.Rule;
import java.awt.Font;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Dialogs;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * FXML Controller class
 *
 * @author Nicolò Paternoster <paternoster.nicolo at gmail.com>
 */

public class DashboardStatusController implements Initializable {
    @FXML //  fx:id="listActive"
    private ListView listActive;

    @FXML //  fx:id="listExecuted"
    private ListView listExecuted;

    @FXML //  fx:id="titleActive"
    private Text titleActive;

    @FXML //  fx:id="titleExecuted"
    private Text titleExecuted;

    @FXML //  fx:id="clearBtn"
    private Button clearBtn;

    public final String TITLE_ACTIVE = "Active rules (";
    public final String TITLE_EXECUTED = "Executed orders (";

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        assert clearBtn != null : "fx:id=\"clearBtn\" was not injected: check your FXML file 'DashboardStatus.fxml'.";
        assert listActive != null : "fx:id=\"listActive\" was not injected: check your FXML file 'DashboardStatus.fxml'.";
        assert listExecuted != null : "fx:id=\"listExecuted\" was not injected: check your FXML file 'DashboardStatus.fxml'.";
        assert titleActive != null : "fx:id=\"titleActive\" was not injected: check your FXML file 'DashboardStatus.fxml'.";
        assert titleExecuted != null : "fx:id=\"titleExecuted\" was not injected: check your FXML file 'DashboardStatus.fxml'.";

        updateTitles();
        listActive.setItems(Global.strategy.getActiveRulesList());
        listExecuted.setItems(Global.strategy.getExecutedRulesList());

        listActive.setCellFactory(new Callback<ListView<Rule>,
            ListCell<Rule>>() {
                @Override
                public ListCell<Rule> call(ListView<Rule> p) {
                    return new RuleActive();
                }
            }
        );

        listExecuted.setCellFactory(new Callback<ListView<Rule>,
            ListCell<Rule>>() {
                @Override
                public ListCell<Rule> call(ListView<Rule> p) {
                    return new RuleExecuted();
                }
            }
        );

        listExecuted.getSelectionModel().selectedItemProperty().addListener(
            new ChangeListener<Rule>() {
            @Override
            public void changed(ObservableValue<? extends Rule> ov, Rule t, Rule t1) {
                if(t1!=null)
                {
                    if(!t1.isSeen())
                    {
                        t1.setSeen(true);
                        Global.strategy.writeStrategyToFile(Settings.STRATEGY_PATH);
                        updateTitles();
                        updateLists();
                    }
                }
            }
        });
       }

    public void clearExecuted()
    {
          Global.strategy.clearExecuted();
          updateTitles();
          updateLists();
    }

    public void updateTitles()
    {
        titleActive.setText(TITLE_ACTIVE+Global.strategy.countActiveRules()+")");
        titleExecuted.setText(TITLE_EXECUTED+Global.strategy.countExecutedRules()+")");
    }

    public void updateLists()
    {
        //Based on a workaround tnx stackoverflow http://stackoverflow.com/a/12613774/748381
        listActive.setVisible(false);
        listActive.setVisible(true);
        listExecuted.setVisible(false);
        listExecuted.setVisible(true);
    }

     static class RuleActive extends ListCell<Rule> {
        @Override
        public void updateItem(Rule item, boolean empty) {
            super.updateItem(item, empty);
            if (item != null) {
                    setText(item.toString());
            }
        }
    }

    static class RuleExecuted extends ListCell<Rule> {
        @Override
        public void updateItem(Rule item, boolean empty) {
            super.updateItem(item, empty);
            if (item != null) {
                    setText(item.toString()+" ("+item.getExecutedTimestamp()+" - "+item.getExecutedOrderResponse()+")");
                    if(!item.isSeen())
                    {
                        setTextFill(Color.web("#287392"));

                    }
                    else
                    {
                        setTextFill(Color.web("black"));
                    }
            }
        }

        private void setTextFill(int BOLD) {
            throw new UnsupportedOperationException("Not supported yet."); //TODO change body of generated methods, choose Tools | Templates.
        }

    }

}


text:
package com.smartlogic.ontologyeditor.examples;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

import com.smartlogic.cloud.CloudException;
import com.smartlogic.ontologyeditor.OEClientException;
import com.smartlogic.ontologyeditor.OEClientReadWrite;
import com.smartlogic.ontologyeditor.beans.ChangeRecord;

public class GetChangesSince extends ModelManipulation {
	public static void main(String args[]) throws IOException, CloudException, OEClientException {
		runTests(new GetChangesSince());
	}

	@Override
	protected void alterModel(OEClientReadWrite oeClient) throws OEClientException {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = simpleDateFormat.parse("2017-06-01");

			Collection<ChangeRecord> changeRecords = oeClient.getChangesSince(date);

			for (ChangeRecord changeRecord : changeRecords) {
				System.err.println(changeRecord);
			}
		} catch (ParseException e) {
			System.err.println("Date parse exception - shouldn't happen");
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('infrastructure', '0025_auto_20210721_1540'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='infrastructuremaintenancedifficultylevel',
            options={'ordering': ('label',), 'verbose_name': 'Maintenance difficulty', 'verbose_name_plural': 'Maintenance difficulty levels'},
        ),
        migrations.AlterModelOptions(
            name='infrastructureusagedifficultylevel',
            options={'ordering': ('label',), 'verbose_name': 'Usage difficulty', 'verbose_name_plural': 'Usage difficulty levels'},
        ),
        migrations.AlterField(
            model_name='infrastructure',
            name='maintenance_difficulty',
            field=models.ForeignKey(blank=True, help_text='Danger level of infrastructure maintenance', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='infrastructures_set', to='infrastructure.infrastructuremaintenancedifficultylevel', verbose_name='Maintenance difficulty'),
        ),
        migrations.AlterField(
            model_name='infrastructure',
            name='type',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='infrastructures', to='infrastructure.infrastructuretype', verbose_name='Type'),
        ),
    ]


text:
class GitQuickStats < Formula
  desc "Simple and efficient way to access statistics in git"
  homepage "https://github.com/arzzen/git-quick-stats"
  url "https://github.com/arzzen/git-quick-stats/archive/2.1.1.tar.gz"
  sha256 "d54d97138352e92c12ae27b575beb9e67e4d0f6559ed21f28d2b2d7a84fa0c40"

  bottle :unneeded

  def install
    bin.install "git-quick-stats"
  end

  test do
    system "git", "init"
    assert_match "All branches (sorted by most recent commit)",
      shell_output("#{bin}/git-quick-stats --branches-by-date")
    assert_match /^Invalid argument/, shell_output("#{bin}/git-quick-stats command", 1)
  end
end


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.Text.DecoderExceptionFallbackBuffer
struct DecoderExceptionFallbackBuffer_t2938508785;
// System.Byte[]
struct ByteU5BU5D_t58506160;

#include "codegen/il2cpp-codegen.h"

// System.Void System.Text.DecoderExceptionFallbackBuffer::.ctor()
extern "C"  void DecoderExceptionFallbackBuffer__ctor_m1509764995 (DecoderExceptionFallbackBuffer_t2938508785 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.DecoderExceptionFallbackBuffer::get_Remaining()
extern "C"  int32_t DecoderExceptionFallbackBuffer_get_Remaining_m629320722 (DecoderExceptionFallbackBuffer_t2938508785 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean System.Text.DecoderExceptionFallbackBuffer::Fallback(System.Byte[],System.Int32)
extern "C"  bool DecoderExceptionFallbackBuffer_Fallback_m3367248051 (DecoderExceptionFallbackBuffer_t2938508785 * __this, ByteU5BU5D_t58506160* ___bytesUnknown, int32_t ___index, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Char System.Text.DecoderExceptionFallbackBuffer::GetNextChar()
extern "C"  uint16_t DecoderExceptionFallbackBuffer_GetNextChar_m3794963074 (DecoderExceptionFallbackBuffer_t2938508785 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;


text:
<?php

namespace App\Socket;

class Constants
{
    /**
     * Socket events
     */

    const SOCKET_SET_IDENTIFICATION = 'set:identification';
    const SOCKET_ACTION_SEARCH      = 'action:search';
    const SOCKET_SET_SETTINGS       = 'set:settings';

    /**
     * Settings
     */

    const SETTING_SAVE_LOCATION     = 'save:location';
    const SETTING_FORECAST_COUNT    = 'forecast:days:count';

    /**
     * Misc
     */

    const WEAHER_CACHE_NAMESPACE    = 'weather:cache';
}


text:
require 'strategies/special_characters_helper'

describe 'the `match_prev_cmd` strategy' do
  let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=match_prev_cmd'] }

  it 'suggests the last matching history entry after the previous command' do
    with_history(
      'echo what',
      'ls foo',
      'echo what',
      'ls bar',
      'ls baz',
      'echo what'
    ) do
      session.send_string('ls')
      wait_for { session.content }.to eq('ls bar')
    end
  end

  include_examples 'special characters'
end


text:
package stroom.util.shared;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.swagger.v3.oas.annotations.media.Schema;

import java.util.Objects;

@JsonPropertyOrder({"offset", "length"})
@JsonInclude(Include.NON_NULL)
@Schema(description = "The offset and length of a range of data in a sub-set of a query result set")
public final class OffsetRange {

    @Schema(description = "The start offset for this sub-set of data, where zero is the offset of the first record " +
            "in the full result set",
            example = "0",
            required = true)
    @JsonProperty
    private final Long offset;

    @Schema(description = "The length in records of the sub-set of results",
            example = "100",
            required = true)
    @JsonProperty
    private final Long length;

    public static OffsetRange zero() {
        return new OffsetRange(Long.valueOf(0), Long.valueOf(0));
    }

    public static OffsetRange of(final Long offset, final Long length) {
        return new OffsetRange(offset, length);
    }

    public OffsetRange(final Integer offset, final Integer length) {
        this.offset = offset.longValue();
        this.length = length.longValue();
    }

    @JsonCreator
    public OffsetRange(@JsonProperty("offset") final Long offset,
                       @JsonProperty("length") final Long length) {
        this.offset = offset;
        this.length = length;
    }

    public Long getOffset() {
        return offset;
    }

    public Long getLength() {
        return length;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        OffsetRange that = (OffsetRange) o;
        return Objects.equals(offset, that.offset) &&
                Objects.equals(length, that.length);
    }

    @Override
    public int hashCode() {
        return Objects.hash(offset, length);
    }

    @Override
    public String toString() {
        return "OffsetRange{" +
                "offset=" + offset +
                ", length=" + length +
                '}';
    }

    public static Builder builder() {
        return new Builder();
    }

    public Builder copy() {
        return new Builder(this);
    }

    /**
     * Builder for constructing a {@link OffsetRange}
     */
    public static final class Builder {

        private Long offset;
        private Long length;

        private Builder() {
        }

        private Builder(final OffsetRange offsetRange) {
            offset = offsetRange.offset;
            length = offsetRange.length;
        }

        /**
         * @param value The start offset for this sub-set of data,
         *              where zero is the offset of the first record in the full result set
         * @return The {@link Builder}, enabling method chaining
         */
        public Builder offset(final Long value) {
            this.offset = value;
            return this;
        }

        /**
         * @param value The length in records of the sub-set of results
         * @return The {@link Builder}, enabling method chaining
         */
        public Builder length(final Long value) {
            this.length = value;
            return this;
        }

        public OffsetRange build() {
            return new OffsetRange(offset, length);
        }
    }
}


text:
from neutron_lib.db import model_base
import sqlalchemy as sa
from sqlalchemy import orm

from neutron.db import models_v2

class PortBindingPort(model_base.BASEV2):
    port_id = sa.Column(sa.String(36),
                        sa.ForeignKey('ports.id', ondelete="CASCADE"),
                        primary_key=True)
    host = sa.Column(sa.String(255), nullable=False)
    port = orm.relationship(
        models_v2.Port,
        backref=orm.backref("portbinding",
                            lazy='joined', uselist=False,
                            cascade='delete'))


text:
class AddNoteToSeriesStatement < ActiveRecord::Migration[4.2]
  def self.up
    add_column :series_statements, :note, :text
  end

  def self.down
    remove_column :series_statements, :note
  end
end


text:
// Copyright 2019-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import "MaterialSnapshot.h"

#import "MaterialAvailability.h"
#import "MaterialChips.h"
#import "MaterialChips+Theming.h"

/**
 An MDCChipView subclass that allows the user to override the @c traitCollection property.
 */
@interface MDCChipViewWithCustomTraitCollection : MDCChipView
@property(nonatomic, strong) UITraitCollection *traitCollectionOverride;
@end

@implementation MDCChipViewWithCustomTraitCollection
- (UITraitCollection *)traitCollection {
  return self.traitCollectionOverride ?: [super traitCollection];
}
@end

/**
 A Snapshot test case for testing MDCChipViewWithCustomTraitCollection
 */
@interface MDCChipViewCustomTraitCollectionSnapshotTests : MDCSnapshotTestCase

@property(nonatomic, strong) MDCContainerScheme *containerScheme;
@property(nonatomic, strong) MDCChipViewWithCustomTraitCollection *chip;

@end

@implementation MDCChipViewCustomTraitCollectionSnapshotTests

- (void)setUp {
  [super setUp];

  // Uncomment below to recreate all the goldens (or add the following line to the specific
  // test you wish to recreate the golden for).
  //          self.recordMode = YES;

  self.chip = [[MDCChipViewWithCustomTraitCollection alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
  self.containerScheme = [[MDCContainerScheme alloc] init];
  self.containerScheme.colorScheme =
      [[MDCSemanticColorScheme alloc] initWithDefaults:MDCColorSchemeDefaultsMaterial201804];
}

- (void)tearDown {
  self.chip = nil;
  self.containerScheme = nil;

  [super tearDown];
}

#pragma mark - Helpers

- (void)generateSnapshotAndVerifyForView:(UIView *)view {
  CGSize aSize = [view sizeThatFits:CGSizeMake(300, INFINITY)];
  view.bounds = CGRectMake(0, 0, aSize.width, aSize.height);
  [view layoutIfNeeded];

  UIView *snapshotView = [view mdc_addToBackgroundView];
  [self snapshotVerifyView:snapshotView];
}

- (void)testDynamicColorSupport {
#if MDC_AVAILABLE_SDK_IOS(13_0)
  if (@available(iOS 13.0, *)) {
    // Given
    UIColor *dynamicShadowColor =
        [UIColor colorWithDynamicProvider:^(UITraitCollection *traitCollection) {
          if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
            return UIColor.magentaColor;
          } else {
            return UIColor.greenColor;
          }
        }];
    UIColor *dynamicBackgroundColor =
        [UIColor colorWithDynamicProvider:^(UITraitCollection *traitCollection) {
          if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
            return UIColor.orangeColor;
          } else {
            return UIColor.redColor;
          }
        }];
    UIColor *dynamicBorderColor =
        [UIColor colorWithDynamicProvider:^(UITraitCollection *traitCollection) {
          if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
            return UIColor.yellowColor;
          } else {
            return UIColor.brownColor;
          }
        }];

    [self.chip setBorderWidth:3 forState:UIControlStateHighlighted];
    [self.chip setShadowColor:dynamicShadowColor forState:UIControlStateHighlighted];
    [self.chip setBorderColor:dynamicBorderColor forState:UIControlStateHighlighted];
    [self.chip setBackgroundColor:dynamicBackgroundColor forState:UIControlStateHighlighted];
    self.chip.highlighted = YES;

    // When
    self.chip.traitCollectionOverride =
        [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark];

    // Then
    [self.chip sizeToFit];
    UIView *snapshotView = [self.chip mdc_addToBackgroundView];
    [self snapshotVerifyViewForIOS13:snapshotView];
  }
#endif  // MDC_AVAILABLE_SDK_IOS(13_0)
}

- (void)testPreferredFontForAXXXLContentSizeCategory {
  // Given
  [self.chip applyThemeWithScheme:self.containerScheme];
  UITraitCollection *xsTraitCollection = [UITraitCollection
      traitCollectionWithPreferredContentSizeCategory:UIContentSizeCategoryExtraSmall];
  UIFont *originalFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody
                             compatibleWithTraitCollection:xsTraitCollection];
  self.chip.traitCollectionOverride = xsTraitCollection;
  UITraitCollection *aXXXLTraitCollection =
      [UITraitCollection traitCollectionWithPreferredContentSizeCategory:
                             UIContentSizeCategoryAccessibilityExtraExtraExtraLarge];
  self.chip.titleLabel.text = @"Title";
  self.chip.titleLabel.font = originalFont;
  self.chip.titleLabel.adjustsFontForContentSizeCategory = YES;

  // When
  self.chip.traitCollectionOverride = aXXXLTraitCollection;
  // Force the Dynamic Type system to update the button's font.
  [self.chip drawViewHierarchyInRect:self.chip.bounds afterScreenUpdates:YES];

  // Then
  [self generateSnapshotAndVerifyForView:self.chip];
}

- (void)testPreferredFontForXSContentSizeCategory {
  // Given
  [self.chip applyThemeWithScheme:self.containerScheme];
  UITraitCollection *aXXXLTraitCollection =
      [UITraitCollection traitCollectionWithPreferredContentSizeCategory:
                             UIContentSizeCategoryAccessibilityExtraExtraExtraLarge];
  UIFont *originalFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody
                             compatibleWithTraitCollection:aXXXLTraitCollection];
  self.chip.traitCollectionOverride = aXXXLTraitCollection;
  self.chip.titleLabel.text = @"Title";
  self.chip.titleLabel.font = originalFont;
  self.chip.titleLabel.adjustsFontForContentSizeCategory = YES;

  // When
  UITraitCollection *xsTraitCollection = [UITraitCollection
      traitCollectionWithPreferredContentSizeCategory:UIContentSizeCategoryExtraSmall];

  self.chip.traitCollectionOverride = xsTraitCollection;
  // Force the Dynamic Type system to update the button's font.
  [self.chip drawViewHierarchyInRect:self.chip.bounds afterScreenUpdates:YES];

  // Then
  [self generateSnapshotAndVerifyForView:self.chip];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate
        android:fromDegrees="-90"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:toDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="1000"
        android:startOffset="0"
        />

    <scale
        android:fromXScale="0.7"
        android:fromYScale="0.7"
        android:toXScale="1"
        android:toYScale="1"
        android:duration="500"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:startOffset="0"
        />
</set>


text:
@interface IDTSplitViewController : UISplitViewController

@end


text:
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link href="style.css" rel="stylesheet">
    <title>Critical Path: Script Async</title>

Hello web performance students!


text:
<?php
class ESmartyViewRender extends CApplicationComponent implements IViewRenderer{

	public $fileExtension='.tpl';
	public $filePermission=0755;
	private $smarty;

	function init()	{
		Yii::import('application.vendors.smarty.libs.*');
		spl_autoload_unregister(array('YiiBase','autoload'));
		require_once('Smarty.class.php');
		spl_autoload_register(array('YiiBase','autoload'));
		$this->smarty = new Smarty();
		$this->smarty->template_dir = '';
		$compileDir = Yii::app()->getRuntimePath().'/smarty/compiled/';
		if(!file_exists($compileDir)){
			mkdir($compileDir, $this->filePermission, true);
		}
		$this->smarty->compile_dir = $compileDir;
		$this->smarty->assign('Yii', Yii::app());
	}
	/**
	 * Renders a view file.
	 * This method is required by {@link IViewRenderer}.
	 * @param CBaseController the controller or widget who is
	 rendering the view file.
	 * @param string the view file path
	 * @param mixed the data to be passed to the view
	 * @param boolean whether the rendering result should be
	 returned
	 * @return mixed the rendering result, or null if the rendering
	 result is not needed.
	 */
	public function renderFile($context,$sourceFile,$data,$return) {
		// current controller properties will be accessible as {this.property}
		$data['this'] = $context;
		if(!is_file($sourceFile) || ($file=realpath($sourceFile))===false )
			throw new CException(Yii::t('ext','View file"$sourceFile" does not exist.', array('{file}'=>$sourceFile)));

		$this->smarty->assign($data);
		if($return)
			return $this->smarty->fetch($sourceFile);
		else
			$this->smarty->display($sourceFile);
		}
}?>


text:
`Home <index.html>`__ OpenStack Ansible Installation Guide

Utility container
-----------------

The utility container provides a space where miscellaneous tools and
other software can be installed. Tools and objects can be placed in a
utility container if they do not require a dedicated container or if it
is impractical to create a new container for a single tool or object.
Utility containers can also be used when tools cannot be installed
directly onto a host.

For example, the tempest playbooks are installed on the utility
container since tempest testing does not need a container of its own.
For another example of using the utility container, see `the section
called "Verifying OpenStack
operation" <install-openstack-verify.html>`__.

--------------

.. include:: navigation.txt


text:
/*
 * Theme Name: AngularJS Theme
 * Theme URI:
 * Author:
 * Author URI:
 * Description: AngularJS Theme
 * Version: 0.1
 */


text:
module Curryrs.Types (
    module Foreign.C.Types
  , module Foreign.C.String
  , Chr
  , Str
  , U8
  , U16
  , U32
  , U64
  , I8
  , I16
  , I32
  , I64
  , F32
  , F64
  , Boolean
  ) where

import Data.Int
import Data.Word
import Foreign.C.Types
import Foreign.C.String

-- We are only defining types that map to Rust types here
-- We don't need the full array of C types in Rust

-- |
-- Used to represent Char in both languages
type Chr = CChar

-- |
-- Used to represent Strings in both languages
type Str = CString

-- |
-- Used to represent 8 bit unsigned numbers in both languages
type U8  = Word8

-- |
-- Used to represent 16 bit unsigned numbers in both languages
type U16 = Word16

-- |
-- Used to represent 32 bit unsigned numbers in both languages
type U32 = Word32

-- |
-- Used to represent 64 bit unsigned numbers in both languages
type U64 = Word64

-- |
-- Used to represent 8 bit signed numbers in both languages
type I8  = Int8

-- |
-- Used to represent 16 bit signed numbers in both languages
type I16 = Int16

-- |
-- Used to represent 32 bit signed numbers in both languages
type I32 = Int32

-- |
-- Used to represent 64 bit signed numbers in both languages
type I64 = Int64

-- |
-- Used to represent 32 bit floating point numbers in both languages
type F32 = CFloat

-- |
-- Used to represent 64 bit floating point numbers in both languages
type F64 = CDouble

-- |
-- Used to represent Booleans in both languages
type Boolean = Word8


text:
<?php

//validasi belum dikerjakan

Class Student extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Student_Model');
        $this->load->library('form_validation');//SAAT DIANDROID TIDAK DIGUNAKAN, UBAH/HAPUS BEBERAPA CODE INI
    }

    public function index() {
        $param['data'] = $this->Student_Model->getAll()->result_array();
        $param['asal'] = "data";
        //buat include template
        $this->load->view('include/header', $param);
        $this->load->view('tabel-student', $param);
        $this->load->view('include/footer');
        //--------------------------------------------
    }

    function input() {
        $this->form_validation->set_rules('nama_siswa', 'Nama Siswa', 'required');
        $this->form_validation->set_rules('no_ponsel_siswa', 'Nomor Ponsel', 'required');
        $this->form_validation->set_rules('jenis_kelamin_siswa', 'Jenis Kelamin', 'required');
        $this->form_validation->set_rules('alamat_siswa', 'Alamat', 'required');
        $this->form_validation->set_rules('email_siswa', 'Email', 'required');
        $this->form_validation->set_rules('password_siswa', 'Password', 'required');

        if ($input = $this->input->post()) {
            $nama_siswa = $input['nama_siswa'];
            $no_identitas_siswa = $input['no_identitas_siswa'];
            $jenis_kelamin_siswa = $input['jenis_kelamin_siswa'];
            $tempat_lahir_siswa = $input['tempat_lahir_siswa'];
            $tanggal_lahir_siswa = $input['tanggal_lahir_siswa'];
            $no_ponsel_siswa = $input['no_ponsel_siswa'];
            $sekolah_siswa = $input['sekolah_siswa'];
            $email_siswa = $input['email_siswa'];
            $password_siswa = $input['password_siswa'];

            $latitude_siswa = $input['latitude_siswa'];
            $longitude_siswa = $input['longitude_siswa'];
            $alamat_siswa = $input['alamat_siswa'];
            $foto_siswa = file_get_contents($_FILES["foto_siswa"]["tmp_name"]);

            $data = array(
                'nama_siswa' => $nama_siswa,
                'no_identitas_siswa' => $no_identitas_siswa,
                'jenis_kelamin_siswa' => $jenis_kelamin_siswa,
                'tempat_lahir_siswa' => $tempat_lahir_siswa,
                'tanggal_lahir_siswa' => date("d-m-Y", strtotime($tanggal_lahir_siswa)),
                'no_ponsel_siswa' => $no_ponsel_siswa,
                'sekolah_siswa' => $sekolah_siswa,
                'email_siswa' => $email_siswa,
                'password_siswa' => $password_siswa,
                'latitude_siswa' => $latitude_siswa,
                'longitude_siswa' => $longitude_siswa,
                'alamat_siswa' => $alamat_siswa,
                'foto_siswa' => $foto_siswa
            );
            if ($this->form_validation->run() == TRUE) {
                $result = $this->Student_Model->insert($data);
                echo json_encode($result);
                redirect('/admin/student');
            }
        }
        $this->load->view('include/header');
        $this->load->view('detail-student');
        $this->load->view('include/footer');
           //-------------UNTUK ANDROID -------------------------------------------
        //ANDROID KIRIM REQUEST BUAT MENTOR BARU
        //1. TERIMA DAN DECODE DATA-DATA ANDROID
        //2. MASUKIN KE DATABASE
        //3. KIRIM RESPONSE KE ANDROID
        //----------------------------------------------------------------------
    }

    function edit($ID) {
        $this->form_validation->set_rules('nama_siswa', 'Nama Siswa', 'required');
        $this->form_validation->set_rules('no_ponsel_siswa', 'Nomor Ponsel', 'required');
        $this->form_validation->set_rules('jenis_kelamin_siswa', 'Jenis Kelamin', 'required');
        $this->form_validation->set_rules('alamat_siswa', 'Alamat', 'required');
        $this->form_validation->set_rules('email_siswa', 'Email', 'required');
        $this->form_validation->set_rules('password_siswa', 'Password', 'required');

        if ($input = $this->input->post()) {

            $nama_siswa = $input['nama_siswa'];
            $no_identitas_siswa = $input['no_identitas_siswa'];
            $jenis_kelamin_siswa = $input['jenis_kelamin_siswa'];
            $tempat_lahir_siswa = $input['tempat_lahir_siswa'];
            $tanggal_lahir_siswa = $input['tanggal_lahir_siswa'];
            $no_ponsel_siswa = $input['no_ponsel_siswa'];
            $sekolah_siswa = $input['sekolah_siswa'];
            $email_siswa = $input['email_siswa'];
            $password_siswa = $input['password_siswa'];

            $latitude_siswa = $input['latitude_siswa'];
            $longitude_siswa = $input['longitude_siswa'];
            $alamat_siswa = $input['alamat_siswa'];
            if (file_get_contents($_FILES["foto_mentor"]["tmp_name"]) == NULL) {
                $data = array(
                    'nama_siswa' => $nama_siswa,
                    'no_identitas_siswa' => $no_identitas_siswa,
                    'jenis_kelamin_siswa' => $jenis_kelamin_siswa,
                    'tempat_lahir_siswa' => $tempat_lahir_siswa,
                    'tanggal_lahir_siswa' => $tanggal_lahir_siswa,
                    'no_ponsel_siswa' => $no_ponsel_siswa,
                    'sekolah_siswa' => $sekolah_siswa,
                    'email_siswa' => $email_siswa,
                    'password_siswa' => $password_siswa,
                    'latitude_siswa' => $latitude_siswa,
                    'longitude_siswa' => $longitude_siswa,
                    'alamat_siswa' => $alamat_siswa,
                );
            } else {
                $foto_siswa = file_get_contents($_FILES["foto_siswa"]["tmp_name"]);
                $data = array(
                    'nama_siswa' => $nama_siswa,
                    'no_identitas_siswa' => $no_identitas_siswa,
                    'jenis_kelamin_siswa' => $jenis_kelamin_siswa,
                    'tempat_lahir_siswa' => $tempat_lahir_siswa,
                    'tanggal_lahir_siswa' => $tanggal_lahir_siswa,
                    'no_ponsel_siswa' => $no_ponsel_siswa,
                    'sekolah_siswa' => $sekolah_siswa,
                    'email_siswa' => $email_siswa,
                    'password_siswa' => $password_siswa,
                    'latitude_siswa' => $latitude_siswa,
                    'longitude_siswa' => $longitude_siswa,
                    'alamat_siswa' => $alamat_siswa,
                    'foto_siswa' => $foto_siswa
                );
            }
            if ($this->form_validation->run() == TRUE) {
                $result = $this->Student_Model->edit($ID, $data);
                echo json_encode($result);
                redirect('/homesiswa/view/' . $ID);
            }
        }
        $param['data'] = $this->Student_Model->getById($ID)->row_array();
        $this->load->view('include/header');
        $this->load->view('detail-student', $param);
        $this->load->view('include/footer');
        //-------------UNTUK ANDROID -------------------------------------------
        //ANDROID KIRIM REQUEST BUAT EDIT SISWA
        //1. KIRIM DATA-DATA SISWA KE ANDROID SESUAI ID REQUEST
        //2. TERIMA DAN DECODE DATA-DATA ANDROID
        //3. MASUKIN KE DATABASE
        //4. KIRIM RESPONSE KE ANDROID
        //----------------------------------------------------------------------
    }

    function delete($ID) {
        $result = $this->Student_Model->delete($ID);
        echo json_encode($result);
        redirect('/admin/student');
    }

}


text:
package org.apache.hadoop.yarn.server.timelineservice.reader;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.server.timelineservice.TimelineContext;

/**
 * Encapsulates fields necessary to make a query in timeline reader.
 */
@Private
@Unstable
public class TimelineReaderContext extends TimelineContext {

  private String entityType;
  private String entityId;
  private Long entityIdPrefix;
  private String doAsUser;
  public TimelineReaderContext(String clusterId, String userId, String flowName,
      Long flowRunId, String appId, String entityType, String entityId) {
    super(clusterId, userId, flowName, flowRunId, appId);
    this.entityType = entityType;
    this.entityId = entityId;
  }

  public TimelineReaderContext(String clusterId, String userId, String flowName,
      Long flowRunId, String appId, String entityType, Long entityIdPrefix,
      String entityId) {
    this(clusterId, userId, flowName, flowRunId, appId, entityType, entityId);
    this.entityIdPrefix = entityIdPrefix;
  }

  public TimelineReaderContext(String clusterId, String userId, String flowName,
      Long flowRunId, String appId, String entityType, Long entityIdPrefix,
      String entityId, String doasUser) {
    this(clusterId, userId, flowName, flowRunId, appId, entityType, entityId);
    this.entityIdPrefix = entityIdPrefix;
    this.doAsUser = doasUser;
  }

  public TimelineReaderContext(TimelineReaderContext other) {
    this(other.getClusterId(), other.getUserId(), other.getFlowName(),
        other.getFlowRunId(), other.getAppId(), other.getEntityType(),
        other.getEntityIdPrefix(), other.getEntityId(), other.getDoAsUser());
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = super.hashCode();
    result = prime * result
        + ((entityIdPrefix == null) ? 0 : entityIdPrefix.hashCode());
    result = prime * result + ((entityId == null) ? 0 : entityId.hashCode());
    result =
        prime * result + ((entityType == null) ? 0 : entityType.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (!super.equals(obj)) {
      return false;
    }
    TimelineReaderContext other = (TimelineReaderContext) obj;
    if (entityId == null) {
      if (other.entityId != null) {
        return false;
      }
    } else if (!entityId.equals(other.entityId)) {
      return false;
    }
    if (entityType == null) {
      if (other.entityType != null) {
        return false;
      }
    } else if (!entityType.equals(other.entityType)) {
      return false;
    }
    return true;
  }

  public String getEntityType() {
    return entityType;
  }

  public void setEntityType(String type) {
    this.entityType = type;
  }

  public String getEntityId() {
    return entityId;
  }

  public void setEntityId(String id) {
    this.entityId = id;
  }

  public Long getEntityIdPrefix() {
    return entityIdPrefix;
  }

  public void setEntityIdPrefix(Long entityIdPrefix) {
    this.entityIdPrefix = entityIdPrefix;
  }

  public String getDoAsUser() {
    return doAsUser;
  }

  public void setDoAsUser(String doAsUser) {
    this.doAsUser = doAsUser;
  }
}


text:
<?php namespace Ixudra\Authentication\Services\Form;

use Ixudra\Core\Services\Form\BaseFormHelper;
use Ixudra\Authentication\Repositories\Eloquent\EloquentUserRepository;

use App;

class UserFormHelper extends BaseFormHelper {

    protected $repository;

    public function __construct(EloquentUserRepository $userRepository)
    {
        $this->repository = $userRepository;
    }

    public function getSuggestionsForAutoComplete($query)
    {
        $models = $this->repository->search( array( 'query' => $query ) );

        return $this->convertToAutoComplete( $models );
    }

    protected function convertToSelectList($includeNull, $models)
    {
        $results = array();
        if( $includeNull ) {
            $results[ 0 ] = '';
        }

        foreach( $models as $model ) {
            $results[ $model->id ] = $model->present()->fullName;
        }

        return $results;
    }

    protected function convertToAutoComplete($models)
    {
        $results = array();
        foreach( $models as $model ) {
            $results[] = array(
                'data'          => $model->id,
                'value'         => $model->present()->fullName
            );
        }

        return $results;
    }

}


text:
package uk.ac.cam.cl.rendezvous;

import java.io.IOException;
import java.net.HttpURLConnection;

import org.apache.commons.io.IOUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

final class RendezvousResponse {

	private static final Gson GSON = new GsonBuilder()
			.registerTypeAdapter(byte[].class, new ByteArrayGsonSerializer())
			.disableHtmlEscaping()
			.create();

	// Response codes
	public static final int CLOSED = -1;
	public static final int OK = 0;
	public static final int TIMED_OUT = 2;

	public static RendezvousResponse fromConnection(HttpURLConnection connection)
			throws IOException {
		// Check response code
		if (connection.getResponseCode() != 200) {
			throw new IOException("response code was not 200 OK");
		}
		// Check content is non-empty
		if (connection.getContentLength() <= 0) {
			throw new IOException("response was empty response");
		}
		// TODO replace these checks with guava preconditions methods?

		// Read bytes
		byte[] responseBytes = new byte[connection.getContentLength()];
		IOUtils.readFully(connection.getInputStream(), responseBytes);

		return GSON.fromJson(new String(responseBytes, "UTF-8"), RendezvousResponse.class);
	}

	private RendezvousResponse() {
		super();
	}

	public int code;
	public String status;
	public String message;
	public byte[] data;

	@Override
	public String toString() {
		return GSON.toJson(this);
	}
}


text:
@protocol WXApiManagerDelegate <NSObject>

@optional

- (void)managerDidRecvShowMessageReq:(ShowMessageFromWXReq *)request;

- (void)managerDidRecvLaunchFromWXReq:(LaunchFromWXReq *)request;

- (void)managerDidRecvMessageResponse:(SendMessageToWXResp *)response;

- (void)managerDidRecvAuthResponse:(SendAuthResp *)response;

- (void)managerDidRecvAddCardResponse:(AddCardToWXCardPackageResp *)response;

- (void)managerDidRecvChooseCardResponse:(WXChooseCardResp *)response;

- (void)managerDidRecvChooseInvoiceResponse:(WXChooseInvoiceResp *)response;

- (void)managerDidRecvSubscribeMsgResponse:(WXSubscribeMsgResp *)response;

- (void)managerDidRecvLaunchMiniProgram:(WXLaunchMiniProgramResp *)response;

- (void)managerDidRecvInvoiceAuthInsertResponse:(WXInvoiceAuthInsertResp *)response;

- (void)managerDidRecvNonTaxpayResponse:(WXNontaxPayResp *)response;

- (void)managerDidRecvPayInsuranceResponse:(WXPayInsuranceResp *)response;
@end

@interface WXApiManager : NSObject<WXApiDelegate>

@property (nonatomic, assign) id<WXApiManagerDelegate> delegate;

+ (instancetype)sharedManager;

@end


text:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 *= require_tree .
 */
* {
  margin: 0;
  font-family: 'Open Sans', sans-serif;
  border: none;
}

body {
  background-color: #EAEAEA;
  margin-bottom: 10%;
}

a {
  color: #666666;
  text-decoration: none;
  transition:color .1s ease-out;
}

a:hover {
  color:rgb(188, 0, 0);
}

#errors {
  color: red;
  padding-top: 2em;
  list-style: none;
  text-align: center;
  border-bottom: none;
}
#errors > * {
  list-style: none;
  list-style-type: none;
  border:none;
}


text:
using CatLib.Debugger.Log;
using System;

namespace CatLib.Debugger.WebLog.LogHandler
{
    /// <summary>
    /// Web日志处理器
    /// </summary>
    public class WebLogHandler : ILogHandler
    {
        /// <summary>
        /// 日志存储
        /// </summary>
        private readonly LogStore store;

        /// <summary>
        /// 网络日志处理器
        /// </summary>
        /// <param name="store"></param>
        public WebLogHandler(LogStore store)
        {
            Guard.Requires<ArgumentNullException>(store != null);
            this.store = store;
        }

        /// <summary>
        /// 日志处理器
        /// </summary>
        /// <param name="log">日志条目</param>
        public void Handler(ILogEntry log)
        {
            store.Log(log);
        }
    }
}


text:
require_relative "../test_helper"

module SmartAnswer
  class NodeTest < ActiveSupport::TestCase
    setup do
      @flow = Flow.build
      @node = Node.new(@flow, "node-name")
      @load_path = FlowRegistry.instance.load_path
    end

    test "#template_directory returns the path to the templates based on the class name" do
      @flow.class.stubs(:name).returns("MyFlow")

      expected_directory = Pathname.new(@load_path).join("my_flow")
      assert_equal expected_directory, @node.template_directory
    end

    test "#template_name can set a specific template name" do
      question = Question::Base.new(@flow, :how_much?)
      question.template_name("custom_template_file")
      assert_equal "custom_template_file", question.template_name
    end

    test "#template_name defaults to returning the filesystem_friendly_name" do
      question = Question::Base.new(@flow, :how_much?)
      assert_equal question.filesystem_friendly_name, question.template_name
    end

    test "#filesystem_friendly_name returns name without trailing question mark" do
      question = Question::Base.new(@flow, :how_much?)
      assert_equal "how_much", question.filesystem_friendly_name
    end

    test "#slug returns name without trailing question mark and underscores replaced with dashes" do
      question = Question::Base.new(@flow, :how_much?)
      assert_equal "how-much", question.slug
    end

    test "#view_template sets the view template path" do
      node = Node.new(@flow, "node-name") { view_template "path/to/view" }
      assert_equal "path/to/view", node.view_template_path
    end

    test "#view_template_path return nil is not set" do
      node = Node.new(@flow, "node-name")
      assert_nil node.view_template_path
    end

    test "#presenter returns a presenter object" do
      node = Node.new(@flow, "node-name")
      assert_instance_of Node::PRESENTER_CLASS, node.presenter
    end

    context "#next_node" do
      should "raise exception if next_node is called without a block" do
        e = assert_raises(ArgumentError) do
          @node.next_node
        end
        assert_equal "You must specify a block", e.message
      end

      should "raise exception if next_node is invoked multiple times" do
        e = assert_raises do
          @node.next_node { outcome :one }
          @node.next_node { outcome :two }
        end
        assert_equal "Multiple calls to next_node are not allowed", e.message
      end
    end

    context "#permitted_next_nodes" do
      should "return nodes returned via syntactic sugar methods" do
        @node.next_node do |response|
          if response == "yes"
            outcome :done
          else
            question :another_question
          end
        end
        assert_equal %i[done another_question], @node.permitted_next_nodes
      end

      should "not return nodes not returned via syntactic sugar methods" do
        @node.next_node do |response|
          if response == "yes"
            outcome :done
          else
            :another_question
          end
        end
        assert @node.permitted_next_nodes.include?(:done)
        assert_not @node.permitted_next_nodes.include?(:another_question)
      end

      should "not return duplicate permitted next nodes" do
        @node.next_node { outcome :done }
        assert_equal [:done], @node.permitted_next_nodes
      end
    end

    context "#setup" do
      should "be a method" do
        assert_nil @node.setup(nil)
      end
    end

    context "#transition" do
      should "copy values from initial state to new state" do
        @node.next_node { outcome :done }
        initial_state = SmartAnswer::State.new(@node.name)
        initial_state.something_else = "Carried over"
        new_state = @node.transition(initial_state, nil)
        assert_equal "Carried over", new_state.something_else
      end

      should "set current_node_name to value returned from next_node_for" do
        @node.next_node { outcome :done }
        initial_state = SmartAnswer::State.new(@node.name)
        @node.stubs(:next_node_for).returns(:done)
        new_state = @node.transition(initial_state, nil)
        assert_equal :done, new_state.current_node_name
      end

      should "set current_node_name to result of calling next_node block" do
        @node.next_node { outcome :done }
        initial_state = SmartAnswer::State.new(@node.name)
        new_state = @node.transition(initial_state, nil)
        assert_equal :done, new_state.current_node_name
      end

      should "make state available to code in next_node block" do
        @node.next_node do
          colour == "red" ? outcome(:was_red) : outcome(:wasnt_red)
        end
        initial_state = SmartAnswer::State.new(@node.name)
        initial_state.colour = "red"
        new_state = @node.transition(initial_state, nil)
        assert_equal :was_red, new_state.current_node_name
      end
    end

    context "#next_node_for" do
      should "raise an exception if next_node does not return key via question or outcome method" do
        @node.next_node do
          outcome :another_outcome
          :not_allowed_next_node
        end
        state = SmartAnswer::State.new(@node.name)

        expected_message = "Next node (not_allowed_next_node) not returned via question or outcome method"
        exception = assert_raises do
          @node.next_node_for(state, "response")
        end
        assert_equal expected_message, exception.message
      end

      should "raise an exception if next_node does not return a node key" do
        @node.next_node do
          skip = false
          outcome :skipped if skip
        end
        initial_state = SmartAnswer::State.new(@node.name)
        initial_state.accepted_responses = { question_1: "red" }
        error = assert_raises(SmartAnswer::Node::NextNodeUndefined) do
          @node.next_node_for(initial_state, nil)
        end
        expected_message = %(Next node undefined. Node: #{@node.name}.)
        assert_equal expected_message, error.message
      end

      should "raise an exception if next_node was not called for question" do
        initial_state = SmartAnswer::State.new(@node.name)
        assert_raises(SmartAnswer::Node::NextNodeUndefined) do
          @node.next_node_for(initial_state, nil)
        end
      end

      should "allow calls to #question syntactic sugar method" do
        @node.next_node { question :another_question }
        state = SmartAnswer::State.new(@node.name)
        next_node = @node.next_node_for(state, nil)
        assert_equal :another_question, next_node
      end

      should "should allow calls to #outcome syntactic sugar method" do
        @node.next_node { outcome :done }
        state = SmartAnswer::State.new(@node.name)
        next_node = @node.next_node_for(state, nil)
        assert_equal :done, next_node
      end
    end

    context "#redact" do
      should "return true if question is redacted" do
        assert_equal true, @node.redact(true)
      end

      should "return false if question is not redacted" do
        assert_equal false, @node.redact
      end
    end
  end
end


text:
namespace media {
class VideoCaptureDeviceMac;
}

@class CrAVCaptureDevice;
@class CrAVCaptureSession;
@class CrAVCaptureVideoDataOutput;
@class CrAVCaptureStillImageOutput;

// Class used by VideoCaptureDeviceMac (VCDM) for video and image capture using
// AVFoundation API. This class lives inside the thread created by its owner
// VCDM.
//
//  * Clients (VCDM) should call +deviceNames to fetch the list of devices
//    available in the system; this method returns the list of device names that
//    have to be used with -setCaptureDevice:.
//  * Previous to any use, clients (VCDM) must call -initWithFrameReceiver: to
//    initialise an object of this class and register a |frameReceiver_|.
//  * Frame receiver registration or removal can also happen via explicit call
//    to -setFrameReceiver:. Re-registrations are safe and allowed, even during
//    capture using this method.
//  * Method -setCaptureDevice: must be called at least once with a device
//    identifier from +deviceNames. Creates all the necessary AVFoundation
//    objects on first call; it connects them ready for capture every time.
//    This method should not be called during capture (i.e. between
//    -startCapture and -stopCapture).
//  * -setCaptureWidth:height:frameRate: is called if a resolution or frame rate
//    different than the by default one set by -setCaptureDevice: is needed.
//    This method should not be called during capture. This method must be
//    called after -setCaptureDevice:.
//  * -startCapture registers the notification listeners and starts the
//    capture. The capture can be stop using -stopCapture. The capture can be
//    restarted and restoped multiple times, reconfiguring or not the device in
//    between.
//  * -setCaptureDevice can be called with a |nil| value, case in which it stops
//    the capture and disconnects the library objects. This step is not
//    necessary.
//  * Deallocation of the library objects happens gracefully on destruction of
//    the VideoCaptureDeviceAVFoundation object.
//
//
@interface VideoCaptureDeviceAVFoundation
    : NSObject<CrAVCaptureVideoDataOutputSampleBufferDelegate> {
 @private
  // The following attributes are set via -setCaptureHeight:width:frameRate:.
  int frameWidth_;
  int frameHeight_;
  float frameRate_;

  base::Lock lock_;  // Protects concurrent setting and using |frameReceiver_|.
  media::VideoCaptureDeviceMac* frameReceiver_;  // weak.

  base::scoped_nsobject<CrAVCaptureSession> captureSession_;

  // |captureDevice_| is an object coming from AVFoundation, used only to be
  // plugged in |captureDeviceInput_| and to query for session preset support.
  CrAVCaptureDevice* captureDevice_;
  // |captureDeviceInput_| is owned by |captureSession_|.
  CrAVCaptureDeviceInput* captureDeviceInput_;
  base::scoped_nsobject<CrAVCaptureVideoDataOutput> captureVideoDataOutput_;

  // An AVDataOutput specialized for taking pictures out of |captureSession_|.
  base::scoped_nsobject<CrAVCaptureStillImageOutput> stillImageOutput_;

  base::ThreadChecker main_thread_checker_;
}

// Returns a dictionary of capture devices with friendly name and unique id.
+ (NSDictionary*)deviceNames;

// Retrieve the capture supported formats for a given device |descriptor|.
+ (void)getDevice:(const media::VideoCaptureDeviceDescriptor&)descriptor
    supportedFormats:(media::VideoCaptureFormats*)formats;

// Initializes the instance and the underlying capture session and registers the
// frame receiver.
- (id)initWithFrameReceiver:(media::VideoCaptureDeviceMac*)frameReceiver;

// Sets the frame receiver.
- (void)setFrameReceiver:(media::VideoCaptureDeviceMac*)frameReceiver;

// Sets which capture device to use by name, retrieved via |deviceNames|. Once
// the deviceId is known, the library objects are created if needed and
// connected for the capture, and a by default resolution is set. If deviceId is
// nil, then the eventual capture is stopped and library objects are
// disconnected. Returns YES on success, NO otherwise. This method should not be
// called during capture.
- (BOOL)setCaptureDevice:(NSString*)deviceId;

// Configures the capture properties for the capture session and the video data
// output; this means it MUST be called after setCaptureDevice:. Return YES on
// success, else NO.
- (BOOL)setCaptureHeight:(int)height
                   width:(int)width
               frameRate:(float)frameRate;

// Starts video capturing and register the notification listeners. Must be
// called after setCaptureDevice:, and, eventually, also after
// setCaptureHeight:width:frameRate:. Returns YES on success, NO otherwise.
- (BOOL)startCapture;

// Stops video capturing and stops listening to notifications.
- (void)stopCapture;

// Takes a photo. This method should only be called between -startCapture and
// -stopCapture.
- (void)takePhoto;

@end

#endif  // MEDIA_CAPTURE_VIDEO_MAC_VIDEO_CAPTURE_DEVICE_AVFOUNDATION_MAC_H_


text:
// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package admin

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"errors"
	"fmt"
	"strings"
	"testing"
	"time"

	"github.com/golang/mock/gomock"
	"github.com/golang/protobuf/proto" //nolint:staticcheck
	"github.com/golang/protobuf/ptypes"
	"github.com/golang/protobuf/ptypes/empty"
	"github.com/golang/protobuf/ptypes/timestamp"
	"github.com/google/go-cmp/cmp"
	"github.com/google/trillian"
	"github.com/google/trillian/crypto/keys"
	"github.com/google/trillian/crypto/keys/der"
	"github.com/google/trillian/crypto/keyspb"
	"github.com/google/trillian/crypto/sigpb"
	"github.com/google/trillian/extension"
	"github.com/google/trillian/storage"
	"github.com/google/trillian/storage/testonly"
	"google.golang.org/genproto/protobuf/field_mask"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	ttestonly "github.com/google/trillian/testonly"
)

func TestServer_BeginError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	// PEM on the testonly trees is ECDSA, so let's use an ECDSA key for tests.
	privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("Error generating test key: %v", err)
	}

	validTree := proto.Clone(testonly.LogTree).(*trillian.Tree)

	// Need to remove the public key, as it won't correspond to the privateKey that was just generated.
	validTree.PublicKey = nil

	keyProto := &empty.Empty{}
	validTree.PrivateKey = ttestonly.MustMarshalAny(t, keyProto)
	keys.RegisterHandler(fakeKeyProtoHandler(keyProto, privateKey))
	defer keys.UnregisterHandler(keyProto)

	tests := []struct {
		desc     string
		fn       func(context.Context, *Server) error
		snapshot bool
	}{
		{
			desc: "ListTrees",
			fn: func(ctx context.Context, s *Server) error {
				_, err := s.ListTrees(ctx, &trillian.ListTreesRequest{})
				return err
			},
			snapshot: true,
		},
		{
			desc: "GetTree",
			fn: func(ctx context.Context, s *Server) error {
				_, err := s.GetTree(ctx, &trillian.GetTreeRequest{TreeId: 12345})
				return err
			},
			snapshot: true,
		},
		{
			desc: "CreateTree",
			fn: func(ctx context.Context, s *Server) error {
				_, err := s.CreateTree(ctx, &trillian.CreateTreeRequest{Tree: validTree})
				return err
			},
		},
	}

	ctx := context.Background()
	for _, test := range tests {
		as := storage.NewMockAdminStorage(ctrl)
		if test.snapshot {
			as.EXPECT().Snapshot(gomock.Any()).Return(nil, errors.New("snapshot error"))
		} else {
			as.EXPECT().ReadWriteTransaction(gomock.Any(), gomock.Any()).Return(errors.New("begin error"))
		}

		registry := extension.Registry{
			AdminStorage: as,
		}

		s := &Server{registry: registry}
		if err := test.fn(ctx, s); err == nil {
			t.Errorf("%v: got = %v, want non-nil", test.desc, err)
		}
	}
}

func TestServer_ListTrees(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	activeLog := proto.Clone(testonly.LogTree).(*trillian.Tree)
	frozenLog := proto.Clone(testonly.LogTree).(*trillian.Tree)
	frozenLog.TreeState = trillian.TreeState_FROZEN
	deletedLog := proto.Clone(testonly.LogTree).(*trillian.Tree)
	activeMap := proto.Clone(testonly.MapTree).(*trillian.Tree)
	deletedMap := proto.Clone(testonly.MapTree).(*trillian.Tree)

	id := int64(17)
	nowPB := ptypes.TimestampNow()
	for _, tree := range []*trillian.Tree{activeLog, frozenLog, deletedLog, activeMap, deletedMap} {
		tree.TreeId = id
		tree.CreateTime = proto.Clone(nowPB).(*timestamp.Timestamp)
		tree.UpdateTime = proto.Clone(nowPB).(*timestamp.Timestamp)
		id++
		nowPB.Seconds++
	}
	for _, tree := range []*trillian.Tree{deletedLog, deletedMap} {
		tree.Deleted = true
		tree.DeleteTime = proto.Clone(nowPB).(*timestamp.Timestamp)
		nowPB.Seconds++
	}
	nonDeletedTrees := []*trillian.Tree{activeLog, frozenLog, activeMap}
	allTrees := []*trillian.Tree{activeLog, frozenLog, deletedLog, activeMap, deletedMap}

	tests := []struct {
		desc  string
		req   *trillian.ListTreesRequest
		trees []*trillian.Tree
	}{
		{desc: "emptyNonDeleted", req: &trillian.ListTreesRequest{}},
		{desc: "empty", req: &trillian.ListTreesRequest{ShowDeleted: true}},
		{desc: "nonDeleted", req: &trillian.ListTreesRequest{}, trees: nonDeletedTrees},
		{
			desc:  "allTreesDeleted",
			req:   &trillian.ListTreesRequest{ShowDeleted: true},
			trees: allTrees,
		},
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,  /* keygen */
			true, /* snapshot */
			true, /* shouldCommit */
			false /* commitErr */)

		tx := setup.snapshotTX
		tx.EXPECT().ListTrees(gomock.Any(), test.req.ShowDeleted).Return(test.trees, nil)

		s := setup.server
		resp, err := s.ListTrees(ctx, test.req)
		if err != nil {
			t.Errorf("%v: ListTrees() returned err = %v", test.desc, err)
			continue
		}
		want := []*trillian.Tree{}
		for _, tree := range test.trees {
			wantTree := proto.Clone(tree).(*trillian.Tree)
			wantTree.PrivateKey = nil // redacted
			want = append(want, wantTree)
		}
		for i, wantTree := range want {
			if !proto.Equal(resp.Tree[i], wantTree) {
				t.Errorf("%v: post-ListTrees() diff (-got +want):\n%v", test.desc, cmp.Diff(resp.Tree, want))
				break
			}
		}
	}
}

func TestServer_ListTreesErrors(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		desc      string
		listErr   error
		commitErr bool
	}{
		{desc: "listErr", listErr: errors.New("error listing trees")},
		{desc: "commitErr", commitErr: true},
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,                 /* keygen */
			true,                /* snapshot */
			test.listErr == nil, /* shouldCommit */
			test.commitErr /* commitErr */)

		tx := setup.snapshotTX
		tx.EXPECT().ListTrees(gomock.Any(), false).Return(nil, test.listErr)

		s := setup.server
		if _, err := s.ListTrees(ctx, &trillian.ListTreesRequest{}); err == nil {
			t.Errorf("%v: ListTrees() returned err = nil, want non-nil", test.desc)
		}
	}
}

func TestServer_GetTree(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		desc              string
		getErr, commitErr bool
	}{
		{
			desc: "success",
		},
		{
			desc:   "unknownTree",
			getErr: true,
		},
		{
			desc:      "commitError",
			commitErr: true,
		},
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,          /* keygen */
			true,         /* snapshot */
			!test.getErr, /* shouldCommit */
			test.commitErr)

		tx := setup.snapshotTX
		s := setup.server

		storedTree := proto.Clone(testonly.LogTree).(*trillian.Tree)
		storedTree.TreeId = 12345
		if test.getErr {
			tx.EXPECT().GetTree(gomock.Any(), storedTree.TreeId).Return(nil, errors.New("GetTree failed"))
		} else {
			tx.EXPECT().GetTree(gomock.Any(), storedTree.TreeId).Return(storedTree, nil)
		}
		wantErr := test.getErr || test.commitErr

		tree, err := s.GetTree(ctx, &trillian.GetTreeRequest{TreeId: storedTree.TreeId})
		if hasErr := err != nil; hasErr != wantErr {
			t.Errorf("%v: GetTree() = (_, %v), wantErr = %v", test.desc, err, wantErr)
			continue
		} else if hasErr {
			continue
		}

		wantTree := proto.Clone(storedTree).(*trillian.Tree)
		wantTree.PrivateKey = nil // redacted
		if diff := cmp.Diff(tree, wantTree, cmp.Comparer(proto.Equal)); diff != "" {
			t.Errorf("%v: post-GetTree diff (-got +want):\n%v", test.desc, diff)
		}
	}
}

func TestServer_CreateTree(t *testing.T) {
	// PEM on the testonly trees is ECDSA, so let's use an ECDSA key for tests.
	ecdsaPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("Error generating test ECDSA key: %v", err)
	}

	rsaPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096)
	if err != nil {
		t.Fatalf("Error generating test RSA key: %v", err)
	}

	// Need to change the public key to correspond with the ECDSA private key generated above.
	validTree := proto.Clone(testonly.LogTree).(*trillian.Tree)
	// Except in key generation test cases, a keys.ProtoHandler will be registered that
	// returns ecdsaPrivateKey when passed an empty proto.
	wantKeyProto := &empty.Empty{}
	validTree.PrivateKey = ttestonly.MustMarshalAny(t, wantKeyProto)
	validTree.PublicKey = func() *keyspb.PublicKey {
		pb, err := der.ToPublicProto(ecdsaPrivateKey.Public())
		if err != nil {
			t.Fatalf("Error marshaling ECDSA public key: %v", err)
		}
		return pb
	}()

	mismatchedPublicKey := proto.Clone(validTree).(*trillian.Tree)
	mismatchedPublicKey.PublicKey = testonly.LogTree.GetPublicKey()

	omittedPublicKey := proto.Clone(validTree).(*trillian.Tree)
	omittedPublicKey.PublicKey = nil

	omittedPrivateKey := proto.Clone(validTree).(*trillian.Tree)
	omittedPrivateKey.PrivateKey = nil

	omittedKeys := proto.Clone(omittedPublicKey).(*trillian.Tree)
	omittedKeys.PrivateKey = nil

	invalidTree := proto.Clone(validTree).(*trillian.Tree)
	invalidTree.TreeState = trillian.TreeState_UNKNOWN_TREE_STATE

	invalidHashAlgo := proto.Clone(validTree).(*trillian.Tree)
	invalidHashAlgo.HashAlgorithm = sigpb.DigitallySigned_NONE

	invalidHashStrategy := proto.Clone(validTree).(*trillian.Tree)
	invalidHashStrategy.HashStrategy = trillian.HashStrategy_UNKNOWN_HASH_STRATEGY

	invalidSignatureAlgo := proto.Clone(validTree).(*trillian.Tree)
	invalidSignatureAlgo.SignatureAlgorithm = sigpb.DigitallySigned_ANONYMOUS

	keySignatureMismatch := proto.Clone(validTree).(*trillian.Tree)
	keySignatureMismatch.SignatureAlgorithm = sigpb.DigitallySigned_RSA

	tests := []struct {
		desc                  string
		req                   *trillian.CreateTreeRequest
		wantKeyGenerator      bool
		createErr             error
		commitErr, wantCommit bool
		wantErr               string
	}{
		{
			desc:       "validTree",
			req:        &trillian.CreateTreeRequest{Tree: validTree},
			wantCommit: true,
		},
		{
			desc:    "nilTree",
			req:     &trillian.CreateTreeRequest{},
			wantErr: "tree is required",
		},
		{
			desc:    "mismatchedPublicKey",
			req:     &trillian.CreateTreeRequest{Tree: mismatchedPublicKey},
			wantErr: "public and private keys are not a pair",
		},
		{
			desc:    "omittedPrivateKey",
			req:     &trillian.CreateTreeRequest{Tree: omittedPrivateKey},
			wantErr: "private_key or key_spec is required",
		},
		{
			desc: "privateKeySpec",
			req: &trillian.CreateTreeRequest{
				Tree: omittedKeys,
				KeySpec: &keyspb.Specification{
					Params: &keyspb.Specification_EcdsaParams{},
				},
			},
			wantKeyGenerator: true,
			wantCommit:       true,
		},
		{
			desc: "privateKeySpecButNoKeyGenerator",
			req: &trillian.CreateTreeRequest{
				Tree: omittedKeys,
				KeySpec: &keyspb.Specification{
					Params: &keyspb.Specification_EcdsaParams{},
				},
			},
			wantErr: "key generation is not enabled",
		},
		{
			// Tree specifies ECDSA signatures, but key specification provides RSA parameters.
			desc: "privateKeySpecWithMismatchedAlgorithm",
			req: &trillian.CreateTreeRequest{
				Tree: omittedKeys,
				KeySpec: &keyspb.Specification{
					Params: &keyspb.Specification_RsaParams{},
				},
			},
			wantKeyGenerator: true,
			wantErr:          "signature not supported by signer",
		},
		{
			desc: "privateKeySpecAndPrivateKeyProvided",
			req: &trillian.CreateTreeRequest{
				Tree: validTree,
				KeySpec: &keyspb.Specification{
					Params: &keyspb.Specification_EcdsaParams{},
				},
			},
			wantKeyGenerator: true,
			wantErr:          "private_key and key_spec fields are mutually exclusive",
		},
		{
			desc: "privateKeySpecAndPublicKeyProvided",
			req: &trillian.CreateTreeRequest{
				Tree: omittedPrivateKey,
				KeySpec: &keyspb.Specification{
					Params: &keyspb.Specification_EcdsaParams{},
				},
			},
			wantKeyGenerator: true,
			wantErr:          "public_key and key_spec fields are mutually exclusive",
		},
		{
			desc:       "omittedPublicKey",
			req:        &trillian.CreateTreeRequest{Tree: omittedPublicKey},
			wantCommit: true,
		},
		{
			desc:    "invalidHashAlgo",
			req:     &trillian.CreateTreeRequest{Tree: invalidHashAlgo},
			wantErr: "unexpected hash algorithm",
		},
		{
			desc:    "invalidHashStrategy",
			req:     &trillian.CreateTreeRequest{Tree: invalidHashStrategy},
			wantErr: "unknown hasher",
		},
		{
			desc:    "invalidSignatureAlgo",
			req:     &trillian.CreateTreeRequest{Tree: invalidSignatureAlgo},
			wantErr: "signature algorithm not supported",
		},
		{
			desc:    "keySignatureMismatch",
			req:     &trillian.CreateTreeRequest{Tree: keySignatureMismatch},
			wantErr: "signature not supported by signer",
		},
		{
			desc:      "createErr",
			req:       &trillian.CreateTreeRequest{Tree: invalidTree},
			createErr: errors.New("storage CreateTree failed"),
			wantErr:   "storage CreateTree failed",
		},
		{
			desc:       "commitError",
			req:        &trillian.CreateTreeRequest{Tree: validTree},
			commitErr:  true,
			wantCommit: true,
			wantErr:    "commit error",
		},
	}

	ctx := context.Background()
	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctrl := gomock.NewController(t)
			defer ctrl.Finish()

			var privateKey crypto.Signer = ecdsaPrivateKey
			var keygen keys.ProtoGenerator
			// If KeySpec is set, select the correct type of key to "generate".
			if test.req.GetKeySpec() != nil {
				switch keySpec := test.req.GetKeySpec().GetParams().(type) {
				case *keyspb.Specification_EcdsaParams:
					privateKey = ecdsaPrivateKey
				case *keyspb.Specification_RsaParams:
					privateKey = rsaPrivateKey
				default:
					t.Fatalf("unexpected KeySpec.Params type: %T", keySpec)
				}

				if test.wantKeyGenerator {
					// Setup a fake key generator. If it receives the expected KeySpec, it returns wantKeyProto,
					// which a keys.ProtoHandler will expect to receive later on.
					keygen = fakeKeyProtoGenerator(test.req.GetKeySpec(), wantKeyProto)
				}
			}

			keys.RegisterHandler(fakeKeyProtoHandler(wantKeyProto, privateKey))
			defer keys.UnregisterHandler(wantKeyProto)

			setup := setupAdminServer(ctrl, keygen, false /* snapshot */, test.wantCommit, test.commitErr)
			tx := setup.tx
			s := setup.server
			nowPB := ptypes.TimestampNow()

			if test.req.Tree != nil {
				newTree := proto.Clone(test.req.Tree).(*trillian.Tree)
				newTree.TreeId = 12345
				newTree.CreateTime = nowPB
				newTree.UpdateTime = nowPB
				newTree.PublicKey, err = der.ToPublicProto(privateKey.Public())
				tx.EXPECT().CreateTree(gomock.Any(), gomock.Any()).MaxTimes(1).Return(newTree, test.createErr)
			}

			// Copy test.req so that any changes CreateTree makes don't affect the original, which may be shared between tests.
			reqCopy := proto.Clone(test.req).(*trillian.CreateTreeRequest)
			tree, err := s.CreateTree(ctx, reqCopy)
			switch gotErr := err != nil; {
			case gotErr && !strings.Contains(err.Error(), test.wantErr):
				t.Fatalf("CreateTree() = (_, %q), want (_, %q)", err, test.wantErr)
			case gotErr:
				return
			case test.wantErr != "":
				t.Fatalf("CreateTree() = (_, nil), want (_, %q)", test.wantErr)
			}

			wantTree := proto.Clone(test.req.Tree).(*trillian.Tree)
			wantTree.TreeId = 12345
			wantTree.CreateTime = nowPB
			wantTree.UpdateTime = nowPB
			wantTree.PrivateKey = nil // redacted
			wantTree.PublicKey, err = der.ToPublicProto(privateKey.Public())
			if err != nil {
				t.Fatalf("failed to marshal test public key as protobuf: %v", err)
			}
			if diff := cmp.Diff(tree, wantTree, cmp.Comparer(proto.Equal)); diff != "" {
				t.Fatalf("post-CreateTree diff (-got +want):\n%v", diff)
			}
		})
	}
}

func TestServer_CreateTree_AllowedTreeTypes(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		desc      string
		treeTypes []trillian.TreeType
		req       *trillian.CreateTreeRequest
		wantCode  codes.Code
		wantMsg   string
	}{
		{
			desc:      "mapOnLogServer",
			treeTypes: []trillian.TreeType{trillian.TreeType_LOG},
			req:       &trillian.CreateTreeRequest{Tree: testonly.MapTree},
			wantCode:  codes.InvalidArgument,
			wantMsg:   "tree type MAP not allowed",
		},
		{
			desc:      "logOnMapServer",
			treeTypes: []trillian.TreeType{trillian.TreeType_MAP},
			req:       &trillian.CreateTreeRequest{Tree: testonly.LogTree},
			wantCode:  codes.InvalidArgument,
			wantMsg:   "tree type LOG not allowed",
		},
		{
			desc:      "preorderedLogOnLogServer",
			treeTypes: []trillian.TreeType{trillian.TreeType_LOG},
			req:       &trillian.CreateTreeRequest{Tree: testonly.PreorderedLogTree},
			wantCode:  codes.InvalidArgument,
			wantMsg:   "tree type PREORDERED_LOG not allowed",
		},
		{
			desc:      "preorderedLogOnMapServer",
			treeTypes: []trillian.TreeType{trillian.TreeType_MAP},
			req:       &trillian.CreateTreeRequest{Tree: testonly.PreorderedLogTree},
			wantCode:  codes.InvalidArgument,
			wantMsg:   "tree type PREORDERED_LOG not allowed",
		},
		{
			desc:      "logOnLogServer",
			treeTypes: []trillian.TreeType{trillian.TreeType_LOG},
			req:       &trillian.CreateTreeRequest{Tree: testonly.LogTree},
			wantCode:  codes.OK,
		},
		{
			desc:      "preorderedLogAllowed",
			treeTypes: []trillian.TreeType{trillian.TreeType_LOG, trillian.TreeType_PREORDERED_LOG},
			req:       &trillian.CreateTreeRequest{Tree: testonly.PreorderedLogTree},
			wantCode:  codes.OK,
		},
		{
			desc:      "mapOnMapServer",
			treeTypes: []trillian.TreeType{trillian.TreeType_MAP},
			req:       &trillian.CreateTreeRequest{Tree: testonly.MapTree},
			wantCode:  codes.OK,
		},
		// treeTypes = nil is exercised by all other tests.
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,   // keygen
			false, // snapshot
			test.wantCode == codes.OK,
			false)
		s := setup.server
		tx := setup.tx
		s.allowedTreeTypes = test.treeTypes

		// Storage interactions aren't the focus of this test, so mocks are configured in a rather
		// permissive way.
		tx.EXPECT().CreateTree(gomock.Any(), gomock.Any()).AnyTimes().Return(&trillian.Tree{}, nil)

		_, err := s.CreateTree(ctx, test.req)
		switch s, ok := status.FromError(err); {
		case !ok || s.Code() != test.wantCode:
			t.Errorf("%v: CreateTree() returned err = %v, wantCode = %s", test.desc, err, test.wantCode)
		case err != nil && !strings.Contains(err.Error(), test.wantMsg):
			t.Errorf("%v: CreateTree() returned err = %q, wantMsg = %q", test.desc, err, test.wantMsg)
		}
	}
}

func TestServer_UpdateTree(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	nowPB := ptypes.TimestampNow()
	existingTree := proto.Clone(testonly.LogTree).(*trillian.Tree)
	existingTree.TreeId = 12345
	existingTree.CreateTime = nowPB
	existingTree.UpdateTime = nowPB
	existingTree.MaxRootDuration = ptypes.DurationProto(1 * time.Nanosecond)

	// Any valid proto works here, the type doesn't matter for this test.
	settings := ttestonly.MustMarshalAny(t, &empty.Empty{})

	// successTree specifies changes in all rw fields
	successTree := &trillian.Tree{
		TreeState:       trillian.TreeState_FROZEN,
		DisplayName:     "Brand New Tree Name",
		Description:     "Brand New Tree Desc",
		StorageSettings: settings,
		MaxRootDuration: ptypes.DurationProto(2 * time.Nanosecond),
		PrivateKey:      ttestonly.MustMarshalAny(t, &empty.Empty{}),
	}
	successMask := &field_mask.FieldMask{
		Paths: []string{"tree_state", "display_name", "description", "storage_settings", "max_root_duration", "private_key"},
	}

	successWant := proto.Clone(existingTree).(*trillian.Tree)
	successWant.TreeState = successTree.TreeState
	successWant.DisplayName = successTree.DisplayName
	successWant.Description = successTree.Description
	successWant.StorageSettings = successTree.StorageSettings
	successWant.PrivateKey = nil // redacted on responses
	successWant.MaxRootDuration = successTree.MaxRootDuration

	tests := []struct {
		desc                           string
		req                            *trillian.UpdateTreeRequest
		currentTree, wantTree          *trillian.Tree
		updateErr                      error
		commitErr, wantErr, wantCommit bool
	}{
		{
			desc:        "success",
			req:         &trillian.UpdateTreeRequest{Tree: successTree, UpdateMask: successMask},
			currentTree: existingTree,
			wantTree:    successWant,
			wantCommit:  true,
		},
		{
			desc:    "nilTree",
			req:     &trillian.UpdateTreeRequest{},
			wantErr: true,
		},
		{
			desc:        "nilUpdateMask",
			req:         &trillian.UpdateTreeRequest{Tree: successTree},
			currentTree: existingTree,
			wantErr:     true,
		},
		{
			desc:        "emptyUpdateMask",
			req:         &trillian.UpdateTreeRequest{Tree: successTree, UpdateMask: &field_mask.FieldMask{}},
			currentTree: existingTree,
			wantErr:     true,
		},
		{
			desc: "readonlyField",
			req: &trillian.UpdateTreeRequest{
				Tree:       successTree,
				UpdateMask: &field_mask.FieldMask{Paths: []string{"tree_id"}},
			},
			currentTree: existingTree,
			wantErr:     true,
		},
		{
			desc:        "updateErr",
			req:         &trillian.UpdateTreeRequest{Tree: successTree, UpdateMask: successMask},
			updateErr:   errors.New("error updating tree"),
			currentTree: existingTree,
			wantErr:     true,
		},
		{
			desc:        "commitErr",
			req:         &trillian.UpdateTreeRequest{Tree: successTree, UpdateMask: successMask},
			currentTree: existingTree,
			commitErr:   true,
			wantErr:     true,
			wantCommit:  true,
		},
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,   /* keygen */
			false, /* snapshot */
			test.wantCommit,
			test.commitErr)

		tx := setup.tx
		s := setup.server

		if test.req.Tree != nil {
			tx.EXPECT().UpdateTree(gomock.Any(), test.req.Tree.TreeId, gomock.Any()).MaxTimes(1).Do(func(ctx context.Context, treeID int64, updateFn func(*trillian.Tree)) {
				// This step should be done by the storage layer, but since we're mocking it we have to trigger it ourselves.
				updateFn(test.currentTree)
			}).Return(test.currentTree, test.updateErr)
		}

		tree, err := s.UpdateTree(ctx, test.req)
		if hasErr := err != nil; hasErr != test.wantErr {
			t.Errorf("%v: UpdateTree() returned err = %q, wantErr = %v", test.desc, err, test.wantErr)
			continue
		} else if hasErr {
			continue
		}

		if !proto.Equal(tree, test.wantTree) {
			diff := cmp.Diff(tree, test.wantTree)
			t.Errorf("%v: post-UpdateTree diff:\n%v", test.desc, diff)
		}
	}
}

func TestServer_DeleteTree(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	logTree := proto.Clone(testonly.LogTree).(*trillian.Tree)
	mapTree := proto.Clone(testonly.MapTree).(*trillian.Tree)
	for i, tree := range []*trillian.Tree{logTree, mapTree} {
		tree.TreeId = int64(i) + 10
		tree.CreateTime, _ = ptypes.TimestampProto(time.Unix(int64(i)*3600, 0))
		tree.UpdateTime = tree.CreateTime
	}

	tests := []struct {
		desc string
		tree *trillian.Tree
	}{
		{desc: "logTree", tree: logTree},
		{desc: "mapTree", tree: mapTree},
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,   /* keygen */
			false, /* snapshot */
			true,  /* shouldCommit */
			false)
		req := &trillian.DeleteTreeRequest{TreeId: test.tree.TreeId}

		tx := setup.tx
		tx.EXPECT().SoftDeleteTree(gomock.Any(), req.TreeId).Return(test.tree, nil)

		s := setup.server
		got, err := s.DeleteTree(ctx, req)
		if err != nil {
			t.Errorf("%v: DeleteTree() returned err = %v", test.desc, err)
			continue
		}

		want := proto.Clone(test.tree).(*trillian.Tree)
		want.PrivateKey = nil // redacted
		if !proto.Equal(got, want) {
			diff := cmp.Diff(got, want)
			t.Errorf("%v: post-DeleteTree() diff (-got +want):\n%v", test.desc, diff)
		}
	}
}

func TestServer_DeleteTreeErrors(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		desc      string
		deleteErr error
		commitErr bool
	}{
		{desc: "deleteErr", deleteErr: errors.New("unknown tree")},
		{desc: "commitErr", commitErr: true},
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,
			false,
			test.deleteErr == nil,
			test.commitErr)
		req := &trillian.DeleteTreeRequest{TreeId: 10}

		tx := setup.tx
		tx.EXPECT().SoftDeleteTree(gomock.Any(), req.TreeId).Return(&trillian.Tree{}, test.deleteErr)

		s := setup.server
		if _, err := s.DeleteTree(ctx, req); err == nil {
			t.Errorf("%v: DeleteTree() returned err = nil, want non-nil", test.desc)
		}
	}
}

func TestServer_UndeleteTree(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	activeLog := proto.Clone(testonly.LogTree).(*trillian.Tree)
	frozenLog := proto.Clone(testonly.LogTree).(*trillian.Tree)
	frozenLog.TreeState = trillian.TreeState_FROZEN
	activeMap := proto.Clone(testonly.MapTree).(*trillian.Tree)
	for i, tree := range []*trillian.Tree{activeLog, frozenLog, activeMap} {
		tree.TreeId = int64(i) + 10
		tree.CreateTime, _ = ptypes.TimestampProto(time.Unix(int64(i)*3600, 0))
		tree.UpdateTime = tree.CreateTime
		tree.Deleted = true
		tree.DeleteTime, _ = ptypes.TimestampProto(time.Unix(int64(i)*3600+10, 0))
	}

	tests := []struct {
		desc string
		tree *trillian.Tree
	}{
		{desc: "activeLog", tree: activeLog},
		{desc: "frozenLog", tree: frozenLog},
		{desc: "activeMap", tree: activeMap},
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,   /* keygen */
			false, /* snapshot */
			true,  /* shouldCommit */
			false)
		req := &trillian.UndeleteTreeRequest{TreeId: test.tree.TreeId}

		tx := setup.tx
		tx.EXPECT().UndeleteTree(gomock.Any(), req.TreeId).Return(test.tree, nil)

		s := setup.server
		got, err := s.UndeleteTree(ctx, req)
		if err != nil {
			t.Errorf("%v: UndeleteTree() returned err = %v", test.desc, err)
			continue
		}

		want := proto.Clone(test.tree).(*trillian.Tree)
		want.PrivateKey = nil // redacted
		if !proto.Equal(got, want) {
			diff := cmp.Diff(got, want)
			t.Errorf("%v: post-UneleteTree() diff (-got +want):\n%v", test.desc, diff)
		}
	}
}

func TestServer_UndeleteTreeErrors(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		desc        string
		undeleteErr error
		commitErr   bool
	}{
		{desc: "undeleteErr", undeleteErr: errors.New("unknown tree")},
		{desc: "commitErr", commitErr: true},
	}

	ctx := context.Background()
	for _, test := range tests {
		setup := setupAdminServer(
			ctrl,
			nil,
			false,
			test.undeleteErr == nil,
			test.commitErr)
		req := &trillian.UndeleteTreeRequest{TreeId: 10}

		tx := setup.tx
		tx.EXPECT().UndeleteTree(gomock.Any(), req.TreeId).Return(&trillian.Tree{}, test.undeleteErr)

		s := setup.server
		if _, err := s.UndeleteTree(ctx, req); err == nil {
			t.Errorf("%v: UndeleteTree() returned err = nil, want non-nil", test.desc)
		}
	}
}

// adminTestSetup contains an operational Server and required dependencies.
// It's created via setupAdminServer.
type adminTestSetup struct {
	registry   extension.Registry
	as         storage.AdminStorage
	tx         *storage.MockAdminTX
	snapshotTX *storage.MockReadOnlyAdminTX
	server     *Server
}

// setupAdminServer configures mocks according to input parameters.
// Storage will be set to use either snapshots or regular TXs via snapshot parameter.
// Whether the snapshot/TX is expected to be committed (and if it should error doing so) is
// controlled via shouldCommit and commitErr parameters.
func setupAdminServer(ctrl *gomock.Controller, keygen keys.ProtoGenerator, snapshot, shouldCommit, commitErr bool) adminTestSetup {
	as := &testonly.FakeAdminStorage{}

	var snapshotTX *storage.MockReadOnlyAdminTX
	var tx *storage.MockAdminTX
	if snapshot {
		snapshotTX = storage.NewMockReadOnlyAdminTX(ctrl)
		snapshotTX.EXPECT().Close().MaxTimes(1).Return(nil)
		as.ReadOnlyTX = append(as.ReadOnlyTX, snapshotTX)
		if shouldCommit {
			if commitErr {
				snapshotTX.EXPECT().Commit().Return(errors.New("commit error"))
			} else {
				snapshotTX.EXPECT().Commit().Return(nil)
			}
		}
	} else {
		tx = storage.NewMockAdminTX(ctrl)
		tx.EXPECT().Close().MaxTimes(1).Return(nil)
		as.TX = append(as.TX, tx)
		if shouldCommit {
			if commitErr {
				tx.EXPECT().Commit().Return(errors.New("commit error"))
			} else {
				tx.EXPECT().Commit().Return(nil)
			}
		}
	}

	registry := extension.Registry{
		AdminStorage: as,
		NewKeyProto:  keygen,
	}

	s := &Server{registry: registry}

	return adminTestSetup{registry, as, tx, snapshotTX, s}
}

func fakeKeyProtoHandler(wantKeyProto proto.Message, key crypto.Signer) (proto.Message, keys.ProtoHandler) {
	return wantKeyProto, func(ctx context.Context, gotKeyProto proto.Message) (crypto.Signer, error) {
		if !proto.Equal(gotKeyProto, wantKeyProto) {
			return nil, fmt.Errorf("NewSigner(_, %#v) called, want NewSigner(_, %#v)", gotKeyProto, wantKeyProto)
		}
		return key, nil
	}
}

func fakeKeyProtoGenerator(wantKeySpec *keyspb.Specification, keyProto proto.Message) keys.ProtoGenerator {
	return func(ctx context.Context, gotKeySpec *keyspb.Specification) (proto.Message, error) {
		if !proto.Equal(gotKeySpec, wantKeySpec) {
			return nil, fmt.Errorf("NewKeyProto(_, %#v) called, want NewKeyProto(_, %#v)", gotKeySpec, wantKeySpec)
		}
		return keyProto, nil
	}
}


text: ETahi.<%= class_name %>OverlayController = ETahi.TaskController.extend();


text:
try:
    a
except :
    <warning descr="Python version 3.0, 3.1, 3.2, 3.3, 3.4, 3.5 do not support this syntax.">raise ImportError, ImportWarning</warning>

<warning descr="Python version 3.0, 3.1, 3.2, 3.3, 3.4, 3.5 do not support this syntax. Raise with no arguments can only be used in an except block">raise</warning>


text:
package org.apache.commons.collections4.iterators;

import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.Iterator;
import java.util.NoSuchElementException;

import org.junit.jupiter.api.Test;

/**
 * Tests the ObjectArrayIterator.
 */
public class ObjectArrayIteratorTest<E> extends AbstractIteratorTest<E> {

    protected String[] testArray = { "One", "Two", "Three" };

    public ObjectArrayIteratorTest() {
        super(ObjectArrayIteratorTest.class.getSimpleName());
    }

    @Override
    @SuppressWarnings("unchecked")
    public ObjectArrayIterator<E> makeEmptyIterator() {
        return new ObjectArrayIterator<>((E[]) new Object[0]);
    }

    @Override
    @SuppressWarnings("unchecked")
    public ObjectArrayIterator<E> makeObject() {
        return new ObjectArrayIterator<>((E[]) testArray);
    }

    @SuppressWarnings("unchecked")
    public ObjectArrayIterator<E> makeArrayIterator() {
        return new ObjectArrayIterator<>();
    }

    public ObjectArrayIterator<E> makeArrayIterator(final E[] array) {
        return new ObjectArrayIterator<>(array);
    }

    public ObjectArrayIterator<E> makeArrayIterator(final E[] array, final int index) {
        return new ObjectArrayIterator<>(array, index);
    }

    public ObjectArrayIterator<E> makeArrayIterator(final E[] array, final int start, final int end) {
        return new ObjectArrayIterator<>(array, start, end);
    }

    @Override
    public boolean supportsRemove() {
        return false;
    }

    @Test
    public void testIterator() {
        final Iterator<E> iter = makeObject();
        for (final String testValue : testArray) {
            final E iterValue = iter.next();

            assertEquals("Iteration value is correct", testValue, iterValue);
        }

        assertFalse("Iterator should now be empty", iter.hasNext());

        try {
            iter.next();
        } catch (final Exception e) {
            assertEquals("NoSuchElementException must be thrown", e.getClass(), new NoSuchElementException().getClass());
        }
    }

    @Test
    public void testNullArray() {
        assertThrows(NullPointerException.class, () -> makeArrayIterator(null));
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testReset() {
        final ObjectArrayIterator<E> it = makeArrayIterator((E[]) testArray);
        it.next();
        it.reset();
        assertEquals("One", it.next());
    }

}


text:
using System;
using System.Windows.Forms;

using nMqtt.SampleApp.Views;
using nMqtt.SampleApp.ViewModels;
using System.Diagnostics;

namespace nMqttSampleApp
{
	class Program
	{
		[STAThread]
		public static void Main (string[] args)
		{
			Application.EnableVisualStyles();
			Application.Run(new ShellForm(new ShellViewModel()));
		}
	}
}


text:
<?php

namespace Kint\Parser;

use Kint\Object\BasicObject;
use Kint\Object\InstanceObject;
use Kint\Object\Representation\Representation;
use ReflectionClass;
use ReflectionProperty;

class ClassStaticsPlugin extends Plugin
{
    private static $cache = array();

    public function getTypes()
    {
        return array('object');
    }

    public function getTriggers()
    {
        return Parser::TRIGGER_SUCCESS;
    }

    public function parse(&$var, BasicObject &$o, $trigger)
    {
        $class = \get_class($var);
        $reflection = new ReflectionClass($class);

        // Constants
        // TODO: PHP 7.1 allows private consts but reflection doesn't have a way to check them yet
        if (!isset(self::$cache[$class])) {
            $consts = array();

            foreach ($reflection->getConstants() as $name => $val) {
                $const = BasicObject::blank($name, '\\'.$class.'::'.$name);
                $const->const = true;
                $const->depth = $o->depth + 1;
                $const->owner_class = $class;
                $const->operator = BasicObject::OPERATOR_STATIC;
                $const = $this->parser->parse($val, $const);

                $consts[] = $const;
            }

            self::$cache[$class] = $consts;
        }

        $statics = new Representation('Static class properties', 'statics');
        $statics->contents = self::$cache[$class];

        foreach ($reflection->getProperties(ReflectionProperty::IS_STATIC) as $static) {
            $prop = new BasicObject();
            $prop->name = '$'.$static->getName();
            $prop->depth = $o->depth + 1;
            $prop->static = true;
            $prop->operator = BasicObject::OPERATOR_STATIC;
            $prop->owner_class = $static->getDeclaringClass()->name;

            $prop->access = BasicObject::ACCESS_PUBLIC;
            if ($static->isProtected()) {
                $prop->access = BasicObject::ACCESS_PROTECTED;
            } elseif ($static->isPrivate()) {
                $prop->access = BasicObject::ACCESS_PRIVATE;
            }

            if ($this->parser->childHasPath($o, $prop)) {
                $prop->access_path = '\\'.$prop->owner_class.'::'.$prop->name;
            }

            $static->setAccessible(true);
            $static = $static->getValue();
            $statics->contents[] = $this->parser->parse($static, $prop);
        }

        if (empty($statics->contents)) {
            return;
        }

        \usort($statics->contents, array('Kint\\Parser\\ClassStaticsPlugin', 'sort'));

        $o->addRepresentation($statics);
    }

    private static function sort(BasicObject $a, BasicObject $b)
    {
        $sort = ((int) $a->const) - ((int) $b->const);
        if ($sort) {
            return $sort;
        }

        $sort = BasicObject::sortByAccess($a, $b);
        if ($sort) {
            return $sort;
        }

        return InstanceObject::sortByHierarchy($a->owner_class, $b->owner_class);
    }
}


text:
<?php

namespace AJT\Toggl;

use GuzzleHttp\Client;

/**
 * A TogglClient
 */
class ReportsClient extends TogglClient
{

    /**
     * Factory method to create a new TogglClient
     *
     * The following array keys and values are available options:
     * - base_url: Base URL of web service
     * - api_key: API key
     *
     * See https://www.toggl.com/public/api#api_token for more information on the api token
     *
     * @param array $config Configuration data
     * @return ReportsClient
     * @throws \Exception
     */
    public static function factory(array $config = [])
    {
        $guzzleClient = new Client(self::getClientConfig($config));

        if (isset($config['apiVersion']) && $config['apiVersion'] !== 'v2') {
            throw new InvalidApiVersionException('Only v2 of the reporting api is supported at this time');
        }

        $description = self::getAPIDescriptionByJsonFile('reporting_v2.json');
        return new self($guzzleClient, $description);
    }

    /**
     * Shortcut for executing Commands in the Definitions.
     *
     * @param string $method
     * @param array|null $args
     *
     * @return mixed|void
     *
     */
    public function __call($method, array $args)
    {
        return parent::__call(ucfirst($method), $args);
    }
}


text:
package de.wschneider.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("/")
@Controller
public class WelcomeController {

    @RequestMapping
    public String welcome() {

        return "static";
    }
}


text:
- compare both tunings
- what is similar, what differs?
- generate some chords in both tunings
    - from:
        - plain sine tones
        - complex tones with harmonics
    - set of frequences
        - visualize
    - synthesized sound
- how does a sequence of tones sound?
- how does chords sound?
- measure dissonance
- compare partials that are very near