text:
package redis.client.jedis;

import static org.testng.Assert.assertEquals;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import redis.client.jedis.spring.CustomShardedJedisPoolFactoryBean.PoolBehaviour;
import redis.client.util.RedisConfigUtils;
import redis.client.util.TestConfigUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.Response;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPipeline;
import redis.clients.jedis.exceptions.JedisException;

/**
 * Tests for {@link CustomShardedJedisPool}.
 *
 * @author huagang.li 2014年12月9日 上午9:33:00
 */
public class CustomShardedJedisPoolTest {

    private static final Logger    logger = LoggerFactory.getLogger(CustomShardedJedisPoolTest.class);

    private CustomShardedJedisPool shardedJedisPool;

    @BeforeClass
    public void init() throws InterruptedException {
        List<JedisShardInfo> shards = RedisConfigUtils.parseRedisServerList(TestConfigUtils.getRedisServers(),
                                                                            TestConfigUtils.getTimeoutMillis());

        GenericObjectPoolConfig poolConfig = new JedisPoolConfig();
        // 高并发压测
        poolConfig.setMaxTotal(TestConfigUtils.getMaxTotalNum());
        poolConfig.setMaxIdle(TestConfigUtils.getMaxIdleNum());
        // poolConfig.setMinIdle(TestConfigUtils.getMinIdleNum());
        poolConfig.setMinIdle(3); // local test
        // 对象池管理"池对象"的行为
        boolean lifo = TestConfigUtils.getPoolBehaviour() == PoolBehaviour.LIFO ? true : false;
        poolConfig.setLifo(lifo);
        // 非阻塞
        poolConfig.setBlockWhenExhausted(false);
        // 阻塞等待一段时间
        // poolConfig.setBlockWhenExhausted(true);
        // poolConfig.setMaxWaitMillis(TimeUnit.MILLISECONDS.toMillis(10L));

        // 关闭"在借用或返回池对象时,检测其有效性"(因为这样对性能影响较大)
        poolConfig.setTestOnBorrow(false);
        poolConfig.setTestOnReturn(false);

        /*
         * "Evictor驱逐者守护线程"相关配置,用它来检测"空闲对象"
         */
        poolConfig.setTestWhileIdle(true);
        // 每隔5秒钟执行一次,保证异常节点被及时探测到(具体隔多久调度一次,根据业务需求来定)
        // poolConfig.setTimeBetweenEvictionRunsMillis(TimeUnit.SECONDS.toMillis(TestConfigUtils.getTimeBetweenEvictionRunsSeconds()));
        poolConfig.setTimeBetweenEvictionRunsMillis(TimeUnit.SECONDS.toMillis(2L)); // local test
        // 关闭后台Evictor守护线程
        // poolConfig.setTimeBetweenEvictionRunsMillis(-1L); // local test
        // 每次检测的空闲对象个数
        // poolConfig.setNumTestsPerEvictionRun(TestConfigUtils.getNumTestsPerEvictionRun());
        poolConfig.setNumTestsPerEvictionRun(3); // local test
        // 当池对象的空闲时间超过该值时,就被纳入到驱逐检测范围
        poolConfig.setSoftMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(TestConfigUtils.getMinEvictableIdleTimeMinutes()));
        // 池的最小驱逐空闲时间(空闲驱逐时间)
        // 当池对象的空闲时间超过该值时,立马被驱逐
        poolConfig.setMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(TestConfigUtils.getMaxEvictableIdleTimeMinutes()));

        this.shardedJedisPool = new CustomShardedJedisPool(poolConfig, shards, (int) TimeUnit.SECONDS.toMillis(1), 2);
    }

    private static final String DEFAUL_VALUE = "1";

    private static final String RET_OK       = "OK";

    /**
     * 管道,用于执行一连串不同的命令。
     *

     * 特性:各个命令可以被发送到不同的服务器,但不保证所有命令的原子性
     *

     * 使用"管道"有更好的性能:以这种方式发送命令,无需等待响应,

     * 同时在最后才真正读取响应信息,这是非常快的。
     */
    @Test(description = "验证'有序集合结合管道(Pipeline)操作的功能'")
    public void pipeline() {
        String key = "pipeline";

        try {
            ShardedJedis jedis = shardedJedisPool.getResource();

            // 清空缓存数据
            jedis.del(key);

            ShardedJedisPipeline pipeline = jedis.pipelined();
            Response<Long> newElementNum = pipeline.zadd(key, System.currentTimeMillis(), "23");
            Map<String, Double> scoreMembers = new HashMap<>(4);
            scoreMembers.put("10", new Double(System.currentTimeMillis() + 1));
            scoreMembers.put("7", new Double(System.currentTimeMillis() + 2));
            pipeline.zadd(key, scoreMembers);
            Response<Long> elementNum = pipeline.zcard(key);
            pipeline.sync();

            jedis.close();

            assertEquals(newElementNum.get().intValue(), 1);
            assertEquals(elementNum.get().intValue(), 3);
        } catch (JedisException e) {
            logger.error(e.getMessage(), e);
        }

    }

    @Test(description = "验证\"自动摘除异常(宕机)的Redis服务器,自动添加恢复正常的Redis服务器\"功能")
    public void autoDetectBrokenRedisServer() throws InterruptedException {
        ShardedJedis jedis = null;
        JedisShardInfo shardInfo = null;
        String key = null;

        int size = 4;
        for (int i = 1; i <= size; i++) {
            key = "auto_detect_broken_redis_server_" + i;

            try {
                // 获取一条Redis连接
                jedis = shardedJedisPool.getResource();

                // log Shard info
                shardInfo = jedis.getShardInfo(key);
                logger.info("Shard Info: " + shardInfo);

                String statusCode = jedis.set(key, DEFAUL_VALUE);
                assertEquals(statusCode, RET_OK);
                // 返回连接到连接池
                jedis.close();

                // 关闭处理节点的服务端连接,模拟Redis服务器出现异常(宕机)的场景,便于驱逐者定时器自动摘除异常(宕机)的Redis服务器
                // 但只要请求一次命令又会重新连接上,模拟异常Redis服务器恢复正常的场景,便于驱逐者定时器自动添加恢复正常的Redis服务器
                if (1 == i) {
                    clientKill(jedis.getShard(key));
                }
            } catch (JedisException je) {
                String errorMsg = String.format("Failed to operate on '%s' Jedis Client", shardInfo);
                logger.warn(errorMsg, je);
            }

            logger.info("Complete time: {}", Integer.valueOf(i));
            if (i < size) {
                TimeUnit.SECONDS.sleep(2L);
            }
        }
    }

    private static final String DEAD_SERVER_CLIENT_NAME = "DEAD";

    /**
     * 关闭一个给定的客户端连接。
     *
     * @param jedis
     */
    public static void clientKill(Jedis jedis) {
        jedis.clientSetname(DEAD_SERVER_CLIENT_NAME);

        // CLIENT LIST (返回连接到这台服务器的所有客户端的信息和统计数据) - http://redis.io/commands/client-list
        // CLIENT LIST (多了name字段):
        // "id=4 addr=127.0.0.1:50946 fd=6 name=DEAD age=0 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 events=r cmd=client"
        for (String clientInfo : jedis.clientList().split("\n")) {
            if (clientInfo.contains(DEAD_SERVER_CLIENT_NAME)) {
                for (String field : clientInfo.split(" ")) {
                    if (field.contains("addr")) {
                        String hostAndPort = field.split("=")[1];
                        // It would be better if we kill the client by Id (CLIENT KILL ID client-id) as it's safer but
                        // Jedis doesn't implement the command yet.
                        // CLIENT KILL (关闭一个给定的客户端连接) - http://redis.io/commands/client-kill
                        jedis.clientKill(hostAndPort);
                    }
                }
            }
        }
    }

    /**
     * 注意:将{@link GenericObjectPoolConfig#setTimeBetweenEvictionRunsMillis(long)}设置为500L。

     * 正常情况下,1和3落到6381端口,2、4和5落到6380端口。
     *
     * @throws InterruptedException
     */
    @Test(enabled = false, description = "验证\"当集群中的某些节点出现异常(宕机)时,不影响其它节点数据的正常访问\"功能")
    public void accessOtherShardsNormally() throws InterruptedException {
        ShardedJedis jedis = null;
        JedisShardInfo shardInfo = null;
        String key = null;

        int size = 5;
        for (int i = 1; i <= size; i++) {
            key = "st_" + i;

            try {
                // 获取一条Redis连接
                jedis = shardedJedisPool.getResource();

                // log Shard info
                shardInfo = jedis.getShardInfo(key);
                logger.info("Shard Info: " + shardInfo);

                String statusCode = jedis.set(key, DEFAUL_VALUE);
                assertEquals(statusCode, RET_OK);
                // 返回连接到连接池
                jedis.close();

                // 关闭第一个被访问到的Redis服务器,模拟Redis服务器宕机的场景
                if (1 == i) {
                    Jedis client = jedis.getShard(key);
                    statusCode = client.shutdown();
                    assertEquals(statusCode, null); // 不返回任何响应信息
                }

            } catch (JedisException je) {
                String errorMsg = String.format("Failed to operate on '%s' Jedis Client", shardInfo);
                logger.warn(errorMsg, je);
            }

            logger.info("Complete time: {}", Integer.valueOf(i));
            if (i < size) {
                TimeUnit.SECONDS.sleep(3L);
            }
        }
    }

    /**
     *

     * 当正常节点出现异常被自动摘除后,原来落到该节点上的数据会自动转移到其它有效节点上;
     * 当异常节点恢复正常被自动添加后,原来落到该节点上的数据会重新映射回该节点上。
     *

     */
    @Test(enabled = false, description = "通过手动模拟(kill Redis服务器)来验证\"自动摘除异常(宕机)的Redis服务器,自动添加恢复正常的Redis服务器\"功能")
    public void manualDetectBrokenRedisServer() throws InterruptedException {
        ShardedJedis jedis = null;
        JedisShardInfo shardInfo = null;
        String key = null;

        int size = 7;
        for (int i = 1; i <= size; i++) {
            key = "st_" + i;

            // 获取一条Redis连接
            jedis = shardedJedisPool.getResource();

            // log Shard info
            shardInfo = jedis.getShardInfo(key);
            logger.info("Shard Info: " + shardInfo);

            try {
                String ret = jedis.set(key, "1");
                assertEquals(ret, RET_OK);
            } catch (JedisException e) {
                logger.error(e.getMessage(), e);
            }

            logger.info("Complete time: {}", Integer.valueOf(i));
            if (i < size) {
                TimeUnit.SECONDS.sleep(5L);
            }
        }
    }

    @AfterClass
    public void destroy() {
        if (shardedJedisPool != null) {
            shardedJedisPool.close();
        }
    }

}


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

