text:
use std::{collections::HashMap, rc::Rc};

use crate::basic::{Compression, Encoding};
use crate::schema::types::ColumnPath;

const DEFAULT_PAGE_SIZE: usize = 1024 * 1024;
const DEFAULT_WRITE_BATCH_SIZE: usize = 1024;
const DEFAULT_WRITER_VERSION: WriterVersion = WriterVersion::PARQUET_1_0;
const DEFAULT_COMPRESSION: Compression = Compression::UNCOMPRESSED;
const DEFAULT_DICTIONARY_ENABLED: bool = true;
const DEFAULT_DICTIONARY_PAGE_SIZE_LIMIT: usize = DEFAULT_PAGE_SIZE;
const DEFAULT_STATISTICS_ENABLED: bool = true;
const DEFAULT_MAX_STATISTICS_SIZE: usize = 4096;
const DEFAULT_MAX_ROW_GROUP_SIZE: usize = 128 * 1024 * 1024;
const DEFAULT_CREATED_BY: &str = env!("PARQUET_CREATED_BY");

/// Parquet writer version.
///
/// Basic constant, which is not part of the Thrift definition.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WriterVersion {
    PARQUET_1_0,
    PARQUET_2_0,
}

impl WriterVersion {
    /// Returns writer version as `i32`.
    pub fn as_num(&self) -> i32 {
        match self {
            WriterVersion::PARQUET_1_0 => 1,
            WriterVersion::PARQUET_2_0 => 2,
        }
    }
}

/// Reference counted writer properties.
pub type WriterPropertiesPtr = Rc<WriterProperties>;

/// Writer properties.
///
/// It is created as an immutable data structure, use [`WriterPropertiesBuilder`] to
/// assemble the properties.
#[derive(Debug, Clone)]
pub struct WriterProperties {
    data_pagesize_limit: usize,
    dictionary_pagesize_limit: usize,
    write_batch_size: usize,
    max_row_group_size: usize,
    writer_version: WriterVersion,
    created_by: String,
    default_column_properties: ColumnProperties,
    column_properties: HashMap<ColumnPath, ColumnProperties>,
}

impl WriterProperties {
    /// Returns builder for writer properties with default values.
    pub fn builder() -> WriterPropertiesBuilder {
        WriterPropertiesBuilder::with_defaults()
    }

    /// Returns data page size limit.
    pub fn data_pagesize_limit(&self) -> usize {
        self.data_pagesize_limit
    }

    /// Returns dictionary page size limit.
    pub fn dictionary_pagesize_limit(&self) -> usize {
        self.dictionary_pagesize_limit
    }

    /// Returns configured batch size for writes.
    ///
    /// When writing a batch of data, this setting allows to split it internally into
    /// smaller batches so we can better estimate the size of a page currently being
    /// written.
    pub fn write_batch_size(&self) -> usize {
        self.write_batch_size
    }

    /// Returns max size for a row group.
    pub fn max_row_group_size(&self) -> usize {
        self.max_row_group_size
    }

    /// Returns configured writer version.
    pub fn writer_version(&self) -> WriterVersion {
        self.writer_version
    }

    /// Returns `created_by` string.
    pub fn created_by(&self) -> &str {
        &self.created_by
    }

    /// Returns encoding for a data page, when dictionary encoding is enabled.
    /// This is not configurable.
    #[inline]
    pub fn dictionary_data_page_encoding(&self) -> Encoding {
        // PLAIN_DICTIONARY encoding is deprecated in writer version 1.
        // Dictionary values are encoded using RLE_DICTIONARY encoding.
        Encoding::RLE_DICTIONARY
    }

    /// Returns encoding for dictionary page, when dictionary encoding is enabled.
    /// This is not configurable.
    #[inline]
    pub fn dictionary_page_encoding(&self) -> Encoding {
        // PLAIN_DICTIONARY is deprecated in writer version 1.
        // Dictionary is encoded using plain encoding.
        Encoding::PLAIN
    }

    /// Returns encoding for a column, if set.
    /// In case when dictionary is enabled, returns fallback encoding.
    ///
    /// If encoding is not set, then column writer will choose the best encoding
    /// based on the column type.
    pub fn encoding(&self, col: &ColumnPath) -> Option<Encoding> {
        self.column_properties
            .get(col)
            .and_then(|c| c.encoding())
            .or_else(|| self.default_column_properties.encoding())
    }

    /// Returns compression codec for a column.
    pub fn compression(&self, col: &ColumnPath) -> Compression {
        self.column_properties
            .get(col)
            .and_then(|c| c.compression())
            .or_else(|| self.default_column_properties.compression())
            .unwrap_or(DEFAULT_COMPRESSION)
    }

    /// Returns `true` if dictionary encoding is enabled for a column.
    pub fn dictionary_enabled(&self, col: &ColumnPath) -> bool {
        self.column_properties
            .get(col)
            .and_then(|c| c.dictionary_enabled())
            .or_else(|| self.default_column_properties.dictionary_enabled())
            .unwrap_or(DEFAULT_DICTIONARY_ENABLED)
    }

    /// Returns `true` if statistics are enabled for a column.
    pub fn statistics_enabled(&self, col: &ColumnPath) -> bool {
        self.column_properties
            .get(col)
            .and_then(|c| c.statistics_enabled())
            .or_else(|| self.default_column_properties.statistics_enabled())
            .unwrap_or(DEFAULT_STATISTICS_ENABLED)
    }

    /// Returns max size for statistics.
    /// Only applicable if statistics are enabled.
    pub fn max_statistics_size(&self, col: &ColumnPath) -> usize {
        self.column_properties
            .get(col)
            .and_then(|c| c.max_statistics_size())
            .or_else(|| self.default_column_properties.max_statistics_size())
            .unwrap_or(DEFAULT_MAX_STATISTICS_SIZE)
    }
}

/// Writer properties builder.
pub struct WriterPropertiesBuilder {
    data_pagesize_limit: usize,
    dictionary_pagesize_limit: usize,
    write_batch_size: usize,
    max_row_group_size: usize,
    writer_version: WriterVersion,
    created_by: String,
    default_column_properties: ColumnProperties,
    column_properties: HashMap<ColumnPath, ColumnProperties>,
}

impl WriterPropertiesBuilder {
    /// Returns default state of the builder.
    fn with_defaults() -> Self {
        Self {
            data_pagesize_limit: DEFAULT_PAGE_SIZE,
            dictionary_pagesize_limit: DEFAULT_DICTIONARY_PAGE_SIZE_LIMIT,
            write_batch_size: DEFAULT_WRITE_BATCH_SIZE,
            max_row_group_size: DEFAULT_MAX_ROW_GROUP_SIZE,
            writer_version: DEFAULT_WRITER_VERSION,
            created_by: DEFAULT_CREATED_BY.to_string(),
            default_column_properties: ColumnProperties::new(),
            column_properties: HashMap::new(),
        }
    }

    /// Finalizes the configuration and returns immutable writer properties struct.
    pub fn build(self) -> WriterProperties {
        WriterProperties {
            data_pagesize_limit: self.data_pagesize_limit,
            dictionary_pagesize_limit: self.dictionary_pagesize_limit,
            write_batch_size: self.write_batch_size,
            max_row_group_size: self.max_row_group_size,
            writer_version: self.writer_version,
            created_by: self.created_by,
            default_column_properties: self.default_column_properties,
            column_properties: self.column_properties,
        }
    }

    // ----------------------------------------------------------------------
    // Writer properies related to a file

    /// Sets writer version.
    pub fn set_writer_version(mut self, value: WriterVersion) -> Self {
        self.writer_version = value;
        self
    }

    /// Sets data page size limit.
    pub fn set_data_pagesize_limit(mut self, value: usize) -> Self {
        self.data_pagesize_limit = value;
        self
    }

    /// Sets dictionary page size limit.
    pub fn set_dictionary_pagesize_limit(mut self, value: usize) -> Self {
        self.dictionary_pagesize_limit = value;
        self
    }

    /// Sets write batch size.
    pub fn set_write_batch_size(mut self, value: usize) -> Self {
        self.write_batch_size = value;
        self
    }

    /// Sets max size for a row group.
    pub fn set_max_row_group_size(mut self, value: usize) -> Self {
        self.max_row_group_size = value;
        self
    }

    /// Sets "created by" property.
    pub fn set_created_by(mut self, value: String) -> Self {
        self.created_by = value;
        self
    }

    // ----------------------------------------------------------------------
    // Setters for any column (global)

    /// Sets encoding for any column.
    ///
    /// If dictionary is not enabled, this is treated as a primary encoding for all
    /// columns. In case when dictionary is enabled for any column, this value is
    /// considered to be a fallback encoding for that column.
    ///
    /// Panics if user tries to set dictionary encoding here, regardless of dictinoary
    /// encoding flag being set.
    pub fn set_encoding(mut self, value: Encoding) -> Self {
        self.default_column_properties.set_encoding(value);
        self
    }

    /// Sets compression codec for any column.
    pub fn set_compression(mut self, value: Compression) -> Self {
        self.default_column_properties.set_compression(value);
        self
    }

    /// Sets flag to enable/disable dictionary encoding for any column.
    ///
    /// Use this method to set dictionary encoding, instead of explicitly specifying
    /// encoding in `set_encoding` method.
    pub fn set_dictionary_enabled(mut self, value: bool) -> Self {
        self.default_column_properties.set_dictionary_enabled(value);
        self
    }

    /// Sets flag to enable/disable statistics for any column.
    pub fn set_statistics_enabled(mut self, value: bool) -> Self {
        self.default_column_properties.set_statistics_enabled(value);
        self
    }

    /// Sets max statistics size for any column.
    /// Applicable only if statistics are enabled.
    pub fn set_max_statistics_size(mut self, value: usize) -> Self {
        self.default_column_properties
            .set_max_statistics_size(value);
        self
    }

    // ----------------------------------------------------------------------
    // Setters for a specific column

    /// Helper method to get existing or new mutable reference of column properties.
    #[inline]
    fn get_mut_props(&mut self, col: ColumnPath) -> &mut ColumnProperties {
        self.column_properties
            .entry(col)
            .or_insert(ColumnProperties::new())
    }

