text:
shared_examples 'Scale_mark' do
  describe 'when update is true' do
    describe 'when mark is nil' do
      before :each do
        mark.update(mark: nil)
      end
      it 'should return nil' do
        expect(mark.scale_mark(curr_max_mark, mark.criterion.max_mark)).to eq(nil)
      end
      it 'should not update the mark' do
        expect(mark.mark).to eq(nil)
      end
    end
    describe 'when mark is 0 or prev_max_mark is 0' do
      before :each do
        mark.update(mark: 0)
      end
      it 'should return 0' do
        expect(mark.scale_mark(curr_max_mark, mark.criterion.max_mark)).to eq(0)
        expect(mark.scale_mark(curr_max_mark, 0)).to eq(0)
      end
      it 'should not update the mark' do
        expect(mark.mark).to eq(0)
      end
    end
    it 'should update and return the new_mark' do
      expect(mark.scale_mark(curr_max_mark, mark.criterion.max_mark)).to eq(mark.mark)
    end
  end
  describe 'when update is false' do
    it 'should not update the new mark' do
      expect(mark.scale_mark(curr_max_mark, mark.criterion.max_mark, update: false)).not_to eq(mark.mark)
    end
  end
end


text:
$:.unshift File.dirname(__FILE__) + "/../lib"

require 'test/unit'
require 'etcutils'

$eu_user = EtcUtils.me.uid.zero? ? "root" : "user"

class Test::Unit::TestCase; include EtcUtils; end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  		<title>Bootstrap Grid</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

                            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                            It has survived not only five centuries, but also the leap into electronic typesetting,
                            remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
                            Lorem Ipsum passages,
                            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                            It has survived not only five centuries, but also the leap into electronic typesetting,
                            remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
                            Lorem Ipsum passages,
                            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

                            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                            It has survived not only five centuries, but also the leap into electronic typesetting,
                            remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
                            Lorem Ipsum passages,
                            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                            It has survived not only five centuries, but also the leap into electronic typesetting,
                            remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
                            Lorem Ipsum passages,
                            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

                            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                            It has survived not only five centuries, but also the leap into electronic typesetting,
                            remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
                            Lorem Ipsum passages,
                            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                            It has survived not only five centuries, but also the leap into electronic typesetting,
                            remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
                            Lorem Ipsum passages,
                            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

                            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                            It has survived not only five centuries, but also the leap into electronic typesetting,
                            remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
                            Lorem Ipsum passages,
                            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                            It has survived not only five centuries, but also the leap into electronic typesetting,
                            remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
                            Lorem Ipsum passages,
                            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


text:
package com.itfsw.mybatis.generator.plugins.utils;

import com.itfsw.mybatis.generator.plugins.utils.hook.IIncrementPluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.IIncrementsPluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Element;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.config.GeneratedKey;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;

/**
 * ---------------------------------------------------------------------------
 * Xml 节点生成工具 参考 org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator
 * ---------------------------------------------------------------------------
 * @author: hewei
 * @time:2016/12/29 16:47
 * ---------------------------------------------------------------------------
 */
public class XmlElementGeneratorTools {

    /**
     * This method should return an XmlElement for the select key used to
     * automatically generate keys.
     * @param introspectedColumn the column related to the select key statement
     * @param generatedKey       the generated key for the current table
     * @return the selectKey element
     */
    public static Element getSelectKey(IntrospectedColumn introspectedColumn, GeneratedKey generatedKey) {
        return getSelectKey(introspectedColumn, generatedKey, null);
    }

    public static Element getSelectKey(IntrospectedColumn introspectedColumn, GeneratedKey generatedKey, String prefix) {
        String identityColumnType = introspectedColumn.getFullyQualifiedJavaType().getFullyQualifiedName();

        XmlElement answer = new XmlElement("selectKey");
        answer.addAttribute(new Attribute("resultType", identityColumnType));
        answer.addAttribute(new Attribute("keyProperty", (prefix == null ? "" : prefix) + introspectedColumn.getJavaProperty()));
        answer.addAttribute(new Attribute("order", generatedKey.getMyBatis3Order()));

        answer.addElement(new TextElement(generatedKey.getRuntimeSqlStatement()));

        return answer;
    }

    public static Element getBaseColumnListElement(IntrospectedTable introspectedTable) {
        XmlElement answer = new XmlElement("include");
        answer.addAttribute(new Attribute("refid", introspectedTable.getBaseColumnListId()));
        return answer;
    }

    public static Element getBlobColumnListElement(IntrospectedTable introspectedTable) {
        XmlElement answer = new XmlElement("include");
        answer.addAttribute(new Attribute("refid", introspectedTable.getBlobColumnListId()));
        return answer;
    }

    public static Element getExampleIncludeElement(IntrospectedTable introspectedTable) {
        XmlElement ifElement = new XmlElement("if");
        ifElement.addAttribute(new Attribute("test", "_parameter != null"));

        XmlElement includeElement = new XmlElement("include");
        includeElement.addAttribute(new Attribute("refid", introspectedTable.getExampleWhereClauseId()));
        ifElement.addElement(includeElement);

        return ifElement;
    }

    public static Element getUpdateByExampleIncludeElement(IntrospectedTable introspectedTable) {
        XmlElement ifElement = new XmlElement("if");
        ifElement.addAttribute(new Attribute("test", "_parameter != null"));

        XmlElement includeElement = new XmlElement("include");
        includeElement.addAttribute(new Attribute("refid", introspectedTable.getMyBatis3UpdateByExampleWhereClauseId()));
        ifElement.addElement(includeElement);

        return ifElement;
    }

    /**
     * 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
     * @param element
     * @param introspectedTable
     */
    public static void useGeneratedKeys(XmlElement element, IntrospectedTable introspectedTable) {
        useGeneratedKeys(element, introspectedTable, null);
    }