<Profile xmlns="http://hl7.org/fhir">
  <text>
    <status value="generated"/>

Type definition for HumanName from FHIR Specification

  </text>
  <name value="Basic Profile for HumanName"/>
  <publisher value="FHIR Specification"/>
  <description value="Basic Profile for HumanName for validation support"/>
  <status value="draft"/>
  <date value="2014-02-03"/>
  <mapping>
    <identity value="rim"/>
    <uri value="http://hl7.org/v3"/>
    <name value="RIM"/>
  </mapping>
  <mapping>
    <identity value="v2"/>
    <uri value="http://hl7.org/v2"/>
    <name value="HL7 v2"/>
  </mapping>
  <mapping>
    <identity value="servd"/>
    <uri value="http://www.omg.org/spec/ServD/1.0/"/>
    <name value="ServD"/>
  </mapping>
  <structure>
    <type value="HumanName"/>
    <element>
      <path value="HumanName"/>
      <definition>
        <short value="Name of a human - parts and usage"/>
        <formal value="A human's name with the ability to identify parts and usage."/>
        <comments value="Names may be changed, or repudiated, or people may have different names in different contexts. Names may be divided into parts of different type that have variable significance depending on context, though the division into parts does not always matter. With personal names, the different parts may or may not be imbued with some implicit meaning; various cultures associate different importance with the name parts and the degree to which systems must care about name parts around the world varies widely."/>
        <min value="1"/>
        <max value="1"/>
        <type>

        </type>
        <isModifier value="false"/>
        <mapping>
          <identity value="rim"/>
          <map value="EN (actually, PN)"/>
        </mapping>
        <mapping>
          <identity value="v2"/>
          <map value="XPN"/>
        </mapping>
        <mapping>
          <identity value="servd"/>
          <map value="ProviderName"/>
        </mapping>
      </definition>
    </element>
    <element>
      <path value="HumanName.extension"/>
      <definition>
        <short value="Additional Content defined by implementations"/>
        <formal value="May be used to represent additional information that is not part of the basic definition of the resource. In order to make the use of extensions safe and manageable, there is a strict governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension."/>
        <comments value="there can be no stigma associated with the use of extensions by any application, project, or standard - regardless of the institution or jurisdiction that uses or defines the extensions.  The use of extensions is what allows the FHIR specification to retain a core simplicity for everyone."/>
        <synonym value="extensions"/>
        <synonym value="user content"/>
        <min value="0"/>
        <max value="*"/>
        <type>

        </type>
        <isModifier value="false"/>
      </definition>
    </element>
    <element>
      <path value="HumanName.modifierExtension"/>
      <definition>
        <short value="Extensions that cannot be ignored"/>
        <formal value="May be used to represent additional information that is not part of the basic definition of the resource, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions."/>
        <comments value="there can be no stigma associated with the use of extensions by any application, project, or standard - regardless of the institution or jurisdiction that uses or defines the extensions.  The use of extensions is what allows the FHIR specification to retain a core simplicity for everyone."/>
        <synonym value="extensions"/>
        <synonym value="user content"/>
        <min value="0"/>
        <max value="*"/>
        <type>

        </type>
        <isModifier value="false"/>
      </definition>
    </element>
    <element>
      <path value="HumanName.use"/>
      <definition>
        <short value="usual | official | temp | nickname | anonymous | old | maiden"/>
        <formal value="Identifies the purpose for this name."/>
        <comments value="This is labeled as "Is Modifier" because applications should not mistake a temporary or old name etc for a current/permanent one. Applications can assume that a name is current unless it explicitly says that it is temporary or old."/>
        <min value="0"/>
        <max value="1"/>
        <type>

        </type>
        <isModifier value="true"/>
        <binding>
          <name value="NameUse"/>
          <isExtensible value="false"/>
          <conformance value="required"/>
          <referenceResource>
            <reference value="http://hl7.org/fhir/name-use"/>
          </referenceResource>
        </binding>
        <mapping>
          <identity value="rim"/>
          <map value="unique(./use)"/>
        </mapping>
        <mapping>
          <identity value="v2"/>
          <map value="XPN.7, but often indicated by which field contains the name"/>
        </mapping>
        <mapping>
          <identity value="servd"/>
          <map value="./NamePurpose"/>
        </mapping>
      </definition>
    </element>
    <element>
      <path value="HumanName.text"/>
      <definition>
        <short value="Text representation of the full name"/>
        <formal value="A full text representation of the name."/>
        <comments value="Can provide both a text representation and structured parts."/>
        <min value="0"/>
        <max value="1"/>
        <type>

        </type>
        <isModifier value="false"/>
        <mapping>
          <identity value="rim"/>
          <map value="./formatted"/>
        </mapping>
        <mapping>
          <identity value="v2"/>
          <map value="implied by XPN.11"/>
        </mapping>
      </definition>
    </element>
    <element>
      <path value="HumanName.family"/>
      <definition>
        <short value="Family name (often called 'Surname')"/>
        <formal value="The part of a name that links to the genealogy. In some cultures (e.g. Eritrea) the family name of a son is the first name of his father."/>
        <comments value="For family name, hyphenated names such as "Smith-Jones" are a single name, but names with spaces such as "Smith Jones" are broken into multiple parts."/>
        <min value="0"/>
        <max value="*"/>
        <type>

        </type>
        <isModifier value="false"/>
        <mapping>
          <identity value="rim"/>
          <map value="./part[partType = FAM]"/>
        </mapping>
        <mapping>
          <identity value="v2"/>
          <map value="XPN.1"/>
        </mapping>
        <mapping>
          <identity value="servd"/>
          <map value="./FamilyName"/>
        </mapping>
      </definition>
    </element>
    <element>
      <path value="HumanName.given"/>
      <definition>
        <short value="Given names (not always 'first'). Includes middle names"/>
        <formal value="Given name."/>
        <comments value="If only initials are recorded, they may be used in place of the full name.  Not called "first name" since given names do not always come first."/>
        <min value="0"/>
        <max value="*"/>
        <type>

        </type>
        <isModifier value="false"/>
        <mapping>
          <identity value="rim"/>
          <map value="./part[partType = GIV]"/>
        </mapping>
        <mapping>
          <identity value="v2"/>
          <map value="XPN.2 + XPN.3"/>
        </mapping>
        <mapping>
          <identity value="servd"/>
          <map value="./GivenNames"/>
        </mapping>
      </definition>
    </element>
    <element>
      <path value="HumanName.prefix"/>
      <definition>
        <short value="Parts that come before the name"/>
        <formal value="Part of the name that is acquired as a title due to academic, legal, employment or nobility status, etc. and that appears at the start of the name."/>
        <min value="0"/>
        <max value="*"/>
        <type>

        </type>
        <isModifier value="false"/>
        <mapping>
          <identity value="rim"/>
          <map value="./part[partType = PFX]"/>
        </mapping>
        <mapping>
          <identity value="v2"/>
          <map value="XPN.5"/>
        </mapping>
        <mapping>
          <identity value="servd"/>
          <map value="./TitleCode"/>
        </mapping>
      </definition>
    </element>
    <element>
      <path value="HumanName.suffix"/>
      <definition>
        <short value="Parts that come after the name"/>
        <formal value="Part of the name that is acquired as a title due to academic, legal, employment or nobility status, etc. and that appears at the end of the name."/>
        <min value="0"/>
        <max value="*"/>
        <type>

        </type>
        <isModifier value="false"/>
        <mapping>
          <identity value="rim"/>
          <map value="./part[partType = SFX]"/>
        </mapping>
        <mapping>
          <identity value="v2"/>
          <map value="XPN/4"/>
        </mapping>
      </definition>
    </element>
    <element>
      <path value="HumanName.period"/>
      <definition>
        <short value="Time period when name was/is in use"/>
        <formal value="Indicates the period of time when this name was valid for the named person."/>
        <min value="0"/>
        <max value="1"/>
        <type>

        </type>
        <isModifier value="false"/>
        <mapping>
          <identity value="rim"/>
          <map value="./usablePeriod[type="IVL<TS>"]"/>
        </mapping>
        <mapping>
          <identity value="v2"/>
          <map value="XPN.13 + XPN.14"/>
        </mapping>
        <mapping>
          <identity value="servd"/>
          <map value="./StartDate and ./EndDate"/>
        </mapping>
      </definition>
    </element>
  </structure>
