text:
div.markItUp a:link,
div.markItUp a:visited {
  color:#000;
  text-decoration:none;
}
div.markItUp  {
}
div.markItUpContainer  {
  border:1px solid #3C769D;
  background:#FFF url(images/bg-container.png) repeat-x top left;
  padding:5px 5px 2px 5px;
  font:11px Verdana, Arial, Helvetica, sans-serif;
  border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
}
textarea.markItUpEditor,
textarea.markItUpEditor:active,
.dm textarea.markItUpEditor,
.dm textarea.markItUpEditor:active,
.sf_admin_form_row_inner textarea.markItUpEditor {
  font:12px 'Courier New', Courier, monospace;
  border:3px solid #3C769D;
  width: 98%;
  background:#FFF url(images/bg-editor.png) repeat-x top left;
  clear:both; display:block;
  line-height:18px;
  overflow:auto;
}

div.markItUpFooter {
  width:100%;
}
div.markItUpResizeHandler {
  overflow:hidden;
  width:22px; height:5px;
  margin-left:auto;
  margin-right:auto;
  background-image:url(images/handle.png);
}
/***************************************************************************************/
/* first row of buttons */
div.markItUpHeader ul li  {
  list-style:none;
  float:left;
  position:relative;
}
div.markItUpHeader ul li.markItUpSeparator {
  margin:0 10px;
  width:1px;
  height:16px;
  overflow:hidden;
  background-color:#CCC;
}
div.markItUpHeader ul a {
  display:block;
  width:16px; height:16px;
  text-indent:-10000px;
  background-repeat:no-repeat;
  padding:3px !important;
  margin:0px;
}

.markdown_preview {
  padding: 10px;
  border: 1px solid #3C769D;
  background: #F8F8F8;
  background-position: 0 -28px;
  overflow-y: auto;
  border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
}

div.markItUpContainer div.ui-resizable-s {
  bottom: 0;
  background: url(images/handle.png) no-repeat center 2px;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="fluidpirates.fluidpirates_android.oneProposition">
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="100dp"
        android:id="@+id/list"
        android:layout_alignParentBottom="true"
        android:background="@android:color/holo_blue_bright"
        android:listSelector="@android:color/holo_blue_dark">
    </ListView>

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
package ml.iamwhatiam.tao.ddd;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * meta java bean
 *
 * @author iMinusMinus
 * @since 2017-02-09
 * @version 0.0.1
 *
 */
public class JavaBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private Logger log = LoggerFactory.getLogger(JavaBean.class);

	private static Set<String> keywords;

	static {
		keywords = new HashSet<String>();
        keywords.add("package");
        keywords.add("class");
        keywords.add("interface");
        keywords.add("import");
        keywords.add("extends");
        keywords.add("implements");
        keywords.add("public");
        keywords.add("protected");
        keywords.add("private");
        keywords.add("abstract");
        keywords.add("native");
        keywords.add("static");
        keywords.add("final");
        keywords.add("transient");
        keywords.add("volatile");
        keywords.add("boolean");
        keywords.add("byte");
        keywords.add("char");
        keywords.add("short");
        keywords.add("int");
        keywords.add("long");
        keywords.add("float");
        keywords.add("double");
        keywords.add("void");
        keywords.add("return");
        keywords.add("if");
        keywords.add("else");
        keywords.add("for");
        keywords.add("do");
        keywords.add("while");
        keywords.add("switch");
        keywords.add("case");
        keywords.add("default");
        keywords.add("continue");
        keywords.add("break");
        keywords.add("goto");
        keywords.add("try");
        keywords.add("catch");
        keywords.add("finally");
        keywords.add("throw");
        keywords.add("throws");
        keywords.add("new");
        keywords.add("true");
        keywords.add("false");
        keywords.add("null");
        keywords.add("instanceof");
        keywords.add("synchronized");
        keywords.add("super");
        keywords.add("this");
        keywords.add("strictfp");
        keywords.add("enum");
        keywords.add("const");
        keywords.add("assert");
	}

	private String name;

	private String comment;

	private List<Property> properties;

//	private Constraint cascade;

	private Set<String> imports = new TreeSet<String>();

	public JavaBean(String name) {
		if(keywords.contains(name)) {
			log.error("field name must not be java keyword: [{}]", name);
			throw new IllegalArgumentException("field name must not be java keyword");
		}
		else this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		if(keywords.contains(name)) {
			log.error("field name must not be java keyword: [{}]", name);
			throw new IllegalArgumentException("field name must not be java keyword");
		}
		else this.name = name;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public List<Property> getProperties() {
		return properties;
	}

	public void setProperties(List<Property> properties) {
		this.properties = properties;
	}

	public void addProperty(Property property) {
		if(properties == null)
			properties = new ArrayList<Property>();
		properties.add(property);
	}

	public Set<String> getImports() {
		return imports;
	}

	public class Property implements Serializable {

		private static final long serialVersionUID = 1L;

		/**
		 * field name
		 */
		private String name;

		/**
		 * field type name
		 */
		private String type;

		/**
		 * field type
		 */
		private Class<?> klazz;

		/**
		 * field default value
		 */
		private Object defaultValue;

		/**
		 * field value
		 */
		private Object value;

		/**
		 * field comment
		 */
		private String comment;

		/**
		 * field constraints
		 */
		private List<Constraint> constraints;

		/**
		 * inner bean
		 */
		private JavaBean bean;

		public Property(String name, Class<?> javaType) {
			this.klazz = javaType;
			if(keywords.contains(name)) {
				log.error("field name must not be java keyword: [{}]", name);
				throw new IllegalArgumentException("field name must not be java keyword");
			}
			else this.name = name;
			this.type = javaType.getName();
			if(!javaType.isPrimitive() && !javaType.getPackage().getName().equals("java.lang"))
				imports.add(javaType.getName());
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			if(keywords.contains(name)) {
				log.error("field name must not be java keyword: [{}]", name);
				throw new IllegalArgumentException("field name must not be java keyword");
			}
			else this.name = name;
		}

		public String getType() {
			return type;
		}

		void setType(String type) {
			this.type = type;
		}

		public Class<?> getKlazz() {
			return klazz;
		}

		public Object getDefaultValue() {
			return defaultValue;
		}

		public void setDefaultValue(Object defaultValue) {
			this.defaultValue = defaultValue;
		}

		public Object getValue() {
			return value;
		}

		public void setValue(Object value) {
			this.value = value;
		}

		public String getComment() {
			return comment;
		}

		public void setComment(String comment) {
			this.comment = comment;
		}

		public List<Constraint> getConstraints() {
			return constraints;
		}

		public void addConstraint(Constraint constraint) {
			if(constraints == null)
				constraints = new ArrayList<Constraint>();
			constraints.add(constraint);
		}

		public void setConstraints(List<Constraint> constraints) {
			this.constraints = constraints;
		}

		public JavaBean getBean() {
			return bean;
		}

		public void setBean(JavaBean bean) {
			this.bean = bean;
		}

	}

	public class Constraint implements Serializable {

		private static final long serialVersionUID = 1L;

		private String type;

		private Class<? extends Annotation> annotationType;

		private Map<String, Object> values;

		//ignore message, payload and groups

		public Constraint(Class<? extends Annotation> type) {
			this.type = type.getSimpleName();
			this.annotationType = type;
			if(!type.getPackage().getName().equals("java.lang"))
				imports.add(type.getName());
		}

		public Constraint(Class<? extends Annotation> type, Map<String, Object> values) {
			this.type = type.getSimpleName();
			this.annotationType = type;
			if(!type.getPackage().getName().equals("java.lang"))
				imports.add(type.getName());
			this.values = values;
		}

		public String getType() {
			return type;
		}

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

		public Class<? extends Annotation> getAnnotationType() {
			return annotationType;
		}

		public Map<String, Object> getValues() {
			return values;
		}

		public void setValues(Map<String, Object> values) {
			this.values = values;
		}

	}

}


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 enable

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    internal sealed class SynthesizedEmbeddedNativeIntegerAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase
    {
        private readonly ImmutableArray<FieldSymbol> _fields;
        private readonly ImmutableArray<MethodSymbol> _constructors;
        private readonly TypeSymbol _boolType;

        private const string FieldName = "TransformFlags";

        public SynthesizedEmbeddedNativeIntegerAttributeSymbol(
            string name,
            NamespaceSymbol containingNamespace,
            ModuleSymbol containingModule,
            NamedTypeSymbol systemAttributeType,
            TypeSymbol boolType)
            : base(name, containingNamespace, containingModule, baseType: systemAttributeType)
        {
            _boolType = boolType;

            var boolArrayType = TypeWithAnnotations.Create(
                ArrayTypeSymbol.CreateSZArray(
                    boolType.ContainingAssembly,
                    TypeWithAnnotations.Create(boolType)));

            _fields = ImmutableArray.Create<FieldSymbol>(
                new SynthesizedFieldSymbol(
                    this,
                    boolArrayType.Type,
                    FieldName,
                    isPublic: true,
                    isReadOnly: true,
                    isStatic: false));

            _constructors = ImmutableArray.Create<MethodSymbol>(
                new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(
                    this,
                    m => ImmutableArray<ParameterSymbol>.Empty,
                    (f, s, p) => GenerateParameterlessConstructorBody(f, s)),
                new SynthesizedEmbeddedAttributeConstructorWithBodySymbol(
                    this,
                    m => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, boolArrayType, 0, RefKind.None)),
                    (f, s, p) => GenerateBoolArrayConstructorBody(f, s, p)));

            // Ensure we never get out of sync with the description
            Debug.Assert(_constructors.Length == AttributeDescription.NativeIntegerAttribute.Signatures.Length);
        }

        internal override IEnumerable<FieldSymbol> GetFieldsToEmit() => _fields;

        public override ImmutableArray<MethodSymbol> Constructors => _constructors;

        internal override AttributeUsageInfo GetAttributeUsageInfo()
        {
            return new AttributeUsageInfo(
                AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue,
                allowMultiple: false,
                inherited: false);
        }

        private void GenerateParameterlessConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder<BoundStatement> statements)
        {
            statements.Add(
                factory.ExpressionStatement(
                    factory.AssignmentExpression(
                        factory.Field(
                            factory.This(),
                            _fields.Single()),
                        factory.Array(
                            _boolType,
                            ImmutableArray.Create<BoundExpression>(factory.Literal(true))
                        )
                    )
                )
            );
        }

        private void GenerateBoolArrayConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder<BoundStatement> statements, ImmutableArray<ParameterSymbol> parameters)
        {
            statements.Add(
                factory.ExpressionStatement(
                    factory.AssignmentExpression(
                        factory.Field(
                            factory.This(),
                            _fields.Single()),
                        factory.Parameter(parameters.Single())
                    )
                )
            );
        }
    }
}