    /**
     * 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
     * @param element
     * @param introspectedTable
     * @param prefix
     */
    public static void useGeneratedKeys(XmlElement element, IntrospectedTable introspectedTable, String prefix) {
        GeneratedKey gk = introspectedTable.getGeneratedKey();
        if (gk != null) {
            IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, gk.getColumn());
            // if the column is null, then it's a configuration error. The
            // warning has already been reported
            if (introspectedColumn != null) {
                // 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
                element.addAttribute(new Attribute("useGeneratedKeys", "true"));
                element.addAttribute(new Attribute("keyProperty", (prefix == null ? "" : prefix) + introspectedColumn.getJavaProperty()));
                element.addAttribute(new Attribute("keyColumn", introspectedColumn.getActualColumnName()));
            }
        }
    }

    /**
     * 生成keys Ele
     * @param columns
     * @return
     */
    public static List<Element> generateKeys(List<IntrospectedColumn> columns) {
        return generateKeys(columns, false);
    }

    /**
     * 生成keys Ele
     * @param columns
     * @param bracket
     * @return
     */
    public static List<Element> generateKeys(List<IntrospectedColumn> columns, boolean bracket) {
        return generateCommColumns(columns, null, bracket, 1);
    }

    /**
     * 生成keys Selective Ele
     * @param columns
     * @return
     */
    public static XmlElement generateKeysSelective(List<IntrospectedColumn> columns) {
        return generateKeysSelective(columns, null);
    }

    /**
     * 生成keys Selective Ele
     * @param columns
     * @param prefix
     * @return
     */
    public static XmlElement generateKeysSelective(List<IntrospectedColumn> columns, String prefix) {
        return generateKeysSelective(columns, prefix, true);
    }

    /**
     * 生成keys Selective Ele
     * @param columns
     * @param prefix
     * @param bracket
     * @return
     */
    public static XmlElement generateKeysSelective(List<IntrospectedColumn> columns, String prefix, boolean bracket) {
        return generateCommColumnsSelective(columns, prefix, bracket, 1);
    }

    /**
     * 生成values Ele
     * @param columns
     * @return
     */
    public static List<Element> generateValues(List<IntrospectedColumn> columns) {
        return generateValues(columns, null);
    }

    /**
     * 生成values Ele
     * @param columns
     * @param prefix
     * @return
     */
    public static List<Element> generateValues(List<IntrospectedColumn> columns, String prefix) {
        return generateValues(columns, prefix, true);
    }

    /**
     * 生成values Ele
     * @param columns
     * @param prefix
     * @param bracket
     * @return
     */
    public static List<Element> generateValues(List<IntrospectedColumn> columns, String prefix, boolean bracket) {
        return generateCommColumns(columns, prefix, bracket, 2);
    }

    /**
     * 生成values Selective Ele
     * @param columns
     * @return
     */
    public static XmlElement generateValuesSelective(List<IntrospectedColumn> columns) {
        return generateValuesSelective(columns, null);
    }

    /**
     * 生成values Selective Ele
     * @param columns
     * @param prefix
     * @return
     */
    public static XmlElement generateValuesSelective(List<IntrospectedColumn> columns, String prefix) {
        return generateValuesSelective(columns, prefix, true);
    }

    /**
     * 生成values Selective Ele
     * @param columns
     * @param prefix
     * @param bracket
     * @return
     */
    public static XmlElement generateValuesSelective(List<IntrospectedColumn> columns, String prefix, boolean bracket) {
        return generateCommColumnsSelective(columns, prefix, bracket, 2);
    }

    /**
     * 生成sets Ele
     * @param columns
     * @return
     */
    public static List<Element> generateSets(List<IntrospectedColumn> columns) {
        return generateSets(columns, null);
    }

    /**
     * 生成sets Ele
     * @param columns
     * @param prefix
     * @return
     */
    public static List<Element> generateSets(List<IntrospectedColumn> columns, String prefix) {
        return generateCommColumns(columns, prefix, false, 3);
    }

    /**
     * 生成sets Selective Ele
     * @param columns
     * @return
     */
    public static XmlElement generateSetsSelective(List<IntrospectedColumn> columns) {
        return generateSetsSelective(columns, null);
    }

    /**
     * 生成sets Selective Ele
     * @param columns
     * @param prefix
     * @return
     */
    public static XmlElement generateSetsSelective(List<IntrospectedColumn> columns, String prefix) {
        return generateCommColumnsSelective(columns, prefix, false, 3);
    }

    /**
     * 生成keys Ele (upsert)
     * @param columns
     * @param prefix
     * @return
     */
    public static List<Element> generateUpsertKeys(List<IntrospectedColumn> columns, String prefix) {
        return generateCommColumns(columns, prefix, true, 1, true);
    }

    /**
     * 生成values Ele (upsert)
     * @param columns
     * @param prefix
     * @param bracket
     * @return
     */
    public static List<Element> generateUpsertValues(List<IntrospectedColumn> columns, String prefix, boolean bracket) {
        return generateCommColumns(columns, prefix, bracket, 2, true);
    }

    /**
     * 生成sets Ele (upsert)
     * @param columns
     * @param prefix
     * @return
     */
    public static List<Element> generateUpsertSets(List<IntrospectedColumn> columns, String prefix) {
        return generateCommColumns(columns, prefix, false, 3, true);
    }

    /**
     * 通用遍历columns
     * @param columns
     * @param prefix
     * @param bracket
     * @param type    1:key,2:value,3:set
     * @return
     */
    private static List<Element> generateCommColumns(List<IntrospectedColumn> columns, String prefix, boolean bracket, int type) {
        return generateCommColumns(columns, prefix, bracket, type, false);
    }

    /**
     * 通用遍历columns
     * @param columns
     * @param prefix
     * @param bracket
     * @param type    1:key,2:value,3:set
     * @param upsert
     * @return
     */
    private static List<Element> generateCommColumns(List<IntrospectedColumn> columns, String prefix, boolean bracket, int type, boolean upsert) {
        List<Element> list = new ArrayList<>();

        // 只有upsert插件才会传入 IdentityAndGeneratedAlwaysColumn
        if (upsert && hasIdentityAndGeneratedAlwaysColumns(columns)) {
            XmlElement trimEle = generateTrim(bracket);

            for (IntrospectedColumn introspectedColumn : columns) {
                if (introspectedColumn.isGeneratedAlways() || introspectedColumn.isIdentity()) {
                    generateSelectiveToTrimEleTo(trimEle, introspectedColumn, prefix, type);
                } else if (type == 3 && PluginTools.getHook(IIncrementPluginHook.class).generateIncrementSetSelective(introspectedColumn, prefix) != null) {
                    // IncrementPlugin 插件支持
                    trimEle.addElement(PluginTools.getHook(IIncrementPluginHook.class).generateIncrementSetSelective(introspectedColumn, prefix));
                } else {
                    generateSelectiveCommColumnTo(trimEle, introspectedColumn, prefix, type);
                }
            }

            return Arrays.asList(trimEle);
        } else {
            StringBuilder sb = new StringBuilder(bracket ? "(" : "");
            Iterator<IntrospectedColumn> columnIterator = columns.iterator();
            while (columnIterator.hasNext()) {
                IntrospectedColumn introspectedColumn = columnIterator.next();

                switch (type) {
                    case 3:
                        List<Element> incrementEles = PluginTools.getHook(IIncrementsPluginHook.class).incrementSetElementGenerated(introspectedColumn, prefix, false);
                        XmlElement incrementEle = PluginTools.getHook(IIncrementPluginHook.class).generateIncrementSet(introspectedColumn, prefix, false);

                        if (incrementEle != null) {
                            // 增量插件支持
                            if (sb.length() > 0) {
                                list.add(new TextElement(sb.toString()));
                                sb.setLength(0);
                            }
                            list.add(incrementEle);
                        } else if (!incrementEles.isEmpty()) {
                            // 增量插件支持
                            if (sb.length() > 0) {
                                list.add(new TextElement(sb.toString()));
                                sb.setLength(0);
                            }
                            list.addAll(incrementEles);
                        } else {
                            sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
                            sb.append(" = ");
                            sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix));
                        }

                        break;
                    case 2:
                        sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix));
                        break;
                    case 1:
                        sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
                        break;
                }

                if (columnIterator.hasNext()) {
                    sb.append(", ");
                }

                // 保持和官方一致 80 进行换行
                if (type == 1 || type == 2) {
                    if (sb.length() > 80) {
                        list.add(new TextElement(sb.toString()));
                        sb.setLength(0);
                        OutputUtilities.xmlIndent(sb, 1);
                    }
                } else {
                    list.add(new TextElement(sb.toString()));
                    sb.setLength(0);
                }
            }
            if (sb.length() > 0 || bracket) {
                list.add(new TextElement(sb.append(bracket ? ")" : "").toString()));
            }

            return list;
        }
    }

    /**
     * 通用遍历columns
     * @param columns
     * @param prefix
     * @param bracket
     * @param type    1:key,2:value,3:set
     * @return
     */
    private static XmlElement generateCommColumnsSelective(List<IntrospectedColumn> columns, String prefix, boolean bracket, int type) {
        XmlElement trimEle = generateTrim(bracket);
        for (IntrospectedColumn introspectedColumn : columns) {
            generateSelectiveToTrimEleTo(trimEle, introspectedColumn, prefix, type);
        }
        return trimEle;
    }

    /**
     * trim 节点
     * @param bracket
     * @return
     */
    private static XmlElement generateTrim(boolean bracket) {
        XmlElement trimEle = new XmlElement("trim");
        if (bracket) {
            trimEle.addAttribute(new Attribute("prefix", "("));
            trimEle.addAttribute(new Attribute("suffix", ")"));
            trimEle.addAttribute(new Attribute("suffixOverrides", ","));
        } else {
            trimEle.addAttribute(new Attribute("suffixOverrides", ","));
        }
        return trimEle;
    }

    /**
     * 生成选择列到trim 节点
     * @param trimEle
     * @param introspectedColumn
     * @param prefix
     * @param type               1:key,2:value,3:set
     */
    private static void generateSelectiveToTrimEleTo(XmlElement trimEle, IntrospectedColumn introspectedColumn, String prefix, int type) {
        if (type != 3 && (introspectedColumn.isSequenceColumn() || introspectedColumn.getFullyQualifiedJavaType().isPrimitive())) {
            // if it is a sequence column, it is not optional
            // This is required for MyBatis3 because MyBatis3 parses
            // and calculates the SQL before executing the selectKey

            // if it is primitive, we cannot do a null check
            generateSelectiveCommColumnTo(trimEle, introspectedColumn, prefix, type);
        } else if (type == 3 && PluginTools.getHook(IIncrementPluginHook.class).generateIncrementSetSelective(introspectedColumn, prefix) != null) {
            // IncrementPlugin 插件支持
            trimEle.addElement(PluginTools.getHook(IIncrementPluginHook.class).generateIncrementSetSelective(introspectedColumn, prefix));
        } else {
            XmlElement eleIf = new XmlElement("if");
            eleIf.addAttribute(new Attribute("test", introspectedColumn.getJavaProperty(prefix) + " != null"));

            generateSelectiveCommColumnTo(eleIf, introspectedColumn, prefix, type);

            trimEle.addElement(eleIf);
        }
    }

    /**
     * 生成
     * @param element
     * @param introspectedColumn
     * @param prefix
     * @param type               1:key,2:value,3:set
     */
    private static void generateSelectiveCommColumnTo(XmlElement element, IntrospectedColumn introspectedColumn, String prefix, int type) {
        switch (type) {
            case 3:
                List<Element> incrementEles = PluginTools.getHook(IIncrementsPluginHook.class).incrementSetElementGenerated(introspectedColumn, prefix, true);
                if (!incrementEles.isEmpty()) {
                    // 增量插件支持
                    for (Element ele : incrementEles) {
                        element.addElement(ele);
                    }
                } else {
                    element.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = " + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
                }
                break;
            case 2:
                element.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
                break;
            case 1:
                element.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ","));
                break;
        }
    }

    /**
     * 生成 xxxByPrimaryKey 的where 语句
     * @param element
     * @param primaryKeyColumns
     * @return
     */
    public static void generateWhereByPrimaryKeyTo(XmlElement element, List<IntrospectedColumn> primaryKeyColumns) {
        generateWhereByPrimaryKeyTo(element, primaryKeyColumns, null);
    }

    /**
     * 生成 xxxByPrimaryKey 的where 语句
     * @param element
     * @param primaryKeyColumns
     * @param prefix
     * @return
     */
    public static void generateWhereByPrimaryKeyTo(XmlElement element, List<IntrospectedColumn> primaryKeyColumns, String prefix) {
        StringBuilder sb = new StringBuilder();
        boolean and = false;
        for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {
            sb.setLength(0);
            if (and) {
                sb.append("  and ");
            } else {
                sb.append("where ");
                and = true;
            }

            sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
            sb.append(" = ");
            sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix));
            element.addElement(new TextElement(sb.toString()));
        }
    }

    /**
     * 是否存在自增或者生成的column
     * @param columns
     * @return
     */
    private static boolean hasIdentityAndGeneratedAlwaysColumns(List<IntrospectedColumn> columns) {
        for (IntrospectedColumn ic : columns) {
            if (ic.isGeneratedAlways() || ic.isIdentity()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 生成resultMap的result 节点
     * @param name
     * @param introspectedColumn
     * @return
     */
    public static XmlElement generateResultMapResultElement(String name, IntrospectedColumn introspectedColumn) {
        XmlElement resultElement = new XmlElement(name);

        resultElement.addAttribute(new Attribute("column", MyBatis3FormattingUtilities.getRenamedColumnNameForResultMap(introspectedColumn)));
        resultElement.addAttribute(new Attribute("property", introspectedColumn.getJavaProperty()));
        resultElement.addAttribute(new Attribute("jdbcType", introspectedColumn.getJdbcTypeName()));

        if (stringHasValue(introspectedColumn.getTypeHandler())) {
            resultElement.addAttribute(new Attribute("typeHandler", introspectedColumn.getTypeHandler()));
        }
        return resultElement;
    }

    /**
     * 生成逻辑删除列的删除值
     * @param logicalDeleteColumn
     * @param value
     * @return
     */
    public static String generateLogicalDeleteColumnValue(IntrospectedColumn logicalDeleteColumn, String value) {
        StringBuilder sb = new StringBuilder();
        // 判断字段类型
        if (value == null || "NULL".equalsIgnoreCase(value)) {
            sb.append("NULL");
        } else if (logicalDeleteColumn.isStringColumn()) {
            sb.append("'");
            sb.append(value);
            sb.append("'");
        } else if (logicalDeleteColumn.getFullyQualifiedJavaType().getFullyQualifiedName().equals(Long.class.getName())) {
            sb.append(value.replaceAll("L|l", ""));
        } else if (logicalDeleteColumn.getFullyQualifiedJavaType().getFullyQualifiedName().equals(Float.class.getName())) {
            sb.append(value.replaceAll("F|f", ""));
        } else {
            sb.append(value);
        }
        return sb.toString();
    }

    /**
     * Gets the parameter clause.
     * @param valueStr
     * @param introspectedColumn the introspected column
     * @return the parameter clause
     */
    public static String getParameterClause(String valueStr, IntrospectedColumn introspectedColumn) {
        StringBuilder sb = new StringBuilder();

        sb.append("#{");
        sb.append(valueStr);
        sb.append(",jdbcType=");
        sb.append(introspectedColumn.getJdbcTypeName());

        if (stringHasValue(introspectedColumn.getTypeHandler())) {
            sb.append(",typeHandler=");
            sb.append(introspectedColumn.getTypeHandler());
        }

        sb.append('}');

        return sb.toString();
    }
}


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

namespace BashChelik.Native
{
    class NativeConstants
    {
        ///Size of all UTF-8 and binary fields in bytes
        #region EID_DOCUMENT_DATA Size
        internal const int EID_MAX_DocRegNo = 9;
        internal const int EID_MAX_DocumentType = 2;
        internal const int EID_MAX_IssuingDate = 10;
        internal const int EID_MAX_ExpiryDate = 10;
        internal const int EID_MAX_IssuingAuthority = 100;
        #endregion

        ///Size of all UTF-8 and binary fields in bytes
        #region EID_FIXED_PERSONAL_DATA Size
        internal const int EID_MAX_PersonalNumber = 13;
        internal const int EID_MAX_Surname = 200;
        internal const int EID_MAX_GivenName = 200;
        internal const int EID_MAX_ParentGivenName = 200;
        internal const int EID_MAX_Sex = 2;
        internal const int EID_MAX_PlaceOfBirth = 200;
        internal const int EID_MAX_StateOfBirth = 200;
        internal const int EID_MAX_DateOfBirth = 10;
        internal const int EID_MAX_CommunityOfBirth = 200;
        #endregion

        ///Size of all UTF-8 and binary fields in bytes
        #region EID_VARIABLE_PERSONAL_DATA Size
        internal const int EID_MAX_State = 100;
        internal const int EID_MAX_Community = 200;
        internal const int EID_MAX_Place = 200;
        internal const int EID_MAX_Street = 200;
        internal const int EID_MAX_HouseNumber = 20;
        internal const int EID_MAX_HouseLetter = 8;
        internal const int EID_MAX_Entrance = 10;
        internal const int EID_MAX_Floor = 6;
        internal const int EID_MAX_ApartmentNumber = 12;
        internal const int EID_MAX_AddressDate = 10;
        internal const int EID_MAX_AddressLabel = 60;
        #endregion

        ///Size of all UTF-8 and binary fields in bytes
        #region EID_PORTRAIT
        internal const int EID_MAX_Portrait = 7700;
        #endregion

        ///Size of all UTF-8 and binary fields in bytes
        #region EID_CERTIFICATE
        internal const int EID_MAX_Certificate = 2048;
        #endregion

        //
        // Option identifiers, used in function EidSetOption
        //
        internal int EID_O_KEEP_CARD_CLOSED = 1;

        //
        // Certificate types, used in function EidReadCertificate
        //
        internal const int EID_Cert_MoiIntermediateCA = 1;
        internal const int EID_Cert_User1 = 2;
        internal const int EID_Cert_User2 = 3;

        //
        // Block types, used in function EidVerifySignature
        //
        internal const int EID_SIG_CARD = 1;
        internal const int EID_SIG_FIXED = 2;
        internal const int EID_SIG_VARIABLE = 3;
        internal const int EID_SIG_PORTRAIT = 4;

        // For new card version EidVerifySignature function will return EID_E_UNABLE_TO_EXECUTE for
        // parameter EID_SIG_PORTRAIT. Portrait is in new cards part of EID_SIG_FIXED. To determine
        // the card version use second parameter of function EidBeginRead

    }
}


text:
class BookmarkNode;

// A button cell that handles drawing/highlighting of buttons in the
// bookmark bar.  This cell forwards mouseEntered/mouseExited events
// to its control view so that pseudo-menu operations
// (e.g. hover-over to open) can be implemented.
@interface BookmarkButtonCell : GradientButtonCell<NSMenuDelegate> {
 @private
  BOOL empty_;  // is this an "empty" button placeholder button cell?

  // Starting index of bookmarkFolder children that we care to use.
  int startingChildIndex_;

  // Should we draw the folder arrow as needed?  Not used for the bar
  // itself but used on the folder windows.
  BOOL drawFolderArrow_;

  // Arrow for folders
  scoped_nsobject<NSImage> arrowImage_;
}

@property(nonatomic, readwrite, assign) const BookmarkNode* bookmarkNode;
@property(nonatomic, readwrite, assign) int startingChildIndex;
@property(nonatomic, readwrite, assign) BOOL drawFolderArrow;

// Create a button cell which draws with a theme.
+ (id)buttonCellForNode:(const BookmarkNode*)node
            contextMenu:(NSMenu*)contextMenu
               cellText:(NSString*)cellText
              cellImage:(NSImage*)cellImage;

// Initialize a button cell which draws with a theme.
// Designated initializer.
- (id)initForNode:(const BookmarkNode*)node
      contextMenu:(NSMenu*)contextMenu
         cellText:(NSString*)cellText
        cellImage:(NSImage*)cellImage;

- (BOOL)empty;  // returns YES if empty.
- (void)setEmpty:(BOOL)empty;

// |-setBookmarkCellText:image:| is used to set the text and image of
// a BookmarkButtonCell, and align the image to the left (NSImageLeft)
// if there is text in the title, and centered (NSImageCenter) if
// there is not.  If |title| is nil, do not reset the title.
- (void)setBookmarkCellText:(NSString*)title
                      image:(NSImage*)image;

// Set the color of text in this cell.
- (void)setTextColor:(NSColor*)color;

- (BOOL)isFolderButtonCell;

@end

#endif  // CHROME_BROWSER_UI_COCOA_BOOKMARKS_BOOKMARK_BUTTON_CELL_H_


text:
import copy
import typing
from types import SimpleNamespace

from federatedml.param.base_param import BaseParam
from federatedml.param.cross_validation_param import CrossValidationParam
from federatedml.param.predict_param import PredictParam
from federatedml.param.callback_param import CallbackParam
import json

class HomoNNParam(BaseParam):
    """
    Parameters used for Homo Neural Network.

    Parameters
    ----------
    secure_aggregate : bool
        enable secure aggregation or not, defaults to True.
    aggregate_every_n_epoch : int
        aggregate model every n epoch, defaults to 1.
    config_type : {"nn", "keras", "tf"}
        config type
    nn_define : dict
        a dict represents the structure of neural network.
    optimizer : str or dict
        optimizer method, accept following types:
        1. a string, one of "Adadelta", "Adagrad", "Adam", "Adamax", "Nadam", "RMSprop", "SGD"
        2. a dict, with a required key-value pair keyed by "optimizer",
            with optional key-value pairs such as learning rate.
        defaults to "SGD"
    loss : str
        loss
    metrics: str or list of str
        metrics
    max_iter: int
        the maximum iteration for aggregation in training.
    batch_size : int
        batch size when updating model.
        -1 means use all data in a batch. i.e. Not to use mini-batch strategy.
        defaults to -1.
    early_stop : {'diff', 'weight_diff', 'abs'}
        Method used to judge converge or not.
            a)	diff: Use difference of loss between two iterations to judge whether converge.
            b)  weight_diff: Use difference between weights of two consecutive iterations
            c)	abs: Use the absolute value of loss to judge whether converge. i.e. if loss < eps, it is converged.
    encode_label : bool
        encode label to one_hot.
    """

    def __init__(
        self,
        api_version: int = 0,
        secure_aggregate: bool = True,
        aggregate_every_n_epoch: int = 1,
        config_type: str = "nn",
        nn_define: dict = None,
        optimizer: typing.Union[str, dict, SimpleNamespace] = "SGD",
        loss: str = None,
        metrics: typing.Union[str, list] = None,
        max_iter: int = 100,
        batch_size: int = -1,
        early_stop: typing.Union[str, dict, SimpleNamespace] = "diff",
        encode_label: bool = False,
        predict_param=PredictParam(),
        cv_param=CrossValidationParam(),
        callback_param=CallbackParam(),
    ):
        super(HomoNNParam, self).__init__()

        self.api_version = api_version

        self.secure_aggregate = secure_aggregate
        self.aggregate_every_n_epoch = aggregate_every_n_epoch

        self.config_type = config_type
        self.nn_define = nn_define or []
        self.encode_label = encode_label

        self.batch_size = batch_size
        self.max_iter = max_iter
        self.early_stop = early_stop
        self.metrics = metrics
        self.optimizer = optimizer
        self.loss = loss

        self.predict_param = copy.deepcopy(predict_param)
        self.cv_param = copy.deepcopy(cv_param)
        self.callback_param = copy.deepcopy(callback_param)

    def check(self):
        supported_config_type = ["nn", "keras", "pytorch"]
        if self.config_type not in supported_config_type:
            raise ValueError(f"config_type should be one of {supported_config_type}")
        self.early_stop = _parse_early_stop(self.early_stop)
        self.metrics = _parse_metrics(self.metrics)
        self.optimizer = _parse_optimizer(self.optimizer)

    def generate_pb(self):
        from federatedml.protobuf.generated import nn_model_meta_pb2

        pb = nn_model_meta_pb2.HomoNNParam()
        pb.secure_aggregate = self.secure_aggregate
        pb.encode_label = self.encode_label
        pb.aggregate_every_n_epoch = self.aggregate_every_n_epoch
        pb.config_type = self.config_type

        if self.config_type == "nn":
            for layer in self.nn_define:
                pb.nn_define.append(json.dumps(layer))
        elif self.config_type == "keras":
            pb.nn_define.append(json.dumps(self.nn_define))
        elif self.config_type == "pytorch":
            for layer in self.nn_define:
                pb.nn_define.append(json.dumps(layer))

        pb.batch_size = self.batch_size
        pb.max_iter = self.max_iter

        pb.early_stop.early_stop = self.early_stop.converge_func
        pb.early_stop.eps = self.early_stop.eps

        for metric in self.metrics:
            pb.metrics.append(metric)

        pb.optimizer.optimizer = self.optimizer.optimizer
        pb.optimizer.args = json.dumps(self.optimizer.kwargs)
        pb.loss = self.loss
        return pb

    def restore_from_pb(self, pb, is_warm_start_mode: bool = False):
        self.secure_aggregate = pb.secure_aggregate
        self.encode_label = pb.encode_label
        self.aggregate_every_n_epoch = pb.aggregate_every_n_epoch
        self.config_type = pb.config_type

        if self.config_type == "nn":
            for layer in pb.nn_define:
                self.nn_define.append(json.loads(layer))
        elif self.config_type == "keras":
            self.nn_define = json.loads(pb.nn_define[0])
        elif self.config_type == "pytorch":
            for layer in pb.nn_define:
                self.nn_define.append(json.loads(layer))
        else:
            raise ValueError(f"{self.config_type} is not supported")

        self.batch_size = pb.batch_size
        if not is_warm_start_mode:
            self.max_iter = pb.max_iter
            self.optimizer = _parse_optimizer(
                dict(optimizer=pb.optimizer.optimizer, **json.loads(pb.optimizer.args))
            )
        self.early_stop = _parse_early_stop(
            dict(early_stop=pb.early_stop.early_stop, eps=pb.early_stop.eps)
        )
        self.metrics = list(pb.metrics)
        self.loss = pb.loss
        return pb

def _parse_metrics(param):
    """
    Examples:

        1. "metrics": "Accuracy"
        2. "metrics": ["Accuracy"]
    """
    if not param:
        return []
    elif isinstance(param, str):
        return [param]
    elif isinstance(param, list):
        return param
    else:
        raise ValueError(f"invalid metrics type: {type(param)}")

def _parse_optimizer(param):
    """
    Examples:

        1. "optimize": "SGD"
        2. "optimize": {
                "optimizer": "SGD",
                "learning_rate": 0.05
            }
    """
    kwargs = {}
    if isinstance(param, str):
        return SimpleNamespace(optimizer=param, kwargs=kwargs)
    elif isinstance(param, dict):
        optimizer = param.get("optimizer", kwargs)
        if not optimizer:
            raise ValueError(f"optimizer config: {param} invalid")
        kwargs = {k: v for k, v in param.items() if k != "optimizer"}
        return SimpleNamespace(optimizer=optimizer, kwargs=kwargs)
    else:
        raise ValueError(f"invalid type for optimize: {type(param)}")

def _parse_early_stop(param):
    """
    Examples:

        1. "early_stop": "diff"
        2. "early_stop": {
                "early_stop": "diff",
                "eps": 0.0001
            }
    """
    default_eps = 0.0001
    if isinstance(param, str):
        return SimpleNamespace(converge_func=param, eps=default_eps)
    elif isinstance(param, dict):
        early_stop = param.get("early_stop", param.get("converge_func"))
        eps = param.get("eps", default_eps)
        if not early_stop:
            raise ValueError(f"early_stop config: {param} invalid")
        return SimpleNamespace(converge_func=early_stop, eps=eps)
    else:
        raise ValueError(f"invalid type for early_stop: {type(param)}")


text:
{% load i18n future pages_tags %}

{% spaceless %}
{% if page_branch_in_menu %}

    {% for page in page_branch %}

        {% if not has_home and page.is_primary and forloop.first %}

                {% trans "Home" %}

        {% endif %}

        {% if page.in_menu %}

                {{ page.title }}

            {% if page.has_children_in_menu %}
                {% page_menu page %}
            {% endif %}

        {% endif %}
    {% endfor %}

{% endif %}
{% endspaceless %}


text:
require "formula"

class GoAppEngine64 < Formula
  homepage "http://code.google.com/appengine/docs/go/overview.html"

  if OS.mac?
    url "https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_darwin_amd64-1.9.14.zip"
    sha1 "45493333185b74cba6be690f2ca72f7639a14969"
  elsif OS.linux?
    url "https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.14.zip"
    sha1 "406003781e36bc6b01406f5f0025eec0550ba8c6"
  else
    raise "Unknown operating system"
  end

  def install
    cd ".."
    share.install "go_appengine" => name
    %w[
      api_server.py appcfg.py bulkloader.py bulkload_client.py dev_appserver.py download_appstats.py goapp
    ].each do |fn|
      bin.install_symlink share/name/fn
    end
  end
end


text:
@implementation CHLSharedViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end


text:
package picard.sam.markduplicates;

import java.util.stream.Collectors;
import htsjdk.samtools.metrics.MetricBase;
import htsjdk.samtools.util.Histogram;
import htsjdk.samtools.util.QualityUtil;
import picard.PicardException;
import picard.util.MathUtil;

/**
 * Metrics that are calculated during the process of marking duplicates
 * within a stream of SAMRecords using the UmiAwareDuplicateSetIterator.
 */
public class UmiMetrics extends MetricBase {
    private final Histogram<String> observedUmis = new Histogram<>();
    private final Histogram<String> inferredUmis = new Histogram<>();
    private long observedUmiBases = 0;
    private long observedUmiWithNs = 0;
    private long totalObservedUmisWithoutNs = 0;

    /** Library that was used to generate UMI data. */
    public String LIBRARY;

    /** Number of bases in each UMI */
    public double MEAN_UMI_LENGTH = 0.0;

    /** Number of different UMI sequences observed */
    public long OBSERVED_UNIQUE_UMIS = 0;

    /** Number of different inferred UMI sequences derived */
    public long INFERRED_UNIQUE_UMIS = 0;

    /** Number of errors inferred by comparing the observed and inferred UMIs */
    public long OBSERVED_BASE_ERRORS = 0;

    /** Number of duplicate sets found before taking UMIs into account */
    public long DUPLICATE_SETS_IGNORING_UMI = 0;

    /** Number of duplicate sets found after taking UMIs into account */
    public long DUPLICATE_SETS_WITH_UMI = 0;

    /**
     * Entropy (in base 4) of the observed UMI sequences, indicating the
     * effective number of bases in the UMIs.  If this is significantly
     * smaller than UMI_LENGTH, it indicates that the UMIs are not
     * distributed uniformly.
     */
    public double OBSERVED_UMI_ENTROPY = 0;

    /** Entropy (in base 4) of the inferred UMI sequences, indicating the
     * effective number of bases in the inferred UMIs.  If this is significantly
     * smaller than UMI_LENGTH, it indicates that the UMIs are not
     * distributed uniformly.
     */
    public double INFERRED_UMI_ENTROPY = 0;

    /** Estimation of Phred scaled quality scores for UMIs */
    public double UMI_BASE_QUALITIES = 0.0;

    /** The percentage of reads that contain an UMI that contains at least one N */
    public double PCT_UMI_WITH_N = 0.0;

    public UmiMetrics() { }

    public UmiMetrics(final String library) {
        LIBRARY = library;
    }

    public UmiMetrics(final String library, final double length, final int observedUniqueUmis, final int inferredUniqueUmis,
                      final int observedBaseErrors, final int duplicateSetsWithoutUmi,
                      final int duplicateSetsWithUmi, final double effectiveLengthOfInferredUmis,
                      final double effectiveLengthOfObservedUmis, final double estimatedBaseQualityOfUmis,
                      final double percentUmiWithN) {

        LIBRARY = library;
        MEAN_UMI_LENGTH = length;
        OBSERVED_UNIQUE_UMIS = observedUniqueUmis;
        INFERRED_UNIQUE_UMIS = inferredUniqueUmis;
        OBSERVED_BASE_ERRORS = observedBaseErrors;
        DUPLICATE_SETS_IGNORING_UMI = duplicateSetsWithoutUmi;
        DUPLICATE_SETS_WITH_UMI = duplicateSetsWithUmi;
        INFERRED_UMI_ENTROPY = effectiveLengthOfInferredUmis;
        OBSERVED_UMI_ENTROPY = effectiveLengthOfObservedUmis;
        UMI_BASE_QUALITIES = estimatedBaseQualityOfUmis;
        PCT_UMI_WITH_N = percentUmiWithN;
    }

    public void calculateDerivedFields() {
        OBSERVED_UNIQUE_UMIS = observedUmis.size();
        INFERRED_UNIQUE_UMIS = inferredUmis.size();

        // Percent of UMIs that contain at least one N of total number of UMIs observed (observed UMIs is a count of UMIs without N)
        PCT_UMI_WITH_N = (double) observedUmiWithNs/ ((double) observedUmiWithNs + (double) totalObservedUmisWithoutNs);
        OBSERVED_UMI_ENTROPY = effectiveNumberOfBases(observedUmis);
        INFERRED_UMI_ENTROPY = effectiveNumberOfBases(inferredUmis);
        UMI_BASE_QUALITIES = QualityUtil.getPhredScoreFromErrorProbability((double) OBSERVED_BASE_ERRORS / (double) observedUmiBases);
    }

    /**
     * Add an observation of a UMI to the metrics
     * @param observedUmi String containing the observed UMI
     * @param inferredUmi String containing the UMI inferred after error correcting the observed UMI
     */
    public void addUmiObservation(String observedUmi, String inferredUmi) {
        observedUmis.increment(observedUmi);
        inferredUmis.increment(inferredUmi);
        observedUmiBases += observedUmi.length();
        totalObservedUmisWithoutNs++;
    }

    /** Add an observation of a UMI containing at least one N to the metrics */
    public void addUmiObservationN() {
        observedUmiWithNs++;
    }

    private double effectiveNumberOfBases(Histogram<?> observations) {
        double totalObservations = observations.getSumOfValues();

        // Convert to log base 4 so that the entropy is now a measure
        // of the effective number of DNA bases.  If we used log(2.0)
        // our result would be in bits.
        double entropyBaseE = observations.values().stream().collect(Collectors.summingDouble(
                v -> {double p = v.getValue() / totalObservations;
                        return -p * Math.log(p);}));

        return entropyBaseE / MathUtil.LOG_4_BASE_E;
    }
}


text:
var reader = require('../feed-reader')
  , nock = require('nock')
  , assert = require('chai').assert

describe('feed-reader', function () {
  it('returns feed stream on good url', function (done) {
    var scope = nock('http://blog.jerryorr.com')
      .get('/feed')
      .replyWithFile(200, __dirname + '/goodfeed.xml')

    var articleCount = 0
    reader.read('http://blog.jerryorr.com/feed')
      .on('readable', function () {
        var stream = this
          , item

        while (item = stream.read()) {
          assert(item.title)
          assert(item.description)

          articleCount++
        }
      })
      .on('end', function () {
        assert.equal(articleCount, 9)
        done()
      })
      .on('error', function (err) {
        done(err)
      })
  })

  it('emits error event on 404', function (done) {
    var scope = nock('http://blog.jerryorr.com')
      .get('/feed')
      .reply(404)

    reader.read('http://blog.jerryorr.com/feed')
      .on('readable', function () {
        done(new Error('readable event handler should not be called'))
      })
      .on('end', function () {
        done(new Error('end event handler should not be called'))
      })
      .on('error', function (err) {
        assert(err)
        done()
      })
  })

  it('emits error event on bogus URL', function (done) {
    reader.read('http://thisisnotavalidurlsothisreapertestshouldfail.com')
      .on('readable', function () {
        done(new Error('readable event handler should not be called'))
      })
      .on('end', function () {
        done(new Error('end event handler should not be called'))
      })
      .on('error', function (err) {
        assert(err)
        done()
      })
  })
})


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

using System;
using System.Globalization;
using System.Reflection;

namespace Microsoft.Azure.Management.DataFactories.Models
{
    public abstract class AdfResourceProperties<TExtensibleTypeProperties, TGenericTypeProperties>
        where TExtensibleTypeProperties : TypeProperties
        where TGenericTypeProperties : TExtensibleTypeProperties
    {
        /// <summary>
        /// The type of the resource. May be the name of a built-in ADF type or
        /// a type registered by a user and available to the data factory this resource
        /// is a member of.
        /// </summary>
        [AdfRequired]
        public string Type { get; private set; }

        private TExtensibleTypeProperties typeProperties;

        /// <summary>
        /// The properties specific to the resource type.
        /// </summary>
        [AdfRequired]
        public TExtensibleTypeProperties TypeProperties
        {
            get
            {
                return this.typeProperties;
            }

            set
            {
                this.SetTypeProperties(value);
            }
        }

        protected AdfResourceProperties()
        {
        }

        protected AdfResourceProperties(TExtensibleTypeProperties properties, string typeName = null)
            : this()
        {
            this.SetTypeProperties(properties, typeName);
        }

        private void SetTypeProperties(TExtensibleTypeProperties properties, string typeName = null)
        {
            this.typeProperties = properties;

            Type type = properties.GetType();
            Type genericTypePropertiesType = typeof(TGenericTypeProperties);
            if (type == genericTypePropertiesType)
            {
                if (typeName == null)
                {
                    throw new ArgumentException(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "'typeName' cannot be null if 'properties' is a {0} instance. The setter "
                            + "for 'typeProperties' cannot be used if its value is GenericLinkedService, GenericTable or GenericActivity.",
                            genericTypePropertiesType.Name));
                }

                this.Type = typeName;
            }
            else
            {
                this.Type = GetTypeName(type, typeName);
            }
        }

        private static string GetTypeName(Type type, string actualTypeName)
        {
            if (type == typeof(TGenericTypeProperties))
            {
                Ensure.IsNotNullOrEmpty(actualTypeName, "actualTypeName");
                return actualTypeName;
            }

            return DataFactoryUtilities.GetResourceTypeName(type);
        }
    }
}


text:
using MS.Internal;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Markup;
using System.Windows.Media.Media3D.Converters;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Windows.Media.Imaging;
#pragma warning disable 1634, 1691  // suppressing PreSharp warnings

namespace System.Windows.Media.Media3D.Converters
{
    /// <summary>
    /// Size3DValueSerializer - ValueSerializer class for converting instances of strings to and from Size3D instances
    /// This is used by the MarkupWriter class.
    /// </summary>
    public class Size3DValueSerializer : ValueSerializer
    {
        /// <summary>
        /// Returns true.
        /// </summary>
        public override bool CanConvertFromString(string value, IValueSerializerContext context)
        {
            return true;
        }

        /// <summary>
        /// Returns true if the given value can be converted into a string
        /// </summary>
        public override bool CanConvertToString(object value, IValueSerializerContext context)
        {

            // Validate the input type
            if (!(value is Size3D))
            {
                return false;
            }

            return true;

        }

        /// <summary>
        /// Converts a string into a Size3D.
        /// </summary>
        public override object ConvertFromString(string value, IValueSerializerContext context)
        {
            if (value != null)
            {
                return Size3D.Parse(value );
            }
            else
            {
                return base.ConvertFromString( value, context );
            }

        }

        /// <summary>
        /// Converts the value into a string.
        /// </summary>
        public override string ConvertToString(object value, IValueSerializerContext context)
        {
            if (value is Size3D)
            {
                Size3D instance = (Size3D) value;

                #pragma warning suppress 6506 // instance is obviously not null
                return instance.ConvertToString(null, System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS);
            }

            return base.ConvertToString(value, context);
        }
    }

}


text:
<component name="libraryTable">
  <library name="estimote-sdk-preview">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/EstimoteSDK/estimote-sdk-preview.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>TestSerrviziFile</title>
<meta name="date" content="2017-01-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

it.speedhouse.test

Class TestSerrviziFile

java.lang.Object

it.speedhouse.test.TestSerrviziFile

public class TestSerrviziFile
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

TestSerrviziFile()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
setUp()

void
tearDown()

void
testEstraiColonne()

void
testEstraiRighe()

void
testEstraiTipi()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TestSerrviziFile

public TestSerrviziFile()

Method Detail

setUp

public void setUp()

tearDown

public void tearDown()

testEstraiRighe

public void testEstraiRighe()
                     throws java.io.FileNotFoundException

Throws:

java.io.FileNotFoundException

testEstraiTipi

public void testEstraiTipi()
                    throws java.io.FileNotFoundException

Throws:

java.io.FileNotFoundException

testEstraiColonne

public void testEstraiColonne()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
extern crate hero_wfgen;

use hero_wfgen::{DEFAULT_WAVETABLE_SIZE, gen_lut, sin, saw};

const WT_SRC: &'static str = "src/wavetable";

fn main() {
    let mut sin_gen = sin::SinGen::new(DEFAULT_WAVETABLE_SIZE);
    gen_lut(WT_SRC, "sin", &mut sin_gen).unwrap();

    let mut saw_gen = saw::SawGen::new(DEFAULT_WAVETABLE_SIZE);
    gen_lut(WT_SRC, "saw", &mut saw_gen).unwrap();
}


text:
{% extends "site_base.html" %}
{% load humanize %}

{% block body_class %}home{% endblock %}

{% block content %}

Search our Data Resources.

	{% include 'ddi/snippets/search_form.html' %}

{% include 'ddi/snippets/loading.html' %}

New Additions

					{% for res in new_resources %}

							{{ res.document_version.date|naturalday }}
							{{ res.title }}

					{% empty %}
					No resources have been added since {{ new_since|naturalday }}.
					{% endfor %}

{% endblock %}


text:
<?php
namespace Rails\I18n\Locales;

abstract class AbstractLocales
{
    protected $translations = [];

    public function tr()
    {
        return $this->translations;
    }
}


text:
package Project;

import java.io.*;

public class Interface {
	// input from stdin
	private static BufferedReader input = new BufferedReader(
			new InputStreamReader(System.in));

	// error method
	public static void error(String message, String re) throws Rep_Exception {
		throw new Rep_Exception(message + re);
	}

	public static void error(String message) throws Rep_Exception {
		throw new Rep_Exception(message);
	}

	public static void main(String[] args) throws IOException {
		// Does the user want to enter an new string and test?
		String repeatExpres = new String("y");

		String repeatTest = new String("y");

		// the expression
		String regExpres = new String();

		// "test string" against expression
		String testExpres = new String();

		// initialize NDFA used to test string
		NDFA graph = null;

		// instance of parser
		Parser grep = new Parser();

		// Whether the test string matches the expression
		boolean answer;

		// repeat test until the user indicates to stop
		while (repeatExpres.charAt(0) == 'y') {
			repeatTest = "y";
			System.out.println("Please enter a regular expression:");
			// get the RE
			regExpres = input.readLine();
			// set Parser
			grep.set_parser_target(regExpres);
			// eye candy for user
			System.out.println();
			System.out.println("The RE is: " + regExpres);
			System.out.println();

			// parse the expression
			try {
				graph = grep.RE();
			} catch (Rep_Exception e) {
				repeatTest = ("n"); // If there is an exception do not ask for
									// test strings
			}

			// Get test strings and test them against expression
			while (repeatTest.charAt(0) == 'y') {
				System.out.print("Please enter a string ");
				System.out.println("to test against that RE:");
				try {
					testExpres = input.readLine();
					answer = graph.run(testExpres);
					System.out.println();
					if (answer) {
						System.out.println("The string \"" + testExpres
								+ "\" matches the RE.");
					} else {
						System.out.println("The string \"" + testExpres
								+ "\" does not match the RE.");
					}
					System.out.println();
				} catch (Rep_Exception e) {
				}
				System.out.print("Do you want to test ");
				System.out.println("another string? (y/[n])");
				repeatTest = input.readLine();
				System.out.println();
			}
			System.out.print("Do you want to enter a different ");
			System.out.println("regular expression? (y/[n])");
			repeatExpres = input.readLine();
			System.out.println();
		}
		System.out.println("Thank you.");
		System.out.println("");
		return;
	}
}


text:
require 'rails/all'
require 'jquery-rails'
require 'jquery-ui-rails'
require 'deface'
require 'select2-rails'

require 'gesmew_core'
require 'gesmew_api'

require 'gesmew/responder'
require 'gesmew/backend/action_callbacks'
require 'gesmew/backend/callbacks'
require 'gesmew/backend/engine'
require 'bootstrap-wysihtml5-rails'
require 'react_webpack_rails'


text:
using System.Collections.Generic;

namespace Azure.Management.Network.Models
{
    /// <summary> Response for ListExpressRouteCircuit API service call. </summary>
    public partial class ExpressRouteCircuitListResult
    {
        /// <summary> Initializes a new instance of ExpressRouteCircuitListResult. </summary>
        internal ExpressRouteCircuitListResult()
        {
        }

        /// <summary> Initializes a new instance of ExpressRouteCircuitListResult. </summary>
        /// <param name="value"> A list of ExpressRouteCircuits in a resource group. </param>
        /// <param name="nextLink"> The URL to get the next set of results. </param>
        internal ExpressRouteCircuitListResult(IReadOnlyList<ExpressRouteCircuit> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> A list of ExpressRouteCircuits in a resource group. </summary>
        public IReadOnlyList<ExpressRouteCircuit> Value { get; }
        /// <summary> The URL to get the next set of results. </summary>
        public string NextLink { get; }
    }
}


text:
var mongoose = require('mongoose');

var categorySchema = mongoose.Schema({
    name: { type: String, require: '{PATH} is required', unique: true }
});

mongoose.model('Category', categorySchema);


text:
import React, { Component } from 'react';
import Form from './Form';

export default class App extends Component {
	render() {
		return (

						<Form />

		);
	}
}


text:
(function($) {
    "use strict"; // Start of use strict

    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 51
    });

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });

    // Offset for Main Navigation
    $('#mainNav').affix({
        offset: {
            top: 100
        }
    })

    // Initialize and Configure Scroll Reveal Animation
    window.sr = ScrollReveal();
    sr.reveal('.sr-icons', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 200);
    sr.reveal('.sr-button', {
        duration: 1000,
        delay: 200
    });
    sr.reveal('.sr-contact', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 300);

    // Initialize and Configure Magnific Popup Lightbox Plugin
    $('.popup-gallery').magnificPopup({
        delegate: 'a',
        type: 'image',
        tLoading: 'Loading image #%curr%...',
        mainClass: 'mfp-img-mobile',
        gallery: {
            enabled: true,
            navigateByImgClick: true,
            preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
        },
        image: {
            tError: 'The image #%curr% could not be loaded.'
        }
    });

})(jQuery); // End of use strict