</Profile>

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  Child page
categories: HOWTO
weight:  100
parent:  navigation.html
---

This is a child page

{% children %}


text:
/* eslint-env mocha */
/* global expect, testContext */
/* eslint-disable prefer-arrow-callback, no-unused-expressions, max-nested-callbacks */
import Promise from 'bluebird'
import {RETROSPECTIVE_DESCRIPTOR} from 'src/common/models/surveyBlueprint'
import {Project, Survey} from 'src/server/services/dataService'
import {resetDB, expectSetEquality} from 'src/test/helpers'
import factory from 'src/test/factories'

import {
  ensureRetrospectiveSurveysExist,
} from '../ensureCycleReflectionSurveysExist'

describe(testContext(__filename), function () {
  beforeEach(resetDB)

  describe('ensureRetrospectiveSurveysExist', function () {
    beforeEach(async function () {
      this.cycle = await factory.create('cycle')
      this.createMembersAndProjects = async numMembersPerProject => {
        const numProjects = Math.min(numMembersPerProject, 2)
        const numMembersTotal = numProjects * numMembersPerProject
        this.phase = await factory.create('phase', {hasRetrospective: true})
        this.members = await factory.createMany('member', numMembersTotal, {chapterId: this.cycle.chapterId, phaseId: this.phase.id})
        this.projects = await Promise.all(Array.from(Array(numProjects).keys()).map(i => {
          return factory.create('project', {
            chapterId: this.cycle.chapterId,
            cycleId: this.cycle.id,
            phaseId: this.phase.id,
            memberIds: this.members
              .slice(i * numMembersPerProject, i * numMembersPerProject + numMembersPerProject)
              .map(p => p.id),
          })
        }))
      }
    })

    describe('when there is a retrospective surveyBlueprint with questions', function () {
      beforeEach(async function () {
        const teamQuestions = [await factory.create('question', {responseType: 'relativeContribution', subjectType: 'team'})]
        const memberQuestions = await factory.createMany('question', {responseType: 'likert7Agreement', subjectType: 'member'}, 2)
        const projectQuestions = await factory.createMany('question', {responseType: 'numeric', subjectType: 'project'}, 2)
        this.questions = teamQuestions.concat(memberQuestions).concat(projectQuestions)
        this.surveyBlueprint = await factory.create('surveyBlueprint', {
          descriptor: RETROSPECTIVE_DESCRIPTOR,
          defaultQuestionRefs: this.questions.map(q => ({questionId: q.id}))
        })
      })

      it('creates a survey for each project team with all of the default retro questions', async function () {
        const numMembersPerProject = 4
        await this.createMembersAndProjects(numMembersPerProject)
        await ensureRetrospectiveSurveysExist(this.cycle)

        await _itBuildsTheSurveyProperly(this.projects, this.questions)
      })

      it('ignores questions with a `responseType` of `relativeContribution` for single-member teams', async function () {
        const numMembersPerProject = 1
        await this.createMembersAndProjects(numMembersPerProject)
        await ensureRetrospectiveSurveysExist(this.cycle)

        await _itBuildsTheSurveyProperly(this.projects, this.questions, {shouldIncludeRelativeContribution: false})
      })

      describe('when there are other projects in the chapter but not in this cycle', function () {
        it('ignores them', async function () {
          const projectFromAnotherCycleBefore = await factory.create('project', {chapterId: this.cycle.chapterId})
          await ensureRetrospectiveSurveysExist(this.cycle)

          const projectFromAnotherCycleAfter = await Project.get(projectFromAnotherCycleBefore.id)
          expect(projectFromAnotherCycleAfter.retrospectiveSurveyId).to.deep.eq(projectFromAnotherCycleBefore.retrospectiveSurveyId)
          expect(projectFromAnotherCycleAfter.updatedAt).to.deep.eq(projectFromAnotherCycleBefore.updatedAt)
        })
      })

      it('creates any missing surveys when run multiple times', async function () {
        const numMembersPerProject = 4
        await this.createMembersAndProjects(numMembersPerProject)
        await ensureRetrospectiveSurveysExist(this.cycle)

        const firstProject = (await Project.filter({chapterId: this.cycle.chapterId, cycleId: this.cycle.id}))[0]
        const {retrospectiveSurveyId} = firstProject
        await Project.get(firstProject.id).update({retrospectiveSurveyId: null})
        await Survey.get(retrospectiveSurveyId).delete().execute()

        await ensureRetrospectiveSurveysExist(this.cycle)
        const replacedProject = await Project.get(firstProject.id)
        expect(replacedProject.retrospectiveSurveyId).to.exist
      })
    })

    describe('when there is no retrospective surveyBlueprint', function () {
      it('rejects the promise', async function () {
        const numMembersPerProject = 4
        await this.createMembersAndProjects(numMembersPerProject)
        return expect(ensureRetrospectiveSurveysExist(this.cycle)).to.be.rejected
      })
    })
  })
})

