text:
package com.fsryan.forsuredb.integrationtest.singletable;

import com.fsryan.forsuredb.annotations.*;
import com.fsryan.forsuredb.api.FSGetApi;
import com.fsryan.forsuredb.api.Retriever;
import com.fsryan.forsuredb.integrationtest.RandomString;
import com.google.auto.value.AutoValue;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

@FSTable("all_types")
@FSStaticData("all_types_static_data.xml")
public interface AllTypesTable extends FSGetApi {
    @FSColumn("int_column") @FSDefault("42") int intColumn(Retriever retriever);
    @FSColumn("integer_wrapper_column") @Index Integer integerWrapperColumn(Retriever retriever);
    @FSColumn("long_column") long longColumn(Retriever retriever);
    @FSColumn("long_wrapper_column") Long longWrapperColumn(Retriever retriever);
    @FSColumn("float_column") float floatColumn(Retriever retriever);
    @FSColumn("float_wrapper_column") Float floatWrapperColumn(Retriever retriever);
    @FSColumn("double_column") double doubleColumn(Retriever retriever);
    @FSColumn("double_wrapper_column") Double doubleWrapperColumn(Retriever retriever);
    @FSColumn("byte_array_column") byte[] byteArrayColumn(Retriever retriever);
    @FSColumn("string_column") @Unique(index = true) String stringColumn(Retriever retriever);
    @FSColumn("big_integer_column") BigInteger bigIntegerColumn(Retriever retriever);
    @FSColumn("big_decimal_column") BigDecimal bigDecimalColumn(Retriever retriever);
    @FSColumn("date_column") Date dateColumn(Retriever retriever);
    @FSColumn("boolean_column") boolean booleanColumn(Retriever retriever);
    @FSColumn("boolean_wrapper_column") Boolean booleanWrapperColumn(Retriever retriever);

    /**
     * <p>This is atypical for a table that is not a doc store. This is used to make data generation for tests easier.
     * If you want to serialize to objects, then I recommend using {@link com.fsryan.forsuredb.api.FSDocStoreGetApi}
     * as opposed to {@link FSGetApi}
     */
    @AutoValue
    abstract class Record {

        @AutoValue.Builder
        public static abstract class Builder {
            public abstract Builder bigDecimalColumn(@Nullable BigDecimal bigDecimalColumn);
            public abstract Builder bigIntegerColumn(@Nullable BigInteger bigIntegerColumn);
            public abstract Builder booleanColumn(boolean booleanColumn);
            public abstract Builder booleanWrapperColumn(@Nullable Boolean booleanWrapperColumn);
            public abstract Builder byteArrayColumn(@Nullable byte[] byteArrayColumn);
            public abstract Builder dateColumn(@Nullable Date dateColumn);
            public abstract Builder doubleColumn(double doubleColumn);
            public abstract Builder doubleWrapperColumn(@Nullable Double doubleWrapperColumn);
            public abstract Builder floatColumn(float floatColumn);
            public abstract Builder floatWrapperColumn(@Nullable Float floatWrapperColumn);
            public abstract Builder intColumn(int intColumn);
            public abstract Builder integerWrapperColumn(@Nullable Integer integerWrapperColumn);
            public abstract Builder longColumn(long longColumn);
            public abstract Builder longWrapperColumn(@Nullable Long longWrapperColumn);
            public abstract Builder stringColumn(@Nullable String stringColumn);
            public abstract Record build();
        }

        public static Record createRandom() {
            return createRandomBuilder().build();
        }

        public static Record createRandom(int byteLength, int stringLength) {
            return createRandomBuilder(byteLength, stringLength).build();
        }

        public static Builder createRandomBuilder() {
            return createRandomBuilder(
                    ThreadLocalRandom.current().nextInt(32) + 1,
                    // by default, strings are between 33 and 64 characters to minimize likelihood of collisions
                    ThreadLocalRandom.current().nextInt(32) + 33
            );
        }

        public static Builder createRandomBuilder(int byteLength, int stringLength) {
            long l1 = ThreadLocalRandom.current().nextLong();
            long l2 = ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE);
            long l3 = ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE);
            final BigDecimal bigDecimal = new BigDecimal(Long.toString(l1) + Long.toString(l2) + "." + Long.toString(l3));

            l1 = ThreadLocalRandom.current().nextLong();
            l2 = ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE);
            final BigInteger bigInteger = new BigInteger(Long.toString(l1) + Long.toString(l2));

            final boolean booleanColumn = ThreadLocalRandom.current().nextBoolean();
            final Boolean booleanWrapperColumn = ThreadLocalRandom.current().nextBoolean();
            final byte[] byteArrayColumn = new byte[Math.max(0, byteLength)];
            ThreadLocalRandom.current().nextBytes(byteArrayColumn);
            final Date dateColumn = new Date(ThreadLocalRandom.current().nextLong(0, new Date().getTime()));
            final double doubleColumn = ThreadLocalRandom.current().nextDouble() * ThreadLocalRandom.current().nextLong();
            final Double doubleWrapperColumn = ThreadLocalRandom.current().nextDouble() * ThreadLocalRandom.current().nextLong();
            final float floatColumn = ThreadLocalRandom.current().nextFloat() * ThreadLocalRandom.current().nextInt();
            final Float floatWrapperColumn = ThreadLocalRandom.current().nextFloat() * ThreadLocalRandom.current().nextInt();
            final int intColumn = ThreadLocalRandom.current().nextInt();
            final Integer integerWrapperColumn = ThreadLocalRandom.current().nextInt();
            final long longColumn = ThreadLocalRandom.current().nextLong();
            final Long longWrapperColumn = ThreadLocalRandom.current().nextLong();
            final String stringColumn = new RandomString(stringLength).nextString();
            return builder()
                    .bigDecimalColumn(bigDecimal)
                    .bigIntegerColumn(bigInteger)
                    .booleanColumn(booleanColumn)
                    .booleanWrapperColumn(booleanWrapperColumn)
                    .byteArrayColumn(byteArrayColumn)
                    .dateColumn(dateColumn)
                    .doubleColumn(doubleColumn)
                    .doubleWrapperColumn(doubleWrapperColumn)
                    .floatColumn(floatColumn)
                    .floatWrapperColumn(floatWrapperColumn)
                    .intColumn(intColumn)
                    .integerWrapperColumn(integerWrapperColumn)
                    .longColumn(longColumn)
                    .longWrapperColumn(longWrapperColumn)
                    .stringColumn(stringColumn);
        }

        public static Record create(@Nullable BigDecimal bigDecimal,
                                    @Nullable BigInteger bigInteger,
                                    boolean booleanColumn,
                                    @Nullable Boolean booleanWrapperColumn,
                                    @Nullable byte[] byteArrayColumn,
                                    @Nullable Date dateColumn,
                                    double doubleColumn,
                                    @Nullable Double doubleWrapperColumn,
                                    float floatColumn,
                                    @Nullable Float floatWrapperColumn,
                                    int intColumn,
                                    @Nullable Integer integerWrapperColumn,
                                    long longColumn,
                                    @Nullable Long longWrapperColumn,
                                    @Nullable String stringColumn) {
            return builder()
                    .bigDecimalColumn(bigDecimal)
                    .bigIntegerColumn(bigInteger)
                    .booleanColumn(booleanColumn)
                    .booleanWrapperColumn(booleanWrapperColumn)
                    .byteArrayColumn(byteArrayColumn)
                    .dateColumn(dateColumn)
                    .doubleColumn(doubleColumn)
                    .doubleWrapperColumn(doubleWrapperColumn)
                    .floatColumn(floatColumn)
                    .floatWrapperColumn(floatWrapperColumn)
                    .intColumn(intColumn)
                    .integerWrapperColumn(integerWrapperColumn)
                    .longColumn(longColumn)
                    .longWrapperColumn(longWrapperColumn)
                    .stringColumn(stringColumn)
                    .build();
        }

        public static Builder builder() {
            return new AutoValue_AllTypesTable_Record.Builder();
        }

        @Nullable public abstract BigDecimal bigDecimalColumn();
        @Nullable public abstract BigInteger bigIntegerColumn();
        public abstract boolean booleanColumn();
        @Nullable public abstract Boolean booleanWrapperColumn();
        @Nullable public abstract byte[] byteArrayColumn();
        @Nullable public abstract Date dateColumn();
        public abstract double doubleColumn();
        @Nullable public abstract Double doubleWrapperColumn();
        public abstract float floatColumn();
        @Nullable public abstract Float floatWrapperColumn();
        public abstract int intColumn();
        @Nullable public abstract Integer integerWrapperColumn();
        public abstract long longColumn();
        @Nullable public abstract Long longWrapperColumn();
        @Nullable public abstract String stringColumn();
        @Nonnull public abstract Builder toBuilder();
    }
}


text:
FROM node:7.4

ADD init-app.sh /usr/local/bin/

# Set up an unprivileged user so that we can drop out of root.
# Make /home/paradrop so that npm can drop some files in there.
# Make /opt/paradrop/app for installing the app files.
# Add cap_net_bind_service to node so that it can bind to ports 1-1024.
RUN useradd --system --uid 999 paradrop && \
    mkdir -p /home/paradrop && \
    chown paradrop /home/paradrop && \
    mkdir -p /opt/paradrop/app && \
    chown paradrop /opt/paradrop/app && \
    chmod a+s /opt/paradrop/app && \
    setcap 'cap_net_bind_service=+ep' /usr/local/bin/node

# Install popular tools here.
RUN npm install --global gulp-cli

# Defang setuid/setgid binaries.
RUN find / -perm +6000 -type f -exec chmod a-s {} \; || true

WORKDIR /opt/paradrop/app

# Copy paradrop.yaml and package.json, the latter only if it exists. Then call
# init-app.sh to install dependencies. These layers will be cached as long as
# the requirements do not change.
ONBUILD COPY paradrop.yaml package.jso[n] /opt/paradrop/app/
ONBUILD RUN init-app.sh

# Now copy the rest of the files.
ONBUILD COPY . /opt/paradrop/app/
ONBUILD RUN chown paradrop:paradrop -R /opt/paradrop/app

ONBUILD USER paradrop

redpajama_set_name: RedPajamaGithub