$(document).ready(function(){

    // Init ScrollMagic
    var controller = new ScrollMagic.Controller();

    // build a scene
    var ourScene = new ScrollMagic.Scene({
        triggerElement: '#project01'
    })
    .setClassToggle('#project01', 'fade-in') // add class to project01
    .addTo(controller);

    // build a scene
    var ourScene = new ScrollMagic.Scene({
        triggerElement: '#project02'
    })
    .setClassToggle('#project02', 'fade-in')
    .addTo(controller);

    // build a scene
    var ourScene = new ScrollMagic.Scene({
        triggerElement: '#project03'
    })
    .setClassToggle('#project03', 'fade-in')
    .addTo(controller);
});


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('actstream', '0002_remove_action_data'),
    ]

    operations = [
        migrations.AddField(
            model_name='follow',
            name='flag',
            field=models.CharField(blank=True, db_index=True, default='', max_length=255),
        ),
        migrations.AlterUniqueTogether(
            name='follow',
            unique_together=set([('user', 'content_type', 'object_id', 'flag')]),
        ),
    ]


text:
tarball_url = node["cycle_server"]["grill"]["url"]
install_file = File.basename(tarball_url)
install_name = File.basename(tarball_url, '.tar.gz')

if tarball_url =~ /example.com/
  Chef::Application.fatal!("You must change the download url to your private repository.")