async function _itBuildsTheSurveyProperly(projects, questions, opts = null) {
  const options = opts || {shouldIncludeRelativeContribution: true}

  const tqFilter = options.shouldIncludeRelativeContribution ?
    question => question.subjectType === 'team' :
    question => question.subjectType === 'team' && question.responseType !== 'relativeContribution'
  const teamQuestions = questions.filter(tqFilter)
  const memberQuestions = questions.filter(_ => _.subjectType === 'member')
  const projectQuestions = questions.filter(_ => _.subjectType === 'project')
  const rcQuestions = questions.filter(_ => _.responseType === 'relativeContribution')

  const surveys = await Survey.run()
  expect(surveys).to.have.length(projects.length)

  const updatedProjects = await Project.getAll(...projects.map(p => p.id))
  updatedProjects.forEach(project => {
    const {memberIds, retrospectiveSurveyId, id: projectId} = project

    const survey = surveys.find(({id}) => id === retrospectiveSurveyId)
    expect(survey).to.exist

    let questionIds = questions.map(({id}) => id)
    questionIds = options.shouldIncludeRelativeContribution ?
      questionIds :
      questionIds.filter(questionId => !rcQuestions.find(rcQuestion => rcQuestion.id === questionId))

    const surveyRefIds = survey.questionRefs.map(({questionId}) => questionId)

    const refOffsets = surveyRefIds.map(refId => questionIds.indexOf(refId))
    expect(refOffsets).to.deep.equal(refOffsets.sort())

    expectSetEquality(questionIds, surveyRefIds)

    teamQuestions.forEach(question => {
      const refs = survey.questionRefs.filter(ref => ref.questionId === question.id)
      expect(refs).to.have.length(1)
      expect(refs[0].subjectIds.sort()).to.deep.eq(memberIds.sort())
    })

    const compareFirstElement = ([a], [b]) => a < b ? -1 : 1
    memberQuestions.forEach(question => {
      const refs = survey.questionRefs.filter(ref => ref.questionId === question.id)
      expect(refs).to.have.length(memberIds.length)
      expect(refs.map(ref => ref.subjectIds).sort(compareFirstElement))
       .to.deep.eq(memberIds.sort().map(id => [id]))
    })

    projectQuestions.forEach(question => {
      const refs = survey.questionRefs.filter(ref => ref.questionId === question.id)
      expect(refs).to.have.length(1)
      expect(refs[0].subjectIds.sort()).to.deep.eq([projectId])
    })

    rcQuestions.forEach(question => {
      const refs = survey.questionRefs.filter(ref => ref.questionId === question.id)
      const expectedNumRCQuestions = options.shouldIncludeRelativeContribution ? 1 : 0
      expect(refs).to.have.length(expectedNumRCQuestions)
      if (expectedNumRCQuestions > 0) {
        expect(refs[0].subjectIds.sort()).to.deep.eq(memberIds.sort())
      }
    })
  })
}