text: Hometasks for 3rd semestr


text:
Admin.StatsUsersTableView = Ember.View.extend({
  tagName: 'table',

  classNames: ['table', 'table-striped', 'table-bordered', 'table-condensed'],

  didInsertElement: function() {
    this.$().DataTable({
      searching: false,
      serverSide: true,
      ajax: {
        url: '/admin/stats/users.json',
        data: _.bind(function(data) {
          var query = this.get('controller.query.params');
          return _.extend({}, data, query);
        }, this)
      },
      order: [[4, 'desc']],
      columns: [
        {
          data: 'email',
          title: 'Email',
          defaultContent: '-',
          render: _.bind(function(email, type, data) {
            if(type === 'display' && email && email !== '-') {
              var params = _.clone(this.get('controller.query.params'));
              params.search = 'user_id:"' + data.id + '"';
              var link = '#/stats/logs/' + $.param(params);

              return '' + _.escape(email) + '';
            }

            return email;
          }, this),
        },
        {
          data: 'first_name',
          title: 'First Name',
          defaultContent: '-',
          render: Admin.DataTablesHelpers.renderEscaped,
        },
        {
          data: 'last_name',
          title: 'Last Name',
          defaultContent: '-',
          render: Admin.DataTablesHelpers.renderEscaped,
        },
        {
          data: 'created_at',
          type: 'date',
          title: 'Signed Up',
          defaultContent: '-',
          render: Admin.DataTablesHelpers.renderTime,
        },
        {
          data: 'hits',
          title: 'Hits',
          defaultContent: '-',
          render: function(number, type) {
            if(type === 'display' && number && number !== '-') {
              return numeral(number).format('0,0');
            }

            return number;
          },
        },
        {
          data: 'last_request_at',
          type: 'date',
          title: 'Last Request',
          defaultContent: '-',
          render: Admin.DataTablesHelpers.renderTime,
        },
        {
          data: 'use_description',
          title: 'Use Description',
          defaultContent: '-',
          render: Admin.DataTablesHelpers.renderEscaped,
        },
      ]
    });
  },

  refreshData: function() {
    this.$().DataTable().draw();
  }.observes('controller.query.params.query', 'controller.query.params.search', 'controller.query.params.start_at', 'controller.query.params.end_at'),
});


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/errl/errled.H $                               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2011,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef ERRLED_H
#define ERRLED_H

/**
 *  @file errled.H
 *
 *  @brief A class for the 'ED' section of an error log.
 *  This class manages those ErrlEntry data items that are destined
 *  to be saved in the ED PEL section.
*/

#include <errl/errlentry.H>
#include <errl/errlsctnhdr.H>

namespace ERRORLOG
{

class ErrlED
{

    // ErrlEntry may access private elements of this class.  Data items that
    // you would expect to be part of ErrlEntry are actually instance data
    // in this class.
    friend class ErrlEntry;

private:

    /**
     *  @brief Data export size. Amount of flat storage (in bytes) required to
     *  store the object.
     *
     *  @return size in bytes
     */
    uint64_t flatSize() const;

    /**
     *  @brief Data Export facility. Flatten the object into PEL for the
     *  'ED' section.
     *
     *  @param[in,out] io_pBuffer Pointer to buffer where flat data will go.
     *  @param[in]     i_cbBuffer Count of bytes in target buffer
     *  @return        uint64_t   The size of the flattened data in the output buffer
     *                            or 0 if i_cbBuffer is not large enough to hold the data
     *
     */
    uint64_t flatten(  void * io_pBuffer, const uint64_t i_cbBuffer );

    /**
     * @brief Import data
     * @param[in] i_buf, the pointer to the flattened data
     * @return number of bytes consumed
     */
    uint64_t unflatten( const void * i_buf );

    /**  @brief Set the component ID into the ED.
     *   Only should be called from ErrlEntry instance.
     *
     *   @param[in]  i_compId   component ID
     */
    void setComponentId( compId_t i_compId );

    static const int VER = 1; // section version
    static const int SST = 0; // section subtype
    static const int SLEN = 0xD4; // 212 total bytes
                                  // 8 section header
                                  // 4 creatorId
                                  // 200 data

    pelEDHeaderSection_t iv = {
        pelSectionHeader_t { ERRL_SID_EXTENDED_USER_DEFINED,
                             ErrlED::SLEN,
                             ErrlED::VER,
                             ErrlED::SST,
                             0 } // Component ID is zero until commit time
    };

    static_assert(SLEN == sizeof(iv));

};

/*****************************************************************************/
// Export data size

inline uint64_t ErrlED::flatSize() const
{
    return sizeof(iv);
}

/*****************************************************************************/
// For user headers, the comp ID represents the committing component.

inline void ErrlED::setComponentId( const compId_t i_compId )
{
  iv.sectionheader.compId = i_compId;
}

} // namespace

#endif //ERRLED_H


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

namespace DSDDemo.Permits
{
    public class ConditionalUse : BasePermit
    {
        public ConditionalUse()
        {
            permitCount = 956;
            prefix = "CU";
            displayLabel = "Conditional Use (CU)";
            int group = 1;
            Field field;

            field = new Field("Conditional Use Desc");
            field.GroupOrder = group++;
            field.GroupName = "1";
            AddField(field);

            field = new Field("# of Parcels Approved");
            AddField(field);
            field = new Field("Ave Acreage per Parcel");
            AddField(field);
            field = new Field("City Impact/JEPA");
            AddField(field);
            field = new Field("Fire District");
            AddField(field);
            field = new Field("Irrigation District");
            AddField(field);
            field = new Field("Highway District");
            AddField(field);
            field = new Field("Flood District");
            AddField(field);
            field = new Field("School District");
            AddField(field);
            field = new Field("State/Federal #1");
            AddField(field);
            field = new Field("State/Federal #2");
            AddField(field);
            field = new Field("Notification Distance");
            AddField(field);

            field = new Field("Photo");
            field.GroupOrder = group++;
            field.GroupName = "Traffic";
            AddField(field);
            field = new Field("Existing Parking");
            AddField(field);
            field = new Field("Proposed Parking");
            AddField(field);
            field = new Field("Eliminated Parking");
            AddField(field);
            field = new Field("Other Parking Provision");
            AddField(field);
            field = new Field("Residents-Workers");
            AddField(field);
            field = new Field("Hours");
            AddField(field);
            field = new Field("Traffic");
            AddField(field);
            field = new Field("Shoreline");
            AddField(field);
            field = new Field("Designation");
            AddField(field);

            field = new Field("Blank Field");
            field.GroupOrder = group++;
            field.GroupName = "Request Schedule";
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);

            field = new Field("Blank Field");
            field.GroupOrder = group++;
            field.GroupName = "FCO's info";
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);

            field = new Field("Blank Field");
            field.GroupOrder = group++;
            field.GroupName = "General info";
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);

            field = new Field("Blank Field");
            field.GroupOrder = group++;
            field.GroupName = "Appeal Info";
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);
            field = new Field("Blank Field");
            AddField(field);

        }
    }
}


text:
.. include:: meta-admin_referrers.rst

.. todo:: Not yet documented.


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 */
package com.example.tutorial;

public enum PhoneType implements org.apache.thrift.TEnum {
  MOBILE(0),
  HOME(1),
  WORK(2);

  private final int value;

  private PhoneType(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static PhoneType findByValue(int value) {
    switch (value) {
      case 0:
        return MOBILE;
      case 1:
        return HOME;
      case 2:
        return WORK;
      default:
        return null;
    }
  }
}


text:
package com.helicalinsight.datasource.managed;

/**
 * Created by user on 3/23/2016.
 *
 * @author Rajasekhar
 */
class JdbcQueryTimeoutException extends RuntimeException {

    public JdbcQueryTimeoutException(String message) {
        super(message);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    	android:layout_height="wrap_content">

    <fragment android:name="uk.co.threeequals.notepad.ItemFragment"
        android:id="@+id/list"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/notes_fragment_list"
        android:layout_margin="@dimen/horizontal_padding" />
</LinearLayout>


text:
"""

Module: credentials.py
Desc: tracking credentials and other confidential info outside database
Author: on_three
Email: on.three.email@gmail.com
DATE: Thursday, Sept 11th 2014

BING CREDENTIALS to import

*THE VALUES BELOW ARE DUMMY VALUES*
*DO NOT ENTER YOUR ACTUAL CREDENTIALS IN A FILE*
*IN CONFIGURATION MANAGEMENT*

"""

BING_CLIENT_ID =  u'XXXXX'
BING_CLIENT_SECRET =  u'XXXXX'

from irc import foreground
from irc import background
from irc import style

class Stream(object):
	def __init__(self, name, desc, url):
		self._name = name
		self._desc = desc
		self._url = url
	def __unicode__(self):
		return foreground(u'white') + background(u'black') \
			+ u' ' + self._name + u' ' \
			+ foreground(u'white') + background(u'green') + u' ' + self._url + u' '\
			+ foreground(u'white') + background('black') + u' ' + self._desc + u' '
	def __str__(self):
		return unicode(self).encode('utf-8')

STREAM_INFO = {
	Stream(u'xxxxx', u'480p 25fps (h264/mpga)ts', u'http://xxxxx.xxx:xxx/xxx.ts')
}

class WeeabotDotCom(object):
  '''web+database support
  '''
  HOSTNAME = u'http://www.xxx.com/'
  USERNAME = u'xxx'
  PASSWORD = u'xxx'


text:
package com.kw_support.view;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;

/**
 * Created by G-chen on 2015-3-15.
 * ScrollView反弹效果的实现 被OverScrollView取代
 */
@Deprecated
public class BounceScrollView extends ScrollView {

    private View inner;                                 // 孩子view

    private Rect normal = new Rect();                   // 矩形,用于判断是否需要动画

    private float y;                                    // 点击是的坐标

    private boolean isCount = false;                  // 是否开始计算移动的距离

    private int size = 3;                              // 可以拉伸的长度为屏幕宽度的比值

    private float mLastMotionX;
    private float mLastMotionY;

    public BounceScrollView(Context context) {
        super(context);
    }

    public BounceScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BounceScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        if (getChildCount() > 0) {
            inner = getChildAt(0);                      // 获取第一个子View
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();

        final float motionX = ev.getX();
        final float motionY = ev.getY();

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastMotionX = motionX;
                mLastMotionY = motionY;

                break;
            case MotionEvent.ACTION_MOVE:
                int xDiff = (int) Math.abs(motionX - mLastMotionX);
                int yDiff = (int) Math.abs(motionY - mLastMotionY);

                if (yDiff * 0.3f > xDiff) {
                    return true;
                }
                break;
        }

        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (null != inner) {
            commOnTouchEvent(ev);
        }
        return super.onTouchEvent(ev);
    }

    private void commOnTouchEvent(MotionEvent ev) {
        int action = ev.getAction();

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:
                if (isNeedAnimation()) {
                    animation();
                    isCount = false;
                }
                break;
            /***
             * 排除出第一次移动计算,因为第一次无法得知y坐标, 在MotionEvent.ACTION_DOWN中获取不到,
             * 因为此时是MyScrollView的touch事件传递到到了LIstView的孩子item上面.所以从第二次计算开始.
             * 然而我们也要进行初始化,就是第一次移动的时候让滑动距离归0. 之后记录准确了就正常执行.
             */
            case MotionEvent.ACTION_MOVE:
                final float dY = y;
                float curY = ev.getY();
                int deltaY = (int) (dY - curY);

                if (!isCount) {
                    deltaY = 0;                      // 归0,第一次不计算
                }

                y = curY;
                // 当滚动到最上面或者最下面时就不再滚动,这时候移动布局
                if (isNeedMove()) {
                    // 初始化头部矩形
                    if (normal.isEmpty()) {
                        // 保持正常的布局位置
                        normal.set(inner.getLeft(), inner.getTop(),
                                inner.getRight(), inner.getBottom());
                    }
                    // 移动布局
                    inner.layout(inner.getLeft(), inner.getTop() - deltaY / size,
                            inner.getRight(), inner.getBottom() - deltaY / size);
                }

                isCount = true;
                break;
            default:
                break;
        }
    }