    /// Sets encoding for a column.
    /// Takes precedence over globally defined settings.
    ///
    /// If dictionary is not enabled, this is treated as a primary encoding for this
    /// column. In case when dictionary is enabled for this column, either through
    /// global defaults or explicitly, this value is considered to be a fallback
    /// encoding for this column.
    ///
    /// Panics if user tries to set dictionary encoding here, regardless of dictinoary
    /// encoding flag being set.
    pub fn set_column_encoding(mut self, col: ColumnPath, value: Encoding) -> Self {
        self.get_mut_props(col).set_encoding(value);
        self
    }

    /// Sets compression codec for a column.
    /// Takes precedence over globally defined settings.
    pub fn set_column_compression(mut self, col: ColumnPath, value: Compression) -> Self {
        self.get_mut_props(col).set_compression(value);
        self
    }

    /// Sets flag to enable/disable dictionary encoding for a column.
    /// Takes precedence over globally defined settings.
    pub fn set_column_dictionary_enabled(mut self, col: ColumnPath, value: bool) -> Self {
        self.get_mut_props(col).set_dictionary_enabled(value);
        self
    }

    /// Sets flag to enable/disable statistics for a column.
    /// Takes precedence over globally defined settings.
    pub fn set_column_statistics_enabled(mut self, col: ColumnPath, value: bool) -> Self {
        self.get_mut_props(col).set_statistics_enabled(value);
        self
    }

    /// Sets max size for statistics for a column.
    /// Takes precedence over globally defined settings.
    pub fn set_column_max_statistics_size(
        mut self,
        col: ColumnPath,
        value: usize,
    ) -> Self {
        self.get_mut_props(col).set_max_statistics_size(value);
        self
    }
}

/// Container for column properties that can be changed as part of writer.
///
/// If a field is `None`, it means that no specific value has been set for this column,
/// so some subsequent or default value must be used.
#[derive(Debug, Clone, PartialEq)]
struct ColumnProperties {
    encoding: Option<Encoding>,
    codec: Option<Compression>,
    dictionary_enabled: Option<bool>,
    statistics_enabled: Option<bool>,
    max_statistics_size: Option<usize>,
}

impl ColumnProperties {
    /// Initialise column properties with default values.
    fn new() -> Self {
        Self {
            encoding: None,
            codec: None,
            dictionary_enabled: None,
            statistics_enabled: None,
            max_statistics_size: None,
        }
    }

    /// Sets encoding for this column.
    ///
    /// If dictionary is not enabled, this is treated as a primary encoding for a column.
    /// In case when dictionary is enabled for a column, this value is considered to
    /// be a fallback encoding.
    ///
    /// Panics if user tries to set dictionary encoding here, regardless of dictinoary
    /// encoding flag being set. Use `set_dictionary_enabled` method to enable dictionary
    /// for a column.
    fn set_encoding(&mut self, value: Encoding) {
        if value == Encoding::PLAIN_DICTIONARY || value == Encoding::RLE_DICTIONARY {
            panic!("Dictionary encoding can not be used as fallback encoding");
        }
        self.encoding = Some(value);
    }

    /// Sets compression codec for this column.
    fn set_compression(&mut self, value: Compression) {
        self.codec = Some(value);
    }

    /// Sets whether or not dictionary encoding is enabled for this column.
    fn set_dictionary_enabled(&mut self, enabled: bool) {
        self.dictionary_enabled = Some(enabled);
    }

    /// Sets whether or not statistics are enabled for this column.
    fn set_statistics_enabled(&mut self, enabled: bool) {
        self.statistics_enabled = Some(enabled);
    }

    /// Sets max size for statistics for this column.
    fn set_max_statistics_size(&mut self, value: usize) {
        self.max_statistics_size = Some(value);
    }

    /// Returns optional encoding for this column.
    fn encoding(&self) -> Option<Encoding> {
        self.encoding
    }

    /// Returns optional compression codec for this column.
    fn compression(&self) -> Option<Compression> {
        self.codec
    }

    /// Returns `Some(true)` if dictionary encoding is enabled for this column, if
    /// disabled then returns `Some(false)`. If result is `None`, then no setting has
    /// been provided.
    fn dictionary_enabled(&self) -> Option<bool> {
        self.dictionary_enabled
    }

    /// Returns `Some(true)` if statistics are enabled for this column, if disabled then
    /// returns `Some(false)`. If result is `None`, then no setting has been provided.
    fn statistics_enabled(&self) -> Option<bool> {
        self.statistics_enabled
    }

    /// Returns optional max size in bytes for statistics.
    fn max_statistics_size(&self) -> Option<usize> {
        self.max_statistics_size
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_writer_version() {
        assert_eq!(WriterVersion::PARQUET_1_0.as_num(), 1);
        assert_eq!(WriterVersion::PARQUET_2_0.as_num(), 2);
    }

    #[test]
    fn test_writer_properties_default_settings() {
        let props = WriterProperties::builder().build();
        assert_eq!(props.data_pagesize_limit(), DEFAULT_PAGE_SIZE);
        assert_eq!(
            props.dictionary_pagesize_limit(),
            DEFAULT_DICTIONARY_PAGE_SIZE_LIMIT
        );
        assert_eq!(props.write_batch_size(), DEFAULT_WRITE_BATCH_SIZE);
        assert_eq!(props.max_row_group_size(), DEFAULT_MAX_ROW_GROUP_SIZE);
        assert_eq!(props.writer_version(), DEFAULT_WRITER_VERSION);
        assert_eq!(props.created_by(), DEFAULT_CREATED_BY);
        assert_eq!(props.encoding(&ColumnPath::from("col")), None);
        assert_eq!(
            props.compression(&ColumnPath::from("col")),
            DEFAULT_COMPRESSION
        );
        assert_eq!(
            props.dictionary_enabled(&ColumnPath::from("col")),
            DEFAULT_DICTIONARY_ENABLED
        );
        assert_eq!(
            props.statistics_enabled(&ColumnPath::from("col")),
            DEFAULT_STATISTICS_ENABLED
        );
        assert_eq!(
            props.max_statistics_size(&ColumnPath::from("col")),
            DEFAULT_MAX_STATISTICS_SIZE
        );
    }

    #[test]
    fn test_writer_properties_dictionary_encoding() {
        // dictionary encoding is not configurable, and it should be the same for both
        // writer version 1 and 2.
        for version in vec![WriterVersion::PARQUET_1_0, WriterVersion::PARQUET_2_0] {
            let props = WriterProperties::builder()
                .set_writer_version(version)
                .build();
            assert_eq!(props.dictionary_page_encoding(), Encoding::PLAIN);
            assert_eq!(
                props.dictionary_data_page_encoding(),
                Encoding::RLE_DICTIONARY
            );
        }
    }

    #[test]
    #[should_panic(expected = "Dictionary encoding can not be used as fallback encoding")]
    fn test_writer_properties_panic_when_plain_dictionary_is_fallback() {
        // Should panic when user specifies dictionary encoding as fallback encoding.
        WriterProperties::builder()
            .set_encoding(Encoding::PLAIN_DICTIONARY)
            .build();
    }

    #[test]
    #[should_panic(expected = "Dictionary encoding can not be used as fallback encoding")]
    fn test_writer_properties_panic_when_rle_dictionary_is_fallback() {
        // Should panic when user specifies dictionary encoding as fallback encoding.
        WriterProperties::builder()
            .set_encoding(Encoding::RLE_DICTIONARY)
            .build();
    }

    #[test]
    #[should_panic(expected = "Dictionary encoding can not be used as fallback encoding")]
    fn test_writer_properties_panic_when_dictionary_is_enabled() {
        WriterProperties::builder()
            .set_dictionary_enabled(true)
            .set_column_encoding(ColumnPath::from("col"), Encoding::RLE_DICTIONARY)
            .build();
    }

    #[test]
    #[should_panic(expected = "Dictionary encoding can not be used as fallback encoding")]
    fn test_writer_properties_panic_when_dictionary_is_disabled() {
        WriterProperties::builder()
            .set_dictionary_enabled(false)
            .set_column_encoding(ColumnPath::from("col"), Encoding::RLE_DICTIONARY)
            .build();
    }

    #[test]
    fn test_writer_properties_builder() {
        let props = WriterProperties::builder()
            // file settings
            .set_writer_version(WriterVersion::PARQUET_2_0)
            .set_data_pagesize_limit(10)
            .set_dictionary_pagesize_limit(20)
            .set_write_batch_size(30)
            .set_max_row_group_size(40)
            .set_created_by("default".to_owned())
            // global column settings
            .set_encoding(Encoding::DELTA_BINARY_PACKED)
            .set_compression(Compression::GZIP)
            .set_dictionary_enabled(false)
            .set_statistics_enabled(false)
            .set_max_statistics_size(50)
            // specific column settings
            .set_column_encoding(ColumnPath::from("col"), Encoding::RLE)
            .set_column_compression(ColumnPath::from("col"), Compression::SNAPPY)
            .set_column_dictionary_enabled(ColumnPath::from("col"), true)
            .set_column_statistics_enabled(ColumnPath::from("col"), true)
            .set_column_max_statistics_size(ColumnPath::from("col"), 123)
            .build();

        assert_eq!(props.writer_version(), WriterVersion::PARQUET_2_0);
        assert_eq!(props.data_pagesize_limit(), 10);
        assert_eq!(props.dictionary_pagesize_limit(), 20);
        assert_eq!(props.write_batch_size(), 30);
        assert_eq!(props.max_row_group_size(), 40);
        assert_eq!(props.created_by(), "default");

        assert_eq!(
            props.encoding(&ColumnPath::from("a")),
            Some(Encoding::DELTA_BINARY_PACKED)
        );
        assert_eq!(props.compression(&ColumnPath::from("a")), Compression::GZIP);
        assert_eq!(props.dictionary_enabled(&ColumnPath::from("a")), false);
        assert_eq!(props.statistics_enabled(&ColumnPath::from("a")), false);
        assert_eq!(props.max_statistics_size(&ColumnPath::from("a")), 50);

        assert_eq!(
            props.encoding(&ColumnPath::from("col")),
            Some(Encoding::RLE)
        );
        assert_eq!(
            props.compression(&ColumnPath::from("col")),
            Compression::SNAPPY
        );
        assert_eq!(props.dictionary_enabled(&ColumnPath::from("col")), true);
        assert_eq!(props.statistics_enabled(&ColumnPath::from("col")), true);
        assert_eq!(props.max_statistics_size(&ColumnPath::from("col")), 123);
    }

    #[test]
    fn test_writer_properties_builder_partial_defaults() {
        let props = WriterProperties::builder()
            .set_encoding(Encoding::DELTA_BINARY_PACKED)
            .set_compression(Compression::GZIP)
            .set_column_encoding(ColumnPath::from("col"), Encoding::RLE)
            .build();

        assert_eq!(
            props.encoding(&ColumnPath::from("col")),
            Some(Encoding::RLE)
        );
        assert_eq!(
            props.compression(&ColumnPath::from("col")),
            Compression::GZIP
        );
        assert_eq!(
            props.dictionary_enabled(&ColumnPath::from("col")),
            DEFAULT_DICTIONARY_ENABLED
        );
    }
}


text:
static const int kButtonCornerRadius = 5;

@implementation HTLRoundButton

- (void)configure {
    self.layer.cornerRadius = kButtonCornerRadius;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self configure];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];

    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    return self;
}