end

# Sanity check memory settings
mem_req = ( node["cycle_server"]["grill"]["webServerMaxHeapSizeMB"].to_i +
    node["cycle_server"]["grill"]["databaseMaxHeapSizeMB"].to_i +
    node["cycle_server"]["grill"]["brokerMaxHeapSizeMB"].to_i )
if mem_req > ( node[:memory][:total].to_i / 1024 * 0.90 )
  Chef::Application.fatal!("Component heap size attributes require more than 90% of total system memory. Cowardly refusing to continue")
end

# You can disable inclusion of the java recipe if you have your own way of providing it
if node["cycle_server"]["grill"]["include_java"]
  unless node["java"]["install_flavor"] =~ /oracle/
    Chef::Application.fatal!("Only Oracle Java is supported. You must change your java install_flavor")
  end

  include_recipe "java"
end

# Make the recipe more concise
grill_user = node["cycle_server"]["grill"]["user"]
grill_group = node["cycle_server"]["grill"]["group"]

# You can disable management of the Grill user/group if you have your own way of providing it
if node["cycle_server"]["grill"]["manage_user"]
  group grill_group do
    action [:create, :manage]
  end

  user grill_user do
    comment "Cycleserver Grill user"
    gid grill_group
    home "/home/#{grill_user}"
    action [:create, :manage]
    supports :manage_home => true
  end