text:
package model.command.testdata

import model.SchemeId
import model.exchange.AssessorAvailability
import model.persisted.assessor.AssessorStatus
import model.persisted.assessor.AssessorStatus.AssessorStatus
import org.joda.time.LocalDate
import play.api.libs.json.JodaWrites._ // This is needed for DateTime serialization
import play.api.libs.json.JodaReads._ // This is needed for DateTime serialization
import play.api.libs.json.{ Json, OFormat }

object CreateAdminRequest {

  case class CreateAdminRequest(emailPrefix: Option[String], firstName: Option[String], lastName: Option[String],
                                preferredName: Option[String], roles: Option[List[String]], phone: Option[String],
                                assessor: Option[AssessorRequest]) extends CreateTestDataRequest {
  }

  object CreateAdminRequest {
    implicit val createAdminRequestFormat: OFormat[CreateAdminRequest] = Json.format[CreateAdminRequest]
  }

  case class AssessorRequest(skills: Option[List[String]] = None,
                             sifterSchemes: Option[List[SchemeId]] = None,
                             civilServant: Option[Boolean] = None,
                             availability: Option[Set[AssessorAvailabilityRequest]] = None,
                             status: AssessorStatus = AssessorStatus.CREATED)

  object AssessorRequest {
    implicit val assessorTestDataFormat: OFormat[AssessorRequest] = Json.format[AssessorRequest]
  }

  case class AssessorAvailabilityRequest(location: String, date: LocalDate)

  object AssessorAvailabilityRequest {
    implicit val assessorAvailabilityRequestFormat: OFormat[AssessorAvailabilityRequest] = Json.format[AssessorAvailabilityRequest]

    def apply(exchange: AssessorAvailability): AssessorAvailabilityRequest = {
      AssessorAvailabilityRequest(exchange.location, exchange.date)
    }
  }

}


text:
<?php

declare (strict_types=1);
namespace Rector\CodeQuality\Rector\FunctionLike;

use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Property;
use PhpParser\NodeTraverser;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\Type;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\MethodName;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\NodeTypeResolver\PHPStan\Type\StaticTypeAnalyzer;
use Rector\NodeTypeResolver\PHPStan\Type\TypeFactory;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
 * @changelog https://phpstan.org/r/e909844a-084e-427e-92ac-fed3c2aeabab
 *
 * @see \Rector\Tests\CodeQuality\Rector\FunctionLike\RemoveAlwaysTrueConditionSetInConstructorRector\RemoveAlwaysTrueConditionSetInConstructorRectorTest
 */
final class RemoveAlwaysTrueConditionSetInConstructorRector extends \Rector\Core\Rector\AbstractRector
{
    /**
     * @var \Rector\NodeTypeResolver\PHPStan\Type\StaticTypeAnalyzer
     */
    private $staticTypeAnalyzer;
    /**
     * @var \Rector\NodeTypeResolver\PHPStan\Type\TypeFactory
     */
    private $typeFactory;
    public function __construct(\Rector\NodeTypeResolver\PHPStan\Type\StaticTypeAnalyzer $staticTypeAnalyzer, \Rector\NodeTypeResolver\PHPStan\Type\TypeFactory $typeFactory)
    {
        $this->staticTypeAnalyzer = $staticTypeAnalyzer;
        $this->typeFactory = $typeFactory;
    }
    public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
    {
        return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('If conditions is always true, perform the content right away', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE'
final class SomeClass
{
    private $value;

    public function __construct(stdClass $value)
    {
        $this->value = $value;
    }

    public function go()
    {
        if ($this->value) {
            return 'yes';
        }
    }
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
final class SomeClass
{
    private $value;

    public function __construct(stdClass $value)
    {
        $this->value = $value;
    }

    public function go()
    {
        return 'yes';
    }
}
CODE_SAMPLE
)]);
    }
    /**
     * @return array<class-string<Node>>
     */
    public function getNodeTypes() : array
    {
        return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\Closure::class];
    }
    /**
     * @param ClassMethod|Closure $node
     */
    public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
    {
        if ($node->stmts === null) {
            return null;
        }
        if ($node->stmts === []) {
            return null;
        }
        $haveNodeChanged = \false;
        foreach ($node->stmts as $key => $stmt) {
            if ($stmt instanceof \PhpParser\Node\Stmt\Expression) {
                $stmt = $stmt->expr;
            }
            if (!$this->isAlwaysTruableNode($stmt)) {
                continue;
            }
            /** @var If_ $stmt */
            if (\count($stmt->stmts) === 1) {
                $node->stmts[$key] = $stmt->stmts[0];
                continue;
            }
            $haveNodeChanged = \true;
            // move all nodes one level up
            \array_splice($node->stmts, $key, \count($stmt->stmts) - 1, $stmt->stmts);
        }
        if ($haveNodeChanged) {
            return $node;
        }
        return null;
    }
    private function isAlwaysTruableNode(\PhpParser\Node $node) : bool
    {
        if (!$node instanceof \PhpParser\Node\Stmt\If_) {
            return \false;
        }
        // just one if
        if ($node->elseifs !== []) {
            return \false;
        }
        // there is some else
        if ($node->else !== null) {
            return \false;
        }
        // only property fetch, because of constructor set
        if (!$node->cond instanceof \PhpParser\Node\Expr\PropertyFetch) {
            return \false;
        }
        $propertyFetchType = $this->resolvePropertyFetchType($node->cond);
        return $this->staticTypeAnalyzer->isAlwaysTruableType($propertyFetchType);
    }
    private function resolvePropertyFetchType(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : \PHPStan\Type\Type
    {
        $classLike = $propertyFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE);
        if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) {
            return new \PHPStan\Type\MixedType();
        }
        $propertyName = $this->getName($propertyFetch);
        if ($propertyName === null) {
            return new \PHPStan\Type\MixedType();
        }
        $property = $classLike->getProperty($propertyName);
        if (!$property instanceof \PhpParser\Node\Stmt\Property) {
            return new \PHPStan\Type\MixedType();
        }
        // anything but private can be changed from outer scope
        if (!$property->isPrivate()) {
            return new \PHPStan\Type\MixedType();
        }
        // set in constructor + changed in class
        $propertyTypeFromConstructor = $this->resolvePropertyTypeAfterConstructor($classLike, $propertyName);
        $resolvedTypes = [];
        $resolvedTypes[] = $propertyTypeFromConstructor;
        $defaultValue = $property->props[0]->default;
        if ($defaultValue !== null) {
            $resolvedTypes[] = $this->getStaticType($defaultValue);
        }
        $resolveAssignedType = $this->resolveAssignedTypeInStmtsByPropertyName($classLike->stmts, $propertyName);
        if ($resolveAssignedType !== null) {
            $resolvedTypes[] = $resolveAssignedType;
        }
        return $this->typeFactory->createMixedPassedOrUnionTypeAndKeepConstant($resolvedTypes);
    }
    private function resolvePropertyTypeAfterConstructor(\PhpParser\Node\Stmt\Class_ $class, string $propertyName) : \PHPStan\Type\Type
    {
        $propertyTypeFromConstructor = null;
        $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT);
        if ($constructClassMethod !== null) {
            $propertyTypeFromConstructor = $this->resolveAssignedTypeInStmtsByPropertyName((array) $constructClassMethod->stmts, $propertyName);
        }
        if ($propertyTypeFromConstructor !== null) {
            return $propertyTypeFromConstructor;
        }
        // undefined property is null by default
        return new \PHPStan\Type\NullType();
    }
    /**
     * @param Stmt[] $stmts
     */
    private function resolveAssignedTypeInStmtsByPropertyName(array $stmts, string $propertyName) : ?\PHPStan\Type\Type
    {
        $resolvedTypes = [];
        $this->traverseNodesWithCallable($stmts, function (\PhpParser\Node $node) use($propertyName, &$resolvedTypes) : ?int {
            if ($node instanceof \PhpParser\Node\Stmt\ClassMethod && $this->isName($node, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) {
                return \PhpParser\NodeTraverser::DONT_TRAVERSE_CHILDREN;
            }
            if (!$this->isPropertyFetchAssignOfPropertyName($node, $propertyName)) {
                return null;
            }
            if (!$node instanceof \PhpParser\Node\Expr\Assign) {
                return null;
            }
            $resolvedTypes[] = $this->getStaticType($node->expr);
            return null;
        });
        if ($resolvedTypes === []) {
            return null;
        }
        return $this->typeFactory->createMixedPassedOrUnionTypeAndKeepConstant($resolvedTypes);
    }
    /**
     * E.g. $this->{value} = x
     */
    private function isPropertyFetchAssignOfPropertyName(\PhpParser\Node $node, string $propertyName) : bool
    {
        if (!$node instanceof \PhpParser\Node\Expr\Assign) {
            return \false;
        }
        if (!$node->var instanceof \PhpParser\Node\Expr\PropertyFetch) {
            return \false;
        }
        return $this->isName($node->var, $propertyName);
    }
}


text:
layout: post
title: "如何不借助Virtualbox在OSX平台上基于xhyve运行docker-machine"
modified: 2016-04-14 16:47:50 +0800
tags: [xhyve,Docker]
image:
  feature:
  credit:
  creditlink:
comments:
share:
---
相对于Virtualbox,[xhyve](https://github.com/mist64/xhyve)更加轻量级,这也是Docker Toolbox下一个版本的重大更新,虽然我提交了Docker Toolbox Beta的申请,但是,截至本文写作时,还未得到安装介质。

## 安装xhyve与docker

{% highlight bash %}
brew install xhyve docker docker-machine docker-compose docker-machine-driver-xhyve
{% endhighlight %}

注意:如果你在安装前已经安装了Docker Toolbox,安装时会遇到错误提示,所以,执行以上命令前,要么卸载Docker Toolbox,要么根据提示修复错误,我自己实践地是后一种方式。

## 创建docker-machine

{% highlight bash %}
sudo chown root:wheel $(brew --prefix)/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
sudo chmod u+s $(brew --prefix)/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
docker-machine create default --driver xhyve
{% endhighlight %}

初始化Shell:
{% highlight bash %}
eval $(docker-machine env default)
{% endhighlight %}

## 设置docker-machine代理

由于在公司实验,所以不得不设置代理。执行以下命令进入boot2docker:

{% highlight bash %}
docker-machine ssh default
{% endhighlight %}

编辑profile文件:
{% highlight bash %}
sudo vi /var/lib/boot2docker/profile
{% endhighlight %}

添加以下内容:

{% highlight bash %}
export http_proxy=http://your-proxy-host:your-proxy-port
export https_proxy=http://your-proxy-host:your-proxy-port
{% endhighlight %}

重新启动:

{% highlight bash %}
docker-machine restart default
{% endhighlight %}

## 测试

打开Terminal,执行:

{% highlight bash %}
eval $(docker-machine env default)
{% endhighlight %}

下载容器镜像:

{% highlight bash %}
docker pull ubuntu
{% endhighlight %}

查看容器镜像:
{% highlight bash %}
docker images
{% endhighlight %}

妥了!以后再也不用Virtualbox这个笨家伙了!


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-185.js
 * @description Object.getOwnPropertyDescriptor returns data desc (all false) for properties on built-ins (Function.prototype)
 */

function testcase() {
  var desc = Object.getOwnPropertyDescriptor(Function, "prototype");

  if (desc.writable === false &&
      desc.enumerable === false &&
      desc.configurable === false &&
      desc.hasOwnProperty('get') === false &&
      desc.hasOwnProperty('set') === false) {
    return true;
  }
 }
runTestCase(testcase);


text:
import { StateParams, StateService } from '@uirouter/core';
import { IScope } from 'angular';
import * as _ from 'lodash';

import { IdentityProvider } from '../../entities/identity-provider/identityProvider';
import { User } from '../../entities/user';
import AuthenticationService from '../../services/authentication.service';
import ReCaptchaService from '../../services/reCaptcha.service';
import RouterService from '../../services/router.service';
import UserService from '../../services/user.service';

class LoginController {
  user: any = {};
  userCreationEnabled: boolean;
  localLoginDisabled: boolean;

  constructor(
    private AuthenticationService: AuthenticationService,
    private UserService: UserService,
    private $state: StateService,
    private Constants,
    private $rootScope: IScope,
    private RouterService: RouterService,
    private identityProviders,
    private $window,
    private $stateParams: StateParams,
    private $scope,
    private ReCaptchaService: ReCaptchaService,
  ) {
    'ngInject';
    this.userCreationEnabled = Constants.org.settings.management.userCreation.enabled;
    this.localLoginDisabled = !Constants.org.settings.authentication.localLogin.enabled || false;
    this.$state = $state;
    this.$rootScope = $rootScope;
    this.$scope = $scope;
    $scope.canBeDisabled = false;
  }

  $onInit() {
    this.ReCaptchaService.displayBadge();
    document.addEventListener('click', this._toDisabledMode);
  }

  $onDestroy() {
    document.removeEventListener('click', this._toDisabledMode);
  }

  authenticate(identityProvider: string) {
    const nonce = this.AuthenticationService.nonce(32);

    const redirectUri = this.getRedirectUri();

    this.$window.localStorage[nonce] = JSON.stringify({ redirectUri });

    const provider = _.find(this.identityProviders, { id: identityProvider }) as IdentityProvider;
    this.AuthenticationService.authenticate(provider, nonce);
  }

  _toDisabledMode = () => {
    this.$scope.canBeDisabled = true;
    this.$scope.$apply();
    document.removeEventListener('click', this._toDisabledMode);
  };

  login() {
    this.ReCaptchaService.execute('login').then(() =>
      this.UserService.login(this.user)
        .then(() => {
          this.UserService.current().then((user) => {
            this.loginSuccess(user);
          });
        })
        .catch(() => {
          this.user.username = '';
          this.user.password = '';
        }),
    );
  }

  loginSuccess(user: User) {
    this.$rootScope.$broadcast('graviteeUserRefresh', { user: user });
    const redirectUri = this.getRedirectUri();
    if (redirectUri && !redirectUri.includes('/newsletter')) {
      this.$window.location.href = redirectUri;
    } else {
      const route = this.RouterService.getLastRoute();
      if (
        route.from &&
        route.from.name !== '' &&
        route.from.name !== 'logout' &&
        route.from.name !== 'confirm' &&
        route.from.name !== 'resetPassword'
      ) {
        this.$state.go(route.from.name, route.fromParams);
      } else {
        this.$state.go('management');
      }
    }
  }

  getProviderBackGroundColor(provider: any) {
    if (provider.color) {
      return provider.color;
    }
    if (provider.type === 'OIDC') {
      return 'black';
    }
    if (provider.type === 'GRAVITEEIO_AM') {
      return '#86c3d0';
    }
    return '';
  }

  getProviderColor(provider: any) {
    if (provider.type === 'GRAVITEEIO_AM') {
      return '#383E3F';
    }
    return 'white';
  }

  getProviderStyle(provider: any) {
    return {
      'background-color': this.getProviderBackGroundColor(provider),
      color: this.getProviderColor(provider),
    };
  }

  getRedirectUri() {
    let redirectUri = '';
    if (this.$state.params.redirectUri) {
      if (this.$state.params.redirectUri.toLowerCase().startsWith('http')) {
        redirectUri = this.$state.params.redirectUri;
        if (this.$state.params['#']) {
          redirectUri += '#' + this.$state.params['#'];
        }
      } else {
        redirectUri = '#!' + this.$state.params.redirectUri;
      }
    }
    return redirectUri;
  }
}

export default LoginController;


text:
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
SOURCEDIR     = .
BUILDDIR      = _build

# Put it first so that "make" without argument is like "make help".
help:
	@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

api:
	javasphinx-apidoc -f --title "KOMORAN API" -o api/ ../src/main/java/kr/co/shineware/nlp/komoran/

docs:
	make clean
#	make -B api
	make html

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
	@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Vida es una sola, hay que viajar!">

    <title>Blog - Nomadas</title>

    <link rel="canonical" href="http://nomadas.com.ve/blog/pagina2/">

    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <link rel="stylesheet" href="/css/clean-blog.css">

    <link rel="stylesheet" href="/css/syntax.css">

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Nomadas

                    Home

                    About

                    Acerca de

                    Contact

                    Blog

                    Blog

Blog

                    Todos los articulos en orden cronologico

            Dinosaurs are extinct today

            because they lacked opposable thumbs and the brainpower to build a space program.

Posted by Start Bootstrap on June 10, 2014

        ← Newer Posts

Copyright © Nomadas 2016


text:
namespace performance_manager {

namespace {

// Private implementation of the node attached data. This keeps the complexity
// out of the header file.
class PageLiveStateDataImpl
    : public PageLiveStateDecorator::Data,
      public NodeAttachedDataImpl<PageLiveStateDataImpl> {
 public:
  struct Traits : public NodeAttachedDataInMap<PageNodeImpl> {};
  ~PageLiveStateDataImpl() override = default;
  PageLiveStateDataImpl(const PageLiveStateDataImpl& other) = delete;
  PageLiveStateDataImpl& operator=(const PageLiveStateDataImpl&) = delete;

  // PageLiveStateDecorator::Data:
  bool IsConnectedToUSBDevice() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_connected_to_usb_device_;
  }
  bool IsConnectedToBluetoothDevice() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_connected_to_bluetooth_device_;
  }
  bool IsCapturingVideo() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_capturing_video_;
  }
  bool IsCapturingAudio() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_capturing_audio_;
  }
  bool IsBeingMirrored() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_being_mirrored_;
  }
  bool IsCapturingWindow() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_capturing_window_;
  }
  bool IsCapturingDisplay() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_capturing_display_;
  }
  bool IsAutoDiscardable() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_auto_discardable_;
  }
  bool WasDiscarded() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return was_discarded_;
  }
  bool IsActiveTab() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return is_active_tab_;
  }
  bool IsContentSettingTypeAllowed(ContentSettingsType type) const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    auto it = content_settings_.find(type);
    return it != content_settings_.end() && it->second == CONTENT_SETTING_ALLOW;
  }

  void SetIsConnectedToUSBDeviceForTesting(bool value) override {
    set_is_connected_to_usb_device(value);
  }
  void SetIsConnectedToBluetoothDeviceForTesting(bool value) override {
    set_is_connected_to_bluetooth_device(value);
  }
  void SetIsCapturingVideoForTesting(bool value) override {
    set_is_capturing_video(value);
  }
  void SetIsCapturingAudioForTesting(bool value) override {
    set_is_capturing_audio(value);
  }
  void SetIsBeingMirroredForTesting(bool value) override {
    set_is_being_mirrored(value);
  }
  void SetIsCapturingWindowForTesting(bool value) override {
    set_is_capturing_window(value);
  }
  void SetIsCapturingDisplayForTesting(bool value) override {
    set_is_capturing_display(value);
  }
  void SetIsAutoDiscardableForTesting(bool value) override {
    set_is_auto_discardable(value);
  }
  void SetWasDiscardedForTesting(bool value) override {
    set_was_discarded(value);
  }
  void SetIsActiveTabForTesting(bool value) override {
    set_is_active_tab(value);
  }
  void SetContentSettingsForTesting(
      const std::map<ContentSettingsType, ContentSetting>& settings) override {
    set_content_settings(settings);
  }

  void set_is_connected_to_usb_device(bool is_connected_to_usb_device) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_connected_to_usb_device_ == is_connected_to_usb_device)
      return;
    is_connected_to_usb_device_ = is_connected_to_usb_device;
    for (auto& obs : observers_)
      obs.OnIsConnectedToUSBDeviceChanged(page_node_);
  }
  void set_is_connected_to_bluetooth_device(
      bool is_connected_to_bluetooth_device) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_connected_to_bluetooth_device_ == is_connected_to_bluetooth_device)
      return;
    is_connected_to_bluetooth_device_ = is_connected_to_bluetooth_device;
    for (auto& obs : observers_)
      obs.OnIsConnectedToBluetoothDeviceChanged(page_node_);
  }
  void set_is_capturing_video(bool is_capturing_video) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_capturing_video_ == is_capturing_video)
      return;
    is_capturing_video_ = is_capturing_video;
    for (auto& obs : observers_)
      obs.OnIsCapturingVideoChanged(page_node_);
  }
  void set_is_capturing_audio(bool is_capturing_audio) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_capturing_audio_ == is_capturing_audio)
      return;
    is_capturing_audio_ = is_capturing_audio;
    for (auto& obs : observers_)
      obs.OnIsCapturingAudioChanged(page_node_);
  }
  void set_is_being_mirrored(bool is_being_mirrored) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_being_mirrored_ == is_being_mirrored)
      return;
    is_being_mirrored_ = is_being_mirrored;
    for (auto& obs : observers_)
      obs.OnIsBeingMirroredChanged(page_node_);
  }
  void set_is_capturing_window(bool is_capturing_window) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_capturing_window_ == is_capturing_window)
      return;
    is_capturing_window_ = is_capturing_window;
    for (auto& obs : observers_)
      obs.OnIsCapturingWindowChanged(page_node_);
  }
  void set_is_capturing_display(bool is_capturing_display) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_capturing_display_ == is_capturing_display)
      return;
    is_capturing_display_ = is_capturing_display;
    for (auto& obs : observers_)
      obs.OnIsCapturingDisplayChanged(page_node_);
  }
  void set_is_auto_discardable(bool is_auto_discardable) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_auto_discardable_ == is_auto_discardable)
      return;
    is_auto_discardable_ = is_auto_discardable;
    for (auto& obs : observers_)
      obs.OnIsAutoDiscardableChanged(page_node_);
  }
  void set_was_discarded(bool was_discarded) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (was_discarded_ == was_discarded)
      return;
    was_discarded_ = was_discarded;
    for (auto& obs : observers_)
      obs.OnWasDiscardedChanged(page_node_);
  }
  void set_is_active_tab(bool is_active_tab) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (is_active_tab_ == is_active_tab)
      return;
    is_active_tab_ = is_active_tab;
    for (auto& obs : observers_)
      obs.OnIsActiveTabChanged(page_node_);
  }
  void set_content_settings(
      std::map<ContentSettingsType, ContentSetting> settings) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    // Content settings are set for the first time when the page navigates, and
    // subsequently when a notification that they have changed is received.
    // Therefore, no need to check to see if they're equal to the previous
    // value.
    content_settings_ = std::move(settings);
    for (auto& obs : observers_)
      obs.OnContentSettingsChanged(page_node_);
  }

 private:
  // Make the impl our friend so it can access the constructor and any
  // storage providers.
  friend class ::performance_manager::NodeAttachedDataImpl<
      PageLiveStateDataImpl>;

  explicit PageLiveStateDataImpl(const PageNodeImpl* page_node)
      : page_node_(page_node) {}

  bool is_connected_to_usb_device_ GUARDED_BY_CONTEXT(sequence_checker_) =
      false;
  bool is_connected_to_bluetooth_device_ GUARDED_BY_CONTEXT(sequence_checker_) =
      false;
  bool is_capturing_video_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  bool is_capturing_audio_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  bool is_being_mirrored_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  bool is_capturing_window_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  bool is_capturing_display_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  bool is_auto_discardable_ GUARDED_BY_CONTEXT(sequence_checker_) = true;
  bool was_discarded_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  bool is_active_tab_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  std::map<ContentSettingsType, ContentSetting> content_settings_
      GUARDED_BY_CONTEXT(sequence_checker_);

  const raw_ptr<const PageNode> page_node_;
};