@end

redpajama_set_name: RedPajamaGithub


text:
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormControl } from '@angular/forms';

import { Comment, Diff, Thread } from '@/core/proto';
import { DiffUpdateService, NotificationService } from '@/core/services';
import { ThreadService } from '../../thread.service';

@Component({
  selector: 'thread-edit-comment',
  templateUrl: './thread-edit-comment.component.html',
  styleUrls: ['./thread-edit-comment.component.scss'],
  providers: [ThreadService],
})
export class ThreadEditCommentComponent implements OnInit {
  textarea = new FormControl();

  @Input() diff: Diff;
  @Input() thread: Thread;
  @Input() comment: Comment;
  @Input() commentIndex: number;
  @Output() closeEmitter = new EventEmitter<void>();

  constructor(
    private diffUpdateService: DiffUpdateService,
    private notificationService: NotificationService,
    private threadService: ThreadService,
  ) { }

  ngOnInit() {
    this.textarea.setValue(this.comment.getContent());
  }

  close(): void {
    this.closeEmitter.emit();
  }

  // Saves comment in firebase
  save(): void {
    const comment: Comment = this.getComment(this.comment.getId());
    if (comment) {
      comment.setContent(this.textarea.value);
      comment.setIsModified(true);
      this.diffUpdateService.saveComment(this.diff);
    }
    this.close();
  }

  // While user was editing a comment, diff could be changed.
  // So we don't change current comment, we take comment from updated diff and change it instead.
  getComment(id: string): Comment {
    const updatedThread: Thread = this.threadService.getThread(this.diff, this.thread);
    if (!updatedThread) {
      this.notificationService.error('Sorry, but the thread is already deleted :(');
      return;
    }

    for (const comment of updatedThread.getCommentList()) {
      if (comment.getId() === id) {
        return comment;
      }
    }

    this.notificationService.error('Sorry, but the comment is already deleted :(');
  }
}


text:
package org.wso2.siddhi.query.api.execution.query.input.state;

/**
 * Count state element used in patterns
 */
public class CountStateElement implements StateElement {

    private static final long serialVersionUID = 1L;
    public static final int ANY = -1;
    private StreamStateElement streamStateElement;
    private int minCount = ANY;
    private int maxCount = ANY;
    private int[] queryContextStartIndex;
    private int[] queryContextEndIndex;

    public CountStateElement(StreamStateElement streamStateElement, int minCount, int maxCount) {
        this.streamStateElement = streamStateElement;
        this.minCount = minCount;
        this.maxCount = maxCount;
    }

    public int getMinCount() {
        return minCount;
    }

    public int getMaxCount() {
        return maxCount;
    }

    public StreamStateElement getStreamStateElement() {
        return streamStateElement;
    }

    @Override
    public String toString() {
        return "CountStateElement{" +
                "streamStateElement=" + streamStateElement +
                ", minCount=" + minCount +
                ", maxCount=" + maxCount +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof CountStateElement)) {
            return false;
        }

        CountStateElement that = (CountStateElement) o;

        if (maxCount != that.maxCount) {
            return false;
        }
        if (minCount != that.minCount) {
            return false;
        }
        if (streamStateElement != null ? !streamStateElement.equals(that.streamStateElement) : that
                .streamStateElement != null) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int result = streamStateElement != null ? streamStateElement.hashCode() : 0;
        result = 31 * result + minCount;
        result = 31 * result + maxCount;
        return result;
    }

    @Override
    public int[] getQueryContextStartIndex() {
        return queryContextStartIndex;
    }

    @Override
    public void setQueryContextStartIndex(int[] lineAndColumn) {
        queryContextStartIndex = lineAndColumn;
    }

    @Override
    public int[] getQueryContextEndIndex() {
        return queryContextEndIndex;
    }

    @Override
    public void setQueryContextEndIndex(int[] lineAndColumn) {
        queryContextEndIndex = lineAndColumn;
    }
}


text:
module Fog
  module Compute
    class Cloudstack

      class Real
        # Creates a egress firewall rule for a given network
        #
        # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.4/root_admin/createEgressFirewallRule.html]
        def create_egress_firewall_rule(*args)
          options = {}
          if args[0].is_a? Hash
            options = args[0]
            options.merge!('command' => 'createEgressFirewallRule')
          else
            options.merge!('command' => 'createEgressFirewallRule',
            'networkid' => args[0],
            'protocol' => args[1])
          end
          request(options)
        end
      end

    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Phpml\Tests\SupportVectorMachine;

use Phpml\Exception\InvalidArgumentException;
use Phpml\Exception\InvalidOperationException;
use Phpml\Exception\LibsvmCommandException;
use Phpml\SupportVectorMachine\Kernel;
use Phpml\SupportVectorMachine\SupportVectorMachine;
use Phpml\SupportVectorMachine\Type;
use PHPUnit\Framework\TestCase;

class SupportVectorMachineTest extends TestCase
{
    public function testTrainCSVCModelWithLinearKernel(): void
    {
        $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
        $labels = ['a', 'a', 'a', 'b', 'b', 'b'];

        $model =
            'svm_type c_svc
kernel_type linear
nr_class 2
total_sv 2
rho 0
label 0 1
nr_sv 1 1
SV
0.25 1:2 2:4
-0.25 1:4 2:2
';

        $svm = new SupportVectorMachine(Type::C_SVC, Kernel::LINEAR, 100.0);
        $svm->train($samples, $labels);

        $this->assertEquals($model, $svm->getModel());
    }

    public function testTrainCSVCModelWithProbabilityEstimate(): void
    {
        $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
        $labels = ['a', 'a', 'a', 'b', 'b', 'b'];

        $svm = new SupportVectorMachine(
            Type::C_SVC,
            Kernel::LINEAR,
            100.0,
            0.5,
            3,
            null,
            0.0,
            0.1,
            0.01,
            100,
            true,
            true
        );
        $svm->train($samples, $labels);

        $this->assertContains(PHP_EOL.'probA ', $svm->getModel());
        $this->assertContains(PHP_EOL.'probB ', $svm->getModel());
    }

    public function testPredictSampleWithLinearKernel(): void
    {
        $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
        $labels = ['a', 'a', 'a', 'b', 'b', 'b'];

        $svm = new SupportVectorMachine(Type::C_SVC, Kernel::LINEAR, 100.0);
        $svm->train($samples, $labels);

        $predictions = $svm->predict([
            [3, 2],
            [2, 3],
            [4, -5],
        ]);

        $this->assertEquals('b', $predictions[0]);
        $this->assertEquals('a', $predictions[1]);
        $this->assertEquals('b', $predictions[2]);
    }

    public function testPredictSampleFromMultipleClassWithRbfKernel(): void
    {
        $samples = [
            [1, 3], [1, 4], [1, 4],
            [3, 1], [4, 1], [4, 2],
            [-3, -1], [-4, -1], [-4, -2],
        ];
        $labels = [
            'a', 'a', 'a',
            'b', 'b', 'b',
            'c', 'c', 'c',
        ];

        $svm = new SupportVectorMachine(Type::C_SVC, Kernel::RBF, 100.0);
        $svm->train($samples, $labels);

        $predictions = $svm->predict([
            [1, 5],
            [4, 3],
            [-4, -3],
        ]);

        $this->assertEquals('a', $predictions[0]);
        $this->assertEquals('b', $predictions[1]);
        $this->assertEquals('c', $predictions[2]);
    }

    public function testPredictProbability(): void
    {
        $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
        $labels = ['a', 'a', 'a', 'b', 'b', 'b'];

        $svm = new SupportVectorMachine(
            Type::C_SVC,
            Kernel::LINEAR,
            100.0,
            0.5,
            3,
            null,
            0.0,
            0.1,
            0.01,
            100,
            true,
            true
        );
        $svm->train($samples, $labels);

        $predictions = $svm->predictProbability([
            [3, 2],
            [2, 3],
            [4, -5],
        ]);

        $this->assertTrue($predictions[0]['a'] < $predictions[0]['b']);
        $this->assertTrue($predictions[1]['a'] > $predictions[1]['b']);
        $this->assertTrue($predictions[2]['a'] < $predictions[2]['b']);

        // Should be true because the latter is farther from the decision boundary
        $this->assertTrue($predictions[0]['b'] < $predictions[2]['b']);
    }

    public function testThrowExceptionWhenVarPathIsNotWritable(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('is not writable');
        $svm = new SupportVectorMachine(Type::C_SVC, Kernel::RBF);
        $svm->setVarPath('var-path');
    }

    public function testThrowExceptionWhenBinPathDoesNotExist(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('does not exist');
        $svm = new SupportVectorMachine(Type::C_SVC, Kernel::RBF);
        $svm->setBinPath('bin-path');
    }

    public function testThrowExceptionWhenFileIsNotFoundInBinPath(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('not found');
        $svm = new SupportVectorMachine(Type::C_SVC, Kernel::RBF);
        $svm->setBinPath('var');
    }

