text:
package org.neo4j.driver.internal.async.outbound;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.neo4j.driver.Values.value;
import static org.neo4j.driver.internal.logging.DevNullLogging.DEV_NULL_LOGGING;
import static org.neo4j.driver.internal.messaging.MessageFormat.Writer;
import static org.neo4j.driver.internal.messaging.request.PullAllMessage.PULL_ALL;
import static org.neo4j.driver.testutil.TestUtil.assertByteBufContains;

import io.netty.buffer.ByteBuf;
import io.netty.channel.embedded.EmbeddedChannel;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.neo4j.driver.Query;
import org.neo4j.driver.Value;
import org.neo4j.driver.Values;
import org.neo4j.driver.internal.async.connection.ChannelAttributes;
import org.neo4j.driver.internal.async.inbound.InboundMessageDispatcher;
import org.neo4j.driver.internal.messaging.Message;
import org.neo4j.driver.internal.messaging.MessageFormat;
import org.neo4j.driver.internal.messaging.v3.MessageFormatV3;
import org.neo4j.driver.internal.packstream.PackOutput;

class OutboundMessageHandlerTest {
    private final EmbeddedChannel channel = new EmbeddedChannel();

    @BeforeEach
    void setUp() {
        ChannelAttributes.setMessageDispatcher(channel, new InboundMessageDispatcher(channel, DEV_NULL_LOGGING));
    }

    @AfterEach
    void tearDown() {
        channel.finishAndReleaseAll();
    }

    @Test
    void shouldOutputByteBufAsWrittenByWriterAndMessageBoundary() {
        MessageFormat messageFormat = mockMessageFormatWithWriter(1, 2, 3, 4, 5);
        OutboundMessageHandler handler = newHandler(messageFormat);
        channel.pipeline().addLast(handler);

        // do not care which message, writer will return predefined bytes anyway
        assertTrue(channel.writeOutbound(PULL_ALL));
        assertTrue(channel.finish());

        assertEquals(1, channel.outboundMessages().size());

        ByteBuf buf = channel.readOutbound();
        assertByteBufContains(
                buf,
                (short) 5,
                (byte) 1,
                (byte) 2,
                (byte) 3,
                (byte) 4,
                (byte) 5, // message body
                (byte) 0,
                (byte) 0 // message boundary
                );
    }

    @Test
    void shouldSupportByteArraysByDefault() {
        OutboundMessageHandler handler = newHandler(new MessageFormatV3());
        channel.pipeline().addLast(handler);

        Map<String, Value> params = new HashMap<>();
        params.put("array", value(new byte[] {1, 2, 3}));

        assertTrue(channel.writeOutbound(new Query("RETURN 1", Values.value(params))));
        assertTrue(channel.finish());
    }

    private static MessageFormat mockMessageFormatWithWriter(final int... bytesToWrite) {
        MessageFormat messageFormat = mock(MessageFormat.class);

        when(messageFormat.newWriter(any(PackOutput.class))).then(invocation -> {
            PackOutput output = invocation.getArgument(0);
            return mockWriter(output, bytesToWrite);
        });

        return messageFormat;
    }

    private static Writer mockWriter(final PackOutput output, final int... bytesToWrite) throws IOException {
        Writer writer = mock(Writer.class);

        doAnswer(invocation -> {
                    for (int b : bytesToWrite) {
                        output.writeByte((byte) b);
                    }
                    return writer;
                })
                .when(writer)
                .write(any(Message.class));

        return writer;
    }

    private static OutboundMessageHandler newHandler(MessageFormat messageFormat) {
        return new OutboundMessageHandler(messageFormat, DEV_NULL_LOGGING);
    }
}


text:
@()(body: String => Html)

@defining(Application.currentUsername()) { auth =>
	@if( auth != null ) { @body(auth) }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="曹浩之Helloted的技术博客,用于记录一些技术成长过程中的技术分享,包括客户端iOS/Android,后台Pyhon/Java,跨平台开发Flutter">

    <title>UITableView实践(一):实现原理 - Helloted Blog</title>

    <link rel="canonical" href="http://www.helloted.com/ios/2018/04/25/tableView_1/">

    <link rel="shortcut icon" href="/img/favicon.ico">

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

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

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

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

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

            </button>
            Helloted Blog

                    Home

                    Categorys

                    Archive

                    About

                    APP

                    Mac App

UITableView实践(一):实现原理

通过查看UITableView的源码来查看实现原理

                    Posted by Ted on April 25, 2018

一、综述

UITableView应该是iOS中最经典也是最常见的一个控件了。使用很普遍

UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
tableView.delegate = self;
tableView.dataSource = self;
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"MyCellReuseIdentifier"];
[self.view addSubview:tableView];

#pragma mark - UITableViewDelegate
// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

#pragma mark - UITableViewDataSource
// Cell复用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCellReuseIdentifier"];
    return cell;
}

// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

Chameleon项目

If you're an iOS developer, you're already familiar with UIKit, the framework used to create apps for the iPhone, iPod and iPad. Chameleon is a drop in replacement for UIKit that runs on Mac OS X. In many cases, your iOS code doesn't need to change at all in order to run on a Mac.

This new framework is a clean room implementation of the work done by Apple for iOS. The only thing Chameleon has in common with UIKit are the public class and method names. The code is based on Apple's documentation and does not use any private APIs or other techniques disallowed by the Mac App Store.

我们知道在iOS上开发的视图使用UIKit,Mac OS则没有。Chameleon项目就是将UIKit的代码也可以运行在macOS上。我们可以通过Chameleon项目的源码来一探究竟,UITableView是如何实现的。

二、初始化

1、init

initWithFrame:(CGRect)frame style:(UITableViewStyle)theStyle是最常用的初始化方式,那么Chameleon项目是怎么做的呢?

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)theStyle
{
    if ((self=[super initWithFrame:frame])) {
        _style = theStyle;
       // 已生成Cell的缓存
        _cachedCells = [[NSMutableDictionary alloc] init];
       // Secitons的缓存
        _sections = [[NSMutableArray alloc] init];
       // 复用的Cells
        _reusableCells = [[NSMutableSet alloc] init];

      	// 一些基本属性的初始化
        self.separatorColor = [UIColor colorWithRed:.88f green:.88f blue:.88f alpha:1];
        self.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.showsHorizontalScrollIndicator = NO;
        self.allowsSelection = YES;
        self.allowsSelectionDuringEditing = NO;
        self.sectionHeaderHeight = self.sectionFooterHeight = 22;
        self.alwaysBounceVertical = YES;

        if (_style == UITableViewStylePlain) {
            self.backgroundColor = [UIColor whiteColor];
        }

      	// setNeedsLayout
        [self _setNeedsReload];
    }
    return self;
}

- (void)_setNeedsReload
{
    _needsReload = YES;
    [self setNeedsLayout];
}

初始化大概分为三部分:

用来装载实例的容器初始化

基本属性的默认值赋值

标记需要setNeedsLayout

我们知道,iOS的交互流程是这样的

所以,接下来就是layoutSubviews

2、layoutSubviews

- (void)layoutSubviews
{
    _backgroundView.frame = self.bounds;
    [self _reloadDataIfNeeded];
    [self _layoutTableView];
    [super layoutSubviews];
}

reloadData

- (void)reloadData
{
    // clear the caches and remove the cells since everything is going to change
    [[_cachedCells allValues] makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_reusableCells makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_reusableCells removeAllObjects];
    [_cachedCells removeAllObjects];

    // clear prior selection
    _selectedRow = nil;
    _highlightedRow = nil;

    // trigger the section cache to be repopulated
    [self _updateSectionsCache];
    [self _setContentSize];

    _needsReload = NO;
}

因为需要重新加载数据,所以将缓存以及复用的Cell都清空掉,SectionsCache也更新掉

layoutTableView

- (void)_layoutTableView
{
    // lays out headers and rows that are visible at the time. this should also do cell
    // dequeuing and keep a list of all existing cells that are visible and those
    // that exist but are not visible and are reusable
    // if there's no section cache, no rows will be laid out but the header/footer will (if any).

    const CGSize boundsSize = self.bounds.size;
    const CGFloat contentOffset = self.contentOffset.y;
    const CGRect visibleBounds = CGRectMake(0,contentOffset,boundsSize.width,boundsSize.height);
    CGFloat tableHeight = 0;

    if (_tableHeaderView) {
        CGRect tableHeaderFrame = _tableHeaderView.frame;
        tableHeaderFrame.origin = CGPointZero;
        tableHeaderFrame.size.width = boundsSize.width;
        _tableHeaderView.frame = tableHeaderFrame;
        tableHeight += tableHeaderFrame.size.height;
    }

    // layout sections and rows
    NSMutableDictionary *availableCells = [_cachedCells mutableCopy];
    const NSInteger numberOfSections = [_sections count];
    [_cachedCells removeAllObjects];

    for (NSInteger section=0; section<numberOfSections; section++) {
        CGRect sectionRect = [self rectForSection:section];
        tableHeight += sectionRect.size.height;
        if (CGRectIntersectsRect(sectionRect, visibleBounds)) {
            const CGRect headerRect = [self rectForHeaderInSection:section];
            const CGRect footerRect = [self rectForFooterInSection:section];
            UITableViewSection *sectionRecord = [_sections objectAtIndex:section];
            const NSInteger numberOfRows = sectionRecord.numberOfRows;

            if (sectionRecord.headerView) {
                sectionRecord.headerView.frame = headerRect;
            }

            if (sectionRecord.footerView) {
                sectionRecord.footerView.frame = footerRect;
            }

            for (NSInteger row=0; row<numberOfRows; row++) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
                CGRect rowRect = [self rectForRowAtIndexPath:indexPath];
                if (CGRectIntersectsRect(rowRect,visibleBounds) && rowRect.size.height > 0) {
                    UITableViewCell *cell = [availableCells objectForKey:indexPath] ?: [self.dataSource tableView:self cellForRowAtIndexPath:indexPath];
                    if (cell) {
                        [_cachedCells setObject:cell forKey:indexPath];
                        [availableCells removeObjectForKey:indexPath];
                        cell.highlighted = [_highlightedRow isEqual:indexPath];
                        cell.selected = [_selectedRow isEqual:indexPath];
                        cell.frame = rowRect;
                        cell.backgroundColor = self.backgroundColor;
                        [cell _setSeparatorStyle:_separatorStyle color:_separatorColor];
                        [self addSubview:cell];
                    }
                }
            }
        }
    }

    // remove old cells, but save off any that might be reusable
    for (UITableViewCell *cell in [availableCells allValues]) {
        if (cell.reuseIdentifier) {
            [_reusableCells addObject:cell];
        } else {
            [cell removeFromSuperview];
        }
    }

    // non-reusable cells should end up dealloced after at this point, but reusable ones live on in _reusableCells.

    // now make sure that all available (but unused) reusable cells aren't on screen in the visible area.
    // this is done becaue when resizing a table view by shrinking it's height in an animation, it looks better. The reason is that
    // when an animation happens, it sets the frame to the new (shorter) size and thus recalcuates which cells should be visible.
    // If it removed all non-visible cells, then the cells on the bottom of the table view would disappear immediately but before
    // the frame of the table view has actually animated down to the new, shorter size. So the animation is jumpy/ugly because
    // the cells suddenly disappear instead of seemingly animating down and out of view like they should. This tries to leave them
    // on screen as long as possible, but only if they don't get in the way.
    NSArray* allCachedCells = [_cachedCells allValues];
    for (UITableViewCell *cell in _reusableCells) {
        if (CGRectIntersectsRect(cell.frame,visibleBounds) && ![allCachedCells containsObject: cell]) {
            [cell removeFromSuperview];
        }
    }

    if (_tableFooterView) {
        CGRect tableFooterFrame = _tableFooterView.frame;
        tableFooterFrame.origin = CGPointMake(0,tableHeight);
        tableFooterFrame.size.width = boundsSize.width;
        _tableFooterView.frame = tableFooterFrame;
    }
}