    private void animation() {
        // 开启动画
        TranslateAnimation tsAnim = new TranslateAnimation(0, 0, inner.getTop(), normal.top);
        tsAnim.setDuration(200);
        inner.startAnimation(tsAnim);

        // 设置回到正常的布局为位置
        inner.layout(normal.left, normal.top, normal.right, normal.bottom);
        normal.setEmpty();
    }

    public boolean isNeedAnimation() {
        return !normal.isEmpty();
    }

    /**
     * 是否要移动布局
     * inner.getMeasuredHeight()是获取控件的总高度
     * getHeight是屏幕的高度
     */
    public boolean isNeedMove() {
        int offset = inner.getMeasuredHeight() - getHeight();
        int scrollY = getScrollY();

        // 0是顶部,后面的是底部
        if (scrollY == 0 || scrollY == offset) {
            return true;
        }
        return false;
    }
}


text:
module Spree
  module Crm
    class Size < ActiveResource::Base
      include RemoteModel

      self.settings_class = CrmSettings
      authenticates_with_email_and_token
      add_response_method :http_response
    end
  end
end


text:
layout: page
title: Murray - Lamb Wedding
date: 2016-05-24
author: Jordan Zavala
tags: weekly links, java
status: published
summary: Aenean imperdiet laoreet turpis, nec egestas nulla vulputate.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/25/2019
  endDate: 04/28/2019
  ctyhocn: HELMTHX
  groupCode: MLW
published: true
---
Pellentesque velit massa, blandit et auctor nec, vulputate quis lacus. Mauris pharetra eu nibh a euismod. Phasellus cursus, mi eget cursus maximus, lacus orci vehicula lacus, sed condimentum nunc magna eget sapien. Etiam imperdiet sem tellus, sed dictum augue tempor tincidunt. Sed nibh nisl, tempor in molestie id, mollis eu velit. Nunc aliquet ligula augue, vel consequat erat dignissim hendrerit. Sed eu egestas dui, porttitor vestibulum risus. Morbi posuere eu sapien id venenatis. Ut dictum maximus nibh bibendum lacinia. Fusce sed gravida augue, vitae blandit elit.
Maecenas malesuada dolor ac nunc aliquet rutrum. Vivamus iaculis vel nulla id vestibulum. Aliquam aliquam imperdiet massa, sit amet pellentesque justo ultrices vel. Pellentesque rutrum lorem id tortor posuere vestibulum. Mauris finibus mauris arcu, et porttitor ipsum ultrices sed. Nullam sed leo velit. Etiam ultricies aliquam mauris at tempus. Curabitur ultricies consectetur molestie.

* In vitae nunc non diam placerat convallis eget ac massa.

Morbi rutrum vestibulum nisl ut sollicitudin. Mauris interdum vehicula quam eget posuere. Cras magna sapien, ultrices id risus et, accumsan auctor leo. Donec eu hendrerit augue. Sed non felis ornare, luctus metus vitae, varius magna. In aliquet, odio ut imperdiet semper, orci tortor commodo libero, sed lobortis libero mi eget turpis. Vivamus bibendum, massa sed mollis elementum, urna arcu pellentesque ligula, nec aliquam odio purus non justo. Etiam feugiat eu nunc eget ornare. Etiam diam nulla, eleifend sit amet suscipit non, vehicula non ipsum. Nullam consectetur libero non laoreet facilisis. Nullam vitae efficitur purus. Sed vel nulla dignissim, hendrerit diam sit amet, malesuada ipsum.


text:
package com.mossle.card.persistence.domain;

// Generated by Hibernate Tools
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * CardInfo .
 *
 * @author Lingo
 */
@Entity
@Table(name = "CARD_INFO")
public class CardInfo implements java.io.Serializable {
    private static final long serialVersionUID = 0L;

    /** null. */
    private Long id;

    /** null. */
    private String code;

    /** null. */
    private String description;

    /** null. */
    private String tenantId;

    public CardInfo() {
    }

    public CardInfo(Long id) {
        this.id = id;
    }

    public CardInfo(Long id, String code, String description, String tenantId) {
        this.id = id;
        this.code = code;
        this.description = description;
        this.tenantId = tenantId;
    }

    /** @return null. */
    @Id
    @Column(name = "ID", unique = true, nullable = false)
    public Long getId() {
        return this.id;
    }

    /**
     * @param id
     *            null.
     */
    public void setId(Long id) {
        this.id = id;
    }

    /** @return null. */
    @Column(name = "CODE", length = 200)
    public String getCode() {
        return this.code;
    }

    /**
     * @param code
     *            null.
     */
    public void setCode(String code) {
        this.code = code;
    }

    /** @return null. */
    @Column(name = "DESCRIPTION", length = 200)
    public String getDescription() {
        return this.description;
    }

    /**
     * @param description
     *            null.
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /** @return null. */
    @Column(name = "TENANT_ID", length = 64)
    public String getTenantId() {
        return this.tenantId;
    }

    /**
     * @param tenantId
     *            null.
     */
    public void setTenantId(String tenantId) {
        this.tenantId = tenantId;
    }
}


text:
require 'spec_helper'

module Spree
  module Stock
    describe Differentiator, type: :model do
      subject { Differentiator.new(order, packages) }

      let(:variant1) { mock_model(Variant) }
      let(:variant2) { mock_model(Variant) }

      let(:line_item1) { build(:line_item, variant: variant1, quantity: 2) }
      let(:line_item2) { build(:line_item, variant: variant2, quantity: 2) }

      let(:stock_location) { mock_model(StockLocation) }

      let(:inventory_unit1) { build(:inventory_unit, variant: variant1, line_item: line_item1) }
      let(:inventory_unit2) { build(:inventory_unit, variant: variant2, line_item: line_item2) }

      let(:order) { mock_model(Order, line_items: [line_item1, line_item2]) }

      let(:package1) do
        Package.new(stock_location).tap { |p| p.add(inventory_unit1) }
      end

      let(:package2) do
        Package.new(stock_location).tap { |p| p.add(inventory_unit2) }
      end

      let(:packages) { [package1, package2] }

      it { is_expected.to be_missing }

      it 'calculates the missing items' do
        expect(subject.missing[variant1]).to eq 1
        expect(subject.missing[variant2]).to eq 1
      end
    end
  end
end


text:
package cppncss.measure;

/**
 * Computes the average of a series of values.
 *
 * @author Mathieu Champlon
 */
public final class Average
{
    private final String label;
    private float average;
    private float count;

    /**
     * Create an average.
     *
     * @param label the label of the measurement
     * @param value the first value of the measurement
     */
    public Average( final String label, final int value )
    {
        this.label = label;
        this.average = value;
        this.count = 1;
    }

    /**
     * Add a value to the average and recompute it.
     * <p>
     * If the label does not match the label given at creation the measurement is ignored.
     *
     * @param label the label of the measurement
     * @param value the value of the measurement
     * @return whether the measurement has been accepted or not
     */
    public boolean update( final String label, final int value )
    {
        if( !this.label.equals( label ) )
            return false;
        average = (average * count + value) / (count + 1);
        ++count;
        return true;
    }

    /**
     * Accept a visitor.
     *
     * @param observer an average observer
     */
    public void accept( final AverageObserver observer )
    {
        observer.notify( label, average );
    }
}


text:
             <li class="<?php echo $cur_title[0];?>"><?php echo anchor("admin/index","Home","")?>

             <li class="dropdown <?php echo $cur_title[1];?>">

                文章

<?php echo anchor("admin/Articles/edit","撰写文章","")?>

<?php echo anchor("admin/Articles/index","管理文章","")?>

             <li class="<?php echo $cur_title[2];?>"><?php echo anchor("admin/Category/index","分类","")?>
             <li class="<?php echo $cur_title[3];?>"><?php echo anchor("admin/Tag/index","标签","")?>
              <li class="dropdown <?php echo $cur_title[4];?>">

                功能

<?php echo anchor("admin/Others/back_up","备份","")?>

<?php echo anchor("admin/Others/change_password","修改密码","")?>

             <button type="button" class="btn btn-default btn-md" data-toggle="modal" data-target="#myModal" style="float:right;margin-top:5px;color:#1780C7">