const char kDescriberName[] = "PageLiveStateDecorator";

}  // namespace

void PageLiveStateDecorator::Delegate::GetContentSettingsAndReply(
    WebContentsProxy web_contents_proxy,
    const GURL& url,
    GetContentSettingsForUrlCallback callback) {
  content::WebContents* web_contents = web_contents_proxy.Get();
  if (web_contents) {
    PerformanceManager::CallOnGraph(
        FROM_HERE,
        base::BindOnce(
            std::move(callback),
            PerformanceManager::GetPrimaryPageNodeForWebContents(web_contents),
            GetContentSettingsForUrl(web_contents, url)));
  }
}

PageLiveStateDecorator::PageLiveStateDecorator(
    base::SequenceBound<Delegate> delegate)
    : delegate_(std::move(delegate)) {}
PageLiveStateDecorator::~PageLiveStateDecorator() = default;

// static
void PageLiveStateDecorator::OnIsConnectedToUSBDeviceChanged(
    content::WebContents* contents,
    bool is_connected_to_usb_device) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_connected_to_usb_device,
      is_connected_to_usb_device);
}

// static
void PageLiveStateDecorator::OnIsConnectedToBluetoothDeviceChanged(
    content::WebContents* contents,
    bool is_connected_to_bluetooth_device) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_connected_to_bluetooth_device,
      is_connected_to_bluetooth_device);
}

// static
void PageLiveStateDecorator::OnIsCapturingVideoChanged(
    content::WebContents* contents,
    bool is_capturing_video) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_capturing_video,
      is_capturing_video);
}

// static
void PageLiveStateDecorator::OnIsCapturingAudioChanged(
    content::WebContents* contents,
    bool is_capturing_audio) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_capturing_audio,
      is_capturing_audio);
}

// static
void PageLiveStateDecorator::OnIsBeingMirroredChanged(
    content::WebContents* contents,
    bool is_being_mirrored) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_being_mirrored,
      is_being_mirrored);
}

// static
void PageLiveStateDecorator::OnIsCapturingWindowChanged(
    content::WebContents* contents,
    bool is_capturing_window) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_capturing_window,
      is_capturing_window);
}

// static
void PageLiveStateDecorator::OnIsCapturingDisplayChanged(
    content::WebContents* contents,
    bool is_capturing_display) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_capturing_display,
      is_capturing_display);
}

// static
void PageLiveStateDecorator::SetIsAutoDiscardable(
    content::WebContents* contents,
    bool is_auto_discardable) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_auto_discardable,
      is_auto_discardable);
}

// static
void PageLiveStateDecorator::SetWasDiscarded(content::WebContents* contents,
                                             bool was_discarded) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_was_discarded, was_discarded);
}

// static
void PageLiveStateDecorator::SetIsActiveTab(content::WebContents* contents,
                                            bool is_active_tab) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_is_active_tab, is_active_tab);
}

// static
void PageLiveStateDecorator::SetContentSettings(
    content::WebContents* contents,
    std::map<ContentSettingsType, ContentSetting> settings) {
  SetPropertyForWebContentsPageNode(
      contents, &PageLiveStateDataImpl::set_content_settings, settings);
}

void PageLiveStateDecorator::OnPassedToGraph(Graph* graph) {
  graph->GetNodeDataDescriberRegistry()->RegisterDescriber(this,
                                                           kDescriberName);
  graph->AddPageNodeObserver(this);
}

void PageLiveStateDecorator::OnTakenFromGraph(Graph* graph) {
  graph->RemovePageNodeObserver(this);
  graph->GetNodeDataDescriberRegistry()->UnregisterDescriber(this);
}

base::Value PageLiveStateDecorator::DescribePageNodeData(
    const PageNode* node) const {
  auto* data = Data::FromPageNode(node);
  if (!data)
    return base::Value();

  base::Value ret(base::Value::Type::DICTIONARY);
  ret.SetBoolKey("IsConnectedToUSBDevice", data->IsConnectedToUSBDevice());
  ret.SetBoolKey("IsConnectedToBluetoothDevice",
                 data->IsConnectedToBluetoothDevice());
  ret.SetBoolKey("IsCapturingVideo", data->IsCapturingVideo());
  ret.SetBoolKey("IsCapturingAudio", data->IsCapturingAudio());
  ret.SetBoolKey("IsBeingMirrored", data->IsBeingMirrored());
  ret.SetBoolKey("IsCapturingWindow", data->IsCapturingWindow());
  ret.SetBoolKey("IsCapturingDisplay", data->IsCapturingDisplay());
  ret.SetBoolKey("IsAutoDiscardable", data->IsAutoDiscardable());
  ret.SetBoolKey("WasDiscarded", data->WasDiscarded());
  ret.SetBoolKey("IsActiveTab", data->IsActiveTab());

  return ret;
}

void PageLiveStateDecorator::OnMainFrameUrlChanged(const PageNode* page_node) {
  // Don't get the content settings on android on each navigation because it may
  // induce scroll jank. There are many same-document navigations while
  // scrolling and getting the settings can invoke expensive platform APIs on
  // Android. Moreover, this information is only used to decide if a tab should
  // be discarded, which doesn't happen through Chrome code on that platform.
#if !BUILDFLAG(IS_ANDROID)
  // Get the content settings from the main thread.
  // This call is not using `Then` and is instead passing a callback for the
  // delegate to invoke with `CallOnGraph` on purpose. This is because it's
  // possible for the first async call to be placed in the UI thread's task
  // queue, and skipped as part of browser shutdown before being run. When that
  // happens, the post task's reply has to be destroyed on its owner sequence,
  // so a task is posted back to the Performance Manager sequence. At that point
  // shutdown is complete, and the PM sequence is `BLOCK_SHUTDOWN` so a DCHECK
  // is triggered. See crbug.com/1375270.
  delegate_.AsyncCall(&Delegate::GetContentSettingsAndReply)
      .WithArgs(page_node->GetContentsProxy(), page_node->GetMainFrameUrl(),
                base::BindOnce(
                    &PageLiveStateDecorator::OnContentSettingsReceived,
                    weak_factory_.GetWeakPtr(), page_node->GetMainFrameUrl()));
#endif
}

void PageLiveStateDecorator::OnContentSettingsReceived(
    const GURL& url,
    base::WeakPtr<const PageNode> page_node,
    const std::map<ContentSettingsType, ContentSetting>& settings) {
  // If the page node doesn't exist anymore, or it has navigated to a different
  // URL, there's nothing to do.
  if (!page_node || page_node->GetMainFrameUrl() != url) {
    return;
  }

  PageLiveStateDataImpl::GetOrCreate(PageNodeImpl::FromNode(page_node.get()))
      ->set_content_settings(settings);
}

PageLiveStateDecorator::Data::Data() = default;
PageLiveStateDecorator::Data::~Data() = default;

void PageLiveStateDecorator::Data::AddObserver(
    PageLiveStateObserver* observer) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  observers_.AddObserver(observer);
}

void PageLiveStateDecorator::Data::RemoveObserver(
    PageLiveStateObserver* observer) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  observers_.RemoveObserver(observer);
}

const PageLiveStateDecorator::Data* PageLiveStateDecorator::Data::FromPageNode(
    const PageNode* page_node) {
  return PageLiveStateDataImpl::Get(PageNodeImpl::FromNode(page_node));
}

PageLiveStateDecorator::Data*
PageLiveStateDecorator::Data::GetOrCreateForPageNode(
    const PageNode* page_node) {
  return PageLiveStateDataImpl::GetOrCreate(PageNodeImpl::FromNode(page_node));
}

PageLiveStateObserver::PageLiveStateObserver() = default;
PageLiveStateObserver::~PageLiveStateObserver() = default;

}  // namespace performance_manager


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TheBraverest.Models
{
    /// <summary>
    /// Standard information for a summoner spell
    /// </summary>
    public class SelectedSummonerSpell : SelectedValue
    {
        /// <summary>
        /// The key for the summoner spell
        /// </summary>
        public string Key { get; set; }
    }
}


text:
    <umb-panel>
        <umb-header>

{{selectedCatalog.name}}: Shipping Providers & Methods

                         1">Select Catalog

            <merchello-tabs tabs="tabs"></merchello-tabs>
        </umb-header>
        <merchello-panel class="row-fluid">

                        Shipping Countries
                        A list of the catalog's shipping providers and methods, sorted by country.

                         Add Country

                        <ship-country-gateway-providers country="country" reload="loadCountries()" delete="deleteCountryDialog(country)"></ship-country-gateway-providers>

                        Warehouse

                    <merchello-address address="primaryWarehouseAddress" data-ng-show="!primaryWarehouseAddress.isEmpty()"></merchello-address>

                        Current Catalog