    public function testThrowExceptionWhenLibsvmFailsDuringTrain(): void
    {
        $this->expectException(LibsvmCommandException::class);
        $this->expectExceptionMessage('ERROR: unknown svm type');

        $svm = new SupportVectorMachine(99, Kernel::RBF);
        $svm->train([], []);
    }

    public function testThrowExceptionWhenLibsvmFailsDuringPredict(): void
    {
        $this->expectException(LibsvmCommandException::class);
        $this->expectExceptionMessage('can\'t open model file');

        $svm = new SupportVectorMachine(Type::C_SVC, Kernel::RBF);
        $svm->predict([1]);
    }

    public function testThrowExceptionWhenPredictProbabilityCalledWithoutProperModel(): void
    {
        $this->expectException(InvalidOperationException::class);
        $this->expectExceptionMessage('Model does not support probabiliy estimates');

        $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
        $labels = ['a', 'a', 'a', 'b', 'b', 'b'];

        $svm = new SupportVectorMachine(Type::C_SVC, Kernel::LINEAR, 100.0);
        $svm->train($samples, $labels);

        $predictions = $svm->predictProbability([
            [3, 2],
            [2, 3],
            [4, -5],
        ]);
    }
}


text:
class AtmLocationRequestOptions(object):

    KILOMETER = 'KILOMETER'
    MILE = 'MILE'
    SUPPORT_EMV_YES = 1
    SUPPORT_EMV_NO = 2
    SUPPORT_EMV_UNKNOWN = 0
    INTERNATIONAL_MAESTRO_ACCEPTED_YES = 1

    def __init__(self, page_offset, page_length):
        self.page_offset = page_offset
        self.page_length = page_length
        self.category = ''
        self.address_line1 = ''
        self.address_line2 = ''
        self.city = ''
        self.country_subdivision = ''
        self.postal_code = ''
        self.country = ''
        self.latitude = ''
        self.longitude = ''
        self.distance_unit = ''
        self.radius = ''
        self.support_emv = ''
        self.international_maestro_accepted = ''


text:
<script>
if (window.testRunner)
    testRunner.dumpAsText();
</script>
<meta http-equiv="Content-Security-Policy" content="frame-src about:">
This iframe should not be blocked by Content-Security-Policy:
<iframe src="about:blank"></iframe>


text:
package org.keycloak.adapters;

import java.io.IOException;

import org.jboss.logging.Logger;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.RSATokenVerifier;
import org.keycloak.VerificationException;
import org.keycloak.constants.AdapterConstants;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.util.KeycloakUriBuilder;

/**
 * @author Marek Posolda
 */
public class CookieTokenStore {

    private static final Logger log = Logger.getLogger(CookieTokenStore.class);
    private static final String DELIM = "___";

    public static void setTokenCookie(KeycloakDeployment deployment, HttpFacade facade, RefreshableKeycloakSecurityContext session) {
        log.debugf("Set new %s cookie now", AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE);
        String accessToken = session.getTokenString();
        String idToken = session.getIdTokenString();
        String refreshToken = session.getRefreshToken();
        String cookie = new StringBuilder(accessToken).append(DELIM)
                .append(idToken).append(DELIM)
                .append(refreshToken).toString();

        String cookiePath = getContextPath(facade);
        facade.getResponse().setCookie(AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE, cookie, cookiePath, null, -1, deployment.getSslRequired().isRequired(facade.getRequest().getRemoteAddr()), true);
    }

    public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> getPrincipalFromCookie(KeycloakDeployment deployment, HttpFacade facade, AdapterTokenStore tokenStore) {
        OIDCHttpFacade.Cookie cookie = facade.getRequest().getCookie(AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE);
        if (cookie == null) {
            log.debug("Not found adapter state cookie in current request");
            return null;
        }

        String cookieVal = cookie.getValue();

        String[] tokens = cookieVal.split(DELIM);
        if (tokens.length != 3) {
            log.warnf("Invalid format of %s cookie. Count of tokens: %s, expected 3", AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE, tokens.length);
            return null;
        }

        String accessTokenString = tokens[0];
        String idTokenString = tokens[1];
        String refreshTokenString = tokens[2];

        try {
            // Skip check if token is active now. It's supposed to be done later by the caller
            AccessToken accessToken = RSATokenVerifier.verifyToken(accessTokenString, deployment.getRealmKey(), deployment.getRealmInfoUrl(), false);
            IDToken idToken;
            if (idTokenString != null && idTokenString.length() > 0) {
                JWSInput input = new JWSInput(idTokenString);
                try {
                    idToken = input.readJsonContent(IDToken.class);
                } catch (IOException e) {
                    throw new VerificationException(e);
                }
            } else {
                idToken = null;
            }

            log.debug("Token Verification succeeded!");
            RefreshableKeycloakSecurityContext secContext = new RefreshableKeycloakSecurityContext(deployment, tokenStore, accessTokenString, accessToken, idTokenString, idToken, refreshTokenString);
            return new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(AdapterUtils.getPrincipalName(deployment, accessToken), secContext);
        } catch (VerificationException ve) {
            log.warn("Failed verify token", ve);
            return null;
        }
    }

    public static void removeCookie(HttpFacade facade) {
        String cookiePath = getContextPath(facade);
        facade.getResponse().resetCookie(AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE, cookiePath);
    }

    private static String getContextPath(HttpFacade facade) {
        String uri = facade.getRequest().getURI();
        String path = KeycloakUriBuilder.fromUri(uri).getPath();
        int index = path.indexOf("/", 1);
        return index == -1 ? path : path.substring(0, index);
    }
}


text:
package de.marius_oe.cfs.cryption;

import static org.junit.Assert.assertArrayEquals;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.junit.Test;

public class CrypterTest {

	private static final byte[] testInput = new byte[] { 43, -97, -86, 14, -63, 112, 100, 64, -23, 0, 64, -54, -85, 68, -116, -75, -64, -76, 54, -127 };

	/**
	 * Testing the if the output of an encrypted and decrypted data stream is
	 * equals to the input data.
	 */
	@Test
	public void decryptionAndEncryptionTest() {

		boolean useCompression = false;

		// Encryption
		ByteArrayInputStream plainInputStream = new ByteArrayInputStream(testInput);
		ByteArrayOutputStream encryptedOutputStream = new ByteArrayOutputStream();

		Crypter.encrypt(plainInputStream, encryptedOutputStream, useCompression);

		// Decryption
		InputStream cryptedInputStream = new ByteArrayInputStream(encryptedOutputStream.toByteArray());
		ByteArrayOutputStream plainOutputStream = new ByteArrayOutputStream();

		Crypter.decrypt(cryptedInputStream, plainOutputStream, useCompression);

		assertArrayEquals(testInput, plainOutputStream.toByteArray());
	}

}


text:
package io.github.imsmobile.fahrplan.setting;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.StringRes;

import io.github.imsmobile.fahrplan.R;

public class Setting {

    private final Context context;

    public Setting(Context context) {
        this.context = context;
    }

    public boolean getBooleanSettings(@StringRes int key, boolean defaultValue) {
        return Boolean.valueOf(getSettings(key, String.valueOf(defaultValue)));
    }

    public String getSettings(@StringRes int key, String defaultValue) {
        SharedPreferences preferences = context.getSharedPreferences(context.getString(R.string.setting_name), Context.MODE_PRIVATE);
        return preferences.getString(context.getString(key), defaultValue);
    }

    public void saveBooleanSettings(int key, boolean value) {
        saveSettings(key, String.valueOf(value));
    }

    public void saveSettings(int key, String value) {
        SharedPreferences preferences = context.getSharedPreferences(context.getString(R.string.setting_name), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(context.getString(key), value);
        editor.apply();
    }
}


text:
layout: post
---

The primary way scope is created is by declaring a new function.

Each function declared creates a new scope for itself.

Variables therefore belong to the function, and can be used and reused throughout the entirety of the function, including within any nested scopes.

## HIDING IN SCOPE

Function scope can be used to "hide" variables and functions.

This is common when defining an API for a module/object - only return/expose what is minimally required and restrict access to everything else.

{% highlight javascript %}
function module(a){

	console.log(moduleHelper(a));

}

function moduleHelper(a){

	return a-b;

}

var b = 5;

console.log(b); // 5
moduleHelper(10); // 5
module(10); // 5
{% endhighlight %}

Because in the above scenario var b and moduleHelper() are actually private to module and therefore shouldn't be in the outer (global) scope, we can rework the scope tree to restrict external access to these, as below...

{% highlight javascript %}
function module(a){

	var b = 5;

	function moduleHelper(a){

		return a-b;

	}

	console.log(moduleHelper(a));

}

console.log(b); // ReferenceError, b is not defined
moduleHelper(10); // ReferenceError: moduleHelper is not defined
module(10); // 5
{% endhighlight %}


text:
package com.mastertheboss.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.mastertheboss.model.SimpleProperty;

@Stateless

public class  ServiceBean   {

	@Inject
	private Event<SimpleProperty> propEventSrc;

	@Inject
	private EntityManager em;

	public void put(SimpleProperty p){

	      em.persist(p);
	      propEventSrc.fire(p);

	}

	public void delete(SimpleProperty p){

		Query query = em.createQuery("delete FROM SimpleProperty p where p.key='"+p.getKey()+"'");

		query.executeUpdate();
		propEventSrc.fire(p);

	}

}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />

  <title>
  Tag → verification

   | Il y a du thé renversé au bord de la table !
</title>

  <meta name="author" content="David Teller" />
  <meta name="description" content="Aventure! Excitement! Random ramblings by David Teller!" />

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:site" content="@ImYoric" />
  <meta name="twitter:title" content="Il y a du thé renversé au bord de la table !" />
  <meta name="twitter:description" content="Aventure! Excitement! Random ramblings by David Teller!" />
  <meta name="twitter:image" content="https://yoric.github.io/img/avatar.jpg" />

