text:
package e2e

import (
	"fmt"
	"os"
	"path"
	"testing"

	"github.com/onsi/ginkgo"
	"github.com/onsi/ginkgo/config"
	"github.com/onsi/ginkgo/reporters"
	"github.com/onsi/gomega"
	"k8s.io/klog"

	runtimeutils "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/component-base/logs"
	commontest "k8s.io/kubernetes/test/e2e/common"
	"k8s.io/kubernetes/test/e2e/framework"
	e2elog "k8s.io/kubernetes/test/e2e/framework/log"

	// ensure auth plugins are loaded
	_ "k8s.io/client-go/plugin/pkg/client/auth"

	// ensure that cloud providers are loaded
	_ "k8s.io/kubernetes/test/e2e/framework/providers/aws"
	_ "k8s.io/kubernetes/test/e2e/framework/providers/azure"
	_ "k8s.io/kubernetes/test/e2e/framework/providers/gce"
	_ "k8s.io/kubernetes/test/e2e/framework/providers/kubemark"
	_ "k8s.io/kubernetes/test/e2e/framework/providers/openstack"
	_ "k8s.io/kubernetes/test/e2e/framework/providers/vsphere"
)

var _ = ginkgo.SynchronizedBeforeSuite(func() []byte {
	// Reference common test to make the import valid.
	commontest.CurrentSuite = commontest.E2E
	framework.SetupSuite()
	return nil
}, func(data []byte) {
	// Run on all Ginkgo nodes
})

var _ = ginkgo.SynchronizedAfterSuite(func() {
	framework.CleanupSuite()
}, func() {
	framework.AfterSuiteActions()
})