{{selectedCatalog.name}}

{{selectedCatalog.description}}

                     Add Catalog

        </merchello-panel>
    </umb-panel>


text:
<?xml version="1.0" encoding="UTF-8"?><document>
<properties>
<author email="tom@infoether.com">Tom Copeland</author>
<title>Ruleset: Strict Exceptions</title>
</properties>

These rules provide some strict guidelines about throwing and catching exceptions.

   <subsection name="AvoidCatchingThrowable">

Since: PMD 1.2

Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as
OutOfMemoryError that should be exposed and managed separately.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.strictexception.AvoidCatchingThrowableRule

Example(s):
	        	<source>

public void bar() {
	try {
     // do something
    } catch (Throwable th) {  // should not catch Throwable
		th.printStackTrace();
    }
  }

      </source>

This rule has the following properties:

Name
Default Value
Description

violationSuppressRegex

Suppress violations with messages matching a regular expression

violationSuppressXPath

Suppress violations on nodes which match a given relative XPath expression.

</subsection>

   <subsection name="SignatureDeclareThrowsException">

Since: PMD 1.2

Methods that declare the generic Exception as a possible throwable are not very helpful since their
failure modes are unclear. Use a class derived from RuntimeException or a more specific checked exception.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.strictexception.SignatureDeclareThrowsExceptionRule

Example(s):
	        	<source>

public void foo() throws Exception {
}

      </source>

This rule has the following properties:

Name
Default Value
Description

violationSuppressRegex

Suppress violations with messages matching a regular expression

violationSuppressXPath

Suppress violations on nodes which match a given relative XPath expression.

</subsection>

    <subsection name="ExceptionAsFlowControl">

Since: PMD 1.8

Using Exceptions as form of flow control is not recommended as they obscure true exceptions when debugging.
Either add the necessary validation or use an alternate control structure.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.strictexception.ExceptionAsFlowControlRule

Example(s):
	        	<source>

public void bar() {
    try {
      try {
      } catch (Exception e) {
        throw new WrapperException(e);
       // this is essentially a GOTO to the WrapperException catch block
       }
     } catch (WrapperException e) {
     // do some more stuff
    }
  }

      </source>

This rule has the following properties:

Name
Default Value
Description

violationSuppressRegex

Suppress violations with messages matching a regular expression

violationSuppressXPath

Suppress violations on nodes which match a given relative XPath expression.

</subsection>

<subsection name="AvoidCatchingNPE">

Since: PMD 1.8

Code should never throw NullPointerExceptions under normal circumstances.  A catch block may hide the
original error, causing other, more subtle problems later on.

<source>

//CatchStatement/FormalParameter/Type
 /ReferenceType/ClassOrInterfaceType[@Image='NullPointerException']

        </source>Example(s):
	        	<source>
public class Foo {
  void bar() {
    try {
      // do something
      }  catch (NullPointerException npe) {
    }
  }
}

    </source>
</subsection>

  <subsection name="AvoidThrowingRawExceptionTypes">

Since: PMD 1.8

Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable,
Exception, or Error, use a subclassed exception or error instead.

<source>

//AllocationExpression
 /ClassOrInterfaceType[
 (@Image='Throwable' and count(//ImportDeclaration/Name[ends-with(@Image,'Throwable')]) = 0)
or
 (@Image='Exception' and count(//ImportDeclaration/Name[ends-with(@Image,'Exception')]) = 0)
or
 (@Image='Error'  and count(//ImportDeclaration/Name[ends-with(@Image,'Error')]) = 0)
or
( @Image='RuntimeException'  and count(//ImportDeclaration/Name[ends-with(@Image,'RuntimeException')]) = 0)
]

        </source>Example(s):
	        	<source>

public class Foo {
  public void bar() throws Exception {
    throw new Exception();
   }
}

    </source>
</subsection>

    <subsection name="AvoidThrowingNullPointerException">

Since: PMD 1.8

Avoid throwing NullPointerExceptions. These are confusing because most people will assume that the
virtual machine threw it. Consider using an IllegalArgumentException instead; this will be
clearly seen as a programmer-initiated exception.

<source>

//AllocationExpression/ClassOrInterfaceType[@Image='NullPointerException']

          </source>Example(s):
	        	<source>

public class Foo {
  void bar() {
    throw new NullPointerException();
  }
}

      </source>
</subsection>

  <subsection name="AvoidRethrowingException">

Since: PMD 3.8

Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.

<source>

//CatchStatement[FormalParameter
 /VariableDeclaratorId/@Image = Block/BlockStatement/Statement
 /ThrowStatement/Expression/PrimaryExpression[count(PrimarySuffix)=0]/PrimaryPrefix/Name/@Image
 and count(Block/BlockStatement/Statement) =1]

            </source>Example(s):
	        	<source>
public void bar() {
    try {
    // do something
    }  catch (SomeException se) {
       throw se;
    }
}

    </source>
</subsection>

  <subsection name="DoNotExtendJavaLangError">

Since: PMD 4.0

Errors are system exceptions. Do not extend them.

<source>

//ClassOrInterfaceDeclaration/ExtendsList/ClassOrInterfaceType
  [@Image="Error" or @Image="java.lang.Error"]

        </source>Example(s):
	        	<source>
public class Foo extends Error { }
    </source>
</subsection>

	<subsection name="DoNotThrowExceptionInFinally">

Since: PMD 4.2

Throwing exceptions within a 'finally' block is confusing since they may mask other exceptions
or code defects.
Note: This is a PMD implementation of the Lint4j rule "A throw in a finally block"

<source>

//FinallyStatement[descendant::ThrowStatement]

			  </source>Example(s):
	        	<source>

public class Foo {
	public void bar() {
		try {
			// Here do some stuff
		} catch( Exception e) {
			// Handling the issue
		} finally {
			// is this really a good idea ?
			throw new Exception();
		}
	}
}

    	</source>
</subsection>

  <subsection name="AvoidThrowingNewInstanceOfSameException">

Since: PMD 4.2.5

Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to
code size and runtime complexity.

<source>

//CatchStatement[
  count(Block/BlockStatement/Statement) = 1
  and
  FormalParameter/Type/ReferenceType/ClassOrInterfaceType/@Image = Block/BlockStatement/Statement/ThrowStatement/Expression/PrimaryExpression/PrimaryPrefix/AllocationExpression/ClassOrInterfaceType/@Image
  and
  count(Block/BlockStatement/Statement/ThrowStatement/Expression/PrimaryExpression/PrimaryPrefix/AllocationExpression/Arguments/ArgumentList/Expression) = 1
  and
  FormalParameter/VariableDeclaratorId = Block/BlockStatement/Statement/ThrowStatement/Expression/PrimaryExpression/PrimaryPrefix/AllocationExpression/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name
  ]

      </source>Example(s):
	        	<source>
public void bar() {
      try {
       // do something
      }  catch (SomeException se) {
         // harmless comment
           throw new SomeException(se);
      }
}

    </source>
</subsection>

  <subsection name="AvoidCatchingGenericException">

Since: PMD 4.2.6

Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block

<source>

        //CatchStatement/FormalParameter/Type/ReferenceType/ClassOrInterfaceType[
          @Image='NullPointerException' or
          @Image='Exception' or
          @Image='RuntimeException']

      </source>Example(s):
	        	<source>

package com.igate.primitive;

public class PrimitiveType {

  public void downCastPrimitiveType() {
    try {
      System.out.println(" i [" + i + "]");
    } catch(Exception e) {
      e.printStackTrace();
    } catch(RuntimeException e) {
      e.printStackTrace();
    } catch(NullPointerException e) {
      e.printStackTrace();
    }
  }
}

    </source>
</subsection>

	<subsection name="AvoidLosingExceptionInformation">

Since: PMD 4.2.6

Statements in a catch block that invoke accessors on the exception without using the information
only add to code size.  Either remove the invocation, or use the return result.

<source>

//CatchStatement/Block/BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name
[
   @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Image, '.getMessage')
   or
   @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Image, '.getLocalizedMessage')
   or
   @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Image, '.getCause')
   or
   @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Image, '.getStackTrace')
   or
   @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Image, '.toString')
]

				</source>Example(s):
	        	<source>

public void bar() {
	try {
		// do something
	} catch (SomeException se) {
		se.getMessage();
	}
}

		</source>
</subsection>

</document>


text:
@interface AGMappingPairNumberTests : AGMappingTestcase

@end

@implementation AGMappingPairNumberTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testThatItMapsNumber {
    AGMock *obj = [self createTestObj];
    NSDictionary *dict = @{
                           @"someField": @{
                                   @"number": @(123)
                                   }
                           };
    AGMappingPairNumber *mpNumber = [AGMappingPairNumber mappingPairWithKeyPathFrom:@"someField.number"
                                                                              keyTo:@"number"];
    [mpNumber mapValueFromJSONObject:dict toObject:obj];
    XCTAssertEqual(obj.number, @(123));
}

- (void)testThatItMapsUndefinedToNil {
    AGMock *obj = [self createTestObj];
    NSDictionary *dict = @{
                           @"someField": @{}
                          };
    AGMappingPairNumber *mpNumber = [AGMappingPairNumber mappingPairWithKeyPathFrom:@"someField.number"
                                                                              keyTo:@"number"];
    [mpNumber mapValueFromJSONObject:dict toObject:obj];
    XCTAssertNil(obj.number);
}

- (void) testThatItMapsNullToNil {
    id smth =[AGMappingPairNumber objectWithJSONValue:[NSNull null]];
    XCTAssertNil(smth);
}

- (void)testThatItMapsStringToNumber {
    AGMock *obj = [self createTestObj];
    NSDictionary *dict = @{
                           @"someField": @{
                                            @"number": @"123"
                                        }
                           };
    AGMappingPairNumber *mpNumber = [AGMappingPairNumber mappingPairWithKeyPathFrom:@"someField.number"
                                                                              keyTo:@"number"];
    [mpNumber mapValueFromJSONObject:dict toObject:obj];
    XCTAssertEqual(obj.number, [NSNumber numberWithLong:123]);
}

- (void)testThatItMapsFloatingPointStringToNumber {
    AGMock *obj = [self createTestObj];
    NSDictionary *dict = @{
                           @"someField": @{
                                   @"number": @"123.43"
                                   }
                           };
    AGMappingPairNumber *mpNumber = [AGMappingPairNumber mappingPairWithKeyPathFrom:@"someField.number"
                                                                              keyTo:@"number"];
    [mpNumber mapValueFromJSONObject:dict toObject:obj];
    XCTAssertTrue([obj.number isEqualToNumber:@(123.43)]);
}