end

remote_file "#{Chef::Config[:file_cache_path]}/#{install_file}" do
  source tarball_url
  mode "0644"
  owner grill_user
  group grill_group
  checksum node["cycle_server"]["grill"]["checksum"]
end

# Check if we've installed this version before
unless File.directory?("/opt/#{install_name}")

  # Grill is packaged as "cycleserver" directory so extract it temporarily
  execute "extract_grill" do
    command "tar zxf #{Chef::Config[:file_cache_path]}/#{install_file} -C #{Chef::Config[:file_cache_path]}/"
  end

  execute "move_grill" do
    command "mv #{Chef::Config[:file_cache_path]}/cycle_server /opt/#{install_name}"
  end

  execute "chown_grill" do
    command "chown -R #{grill_user}:#{grill_group} /opt/#{install_name}"
  end

  link "/opt/cycle_server" do
    to "/opt/#{install_name}"
  end

end #unless installed

template "/etc/init.d/cycle_server" do
  source "cycle_server.init.erb"
  owner "root"
  group "root"
  mode "0755"
  variables(
      :grill_user => grill_user
  )
end

template "/etc/logrotate.d/cycle_server" do
  source "cycle_server.logrotate.erb"
  owner "root"
  group "root"
  mode "0644"
end

template "/opt/cycle_server/config/cycle_server.properties" do
  source "cycle_server.properties.erb"
  owner grill_user
  group grill_group
  mode "0644"
  notifies :restart, "service[cycle_server]"