这一步操作主要是将已经初始化的Cells重新布局,以及其他布局如HeadView,FootView的设置

三、Cell复用

cell在初始化的时候会绑定一个Identifier用以以后复用

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if ((self=[self initWithFrame:CGRectMake(0,0,320,_UITableViewDefaultRowHeight)])) {
        _style = style;
        _reuseIdentifier = [reuseIdentifier copy];
    }
    return self;
}

如上文,在UITableView初始化的时候,会初始化一个空的集合用来装载可复用的Cell。这是一个可变的集合

_reusableCells = [[NSMutableSet alloc] init];

在UITableView重载数据reloadData时,会将里面的cell清空

[_reusableCells makeObjectsPerformSelector:@selector(removeFromSuperview)];
[_reusableCells removeAllObjects];

在TableView滑动或者做了其他更新布局layoutTableView,将绑定了Identifier的cell装入集合以便复用

    // remove old cells, but save off any that might be reusable
    for (UITableViewCell *cell in [availableCells allValues]) {
        if (cell.reuseIdentifier) {
            [_reusableCells addObject:cell];
        } else {
            [cell removeFromSuperview];
        }
    }

下面是UITableview数据源协议的复用代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCellReuseIdentifier"];
    return cell;
}

根据Identifier将cell从集合中取出

- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier
{
    for (UITableViewCell *cell in _reusableCells) {
        if ([cell.reuseIdentifier isEqualToString:identifier]) {
            UITableViewCell *strongCell = cell;

            // the above strongCell reference seems totally unnecessary, but without it ARC apparently
            // ends up releasing the cell when it's removed on this line even though we're referencing it
            // later in this method by way of the cell variable. I do not like this.
            [_reusableCells removeObject:cell];
            return strongCell;
        }
    }

    return nil;
}

Cell复用的三个容器

NSMutableDictionary 类型 _cachedCells:用来存储当前屏幕上所有 Cell 与其对应的 indexPath。以键值对的关系进行存储。

NSMutableDictionary 类型 availableCells:当列表发生滑动的时候,部分 Cell 从屏幕移出,这个容器会对 _cachedCells 进行拷贝,然后将屏幕上此时的 Cell 全部去除。即最终取出所有退出屏幕的 Cell。

NSMutableSet 类型 _reusableCells:用来收集曾经出现过此时未出现在屏幕上的 Cell。当再出滑入主屏幕时,则直接使用其中的对象根据 CGRectIntersectsRect Rect 碰撞试验进行复用。

当到状态 ② 的时候,我们发现 _reusableCells 容器中,已经出现了状态 ① 中已经退出屏幕的 Cell 0。而当我们重新将 Cell 0 滑入界面的时候,在系统 addView 渲染阶段,会直接将 _reusableCells 中的 Cell 0 立即取出进行渲染,从而代替创建新的实例再进行渲染,简化了时间与性能上的开销。

参考:

https://github.com/BigZaphod/Chameleon

http://www.desgard.com/TableView-Reuse/

                        ← 上一篇

                        下一篇 →

Copyright © Helloted 2022


text:
package gov.hhs.onc.dcdt.dns.utils;

import gov.hhs.onc.dcdt.collections.impl.AbstractToolTransformer;
import gov.hhs.onc.dcdt.dns.DnsDclassType;
import gov.hhs.onc.dcdt.dns.DnsException;
import gov.hhs.onc.dcdt.dns.DnsKeyAlgorithmType;
import gov.hhs.onc.dcdt.dns.DnsRecordType;
import gov.hhs.onc.dcdt.dns.DnsSpfStrings;
import gov.hhs.onc.dcdt.dns.config.DnsRecordConfig;
import gov.hhs.onc.dcdt.utils.ToolArrayUtils;
import gov.hhs.onc.dcdt.utils.ToolClassUtils;
import gov.hhs.onc.dcdt.utils.ToolEnumUtils;
import gov.hhs.onc.dcdt.utils.ToolListUtils;
import gov.hhs.onc.dcdt.utils.ToolStringUtils;
import java.security.PublicKey;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnegative;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.xbill.DNS.CNAMERecord;
import org.xbill.DNS.DNSKEYRecord;
import org.xbill.DNS.DNSKEYRecord.Protocol;
import org.xbill.DNS.DNSSEC.DNSSECException;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.NSRecord;
import org.xbill.DNS.Name;
import org.xbill.DNS.Record;
import org.xbill.DNS.SRVRecord;

public abstract class ToolDnsRecordUtils {
    public static class DnsRecordDataStringTransformer extends AbstractToolTransformer<Record, String> {
        public final static DnsRecordDataStringTransformer INSTANCE = new DnsRecordDataStringTransformer();

        @Override
        protected String transformInternal(Record record) throws Exception {
            return record.rdataToString();
        }
    }

    public static class DnsRecordTargetTransformer extends AbstractToolTransformer<Record, Name> {
        public final static DnsRecordTargetTransformer INSTANCE = new DnsRecordTargetTransformer();

        @Nullable
        @Override
        protected Name transformInternal(Record record) throws Exception {
            // noinspection ConstantConditions
            switch (ToolEnumUtils.findByCode(DnsRecordType.class, record.getType())) {
                case CNAME:
                    return ((CNAMERecord) record).getTarget();

                case MX:
                    return ((MXRecord) record).getTarget();

                case NS:
                    return ((NSRecord) record).getTarget();

                case SRV:
                    return ((SRVRecord) record).getTarget();

                default:
                    return null;
            }
        }
    }

    public static class DnsRecordConfigTransformer extends AbstractToolTransformer<DnsRecordConfig<? extends Record>, Record> {
        public final static DnsRecordConfigTransformer INSTANCE = new DnsRecordConfigTransformer();

        @Override
        protected Record transformInternal(DnsRecordConfig<? extends Record> recordConfig) throws Exception {
            return recordConfig.toRecord();
        }
    }

    public final static DateFormat DATE_FORMAT_SERIAL = new SimpleDateFormat("yyyyMMdd");

    public static String buildSpf(String ... spfStrs) {
        return buildSpf(ToolArrayUtils.asList(spfStrs));
    }

    public static String buildSpf(List<String> spfStrs) {
        if (!Objects.equals(ToolListUtils.getFirst(spfStrs), DnsSpfStrings.MOD_VERSION_1)) {
            ToolListUtils.addFirst(spfStrs, DnsSpfStrings.MOD_VERSION_1);
        }

        if (!Objects.equals(ToolListUtils.getLast(spfStrs), DnsSpfStrings.MECH_ALL_FAIL)) {
            spfStrs.add(DnsSpfStrings.MECH_ALL_FAIL);
        }

        // noinspection ConstantConditions
        return ToolStringUtils.joinDelimit(spfStrs, DnsSpfStrings.DELIM);
    }

    @Nonnegative
    public static int generateSerial() {
        return generateSerial(0);
    }

    @Nonnegative
    public static int generateSerial(@Nonnegative int seqNum) {
        return Integer.parseInt(DATE_FORMAT_SERIAL.format(new Date()) + StringUtils.leftPad(Integer.toString(seqNum), 2, Integer.toString(0)));
    }