-(void) testThatItMapsNotNumericalStringToZero {
    AGMock *obj = [self createTestObj];
    NSDictionary *dict = @{
                           @"someField": @{
                                   @"number": @"blah"
                                   }
                           };
    AGMappingPairNumber *mpNumber = [AGMappingPairNumber mappingPairWithKeyPathFrom:@"someField.number"
                                                                              keyTo:@"number"];
    [mpNumber mapValueFromJSONObject:dict toObject:obj];
    XCTAssertTrue([obj.number isEqualToNumber:@(0)]);
}

@end


text:
extern "C" {
#endif

#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>

typedef void (*ftimer_cb)(void*);
typedef struct _f_timer {
    timer_t timerid;
    struct  sigevent sev;
    struct  itimerspec its;

    ftimer_cb cb;
    void*   arg;
} ftimer;

int    ftimer_create(ftimer*, long long nsecs, long long alter,
                    ftimer_cb pfunc, void* arg);
int    ftimer_start(ftimer*);
int    ftimer_del(ftimer*);

#ifdef __linux__
# ifndef HAVE_TIMERFD_H
# define HAVE_TIMERFD_H 1

# include <sys/timerfd.h>

int    ftimerfd_create();
int    ftimerfd_start(int fd, long long nsecs, long long alter);
int    ftimerfd_stop(int fd);
# endif
#endif

// return a time value its format is:
// current time * 1000000 + current usec
unsigned long long ftime_gettime();

#ifdef __cplusplus
}
#endif

#endif


text:
{% extends "studies/study.html" %}
{% block studycontent %}

ODB{{ investigation_id }}-S{{ study_description.id }}: Study Samples
        {% if study_protocols|length != 0 %}
            <button class="btn btn-sm btn-danger pull-right" data-toggle="modal" data-target="#new_samples_file">
                 Create Samples Metadata File
            </button>{% endif %}

    {% if study_protocols|length == 0  %}

No Protocols Found?

Before you can add any Study Samples, you are requried to first submit some study protocols.

    {% elif study_samples_table|length > 1 %}

Study Samples

                {% for x in study_samples_table[0] %}
                    {{ x }}
                {% endfor %}

            {% for x in study_samples_table[1:] %}

                    {% for y in x %}
                        {{ y }}
                    {% endfor %}

            {% endfor %}

    {% else %}
        <button class="btn btn-sm btn-danger pull-right" data-toggle="modal" data-target="#upload_samples_file"> Upload</button>

No Study Samples data found?

    {% endif %}
        {% include "studies/modals/samples/new_samples.html" %}
        {% include "studies/modals/samples/upload_samples.html" %}

{% endblock %}


text:
/**
 *
 */
package top.phrack.ctf.models.services.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import top.phrack.ctf.models.dao.CountriesMapper;
import top.phrack.ctf.models.services.CountryServices;
import top.phrack.ctf.pojo.Countries;

/**
 * 国家接口的实现
 *
 * @author Jarvis
 * @date 2016年4月8日
 */
@Service("CountryServices")
public class CountryServicesImpl implements CountryServices {

	@Resource
	private CountriesMapper countriesMapper;
	/* (non-Javadoc)
	 * @see top.phrack.ctf.models.services.CountryServices#SelectAllCountry()
	 */
	public List<Countries> SelectAllCountry() {
		return countriesMapper.SelectAll();
	}
	/* (non-Javadoc)
	 * @see top.phrack.ctf.models.services.CountryServices#getCountryById(java.lang.Long)
	 */
	public Countries getCountryById(Long id) {

		return countriesMapper.selectByPrimaryKey(id);
	}
	/* (non-Javadoc)
	 * @see top.phrack.ctf.models.services.CountryServices#getCountryByCode(java.lang.String)
	 */
	@Override
	public Countries getCountryByCode(String code) {

		return countriesMapper.selectCountryByCode(code);
	}

}


text:
export = IdoDB;
declare function IdoDB(): void;
declare class IdoDB {
    tableExists(tableName: string): void;
    getTablesNames(): any[];
    dropTable(tableName: string): void;
    getTable(tableName: string): any;
    getDBStatistics(): string;
    uniqueId: any;
    name: any;
}