              </button>
              <?php echo anchor("Articles/index",'<button type="button" class="btn btn-default btn-md"style="float:right;margin-top:5px;color:#1780C7">

              </button>',"")?>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

嘿

        不再写点了?

        <?php echo anchor('admin/Index/logout','<button type="button" class="btn btn-primary">是的,再见!</button>')?>
        <button type="button" class="btn btn-default" data-dismiss="modal">考虑下咯</button>


text:
.. change::
    :tags: bug, orm
    :tickets: 8862

    Fixed bug where :meth:`_orm.Session.merge` would fail to preserve the
    current loaded contents of relationship attributes that were indicated with
    the :paramref:`_orm.relationship.viewonly` parameter, thus defeating
    strategies that use :meth:`_orm.Session.merge` to pull fully loaded objects
    from caches and other similar techniques. In a related change, fixed issue
    where an object that contains a loaded relationship that was nonetheless
    configured as ``lazy='raise'`` on the mapping would fail when passed to
    :meth:`_orm.Session.merge`; checks for "raise" are now suspended within
    the merge process assuming the :paramref:`_orm.Session.merge.load`
    parameter remains at its default of ``True``.

    Overall, this is a behavioral adjustment to a change introduced in the 1.4
    series as of :ticket:`4994`, which took "merge" out of the set of cascades
    applied by default to "viewonly" relationships. As "viewonly" relationships
    aren't persisted under any circumstances, allowing their contents to
    transfer during "merge" does not impact the persistence behavior of the
    target object. This allows :meth:`_orm.Session.merge` to correctly suit one
    of its use cases, that of adding objects to a :class:`.Session` that were
    loaded elsewhere, often for the purposes of restoring from a cache.


text:
package org.apache.camel.component.jetty.rest.producer;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jetty.BaseJettyTest;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class HttpRestProducerGetTest extends BaseJettyTest {

    @Test
    public void testHttpProducerGet() throws Exception {
        String out = fluentTemplate.withHeader("id", "123").to("direct:start").request(String.class);
        assertEquals("123;Donald Duck", out);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                restConfiguration().component("jetty").host("localhost").port(getPort())
                        // use camel-http as rest client
                        .producerComponent("http");

                from("direct:start").to("rest:get:users/{id}/basic");

                // use the rest DSL to define the rest services
                rest("/users/").get("{id}/basic").route().to("mock:input").process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        String id = exchange.getIn().getHeader("id", String.class);
                        exchange.getMessage().setBody(id + ";Donald Duck");
                    }
                });
            }
        };
    }

}


text:
package org.apache.ambari.server.serveraction.kerberos;

import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.state.stack.OsFamily;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

public class KerberosOperationHandlerFactoryTest {

  private static Injector injector;

  @BeforeClass
  public static void beforeClass() throws AmbariException {
    injector = Guice.createInjector(new AbstractModule() {
      @Override
      protected void configure() {
        Configuration configuration = EasyMock.createNiceMock(Configuration.class);
        expect(configuration.getServerOsFamily()).andReturn("redhat6").anyTimes();
        replay(configuration);

        bind(Configuration.class).toInstance(configuration);
        bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class));
      }
    });
  }

  @Test
  public void testForAD() {
    Assert.assertEquals(MITKerberosOperationHandler.class,
      injector.getInstance(KerberosOperationHandlerFactory.class).getKerberosOperationHandler(KDCType.MIT_KDC).getClass());
  }

  @Test
  public void testForMIT() {
    Assert.assertEquals(ADKerberosOperationHandler.class,
        injector.getInstance(KerberosOperationHandlerFactory.class).getKerberosOperationHandler(KDCType.ACTIVE_DIRECTORY).getClass());
  }

  @Test(expected = IllegalArgumentException.class)
  public void testForNone() {
    Assert.assertNull(injector.getInstance(KerberosOperationHandlerFactory.class).getKerberosOperationHandler(KDCType.NONE));
  }

  @Test(expected = IllegalArgumentException.class)
  public void testForNull() {
    Assert.assertNull(injector.getInstance(KerberosOperationHandlerFactory.class).getKerberosOperationHandler(null));
  }
}


text:
require 'simplecov'
SimpleCov.start

ENV['RACK_ENV'] = 'test'

class MockDataSource
  class Undefined; end

  attr_reader :result, :results

  def results
    @results
  end

  def initialize(entities)
    @entities = entities
    @result = Undefined
    @results = []
  end

  # def get(entity_type, interface=:simple)
  #   if block_given?
  #     return yield @entities[entity_type]
  #   end

  #   @entities[entity_type]
  # end

  def get(route, interface=:simple)
    case
    when route.match(/\A[a-z]+\z/)
      if block_given?
        return yield @entities[route]
      else
        return @entities[route]
      end
    when route.match(/\A[a-z]+[\/][a-zA-Z0-9]+\z/)
      entity_type = route.match(/\A[a-z]+/).to_s
      entity_id   = route.match(/[a-zA-Z0-9]+\z/).to_s
      return @entities[entity_type].detect {|x| x["id"] == entity_id}
    else raise ArgumentError, "Invalid route given to MockDataSource.get  \"#{route}\""
    end
  end

  def put(entity, entity_type, interface=:simple)
    @results << entity
    @result = entity
  end
end


text:
package com.alibaba.jstorm.utils;

public class HttpserverUtils {

    public static final String HTTPSERVER_CONTEXT_PATH_LOGVIEW = "/logview";

    public static final String HTTPSERVER_LOGVIEW_PARAM_CMD = "cmd";

    public static final String HTTPSERVER_LOGVIEW_PARAM_CMD_LIST = "listDir";

    public static final String HTTPSERVER_LOGVIEW_PARAM_CMD_SHOW = "showLog";

    public static final String HTTPSERVER_LOGVIEW_PARAM_CMD_SEARCH_LOG = "searchLog";

    public static final String HTTPSERVER_LOGVIEW_PARAM_CMD_JSTACK = "jstack";

    public static final String HTTPSERVER_LOGVIEW_PARAM_CMD_SHOW_CONF = "showConf";

    public static final String HTTPSERVER_LOGVIEW_PARAM_CMD_DOWNLOAD = "download";

    public static final String HTTPSERVER_LOGVIEW_PARAM_LOGFILE = "log";

    public static final String HTTPSERVER_LOGVIEW_PARAM_POS = "pos";

    public static final String HTTPSERVER_LOGVIEW_PARAM_DIR = "dir";

    public static final String HTTPSERVER_LOGVIEW_PARAM_WORKER_PORT = "workerPort";

    public static final String HTTPSERVER_LOGVIEW_PARAM_SIZE_FORMAT = "%016d\n";

    public static final int LOG_SEARCH_BLOCK_SIZE = 1024 * 16;  //16K

    public static final String HTTPSERVER_LOGVIEW_PAGE_SIZE = "size";
}


text:
"""
Because migrations are complicated, we're keeping our public fields here.

This deals with circular dependency issues between LANDINGUser and Organization
"""

from django.db import models
from django_extensions.db.models import TimeStampedModel

from superperms.orgs.models import ExportableField, Organization

INTERNAL = 0
PUBLIC = 1

FIELD_CHOICES = (
    (INTERNAL, 'Internal'),
    (PUBLIC, 'Public')
)

class SharedBuildingField(TimeStampedModel):
    """BuildingSnapshot Exported Field, either public or internally shared."""
    org = models.ForeignKey(Organization)
    field = models.ForeignKey(ExportableField)
    field_type = models.IntegerField(default=INTERNAL, choices=FIELD_CHOICES)

    def __unicode__(self):
        return u'{0} - {1} - {2}'.format(
            self.org, self.field.name, self.get_field_type_display()
        )


text:
package apps::cisco::cms::restapi::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_custom);

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $self->{version} = '1.0';
    %{$self->{modes}} = (
        'alarms'            => 'apps::cisco::cms::restapi::mode::alarms',
        'calls'             => 'apps::cisco::cms::restapi::mode::calls',
        'database-status'   => 'apps::cisco::cms::restapi::mode::databasestatus',
        'licenses'          => 'apps::cisco::cms::restapi::mode::licenses',
        'system-status'     => 'apps::cisco::cms::restapi::mode::systemstatus',
    );

    $self->{custom_modes}{xmlapi} = 'apps::cisco::cms::restapi::custom::xmlapi';
    return $self;
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check Cisco Meeting Server (CMS) API.

=cut


text:
using System;
using System.Linq;
using System.Reflection;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using Goofy.Core.Configuration;
using Goofy.Extensions;

namespace Goofy.Core.Infrastructure
{
    public class GoofyEngine : IEngine
    {
        protected GoofyCoreConfiguration _goofyCoreConfiguration;
        protected readonly IServiceCollection _services;
        protected readonly IResourcesLocator _resourcesLoader;
        private readonly ILogger<GoofyEngine> _logger;

        public GoofyCoreConfiguration GoofyCoreConfiguration
        {
            get
            {
                if (_goofyCoreConfiguration == null)
                {
                    _goofyCoreConfiguration = new GoofyCoreConfiguration();
                }
                return _goofyCoreConfiguration;
            }
        }

        public GoofyEngine(IServiceCollection services,
                           IResourcesLocator resourcesLoader,
                           ILogger<GoofyEngine> logger)
        {
            _services = services;
            _resourcesLoader = resourcesLoader;
            _logger = logger;
        }

        public virtual void Start()
        {
            /* Todas las tareas que se ejecutan a continuación se realizan luego de que los
            ensamblados de los plugins son cargados */

            // Agregar las dependencias provistas por otros ensamblados(propios o de 3ros)
            RegisterDependencies();

            //Correr tareas de inicio provistas por otros ensamblados(propios o de 3ros)
            if (GoofyCoreConfiguration.RunStartupTasks)
            {
                ExecActionForeachSortableType<IRunAtStartup>(startupTask => startupTask.Run());
            }

            //Remover servicios que sólo son utilizados durante el inicio de Goofy
            RemoveDesignTimeServices();
            //Quitar IServiceCollection de las dependencias
            _services.Remove<IServiceCollection>();
        }