end

service "cycle_server" do
  supports :status => false, :restart => true
  status_command "ps -ef | grep [c]ycle_server"
  action [ :start, :enable ]
end


text:
package org.apache.wiki.htmltowiki.syntax.markdown;

import org.apache.wiki.htmltowiki.XHtmlElementToWikiTranslator;
import org.apache.wiki.htmltowiki.syntax.DlDecorator;

import java.io.PrintWriter;

/**
 * Markdown syntax implementation of {@link DlDecorator}.
 */
class MarkdownDlDecorator extends DlDecorator {

    MarkdownDlDecorator( final PrintWriter out, final XHtmlElementToWikiTranslator chain ) {
        super( out, chain );
    }

    /** {@inheritDoc} */
    @Override
    protected String markupDlOpen() {
        return "\n";
    }

    /** {@inheritDoc} */
    @Override
    protected String markupDlClose() {
        return "\n";
    }

}


text:
.. _level: ../../vim/SharesInfo.rst#level

.. _shares: ../../vim/SharesInfo.rst#shares

.. _vim.SharesInfo: ../../vim/SharesInfo.rst

.. _vim.SharesInfo.Level: ../../vim/SharesInfo/Level.rst

.. _networkResourcePoolHighShareValue: ../../vim/DistributedVirtualSwitch/FeatureCapability.rst#networkResourcePoolHighShareValue

vim.SharesInfo.Level
====================
  Simplified shares notation. These designations have different meanings for different resources.
  :contained by: `vim.SharesInfo`_

  :type: `vim.SharesInfo.Level`_

  :name: custom

values:
--------

high
   For CPU: Shares = 2000 * nmumber of virtual CPUsFor Memory: Shares = 20 * virtual machine memory size in megabytesFor Disk: Shares = 2000For Network: Shares = `networkResourcePoolHighShareValue`_

custom
   If you specifycustomfor the `level`_ property, when there is resource contention the Server uses the `shares`_ value to determine resource allocation.

low
   For CPU: Shares = 500 * number of virtual CPUsFor Memory: Shares = 5 * virtual machine memory size in megabytesFor Disk: Shares = 500For Network: Shares = 0.25 * `networkResourcePoolHighShareValue`_

normal
   For CPU: Shares = 1000 * number of virtual CPUsFor Memory: Shares = 10 * virtual machine memory size in megabytesFor Disk: Shares = 1000For Network: Shares = 0.5 * `networkResourcePoolHighShareValue`_


text:
/*
  A Three.js 'Object3D' representing a cube where each inner face displays a
  tile of a cubic panorama. The textures of the faces are render targets and can
  be rendered to at will.
  'tiles' is a dictionary of images representing the faces of the cube.
  Keys are: north, west, south, east, top, bottom. North is the yaw rotation
  of 0 radians and rotation is counter-clockwise.
  Event: render
*/
demo.CubicPanorama = function CubicPanorama(renderer, size, tiles)
{
  var
    camera = new THREE.OrthographicCamera(-0.5, 0.5, 0.5, -0.5, -0.5, 0.5),
    geometry = new THREE.PlaneBufferGeometry(1, 1),
    light = new THREE.AmbientLight(0xbbbbbb),
    scene = new THREE.Scene(),
    drawingBoard = new THREE.Mesh(
      geometry,
      new THREE.MeshBasicMaterial({
        map: new THREE.Texture()
      })
    ),

    faces = {},

    tileKeys = ['north', 'west', 'south', 'east', 'bottom', 'top'];

  THREE.Object3D.apply(this);

  this.renderTargets = {};

  // 'tiles' are a dictionary of textures.
  this.setTiles = function setTiles(tiles)
  {
    renderer.setViewport(0, 0, size, size);

    _.each(
      tiles,
      function iteratee(texture, key)
      {
        drawingBoard.material.map = texture;

        renderer.render(scene, camera, this.renderTargets[key]);
      },
      this
    );

    this.dispatchEvent({type: 'render'});
  };

  // Set up container and textures for cubic projection panorama.
  _.each(
    tileKeys,
    function iteratee(key)
    {
      var target = new THREE.WebGLRenderTarget(
            size,
            size,
            {
              // Mipmaps aren't generated by perspective scaling.
              minFilter: THREE.LinearFilter
            }
          );

      this.renderTargets[key] = target;

      faces[key] = new THREE.Mesh(
        geometry,
        new THREE.MeshBasicMaterial({map: target})
      );

      this.add(faces[key]);
    },
    this
  );

  // Position cube faces.
  faces.north.position.z  = -0.5;

  faces.west.rotation.y   = Math.PI / 2;
  faces.west.position.x   = -0.5;

  faces.south.rotation.y  = Math.PI;
  faces.south.position.z  = 0.5;

  faces.east.rotation.y   = Math.PI * 3 / 2;
  faces.east.position.x   = 0.5;

  faces.bottom.rotation.x = Math.PI * 3 / 2;
  faces.bottom.position.y = -0.5;

  faces.top.rotation.x    = Math.PI / 2;
  faces.top.position.y    = 0.5;

  scene.add(light);
  scene.add(drawingBoard);

  if (tiles)
    this.setTiles(tiles);
};

