text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="FaultedEarth" default="dist" basedir=".">

    <description>
        FaultedEarth Build File
    </description>

    <property name="build" location="build"/>
    <property name="app.proxy.geoserver" value="http://localhost/geoserver/"/>
    <property name="app.proxy.observations" value="http://localhost/observations/"/>
    <property name="app.port" value="8080"/>
    <property name="app.deploy.geoserver" value="/geoserver/"/>

    <target name="init">

        <mkdir dir="${build}"/>

        <echo message="pulling in ringo (ignore fatal warning)"/>
        <mkdir dir="${build}/ringo"/>
        <exec executable="git" dir="${build}/ringo" failonerror="false">
            <arg line="clone -nq git://github.com/ringo/ringojs.git ."/>
        </exec>
        <exec executable="git" dir="${build}/ringo" failonerror="true">
            <arg line="pull origin master"/>
        </exec>
        <exec executable="git" dir="${build}/ringo" failonerror="true">
            <arg line="checkout 7af8f2bba20890e4860973fea5254b55bd00c7d7"/>
        </exec>

        <echo message="building ringo jars"/>
        <ant dir="${build}/ringo" target="jar"/>
        <!-- uncomment this if you have additional jars in a lib dir
        <copy todir="${build}/ringo/lib" flatten="true" includeEmptyDirs="false">
            <fileset dir="lib"/>
        </copy>
        -->

        <echo message="pulling in buildkit (ignore fatal warning)"/>
        <mkdir dir="${build}/buildkit"/>
        <exec executable="git" dir="${build}/buildkit" failonerror="false">
            <arg line="clone -nq git://github.com/tschaub/buildkit.git ."/>
        </exec>
        <exec executable="git" dir="${build}/buildkit" failonerror="true">
            <arg line="pull origin master"/>
        </exec>
        <exec executable="git" dir="${build}/buildkit" failonerror="true">
            <arg line="checkout 86eacbd7b3bf62b8e99f46911dd5a633464b8570"/>
        </exec>

    </target>

    <target name="buildjs">

        <mkdir dir="${build}/${ant.project.name}/WEB-INF/app/static/script"/>
        <java jar="${build}/ringo/run.jar" fork="true" failonerror="true">
            <sysproperty key="ringo.home" path="${build}/ringo"/>
            <arg path="${build}/buildkit/lib/buildkit/build.js"/>
            <arg line="-o ${build}/${ant.project.name}/WEB-INF/app/static/script buildjs.cfg"/>
        </java>

    </target>

    <target name="dist" depends="init, buildjs, redist"/>

    <target name="redist">

        <mkdir dir="${build}/${ant.project.name}"/>

        <copy todir="${build}/${ant.project.name}">
            <fileset dir="src/main/webapp/">
            </fileset>
        </copy>
        <copy todir="${build}/${ant.project.name}/WEB-INF/lib" flatten="true" includeEmptyDirs="false">
            <fileset dir="${build}/ringo/lib"/>
        </copy>
        <copy todir="${build}/${ant.project.name}/WEB-INF/app">
            <fileset dir="app">
                <exclude name="**/externals/**"/>
                <exclude name="**/script/**"/>
            </fileset>
        </copy>
        <!-- copy Ext resources -->
        <copy todir="${build}/${ant.project.name}/WEB-INF/app/static/externals/ext">
            <fileset dir="app/static/externals/ext"/>
        </copy>
        <!-- copy OpenLayers resources -->
        <copy todir="${build}/${ant.project.name}/WEB-INF/app/static/externals/openlayers/theme">
            <fileset dir="app/static/externals/openlayers/theme"/>
        </copy>
        <!-- copy GeoExt resources -->
        <copy todir="${build}/${ant.project.name}/WEB-INF/app/static/externals/geoext/resources">
            <fileset dir="app/static/externals/geoext/resources"/>
        </copy>
        <!-- copy gxp resources -->
        <copy todir="${build}/${ant.project.name}/WEB-INF/app/static/externals/gxp/src/theme">
            <fileset dir="app/static/externals/gxp/src/theme"/>
        </copy>
    </target>

    <target name="debug">
        <java jar="${build}/ringo/run.jar" fork="true">
            <sysproperty key="app.proxy.geoserver" value="${app.proxy.geoserver}"/>
            <sysproperty key="app.proxy.observations" value="${app.proxy.observations}"/>
            <sysproperty key="ringo.home" path="${build}/ringo"/>
            <arg path="app/main.js"/>
            <arg line="-p ${app.port}"/>
        </java>
    </target>

    <target name="cleanstatic">
        <delete dir="${build}/${ant.project.name}/WEB-INF/app/static"/>
    </target>

    <target name="replace">
        <replace file="${build}/${ant.project.name}/WEB-INF/app/static/index.html" token='"/geoserver/' value='"${app.deploy.geoserver}'/>
        <replace file="${build}/${ant.project.name}/WEB-INF/app/static/theme/app/style.css" token='(/geoserver/' value='(${app.deploy.geoserver}'/>
    </target>

    <target name="static-war" depends="cleanstatic, dist, replace">
        <war destfile="${build}/${ant.project.name}.war" needxmlfile="false">
            <fileset dir="${build}/${ant.project.name}/WEB-INF/app/static"/>
        </war>
    </target>

    <target name="war" depends="dist">
        <war destfile="${build}/${ant.project.name}.war">
            <fileset dir="${build}/${ant.project.name}"/>
        </war>
    </target>

    <target name="clean" description="remove previous build and all dependencies">
        <delete dir="${build}"/>
    </target>

</project>


text:
gem	'minitest'
require 'minitest/autorun'
require 'minitest/pride'
require_relative File.join('..', 'lib', 'sms-easy.rb')

redpajama_set_name: RedPajamaGithub


text:
import datetime
import zipfile
import os
import time
from django.conf import settings
from django.utils import timezone
import pytz

def datetime_to_db_time(adatetime):
    return adatetime.hour * 3600 + 60 * adatetime.minute + adatetime.second

def datetime_range_to_db_time(datetime1, datetime2):
    d1 = datetime_to_db_time(datetime1)
    d2 = datetime_to_db_time(datetime2)
    if d1 > d2: # in gtfs, instead of midnight passing to the next day, you count in more time for the same day, i.e 25:00 instead of 01:00
        d2 = d2 + 24*3600
    return d1,d2

def db_time_to_datetime(db_time):
    return datetime.time(db_time / 3600 % 24, (db_time % 3600) / 60, db_time % 60)

def get_utc_time_underscored():
    """ return UTC time as underscored, to timestamp folders """
    t = datetime.datetime.utcnow()
    return t.strftime('%Y_%m_%d_%H_%M_%S')

def get_local_time_underscored():
    """ return time as underscored, to timestamp folders """
    t = datetime.datetime.now()
    return t.strftime('%Y_%m_%d_%H_%M_%S')

def mkdir_p(path):
    """ mkdir -p path """
    if not os.path.exists(path):
        os.makedirs(path)

def rmf(path):
    import shutil
    print 'Trying to delete path %s' % (path)
    if os.path.exists(path):
        print 'Deleting path %s' %(path)
        shutil.rmtree(path)

def ftp_get_file(host,remote_name,local_path):
    """ get file remote_name from FTP host host and copied it inot local_path"""
    from ftplib import FTP
    f = FTP(host)
    f.login()
    fh = open(local_path,'wb')
    f.retrbinary('RETR %s' % (remote_name), fh.write)
    fh.close()
    f.quit()
    print("Copied from host %s: %s => %s" % (host,remote_name,local_path))

def unzip_file(fname,dirname):
    """ unzip file fname into dirname """
    zf = zipfile.ZipFile(fname)
    zf.extractall(path=dirname)
    print("Unzipped %s => %s" % (fname,dirname))

def benchit(func):
    """ decorator to measure time """
    def wrap(*args,**kwargs):
        time_start = time.time()
        res = func(*args,**kwargs)
        time_end = time.time()
        delta = time_end - time_start
        print('Function %s took %.2f seconds' % (func.__name__,delta))
        return res
    return wrap

def parse_form_date(dt_str):
    """ parse the datetime string as returned from the form """
    import dateutil.parser
    if not dt_str or dt_str.lower() == 'none':
        return None
    return dateutil.parser.parse(dt_str)

def parse_gtfs_date(value):
    year = int(value[0:4])
    month = int(value[4:6])
    day = int(value[6:8])
    return datetime.date(year,month,day)

def parse_bool(value):
    int_value = int(value)
    return True if int_value else False

def normalize_time(value):
    """ we normalize time (without date) into integer based on minutes
    we ignore the seconds """
    h,m,s = [int(x) for x in value.split(':')]  # @UnusedVariable
    return h * 60*60 + m * 60 + s

def denormalize_time_to_string(value):
    s = value % 60
    value = value - s
    value = value / 60
    m = value % 60
    h = value / 60
    return '%02d:%02d:%02d' % (h,m,s)

def get_weekdayname(dt):
    return dt.strftime('%A')