text:
#ifndef __AFXWIN_H__
	#error include 'stdafx.h' before including this file for PCH
#endif

#include "resource.h"		// main symbols

/////////////////////////////////////////////////////////////////////////////
// CPumpKINApp:
// See PumpKIN.cpp for the implementation of this class
//

class CPumpKINApp : public CWinApp
{
public:
	CString m_HelpFile;
	CPumpKINApp();

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CPumpKINApp)
	public:
	virtual BOOL InitInstance();
	//}}AFX_VIRTUAL

// Implementation

	//{{AFX_MSG(CPumpKINApp)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////


text:
CREATE TABLE working_hours (
  id int auto_increment,
  dayOfWeek int NOT NULL,
  start time NOT NULL,
  "end" time NOT NULL,
  employee_id int NOT NULL
);

ALTER TABLE working_hours
ADD CONSTRAINT FK_workinghours_employee FOREIGN KEY (employee_id) REFERENCES employee(id);

INSERT INTO working_hours(dayOfWeek, start, "end", employee_id)
SELECT 1, '08:00', CONCAT(workHoursPerDay + 8, ':00'), id FROM employee;
INSERT INTO working_hours(dayOfWeek, start, "end", employee_id)
SELECT 2, '08:00', CONCAT(workHoursPerDay + 8, ':00'), id FROM employee;
INSERT INTO working_hours(dayOfWeek, start, "end", employee_id)
SELECT 3, '08:00', CONCAT(workHoursPerDay + 8, ':00'), id FROM employee;
INSERT INTO working_hours(dayOfWeek, start, "end", employee_id)
SELECT 4, '08:00', CONCAT(workHoursPerDay + 8, ':00'), id FROM employee;
INSERT INTO working_hours(dayOfWeek, start, "end", employee_id)
SELECT 5, '08:00', CONCAT(workHoursPerDay + 8, ':00'), id FROM employee;

