text:
package com.parking.parkingguide.menuact;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.parking.parkingguide.R;
import com.parking.parkingguide.bean.HistoryBean;
import com.parking.parkingguide.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HistoryActivity extends AppCompatActivity {
    String month;
    String day;
    ListView listView;
    ArrayList<HistoryBean.Result> results;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inner_layout_history);
        EventBus.getDefault().register(this);
        Calendar calendar=Calendar.getInstance();
        listView=(ListView)findViewById(R.id.lv_history);
        month=calendar.get(Calendar.MONTH)+"";
        day=calendar.get(Calendar.DAY_OF_MONTH)+"";
        getDataFromSerber();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    private void getDataFromSerber(){
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder().url("http://api.juheapi.com/japi/toh?v=1.0&month="+month
        +"&day="+day+"&key=13066f9857a04076246fe18bf648c4bf").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtils.showToastShort(HistoryActivity.this,"数据获取失败");
                call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData=response.body().string();
                Gson gson=new Gson();
                HistoryBean historyBean=gson.fromJson(responseData,HistoryBean.class);
                EventBus.getDefault().post(historyBean);
                call.cancel();
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleHistory(HistoryBean historyBean){
        results=historyBean.result;
        listView.setAdapter(new ListHisAdapter());
    }
    class ListHisAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return results.size();
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder=null;
            if(view==null){
                holder=new ViewHolder();
                view=View.inflate(HistoryActivity.this,R.layout.item_listview,null);
                holder.tvData= (TextView) view.findViewById(R.id.tv_his_data);
                holder.tvLunar= (TextView) view.findViewById(R.id.tv_his_lunar);
                holder.tvTitle= (TextView) view.findViewById(R.id.tv_his_title);
                holder.tvDes= (TextView) view.findViewById(R.id.tv_his_des);
                view.setTag(holder);
            }else {
                holder=(ViewHolder) view.getTag();
            }
            HistoryBean.Result result=results.get(i);
            holder.tvData.setText(""+result.year+"年"+result.month+"月"+result.day+"日");
            holder.tvLunar.setText(""+result.lunar);
            holder.tvTitle.setText(""+result.title);
            holder.tvDes.setText(""+result.des);
            return view;
        }
        class ViewHolder{
            TextView tvData,tvLunar,tvTitle,tvDes;
        }
    }
}


text:
"""Tests for the optimizers module."""

import functools

from absl.testing import absltest
import numpy as np

import jax.numpy as jnp
import jax._src.test_util as jtu
from jax import jit, grad, jacfwd, jacrev
from jax import tree_util
from jax import lax
from jax.example_libraries import optimizers

from jax.config import config
config.parse_flags_with_absl()