text:
Mask operations on matrices {#tutorial_mat_mask_operations}
===========================

@tableofcontents

@prev_tutorial{tutorial_how_to_scan_images}
@next_tutorial{tutorial_mat_operations}

|    |    |
| -: | :- |
| Original author | Bernát Gábor |
| Compatibility | OpenCV >= 3.0 |

Mask operations on matrices are quite simple. The idea is that we recalculate each pixel's value in
an image according to a mask matrix (also known as kernel). This mask holds values that will adjust
how much influence neighboring pixels (and the current pixel) have on the new pixel value. From a
mathematical point of view we make a weighted average, with our specified values.

Our test case
-------------

Let's consider the issue of an image contrast enhancement method. Basically we want to apply for
every pixel of the image the following formula:

\f[I(i,j) = 5*I(i,j) - [ I(i-1,j) + I(i+1,j) + I(i,j-1) + I(i,j+1)]\f]\f[\iff I(i,j)*M, \text{where }
M = \bordermatrix{ _i\backslash ^j  & -1 &  0 & +1 \cr
                     -1 &  0 & -1 &  0 \cr
                      0 & -1 &  5 & -1 \cr
                     +1 &  0 & -1 &  0 \cr
                 }\f]

The first notation is by using a formula, while the second is a compacted version of the first by
using a mask. You use the mask by putting the center of the mask matrix (in the upper case noted by
the zero-zero index) on the pixel you want to calculate and sum up the pixel values multiplied with
the overlapped matrix values. It's the same thing, however in case of large matrices the latter
notation is a lot easier to look over.

Code
----

@add_toggle_cpp
You can download this source code from [here
](https://raw.githubusercontent.com/opencv/opencv/4.x/samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp) or look in the
OpenCV source code libraries sample directory at
`samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp`.
@include samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp
@end_toggle

@add_toggle_java
You can download this source code from [here
](https://raw.githubusercontent.com/opencv/opencv/4.x/samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java) or look in the
OpenCV source code libraries sample directory at
`samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java`.
@include samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java
@end_toggle

@add_toggle_python
You can download this source code from [here
](https://raw.githubusercontent.com/opencv/opencv/4.x/samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py) or look in the
OpenCV source code libraries sample directory at
`samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py`.
@include samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py
@end_toggle

The Basic Method
----------------

Now let us see how we can make this happen by using the basic pixel access method or by using the
**filter2D()** function.

Here's a function that will do this:
@add_toggle_cpp
@snippet samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp basic_method

At first we make sure that the input images data is in unsigned char format. For this we use the
@ref cv::CV_Assert function that throws an error when the expression inside it is false.
@snippet samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp 8_bit
@end_toggle

@add_toggle_java
@snippet samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java basic_method

At first we make sure that the input images data in unsigned 8 bit format.
@snippet samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java 8_bit
@end_toggle

@add_toggle_python
@snippet samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py basic_method

At first we make sure that the input images data in unsigned 8 bit format.
@code{.py}
my_image = cv.cvtColor(my_image, cv.CV_8U)
@endcode

@end_toggle

We create an output image with the same size and the same type as our input. As you can see in the
@ref tutorial_how_to_scan_images_storing "storing" section, depending on the number of channels we may have one or more
subcolumns.

@add_toggle_cpp
We will iterate through them via pointers so the total number of elements depends on
this number.
@snippet samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp create_channels
@end_toggle

@add_toggle_java
@snippet samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java create_channels
@end_toggle

@add_toggle_python
@code{.py}
height, width, n_channels = my_image.shape
result = np.zeros(my_image.shape, my_image.dtype)
@endcode
@end_toggle

@add_toggle_cpp
We'll use the plain C [] operator to access pixels. Because we need to access multiple rows at the
same time we'll acquire the pointers for each of them (a previous, a current and a next line). We
need another pointer to where we're going to save the calculation. Then simply access the right
items with the [] operator. For moving the output pointer ahead we simply increase this (with one
byte) after each operation:
@snippet samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp basic_method_loop

On the borders of the image the upper notation results inexistent pixel locations (like minus one -
minus one). In these points our formula is undefined. A simple solution is to not apply the kernel
in these points and, for example, set the pixels on the borders to zeros:

@snippet samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp borders
@end_toggle

@add_toggle_java
We need to access multiple rows and columns which can be done by adding or subtracting 1 to the current center (i,j).
Then we apply the sum and put the new value in the Result matrix.
@snippet samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java basic_method_loop

On the borders of the image the upper notation results in inexistent pixel locations (like (-1,-1)).
In these points our formula is undefined. A simple solution is to not apply the kernel
in these points and, for example, set the pixels on the borders to zeros:

@snippet samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java borders
@end_toggle

@add_toggle_python
We need to access multiple rows and columns which can be done by adding or subtracting 1 to the current center (i,j).
Then we apply the sum and put the new value in the Result matrix.
@snippet samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py basic_method_loop
@end_toggle

The filter2D function
---------------------

Applying such filters are so common in image processing that in OpenCV there is a function that
will take care of applying the mask (also called a kernel in some places). For this you first need
to define an object that holds the mask:

@add_toggle_cpp
@snippet samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp kern
@end_toggle

@add_toggle_java
@snippet samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java kern
@end_toggle

@add_toggle_python
@snippet samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py kern
@end_toggle

Then call the **filter2D()** function specifying the input, the output image and the kernel to
use:

@add_toggle_cpp
@snippet samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp filter2D
@end_toggle

@add_toggle_java
@snippet samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java filter2D
@end_toggle

@add_toggle_python
@snippet samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py filter2D
@end_toggle

The function even has a fifth optional argument to specify the center of the kernel, a sixth
for adding an optional value to the filtered pixels before storing them in K and a seventh one
for determining what to do in the regions where the operation is undefined (borders).

This function is shorter, less verbose and, because there are some optimizations, it is usually faster
than the *hand-coded method*. For example in my test while the second one took only 13
milliseconds the first took around 31 milliseconds. Quite some difference.

For example:

![](images/resultMatMaskFilter2D.png)

@add_toggle_cpp
Check out an instance of running the program on our [YouTube
channel](http://www.youtube.com/watch?v=7PF1tAU9se4) .
@youtube{7PF1tAU9se4}
@end_toggle


text:
<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<izpack:installation version="5.0"
                     xmlns:izpack="http://izpack.org/schema/installation"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://izpack.org/schema/installation http://izpack.org/schema/5.0/izpack-installation-5.0.xsd">
    <info>
        <appname>Test Installation</appname>
        <appversion>1.4 beta 666</appversion>
    </info>

    <guiprefs width="640" height="480" resizable="yes"/>
    <locale>
        <langpack iso3="eng"/>
    </locale>

    <panels>
        <panel classname="HelloPanel" id="HelloPanel1">
            <validator classname="com.izforge.izpack.integration.datavalidator.TestDataValidator"/>
            <actions>
                <action stage="preconstruct" classname="com.izforge.izpack.integration.panelaction.PreConstructPanelAction"/>
                <action stage="preactivate" classname="com.izforge.izpack.integration.panelaction.PreActivatePanelAction"/>
                <action stage="prevalidate" classname="com.izforge.izpack.integration.panelaction.PreValidatePanelAction">
                    <param name="prop1" value="value1"/>
                </action>
                <action stage="postvalidate" classname="com.izforge.izpack.integration.panelaction.PostValidatePanelAction">
                    <param name="prop2" value="value2"/>
                    <param name="prop3" value="value3"/>
                </action>
            </actions>
        </panel>

        <panel classname="HelloPanel" id="HelloPanel2">
            <validator classname="com.izforge.izpack.integration.datavalidator.TestDataValidator"/>
            <actions>
                <action stage="preconstruct" classname="com.izforge.izpack.integration.panelaction.TestPanelAction"/>
                <action stage="preactivate" classname="com.izforge.izpack.integration.panelaction.TestPanelAction"/>
                <action stage="prevalidate" classname="com.izforge.izpack.integration.panelaction.TestPanelAction">
                    <param name="prop1" value="value1"/>
                </action>
                <action stage="postvalidate" classname="com.izforge.izpack.integration.panelaction.TestPanelAction">
                    <param name="prop2" value="value2"/>
                    <param name="prop3" value="value3"/>
                </action>
            </actions>
        </panel>

        <panel classname="SimpleFinishPanel" id="SimpleFinishPanel">
            <!-- NOTE: the validator and prevalidate and postvalidate actions associated with last panel are ignored -->
            <validator classname="com.izforge.izpack.integration.datavalidator.TestDataValidator"/>
            <actions>
                <action stage="preconstruct"
                        classname="com.izforge.izpack.integration.panelaction.PreConstructPanelAction"/>
                <action stage="preactivate"
                        classname="com.izforge.izpack.integration.panelaction.PreActivatePanelAction"/>
                <action stage="prevalidate"
                        classname="com.izforge.izpack.integration.panelaction.PreValidatePanelAction"/>
                <action stage="postvalidate"
                        classname="com.izforge.izpack.integration.panelaction.PostValidatePanelAction"/>
            </actions>
        </panel>
    </panels>

    <packs>
        <pack name="Base" required="yes">
            <description>The base files</description>
        </pack>
    </packs>
</izpack:installation>


text:
package org.neo4j.kernel.impl.api;

import org.neo4j.kernel.KernelHealth;
import org.neo4j.kernel.api.KernelAPI;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.TransactionHook;
import org.neo4j.kernel.api.exceptions.TransactionFailureException;
import org.neo4j.kernel.impl.transaction.TransactionMonitor;
import org.neo4j.kernel.lifecycle.LifecycleAdapter;

/**
 * This is the Neo4j Kernel, an implementation of the Kernel API which is an internal component used by Cypher and the
 * Core API (the API under org.neo4j.graphdb).
 *
 *
Structure

 *
 * The Kernel lets you start transactions. The transactions allow you to create "statements", which, in turn, operate
 * against the database. Statements and transactions are separate concepts due to isolation requirements. A single
 * cypher query will normally use one statement, and there can be multiple statements executed in one transaction.
 *
 * Please refer to the {@link KernelTransaction} javadoc for details.
 *
 * The architecture of the kernel is based around a layered design, where one layer performs some task, and potentially
 * delegates down to a lower layer. For instance, writing to the database will pass through
 * {@link LockingStatementOperations}, which will grab locks and delegate to {@link StateHandlingStatementOperations}
 * which will store the change in the transaction state, to be applied later if the transaction is committed.
 *
 * A read will, similarly, pass through {@link LockingStatementOperations}. It then reaches
 * {@link StateHandlingStatementOperations}, which includes any changes that exist in the current transaction, and then
 * finally {@link org.neo4j.kernel.impl.api.store.StoreReadLayer} will read the current committed state from
 * the stores or caches.
 *
 *
Refactoring

 *
 * There are several sources of pain around the current state, which we hope to refactor away down the line.
 *
 * One pain is transaction state, which is maintained in the {@link org.neo4j.kernel.impl.api.state.TxState} class.
 * This class is huge and complicated, as it has been used as a gathering point for consolidating all transaction state
 * management in one place. This is now done, and the TxState class should now be refactored to be easier to understand.
 *
 * Please expand and update this as you learn things or find errors in the text above.
 */
public class Kernel extends LifecycleAdapter implements KernelAPI
{
    private final KernelTransactions transactions;
    private final TransactionHooks hooks;
    private final KernelHealth health;
    private final TransactionMonitor transactionMonitor;

    public Kernel( KernelTransactions transactionFactory,
                   TransactionHooks hooks, KernelHealth health, TransactionMonitor transactionMonitor )
    {
        this.transactions = transactionFactory;
        this.hooks = hooks;
        this.health = health;
        this.transactionMonitor = transactionMonitor;
    }

    @Override
    public KernelTransaction newTransaction() throws TransactionFailureException
    {
        health.assertHealthy( TransactionFailureException.class );
        KernelTransaction transaction = transactions.newInstance();
        transactionMonitor.transactionStarted();
        return transaction;
    }

    @Override
    public void registerTransactionHook( TransactionHook hook )
    {
        hooks.register( hook );
    }

    @Override
    public void unregisterTransactionHook( TransactionHook hook )
    {
        hooks.unregister( hook );
    }

    @Override
    public void stop() throws Throwable
    {
        transactions.disposeAll();
    }
}


text:
package git4idea.tests;

import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vfs.VirtualFile;

public class GitChangeProviderConflictTest extends GitChangeProviderTest {

  /**
   * "modify-modify" merge conflict.
   * 1. Create a file and commit it.
   * 2. Create new branch and switch to it.
   * 3. Edit the file in that branch and commit.
   * 4. Switch to master, conflictly edit the file and commit.
   * 5. Merge the branch on master.
   * Merge conflict "modify-modify" happens.
   */
  public void testConflictMM() throws Exception {
    modifyFileInBranches("a.txt", FileAction.MODIFY, FileAction.MODIFY);
    assertChanges(atxt, FileStatus.MERGED_WITH_CONFLICTS);
  }

  /**
   * Modify-Delete conflict.
   */
  public void testConflictMD() throws Exception {
    modifyFileInBranches("a.txt", FileAction.MODIFY, FileAction.DELETE);
    assertChanges(atxt, FileStatus.MERGED_WITH_CONFLICTS);
  }

  /**
   * Delete-Modify conflict.
   */
  public void testConflictDM() throws Exception {
    modifyFileInBranches("a.txt", FileAction.DELETE, FileAction.MODIFY);
    assertChanges(atxt, FileStatus.MERGED_WITH_CONFLICTS);
  }

  /**
   * Create a file with conflicting content.
   */
  public void testConflictCC() throws Exception {
    modifyFileInBranches("z.txt", FileAction.CREATE, FileAction.CREATE);
    VirtualFile zfile = projectRoot.findChild("z.txt");
    assertChanges(zfile, FileStatus.MERGED_WITH_CONFLICTS);
  }

  public void testConflictRD() throws Exception {
    modifyFileInBranches("a.txt", FileAction.RENAME, FileAction.DELETE);
    VirtualFile newfile = projectRoot.findChild("a.txt_master_new"); // renamed in master
    assertChanges(newfile, FileStatus.MERGED_WITH_CONFLICTS);
  }

  public void testConflictDR() throws Exception {
    modifyFileInBranches("a.txt", FileAction.DELETE, FileAction.RENAME);
    VirtualFile newFile = projectRoot.findChild("a.txt_feature_new"); // deleted in master, renamed in feature
    assertChanges(newFile, FileStatus.MERGED_WITH_CONFLICTS);
  }

}


text:
- This is a fake1 major release note.
##### __FakePack1_Integration2__
- This is a fake2 major release note.


text:
use std::cell::RefCell;
use std::io;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::rc::Rc;
use std::time::Duration;

use futures::{Future, Stream};
use futures::future;
use futures::future::{loop_fn, Either, Loop};

use hyper;
use hyper::{Method, StatusCode};
use hyper::header::{ContentLength, ContentType};
use hyper::server::{Http, Request, Response, Service};
use hyper::mime::APPLICATION_JSON;

use serde::Serialize;
use serde::de::DeserializeOwned;

use serde_json;

use sha2::Sha256;

use tokio_core::reactor;
use tokio_core::reactor::Core;
use tokio_core::net::{TcpListener, UdpSocket};

use common::{create_timeout, OS_RNG};

use couplings::{Couplings, EndpointAddrs};

use key::{AutoUpdatingKey, Key, KeyDigest};

use relay_protocol::{listen_key_to_connect_key, AddrCertificateRequest, AddrCertificateResponse,
                     ConnectRequest, ConnectResponse, CreateKeysRequest, CreateKeysResponse,
                     GetUdpAddrsRequest, GetUdpAddrsResponse, ListenRequest, ListenResponse};

fn handle_json_request<A, B, H, F>(
    request: Request,
    handler: H,
) -> Box<Future<Item = Response, Error = hyper::Error>>
where
    A: DeserializeOwned,
    B: Serialize + 'static,
    H: FnOnce(A) -> F + 'static,
    F: Future<Item = B, Error = ()> + 'static,
{
    Box::new(request.body().concat2().and_then(move |body| {
        match serde_json::from_slice(&body) {
            Ok(request) => future::Either::A(
                handler(request)
                    .map(move |response| {
                        let response_text = serde_json::to_string(&response).unwrap();
                        Response::new()
                            .with_header(ContentLength(response_text.len() as u64))
                            .with_body(response_text)
                    })
                    .or_else(move |_| {
                        future::ok(Response::new().with_status(StatusCode::BadRequest))
                    }),
            ),
            Err(_) => future::Either::B(future::ok(
                Response::new().with_status(StatusCode::BadRequest),
            )),
        }
    }))
}

pub struct RelayService {
    core_handle: reactor::Handle,
    addr_ca_key: Rc<RefCell<AutoUpdatingKey>>,
    udp_addr_v4: Option<(Ipv4Addr, u16)>,
    udp_addr_v6: Option<(Ipv6Addr, u16)>,
    server_key: Key,
    wait_timeout: Duration,
    couplings: Rc<RefCell<Couplings>>,
}

impl Service for RelayService {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;

    fn call(&self, request: Request) -> Self::Future {
        if request.method() != &Method::Post
            || request.headers().get() != Some(&ContentType(APPLICATION_JSON))
        {
            return Box::new(future::ok(
                Response::new().with_status(StatusCode::BadRequest),
            ));
        }

        match request.path() {
            "/get_udp_addrs" => {
                let response = GetUdpAddrsResponse {
                    addr_v4: self.udp_addr_v4,
                    addr_v6: self.udp_addr_v6,
                };
                handle_json_request(request, move |_: GetUdpAddrsRequest| future::ok(response))
            }
            "/create_keys" => {
                let response = OS_RNG.with(|rng| {
                    CreateKeysResponse::generate(&mut *rng.borrow_mut(), self.server_key)
                });
                handle_json_request(request, move |_: CreateKeysRequest| future::ok(response))
            }
            "/listen" => {
                let addr_ca_key = self.addr_ca_key.clone();
                let couplings = self.couplings.clone();
                let server_key = self.server_key;
                let wait_timeout = self.wait_timeout;
                let core_handle = self.core_handle.clone();
                handle_json_request(request, move |request: ListenRequest| {
                    if !request.is_valid(&mut addr_ca_key.borrow_mut()) {
                        return Either::A(future::err(()));
                    }
                    let connect_key = listen_key_to_connect_key(request.listen_key, server_key);
                    let addrs = EndpointAddrs {
                        addr_v4: request.addr_v4.map(|x| (x.ip, x.port)),
                        addr_v6: request.addr_v6.map(|x| (x.ip, x.port)),
                    };
                    let mut couplings = couplings.borrow_mut();
                    Either::B(
                        couplings
                            .listen(connect_key, addrs)
                            .select(
                                create_timeout(wait_timeout, &core_handle)
                                    .then(|_| future::ok(ListenResponse::default())),
                            )
                            .map(|(x, _)| x)
                            .map_err(|(x, _)| x),
                    )
                })
            }
            "/connect" => {
                let addr_ca_key = self.addr_ca_key.clone();
                let couplings = self.couplings.clone();
                let wait_timeout = self.wait_timeout;
                let core_handle = self.core_handle.clone();
                handle_json_request(request, move |request: ConnectRequest| {
                    if !request.is_valid(&mut addr_ca_key.borrow_mut()) {
                        return Either::A(future::err(()));
                    }
                    let addrs = EndpointAddrs {
                        addr_v4: request.addr_v4.map(|x| (x.ip, x.port)),
                        addr_v6: request.addr_v6.map(|x| (x.ip, x.port)),
                    };
                    let mut couplings = couplings.borrow_mut();
                    Either::B(
                        couplings
                            .connect(request.connect_key, addrs)
                            .select(
                                create_timeout(wait_timeout, &core_handle)
                                    .then(|_| future::ok(ConnectResponse::default())),
                            )
                            .map(|(x, _)| x)
                            .map_err(|(x, _)| x),
                    )
                })
            }
            _ => Box::new(future::ok(
                Response::new().with_status(StatusCode::NotFound),
            )),
        }
    }
}

fn addr_ca_loop(
    addr_ca_key: Rc<RefCell<AutoUpdatingKey>>,
    socket: UdpSocket,
) -> Box<Future<Item = (), Error = io::Error>> {
    Box::new(loop_fn((socket, vec![0; 512]), move |(socket, buf)| {
        let addr_ca_key = addr_ca_key.clone();
        socket
            .recv_dgram(buf)
            .and_then(
                move |(socket, buf, len, remote_addr)| match serde_json::from_slice::<
                    AddrCertificateRequest,
                >(&buf[0..len])
                {
                    Ok(request) => {
                        let response = serde_json::to_string(&AddrCertificateResponse::generate(
                            remote_addr.ip(),
                            remote_addr.port(),
                            request.client_key_hash,
                            &mut addr_ca_key.borrow_mut(),
                        )).unwrap();
                        Either::A(
                            socket
                                .send_dgram(response, remote_addr)
                                .map(|(socket, _)| (socket, buf)),
                        )
                    }
                    Err(_) => Either::B(future::ok((socket, buf))),
                },
            )
            .and_then(|x| future::ok(Loop::Continue(x)))
    }))
}

#[derive(Serialize, Deserialize)]
pub struct UdpConfigurationV4 {
    pub listen_addr: SocketAddrV4,
    pub public_addr: SocketAddrV4,
}

#[derive(Serialize, Deserialize)]
pub struct UdpConfigurationV6 {
    pub listen_addr: SocketAddrV6,
    pub public_addr: SocketAddrV6,
}

#[derive(Serialize, Deserialize)]
pub struct Configuration {
    pub http_listen_addr: SocketAddr,
    pub udp_v4: Option<UdpConfigurationV4>,
    pub udp_v6: Option<UdpConfigurationV6>,
    pub server_secret: String,
    pub wait_timeout_ms: u64,
    pub addr_ca_key_update_interval_ms: u64,
}

pub struct Server {
    conf: Configuration,
    core: Core,
    http_listener: TcpListener,
    udp_socket_v4: Option<UdpSocket>,
    udp_socket_v6: Option<UdpSocket>,
    http_local_addr: SocketAddr,
    udp_public_addr_v4: Option<(Ipv4Addr, u16)>,
    udp_public_addr_v6: Option<(Ipv6Addr, u16)>,
    addr_ca_key: Rc<RefCell<AutoUpdatingKey>>,
    couplings: Rc<RefCell<Couplings>>,
}

impl Server {
    pub fn new(conf: Configuration) -> Result<Server, String> {
        let core = Core::new().map_err(|x| format!("Could not create Tokio core: {}", x))?;
        let http_listener =
            TcpListener::bind(&conf.http_listen_addr, &core.handle()).map_err(|e| {
                format!(
                    "Could not create TCP listener bound to address '{}': {}",
                    conf.http_listen_addr,
                    e
                )
            })?;

        let http_local_addr = http_listener.local_addr().map_err(|e| {
            format!(
                "Could not determine local address of the HTTP listener: {}",
                e
            )
        })?;

        if conf.udp_v4.is_none() && conf.udp_v6.is_none() {
            return Err(format!("Both udp_v4 and udp_v6 missing from configuration"));
        }

        let (udp_socket_v4, udp_public_addr_v4) = match conf.udp_v4 {
            Some(UdpConfigurationV4 {
                listen_addr,
                public_addr,
            }) => {
                let socket = UdpSocket::bind(&SocketAddr::V4(listen_addr), &core.handle())
                    .map_err(|e| {
                        format!(
                            "Could not create UDP socket bound to address '{}': {}",
                            listen_addr,
                            e
                        )
                    })?;
                let public_port = match public_addr.port() {
                    0 => socket
                        .local_addr()
                        .map_err(|e| {
                            format!("Could not determine local address for UDP socket: {}", e)
                        })?
                        .port(),
                    port => port,
                };
                (Some(socket), Some((*public_addr.ip(), public_port)))
            }
            _ => (None, None),
        };

        let (udp_socket_v6, udp_public_addr_v6) = match conf.udp_v6 {
            Some(UdpConfigurationV6 {
                listen_addr,
                public_addr,
            }) => {
                let socket = UdpSocket::bind(&SocketAddr::V6(listen_addr), &core.handle())
                    .map_err(|e| {
                        format!(
                            "Could not create UDP socket bound to address '{}': {}",
                            listen_addr,
                            e
                        )
                    })?;
                let public_port = match public_addr.port() {
                    0 => socket
                        .local_addr()
                        .map_err(|e| {
                            format!("Could not determine local address for UDP socket: {}", e)
                        })?
                        .port(),
                    port => port,
                };
                (Some(socket), Some((*public_addr.ip(), public_port)))
            }
            _ => (None, None),
        };

        let addr_ca_key_update_interval =
            Duration::from_millis(conf.addr_ca_key_update_interval_ms);
        Ok(Server {
            conf: conf,
            core: core,
            http_listener: http_listener,
            udp_socket_v4: udp_socket_v4,
            udp_socket_v6: udp_socket_v6,
            http_local_addr: http_local_addr,
            udp_public_addr_v4: udp_public_addr_v4,
            udp_public_addr_v6: udp_public_addr_v6,
            addr_ca_key: Rc::new(RefCell::new(
                AutoUpdatingKey::new(addr_ca_key_update_interval),
            )),
            couplings: Couplings::new_rc(),
        })
    }

    pub fn http_local_addr(&self) -> SocketAddr {
        self.http_local_addr
    }

    pub fn couplings(&self) -> Rc<RefCell<Couplings>> {
        self.couplings.clone()
    }

    fn server_future(self) -> (Core, Box<Future<Item = (), Error = io::Error>>) {
        let core_handle = self.core.handle();
        let server_key = Sha256::digest_key(self.conf.server_secret.as_bytes());
        let addr_ca_key = self.addr_ca_key.clone();
        let udp_public_addr_v4 = self.udp_public_addr_v4;
        let udp_public_addr_v6 = self.udp_public_addr_v6;
        let couplings = self.couplings;
        let wait_timeout = Duration::from_millis(self.conf.wait_timeout_ms);

        let http_loop = self.http_listener.incoming().for_each(move |(sock, addr)| {
            let service = RelayService {
                core_handle: core_handle.clone(),
                addr_ca_key: addr_ca_key.clone(),
                udp_addr_v4: udp_public_addr_v4,
                udp_addr_v6: udp_public_addr_v6,
                server_key: server_key,
                wait_timeout: wait_timeout,
                couplings: couplings.clone(),
            };
            Http::new().bind_connection(&core_handle, sock, addr, service);
            Ok(())
        });

        let udp_loop_v4 = match self.udp_socket_v4 {
            Some(socket) => addr_ca_loop(self.addr_ca_key.clone(), socket),
            None => Box::new(future::empty()),
        };
        let udp_loop_v6 = match self.udp_socket_v6 {
            Some(socket) => addr_ca_loop(self.addr_ca_key.clone(), socket),
            None => Box::new(future::empty()),
        };

        let combined = http_loop
            .select(udp_loop_v4)
            .map(|(x, _)| x)
            .map_err(|(x, _)| x)
            .select(udp_loop_v6)
            .map(|(x, _)| x)
            .map_err(|(x, _)| x);
        (self.core, Box::new(combined))
    }

    pub fn run(self) -> io::Result<()> {
        let (mut core, future) = self.server_future();
        core.run(future)
    }

    pub fn run_until<F>(self, shutdown_signal: F) -> io::Result<()>
    where
        F: Future<Item = (), Error = ()>,
    {
        let (mut core, future) = self.server_future();
        core.run(
            future
                .select(shutdown_signal.or_else(|_| Ok(())))
                .map(|(x, _)| x)
                .map_err(|(x, _)| x),
        )
    }
}