        private void ExecActionForeachSortableType<T>(Action<T> action) where T : ISortableTask
        {
            var depAssemblerTypes = _resourcesLoader.FindClassesOfType<T>()
                                                   .Select(t => (T)_services.Resolve(t));
            var assemblers = depAssemblerTypes.OrderBy(s => s.Order);
            foreach (var depAssembler in assemblers)
            {
                action(depAssembler);
            }
        }

        private void ExecActionForeachType<T>(Action<T> action)
        {
            var depAssemblerTypes = _resourcesLoader.FindClassesOfType<T>()
                                                   .Select(t => (T)_services.Resolve(t));
            foreach (var depAssembler in depAssemblerTypes)
            {
                action(depAssembler);
            }
        }

        protected virtual void RegisterDependencies()
        {
            ExecActionForeachSortableType<IDependencyAssembler>(
                                                                 d =>
                                                                 {
                                                                     d.Register(_services);
                                                                 }
                                                              );
        }

        protected virtual void RemoveDesignTimeServices()
        {
            var servicesForDeleting = _services.Where(s => ServiceIsDesignTimeService(s)).ToArray();
            foreach (var serviceDescriptor in servicesForDeleting)
            {
                _services.Remove(serviceDescriptor);
                var implementationType = serviceDescriptor.ImplementationType ?? serviceDescriptor.ImplementationInstance.GetType();
                _logger.LogInformation(string.Format("Remove implementationType \"{0}\", for service \"{1}\".", implementationType, serviceDescriptor.ServiceType));
            }
        }

        private bool ServiceIsDesignTimeService(ServiceDescriptor serviceDescriptor)
        {
            var serviceType = serviceDescriptor.ServiceType;
            if (serviceType != null)
                return typeof(IDesignTimeService).GetTypeInfo().IsAssignableFrom(serviceType.GetTypeInfo());
            return false;
        }
    }
}


text:
import re
from subprocess import CalledProcessError

from libqtile.log_utils import logger
from libqtile.widget import base

kb_layout_regex = re.compile(r'layout:\s+(?P<layout>\w+)')
kb_variant_regex = re.compile(r'variant:\s+(?P<variant>\w+)')

class KeyboardLayout(base.InLoopPollText):
    """Widget for changing and displaying the current keyboard layout

    It requires setxkbmap to be available in the system.
    """
    orientations = base.ORIENTATION_HORIZONTAL
    defaults = [
        ("update_interval", 1, "Update time in seconds."),
        ("configured_keyboards", ["us"], "A list of predefined keyboard layouts "
            "represented as strings. For example: "
            "['us', 'us colemak', 'es', 'fr']."),
        ("display_map", {}, "Custom display of layout. Key should be in format "
            "'layout variant'. For example: "
            "{'us': 'us ', 'lt sgs': 'sgs', 'ru phonetic': 'ru '}"),
        ("option", None, "string of setxkbmap option. Ex., 'compose:menu,grp_led:scroll'"),
    ]

    def __init__(self, **config):
        base.InLoopPollText.__init__(self, **config)
        self.add_defaults(KeyboardLayout.defaults)

    def button_press(self, x, y, button):
        if button == 1:
            self.next_keyboard()

    def next_keyboard(self):
        """Set the next layout in the list of configured keyboard layouts as
        new current layout in use

        If the current keyboard layout is not in the list, it will set as new
        layout the first one in the list.
        """

        current_keyboard = self.keyboard
        if current_keyboard in self.configured_keyboards:
            # iterate the list circularly
            next_keyboard = self.configured_keyboards[
                (self.configured_keyboards.index(current_keyboard) + 1) %
                len(self.configured_keyboards)]
        else:
            next_keyboard = self.configured_keyboards[0]

        self.keyboard = next_keyboard

        self.tick()

    def poll(self):
        if self.keyboard in self.display_map.keys():
            return self.display_map[self.keyboard]
        return self.keyboard.upper()

    def get_keyboard_layout(self, setxkbmap_output):
        match_layout = kb_layout_regex.search(setxkbmap_output)
        match_variant = kb_variant_regex.search(setxkbmap_output)

        if match_layout is None:
            return 'ERR'

        kb = match_layout.group('layout')
        if match_variant:
            kb += " " + match_variant.group('variant')
        return kb

    @property
    def keyboard(self):
        """Return the currently used keyboard layout as a string

        Examples: "us", "us dvorak".  In case of error returns "unknown".
        """
        try:
            command = 'setxkbmap -verbose 10 -query'
            setxkbmap_output = self.call_process(command.split(' '))
            keyboard = self.get_keyboard_layout(setxkbmap_output)
            return str(keyboard)
        except CalledProcessError as e:
            logger.error('Can not get the keyboard layout: {0}'.format(e))
        except OSError as e:
            logger.error('Please, check that xset is available: {0}'.format(e))
        return "unknown"

    @keyboard.setter
    def keyboard(self, keyboard):
        command = ['setxkbmap']
        command.extend(keyboard.split(" "))
        if self.option:
            command.extend(['-option', self.option])
        try:
            self.call_process(command)
        except CalledProcessError as e:
            logger.error('Can not change the keyboard layout: {0}'.format(e))
        except OSError as e:
            logger.error('Please, check that setxkbmap is available: {0}'.format(e))

    def cmd_next_keyboard(self):
        """Select next keyboard layout"""
        self.next_keyboard()


text:
@class MISSING_TYPE;

@interface _TtC12SourceEditor25SourceEditorLayoutManager : _TtCs12_SwiftObject
{
    MISSING_TYPE *dataSource;
    MISSING_TYPE *delegate;
    MISSING_TYPE *container;
    MISSING_TYPE *effectController;
    MISSING_TYPE *fontTheme;
    MISSING_TYPE *colorTheme;
    MISSING_TYPE *showInvisiblesTheme;
    MISSING_TYPE *showInvisiblesOverlayProvider;
    MISSING_TYPE *fontRenderingAttributes;
    MISSING_TYPE *textRenderingColorSpace;
    MISSING_TYPE *_defaultLineHeight;
    MISSING_TYPE *_spaceWidth;
    MISSING_TYPE *_paragraphStyle;
    MISSING_TYPE *_defaultDisplayStringAttributes;
    MISSING_TYPE *_defaultPasteboardStringAttributes;
    MISSING_TYPE *_defaultAccessibilityStringAttributes;
    MISSING_TYPE *currentLayoutPassBoundsWidth;
    MISSING_TYPE *$__lazy_storage_$_lineSpacing;
    MISSING_TYPE *lineWrappingStyle;
    MISSING_TYPE *avoidCroppedLayout;
    MISSING_TYPE *lineExpansionEffects;
    MISSING_TYPE *lineShiftEffects;
    MISSING_TYPE *lineShiftCompensationEffects;
    MISSING_TYPE *columnExpansionEffects;
    MISSING_TYPE *columnShiftEffects;
    MISSING_TYPE *columnShiftCompensationEffect;
    MISSING_TYPE *textHighlightPaths;
    MISSING_TYPE *layoutVisualizations;
    MISSING_TYPE *marginAccessories;
    MISSING_TYPE *layoutOverrideProviders;
    MISSING_TYPE *textAttributeOverrideProviders;
    MISSING_TYPE *lineHighlightOverrideProviders;
    MISSING_TYPE *columnShiftOverrideProviders;
    MISSING_TYPE *lineFragmentOverlayProviders;
    MISSING_TYPE *lineLayerRangeOverrideProviders;
    MISSING_TYPE *hiddenTextOverrideProviders;
    MISSING_TYPE *additionalLineSpacing;
    MISSING_TYPE *maxContentWidth;
    MISSING_TYPE *previouslyVisibleAuxAndSubstitutionViews;
    MISSING_TYPE *visibleAuxAndSubstitutionViews;
    MISSING_TYPE *separatorViews;
    MISSING_TYPE *separatorViewLayoutCursor;
    MISSING_TYPE *layoutStrategy;
    MISSING_TYPE *$__lazy_storage_$_dataSourceObserver;
    MISSING_TYPE *$__lazy_storage_$_identifier;
    MISSING_TYPE *isAdjustingViewport;
    MISSING_TYPE *cachedLineLayerCount;
    MISSING_TYPE *layoutScale;
    MISSING_TYPE *hasPreviouslyAttachedAuxiliaryView;
    MISSING_TYPE *hasPreviouslyAttachedSubstitutionView;
}

@end


text:
namespace RakeRunner.Library.Models
{
    public class RakeTask
    {
        public string Task { get; set; }

        public string Description { get; set; }
    }
}


text:
'use strict';

var Analytics = require('@segment/analytics.js-core').constructor;
var integration = require('@segment/analytics.js-integration');
var sandbox = require('@segment/clear-env');
var tester = require('@segment/analytics.js-integration-tester');
var Kenshoo = require('../lib/');

describe('Kenshoo', function() {
  var analytics;
  var kenshoo;
  var options = {
    cid: 'd590cb3f-ec81-4da7-97d6-3013ec020455',
    subdomain: '1223'
  };

  beforeEach(function() {
    analytics = new Analytics();
    kenshoo = new Kenshoo(options);
    analytics.use(Kenshoo);
    analytics.use(tester);
    analytics.add(kenshoo);
  });

  afterEach(function() {
    analytics.restore();
    analytics.reset();
    kenshoo.reset();
    sandbox();
  });

  it('should have the right settings', function() {
    analytics.compare(Kenshoo, integration('Kenshoo')
      .global('k_trackevent')
      .option('cid', '')
      .option('events', [])
      .option('subdomain', ''));
  });

  describe('before loading', function() {
    beforeEach(function() {
      analytics.stub(kenshoo, 'load');
    });

    describe('#initialize', function() {
      it('should call #load', function() {
        analytics.initialize();
        analytics.page();
        analytics.called(kenshoo.load);
      });
    });
  });

  describe('loading', function() {
    it('should load', function(done) {
      analytics.load(kenshoo, done);
    });
  });

  describe('after loading', function() {
    beforeEach(function(done) {
      analytics.once('ready', done);
      analytics.initialize();
      analytics.page();
    });

    describe('#track', function() {
      beforeEach(function() {
        analytics.stub(window, 'k_trackevent');
      });

      it('should track custom events', function() {
        kenshoo.options.events = ['event'];
        analytics.track('event', {
          revenue: '42',
          orderId: '84',
          coupon: 'promo',
          currency: 'EUR'
        });

        analytics.called(window.k_trackevent, [
          'id=' + options.cid,
          'type=conv',
          'val=42',
          'orderId=84',
          'promoCode=promo',
          'valueCurrency=EUR',
          'GCID=',
          'kw=',
          'product='
        ], options.subdomain);
      });

      it('should not track undefined events', function() {
        analytics.track('random', {
          revenue: '42',
          orderId: '84',
          coupon: 'promo',
          currency: 'EUR'
        });

        analytics.didNotCall(window.k_trackevent);
      });
    });

    describe('#page', function() {
      beforeEach(function() {
        analytics.stub(window, 'k_trackevent');
      });

      it('should not make any event calls', function() {
        analytics.page();
        analytics.didNotCall(window.k_trackevent);
      });
    });
  });
});