  <meta property="og:type" content="website" />
  <meta property="og:title" content="Il y a du thé renversé au bord de la table !" />
  <meta property="og:description" content="Aventure! Excitement! Random ramblings by David Teller!" />
  <meta property="og:url" content="https://yoric.github.io/tags/verification/" />
  <meta property="og:image" content="https://yoric.github.io/img/avatar.jpg" />

<meta name="generator" content="Hugo 0.75.1" />

<link rel="canonical" href="https://yoric.github.io/tags/verification/" />
<link rel="alternative" href="https://yoric.github.io/index.xml" title="Il y a du thé renversé au bord de la table !" type="application/atom+xml" />

<meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="format-detection" content="telephone=no,email=no,adress=no" />
<meta http-equiv="Cache-Control" content="no-transform" />

<meta name="robots" content="index,follow" />
<meta name="referrer" content="origin-when-cross-origin" />

<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="Il y a du thé renversé au bord de la table !" />
<meta name="msapplication-tooltip" content="Il y a du thé renversé au bord de la table !" />
<meta name='msapplication-navbutton-color' content="#5fbf5e" />
<meta name="msapplication-TileColor" content="#5fbf5e" />
<meta name="msapplication-TileImage" content="/img/tile-image-windows.png" />
<link rel="icon" href="https://yoric.github.io/img/favicon.ico" />
<link rel="icon" type="image/png" sizes="16x16" href="https://yoric.github.io/img/favicon-16x16.png" />
<link rel="icon" type="image/png" sizes="32x32" href="https://yoric.github.io/img/favicon-32x32.png" />
<link rel="icon" sizes="192x192" href="https://yoric.github.io/img/touch-icon-android.png" />
<link rel="apple-touch-icon" href="https://yoric.github.io/img/touch-icon-apple.png" />
<link rel="mask-icon" href="https://yoric.github.io/img/safari-pinned-tab.svg" color="#5fbf5e" />

<link rel="stylesheet" href="//cdn.bootcss.com/video.js/6.2.8/alt/video-js-cdn.min.css" />

<link rel="stylesheet" href="https://yoric.github.io/css/bundle.css" />

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">

Il y a du thé renversé au bord de la table !

Aventure! Excitement! Random ramblings by David Teller!

  <button class="menu-toggle" type="button">

  </button>

Main Menu

            Home

            About

            Categories

            Tags

Social Networks

Posts List

JavaScript Binary AST diaries - How to replace proving with validating for fun and profit

@David Teller · Feb 23, 2018 · 8 min read

In this entry, I'd like to discuss one of the most interesting and unusual aspects of the Binary AST: how we gain performance by turning proof-building into validation, and why this is very good news for performance (and maybe not so good news for file size).

    Read More →

© 2017-2020 Il y a du thé renversé au bord de la table !

Powered by Hugo with theme Nuo.


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bryologist 104(4): 568 (2001)

#### Original name
Cladonia cucullata S. Hammer

### Remarks
null


text:
<?xml version="1.0"?>

<document>
  <properties>
    <title>Building JMeter and Add-Ons</title>
  </properties>

Note to developers:
This is a very brief overview.
There is more infomation on the JMeter Wiki.

Building Add-Ons

There is no need to build JMeter if you just want to build an add-on.
Just download the binary archive and add the jars to the classpath.
You may want to also download the source so it can be used by the IDE.

See the extras/addons* files in the source tree for some suggestions

Building JMeter

Acquiring the source

The full source is distributed alongside the binary, or it can be downloaded from SVN.

The source archive and SVN do not contain any of the required library files.
These need to be downloaded by running the Ant command:

ant download_jars

Or you can download the binary distribution archive for a release and unpack it into the same directory structure as the source.
This will ensure that the lib/ directory contains the jar files needed for running JMeter.
There are a few additional jars that are needed to build JMeter, download these using:

ant download_jars

This will retrieve any missing jars.

Compiling and packaging JMeter using Ant

JMeter can be built entirely using Ant.
The basic command is:

ant [install]

See build.xml for the other targets that can be used.

Compiling and packaging JMeter using Eclipse

Once you have downloaded the source from SVN or the release archives and run the ant download_jars target to
install the dependent jars, you can configure Eclipse. The easiest way to do this is to replace the Eclipse .classpath
file with the eclipse.classpath file provided with JMeter. This will set up the source-paths and most of the libraries.

See also the file eclipse.readme.

</document>


text:
from thefuck.specific.git import git_support

@git_support
def match(command):
    return (' git clone ' in command.script
            and 'fatal: Too many arguments.' in command.output)

@git_support
def get_new_command(command):
    return command.script.replace(' git clone ', ' ', 1)


text:
DNSSEC Tests
============

Running the test

`ginkgo -- -ns=router-01.thecdn.example.com:53  -ds=ds-01.thecdn.example.com.`

Sample Output
```
Running Suite: Dnssec Suite
===========================
Random Seed: 1476984556
Will run 4 of 4 specs

2016/10/20 11:29:17 Nameserver router-01.thecdn.example.com:53
2016/10/20 11:29:17 DeliveryService ds-01.thecdn.example.com.
••••
Ran 4 of 4 Specs in 0.110 seconds
SUCCESS! -- 4 Passed | 0 Failed | 0 Pending | 0 Skipped PASS

Ginkgo ran 1 suite in 825.345359ms
Test Suite Passed
```


text:
<?php

namespace PayPal\Ipn\Exception;

class UnexpectedResponseStatusException extends \Exception {}


text:
define([
    'angular',
    'angularBootstrap',
    'angularUIRouter',
    'restangular',
    'angularUIUtils',
    'plusOne',
    './home/index',
    './design/index'
    ], function (ng) {
    'use strict';

    var module = ng.module('app', [
        'app.home',
        'app.design',
        'restangular',
        'ui.router'
    ]);

    module.config(
        [ '$stateProvider', '$urlRouterProvider', 'RestangularProvider',

        function ( $stateProvider, $urlRouterProvider , RestangularProvider) {
        $urlRouterProvider.otherwise( '/home' );
            RestangularProvider.setBaseUrl('../api/v1');
            RestangularProvider.setRequestSuffix('.json');

        }]);

    module.controller( 'AppCtrl',
        ['$scope', '$location',

        function ( $scope, $location ) {
        $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
            if ( angular.isDefined( toState.data.pageTitle ) ) {
                $scope.pageTitle = toState.data.pageTitle + ' | Angular-Enterprise-Kickstart' ;
            }
        });
    }]);

    return module;
});


text:
group node['cassandra']['group'] do
  system node['cassandra']['system_user']
  only_if { node['cassandra']['setup_user'] }
  action :create
end

user node['cassandra']['user'] do
  comment 'Cassandra Server user'
  gid node['cassandra']['group']
  home node['cassandra']['user_home'] if node['cassandra']['user_home']
  system node['cassandra']['system_user']
  shell '/bin/bash'
  only_if { node['cassandra']['setup_user'] }
  action :create
end

group node['cassandra']['group'] do
  members [node['cassandra']['user']]
  append true
  only_if { node['cassandra']['setup_user'] }
  action :modify
end


