text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Batch;
using Microsoft.Azure.Test;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using System.Collections.Generic;
using System.Management.Automation;
using Xunit;
using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants;

namespace Microsoft.Azure.Commands.Batch.Test.ScenarioTests
{
    public class WorkItemTests
    {
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestNewWorkItem()
        {
            BatchController controller = BatchController.NewInstance;
            string resourceGroupName = "test-new-wi";
            string accountName = "testnewwi";
            string location = "eastus";
            BatchAccountContext context = null;
            controller.RunPsTestWorkflow(
                () => { return new string[] { string.Format("Test-NewWorkItem '{0}'", accountName) }; },
                () =>
                {
                    context = ScenarioTestHelpers.CreateTestAccountAndResourceGroup(controller, resourceGroupName, accountName, location);
                },
                () =>
                {
                    ScenarioTestHelpers.CleanupTestAccount(controller, resourceGroupName, accountName);
                },
                TestUtilities.GetCallingClass(),
                TestUtilities.GetCurrentMethodName());
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestGetWorkItemByName()
        {
            BatchController controller = BatchController.NewInstance;
            string resourceGroupName = "test-get-wi";
            string accountName = "testgetwi";
            string location = "eastus";
            string workItemName = "testName";
            BatchAccountContext context = null;
            controller.RunPsTestWorkflow(
                () => { return new string[] { string.Format("Test-GetWorkItemByName '{0}' '{1}'", accountName, workItemName) }; },
                () =>
                {
                    context = ScenarioTestHelpers.CreateTestAccountAndResourceGroup(controller, resourceGroupName, accountName, location);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName);
                },
                () =>
                {
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName);
                    ScenarioTestHelpers.CleanupTestAccount(controller, resourceGroupName, accountName);
                },
                TestUtilities.GetCallingClass(),
                TestUtilities.GetCurrentMethodName());
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestListWorkItemsByFilter()
        {
            BatchController controller = BatchController.NewInstance;
            string resourceGroupName = "test-list-wi-filter";
            string accountName = "testlistwifilter";
            string location = "eastus";
            string workItemName1 = "testName1";
            string workItemName2 = "testName2";
            string workItemName3 = "thirdtestName";
            string workItemPrefix = "testName";
            int matches = 2;
            BatchAccountContext context = null;
            controller.RunPsTestWorkflow(
                () => { return new string[] { string.Format("Test-ListWorkItemsByFilter '{0}' '{1}' '{2}'", accountName, workItemPrefix, matches) }; },
                () =>
                {
                    context = ScenarioTestHelpers.CreateTestAccountAndResourceGroup(controller, resourceGroupName, accountName, location);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName1);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName2);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName3);
                },
                () =>
                {
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName1);
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName2);
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName3);
                    ScenarioTestHelpers.CleanupTestAccount(controller, resourceGroupName, accountName);
                },
                TestUtilities.GetCallingClass(),
                TestUtilities.GetCurrentMethodName());
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestListWorkItemsWithMaxCount()
        {
            BatchController controller = BatchController.NewInstance;
            string resourceGroupName = "test-list-wi-maxcount";
            string accountName = "testlistwimaxcount";
            string location = "eastus";
            string workItemName1 = "testName1";
            string workItemName2 = "testName2";
            string workItemName3 = "thirdtestName";
            int maxCount = 1;
            BatchAccountContext context = null;
            controller.RunPsTestWorkflow(
                () => { return new string[] { string.Format("Test-ListWorkItemsWithMaxCount '{0}' '{1}'", accountName, maxCount) }; },
                () =>
                {
                    context = ScenarioTestHelpers.CreateTestAccountAndResourceGroup(controller, resourceGroupName, accountName, location);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName1);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName2);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName3);
                },
                () =>
                {
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName1);
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName2);
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName3);
                    ScenarioTestHelpers.CleanupTestAccount(controller, resourceGroupName, accountName);
                },
                TestUtilities.GetCallingClass(),
                TestUtilities.GetCurrentMethodName());
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestListAllWorkItems()
        {
            BatchController controller = BatchController.NewInstance;
            string resourceGroupName = "test-list-wi";
            string accountName = "testlistwi";
            string location = "eastus";
            string workItemName1 = "testName1";
            string workItemName2 = "testName2";
            string workItemName3 = "thirdtestName";
            int count = 3;
            BatchAccountContext context = null;
            controller.RunPsTestWorkflow(
                () => { return new string[] { string.Format("Test-ListAllWorkItems '{0}' '{1}'", accountName, count) }; },
                () =>
                {
                    context = ScenarioTestHelpers.CreateTestAccountAndResourceGroup(controller, resourceGroupName, accountName, location);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName1);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName2);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName3);
                },
                () =>
                {
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName1);
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName2);
                    ScenarioTestHelpers.DeleteWorkItem(controller, context, workItemName3);
                    ScenarioTestHelpers.CleanupTestAccount(controller, resourceGroupName, accountName);
                },
                TestUtilities.GetCallingClass(),
                TestUtilities.GetCurrentMethodName());
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestDeleteWorkItem()
        {
            BatchController controller = BatchController.NewInstance;
            string resourceGroupName = "test-delete-wi";
            string accountName = "testdeletewi";
            string location = "eastus";
            string workItemName = "testWorkItem";

            BatchAccountContext context = null;
            controller.RunPsTestWorkflow(
                () => { return new string[] { string.Format("Test-DeleteWorkItem '{0}' '{1}' '0'", accountName, workItemName) }; },
                () =>
                {
                    context = ScenarioTestHelpers.CreateTestAccountAndResourceGroup(controller, resourceGroupName, accountName, location);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName);
                },
                () =>
                {
                    ScenarioTestHelpers.CleanupTestAccount(controller, resourceGroupName, accountName);
                },
                TestUtilities.GetCallingClass(),
                TestUtilities.GetCurrentMethodName());
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestDeleteWorkItemPipeline()
        {
            BatchController controller = BatchController.NewInstance;
            string resourceGroupName = "test-delete-wi-pipe";
            string accountName = "testdeletewipipe";
            string location = "eastus";
            string workItemName = "testWorkItem";

            BatchAccountContext context = null;
            controller.RunPsTestWorkflow(
                () => { return new string[] { string.Format("Test-DeleteWorkItem '{0}' '{1}' '1'", accountName, workItemName) }; },
                () =>
                {
                    context = ScenarioTestHelpers.CreateTestAccountAndResourceGroup(controller, resourceGroupName, accountName, location);
                    ScenarioTestHelpers.CreateTestWorkItem(controller, context, workItemName);
                },
                () =>
                {
                    ScenarioTestHelpers.CleanupTestAccount(controller, resourceGroupName, accountName);
                },
                TestUtilities.GetCallingClass(),
                TestUtilities.GetCurrentMethodName());
        }
    }

    // Cmdlets that use the HTTP Recorder interceptor for use with scenario tests
    [Cmdlet(VerbsCommon.Get, "AzureBatchWorkItem_ST", DefaultParameterSetName = Constants.ODataFilterParameterSet)]
    public class GetBatchWorkItemScenarioTestCommand : GetBatchWorkItemCommand
    {
        public override void ExecuteCmdlet()
        {
            AdditionalBehaviors = new List<BatchClientBehavior>() { ScenarioTestHelpers.CreateHttpRecordingInterceptor() };
            base.ExecuteCmdlet();
        }
    }

    [Cmdlet(VerbsCommon.New, "AzureBatchWorkItem_ST")]
    public class NewBatchWorkItemScenarioTestCommand : NewBatchWorkItemCommand
    {
        public override void ExecuteCmdlet()
        {
            AdditionalBehaviors = new List<BatchClientBehavior>() { ScenarioTestHelpers.CreateHttpRecordingInterceptor() };
            base.ExecuteCmdlet();
        }
    }

    [Cmdlet(VerbsCommon.Remove, "AzureBatchWorkItem_ST")]
    public class RemoveBatchWorkItemScenarioTestCommand : RemoveBatchWorkItemCommand
    {
        public override void ExecuteCmdlet()
        {
            AdditionalBehaviors = new List<BatchClientBehavior>() { ScenarioTestHelpers.CreateHttpRecordingInterceptor() };
            base.ExecuteCmdlet();
        }
    }
}


text:
/* ----------------------------------------------------------------------
 * Project:      CMSIS DSP Library
 * Title:        arm_conv_opt_q7.c
 * Description:  Convolution of Q7 sequences
 *
 * $Date:        27. January 2017
 * $Revision:    V.1.5.1
 *
 * Target Processor: Cortex-M cores
 * -------------------------------------------------------------------- */
/*
 * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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
 *
 * 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.
 */

#include "arm_math.h"

/**
 * @ingroup groupFilters
 */

/**
 * @addtogroup Conv
 * @{
 */

/**
 * @brief Convolution of Q7 sequences.
 * @param[in] *pSrcA points to the first input sequence.
 * @param[in] srcALen length of the first input sequence.
 * @param[in] *pSrcB points to the second input sequence.
 * @param[in] srcBLen length of the second input sequence.
 * @param[out] *pDst points to the location where the output result is written.  Length srcALen+srcBLen-1.
 * @param[in]  *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
 * @param[in]  *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
 * @return none.
 *
 * \par Restrictions
 *  If the silicon does not support unaligned memory access enable the macro UNALIGNED_SUPPORT_DISABLE
 *	In this case input, output, scratch1 and scratch2 buffers should be aligned by 32-bit
 *
 * @details
 * Scaling and Overflow Behavior:
 *
 * \par
 * The function is implemented using a 32-bit internal accumulator.
 * Both the inputs are represented in 1.7 format and multiplications yield a 2.14 result.
 * The 2.14 intermediate results are accumulated in a 32-bit accumulator in 18.14 format.
 * This approach provides 17 guard bits and there is no risk of overflow as long as max(srcALen, srcBLen)<131072.
 * The 18.14 result is then truncated to 18.7 format by discarding the low 7 bits and then saturated to 1.7 format.
 *
 */