text:
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.IO;
using Assert = Lucene.Net.TestFramework.Assert;

namespace Lucene.Net.Index
{

    using Directory = Lucene.Net.Store.Directory;
    using Document = Documents.Document;
    using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;

    [TestFixture]
    public class TestPersistentSnapshotDeletionPolicy : TestSnapshotDeletionPolicy
    {
        [SetUp]
        public override void SetUp()
        {
            base.SetUp();
        }

        [TearDown]
        public override void TearDown()
        {
            base.TearDown();
        }

        private SnapshotDeletionPolicy GetDeletionPolicy(Directory dir)
        {
            return new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.CREATE);
        }

        [Test]
        public virtual void TestExistingSnapshots()
        {
            int numSnapshots = 3;
            MockDirectoryWrapper dir = NewMockDirectory();
            IndexWriter writer = new IndexWriter(dir, GetConfig(Random, GetDeletionPolicy(dir)));
            PersistentSnapshotDeletionPolicy psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy;
            Assert.IsNull(psdp.LastSaveFile);
            PrepareIndexAndSnapshots(psdp, writer, numSnapshots);
            Assert.IsNotNull(psdp.LastSaveFile);
            writer.Dispose();

            // Make sure only 1 save file exists:
            int count = 0;
            foreach (string file in dir.ListAll())
            {
                if (file.StartsWith(PersistentSnapshotDeletionPolicy.SNAPSHOTS_PREFIX, StringComparison.Ordinal))
                {
                    count++;
                }
            }
            Assert.AreEqual(1, count);

            // Make sure we fsync:
            dir.Crash();
            dir.ClearCrash();

            // Re-initialize and verify snapshots were persisted
            psdp = new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND);

            writer = new IndexWriter(dir, GetConfig(Random, psdp));
            psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy;

            Assert.AreEqual(numSnapshots, psdp.GetSnapshots().Count);
            Assert.AreEqual(numSnapshots, psdp.SnapshotCount);
            AssertSnapshotExists(dir, psdp, numSnapshots, false);

            writer.AddDocument(new Document());
            writer.Commit();
            snapshots.Add(psdp.Snapshot());
            Assert.AreEqual(numSnapshots + 1, psdp.GetSnapshots().Count);
            Assert.AreEqual(numSnapshots + 1, psdp.SnapshotCount);
            AssertSnapshotExists(dir, psdp, numSnapshots + 1, false);

            writer.Dispose();
            dir.Dispose();
        }

        [Test]
        public virtual void TestNoSnapshotInfos()
        {
            Directory dir = NewDirectory();
            new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.CREATE);
            dir.Dispose();
        }

        [Test]
        public virtual void TestMissingSnapshots()
        {
            Directory dir = NewDirectory();
            try
            {
                new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND);
                Assert.Fail("did not hit expected exception");
            }
            catch (Exception ise) when (ise.IsIllegalStateException())
            {
                // expected
            }
            dir.Dispose();
        }

        [Test]
        public virtual void TestExceptionDuringSave()
        {
            MockDirectoryWrapper dir = NewMockDirectory();
            dir.FailOn(new FailureAnonymousClass(this, dir));
            IndexWriter writer = new IndexWriter(dir, GetConfig(Random, new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.CREATE_OR_APPEND)));
            writer.AddDocument(new Document());
            writer.Commit();

            PersistentSnapshotDeletionPolicy psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy;
            try
            {
                psdp.Snapshot();
            }
            catch (Exception ioe) when (ioe.IsIOException())
            {
                if (ioe.Message.Equals("now fail on purpose", StringComparison.Ordinal))
                {
                    // ok
                }
                else
                {
                    throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
                }
            }
            Assert.AreEqual(0, psdp.SnapshotCount);
            writer.Dispose();
            Assert.AreEqual(1, DirectoryReader.ListCommits(dir).Count);
            dir.Dispose();
        }

        private sealed class FailureAnonymousClass : Failure
        {
            private readonly TestPersistentSnapshotDeletionPolicy outerInstance;

            private MockDirectoryWrapper dir;

            public FailureAnonymousClass(TestPersistentSnapshotDeletionPolicy outerInstance, MockDirectoryWrapper dir)
            {
                this.outerInstance = outerInstance;
                this.dir = dir;
            }

            public override void Eval(MockDirectoryWrapper dir)
            {
                // LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)]
                // to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods.
                if (StackTraceHelper.DoesStackTraceContainMethod(typeof(PersistentSnapshotDeletionPolicy).Name, "Persist"))
                {
                    throw new IOException("now fail on purpose");
                }
            }
        }

        [Test]
        public virtual void TestSnapshotRelease()
        {
            Directory dir = NewDirectory();
            IndexWriter writer = new IndexWriter(dir, GetConfig(Random, GetDeletionPolicy(dir)));
            PersistentSnapshotDeletionPolicy psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy;
            PrepareIndexAndSnapshots(psdp, writer, 1);
            writer.Dispose();

            psdp.Release(snapshots[0]);

            psdp = new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND);
            Assert.AreEqual(0, psdp.SnapshotCount, "Should have no snapshots !");
            dir.Dispose();
        }

        [Test]
        public virtual void TestSnapshotReleaseByGeneration()
        {
            Directory dir = NewDirectory();
            IndexWriter writer = new IndexWriter(dir, GetConfig(Random, GetDeletionPolicy(dir)));
            PersistentSnapshotDeletionPolicy psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy;
            PrepareIndexAndSnapshots(psdp, writer, 1);
            writer.Dispose();

            psdp.Release(snapshots[0].Generation);

            psdp = new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND);
            Assert.AreEqual(0, psdp.SnapshotCount, "Should have no snapshots !");
            dir.Dispose();
        }

        #region TestSnapshotDeletionPolicy
        // LUCENENET NOTE: Tests in a base class are not pulled into the correct
        // context in Visual Studio. This fixes that with the minimum amount of code necessary
        // to run them in the correct context without duplicating all of the tests.

        [Test]
        public override void TestSnapshotDeletionPolicy_Mem()
        {
            base.TestSnapshotDeletionPolicy_Mem();
        }

        [Test]
        public override void TestBasicSnapshots()
        {
            base.TestBasicSnapshots();
        }

        [Test]
        public override void TestMultiThreadedSnapshotting()
        {
            base.TestMultiThreadedSnapshotting();
        }

        [Test]
        public override void TestRollbackToOldSnapshot()
        {
            base.TestRollbackToOldSnapshot();
        }

        [Test]
        public override void TestReleaseSnapshot()
        {
            base.TestReleaseSnapshot();
        }

        [Test]
        public override void TestSnapshotLastCommitTwice()
        {
            base.TestSnapshotLastCommitTwice();
        }

        [Test]
        public override void TestMissingCommits()
        {
            base.TestMissingCommits();
        }

        #endregion
    }
}


text:
require 'commands/base'
require 'commands/setup'
require 'commands/action'
require 'commands/help'


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Web Performance</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/moon.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Web Performance

Possible optimizations of the new platform (Kuoni site)

						Created by Mindaugas Murauskas / @minusm

Why?

						“Performance is a feature. Deliver your content to users as quickly as possible. Once they're in your app, make page interaction and rendering as smooth as possible.”

						- Google

Goal?

1000ms

Current situation

WebPageTest.org

        		<video src="assets/video.mp4" controls></video>

WebPageTest.org

Google Page Insites

YSlow

Google Chrome Developer Tools

Compression

Enabling gzip compression can reduce the size of the transferred response by up to 90%

browser caching

Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network.

Eliminate render-blocking

Solution

Move JS to bottom and allow parser do it's job

If we can't move JS to bottom, at least order CSS to be first and JS second

Make JS Asynchronous using the HTML async attribute

Minify all

Minification refers to the process of removing unnecessary or redundant data without affecting how the resource is processed by the browser.

Solution

Some files are still not minified, but biggest part is ok. Hurray!

How it's done?

Optimize Images

Images often account for most of the downloaded bytes on a page. As a result, optimizing images can often yield some of the largest byte savings and performance improvements.

Solution

It depends...

Reduce HTTP requests

We have 72 of them on frontpage

Decreasing the number of components on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads.

Solution

Remove what's not needed.
lodash.backbone.js looks strange

Lazy load some of parts as mro.itemmap.js and maps.googleapis.com...