text:
/**
 * EscalationRules.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.sforce.soap._2006._04.metadata;

public class EscalationRules  extends com.sforce.soap._2006._04.metadata.Metadata  implements java.io.Serializable {
    private com.sforce.soap._2006._04.metadata.EscalationRule[] escalationRule;

    public EscalationRules() {
    }

    public EscalationRules(
           java.lang.String fullName,
           com.sforce.soap._2006._04.metadata.EscalationRule[] escalationRule) {
        super(
            fullName);
        this.escalationRule = escalationRule;
    }

    /**
     * Gets the escalationRule value for this EscalationRules.
     *
     * @return escalationRule
     */
    public com.sforce.soap._2006._04.metadata.EscalationRule[] getEscalationRule() {
        return escalationRule;
    }

    /**
     * Sets the escalationRule value for this EscalationRules.
     *
     * @param escalationRule
     */
    public void setEscalationRule(com.sforce.soap._2006._04.metadata.EscalationRule[] escalationRule) {
        this.escalationRule = escalationRule;
    }

    public com.sforce.soap._2006._04.metadata.EscalationRule getEscalationRule(int i) {
        return this.escalationRule[i];
    }

    public void setEscalationRule(int i, com.sforce.soap._2006._04.metadata.EscalationRule _value) {
        this.escalationRule[i] = _value;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof EscalationRules)) return false;
        EscalationRules other = (EscalationRules) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = super.equals(obj) &&
            ((this.escalationRule==null && other.getEscalationRule()==null) ||
             (this.escalationRule!=null &&
              java.util.Arrays.equals(this.escalationRule, other.getEscalationRule())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = super.hashCode();
        if (getEscalationRule() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getEscalationRule());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getEscalationRule(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(EscalationRules.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "EscalationRules"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("escalationRule");
        elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "escalationRule"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "EscalationRule"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        elemField.setMaxOccursUnbounded(true);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
package org.cch.exercise.jms;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableJms
@EnableScheduling
public class Application {

    // Default jmsListenerContainerFactory is created by JmsAnnotationDrivenConfiguration when custom one is not
    // defined. JmsAnnotationDrivenConfiguration is pulled in by JmsAutoConfiguration.

    // JmsAutoConfiguration is specified in spring.factory file from spring-boot-autoconfigurer.jar

    // Default jmsTemplate is created by JmsAutoConfiguration when custom one is not defined (ConditionalOnMissingBean).

    // ActiveMQAutoConfiguration is specified in spring.factory file from spring-boot-autoconfigurer.jar

    // ActiveMQConnectionFactoryConfiguration is pulled in by ActiveMQAutoConfiguration.

    // Default JMS ConnectionFactory is created by ActiveMQConnectionFactoryConfiguration when custom
    // ConnectionFactory bean is not defined (ConditionalOnMissingBean)

    public static void main(String[] args) {

        // Clean out any ActiveMQ data from a previous run
//        FileSystemUtils.deleteRecursively(new File("activemq-data"));

        ApplicationContext context = SpringApplication.run(Application.class, args);

    }
}


text:
package org.jboss.shrinkwrap.resolver.impl.maven.integration;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.jboss.shrinkwrap.resolver.api.NoResolvedResultException;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.impl.maven.bootstrap.MavenSettingsBuilder;
import org.jboss.shrinkwrap.resolver.impl.maven.util.TestFileUtil;
import org.jboss.shrinkwrap.resolver.impl.maven.util.ValidationUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;

/**
 * Tests resolution of the artifacts witch remote repository protected by password
 *
 * @author Karel Piwko
 */
public class RepositoryAuthTestCase {
    private static final Logger log = Logger.getLogger(RepositoryAuthTestCase.class.getName());

    private static final int HTTP_TEST_PORT = 12345;

    private Server server;

    @BeforeClass
    public static void initialize() {
        System.clearProperty("maven.repo.local"); // May conflict with release settings
    }

    /**
     * Cleanup, remove the repositories from previous tests, start the server
     */
    @Before
    public void init() throws Exception {
        TestFileUtil.removeDirectory(new File("target/auth-repository"));
        this.server = startHttpServer();
    }

    @After
    public void after() throws Exception {
        shutdownHttpServer(server);
        System.clearProperty(MavenSettingsBuilder.ALT_SECURITY_SETTINGS_XML_LOCATION);
    }

    @Test(expected = NoResolvedResultException.class)
    public void searchRemoteWithWrongPassword() throws Exception {
        // Configure with wrong password and expect to fail
        Maven.configureResolver().fromFile("target/settings/profiles/settings-wrongauth.xml")
                .resolve("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").withoutTransitivity().asSingle(File.class);
    }

    @Test
    public void searchRemoteWithCorrectPassword() throws Exception {
        // Configure with correct password and expect to pass
        final File resolved = Maven.configureResolver().fromFile("target/settings/profiles/settings-auth.xml")
                .resolve("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").withoutTransitivity().asSingle(File.class);
        new ValidationUtil("test-deps-i").validate(resolved);
    }

    // test encrypted passwords
    // SHRINKRES-38
    // mvn --encrypt-master-password shrinkwrap-resolver
    // {0lZ8CB4jdmMHl0jEG1zDN7GKYVSlvzGJZs5Pq/Y8kr5TrLx9yQAz/a4bjFfqFLc/}
    // mvn --encrypt-password shrinkwrap
    // {70+YZM/w7f8HQrEZUGZABCHAW62qMo+Y8okw7xzLwOM=}
    @Test
    public void searchRemoteWithEncryptedPassword() throws Exception {

        // set settings-security.xml with master password location
        System.setProperty(MavenSettingsBuilder.ALT_SECURITY_SETTINGS_XML_LOCATION,
                "target/settings/profiles/settings-security.xml");

        // Configure with correct password and expect to pass
        final File resolved = Maven.configureResolver().fromFile("target/settings/profiles/settings-auth-encrypted.xml")
                .resolve("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").withoutTransitivity().asSingle(File.class);
        new ValidationUtil("test-deps-i").validate(resolved);
    }

    private Server startHttpServer() {
        // Start an Embedded HTTP Server
        final Handler handler = new AuthStaticFileHandler("shrinkwrap", "shrinkwrap");
        final Server httpServer = new Server(HTTP_TEST_PORT);
        httpServer.setHandler(handler);
        try {
            httpServer.start();
            log.info("HTTP Server Started: " + httpServer);
            return httpServer;
        } catch (final Exception e) {
            throw new RuntimeException("Could not start server");
        }
    }

    private void shutdownHttpServer(final Server httpServer) {
        if (httpServer != null) {
            try {
                httpServer.stop();
            } catch (final Exception e) {
                // Swallow
                log.severe("Could not stop HTTP Server cleanly, " + e.getMessage());
            }
            log.info("HTTP Server Stopped: " + httpServer);
        }
    }

    /**
     * Jetty Handler to serve a static character file from the web root with Authorization check
     */
    private static class AuthStaticFileHandler extends AbstractHandler implements Handler {

        private static final String AUTH_HEADER = "Authorization";

        private final String user;
        private final String password;

        public AuthStaticFileHandler(String user, String password) {
            super();
            this.user = user;
            this.password = password;
        }

        /**
         * @see org.mortbay.jetty.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest,
         * javax.servlet.http.HttpServletResponse, int)
         */
        @Override
        public void handle(final String target, final HttpServletRequest request, final HttpServletResponse response,
                final int dispatch) throws IOException, ServletException {

            log.fine("Authorizing request for artifact");
            final String authHeader = request.getHeader(AUTH_HEADER);
            if (authHeader == null || authHeader.length() == 0) {
                log.warning("Unauthorized access, please provide credentials");
                response.addHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                        "Unauthorized access, please provide credentials");
                return;
            }

            if (!authorize(request)) {
                log.warning("Invalid credentials");
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid credentials");
                return;
            }

            // Set content type and status before we write anything to the stream
            response.setContentType("text/xml");
            response.setStatus(HttpServletResponse.SC_OK);

            // Obtain the requested file relative to the webroot
            final URL root = getCodebaseLocation();
            final URL fileUrl = new URL(root.toExternalForm() + target);
            URI uri = null;
            try {
                uri = fileUrl.toURI();
            } catch (final URISyntaxException urise) {
                throw new RuntimeException(urise);
            }
            final File file = new File(uri);

            // File not found, so 404
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                log.warning("Requested file is not found: " + file);
                return;
            }

            // Write out each line
            final BufferedReader reader = new BufferedReader(new FileReader(file));
            final PrintWriter writer = response.getWriter();
            String line = null;
            while ((line = reader.readLine()) != null) {
                writer.println(line);
            }

            // Close 'er up
            writer.flush();
            reader.close();
            writer.close();
        }

        private URL getCodebaseLocation() throws MalformedURLException {
            return new File("target/repository").toURI().toURL();
        }

        private boolean authorize(HttpServletRequest request) {
            String authHeader = request.getHeader(AUTH_HEADER);

            // Basic auth
            if (authHeader != null && authHeader.startsWith("Basic")) {
                String credentials = user + ":" + password;

                String challenge = "Basic "
                        + new String(Base64.encodeBase64(credentials.getBytes(Charset.defaultCharset())),
                                Charset.defaultCharset());

                return authHeader.equals(challenge);
            }

            return false;
        }
    }

}


text:
#pragma once
#ifndef VOTCA_XTP_DFTGWBSE_H
#define VOTCA_XTP_DFTGWBSE_H

// Standard includes
#include <cstdio>

// Local VOTCA includes
#include "votca/xtp/logger.h"
#include "votca/xtp/qmtool.h"

namespace votca {
namespace xtp {

class DftGwBse final : public QMTool {
 public:
  DftGwBse() = default;

  ~DftGwBse() = default;

  std::string Identify() const { return "dftgwbse"; }

 protected:
  void ParseOptions(const tools::Property &user_options);
  bool Run();

 private:
  std::string guess_file_;
  std::string mpsfile_;

  std::string xyzfile_;
  std::string xml_output_;    // .xml output
  std::string archive_file_;  // .orb file to parse to

  tools::Property package_options_;
  tools::Property gwbseengine_options_;
  tools::Property geoopt_options_;

  Logger log_;

  bool do_optimize_;
};

}  // namespace xtp
}  // namespace votca

#endif  // VOTCA_XTP_DFTGWBSE_H


text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.EnvironmentAbstractions;
using Microsoft.Extensions.DependencyModel.Resolution;
using Xunit;
using FluentAssertions;

namespace Microsoft.Extensions.DependencyModel.Tests
{
    public class AppBaseResolverTests
    {
        private static string BasePath = Path.Combine("Base","Path");
        private static string BasePathRefs = Path.Combine(BasePath, "refs");

        private static string SharedFxPath = Path.Combine("shared", "fx");
        private static string SharedFxPathRefs = Path.Combine(SharedFxPath, "refs");

        private static DependencyContextPaths DependencyContextPaths = new DependencyContextPaths(null, Path.Combine(SharedFxPath, "deps.json"));

        [Fact]
        public void ResolvesProjectType()
        {
            var fileSystem = FileSystemMockBuilder
                 .Create()
                 .AddFiles(BasePathRefs, TestLibraryFactory.DefaultAssembly)
                 .Build();
            var resolver = CreateResolver(fileSystem);
            var library = TestLibraryFactory.Create(
                TestLibraryFactory.ProjectType,
                assemblies: TestLibraryFactory.EmptyAssemblies);

            var result = resolver.TryResolveAssemblyPaths(library, null);

            Assert.True(result);
        }

        [Fact]
        public void ResolvesPackageType()
        {
            var fileSystem = FileSystemMockBuilder
                 .Create()
                 .AddFiles(BasePathRefs, TestLibraryFactory.DefaultAssembly)
                 .Build();
            var resolver = CreateResolver(fileSystem);
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.PackageType,
               assemblies: TestLibraryFactory.EmptyAssemblies);

            var result = resolver.TryResolveAssemblyPaths(library, null);

            Assert.True(result);
        }

        [Fact]
        public void ResolvesReferenceAssemblyType()
        {
            var fileSystem = FileSystemMockBuilder
                 .Create()
                 .AddFiles(BasePathRefs, TestLibraryFactory.DefaultAssembly)
                 .Build();
            var resolver = CreateResolver(fileSystem);
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.ReferenceAssemblyType,
               assemblies: TestLibraryFactory.EmptyAssemblies);

            var result = resolver.TryResolveAssemblyPaths(library, null);

            Assert.True(result);
        }

        [Fact]
        public void RequiresExistingRefsFolderForNonProjects()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePath, TestLibraryFactory.DefaultAssembly, TestLibraryFactory.SecondAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.ReferenceAssemblyType,
               assemblies: TestLibraryFactory.TwoAssemblies);
            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.False(result);
            assemblies.Should().HaveCount(0);
        }

        [Fact]
        public void ResolvesProjectWithoutRefsFolder()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePath, TestLibraryFactory.DefaultAssembly, TestLibraryFactory.SecondAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.ProjectType,
               assemblies: TestLibraryFactory.TwoAssemblies);
            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.True(result);
            assemblies.Should().HaveCount(2);
            assemblies.Should().Contain(Path.Combine(BasePath, TestLibraryFactory.DefaultAssembly));
            assemblies.Should().Contain(Path.Combine(BasePath, TestLibraryFactory.SecondAssembly));
        }

        [Fact]
        public void RequiresAllLibrariesToExist()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePath, TestLibraryFactory.DefaultAssembly)
                .AddFiles(BasePathRefs, TestLibraryFactory.DefaultAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.ReferenceAssemblyType,
               assemblies: TestLibraryFactory.TwoAssemblies);
            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var exception = Assert.Throws<InvalidOperationException>(() => resolver.TryResolveAssemblyPaths(library, assemblies));
            exception.Message.Should()
                .Contain(BasePath)
                .And.Contain(BasePathRefs)
                .And.Contain(TestLibraryFactory.SecondAssembly);
        }

        [Fact]
        public void ResolvesIfAllAreInBaseDir()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePath, TestLibraryFactory.DefaultAssembly, TestLibraryFactory.SecondAssembly)
                .AddFiles(BasePathRefs, "Dummy.dll")
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.ReferenceAssemblyType,
               assemblies: TestLibraryFactory.TwoAssemblies);
            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.True(result);
            assemblies.Should().HaveCount(2);
            assemblies.Should().Contain(Path.Combine(BasePath, TestLibraryFactory.DefaultAssembly));
            assemblies.Should().Contain(Path.Combine(BasePath, TestLibraryFactory.SecondAssembly));
        }

        [Fact]
        public void ResolvesIfAllAreInRefDir()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePathRefs, TestLibraryFactory.DefaultAssembly, TestLibraryFactory.SecondAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.ReferenceAssemblyType,
               assemblies: TestLibraryFactory.TwoAssemblies);

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.True(result);
            assemblies.Should().HaveCount(2);
            assemblies.Should().Contain(Path.Combine(BasePathRefs, TestLibraryFactory.DefaultAssembly));
            assemblies.Should().Contain(Path.Combine(BasePathRefs, TestLibraryFactory.SecondAssembly));
        }

        [Fact]
        public void ResolvesIfOneInBaseOtherInRefs()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePath, TestLibraryFactory.DefaultAssembly)
                .AddFiles(BasePathRefs, TestLibraryFactory.SecondAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.ReferenceAssemblyType,
               assemblies: TestLibraryFactory.TwoAssemblies);

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.True(result);
            assemblies.Should().HaveCount(2);
            assemblies.Should().Contain(Path.Combine(BasePath, TestLibraryFactory.DefaultAssembly));
            assemblies.Should().Contain(Path.Combine(BasePathRefs, TestLibraryFactory.SecondAssembly));
        }

        [Fact]
        public void PrefersRefs()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePath, TestLibraryFactory.DefaultAssembly)
                .AddFiles(BasePathRefs, TestLibraryFactory.DefaultAssembly)
                .AddFile(SharedFxPath, TestLibraryFactory.DefaultAssembly)
                .AddFile(SharedFxPathRefs, TestLibraryFactory.DefaultAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.PackageType
               );

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.True(result);
            assemblies.Should().HaveCount(1);
            assemblies.Should().Contain(Path.Combine(BasePathRefs, TestLibraryFactory.DefaultAssembly));
        }

        [Fact]
        public void SearchesInSharedFxRefsPathForPublishedPortable()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePathRefs, TestLibraryFactory.SecondAssembly)
                .AddFiles(SharedFxPathRefs, TestLibraryFactory.DefaultAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.PackageType
               );

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();
            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.True(result);
            assemblies.Should().HaveCount(1);
            assemblies.Should().Contain(Path.Combine(SharedFxPathRefs, TestLibraryFactory.DefaultAssembly));
        }

        [Fact]
        public void SearchesInSharedFxPathForPublishedPortable()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePathRefs, TestLibraryFactory.SecondAssembly)
                .AddFiles(SharedFxPath, TestLibraryFactory.DefaultAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.PackageType
               );

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.True(result);
            assemblies.Should().HaveCount(1);
            assemblies.Should().Contain(Path.Combine(SharedFxPath, TestLibraryFactory.DefaultAssembly));
        }

        [Fact]
        public void PrefersSharedFxPathRefsPathPublishedPortable()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePathRefs, TestLibraryFactory.SecondAssembly)
                .AddFiles(SharedFxPath, TestLibraryFactory.DefaultAssembly)
                .AddFiles(SharedFxPathRefs, TestLibraryFactory.DefaultAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.PackageType
               );

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);

            Assert.True(result);
            assemblies.Should().HaveCount(1);
            assemblies.Should().Contain(Path.Combine(SharedFxPathRefs, TestLibraryFactory.DefaultAssembly));
        }

        [Fact]
        public void SkipsSharedFxPathForNonPublishedPortable()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(SharedFxPath, TestLibraryFactory.DefaultAssembly)
                .AddFiles(SharedFxPathRefs, TestLibraryFactory.DefaultAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.PackageType
               );

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);
            Assert.False(result);
        }

        [Fact]
        public void ShouldThrowForNonResolvedInPublishedApps()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .AddFiles(BasePathRefs, TestLibraryFactory.SecondAssembly)
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.PackageType
               );

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            Assert.Throws<InvalidOperationException>(() => resolver.TryResolveAssemblyPaths(library, assemblies));
        }

        [Fact]
        public void ShouldSkipForNonResolvedInNonPublishedApps()
        {
            var fileSystem = FileSystemMockBuilder
                .Create()
                .Build();
            var library = TestLibraryFactory.Create(
               TestLibraryFactory.PackageType
               );

            var resolver = CreateResolver(fileSystem);
            var assemblies = new List<string>();

            var result = resolver.TryResolveAssemblyPaths(library, assemblies);
            Assert.False(result);
        }

        private static AppBaseCompilationAssemblyResolver CreateResolver(IFileSystem fileSystem)
        {
            return new AppBaseCompilationAssemblyResolver(fileSystem, BasePath, DependencyContextPaths);
        }
    }
}