    @Nonnegative
    public static int getKeyTag(DnsKeyAlgorithmType keyAlgType, PublicKey publicKey) throws DnsException {
        try {
            return new DNSKEYRecord(Name.root, DnsDclassType.IN.getCode(), 0, 0, Protocol.DNSSEC, keyAlgType.getCode(), publicKey).getFootprint();
        } catch (DNSSECException e) {
            throw new DnsException(String.format("Unable to get key tag for public key (class=%s, algType=%s).", ToolClassUtils.getName(publicKey),
                keyAlgType.name()), e);
        }
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="EntityActivityTestFixture.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   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.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Activities;
using DataAccessLayer;
using EntityActivities;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EntityActivitiesUnitTests
{
    ///
    /// Test for campaign related activities
    ///
    [TestClass]
    public class EntityActivityTestFixture
    {
        /// Test auth user id
        private string authUserId;

        /// Test company entity id
        private EntityId companyEntityId;

        /// Per-test initialization
        [TestInitialize]
        public void TestInitialize()
        {
            this.authUserId = Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString("N")));
            this.companyEntityId = new EntityId();
        }

        ///
        /// Test creating a context from a valid request with a company ID
        ///
        [TestMethod]
        public void CreateContextWithCompany()
        {
            var request = new ActivityRequest
            {
                Task = "Test",
                Values =
                {
                    { "AuthUserId", this.authUserId },
                    { "CompanyEntityId", this.companyEntityId.ToString() }
                }
            };

            var context = EntityActivity.CreateRepositoryContext(RepositoryContextType.ExternalEntitySave, request, "CompanyEntityId");

            Assert.IsNotNull(context);
            Assert.AreEqual(this.authUserId, context.UserId);
            Assert.AreEqual(this.companyEntityId, context.ExternalCompanyId);
        }

        ///
        /// Test creating a context from a valid request without a company ID
        ///
        [TestMethod]
        public void CreateContextWithoutCompany()
        {
            var request = new ActivityRequest
            {
                Task = "Test",
                Values =
                {
                    { "AuthUserId", this.authUserId },
                }
            };

            var context = EntityActivity.CreateRepositoryContext(RepositoryContextType.InternalEntityGet, request);

            Assert.IsNotNull(context);
            Assert.AreEqual(this.authUserId, context.UserId);
            Assert.IsNull(context.ExternalCompanyId);
        }

        ///
        /// The entity filter is populated on the context according to the type of operation
        ///
        [TestMethod]
        public void CreateContextEntityFilterIsMapped()
        {
            var request = new ActivityRequest
            {
                Task = "Test",
                Values =
                {
                    { "AuthUserId", this.authUserId },
                }
            };

            // Internal operations map to the DefaultInternalEntityFilter
            var context = EntityActivity.CreateRepositoryContext(RepositoryContextType.InternalEntityGet, request);
            this.AssertEntityFilter(EntityActivity.DefaultInternalGetEntityFilter, context.EntityFilter);
            context = EntityActivity.CreateRepositoryContext(RepositoryContextType.InternalEntitySave, request);
            this.AssertEntityFilter(EntityActivity.DefaultInternalSaveEntityFilter, context.EntityFilter);

            // External operations map to the external get/set filters respectively
            context = EntityActivity.CreateRepositoryContext(RepositoryContextType.ExternalEntityGet, request);
            this.AssertEntityFilter(EntityActivity.DefaultGetEntityFilter, context.EntityFilter);
            context = EntityActivity.CreateRepositoryContext(RepositoryContextType.ExternalEntitySave, request);
            this.AssertEntityFilter(EntityActivity.DefaultSaveEntityFilter, context.EntityFilter);
        }

        ///
        /// Test creating a context from an invalid request missing the this.authUserId
        ///
        [TestMethod]
        [ExpectedException(typeof(KeyNotFoundException))]
        public void CreateContextMissingUserId()
        {
            var request = new ActivityRequest
            {
                Task = "Test",
                Values = { }
            };

            EntityActivity.CreateRepositoryContext(RepositoryContextType.InternalEntityGet, request);
        }

        ///
        /// Test creating a context from an invalid request missing the company ID
        ///
        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void CreateContextMissingCompanyId()
        {
            var request = new ActivityRequest
            {
                Task = "Test",
                Values =
                {
                    { "AuthUserId", this.authUserId }
                }
            };

            EntityActivity.CreateRepositoryContext(RepositoryContextType.ExternalEntitySave, request, "CompanyEntityId");
        }

        ///
        /// Compare the filters in two IEntityFilters to see if they are the same
        ///
        /// <param name="expectedEntityFilter">expected filter</param>
        /// <param name="actualEntityFilter">actual filter</param>
        private void AssertEntityFilter(IEntityFilter expectedEntityFilter, IEntityFilter actualEntityFilter)
        {
            Assert.IsTrue(expectedEntityFilter.Filters.SequenceEqual(actualEntityFilter.Filters));
        }
    }
}


text:
package io.petros.posts.activity.posts.view.recycler;

import java.util.List;

import io.petros.posts.model.Post;

public interface RecyclerViewAdapter {

    void reloadAdapter(final List<Post> posts);

    Post getItem(final int position);

}


text:
enum TestEnum {
    Six = 6,
    Seven = 7,
    Eight = 8
}

const SIX = TestEnum.Six
const SEVEN = TestEnum.Seven
const EIGHT = TestEnum.Eight

function foo(num: TestEnum) {
    return num
}