ALTER TABLE employee
DROP COLUMN workHoursPerDay;


text:
class FooListener {
public:
    virtual ~FooListener() {}

    virtual void foo() = 0;
};


text:
class SoftwareServo
{
  private:
    uint8_t pin;
    uint8_t angle;       // in degrees
    uint16_t pulse0;     // pulse width in TCNT0 counts
    uint8_t min16;       // minimum pulse, 16uS units  (default is 34)
    uint8_t max16;       // maximum pulse, 16uS units, 0-4ms range (default is 150)
    class SoftwareServo *next;
    static SoftwareServo* first;
  public:
    SoftwareServo();
    uint8_t attach(int);     // attach to a pin, sets pinMode, returns 0 on failure, won't
                             // position the servo until a subsequent write() happens
    void detach();
    void write(int);         // specify the angle in degrees, 0 to 180
    uint8_t read();
    uint8_t attached();
    void setMinimumPulse(uint16_t);  // pulse length for 0 degrees in microseconds, 540uS default
    void setMaximumPulse(uint16_t);  // pulse length for 180 degrees in microseconds, 2400uS default
    static void refresh();    // must be called at least every 50ms or so to keep servo alive
                              // you can call more often, it won't happen more than once every 20ms
};

#endif


text:
package com.alibaba.rocketmq.broker.processor;

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