def get_utc_time_from_timestamp(ts):
    return datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=timezone.utc)

def get_utc_now():
    return datetime.datetime.utcnow().replace(tzinfo=timezone.utc)

def get_localtime_now():
    return get_localtime(get_utc_now())

def delete_from_model(*models):
    from django.db import connection
    cursor = connection.cursor()
    table_names = [model._meta.db_table for model in models]
    sql = "truncate %s RESTART IDENTITY CASCADE;" % (','.join(table_names))
    cursor.execute(sql)
    print 'DELETED %s' % (table_names)

def get_localtime(dt):
    tz = pytz.timezone(settings.TIME_ZONE)
    return dt.astimezone(tz)

def get_normal_time(dt):
    local_dt = get_localtime(dt)
    h = local_dt.hour
    m = local_dt.minute
    s = local_dt.second
    return h*3600+60*m+s

def dt_time_to_unix_time(dt):
    epoch = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
    delta = dt - epoch
    return delta.total_seconds()

def unix_time_to_localtime(ts):
    dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.UTC)
    return get_localtime(dt)

def meter_distance_to_coord_distance(meter_distance):
    """ the following (non-exact) calculation yields a conversion from meter distances
        to lat-lon distance which should be accurate enough for Israel
        tel_aviv = [32.071589, 34.778227]
        rehovot = [31.896010, 34.811525]
        meter_distance = 19676
        delta_coords = [tel_aviv[0]-rehovot[0], tel_aviv[1]-rehovot[1]]
        delta_coords_norm = (delta_coords[0]**2 + delta_coords[1]**2)**0.5
        meters_over_coords = meter_distance/delta_coords_norm # equals 110101 """
    meters_over_coords = 110101.0
    return meter_distance/meters_over_coords

def latlon_to_meters(lat1,lon1,lat2,lon2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    from math import radians, cos, sin, asin, sqrt
    # convert decimal degrees to radians
    lat1 = radians(lat1)
    lon1 = radians(lon1)
    lat2 = radians(lat2)
    lon2 = radians(lon2)

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    km = 6367 * c
    return km * 1000

def autoregister(*app_list):
    from django.db.models import get_models, get_app
    from django.contrib import admin
    from django.contrib.admin.sites import AlreadyRegistered
    for app_name in app_list:
        app_models = get_app(app_name)
        for model in get_models(app_models):
            try:
                admin.site.register(model)
            except AlreadyRegistered:
                pass


text:
/**
 * @file Omnitone HOARenderer. This is user-facing API for the higher-order
 * ambisonic decoder and the optimized binaural renderer.
 */

import BufferList from './buffer-list.js';
import HOAConvolver from './hoa-convolver.js';
import HOARotator from './hoa-rotator.js';
import TOAHrirBase64 from './resources/omnitone-toa-hrir-base64.js';
import SOAHrirBase64 from './resources/omnitone-soa-hrir-base64.js';
import Utils from './utils.js';

/**
 * @typedef {string} RenderingMode
 */

/**
 * Rendering mode ENUM.
 * @enum {RenderingMode}
 */
const RenderingMode = {
  /** @type {string} Use ambisonic rendering. */
  AMBISONIC: 'ambisonic',
  /** @type {string} Bypass. No ambisonic rendering. */
  BYPASS: 'bypass',
  /** @type {string} Disable audio output. */
  OFF: 'off',
};

// Currently SOA and TOA are only supported.
const SupportedAmbisonicOrder = [2, 3];

/**
 * Omnitone HOA renderer class. Uses the optimized convolution technique.
 * @constructor
 * @param {AudioContext} context - Associated AudioContext.
 * @param {Object} config
 * @param {Number} [config.ambisonicOrder=3] - Ambisonic order.
 * @param {Array} [config.hrirPathList] - A list of paths to HRIR files. It
 * overrides the internal HRIR list if given.
 * @param {RenderingMode} [config.renderingMode='ambisonic'] - Rendering mode.
 */
function HOARenderer(context, config) {
  this._context = Utils.isAudioContext(context) ?
      context :
      Utils.throw('HOARenderer: Invalid BaseAudioContext.');

  this._config = {
    ambisonicOrder: 3,
    renderingMode: RenderingMode.AMBISONIC,
  };

  if (config && config.ambisonicOrder) {
    if (SupportedAmbisonicOrder.includes(config.ambisonicOrder)) {
      this._config.ambisonicOrder = config.ambisonicOrder;
    } else {
      Utils.log(
          'HOARenderer: Invalid ambisonic order. (got ' +
          config.ambisonicOrder + ') Fallbacks to 3rd-order ambisonic.');
    }
  }

  this._config.numberOfChannels =
      (this._config.ambisonicOrder + 1) * (this._config.ambisonicOrder + 1);
  this._config.numberOfStereoChannels =
      Math.ceil(this._config.numberOfChannels / 2);

  if (config && config.hrirPathList) {
    if (Array.isArray(config.hrirPathList) &&
        config.hrirPathList.length === this._config.numberOfStereoChannels) {
      this._config.pathList = config.hrirPathList;
    } else {
      Utils.throw(
          'HOARenderer: Invalid HRIR URLs. It must be an array with ' +
          this._config.numberOfStereoChannels + ' URLs to HRIR files.' +
          ' (got ' + config.hrirPathList + ')');
    }
  }

  if (config && config.renderingMode) {
    if (Object.values(RenderingMode).includes(config.renderingMode)) {
      this._config.renderingMode = config.renderingMode;
    } else {
      Utils.log(
          'HOARenderer: Invalid rendering mode. (got ' +
          config.renderingMode + ') Fallbacks to "ambisonic".');
    }
  }

  this._buildAudioGraph();

  this._isRendererReady = false;
}

/**
 * Builds the internal audio graph.
 * @private
 */
HOARenderer.prototype._buildAudioGraph = function() {
  this.input = this._context.createGain();
  this.output = this._context.createGain();
  this._bypass = this._context.createGain();
  this._hoaRotator = new HOARotator(this._context, this._config.ambisonicOrder);
  this._hoaConvolver =
      new HOAConvolver(this._context, this._config.ambisonicOrder);
  this.input.connect(this._hoaRotator.input);
  this.input.connect(this._bypass);
  this._hoaRotator.output.connect(this._hoaConvolver.input);
  this._hoaConvolver.output.connect(this.output);

  this.input.channelCount = this._config.numberOfChannels;
  this.input.channelCountMode = 'explicit';
  this.input.channelInterpretation = 'discrete';
};

/**
 * Internal callback handler for |initialize| method.
 * @private
 * @param {function} resolve - Resolution handler.
 * @param {function} reject - Rejection handler.
 */
HOARenderer.prototype._initializeCallback = function(resolve, reject) {
  let bufferList;
  if (this._config.pathList) {
    bufferList =
        new BufferList(this._context, this._config.pathList, {dataType: 'url'});
  } else {
    bufferList = this._config.ambisonicOrder === 2
        ? new BufferList(this._context, SOAHrirBase64)
        : new BufferList(this._context, TOAHrirBase64);
  }

  bufferList.load().then(
      function(hrirBufferList) {
        this._hoaConvolver.setHRIRBufferList(hrirBufferList);
        this.setRenderingMode(this._config.renderingMode);
        this._isRendererReady = true;
        Utils.log('HOARenderer: HRIRs loaded successfully. Ready.');
        resolve();
      }.bind(this),
      function() {
        const errorMessage = 'HOARenderer: HRIR loading/decoding failed.';
        reject(errorMessage);
        Utils.throw(errorMessage);
      });
};

/**
 * Initializes and loads the resource for the renderer.
 * @return {Promise}
 */
HOARenderer.prototype.initialize = function() {
  Utils.log(
      'HOARenderer: Initializing... (mode: ' + this._config.renderingMode +
      ', ambisonic order: ' + this._config.ambisonicOrder + ')');

  return new Promise(this._initializeCallback.bind(this));
};

/**
 * Updates the rotation matrix with 3x3 matrix.
 * @param {Number[]} rotationMatrix3 - A 3x3 rotation matrix. (column-major)
 */
HOARenderer.prototype.setRotationMatrix3 = function(rotationMatrix3) {
  if (!this._isRendererReady) {
    return;
  }

  this._hoaRotator.setRotationMatrix3(rotationMatrix3);
};

/**
 * Updates the rotation matrix with 4x4 matrix.
 * @param {Number[]} rotationMatrix4 - A 4x4 rotation matrix. (column-major)
 */
HOARenderer.prototype.setRotationMatrix4 = function(rotationMatrix4) {
  if (!this._isRendererReady) {
    return;
  }

  this._hoaRotator.setRotationMatrix4(rotationMatrix4);
};

/**
 * Set the decoding mode.
 * @param {RenderingMode} mode - Decoding mode.
 *  - 'ambisonic': activates the ambisonic decoding/binaurl rendering.
 *  - 'bypass': bypasses the input stream directly to the output. No ambisonic
 *    decoding or encoding.
 *  - 'off': all the processing off saving the CPU power.
 */
HOARenderer.prototype.setRenderingMode = function(mode) {
  if (mode === this._config.renderingMode) {
    return;
  }

  switch (mode) {
    case RenderingMode.AMBISONIC:
      this._hoaConvolver.enable();
      this._bypass.disconnect();
      break;
    case RenderingMode.BYPASS:
      this._hoaConvolver.disable();
      this._bypass.connect(this.output);
      break;
    case RenderingMode.OFF:
      this._hoaConvolver.disable();
      this._bypass.disconnect();
      break;
    default:
      Utils.log(
          'HOARenderer: Rendering mode "' + mode + '" is not ' +
          'supported.');
      return;
  }

  this._config.renderingMode = mode;
  Utils.log('HOARenderer: Rendering mode changed. (' + mode + ')');
};

export default HOARenderer;


text:
Instruction::Instruction(int time_issued, int track)
{
    this->time_issued = time_issued;
    this->track = track;
}

void Instruction::display()
{
    printf("==> inst: %d %d\n", time_issued, track);
}


text:
import AuthMiddleware from '../middleware/authentication';
import UserController from '../controllers/user_controller';
import upload from '../utils/image_processing';

module.exports = (router, app) => {

    router.route('/users')
	.get(AuthMiddleware.isAuthenticated, UserController.allUsers);

    router.route('/users/upload_avatar')
    	.post(upload.upload.single('file'), UserController.uploadAvatar);

    router.route('/users/:user_id')
	.put(AuthMiddleware.isAuthenticated, UserController.updateUser)
	.get(AuthMiddleware.isAuthenticated, UserController.findUserByUserId);

    app.use('/', router);
}


text:
experiment_name=${1:-section1-all-20171114-08}
original_experiment_name=${experiment_name}

ner_tagger_root=/home/onur/projects/research/focus/ner-tagger-dynet-multilayer

n_trials=10

dim=10
morpho_tag_type=char

for trial in `seq 1 ${n_trials}`; do

	for morpho_tag_type in char ; do

		small_sizes="char_dim=$dim \
		char_lstm_dim=$dim \
		morpho_tag_dim=$dim \
		morpho_tag_lstm_dim=$dim \
		morpho_tag_type=${morpho_tag_type} \
		word_dim=$dim \
		word_lstm_dim=$dim "

		# experiment_name=${original_experiment_name}-dim-${dim}-morpho_tag_type-${morpho_tag_type}-trial-`printf "%02d" ${trial}`
		experiment_name=${original_experiment_name}-adam-sweep-sparse_updates_enabled

		for learning_rate in 0.1 0.05 0.01 0.005 0.001 ; do
			for sparse_updates_enabled in 0 ; do
				pre_command="echo ${original_experiment_name}-learning_rate-${learning_rate}-trial-`printf "%02d" ${trial}` >> ${experiment_name}.log"
				command=${pre_command}" && ""cd ${ner_tagger_root} && \
				source /usr/local/bin/virtualenvwrapper.sh && workon dynet && \
				source environment-variables && python control_experiments.py -m joint_ner_and_md with \
				active_models=0 \
				integration_mode=0 \
				dynet_gpu=0 \
				embeddings_filepath=\"\" \
				train_filepath=turkish/gungor.ner.train.14.only_consistent \
				dev_filepath=turkish/gungor.ner.dev.14.only_consistent \
				test_filepath=turkish/gungor.ner.test.14.only_consistent \
				$small_sizes \
				lr_method=`printf "adam-alpha_float@%.03lf" ${learning_rate}` \
				sparse_updates_enabled=${sparse_updates_enabled}
				max_epochs=10 \
				experiment_name=${experiment_name} ;"
				echo $command;
			done;
		done
	done
done


text:
package net.phonex.intellij.android.dbmodel;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import net.phonex.intellij.android.dbmodel.util.PsiUtils;

import java.util.List;

public class CreateTableAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        PsiClass psiClass = PsiUtils.getPsiClassFromContext(e);

        GenerateDialog dlg = new GenerateDialog(psiClass);
        dlg.show();

        if (dlg.isOK()) {
            generateParcelable(psiClass, dlg.getSelectedFields());
        }
    }

    private void generateParcelable(final PsiClass psiClass, final List<PsiField> fields) {
        new WriteCommandAction.Simple(psiClass.getProject(), psiClass.getContainingFile()) {
            @Override
            protected void run() throws Throwable {
                new CodeGenerator(psiClass, fields).generateCreateTable();
            }
        }.execute();
    }

    @Override
    public void update(AnActionEvent e) {
        PsiClass psiClass = PsiUtils.getPsiClassFromContext(e);
        e.getPresentation().setEnabled(psiClass != null && !psiClass.isEnum() && !psiClass.isInterface());
    }
}