function bar() {
    let sixteen = 16;
    foo(s    // sixteen
    foo(S    // SEVEN; SIX
}


text:
Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case.

 * Abstract Factory groups object factories that have a common theme.
 * Builder constructs complex objects by separating construction and representation.
 * Factory Method creates objects without specifying the exact class to create.
 * Prototype creates objects by cloning an existing object.
 * Singleton restricts object creation for a class to only one instance.

### Structural

These concern class and object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.

 * Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.
 * Bridge decouples an abstraction from its implementation so that the two can vary independently.
 * Composite composes zero-or-more similar objects so that they can be manipulated as one object.
 * Decorator dynamically adds/overrides behaviour in an existing method of an object.
 * Facade provides a simplified interface to a large body of code.
 * Flyweight reduces the cost of creating and manipulating a large number of similar objects.
 * Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.

### Behavioural

Most of these design patterns are specifically concerned with communication between objects.

 * Chain of responsibility delegates commands to a chain of processing objects.
 * Command creates objects which encapsulate actions and parameters.
 * Interpreter implements a specialized language.
 * Iterator accesses the elements of an object sequentially without exposing its underlying representation.
 * Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
 * Memento provides the ability to restore an object to its previous state (undo).
 * Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.
 * State allows an object to alter its behavior when its internal state changes.
 * Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.
 * Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
 * Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object.


text:
package com.pdm.box2dhelloworld.android;

import android.os.Bundle;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.pdm.box2dhelloworld.Box2DHelloWorld;

public class AndroidLauncher extends AndroidApplication {
	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		initialize(new Box2DHelloWorld(), config);
	}
}


text:
class Publications::Users::PostsController < Publications::UsersController
  def index
    @posts      = @user.publication_posts.visible.newly.page(params[:page])
    @categories = @user.publication_categories
  end

  def show
    @post = @user.publication_posts.visible.find(params[:id])

    redirect_to user_posts_path(@user) unless @post.visible
    @comments = @post.comments.newly.page(params[:page])
  end
end


text:
# goconfig
[![MIT Licensed](https://img.shields.io/badge/license-MIT-green.svg)](https://tldrlegal.com/license/mit-license)

goconfig uses a struct as input and populates the fields of this struct with parameters from command line, environment variables and configuration file.

## Install

```
go get github.com/crgimenes/goconfig
```

## Example

```go
package main

import "github.com/crgimenes/goconfig"

/*
step 1: Declare your configuration struct,
it may or may not contain substructures.
*/

type mongoDB struct {
	Host string `cfgDefault:"example.com" cfgRequired:"true"`
	Port int    `cfgDefault:"999"`
}

type configTest struct {
	Domain    string
	DebugMode bool `json:"db" cfg:"db" cfgDefault:"false"`
	MongoDB   mongoDB
	IgnoreMe  string `cfg:"-"`
}

func main() {

	// step 2: Instantiate your structure.
	config := configTest{}

	// step 3: Pass the instance pointer to the parser
	err := goconfig.Parse(&config)
	if err != nil {
		println(err)
		return
	}

	/*
	   The parser populated your struct with the data
	   it took from environment variables and command
	   line and now you can use it.
	*/

	println("config.Domain......:", config.Domain)
	println("config.DebugMode...:", config.DebugMode)
	println("config.MongoDB.Host:", config.MongoDB.Host)
	println("config.MongoDB.Port:", config.MongoDB.Port)
}
```

With the example above try environment variables like *$DOMAIN* or *$MONGODB_HOST* and run the example again to see what happens.

You can also try using parameters on the command line, try -h to see the help.

## Contributing

- Fork the repo on GitHub
- Clone the project to your own machine
- Create a *branch* with your modifications `git checkout -b fantastic-feature`.
- Then _commit_ your changes `git commit -m 'Implementation of new fantastic feature'`
- Make a _push_ to your _branch_ `git push origin fantastic-feature`.
- Submit a **Pull Request** so that we can review your changes


text:
set -x

export ZOOBINDIR=$EQ_MATERIALS_DIR/zookeeper/bin
. $ZOOBINDIR/zkEnv.sh

while :
do
    java -cp $CLASSPATH:$EQ_MATERIALS_DIR/CreateZnodeZkCli CreateZnodeZkCli localhost:2181,localhost:2182,localhost:2183,localhost:2184,localhost:2185
    sleep 1
done


text:
// flow-typed signature: cb4d1fed7988debc8084fe86a06cd8a2
// flow-typed version: <<STUB>>/asar_v^0.13.0/flow_v0.39.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'asar'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'asar' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module 'asar/bin/asar' {
  declare module.exports: any;
}

declare module 'asar/lib/asar' {
  declare module.exports: any;
}

declare module 'asar/lib/crawlfs' {
  declare module.exports: any;
}

declare module 'asar/lib/disk' {
  declare module.exports: any;
}

declare module 'asar/lib/filesystem' {
  declare module.exports: any;
}

declare module 'asar/lib/snapshot' {
  declare module.exports: any;
}

// Filename aliases
declare module 'asar/bin/asar.js' {
  declare module.exports: $Exports<'asar/bin/asar'>;
}
declare module 'asar/lib/asar.js' {
  declare module.exports: $Exports<'asar/lib/asar'>;
}
declare module 'asar/lib/crawlfs.js' {
  declare module.exports: $Exports<'asar/lib/crawlfs'>;
}
declare module 'asar/lib/disk.js' {
  declare module.exports: $Exports<'asar/lib/disk'>;
}
declare module 'asar/lib/filesystem.js' {
  declare module.exports: $Exports<'asar/lib/filesystem'>;
}
declare module 'asar/lib/snapshot.js' {
  declare module.exports: $Exports<'asar/lib/snapshot'>;
}


text:
<?php

namespace System\Web\Mvc\Validators;

class IsNumeric extends Validator {

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

    public function isValid(){
        if(is_numeric($this->value)){
            return true;
        }
        return false;
    }
}


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

<title>MyStructure (Beginning Cryptography with Java Examples)</title>
<meta name="date" content="2015-01-24">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

chapter5

Class MyStructure

java.lang.Object

ASN1Encodable

chapter5.MyStructure

public class MyStructure
extends ASN1Encodable

Implementation of an example ASN.1 structure.

 MyStructure ::= SEQUENCE {
                   version INTEGER DEFAULT 0,
                   created GeneralizedTime,
                   baseData OCTET STRING,
                   extraData [0] UTF8String OPTIONAL,
                   commentData [1] UTF8String OPTIONAL }

Constructor Summary

Constructors

Constructor and Description

MyStructure(ASN1Sequence seq)

Constructor from an ASN.1 SEQUENCE

MyStructure(int version,
           java.util.Date created,
           byte[] baseData,
           java.lang.String extraData,
           java.lang.String commentData)

Constructor from corresponding Java objects and primitives.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

DERObject
toASN1Object()

Methods inherited from class java.lang.Object

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

Constructor Detail

MyStructure

public MyStructure(ASN1Sequence seq)

Constructor from an ASN.1 SEQUENCE

MyStructure

public MyStructure(int version,
                   java.util.Date created,
                   byte[] baseData,
                   java.lang.String extraData,
                   java.lang.String commentData)

Constructor from corresponding Java objects and primitives.

Method Detail

toASN1Object

public DERObject toASN1Object()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Examples from "Beginning Cryptography with Java"


text:
<?xml version="1.0"?>
<ConfirmTransportRequestResponse xmlns="http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/">
  <ConfirmTransportRequestResult>
    <TransportResult>
      <TransportStatus>CONFIRMING</TransportStatus>
    </TransportResult>
  </ConfirmTransportRequestResult>
  <ResponseMetadata>
    <RequestId>27bdc3df-d41b-4cf5-a96d-047815797bbf</RequestId>
  </ResponseMetadata>
</ConfirmTransportRequestResponse>


text:
package factories;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONException;
import org.json.JSONObject;
import pojos.GameCharacter;

import static factories.FactoryConfig.API_VERSION;
import static factories.FactoryConfig.REQUEST_ADDRESS;
import static factories.FactoryConfig.REQUEST_PORT;

public class BidirectionalGameCharacterFactory {

    private static final String FIELD_ID = "id";
    private static final String FIELD_NAME = "name";
    private static final String FIELD_PICTURE_PATH = "picturePath";
    private static final String FIELD_QUESTIONS_NUMBER = "questionsNumber";

    /**
     * Gets the attributes of a game character from de db service.
     * @param id id that identifies this game character.
     * @return A new game character instance.
     * @throws UnirestException
     */
    // TODO: Lacks security
    // overload may be added
    public static GameCharacter newInstance(Long id) throws UnirestException {
        String url = String.format("http://%s:%s/%s/character/%s",
                REQUEST_ADDRESS, REQUEST_PORT, API_VERSION, id.toString());

        HttpResponse<JsonNode> response = Unirest.get(url).asJson();
        JSONObject jsonObject = response.getBody().getObject();

        GameCharacter gameCharacter = null;
        try {

            gameCharacter = new GameCharacter();

            gameCharacter.setId(jsonObject.getLong(FIELD_ID));
            gameCharacter.setName(jsonObject.getString(FIELD_NAME));
            gameCharacter.setPicturePath(jsonObject.getString(FIELD_PICTURE_PATH));
            gameCharacter.setQuestionsNumber(jsonObject.getLong(FIELD_QUESTIONS_NUMBER));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return gameCharacter;
    }

    public static void main(String[] args) {
        GameCharacter character = new GameCharacter(Long.valueOf(2), "Bongo", "/home", 10L);
        try {
            remove(character);
        } catch (UnirestException e) {
            e.printStackTrace();
        }
    }

    public static Boolean remove(GameCharacter gameCharacter) throws UnirestException {
        String url = String.format("http://%s:%s/%s/character/%s",
                REQUEST_ADDRESS, REQUEST_PORT, API_VERSION, gameCharacter.getId().toString());

        HttpResponse<JsonNode> response = Unirest.delete(url).asJson();

        if(response.getStatus() == 200)
            return Boolean.TRUE;
        return Boolean.FALSE;
    }

    public static Boolean persist(GameCharacter gameCharacter) throws UnirestException {
        String url = String.format("http://%s:%s/%s/character/",
                REQUEST_ADDRESS, REQUEST_PORT, API_VERSION);

        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();

            jsonObject.put(FIELD_ID, gameCharacter.getId().toString());
            jsonObject.put(FIELD_NAME, gameCharacter.getName());
            jsonObject.put(FIELD_PICTURE_PATH, gameCharacter.getPicturePath());
            jsonObject.put(FIELD_QUESTIONS_NUMBER, gameCharacter.getQuestionsNumber());
        } catch (JSONException e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }

        HttpResponse<JsonNode> httpResponse = Unirest.post(url)
                .header("Content-Type", "application/json")
                .body(jsonObject.toString())
                .asJson();

        if (httpResponse.getStatus() == 201) {
            return Boolean.TRUE;
        }

        return Boolean.FALSE;
    }

}


text:
namespace fdw.Common.Data
{
    public abstract class FdwDataObject : IFdwDataObject
    {
        private readonly int _id;

        protected FdwDataObject(int id)
        {
            _id = id;
        }

        public int Id { get { return _id; } }
    }
}


text:
package test

import (
	"math/rand"
	"reflect"
	"testing"
	"time"

	info "github.com/google/cadvisor/info/v1"
	"github.com/google/cadvisor/storage"
)

type TestStorageDriver interface {
	StatsEq(a *info.ContainerStats, b *info.ContainerStats) bool
	storage.StorageDriver
}

func buildTrace(cpu, mem []uint64, duration time.Duration) []*info.ContainerStats {
	if len(cpu) != len(mem) {
		panic("len(cpu) != len(mem)")
	}

	ret := make([]*info.ContainerStats, len(cpu))
	currentTime := time.Now()

	var cpuTotalUsage uint64 = 0
	for i, cpuUsage := range cpu {
		cpuTotalUsage += cpuUsage
		stats := new(info.ContainerStats)
		stats.Timestamp = currentTime
		currentTime = currentTime.Add(duration)

		stats.Cpu.Usage.Total = cpuTotalUsage
		stats.Cpu.Usage.User = stats.Cpu.Usage.Total
		stats.Cpu.Usage.System = 0
		stats.Cpu.Usage.PerCpu = []uint64{cpuTotalUsage}

		stats.Memory.Usage = mem[i]

		stats.Network.RxBytes = uint64(rand.Intn(10000))
		stats.Network.RxErrors = uint64(rand.Intn(1000))
		stats.Network.TxBytes = uint64(rand.Intn(100000))
		stats.Network.TxErrors = uint64(rand.Intn(1000))

		stats.Filesystem = make([]info.FsStats, 1)
		stats.Filesystem[0].Device = "/dev/sda1"
		stats.Filesystem[0].Limit = 1024000000
		stats.Filesystem[0].Usage = 1024000
		ret[i] = stats
	}
	return ret
}

func TimeEq(t1, t2 time.Time, tolerance time.Duration) bool {
	// t1 should not be later than t2
	if t1.After(t2) {
		t1, t2 = t2, t1
	}
	diff := t2.Sub(t1)
	if diff <= tolerance {
		return true
	}
	return false
}

func durationEq(a, b time.Duration, tolerance time.Duration) bool {
	if a > b {
		a, b = b, a
	}
	diff := a - b
	if diff <= tolerance {
		return true
	}
	return false
}

const (
	// 10ms, i.e. 0.01s
	timePrecision time.Duration = 10 * time.Millisecond
)

// This function is useful because we do not require precise time
// representation.
func DefaultStatsEq(a, b *info.ContainerStats) bool {
	if !TimeEq(a.Timestamp, b.Timestamp, timePrecision) {
		return false
	}
	if !reflect.DeepEqual(a.Cpu, b.Cpu) {
		return false
	}
	if !reflect.DeepEqual(a.Memory, b.Memory) {
		return false
	}
	if !reflect.DeepEqual(a.Network, b.Network) {
		return false
	}
	if !reflect.DeepEqual(a.Filesystem, b.Filesystem) {
		return false
	}

	return true
}

// This function will generate random stats and write
// them into the storage. The function will not close the driver
func StorageDriverFillRandomStatsFunc(
	containerName string,
	N int,
	driver TestStorageDriver,
	t *testing.T,
) {
	cpuTrace := make([]uint64, 0, N)
	memTrace := make([]uint64, 0, N)

	// We need N+1 observations to get N samples
	for i := 0; i < N+1; i++ {
		cpuTrace = append(cpuTrace, uint64(rand.Intn(1000)))
		memTrace = append(memTrace, uint64(rand.Intn(1000)))
	}

	samplePeriod := 1 * time.Second

	ref := info.ContainerReference{
		Name: containerName,
	}

	trace := buildTrace(cpuTrace, memTrace, samplePeriod)

	for _, stats := range trace {
		err := driver.AddStats(ref, stats)
		if err != nil {
			t.Fatalf("unable to add stats: %v", err)
		}
	}
}

func StorageDriverTestRetrievePartialRecentStats(driver TestStorageDriver, t *testing.T) {
	defer driver.Close()
	N := 100
	memTrace := make([]uint64, N)
	cpuTrace := make([]uint64, N)
	for i := 0; i < N; i++ {
		memTrace[i] = uint64(i + 1)
		cpuTrace[i] = uint64(1)
	}

	ref := info.ContainerReference{
		Name: "container",
	}

	trace := buildTrace(cpuTrace, memTrace, 1*time.Second)

	for _, stats := range trace {
		driver.AddStats(ref, stats)
	}

	recentStats, err := driver.RecentStats(ref.Name, 10)
	if err != nil {
		t.Fatal(err)
	}
	if len(recentStats) == 0 {
		t.Fatal("should at least store one stats")
	}

	if len(recentStats) > 10 {
		t.Fatalf("returned %v stats, not 10.", len(recentStats))
	}

	actualRecentStats := trace[len(trace)-len(recentStats):]

	// The returned stats should be sorted in time increasing order
	for i, s := range actualRecentStats {
		r := recentStats[i]
		if !driver.StatsEq(s, r) {
			t.Errorf("unexpected stats %+v with memory usage %v; should be %+v", r, r.Memory.Usage, s)
		}
	}
}

func StorageDriverTestRetrieveAllRecentStats(driver TestStorageDriver, t *testing.T) {
	defer driver.Close()
	N := 100
	memTrace := make([]uint64, N)
	cpuTrace := make([]uint64, N)
	for i := 0; i < N; i++ {
		memTrace[i] = uint64(i + 1)
		cpuTrace[i] = uint64(1)
	}

	ref := info.ContainerReference{
		Name: "container",
	}

	trace := buildTrace(cpuTrace, memTrace, 1*time.Second)

	for _, stats := range trace {
		driver.AddStats(ref, stats)
	}

	recentStats, err := driver.RecentStats(ref.Name, -1)
	if err != nil {
		t.Fatal(err)
	}
	if len(recentStats) == 0 {
		t.Fatal("should at least store one stats")
	}
	if len(recentStats) > N {
		t.Fatalf("returned %v stats, not %d.", len(recentStats), N)
	}

	actualRecentStats := trace[len(trace)-len(recentStats):]

	// The returned stats should be sorted in time increasing order
	for i, s := range actualRecentStats {
		r := recentStats[i]
		if !driver.StatsEq(s, r) {
			t.Errorf("unexpected stats %+v with memory usage %v", r, r.Memory.Usage)
		}
	}
}

func StorageDriverTestNoRecentStats(driver TestStorageDriver, t *testing.T) {
	defer driver.Close()
	nonExistContainer := "somerandomecontainer"
	stats, _ := driver.RecentStats(nonExistContainer, -1)
	if len(stats) > 0 {
		t.Errorf("RecentStats() returns %v stats on non exist container", len(stats))
	}
}

func StorageDriverTestRetrieveZeroRecentStats(driver TestStorageDriver, t *testing.T) {
	defer driver.Close()
	N := 100
	memTrace := make([]uint64, N)
	cpuTrace := make([]uint64, N)
	for i := 0; i < N; i++ {
		memTrace[i] = uint64(i + 1)
		cpuTrace[i] = uint64(1)
	}

	ref := info.ContainerReference{
		Name: "container",
	}

	trace := buildTrace(cpuTrace, memTrace, 1*time.Second)

	for _, stats := range trace {
		driver.AddStats(ref, stats)
	}

	recentStats, err := driver.RecentStats(ref.Name, 0)
	if err != nil {
		t.Fatal(err)
	}
	if len(recentStats) > 0 {
		t.Errorf("RecentStats() returns %v stats when requests for 0 stats", len(recentStats))
	}
}


text:
package com.ait.lienzo.client.core.event;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;

public abstract class AbstractNodeEvent<H extends EventHandler> extends GwtEvent<H> implements INodeEvent
{
    private boolean m_dead = false;

    @Override
    public final boolean isAlive()
    {
        return (false == m_dead);
    }

    @Override
    public final void preventDefault()
    {
        m_dead = true;
    }

    @Override
    public final void stopPropagation()
    {
        m_dead = true;
    }

    @Override
    public final GwtEvent<?> getNodeEvent()
    {
        return this;
    }
}


text:
title:  Inside Story
date:  20/03/2020
---

#### Heart for Mission

_By Joyce_

Joyce is a 25-year-old Global Mission pioneer who, with another female Global Mission pioneer, planted a church for young people in a city of 10 million people. Because she lives in a closed country hostile to Christianity, Adventist Mission is not publishing her full name or location. Here's what Joyce said when asked by editor Andrew McChesney, "Why did you decide to be a missionary?"

I have one sister, Sarah, and she was born with a congenital heart defect.

My grandmother was very worried, and she looked and looked for the best hospital. But the doctors couldn't help Sarah. So, my grandmother visited our traditional places of worship to ask for help, but no one there could help my sister.

Finally, the doctor told my parents that he could do nothing more.

"Take care of Sarah as best as you can", he said. "If she wants to something special to eat or a new toy, give it to her to make her happy".

One day, when Sarah was 7, a Seventh-day Adventist relative came to visit from far away. She saw that my grandmother was worried about Sarah, and she said, "If you believe in Jesus, you will be blessed".

The next Sabbath, my grandmother took me to church. I was 3. Church members gathered in a circle around us and prayed for us and for Sarah.

Just a few days later, Sarah was healed! Her heart was perfect! The doctor couldn't believe it. He ran several medical tests, and he couldn't find any problems with Sarah's heart. It was a miracle!

The miracle changed my family. My grandmother and my parents started going to church every Sabbath, and soon they were baptized. Then my parents decided that they wanted to tell other people about Jesus. So, they quit their jobs, received church training, and became Global Mission pioneers. When my sister grew up, she also became a Global Mission pioneer. Last year, I decided to become a Global Mission pioneer.

As a missionary, I give Bible studies, I pray with people, and I preach. I work with a partner, another Global Mission pioneer who is 23, and we just opened a new church for young people in this city.

Relatives who aren't Christians don't understand why I am a missionary. They tell me to look for another job. Sometimes I feel discouraged when I hear such negative words, but my parents pray for me. My mother even fasts and prays for me on Sabbaths. My parents remind me that I am not working for man. I am working for God.

My parents are right. I am working for God. God is so wonderful and powerful in healing my sister. I believe God is leading me every step of the way.

Inside Story~


text:
module Nutmeg
  class TreeFromJson
    attr_accessor :base_tree, :tags, :tree_hash, :tree, :tag_tree

    def initialize(data)
      @data = JSON.load(data)
      @base_tree = @data
      @tag_tree = Tree::TreeNode.new("ROOT", {:tag => "root",:otag => "root", :level => nil, :slug => "root"})
      base_tree.each do |node|
        node_tree = @tag_tree << Tree::TreeNode.new(node["id"], node_hash(node))
        build_node(node_tree, node)
      end
      @tree = Nutmeg::TagTree.new(@tag_tree)
      nil
    end

    private
      def node_hash(node)
        {
          :tag_id => node["data"]["id"],
          :tag => node["id"],
          :slug => node["data"]["slug"],
          :name => node["data"]["name"],
          :description => node["data"]["description"],
          :tag_image => node["data"]["tag_image"],
          :tag_image_file_name => node["data"]["tag_image_file_name"]
        }
      end

      def build_node(parent, node)
        # puts "Building node #{node['id']}"
        # puts "===="
        #puts node["children"].map{|d| d["id"]}

        node["children"].each do |child|
          #puts "Adding #{child['id']} to #{node['id']}"
          node_tree = parent << Tree::TreeNode.new(child["id"], node_hash(child))
          build_node(node_tree, child)
        end
      end

      def get_levels
        @levels = @tree_hash.collect do |tag|
          tag[:level]
        end.uniq.sort
      end

      def get_children(parent, level)
        @tree_hash.select{|node| node[:parent] == parent && node[:level] > level }
      end

      def traverse_tree
        base_tree.each do |node|
          walk(node.symbolize_keys!)
        end
      end

      def walk(array, level = 0, parent = nil)
        array.keys.each do |key|
          @tree_hash << {:tag => [key, level,parent].join("_"), :level => level, :parent => parent, :otag => key, :slug => @tags[key], :tag_id => key}
          return if array[key].nil?
          array[key].compact.each do |child|
            walk(child, level + 1, [key, level,parent].join("_"))
          end
        end
      end
  end
end


text:
namespace cc {

class MockLayerTreeMutator : public LayerTreeMutator {
 public:
  MockLayerTreeMutator();
  ~MockLayerTreeMutator() override;
  // gmock cannot mock methods with move-only args so we forward it ourself.
  bool Mutate(std::unique_ptr<MutatorInputState> input_state,
              MutateQueuingStrategy queueing_strategy,
              DoneCallback done_callback) override {
    MutateRef(input_state.get());
    return true;
  }

  MOCK_METHOD1(MutateRef, void(MutatorInputState* input_state));
  MOCK_METHOD1(SetClient, void(LayerTreeMutatorClient* client));
  MOCK_METHOD0(HasMutators, bool());
};

}  // namespace cc

#endif  // CC_TEST_MOCK_LAYER_TREE_MUTATOR_H_


text:
<html>

<head>
    <!-- <link rel="stylesheet" href="../src/lww.css" /> -->
    <link rel="stylesheet" href="../src/style/css/lww.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <!-- <script defer src="./demo.js"></script> -->
    <script defer src="../dist/lww.js"></script>
    <script defer src="./demo-src.js"></script>
</head>

<body ng-app "LWWDemo">
</body>

</html>


text:
cask "protonvpn" do
  version "1.9.0,12151435"
  sha256 "03f54302936f0cdf59d651731291b9df64411842a6766d7bfcd0a0d45649f4ac"

  url "https://protonvpn.com/download/ProtonVPN_mac_v#{version.before_comma}.dmg"
  name "ProtonVPN"
  desc "VPN client focusing on security"
  homepage "https://protonvpn.com/"

  livecheck do
    url "https://protonvpn.com/download/macos-update2.xml"
    strategy :sparkle
  end

  auto_updates true
  depends_on macos: ">= :sierra"

  app "ProtonVPN.app"

  uninstall launchctl: "ch.protonvpn.ProtonVPNStarter",
            quit:      "ch.protonvpn.mac"

  zap trash: [
    "~/Library/Application Scripts/ch.protonvpn.ProtonVPNStarter",
    "~/Library/Application Scripts/ch.protonvpn.mac",
    "~/Library/Application Support/CrashReporter/ProtonVPN*",
    "~/Library/Application Support/ProtonVPN",
    "~/Library/Caches/SentryCrash/ProtonVPN",
    "~/Library/Caches/ch.protonvpn.mac",
    "~/Library/Caches/com.apple.nsurlsessiond/Downloads/ch.protonvpn.mac",
    "~/Library/Containers/ch.protonvpn.*",
    "~/Library/Cookies/ch.protonvpn.mac.binarycookies",
    "~/Library/Logs/ProtonVPN.log",
    "~/Library/Preferences/ch.protonvpn.mac.plist",
    "~/Library/WebKit/ch.protonvpn.mac",
  ]
end


text:
package org.camunda.bpm.engine.test.history.useroperationlog;

import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.interceptor.CommandExecutor;
import org.camunda.bpm.engine.impl.oplog.UserOperationLogContext;
import org.camunda.bpm.engine.impl.oplog.UserOperationLogContextEntry;
import org.camunda.bpm.engine.impl.persistence.entity.PropertyChange;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.util.ProcessEngineBootstrapRule;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;

import java.util.Arrays;
import java.util.UUID;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class CustomUserOperationLogTest  {

    public static final String USER_ID = "demo";

    @ClassRule
    public static ProcessEngineBootstrapRule bootstrapRule = new ProcessEngineBootstrapRule(
            "org/camunda/bpm/engine/test/history/useroperationlog/enable.legacy.user.operation.log.camunda.cfg.xml");

    private static final String TASK_ID = UUID.randomUUID().toString();

    private CommandExecutor commandExecutor;
    private HistoryService historyService;

    @Before
    public void setUp() throws Exception {
        commandExecutor = ((ProcessEngineConfigurationImpl)bootstrapRule.getProcessEngine().getProcessEngineConfiguration()).getCommandExecutorTxRequired();
        historyService = bootstrapRule.getProcessEngine().getHistoryService();
    }

    @Test
    public void testDoNotOverwriteUserId() throws Exception {
        commandExecutor.execute(new Command<Void>(){
            @Override
            public Void execute(final CommandContext commandContext) {
                final UserOperationLogContext userOperationLogContext = new UserOperationLogContext();
                userOperationLogContext.setUserId("kermit");

                final UserOperationLogContextEntry entry = new UserOperationLogContextEntry("foo", "bar");
                entry.setPropertyChanges(Arrays.asList(new PropertyChange(null, null, null)));
                entry.setTaskId(TASK_ID);
                userOperationLogContext.addEntry(entry);

                commandContext.getOperationLogManager().logUserOperations(userOperationLogContext);
                return null;
            }
        });

        // and check its there
        assertThat(historyService.createUserOperationLogQuery().taskId(TASK_ID).singleResult().getUserId(), is("kermit"));
    }
}


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <!--Create a module that works with moving div elements-->
    <title>Task 2</title>
    <style>
        button#addRectBtn {
            margin-left: 500px;
        }
    </style>
    <script>
        var movingShapes = (function () {
            function generateDiv() {
                var generated = document.createElement('div');
                var width = 50;
                var height = 50;
                generated.style.width = width + "px";
                generated.style.height = height + "px";

                generated.style.textAlign = 'center';

                generated.style.borderRadius = width + "px";
                generated.style.borderWidth = 5 + "px";
                generated.style.borderStyle = 'solid';

                generated.style.backgroundColor = getRandomColor();
                generated.style.color = getRandomColor();
                generated.style.borderColor = getRandomColor();

                generated.style.position = 'absolute';

                return generated;
            }

            function getRandomColor() {
                var red = Math.floor(Math.random() * 256);
                var green = Math.floor(Math.random() * 256);
                var blue = Math.floor(Math.random() * 256);

                return "rgb(" + red + "," + green + "," + blue + ")";
            }

            function addMovingShape(type) {
                var div = generateDiv();
                div.setAttribute('movementConst', 0);
                document.body.appendChild(div);
                if (type == 'rect') {
                    moveThatRect(div);
                }
                else {
                    moveThatEll(div);
                }

            }

            var rectX = 300;
            var rectY = 300;

            function moveThatRect(div) {
                function rectMovement() {
                    var movement = parseInt(div.getAttribute('movementConst'));
                    movement+=3;
                    if (movement === 360) {
                        movement = 0;
                    }

                    if (movement <= 90) {
                        var x = (rectX * (movement / 90));
                        div.style.left = x + "px";
                    }
                    else if (movement <= 180) {
                        var y = (rectY * ((movement-90) / 90));
                        div.style.top = y + "px";
                    }
                    else if (movement <= 270) {
                        var x2 = (rectX - rectX * ((movement - 180) / 90));
                        div.style.left = x2 + "px";
                    }
                    else {
                        var y2 = (rectY - rectY * ((movement - 270) / 90));
                        div.style.top = y2 + "px";
                    }

                    div.setAttribute('movementConst', movement);
                }
                setInterval(rectMovement, 75);
            }

            var ellX = 300;
            var ellY = 150;
            var ellR = 150;
            function moveThatEll(div) {
                function ellMovement() {
                    var movement = parseInt(div.getAttribute('movementConst'));
                    movement += 3;
                    if (movement === 360) {
                        movement = 0;
                    }

                    var left = ellX + Math.cos((2 * 3.14 / 180) * (movement)) * ellR;
                    var right = 2 * (ellY + Math.sin((2 * 3.14 / 180) * (movement)) * ellR);
                    div.style.left = left + "px";
                    div.style.top = right + "px";

                    div.setAttribute('movementConst', movement);
                }
                setInterval(ellMovement, 100);
            }

            return {
                add: addMovingShape
            };
        })();

    </script>
</head>
<body>
    <button id="addRectBtn">Add Rect Move</button><button id="addCircleBtn">Add Circle Move</button><br />
    <script>
        //testing
        movingShapes.add('ellipse')
        var addCircleBtn = document.getElementById('addCircleBtn');
        addCircleBtn.addEventListener('click', function () {
            movingShapes.add('ellipse');
        });

        var addRectBtn = document.getElementById('addRectBtn');
        addRectBtn.addEventListener('click', function () {
            movingShapes.add('rect');
        });
        //movingShapes.add('rect');
        //movingShapes.add('ellipse');
    </script>
</body>
</html>


text:
<component name="ArtifactManager">
  <artifact type="jar" name="morphling-builder-base:jar">
    <output-path>$PROJECT_DIR$/../libs</output-path>
    <root id="archive" name="morphling-builder-base.jar">
      <element id="module-output" name="morphling-builder-base" />
    </root>
  </artifact>
</component>


text:
using ApiMeter.Configuration;
using ApiMeter.Domain;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace ApiMeter.Providers.BufferProvider
{
    /// <summary>
    /// A Redis data provider to write raw metric data into
    /// </summary>
    public class RedisBufferDataProvider : BufferDataProviderBase
    {
        private static RedisClient _client;

        public RedisBufferDataProvider(IApiMeterConfiguration configuration)
            : base(configuration)
        {
            _client = new RedisClient(base.configuration.RedisServerUrl, base.configuration.RedisServerPort);
            _client.ConnectTimeout = base.configuration.RedisConnectionTimeout;
            _client.SendTimeout = base.configuration.RedisSendTimeout;

        }

        /// <summary>
        /// Writes request and response raw data into Redis
        /// </summary>
        /// <param name="data">Request and response metrics in raw form</param>
        public override void Write(RequestResponseData data)
        {
            try
            {
                _client.Add<RequestResponseData>(data.ID.ToString(), data, TimeSpan.FromMinutes(base.configuration.RedisTimeToLive));
            }
            catch (Exception ex)
            {
                Trace.Write(ex.Message);
            }
        }

        /// <summary>
        /// Gets all the available request and response data available on Redis
        /// </summary>
        /// <returns>A collection of available request and response data</returns>
        public override IList<RequestResponseData> GetAll()
        {
            try
            {
                return _client.GetAll<RequestResponseData>();
            }
            catch (Exception ex)
            {
                Trace.Write(ex.Message);
                return null;
            }
        }

        /// <summary>
        /// Deletes a particular request and response data item from Redis
        /// </summary>
        /// <param name="data">Data to be deleted</param>
        public override void Delete(RequestResponseData data)
        {
            try
            {
                _client.Del(data.ID.ToString());
            }
            catch (Exception ex)
            {
                Trace.Write(ex.Message);
            }
        }
    }
}


text:
namespace boost{
namespace intrusive{
   //Create namespace to avoid compilation errors
}}

namespace boost{ namespace container{ namespace container_detail{

namespace bi = boost::intrusive;

}}}

#include <utility>
#include <memory>
#include <functional>
#include <iosfwd>
#include <string>

/// @endcond

//////////////////////////////////////////////////////////////////////////////
//                             Containers
//////////////////////////////////////////////////////////////////////////////

namespace boost {
namespace container {

//vector class
template <class T
         ,class A = std::allocator<T> >
class vector;

//vector class
template <class T
         ,class A = std::allocator<T> >
class stable_vector;

//vector class
template <class T
         ,class A = std::allocator<T> >
class deque;

//list class
template <class T
         ,class A = std::allocator<T> >
class list;

//slist class
template <class T
         ,class A = std::allocator<T> >
class slist;

//set class
template <class T
         ,class Pred  = std::less<T>
         ,class A = std::allocator<T> >
class set;

//multiset class
template <class T
         ,class Pred  = std::less<T>
         ,class A = std::allocator<T> >
class multiset;

//map class
template <class Key
         ,class T
         ,class Pred  = std::less<Key>
         ,class A = std::allocator<std::pair<const Key, T> > >
class map;

//multimap class
template <class Key
         ,class T
         ,class Pred  = std::less<Key>
         ,class A = std::allocator<std::pair<const Key, T> > >
class multimap;

//flat_set class
template <class T
         ,class Pred  = std::less<T>
         ,class A = std::allocator<T> >
class flat_set;

//flat_multiset class
template <class T
         ,class Pred  = std::less<T>
         ,class A = std::allocator<T> >
class flat_multiset;

//flat_map class
template <class Key
         ,class T
         ,class Pred  = std::less<Key>
         ,class A = std::allocator<std::pair<Key, T> > >
class flat_map;

//flat_multimap class
template <class Key
         ,class T
         ,class Pred  = std::less<Key>
         ,class A = std::allocator<std::pair<Key, T> > >
class flat_multimap;

//basic_string class
template <class CharT
         ,class Traits = std::char_traits<CharT>
         ,class A  = std::allocator<CharT> >
class basic_string;

//! Type used to tag that the input range is
//! guaranteed to be ordered
struct ordered_range_impl_t {};

//! Type used to tag that the input range is
//! guaranteed to be ordered and unique
struct ordered_unique_range_impl_t{};

/// @cond

typedef ordered_range_impl_t * ordered_range_t;
typedef ordered_unique_range_impl_t *ordered_unique_range_t;

/// @endcond

//! Value used to tag that the input range is
//! guaranteed to be ordered
static const ordered_range_t ordered_range = 0;

//! Value used to tag that the input range is
//! guaranteed to be ordered and unique
static const ordered_unique_range_t ordered_unique_range = 0;

/// @cond

namespace detail_really_deep_namespace {

//Otherwise, gcc issues a warning of previously defined
//anonymous_instance and unique_instance
struct dummy
{
   dummy()
   {
      (void)ordered_range;
      (void)ordered_unique_range;
   }
};

}  //detail_really_deep_namespace {

/// @endcond

}}  //namespace boost { namespace container {

#endif //#ifndef BOOST_CONTAINER_CONTAINER_FWD_HPP


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin_model extends CI_Model {
    public function get_user(){
        $data = array(
            'username'=>$this->input->post('username'),
            'password'=>md5(md5($this->input->post('password')))
        );
        $query = $this->db->get_where('user',$data);
        if($query->num_rows()>0){

            $data = array(
                    'user_id' => $query->row(0)->id,
                    'username'=>  $query->row(0)->username,
                    'role'=> $query->row(0)->role,
                    'id_personalia'=>$query->row(0)->id_personalia
            );

            $this->session->set_userdata($data);
            return $query->result();
        }else{
            return false;
        }
    }
    public function is_logged_in(){
        return $this->session->userdata('user_id') != False;
    }
    public function is_admin(){
        return $this->session->userdata('role') == "admin";
    }
    public function is_user(){
        return $this->session->userdata('role') == "user";
    }

    public function get_post(){
        $this->db->select('*');
        $this->db->from('post');
        $this->db->join('category', 'post.category = category.id_category');
        $query = $this->db->get();
        if($query->num_rows()>=0){
            return $query->result_array();
        }else{
            return false;
        }
    }

}


text:
using System;
using Excel = Microsoft.Office.Interop.Excel;

namespace Wbs.Everdigm.Desktop
{
    public class OfficeConvert
    {
        /// <summary>
        /// 把Excel文件转换成PDF格式文件
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool ExcelConvertToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;
            Excel.ApplicationClass application = null;
            Excel.Workbook workBook = null;
            try
            {
                application = new Excel.ApplicationClass();
                object target = targetPath;
                object type = targetType;
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                    missing, missing, missing, missing, missing, missing, missing, missing, missing);
                workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
    }
}


text:
'use strict';
const common = require('../common');
const assert = require('assert');

const binding = process.binding('http_parser');
const methods = binding.methods;
const HTTPParser = binding.HTTPParser;

const REQUEST = HTTPParser.REQUEST;
const RESPONSE = HTTPParser.RESPONSE;

const kOnHeaders = HTTPParser.kOnHeaders | 0;
const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0;
const kOnBody = HTTPParser.kOnBody | 0;
const kOnMessageComplete = HTTPParser.kOnMessageComplete | 0;

// The purpose of this test is not to check HTTP compliance but to test the
// binding. Tests for pathological http messages should be submitted
// upstream to https://github.com/joyent/http-parser for inclusion into
// deps/http-parser/test.c

function newParser(type) {
  const parser = new HTTPParser(type);

  parser.headers = [];
  parser.url = '';

  parser[kOnHeaders] = function(headers, url) {
    parser.headers = parser.headers.concat(headers);
    parser.url += url;
  };

  parser[kOnHeadersComplete] = function(info) {
  };

  parser[kOnBody] = common.mustNotCall('kOnBody should not be called');

  parser[kOnMessageComplete] = function() {
  };

  return parser;
}

function mustCall(f, times) {
  let actual = 0;

  process.setMaxListeners(256);
  process.on('exit', function() {
    assert.strictEqual(actual, times || 1);
  });

  return function() {
    actual++;
    return f.apply(this, Array.prototype.slice.call(arguments));
  };
}

function expectBody(expected) {
  return mustCall(function(buf, start, len) {
    const body = String(buf.slice(start, start + len));
    assert.strictEqual(body, expected);
  });
}

//
// Simple request test.
//
{
  const request = Buffer.from('GET /hello HTTP/1.1\r\n\r\n');

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 1);
    assert.strictEqual(method, methods.indexOf('GET'));
    assert.strictEqual(url || parser.url, '/hello');
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser.execute(request, 0, request.length);

  //
  // Check that if we throw an error in the callbacks that error will be
  // thrown from parser.execute()
  //

  parser[kOnHeadersComplete] = function(info) {
    throw new Error('hello world');
  };

  parser.reinitialize(HTTPParser.REQUEST);

  assert.throws(function() {
    parser.execute(request, 0, request.length);
  }, Error, 'hello world');
}