import com.alibaba.rocketmq.broker.BrokerController;
import com.alibaba.rocketmq.common.constant.LoggerName;
import com.alibaba.rocketmq.remoting.netty.NettyRequestProcessor;
import com.alibaba.rocketmq.remoting.protocol.RemotingCommand;
import io.netty.channel.ChannelHandlerContext;

/**
 * 向Client转发请求,通常用于管理、监控、统计目的
 *
 * @author shijia.wxr<vintage.wang@gmail.com>
 * @since 2013-7-26
 */
public class ForwardRequestProcessor implements NettyRequestProcessor {
    private static final Logger log = LoggerFactory.getLogger(LoggerName.BrokerLoggerName);

    private final BrokerController brokerController;

    public ForwardRequestProcessor(final BrokerController brokerController) {
        this.brokerController = brokerController;
    }

    @Override
    public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) {
        // TODO Auto-generated method stub
        return null;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Eesti NSV Tead. Akad. Toim. , Biol. seer 16(4): 393 (1967)

#### Original name
Tubulicrinis orientalis Parmasto

### Remarks
null


text:
import sys

from django.conf import settings
from django.core.management import execute_from_command_line

if not settings.configured:
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
            }
        },
        MIDDLEWARE_CLASSES=(
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'django.contrib.redirects.middleware.RedirectFallbackMiddleware'
        ),
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.admin',
            'django.contrib.redirects',

            'opps.core',
            'opps.containers',
            'opps.archives',
            'opps.channels',
            'opps.boxes',
            'opps.sitemaps',
            'opps.articles',
            'opps.sources',
            'opps.images',
            'opps.flatpages',

            'opps.timelinejs',

        ),
        SITE_ID = 1,
        ROOT_URLCONF = "opps.urls",
        TEST_RUNNER = 'django_coverage.coverage_runner.CoverageRunner',
        HAYSTACK_CONNECTIONS = {
            'default': {
                'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'
            }
        }
    )

def runtests():
    argv = [sys.argv[0], 'test', 'timelinejs']
    execute_from_command_line(argv)
    sys.exit(0)

if __name__ == '__main__':
    runtests()


text:
package org.opengroup.osdu.workflow.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.internal.cfg.context.DefaultConstraintMapping;
import org.hibernate.validator.spi.cfg.ConstraintMappingContributor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class ValidationConfiguration {

  private final List<ConstraintMappingContributor> contributors;

  public ValidationConfiguration(Optional<List<ConstraintMappingContributor>> contributors) {
    this.contributors = contributors.orElseGet(ArrayList::new);
  }

  @Bean
  public LocalValidatorFactoryBean validatorFactory() {
    return new ValidatorFactoryBean(this.contributors);
  }

  public static class ValidatorFactoryBean extends LocalValidatorFactoryBean {

    private final List<ConstraintMappingContributor> contributors;

    ValidatorFactoryBean(List<ConstraintMappingContributor> contributors) {
      this.contributors = contributors;
    }

    @Override
    protected void postProcessConfiguration(javax.validation.Configuration<?> cfg) {
      if (cfg instanceof HibernateValidatorConfiguration) {
        HibernateValidatorConfiguration configuration = (HibernateValidatorConfiguration) cfg;
        this.contributors.forEach(contributor -> contributor.createConstraintMappings(() -> {
          DefaultConstraintMapping mapping = new DefaultConstraintMapping();
          configuration.addMapping(mapping);
          return mapping;
        }));
      }
    }
  }

}


text:
#define _GNU_SOURCE
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <inttypes.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include "lookup.h"