class OptimizerTests(jtu.JaxTestCase):

  def _CheckOptimizer(self, optimizer, loss, x0, num_steps, *args, **kwargs):
    self._CheckFuns(optimizer, loss, x0, *args)
    self._CheckRun(optimizer, loss, x0, num_steps, *args, **kwargs)

  def _CheckFuns(self, optimizer, loss, x0, *args):
    init_fun, update_fun, get_params = optimizer(*args)
    opt_state = init_fun(x0)
    self.assertAllClose(x0, get_params(opt_state))
    opt_state2 = update_fun(0, grad(loss)(x0), opt_state)  # doesn't crash
    self.assertEqual(tree_util.tree_structure(opt_state),
                     tree_util.tree_structure(opt_state2))

  @jtu.skip_on_devices('gpu')
  def _CheckRun(self, optimizer, loss, x0, num_steps, *args, **kwargs):
    init_fun, update_fun, get_params = optimizer(*args)

    opt_state = init_fun(x0)
    for i in range(num_steps):
      x = get_params(opt_state)
      g = grad(loss)(x)
      opt_state = update_fun(i, g, opt_state)
    xstar = get_params(opt_state)
    self.assertLess(loss(xstar), 1e-2)

    update_fun_jitted = jit(update_fun)
    opt_state = init_fun(x0)
    for i in range(num_steps):
      x = get_params(opt_state)
      g = grad(loss)(x)
      opt_state = update_fun_jitted(i, g, opt_state)
    xstar = get_params(opt_state)
    self.assertLess(loss(xstar), 1e-2)

  def testSgdScalar(self):
    def loss(x): return x**2
    x0 = 1.
    num_iters = 100
    step_size = 0.1
    self._CheckOptimizer(optimizers.sgd, loss, x0, num_iters, step_size)

  def testSgdVector(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    num_iters = 100
    step_size = 0.1
    self._CheckOptimizer(optimizers.sgd, loss, x0, num_iters, step_size)

  def testSgdNestedTuple(self):
    def loss(xyz):
      x, (y, z) = xyz
      return sum(jnp.dot(a, a) for a in [x, y, z])
    x0 = (jnp.ones(2), (jnp.ones(2), jnp.ones(2)))
    num_iters = 100
    step_size = 0.1
    self._CheckOptimizer(optimizers.sgd, loss, x0, num_iters, step_size)

  def testMomentumVector(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    num_iters = 100
    step_size = 0.1
    mass = 0.
    self._CheckOptimizer(optimizers.momentum, loss, x0, num_iters, step_size, mass)

  def testMomentumDict(self):
    def loss(dct): return jnp.dot(dct['x'], dct['x'])
    x0 = {'x': jnp.ones(2)}
    num_iters = 100
    step_size = 0.1
    mass = 0.
    self._CheckOptimizer(optimizers.momentum, loss, x0, num_iters, step_size, mass)

  def testRmspropVector(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    num_iters = 100
    step_size = 0.1
    self._CheckOptimizer(optimizers.rmsprop, loss, x0, num_iters, step_size)

  def testAdamVector(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    num_iters = 100
    step_size = 0.1
    self._CheckOptimizer(optimizers.adam, loss, x0, num_iters, step_size)

  def testSgdClosure(self):
    def loss(y, x): return y**2 * x**2
    x0 = 1.
    y = 1.
    num_iters = 20
    step_size = 0.1
    partial_loss = functools.partial(loss, y)
    self._CheckRun(optimizers.sgd, partial_loss, x0, num_iters, step_size)

  def testAdagrad(self):

    def loss(xs):
      x1, x2 = xs
      return jnp.sum(x1**2) + jnp.sum(x2**2)

    num_iters = 100
    step_size = 0.1
    x0 = (jnp.ones(2), jnp.ones((2, 2)))
    self._CheckOptimizer(optimizers.adagrad, loss, x0, num_iters, step_size)

  def testSM3Scalar(self):
    def loss(x): return x**2
    x0 = jnp.array(1.)
    num_iters = 100
    step_size = 0.1
    self._CheckOptimizer(optimizers.sm3, loss, x0, num_iters, step_size)

  def testSM3Vector(self):
    def loss(xs):
      x1, x2 = xs
      return jnp.sum(x1 ** 2) + jnp.sum(x2 ** 2)

    num_iters = 100
    step_size = 0.1
    x0 = (jnp.ones(2), jnp.ones((2, 2)))
    self._CheckOptimizer(optimizers.sm3, loss, x0, num_iters, step_size)

  def testAdaMaxVector(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    num_iters = 100
    step_size = 0.1
    self._CheckOptimizer(optimizers.adamax, loss, x0, num_iters, step_size)

  def testSgdVectorExponentialDecaySchedule(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    step_schedule = optimizers.exponential_decay(0.1, 3, 2.)
    self._CheckFuns(optimizers.sgd, loss, x0, step_schedule)

  def testSgdVectorInverseTimeDecaySchedule(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    step_schedule = optimizers.inverse_time_decay(0.1, 3, 2.)
    self._CheckFuns(optimizers.sgd, loss, x0, step_schedule)

  def testAdamVectorInverseTimeDecaySchedule(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    step_schedule = optimizers.inverse_time_decay(0.1, 3, 2.)
    self._CheckFuns(optimizers.adam, loss, x0, step_schedule)

  def testMomentumVectorInverseTimeDecayStaircaseSchedule(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    step_sched = optimizers.inverse_time_decay(0.1, 3, 2., staircase=True)
    mass = 0.9
    self._CheckFuns(optimizers.momentum, loss, x0, step_sched, mass)

  def testRmspropmomentumVectorPolynomialDecaySchedule(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    step_schedule = optimizers.polynomial_decay(1.0, 50, 0.1)
    self._CheckFuns(optimizers.rmsprop_momentum, loss, x0, step_schedule)

  def testRmspropVectorPiecewiseConstantSchedule(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    step_schedule = optimizers.piecewise_constant([25, 75], [1.0, 0.5, 0.1])
    self._CheckFuns(optimizers.rmsprop, loss, x0, step_schedule)

  def testTracedStepSize(self):
    def loss(x): return jnp.dot(x, x)
    x0 = jnp.ones(2)
    step_size = 0.1

    init_fun, _, _ = optimizers.sgd(step_size)
    opt_state = init_fun(x0)

    @jit
    def update(opt_state, step_size):
      _, update_fun, get_params = optimizers.sgd(step_size)
      x = get_params(opt_state)
      g = grad(loss)(x)
      return update_fun(0, g, opt_state)

    update(opt_state, 0.9)  # doesn't crash

  # TODO(mattjj): re-enable
  # def testDeviceTupleState(self):
  #   init_fun, update_fun, _ = optimizers.sgd(0.1)
  #   opt_state = init_fun(jnp.zeros(3))
  #   self.assertIsInstance(opt_state, optimizers.OptimizerState)
  #   self.assertIsInstance(opt_state.packed_state, core.JaxTuple)
  #   opt_state = jit(update_fun)(0, jnp.zeros(3), opt_state)
  #   self.assertIsInstance(opt_state, optimizers.OptimizerState)
  #   self.assertIsInstance(opt_state.packed_state, xla.DeviceTuple)

  def testUpdateFunStructureMismatchErrorMessage(self):
    @optimizers.optimizer
    def opt_maker():
      def init_fun(x0):
        return {'x': x0}
      def update_fun(i, g, opt_state):
        x = opt_state['x']
        return {'x': x - 0.1 * g, 'v': g}  # bug!
      def get_params(opt_state):
        return opt_state['x']
      return init_fun, update_fun, get_params

    init_fun, update_fun, get_params = opt_maker()
    opt_state = init_fun(jnp.zeros(3))
    self.assertRaises(TypeError, lambda: update_fun(opt_state))

  def testUtilityNorm(self):
    x0 = (jnp.ones(2), (jnp.ones(3), jnp.ones(4)))
    norm = optimizers.l2_norm(x0)
    expected = np.sqrt(np.sum(np.ones(2+3+4)**2))
    self.assertAllClose(norm, expected, check_dtypes=False)

  def testUtilityClipGrads(self):
    g = (jnp.ones(2), (jnp.ones(3), jnp.ones(4)))
    norm = optimizers.l2_norm(g)

    ans = optimizers.clip_grads(g, 1.1 * norm)
    expected = g
    self.assertAllClose(ans, expected, check_dtypes=False)

    ans = optimizers.l2_norm(optimizers.clip_grads(g, 0.9 * norm))
    expected = 0.9 * norm
    self.assertAllClose(ans, expected, check_dtypes=False)

  def testIssue758(self):
    # code from https://github.com/google/jax/issues/758
    # this is more of a scan + jacfwd/jacrev test, but it lives here to use the
    # optimizers.py code

    def harmonic_bond(conf, params):
      return jnp.sum(conf * params)

    opt_init, opt_update, get_params = optimizers.sgd(5e-2)

    x0 = np.array([0.5], dtype=np.float64)

    def minimize_structure(test_params):
      energy_fn = functools.partial(harmonic_bond, params=test_params)
      grad_fn = grad(energy_fn, argnums=(0,))
      opt_state = opt_init(x0)

      def apply_carry(carry, _):
        i, x = carry
        g = grad_fn(get_params(x))[0]
        new_state = opt_update(i, g, x)
        new_carry = (i+1, new_state)
        return new_carry, _

      carry_final, _ = lax.scan(apply_carry, (0, opt_state), jnp.zeros((75, 0)))
      trip, opt_final = carry_final
      assert trip == 75
      return opt_final

    initial_params = jnp.array(0.5)
    minimize_structure(initial_params)

    def loss(test_params):
      opt_final = minimize_structure(test_params)
      return 1.0 - get_params(opt_final)[0]

    loss_opt_init, loss_opt_update, loss_get_params = optimizers.sgd(5e-2)

    J1 = jacrev(loss, argnums=(0,))(initial_params)
    J2 = jacfwd(loss, argnums=(0,))(initial_params)
    self.assertAllClose(J1, J2, rtol=1e-6)

  def testUnpackPackRoundTrip(self):
    opt_init, _, _ = optimizers.momentum(0.1, mass=0.9)
    params = [{'w': self.rng().randn(1, 2), 'bias': self.rng().randn(2)}]
    expected = opt_init(params)
    ans = optimizers.pack_optimizer_state(
        optimizers.unpack_optimizer_state(expected))
    self.assertEqual(ans, expected)

if __name__ == '__main__':
  absltest.main(testLoader=jtu.JaxTestLoader())

redpajama_set_name: RedPajamaGithub


text:
import edit_button from '../edit_button.html';

export default function (nga, admin) {
	var devices = admin.getEntity('Devices')
	devices.listView()
		.title('
Devices  List
')
		.batchActions([
            '<sendpush type="SOFTWARE_INSTALL" selection="selection"></sendpush>',
			'<sendpush type="deletedata" selection="selection"></sendpush>',
			'<sendpush type="deletesharedpreferences" selection="selection"></sendpush>'
        ])
        .actions(['<remove type="remove_devices" selection="selection"></remove>','batch', 'export', 'filter'])
		.fields([
			nga.field('id')
				.label('ID'),
			nga.field('username')
				.label('Username'),
			nga.field('device_ip', 'string')
				.map(function truncate(value) {
                 	if (!value) {
                            return '';
                      	}
                            return value.length > 14 ? value.substr(0, 14) + '...' : value;
						  })
				.template((entry) => `<a target="_blank" href="https://tools.keycdn.com/geo?host=${entry.values.device_ip}">{{entry.values.device_ip}}</a>`)
				.label('IP'),
            nga.field('city', 'string')
                .label('City'),
			nga.field('device_mac_address', 'string')
				.label('Ethernet'),
			nga.field('device_wifimac_address', 'string')
				.label('WiFi'),
			nga.field('appid')
				.map(function app(value) {
					if (value === 1) {
						return 'Box';
					} else if (value === 2) {
						return 'Android';
					} else if (value === 3) {
						return 'Ios';
					} else if (value === 4) {
						return 'Stv';
					} else if (value === 5) {
						return 'Samsung';
					} else if (value === 6) {
						return 'Apple TV';
					} else if(value === 7) {
						return 'Web Smart TV';
					} else if(value === 8) {
						return 'Web App';
					} else if(value === 9) {
						return 'Roku TV';
					}
				})
				.label('App'),
			nga.field('app_version')
				.label('App Version'),
			nga.field('hdmi')
				.label('HDMI'),
			nga.field('device_brand')
				.map(function truncate(value) {
                 	if (!value) {
                            return '';
                      	}
                            return value.length > 14 ? value.substr(0, 14) + '...' : value;
                      	})
				.label('Device Brand'),
			nga.field('device_active', 'boolean')
				.label('Device Active'),
			nga.field('api_version', 'string')
				.label('Api Version'),
		])
		.filters([
          nga.field('q')
              .label('')
              .template('
<input type="text" ng-model="value" placeholder="Search" class="form-control">
')
              .pinned(true),
           nga.field('appid','choice')
						 .choices([
							 {value: 1, label: 'Box'},
							 {value: 2, label: 'Android'},
							 {value: 3, label: 'Ios'},
							 {value: 4, label: 'Stv'},
							 {value: 5, label: 'Samsung'},
							 {value: 6, label: 'Apple TV'},
							 {value: 7, label: 'Web Smart TV'},
							 {value: 8, label: 'Web App'},
							 {value: 9, label: 'Roku TV'}
						 ])
           	  .attributes({ placeholder: 'App Id' })
        	  .label('App ID'),
           nga.field('app_version')
           	  .attributes({ placeholder: 'App Version' })
        	  .label('App Version'),
           nga.field('api_version')
           	  .attributes({ placeholder: 'Api Version' })
        	  .label('Api Version'),
           nga.field('ntype','choice')
               .choices([
                   { value: 1, label: 'Wifi' },
                   { value: 2, label: 'Ethernet' },
                   { value: 3, label: 'GPRS' }
               ])
           	  .attributes({ placeholder: 'Ntype' })
        	  .label('Ntype'),
            nga.field('device_active', 'boolean')
                .filterChoices([
                    { value: true, label: 'Active' },
                    { value: false, label: 'Not Active' }
                ])
                .label('Device Active'),
            nga.field('hdmi')
                .attributes({ placeholder: 'HDMI' })
                .label('HDMI'),
            nga.field('username')
                .attributes({ placeholder: 'Username' })
                .label('Username'),
        ])
        .sortField('appid')
        .sortDir('ASC')
		.listActions([' More',' <remote-login device_id="{{entry.values.id}}" company_id="{{entry.values.company_id}}"></remote-login>'])
		.exportFields([
         devices.listView().fields(),
        ]);

	devices.creationView()
		.title('
Devices  Create: Device
')
		.fields([
			nga.field('username')
				.attributes({ placeholder: 'Username' })
				.validation({ required: true })
				.editable(false)
				.label('Username'),
			nga.field('googleappid', 'string')
				.editable(false)
				.attributes({ placeholder: 'Google App Id' })
				.label('Google App ID'),
			nga.field('device_active', 'boolean')
				.validation({ required: true })
				.label('Device Active'),
			nga.field('device_mac_address', 'string')
				.attributes({ placeholder: 'Device Mac Address' })
				.validation({ required: true })
				.editable(false)
				.label('Device Mac Address'),
			nga.field('device_wifimac_address', 'string')
				.attributes({ placeholder: 'Device Wifi Mac Address' })
				.validation({ required: true })
				.editable(false)
				.label('Device Wifi Mac Address'),
			nga.field('device_ip', 'string')
				.attributes({ placeholder: 'Device IP' })
				.validation({ required: true })
				.editable(false)
				.label('Device IP'),
            nga.field('city', 'string')
                .attributes({ placeholder: 'City' })
                .validation({ required: true })
                .editable(false)
                .label('City'),
			nga.field('device_id', 'string')
				.attributes({ placeholder: 'Device ID' })
				.validation({ required: true })
				.editable(false)
				.label('Device ID'),
			nga.field('ntype', 'string')
				.attributes({ placeholder: 'Ntype' })
				.validation({ required: true })
				.editable(false)
				.label('Ntype'),
			nga.field('appid', 'string')
				.attributes({ placeholder: 'App ID' })
				.validation({ required: true })
				.editable(false)
				.label('App ID'),
			nga.field('api_version', 'string')
				.attributes({ placeholder: 'Api Version' })
				.validation({ required: true })
				.editable(false)
				.label('Api Version'),
			nga.field('firmware', 'string')
				.editable(false)
				.label('Firmware'),
			nga.field('os')
				.editable(false)
				.label('Os'),
			nga.field('screen_resolution')
				.editable(false)
				.label('Screen Resolution'),
			nga.field('hdmi')
				.editable(false)
				.label('HDMI'),
			nga.field('device_brand')
				.editable(false)
				.label('Device Brand'),
			nga.field('app_version', 'string')
				.editable(false)
				.validation({ required: true })
				.label('App Version'),
			nga.field('createdAt', 'datetime')
				.editable(false)
				.label('First Login'),
			nga.field('updatedAt', 'datetime')
				.editable(false)
				.label('Last Login'),
            nga.field('template')
            	.label('')
            	.template(edit_button),
		])

    devices.editionView()
    	.title('
Devices  Edit: {{ entry.values.username }}
')
    	.actions(['list'])
		.fields([
			devices.creationView().fields(),
        ]);

	return devices;

}


text:
const Sqlite = require('nativescript-sqlite');

import {List} from 'immutable';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Observer}   from 'rxjs/Observer';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/share';

import {Score} from './score';
import {ScoreSql} from './score.sql';
import {DbBaseService} from '../db-base.service';

@Injectable()
export class ScoreService extends DbBaseService {

  dataChange$: Observable<Score[]>;
  minMovesChange$: Observable<number>;
  levelChange$: Observable<number>;
  nextRowChange$: Observable<number>;

  private _nextId: number;
  private _nextRow: number;
  private _nextRowObserver: Observer<number>;
  private _data: List<Score>;
  private _dataObserver: Observer<Score[]>;
  private _minMoves: number;
  private _minMovesObserver: Observer<number>;
  private _level: number;
  private _levelObserver: Observer<number>;

  get nextRow(): number {
    return this._nextRow;
  }

  set nextRow(value: number) {
    this.consoleLogMsg('score.service', 'set nextRow');
    if (this._nextRow !== value) {
      this._nextRow = value;
      if (this._nextRowObserver) {
        this._nextRowObserver.next(value);
      }
    }
  }

  get nextId(): number {
    return this._nextId;
  }

  get data(): Score[] {
    return this._data.toArray();
  }

  set data(value: Score[]) {
    this.consoleLogMsg('score.service', 'set data');
    let list: List<Score> = List(value);
    this._data = list;
    if (this._dataObserver) {
      this._dataObserver.next(value);
    }
  }

  get minMoves(): number {
    return this._minMoves;
  }

  set minMoves(value: number) {
    if (this._minMoves != value) {
      this._minMoves = value;
      if (this._minMovesObserver) {
        this._minMovesObserver.next(value);
      }
    }
  }

  get level(): number {
    return this._level;
  }

  set level(value: number) {
    if (this._level !== value) {
      this._level = value;
      this.fetch(value);
      if (this._levelObserver) {
        this._levelObserver.next(value);
      }
    }
  }

  constructor() {
    super();

    this._data = List([]);
    this._minMoves = null;
    this._level = null;

    this.dataChange$ = new Observable<Score[]>(
      (observer: any) => this._dataObserver = observer
    ).share();

    this.minMovesChange$ = new Observable<number>(
      (observer: any) => this._minMovesObserver = observer
    ).share();

    this.levelChange$ = new Observable<number>(
      (observer: any) => this._levelObserver = observer
    ).share();

    this.nextRowChange$ = new Observable<number>(
      (observer: any) => this._nextRowObserver = observer
    ).share();

    this.subscriptions.push(this.databaseChange$
      .subscribe(
        (database: any) => this.onDatabaseChange(database)
      ));

  }

  truncate() {
    this.consoleLogMsg('score.service', 'truncate');
    if (this.database) {
      this.consoleLogMsg('score.service', ScoreSql.dropHighScore);
      this.database.execSQL(ScoreSql.dropHighScore)
        .then((err:any) => {
          if (err) {
            this.consoleLogMsg('score.service', 'ERROR: Attempt to drop the high_scores table failed.');
            return;
          }
          this.consoleLogMsg('score.service', ScoreSql.createHighScore);
          this.database.execSQL(ScoreSql.createHighScore)
            .then((err:any) => {
              if (err) {
                this.consoleLogMsg('score.service', 'ERROR: Attempt to create the high_scores table failed.');
                return;
              }
              this._data = List([]);
              this.fetch(this.level);
            });
        });
    }
  }

  insert(score: Score) {
    this.consoleLogMsg('score.service', 'insert');
    this.consoleLogRecord(0, score);
    if (this.database) {
      this.database.execSQL(ScoreSql.insertHighScore, [score.id, score.user, score.time, score.moves, score.level])
        .then((item: any) => {
          this.consoleLogRecord(0, item);
        });
    }
  }

  fetch(level: number) {
    this.consoleLogMsg('score.service', 'fetch');
    let scores: Score[] = [],
      row: number = 1;
    if (this.database) {
      this.database.all(ScoreSql.selectHighScore).then((items: any[]) => {
        if (items && items.length) {
          items.forEach((item: any, index: number) => {
            let score: Score = new Score(
              item.hasOwnProperty('id') ? +(item.id) : 1,
              item.hasOwnProperty('user') ? item.user : null,
              item.hasOwnProperty('time') ? item.time : null,
              item.hasOwnProperty('moves') ? +(item.moves) : 0,
              item.hasOwnProperty('level') ? +(item.level) : 1,
              item.hasOwnProperty('id') && +(item.id) % 2 === 0 ? 'highScoreEven' : 'highScoreOdd'
            );
            score.row = row;
            this.consoleLogRecord(index, score);
            scores.push(score);
            row++;
          });
          this.data = scores;
          this.calc();
        } else {
          this.minMoves = 0;
          this.data = [];
        }
      }, error => {
        this.consoleLogMsg("SELECT ERROR", error);
      });
    }

  }

  isHighScore(moves: number, level: number): boolean {
    this.consoleLogMsg('score.service', 'isHighScore');
    if (level === this.level && this.minMoves) {
      return moves < this.minMoves ? true : false;
    }
    return false;
  }

  calc() {
    this.calcMinMoves();
    this.calcNextId();
    this.calcNextRow();
  }

  onDatabaseChange(database: any) {
    this.consoleLogMsg('score.service', 'onDatabaseChange');
    if (database && this.level) {
      this.fetch(this.level);
    } else {
      this.consoleLogMsg('score.service', 'WARNING: No level set in the score service.');
    }
  }

  private calcMinMoves() {
    this.consoleLogMsg('score.service', 'calcMinMoves');
    let moves: number = 0;
    if (this._data.size > 0) {
      this._data.map((score: Score) => {
        if (moves === 0 || score.moves < moves) {
          moves = score.moves;
        }
      });
    }
    this._minMoves = moves;
  }

  private calcNextId() {
    this.consoleLogMsg('score.service', 'calcNextId');
    let id: number = 1;
    if (this._data.size > 0) {
      this._data.map((score: Score) => {
        if (score.id > id) {
          id = score.id;
        }
      });
      id++;
    }
    this._nextId = id;
    this.consoleLogMsg('score.service', 'nextId = ' + this.nextId);
  }

  private calcNextRow() {
    this.consoleLogMsg('score.service', 'calcNextRow');
    let row: number = 1;
    if (this._data.size > 0) {
      this._data.map((score: Score) => {
        if (score.row > row) {
          row = score.row;
        }
      });
      row++;
    }
    this.nextRow = row;
    this.consoleLogMsg('score.service', 'nextRow = ' + this.nextRow);
  }

}


text:
import numpy
import unittest
import sys
sys.path.append('.')

from chempy.io.gaussian import *
from chempy.states import *

################################################################################

class GaussianTest(unittest.TestCase):
    """
    Contains unit tests for the chempy.io.gaussian module, used for reading
    and writing Gaussian files.
    """

    def testLoadEthyleneFromGaussianLog(self):
        """
        Uses a Gaussian03 log file for ethylene (C2H4) to test that its
        molecular degrees of freedom can be properly read.
        """

        log = GaussianLog('unittest/ethylene.log')
        s = log.loadStates()
        E0 = log.loadEnergy()

        self.assertTrue(len([mode for mode in s.modes if isinstance(mode,Translation)]) == 1)
        self.assertTrue(len([mode for mode in s.modes if isinstance(mode,RigidRotor)]) == 1)
        self.assertTrue(len([mode for mode in s.modes if isinstance(mode,HarmonicOscillator)]) == 1)
        self.assertTrue(len([mode for mode in s.modes if isinstance(mode,HinderedRotor)]) == 0)

        trans = [mode for mode in s.modes if isinstance(mode,Translation)][0]
        rot = [mode for mode in s.modes if isinstance(mode,RigidRotor)][0]
        vib = [mode for mode in s.modes if isinstance(mode,HarmonicOscillator)][0]
        Tlist = numpy.array([298.15], numpy.float64)
        self.assertAlmostEqual(trans.getPartitionFunction(Tlist) / 1.01325 / 5.83338e6, 1.0, 3)
        self.assertAlmostEqual(rot.getPartitionFunction(Tlist) / 2.59622e3, 1.0, 3)
        self.assertAlmostEqual(vib.getPartitionFunction(Tlist) / 1.0481e0, 1.0, 3)

        self.assertAlmostEqual(E0 / 6.02214179e23 / 4.35974394e-18 / -78.563169, 1.0, 2)
        self.assertEqual(s.spinMultiplicity, 1)

    def testLoadOxygenFromGaussianLog(self):
        """
        Uses a Gaussian03 log file for oxygen (O2) to test that its
        molecular degrees of freedom can be properly read.
        """

        log = GaussianLog('unittest/oxygen.log')
        s = log.loadStates()
        E0 = log.loadEnergy()

        self.assertTrue(len([mode for mode in s.modes if isinstance(mode,Translation)]) == 1)
        self.assertTrue(len([mode for mode in s.modes if isinstance(mode,RigidRotor)]) == 1)
        self.assertTrue(len([mode for mode in s.modes if isinstance(mode,HarmonicOscillator)]) == 1)
        self.assertTrue(len([mode for mode in s.modes if isinstance(mode,HinderedRotor)]) == 0)

        trans = [mode for mode in s.modes if isinstance(mode,Translation)][0]
        rot = [mode for mode in s.modes if isinstance(mode,RigidRotor)][0]
        vib = [mode for mode in s.modes if isinstance(mode,HarmonicOscillator)][0]
        Tlist = numpy.array([298.15], numpy.float64)
        self.assertAlmostEqual(trans.getPartitionFunction(Tlist) / 1.01325 / 7.11169e6, 1.0, 3)
        self.assertAlmostEqual(rot.getPartitionFunction(Tlist) / 7.13316e1, 1.0, 3)
        self.assertAlmostEqual(vib.getPartitionFunction(Tlist) / 1.000037e0, 1.0, 3)

        self.assertAlmostEqual(E0 / 6.02214179e23 / 4.35974394e-18 / -150.374756, 1.0, 4)
        self.assertEqual(s.spinMultiplicity, 3)

if __name__ == '__main__':
    unittest.main( testRunner = unittest.TextTestRunner(verbosity=2) )


text:
#ifndef AERON_PUBLICATION_H
#define AERON_PUBLICATION_H

#include <array>
#include <memory>
#include <string>

#include "concurrent/logbuffer/BufferClaim.h"
#include "concurrent/logbuffer/TermAppender.h"
#include "concurrent/status/UnsafeBufferPosition.h"
#include "concurrent/status/StatusIndicatorReader.h"
#include "LogBuffers.h"
#include "util/Export.h"

namespace aeron
{

using namespace aeron::concurrent::status;

class ClientConductor;

static const std::int64_t NOT_CONNECTED = -1;
static const std::int64_t BACK_PRESSURED = -2;
static const std::int64_t ADMIN_ACTION = -3;
static const std::int64_t PUBLICATION_CLOSED = -4;
static const std::int64_t MAX_POSITION_EXCEEDED = -5;

/**
 * @example BasicPublisher.cpp
 */
/**
 * Aeron Publisher API for sending messages to subscribers of a given channel and streamId pair. Publishers
 * are created via an {@link Aeron} object, and messages are sent via an offer method or a claim and commit
 * method combination.
 *

 * The APIs used to send are all non-blocking.
 *

 * Note: Publication instances are threadsafe and can be shared between publisher threads.
 * @see Aeron#addPublication
 * @see Aeron#findPublication
 */
class CLIENT_EXPORT Publication
{
public:

    /// @cond HIDDEN_SYMBOLS
    Publication(
        ClientConductor &conductor,
        const std::string &channel,
        std::int64_t registrationId,
        std::int64_t originalRegistrationId,
        std::int32_t streamId,
        std::int32_t sessionId,
        UnsafeBufferPosition &publicationLimit,
        std::int32_t channelStatusId,
        std::shared_ptr<LogBuffers> logBuffers);
    /// @endcond

    ~Publication();

    /**
     * Media address for delivery to the channel.
     *
     * @return Media address for delivery to the channel.
     */
    inline const std::string &channel() const
    {
        return m_channel;
    }

    /**
     * Stream identity for scoping within the channel media address.
     *
     * @return Stream identity for scoping within the channel media address.
     */
    inline std::int32_t streamId() const
    {
        return m_streamId;
    }

    /**
     * Session under which messages are published. Identifies this Publication instance.
     *
     * @return the session id for this publication.
     */
    inline std::int32_t sessionId() const
    {
        return m_sessionId;
    }

    /**
     * The initial term id assigned when this Publication was created. This can be used to determine how many
     * terms have passed since creation.
     *
     * @return the initial term id.
     */
    inline std::int32_t initialTermId() const
    {
        return m_initialTermId;
    }

    /**
     * Get the original registration used to register this Publication with the media driver by the first publisher.
     *
     * @return the original registrationId of the publication.
     */
    inline std::int64_t originalRegistrationId() const
    {
        return m_originalRegistrationId;
    }

    /**
     * Registration Id returned by Aeron::addPublication when this Publication was added.
     *
     * @return the registrationId of the publication.
     */
    inline std::int64_t registrationId() const
    {
        return m_registrationId;
    }

    /**
     * Is this Publication the original instance added to the driver? If not then it was added after another client
     * has already added the publication.
     *
     * @return true if this instance is the first added otherwise false.
     */
    inline bool isOriginal() const
    {
        return m_originalRegistrationId == m_registrationId;
    }

    /**
     * Maximum message length supported in bytes.
     *
     * @return maximum message length supported in bytes.
     */
    inline util::index_t maxMessageLength() const
    {
        return m_maxMessageLength;
    }

    /**
     * Maximum length of a message payload that fits within a message fragment.
     *
     * This is he MTU length minus the message fragment header length.
     *
     * @return maximum message fragment payload length.
     */
    inline util::index_t maxPayloadLength() const
    {
        return m_maxPayloadLength;
    }

    /**
     * Get the length in bytes for each term partition in the log buffer.
     *
     * @return the length in bytes for each term partition in the log buffer.
     */
    inline std::int32_t termBufferLength() const
    {
        return m_appenders[0]->termBuffer().capacity();
    }

    /**
     * Number of bits to right shift a position to get a term count for how far the stream has progressed.
     *
     * @return of bits to right shift a position to get a term count for how far the stream has progressed.
     */
    inline std::int32_t positionBitsToShift() const
    {
        return m_positionBitsToShift;
    }

    /**
     * Has this Publication seen an active subscriber recently?
     *
     * @return true if this Publication has seen an active subscriber recently.
     */
    inline bool isConnected() const
    {
        return !isClosed() && LogBufferDescriptor::isConnected(m_logMetaDataBuffer);
    }

    /**
     * Has this object been closed and should no longer be used?
     *
     * @return true if it has been closed otherwise false.
     */
    inline bool isClosed() const
    {
        return std::atomic_load_explicit(&m_isClosed, std::memory_order_acquire);
    }

    /**
     * Get the max possible position the stream can reach given term length.
     *
     * @return the max possible position the stream can reach given term length.
     */
    inline std::int64_t maxPossiblePosition() const
    {
        return m_maxPossiblePosition;
    }

    /**
     * Get the current position to which the publication has advanced for this stream.
     *
     * @return the current position to which the publication has advanced for this stream or {@link CLOSED}.
     */
    inline std::int64_t position() const
    {
        std::int64_t result = PUBLICATION_CLOSED;

        if (!isClosed())
        {
            const std::int64_t rawTail = LogBufferDescriptor::rawTailVolatile(m_logMetaDataBuffer);
            const std::int32_t termOffset = LogBufferDescriptor::termOffset(rawTail, termBufferLength());

            result = LogBufferDescriptor::computePosition(
                LogBufferDescriptor::termId(rawTail), termOffset, m_positionBitsToShift, m_initialTermId);
        }

        return result;
    }

    /**
     * Get the position limit beyond which this {@link Publication} will be back pressured.
     *
     * This should only be used as a guide to determine when back pressure is likely to be applied.
     *
     * @return the position limit beyond which this {@link Publication} will be back pressured.
     */
    inline std::int64_t publicationLimit() const
    {
        if (isClosed())
        {
            return PUBLICATION_CLOSED;
        }

        return m_publicationLimit.getVolatile();
    }

    /**
     * Get the counter id used to represent the publication limit.
     *
     * @return the counter id used to represent the publication limit.
     */
    inline std::int32_t publicationLimitId() const
    {
        return m_publicationLimit.id();
    }

    /**
     * Available window for offering into a publication before the {@link #positionLimit()} is reached.
     *
     * @return  window for offering into a publication before the {@link #positionLimit()} is reached. If
     * the publication is closed then {@link #CLOSED} will be returned.
     */
    inline std::int64_t availableWindow() const
    {
        std::int64_t result = PUBLICATION_CLOSED;

        if (!isClosed())
        {
            result = m_publicationLimit.getVolatile() - position();
        }

        return result;
    }

    /**
     * Get the counter id used to represent the channel status.
     *
     * @return the counter id used to represent the channel status.
     */
    inline std::int32_t channelStatusId() const
    {
        return m_channelStatusId;
    }

    /**
     * Get the status for the channel of this {@link Publication}
     *
     * @return status code for this channel
     */
    std::int64_t channelStatus() const;

    /**
     * Fetches the local socket addresses for this publication. If the channel is not
     * {@link aeron::concurrent::status::ChannelEndpointStatus::CHANNEL_ENDPOINT_ACTIVE}, then this will return an
     * empty list.
     *
     * The format is as follows:
     *

     *

     * IPv4: ip address:port
     *

     * IPv6: [ip6 address]:port
     *

     *

     * This is to match the formatting used in the Aeron URI
     *
     * @return local socket address for this subscription.
     * @see #channelStatus()
     */
    std::vector<std::string> localSocketAddresses() const;

    /**
     * Non-blocking publish of a buffer containing a message.
     *
     * @param buffer containing message.
     * @param offset offset in the buffer at which the encoded message begins.
     * @param length in bytes of the encoded message.
     * @param reservedValueSupplier for the frame.
     * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED},
     * {@link #ADMIN_ACTION} or {@link #CLOSED}.
     */
    inline std::int64_t offer(
        const concurrent::AtomicBuffer &buffer,
        util::index_t offset,
        util::index_t length,
        const on_reserved_value_supplier_t &reservedValueSupplier)
    {
        std::int64_t newPosition = PUBLICATION_CLOSED;

        if (!isClosed())
        {
            const std::int64_t limit = m_publicationLimit.getVolatile();
            const std::int32_t termCount = LogBufferDescriptor::activeTermCount(m_logMetaDataBuffer);
            TermAppender *termAppender = m_appenders[LogBufferDescriptor::indexByTermCount(termCount)].get();
            const std::int64_t rawTail = termAppender->rawTailVolatile();
            const std::int64_t termOffset = rawTail & 0xFFFFFFFF;
            const std::int32_t termId = LogBufferDescriptor::termId(rawTail);
            const std::int64_t position = LogBufferDescriptor::computeTermBeginPosition(
                termId, m_positionBitsToShift, m_initialTermId) + termOffset;

            if (termCount != (termId - m_initialTermId))
            {
                return ADMIN_ACTION;
            }

            if (position < limit)
            {
                std::int32_t resultingOffset;
                if (length <= m_maxPayloadLength)
                {
                    resultingOffset = termAppender->appendUnfragmentedMessage(
                        m_headerWriter, buffer, offset, length, reservedValueSupplier, termId);
                }
                else
                {
                    checkMaxMessageLength(length);
                    resultingOffset = termAppender->appendFragmentedMessage(
                        m_headerWriter, buffer, offset, length, m_maxPayloadLength, reservedValueSupplier, termId);
                }

                newPosition = Publication::newPosition(
                    termCount, static_cast<std::int32_t>(termOffset), termId, position, resultingOffset);
            }
            else
            {
                newPosition = Publication::backPressureStatus(position, length);
            }
        }

        return newPosition;
    }

    /**
     * Non-blocking publish of a buffer containing a message.
     *
     * @param buffer containing message.
     * @param offset offset in the buffer at which the encoded message begins.
     * @param length in bytes of the encoded message.
     * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED},
     * {@link #ADMIN_ACTION} or {@link #CLOSED}.
     */
    inline std::int64_t offer(const concurrent::AtomicBuffer &buffer, util::index_t offset, util::index_t length)
    {
        return offer(buffer, offset, length, DEFAULT_RESERVED_VALUE_SUPPLIER);
    }

    /**
     * Non-blocking publish of a buffer containing a message.
     *
     * @param buffer containing message.
     * @return The new stream position on success, otherwise {@link BACK_PRESSURED} or {@link NOT_CONNECTED}.
     */
    inline std::int64_t offer(const concurrent::AtomicBuffer &buffer)
    {
        return offer(buffer, 0, buffer.capacity());
    }

    /**
     * Non-blocking publish of buffers containing a message.
     *
     * @param startBuffer containing part of the message.
     * @param lastBuffer after the message.
     * @param reservedValueSupplier for the frame.
     * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED},
     * {@link #ADMIN_ACTION} or {@link #CLOSED}.
     */
    template<class BufferIterator>
    std::int64_t offer(
        BufferIterator startBuffer,
        BufferIterator lastBuffer,
        const on_reserved_value_supplier_t &reservedValueSupplier = DEFAULT_RESERVED_VALUE_SUPPLIER)
    {
        util::index_t length = 0;
        for (BufferIterator it = startBuffer; it != lastBuffer; ++it)
        {
            if (AERON_COND_EXPECT(length + it->capacity() < 0, false))
            {
                throw aeron::util::IllegalStateException(
                    "length overflow: " + std::to_string(length) + " + " + std::to_string(it->capacity()) +
                        " > " + std::to_string(length + it->capacity()),
                    SOURCEINFO);
            }

            length += it->capacity();
        }

        std::int64_t newPosition = PUBLICATION_CLOSED;

        if (!isClosed())
        {
            const std::int64_t limit = m_publicationLimit.getVolatile();
            const std::int32_t termCount = LogBufferDescriptor::activeTermCount(m_logMetaDataBuffer);
            TermAppender *termAppender = m_appenders[LogBufferDescriptor::indexByTermCount(termCount)].get();
            const std::int64_t rawTail = termAppender->rawTailVolatile();
            const std::int64_t termOffset = rawTail & 0xFFFFFFFF;
            const std::int32_t termId = LogBufferDescriptor::termId(rawTail);
            const std::int64_t position = LogBufferDescriptor::computeTermBeginPosition(
                termId, m_positionBitsToShift, m_initialTermId) + termOffset;

            if (termCount != (termId - m_initialTermId))
            {
                return ADMIN_ACTION;
            }

            if (position < limit)
            {
                std::int32_t resultingOffset;
                if (length <= m_maxPayloadLength)
                {
                    resultingOffset = termAppender->appendUnfragmentedMessage(
                        m_headerWriter, startBuffer, length, reservedValueSupplier, termId);
                }
                else
                {
                    checkMaxMessageLength(length);
                    resultingOffset = termAppender->appendFragmentedMessage(
                        m_headerWriter, startBuffer, length, m_maxPayloadLength, reservedValueSupplier, termId);
                }

                newPosition = Publication::newPosition(
                    termCount, static_cast<std::int32_t>(termOffset), termId, position, resultingOffset);
            }
            else
            {
                newPosition = Publication::backPressureStatus(position, length);
            }
        }

        return newPosition;
    }

    /**
     * Non-blocking publish of array of buffers containing a message.
     *
     * @param buffers containing parts of the message.
     * @param length of the array of buffers.
     * @param reservedValueSupplier for the frame.
     * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED},
     * {@link #ADMIN_ACTION} or {@link #CLOSED}.
     */
    std::int64_t offer(
        const concurrent::AtomicBuffer buffers[],
        size_t length,
        const on_reserved_value_supplier_t &reservedValueSupplier = DEFAULT_RESERVED_VALUE_SUPPLIER)
    {
        return offer(buffers, buffers + length, reservedValueSupplier);
    }

    /**
     * Non-blocking publish of array of buffers containing a message.
     *
     * @param buffers containing parts of the message.
     * @param reservedValueSupplier for the frame.
     * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED},
     * {@link #ADMIN_ACTION} or {@link #CLOSED}.
     */
    template<size_t N>
    std::int64_t offer(
        const std::array<concurrent::AtomicBuffer, N> &buffers,
        const on_reserved_value_supplier_t &reservedValueSupplier = DEFAULT_RESERVED_VALUE_SUPPLIER)
    {
        return offer(buffers.begin(), buffers.end(), reservedValueSupplier);
    }

    /**
     * Try to claim a range in the publication log into which a message can be written with zero copy semantics.
     * Once the message has been written then {@link BufferClaim#commit()} should be called thus making it available.
     *

     * Note: This method can only be used for message lengths less than MTU length minus header.
     *
     * @code
     *     BufferClaim bufferClaim; // Can be stored and reused to avoid allocation
     *
     *     if (publication->tryClaim(messageLength, bufferClaim) > 0)
     *     {
     *         try
     *         {
     *              AtomicBuffer& buffer = bufferClaim.buffer();
     *              const index_t offset = bufferClaim.offset();
     *
     *              // Work with buffer directly or wrap with a flyweight
     *         }
     *         finally
     *         {
     *             bufferClaim.commit();
     *         }
     *     }
     * @endcode
     *
     * @param length      of the range to claim, in bytes..
     * @param bufferClaim to be populate if the claim succeeds.
     * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED},
     * {@link #ADMIN_ACTION} or {@link #CLOSED}.
     * @throws IllegalArgumentException if the length is greater than max payload length within an MTU.
     * @see BufferClaim::commit
     */
    inline std::int64_t tryClaim(util::index_t length, concurrent::logbuffer::BufferClaim &bufferClaim)
    {
        checkPayloadLength(length);
        std::int64_t newPosition = PUBLICATION_CLOSED;

        if (!isClosed())
        {
            const std::int64_t limit = m_publicationLimit.getVolatile();
            const std::int32_t termCount = LogBufferDescriptor::activeTermCount(m_logMetaDataBuffer);
            TermAppender *termAppender = m_appenders[LogBufferDescriptor::indexByTermCount(termCount)].get();
            const std::int64_t rawTail = termAppender->rawTailVolatile();
            const std::int64_t termOffset = rawTail & 0xFFFFFFFF;
            const std::int32_t termId = LogBufferDescriptor::termId(rawTail);
            const std::int64_t position = LogBufferDescriptor::computeTermBeginPosition(
                termId, m_positionBitsToShift, m_initialTermId) + termOffset;

            if (termCount != (termId - m_initialTermId))
            {
                return ADMIN_ACTION;
            }

            if (position < limit)
            {
                const std::int32_t resultingOffset = termAppender->claim(m_headerWriter, length, bufferClaim, termId);
                newPosition = Publication::newPosition(
                    termCount, static_cast<std::int32_t>(termOffset), termId, position, resultingOffset);
            }
            else
            {
                newPosition = Publication::backPressureStatus(position, length);
            }
        }

        return newPosition;
    }

    /**
     * Add a destination manually to a multi-destination-cast Publication.
     *
     * @param endpointChannel for the destination to add
     * @return correlation id for the add command
     */
    std::int64_t addDestination(const std::string &endpointChannel);

    /**
     * Remove a previously added destination manually from a multi-destination-cast Publication.
     *
     * @param endpointChannel for the destination to remove
     * @return correlation id for the remove command
     */
    std::int64_t removeDestination(const std::string &endpointChannel);

    /**
     * Retrieve the status of the associated add or remove destination operation with the given correlationId.
     *
     * This method is non-blocking.
     *
     * The value returned is dependent on what has occurred with respect to the media driver:
     *
     * - If the correlationId is unknown, then an exception is thrown.
     * - If the media driver has not answered the add/remove command, then a false is returned.
     * - If the media driver has successfully added or removed the destination then true is returned.
     * - If the media driver has returned an error, this method will throw the error returned.
     *
     * @see Publication::addDestination
     * @see Publication::removeDestination
     *
     * @param correlationId of the add/remove command returned by Publication::addDestination
     * or Publication::removeDestination
     * @return true for added or false if not.
     */
    bool findDestinationResponse(std::int64_t correlationId);

    /// @cond HIDDEN_SYMBOLS
    inline void close()
    {
        std::atomic_store_explicit(&m_isClosed, true, std::memory_order_release);
    }
    /// @endcond

private:
    ClientConductor &m_conductor;
    AtomicBuffer &m_logMetaDataBuffer;
    const std::string m_channel;
    std::int64_t m_registrationId;
    std::int64_t m_originalRegistrationId;
    std::int64_t m_maxPossiblePosition;
    std::int32_t m_streamId;
    std::int32_t m_sessionId;
    std::int32_t m_initialTermId;
    std::int32_t m_maxPayloadLength;
    std::int32_t m_maxMessageLength;
    std::int32_t m_positionBitsToShift;
    ReadablePosition<UnsafeBufferPosition> m_publicationLimit;
    std::int32_t m_channelStatusId;
    std::atomic<bool> m_isClosed = { false };

    std::shared_ptr<LogBuffers> m_logBuffers;
    std::unique_ptr<TermAppender> m_appenders[3];
    HeaderWriter m_headerWriter;

    inline std::int64_t newPosition(
        std::int32_t termCount,
        std::int32_t termOffset,
        std::int32_t termId,
        std::int64_t position,
        std::int32_t resultingOffset)
    {
        if (resultingOffset > 0)
        {
            return (position - termOffset) + resultingOffset;
        }

        if ((position + termOffset) > m_maxPossiblePosition)
        {
            return MAX_POSITION_EXCEEDED;
        }

        LogBufferDescriptor::rotateLog(m_logMetaDataBuffer, termCount, termId);

        return ADMIN_ACTION;
    }

    inline std::int64_t backPressureStatus(std::int64_t currentPosition, std::int32_t messageLength)
    {
        if ((currentPosition + messageLength) >= m_maxPossiblePosition)
        {
            return MAX_POSITION_EXCEEDED;
        }

        if (LogBufferDescriptor::isConnected(m_logMetaDataBuffer))
        {
            return BACK_PRESSURED;
        }

        return NOT_CONNECTED;
    }

    inline void checkMaxMessageLength(const util::index_t length) const
    {
        if (length > m_maxMessageLength)
        {
            throw util::IllegalArgumentException(
                "encoded message exceeds maxMessageLength of " + std::to_string(m_maxMessageLength) +
                ", length=" + std::to_string(length), SOURCEINFO);
        }
    }

    inline void checkPayloadLength(const util::index_t length) const
    {
        if (AERON_COND_EXPECT((length > m_maxPayloadLength), false))
        {
            throw util::IllegalArgumentException(
                "encoded message exceeds maxPayloadLength of " + std::to_string(m_maxPayloadLength) +
                ", length=" + std::to_string(length), SOURCEINFO);
        }
    }
};

}

#endif


text:
namespace UnrealBuildTool.Rules
{
	public class SimpleHMD : ModuleRules
	{
		public SimpleHMD(TargetInfo Target)
		{
			PrivateIncludePaths.AddRange(
				new string[] {
					"SimpleHMD/Private",
					"../../../../Source/Runtime/Renderer/Private",
					// ... add other private include paths required here ...
				}
				);

			PrivateDependencyModuleNames.AddRange(
				new string[]
				{
					"Core",
					"CoreUObject",
					"Engine",
					"InputCore",
					"RHI",
					"RenderCore",
					"Renderer",
					"ShaderCore",
					"HeadMountedDisplay"
				}
				);
		}
	}
}


text:
namespace base {

namespace {

MessageLoop::MessagePumpFactory* message_pump_for_ui_factory_ = nullptr;

std::unique_ptr<MessagePump> ReturnPump(std::unique_ptr<MessagePump> pump) {
  return pump;
}

}  // namespace

class MessageLoop::Controller : public SequencedTaskSource::Observer {
 public:
  // Constructs a MessageLoopController which controls |message_loop|, notifying
  // |task_annotator_| when tasks are queued scheduling work on |message_loop|
  // as fits. |message_loop| and |task_annotator_| will not be used after
  // DisconnectFromParent() returns.
  Controller(MessageLoop* message_loop);

  ~Controller() override;

  // SequencedTaskSource::Observer:
  void WillQueueTask(PendingTask* task) final;
  void DidQueueTask(bool was_empty) final;

  void StartScheduling();

  // Disconnects |message_loop_| from this Controller instance (DidQueueTask()
  // will no-op from this point forward).
  void DisconnectFromParent();

  // Shares this Controller's TaskAnnotator with MessageLoop as TaskAnnotator
  // requires DidQueueTask(x)/RunTask(x) to be invoked on the same TaskAnnotator
  // instance.
  debug::TaskAnnotator& task_annotator() { return task_annotator_; }

 private:
  // A TaskAnnotator which is owned by this Controller to be able to use it
  // without locking |message_loop_lock_|. It cannot be owned by MessageLoop
  // because this Controller cannot access |message_loop_| safely without the
  // lock. Note: the TaskAnnotator API itself is thread-safe.
  debug::TaskAnnotator task_annotator_;

  // Lock that serializes |message_loop_->ScheduleWork()| and access to all
  // members below.
  base::Lock message_loop_lock_;

  // Points to this Controller's outer MessageLoop instance. Null after
  // DisconnectFromParent().
  MessageLoop* message_loop_;

  // False until StartScheduling() is called.
  bool is_ready_for_scheduling_ = false;

  // True if DidQueueTask() has been called before StartScheduling(); letting it
  // know whether it needs to ScheduleWork() right away or not.
  bool pending_schedule_work_ = false;

  DISALLOW_COPY_AND_ASSIGN(Controller);
};

MessageLoop::Controller::Controller(MessageLoop* message_loop)
    : message_loop_(message_loop) {}

MessageLoop::Controller::~Controller() {
  DCHECK(!message_loop_)
      << "DisconnectFromParent() needs to be invoked before destruction.";
}

void MessageLoop::Controller::WillQueueTask(PendingTask* task) {
  task_annotator_.WillQueueTask("MessageLoop::PostTask", task);
}

void MessageLoop::Controller::DidQueueTask(bool was_empty) {
  // Avoid locking if we don't need to schedule.
  if (!was_empty)
    return;

  AutoLock auto_lock(message_loop_lock_);

  if (message_loop_ && is_ready_for_scheduling_)
    message_loop_->ScheduleWork();
  else
    pending_schedule_work_ = true;
}

void MessageLoop::Controller::StartScheduling() {
  AutoLock lock(message_loop_lock_);
  DCHECK(message_loop_);
  DCHECK(!is_ready_for_scheduling_);
  is_ready_for_scheduling_ = true;
  if (pending_schedule_work_)
    message_loop_->ScheduleWork();
}

void MessageLoop::Controller::DisconnectFromParent() {
  AutoLock lock(message_loop_lock_);
  message_loop_ = nullptr;
}

//------------------------------------------------------------------------------

MessageLoop::MessageLoop(Type type)
    : MessageLoop(type, MessagePumpFactoryCallback()) {
  BindToCurrentThread();
}

MessageLoop::MessageLoop(std::unique_ptr<MessagePump> pump)
    : MessageLoop(TYPE_CUSTOM, BindOnce(&ReturnPump, std::move(pump))) {
  BindToCurrentThread();
}

MessageLoop::~MessageLoop() {
  // If |pump_| is non-null, this message loop has been bound and should be the
  // current one on this thread. Otherwise, this loop is being destructed before
  // it was bound to a thread, so a different message loop (or no loop at all)
  // may be current.
  DCHECK((pump_ && MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)) ||
         (!pump_ && !MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)));

  // iOS just attaches to the loop, it doesn't Run it.
  // TODO(stuartmorgan): Consider wiring up a Detach().
#if !defined(OS_IOS)
  // There should be no active RunLoops on this thread, unless this MessageLoop
  // isn't bound to the current thread (see other condition at the top of this
  // method).
  DCHECK(
      (!pump_ && !MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)) ||
      !RunLoop::IsRunningOnCurrentThread());
#endif  // !defined(OS_IOS)

#if defined(OS_WIN)
  if (in_high_res_mode_)
    Time::ActivateHighResolutionTimer(false);
#endif
  // Clean up any unprocessed tasks, but take care: deleting a task could
  // result in the addition of more tasks (e.g., via DeleteSoon).  We set a
  // limit on the number of times we will allow a deleted task to generate more
  // tasks.  Normally, we should only pass through this loop once or twice.  If
  // we end up hitting the loop limit, then it is probably due to one task that
  // is being stubborn.  Inspect the queues to see who is left.
  bool tasks_remain;
  for (int i = 0; i < 100; ++i) {
    DeletePendingTasks();
    // If we end up with empty queues, then break out of the loop.
    tasks_remain = sequenced_task_source_->HasTasks();
    if (!tasks_remain)
      break;
  }
  DCHECK(!tasks_remain);

  // Let interested parties have one last shot at accessing this.
  for (auto& observer : destruction_observers_)
    observer.WillDestroyCurrentMessageLoop();

  thread_task_runner_handle_.reset();

  // Detach this instance's Controller from |this|. After this point,
  // |underlying_task_runner_| may still receive tasks and notify the controller
  // but the controller will no-op (and not use this MessageLoop after free).
  // |underlying_task_runner_| being ref-counted and potentially kept alive by
  // many SingleThreadTaskRunner refs, the best we can do is tell it to shutdown
  // after which it will start returning false to PostTasks that happen-after
  // this point (note that invoking Shutdown() first would not remove the need
  // to DisconnectFromParent() since the controller is invoked *after* a task is
  // enqueued and the incoming queue's lock is released (see
  // MessageLoopTaskRunner::AddToIncomingQueue()).
  // Details : while an "in-progress post tasks" refcount in Controller in lieu
  // of |message_loop_lock_| would be an option to handle the "pending post
  // tasks on shutdown" case, |message_loop_lock_| would still be required to
  // serialize ScheduleWork() call and as such that optimization isn't worth it.
  message_loop_controller_->DisconnectFromParent();
  underlying_task_runner_->Shutdown();

  // OK, now make it so that no one can find us.
  if (MessageLoopCurrent::IsBoundToCurrentThreadInternal(this))
    MessageLoopCurrent::UnbindFromCurrentThreadInternal(this);
}

// static
MessageLoopCurrent MessageLoop::current() {
  return MessageLoopCurrent::Get();
}

// static
bool MessageLoop::InitMessagePumpForUIFactory(MessagePumpFactory* factory) {
  if (message_pump_for_ui_factory_)
    return false;

  message_pump_for_ui_factory_ = factory;
  return true;
}

// static
std::unique_ptr<MessagePump> MessageLoop::CreateMessagePumpForType(Type type) {
  if (type == MessageLoop::TYPE_UI) {
    if (message_pump_for_ui_factory_)
      return message_pump_for_ui_factory_();
#if defined(OS_IOS) || defined(OS_MACOSX)
    return MessagePumpMac::Create();
#elif defined(OS_NACL) || defined(OS_AIX)
    // Currently NaCl and AIX don't have a UI MessageLoop.
    // TODO(abarth): Figure out if we need this.
    NOTREACHED();
    return nullptr;
#else
    return std::make_unique<MessagePumpForUI>();
#endif
  }

  if (type == MessageLoop::TYPE_IO)
    return std::unique_ptr<MessagePump>(new MessagePumpForIO());

#if defined(OS_ANDROID)
  if (type == MessageLoop::TYPE_JAVA)
    return std::unique_ptr<MessagePump>(new MessagePumpForUI());
#endif

  DCHECK_EQ(MessageLoop::TYPE_DEFAULT, type);
#if defined(OS_IOS)
  // On iOS, a native runloop is always required to pump system work.
  return std::make_unique<MessagePumpCFRunLoop>();
#else
  return std::make_unique<MessagePumpDefault>();
#endif
}

bool MessageLoop::IsType(Type type) const {
  return type_ == type;
}

// TODO(gab): Migrate TaskObservers to RunLoop as part of separating concerns
// between MessageLoop and RunLoop and making MessageLoop a swappable
// implementation detail. http://crbug.com/703346
void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
  task_observers_.push_back(task_observer);
}

void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
  auto it =
      std::find(task_observers_.begin(), task_observers_.end(), task_observer);
  DCHECK(it != task_observers_.end());
  task_observers_.erase(it);
}

void MessageLoop::SetAddQueueTimeToTasks(bool enable) {
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
  underlying_task_runner_->SetAddQueueTimeToTasks(enable);
}

bool MessageLoop::IsIdleForTesting() {
  // Have unprocessed tasks? (this reloads the work queue if necessary)
  if (sequenced_task_source_->HasTasks())
    return false;

  // Have unprocessed deferred tasks which can be processed at this run-level?
  if (pending_task_queue_.deferred_tasks().HasTasks() &&
      !RunLoop::IsNestedOnCurrentThread()) {
    return false;
  }

  return true;
}

//------------------------------------------------------------------------------

// static
std::unique_ptr<MessageLoop> MessageLoop::CreateUnbound(
    Type type,
    MessagePumpFactoryCallback pump_factory) {
  return WrapUnique(new MessageLoop(type, std::move(pump_factory)));
}

MessageLoop::MessageLoop(Type type, MessagePumpFactoryCallback pump_factory)
    : MessageLoopCurrent(this),
      type_(type),
      pump_factory_(std::move(pump_factory)),
      message_loop_controller_(
          new Controller(this)),  // Ownership transferred on the next line.
      underlying_task_runner_(MakeRefCounted<internal::MessageLoopTaskRunner>(
          WrapUnique(message_loop_controller_))),
      sequenced_task_source_(underlying_task_runner_.get()),
      task_runner_(underlying_task_runner_) {
  // If type is TYPE_CUSTOM non-null pump_factory must be given.
  DCHECK(type_ != TYPE_CUSTOM || !pump_factory_.is_null());

  // Bound in BindToCurrentThread();
  DETACH_FROM_THREAD(bound_thread_checker_);
}

void MessageLoop::BindToCurrentThread() {
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);

  DCHECK(!pump_);
  if (!pump_factory_.is_null())
    pump_ = std::move(pump_factory_).Run();
  else
    pump_ = CreateMessagePumpForType(type_);

  DCHECK(!MessageLoopCurrent::IsSet())
      << "should only have one message loop per thread";
  MessageLoopCurrent::BindToCurrentThreadInternal(this);

  underlying_task_runner_->BindToCurrentThread();
  message_loop_controller_->StartScheduling();
  SetThreadTaskRunnerHandle();
  thread_id_ = PlatformThread::CurrentId();

  scoped_set_sequence_local_storage_map_for_current_thread_ = std::make_unique<
      internal::ScopedSetSequenceLocalStorageMapForCurrentThread>(
      &sequence_local_storage_map_);

  RunLoop::RegisterDelegateForCurrentThread(this);

#if defined(OS_ANDROID)
  // On Android, attach to the native loop when there is one.
  if (type_ == TYPE_UI || type_ == TYPE_JAVA)
    static_cast<MessagePumpForUI*>(pump_.get())->Attach(this);
#endif
}

std::string MessageLoop::GetThreadName() const {
  DCHECK_NE(kInvalidThreadId, thread_id_)
      << "GetThreadName() must only be called after BindToCurrentThread()'s "
      << "side-effects have been synchronized with this thread.";
  return ThreadIdNameManager::GetInstance()->GetName(thread_id_);
}

void MessageLoop::SetTaskRunner(
    scoped_refptr<SingleThreadTaskRunner> task_runner) {
  DCHECK(task_runner);
  if (thread_id_ == kInvalidThreadId) {
    // ThreadTaskRunnerHandle will be set during BindToCurrentThread().
    task_runner_ = std::move(task_runner);
  } else {
    // Once MessageLoop is bound, |task_runner_| may only be altered on the
    // bound thread.
    DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
    DCHECK(task_runner->BelongsToCurrentThread());
    task_runner_ = std::move(task_runner);
    SetThreadTaskRunnerHandle();
  }
}

void MessageLoop::Run(bool application_tasks_allowed) {
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
  if (application_tasks_allowed && !task_execution_allowed_) {
    // Allow nested task execution as explicitly requested.
    DCHECK(RunLoop::IsNestedOnCurrentThread());
    task_execution_allowed_ = true;
    pump_->Run(this);
    task_execution_allowed_ = false;
  } else {
    pump_->Run(this);
  }
}

void MessageLoop::Quit() {
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
  pump_->Quit();
}

#if defined(STARBOARD)
void MessageLoop::RunUntilIdleForTesting() {
  base::RunLoop run_loop;
  run_loop.RunUntilIdle();
}
#endif

void MessageLoop::EnsureWorkScheduled() {
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
  if (sequenced_task_source_->HasTasks())
    pump_->ScheduleWork();
}

void MessageLoop::SetThreadTaskRunnerHandle() {
  TRACK_MEMORY_SCOPE("MessageLoop");
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
  // Clear the previous thread task runner first, because only one can exist at
  // a time.
  thread_task_runner_handle_.reset();
  thread_task_runner_handle_.reset(new ThreadTaskRunnerHandle(task_runner_));
}

bool MessageLoop::ProcessNextDelayedNonNestableTask() {
  if (RunLoop::IsNestedOnCurrentThread())
    return false;

  while (pending_task_queue_.deferred_tasks().HasTasks()) {
    PendingTask pending_task = pending_task_queue_.deferred_tasks().Pop();
    if (!pending_task.task.IsCancelled()) {
      RunTask(&pending_task);
      return true;
    }
  }

  return false;
}

void MessageLoop::RunTask(PendingTask* pending_task) {
  DCHECK(task_execution_allowed_);

  // Execute the task and assume the worst: It is probably not reentrant.
  task_execution_allowed_ = false;

  TRACE_TASK_EXECUTION("MessageLoop::RunTask", *pending_task);

  for (TaskObserver* task_observer : task_observers_)
    task_observer->WillProcessTask(*pending_task);
  message_loop_controller_->task_annotator().RunTask("MessageLoop::PostTask",
                                                     pending_task);
  for (TaskObserver* task_observer : task_observers_)
    task_observer->DidProcessTask(*pending_task);

  task_execution_allowed_ = true;
}

bool MessageLoop::DeferOrRunPendingTask(PendingTask pending_task) {
  if (pending_task.nestable == Nestable::kNestable ||
      !RunLoop::IsNestedOnCurrentThread()) {
    RunTask(&pending_task);
    // Show that we ran a task (Note: a new one might arrive as a
    // consequence!).
    return true;
  }

  // We couldn't run the task now because we're in a nested run loop
  // and the task isn't nestable.
  pending_task_queue_.deferred_tasks().Push(std::move(pending_task));
  return false;
}

void MessageLoop::DeletePendingTasks() {
  // Delete all currently pending tasks but not tasks potentially posted from
  // their destructors. See ~MessageLoop() for the full logic mitigating against
  // infite loops when clearing pending tasks. The ScopedClosureRunner below
  // will be bound to a task posted at the end of the queue. After it is posted,
  // tasks will be deleted one by one, when the bound ScopedClosureRunner is
  // deleted and sets |deleted_all_originally_pending|, we know we've deleted
  // all originally pending tasks.
  bool deleted_all_originally_pending = false;
  ScopedClosureRunner capture_deleted_all_originally_pending(BindOnce(
      [](bool* deleted_all_originally_pending) {
        *deleted_all_originally_pending = true;
      },
      Unretained(&deleted_all_originally_pending)));
  sequenced_task_source_->InjectTask(
      BindOnce([](ScopedClosureRunner) {},
               std::move(capture_deleted_all_originally_pending)));

  while (!deleted_all_originally_pending) {
    PendingTask pending_task = sequenced_task_source_->TakeTask();

    // New delayed tasks should be deleted after older ones.
    if (!pending_task.delayed_run_time.is_null())
      pending_task_queue_.delayed_tasks().Push(std::move(pending_task));
  }

  pending_task_queue_.deferred_tasks().Clear();
  // TODO(robliao): Determine if we can move delayed task destruction before
  // deferred tasks to maintain the MessagePump DoWork, DoDelayedWork, and
  // DoIdleWork processing order.
  pending_task_queue_.delayed_tasks().Clear();
}

void MessageLoop::ScheduleWork() {
  pump_->ScheduleWork();
}

TimeTicks MessageLoop::CapAtOneDay(TimeTicks next_run_time) {
  return std::min(next_run_time, recent_time_ + TimeDelta::FromDays(1));
}

bool MessageLoop::DoWork() {
  if (!task_execution_allowed_)
    return false;

  // Execute oldest task.
  while (sequenced_task_source_->HasTasks()) {
    PendingTask pending_task = sequenced_task_source_->TakeTask();
    if (pending_task.task.IsCancelled())
      continue;

    if (!pending_task.delayed_run_time.is_null()) {
      int sequence_num = pending_task.sequence_num;
      TimeTicks delayed_run_time = pending_task.delayed_run_time;
      pending_task_queue_.delayed_tasks().Push(std::move(pending_task));
      // If we changed the topmost task, then it is time to reschedule.
      if (pending_task_queue_.delayed_tasks().Peek().sequence_num ==
          sequence_num) {
        pump_->ScheduleDelayedWork(delayed_run_time);
      }
    } else if (DeferOrRunPendingTask(std::move(pending_task))) {
      return true;
    }
  }

  // Nothing happened.
  return false;
}

bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
  TRACK_MEMORY_SCOPE("MessageLoop");
  if (!task_execution_allowed_ ||
      !pending_task_queue_.delayed_tasks().HasTasks()) {
    *next_delayed_work_time = TimeTicks();
    return false;
  }

  // When we "fall behind", there will be a lot of tasks in the delayed work
  // queue that are ready to run.  To increase efficiency when we fall behind,
  // we will only call Time::Now() intermittently, and then process all tasks
  // that are ready to run before calling it again.  As a result, the more we
  // fall behind (and have a lot of ready-to-run delayed tasks), the more
  // efficient we'll be at handling the tasks.

  TimeTicks next_run_time =
      pending_task_queue_.delayed_tasks().Peek().delayed_run_time;

  if (next_run_time > recent_time_) {
    recent_time_ = TimeTicks::Now();  // Get a better view of Now();
    if (next_run_time > recent_time_) {
      *next_delayed_work_time = CapAtOneDay(next_run_time);
      return false;
    }
  }

  PendingTask pending_task = pending_task_queue_.delayed_tasks().Pop();

  if (pending_task_queue_.delayed_tasks().HasTasks()) {
    *next_delayed_work_time = CapAtOneDay(
        pending_task_queue_.delayed_tasks().Peek().delayed_run_time);
  }

  return DeferOrRunPendingTask(std::move(pending_task));
}

bool MessageLoop::DoIdleWork() {
  if (ProcessNextDelayedNonNestableTask())
    return true;

#if defined(OS_WIN)
  bool need_high_res_timers = false;
#endif

  // Do not report idle metrics if about to quit the loop and/or in a nested
  // loop where |!task_execution_allowed_|. In the former case, the loop isn't
  // going to sleep and in the latter case DoDelayedWork() will not actually do
  // the work this is prepping for.
  if (ShouldQuitWhenIdle()) {
    pump_->Quit();
  } else if (task_execution_allowed_) {
    // Only track idle metrics in MessageLoopForUI to avoid too much contention
    // logging the histogram (https://crbug.com/860801) -- there's typically
    // only one UI thread per process and, for practical purposes, restricting
    // the MessageLoop diagnostic metrics to it yields similar information.
    if (type_ == TYPE_UI)
      pending_task_queue_.ReportMetricsOnIdle();

#if defined(OS_WIN)
    // On Windows we activate the high resolution timer so that the wait
    // _if_ triggered by the timer happens with good resolution. If we don't
    // do this the default resolution is 15ms which might not be acceptable
    // for some tasks.
    need_high_res_timers = pending_task_queue_.HasPendingHighResolutionTasks();
#endif
  }

#if defined(OS_WIN)
  if (in_high_res_mode_ != need_high_res_timers) {
    in_high_res_mode_ = need_high_res_timers;
    Time::ActivateHighResolutionTimer(in_high_res_mode_);
  }
#endif

  // When we return we will do a kernel wait for more tasks.
  return false;
}

#if !defined(OS_NACL)

//------------------------------------------------------------------------------
// MessageLoopForUI

MessageLoopForUI::MessageLoopForUI(Type type) : MessageLoop(type) {
#if defined(OS_ANDROID)
  DCHECK(type == TYPE_UI || type == TYPE_JAVA);
#else
  DCHECK_EQ(type, TYPE_UI);
#endif
}

// static
MessageLoopCurrentForUI MessageLoopForUI::current() {
  return MessageLoopCurrentForUI::Get();
}

// static
bool MessageLoopForUI::IsCurrent() {
  return MessageLoopCurrentForUI::IsSet();
}

#if defined(STARBOARD)
void MessageLoopForUI::Start() {
  // No Histogram support for UI message loop as it is managed by Starboard.
  static_cast<base::MessagePumpUIStarboard*>(pump_.get())->Start(this);
}
#endif

#if defined(OS_IOS)
void MessageLoopForUI::Attach() {
  static_cast<MessagePumpUIApplication*>(pump_.get())->Attach(this);
}
#endif  // defined(OS_IOS)

#if defined(OS_ANDROID)
void MessageLoopForUI::Abort() {
  static_cast<MessagePumpForUI*>(pump_.get())->Abort();
}

bool MessageLoopForUI::IsAborted() {
  return static_cast<MessagePumpForUI*>(pump_.get())->IsAborted();
}

void MessageLoopForUI::QuitWhenIdle(base::OnceClosure callback) {
  static_cast<MessagePumpForUI*>(pump_.get())
      ->QuitWhenIdle(std::move(callback));
}
#endif  // defined(OS_ANDROID)

#if defined(OS_WIN)
void MessageLoopForUI::EnableWmQuit() {
  static_cast<MessagePumpForUI*>(pump_.get())->EnableWmQuit();
}
#endif  // defined(OS_WIN)

#endif  // !defined(OS_NACL)

//------------------------------------------------------------------------------
// MessageLoopForIO

// static
MessageLoopCurrentForIO MessageLoopForIO::current() {
  return MessageLoopCurrentForIO::Get();
}

// static
bool MessageLoopForIO::IsCurrent() {
  return MessageLoopCurrentForIO::IsSet();
}

}  // namespace base


text:
<TITLE>Review for Saving Private Ryan (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Saving Private Ryan (1998)

reviewed by
Alex Fung

SAVING PRIVATE RYAN (DreamWorks - 1998)
Starring Tom Hanks, Edward Burns, Tom Sizemore, Jeremy Davies,
  Vin Diesel, Adam Goldberg, Barry Pepper, Giovanni Ribisi,
  Matt Damon
Screenplay by Robert Rodat
Produced by Steven Spielberg, Ian Bryce, Mark Gordon, Gary Levinsohn
Directed by Steven Spielberg
Running time: 169 minutes

                  ***1/2 (out of four stars)
                     Alternate Rating: A-

Note: Some may consider portions of the following text to be spoilers.
      Be forewarned.

    -------------------------------------------------------------

   A sight which never fails to affect me is the annual commemoratory
   gatherings of WWII veterans at war monuments.  It's been over fifty
   years since the curtain fell on the last Great War, and the young men
   who then risked life and limb to fight for their country are now
   aging seniors.  As their numbers dwindle with time and the ceremonies
   now barely rate a five-second blurb with the youth-obsessed media, I
   can't help but be terribly moved to witness these elderly men, in
   full uniform and decorated with ribbons and medals, ignoring the
   protests of their weary bodies as they march with fierce pride and
   solemnly salute their fallen comrades.  I'm overwhelmed with a sense
   of gratitude for the sacrifices and horrors to which these men have
   subjected themselves for the greater good, and saddened by the
   disinterest of the press and the public alike as indicated by the
   sparse attendance of the proceedings.  Shamefully, we have forgotten.
   Steven Spielberg's film, SAVING PRIVATE RYAN, attempts to address
   this situation by honouring these valiant soldiers.

   A noble goal, to be sure, but good intentions don't necessarily
   translate into a good film; it's dangerous to fall into the trap of
   judging a film based upon the worthiness of its subject matter.  At
   its best, SAVING PRIVATE RYAN is a staggering achievement of
   verisimilitude, recreating the stark terror of the battlefield as
   perhaps no film has ever done before.  Narratively symmetric, it
   opens with a washed-out shot of the stars and stripes fluttering in
   the wind, a present-day war cemetery sequence, and a spectacular
   half-hour battle scene, and closes with a reversal of the same
   elements, in effect coming full circle, although the picture's
   systematic emotional bombardment will undoubtedly result in the
   audience leaving the screening in a markedly different state of mind
   than that as they entered.

   The opening battle segment on the shores of Omaha Beach during the
   D-Day assault is particularly stunning, impressing at once the
   hellish atmosphere of mayhem and carnage, and perhaps most
   significantly, the notion of futility.  History informs us that we
   (referring to the Allied forces) won Omaha, and yet the film
   unblinkingly presents us to the chaos of our troops being mowed down
   in hails of bullets, shredded to pieces by explosives, blood and
   entrails splattering and spilling everywhere, with the cries and
   screams of the wounded and terrified only muted by detonations and
   the sound of ammunition tearing through flesh.  (Curiously enough,
   although SAVING PRIVATE RYAN barely straddled the line between an R
   and the dreaded NC-17 rating from the MPAA, in Ontario it's been
   designated with a relatively biteless rating of AA -- adult
   accompaniment required for under-14s, far weaker than the Rs
   inexplicably given for tame fare such as HIGH ART and HENRY FOOL.)
   Impeccably staged by Mr. Spielberg and captured with the stark,
   glamourless flavour of authentic combat footage by cinematographer
   Janusz Kaminski, the net effect is intensely assaulting and at once
   captures the immense suffering of the soldiers.

   The film wisely decides to forego introductions to the troops prior
   to the battle -- although we immediately latch upon the recognizable
   visage of our modern equivalent to the Jimmy Stewart-ish Everyman,
   Tom Hanks -- lending an unexpected sense of despair to the
   proceedings; not provided with the tools to be allowed to relate to
   the slaughtered onscreen victims as characters and heroes, we're
   forced to view them simply as men, and consequently the bitter
   sentiment of wasted lives is palpable.  Smartly, Mr. Spielberg never
   provides a malevolent close-up of the Axis snipers during the first
   half of this battle -- the Allieds are essentially being attacked by
   a faceless enemy -- and he refrains from indulging in emblematic
   jingoism, avoiding the blatant use of the hateful Nazi swastika until
   quite late in the game; from a larger, philosophical perspective,
   this was a just war, but strictly on the microscopic level of this
   battleground as inspected by this film, principles such as right and
   wrong, good and evil, and heroes and villains don't enter into the
   fray: both sides being humanized, these are men fighting just to stay
   alive.  When the Allied troops are able to topple the German
   stronghold, the mood isn't that of triumphant euphoria or jubilation,
   but of unadulterated relief.

   The Omaha segment is so impressively achieved that it almost seems
   curmudgeonly to point out how clunky the film's screenplay,
   particularly the dialogue, becomes during the middle segment as the
   plot unfolds before giving way to the extended closing battle
   sequence.  Assigned to locate and retrieve a Pvt. James Ryan in a
   goodwill mission, Cpt. John Miller (Mr. Hanks) and his men -- Sgt.
   Horvath (Tom Sizemore), Pvts. Reiben (Edward Burns), Jackson (Barry
   Pepper), Mellish (Adam Goldberg) and Caparzo (Vin Diesel), Medic Wade
   (Giovanni Ribisi), and later, a green translator, Cpl. Upham (Jeremy
   Davies) -- are sent behind enemy lines, and much moralizing and
   philosophizing is performed.  It's all well-intentioned but
   comparatively ineffective in terms of execution, rife with contrived,
   Oscar-ready outbursts of introspection, banter which neither sounds
   genuinely naturalistic nor adequately addresses the issues raised on
   any more than a surface level, and a propensity to lend unearned
   gravity to profundities which lean more towards hokiness than
   provocation.  There's also the problem of tone: the film clearly
   endeavours to capture the aura of a wartorn Europe as seen through
   the bleary eyes of our heroes, and yet two unnecessary comic bits are
   interjected which seem suited for sitcom-level storytelling; it's
   surprising that the film so willingly and needlessly undermines its
   achieved ambiance.  The film's middle stretch has interludes of
   dramatic interest and some thematic exploration, but it's hardly
   groundshattering material.

   SAVING PRIVATE RYAN's arduous middle section would probably be even
   more problematic if not for its direction.  I'm not convinced that
   Mr. Spielberg is The Great Filmmaker Of Our Time; he's indisputably
   made some Great Films (including JAWS, RAIDERS OF THE LOST ARK, and
   SCHINDLER'S LIST), but, as I recently remarked to a colleague, in a
   reality where Martin Scorsese still walks the Earth, designating Mr.
   Spielberg as America's finest filmmaker (as Time Magazine recently
   declared) is sheer folly.  Nonetheless, he's a director of not
   inconsequential strengths, chief of which is his ability to elicit an
   emotional reaction from his audience; Mr. Spielberg can easily lay
   claim to the title of Master of Emotional Manipulation.  It's a trait
   most conducive to exploitation for this film's subject matter.  I
   appreciated the simple but effective manner of layering several
   voice-overs reading different condolence telegrams as the camera
   panned across a busy room to convey the enormity and tragedy of the
   war, and particularly liked the use of silence accompanying a bit
   with a secretary wordlessly shuffling between three letters and then
   rushing off to draw the attention of her supervisor.  With nary a
   word, the onscreen implications are brutally clear; indeed, what
   words are suitable for such a grievous loss?  It's a much more subtle
   touch than a later monologue by Harve Presnell (performed well,
   incidentally) involving a stirring letter reading.

   For the most part, the film eschews subtlety for the use of emblems,
   both literal and figurative.  Not only does SAVING PRIVATE RYAN open
   and close with a colour-muted shot of the American flag, its vibrancy
   literally drained from it, but it epitomizes in wholesome Pvt. Ryan
   (Matt Damon) the spirit of America; it's no accident that he's from
   Iowa, dead center in the heartland of America, and that his family
   background is in that most American of professions, farming.  (When
   Pvt. Ryan's mother appears onscreen, she's even in the kitchen --
   kudos to the filmmakers for the restraint of not depicting her baking
   an apple pie.)  When Cpt. Miller addresses Pvt. Ryan, particularly at
   a pivotal moment late in the film, he's essentially speaking to the
   audience.  However, the audience surrogate in the picture is not that
   of Pvt. Ryan, but of Cpl. Upham, a nervous wreck thrown into battle
   for the first time.  Like him, we're seeing the horrors of the war
   through startled, inexperienced and idealistic eyes, and consequently
   we're simultaneously dismayed and empathetic at his limited
   effectiveness as a soldier.  Though it was an interesting touch to
   encapsulate the entire conflict into a single scenario -- a German
   soldier killing a Jew as an American soldier stands by helplessly --
   I was most impressed with the film's cynical lesson about the
   consequences of moral righteousness at wartime, an unexpected bit of
   grimness atypical for a film in Mr. Spielberg's oeuvre (although it's
   disappointingly tempered and dulled by a cathartic counterresponse
   which, while audience-pleasing, plays false).

   While SAVING PRIVATE RYAN is far from flawless, during its best
   stretches there are moments of sheer visceral bravura.  Its
   recreation of battles, with the sea literally awash with blood and
   soldiers being slain with horrifying ease, is a testament to the real
   brutality of war.  It's a price which our WWII veterans paid on our
   behalf, and it's something that we should not forget.

          - Alex Fung
          email: aw220@freenet.carleton.ca
          web  : http://www.ncf.carleton.ca/~aw220/

--
Alex Fung (aw220@freenet.carleton.ca) | http://www.ncf.carleton.ca/~aw220/
"...a first screenplay unaccompanied by a powerful agent or industry
 sponsor is generally a pathetic fetus of a film, nothing more."
                               - Andrew Sarris

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 com.oracle.truffle.llvm.parser.factories;

import java.util.Arrays;

import com.oracle.truffle.llvm.nodes.base.LLVMExpressionNode;
import com.oracle.truffle.llvm.nodes.base.LLVMNode;
import com.oracle.truffle.llvm.nodes.impl.base.LLVMTerminatorNode;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI16Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI32Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI64Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI8Node;
import com.oracle.truffle.llvm.nodes.impl.control.LLVMSwitchNode.LLVMI16ProfilingSwitchNode;
import com.oracle.truffle.llvm.nodes.impl.control.LLVMSwitchNode.LLVMI16SwitchNode;
import com.oracle.truffle.llvm.nodes.impl.control.LLVMSwitchNode.LLVMI32ProfilingSwitchNode;
import com.oracle.truffle.llvm.nodes.impl.control.LLVMSwitchNode.LLVMI32SwitchNode;
import com.oracle.truffle.llvm.nodes.impl.control.LLVMSwitchNode.LLVMI64ProfilingSwitchNode;
import com.oracle.truffle.llvm.nodes.impl.control.LLVMSwitchNode.LLVMI64SwitchNode;
import com.oracle.truffle.llvm.nodes.impl.control.LLVMSwitchNode.LLVMI8ProfilingSwitchNode;
import com.oracle.truffle.llvm.nodes.impl.control.LLVMSwitchNode.LLVMI8SwitchNode;
import com.oracle.truffle.llvm.parser.LLVMBaseType;
import com.oracle.truffle.llvm.runtime.options.LLVMBaseOptionFacade;

public class LLVMSwitchFactory {

    public static LLVMTerminatorNode createSwitch(LLVMExpressionNode cond, int defaultLabel, int[] otherLabels, LLVMExpressionNode[] cases,
                    LLVMBaseType llvmType, LLVMNode[] phiWriteNodes) {
        switch (llvmType) {
            case I8:
                LLVMI8Node[] i8Cases = Arrays.copyOf(cases, cases.length, LLVMI8Node[].class);
                if (LLVMBaseOptionFacade.injectBranchProbabilities()) {
                    return new LLVMI8ProfilingSwitchNode((LLVMI8Node) cond, i8Cases, otherLabels, defaultLabel, phiWriteNodes);
                } else {
                    return new LLVMI8SwitchNode((LLVMI8Node) cond, i8Cases, otherLabels, defaultLabel, phiWriteNodes);
                }
            case I16:
                LLVMI16Node[] i16Cases = Arrays.copyOf(cases, cases.length, LLVMI16Node[].class);
                if (LLVMBaseOptionFacade.injectBranchProbabilities()) {
                    return new LLVMI16ProfilingSwitchNode((LLVMI16Node) cond, i16Cases, otherLabels, defaultLabel, phiWriteNodes);
                } else {
                    return new LLVMI16SwitchNode((LLVMI16Node) cond, i16Cases, otherLabels, defaultLabel, phiWriteNodes);
                }
            case I32:
                LLVMI32Node[] i32Cases = Arrays.copyOf(cases, cases.length, LLVMI32Node[].class);
                if (LLVMBaseOptionFacade.injectBranchProbabilities()) {
                    return new LLVMI32ProfilingSwitchNode((LLVMI32Node) cond, i32Cases, otherLabels, defaultLabel, phiWriteNodes);
                } else {
                    return new LLVMI32SwitchNode((LLVMI32Node) cond, i32Cases, otherLabels, defaultLabel, phiWriteNodes);
                }
            case I64:
                LLVMI64Node[] i64Cases = Arrays.copyOf(cases, cases.length, LLVMI64Node[].class);
                if (LLVMBaseOptionFacade.injectBranchProbabilities()) {
                    return new LLVMI64ProfilingSwitchNode((LLVMI64Node) cond, i64Cases, otherLabels, defaultLabel, phiWriteNodes);
                } else {
                    return new LLVMI64SwitchNode((LLVMI64Node) cond, i64Cases, otherLabels, defaultLabel, phiWriteNodes);
                }
            default:
                throw new AssertionError(llvmType);
        }
    }

}


text:
var express = require('express');
var User = require('./api/user');
var config = require('./config');

var router = express.Router();

//用户
router.post('/user', User.regist);

router.post('/randVCode', User.randVerifyCode);

module.exports = router;


text:
#include <aws/directconnect/model/DescribeInterconnectsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::DirectConnect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DescribeInterconnectsRequest::DescribeInterconnectsRequest() :
    m_interconnectIdHasBeenSet(false)
{
}

Aws::String DescribeInterconnectsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_interconnectIdHasBeenSet)
  {
   payload.WithString("interconnectId", m_interconnectId);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DescribeInterconnectsRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "OvertureService.DescribeInterconnects"));
  return headers;

}


text:
<?php

namespace swap;

/**
 * [类型] 时间值
 */
class time_value extends value {

    public function is_valid() {
        return self::is_valid_time($this->value);
    }

    public static function is_valid_time($time) {
        return false;
    }
}


text:
"use strict";

var path = require("path");

var pattern = function(file) {
  return {
    pattern: file,
    included: true,
    served: true,
    watched: false
  };
};

var framework = function(files) {
  files.unshift(pattern(path.resolve(require.resolve("mocha-should"))));
};

framework.$inject = [ "config.files" ];

module.exports = {
  "framework:mochashould": [ "factory", framework ]
};


text:
import "reflect-metadata"
import {
    createTestingConnections,
    closeTestingConnections,
    reloadTestingDatabases,
} from "../../utils/test-utils"
import { DataSource } from "../../../src/data-source/DataSource"
import { expect } from "chai"
import { Dummy } from "./entity/dummy"
import { transformer, WrappedNumber } from "./transformer"

describe("github issues > #2557 object looses its prototype before transformer.to()", () => {
    let connections: DataSource[]
    before(
        async () =>
            (connections = await createTestingConnections({
                entities: [__dirname + "/entity/*{.js,.ts}"],
                schemaCreate: true,
                dropSchema: true,
            })),
    )
    beforeEach(() => reloadTestingDatabases(connections))
    after(() => closeTestingConnections(connections))

    it("should give correct object in transformer.to", () =>
        Promise.all(
            connections.map(async (connection) => {
                const dummy = new Dummy()
                dummy.id = 1
                dummy.num = new WrappedNumber(3)

                await connection.getRepository(Dummy).save(dummy)

                expect(transformer.lastValue).to.be.instanceOf(WrappedNumber)
            }),
        ))

    // you can add additional tests if needed
})


text:
<?php

namespace Drone\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class DroneUserBundle extends Bundle
{
	public function getParent()
    {
        return 'FOSUserBundle';
    }
}