//
// Simple response test.
//
{
  const request = Buffer.from(
    'HTTP/1.1 200 OK\r\n' +
    'Content-Type: text/plain\r\n' +
    'Content-Length: 4\r\n' +
    '\r\n' +
    'pong'
  );

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, undefined);
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 1);
    assert.strictEqual(statusCode, 200);
    assert.strictEqual(statusMessage, 'OK');
  };

  const onBody = (buf, start, len) => {
    const body = String(buf.slice(start, start + len));
    assert.strictEqual(body, 'pong');
  };

  const parser = newParser(RESPONSE);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser[kOnBody] = mustCall(onBody);
  parser.execute(request, 0, request.length);
}

//
// Response with no headers.
//
{
  const request = Buffer.from(
    'HTTP/1.0 200 Connection established\r\n\r\n');

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 0);
    assert.strictEqual(method, undefined);
    assert.strictEqual(statusCode, 200);
    assert.strictEqual(statusMessage, 'Connection established');
    assert.deepStrictEqual(headers || parser.headers, []);
  };

  const parser = newParser(RESPONSE);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser.execute(request, 0, request.length);
}

//
// Trailing headers.
//
{
  const request = Buffer.from(
    'POST /it HTTP/1.1\r\n' +
    'Transfer-Encoding: chunked\r\n' +
    '\r\n' +
    '4\r\n' +
    'ping\r\n' +
    '0\r\n' +
    'Vary: *\r\n' +
    'Content-Type: text/plain\r\n' +
    '\r\n'
  );

  let seen_body = false;

  const onHeaders = (headers, url) => {
    assert.ok(seen_body); // trailers should come after the body
    assert.deepStrictEqual(headers,
                           ['Vary', '*', 'Content-Type', 'text/plain']);
  };

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('POST'));
    assert.strictEqual(url || parser.url, '/it');
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 1);
    // expect to see trailing headers now
    parser[kOnHeaders] = mustCall(onHeaders);
  };

  const onBody = (buf, start, len) => {
    const body = String(buf.slice(start, start + len));
    assert.strictEqual(body, 'ping');
    seen_body = true;
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser[kOnBody] = mustCall(onBody);
  parser.execute(request, 0, request.length);
}