text:
goog.provide('goog.async.DelayTest');
goog.setTestOnly('goog.async.DelayTest');

goog.require('goog.async.Delay');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.jsunit');

var invoked = false;
var delay = null;
var clock = null;

function callback() {
  invoked = true;
}

function setUp() {
  clock = new goog.testing.MockClock(true);
  invoked = false;
  delay = new goog.async.Delay(callback, 200);
}

function tearDown() {
  clock.dispose();
  delay.dispose();
}

function testDelay() {
  delay.start();
  assertFalse(invoked);

  clock.tick(100);
  assertFalse(invoked);

  clock.tick(100);
  assertTrue(invoked);
}

function testStop() {
  delay.start();

  clock.tick(100);
  assertFalse(invoked);

  delay.stop();
  clock.tick(100);
  assertFalse(invoked);
}

function testIsActive() {
  assertFalse(delay.isActive());
  delay.start();
  assertTrue(delay.isActive());
  clock.tick(200);
  assertFalse(delay.isActive());
}

function testRestart() {
  delay.start();
  clock.tick(100);

  delay.stop();
  assertFalse(invoked);

  delay.start();
  clock.tick(199);
  assertFalse(invoked);

  clock.tick(1);
  assertTrue(invoked);

  invoked = false;
  delay.start();
  clock.tick(200);
  assertTrue(invoked);
}

function testOverride() {
  delay.start(50);
  clock.tick(49);
  assertFalse(invoked);

  clock.tick(1);
  assertTrue(invoked);
}

function testDispose() {
  delay.start();
  delay.dispose();
  assertTrue(delay.isDisposed());

  clock.tick(500);
  assertFalse(invoked);
}

function testFire() {
  delay.start();

  clock.tick(50);
  delay.fire();
  assertTrue(invoked);
  assertFalse(delay.isActive());

  invoked = false;
  clock.tick(200);
  assertFalse('Delay fired early with fire call, timeout should have been ' +
      'cleared', invoked);
}

function testFireIfActive() {
  delay.fireIfActive();
  assertFalse(invoked);

  delay.start();
  delay.fireIfActive();
  assertTrue(invoked);
  invoked = false;
  clock.tick(300);
  assertFalse('Delay fired early with fireIfActive, timeout should have been ' +
      'cleared', invoked);
}


text:
{% if page.date > site.time and page.eventbrite_id %}

{% endif %}


text:
/* @flow */

export { default as actions } from './actions';
export { default as reducer } from './reducer';

export { default as OtherLocales } from './components/OtherLocales';
export { default as OtherLocalesCount } from './components/Count';

export type { LocalesState } from './reducer';

// Name of this module.
// Used as the key to store this module's reducer.
export const NAME: string = 'otherlocales';


text:
module DiabeticToolbox
  class ChangeMemberEmailMailer < ApplicationMailer
    require 'mail'

    #region Mailmen
    def send_confirmation_link(member)
      @member = member
      if @member.present?
        mail to: recipient.format, subject: I18n.t('mailers.change_member_email.subject')
      end
    end
    #endregion

    #region Private
    private
    def recipient
      to = Mail::Address.new @member.unconfirmed_email
      to.display_name = "#{@member.first_name} #{@member.last_name}"
      to
    end
    #endregion
  end
end


text:
package com.terremark.api;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for CatalogItemLicensedBy.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="CatalogItemLicensedBy">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="ServiceProvider"/>
 *     <enumeration value="Customer"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "CatalogItemLicensedBy")
@XmlEnum
public enum CatalogItemLicensedBy {

    @XmlEnumValue("ServiceProvider")
    SERVICE_PROVIDER("ServiceProvider"),
    @XmlEnumValue("Customer")
    CUSTOMER("Customer");
    private final String value;