demo.CubicPanorama.prototype = Object.create(THREE.Object3D.prototype);
demo.CubicPanorama.prototype.constructor = demo.CubicPanorama;


text:
#pragma once

#include "if.h"

#ifdef SUPPORT_MIDI

#include <mmsystem.h>
#include <vector>
#include "ringbuff.h"
#include "chip/chip.h"
#include "withlock.h"

namespace c86ctl{

class GimicMIDI : public GimicIF
{
private:
	GimicMIDI(HMIDIOUT h);

public:
	~GimicMIDI(void);

public:
	virtual int init(void);
	virtual void tick(void);
	virtual Chip* getChip(){ return chip; };
	virtual const GimicParam* getParam(){ return &gimicParam; };

public:
	// IGimic
	virtual int __stdcall setSSGVolume(UCHAR vol);
	virtual int __stdcall getSSGVolume(UCHAR *vol);
	virtual int __stdcall setPLLClock(UINT clock);
	virtual int __stdcall getPLLClock(UINT *clock);
	virtual int __stdcall getMBInfo(struct Devinfo *info);
	virtual int __stdcall getModuleInfo(struct Devinfo *info);
	virtual int __stdcall getFWVer( UINT *major, UINT *minor, UINT *rev, UINT *build );

public:
	// IRealChip
	virtual int __stdcall reset(void);
	virtual void __stdcall out(UINT addr, UCHAR data);
	virtual UCHAR __stdcall in( UINT addr );

public:
	// IRealChip2
	virtual int __stdcall getChipStatus( UINT addr, UCHAR *status );
	virtual void __stdcall directOut(UINT addr, UCHAR data){};

//	virtual int __stdcall adpcmZeroClear(void);
//	virtual int __stdcall adpcmWrite( UINT startAddr, UINT size, UCHAR *data );
//	virtual int __stdcall adpcmRead( UINT startAddr, UINT size, UCHAR *data );

private:
	void sendSysEx( uint8_t *data, uint32_t sz );

private:
	HMIDIOUT hHandle;
	CRingBuff<UCHAR> rbuff;

	Chip *chip;
	ChipType chiptype;
	GimicParam gimicParam;

public:
	//static std::vector< std::shared_ptr<GimicIF> > CreateInstances(void);
	static int UpdateInstances( withlock< std::vector< std::shared_ptr<GimicIF> > > &gimics);

};

typedef std::shared_ptr<GimicMIDI> GimicMIDIPtr;

};

#endif


text:
<?php
/*
 * Piklist Checker
 * Version: 0.6.2
 *
 * Verifies that Piklist is installed and activated.
 * If not:
 ** Your plugin will be deactivated and user will be notifed.
 ** Themes will show a notice.
 *
 * Developers:
 ** Instructions on how to use this file in your plugin can be found here:
 ** http://piklist.com/user-guide/docs/piklist-checker/
 *
 * Most recent version of this file can be found here:
 * http://s-plugins.wordpress.org/piklist/assets/class-piklist-checker.php
 */