//
// Test header ordering.
//
{
  const request = Buffer.from(
    'GET / HTTP/1.0\r\n' +
    'X-Filler: 1337\r\n' +
    'X-Filler:   42\r\n' +
    'X-Filler2:  42\r\n' +
    '\r\n'
  );

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('GET'));
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 0);
    assert.deepStrictEqual(
      headers || parser.headers,
      ['X-Filler', '1337', 'X-Filler', '42', 'X-Filler2', '42']);
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser.execute(request, 0, request.length);
}

//
// Test large number of headers
//
{
  // 256 X-Filler headers
  const lots_of_headers = 'X-Filler: 42\r\n'.repeat(256);

  const request = Buffer.from(
    'GET /foo/bar/baz?quux=42#1337 HTTP/1.0\r\n' +
    lots_of_headers +
    '\r\n'
  );

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('GET'));
    assert.strictEqual(url || parser.url, '/foo/bar/baz?quux=42#1337');
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 0);

    headers = headers || parser.headers;

    assert.strictEqual(headers.length, 2 * 256); // 256 key/value pairs
    for (let i = 0; i < headers.length; i += 2) {
      assert.strictEqual(headers[i], 'X-Filler');
      assert.strictEqual(headers[i + 1], '42');
    }
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser.execute(request, 0, request.length);
}