#define ALIGN (sizeof(struct { char a; char *b; }) - sizeof(char *))

int getservbyname_r(const char *name, const char *prots,
	struct servent *se, char *buf, size_t buflen, struct servent **res)
{
	struct service servs[MAXSERVS];
	int cnt, proto, align;

	*res = 0;

	/* Don't treat numeric port number strings as service records. */
	char *end = "";
	strtoul(name, &end, 10);
	if (!*end) return ENOENT;

	/* Align buffer */
	align = -(uintptr_t)buf & ALIGN-1;
	if (buflen < 2*sizeof(char *)+align)
		return ERANGE;
	buf += align;

	if (!prots) proto = 0;
	else if (!strcmp(prots, "tcp")) proto = IPPROTO_TCP;
	else if (!strcmp(prots, "udp")) proto = IPPROTO_UDP;
	else return EINVAL;

	cnt = __lookup_serv(servs, name, proto, 0, 0);
	if (cnt<0) switch (cnt) {
	case EAI_MEMORY:
	case EAI_SYSTEM:
		return ENOMEM;
	default:
		return ENOENT;
	}

	se->s_name = (char *)name;
	se->s_aliases = (void *)buf;
	se->s_aliases[0] = se->s_name;
	se->s_aliases[1] = 0;
	se->s_port = htons(servs[0].port);
	se->s_proto = servs[0].proto == IPPROTO_TCP ? "tcp" : "udp";

	*res = se;
	return 0;
}


text:
hook.Add( "CalcView", "TopDown", function( ply, pos, ang )

	local view = {}
	view.origin = pos + Vector( 0, 0, 100 )
	view.angles = Angle( 90, ang.y, 0 )
	view.drawviewer = true

	return view

end )


text:
@interface Mp3PlayerButton : UIButton
{
    NSURL *_mp3URL;
    CGFloat _progress;
    CGRect _outerCircleRect;
	CGRect _innerCircleRect;

    CGFloat _r;
	CGFloat _g;
	CGFloat _b;
	CGFloat _a;
}

@property(nonatomic,strong) NSURL *mp3URL;
@property(nonatomic,strong) UIImage *playImage;
@property(nonatomic,strong) UIImage *pauseImage;
-(void) setProgress:(CGFloat) newProgress;

@end


text:
const express = require('express');
const Joi = require('joi');
const bodyParser = require('body-parser');
const { validate, ValidationError } = require('../lib/index');

const loginValidation = {
  body: Joi.object({
    email: Joi.string()
      .email()
      .required(),
    password: Joi.string()
      .regex(/[a-zA-Z0-9]{3,30}/)
      .required(),
  }),
};

const userValidation = {
  params: Joi.object({
    id: Joi.number()
      .required(),
  }),
};

const app = express();
app.use(bodyParser.json());

app.post('/login', validate(loginValidation, {}, {}), (req, res) => {
  res.json(200);
});

app.get('/user/:id', validate(userValidation, {}, {}), (req, res) => {
  res.json(200);
});

app.use((err, req, res, next) => {
  if (err instanceof ValidationError) {
    return res.status(err.statusCode).json(err);
  }

  return res.status(500).json(err);
});

app.listen(3000);


text:
void sendint(long value);
void sendbuf(char* text);
void snewline();
void printbits(unsigned int val,char nbits);
void sendbyte(char data);

#endif // SERIO_H_INCLUDED


text:
package com.cloud.network.nicira;

public class VifAttachment extends Attachment {
    private final String type = "VifAttachment";
    private String vif_uuid;

    public VifAttachment() {
    }

    public VifAttachment(String vifUuid) {
        this.vif_uuid = vifUuid;
    }

    public String getVif_uuid() {
        return vif_uuid;
    }

    public void setVif_uuid(String vif_uuid) {
        this.vif_uuid = vif_uuid;
    }

    public String getType() {
        return type;
    }

}


text:
try:
    from urllib.parse import quote  # Py 3
except ImportError:
    from urllib2 import quote  # Py 2
import os
import sys

c = get_config()
c.NbConvertApp.export_format = 'markdown'
c.MarkdownExporter.template_file = 'jekyll-post'
c.Exporter.file_extension = '.md'

def path2url(path):
    """Turn a file path into a URL"""
    parts = path.split(os.path.sep)
    return '{{ site.baseurl }}/notebooks/' + '/'.join(quote(part) for part in parts)

c.MarkdownExporter.filters = {'path2url': path2url}


text:
people = 30
cars = 40
buses = 15

if cars > people:
  print "We should take the cars."
elif cars <people:
  print "We should not take the cars."
else:
  print "We can't bloody decide!"

if buses > cars:
  print "That's too many buses!"
elif buses < cars:
  print "Maybe we could take the buses."
else:
  print "We still can't even decide! ZOMG"

if people > buses:
  print "Alright, let's just take the buses."
else:
  print "Fine, let's stay home then. Jeez"