    CatalogItemLicensedBy(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static CatalogItemLicensedBy fromValue(String v) {
        for (CatalogItemLicensedBy c: CatalogItemLicensedBy.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
package service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;

import engine.processInfoProvider;

/**
 * Created by lenovo on 2016/6/23.
 */
public class lockScreenService extends Service {

    private IntentFilter mIntentFilter;
    private innerService mInnerService;

    @Override
    public void onCreate() {
        //开启服务的时候,监听锁屏的广播
        mIntentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        mInnerService = new innerService();
        registerReceiver(mInnerService,mIntentFilter);

        super.onCreate();

    }

    @Override
    public void onDestroy() {
        if (mInnerService!=null){

            unregisterReceiver(mInnerService);

        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class innerService extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //监听到锁屏广播之后,清理手机进程
            processInfoProvider.killAll(context);

        }
    }
}


text:
[![License](https://img.shields.io/github/license/fuyuno/vulpecula.svg?style=flat-square)](https://github.com/fuyuno/Vulpecula/blob/develop/LICENSE.txt)
Vulpecula.Mobile は、 Vulpecula.iOS 及び Vulpecula.Android の共通ライブラリです。
View, ViewModel, Model の自動バインドなどの機能を含んでいます。
なお、ローカライゼーション、アセット類は、各プロジェクトに存在しています。

### ライセンス
* [The MIT License (MIT)](https://github.com/fuyuno/Vulpecula/blob/develop/LICENSE.txt)

### ライブラリ
#### Prism
> Apache License
>
> (C) Copyright .NET Foundation

* **ライセンス :** Apache License Version 2.0
* **ライセンス全文 :** [licenses/Prism.txt](https://github.com/fuyuno/Vulpecula/blob/develop/licenses/Prism.txt)

#### Rx (Reactive Extensions)
* **ライセンス :** Apache License Version 2.0
* **ライセンス全文 :** [licenses/Apache.txt](https://github.com/fuyuno/Vulpecula/blob/develop/licenses/Apache.txt)


text:
/*
 * Our Regions
 * -----------
 * We instantiate our regions here. Take note how there's
 * nothing special here at all. In fact, it's backwards compatible
 * with normal regions. It just has some super powers if you pair it
 * with the right View.
 *
 */

(function() {
  var normalRegion = new Marionette.TransitionRegion({
    el: '.normal-region'
  });

  var fadeRegion = new Marionette.TransitionRegion({
    el: '.fade-region'
  });

  // For the sliding region, we set the class-level property
  // that makes the transition in and out effects happen concurrently
  var slideRegion = new Marionette.TransitionRegion({
    el: '.slide-region',
    concurrentTransition: true
  });

  window.normalRegion = normalRegion;
  window.fadeRegion = fadeRegion;
  window.slideRegion = slideRegion;
})();

/*
 * NormalView
 * ----------
 * Just a normal ItemView.
 *
 */

(function() {
  var NormalView = Marionette.ItemView.extend({
    template: _.template('
Normal View

A random number: <%= randomNumber %>
'),
    className: 'normal-view view'
  });

  window.NormalView = NormalView;
})();

/*
 * FadeView
 * --------
 * A view that supports animated transitions. All you do is add in
 * either animateIn or animateOut methods. Once you've done your animation
 * simply trigger 'animateOut' or 'animateIn' to let the region know.
 *
 */

(function() {
  var ANIMATION_DURATION = 200;

  var FadeView = Marionette.ItemView.extend({
    template: _.template('
Animated View

A random name: <%= randomName %>
'),
    className: 'animated-view view',

    // Do some jQuery stuff, then, once you're done, trigger 'animateIn' to let the region
    // know that you're done
    animateIn: function() {
      this.$el.animate(
        { opacity: 1 },
        ANIMATION_DURATION,
        _.bind(this.trigger, this, 'animateIn')
      );
    },

    // Same as above, except this time we trigger 'animateOut'
    animateOut: function() {
      this.$el.animate(
        { opacity: 0 },
        ANIMATION_DURATION,
        _.bind(this.trigger, this, 'animateOut')
      );
    }
  });

  window.FadeView = FadeView;
})();

/*
 * SlideView
 * ---------
 * Another view. This one does slide stuff LIKE MAGIC
 *
 */

(function() {
  var ANIMATION_DURATION = 400;

  var SlideView = Marionette.ItemView.extend({
    template: _.template('
Animated View

A random place: <%= randomPlace %>.
Also more test so you can see that they do exist at the same time.
'),
    className: 'animated-view view',

    transitionInCss: {
      position: 'absolute',
      left: 500,
    },

    // Do some jQuery stuff, then, once you're done, trigger 'animateIn' to let the region
    // know that you're done
    animateIn: function() {
      this.$el.animate(
        { left: 0 },
        ANIMATION_DURATION,
        _.bind(this.trigger, this, 'animateIn')
      );
    },

    // Same as above, except this time we trigger 'animateOut'
    animateOut: function() {
      this.$el.animate(
        { left: -500 },
        ANIMATION_DURATION,
        _.bind(this.trigger, this, 'animateOut')
      );
    }
  });

  window.SlideView = SlideView;
})();

/*
 * random
 * ------
 * This generates random numbers and names to populate
 * our templates, to make it a bit more obvious when the
 * view changes.
 *
 */

(function() {
  function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  var names = [
    'Sam', 'Jameskyle', 'Humphreys', 'Jason', 'MeoMix',
    'Joanne', 'jpdesign', 'Jmeas', 'pekala', 'chiplay',
    'joe zim', 'dbailey', 'cobbweb'
  ];

  var places = [
    'Yosemite', 'Philadelphia', 'Boston', 'Brooklyn', 'Ukraine',
    'Kokomo', 'Florida', 'Your house', 'Palo Alto', 'Bermuda'
  ];

  function randomName() {
    var randomIndex = randomNumber(0, names.length-1);
    return names[randomIndex];
  }

  function randomPlace() {
    var randomIndex = randomNumber(0, places.length-1);
    return places[randomIndex];
  }

  window.randomNumber = randomNumber;
  window.randomName = randomName;
  window.randomPlace = randomPlace;
})();

/*
 * buttons
 * -------
 * Make those buttons do something
 *
 */

(function() {
  function newNormal() {
    var normalView = new NormalView({
      model: new Backbone.Model({
        randomNumber: randomNumber(0, 100)
      })
    });
    normalRegion.show(normalView);
  }

  function newFadeView() {
    var fadeView = new FadeView({
      model: new Backbone.Model({
        randomName: randomName()
      })
    });
    fadeRegion.show(fadeView);
  }

  function newSlideView() {
    var slideView = new SlideView({
      model: new Backbone.Model({
        randomPlace: randomPlace()
      })
    });
    slideRegion.show(slideView);
  }

  function emptyNormalRegion() {
    normalRegion.empty();
  }

  function emptyFadeRegion() {
    fadeRegion.empty();
  }

  function emptySlideRegion() {
    slideRegion.empty();
  }

  var $newNormal = $('.show-normal');
  var $fadeIn = $('.fade-in');
  var $slideIn = $('.slide-in');
  var $emptyNormal = $('.empty-normal');
  var $emptyFade = $('.empty-fade');
  var $emptySlide = $('.empty-slide');

  $newNormal.on('click', newNormal);
  $fadeIn.on('click', newFadeView);
  $slideIn.on('click', newSlideView);
  $emptyNormal.on('click', emptyNormalRegion);
  $emptyFade.on('click', emptyFadeRegion);
  $emptySlide.on('click', emptySlideRegion);
})();


text:
class PerformanceReport < Report
  include Reporting::OrganizationReports

  def initialize(start_date)
    self.start_date = (start_date.is_a? Date) ? start_date : Date.parse(start_date)
    self.end_date   = self.start_date + (Date.new(start_date.year,12,31).to_date<<(12-start_date.month)).day
    @name = "Performance report upto #{end_date}"
  end

  def name
    "Performance report upto #{end_date}"
  end

  def to_str
    "#{start_date} - #{end_date}"
  end

  def calc
    @report = []
    t0 = Time.now
    puts "generating..."
    @report[0] = {'Branches' => branch_count(end_date)}
    @report[1] = {'Centers' => centers_count(end_date)}
    @report[2] = {"CMs"  => cms_count(end_date)}
    @report[3] = {"Clients" => clients_count(end_date)}
    @report[4] = {"Borrowers" => borrowers(end_date)}
    @report[5] = {"Disbursed" => disbursed(end_date, "sum")}
    @report[6] = {"Net portfolio" => net_portfolio(end_date)}
    self.raw = @report
    self.report = Marshal.dump(@report)
    self.generation_time = Time.now - t0
    self.save
  end
end


text:
theme :
  name : tom
layout: default
---
{% include JB/setup %}
{% include themes/tom/page.html %}


text:
#ifndef KeyedDecoderCF_h
#define KeyedDecoderCF_h

#include "KeyedCoding.h"
#include <wtf/RetainPtr.h>
#include <wtf/Vector.h>

namespace WebCore {

class KeyedDecoderCF final : public KeyedDecoder {
public:
    KeyedDecoderCF(const uint8_t* data, size_t);
    ~KeyedDecoderCF() override;

private:
    bool decodeBytes(const String& key, const uint8_t*&, size_t&) override;
    bool decodeBool(const String& key, bool&) override;
    bool decodeUInt32(const String& key, uint32_t&) override;
    bool decodeInt32(const String& key, int32_t&) override;
    bool decodeInt64(const String& key, int64_t&) override;
    bool decodeFloat(const String& key, float&) override;
    bool decodeDouble(const String& key, double&) override;
    bool decodeString(const String& key, String&) override;

    bool beginObject(const String& key) override;
    void endObject() override;

    bool beginArray(const String& key) override;
    bool beginArrayElement() override;
    void endArrayElement() override;
    void endArray() override;

    RetainPtr<CFDictionaryRef> m_rootDictionary;

    Vector<CFDictionaryRef, 16> m_dictionaryStack;
    Vector<CFArrayRef, 16> m_arrayStack;
    Vector<CFIndex> m_arrayIndexStack;
};

} // namespace WebCore

#endif // KeyedDecoderCF_h


text:
/* global describe, it */

var expect = require('chai').expect;

describe('kerouac-blog', function() {

  describe('package.json', function() {
    var json = require('../package.json');

    it('should have assembly metadata', function() {
      expect(json.assembly.namespace).to.equal('org.kerouacjs/blog');

      expect(json.assembly.components).to.have.length(2);
      expect(json.assembly.components).to.include('site');
      expect(json.assembly.components).to.include('db/posts');
    });
  });

  it('should throw if required', function() {
    expect(function() {
      var pkg = require('..');
    }).to.throw(Error).with.property('code', 'MODULE_NOT_FOUND');
  });

});