void arm_conv_opt_q7(
  q7_t * pSrcA,
  uint32_t srcALen,
  q7_t * pSrcB,
  uint32_t srcBLen,
  q7_t * pDst,
  q15_t * pScratch1,
  q15_t * pScratch2)
{

  q15_t *pScr2, *pScr1;                          /* Intermediate pointers for scratch pointers */
  q15_t x4;                                      /* Temporary input variable */
  q7_t *pIn1, *pIn2;                             /* inputA and inputB pointer */
  uint32_t j, k, blkCnt, tapCnt;                 /* loop counter */
  q7_t *px;                                      /* Temporary input1 pointer */
  q15_t *py;                                     /* Temporary input2 pointer */
  q31_t acc0, acc1, acc2, acc3;                  /* Accumulator */
  q31_t x1, x2, x3, y1;                          /* Temporary input variables */
  q7_t *pOut = pDst;                             /* output pointer */
  q7_t out0, out1, out2, out3;                   /* temporary variables */

  /* The algorithm implementation is based on the lengths of the inputs. */
  /* srcB is always made to slide across srcA. */
  /* So srcBLen is always considered as shorter or equal to srcALen */
  if (srcALen >= srcBLen)
  {
    /* Initialization of inputA pointer */
    pIn1 = pSrcA;

    /* Initialization of inputB pointer */
    pIn2 = pSrcB;
  }
  else
  {
    /* Initialization of inputA pointer */
    pIn1 = pSrcB;

    /* Initialization of inputB pointer */
    pIn2 = pSrcA;

    /* srcBLen is always considered as shorter or equal to srcALen */
    j = srcBLen;
    srcBLen = srcALen;
    srcALen = j;
  }

  /* pointer to take end of scratch2 buffer */
  pScr2 = pScratch2;

  /* points to smaller length sequence */
  px = pIn2 + srcBLen - 1;

  /* Apply loop unrolling and do 4 Copies simultaneously. */
  k = srcBLen >> 2U;

  /* First part of the processing with loop unrolling copies 4 data points at a time.
   ** a second loop below copies for the remaining 1 to 3 samples. */
  while (k > 0U)
  {
    /* copy second buffer in reversal manner */
    x4 = (q15_t) * px--;
    *pScr2++ = x4;
    x4 = (q15_t) * px--;
    *pScr2++ = x4;
    x4 = (q15_t) * px--;
    *pScr2++ = x4;
    x4 = (q15_t) * px--;
    *pScr2++ = x4;

    /* Decrement the loop counter */
    k--;
  }

  /* If the count is not a multiple of 4, copy remaining samples here.
   ** No loop unrolling is used. */
  k = srcBLen % 0x4U;

  while (k > 0U)
  {
    /* copy second buffer in reversal manner for remaining samples */
    x4 = (q15_t) * px--;
    *pScr2++ = x4;

    /* Decrement the loop counter */
    k--;
  }

  /* Initialze temporary scratch pointer */
  pScr1 = pScratch1;

  /* Fill (srcBLen - 1U) zeros in scratch buffer */
  arm_fill_q15(0, pScr1, (srcBLen - 1U));

  /* Update temporary scratch pointer */
  pScr1 += (srcBLen - 1U);

  /* Copy (srcALen) samples in scratch buffer */
  /* Apply loop unrolling and do 4 Copies simultaneously. */
  k = srcALen >> 2U;

  /* First part of the processing with loop unrolling copies 4 data points at a time.
   ** a second loop below copies for the remaining 1 to 3 samples. */
  while (k > 0U)
  {
    /* copy second buffer in reversal manner */
    x4 = (q15_t) * pIn1++;
    *pScr1++ = x4;
    x4 = (q15_t) * pIn1++;
    *pScr1++ = x4;
    x4 = (q15_t) * pIn1++;
    *pScr1++ = x4;
    x4 = (q15_t) * pIn1++;
    *pScr1++ = x4;

    /* Decrement the loop counter */
    k--;
  }

  /* If the count is not a multiple of 4, copy remaining samples here.
   ** No loop unrolling is used. */
  k = srcALen % 0x4U;

  while (k > 0U)
  {
    /* copy second buffer in reversal manner for remaining samples */
    x4 = (q15_t) * pIn1++;
    *pScr1++ = x4;

    /* Decrement the loop counter */
    k--;
  }

#ifndef UNALIGNED_SUPPORT_DISABLE

  /* Fill (srcBLen - 1U) zeros at end of scratch buffer */
  arm_fill_q15(0, pScr1, (srcBLen - 1U));

  /* Update pointer */
  pScr1 += (srcBLen - 1U);

#else

  /* Apply loop unrolling and do 4 Copies simultaneously. */
  k = (srcBLen - 1U) >> 2U;

  /* First part of the processing with loop unrolling copies 4 data points at a time.
   ** a second loop below copies for the remaining 1 to 3 samples. */
  while (k > 0U)
  {
    /* copy second buffer in reversal manner */
    *pScr1++ = 0;
    *pScr1++ = 0;
    *pScr1++ = 0;
    *pScr1++ = 0;

    /* Decrement the loop counter */
    k--;
  }

  /* If the count is not a multiple of 4, copy remaining samples here.
   ** No loop unrolling is used. */
  k = (srcBLen - 1U) % 0x4U;

  while (k > 0U)
  {
    /* copy second buffer in reversal manner for remaining samples */
    *pScr1++ = 0;

    /* Decrement the loop counter */
    k--;
  }

#endif

  /* Temporary pointer for scratch2 */
  py = pScratch2;

  /* Initialization of pIn2 pointer */
  pIn2 = (q7_t *) py;

  pScr2 = py;

  /* Actual convolution process starts here */
  blkCnt = (srcALen + srcBLen - 1U) >> 2;

  while (blkCnt > 0)
  {
    /* Initialze temporary scratch pointer as scratch1 */
    pScr1 = pScratch1;

    /* Clear Accumlators */
    acc0 = 0;
    acc1 = 0;
    acc2 = 0;
    acc3 = 0;

    /* Read two samples from scratch1 buffer */
    x1 = *__SIMD32(pScr1)++;

    /* Read next two samples from scratch1 buffer */
    x2 = *__SIMD32(pScr1)++;

    tapCnt = (srcBLen) >> 2U;

    while (tapCnt > 0U)
    {

      /* Read four samples from smaller buffer */
      y1 = _SIMD32_OFFSET(pScr2);

      /* multiply and accumlate */
      acc0 = __SMLAD(x1, y1, acc0);
      acc2 = __SMLAD(x2, y1, acc2);

      /* pack input data */
#ifndef ARM_MATH_BIG_ENDIAN
      x3 = __PKHBT(x2, x1, 0);
#else
      x3 = __PKHBT(x1, x2, 0);
#endif

      /* multiply and accumlate */
      acc1 = __SMLADX(x3, y1, acc1);

      /* Read next two samples from scratch1 buffer */
      x1 = *__SIMD32(pScr1)++;

      /* pack input data */
#ifndef ARM_MATH_BIG_ENDIAN
      x3 = __PKHBT(x1, x2, 0);
#else
      x3 = __PKHBT(x2, x1, 0);
#endif

      acc3 = __SMLADX(x3, y1, acc3);

      /* Read four samples from smaller buffer */
      y1 = _SIMD32_OFFSET(pScr2 + 2U);

      acc0 = __SMLAD(x2, y1, acc0);

      acc2 = __SMLAD(x1, y1, acc2);

      acc1 = __SMLADX(x3, y1, acc1);

      x2 = *__SIMD32(pScr1)++;

#ifndef ARM_MATH_BIG_ENDIAN
      x3 = __PKHBT(x2, x1, 0);
#else
      x3 = __PKHBT(x1, x2, 0);
#endif

      acc3 = __SMLADX(x3, y1, acc3);

      pScr2 += 4U;

      /* Decrement the loop counter */
      tapCnt--;
    }

    /* Update scratch pointer for remaining samples of smaller length sequence */
    pScr1 -= 4U;

    /* apply same above for remaining samples of smaller length sequence */
    tapCnt = (srcBLen) & 3U;

    while (tapCnt > 0U)
    {

      /* accumlate the results */
      acc0 += (*pScr1++ * *pScr2);
      acc1 += (*pScr1++ * *pScr2);
      acc2 += (*pScr1++ * *pScr2);
      acc3 += (*pScr1++ * *pScr2++);

      pScr1 -= 3U;

      /* Decrement the loop counter */
      tapCnt--;
    }

    blkCnt--;

    /* Store the result in the accumulator in the destination buffer. */
    out0 = (q7_t) (__SSAT(acc0 >> 7U, 8));
    out1 = (q7_t) (__SSAT(acc1 >> 7U, 8));
    out2 = (q7_t) (__SSAT(acc2 >> 7U, 8));
    out3 = (q7_t) (__SSAT(acc3 >> 7U, 8));

    *__SIMD32(pOut)++ = __PACKq7(out0, out1, out2, out3);

    /* Initialization of inputB pointer */
    pScr2 = py;

    pScratch1 += 4U;

  }

  blkCnt = (srcALen + srcBLen - 1U) & 0x3;

  /* Calculate convolution for remaining samples of Bigger length sequence */
  while (blkCnt > 0)
  {
    /* Initialze temporary scratch pointer as scratch1 */
    pScr1 = pScratch1;

    /* Clear Accumlators */
    acc0 = 0;

    tapCnt = (srcBLen) >> 1U;

    while (tapCnt > 0U)
    {
      acc0 += (*pScr1++ * *pScr2++);
      acc0 += (*pScr1++ * *pScr2++);

      /* Decrement the loop counter */
      tapCnt--;
    }

    tapCnt = (srcBLen) & 1U;

    /* apply same above for remaining samples of smaller length sequence */
    while (tapCnt > 0U)
    {

      /* accumlate the results */
      acc0 += (*pScr1++ * *pScr2++);

      /* Decrement the loop counter */
      tapCnt--;
    }

    blkCnt--;

    /* Store the result in the accumulator in the destination buffer. */
    *pOut++ = (q7_t) (__SSAT(acc0 >> 7U, 8));

    /* Initialization of inputB pointer */
    pScr2 = py;

    pScratch1 += 1U;

  }

}

/**
 * @} end of Conv group
 */

redpajama_set_name: RedPajamaGithub


text:
package jcraft.rebrain.mob;

import jcraft.rebrain.util.EntityCollisionHandler;
import net.minecraft.server.v1_8_R1.EntitySnowman;
import net.minecraft.server.v1_8_R1.World;

public class NoBrainSnowman extends EntitySnowman implements NoBrainEntity {

    public NoBrainSnowman(World world) {
        super(world);
    }

    int collisionCooldown = 4;

    @Override
    protected void bK() {
        if (collisionCooldown-- > 0) {
            return;
        }

        collisionCooldown = 4;

        EntityCollisionHandler.collide(this, true);
    }

    @Override
    public void setFromSpawner() {

    }

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

}


text:
"""
create user and role

Revision ID: 8036f244db77
Revises:
Create Date: 2017-10-11 17:22:00.467780
"""

from alembic import op
import sqlalchemy as sa

import backend