//
// Test request body
//
{
  const request = Buffer.from(
    'POST /it HTTP/1.1\r\n' +
    'Content-Type: application/x-www-form-urlencoded\r\n' +
    'Content-Length: 15\r\n' +
    '\r\n' +
    'foo=42&bar=1337'
  );

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('POST'));
    assert.strictEqual(url || parser.url, '/it');
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 1);
  };

  const onBody = (buf, start, len) => {
    const body = String(buf.slice(start, start + len));
    assert.strictEqual(body, 'foo=42&bar=1337');
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser[kOnBody] = mustCall(onBody);
  parser.execute(request, 0, request.length);
}

//
// Test chunked request body
//
{
  const request = Buffer.from(
    'POST /it HTTP/1.1\r\n' +
    'Content-Type: text/plain\r\n' +
    'Transfer-Encoding: chunked\r\n' +
    '\r\n' +
    '3\r\n' +
    '123\r\n' +
    '6\r\n' +
    '123456\r\n' +
    'A\r\n' +
    '1234567890\r\n' +
    '0\r\n'
  );

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('POST'));
    assert.strictEqual(url || parser.url, '/it');
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 1);
  };

  let body_part = 0;
  const body_parts = ['123', '123456', '1234567890'];

  const onBody = (buf, start, len) => {
    const body = String(buf.slice(start, start + len));
    assert.strictEqual(body, body_parts[body_part++]);
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser[kOnBody] = mustCall(onBody, body_parts.length);
  parser.execute(request, 0, request.length);
}