// RunE2ETests checks configuration parameters (specified through flags) and then runs
// E2E tests using the Ginkgo runner.
// If a "report directory" is specified, one or more JUnit test reports will be
// generated in this directory, and cluster logs will also be saved.
// This function is called on each Ginkgo node in parallel mode.
func RunE2ETests(t *testing.T) {
	runtimeutils.ReallyCrash = true
	logs.InitLogs()
	defer logs.FlushLogs()

	gomega.RegisterFailHandler(e2elog.Fail)
	// Disable skipped tests unless they are explicitly requested.
	if config.GinkgoConfig.FocusString == "" && config.GinkgoConfig.SkipString == "" {
		config.GinkgoConfig.SkipString = `\[Flaky\]|\[Feature:.+\]`
	}

	// Run tests through the Ginkgo runner with output to console + JUnit for Jenkins
	var r []ginkgo.Reporter
	if framework.TestContext.ReportDir != "" {
		// TODO: we should probably only be trying to create this directory once
		// rather than once-per-Ginkgo-node.
		if err := os.MkdirAll(framework.TestContext.ReportDir, 0755); err != nil {
			klog.Errorf("Failed creating report directory: %v", err)
		} else {
			r = append(r, reporters.NewJUnitReporter(path.Join(framework.TestContext.ReportDir, fmt.Sprintf("junit_%v%02d.xml", framework.TestContext.ReportPrefix, config.GinkgoConfig.ParallelNode))))
		}
	}
	klog.Infof("Starting e2e run %q on Ginkgo node %d", framework.RunID, config.GinkgoConfig.ParallelNode)

	ginkgo.RunSpecsWithDefaultAndCustomReporters(t, "Kubernetes e2e suite", r)
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('file_id')->nullable();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->dateTime('last_login')->nullable();
            $table->integer('reputation')->default(0);
            $table->string('oauth_provider')->nullable();
            $table->string('oauth_id')->nullable();
            $table->string('oauth_token')->nullable();
            $table->rememberToken();
            $table->string('email_token')->nullable();
            $table->boolean('email_verified')->default(false);
            $table->boolean('suspended')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Overblog\GraphQLBundle\Config;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Builder\VariableNodeDefinition;

use function is_array;
use function is_int;
use function is_string;
use function preg_match;

abstract class TypeDefinition
{
    public const VALIDATION_LEVEL_CLASS = 0;
    public const VALIDATION_LEVEL_PROPERTY = 1;

    abstract public function getDefinition(): ArrayNodeDefinition;

    final protected function __construct()
    {
    }

    /**
     * @return static
     */
    public static function create(): self
    {
        return new static();
    }

    protected function resolveTypeSection(): VariableNodeDefinition
    {
        return self::createNode('resolveType', 'variable');
    }

    protected function nameSection(): ScalarNodeDefinition
    {
        /** @var ScalarNodeDefinition $node */
        $node = self::createNode('name', 'scalar');

        $node
            ->isRequired()
            ->validate()
                ->ifTrue(fn ($name) => !preg_match('/^[_a-z][_0-9a-z]*$/i', $name))
                ->thenInvalid('Invalid type name "%s". (see http://spec.graphql.org/June2018/#sec-Names)')
            ->end()
        ;

        return $node;
    }

    protected function defaultValueSection(): VariableNodeDefinition
    {
        return self::createNode('defaultValue', 'variable');
    }

    protected function validationSection(int $level): ArrayNodeDefinition
    {
        /** @var ArrayNodeDefinition $node */
        $node = self::createNode('validation', 'array');

        /** @phpstan-ignore-next-line */
        $node
            // allow shorthands
            ->beforeNormalization()
                ->always(function ($value) {
                    if (is_string($value)) {
                        // shorthand: cascade or link
                        return 'cascade' === $value ? ['cascade' => null] : ['link' => $value];
                    }

                    if (is_array($value)) {
                        foreach ($value as $k => $a) {
                            if (!is_int($k)) {
                                // validation: { link: ... , constraints: ..., cascade: ... }
                                return $value;
                            }
                        }
                        // validation: [list of constraints]
                        return ['constraints' => $value];
                    }

                    return [];
                })
            ->end()
            ->children()
                ->scalarNode('link')
                    ->validate()
                        ->ifTrue(function ($link) use ($level) {
                            if (self::VALIDATION_LEVEL_PROPERTY === $level) {
                                return !preg_match('/^(?:\\\\?[A-Za-z][A-Za-z\d]+)*[A-Za-z\d]+::(?:[$]?[A-Za-z][A-Za-z_\d]+|[A-Za-z_\d]+\(\))$/m', $link);
                            } else {
                                return !preg_match('/^(?:\\\\?[A-Za-z][A-Za-z\d]+)*[A-Za-z\d]$/m', $link);
                            }
                        })
                        ->thenInvalid('Invalid link provided: "%s".')
                    ->end()
                ->end()
                ->variableNode('constraints')->end()
            ->end();

        // Add the 'cascade' option if it's a property level validation section
        if (self::VALIDATION_LEVEL_PROPERTY === $level) {
            /** @phpstan-ignore-next-line */
            $node
                ->children()
                    ->arrayNode('cascade')
                        ->children()
                            ->arrayNode('groups')
                                ->beforeNormalization()
                                    ->castToArray()
                                ->end()
                                ->scalarPrototype()->end()
                            ->end()
                        ->end()
                    ->end()
                ->end();
        }

        return $node;
    }

    protected function descriptionSection(): ScalarNodeDefinition
    {
        /** @var ScalarNodeDefinition $node */
        $node = self::createNode('description', 'scalar');

        return $node;
    }

    protected function deprecationReasonSection(): ScalarNodeDefinition
    {
        /** @var ScalarNodeDefinition $node */
        $node = self::createNode('deprecationReason', 'scalar');

        $node->info('Text describing why this field is deprecated. When not empty - field will not be returned by introspection queries (unless forced)');

        return $node;
    }

    protected function typeSection(bool $isRequired = false): ScalarNodeDefinition
    {
        /** @var ScalarNodeDefinition $node */
        $node = self::createNode('type', 'scalar');

        $node->info('One of internal or custom types.');

        if ($isRequired) {
            $node->isRequired();
        }

        return $node;
    }

    /**
     * @return mixed
     *
     * @internal
     */
    protected static function createNode(string $name, string $type = 'array')
    {
        return (new TreeBuilder($name, $type))->getRootNode();
    }
}


text:
package scomp.elements.detailed;

import scomp.common.BaseCase;
import xbean.scomp.element.any.AnyEltDocument;
import xbean.scomp.element.any.AnySimpleDocument;
import xbean.scomp.substGroup.wide.BusinessShirtType;
import org.apache.xmlbeans.XmlString;
import org.apache.xmlbeans.XmlDate;

import java.math.BigInteger;
import java.util.GregorianCalendar;

/**
 *
 *
 */
public class AnyTest extends BaseCase {

    public void testAny() throws Throwable {
        AnyEltDocument doc = AnyEltDocument.Factory.newInstance();
        BusinessShirtType bst = BusinessShirtType.Factory.newInstance();
        bst.setName("shirt");
        bst.setNumber("SkU034");
        bst.setColor("white");
        bst.setSize(new BigInteger("10"));
        doc.setAnyElt(bst);
        try {
            assertTrue(doc.validate(validateOptions));
        }
        catch (Throwable t) {
            showErrors();
            throw t;
        }

        XmlString val = XmlString.Factory.newInstance();
        val.setStringValue("foobar");
        doc.setAnyElt(val);

        try {
            assertTrue(doc.validate(validateOptions));
        }
        catch (Throwable t) {
            showErrors();
            throw t;
        }

    }

    public void testAnySimple() throws Throwable {
        AnySimpleDocument doc =
                AnySimpleDocument.Factory.newInstance();
        XmlString str = XmlString.Factory.newInstance();
        str.setStringValue("foobar");
        doc.setAnySimple(str);
        try {
            assertTrue(doc.validate(validateOptions));
        }
        catch (Throwable t) {
            showErrors();
            throw t;
        }
        XmlDate date = XmlDate.Factory.newInstance();
        date.setCalendarValue(new GregorianCalendar(2004, 8, 12));
        doc.setAnySimple(date);
        try {
            assertTrue(doc.validate(validateOptions));
        }
        catch (Throwable t) {
            showErrors();
            throw t;
        }
    }

}


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
          integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ=="
          crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"
          integrity="sha384-aUGj/X2zp5rLCbBxumKTCw2Z50WgIr1vs/PFN4praOTvYXWlVyh2UtNUU0KAUhAX" crossorigin="anonymous">
    <link rel="stylesheet" href="styles/style.css">

    <meta charset="UTF-8">
    <title>Tic Tac Toe</title>

Tic Tac Toe

        <button class="btn btn-default" id="aiStart">Computer Start First</button>

Dimitar Chaushev 2015


text:
class ChangeColumntypeIntDeviceCommunicationToString < ActiveRecord::Migration
  def change
    change_column :devices, :device_communication, :string

  end
end


text:
artist: Sola Plexus
title: Brown Boys Overcome
date: 2016-08-08
album-art: "/images/Album-DarkSide.jpg"
---


text:
'use strict';

angular.module('holding.tabs', ['holding.calculator', 'holding.pattern'])

.controller('CalculatorCtrl', function($scope, $filter, Calculator) {
	Calculator.init($scope, $filter);
})

.controller('PatternCtrl', function($scope, $ionicLoading, Pattern) {
	$ionicLoading.show({
		template: 'Loading...'
	});
	Pattern.init($scope, $ionicLoading);
})

.config(function($stateProvider, $urlRouterProvider) {

	// Ionic uses AngularUI Router which uses the concept of states
	// Learn more here: https://github.com/angular-ui/ui-router
	// Set up the various states which the app can be in.
	// Each state's controller can be found in controllers.js
	$stateProvider

	// setup an abstract state for the tabs directive
	.state('tab', {
		url: '/tab',
		abstract: true,
		templateUrl: 'templates/tabs.html'
	})

	// Each tab has its own nav history stack:
	.state('tab.tab1', {
		url: '/calculator',
		views: {
			'calculator': {
				templateUrl: 'templates/tabs/calculator.html',
				controller: 'CalculatorCtrl'
			}
		}
	})

	.state('tab.tab2', {
		url: '/pattern',
		views: {
			'pattern': {
				templateUrl: 'templates/tabs/pattern.html',
				controller: 'PatternCtrl'
			}
		}
	});

	// if none of the above states are matched, use this as the fallback
	$urlRouterProvider.otherwise('/tab/calculator');
})

.filter('numberFixedLen', function () {
	return function(val) {
		if (val === 0) {
			return val;
		} else if (val < 10) {
			return '00' + val;
		} else if (val < 100) {
			return '0' + val;
		} else {
			return val;
		}
	};
});


text:
require 'transpec/syntax'
require 'transpec/syntax/mixin/context_sensitive'
require 'transpec/syntax/mixin/examplish'
require 'transpec/syntax/mixin/metadata'
require 'transpec/rspec_dsl'

module Transpec
  class Syntax
    class Example < Syntax
      include Mixin::ContextSensitive, Mixin::Examplish, Mixin::Metadata, RSpecDSL

      def dynamic_analysis_target?
        super && receiver_node.nil? && EXAMPLE_METHODS.include?(method_name)
      end

      def should_be_in_example_group_context?
        true
      end

      def convert_pending_to_skip!
        convert_pending_selector_to_skip!
        convert_pending_metadata_to_skip!
      end

      def description?
        !arg_node.nil?
      end

      private

      def convert_pending_selector_to_skip!
        return unless method_name == :pending
        replace(selector_range, 'skip')
        add_record("pending 'is an example' { }", "skip 'is an example' { }")
      end

      def convert_pending_metadata_to_skip!
        metadata_key_nodes.each do |node|
          next unless pending_symbol?(node)
          replace(symbol_range_without_colon(node), 'skip')
          if node.parent.pair_type?
            add_record("it 'is an example', :pending => value { }",
                       "it 'is an example', :skip => value { }")
          else
            add_record("it 'is an example', :pending { }",
                       "it 'is an example', :skip { }")
          end
        end
      end

      def pending_symbol?(node)
        return false unless node.sym_type?
        key = node.children.first
        key == :pending
      end

      def symbol_range_without_colon(node)
        range = node.loc.expression
        if range.source.start_with?(':')
          Parser::Source::Range.new(range.source_buffer, range.begin_pos + 1, range.end_pos)
        else
          range
        end
      end
    end
  end
end


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.codeStyle;

import com.intellij.application.options.CodeStyle;
import com.intellij.lang.ASTNode;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.codeStyle.javadoc.CommentFormatter;
import com.intellij.psi.javadoc.PsiDocComment;
import org.jetbrains.annotations.NotNull;

public class FormatCommentsProcessor implements PreFormatProcessor {
  @NotNull
  @Override
  public TextRange process(@NotNull final ASTNode element, @NotNull final TextRange range) {
    PsiElement e = SourceTreeToPsiMap.treeElementToPsi(element);
    assert e != null && e.isValid();
    final PsiFile file = e.getContainingFile();
    final Project project = e.getProject();
    if (!CodeStyle.getCustomSettings(file, JavaCodeStyleSettings.class).ENABLE_JAVADOC_FORMATTING ||
        element.getPsi().getContainingFile().getLanguage() != JavaLanguage.INSTANCE
        || InjectedLanguageManager.getInstance(project).isInjectedFragment(element.getPsi().getContainingFile()))
    {
      return range;
    }
    return formatCommentsInner(project, element, range);
  }

  /**
   * Formats PsiDocComments of current ASTNode element and all his children PsiDocComments
   */
  @NotNull
  private static TextRange formatCommentsInner(@NotNull Project project, @NotNull ASTNode element, @NotNull final TextRange markedRange) {
    TextRange resultTextRange = markedRange;
    final PsiElement elementPsi = element.getPsi();
    assert elementPsi.isValid();
    final PsiFile file = elementPsi.getContainingFile();
    boolean shouldFormat = markedRange.contains(element.getTextRange());

    if (shouldFormat) {

      final ASTNode rangeAnchor;
      // There are two possible cases:
      //   1. Given element correspond to comment's owner (e.g. field or method);
      //   2. Given element corresponds to comment itself;
      // However, doc comment formatter replaces old comment with the new one, hence, old element becomes invalid. That's why we need
      // to calculate text length delta not for the given comment element (it's invalid because removed from the AST tree) but for
      // its parent.
      if (elementPsi instanceof PsiDocComment) {
        rangeAnchor = element.getTreeParent();
      }
      else {
        rangeAnchor = element;
      }
      TextRange before = rangeAnchor.getTextRange();
      new CommentFormatter(file).processComment(element);
      int deltaRange = rangeAnchor.getTextRange().getLength() - before.getLength();
      resultTextRange = new TextRange(markedRange.getStartOffset(), markedRange.getEndOffset() + deltaRange);
    }

    // If element is Psi{Method, Field, DocComment} and was formatted there is no reason to continue - we formatted all possible javadocs.
    // If element is out of range its children are also out of range. So in both cases formatting is finished. It's just for optimization.
    if ((shouldFormat && (elementPsi instanceof  PsiMethod || elementPsi instanceof PsiField || elementPsi instanceof PsiDocComment))
        || markedRange.getEndOffset() < element.getStartOffset())
    {
      return resultTextRange;
    }

    ASTNode current = element.getFirstChildNode();
    while (current != null) {
      // When element is PsiClass its PsiDocComment is formatted up to this moment, so we didn't need to format it again.
      if (!(shouldFormat && current.getPsi() instanceof PsiDocComment && elementPsi instanceof PsiClass)) {
        resultTextRange = formatCommentsInner(project, current, resultTextRange);
      }
      current = current.getTreeNext();
    }

    return resultTextRange;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using beRemote.Core.Definitions.Classes;
using beRemote.Core.StorageSystem.StorageBase;

namespace beRemote.GUI.Tabs.ManageLicense
{
    /// <summary>
    /// Interaction logic for ContentTabAbout.xaml
    /// </summary>
    public partial class TabManageLicense
    {
        private List<License> _Licenses = new List<License>();

        public TabManageLicense()
        {
            InitializeComponent();
        }

        public List<License> Licenses
        {
            get { return _Licenses; }
            set { _Licenses = value; }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            License lic = new License(txtFirstname.Text, txtLastname.Text, txtEmail.Text, txtSecret.Text, StorageCore.Core.GetUserSettings().getId());
            StorageCore.Core.AddUserLicense(lic);

            UserControl_Loaded(null, null);

            btnClear_Click(sender, e);
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            txtEmail.Clear();
            txtFirstname.Clear();
            txtLastname.Clear();
            txtSecret.Clear();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _Licenses = StorageCore.Core.GetLicenses();

            //Convert to Datatable (s*** TwoWay-Binding doesn't work *#!!"§"!)
            DataTable dT = new DataTable();
            DataColumn dC = new DataColumn();
            dC.Caption = dC.ColumnName = "Firstname";
            dT.Columns.Add(dC);
            dC = new DataColumn();
            dC.Caption = dC.ColumnName = "Lastname";
            dT.Columns.Add(dC);
            dC = new DataColumn();
            dC.Caption = dC.ColumnName = "Email";
            dT.Columns.Add(dC);
            dC = new DataColumn();
            dC.Caption = dC.ColumnName = "Secret";
            dT.Columns.Add(dC);

            foreach (License lic in _Licenses)
            {
                DataRow dR = dT.NewRow();
                dR["Firstname"] = lic.Firstname;
                dR["Lastname"] = lic.Lastname;
                dR["Email"] = lic.Email;
                dR["Secret"] = lic.Secret;

                dT.Rows.Add(dR);
            }

            dgLicenses.ItemsSource = dT.DefaultView;

            dgLicenses.CanUserAddRows = false;
            dgLicenses.CanUserDeleteRows = false;
            dgLicenses.AlternationCount = 2;
            dgLicenses.AreRowDetailsFrozen = true;
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dgLicenses.SelectedValue == null)
                return;

            DataRow x = ((DataRowView)dgLicenses.SelectedValue).Row;

            License selectedLicense = new License(x.ItemArray[0].ToString(), x.ItemArray[1].ToString(), x.ItemArray[2].ToString(), x.ItemArray[3].ToString(), StorageCore.Core.GetUserId());

            StorageCore.Core.DeleteUserLicense(selectedLicense);
            UserControl_Loaded(null, null);
        }

        private void dgLicenses_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            e.Cancel = true;
        }

        public override void Dispose()
        {
            base.Dispose();
            _Licenses.Clear();
        }
    }
}


text:
FactoryGirl.define do
  factory :user, :class => User do
    name 'stanislaw'
  end

  factory :one_user, :class => OneUser do
    name 'stanislaw'
    role = 'user'
  end
end


text:
<title>添加分类</title>
<link href="/assets/lib/icheck/icheck.css" rel="stylesheet" type="text/css" />

  <form class="form form-horizontal" id="form-member-add">
    <input id="type" value="1" type="hidden">

      *分类名称

        <input type="text" class="input-text" value="" placeholder="" id="name" name="name" datatype="*2-16" nullmsg="分类名称不能为空">

      *分类描述

        <textarea type="text" class="input-text" value="" placeholder="" id="describe_shop" name="describe_shop" datatype="*2-16" nullmsg="分类描述不能为空"></textarea>

      *是否使用:

          <input type="radio" id="status-1" name="status" value="0" datatype="*" checked="checked">
          是

          <input type="radio" id="status-2" name="status" value="1">
          否

        <input class="btn btn-primary radius" type="submit" value="  添加  ">

  </form>

<form id="uploadImgThumb1" enctype="multipart/form-data">
    <input onchange="return uploadThumb1()" name="image" type="file" id="file1" style="display:none;" accept="image/*">
</form>


text:
A MATLAB-based chat room activity analyzer for [Pokémon Showdown](https://github.com/Zarel/Pokemon-Showdown).

## License

***Volk*** is distributed under the terms of the [MIT License](https://github.com/sparktrain/chatstats/blob/master/LICENSE).

## Credits

[![sparktrain](https://avatars2.githubusercontent.com/u/7269774?v=3&s=120)](https://github.com/sparktrain)|
:-:|
[**sparktrain**](https://github.com/sparktrain)|
Developer|


text:
package com.cloud.upgrade.dao;

import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.crypt.EncryptionSecretKeyChecker;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import org.apache.log4j.Logger;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.properties.EncryptableProperties;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.UUID;

public class Upgrade40to41 implements DbUpgrade {
    final static Logger s_logger = Logger.getLogger(Upgrade40to41.class);

    @Override
    public String[] getUpgradableVersionRange() {
        return new String[] { "4.0.0", "4.1.0" };
    }

    @Override
    public String getUpgradedVersion() {
        return "4.1.0";
    }

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

    @Override
    public File[] getPrepareScripts() {
        String script = Script.findScript("", "db/schema-40to410.sql");
        if (script == null) {
            throw new CloudRuntimeException("Unable to find db/schema-40to410.sql");
        }

        return new File[] { new File(script) };
    }

    @Override
    public void performDataMigration(Connection conn) {
        updateRegionEntries(conn);
        upgradeEgressFirewallRules(conn);
    }

    @Override
    public File[] getCleanupScripts() {
        String script = Script.findScript("", "db/schema-40to410-cleanup.sql");
        if (script == null) {
            throw new CloudRuntimeException("Unable to find db/schema-40to410-cleanup.sql");
        }

        return new File[] { new File(script) };
    }

    private void updateRegionEntries(Connection conn) {
        File dbPropsFile = PropertiesUtil.findConfigFile("db.properties");
        final Properties dbProps;
        if (EncryptionSecretKeyChecker.useEncryption()) {
            StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor();
            dbProps = new EncryptableProperties(encryptor);
        } else {
            dbProps = new Properties();
        }
        try {
            dbProps.load(new FileInputStream(dbPropsFile));
        } catch (IOException e) {
            s_logger.fatal("Unable to load db properties file, pl. check the classpath and file path configuration", e);
            return;
        } catch (NullPointerException e) {
            s_logger.fatal("Unable to locate db properties file within classpath or absolute path: db.properties");
            return;
        }
        int region_id = 1;
        String regionId = dbProps.getProperty("region.id");
        if(regionId != null){
            region_id = Integer.parseInt(regionId);
        }
        PreparedStatement pstmt = null;
        try {
            //Update regionId in region table
            s_logger.debug("Updating region table with Id: "+region_id);
            pstmt = conn.prepareStatement("update `cloud`.`region` set id = ?");
            pstmt.setInt(1, region_id);
            pstmt.executeUpdate();

        } catch (SQLException e) {
            throw new CloudRuntimeException("Error while updating region entries", e);
        } finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            } catch (SQLException e) {
            }
        }
    }

    private void upgradeEgressFirewallRules(Connection conn) {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ResultSet rsId = null;
        ResultSet rsNw = null;
        try {
            // update the existing ingress rules traffic type
            pstmt = conn.prepareStatement("update `cloud`.`firewall_rules`  set traffic_type='Ingress' where purpose='Firewall' and ip_address_id is not null and traffic_type is null");
            s_logger.debug("Updating firewall Ingress rule traffic type: " + pstmt);
            pstmt.executeUpdate();

            pstmt = conn.prepareStatement("select network_id FROM `cloud`.`ntwk_service_map` where service='Firewall' and provider='VirtualRouter' ");
            rs = pstmt.executeQuery();
            while (rs.next()) {
                    long netId = rs.getLong(1);
                    //When upgraded from 2.2.14 to 3.0.6 guest_type is updated to Isolated in the 2214to30 clean up sql. clean up executes
                    //after this. So checking for Isolated OR Virtual
                    pstmt = conn.prepareStatement("select account_id, domain_id FROM `cloud`.`networks` where (guest_type='Isolated' OR guest_type='Virtual') and traffic_type='Guest' and vpc_id is NULL and (state='implemented' OR state='Shutdown') and id=? ");
                    pstmt.setLong(1, netId);
                    s_logger.debug("Getting account_id, domain_id from networks table: " + pstmt);
                    rsNw = pstmt.executeQuery();

                    if(rsNw.next()) {
                    long accountId = rsNw.getLong(1);
                    long domainId = rsNw.getLong(2);

                    //Add new rule for the existing networks
                    s_logger.debug("Adding default egress firewall rule for network " + netId);
                    pstmt = conn.prepareStatement("INSERT INTO firewall_rules (uuid, state, protocol, purpose, account_id, domain_id, network_id, xid, created,  traffic_type) VALUES (?, 'Active', 'all', 'Firewall', ?, ?, ?, ?, now(), 'Egress')");
                    pstmt.setString(1, UUID.randomUUID().toString());
                    pstmt.setLong(2, accountId);
                    pstmt.setLong(3, domainId);
                    pstmt.setLong(4, netId);
                    pstmt.setString(5, UUID.randomUUID().toString());
                    s_logger.debug("Inserting default egress firewall rule " + pstmt);
                    pstmt.executeUpdate();

                    pstmt = conn.prepareStatement("select id from firewall_rules where protocol='all' and network_id=?");
                    pstmt.setLong(1, netId);
                    rsId = pstmt.executeQuery();

                    long firewallRuleId;
                    if(rsId.next()) {
                        firewallRuleId = rsId.getLong(1);
                        pstmt = conn.prepareStatement("insert into firewall_rules_cidrs (firewall_rule_id,source_cidr) values (?, '0.0.0.0/0')");
                        pstmt.setLong(1, firewallRuleId);
                        s_logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + pstmt);
                        pstmt.executeUpdate();
                    }
                }
            }
        } catch (SQLException e) {
            throw new CloudRuntimeException("Unable to set egress firewall rules ", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (pstmt != null) {
                    pstmt.close();
                }
            } catch (SQLException e) {
            }
        }
    }

}


text:
#ifndef FUNCTIONUISTATE_H
#define FUNCTIONUISTATE_H

#include <QObject>

/** @addtogroup engine Engine
 * @{
 */

class FunctionUiState : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY(FunctionUiState)

public:
    explicit FunctionUiState(QObject * parent);
    virtual ~FunctionUiState();

    virtual bool copyFrom(const FunctionUiState* uiState);

public:
    void setShowSpeedDial(bool show);
    bool showSpeedDial() const;

private:
    bool m_showSpeedDial;
};

/** @} */

#endif


text:
use std::io;

use WriteRust;
use common::Spec;

impl<'a> WriteRust for ProtocolImplementationWriter<'a> {
    fn write_rust_to<W>(&self, writer: &mut W) -> io::Result<()>
        where W: io::Write
    {
        writeln!(
            writer,
            "impl<'a> ::Protocol<'a> for {struct_name} {{\n\
                type Frame = {mod_name}::Frame<'a>;\n\
                fn protocol_header() -> &'static [u8] {{\n\
                    b\"AMQP\\x00\\x00\\x{minor:02x}\\x{revision:02x}\"\n\
                }} // fn protocol_header()\n\
            }} // impl ::Protocol<'a> for {struct_name}",

            struct_name = self.spec.pascal_case(),
            mod_name = self.spec.mod_name(),
            minor = self.spec.version().minor(),
            revision = self.spec.version().revision(),
        )
    }
}

pub struct ProtocolImplementationWriter<'a> {
    spec: &'a Spec,
}

impl<'a> ProtocolImplementationWriter<'a> {
    pub fn new(spec: &'a Spec) -> Self {
        ProtocolImplementationWriter {
            spec: spec,
        }
    }
}


text:
export const ActionTypes = {
  FETCH_EVENTS: 'FETCH_EVENTS',
  FETCH_EVENTS_SUCCESS: 'FETCH_EVENTS_SUCCESS',
  FETCH_EVENTS_FAILURE: 'FETCH_EVENTS_FAILURE',
  PERSIST_EVENT_SUCCESS: 'PERSIST_EVENT_SUCCESS',

  FETCH_ITEMS: 'FETCH_ITEMS',
  FETCH_ITEMS_SUCCESS: 'FETCH_ITEMS_SUCCESS',
  FETCH_ITEMS_FAILURE: 'FETCH_ITEMS_FAILURE',
  PERSIST_ITEM_SUCCESS: 'PERSIST_ITEM_SUCCESS',
};

export const paths = {
  Events: 'events',
  Items: 'items',
  Index: '/',
};

export const API = {
  //baseUrl: config.baseUrl,
  //refreshAccessTokenPath: config.refreshAccessTokenPath,
};

export const forms = {
  Event: 'eventForm',
  Item: 'itemForm',
};


text:
/**
 * Module dependencies
 * @type {Object}
 */
var util = require('util');
var _ = require('lodash');
var path = require('path');
var async = require('async');
var report = require('reportback')();

var generate = require('./generate');
var FolderHelper = require('./helpers/folder');
var TemplateHelper = require('./helpers/template');
var JSONFileHelper = require('./helpers/jsonfile');
var CopyHelper = require('./helpers/copy');
var NOOP_GENERATOR = require('./rootGenerator');

/**
 * generateTarget()
 *
 * @param  {Object}   options
 */

function generateTarget(options, cb) {

  var sb = report.extend(cb);

  // Options
  var target = options.target;
  var scope = options.scope;
  var parentGenerator = options.parent;
  var recursiveGenerate = options.recursiveGenerate;

  var MAX_RESOLVES = 5,
    _resolves = 0;

  async.until(
    function checkIfTargetIsValidYet() {
      return isValidTarget(target) || (++_resolves > MAX_RESOLVES);
    },
    function tryToParseTarget(async_cb) {
      parseTarget(target, scope, function(err, resolvedTarget) {
        if (err) return async_cb(err);
        target = resolvedTarget;
        return async_cb();
      });
    },
    function afterwards(err) {
      if (err) return sb(err);
      if (!isValidTarget(target)) {
        return sb(new Error('Generator Error: Could not resolve target "' + scope.rootPath + '" (probably a recursive loop)'));
      }

      // Pass down parent Generator's template directory abs path
      scope.templatesDirectory = parentGenerator.templatesDirectory;

      // Interpret generator definition
      if (target.exec) {
        return target.exec(scope, sb);
      }
      if (target.copy) {
        scope = mergeSubtargetScope(scope, typeof target.copy === 'string' ? {
          templatePath: target.copy
        } : target.copy);
        return CopyHelper(scope, sb);
      }
      if (target.folder) {
        scope = mergeSubtargetScope(scope, target.folder);
        return FolderHelper(scope, sb);
      }
      if (target.template) {
        scope = mergeSubtargetScope(scope, typeof target.template === 'string' ? {
          templatePath: target.template
        } : target.template);

        return TemplateHelper(scope, sb);
      }
      if (target.jsonfile) {
        if (typeof target.jsonfile === 'object') {
          if (typeof target.jsonfile.data === 'function') {
            jsonfile.data = target.jsonfile.data(scope);
          }
          scope = mergeSubtargetScope(scope, target.jsonfile);
        } else if (typeof target.jsonfile === 'function') {
          scope = _.merge(scope, {
            data: target.jsonfile(scope)
          });
        }
        return JSONFileHelper(scope, sb);
      }

      // If we made it here, this must be a recursive generator:

      // Now that the generator definition has been resolved,
      // call this method recursively on it, passing along our
      // callback:
      if (++scope._depth > scope.maxHops) {
        return sb(new Error('`maxHops` (' + scope.maxHops + ' exceeded!  There is probably a recursive loop in one of your generators.'));
      }
      return recursiveGenerate(target, scope, sb);

    }
  ); //</ async.until >//
}

module.exports = generateTarget;

/**
 * @param  {[type]} scope     [description]
 * @param  {[type]} subtarget [description]
 * @return {[type]}           [description]
 */
function mergeSubtargetScope(scope, subtarget) {
  return _.merge(scope, _.isObject(subtarget) ? subtarget : {});
}

/**
 * Known helpers
 * @type {Array}
 */
var KNOWN_HELPERS = ['exec', 'folder', 'template', 'jsonfile', 'file', 'copy'];

function targetIsHelper(target) {
  return _.some(target, function(subTarget, key) {
    return _.contains(KNOWN_HELPERS, key);
  });
}

/**
 *
 * @param  {String|Object}   target      [description]
 * @param  {Object}          scope [description]
 * @param  {Function} cb          [description]
 * @return {[type]}               [description]
 */
function parseTarget(target, scope, cb) {

  if (typeof target === 'string') {
    target = {
      generator: target
    };
  }

  // Interpret generator definition
  if (targetIsHelper(target)) {
    return cb(null, target);
  }

  if (target.generator) {

    // Normalize the subgenerator reference
    var subGeneratorRef;
    if (typeof target.generator === 'string') {
      subGeneratorRef = {
        module: target.generator
      };
    } else if (typeof target.generator === 'object') {
      subGeneratorRef = target.generator;
    }
    if (!subGeneratorRef) {
      return cb(new Error('Generator Error: Invalid subgenerator referenced for target "' + scope.rootPath + '"'));
    }

    // Now normalize the sub-generator
    var subGenerator;

    // No `module` means we'll treat this subgenerator as an inline generator definition.
    if (!subGeneratorRef.module) {
      subGenerator = subGeneratorRef;
      if (subGenerator) return cb(null, subGenerator);
    }

    //
    // Otherwise, we'll attempt to load this subgenerator.
    //

    if (typeof subGeneratorRef.module === 'string') {
      // Lookup the generator by name if a `module` was specified
      // (this allows the module for a given generator to be
      //  overridden.)
      var configuredReference = scope.modules && scope.modules[subGeneratorRef.module];

      // Refers to a configured module (i.e. sailsrc or comparable)
      // so keep going.
      if (configuredReference) {
        return cb(null, configuredReference);
      }

      // If this generator type is explicitly set to `false`,
      // disable the generator.
      else if (configuredReference === false) {
        return cb(null, NOOP_GENERATOR);
      }

      // If `configuredReference` is undefined, continue on
      // and try to require the module.
      //
      // ||
      // \/
    }

    // At this point, subGeneratorRef.module should be a string,
    // and the best guess at the generator module we're going
    // to get.
    var module = subGeneratorRef.module;
    var requireError;

    // Try requiring it directly as a path
    try {
      subGenerator = require(module);
    } catch (e0) {
      requireError = e0;
    }

    // Try the scope's rootPath
    if (!subGenerator) {
      try {
        var asDependencyInRootPath = path.resolve(scope.rootPath, 'node_modules', module);
        subGenerator = require(asDependencyInRootPath);
      } catch (e1) {
        requireError = e1;
      }
    }

    // Try the current working directory
    if (!subGenerator) {
      try {
        subGenerator = require(path.resolve(process.cwd(), 'node_modules', module));
      } catch (e1) {
        requireError = e1;
      }
    }

    // If we couldn't find a generator using the configured module,
    // try requiring "sails-generate-<module>" to get the core generator
    if (!subGenerator && !module.match(/^sails-generate-/)) {
      try {
        subGenerator = require('sails-generate-' + module);
      }

      // Ok, we give up.
      catch (e1) {
        requireError = e1;
      }
    }

    // If we were able to find it, send it back!
    if (subGenerator) return cb(null, subGenerator);

    // But if we still can't find it, give up.

    // TODO: look for subGeneratorRef on npm
    // TODO: emit a message to scope.output letting user know what's going on
    return cb(
      new Error('Generator Error: Failed to load "' +
        subGeneratorRef.module + '"...' +
        (requireError ? ' (' + requireError + ')' : '') +
        ''));

  } //fi// target.generator

  return cb(new Error(
    'Unrecognized generator syntax in `targets["' + scope.keyPath + '"]` ::\n' +
    util.inspect(target)));
}

/**
 *
 * @param  {[type]}  target [description]
 * @return {Boolean}        [description]
 */
function isValidTarget(target) {
  var ok = true;

  ok = ok && typeof target === 'object';

  // Is using a helper
  // Or is another generator def.
  ok = ok && (targetIsHelper(target) || _.has(target, 'targets'));

  return ok;
}


text:
"""The tests for the Demo lock platform."""
import unittest

from homeassistant.setup import setup_component
from homeassistant.components import lock

from tests.common import get_test_home_assistant, mock_service
FRONT = 'lock.front_door'
KITCHEN = 'lock.kitchen_door'
OPENABLE_LOCK = 'lock.openable_lock'

class TestLockDemo(unittest.TestCase):
    """Test the demo lock."""

    def setUp(self):  # pylint: disable=invalid-name
        """Set up things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        self.assertTrue(setup_component(self.hass, lock.DOMAIN, {
            'lock': {
                'platform': 'demo'
            }
        }))

    def tearDown(self):  # pylint: disable=invalid-name
        """Stop everything that was started."""
        self.hass.stop()

    def test_is_locked(self):
        """Test if lock is locked."""
        self.assertTrue(lock.is_locked(self.hass, FRONT))
        self.hass.states.is_state(FRONT, 'locked')

        self.assertFalse(lock.is_locked(self.hass, KITCHEN))
        self.hass.states.is_state(KITCHEN, 'unlocked')

    def test_locking(self):
        """Test the locking of a lock."""
        lock.lock(self.hass, KITCHEN)
        self.hass.block_till_done()

        self.assertTrue(lock.is_locked(self.hass, KITCHEN))

    def test_unlocking(self):
        """Test the unlocking of a lock."""
        lock.unlock(self.hass, FRONT)
        self.hass.block_till_done()

        self.assertFalse(lock.is_locked(self.hass, FRONT))

    def test_opening(self):
        """Test the opening of a lock."""
        calls = mock_service(self.hass, lock.DOMAIN, lock.SERVICE_OPEN)
        lock.open_lock(self.hass, OPENABLE_LOCK)
        self.hass.block_till_done()
        self.assertEqual(1, len(calls))


text:
<?php

/**
 * Exemplo de como enviar um sms pela API módulo de sms
 * Author: Team Developers DirectCall
 * Data: 2013-03-14
 * Referencia: http://teste2.directcallsoft.com:8090/pages/viewpage.action?pageId=524534
 */

// URL que será feita a requisição
$urlSms = "http://api.directcallsoft.com/sms/send";

// Numero de origem
$origem = "5521992220009";

// Numero de destino
$destino = "5521992220009";

// Tipo de envio, podendo ser "texto" ou "voz"
$tipo = "texto";

// Texto a ser enviado
$texto = "Olá Mundo!";

// Incluir o RequisitarToken.php para pegar o access_token
include("RequisitarToken.php");

// Formato do retorno, pode ser JSON ou XML
$format = "JSON";

// Dados em formato QUERY_STRING
$data = http_build_query(array('origem'=>$origem, 'destino'=>$destino, 'tipo'=>$tipo, 'access_token'=>$access_token, 'texto'=>$texto));

$ch = 	curl_init();
		curl_setopt($ch, CURLOPT_URL, $urlSms);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		$return = curl_exec($ch);

		curl_close($ch);

		// Converte os dados de JSON para ARRAY
		$dados = json_decode($return, true);

		// Imprime o retorno
		echo "API: ".			$dados['api']."\n";
		echo "MODULO: ".		$dados['modulo']."\n";
		echo "STATUS: ".		$dados['status']."\n";
		echo "CODIGO: ".		$dados['codigo']."\n";
		echo "MENSAGEM: ".		$dados['msg']."\n";
		echo "CALLERID: ".		$dados['callerid']."\n";


text:
ACCEPTED

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

#### Published in
Karstenia 42(2): 46 (2002)

#### Original name
Armillaria elegans Beeli, 1927

### Remarks
null


text:
#!/usr/bin/env node

/**
 * Module dependencies
 */

var nodepath = require('path');
var _ = require('@sailshq/lodash');
var chalk = require('chalk');
var captains = require('captains-log');
var package = require('../package.json');
var rconf = require('../lib/app/configuration/rc');
var Sails = require('../lib/app');

/**
 * `sails lift`
 *
 * Expose method which lifts the appropriate instance of Sails.
 * (Fire up the Sails app in our working directory.)
 *
 * @stability 3
 * @see http://sailsjs.org/documentation/reference/command-line-interface/sails-lift
 */

module.exports = function() {

  // console.time('cli_lift');
  // console.time('cli_prelift');

  // console.time('cli_rc');
  var log = captains(rconf.log);
  // console.timeEnd('cli_rc');

  console.log();
  log.info(chalk.grey('Starting app...'));
  console.log();

  // Build initial scope, mixing-in rc config
  var scope = _.merge({
    rootPath: process.cwd(),
    sailsPackageJSON: package
  }, rconf);

  var appPath = process.cwd();

  // Use the app's local Sails in `node_modules` if it's extant and valid
  var localSailsPath = nodepath.resolve(appPath, 'node_modules/sails');
  if (Sails.isLocalSailsValid(localSailsPath, appPath)) {
    var localSails = require(localSailsPath);
    // console.timeEnd('cli_prelift');

    localSails.lift(scope, afterwards);
    return;
  }

  // Otherwise, if no workable local Sails exists, run the app
  // using the currently running version of Sails.  This is
  // probably always the global install.
  var globalSails = Sails();
  // console.timeEnd('cli_prelift');

  globalSails.lift(scope, afterwards);

  function afterwards (err, sails) {
    if (err) {
      var message = err.stack ? err.stack : err;
      sails ? sails.log.error(message) : log.error(message); process.exit(1);
    }
    // try {console.timeEnd('cli_lift');}catch(e){}
  }
};


text:
import DashboardImmersionContainer from 'components/DashboardImmersion/DashboardImmersionContainer'
import DashboardImmersionData from 'components/DashboardImmersion/DashboardImmersionData'
import DashboardImmersionPresentation from 'components/DashboardImmersion/DashboardImmersionPresentation'

export default {
  Container: DashboardImmersionContainer,
  Data: DashboardImmersionData,
  Presentation: DashboardImmersionPresentation,
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Slimbone App</title>
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="{{config['app']['assets']}}/css/app.css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                  Toggle navigation

                </button>
                Slimbone
                Github code

    {% if config['mode'] == "development" %}

    {% else %}

    {% endif %}

    {% block content %}{% endblock %}

Powered by: Slim PHP Backbone JS Require JS Mongo DB Bootstrap 3 Composer Bower Grunt Scss Twig i18n

KZima 2013


text:
using System.Web;
using System.Web.Routing;

namespace sharp.webApiSession.Handlers
{
    public class SessionStateRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new SessionableControllerHandler(requestContext.RouteData);
        }
    }
}


text:
/**
 * 性能统计 - 用户可操作时间
 */

(function() {
    if (window.performance) {
        window.time = window.time || {
            ready: 0
        };

        window.document.addEventListener('DOMContentLoaded', function() {
            window.time.ready = +new Date - window.performance.timing.navigationStart;
        });
    }
})();


text:
Simple Ruby client for the [BlockCypher](http://www.blockcypher.com) API.

## Setup

Simply using rubygems:

    gem install blockcypher-ruby

## Initializing a client

If you want to use BTC on the main net, which is normally what you want to do, it's as simple as:

    block_cypher = BlockCypher::Api.new

## BlockCypher's documentation

For more information check the API docs at:

http://dev.blockcypher.com

## Contributors

Contributions from [CoinHako](http://www.coinhako.com) and [meXBT](https://mexbt.com)


text:
using System;
using Microsoft.SPOT;
using System.Text;
using System.IO.Ports;
namespace SerialLib {
    public delegate void SerialMessengerHandler(SerialMessenger sender, byte[] message, int offset, int length);

    public class SerialMessenger : IDisposable {
        protected SerialPort Uart;
        protected UTF8Encoding Encoder = new UTF8Encoding();
        protected byte[] Incoming;
        protected int IncomingIndex;

        public event SerialMessengerHandler Messenger;

        public void Initialize(string port = "COM1", int baudRate = 57600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One, int bufferSize = 80) {
            Incoming = new byte[bufferSize];
            Uart = new SerialPort(port, baudRate, parity, dataBits, stopBits);
            Uart.Open();
            Uart.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            IncomingIndex = 0;
        }
        ~SerialMessenger() {
            Dispose();
        }
        public void Dispose() {
            Uart.Flush();
            Uart.DataReceived -= DataReceivedHandler;
            Uart.Close();
            Uart.Dispose();
        }
        public void Send(string line) {
            Send(Encoder.GetBytes(line),0, (byte)line.Length);
        }
        public void SendAck() {
            Send(Ack, 0, (byte)Ack.Length);
        }
        public void SendNack() {
            Send(Nack, 0, (byte)Nack.Length);
        }

        protected byte[] FrameStart = new byte[] { 0x7e, 0x00 };
        protected byte[] FrameStop = new byte[] { 0x7e };
        protected byte[] Ack = new byte[] { 0xaa };
        protected byte[] Nack = new byte[] { 0xff };

        public void Send(byte[] data, int offset, byte count){
            FrameStart[1] = (byte)(count + FrameStart.Length + FrameStop.Length);
            Uart.Write(FrameStart, 0, FrameStart.Length);
            Uart.Flush();
            Uart.Write(data, offset, count);
            Uart.Flush();
            Uart.Write(FrameStop, 0, FrameStop.Length);
            Uart.Flush();
        }
        protected byte FrameComplete;
        protected byte FrameLength;
        protected bool CaptureFrameLength = false;
        protected int ReceivedByteCount;

        public int TotalByteReceived;

        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
            var sp = (SerialPort)sender;
            var readCount = sp.BytesToRead;
            while (readCount > 0) {
                if (IncomingIndex < Incoming.Length) {
                    sp.Read(Incoming, IncomingIndex++, 1);
                    readCount--;
                    ReceivedByteCount++;
                    TotalByteReceived++;
                    if (CaptureFrameLength) {
                        FrameLength = Incoming[IncomingIndex - 1];
                        CaptureFrameLength = false;
                    }
                    if (Incoming[IncomingIndex - 1] == 0x7e) {
                        switch (FrameComplete) {
                            case 0: // start of a frame
                                FrameComplete = 1;
                                FrameLength = 0;
                                CaptureFrameLength = true; // capture the frame length in the next byte
                                break;
                            case 1: // end of a frame marker
                                if ((IncomingIndex >= FrameLength) && Incoming[IncomingIndex - FrameLength + 1] == FrameLength) { // end of frame if the whole frame length has been received only
                                    if (Messenger != null) { // process the payload embedded in the frame
                                        Messenger(this, Incoming, (IncomingIndex - FrameLength) + FrameStart.Length, FrameLength - (FrameStart.Length + FrameStop.Length));
                                        FrameComplete = 0; // Get ready for the next frame
                                        ReceivedByteCount = 0;
                                    } else {
                                        // no message handler, discard everything
                                        FrameComplete = 0;
                                        IncomingIndex = 0;
                                        ReceivedByteCount = 0;
                                        sp.DiscardInBuffer();
                                        SendNack();
                                    }
                                } else {
                                    // something went wrong with the transmission: reset everything.
                                    FrameComplete = 0;
                                    IncomingIndex = 0;
                                    ReceivedByteCount = 0;
                                    sp.DiscardInBuffer();
                                    SendNack();
                                }
                            break;
                        }
                    }
                } else {
                    // case where the buffer rolls over: move the existing data to the beginning of the buffer
                    Array.Copy(Incoming, Incoming.Length - ReceivedByteCount, Incoming, 0, ReceivedByteCount);
                    IncomingIndex = ReceivedByteCount;
                }
            }
        }
    }
}


text:
<!DOCTYPE HTML>

		<title>OmegaGo</title>
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta name="description" content="" />
		<meta name="keywords" content="" />

			<link rel="stylesheet" href="static/css/skel.css" />
			<link rel="stylesheet" href="static/css/style.css" />
			<link rel="stylesheet" href="static/css/style-large.css" />

OmegaGo

Elastic, Highly Distributed Go AI
                                Tournaments

Rachel Kositsky and Joe Doyle

Summary

                We developed a distributed system for running games of
                Go between computation-intensive AIs. This system is
                able to elastically use available computational
                resources to run games between these AIs continuously.
                Despite 15-213 finals limiting the available computers
                in Gates, we ran about 6000 games in the week
                of May 3rd. As of Friday, May 6, we were
                running 35 active games (2 AIs per game)
                with 267 CPU threads across 36 computers.

View
                on Github

Watch the
                            current tournament or Play
                        against an AI!

(If your browser says "This connection is not
                    secure", choose advanced -> continue anyway)

Results

                For this system, we developed 5 AIs, including
                a lock-free parallel Monte-Carlo Tree
                Search, Convolutional Neural
                Networks (CNNs) trained on skilled
                players, and Asynchronous-Policy Monte-Carlo
                Tree Search (AP-MCTS), which combines a CNN
                with MCTS for improved search effectiveness. These AIs
                were run on publically available computers at Carnegie
                Mellon, and the CNNs were trained on the Latedays cluster.

We analysed these
                games to determine the relative win rate of each
                pair of AIs:

                Notably, MCTS with more search threads beats MCTS with
                    fewer, and AP-MCTS is more effective
                against other AIs than the corresponding MCTS. This is
                also supported by the win-rate against One-Move
                Search, which makes the move that immediately increases its
                score by the most -- i.e., it makes the largest
                capture it can, and plays a stone which encloses
                territory if it can.

Due to bugs in
                feature processing, we had to restart training of the
                CNNs on May 5. Since then, we have achieved above
                27% prediction accuracy on samples of
                the training dataset (AlphaGo improved the state of
                the art from 44.4% to 57%):

Approach

AIs

Lock-Free Parallel Monte-Carlo Tree Search

Uses random games to estimate the value of a given
                move.

As a confirmation of effectiveness, MCTS AIs with more
                search threads win with high probability against MCTS AIs
                with fewer search threads.

Atomic updates of the tree are implemented with C++
                std::atomic containers.

Each thread runs a greedy tree search, then plays
                random moves until the end of the game. Once the game is
                completed, the winner is decided and the thread moves
                backwards through the tree, atomically updating the
                expected value of each move until the current game state
                is reached. Once a move is played a certain number of
                times, a new node is allocated and inserted into the tree
                with an atomic compare-and-swap.

Convolutional Neural Networks

Implemented with tiny-cnn (A CPU-based neural network
                library) for minimal dependencies, accelerated with SSE
                vector instructions and OpenMP.

Designed to match the architecture and feature-set of
                Google DeepMind's AlphaGo, with smaller size parameters in
                consideration of the performance constraints of the chosen
                library.

The input features are the same as published for
                AlphaGo, except that the two features for tactical ladder
                search is excluded. The layers of the network are (in
                order):

A 19x19x46 input layer which is fed a binary
                    feature image, with 46 binary features extracted from
                    each point on the board.

A single convolutional layer with k 5x5
                    filters, followed by a Rectified Linear Unit

n "inner" convolutional layers with
                    k 3x3

A convolutional layer with a single 1x1 filter,
                    with biases for each point, followed by a softmax
                    activation

Trained from a collection of 70,000 skilled amateur games using
                stochastic gradient descent with a minibatch size of 256,
                alpha = 0.006. Each round of consisted of sampling 1024
                random board states from the training set, followed 4
                training minibatches. Training was done on Latedays
                worker nodes

Software Architecture

Python Web Server

Hosts game logic, work distribution

Manages a C++ child process which implements game
                logic -- communicates through standard input/output pipes.

Allows a user to start new games with up to 2 AI
                players.

Hosts the game state as the games are played.

Receives moves from workers as HTTP requests.

Sends board state to all players/spectators.

Queues and distributes AI tasks to available workers
                when a new game is started.

Elastic Worker Management

Each worker can be started with no intervention other
                than starting a bash script.

All dependencies are downloaded and compiled
                automatically -- the scripts only depend on git,
                python2.7, virtualenv, cmake, and a C++11 compiler -- and
                installation of Python and virtualenv are partially
                automated for machines that have incompatible
                versions.

Each worker detects how many available CPU threads and
                how much RAM it has, and communicates this to the main
                server (some resources are left out, to avoid totally
                overloading each machine).

All worker processes run with niceness 19, so they
                interfere minimally with other processes on the machine.

The server is resilient to workers disconnecting -- if
                a worker does not send a status to the main server for 30
                seconds, it is deleted from the worker pool.

The workers are resilient to server disconnects as
                well -- if the server restarts, the worker's tasks die,
                and the worker reconnects to the server to service new
                tasks.

The server will spawn matches proportional to its
                available resources, and thus can dynamically adapt to
                changes in workforce.

Background

Go is a total-knowledge two-player
    board game focused on placing pieces to surround territory and
    capture the opponent’s pieces. Until recently, it has been
    infeasible to create a strong Go AI because the branching factor
    of the move tree is incredibly high, making exhaustive search, and
    even A/B pruning, infeasible.

The state of the art in computer Go has been
    Monte Carlo Tree Search, a probabilistic method for move
    evaluation which assigns an expected win rate to each move by
    averaging the outcomes of random games from each move. Modern AIs
    have begun using Convolutional Neural Networks to bias this search
    and to estimate the value of a board state without needing to
    traverse fully down the move tree. Google DeepMind’s AlphaGo
    software recently used this technique to repeatedly defeat some of
    the best professional Go players in the world.

Convolutional Neural Networks are
    commonly used for object recognition and other image processing
    techniques where other algorithmic techniques are either
    insufficient or too costly to develop. If large labelled datasets
    are available, a CNN can provide a high level of precision with
    comparatively little development time. Since a Go board can be
    viewed as a 19x19 image with 3 possible values (black, white,
    open) for each pixels, CNNs can operate on attributes of the
    current board state like an image.

A policy in the
            context of MCTS is a function which takes in the current
            board state and move history, and outputs a probability
            distribution over possible next moves. If the policy is
            computationally expensive, this distribution can used to
            provide initial bias to the tree search. Otherwise, the
            policy may be used to weight the random function during
            the random-play stage of MCTS. For AlphaGo's APV-MCTS and
            our AP-MCTS, CNNs with a final softmax layer act as the
            primary policy weighting moves in the tree search. These
            policies are executed asynchronously, and the MCTS weights
            are updated atomically.

Resources

 The
        primary resource for this project is the paper
    “Mastering the game of Go with deep neural networks and tree
search” (

     http://www.nature.com/nature/journal/v529/n7587/pdf/nature16961.pdf

    ), which describes the implementation of Google’s
        AlphaGo. The citation is:

    Silver, David, et al. "Mastering the game of Go with
        deep neural networks and tree search."

    Nature

     529.7587 (2016): 484-489.

 We used tiny-cnn
        for neural network training and evaluation. This library is
        accelerated with OpenMP and vector instructions, but it is not
        particularly high-performance. However, this library is
        extremely small and has no external dependencies, which made
        it ideal for scaling out. Since we did not need any special
        drivers or complicated dependencies, any AI could be run on
        any machine with enough CPU threads and RAM.

 WGo.js (

     http://wgo.waltheri.net/

    ) provided the main board interface for the web site.

 For training the CNN, we used a randomly selected
        70,000-game subset of the 170,000-game
            database of high-rank amateur games

 To manage workers and host the web
        interface, we use Python and the micro-framework Flask.
        Workers communicate with the server via the Python requests
    library.

Proposal
                        Page

OmegaGo: For when you can't afford Google.


text:
//
//  UISearchBar+MLAdd.h
//  Pods
//
//  Created by molon on 16/8/28.
//
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

/**
 Provides extensions for `UISearchBar`.
 */
@interface UISearchBar (MLAdd)

/**
 If YES, cancel button will be always enabled after `resignFirstResponder`,
 */
@property (nonatomic, assign) BOOL enableCancelButtonAfterResignFirstResponder;

@end

NS_ASSUME_NONNULL_END


text:
package org.collin.dashboard.core;

import org.collin.core.essence.ITetra;
import org.collin.ui.main.CollinComposite;
import org.collin.ui.main.CollinViewerComposite;
import org.collin.ui.main.TetraViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;

public class Dispatcher implements ISelectionChangedListener{

	private static Dispatcher dispatcher = new Dispatcher();

	private CollinComposite ccomposite;
	private CollinViewerComposite vccomposite;
	private TetraViewer tetraViewer;

	private ISelectionChangedListener listener = new ISelectionChangedListener() {

		@Override
		public void selectionChanged(SelectionChangedEvent event) {
			IStructuredSelection selection = event.getStructuredSelection();
			if( selection.isEmpty() )
				return;
			Object obj = selection.getFirstElement();
			if( obj instanceof ITetra)
				tetraViewer.setInput(0, (ITetra<?>) obj);

		}
	};

	public static Dispatcher getInstance() {
		return dispatcher;
	}

	public CollinComposite getCcomposite() {
		return ccomposite;
	}

	public CollinViewerComposite getVccomposite() {
		return vccomposite;
	}

	public void setCcomposite(CollinComposite ccomposite) {
		this.ccomposite = ccomposite;
	}

	public void setVccomposite(CollinViewerComposite vccomposite) {
		if( this.vccomposite != null )
			this.vccomposite.removeSelectionListener(listener);
		this.vccomposite = vccomposite;
		this.vccomposite.setSelectionListener(listener);
	}

	public void setTetraViewer(TetraViewer tetraViewer) {
		this.tetraViewer = tetraViewer;
	}

	@Override
	public void selectionChanged(SelectionChangedEvent event) {
		// TODO Auto-generated method stub

	}

}


text:
package net.kucoe.elvn.lang.result;

import net.kucoe.elvn.List;
import net.kucoe.elvn.ListColor;
import net.kucoe.elvn.util.Config;
import net.kucoe.elvn.util.Display;

/**
 * Switch to list by color
 *
 * @author Vitaliy Basyuk
 */
public class SwitchListColor extends SwitchList {

    /**
     * Color
     */
    public final ListColor color;

    /**
     * Constructs SwitchListColor.
     *
     * @param color
     */
    public SwitchListColor(final ListColor color) {
        this.color = color;
    }

    @Override
    public String execute(final Display display, final Config config) throws Exception {
        List list = config.getList(color);
        if (list != null) {
            display.showList(list);
            return list.getColor();
        }
        return null;
    }

}


text:
import React, { PropTypes } from 'react';

import ChangesLinks from 'es6!display/changes/links';
import { ChangesPage, APINotLoadedPage } from 'es6!display/page_chrome';
import { Grid, GridRow } from 'es6!display/grid';
import { SingleBuildStatus } from 'es6!display/changes/builds';
import { TimeText, display_duration_pieces } from 'es6!display/time';
import { WaitingLiveText } from 'es6!display/changes/build_text';
import { get_runnable_condition,
         get_runnable_condition_color_cls,
         is_waiting } from 'es6!display/changes/build_conditions';

import * as api from 'es6!server/api';

import * as utils from 'es6!utils/utils';

// how often to hit the api server for updates
const POLL_INTERVAL = 10000;

/*
 * Modern query params:
 * - branch: select branch to display.
 * - project: pass multiple times to select projects to display. The value
 *   should be a project slug. All projects should be for the same repo.
 *
 * Antiquated query params: main (multiple times)
 * - The first main parameter determines the list of commits to show.
 *   Additional main parameters will show latest builds for that commit.
 * - A parameter can be just a project slug, or slug::branch.
 */
var PusherPage = React.createClass({

  getInitialTitle() {
    return 'Dashboard';
  },

  getInitialState() {
    var endpoints = this.getEndpoints();

    var state = {};
    _.each(_.keys(endpoints), key => {
      state[key] = null;
    });
    return state;
  },

  componentDidMount() {
    api.fetch(this, this.getEndpoints());

    this.updateInProgress = false;
    this.refreshTimer = window.setInterval(__ => {
      if (!this.isMounted()) {
        return;
      }
      this.liveUpdate();
    }, POLL_INTERVAL);
  },

  render() {
    if (this.updateInProgress) {
      if (api.allLoaded(_.values(this.state.liveUpdate))) {
        this.updateInProgress = false;
        utils.async(__ => {
          var emptyLiveUpdate = _.mapObject(this.getEndpoints(), (v, k) => null);
          this.setState(_.extend(
            {liveUpdate: emptyLiveUpdate},
            this.state.liveUpdate));
        });
      }
    }

    var [slugs, branch] = this.getSlugsAndBranch();
    var endpoints = this.getEndpoints();
    var apiResponses = _.map(endpoints, (v, k) => this.state[k]);

    if (!api.allLoaded(apiResponses)) {
      return <APINotLoadedPage calls={apiResponses} widget={false} />;
    }

    // Adding key=current timestamp forces us to unmount/remount
    // PusherPageContent every re-render. This seems to prevent crazy memory
    // leaks, albeit at the cost of slightly less responsiveness (which is fine
    // for a dashboard.) I think I could solve this in a more sophisticated
    // way, but this is fine for now.
    return <ChangesPage widget={false}>
      <PusherPageContent
        slugs={slugs}
        branch={branch}
        fetchedState={this.state}
        key={+Date.now()}
      />
    </ChangesPage>;
  },

  getSlugsAndBranch() {
    var queryParams = URI(window.location.href).search(true);

    var slugs, branch;
    if (queryParams['project']) {
      // Modern parameters.
      slugs = queryParams['project'];
      if (!_.isArray(slugs)) {
        slugs = [slugs];
      }
      if (queryParams['branch']) {
        branch = queryParams['branch'];
      }
    } else {
      // Antiquated parameters.
      var mains = queryParams['main'];
      if (!_.isArray(mains)) {
        mains = [mains];
      }
      slugs = [];
      _.each(mains, main => {
        let [slug, temp_branch] = main.split('::');
        slugs.push(slug);
        if (!branch && temp_branch) {
          branch = temp_branch;
        }
      });
    }

    return [slugs, branch];
  },

  getEndpoints() {
    var queryParams = URI(window.location.href).search(true);
    let per_page = '50';
    if (queryParams['per_page']) {
      per_page = queryParams['per_page'];
    }

    var [slugs, branch] = this.getSlugsAndBranch();

    var endpoints = {};
    _.each(slugs, slug => {
      endpoints[slug] = URI(`/api/0/projects/${slug}/commits/`)
        .query({ all_builds: 1, branch: branch, per_page: per_page })
        .toString();
    });
    return endpoints;
  },

  liveUpdate() {
    // we'll make new API calls inside of liveUpdate. Once they've all
    // finished, we'll use setState to copy them over
    this.updateInProgress = true;
    this.setState({
      liveUpdate: _.mapObject(this.getEndpoints(), (v, k) => null)
    });

    api.fetchMap(this, 'liveUpdate', this.getEndpoints());
  },

  componentWillUnmount() {
    // clear the timer, if in use (e.g. the widget is expanded)
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
  }
});

var PusherPageContent = React.createClass({

  propTypes: {
    slugs: PropTypes.array.isRequired,
    branch: PropTypes.string.isRequired,
  },

  getInitialState() { return {}; },

  render() {
    var slugs = this.props.slugs;
    var totalProjectCount = slugs.length;

    // we want to map slugs to project data (e.g. so we know the name of the
    // project. This is buried within each buld
    var projectData = {};

    var commitLists = {};
    _.each(slugs, proj => {
      commitLists[proj] = this.props.fetchedState[proj].getReturnedData();
    });

    // I don't want to write anything too complicated, so here's what we'll do:
    // we'll use the first "main" project as the source of truth for revisions,
    // and augment it with displaying builds from other projects.
    var rows = _.map(commitLists[slugs[0]], baseCommit => {
      var everyCommit = {};
      _.each(commitLists, (commitList, proj) => {
        _.each(commitList, commitInList => {
          if (commitInList.sha === baseCommit.sha) {
            everyCommit[proj] = commitInList;
          }
        });
      });

      var initialCells = [];
      _.each(slugs, proj => {
        if (!everyCommit[proj]) {
          initialCells.push(null);
          return;
        }

        var commit = everyCommit[proj];
        var sortedBuilds = _.sortBy(commit.builds, b => b.dateCreated).reverse();
        var lastBuild = _.first(sortedBuilds);
        if (lastBuild) {
          if (lastBuild.project) {
            projectData[lastBuild.project.slug] = lastBuild.project;
          }
          var duration = null;
          if (is_waiting(get_runnable_condition(lastBuild))) {
            duration = <WaitingLiveText runnable={lastBuild} text={false} />;
          } else {
            var pieces = _.chain(display_duration_pieces(lastBuild.duration / 1000))
              .filter(p => p)
              .map(p => p.replace(/[dmsh]/, ''))
              .value();

            duration = pieces.join(":");
          }

          var colorCls = get_runnable_condition_color_cls(get_runnable_condition(lastBuild));
          var durationStyle = {
            display: 'inline-block',
            position: 'relative',
            top: -2,
          };

          initialCells.push(

                <SingleBuildStatus
                  build={lastBuild}
                  parentElem={this}
                />

                {duration}

          );
        } else {
          initialCells.push(null);
        }
      });

      // TODO: add the skip the queue indicator to this page (for consistency,
      // if nothing else)
      var title = utils.truncate(utils.first_line(baseCommit.message));

      let cells = initialCells.concat([
        title,
        ChangesLinks.author(baseCommit.author),
        ChangesLinks.phabCommit(baseCommit),
        <TimeText time={baseCommit.dateCommitted} />
      ]);
      return new GridRow(baseCommit.sha, cells);
    });

    var projectHeaders = _.map(slugs, proj => {
      var name = utils.truncate(
        (projectData[proj] && projectData[proj].name) || proj,
        20);
      return

{name}

;
    });

    var headers = projectHeaders.concat([
      'Name',
      'Author',
      'Commit',
      'Committed'
    ]);

    var classHeaders = _.map(slugs, proj => 'nowrap buildWidgetCell');
    var cellClasses = classHeaders.concat([
      'wide',
      'nowrap',
      'nowrap',
      'nowrap'
    ]);

    return

      <Grid
        colnum={4 + totalProjectCount}
        cellClasses={cellClasses}
        headers={headers}
        data={rows}
      />

;
  },
});

export default PusherPage;


text:
package im.actor.sdk.util;

import java.util.Random;

public class Randoms {

    private static final Random RANDOM = new Random();

    public static long randomId() {
        synchronized (RANDOM) {
            return Math.abs(RANDOM.nextLong());
        }
    }

    public static int randomInt() {
        synchronized (RANDOM) {
            return Math.abs(RANDOM.nextInt());
        }
    }

    public static byte[] generateSeed(int len) {
        synchronized (RANDOM) {
            byte[] res = new byte[len];
            RANDOM.nextBytes(res);
            return res;
        }
    }
}


text:
class CreateMappings < ActiveRecord::Migration
  def self.up
    create_table :mappings do |t|
      t.integer :sabiork_id
      t.integer :chebi_id
      t.integer :kegg_id

      t.timestamps
    end
  end

  def self.down
    drop_table :mappings
  end
end


text:
import sys
import os
import base64

def _EnsurePngIsInPath():
  png_path = os.path.join(os.path.dirname(__file__),
                          '..', '..', '..', 'third_party', 'png')
  if png_path not in sys.path:
    sys.path.append(png_path)

_EnsurePngIsInPath()
import png # pylint: disable=F0401

class PngColor(object):
  """Encapsulates an RGB color retreived from a PngBitmap"""

  def __init__(self, r, g, b, a=255):
    self.r = r
    self.g = g
    self.b = b
    self.a = a

  def IsEqual(self, expected_color, tolerance=0):
    """Verifies that the color is within a given tolerance of
    the expected color"""
    r_diff = abs(self.r - expected_color.r)
    g_diff = abs(self.g - expected_color.g)
    b_diff = abs(self.b - expected_color.b)
    a_diff = abs(self.a - expected_color.a)
    return (r_diff <= tolerance and g_diff <= tolerance
        and b_diff <= tolerance and a_diff <= tolerance)

  def AssertIsRGB(self, r, g, b, tolerance=0):
    assert self.IsEqual(PngColor(r, g, b), tolerance)

  def AssertIsRGBA(self, r, g, b, a, tolerance=0):
    assert self.IsEqual(PngColor(r, g, b, a), tolerance)

class PngBitmap(object):
  """Utilities for parsing and inspecting inspecting a PNG"""

  def __init__(self, base64_png):
    self._png_data = base64.b64decode(base64_png)
    self._png = png.Reader(bytes=self._png_data)
    rgba8_data = self._png.asRGBA8()
    self._width = rgba8_data[0]
    self._height = rgba8_data[1]
    self._pixels = list(rgba8_data[2])
    self._metadata = rgba8_data[3]

  @property
  def width(self):
    """Width of the snapshot"""
    return self._width

  @property
  def height(self):
    """Height of the snapshot"""
    return self._height

  def GetPixelColor(self, x, y):
    """Returns a PngColor for the pixel at (x, y)"""
    row = self._pixels[y]
    offset = x * 4
    return PngColor(row[offset], row[offset+1], row[offset+2], row[offset+3])

  def WriteFile(self, path):
    with open(path, "wb") as f:
      f.write(self._png_data)


text:
package net.imglib2.ops.operation.complex.unary;

import net.imglib2.ops.operation.UnaryOperation;
import net.imglib2.type.numeric.ComplexType;

/**
 * A {@link UnaryOperation} between {@link ComplexType}s.
 *
 * @author Barry DeZonia
 * @deprecated Use net.imagej.ops instead.
 */
@Deprecated
public interface ComplexUnaryOperation<
		I extends ComplexType<I>, O extends ComplexType<O>>
	extends UnaryOperation<I,O>
{
	// no methods: this interface is type constraining and nothing else
}


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

   <extension-point id="classBuilder" name="Class builder" schema="schema/classBuilder.exsd"/>
   <extension-point id="dataParser" name="Data parser" schema="schema/dataParser.exsd"/>
   <extension-point id="scriptingEngine" name="Scripting Engine" schema="schema/scriptingEngine.exsd"/>

   <extension point="com.swtworkbench.community.xswt.classBuilder">
   		<import	packages="com.swtworkbench.community.xswt.scripting"/>
   </extension>

   <extension point="com.swtworkbench.community.xswt.dataParser">
   		<data-parser
   			data-parser-class="com.swtworkbench.community.xswt.scripting.MethodFunctionDataParser"
   			data-class="com.swtworkbench.community.xswt.scripting.Function"/>
   </extension>

</plugin>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
    internal class DifferenceViewerPreview : IDisposable
    {
        private IWpfDifferenceViewer _viewer;

        public DifferenceViewerPreview(IWpfDifferenceViewer viewer)
        {
            Contract.ThrowIfNull(viewer);
            _viewer = viewer;
        }

        public IWpfDifferenceViewer Viewer => _viewer;

        public void Dispose()
        {
            GC.SuppressFinalize(this);

            if (_viewer != null && !_viewer.IsClosed)
            {
                _viewer.Close();
            }

            _viewer = null;
        }

        ~DifferenceViewerPreview()
        {
            // make sure we are not leaking diff viewer
            // we can't close the view from finalizer thread since it must be same
            // thread (owner thread) this UI is created.
            if (Environment.HasShutdownStarted)
            {
                return;
            }

            FatalError.ReportWithoutCrash(new Exception($"Dispose is not called how? viewer state : {_viewer.IsClosed}"));
        }
    }
}


text:
SPEC_BEGIN(HTBUserManagerSpec)

__block HTBUserManager *userManager = nil;

    beforeAll(^{
       userManager = [HTBUserManager sharedManager];
    });

    it(@"tokenを保存して取り出せる", ^{
       AFOAuth1Token *token = [[AFOAuth1Token alloc] initWithKey:@"key"
                                                          secret:@"secret"
                                                         session:@"session"
                                                      expiration:[NSDate date]
                                                       renewable:YES];
        userManager.token = token;
        [[userManager.token.key shouldEventually] equal:@"key"];
        [[userManager.token.secret shouldEventually] equal:@"secret"];
    });

    it(@"authorizeEntryを保存して取り出せる", ^{
        HTBAuthorizeEntry *entry = [[HTBAuthorizeEntry alloc] initWithQueryString:@"oauth_token=dummyoAuthToken%3D%3D&oauth_token_secret=dummyoAuthTokenSecret%3D&url_name=cinnamon&display_name=%e3%81%97%e3%81%aa%e3%82%82%e3%82%93"];
        userManager.authorizeEntry = entry;

        [[userManager.authorizeEntry.username should] equal:@"cinnamon"];
        [[userManager.authorizeEntry.displayName should] equal:@"しなもん"];
    });

    it(@"authorizeEntryの値を削除できる", ^{
        userManager.authorizeEntry = nil;
        [[userManager.authorizeEntry should] beNil];
    });

SPEC_END


text:
<?php

namespace Concardis\Payengine\Lib\Internal\Interfaces;

interface Getable
{

    function get($queryParams);

}


text:
/*
  # Graph

  This classes uses libcairo,libpixman,libplplot to generate a graph
  which is used to inspect the video encoder, audio encoder, network io etc..

 */
#ifndef ROXLU_GRAPH_H
#define ROXLU_GRAPH_H

extern "C" {
#  include <uv.h>
}

#include <map>
#include <string>
#include <vector>
#include <sstream>

#define GRAPH_MODE_NONE 0    /* do nothing with the values */
#define GRAPH_MODE_AVG 1     /* avarage the values */
#define GRAPH_MODE_ABS 2     /* use the absolute given values */
// --------------------------------------------------------------

struct GraphData {
  GraphData();

  std::string getStyle(); /* get the style command, use %d for the line number, e.g: `set style line %d lt 2 lw 3` */
  void setLineStyle(int lineType, int w, int pointType, std::string color); /* set all styles */
  void setLineType(int type); /* set the line type */
  void setLineWidth(int w); /* set the line width */
  void setLinePointType(int t); /* set the point type */
  void setLineColor(std::string col); /* set the line color */

  void setMode(uint8_t m); /* GRAPH_MODE_AVG, etc.. */
  void push(); /* pushes the avarage on top of the data vector */
  size_t size(); /* total number of elements */
  void operator+=(const uint64_t&); /* add something to the total */
  uint64_t& operator[](const unsigned int&); /* get an entry from the data */

  uint8_t mode; /* defaults to GRAPH_MODE_AVG */
  uint64_t total;
  uint64_t num_added;
  std::vector<uint64_t> data; /* keeps track of avarages, see "push()" */

  /* style */
  std::string color; /* line color, a named color, if not set we pick one */
  int type; /* line type */
  int width; /* line width */
  int point_type; /* th epoint type */
};

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

class Graph {
 public:
  Graph();
  ~Graph();
  void start(float timescale); /* timescale: every X-millis we avarage the data which has been added. */
  void update();
  bool save(std::string filename); /* filename = name of file w/o extension */

  GraphData& operator[](std::string);
  std::map<std::string, GraphData> graphs;
  std::string title;
  std::string x_label;
  std::string y_label;
  std::string yrange;
  std::string ytics; /* every `ytics` we create a label on the y axis */
  size_t max_values; /* maximum number of values to keep track of.. if more values are added we pop from the front */

  uint64_t timeout; /* when we 'timeout' and should add a new entry to the avarages, see update() */
  uint64_t timeout_delay; /* delay between time outs */
};

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

inline GraphData& Graph::operator[](std::string name) {
  return graphs[name];
}

inline void GraphData::operator+=(const uint64_t& v) {
  total += v;
  num_added++;
}

inline void GraphData::push() {
  if(num_added == 0) {
    data.push_back(0);
  }
  else {
    if(mode == GRAPH_MODE_AVG) {
      data.push_back(total/num_added);
    }
    else if(mode == GRAPH_MODE_ABS) {
      data.push_back(total);
    }
  }
  total = 0;
  num_added = 0;
}

inline size_t GraphData::size() {
  return data.size();
}

inline uint64_t& GraphData::operator[](const unsigned int& dx) {
  return data[dx];
}

inline void GraphData::setMode(uint8_t m) {
  mode = m;
}

inline void GraphData::setLineType(int t) {
  type = t;
}

inline void GraphData::setLineWidth(int w) {
  width = w;
}

inline void GraphData::setLineColor(std::string c) {
  color = c;
}

inline void GraphData::setLinePointType(int pt) {
  point_type = pt;
}

inline std::string GraphData::getStyle() {
  std::stringstream ss;
  ss << "set style line %d "
     << "lc rgb \"" << color << "\" "
     << "pt " << point_type << " "
     << "ps 1 " << " "
     << "lt " << type << " "
     << "lw " << width
    ;
  std::string s = ss.str();
  return s;
}

inline void GraphData::setLineStyle(int lt, int w, int pt, std::string c) {
  setLineType(lt);
  setLineWidth(w);
  setLineColor(c);
  setLinePointType(pt);
}

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

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

extern Graph network_graph;
extern Graph frames_graph;

#endif


text:
/*
 * This program is distributed under the terms of the MIT license:
 * <https://github.com/v0lkan/talks/blob/master/LICENSE.md>
 * Send your comments and suggestions to <me@volkan.io>.
 */

function ListView(el, options) {
    this.el = el;

    var defaults = {
        itemNodeName : 'li',
        maxSize      : 25,
        isCompact    : true
    };

    this.options = _.extend(defaults, options||{});
}

ListView.prototype.initialize = function() {};
ListView.prototype.destroy    = function() {};

function TreeListView() {}

// Very simple inheritance
TreeListView.prototype        = new ListView();
TreeListView.prototype.parent = ListView;
TreeListView.constructor      = TreeListView;

TreeListView.prototype.initialize = function() {
    doInitialization();

    this.parent.prototype.initialize.call(this, arguments);
};


text:
package com.nway.platform.wform.design.entity;

public class ListPage extends FormField {

	private int index;

	private String formatter;

	private boolean isMultiValue;

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public String getFormatter() {
		return formatter;
	}

	public void setFormatter(String formatter) {
		this.formatter = formatter;
	}

	public boolean isMultiValue() {
		return isMultiValue;
	}

	public void setMultiValue(boolean isMultiValue) {
		this.isMultiValue = isMultiValue;
	}

}