Concatinate mro.*.js and/or files/2/*.js

New admin

Uses build tool

Grunt

Build task

THE END


text:
namespace content {
class TransactionalLevelDBDatabase;
class TransactionalLevelDBIterator;
class LevelDBScope;
class LevelDBWriteBatch;

// Represents a transaction on top of a TransactionalLevelDBDatabase, and is
// backed by a LevelDBScope. This class is not thread-safe.
// Isolation: Read committed
//   All changes written using this transaction are readable through the Get()
//   method and iterators returned by CreateIterator(). They are NOT invisible
//   to other readers - if a key is written to using this transaction and read
//   from in a different transaction or on the database, it might read what was
//   written here.
// Atomicity:
//   All changes in this transaction will be either fully written or fully
//   reverted. It uses the LevelDBScopes system to guarantee this. If this class
//   is destructed before Commit() is called, then it will be rolled back.
// Destruction:
//   On destruction, if the transaction is not committed, it will be rolled
//   back. In a single-sequence scopes setup, this can actually tear down the
//   whole IndexedDBOriginState! So be careful when destroying this object.
class TransactionalLevelDBTransaction
    : public base::RefCounted<TransactionalLevelDBTransaction> {
 public:
  TransactionalLevelDBTransaction(const TransactionalLevelDBTransaction&) =
      delete;
  TransactionalLevelDBTransaction& operator=(
      const TransactionalLevelDBTransaction&) = delete;

  [[nodiscard]] leveldb::Status Put(const base::StringPiece& key,
                                    std::string* value);

  [[nodiscard]] leveldb::Status Remove(const base::StringPiece& key);

  [[nodiscard]] leveldb::Status RemoveRange(
      const base::StringPiece& begin,
      const base::StringPiece& end,
      LevelDBScopeDeletionMode deletion_mode);

  [[nodiscard]] virtual leveldb::Status Get(const base::StringPiece& key,
                                            std::string* value,
                                            bool* found);
  [[nodiscard]] virtual leveldb::Status Commit(bool sync_on_commit);

  // If the underlying scopes system is in single-sequence mode, then this
  // method will return the result of the rollback task.
  [[nodiscard]] leveldb::Status Rollback();

  // The returned iterator must be destroyed before the destruction of this
  // transaction.  This may return null, if it does, status will explain why.
  std::unique_ptr<TransactionalLevelDBIterator> CreateIterator(
      leveldb::Status& status);

  uint64_t GetTransactionSize() const;

  // Sets a callback that will be called after the undo log for this transaction
  // is cleaned up and any deferred deletions (from RemoveRange) are complete.
  // The callback will be called after this transaction is committed, or dropped
  // (destructed) if it is rolled back. The transaction may not be alive when
  // this callback is called.
  void set_commit_cleanup_complete_callback(base::OnceClosure callback) {
    DCHECK(commit_cleanup_complete_callback_.is_null());
    commit_cleanup_complete_callback_ = std::move(callback);
  }

  // Forces the underlying scope to write all pending changes to disk & generate
  // an undo log.
  leveldb::Status ForceWriteChangesAndUndoLog();

 protected:
  friend class DefaultTransactionalLevelDBFactory;
  friend class TransactionalLevelDBTransactionTest;

  TransactionalLevelDBTransaction(TransactionalLevelDBDatabase* db,
                                  std::unique_ptr<LevelDBScope> scope);
  virtual ~TransactionalLevelDBTransaction();

 private:
  friend class base::RefCounted<TransactionalLevelDBTransaction>;
  friend class TransactionalLevelDBIterator;

  // These methods are called from TransactionalLevelDBIterator.
  void OnIteratorLoaded(TransactionalLevelDBIterator* iterator);
  void OnIteratorEvicted(TransactionalLevelDBIterator* iterator);
  void OnIteratorDestroyed(TransactionalLevelDBIterator* iterator);

  void EvictLoadedIterators();

  const raw_ptr<TransactionalLevelDBDatabase> db_;
  // Non-null until the transaction is committed or rolled back.
  std::unique_ptr<LevelDBScope> scope_;
  bool finished_ = false;
  base::OnceClosure commit_cleanup_complete_callback_;

  // These sets contain all iterators created directly through this
  // transaction's |CreateIterator|. We need to track iterators when they're
  // loaded, mark them evicted when the data they cover changes, and remove them
  // when they are destructed.
  //
  // Implementing this could be done with a single list of iterators. However
  // that has the downside that, when data changes, we must iterating over all
  // iterators, many of which will likely already have been evicted.
  //
  // Since we only need to iterate over the loaded iterators on data changes, we
  // can speed up the data change iteration by storing loaded iterators
  // separately. Here that's implemented by storing loaded and evicted iterators
  // in separate sets.
  //
  // Raw pointers are safe here because the destructor of LevelDBIterator
  // removes itself from its associated transaction. It is performant to have
  // |loaded_iterators_| as a flat_set, as the iterator pooling feature of
  // TransactionalLevelDBDatabase ensures a maximum number of
  // TransactionalLevelDBDatabase::kDefaultMaxOpenIteratorsPerDatabase loaded
  // iterators.
  base::flat_set<TransactionalLevelDBIterator*> loaded_iterators_;
  std::set<TransactionalLevelDBIterator*> evicted_iterators_;
  bool is_evicting_all_loaded_iterators_ = false;

  base::WeakPtrFactory<TransactionalLevelDBTransaction> weak_factory_{this};
};

// Reads go straight to the database, ignoring any writes cached in
// write_batch_. Writes are accumulated in a leveldb::WriteBatch and written on
// |Commit()|.
// TODO(dmurph): Remove this and have users just use the database and a
// WriteBatch.
class LevelDBDirectTransaction {
 public:
  LevelDBDirectTransaction(const LevelDBDirectTransaction&) = delete;
  LevelDBDirectTransaction& operator=(const LevelDBDirectTransaction&) = delete;

  virtual ~LevelDBDirectTransaction();

  leveldb::Status Put(const base::StringPiece& key, const std::string* value);
  virtual leveldb::Status Get(const base::StringPiece& key,
                              std::string* value,
                              bool* found);
  void Remove(const base::StringPiece& key);
  leveldb::Status Commit();

  TransactionalLevelDBDatabase* db() { return db_; }

 protected:
  friend class DefaultTransactionalLevelDBFactory;

  explicit LevelDBDirectTransaction(TransactionalLevelDBDatabase* db);

  bool IsFinished() const { return write_batch_ == nullptr; }

  const raw_ptr<TransactionalLevelDBDatabase> db_;
  std::unique_ptr<LevelDBWriteBatch> write_batch_;
};

}  // namespace content

#endif  // COMPONENTS_SERVICES_STORAGE_INDEXED_DB_TRANSACTIONAL_LEVELDB_TRANSACTIONAL_LEVELDB_TRANSACTION_H_


text:
<?php namespace BoundedContext\Contracts\Snapshot;

use BoundedContext\Contracts\Core\Collectable;
use BoundedContext\Contracts\Core\Identifiable;
use BoundedContext\Contracts\Core\Temporal;
use BoundedContext\Contracts\Core\Versionable;
use BoundedContext\Contracts\ValueObject\ValueObject;

interface Snapshot extends Identifiable, Versionable, Collectable, Temporal, ValueObject
{

}


text:
Poetry
======

[![License][license-svg]][license-link]

Poetry is an Android persistence library that allows you to persist a JSON object tree directly into an SQLite database through [OrmLite].
Poetry enables you to write less code and persist data much faster.

Consider this JSON:
```json
{
	"id" : 1,
	"name" : "John Doe"
}
```
And this Java model:
```java
@DatabaseTable
class User
{
	@DatabaseField(id = true)
	public int id;

	@DatabaseField)
	public String name;
}
```
They can be stored into the database like this:
```java
JSONObject json_object = ...; // processed JSON tree
DatabaseHelper helper = ...; // OrmLite databasehelper;
JsonPersister persister = new JsonPersister(helper.getWritableDatabase());
persister.persistObject(User.class, json_object);
```
## Features ##

* Annotation-based model configuration
* Advanced `DatabaseHelper` with easy `DatabaseConfiguration`
* Support for relationships:
	* One-to-one
	* Many-to-one
	* One-to-many
	* Many-to-many
* Persist objects and arrays of objects
* Persist objects with arrays of base types (e.g. JSON String array persisted to separate table)

## Requirements ##

- Android 2.3.3 (API level 10) or higher

## Usage ##

**build.gradle**

```groovy
repositories {
    mavenCentral()
    maven {
        url "https://dl.bintray.com/elastique/poetry"
    }
}
```

```groovy
dependencies {
    compile (
        [group: 'nl.elastique.poetry', name: 'poetry', version: '3.0.1']
    )
}
```

## Demo ##

A [Demo] application is available on GitHub

## Behaviors ##

 * Models that are imported more than once within a single JSON tree are updated every time they are processed.
 * Attributes that are not specified in JSON are not updated
 * Attributes that are imported with null value will have a null value in the database. Make sure your model allows this.
 * When you use `JsonPersister`'s `persistArray()` method, it will import the array and delete all objects from the database that do not correspond to any of the imported IDs.

## Tutorial ##

### Creating a DatabaseHelper ###

The Poetry `DatabaseHelper` allows you to easily configure your database.
In the example below, you can see a custom `DatabaseHelper` with a `DatabaseConfiguration` that holds the model version and model classes.

**MyDatabaseHelper.java**
```java
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.support.ConnectionSource;
import nl.elastique.poetry.database.DatabaseConfiguration;

public class MyDatabaseHelper extends nl.elastique.poetry.database.DatabaseHelper
{
    public final static DatabaseConfiguration sConfiguration = new DatabaseConfiguration(1, new Class<?>[]
    {
        User.class,
        Group.class,
        UserTag.class,
        UserGroup.class
    });

    public DatabaseHelper(Context context)
    {
        super(context, sConfiguration);
    }

    public static DatabaseHelper getHelper(Context context)
    {
        return OpenHelperManager.getHelper(context, DatabaseHelper.class);
    }
}
```

### Mapping custom JSON properties ###

By default, the name of the attribute is used to map from JSON. Your naming conventions might now allow this. You can specify the json key name with the `@MapFrom` annotation.

**User.java**
```java
@DatabaseTable
class User
{
	@DatabaseField(id = true, columnName = "id")
	@MapFrom("id")
    private int mId;

	@DatabaseField(columnName = "name")
	@MapFrom("name")
    private String mName;
}
```

### One-to-many relationships ###

In this example, a `Game` object holds a list of `Player` objects.

**game.json**
```json
{
    "id": 1,
    "players" : [
        {
	        "id": 1,
	        "name": "John"
        },
        {
	        "id": 2,
	        "name": "Jane"
        }
    ]
}
```
**Game.java**
```java
@DatabaseTable
public class Game
{
    @DatabaseField(id = true)
    public int id;

	@ForeignCollectionField(eager = true)
	public ForeignCollection<Player> players;
}
```
**Player.java**
```java
@DatabaseTable
public class Player
{
    @DatabaseField(id = true)
    public int id;

    @DatabaseField
    public String name;
}
```

### Many-to-many relationships ###

In this example, a `User` can have 0 or more `Groups`, and a `Group` can have 0 or more `Users`.

**users.json**
```json
[
	{
	    "id" : 1,
	    "name" : "John",
	    "groups" : [
		    {
			    "id" : 1,
			    "name" : "Group 1"
		    },
		    {
			    "id" : 2,
			    "name" : "Group 2"
		    }
	    ]
	},
	{
	    "id" : 2,
	    "name" : "Jane",
	    "groups" : [
		    {
			    "id" : 1,
			    "name" : "Group 1"
		    }
	    ]
	}
]
```

**User.java**
```java
@DatabaseTable
public class User
{
    @DatabaseField(id = true)
    public int id;

    @DatabaseField
    public String name;

    /**
     * Many-to-many relationships.
     *
     * OrmLite requires a ForeignCollectionField with the helper-type UserGroup to assist in the database relational mapping.
     * JSON-to-SQLite persistence also requires the additional annotation "ManyToManyField"
     */
    @ForeignCollectionField(eager = true)
    @ManyToManyField(targetType = Group.class)
	public ForeignCollection<UserGroup> groups;
}
```
**UserGroup.java**
```java
@DatabaseTable
public class UserGroup
{
    @DatabaseField(generatedId = true)
    public int id;