text:
因为官方的DataBinding文档写的实在太挫,看完之后有些地方还是不知道怎么用。故写了这个demo。Demo基本上包含了所有Databinding的特性,如果有新的特性没有包含进里面,请联系 junguoshen@gmail.com。

## 为什么使用Databinding
1. findViewById()写到烦,希望代码优雅一点
2. UI逻辑要在Java中不优雅,希望像在Html中加入Javascript一样在XML中加入一些动态逻辑
3. 处理数据时要写一大堆的if else或者try catch,希望避免NullPointerExecption
4. 嫌弃自定义一个View太麻烦,不想declare-styleable

## Databinding是什么
简单来讲就是连接数据和Layout的框架。
- 可以将数据传递到Xml中
- 可以简单自定义View的Xml属性和逻辑
- 可以在Xml中建立起View之间的依赖关系
- 可以自动检测数据变化并更改View的状态
- 可以根据View的变化改变Data Model,实现数据双向绑定

## 最佳实践
1. 不要在xml中加入业务逻辑
2. 保持xml的简洁性
3. 使用Binding Adapters真的很棒

## 存在的问题
1. 当使用int给xml属性赋值时,如果该属性接受资源id,那么这个int会认为是资源的id。如果android:text=@{1}, 这样子text不会显示1,反而会报错,因为找不到id为1的资源
2. 表达式里面不能有中文,否则会报错。
3. 表达式不能换行。
4. 当databinding报错时会有一堆找不到binding的错误,这些都可以忽略,真正的错误在最后面那一段。
5. 使用了databinding后没办法在Android Studio里面通过快捷键找到该view的引用(这一点实在有点麻烦,希望Google做工具的Team可以尽快解决吧)

## 技术细节
以下根据DataBinding不同的特性来一一说明。

### Expression
####   可以使用的常用运算符
- 数学符号 + - * / &
- String 连接符 +
- 逻辑运算符 && ||
- 一元操作符 + - ! ~
- 二元操作符 & | ^
- 三元操作符 ?:
- 移位操作符 >> >>> <<
- 比较运算符 == > < >= <=
- instanceof
- 括号 ()
- Cast
- 数组访问 []
- 常量 character, String, numeric, null
- 方法调用
- 访问域变量
- ??

对于"??"这个操作符是DataBinding自定义的,意思是如果前面那个不是空就取前面那个,如果为空则取后面那个。以下两个表达式等效:
```xml
android:text="@{user.displayName ?? user.lastName}"
android:text="@{user.displayName != null ? user.displayName : user.lastName}"
```

####   Resource内联字符串/复数/尺寸
DataBinding可以使用以下表达式
```xml
android:text="@{@string/first_name + @string/last_name}"
android:padding="@{@dimen/padding_inside + @dimen/ padding_outside}"
android:text="@{@plurals/banana(bananaCount)}"
```
####   Collections(List Map访问)
```xml
<data>
    <import type="android.util.SparseArray"/>
    <import type="java.util.Map"/>
    <import type="java.util.List"/>
    <variable name="list" type="List<String>"/>
    <variable name="sparse" type="SparseArray<String>"/>
    <variable name="map" type="Map<String, String>"/>
    <variable name="index" type="int"/>
    <variable name="key" type="String"/>
</data>

android:text="@{list[index]}"
android:text="@{sparse[index]}"
android:text="@{map[key]}"
android:text='@{map["firstName"]}'
android:text="@{map[`firstName`]}"
android:text="@{map["firstName"]}"
```

####   有时候需要使用到的转义字符

字符 | 转义字符
---|---
&| \&
< | \<
> | \>
" | \"
' | \'

####   Lambda Expression
```xml
android:onClick="@{(v)->presenter.onViewClicked(v, user.gender)}"
```
可以调用
```java
public void onViewClicked(View view,  String content) {
    Toast.makeText(view.getContext(), content, Toast.LENGTH_SHORT).show();
}
```
在声明参数时,要么全部写,要么都不写,例如:
```xml
android:onFocusChange="@{(v, fcs)->presenter.onViewClicked(v, fcs, user.gender)}"
android:onFocusChange="@{()->presenter.onViewClicked(user.gender)}"
```
都可以调用
```java
onFocusChange(View v, boolean hasFocus)
```
####   特殊符号
在xml中可以通过ID来引用其他view,并且
在DataBinding的xml中可以直接调用context变量,这个变量就是当前binding的context,例如
```xml
<TextView android:id="@+id/display_name" …/>
<Button
    android:onClick="@{()->presenter.onViewClicked(context, displayName.getText())}"
    …
/>

```