//
// Test chunked request body spread over multiple buffers (packets)
//
{
  let request = Buffer.from(
    'POST /it HTTP/1.1\r\n' +
    'Content-Type: text/plain\r\n' +
    'Transfer-Encoding: chunked\r\n' +
    '\r\n' +
    '3\r\n' +
    '123\r\n' +
    '6\r\n' +
    '123456\r\n'
  );

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('POST'));
    assert.strictEqual(url || parser.url, '/it');
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 1);
  };

  let body_part = 0;
  const body_parts =
          ['123', '123456', '123456789', '123456789ABC', '123456789ABCDEF'];

  const onBody = (buf, start, len) => {
    const body = String(buf.slice(start, start + len));
    assert.strictEqual(body, body_parts[body_part++]);
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser[kOnBody] = mustCall(onBody, body_parts.length);
  parser.execute(request, 0, request.length);

  request = Buffer.from(
    '9\r\n' +
    '123456789\r\n' +
    'C\r\n' +
    '123456789ABC\r\n' +
    'F\r\n' +
    '123456789ABCDEF\r\n' +
    '0\r\n'
  );

  parser.execute(request, 0, request.length);
}

//
// Stress test.
//
{
  const request = Buffer.from(
    'POST /helpme HTTP/1.1\r\n' +
    'Content-Type: text/plain\r\n' +
    'Transfer-Encoding: chunked\r\n' +
    '\r\n' +
    '3\r\n' +
    '123\r\n' +
    '6\r\n' +
    '123456\r\n' +
    '9\r\n' +
    '123456789\r\n' +
    'C\r\n' +
    '123456789ABC\r\n' +
    'F\r\n' +
    '123456789ABCDEF\r\n' +
    '0\r\n'
  );

  function test(a, b) {
    const onHeadersComplete = (versionMajor, versionMinor, headers,
                               method, url, statusCode, statusMessage,
                               upgrade, shouldKeepAlive) => {
      assert.strictEqual(method, methods.indexOf('POST'));
      assert.strictEqual(url || parser.url, '/helpme');
      assert.strictEqual(versionMajor, 1);
      assert.strictEqual(versionMinor, 1);
    };

    let expected_body = '123123456123456789123456789ABC123456789ABCDEF';

    const onBody = (buf, start, len) => {
      const chunk = String(buf.slice(start, start + len));
      assert.strictEqual(expected_body.indexOf(chunk), 0);
      expected_body = expected_body.slice(chunk.length);
    };

    const parser = newParser(REQUEST);
    parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
    parser[kOnBody] = onBody;
    parser.execute(a, 0, a.length);
    parser.execute(b, 0, b.length);

    assert.strictEqual(expected_body, '');
  }

  for (let i = 1; i < request.length - 1; ++i) {
    const a = request.slice(0, i);
    console.error(`request.slice(0, ${i}) = ${JSON.stringify(a.toString())}`);
    const b = request.slice(i);
    console.error(`request.slice(${i}) = ${JSON.stringify(b.toString())}`);
    test(a, b);
  }
}

//
// Byte by byte test.
//
{
  const request = Buffer.from(
    'POST /it HTTP/1.1\r\n' +
    'Content-Type: text/plain\r\n' +
    'Transfer-Encoding: chunked\r\n' +
    '\r\n' +
    '3\r\n' +
    '123\r\n' +
    '6\r\n' +
    '123456\r\n' +
    '9\r\n' +
    '123456789\r\n' +
    'C\r\n' +
    '123456789ABC\r\n' +
    'F\r\n' +
    '123456789ABCDEF\r\n' +
    '0\r\n'
  );

  const onHeadersComplete = (versionMajor, versionMinor, headers,
                             method, url, statusCode, statusMessage,
                             upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('POST'));
    assert.strictEqual(url || parser.url, '/it');
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 1);
    assert.deepStrictEqual(
      headers || parser.headers,
      ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']);
  };

  let expected_body = '123123456123456789123456789ABC123456789ABCDEF';

  const onBody = (buf, start, len) => {
    const chunk = String(buf.slice(start, start + len));
    assert.strictEqual(expected_body.indexOf(chunk), 0);
    expected_body = expected_body.slice(chunk.length);
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
  parser[kOnBody] = onBody;

  for (let i = 0; i < request.length; ++i) {
    parser.execute(request, i, 1);
  }

  assert.strictEqual(expected_body, '');
}

//
// Test parser reinit sequence.
//
{
  const req1 = Buffer.from(
    'PUT /this HTTP/1.1\r\n' +
    'Content-Type: text/plain\r\n' +
    'Transfer-Encoding: chunked\r\n' +
    '\r\n' +
    '4\r\n' +
    'ping\r\n' +
    '0\r\n'
  );

  const req2 = Buffer.from(
    'POST /that HTTP/1.0\r\n' +
    'Content-Type: text/plain\r\n' +
    'Content-Length: 4\r\n' +
    '\r\n' +
    'pong'
  );

  const onHeadersComplete1 = (versionMajor, versionMinor, headers,
                              method, url, statusCode, statusMessage,
                              upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('PUT'));
    assert.strictEqual(url, '/this');
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 1);
    assert.deepStrictEqual(
      headers,
      ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']);
  };

  const onHeadersComplete2 = (versionMajor, versionMinor, headers,
                              method, url, statusCode, statusMessage,
                              upgrade, shouldKeepAlive) => {
    assert.strictEqual(method, methods.indexOf('POST'));
    assert.strictEqual(url, '/that');
    assert.strictEqual(versionMajor, 1);
    assert.strictEqual(versionMinor, 0);
    assert.deepStrictEqual(
      headers,
      ['Content-Type', 'text/plain', 'Content-Length', '4']
    );
  };

  const parser = newParser(REQUEST);
  parser[kOnHeadersComplete] = onHeadersComplete1;
  parser[kOnBody] = expectBody('ping');
  parser.execute(req1, 0, req1.length);

  parser.reinitialize(REQUEST);
  parser[kOnBody] = expectBody('pong');
  parser[kOnHeadersComplete] = onHeadersComplete2;
  parser.execute(req2, 0, req2.length);
}

// Test parser 'this' safety
// https://github.com/joyent/node/issues/6690
assert.throws(function() {
  const request = Buffer.from('GET /hello HTTP/1.1\r\n\r\n');

  const parser = newParser(REQUEST);
  const notparser = { execute: parser.execute };
  notparser.execute(request, 0, request.length);
}, TypeError);


text:
package org.nanoframework.orm.jedis.exception;

/**
 * Jedis操作异常处理类.
 *
 * @author yanghe
 * @since 1.0
 */
public class TimeoutException extends RuntimeException {
    private static final long serialVersionUID = -6151365904901655741L;

    public TimeoutException() {

    }

    public TimeoutException(final String message) {
        super(message);
    }

    public TimeoutException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public TimeoutException(final Throwable cause) {
        super(cause);
    }

}


text:
package com.dianping.cat.report.page.matrix.service;

import java.util.Date;

import org.unidal.lookup.annotation.Inject;

import com.dianping.cat.consumer.matrix.MatrixAnalyzer;
import com.dianping.cat.consumer.matrix.model.entity.MatrixReport;
import com.dianping.cat.helper.TimeHelper;
import com.dianping.cat.report.service.BaseHistoricalModelService;
import com.dianping.cat.report.service.ModelRequest;

public class HistoricalMatrixService extends BaseHistoricalModelService<MatrixReport> {

	@Inject
	private MatrixReportService m_reportService;

	public HistoricalMatrixService() {
		super(MatrixAnalyzer.ID);
	}

	@Override
	protected MatrixReport buildModel(ModelRequest request) throws Exception {
		String domain = request.getDomain();
		long date = request.getStartTime();
		MatrixReport report = getReportFromDatabase(date, domain);

		return report;
	}

	private MatrixReport getReportFromDatabase(long timestamp, String domain) throws Exception {
		return m_reportService.queryReport(domain, new Date(timestamp), new Date(timestamp + TimeHelper.ONE_HOUR));
	}

}


text:
'''
Regex Version of strip()

Write a function that takes a string and does the same thing as the strip()
string method. If no other arguments are passed other than the string to strip,
then whitespace characters will be removed from the beginning and end of
the string. Otherwise, the characters specified in the second argument to
the function will be removed from the string.

'''

from re import compile

def stripInRegexWay(string, bad=" "):
    strip_regex = compile(r'(^[{0}]*)(.*?)([{1}]*$)'.format(bad, bad))
    return strip_regex.search(string).group(2)

assert stripInRegexWay('  dsadas  ') == 'dsadas'
assert stripInRegexWay(' dasd dsd  ') == 'dasd dsd'
assert stripInRegexWay('addsada', 'ad') == 's'
assert stripInRegexWay('adsradsnads', 'ads') == 'radsn'


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * The Date.prototype property "setMonth" has { DontEnum } attributes
 *
 * @path ch15/15.9/15.9.5/15.9.5.38/S15.9.5.38_A1_T1.js
 * @description Checking absence of ReadOnly attribute
 */

x = Date.prototype.setMonth;
if(x === 1)
  Date.prototype.setMonth = 2;
else
  Date.prototype.setMonth = 1;
if (Date.prototype.setMonth === x) {
  $ERROR('#1: The Date.prototype.setMonth has not the attribute ReadOnly');
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingLeft="10dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/white">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/jiangnandaxue"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="笃学尚行,止于至善"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/statusBar2"
            />
    </LinearLayout>
    <LinearLayout
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingLeft="10dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/white">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/zhishan"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="至善学院"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="博学善思,勇于创新,超越自我"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/statusBar2"
            />
    </LinearLayout>
    <LinearLayout
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingLeft="10dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/white">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/shipin"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="食品学院"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="勤业,创新,争先,共赢"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/statusBar2"
            />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/ll_shejixueyuan"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingLeft="10dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/white">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/sheji"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="设计学院"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="爱设计,爱设计学院"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/statusBar2"
            />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/ll_sheji"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="视觉传达系"
            android:textSize="15sp"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:text="1301班"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:text="1302班"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="工业设计系"
            android:textSize="15sp"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:text="1304班"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:text="1305班"/>
        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/jiangran1" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姜然" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="虽然很热,但还是想靠近太阳..."/>
    </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/liusuo1" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="刘硕" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="且行且珍惜"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/sunluyang1" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="孙路阳" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="人生百味皆是经历,当无惧无悔"/>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>