    @DatabaseField(foreign = true)
	public User user;

    @DatabaseField(foreign = true)
    public Group group;
}
```

**Group.java**
```java
@DatabaseTable
public class Group
{
    @DatabaseField(id = true)
    public int id;

    @DatabaseField
    public String name;
}
```

### One-to-one relationships ###

In this example, a `User` can have 0 or 1 `Friend` user.

**users.json**
```json
[
	{
	    "id": 1,
	    "name" : "John",
	    "friend" : { "id" : 2 }
	},
	{
	    "id": 2,
	    "name" : "Jane",
	    "friend" : { "id" : 1 }
	}
]
```

The following alternative JSON is also valid:

**users.json**
```json
[
	{
	    "id": 1,
	    "name" : "John",
	    "friend" : 2
	},
	{
	    "id": 2,
	    "name" : "Jane",
	    "friend" : 1
	}
]
```

**User.java**
```java
@DatabaseTable
public class User
{
    @DatabaseField(id = true)
    public int id;

    @DatabaseField
    public String name;

    @DatabaseField(foreign = true)
    public User friend;
}
```

### Arrays of base types ###

Arrays of base types work the same as one-to-many relationships. The only difference is that you have to define a model that holds the base types and use the `@ForeignCollectionFieldSingleTarget` annotation to specify the database column name that holds the value.

**user.json**
```json
{
    "id": 1,
    "tags" : [
        "tag1",
        "tag2"
    ]
}
```
**User.java**
```java
@DatabaseTable
public class User
{
    @DatabaseField(id = true)
    public int id;

	// The targetField refers to the table's column name
	@ForeignCollectionField(eager = true)
	@ForeignCollectionFieldSingleTarget(targetField = "value")
	@MapFrom("tags")
	public ForeignCollection<UserTag> userTags;
}
```
**UserTag.java**
```java
@DatabaseTable
public class UserTag
{
    @DatabaseField(generatedId = true)
    public int id;

    @DatabaseField(foreign = true)
    public User user;

    @DatabaseField
	public String value;
}
```

[license-svg]: https://img.shields.io/badge/license-Apache%202.0-lightgrey.svg?style=flat
[license-link]: https://github.com/elastique/poetry/blob/master/LICENSE
[OrmLite]: http://ormlite.com
[JSON]: http://json.org/java/
[Demo]: https://github.com/elastique/poetry-demo


text:
using System.Collections.ObjectModel;
using Newtonsoft.Json;

namespace WGnet.Model.WoT.Stronghold
{
    /// <summary>
    /// Информация об Укрепрайоне клана
    /// См. описание <see cref="http://ru.wargaming.net/developers/api_reference/wot/stronghold/info/"/>
    /// </summary>
    public class Stronghold
    {
        /// <summary>
        /// Идентификатор клана
        /// </summary>
        [JsonProperty("clan_id")]
        public long ClanId { get; set; }

        /// <summary>
        /// Показывает, что период обороны активирован
        /// </summary>
        [JsonProperty("defense_mode_is_activated")]
        public bool DefenseModeIsActivated { get; set; }

        /// <summary>
        /// Количество направлений
        /// </summary>
        [JsonProperty("directions_count")]
        public long DirectionsCount { get; set; }

        /// <summary>
        /// Уровень
        /// </summary>
        [JsonProperty("level")]
        public long Level { get; set; }

        /// <summary>
        /// Информация о строениях по уникальным ключам их типов
        /// См. <see cref="StrongholdBuildingsInfo"/>
        /// </summary>
        [JsonProperty("buildings")]
        public ReadOnlyDictionary<int, StrongholdBuildingsInfo> Buildings { get; set; }

        /// <summary>
        /// Информация об активном Периоде обороны
        /// Если оборона отключена, полю присваивается значение null
        /// См. <see cref="StrongholdDefense"/>
        /// </summary>
        [JsonProperty("defense")]
        public StrongholdDefense Defense { get; set; }

        /// <summary>
        /// Секретные данные Укрепрайона
        /// См. <see cref="StrongholdPrivate"/>
        /// </summary>
        [JsonProperty("private")]
        public StrongholdPrivate Private { get; set; }

        /// <summary>
        /// Информация о вылазках
        /// См. <see cref="StrongholdSkirmish"/>
        /// </summary>
        [JsonProperty("skirmish")]
        public StrongholdSkirmish Skirmish { get; set; }
    }
}


text:
import os, sys

DEBUG = True
TEMPLATE_DEBUG = DEBUG

APP = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
sys.path.append(APP)
sys.path.append(PROJECT_ROOT)

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASE_ENGINE = 'sqlite3'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'dev.db'             # Or path to database file if using sqlite3.
DATABASE_USER = ''             # Not used with sqlite3.
DATABASE_PASSWORD = ''         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'dev.db'
    }
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),'media'))

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.abspath(os.path.join(PROJECT_ROOT, 'static'))

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'g2_39yupn*6j4p*cg2%w643jiq-1n_annua*%i8+rq0dx9p=$n'

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

ROOT_URLCONF = 'example.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, 'templates')
)

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'south',
    'simpleapp',
    'simpleprofile',

    'stories',
)

import django
# Little hack for static files
if django.VERSION[1] > 2:
    INSTALLED_APPS += (
        'django.contrib.staticfiles',
        'django.contrib.messages')
    MIDDLEWARE_CLASSES += (
        'django.contrib.messages.middleware.MessageMiddleware',)
else:
    INSTALLED_APPS += ('staticfiles',)

STORY_SETTINGS = {}
AUTH_PROFILE_MODULE = 'simpleprofile.Profile'

try:
    from local_settings import *
except ImportError:
    pass


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" />
<meta property="og:title" content="Contact" />
<meta name="twitter:title" content="Contact"/>
<meta itemprop="name" content="Contact"><meta property="og:description" content="Contact information for DevOpsDays Portland 2018" />
  <meta name="twitter:description" content="Contact information for DevOpsDays Portland 2018" />
  <meta itemprop="description" content="Contact information for DevOpsDays Portland 2018"><meta name="twitter:site" content="@devopsdays">
<meta property="og:type" content="event" />
<meta property="og:url" content="/events/2018-portland/contact/" /><meta name="twitter:creator" content="@devopsdayspdx" /><meta name="twitter:label1" value="Event" />
  <meta name="twitter:data1" value="devopsdays Portland 2018" /><meta name="twitter:label2" value="Dates" />
    <meta name="twitter:data2" value="September 11 - 13, 2018" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="102">
<title>devopsdays Portland 2018 - contact information
</title>

<link href="/css/site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

      <link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" />
      <link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" />

  DevOpsDays

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

events

blog

sponsor

speaking

organizing

about

  Portland
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2">

</button>

                  registration

                  program

                  speakers

                  sponsor

                  contact

                  conduct

devopsdays Portland - Contact

If you’d like to contact us by email: organizers-portland-2018@devopsdays.org

Our local team

Bill Weiss

Organizer

Rally Health

Alastair Drong

Organizer

Joe Nuspl

Organizer

Workday

Michelle Carroll

Organizer

Rich Burroughs

Organizer

Scott Nasello

Organizer

Columbia Sportswear

Matt Greensmith

Organizer

Megan Guiney

Organizer

Tiffany Longworth

Organizer

Puppet

Will Ellett

Organizer

Cozy

Jason Yee

Organizer

DataDog

Organizers emeritus

Spencer Krum

Alice Goldfuss

Jason Yee

Daniel Dreier

The core devopsdays organizer group

Active
Bridget Kromhout (lead), Kris Buytaert, Serhat Can, Jennifer Davis, Bernd Erk, Rafael Gomes, Nathen Harvey, Matthew Jones, Dan Maher, Ken Mugrage, Mike Rosado, Andrew Clay Shafer, Matt Stratton (web team lead), John Willis

Historic
Patrick Debois (founder), Damon Edwards, Anthony Goddard, Lindsay Holmwood, Gildas Le Nadan, Stephen Nelson-Smith, Julian Simpson, Christian Trabold, John Vincent, James Wickett

Platinum Sponsors
Join as Platinum Sponsor!

Gold Sponsors
Join as Gold Sponsor!

Silver Sponsors
Join as Silver Sponsor!

Bronze Sponsors
Join as Bronze Sponsor!

Evening Event Sponsors
Join as Evening Event Sponsor!

Specialty Sponsors
Join as Specialty Sponsor!

Community Sponsors
Join as Community Sponsor!

@DEVOPSDAYS

BLOG

10 years of devopsdays

by Kris Buytaert - 10 May, 2019

It’s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery.
Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.

Blogs

10 May, 2019

Feed

CFP OPEN
Campinas
Macapá
Shanghai
Recife
Charlotte
Prague
Tokyo
Salt Lake City

Propose a talk at an event near you!

About

    devopsdays is a worldwide community conference series for anyone interested in IT improvement.

    About devopsdays

    Privacy Policy

    Code of Conduct