### Include
可以将变量传给include的view,例如:
```xml
<include
    layout="@layout/sub_layout"
    tools:subUser="@{user}"
    tools:lastName="@{user.lastName}"/>
```
然后在sub_layout.xml中
```xml
<layout …>
    <data>
        <variable
            name="subUser"
            type="com.xshen.databindingguide.data.User" />
        <variable name="lastName" type="String" />
    </data>
    …
</layout>

```

### ViewStub
可以在ViewStub中使用DataBinding,例如在xml中
```xml
<ViewStub
    android:id="@+id/view_stub"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout="@layout/sub_layout" />
```
在使用Binding的地方,
```java
mBinding.viewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
    @Override
    public void onInflate(ViewStub stub, View inflated) {
        // 第一次加载
        SubLayoutBinding binding = DataBindingUtil.bind(inflated);
        binding.setLastName("view_stub_inflated");
    }
});
…
if (!mBinding.viewStub.isInflated()) {
    mBinding.viewStub.getViewStub().inflate();
} else {
    // 往后的加载
    SubLayoutBinding binding = (SubLayoutBinding) mBinding.viewStub.getBinding();
    binding.setLastName("view_sub_after_inflate");
}

```

### Attribute Setters
####   Automatic Setters
DataBinding可以自动找到对应view的set方法,例如:
```xml
<com.xshen.databindingguide.ui.CustomTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:customText="@{`Custom Fonts Text`}"/>
```
可以调用View中的对应的set方法
```java
public class CustomTextView extends TextView {
    …
    public void setCustomText(CharSequence text){
        setText("Custom " + text);
    }
}
```
####   Renamed Seters
如果想自定义set方法的名字,可以这样做:
```java
// attribute = "app:customText"这个双引号一定要加,不然会报错,官方的文档错了。。
@BindingMethods({
    @BindingMethod(type = CustomTextView.class,
                   attribute = "app:customText",
                   method = "setMyCustomText")})
public class CustomTextView extends TextView {
    …
    public void setMyCustomText(CharSequence text) {
        setText("Custom " + text);
    }
}
```
####   Custom Setters
这个是神器,很好用,用来在全局自定义某个属性的对应的setter,例如
```xml
<TextView
    …
    app:font="@{`alegreya_bold`}" />
<ImageView
    …
    app:placeholder="@{@drawable/placeholder}" app:url="@{`http://img2.cache.netease.com/….jpg`}" />
```
可以绑定到以下的java代码中:
```java
@BindingAdapter({"bind:font"})
public static void setFont(TextView textView, String fontName) {
    textView.setTypeface(FontCache.getInstance().get(fontName));
}

@BindingAdapter({"bind:url", "bind:placeholder"})
public static void loadImage(ImageView imageView, String url, Drawable drawable){
    Glide.with(imageView.getContext()).load(url).centerCrop()
         .placeholder(drawable).crossFade().into(imageView);
}
```
### RecycleView/ListView
一下是在RecyclerView中使用DataBinding的例子:
```java
public static class ViewHolder extends RecyclerView.ViewHolder {
    public DynamicTextViewBinding binding;
    public ViewHolder(DynamicTextViewBinding b) {
        super(b.getRoot());
        binding = b;
    }
    public DynamicTextViewBinding getBinding() {
        return binding;
    }
}

@Override
public DynamicAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
    DynamicTextViewBinding binding = DynamicTextViewBinding
       .inflate(layoutInflater, parent, false);
    ViewHolder vh = new ViewHolder(binding);
    return vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.getBinding().setText(mDataset[position]);
    holder.getBinding().executePendingBindings();
}
```
### Converter
可以自定义Conveter如下:
```xml
<RelativeLayout
    …
    android:background="@{error.get() ? @color/red: @color/green}">
```
会调用一下java代码
```java
@BindingConversion
public static ColorDrawable convertColorToDrawable(int color) {
    return new ColorDrawable(color);
}

```
### Observable
Observable使用如下:
```java
// 先定义一个Observable的类
public class User extends BaseObservable {
    private String firstName;
    @Bindable
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
        notifyPropertyChanged(BR.firstName);
    }
}
// 也可以这样定义
public class ObservableUser {
    public ObservableField<String> firstName = new ObservableField<>();
}
```
当这个类的属性改变时,与其有绑定的view会自动获取最新的值。
更新Observable对象可以这样做:
```java
User user = new User();
ObservableUser observableUser = new ObservableUser();
ObservableArrayMap<String, Object> userMap = new ObservableArrayMap<>();
ObservableArrayList<Object> userList = new ObservableArrayList<>();

user.setFirstName("Jacky");
user.setLastName("Wang");
user.setAge(25);
observableUser.firstName.set("Jacky");
observableUser.lastName.set("Wang");
observableUser.age.set(25);
userMap.put("firstName", "Jacky");
userMap.put("lastName", "Wang");
userMap.put("age", 25);
userList.set(0, "Jacky");
userList.set(1, "Wang");
userList.set(2, 25);
```

### Two way binding
数据双向绑定,当view内容改变时改变data model,当data model改变时改变view
具体实现如下:
在xml中使用"@="给属性复制
```xml
<EditText
    android:id="@+id/user_name_edit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:textSize="@dimen/text_30px"
    app:text="@={user.firstName}" />
```
在Java中
```java
@BindingAdapter("app:text")
public static void setText(TextView view, CharSequence text) {
    final CharSequence oldText = view.getText();
    if (text == oldText || (text == null && oldText.length() == 0)) {
        return;
    }
    if (text instanceof Spanned) {
        if (text.equals(oldText)) {
            return; // No change in the spans, so don't set anything.
        }
    } else if (!haveContentsChanged(text, oldText)) {
        return; // No content changes, so don't set anything.
    }
    view.setText(text);
}

@InverseBindingAdapter(attribute = "app:text", event = "android:textAttrChanged")
public static String getTextString(TextView view) {
    return view.getText().toString();
}
```
一个DataBinding实现里面已经使用了Two Way Binding的例子:
```xml
<CheckBox
    android:id="@+id/seeAds"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:scaleType="centerInside"
    android:visibility="@{seeAds.checked ? View.VISIBLE : View.GONE}"
    app:placeholder="@{@drawable/placeholder}"
    app:url="@{`http://***.jpg`}" />
```
### Animation transition
可以在bind的过程中使用动画
```java
binding.addOnRebindCallback(new OnRebindCallback() {
    @Override
    public boolean onPreBind(ViewDataBinding binding) {
        ViewGroup sceneRoot = (ViewGroup) binding.getRoot();
        TransitionManager.beginDelayedTransition(sceneRoot);
        return true;
    }
});

```
### Dependency injection
依赖注入可以根据生成环境还是测试环境来使用不同的绑定,例如:
```java
public abstract class DIBindingAdapters {
    @BindingAdapter("app:ditext")
    public abstract void setText(TextView textView, String value);
}

public class TestDIBindingAdapters extends DIBindingAdapters {
    @Override
    public void setText(TextView textView, String value) {
        textView.setText("test " + value);
        }
}

public class TestComponent implements android.databinding.DataBindingComponent {
    @Override
    public DIBindingAdapters getDIBindingAdapters() {
        return new TestDIBindingAdapters();
    }
}