if (!defined('ABSPATH')) exit; // Exit if accessed directly
if (!class_exists('Piklist_Checker'))
{
  class Piklist_Checker
  {
    private static $plugins = array();
    private static $type = null;
    private static $theme = false;
    private static $plugin_list = '';
    public static function admin_notices()
    {
      add_action('network_admin_notices', array('piklist_checker', 'show_message'));
      add_action('admin_notices', array('piklist_checker', 'show_message'));
    }
    public static function check($this_plugin, $checking = 'plugin')
    {
      global $pagenow;
      if ($pagenow == 'update.php' || $pagenow == 'update-core.php' || class_exists('Piklist'))
      {
        return true;
      }
      if($checking == 'plugin')
      {
        require_once(ABSPATH . '/wp-admin/includes/plugin.php');
        if (is_multisite())
        {
          if (is_plugin_active_for_network(plugin_basename($this_plugin)))
          {
            piklist_checker::deactivate_plugins($this_plugin, 'network');
          }
          else
          {
            piklist_checker::deactivate_plugins($this_plugin, 'single-network');
          }
        }
        else
        {
          piklist_checker::deactivate_plugins($this_plugin, 'single');
        }
      }
      else
      {
        piklist_checker::$theme = true;
        if (!empty(self::$type))
        {
          self::$type = 'single';
        }
      }
    }
    public static function deactivate_plugins($this_plugin, $type)
    {
      self::$type = $type;

      if (self::$type == 'single' || self::$type == 'single-network')
      {
        $plugins = get_option('active_plugins', array());
      }
      else
      {
        $plugins = array_flip(get_site_option('active_sitewide_plugins', array()));
      }
      if (!empty(self::$type))
      {
        self::$type = $type;
      }
      $this_plugin = str_replace('\\', '/',$this_plugin);
      foreach ($plugins as $plugin)
      {
        if (strstr($this_plugin, $plugin))
        {
          array_push(piklist_checker::$plugins, $this_plugin);

          deactivate_plugins($plugin);

          return false;
        }
      }
    }
    public static function message()
    {
      $piklist_file = 'piklist/piklist.php';
      $piklist_installed = false;
      if (array_key_exists($piklist_file, get_plugins()))
      {
        $piklist_installed = true;
      }
      $url_proper_dashboard = (self::$type == 'network' ? network_admin_url() : admin_url()) . 'plugins.php'; ?>

      <?php ob_start(); ?>

        <?php if(piklist_checker::$theme == true) : ?>

<?php _e('Your theme requires PIKLIST to work properly.', 'piklist'); ?>

        <?php endif; ?>

        <?php if(!empty(piklist_checker::$plugins)) : ?>

              <?php _e('The following plugin(s) require PIKLIST, and have been deactivated:', 'piklist'); ?>

              <?php foreach(piklist_checker::$plugins as $plugin): $data = get_plugin_data($plugin); ?>

                  <?php piklist_checker::$plugin_list = piklist_checker::$plugin_list . $data['Title'] . ', '; ?>

              <?php endforeach; ?>

              <?php echo rtrim(piklist_checker::$plugin_list, ", "); ?>

        <?php endif; ?>

<?php _e('You can:', 'piklist'); ?>

          <?php
            if ($piklist_installed):
              global $s;
              $context = 'all';
              if (self::$type == 'single' || self::$type == 'single-network'):
                $activate = '' . __('Activate Piklist for this site', 'piklist') . '';
                echo '
' . $activate . '
';
              endif;

              if ((self::$type == 'network' || self::$type == 'single-network') && is_multisite() && is_super_admin()):
                $activate = '' . __('Network Activate Piklist for all sites.', 'piklist') . '';
                echo '
' . $activate . '
';
              endif;
            else:
              $install = '' . __('Install Piklist', 'piklist') . '';
              echo '
' . $install . '
';
            endif;
            if(!empty(piklist_checker::$plugins)) :
              printf(__('%1$s %2$sDismiss this message.', 'piklist'),'
', '','', '
');
            else :
              printf(__('%1$s %2$sChange your theme.', 'piklist'),'
', '','', '
');

            endif;

          ?>

        <?php
          $message = ob_get_contents();
          ob_end_clean();

          return $message;
    }

    public static function show_message($message, $errormsg = true)
    {
      if (!empty(piklist_checker::$plugins) || piklist_checker::$theme == true) : ?>

              <?php echo piklist_checker::message(); ?>

      <?php endif;
    }
  }

  piklist_checker::admin_notices();
}
/*
 * Changelog
 *
 *

  = 0.6.2 =
 * Windows Server support
 = 0.6.1 =
 * Code refactor
 = 0.6.0 =
 * Faster checks.
 * Works with themes that support Piklist.
 = 0.5.1 =
 * Check if class Piklist exists instead of is_plugin_active.
 = 0.5.0 =
 * Now runs in the WordPress admin for a better user experience.
 = 0.4.2 =
 * Check if is_plugin_active_for_network function exists
 * Updated to Text Domain: Piklist
 = 0.4.1 =
 * Fixed Unterminated Comment Notice
 = 0.4.0 =
 * Multisite support
 = 0.3.0 =
 * Bugfix: deactivated plugin after Piklist was upgraded.
 = 0.2.0 =
 * Better messages when plugin is uninstalled
 = 0.1.0 =
 * Initial release
 */


text: export * from './users.service';


text:
ArduinOps
=========

All things Arduino at the Chattanooga Public Library.

## Resources
[Install Crouton](http://www.itworld.com/open-source/402077/how-run-linux-chromebook)

[Crouton](https://github.com/dnschneid/crouton)

[Arduino IDE](http://playground.arduino.cc/Linux/Ubuntu#.UyMMjHVdXKR)

[Arduino IDE on Ubuntu](http://tomwwolf.com/2013/11/26/howto-setup-arduino-on-chromebook/)


text:
namespace Ui
{
    class MainWindowClass;
}

// MainWindow is the root window of the app, containing the QWebView etc.
// Its only task defined here is the initial setup of those widgets.
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    // Construct a MainWindow in which the given url will be loaded. A custom
    // page can be injected, which will be passed on to the QWebView widget.
    MainWindow(const QUrl &url, QWebPage *custom_page = 0, QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindowClass *ui;
};

#endif // MAINWINDOW_H


text:
<?php

namespace phpDocumentor\Configuration;

use JMS\Serializer\Serializer;
use phpDocumentor\Console\Input\ArgvInput;

/**
 * Loads the template and user-defined configuration file from disk and creates a Configuration object from it.
 *
 * This class will merge the template file and the user-defined configuration file together and serialize it into a
 * configuration object (defaults to `phpDocumentor\Configuration`).
 */
class Loader
{
    /** @var Serializer Object used to serialize configuration files to objects. */
    private $serializer;

    /** @var Merger Object that merges variables, including objects. */
    private $merger;

    /**
     * Registers the dependencies with the loader.
     *
     * @param Serializer  $serializer Object used to serialize configuration files to objects.
     * @param Merger      $merger     Object that merges variables, including objects.
     */
    public function __construct(Serializer $serializer, Merger $merger)
    {
        $this->serializer = $serializer;
        $this->merger     = $merger;
    }

    /**
     * Loads the configuration from the provided paths and returns a populated configuration object.
     *
     * @param string $templatePath          Path to configuration file containing default settings.
     * @param string $userConfigurationPath Path to a file containing user overrides.
     * @param string $class                 The class to instantiate and populate with these options.
     *
     * @return object
     */
    public function load($templatePath, $userConfigurationPath, $class = 'phpDocumentor\Configuration')
    {
        $userConfigFilePath = $this->fetchUserConfigFileFromCommandLineOptions();

        if ($this->isValidFile($userConfigFilePath)) {
            chdir(dirname($userConfigFilePath));
        } else {
            $userConfigFilePath = null;
        }

        return $this->createConfigurationObject($templatePath, $userConfigurationPath, $userConfigFilePath, $class);
    }

    /**
     * Reads the `--config`, or `-c`, command line option and returns a path to the configuration file from those
     * options or false if no existing path was given.
     *
     * @return bool|string
     */
    private function fetchUserConfigFileFromCommandLineOptions()
    {
        $input = new ArgvInput();
        $userConfigFilePath = $input->getParameterOption('--config');

        if (!$userConfigFilePath) {
            $userConfigFilePath = $input->getParameterOption('-c');
        }

        if ($userConfigFilePath !== false) {
            $userConfigFilePath = realpath($userConfigFilePath);
        }

        return $userConfigFilePath;
    }

    /**
     * Verifies if the given path is valid and readable.
     *
     * @param bool|string $path
     *
     * @return bool
     */
    private function isValidFile($path)
    {
        return $path && $path != 'none' && is_readable($path);
    }

    /**
     * Combines the given configuration files and serializes a new Configuration object from them.
     *
     * @param string           $templatePath          Path to the template configuration file.
     * @param string           $defaultUserConfigPath Path to the phpdoc.xml or phpdoc,dist.xml in the current working
     *     directory.
     * @param null|bool|string $customUserConfigPath  Path to the user-defined config file given using the command-line.
     * @param string           $class                 Base Configuration class name to construct and populate.
     *
     * @return null|object
     */
    private function createConfigurationObject($templatePath, $defaultUserConfigPath, $customUserConfigPath, $class)
    {
        $config = $this->serializer->deserialize(file_get_contents($templatePath), $class, 'xml');
        $customUserConfigPath = $customUserConfigPath ? : $defaultUserConfigPath;

        if ($customUserConfigPath !== null && is_readable($customUserConfigPath)) {
            $userConfigFile = $this->serializer->deserialize(file_get_contents($customUserConfigPath), $class, 'xml');

            $config = $this->merger->run($config, $userConfigFile);
        }

        return $config;
    }
}


text:
package memcached

import (
	"bufio"
	"bytes"
	"crypto/tls"
	_ "embed"
	"fmt"
	"net"
	"strconv"
	"time"

	"golang.org/x/net/proxy"

	"github.com/influxdata/telegraf"
	tlsint "github.com/influxdata/telegraf/plugins/common/tls"
	"github.com/influxdata/telegraf/plugins/inputs"
)

//go:embed sample.conf
var sampleConfig string

// Memcached is a memcached plugin
type Memcached struct {
	Servers     []string `toml:"servers"`
	UnixSockets []string `toml:"unix_sockets"`
	EnableTLS   bool     `toml:"enable_tls"`
	tlsint.ClientConfig
}

var defaultTimeout = 5 * time.Second

// The list of metrics that should be sent
var sendMetrics = []string{
	"accepting_conns",
	"auth_cmds",
	"auth_errors",
	"bytes",
	"bytes_read",
	"bytes_written",
	"cas_badval",
	"cas_hits",
	"cas_misses",
	"cmd_flush",
	"cmd_get",
	"cmd_set",
	"cmd_touch",
	"conn_yields",
	"connection_structures",
	"curr_connections",
	"curr_items",
	"decr_hits",
	"decr_misses",
	"delete_hits",
	"delete_misses",
	"evicted_active",
	"evicted_unfetched",
	"evictions",
	"expired_unfetched",
	"get_expired",
	"get_flushed",
	"get_hits",
	"get_misses",
	"hash_bytes",
	"hash_is_expanding",
	"hash_power_level",
	"incr_hits",
	"incr_misses",
	"limit_maxbytes",
	"listen_disabled_num",
	"max_connections",
	"reclaimed",
	"rejected_connections",
	"store_no_memory",
	"store_too_large",
	"threads",
	"total_connections",
	"total_items",
	"touch_hits",
	"touch_misses",
	"uptime",
}

func (*Memcached) SampleConfig() string {
	return sampleConfig
}

// Gather reads stats from all configured servers accumulates stats
func (m *Memcached) Gather(acc telegraf.Accumulator) error {
	if len(m.Servers) == 0 && len(m.UnixSockets) == 0 {
		return m.gatherServer(":11211", false, acc)
	}

	for _, serverAddress := range m.Servers {
		acc.AddError(m.gatherServer(serverAddress, false, acc))
	}

	for _, unixAddress := range m.UnixSockets {
		acc.AddError(m.gatherServer(unixAddress, true, acc))
	}

	return nil
}

func (m *Memcached) gatherServer(
	address string,
	unix bool,
	acc telegraf.Accumulator,
) error {
	var conn net.Conn
	var err error
	var dialer proxy.Dialer

	dialer = &net.Dialer{Timeout: defaultTimeout}
	if m.EnableTLS {
		tlsCfg, err := m.ClientConfig.TLSConfig()
		if err != nil {
			return err
		}

		dialer = &tls.Dialer{
			NetDialer: dialer.(*net.Dialer),
			Config:    tlsCfg,
		}
	}

	if unix {
		conn, err = dialer.Dial("unix", address)
		if err != nil {
			return err
		}
		defer conn.Close()
	} else {
		_, _, err = net.SplitHostPort(address)
		if err != nil {
			address = address + ":11211"
		}

		conn, err = dialer.Dial("tcp", address)
		if err != nil {
			return err
		}
		defer conn.Close()
	}

	if conn == nil {
		return fmt.Errorf("Failed to create net connection")
	}

	// Extend connection
	if err := conn.SetDeadline(time.Now().Add(defaultTimeout)); err != nil {
		return err
	}

	// Read and write buffer
	rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))

	// Send command
	if _, err := fmt.Fprint(rw, "stats\r\n"); err != nil {
		return err
	}
	if err := rw.Flush(); err != nil {
		return err
	}

	values, err := parseResponse(rw.Reader)
	if err != nil {
		return err
	}

	// Add server address as a tag
	tags := map[string]string{"server": address}

	// Process values
	fields := make(map[string]interface{})
	for _, key := range sendMetrics {
		if value, ok := values[key]; ok {
			// Mostly it is the number
			if iValue, errParse := strconv.ParseInt(value, 10, 64); errParse == nil {
				fields[key] = iValue
			} else {
				fields[key] = value
			}
		}
	}
	acc.AddFields("memcached", fields, tags)
	return nil
}

func parseResponse(r *bufio.Reader) (map[string]string, error) {
	values := make(map[string]string)

	for {
		// Read line
		line, _, errRead := r.ReadLine()
		if errRead != nil {
			return values, errRead
		}
		// Done
		if bytes.Equal(line, []byte("END")) {
			break
		}
		// Read values
		s := bytes.SplitN(line, []byte(" "), 3)
		if len(s) != 3 || !bytes.Equal(s[0], []byte("STAT")) {
			return values, fmt.Errorf("unexpected line in stats response: %q", line)
		}

		// Save values
		values[string(s[1])] = string(s[2])
	}
	return values, nil
}

func init() {
	inputs.Add("memcached", func() telegraf.Input {
		return &Memcached{}
	})
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- vi: set et smarttab sw=4 tabstop=4: -->
<!--
MIT License

Copyright (c) 2016 Gabriel Robitaille-Montpetit

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.opendaylight.controller</groupId>
    <artifactId>config-parent</artifactId>
    <version>0.5.0-SNAPSHOT</version>
    <relativePath/>
  </parent>

  <groupId>org.opendaylight</groupId>
  <artifactId>scala-cup-impl</artifactId>
  <version>0.1.0-SNAPSHOT</version>
  <packaging>bundle</packaging>

  <properties>
    <scala.maven.plugin.version>3.2.1</scala.maven.plugin.version>
    <maven.compiler.plugin.version>2.0.2</maven.compiler.plugin.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>scala-cup-api</artifactId>
      <version>${project.version}</version>
    </dependency>

    <!-- Testing Dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
    </dependency>

    <dependency>
        <groupId>com.typesafe.akka</groupId>
        <artifactId>akka-actor_${scala.version}</artifactId>
    </dependency>

    <dependency>
        <groupId>com.typesafe.akka</groupId>
        <artifactId>akka-cluster_${scala.version}</artifactId>
    </dependency>

    <dependency>
        <groupId>com.typesafe.akka</groupId>
        <artifactId>akka-persistence_${scala.version}</artifactId>
    </dependency>

    <dependency>
        <groupId>com.typesafe.akka</groupId>
        <artifactId>akka-remote_${scala.version}</artifactId>
    </dependency>

    <dependency>
        <groupId>com.typesafe.akka</groupId>
        <artifactId>akka-testkit_${scala.version}</artifactId>
    </dependency>

    <dependency>
        <groupId>com.typesafe.akka</groupId>
        <artifactId>akka-slf4j_${scala.version}</artifactId>
    </dependency>

    <dependency>
        <groupId>com.typesafe.akka</groupId>
        <artifactId>akka-osgi_${scala.version}</artifactId>
    </dependency>

  </dependencies>

  <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>scala-maven-plugin</artifactId>
                    <version>${scala.maven.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven.compiler.plugin.version}</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>add-source</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>