# revision identifiers, used by Alembic.
revision = '8036f244db77'
down_revision = None
branch_labels = ('security',)
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('role',
    sa.Column('id', sa.BigInteger(), nullable=False),
    sa.Column('created_at', backend.database.types.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.Column('updated_at', backend.database.types.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.Column('name', sa.String(length=50), nullable=False),
    sa.Column('description', sa.String(length=255), nullable=True),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_role'))
    )
    op.create_index(op.f('ix_role_name'), 'role', ['name'], unique=True)
    op.create_table('user',
    sa.Column('id', sa.BigInteger(), nullable=False),
    sa.Column('created_at', backend.database.types.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.Column('updated_at', backend.database.types.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.Column('username', sa.String(length=50), nullable=False),
    sa.Column('email', sa.String(length=50), nullable=False),
    sa.Column('first_name', sa.String(length=32), nullable=False),
    sa.Column('last_name', sa.String(length=64), nullable=False),
    sa.Column('password', sa.String(), nullable=True),
    sa.Column('active', sa.Boolean(name='active'), nullable=False),
    sa.Column('confirmed_at', backend.database.types.DateTime(timezone=True), nullable=True),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_user'))
    )
    op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
    op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)
    op.create_table('user_role',
    sa.Column('user_id', sa.BigInteger(), nullable=False),
    sa.Column('role_id', sa.BigInteger(), nullable=False),
    sa.ForeignKeyConstraint(['role_id'], ['role.id'], name=op.f('fk_user_role_role_id_role')),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], name=op.f('fk_user_role_user_id_user')),
    sa.PrimaryKeyConstraint('user_id', 'role_id', name=op.f('pk_user_role'))
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('user_role')
    op.drop_index(op.f('ix_user_username'), table_name='user')
    op.drop_index(op.f('ix_user_email'), table_name='user')
    op.drop_table('user')
    op.drop_index(op.f('ix_role_name'), table_name='role')
    op.drop_table('role')
    # ### end Alembic commands ###


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

    <dimen name="no_chat_small_margin">4dp</dimen>
    <dimen name="no_chat_very_small_margin">2dp</dimen>
    <dimen name="no_chat_bubble_radios">16dp</dimen>
    <dimen name="no_chat_middle_margin">8dp</dimen>
    <dimen name="no_chat_big_margin">16dp</dimen>
    <dimen name="no_chat_vertical_margin">16dp</dimen>
    <dimen name="no_chat_very_big_margin">60dp</dimen>
    <dimen name="no_chat_horizontal_margin">16dp</dimen>
    <dimen name="no_chat_input_text_size">17sp</dimen>
    <dimen name="no_chat_small_text_size">11sp</dimen>
    <dimen name="no_chat_very_small_text_size">8sp</dimen>
    <dimen name="no_chat_image_width">150dp</dimen>
    <dimen name="no_chat_image_height">250dp</dimen>
    <dimen name="no_chat_small_photo">40dp</dimen>

</resources>


text:
#pragma once

#include <malloc.h>
#include <ros/ros.h>
#include <serial/serial.h>

#include <memory>

using namespace serial;

class SerialInterface
{
private:
  using SerialPtr = std::unique_ptr<serial::Serial>;
  // baudrate
  int baud_;
  // connection related variables
  SerialPtr connection_port_;
  std::string port_;
  bool connected_ = false;
  // logger zone
  const std::string log_zone_;

public:
  SerialInterface(ros::NodeHandle &serial_nh_) : log_zone_("[ SerialInterface ] ")
  {
    serial_nh_.param<int>("BAUD_RATE", baud_, 115200);
    serial_nh_.param<std::string>("SERIAL_PORT", port_, "/dev/imu_top");
  }

  const int &getBaudRate()
  {
    return baud_;
  }

  /**
   * Destructor for the interface
   */
  const std::string &getSerialPort()
  {
    return port_;
  }

  /**
   * Returns true if connection is established with the serial port.
   *
   * @return true if connected to serial, false otherwise
   */
  bool isConnected()
  {
    return connected_;
  }

  /**
   * Destructor
   */
  ~SerialInterface()
  {
    if (connection_port_ != NULL)
    {
      if (connection_port_->isOpen())
      {
        ROS_INFO_STREAM(log_zone_ << " Closing the Serial Port");
        connection_port_->close();
        connected_ = false;
      }
    }
  }

  /**
   * Connects to the serial port.
   */
  void serialConnect()
  {
    try
    {
      const auto uint_baud = static_cast<uint32_t>(baud_);
      const auto timeout = Timeout::simpleTimeout(60000);  // timeout in milliseconds
      connection_port_.reset(new Serial(port_, baud_, timeout));
    }
    catch (IOException &e)
    {
      std::string ioerror = e.what();
      ROS_ERROR_STREAM(log_zone_ << "Unable to connect port: " << port_.c_str());
      ROS_ERROR_STREAM(log_zone_ << "Is the serial port open? : " << ioerror.c_str());
      connected_ = false;
    }

    if (connection_port_ && connection_port_->isOpen())
    {
      ROS_INFO_STREAM(log_zone_ << "Connection Established with Port: " << port_.c_str()
                                << " with baudrate: " << baud_);
      connected_ = true;
    }
  }

  /**
   * Writes a string to the serial port
   *
   * @param str The string to write to the serial port
   */
  inline void serialWriteString(const std::string &str)
  {
    connection_port_->write(str);
  }

  /**
   * Sets the timeout of read and write operations.
   *
   * @param timeout The desired timeout in milliseconds
   */
  void setTimeout(int timeout = 500)
  {
    Timeout t = Timeout::simpleTimeout((uint32_t)timeout);
    connection_port_->setTimeout(t);
  }

  /**
   * Gets the timeout of read operations.
   *
   * @return the current timeout of read operations in milliseconds
   */
  int getTimeout()
  {
    Timeout t = connection_port_->getTimeout();
    return t.read_timeout_constant;
  }

  /**
   * Flushes the read and write string buffers.
   */
  inline void flush()
  {
    connection_port_->flush();
  }

  /**
   * Flushes the read and write string buffers.
   *
   * @return the string read in from serial
   */
  inline std::string serialReadLine()
  {
    std::string str = connection_port_->readline();
    return str;
  }

  /**
   * Gets the number of available bytes
   *
   * @return the number of available bytes
   */
  inline size_t available()
  {
    return connection_port_->available();
  }
};


text:
.flip-container:hover .flipper,
.flip-container.hover .flipper {
  transform: rotateY(180deg);
}
.flip-container {
  perspective: 1000px;
}
.front,
.back {
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  position: absolute;
  top: 0px;
  left: 0px;
}
.flipper {
  transition: 0.65s;
  transform-style: preserve-3d;
  position: relative;
}
.front {
  z-index: 2;
}
.back {
  transform: rotateY(180deg);
}
.flip-container.vertical:hover .flipper.vertical,
.flip-container.vertical.hover .flipper.vertical {
  transform: rotateX(180deg);
}
.back.vertical {
  transform: rotateX(180deg);
}


text:
package edu.uci.ics.hyracks.api.application;

import edu.uci.ics.hyracks.api.context.IHyracksRootContext;
import edu.uci.ics.hyracks.api.lifecycle.ILifeCycleComponentManager;
import edu.uci.ics.hyracks.api.resources.memory.IMemoryManager;

/**
 * Application Context at the Node Controller for an application.
 *
 * @author vinayakb
 */
public interface INCApplicationContext extends IApplicationContext {
    /**
     * Gets the life cycle component manager of the Node Controller.
     *
     * @return
     */
    public ILifeCycleComponentManager getLifeCycleComponentManager();

    /**
     * Gets the node Id of the Node Controller.
     *
     * @return the Node Id.
     */
    public String getNodeId();

    /**
     * Get the Hyracks Root Context.
     *
     * @return The Hyracks Root Context
     */
    public IHyracksRootContext getRootContext();

    /**
     * Set an object that can be later retrieved by the {@link #getApplicationObject()} call.
     *
     * @param object
     *            Application Object
     */
    public void setApplicationObject(Object object);

    /**
     * Get the application object previously set by the {@link #setApplicationObject(Object)} call.
     *
     * @return Application Object
     */
    public Object getApplicationObject();

    /**
     * Get the memory manager at the node.
     *
     * @return Memory Manager
     */
    public IMemoryManager getMemoryManager();

    /**
     * Set the handler for state dumps.
     *
     * @param handler
     */
    public void setStateDumpHandler(IStateDumpHandler handler);
}


text:
      {% if page.title == 'home' %}

Community

Friends Of Cake is an awesome group of individuals working together to promote good standards in the CakePHP community and foster a team of friendly, supportive developers within the latter.

Commitment

We're building a collection of CakePHP plugins actively maintained by Friends Of Cake contributors who commit to follow quality standards set forward in our boarding requirements.

Contribute

Contributions like yours are our lifeblood. Have a plugin that would benefit the community? Once it meets the requirements, read the migration guide to learn how to prepare it for approval.

      {% else %}

      {% endif %}


text:
@implementation NSFileManager (MimeType)
#pragma mark - 类方法
+ (NSString *)getMIMETypeURLRequestAtFilePath:(NSString *)path {
    return [[NSFileManager defaultManager] getMIMETypeURLRequestAtPath:path];
}

+ (NSString *)getMIMETypeWithCAPIAtFilePath:(NSString *)path {
    return [[NSFileManager defaultManager] getMIMETypeWithCAPIAtFilePath:path];
}

#pragma mark - 对象方法
//向该文件发送请求,根据请求头拿到该文件的MIMEType
- (NSString *)getMIMETypeURLRequestAtPath:(NSString *)path {
    //1.确定请求路径
    NSURL *url = [NSURL fileURLWithPath:path];

    //2.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //3.发送请求
    NSHTTPURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    NSString *mimeType = response.MIMEType;
    return mimeType;
}

//调用C语言的API来获得文件的MIMEType ,只能获取本地文件哦,无法获取网络请求来的文件
- (NSString *)getMIMETypeWithCAPIAtFilePath:(NSString *)path {
    if (![self fileExistsAtPath:path]) {
        return nil;
    }

    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (MIMEType == nil) {
        return @"application/octet-stream";
    }
    NSString *result = (__bridge NSString *)(MIMEType);
    CFRelease(MIMEType);
    return result;
}
@end


text:
import lzw

cp_props_file_form = decls = '''\
// Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// Warning! This file is autogenerated.
#include <boost/text/detail/normalization_data.hpp>

#include <boost/text/detail/lzw.hpp>

#include <boost/assert.hpp>

#include <unordered_map>

namespace boost {{ namespace text {{ namespace detail {{

    std::array<uint32_t, {1}> make_all_canonical_decompositions()
    {{
return {{{{
{0}
    }}}};
    }}

    std::array<uint32_t, {3}> make_all_compatible_decompositions()
    {{
return {{{{
{2}
    }}}};
    }}

    namespace {{
        constexpr std::array<uint16_t, {5}> data()
        {{
        return {{{{
{4}
        }}}};
        }}
    }}

    std::unordered_map<uint32_t, cp_props> make_cp_props_map()
    {{
        std::unordered_map<uint32_t, cp_props> retval;
        container::small_vector<unsigned char, 256> buf;
        auto const & compressed = data();
        lzw_decompress(
            compressed.begin(),
            compressed.end(),
            lzw_to_cp_props_iter(retval, buf));
        BOOST_ASSERT(buf.empty());
        BOOST_ASSERT(retval.size() == {6});
        return retval;
    }}

}}}}}}
'''

compose_file_form = decls = '''\
// Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// Warning! This file is autogenerated.
#include <boost/text/detail/normalization_data.hpp>

#include <array>
#include <unordered_map>

namespace boost {{ namespace text {{ namespace detail {{

    namespace {{
        struct data_t {{ uint64_t key_; uint32_t value_; }};
        constexpr std::array<data_t, {1}> data()
        {{
        return {{{{
{0}
        }}}};
        }}
    }}

    std::unordered_map<uint64_t, uint32_t> make_composition_map()
    {{
        std::unordered_map<uint64_t, uint32_t> retval;
        for (auto datum : data()) {{
            retval[datum.key_] = datum.value_;
        }}
        return retval;
    }}

}}}}}}
'''

def cccs(filename):
    intervals = []
    lines = open(filename, 'r').readlines()
    for line in lines:
        line = line[:-1]
        if not line.startswith('#') and len(line) != 0:
            comment_start = line.find('#')
            comment = ''
            if comment_start != -1:
                comment = line[comment_start + 1:].strip()
                line = line[:comment_start]
            fields = map(lambda x: x.strip(), line.split(';'))
            ccc = fields[1]
            if ccc == '0':
                continue
            code_points = fields[0]
            if '..' in code_points:
                cps = code_points.split('.')
                interval = (int(cps[0], 16), int(cps[2], 16) + 1, ccc)
            else:
                cp = int(code_points, 16)
                interval = (cp, cp + 1, ccc)
            intervals.append(interval)

    intervals = sorted(intervals)
    intervals_list = ''
    cccs_dict = {}
    num_intervals = 0
    for interval in intervals:
        if False: #128 < interval[1] - interval[0]:
            num_intervals += 1
            intervals_list += '    ccc_interval{{{}, {}, {}}},\n'.format(
                hex(interval[0]), hex(interval[1]), interval[2]
            )
        else:
            for i in range(interval[0], interval[1]):
                cccs_dict[i] = interval[2]
    return cccs_dict

def expand_decomp_canonical(decomp, all_decomps):
    first_cp = decomp[0][0]
    if decomp[1] and first_cp in all_decomps and all_decomps[first_cp][1]:
        return expand_decomp_canonical((all_decomps[first_cp][0] + decomp[0][1:], True), all_decomps)
    return decomp

def expand_decomp_compatible(decomp, all_decomps):
    expandables = len(filter(lambda cp: cp in all_decomps, decomp[0]))
    if 0 < expandables:
        cps = map(lambda cp: cp in all_decomps and all_decomps[cp][0] or cp, decomp[0])
        flat_cps = []
        for cp in cps:
            if type(cp) == list:
                flat_cps += cp
            else:
                flat_cps.append(cp)
        return expand_decomp_compatible((flat_cps, True), all_decomps)
    return decomp

def get_decompositions(filename, cccs_dict, expand_decomp, canonical_only):
    decomps = {}

    # Pass 1: Find top-level decompositions
    lines = open(filename, 'r').readlines()
    for line in lines:
        line = line[:-1]
        if not line.startswith('#') and len(line) != 0:
            comment_start = line.find('#')
            comment = ''
            if comment_start != -1:
                comment = line[comment_start + 1:].strip()
                line = line[:comment_start]
            fields = map(lambda x: x.strip(), line.split(';'))
            if fields[5] == '':
                continue
            decomp_cps = fields[5].split(' ')
            canonical = True
            if decomp_cps[0].startswith('<'):
                decomp_cps = decomp_cps[1:]
                canonical = False
            decomp_cps = map(lambda x: int(x, 16), decomp_cps)
            cp = int(fields[0], 16)
            decomp = (decomp_cps, canonical)
            decomps[cp] = decomp

    # Pass 2: Expand Pass-1 decompositions
    expanded_decomps = map(
        lambda item: (item[0], expand_decomp(item[1], decomps)),
        sorted(decomps.items())
    )

    # Pass 3: Reorder Pass-2 decompositions uing cccs
    def reorder_cps(cps, cccs_dict):
        for i in range(1, len(cps) - 1):
            cp_a = cps[i]
            cp_b = cps[i + 1]
            # Each must be nonzero....
            if cp_a not in cccs_dict or cp_b not in cccs_dict:
                continue
            ccc_a = cccs_dict[cp_a]
            ccc_b = cccs_dict[cp_b]
            if ccc_b < ccc_a:
                cps[i] = cp_b
                cps[i + 1] = cp_a
        return cps

    decomps = map(
        lambda x: (x[0], (reorder_cps(x[1][0], cccs_dict), x[1][1])),
        expanded_decomps
    )

    all_cps = []
    final_decomps = []
    for k,v in decomps:
        if canonical_only and not v[1]:
            continue
        first = len(all_cps)
        all_cps += v[0]
        last = len(all_cps)
        final_decomps.append((k, (first, last)))

    return (all_cps, final_decomps)

def get_compositions(filename, derived_normalization_props_filename):
    comps = []

    exclusions = set()
    lines = open(derived_normalization_props_filename, 'r').readlines()
    for line in lines:
        line = line[:-1]
        if not line.startswith('#') and len(line) != 0:
            comment_start = line.find('#')
            comment = ''
            if comment_start != -1:
                comment = line[comment_start + 1:].strip()
                line = line[:comment_start]
            fields = map(lambda x: x.strip(), line.split(';'))
            prop = fields[1]
            if prop != 'Full_Composition_Exclusion':
                continue
            code_points = fields[0]
            if '..' in code_points:
                cps = code_points.split('.')
                interval = (int(cps[0], 16), int(cps[2], 16) + 1)
            else:
                cp = int(code_points, 16)
                interval = (cp, cp + 1)
            for cp in range(interval[0], interval[1]):
                exclusions.add(cp)

    lines = open(filename, 'r').readlines()
    for line in lines:
        line = line[:-1]
        if not line.startswith('#') and len(line) != 0:
            comment_start = line.find('#')
            comment = ''
            if comment_start != -1:
                comment = line[comment_start + 1:].strip()
                line = line[:comment_start]
            fields = map(lambda x: x.strip(), line.split(';'))
            if fields[5] == '':
                continue
            decomp_cps = fields[5].split(' ')
            if len(decomp_cps) != 2 or decomp_cps[0].startswith('<'):
                continue
            decomp_cps = map(lambda x: int(x, 16), decomp_cps)
            cp = int(fields[0], 16)
            if cp not in exclusions:
                comps.append((decomp_cps, cp))

    return sorted(comps)

def get_quick_checks(filename):
    retval = {'NFD': {}, 'NFC': {}, 'NFKD': {}, 'NFKC': {}}

    file_prop_to_enum = {'N': 'quick_check::no', 'M': 'quick_check::maybe'}

    lines = open(filename, 'r').readlines()
    for line in lines:
        line = line[:-1]
        if not line.startswith('#') and len(line) != 0:
            comment_start = line.find('#')
            comment = ''
            if comment_start != -1:
                comment = line[comment_start + 1:].strip()
                line = line[:comment_start]
            fields = map(lambda x: x.strip(), line.split(';'))
            prop = fields[1]
            if not prop.endswith('_QC'):
                continue
            normalization_form = prop.split('_')[0]
            code_points = fields[0]
            if '..' in code_points:
                cps = code_points.split('.')
                interval = (int(cps[0], 16), int(cps[2], 16) + 1)
            else:
                cp = int(code_points, 16)
                interval = (cp, cp + 1)
            for cp in range(interval[0], interval[1]):
                retval[normalization_form][cp] = file_prop_to_enum[fields[2]]

    return retval

if __name__ == "__main__":
    composition_mapping = get_compositions('UnicodeData.txt', 'DerivedNormalizationProps.txt')
    item_strings = map(
        lambda x : 'key({}, {}), {}'.format(hex(x[0][0]), hex(x[0][1]), hex(x[1])),
        composition_mapping
    )
    compositions_map = '    { ' + ' },\n    { '.join(item_strings) + ' },\n'

    cpp_file = open('normalization_data_compose.cpp', 'w')
    cpp_file.write(compose_file_form.format(compositions_map, len(item_strings)))

    cccs_dict = cccs('DerivedCombiningClass.txt')

    (canon_all_cps, canon_decomposition_mapping) = \
      get_decompositions('UnicodeData.txt', cccs_dict, expand_decomp_canonical, True)
    canon_decomposition_mapping = dict(canon_decomposition_mapping)
    (compat_all_cps, compat_decomposition_mapping) = \
      get_decompositions('UnicodeData.txt', cccs_dict, expand_decomp_compatible, False)
    compat_decomposition_mapping = dict(compat_decomposition_mapping)

    canon_all_cps_string = '    ' + ',\n    '.join(map(lambda x: hex(x), canon_all_cps)) + ',\n'
    compat_all_cps_string = '    ' + ',\n    '.join(map(lambda x: hex(x), compat_all_cps)) + ',\n'

    quick_check_maps = get_quick_checks('DerivedNormalizationProps.txt')

    all_cps = set()
    for cp in cccs_dict:
        all_cps.add(cp)
    for cp in canon_decomposition_mapping:
        all_cps.add(cp)
    for cp in compat_decomposition_mapping:
        all_cps.add(cp)
    for k,v in quick_check_maps.items():
        for cp in v:
            all_cps.add(cp)

    def decomp_str(decomp):
        return '{{{}, {}}}'.format(decomp[0], decomp[1])
    def cast(quick_check):
        return '(uint8_t)' + quick_check
    def quick_checks_to_byte(quick_check_1, quick_check_2):
        enum_value = {
            'quick_check::yes': 0,
            'quick_check::no': 1,
            'quick_check::maybe': 2
        }
        return enum_value[quick_check_1] << 4 | enum_value[quick_check_2]

    prop_bytes_ = []
    for cp in sorted(all_cps):
        canonical_decomp = (0, 0)
        if cp in canon_decomposition_mapping:
            canonical_decomp = canon_decomposition_mapping[cp]
        compatible_decomp = (0, 0)
        if cp in compat_decomposition_mapping:
            compatible_decomp = compat_decomposition_mapping[cp]
        ccc = 0
        if cp in cccs_dict:
            ccc = cccs_dict[cp]
        nfd_quick_check = 'quick_check::yes'
        if cp in quick_check_maps['NFD']:
            nfd_quick_check = quick_check_maps['NFD'][cp]
        nfkd_quick_check = 'quick_check::yes'
        if cp in quick_check_maps['NFKD']:
            nfkd_quick_check = quick_check_maps['NFKD'][cp]
        nfc_quick_check = 'quick_check::yes'
        if cp in quick_check_maps['NFC']:
            nfc_quick_check = quick_check_maps['NFC'][cp]
        nfkc_quick_check = 'quick_check::yes'
        if cp in quick_check_maps['NFKC']:
            nfkc_quick_check = quick_check_maps['NFKC'][cp]
        lzw.add_cp(prop_bytes_, cp)
        lzw.add_short(prop_bytes_, canonical_decomp[0])
        lzw.add_short(prop_bytes_, canonical_decomp[1])
        lzw.add_short(prop_bytes_, compatible_decomp[0])
        lzw.add_short(prop_bytes_, compatible_decomp[1])
        lzw.add_byte(prop_bytes_, int(ccc))
        lzw.add_byte(prop_bytes_, \
                     quick_checks_to_byte(nfd_quick_check, nfkd_quick_check))
        lzw.add_byte(prop_bytes_, \
                     quick_checks_to_byte(nfc_quick_check, nfkc_quick_check))

    value_per_line = 12
    compressed_bytes = lzw.compress(prop_bytes_)
    props_lines, num_shorts = lzw.compressed_bytes_to_lines(compressed_bytes, value_per_line)
    #print 'rewrote {} * 144 = {} bits as {} * 8 = {} bits'.format(len(all_cps), len(all_cps)*144, len(prop_bytes_), len(prop_bytes_)*8)
    #print 'compressed to {} * 16 = {} bits'.format(len(compressed_bytes), len(compressed_bytes) * 16)

    cpp_file = open('normalization_data_cp_props.cpp', 'w')
    cpp_file.write(cp_props_file_form.format(
        canon_all_cps_string, len(canon_all_cps),
        compat_all_cps_string, len(compat_all_cps),
        props_lines, num_shorts,
        len(all_cps)
    ))

def cps_string(cps):
    cps = map(lambda x: hex(x)[2:], cps)
    return ''.join(map(lambda x: r'\U' + '0' * (8 - len(x)) + x, cps))

def cus_lines(cus):
    as_ints = map(lambda x: ord(x), cus)
    values_per_line = 12
    return lzw.compressed_bytes_to_lines(as_ints, values_per_line)[0]

def utf8_cps(cps):
    s = cps_string(cps)
    exec("s = u'" + s + "'")
    s = s.encode('UTF-8', 'strict')
    retval = cus_lines(s)
    print 'rewrote {} * 32 = {} bits as {} * 8 = {} bits ({} bytes saved)'.format(len(cps), len(cps) * 32, len(s), len(s) * 8, (len(cps) * 32 - len(s) * 8) / 8.0)
    return retval

#utf8_cps(canon_all_cps)
#utf8_cps(compat_all_cps)


text:
import numpy as np
import fff2.glm as glm

# This example routine simulates a number of pure Gaussian white noise
# signals, then fits each one in terms of two regressors: a constant baseline,
# and a linear function of time. The voxelwise t statistics associated
# with the baseline coefficient are then computed.

dimt = 100
dimx = 10
dimy = 11
dimz = 12

# axis defines the "time direction"

y = np.random.randn(dimt, dimx*dimy*dimz)
vy = np.ones([dimt, dimx*dimy*dimz])
e = np.random.randn(dimt, dimx*dimy*dimz)
y = y + e
axis = 0

"""
y = random.randn(dimx, dimt, dimy, dimz)
vy = ones([dimx, dimt, dimy, dimz])
e = random.randn(dimx, dimt, dimy, dimz)
y = y + e
axis = 1
"""

X = np.array([np.ones(dimt), range(dimt)])
X = X.transpose() ## the design matrix X must have dimt lines

"""
pX = linalg.pinv(X)
beta, s2, z, vz = mfx.em(y, vy, X, pX, axis=axis)
##beta, norm_var_beta, s2, dof = glm.kalman.ols(y, X, axis=axis)
##beta, norm_var_beta, s2, dof = glm.ols(y, X, axis=axis)
ll = mfx.log_likelihood(y, vy, X, beta, s2, axis=axis)
"""

m = glm.glm(y, X, vy=vy, axis=axis)
m.fit()
lcon = m.contrast([1,0], type='l')
t, p, z = lcon.test(zscore=True)
F, p = m.contrast([[1,0],[1,-1]], type='L').test() ## recognizes a F contrast

print np.shape(y)
print np.shape(X)


text:
import React, { Component, PropTypes } from 'react';
import { Card, CardTitle, CardText } from 'react-toolbox/lib/card';
import { Button } from 'react-toolbox/lib/button';
import ChordChart from '../chord-chart/chord-chart';

const flatSign = String.fromCharCode(0x266d);
const sharpSign = String.fromCharCode(0x266f);

import './chord-card.scss';

export default class ChordCard extends Component {
    static propTypes = {
        chord: PropTypes.object,
    };

    static contextTypes = {
        isEditable: PropTypes.bool,
        onAddFretClick: PropTypes.func,
    };

    getNumFrets(chord) {
        return Math.max.apply(null, chord.fingerings.map(string => {
            return parseInt(string.fret) ? string.fret : 0;
        }));
    }

    renderAddFretsButton = (numFrets) => {
        const { isEditable, onAddFretClick } = this.context;
        const canAddFrets = numFrets <= 5;
        return isEditable && canAddFrets ? (
            <Button icon='add'
                className='add-more-frets-button'
                label='Add fret'
                onClick={onAddFretClick.bind(this, numFrets)}
                flat primary />
        ) : '';
    };

    renderChordName(name) {
        let modifiedName = name.replace(/\#/g, sharpSign);
        modifiedName = modifiedName.replace(/b\b/g, flatSign);
        return modifiedName;
    }

    render() {
        const { chord, numFrets } = this.props;
        const totalFrets =
            numFrets || Math.max(this.getNumFrets(chord), 4);
        return (
            <Card className='chord-card'>
                <CardTitle className='chord-title'>

{this.renderChordName(chord.name)}

                </CardTitle>
                <ChordChart chord={chord}
                    numFrets={totalFrets}/>

                {this.renderAddFretsButton(totalFrets)}
                <CardText className='chord-details'>

{chord.instrument}

                </CardText>
            </Card>
        );
    }
}


text:
puts "What is your first name?"
first = gets.chomp
puts "What is your middle name?"
middle = gets.chomp
puts "What is your last name?"
last = gets.chomp
puts "Good evening, " + first + " " + middle + " " + last

puts "What is your favorite number?"
fav = gets.chomp
better = fav.to_i + 1
puts better.to_s + " is a bigger and better number."

/
How do you define a local variable?
  Give the variable a name and assign a value to it using =
How do you define a method?
  Use def followed by the name of the method.
What is the difference between a local variable and a method?
  method is like a verb that needs to act on an object. Variable is that object.
How do you run a ruby program from the command line?
  ruby filename.rb
How do you run an RSpec file from the command line?
  rspec filename.rb
What was confusing about this material? What made sense?
  Nothing is really confusing about this material. syntax-wise, Ruby is a relatively simple language to learn.
/


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

<TITLE>
org.openqa.selenium.internal.seleniumemulation (Selenium Remote Control 1.0.3)
</TITLE>

<META NAME="date" CONTENT="2010-02-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package org.openqa.selenium.internal.seleniumemulation

Interface Summary

FilterFunction

LookupStrategy

OptionSelectStrategy

TextMatchingStrategy

Class Summary

AddLocationStrategy

AddSelection

AltKeyDown

AltKeyUp

AltLookupStrategy

AssignId

AttachFile

BaseFilterFunction

BaseOptionSelectStrategy

CaptureScreenshotToString

Check

ClassLookupStrategy

Click

Close

ControlKeyDown

ControlKeyUp

CreateCookie

DeleteAllVisibleCookies

DeleteCookie

DomTraversalLookupStrategy

DoubleClick

DragAndDrop

DragAndDropToObject

ElementFinder

ExactTextMatchingStrategy

FindFirstSelectedOptionProperty

FindSelectedOptionProperties

FireEvent

FireNamedEvent

GetAllButtons

GetAllFields

GetAllLinks

GetAllWindowTitles

GetAttribute

GetAttributeFromAllWindows

GetBodyText

GetCookie

GetCookieByName

GetElementHeight

GetElementIndex

GetElementPositionLeft

GetElementPositionTop

GetElementWidth

GetEval

GetHtmlSource

GetLocation

GetSelectOptions

GetTable

GetText

GetTitle

GetValue

GetXpathCount

GlobTextMatchingStrategy

GoBack

Highlight

IdentifierLookupStrategy

IdLookupStrategy

IdOptionSelectStrategy

ImplicitLookupStrategy

IndexFilterFunction

IndexOptionSelectStrategy

IsChecked

IsCookiePresent

IsEditable

IsElementPresent

IsOrdered

IsSomethingSelected

IsTextPresent

IsVisible

JavascriptLibrary

KeyEvent

KeyState

LabelOptionSelectStrategy

LinkLookupStrategy

MetaKeyDown

MetaKeyUp

MouseEvent

MouseEventAt

NameFilterFunction

NameLookupStrategy

NoOp

Open

OpenWindow

Refresh

RegExTextMatchingStrategy

RemoveAllSelections

RemoveSelection

RunScript

SelectFrame

SelectOption

SelectWindow

SeleneseCommand<T>

SeleniumSelect

SetTimeout

ShiftKeyDown

ShiftKeyUp

Submit

Timer

Type

TypeKeys

Uncheck

ValueFilterFunction

ValueOptionSelectStrategy

WaitForCondition

WaitForPageToLoad

WaitForPopup

WindowFocus

WindowMaximize

Windows

XPathLookupStrategy

Enum Summary

SeleniumSelect.Property

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
package com.github.skjolber.packing.packer;

import com.github.skjolber.packing.api.Container;
import com.github.skjolber.packing.api.PackResult;

/**
 * Logical packager for wrapping preprocessing / optimizations.
 */
//
public interface Adapter<T extends PackResult> {
	T attempt(int containerIndex, T best);
	Container accept(T result);
}


text:
import java.util.Scanner;

public class p03PointInRectangle {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        double  x1 = Double.parseDouble(scan.nextLine());
        double  y1 = Double.parseDouble(scan.nextLine());
        double  x2 = Double.parseDouble(scan.nextLine());
        double  y2 = Double.parseDouble(scan.nextLine());
        double  x = Double.parseDouble(scan.nextLine());
        double  y = Double.parseDouble(scan.nextLine());

        if (x >= x1 && x <= x2 && y >= y1 && y <= y2){
            System.out.println("Inside");
        } else {
            System.out.println("Outside");
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 111: 3 (1967)

#### Original name
Periconiella mucunae M.B. Ellis

### Remarks
null


text:
// This code is in the public domain -- castanyo@yahoo.es

#include <nvmath/Basis.h>

using namespace nv;

/// Normalize basis vectors.
void Basis::normalize(float epsilon /*= NV_EPSILON*/)
{
    normal = ::normalize(normal, epsilon);
    tangent = ::normalize(tangent, epsilon);
    bitangent = ::normalize(bitangent, epsilon);
}

/// Gram-Schmidt orthogonalization.
/// @note Works only if the vectors are close to orthogonal.
void Basis::orthonormalize(float epsilon /*= NV_EPSILON*/)
{
    // N' = |N|
    // T' = |T - (N' dot T) N'|
    // B' = |B - (N' dot B) N' - (T' dot B) T'|

    normal = ::normalize(normal, epsilon);

    tangent -= normal * dot(normal, tangent);
    tangent = ::normalize(tangent, epsilon);

    bitangent -= normal * dot(normal, bitangent);
    bitangent -= tangent * dot(tangent, bitangent);
    bitangent = ::normalize(bitangent, epsilon);
}

/// Robust orthonormalization.
/// Returns an orthonormal basis even when the original is degenerate.
void Basis::robustOrthonormalize(float epsilon /*= NV_EPSILON*/)
{
    if (length(normal) < epsilon)
    {
        normal = cross(tangent, bitangent);

        if (length(normal) < epsilon)
        {
            tangent = Vector3(1, 0, 0);
            bitangent = Vector3(0, 1, 0);
            normal = Vector3(0, 0, 1);
            return;
        }
    }
    normal = ::normalize(normal, epsilon);

    tangent -= normal * dot(normal, tangent);
    bitangent -= normal * dot(normal, bitangent);

    if (length(tangent) < epsilon)
    {
        if (length(bitangent) < epsilon)
        {
            buildFrameForDirection(normal);
        }
        else
        {
            tangent = cross(bitangent, normal);
            nvCheck(isNormalized(tangent, epsilon));
        }
    }
    else
    {
        tangent = ::normalize(tangent, epsilon);
        bitangent -= tangent * dot(tangent, bitangent);

        if (length(bitangent) < epsilon)
        {
            bitangent = cross(tangent, normal);
            nvCheck(isNormalized(bitangent));
        }
        else
        {
            tangent = ::normalize(tangent, epsilon);
        }
    }

    // Check vector lengths.
    nvCheck(isNormalized(normal, epsilon));
    nvCheck(isNormalized(tangent, epsilon));
    nvCheck(isNormalized(bitangent, epsilon));

    // Check vector angles.
    nvCheck(equal(dot(normal, tangent), 0.0f, epsilon));
    nvCheck(equal(dot(normal, bitangent), 0.0f, epsilon));
    nvCheck(equal(dot(tangent, bitangent), 0.0f, epsilon));

    // Check vector orientation.
    const float det = dot(cross(normal, tangent), bitangent);
    nvCheck(equal(det, 1.0f, epsilon) || equal(det, -1.0f, epsilon));
}

/// Build an arbitrary frame for the given direction.
void Basis::buildFrameForDirection(Vector3::Arg d)
{
    nvCheck(isNormalized(d));
    normal = d;

    // Choose minimum axis.
    if (fabsf(normal.x()) < fabsf(normal.y()) && fabsf(normal.x()) < fabsf(normal.z()))
    {
        tangent = Vector3(1, 0, 0);
    }
    else if (fabsf(normal.y()) < fabsf(normal.z()))
    {
        tangent = Vector3(0, 1, 0);
    }
    else
    {
        tangent = Vector3(0, 0, 1);
    }

    // Ortogonalize
    tangent -= normal * dot(normal, tangent);
    tangent = ::normalize(tangent);

    bitangent = cross(normal, tangent);
}

/*
/// Transform by this basis. (From this basis to object space).
Vector3 Basis::transform(Vector3::Arg v) const
{
	Vector3 o = tangent * v.x();
	o += bitangent * v.y();
	o += normal * v.z();
	return o;
}

/// Transform by the transpose. (From object space to this basis).
Vector3 Basis::transformT(Vector3::Arg v)
{
	return Vector3(dot(tangent, v), dot(bitangent, v), dot(normal, v));
}

/// Transform by the inverse. (From object space to this basis).
/// @note Uses Kramer's rule so the inverse is not accurate if the basis is ill-conditioned.
Vector3 Basis::transformI(Vector3::Arg v) const
{
	const float det = determinant();
	nvCheck(!equalf(det, 0.0f));

	const float idet = 1.0f / det;

	// Rows of the inverse matrix.
	Vector3 r0, r1, r2;
	r0.x =  (bitangent.y() * normal.z() - bitangent.z() * normal.y()) * idet;
	r0.y = -(bitangent.x() * normal.z() - bitangent.z() * normal.x()) * idet;
	r0.z =  (bitangent.x() * normal.y() - bitangent.y() * normal.x()) * idet;

	r1.x = -(tangent.y() * normal.z() - tangent.z() * normal.y()) * idet;
	r1.y =  (tangent.x() * normal.z() - tangent.z() * normal.x()) * idet;
	r1.z = -(tangent.x() * normal.y() - tangent.y() * normal.x()) * idet;

	r2.x =  (tangent.y() * bitangent.z() - tangent.z() * bitangent.y()) * idet;
	r2.y = -(tangent.x() * bitangent.z() - tangent.z() * bitangent.x()) * idet;
	r2.z =  (tangent.x() * bitangent.y() - tangent.y() * bitangent.x()) * idet;

	return Vector3(dot(v, r0), dot(v, r1), dot(v, r2));
}
*/


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

<!--
 <copyright>
 </copyright>

 $Id$
-->

<plugin>

   <extension point="org.eclipse.emf.ecore.generated_package">
      <package
            uri="http://model.deployment.itecban.es/ValidationResult"
            class="es.itecban.deployment.model.validation.result.ResultPackage"
            genModel="model/genmodel/es.itecban.deployment.model.validation.genmodel"/>
   </extension>

   <extension point="org.eclipse.emf.ecore.extension_parser">
      <parser
            type="result"
            class="es.itecban.deployment.model.validation.result.util.ResultResourceFactoryImpl"/>
   </extension>

</plugin>


text:
<ion-side-menus enable-menu-with-back-views="false">
  <ion-side-menu-content>
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="menuContent"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu side="left" expose-aside-when="large" class="side-panel">

      <ion-content>

          Hi {{user.contents.name}}!

            Logout

        <ion-list>
          <ion-item menu-close class="item-icon-left" ng-click="goToProfile()">

            Profile
          </ion-item>
          <ion-item menu-close class="centered item-icon-left" ng-click="goToTrips()">

            Stories
          </ion-item>
          <ion-item menu-close class="centered item-icon-left" ng-click="goToFriends()">

            Friends
          </ion-item>
          <ion-item menu-close class="centered item-icon-left" ng-click="goToCars()">

            Cars
          </ion-item>
          <ion-item menu-close class="centered item-icon-left" ng-click="goToAbout()">

            About
          </ion-item>
        </ion-list>
      </ion-content>

  </ion-side-menu>
</ion-side-menus>


text:
package app.api.user;

import core.framework.api.json.Property;
import core.framework.api.validate.NotNull;

public class LoginAJAXResponse {
    @NotNull
    @Property(name = "success")
    public Boolean success;

    @Property(name = "name")
    public String name;

    @Property(name = "role")
    public String role;

    @Property(name = "errorMessage")
    public String errorMessage;
}


text:
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;

namespace NetOffice.OfficeApi
{
	/// <summary>
	/// DispatchInterface SharedWorkspaceFolder
	/// SupportByVersion Office, 11,12,14,15,16
	/// </summary>
	/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.SharedWorkspaceFolder"/> </remarks>
	[SupportByVersion("Office", 11,12,14,15,16)]
	[EntityType(EntityType.IsDispatchInterface)]
 	public class SharedWorkspaceFolder : _IMsoDispObj
	{
		#pragma warning disable

		#region Type Information

		/// <summary>
		/// Instance Type
		/// </summary>
		[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
		public override Type InstanceType
		{
			get
			{
				return LateBindingApiWrapperType;
			}
		}

        private static Type _type;

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        public static Type LateBindingApiWrapperType
        {
            get
            {
                if (null == _type)
                    _type = typeof(SharedWorkspaceFolder);
                return _type;
            }
        }

        #endregion

		#region Ctor

		/// <param name="factory">current used factory core</param>
		/// <param name="parentObject">object there has created the proxy</param>
		/// <param name="proxyShare">proxy share instead if com proxy</param>
		public SharedWorkspaceFolder(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
		public SharedWorkspaceFolder(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
		{

		}

        ///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public SharedWorkspaceFolder(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public SharedWorkspaceFolder(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
		{

		}

		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public SharedWorkspaceFolder(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
		{
		}

		///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public SharedWorkspaceFolder(ICOMObject replacedObject) : base(replacedObject)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public SharedWorkspaceFolder() : base()
		{
		}

		/// <param name="progId">registered progID</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public SharedWorkspaceFolder(string progId) : base(progId)
		{
		}

		#endregion

		#region Properties

		/// <summary>
		/// SupportByVersion Office 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.SharedWorkspaceFolder.FolderName"/> </remarks>
		[SupportByVersion("Office", 11,12,14,15,16)]
		public string FolderName
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "FolderName");
			}
		}

		/// <summary>
		/// SupportByVersion Office 11, 12, 14, 15, 16
		/// Get
		/// Unknown COM Proxy
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.SharedWorkspaceFolder.Parent"/> </remarks>
		[SupportByVersion("Office", 11,12,14,15,16), ProxyResult]
		public object Parent
		{
			get
			{
				return Factory.ExecuteReferencePropertyGet(this, "Parent");
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// SupportByVersion Office 11, 12, 14, 15, 16
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.SharedWorkspaceFolder.Delete"/> </remarks>
		/// <param name="deleteEventIfFolderContainsFiles">optional object deleteEventIfFolderContainsFiles</param>
		[SupportByVersion("Office", 11,12,14,15,16)]
		public void Delete(object deleteEventIfFolderContainsFiles)
		{
			 Factory.ExecuteMethod(this, "Delete", deleteEventIfFolderContainsFiles);
		}

		/// <summary>
		/// SupportByVersion Office 11, 12, 14, 15, 16
		/// </summary>
		/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.SharedWorkspaceFolder.Delete"/> </remarks>
		[CustomMethod]
		[SupportByVersion("Office", 11,12,14,15,16)]
		public void Delete()
		{
			 Factory.ExecuteMethod(this, "Delete");
		}

		#endregion

		#pragma warning restore
	}
}


text:
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import myFirstReducer from './myFirstReducer';

export default combineReducers({
    routerReducer,
    myFirstReducer,
});


text:
Overview
========

Pronounced "Sharp Architecture," this is a solid architectural
foundation for rapidly building maintainable web applications leveraging
the ASP.NET MVC framework with NHibernate. The primary advantage to be
sought in using any architectural framework is to decrease the code one
has to write while increasing the quality of the end product. A
framework should enable developers to spend little time on
infrastructure details while allowing them to focus their attentions on
the domain and user experience. Accordingly, S#arp Architecture adheres
to the following key principles:

*  Focused on Domain Driven Design
*  Loosely coupled
*  Preconfigured Infrastructure
*  Open Ended Presentation

The overall goal of this is to allow developers to worry less about
application "plumbing" and to spend most of their time on adding value
for the client by focusing on the business logic and developing a rich
user experience.

Absolutely essential reading is Eric Evans' `Domain Driven Design <http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215>`_. For a
quick introduction to the subject, see `Domain Driven Design Quickly <http://www.infoq.com/minibooks/domain-driven-design-quickly>`_
which is a concise summary of Evans' classic work. Other useful
background material, albeit dated, includes `NHibernate Best
Practices <http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx>`_.
Although there are major infrastructural changes from the referenced
article when compared to the current S#arp Architecture, the general
structure is very similar and the background reading is helpful in
understanding many of the ideas behind this development foundation.


text:
package com.uaihebert.uaimockserver.model;

import com.uaihebert.uaimockserver.facade.RequestValidatorFacade;
import com.uaihebert.uaimockserver.log.backend.Log;
import com.uaihebert.uaimockserver.util.StringUtils;
import com.uaihebert.uaimockserver.validator.body.UaiJSONComparator;
import com.uaihebert.uaimockserver.validator.body.UaiJSONCompareWrapper;
import com.uaihebert.uaimockserver.validator.body.UaiJsonFieldFailureLogger;
import com.uaihebert.uaimockserver.validator.body.XmlUnitWrapper;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
import org.skyscreamer.jsonassert.comparator.JSONComparator;

import java.util.regex.Pattern;

public enum BodyValidationType {
    VALIDATE_IF_PRESENT_ONLY {
        @Override
        public void validate(final String body, final UaiRequest uaiRequest, final RequestValidatorFacade.RequestAnalysisResult result) {
            if (StringUtils.isNotBlank(body)) {
                return;
            }

            Log.warnFormatted(BODY_VALIDATOR_ERROR_MESSAGE, uaiRequest.method, uaiRequest.path);
            result.abortTheRequest();
        }
    },
    RAW_TEXT {
        @Override
        public void validate(final String body, final UaiRequest uaiRequest, final RequestValidatorFacade.RequestAnalysisResult result) {
            if (uaiRequest.body.equals(body)) {
                return;
            }

            Log.warnFormatted(WRONG_RAW_TEXT_BODY, body, uaiRequest.body);
            result.abortTheRequest();
        }
    },
    JSON_VALIDATE_DEFINED_BODY_AGAINST_ALL_ATTRIBUTES_RECEIVED {
        @Override
        public void validate(final String body, final UaiRequest uaiRequest, final RequestValidatorFacade.RequestAnalysisResult result) {
            VALIDATE_IF_PRESENT_ONLY.validate(body, uaiRequest, result);

            if (result.isAbortTheRequest()) {
                return;
            }

            final JSONCompareResult jsonResult = UaiJSONCompareWrapper.compareJSON(uaiRequest.body, body, STRICT_COMPARATOR);

            if (!jsonResult.failed()) {
                return;
            }

            UaiJsonFieldFailureLogger.logFailure(JSON_BODY_STRICT_ERROR_MESSAGE, jsonResult);

            result.abortTheRequest();
        }
    },
    JSON_VALIDATE_ONLY_DEFINED_ATTRIBUTES_IN_BODY {
        @Override
        public void validate(final String body, final UaiRequest uaiRequest, final RequestValidatorFacade.RequestAnalysisResult result) {
            VALIDATE_IF_PRESENT_ONLY.validate(body, uaiRequest, result);

            if (result.isAbortTheRequest()) {
                return;
            }

            final JSONCompareResult jsonResult = UaiJSONCompareWrapper.compareJSON(uaiRequest.body, body, LENIENT_COMPARATOR);

            if (!jsonResult.failed()) {
                return;
            }

            UaiJsonFieldFailureLogger.logFailure(JSON_BODY_LENIENT_ERROR_MESSAGE, jsonResult);

            result.abortTheRequest();
        }
    },
    XML_BODY_WITH_STRICT_ATTRIBUTE_ORDER {
        @Override
        public void validate(final String body, final UaiRequest uaiRequest, final RequestValidatorFacade.RequestAnalysisResult result) {
            VALIDATE_IF_PRESENT_ONLY.validate(body, uaiRequest, result);

            if (result.isAbortTheRequest()) {
                return;
            }

            if (XmlUnitWrapper.isIdentical(uaiRequest.body, body)) {
                return;
            }

            Log.warnFormatted(WRONG_XML_BODY_WITH_STRICT_ATTRIBUTE_ORDER, body, uaiRequest.body);

            result.abortTheRequest();
        }
    },
    XML_BODY_WITHOUT_STRICT_ATTRIBUTE_ORDER {
        @Override
        public void validate(final String body, final UaiRequest uaiRequest, final RequestValidatorFacade.RequestAnalysisResult result) {
            VALIDATE_IF_PRESENT_ONLY.validate(body, uaiRequest, result);

            if (result.isAbortTheRequest()) {
                return;
            }

            if (XmlUnitWrapper.isSimilar(uaiRequest.body, body)) {
                return;
            }

            Log.warnFormatted(WRONG_XML_BODY_WITHOUT_STRICT_ATTRIBUTE_ORDER, body, uaiRequest.body);

            result.abortTheRequest();
        }
    },
    BY_REGEX {
        @Override
        public void validate(final String body, final UaiRequest uaiRequest, final RequestValidatorFacade.RequestAnalysisResult result) {
            VALIDATE_IF_PRESENT_ONLY.validate(body, uaiRequest, result);

            if (result.isAbortTheRequest()) {
                return;
            }

            final String delimiter = "\n";
            final String[] textPatterns = uaiRequest.body.split(delimiter);

            for(String textPattern : textPatterns){
                final Pattern pattern = Pattern.compile(textPattern);
                if(!pattern.matcher(body).find()){
                    Log.warnFormatted(UNMATCHED_REGEX, body, textPattern);
                    result.abortTheRequest();
                }
            }

        }
    };

    private static final JSONComparator STRICT_COMPARATOR = new UaiJSONComparator(JSONCompareMode.STRICT);
    private static final JSONComparator LENIENT_COMPARATOR = new UaiJSONComparator(JSONCompareMode.LENIENT);

    private static final String WRONG_RAW_TEXT_BODY = "Using the RAW_TEXT validation we received a body with the following text in the body [%s], but the required body is [%s]";
    private static final String BODY_VALIDATOR_ERROR_MESSAGE = "%nThe Route [%s - %s] was defined with the body as mandatory. Send a body in your request or set the bodyRequired to false. %n";
    private static final String JSON_BODY_STRICT_ERROR_MESSAGE = "%nUsing the JSON_VALIDATE_DEFINED_BODY_AGAINST_ALL_ATTRIBUTES_RECEIVED validation we found an error with the attribute [%s]. %nWe received [%s] but what we detected was ---> [%s] %n";
    private static final String JSON_BODY_LENIENT_ERROR_MESSAGE = "%nUsing the JSON_VALIDATE_ONLY_DEFINED_ATTRIBUTES_IN_BODY validation we found an error with the attribute [%s]. %nWe was expecting [%s] but what we detected was ---> [%s] %n";
    private static final String WRONG_XML_BODY_WITH_STRICT_ATTRIBUTE_ORDER = "%nUsing the WRONG_XML_BODY_WITH_STRICT_ATTRIBUTE_ORDER validation we found and error with the XML that we received [%s]; the received XML is not equal to the expected body [%s]. Check the values and the attribute order. %n";
    private static final String WRONG_XML_BODY_WITHOUT_STRICT_ATTRIBUTE_ORDER = "%nUsing the WRONG_XML_BODY_WITHOUT_STRICT_ATTRIBUTE_ORDER validation we found and error with the XML that we received [%s]; the received XML is not equal to the expected body [%s]. Check the values and the attribute order. %n";
    private static final String UNMATCHED_REGEX = "%nUsing the BY_REGEX validation we found and error with the body that we received [%s]; the received body does not match one of the regular expressions [%s]. %n";

    public abstract void validate(final String body, final UaiRequest uaiRequest, final RequestValidatorFacade.RequestAnalysisResult result);
}


text:
#ifndef STREAM_PHP_STREAM_TRANSPORT_H
#define STREAM_PHP_STREAM_TRANSPORT_H

#include <sys/types.h>
#include <sys/socket.h>

typedef php_stream *(php_stream_transport_factory_func)(const char *proto, size_t protolen,
		const char *resourcename, size_t resourcenamelen,
		const char *persistent_id, int options, int flags,
		struct timeval *timeout,
		php_stream_context *context STREAMS_DC);
typedef php_stream_transport_factory_func *php_stream_transport_factory;

int php_stream_xport_register(const char *protocol, php_stream_transport_factory factory);
int php_stream_xport_unregister(const char *protocol);

#define STREAM_XPORT_CLIENT			0
#define STREAM_XPORT_SERVER			1

#define STREAM_XPORT_CONNECT		2
#define STREAM_XPORT_BIND			4
#define STREAM_XPORT_LISTEN			8
#define STREAM_XPORT_CONNECT_ASYNC	16

/* Open a client or server socket connection */
php_stream *php_stream_xport_create(const char *name, size_t namelen, int options,
		int flags, const char *persistent_id,
		struct timeval *timeout,
		php_stream_context *context,
		char **error_string,
		int *error_code);

/* Bind the stream to a local address */
int php_stream_xport_bind(php_stream *stream,
		const char *name, size_t namelen,
		char **error_text);

/* Connect to a remote address */
int php_stream_xport_connect(php_stream *stream,
		const char *name, size_t namelen,
		int asynchronous,
		struct timeval *timeout,
		char **error_text,
		int *error_code);

/* Prepare to listen */
int php_stream_xport_listen(php_stream *stream,
		int backlog,
		char **error_text);

/* Get the next client and their address as a string, or the underlying address
 * structure.  You must efree either of these if you request them */
int php_stream_xport_accept(php_stream *stream, php_stream **client,
		char **textaddr, int *textaddrlen,
		void **addr, socklen_t *addrlen,
		struct timeval *timeout,
		char **error_text);

/* Get the name of either the socket or it's peer */
int php_stream_xport_get_name(php_stream *stream, int want_peer,
		char **textaddr, int *textaddrlen,
		void **addr, socklen_t *addrlen);

enum php_stream_xport_send_recv_flags {
	STREAM_OOB = 1,
	STREAM_PEEK = 2
};

/* Similar to recv() system call; read data from the stream, optionally
 * peeking, optionally retrieving OOB data */
int php_stream_xport_recvfrom(php_stream *stream, char *buf, size_t buflen,
		long flags, void **addr, socklen_t *addrlen,
		char **textaddr, int *textaddrlen);

/* Similar to send() system call; send data to the stream, optionally
 * sending it as OOB data */
int php_stream_xport_sendto(php_stream *stream, const char *buf, size_t buflen,
		long flags, void *addr, socklen_t addrlen);

typedef enum {
	STREAM_SHUT_RD,
	STREAM_SHUT_WR,
	STREAM_SHUT_RDWR
} stream_shutdown_t;

/* Similar to shutdown() system call; shut down part of a full-duplex
 * connection */
int php_stream_xport_shutdown(php_stream *stream, stream_shutdown_t how);

/* Structure definition for the set_option interface that the above functions wrap */

typedef struct _php_stream_xport_param {
	enum {
		STREAM_XPORT_OP_BIND, STREAM_XPORT_OP_CONNECT,
		STREAM_XPORT_OP_LISTEN, STREAM_XPORT_OP_ACCEPT,
		STREAM_XPORT_OP_CONNECT_ASYNC,
		STREAM_XPORT_OP_GET_NAME,
		STREAM_XPORT_OP_GET_PEER_NAME,
		STREAM_XPORT_OP_RECV,
		STREAM_XPORT_OP_SEND,
		STREAM_XPORT_OP_SHUTDOWN
	} op;
	unsigned int want_addr:1;
	unsigned int want_textaddr:1;
	unsigned int want_errortext:1;
	unsigned int how:2;

	struct {
		char *name;
		size_t namelen;
		int backlog;
		struct timeval *timeout;
		struct sockaddr *addr;
		socklen_t addrlen;
		char *buf;
		size_t buflen;
		long flags;
	} inputs;
	struct {
		php_stream *client;
		int returncode;
		struct sockaddr *addr;
		socklen_t addrlen;
		char *textaddr;
		long textaddrlen;

		char *error_text;
		int error_code;
	} outputs;
} php_stream_xport_param;

/* Because both client and server streams use the same mechanisms
   for encryption we use the LSB to denote clients.
*/
typedef enum {
	STREAM_CRYPTO_METHOD_SSLv2_CLIENT = (1 << 1 | 1),
	STREAM_CRYPTO_METHOD_SSLv3_CLIENT = (1 << 2 | 1),
	STREAM_CRYPTO_METHOD_SSLv23_CLIENT = ((1 << 1) | (1 << 2) | 1),
	STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT = (1 << 3 | 1),
	STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT = (1 << 4 | 1),
	STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT = (1 << 5 | 1),
	STREAM_CRYPTO_METHOD_TLS_CLIENT = ((1 << 3) | (1 << 4) | (1 << 5) | 1),
	STREAM_CRYPTO_METHOD_ANY_CLIENT = ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5) | 1),
	STREAM_CRYPTO_METHOD_SSLv2_SERVER = (1 << 1),
	STREAM_CRYPTO_METHOD_SSLv3_SERVER = (1 << 2),
	STREAM_CRYPTO_METHOD_SSLv23_SERVER = ((1 << 1) | (1 << 2)),
	STREAM_CRYPTO_METHOD_TLSv1_0_SERVER = (1 << 3),
	STREAM_CRYPTO_METHOD_TLSv1_1_SERVER = (1 << 4),
	STREAM_CRYPTO_METHOD_TLSv1_2_SERVER = (1 << 5),
	STREAM_CRYPTO_METHOD_TLS_SERVER = ((1 << 3) | (1 << 4) | (1 << 5)),
	STREAM_CRYPTO_METHOD_ANY_SERVER = ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5))
} php_stream_xport_crypt_method_t;

/* These functions provide crypto support on the underlying transport */

int php_stream_xport_crypto_setup(php_stream *stream, php_stream_xport_crypt_method_t crypto_method, php_stream *session_stream);
int php_stream_xport_crypto_enable(php_stream *stream, int activate);

typedef struct _php_stream_xport_crypto_param {
	enum {
		STREAM_XPORT_CRYPTO_OP_SETUP,
		STREAM_XPORT_CRYPTO_OP_ENABLE
	} op;
	struct {
		int activate;
		php_stream_xport_crypt_method_t method;
		php_stream *session;
	} inputs;
	struct {
		int returncode;
	} outputs;
} php_stream_xport_crypto_param;

/* HashTable *php_stream_xport_get_hash(void); */
php_stream_transport_factory_func php_stream_generic_socket_factory;

#endif // STREAM_PHP_STREAM_TRANSPORT_H


text:
<!DOCTYPE html>

    <title>Bohemian</title>
    <meta charset="utf-8" />

    <meta name=viewport content="width=device-width, initial-scale=1">
    <meta name="MobileOptimized" content="320">
    <meta name="HandheldFriendly" content="True">

    <link rel="stylesheet" href="./theme/css/style.css">

    <link rel="stylesheet" href="//brick.a.ssl.fastly.net/Alegreya:400,400i,700,700i,900,900i">
    <link rel="stylesheet" href="./theme/css/theme1.css">

    <link href="localhost/bohemian-theme/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="Bohemian Full Atom Feed" />

          Bohemian

            Blog

Blog

      Proudly powered by Pelican,
      which takes great advantage of Python.

      Bohemian theme by Omphalosskeptic

* Pelican Theme


text:
package org.apache.camel.component.cxf;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.SSLContextParametersAware;
import org.apache.camel.component.cxf.common.message.CxfConstants;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.HeaderFilterStrategyComponent;
import org.apache.camel.support.IntrospectionSupport;
import org.apache.cxf.message.Message;

/**
 * Defines the CXF Component
 */
@Component("cxf")
public class CxfComponent extends HeaderFilterStrategyComponent implements SSLContextParametersAware {

    @Metadata(label = "advanced")
    private Boolean allowStreaming;
    @Metadata(label = "security", defaultValue = "false")
    private boolean useGlobalSslContextParameters;

    public CxfComponent() {
    }

    public CxfComponent(CamelContext context) {
        super(context);
    }

    /**
     * This option controls whether the CXF component, when running in PAYLOAD mode, will DOM parse the incoming messages
     * into DOM Elements or keep the payload as a javax.xml.transform.Source object that would allow streaming in some cases.
     */
    public void setAllowStreaming(Boolean allowStreaming) {
        this.allowStreaming = allowStreaming;
    }

    public Boolean isAllowStreaming() {
        return allowStreaming;
    }

    @Override
    public boolean isUseGlobalSslContextParameters() {
        return this.useGlobalSslContextParameters;
    }

    /**
     * Enable usage of global SSL context parameters.
     */
    @Override
    public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) {
        this.useGlobalSslContextParameters = useGlobalSslContextParameters;
    }

    /**
     * Create a {@link CxfEndpoint} which, can be a Spring bean endpoint having
     * URI format cxf:bean:beanId or transport address endpoint having URI format
     * cxf://transportAddress.
     */
    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {

        CxfEndpoint result;

        Object value = parameters.remove("setDefaultBus");
        if (value != null) {
            log.warn("The option setDefaultBus is @deprecated, use name defaultBus instead");
            if (!parameters.containsKey("defaultBus")) {
                parameters.put("defaultBus", value);
            }
        }

        if (allowStreaming != null && !parameters.containsKey("allowStreaming")) {
            parameters.put("allowStreaming", Boolean.toString(allowStreaming));
        }

        if (remaining.startsWith(CxfConstants.SPRING_CONTEXT_ENDPOINT)) {
            // Get the bean from the Spring context
            String beanId = remaining.substring(CxfConstants.SPRING_CONTEXT_ENDPOINT.length());
            if (beanId.startsWith("//")) {
                beanId = beanId.substring(2);
            }

            result = createCxfSpringEndpoint(beanId);
            // need to check the CamelContext value
            if (getCamelContext().equals(result.getCamelContext())) {
                result.setCamelContext(getCamelContext());
            }
            result.setBeanId(beanId);

        } else {
            // endpoint URI does not specify a bean
            result = createCxfEndpoint(remaining);
        }

        if (result.getCamelContext() == null) {
            result.setCamelContext(getCamelContext());
        }
        setEndpointHeaderFilterStrategy(result);
        setProperties(result, parameters);

        // extract the properties.xxx and set them as properties
        Map<String, Object> properties = IntrospectionSupport.extractProperties(parameters, "properties.");
        if (properties != null) {
            result.setProperties(properties);
        }
        if (result.getProperties() != null) {
            // set the properties of MTOM
            result.setMtomEnabled(Boolean.valueOf((String) result.getProperties().get(Message.MTOM_ENABLED)));
        }

        // use global ssl config if set
        if (result.getSslContextParameters() == null) {
            result.setSslContextParameters(retrieveGlobalSslContextParameters());
        }

        return result;
    }

    protected CxfEndpoint createCxfSpringEndpoint(String beanId) throws Exception {
        return CamelContextHelper.mandatoryLookup(getCamelContext(), beanId, CxfEndpoint.class);
    }

    protected CxfEndpoint createCxfEndpoint(String remaining) {
        return new CxfEndpoint(remaining, this);
    }

    @Override
    protected void afterConfiguration(String uri, String remaining, Endpoint endpoint, Map<String, Object> parameters) throws Exception {
        CxfEndpoint cxfEndpoint = (CxfEndpoint) endpoint;
        cxfEndpoint.updateEndpointUri(uri);
    }

}