```
## 未来计划
1. 吸取DataBinding优点在实际项目中使用
2. 对比Dagger2
3. 看看DataBinding源码

## 参考
1. [Data Binding官方指南](https://developer.android.com/topic/libraries/data-binding/index.html)
1. [Data Binding -- Write Apps Faster (Android Dev Summit 2015)](https://www.youtube.com/watch?v=NBbeQMOcnZ0)
1. [Advanced Data Binding - Google I/O 2016](https://www.youtube.com/watch?v=DAmMN7m3wLU)
1. [Android Spring Cleaning: Data Binding by Lisa Wray](https://www.youtube.com/watch?v=zYGVsTE_scI)
1. [精通 Android Data Binding](https://github.com/LyndonChin/MasteringAndroidDataBinding)


text:
package org.dcm4chee.web.war.folder.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.dcm4che2.data.DicomElement;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4chee.archive.entity.MPPS;
import org.dcm4chee.archive.entity.Series;
import org.dcm4chee.archive.util.JNDIUtils;
import org.dcm4chee.web.dao.folder.StudyListLocal;
import org.dcm4chee.web.war.common.model.AbstractDicomModel;
import org.dcm4chee.web.war.common.model.AbstractEditableDicomModel;

/**
 * @author Gunter Zeilinger <gunterze@gmail.com>
 * @version $Revision: 18061 $ $Date: 2013-09-25 16:06:57 +0800 (周三, 25 9月 2013) $
 * @since Dec 19, 2008
 */
public class PPSModel extends AbstractEditableDicomModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private List<SeriesModel> seriess = new ArrayList<SeriesModel>();

    private SeriesModel series1;
    private int numberOfInstances;
    private int numberOfSeries;
    private Boolean hasForeignPpsInfo;

    public PPSModel(MPPS mpps, SeriesModel series1, StudyModel studyModel, Date createdTime) {
        if (mpps != null) {
            setPk(mpps.getPk());
            this.dataset = mpps.getAttributes();
            this.createdTime = createdTime == null ? new Date() : createdTime;
            hasForeignPpsInfo = false;
        } else {
            setPk(-1);
        }
        setParent(studyModel);
        if (series1 != null) {
            series1.setPPS(this);
            this.series1 = series1;
            seriess.add(series1);
        }
    }

    public void setStudy(StudyModel m) {
        setParent(m);
    }

    public StudyModel getStudy() {
        return (StudyModel) getParent();
    }

    public List<SeriesModel> getSeries() {
        return seriess;
    }

    public SeriesModel getSeries1() {
        return series1;
    }

    public Date getDatetime() {
        if (dataset != null) {
            return toDate(Tag.PerformedProcedureStepStartDate, Tag.PerformedProcedureStepStartTime);
        } else if (series1 == null) {
            return createdTime;
        } else {
            Date d = series1.getPPSStartDatetime();
            if (d == null)
                d = series1.getDatetime();
            if (d == null)
                d = series1.getCreatedTime();
            return d;
        }
    }

    public String getAccessionNumber() {
        return (dataset == null) ? null : dataset.getString(new int[] {
                        Tag.ScheduledStepAttributesSequence, 0,
                        Tag.AccessionNumber });
    }

    public String getSpsid() {
        return dataset != null
                ? dataset.getString(new int[] {
                        Tag.ScheduledStepAttributesSequence, 0,
                        Tag.ScheduledProcedureStepID })
                : null;
    }

    public String getId() {
        return dataset != null
                ? dataset.getString(Tag.PerformedProcedureStepID)
                : series1 == null ? null : series1.getPPSId();
    }

    public String getUid() {
        return dataset != null
                ? dataset.getString(Tag.SOPInstanceUID)
                : series1 == null ? null : series1.getPPSUid();
    }

    public String getDescription() {
        return dataset != null
                ? dataset.getString(Tag.PerformedProcedureStepDescription)
                : series1 == null ? null : series1.getPPSDescription();
    }

    public String getModality() {
        return dataset != null
                ? dataset.getString(Tag.Modality)
                : series1 == null ? null : series1.getModality();
    }

    public String getStationName() {
        return dataset != null
                ? dataset.getString(Tag.PerformedStationName)
                : series1 == null ? null : series1.getStationName();
    }

    public String getStationAET() {
        return dataset != null
                ? dataset.getString(Tag.PerformedStationAETitle)
                : series1 == null ? null : series1.getSourceAET();
    }

    public int getNumberOfSeries() {
        if (numberOfSeries == 0) {
            if (dataset != null) {
                DicomElement sersq = dataset.get(Tag.PerformedSeriesSequence);
                if (sersq != null) {
                    numberOfSeries = sersq.countItems();
                } else {
                    log.warn("Missing PerformedSeriesSequence in PPS! PpsID:"+dataset.getString(Tag.PerformedProcedureStepID));
                }
            } else {
                calcNumberOfChilds();
            }
        }
        return numberOfSeries;
    }

    public boolean hasForeignPpsInfo() {
        if (hasForeignPpsInfo == null) {
            StudyListLocal dao = (StudyListLocal) JNDIUtils.lookup(StudyListLocal.JNDI_NAME);
            hasForeignPpsInfo = dao.hasStudyForeignPpsInfo(this.getStudy().getPk());
        }
        return hasForeignPpsInfo.booleanValue();
    }

    public int getNumberOfInstances() {
        if (numberOfInstances == 0) {
            if (dataset != null) {
                DicomElement sersq = dataset.get(Tag.PerformedSeriesSequence);
                if (sersq != null) {
                    for (int i = 0, n = sersq.countItems(); i < n; i++) {
                        DicomObject ser = sersq.getDicomObject(i);
                        DicomElement imgsq = ser.get(Tag.ReferencedImageSequence);
                        DicomElement nonimgsq = ser.get(
                                Tag.ReferencedNonImageCompositeSOPInstanceSequence);
                        if (imgsq != null) {
                            numberOfInstances += imgsq.countItems();
                        }
                        if (nonimgsq != null) {
                            numberOfInstances += nonimgsq.countItems();
                        }
                    }
                }
            } else {
                calcNumberOfChilds();
            }
        }
        return numberOfInstances;
    }

    private void calcNumberOfChilds() {
        boolean b = seriess.isEmpty();
        if (b)
            expand();
        numberOfSeries = seriess.size();
        for (SeriesModel ser : seriess) {
            numberOfInstances += ser.getNumberOfInstances();
        }
        if (b)
            collapse();
    }
    public String getStatus() {
        return dataset != null
                ? dataset.getString(Tag.PerformedProcedureStepStatus)
                : null;
    }

    public int getRowspan() {
        int rowspan = isDetails() ? 2 : 1;
        for (SeriesModel ser : seriess) {
            rowspan += ser.getRowspan();
        }
        return rowspan;
    }

    public void collapse() {
        seriess.clear();
    }

    public boolean isCollapsed() {
        return seriess.isEmpty();
    }

    public void retainSelectedSeries() {
        for (int i = 0; i < seriess.size(); i++) {
            SeriesModel series = seriess.get(i);
            series.retainSelectedInstances();
            if (series.isCollapsed() && !series.isSelected()) {
                seriess.remove(i);
                i--;
            }
        }
    }

    public void expand() {
        StudyListLocal dao = (StudyListLocal) JNDIUtils.lookup(StudyListLocal.JNDI_NAME);
        String uid = getUid();
        seriess.clear();
        if (uid != null) {
            for (Series ser : dao.findSeriesOfMpps(uid))
                seriess.add(new SeriesModel(ser, this, ser.getCreatedTime()));
        } else {
            List<Series> series = dao.findSeriesOfStudyWithoutPPS(getParent().getPk());
            SeriesModel seriesModel;
            for (Series s : series) {
                seriesModel = new SeriesModel(s, null, s.getCreatedTime());
                if (seriesModel.containedBySamePPS(series1)) {
                    seriess.add(seriesModel);
                }
            }
        }
    }

    @Override
    public int levelOfModel() {
        return PPS_LEVEL;
    }

    @Override
    public List<? extends AbstractDicomModel> getDicomModelsOfNextLevel() {
        return seriess;
    }

    @Override
    public void update(DicomObject dicomObject) {
        StudyListLocal dao = (StudyListLocal)
                JNDIUtils.lookup(StudyListLocal.JNDI_NAME);
        dataset = dao.updateMPPS(getPk(), dicomObject).getAttributes();
    }

    @Override
    public AbstractEditableDicomModel refresh() {
        StudyListLocal dao = (StudyListLocal) JNDIUtils.lookup(StudyListLocal.JNDI_NAME);
        if (dataset != null) {
            dataset = dao.getMPPS(getPk()).getAttributes();
        } else {
            ArrayList<SeriesModel> currentSeries = new ArrayList<SeriesModel>();
            for (Series s : dao.findSeriesOfStudy(getStudy().getPk())) {
                SeriesModel seriesModel = new SeriesModel(s, null, s.getCreatedTime());
                MPPS mpps = s.getModalityPerformedProcedureStep();
                if (mpps == null && seriesModel.containedBySamePPS(getSeries1())) {
                    currentSeries.add(seriesModel);
                }
            }
            seriess.retainAll(currentSeries);
        }
        numberOfSeries = 0;
        numberOfInstances = 0;
        return this;
    }

    @Override
    public String toString() {
        return "MPPS: "+this.getUid();
    }
}


text:
			<img src="<?php echo base_url() ?>external/img/a4.jpg" alt="" class="img_fondo_secciones">

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam id elit consequat
						felis sagittis pulvinar sit amet at diam. Donec sodales nec augue eu gravida.
						Integer bibendum enim sit amet varius maximus. Vestibulum sapien ex,
						varius nec bibendum a, eleifend sit amet odio.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam id elit consequat
						felis sagittis pulvinar sit amet at diam. Donec sodales nec augue eu gravida.
						Integer bibendum enim sit amet varius maximus. Vestibulum sapien ex,
						varius nec bibendum a, eleifend sit amet odio.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam id elit consequat
						felis sagittis pulvinar sit amet at diam. Donec sodales nec augue eu gravida.
						Integer bibendum enim sit amet varius maximus. Vestibulum sapien ex,
						varius nec bibendum a, eleifend sit amet odio.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam id elit consequat
						felis sagittis pulvinar sit amet at diam. Donec sodales nec augue eu gravida.
						Integer bibendum enim sit amet varius maximus. Vestibulum sapien ex,
						varius nec bibendum a, eleifend sit amet odio.


text:
import {SUBMIT_GET_TRANSACTIONS,
        FINISH_GET_TRANSACTIONS,
        SUBMIT_UPDATE_TRANSACTIONS,
        FINISH_UPDATE_TRANSACTIONS,
        SUBMIT_ADD_TRANSACTIONS,
        FINISH_ADD_TRANSACTIONS
         } from 'containers/Transactions/actions/transaction-action-types';

function submitGetTransactions() {
    return {
        transactions:[],
        type: SUBMIT_GET_TRANSACTIONS
    }
}

function finishGetTransactions() {
    return {
        transactions: [],
        type: FINISH_GET_TRANSACTIONS
    }
}

function submitAddTransaction(transactionItem){
    return {
        transactionItem: transactionItem,
        type: SUBMIT_ADD_TRANSACTIONS
    }
}

function finishAddTransaction(transactionItem){
    return {
        transactionItem: transactionItem,
        type: FINISH_ADD_TRANSACTIONS
    }
}

/*Update transactions */
function submitUpdateTransaction(transactionItem){
    return{
        transactionItem:transactionItem,
        type: SUBMIT_UPDATE_TRANSACTIONS
    }
}

/*Update transactions */
function finishUpdateTransaction(transactionItem){
    return{
        transactionItem:transactionItem,
        type: FINISH_UPDATE_TRANSACTIONS
    }
}

export function getTransactions(){
    return (dispatch, getState) => {
            dispatch(submitGetTransactions());
            dispatch(finishGetTransactions());
    }
}

export function updateTransaction(transactionItem){
    return (dispatch, getState) => {
            dispatch(submitUpdateTransaction(transactionItem));
            dispatch(finishUpdateTransaction(transactionItem));
    }
}

export function addTransaction(transactionItem) {
    return (dispatch, getState) => {
            dispatch(submitAddTransaction(transactionItem));
            dispatch(finishAddTransaction(transactionItem));
    }
}


text:
package spark.perf

import scala.collection.JavaConverters._

import joptsimple.{OptionSet, OptionParser}
import org.json4s.JsonDSL._
import org.json4s.JsonAST._

import org.apache.spark.SparkContext

import scala.util.Random

/** Schedule a large number of null tasks to test scheduler/task launching throughput. */
class SchedulerThroughputTest(sc: SparkContext) extends PerfTest {
  val NUM_TRIALS = ("num-trials", "number of trials to run")
  val INTER_TRIAL_WAIT = ("inter-trial-wait",   "seconds to sleep between trials")
  val NUM_TASKS =  ("num-tasks", "number of tasks to create/run in each job")
  val NUM_JOBS = ("num-jobs", "number of jobs to run")
  val RANDOM_SEED = ("random-seed", "seed for random number generator")
  val CLOSURE_SIZE = ("closure-size", "task closure size (in bytes)")

  val parser = new OptionParser()
  var optionSet: OptionSet = _

  Seq(NUM_TRIALS, INTER_TRIAL_WAIT, NUM_TASKS, NUM_JOBS, RANDOM_SEED, CLOSURE_SIZE).map {
    case (opt, desc) =>
      parser.accepts(opt, desc).withRequiredArg().ofType(classOf[Int]).required()
  }

  def initialize(args: Array[String]) = {
    optionSet = parser.parse(args.toSeq: _*)
  }

  def createInputData() = {}

  def run(): (JValue, Seq[JValue]) = {
    val numTrials = optionSet.valueOf(NUM_TRIALS._1).asInstanceOf[Int]
    val interTrialWait = optionSet.valueOf(INTER_TRIAL_WAIT._1).asInstanceOf[Int]
    val numTasks = optionSet.valueOf(NUM_TASKS._1).asInstanceOf[Int]
    val numJobs = optionSet.valueOf(NUM_JOBS._1).asInstanceOf[Int]
    val randomSeed = optionSet.valueOf(RANDOM_SEED._1).asInstanceOf[Int]
    val closureSize = optionSet.valueOf(CLOSURE_SIZE._1).asInstanceOf[Int]

    // Allows us to simulate large task closures; this consists of random bytes in order
    // to make it incompressible:

    val mapFunction = SchedulerThroughputTest.getMapFunction(closureSize, randomSeed)

    val options: Map[String, String] = optionSet.asMap().asScala.flatMap { case (spec, values) =>
      if (spec.options().size() == 1 && values.size() == 1) {
        Some((spec.options().iterator().next(), values.iterator().next().toString))
      } else {
        None
      }
    }.toMap

    val results: Seq[JValue] = (1 to numTrials).map { t =>
      val start = System.currentTimeMillis()
      (1 to numJobs).foreach { _ =>
        sc.makeRDD(1 to numTasks, numTasks).mapPartitions(mapFunction).count()
      }
      val end = System.currentTimeMillis()
      val time = (end - start).toDouble / 1000.0
      System.gc()
      Thread.sleep(interTrialWait * 1000)
      ("time" -> time) : JValue
    }

    (options, results)
  }
}

object SchedulerThroughputTest {

  private def getMapFunction(closureSize: Int, randomSeed: Int) = {
    val closureData: Array[Byte] = Array.ofDim[Byte](closureSize)
    val rand = new Random(randomSeed)
    rand.nextBytes(closureData)

    def mapFunction(iter: Iterator[Int]): Iterator[Int] = {
      closureData.size  // Reference so that the random data is serialized with the task
      iter
    }
    mapFunction _
  }

}


text:
layout: default
title: Where are my Files?
i18n: en
---

# Where are my Files?

The quick answer is that they're in the `mu_code` directory in your home
directory. That's all there is to it.

If you're interested in why, please read on... :-)

Because feedback from teachers tells us that people easily lose their code
(students will save it somewhere and then forget where they put it -- a 21st
century version of "the dog ate my homework").

By having a default location Mu aims to help avoid this problem.

Of course, when you name a file (either the first time you save it, or when
you double-click the filename on its tab in order to rename it) then you can
use the file selector that pops up to navigate to any other directory. It's
also possible to change directories to find a file elsewhere on disk when you
load a new file. In any case, Mu will always default to `mu_code`.


text:
"use strict";
describe("Spotify Service", function() {
    //stubs, spies and mocks
    var _clock,
        _sandbox,
        _ajaxStub,
        _trackApiCallData = Stub_tracks,
        _meApiCallData = Stub_me,
        _userPlaylistsApiCallData = Stub_userPlaylists,
        _userPlaylistsApiCallDataOffset50 = Stub_userPlaylistsOffset50,
        _playlistApiCallData = Stub_playlistApiCallData,
        _offset = 0;

    beforeEach(function() {
        _clock = sinon.useFakeTimers();
        _sandbox = sinon.sandbox.create();

        _ajaxStub = _sandbox.stub($, "ajax", function(url, config) {
            return {
                then: function(success, failed) {
                    var _returnData, _deferredType = 'resolve';

                    if (url.indexOf('https://api.spotify.com/v1/users/erikportin/playlists/53Y8wT46QIMz5H4WQ8O22c/tracks') === 0) {
                        _returnData = _trackApiCallData;
                    } else {
                        switch (url) {
                            case 'https://api.spotify.com/v1/me':
                                if (config.headers.Authorization === 'Bearer access_token_value') {
                                    _returnData = _meApiCallData;
                                } else {
                                    _returnData = new Error('Error getting data');
                                    _deferredType = 'reject';
                                }
                                break;
                            case 'https://api.spotify.com/v1/users/erikportin/playlists?limit=50&offest=0':
                                _returnData = _userPlaylistsApiCallData;
                                break;
                            case 'https://api.spotify.com/v1/users/erikportin/playlists?limit=50&offest=50':
                                _returnData = _userPlaylistsApiCallDataOffset50;
                                break;
                            case 'https://api.spotify.com/v1/users/erikportin/playlists/53Y8wT46QIMz5H4WQ8O22c':
                                _returnData = _playlistApiCallData;
                                break;
                            default:
                                _returnData = new Error('Error getting data');
                                _deferredType = 'reject';
                        }
                    }

                    if (_deferredType === 'resolve') {
                        success.call(this, _returnData);
                    } else {
                        failed.call(this, _returnData);
                    }
                }
            };
        });

        jasmine.addMatchers({
            toBeCalledWithValidRandomOffset: function() {
                return {
                    compare: function(actual, expected) {
                        var _url = actual,
                            _queries = {};

                        _url.split('?')[1].split('&').forEach(function(query) {
                            var keyPair = query.split('=');
                            _queries[keyPair[0]] = parseInt(keyPair[1]);
                        })

                        return {
                            pass: expected >= _queries.offset + _queries.limit
                        };
                    }
                };
            }
        });
    })

    afterEach(function() {
        _sandbox.restore();
        _clock.restore();
    })

    describe("getTokens()", function() {
        it("should return tokens from url search string", function() {
            var _tokens = spotifyService.getTokens('?key1=value1&access_token=access_token_value&key2=value2&refresh_token=refresh_token_value');

            expect(_tokens.refreshToken).toEqual('refresh_token_value');
            expect(_tokens.accessToken).toEqual('access_token_value');

        });
    });

    describe("getUser()", function() {
        it("should return spotify user when token are valid", function() {
            var _user;

            spotifyService.getUser('access_token_value').then(function(user) {
                _user = user;
            });

            expect(_user.display_name).toEqual('Erik Portin');
        });

        it("should fail if token is invalid", function() {
            var _error;

            spotifyService.getUser('inavlid_access_token_value').then(function(user) {}, function(error) {
                _error = error;
            });

            expect(_error).toBeDefined();
        });

    });

    //describe("getPlaylists()", function() {

/*        it("should return playlists if exists", function() {
            Settings.debug = true;
            var _playlists;

            spotifyService.getPlaylists('erikportin').then(function(playlists) {
                console.log('then 3')
                console.log(playlists.obj['53Y8wT46QIMz5H4WQ8O22c'].name)
                _playlists = playlists;
            })

            expect(_playlists['53Y8wT46QIMz5H4WQ8O22c'].name).toEqual('erikportins Big Playlist');
            expect(_playlists['53Y8wT46QIMz5H4WQ8O22c'].id).toEqual('53Y8wT46QIMz5H4WQ8O22c');
            expect(_playlists['53Y8wT46QIMz5H4WQ8O22c'].total).toEqual(30);
            expect(_playlists['53Y8wT46QIMz5H4WQ8O22c'].owner).toEqual('erikportin');

        });*/

        /*      it("should return error if data not available", function() {
        var _error;

        spotifyService.getPlaylists('unavailableUser').then(function(){
            console.log('then')
        },function(error){
          _error = error;
        })

        _clock.tick();

        expect(_error).toBeDefined();

      });

      it("should return playlists from storage", function() {
        var _playlists;

        spotifyService.getPlaylists('erikportin').then(function(playlists){
            console.log('then')
          _playlists = playlists;
        })

        _clock.tick();

        expect(_playlists['53Y8wT46QIMz5H4WQ8O22c'].name).toEqual('erikportins Big Playlist');
        expect(_playlists['53Y8wT46QIMz5H4WQ8O22c'].id).toEqual('53Y8wT46QIMz5H4WQ8O22c');
        expect(_playlists['53Y8wT46QIMz5H4WQ8O22c'].total).toEqual(30);
        expect(_playlists['53Y8wT46QIMz5H4WQ8O22c'].owner).toEqual('erikportin');

        expect(_ajaxStub.called).toBe(false);

      });*/
    //});

    /*    describe("getTracks()", function(){

      it("should return track data", function() {
        var _tracks;

        spotifyService.getTracks('erikportin', '53Y8wT46QIMz5H4WQ8O22c', 200).then(function(tracks){
            console.log('then')
          _tracks = tracks;
        });

        _clock.tick();

        expect(_tracks.length).toBe(5);

        expect(_tracks[0].artist.name).toBeDefined()
        expect(_tracks[0].artist.id).toBeDefined()
        expect(_tracks[0].track.name).toBeDefined()
        expect(_tracks[0].track.url).toBeDefined()

        expect(_tracks[4].artist.name).toBeDefined()
        expect(_tracks[4].artist.id).toBeDefined()
        expect(_tracks[4].track.name).toBeDefined()
        expect(_tracks[4].track.url).toBeDefined()

        expect(_ajaxStub.args[0][0]).toBeCalledWithValidRandomOffset(200);

      });

      it("should fail if data no available", function() {
        var _error;

        spotifyService.getTracks('erikportin', 'unavailableId', 200).then(function(tracks){
            console.log('then 3')
        }, function(error){
          _error = error;
        })

        _clock.tick();

        expect(_error).toBeDefined();

      });

      it("should use stored playlist data if exists", function() {
        var _tracks;

        spotifyService.getTracks('erikportin', '53Y8wT46QIMz5H4WQ8O22c', 99).then(function(tracks){
            console.log('then -1')
          _tracks = tracks;
        })
        _clock.tick();

        spotifyService.getTracks('erikportin', '53Y8wT46QIMz5H4WQ8O22c', 99).then(function(tracks){
            console.log('then -2')
          _tracks = tracks;
        })

        _clock.tick();

        expect(_ajaxStub.calledOnce).toBe(false);
        expect(_tracks.length).toBe(5);

      });
    });
*/

})


text:
<TITLE>Review for Gladiator (2000)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Gladiator (2000)

reviewed by
Ian Waldron-Mantgani

 Gladiator      **1/2

Rated on a 4-star scale
Screening venue: Odeon (Liverpool City Centre)
Released in the UK by UIP on May 12, 2000; certificate 15; 150 minutes;
country of origin USA; aspect ratio 2.35:1

Directed by Ridley Scott; produced by David Franzoni, Branko Lustig, Douglas
Wick.
Written by David Franzoni, John Logan, William Nicholson; from a story by
David Franzoni.
Photographed by John Mathieson; edited by Pietro Scalia.

CAST.....
Russell Crowe..... Maximus
Joaquin Phoenix..... Commodus
Connie Nielsen..... Lucilla
Oliver Reed..... Proximo
Richard Harris..... Marcus Aurelius
Derek Jacobi..... Gracchus
Djimos Honsou..... Juba
David Schofield..... Falco

Ridley Scott's "Gladiator" is an interesting and attractive action movie, but
not a very forceful one. It needs to spend more time with the gladiator
himself. This is a "hero out for revenge" picture that keeps cutting away to
its cardboard villain, just as we're starting to cheer on the protagonist.
It's like channel-hopping between "Spartacus" and "Caligula".

Russell Crowe stars as Maximus, a Roman army general under emperor Marcus
Aurelius (Richard Harris). Marcus is so impressed by Maximus's leadership
that he appoints him as his successor. His son Commodus (Joaquin Phoenix) is
not best pleased by this news, as he himself had expected to be next in line
for the throne. Commodus kills his father, seizes power, and orders the death
penalty for Maximus and his family.

Of course, Maximus escapes this fate, but his wife and child do not. Then
Maximus is kidnapped and sold into slavery. His master, Proximo (Oliver
Reed), forces him to become a gladiator, and when his military training leads
to great slaughtering talent, Proximo takes him to Rome, to perform at the
Coliseum. There the crowd falls in love with him, which forces Commodus into
an awkward position; yes, he's found Maximus, but he can't deal with him,
because if he kills him then he'll lose the support of his people.

The movie is basically taken up by Maximus and Commodus doing a lot of
plotting against each other, punctuated by lofty speeches and gruesome
fights. That is as it should be. The problem is that we don't spend enough
time with Maximus -- the film is divided pretty much equally between him and
the enemy, when it needs to be much more single-minded. Look at "Ben-Hur" or
"Braveheart" -- these films are driven completely by their heroes'
determination, and that's why we get emotionally involved. Crowe gives a
great performance as Maximus -- he has a penetrating stare, commanding voice,
muscular body and towering demeanour. He's a powerful, passionate Hollywood
lead, and we want to invest our care in him. We just don't get the chance.

Because "Gladiator" never gets us wrapped up in Maximus's struggle, the
action sequences are not as tense or affecting as they should be. We can't
simply enjoy the excitement of the violence, either, because it's not
stimulating, it's sick. Roman bloodlust is one of the most shameful things in
history, and Scott, the director, presents it realistically, throwing us into
the middle of gladiator fights by way of giddy close-ups and shutter speeds,
while the chants of the despicable onlookers thunder at our ears in stereo
surround sound.

What we have here, ultimately, is one amazing piece of acting and several
flourishes of wonderful technique, spoiled by unwanted distractions. The
overall bold, colourful nature of the filmmaking might have been enough to
recommend the picture if its better parts hadn't led us to expect something
superior. Strange: "Gladiator" would have been a more enjoyable movie if it
had been made with less skill.

COPYRIGHT(c) 2000 Ian Waldron-Mantgani
Please visit, and encourage others to visit, the UK Critic's website, which
is located at http://members.aol.com/ukcritic

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package main

import (
	"flag"
	"fmt"
	"github.com/slavaVA/go-api.ai"
	"os"
)

var (
	accessToken = flag.String("accessToken", "", "Client access token")
	queryText = flag.String("text", "", "Query text")
	lang = flag.String("lang","en-US", "Query language")
	fileName=flag.String("fileName","out.wav", "Out WAVE file name")
)

func main() {
	flag.Parse()
	if len(*accessToken)==0 {
		fmt.Println("Access token required!")
		return
	}

	fmt.Println("TTS API Endpoint : Lang=",*lang," text=",*queryText," accessToken=",*accessToken)

	exist,sl:=gapiai.IsLanguageSupport(*lang)
	if exist==false {
		fmt.Println("Language not supported: ",*lang)
		return
	}

	cfg:=&gapiai.ApiConfig{
		AccessToken:*accessToken,
		Lang:sl,
	}
	endPoint:=gapiai.DefaultTtsAPIEndpoint(cfg)

	endPoint.EnableLogger(os.Stdout)

	sh,err:=gapiai.NewSpeechToWaveFileHandler(*fileName)
	if err!=nil {
		panic(err)
	}
	if err:=endPoint.DoTts(*queryText,sh);err!=nil{
		panic(err)
	}
}


text:
//// [decoratorReferences.ts]
declare function y(...args: any[]): any;
type T = number;
@y(1 as T, C) // <-- T should be resolved to the type alias, not the type parameter of the class; C should resolve to the class
class C<T> {
    @y(null as T) // <-- y should resolve to the function declaration, not the parameter; T should resolve to the type parameter of the class
    method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
}

//// [decoratorReferences.js]
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var C = /** @class */ (function () {
    function C() {
    }
    C_1 = C;
    C.prototype.method = function (x, y) { }; // <-- decorator y should be resolved at the class declaration, not the parameter.
    var C_1;
    __decorate([
        y(null) // <-- y should resolve to the function declaration, not the parameter; T should resolve to the type parameter of the class
        ,
        __param(0, y)
    ], C.prototype, "method");
    C = C_1 = __decorate([
        y(1, C_1) // <-- T should be resolved to the type alias, not the type parameter of the class; C should resolve to the class
    ], C);
    return C;
}());


text:
<?php

namespace Graze\GuzzleHttp\JsonRpc\Exception;

use Graze\GuzzleHttp\JsonRpc\Test\UnitTestCase;

class RequestExceptionTest extends UnitTestCase
{
    /** @var mixed */
    private $request;
    /** @var mixed */
    private $response;

    public function setUp()
    {
        $this->request = $this->mockRequest();
        $this->response = $this->mockResponse();
    }

    /**
     * @return array
     */
    public function dataCreateClientException()
    {
        return [[-32600], [-32601], [-32602], [-32700]];
    }

    /**
     * @return array
     */
    public function dataCreateServerException()
    {
        return [[-32603], [-32000], [-32099], [-10000]];
    }

    /**
     * @dataProvider dataCreateClientException
     *
     * @param int $code
     */
    public function testCreateClientException($code)
    {
        $this->request->shouldReceive('getRequestTarget')->once()->withNoArgs()->andReturn('http://foo');
        $this->request->shouldReceive('getRpcMethod')->once()->withNoArgs()->andReturn('foo');
        $this->response->shouldReceive('getRpcErrorCode')->once()->withNoArgs()->andReturn($code);
        $this->response->shouldReceive('getRpcErrorMessage')->once()->withNoArgs()->andReturn('bar');
        $this->response->shouldReceive('getStatusCode')->once()->withNoArgs()->andReturn(200);

        $exception = RequestException::create($this->request, $this->response);
        $this->assertInstanceOf('Graze\GuzzleHttp\JsonRpc\Exception\ClientException', $exception);
    }

    /**
     * @dataProvider dataCreateServerException
     *
     * @param int $code
     */
    public function testCreateServerException($code)
    {
        $this->request->shouldReceive('getRequestTarget')->once()->withNoArgs()->andReturn('http://foo');
        $this->request->shouldReceive('getRpcMethod')->once()->withNoArgs()->andReturn('foo');
        $this->response->shouldReceive('getRpcErrorCode')->once()->withNoArgs()->andReturn($code);
        $this->response->shouldReceive('getRpcErrorMessage')->once()->withNoArgs()->andReturn('bar');
        $this->response->shouldReceive('getStatusCode')->once()->withNoArgs()->andReturn(200);

        $exception = RequestException::create($this->request, $this->response);
        $this->assertInstanceOf('Graze\GuzzleHttp\JsonRpc\Exception\ServerException', $exception);
    }
}


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

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_repository_sync"
        android:title="@string/menu_repository_sync" />
    <item android:id="@+id/menu_repository_rename"
        android:title="@string/menu_repository_rename" />
    <item android:id="@+id/menu_repository_delete"
        android:title="@string/menu_repository_delete" />
</menu>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        style="@style/mainLinear"
        android:fillViewport="true"
        android:padding="15dp"
        android:baselineAligned="false">

    <ScrollView style="@style/listItem" android:layout_weight="1">
        <LinearLayout
                style="@style/listItem"
                android:orientation="vertical"
                android:gravity="top">
            <LinearLayout style="@style/ringtoneGroup" android:id="@+id/ringtoneTypePreferenceGroup">
                <RadioButton
                        style="@style/ringtoneRadioButton"
                        android:id="@+id/ringtoneTypePreferenceButton"
                        android:checked="false" />
                <LinearLayout style="@style/ringtoneItem" android:id="@+id/ringtoneTypePreferenceText">
                    <TextView style="@style/ringtoneTypeLabel" android:text="@string/ringtoneTypePreference" />
                    <TextView
                            style="@style/ringtoneTypeDesc"
                            android:id="@+id/ringtoneTypePreferenceDesc"
                            android:text="@string/ringtoneTypePreferenceDesc" />
                </LinearLayout>
            </LinearLayout>
            <LinearLayout style="@style/ringtoneGroup" android:id="@+id/ringtoneTypeDefaultGroup">
                <RadioButton
                        style="@style/ringtoneRadioButton"
                        android:id="@+id/ringtoneTypeDefaultButton"
                        android:checked="true" />
                <LinearLayout style="@style/ringtoneItem" android:id="@+id/ringtoneTypeDefaultText">
                    <TextView style="@style/ringtoneTypeLabel" android:text="@string/ringtoneTypeDefault" />
                    <TextView
                            style="@style/ringtoneTypeDesc"
                            android:id="@+id/ringtoneTypeDefaultDesc"
                            android:text="@string/ringtoneTypeDefaultDesc" />
                </LinearLayout>
            </LinearLayout>
            <LinearLayout style="@style/ringtoneGroup" android:id="@+id/ringtoneTypeRingtoneGroup">
                <RadioButton
                        style="@style/ringtoneRadioButton"
                        android:id="@+id/ringtoneTypeRingtoneButton"
                        android:checked="false" />
                <LinearLayout style="@style/ringtoneItem" android:id="@+id/ringtoneTypeRingtoneText">
                    <TextView style="@style/ringtoneTypeLabel" android:text="@string/ringtoneTypeRingtone" />
                    <TextView
                            style="@style/ringtoneTypeDesc"
                            android:id="@+id/ringtoneTypeRingtoneDesc"
                            android:text="@string/ringtoneTypeRingtoneDesc" />
                </LinearLayout>
            </LinearLayout>
            <LinearLayout style="@style/ringtoneGroup" android:id="@+id/ringtoneTypeMusicGroup">
                <RadioButton
                        style="@style/ringtoneRadioButton"
                        android:id="@+id/ringtoneTypeMusicButton"
                        android:checked="false" />
                <LinearLayout style="@style/ringtoneItem" android:id="@+id/ringtoneTypeMusicText">
                    <TextView style="@style/ringtoneTypeLabel" android:text="@string/ringtoneTypeMusic" />
                    <TextView
                            style="@style/ringtoneTypeDesc"
                            android:id="@+id/ringtoneTypeMusicDesc"
                            android:text="@string/ringtoneTypeMusicDesc" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout style="@style/ringtonePickerListItem" android:id="@+id/ringtoneVolumeGroup">
                <TextView style="@style/ringtonePickerListItemLabel" android:text="@string/ringtoneVolume" />
                <SeekBar
                        style="@style/listItem"
                        android:id="@+id/ringtoneVolumeBar"
                        android:paddingLeft="10dp"
                        android:paddingRight="10dp" />
            </LinearLayout>

            <LinearLayout style="@style/ringtonePickerListItem" android:id="@+id/ringtoneFadeInTimeGroup">
                <TextView style="@style/ringtonePickerListItemLabel" android:text="@string/ringtoneFadeInTime" />
                <Spinner
                        style="@style/listItem"
                        android:id="@+id/ringtoneFadeInTime"
                        android:entries="@array/ringtoneFadeInTimeEntries"
                        android:layout_marginLeft="8dp"
                        android:layout_marginRight="8dp" />
            </LinearLayout>

            <LinearLayout style="@style/ringtonePickerListItem">
                <TextView style="@style/ringtonePickerListItemLabel" android:text="@string/ringtonePreview" />
                <ToggleButton
                        android:id="@+id/ringtonePreview"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="8dp"
                        android:layout_marginRight="8dp"
                        android:textOn="@string/ringtonePreviewPlay"
                        android:textOff="@string/ringtonePreviewStop"
                        android:checked="false" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

    <LinearLayout
            style="@style/listItem"
            android:orientation="horizontal"
            android:layout_weight="0"
            android:layout_marginTop="20dp">
        <Button
            style="@style/toolBarButton"
            android:id="@+id/okButton"
            android:text="@string/buttonOK" />
        <Button
            style="@style/toolBarButton"
            android:id="@+id/cancelButton"
            android:text="@string/buttonCancel" />
    </LinearLayout>
</LinearLayout>