text:
"""tests for rollout function."""

from absl.testing import absltest
from absl.testing import parameterized
import mujoco
import numpy as np
import concurrent.futures
import threading
from mujoco import rollout

#--------------------------- models used for testing ---------------------------

TEST_XML = r"""
<mujoco>
  <worldbody>
    <light pos="0 0 2"/>
    <geom type="plane" size="5 5 .1"/>
    <body pos="0 0 .1">
      <joint name="yaw" axis="0 0 1"/>
      <joint name="pitch" axis="0 1 0"/>
      <geom type="capsule" size=".02" fromto="0 0 0 1 0 0"/>
      <geom type="box" pos="1 0 0" size=".1 .1 .1"/>
      <site name="site" pos="1 0 0"/>
    </body>
  </worldbody>
  <actuator>
    <general joint="pitch" gainprm="100"/>
    <general joint="yaw" dyntype="filter" dynprm="1" gainprm="100"/>
  </actuator>
  <sensor>
    <accelerometer site="site"/>
  </sensor>
</mujoco>
"""

TEST_XML_NO_SENSORS = r"""
<mujoco>
  <worldbody>
    <light pos="0 0 2"/>
    <geom type="plane" size="5 5 .1"/>
    <body pos="0 0 .1">
      <joint name="yaw" axis="0 0 1"/>
      <joint name="pitch" axis="0 1 0"/>
      <geom type="capsule" size=".02" fromto="0 0 0 1 0 0"/>
      <geom type="box" pos="1 0 0" size=".1 .1 .1"/>
      <site name="site" pos="1 0 0"/>
    </body>
  </worldbody>
  <actuator>
    <general joint="pitch" gainprm="100"/>
    <general joint="yaw" dyntype="filter" dynprm="1" gainprm="100"/>
  </actuator>
</mujoco>
"""

TEST_XML_NO_ACTUATORS = r"""
<mujoco>
  <worldbody>
    <light pos="0 0 2"/>
    <geom type="plane" size="5 5 .1"/>
    <body pos="0 0 .1">
      <joint name="yaw" axis="0 0 1"/>
      <joint name="pitch" axis="0 1 0"/>
      <geom type="capsule" size=".02" fromto="0 0 0 1 0 0"/>
      <geom type="box" pos="1 0 0" size=".1 .1 .1"/>
      <site name="site" pos="1 0 0"/>
    </body>
  </worldbody>
  <sensor>
    <accelerometer site="site"/>
  </sensor>
</mujoco>
"""

TEST_XML_MOCAP = r"""
<mujoco>
  <worldbody>
    <body name="1" mocap="true">
    </body>
    <body name="2" mocap="true">
    </body>
  </worldbody>
  <sensor>
    <framepos objtype="xbody" objname="1"/>
    <framequat objtype="xbody" objname="2"/>
  </sensor>
</mujoco>
"""

TEST_XML_EMPTY = r"""
<mujoco>
</mujoco>
"""

ALL_MODELS = {'TEST_XML': TEST_XML,
              'TEST_XML_NO_SENSORS': TEST_XML_NO_SENSORS,
              'TEST_XML_NO_ACTUATORS': TEST_XML_NO_ACTUATORS,
              'TEST_XML_EMPTY': TEST_XML_EMPTY}

#------------------------------- tests -----------------------------------------

class MuJoCoRolloutTest(parameterized.TestCase):

  def setUp(self):
    super().setUp()
    np.random.seed(42)

  #----------------------------- test basic operation

  @parameterized.parameters(ALL_MODELS.keys())
  def test_single_step(self, model_name):
    model = mujoco.MjModel.from_xml_string(ALL_MODELS[model_name])
    data = mujoco.MjData(model)

    initial_state = np.random.randn(model.nq + model.nv + model.na)
    ctrl = np.random.randn(model.nu)
    state, sensordata = rollout.rollout(model, data, initial_state, ctrl)

    mujoco.mj_resetData(model, data)
    py_state, py_sensordata = step(model, data, initial_state, ctrl=ctrl)
    np.testing.assert_array_equal(state, py_state)
    np.testing.assert_array_equal(sensordata, py_sensordata)

  @parameterized.parameters(ALL_MODELS.keys())
  def test_single_rollout(self, model_name):
    nstep = 3  # number of timesteps

    model = mujoco.MjModel.from_xml_string(ALL_MODELS[model_name])
    data = mujoco.MjData(model)

    initial_state = np.random.randn(model.nq + model.nv + model.na)
    ctrl = np.random.randn(nstep, model.nu)
    state, sensordata = rollout.rollout(model, data, initial_state, ctrl)

    py_state, py_sensordata = single_rollout(model, data, initial_state,
                                             ctrl=ctrl)
    np.testing.assert_array_equal(state, np.asarray(py_state))
    np.testing.assert_array_equal(sensordata, np.asarray(py_sensordata))

  @parameterized.parameters(ALL_MODELS.keys())
  def test_multi_step(self, model_name):
    model = mujoco.MjModel.from_xml_string(ALL_MODELS[model_name])
    data = mujoco.MjData(model)

    nstate = 5  # number of initial states

    initial_state = np.random.randn(nstate, model.nq + model.nv + model.na)
    ctrl = np.random.randn(nstate, 1, model.nu)
    state, sensordata = rollout.rollout(model, data, initial_state, ctrl)

    mujoco.mj_resetData(model, data)
    py_state, py_sensordata = multi_rollout(model, data, initial_state,
                                            ctrl=ctrl)
    np.testing.assert_array_equal(state, py_state)
    np.testing.assert_array_equal(sensordata, py_sensordata)

  @parameterized.parameters(ALL_MODELS.keys())
  def test_single_rollout_fixed_ctrl(self, model_name):
    nstep = 3
    model = mujoco.MjModel.from_xml_string(ALL_MODELS[model_name])
    data = mujoco.MjData(model)

    initial_state = np.random.randn(model.nq + model.nv + model.na)
    ctrl = np.random.randn(model.nu)
    state = np.empty((nstep, model.nq + model.nv + model.na))
    sensordata = np.empty((nstep, model.nsensordata))
    rollout.rollout(model, data, initial_state, ctrl,
                    state=state, sensordata=sensordata)

    ctrl = np.tile(ctrl, (nstep, 1))  # repeat??
    py_state, py_sensordata = single_rollout(model, data, initial_state,
                                             ctrl=ctrl)
    np.testing.assert_array_equal(state, py_state)
    np.testing.assert_array_equal(sensordata, py_sensordata)

  @parameterized.parameters(ALL_MODELS.keys())
  def test_multi_rollout(self, model_name):
    model = mujoco.MjModel.from_xml_string(ALL_MODELS[model_name])
    data = mujoco.MjData(model)

    nstate = 2  # number of initial states
    nstep = 3  # number of timesteps

    initial_state = np.random.randn(nstate, model.nq + model.nv + model.na)
    ctrl = np.random.randn(nstate, nstep, model.nu)
    state, sensordata = rollout.rollout(model, data, initial_state, ctrl)

    py_state, py_sensordata = multi_rollout(model, data, initial_state,
                                            ctrl=ctrl)
    np.testing.assert_array_equal(py_state, py_state)
    np.testing.assert_array_equal(py_sensordata, py_sensordata)

  @parameterized.parameters(ALL_MODELS.keys())
  def test_multi_rollout_fixed_ctrl_infer_from_output(self, model_name):
    model = mujoco.MjModel.from_xml_string(ALL_MODELS[model_name])
    data = mujoco.MjData(model)

    nstate = 2  # number of initial states
    nstep = 3  # number of timesteps

    initial_state = np.random.randn(nstate, model.nq + model.nv + model.na)
    ctrl = np.random.randn(nstate, 1, model.nu)  # 1 control in the time dimension
    state = np.empty((nstate, nstep, model.nq + model.nv + model.na))
    state, sensordata = rollout.rollout(model, data, initial_state, ctrl,
                                        state=state)

    ctrl = np.repeat(ctrl, nstep, axis=1)
    py_state, py_sensordata = multi_rollout(model, data, initial_state,
                                            ctrl=ctrl)
    np.testing.assert_array_equal(state, py_state)
    np.testing.assert_array_equal(sensordata, py_sensordata)

  @parameterized.product(arg_nstep=[[3, 1, 1], [3, 3, 1], [3, 1, 3]],
                         model_name=list(ALL_MODELS.keys()))
  def test_multi_rollout_multiple_inputs(self, arg_nstep, model_name):
    model = mujoco.MjModel.from_xml_string(ALL_MODELS[model_name])
    data = mujoco.MjData(model)

    nstate = 4  # number of initial states

    initial_state = np.random.randn(nstate, model.nq + model.nv + model.na)

    # arg_nstep is the horizon for {ctrl, qfrc_applied, xfrc_applied}, respectively
    ctrl = np.random.randn(nstate, arg_nstep[0], model.nu)
    qfrc_applied = np.random.randn(nstate, arg_nstep[1], model.nv)
    xfrc_applied = np.random.randn(nstate, arg_nstep[2], model.nbody*6)

    state, sensordata = rollout.rollout(model, data, initial_state, ctrl,
                                        qfrc_applied=qfrc_applied,
                                        xfrc_applied=xfrc_applied)

    # tile singleton arguments
    nstep = max(arg_nstep)
    if arg_nstep[0] == 1:
      ctrl = np.repeat(ctrl, nstep, axis=1)
    if arg_nstep[1] == 1:
      qfrc_applied = np.repeat(qfrc_applied, nstep, axis=1)
    if arg_nstep[2] == 1:
      xfrc_applied = np.repeat(xfrc_applied, nstep, axis=1)

    py_state, py_sensordata = multi_rollout(model, data, initial_state,
                                            ctrl=ctrl,
                                            qfrc_applied=qfrc_applied,
                                            xfrc_applied=xfrc_applied)
    np.testing.assert_array_equal(state, py_state)
    np.testing.assert_array_equal(sensordata, py_sensordata)

  #----------------------------- test threaded operation

  def test_threading(self):
    model = mujoco.MjModel.from_xml_string(TEST_XML)
    num_workers = 32
    nstate = 10000
    nstep = 5
    initial_state = np.random.randn(nstate, model.nq+model.nv+model.na)
    state = np.zeros((nstate, nstep, model.nq+model.nv+model.na))
    sensordata = np.zeros((nstate, nstep, model.nsensordata))
    ctrl = np.random.randn(nstate, nstep, model.nu)

    thread_local = threading.local()

    def thread_initializer():
      thread_local.data = mujoco.MjData(model)

    def call_rollout(initial_state, ctrl, state):
      rollout.rollout(model, thread_local.data, skip_checks=True,
                      nstate=initial_state.shape[0], nstep=nstep,
                      initial_state=initial_state, ctrl=ctrl, state=state)

    n = initial_state.shape[0] // num_workers  # integer division
    chunks = []  # a list of tuples, one per worker
    for i in range(num_workers-1):
      chunks.append(
          (initial_state[i*n:(i+1)*n], ctrl[i*n:(i+1)*n], state[i*n:(i+1)*n]))
    # last chunk, absorbing the remainder:
    chunks.append(
        (initial_state[(num_workers-1)*n:], ctrl[(num_workers-1)*n:],
         state[(num_workers-1)*n:]))

    with concurrent.futures.ThreadPoolExecutor(
        max_workers=num_workers, initializer=thread_initializer) as executor:
      futures = []
      for chunk in chunks:
        futures.append(executor.submit(call_rollout, *chunk))
      for future in concurrent.futures.as_completed(futures):
        future.result()

    data = mujoco.MjData(model)
    py_state, py_sensordata = multi_rollout(model, data, initial_state,
                                            ctrl=ctrl)
    np.testing.assert_array_equal(state, py_state)

  #----------------------------- test advanced operation

  def test_time(self):
    model = mujoco.MjModel.from_xml_string(TEST_XML)
    data = mujoco.MjData(model)

    nstate = 1
    nstep = 3

    initial_time = np.array([[2.]])
    initial_state = np.random.randn(nstate, model.nq + model.nv + model.na)
    ctrl = np.random.randn(nstate, nstep, model.nu)
    state, sensordata = rollout.rollout(model, data, initial_state, ctrl,
                                        initial_time=initial_time)

    self.assertAlmostEqual(data.time, 2 + nstep*model.opt.timestep)

  def test_warmstart(self):
    model = mujoco.MjModel.from_xml_string(TEST_XML)
    data = mujoco.MjData(model)

    state0 = np.zeros(model.nq + model.nv + model.na)
    ctrl = np.zeros(model.nu)
    state1, _ = step(model, data, state0, ctrl=ctrl)
    initial_warmstart = data.qacc_warmstart.copy()

    state2, _ = step(model, data, state1, ctrl=ctrl)

    state, _ = rollout.rollout(model, data, state1, ctrl)
    assert np.linalg.norm(state-state2) > 0

    state, _ = rollout.rollout(model, data, state1, ctrl,
                               initial_warmstart=initial_warmstart)
    np.testing.assert_array_equal(state, state2)

  def test_mocap(self):
    model = mujoco.MjModel.from_xml_string(TEST_XML_MOCAP)
    data = mujoco.MjData(model)

    initial_state = np.zeros(model.nq + model.nv + model.na)
    pos1 = np.array((1., 2., 3.))
    quat1 = np.array((1., 2., 3., 4.))
    quat1 /= np.linalg.norm(quat1)
    pos2 = np.array((2., 3., 4.))
    quat2 = np.array((2., 3., 4., 5.))
    quat2 /= np.linalg.norm(quat2)
    mocap = np.hstack((pos1, quat1, pos2, quat2))

    state, sensordata = rollout.rollout(model, data, initial_state, mocap=mocap)

    np.testing.assert_array_almost_equal(sensordata[:3], pos1)
    np.testing.assert_array_almost_equal(sensordata[3:], quat2)

  #----------------------------- test correctness

  def test_intercept_mj_errors(self):
    model = mujoco.MjModel.from_xml_string(TEST_XML)
    data = mujoco.MjData(model)

    initial_state = np.zeros(model.nq + model.nv + model.na)
    ctrl = np.zeros((3, model.nu))

    model.opt.solver = 10  # invalid solver type
    with self.assertRaisesWithLiteralMatch(mujoco.FatalError,
                                           'Unknown solver type 10'):
      state, sensordata = rollout.rollout(model, data, initial_state, ctrl)

  def test_invalid(self):
    model = mujoco.MjModel.from_xml_string(TEST_XML)
    data = mujoco.MjData(model)

    initial_state = np.zeros(model.nq + model.nv + model.na)

    ctrl = 'string'
    with self.assertRaisesWithLiteralMatch(
        ValueError, 'ctrl must be a numpy array or float'):
      state, sensordata = rollout.rollout(model, data, initial_state, ctrl)

    qfrc_applied = np.zeros((2, 3, 4, 5))
    with self.assertRaisesWithLiteralMatch(
        ValueError, 'qfrc_applied can have at most 3 dimensions'):
      state, sensordata = rollout.rollout(model, data, initial_state,
                                          qfrc_applied=qfrc_applied)

  def test_bad_sizes(self):
    model = mujoco.MjModel.from_xml_string(TEST_XML)
    data = mujoco.MjData(model)

    initial_state = np.random.randn(model.nq + model.nv + model.na+1)
    with self.assertRaisesWithLiteralMatch(
        ValueError, 'trailing dimension of initial_state must be 5, got 6'):
      state, sensordata = rollout.rollout(model, data, initial_state)

    initial_state = np.random.randn(model.nq + model.nv + model.na)
    ctrl = np.random.randn(model.nu+1)
    with self.assertRaisesWithLiteralMatch(
        ValueError, 'trailing dimension of ctrl must be 2, got 3'):
      state, sensordata = rollout.rollout(model, data, initial_state, ctrl)

    ctrl = np.random.randn(2, model.nu)
    qfrc_applied = np.random.randn(3, model.nv)  # incompatible horizon
    with self.assertRaisesWithLiteralMatch(
        ValueError, 'dimension 1 inferred as 2 but qfrc_applied has 3'):
      state, sensordata = rollout.rollout(model, data, initial_state, ctrl,
                                          qfrc_applied=qfrc_applied)

  def test_stateless(self):
    model = mujoco.MjModel.from_xml_string(TEST_XML)
    model.opt.disableflags |= mujoco.mjtDisableBit.mjDSBL_WARMSTART.value
    data = mujoco.MjData(model)

    # call step with a clean mjData
    initial_state = np.random.randn(model.nq + model.nv + model.na)
    ctrl = np.random.randn(model.nu)
    state, sensordata = rollout.rollout(model, data, initial_state, ctrl)

    # fill mjData with some debug value, see that we still get the same outputs
    mujoco.mj_resetDataDebug(model, data, 255)
    debug_state, debug_sensordata = rollout.rollout(model, data, initial_state,
                                                    ctrl)

    np.testing.assert_array_equal(state, debug_state)
    np.testing.assert_array_equal(sensordata, debug_sensordata)

#--------------- Python implementation of rollout functionality ----------------

def get_state(data):
  return np.hstack((data.qpos, data.qvel, data.act))

def set_state(model, data, state):
  data.qpos = state[:model.nq]
  data.qvel = state[model.nq:model.nq+model.nv]
  data.act = state[model.nq+model.nv:model.nq+model.nv+model.na]

def step(model, data, state, **kwargs):
  if state is not None:
    set_state(model, data, state)
  for key, value in kwargs.items():
    if value is not None:
      setattr(data, key, np.reshape(value, getattr(data, key).shape))
  mujoco.mj_step(model, data)
  return (get_state(data), data.sensordata)

def single_rollout(model, data, initial_state, **kwargs):
  arg_nstep = set([a.shape[0] for a in kwargs.values()])
  assert len(arg_nstep) == 1  # nstep dimensions must match
  nstep = arg_nstep.pop()

  state = np.empty((nstep, model.nq + model.nv + model.na))
  sensordata = np.empty((nstep, model.nsensordata))

  mujoco.mj_resetData(model, data)
  for t in range(nstep):
    kwargs_t = {}
    for key, value in kwargs.items():
      kwargs_t[key] = value[0 if value.ndim == 1 else t]
    state[t], sensordata[t] = step(model, data,
                                   initial_state if t==0 else None,
                                   **kwargs_t)
  return state, sensordata

def multi_rollout(model, data, initial_state, **kwargs):
  nstate = initial_state.shape[0]
  arg_nstep = set([a.shape[1] for a in kwargs.values()])
  assert len(arg_nstep) == 1  # nstep dimensions must match
  nstep = arg_nstep.pop()

  state = np.empty((nstate, nstep, model.nq + model.nv + model.na))
  sensordata = np.empty((nstate, nstep, model.nsensordata))
  for s in range(nstate):
    kwargs_s = {key : value[s] for key, value in kwargs.items()}
    state_s, sensordata_s = single_rollout(model, data, initial_state[s],
                                           **kwargs_s)
    state[s] = state_s
    sensordata[s] = sensordata_s
  return state.squeeze(), sensordata.squeeze()

if __name__ == '__main__':
  absltest.main()


text:
.rect {
  max-width: 150px;
  max-height: 75px;
  padding-right: 10px;
  padding-left: 10px;
  margin: 0 auto;
}

.regBorder {
  border: 2px solid green;
}

.blinkBorder {
  border: 2px solid red;
}
.blinkBorder h3 {
  color: red;
}

/*@keyframes blink {
            25% {
                border: 2px solid red;
            }
        }*/
        /*.blinkBorder {
            animation-name: blink;
            animation-duration: .08s;
            animation-timing-function: step-end;
            animation-iteration-count: infinite;
            animation-direction: alternate;
        }*/

redpajama_set_name: RedPajamaGithub


text:
import path from 'path';

const directories = ['/foo', '/bar', 'baz/abc', 'qwerty', '..'];

const result = path.join(...directories);

console.log(result);


text:
package org.anttribe.zookeeper.console.web.utils;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class AuthUtils
{
    private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(AuthUtils.class);

    private static final String ZK_USER = "zk_user";

    private static final String USER_FILE_PATH = "conf/user.properties";

    public static boolean isLogin()
    {
        HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        Object obj = req.getSession().getAttribute(ZK_USER);
        if (obj != null)
        {
            return true;
        }
        return false;
    }

    public static boolean login(String userName, String password)
    {
        HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        userName = StringUtils.trimToNull(userName);
        password = StringUtils.trimToNull(password);
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password))
        {
            return false;
        }
        Properties properties = getUsers();
        String pwd = properties.getProperty(userName);
        if (StringUtils.equals(password, pwd))
        {
            req.getSession().setAttribute(ZK_USER, userName);
            return true;
        }
        return false;
    }

    public static boolean logout()
    {
        HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        req.getSession().removeAttribute(ZK_USER);
        return false;
    }

    private static Properties getUsers()
    {
        try
        {
            return PropertiesLoaderUtils.loadProperties(new ClassPathResource(USER_FILE_PATH));
        }
        catch (IOException e)
        {
            LOGGER.error("没有找到帐号配置文件.{}", e.getMessage(), e);
        }
        return null;
    }

}


text:
/*
  Red Black Trees
  (C) 1999  Andrea Arcangeli <andrea@suse.de>
  (C) 2002  David Woodhouse <dwmw2@infradead.org>
  (C) 2012  Michel Lespinasse <walken@google.com>
  (C) 2018  Bo Yu <boyu@freewheel.tv>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  linux/include/linux/rbtree_augmented.h
*/

#ifndef _LINUX_RBTREE_AUGMENTED_H
#define _LINUX_RBTREE_AUGMENTED_H

//#include <linux/compiler.h>
#include "compat.h"
#include "rbtree.h"
//#include <linux/rcupdate.h>

/*
 * Please note - only struct rb_augment_callbacks and the prototypes for
 * rb_insert_augmented() and rb_erase_augmented() are intended to be public.
 * The rest are implementation details you are not expected to depend on.
 *
 * See Documentation/rbtree.txt for documentation and samples.
 */

struct rb_augment_callbacks {
	void (*propagate)(struct rb_node *node, struct rb_node *stop);
	void (*copy)(struct rb_node *old, struct rb_node *new);
	void (*rotate)(struct rb_node *old, struct rb_node *new);
};

extern void __rb_insert_augmented(struct rb_node *node,
				  struct rb_root *root,
				  bool newleft, struct rb_node **leftmost,
	void (*augment_rotate)(struct rb_node *old, struct rb_node *new));
/*
 * Fixup the rbtree and update the augmented information when rebalancing.
 *
 * On insertion, the user must update the augmented information on the path
 * leading to the inserted node, then call rb_link_node() as usual and
 * rb_augment_inserted() instead of the usual rb_insert_color() call.
 * If rb_augment_inserted() rebalances the rbtree, it will callback into
 * a user provided function to update the augmented information on the
 * affected subtrees.
 */
static inline void
rb_insert_augmented(struct rb_node *node, struct rb_root *root,
		    const struct rb_augment_callbacks *augment)
{
	__rb_insert_augmented(node, root, false, NULL, augment->rotate);
}

static inline void
rb_insert_augmented_cached(struct rb_node *node,
			   struct rb_root_cached *root, bool newleft,
			   const struct rb_augment_callbacks *augment)
{
	__rb_insert_augmented(node, &root->rb_root,
			      newleft, &root->rb_leftmost, augment->rotate);
}

#define RB_DECLARE_CALLBACKS(rbstatic, rbname, rbstruct, rbfield,	\
			     rbtype, rbaugmented, rbcompute)		\
static inline void							\
rbname ## _propagate(struct rb_node *rb, struct rb_node *stop)		\
{									\
	while (rb != stop) {						\
		rbstruct *node = rb_entry(rb, rbstruct, rbfield);	\
		rbtype augmented = rbcompute(node);			\
		if (node->rbaugmented == augmented)			\
			break;						\
		node->rbaugmented = augmented;				\
		rb = rb_parent(&node->rbfield);				\
	}								\
}									\
static inline void							\
rbname ## _copy(struct rb_node *rb_old, struct rb_node *rb_new)		\
{									\
	rbstruct *old = rb_entry(rb_old, rbstruct, rbfield);		\
	rbstruct *new = rb_entry(rb_new, rbstruct, rbfield);		\
	new->rbaugmented = old->rbaugmented;				\
}									\
static void								\
rbname ## _rotate(struct rb_node *rb_old, struct rb_node *rb_new)	\
{									\
	rbstruct *old = rb_entry(rb_old, rbstruct, rbfield);		\
	rbstruct *new = rb_entry(rb_new, rbstruct, rbfield);		\
	new->rbaugmented = old->rbaugmented;				\
	old->rbaugmented = rbcompute(old);				\
}									\
rbstatic const struct rb_augment_callbacks rbname = {			\
	.propagate = rbname ## _propagate,				\
	.copy = rbname ## _copy,					\
	.rotate = rbname ## _rotate					\
};

#define	RB_RED		0
#define	RB_BLACK	1

#define __rb_parent(pc)    ((struct rb_node *)(pc & ~3))

#define __rb_color(pc)     ((pc) & 1)
#define __rb_is_black(pc)  __rb_color(pc)
#define __rb_is_red(pc)    (!__rb_color(pc))
#define rb_color(rb)       __rb_color((rb)->__rb_parent_color)
#define rb_is_red(rb)      __rb_is_red((rb)->__rb_parent_color)
#define rb_is_black(rb)    __rb_is_black((rb)->__rb_parent_color)

static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p)
{
	rb->__rb_parent_color = rb_color(rb) | (unsigned long)p;
}

static inline void rb_set_parent_color(struct rb_node *rb,
				       struct rb_node *p, int color)
{
	rb->__rb_parent_color = (unsigned long)p | color;
}

static inline void
__rb_change_child(struct rb_node *old, struct rb_node *new,
		  struct rb_node *parent, struct rb_root *root)
{
	if (parent) {
		if (parent->rb_left == old)
			WRITE_ONCE(parent->rb_left, new);
		else
			WRITE_ONCE(parent->rb_right, new);
	} else
		WRITE_ONCE(root->rb_node, new);
}

#if 0
static inline void
__rb_change_child_rcu(struct rb_node *old, struct rb_node *new,
		      struct rb_node *parent, struct rb_root *root)
{
	if (parent) {
		if (parent->rb_left == old)
			rcu_assign_pointer(parent->rb_left, new);
		else
			rcu_assign_pointer(parent->rb_right, new);
	} else
		rcu_assign_pointer(root->rb_node, new);
}
#endif

extern void __rb_erase_color(struct rb_node *parent, struct rb_root *root,
	void (*augment_rotate)(struct rb_node *old, struct rb_node *new));

static __always_inline struct rb_node *
__rb_erase_augmented(struct rb_node *node, struct rb_root *root,
		     struct rb_node **leftmost,
		     const struct rb_augment_callbacks *augment)
{
	struct rb_node *child = node->rb_right;
	struct rb_node *tmp = node->rb_left;
	struct rb_node *parent, *rebalance;
	unsigned long pc;

	if (leftmost && node == *leftmost)
		*leftmost = rb_next(node);

	if (!tmp) {
		/*
		 * Case 1: node to erase has no more than 1 child (easy!)
		 *
		 * Note that if there is one child it must be red due to 5)
		 * and node must be black due to 4). We adjust colors locally
		 * so as to bypass __rb_erase_color() later on.
		 */
		pc = node->__rb_parent_color;
		parent = __rb_parent(pc);
		__rb_change_child(node, child, parent, root);
		if (child) {
			child->__rb_parent_color = pc;
			rebalance = NULL;
		} else
			rebalance = __rb_is_black(pc) ? parent : NULL;
		tmp = parent;
	} else if (!child) {
		/* Still case 1, but this time the child is node->rb_left */
		tmp->__rb_parent_color = pc = node->__rb_parent_color;
		parent = __rb_parent(pc);
		__rb_change_child(node, tmp, parent, root);
		rebalance = NULL;
		tmp = parent;
	} else {
		struct rb_node *successor = child, *child2;

		tmp = child->rb_left;
		if (!tmp) {
			/*
			 * Case 2: node's successor is its right child
			 *
			 *    (n)          (s)
			 *    / \          / \
			 *  (x) (s)  ->  (x) (c)
			 *        \
			 *        (c)
			 */
			parent = successor;
			child2 = successor->rb_right;

			augment->copy(node, successor);
		} else {
			/*
			 * Case 3: node's successor is leftmost under
			 * node's right child subtree
			 *
			 *    (n)          (s)
			 *    / \          / \
			 *  (x) (y)  ->  (x) (y)
			 *      /            /
			 *    (p)          (p)
			 *    /            /
			 *  (s)          (c)
			 *    \
			 *    (c)
			 */
			do {
				parent = successor;
				successor = tmp;
				tmp = tmp->rb_left;
			} while (tmp);
			child2 = successor->rb_right;
			WRITE_ONCE(parent->rb_left, child2);
			WRITE_ONCE(successor->rb_right, child);
			rb_set_parent(child, successor);

			augment->copy(node, successor);
			augment->propagate(parent, successor);
		}

		tmp = node->rb_left;
		WRITE_ONCE(successor->rb_left, tmp);
		rb_set_parent(tmp, successor);

		pc = node->__rb_parent_color;
		tmp = __rb_parent(pc);
		__rb_change_child(node, successor, tmp, root);

		if (child2) {
			successor->__rb_parent_color = pc;
			rb_set_parent_color(child2, parent, RB_BLACK);
			rebalance = NULL;
		} else {
			unsigned long pc2 = successor->__rb_parent_color;
			successor->__rb_parent_color = pc;
			rebalance = __rb_is_black(pc2) ? parent : NULL;
		}
		tmp = successor;
	}

	augment->propagate(tmp, NULL);
	return rebalance;
}

static __always_inline void
rb_erase_augmented(struct rb_node *node, struct rb_root *root,
		   const struct rb_augment_callbacks *augment)
{
	struct rb_node *rebalance = __rb_erase_augmented(node, root,
							 NULL, augment);
	if (rebalance)
		__rb_erase_color(rebalance, root, augment->rotate);
}

static __always_inline void
rb_erase_augmented_cached(struct rb_node *node, struct rb_root_cached *root,
			  const struct rb_augment_callbacks *augment)
{
	struct rb_node *rebalance = __rb_erase_augmented(node, &root->rb_root,
							 &root->rb_leftmost,
							 augment);
	if (rebalance)
		__rb_erase_color(rebalance, &root->rb_root, augment->rotate);
}

#endif	/* _LINUX_RBTREE_AUGMENTED_H */


text:
var AuthService = require("../services/AuthService");

function AmbianceController(LightService,WemoService,SpotifyService, UsersCollection){
  lightService = LightService;
  wemoService = WemoService;
  spotifyService = SpotifyService;
  usersCollection = UsersCollection;
};

AmbianceController.prototype.BuildRouting = function(app,socket){
var self = this;

app.put('/ambiance/:id', function(req, res) {
  new AuthService(usersCollection).PromptForCredentials(req,res,function(){
      wemoService.getState(function(state){
          if(state == "off"){
              wemoService.turnOnWemo(function(result){
                self.turnOnLightsAndMusic(req,res);
             });
          }else{
              self.turnOnLightsAndMusic(req,res);
          }
      });

  });

});

}

AmbianceController.prototype.turnOnLightsAndMusic = function(req,res){
    spotifyService.startAirplay(function(){
      setTimeout(function(){
        spotifyService.startSpotify(req.body.songURI,function(){
              lightService.setGroupState(req.body.state,req.params.id,req.body.hue,req.body.bri,req.body.sat,req.body.effect,function(statusCode,result){
                res.send(result);
              });
          });
      },1000);
    });
}

module.exports = AmbianceController;


text:
//
//  UIImage+Usually.h
//  QQUIKit
//
//  Created by tlt on 17/3/15.
//  Copyright © 2017年 Yuan er. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIImage (Usually)
/**
 获取灰色的图片
 */
+ (UIImage*)grayImage:(UIImage*)sourceImage;

/**
 传入字符串获取二维码

 @param string 要处理的字符串

 @return 二维码
 */
+ (UIImage *)qrcodeImageWithString:(NSString *)string;

/**
 *  @brief  通过路径加载图片 图片一定不能在Assets中
 *
 *  @param imageName 图片名
 *
 *  @return UIImage实例
 */
+ (UIImage *)imageWithName:(NSString *)imageName;

//圆角切割
- (UIImage *)QQ_getCornerRadius:(CGFloat)cornerRadius;

/*
 返回100k以内大小的图片
 */
+(NSData *)imageData:(UIImage *)myimage;

/// 根据本地路径获取视频的第一帧
/// @param url 路径地址
+ (UIImage*)videoPreViewImage:(NSURL *)url;
@end

@interface UIImage (Luban_iOS_Extension_h)

+ (NSData *)lubanCompressImage:(UIImage *)image;
+ (NSData *)lubanCompressImage:(UIImage *)image withMask:(NSString *)maskName;
+ (NSData *)lubanCompressImage:(UIImage *)image withCustomImage:(NSString *)imageName;

@end


text:
<?php

namespace coverallskit\robo;

use coverallskit\CoverallsReportBuilder;

/**
 * Trait loadTasks
 * @package coverallskit\robo
 */
trait loadTasks
{

    protected function taskCoverallsKit()
    {
        $builder = new CoverallsReportBuilder();
        $action = new CoverallsReportAction($builder);

        return new CoverallsKitTask($action);
    }

}


text:
<?php
# MantisBT - A PHP based bugtracking system

# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT.  If not, see <http://www.gnu.org/licenses/>.

# set up error_handler() as the new default error handling function
set_error_handler( 'mc_error_handler' );

/**
 * Webservice APIs
 *
 * @uses api_token_api.php
 */

require_api( 'api_token_api.php' );

/**
 * A factory class that can abstract away operations that can behave differently based
 * on the underlying soap implementation.
 *
 * TODO: Consider removing this class since it currently has one implementation which
 * targets the php soap extension.
 */
class SoapObjectsFactory {
	/**
	 * Generate a new Soap Fault
	 * @param string $p_fault_code   SOAP fault code.
	 * @param string $p_fault_string SOAP fault description.
	 * @return SoapFault
	 */
	static function newSoapFault( $p_fault_code, $p_fault_string ) {
		return new SoapFault( $p_fault_code, $p_fault_string );
	}

	/**
	 * Convert a soap object to an array
	 * @param stdClass|array $p_object Object.
	 * @return array
	 */
	static function unwrapObject( $p_object ) {
		if( is_object( $p_object ) ) {
			return get_object_vars( $p_object );
		}

		return $p_object;
	}

	/**
	 * Convert a timestamp to a soap DateTime variable
	 * @param integer $p_value Integer value to return as date time string.
	 * @return SoapVar
	 */
	static function newDateTimeVar( $p_value ) {
		$t_string_value = self::newDateTimeString( $p_value );

		return new SoapVar( $t_string_value, XSD_DATETIME, 'xsd:dateTime' );
	}

	/**
	 * Convert a timestamp to a DateTime string
	 * @param integer $p_timestamp Integer value to format as date time string.
	 * @return string
	 */
	static function newDateTimeString ( $p_timestamp ) {
		if( $p_timestamp == null || date_is_null( $p_timestamp ) ) {
			return null;
		}

		return date( 'c', (int)$p_timestamp );
	}

	/**
	 * Process Date Time string with strtotime
	 * @param string $p_string String value to process as a date time string.
	 * @return integer
	 */
	static function parseDateTimeString ( $p_string ) {
		return strtotime( $p_string );
	}

	/**
	 * Perform any necessary encoding on a binary string
	 * @param string $p_binary Binary string.
	 * @return string
	 */
	static function encodeBinary ( $p_binary ) {
		return $p_binary;
	}

	/**
	 * Checks if an object is a SoapFault
	 * @param mixed $p_maybe_fault Object to check whether a SOAP fault.
	 * @return boolean
	 */
	static function isSoapFault ( $p_maybe_fault ) {
		if( !is_object( $p_maybe_fault ) ) {
			return false;
		}

		return get_class( $p_maybe_fault ) == 'SoapFault';
	}
}

/**
 * Get the MantisConnect webservice version.
 * @return string
 */
function mc_version() {
	return MANTIS_VERSION;
}

/**
 * Attempts to login the user.
 * If logged in successfully, return user information.
 * If failed to login in, then throw a fault.
 * @param string $p_username Login username.
 * @param string $p_password Login password.
 * @return array Array of user data for the current API user
 */
function mc_login( $p_username, $p_password ) {
	$t_user_id = mci_check_login( $p_username, $p_password );
	if( $t_user_id === false ) {
		return mci_soap_fault_login_failed();
	}

	return mci_user_get( $p_username, $p_password, $t_user_id );
}

/**
 * Given an id, this method returns the user.
 * When calling this method make sure that the caller has the right to retrieve
 * information about the target user.
 * @param string  $p_username Login username.
 * @param string  $p_password Login password.
 * @param integer $p_user_id  A valid user identifier.
 * @return array array of user data for the supplied user id
 */
function mci_user_get( $p_username, $p_password, $p_user_id ) {
	$t_user_data = array();

	# if user doesn't exist, then mci_account_get_array_by_id() will throw.
	$t_user_data['account_data'] = mci_account_get_array_by_id( $p_user_id );
	$t_user_data['access_level'] = access_get_global_level( $p_user_id );
	$t_user_data['timezone'] = user_pref_get_pref( $p_user_id, 'timezone' );

	return $t_user_data;
}

/**
 * access_ if MantisBT installation is marked as offline by the administrator.
 * @return true: offline, false: online
 */
function mci_is_mantis_offline() {
	$t_offline_file = dirname( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'mantis_offline.php';
	return file_exists( $t_offline_file );
}

/**
 * handle a soap API login
 * @param string $p_username Login username.
 * @param string $p_password Login password.
 * @return integer|false return user_id if successful, otherwise false.
 */
function mci_check_login( $p_username, $p_password ) {
	if( mci_is_mantis_offline() ) {
		return false;
	}

	# Must not pass in null password, otherwise, authentication will be by-passed
	# by auth_attempt_script_login().
	$t_password = ( $p_password === null ) ? '' : $p_password;

	# Validate the token
	if( api_token_validate( $p_username, $t_password ) ) {
		# Token is valid, then login the user without worrying about a password.
		if( auth_attempt_script_login( $p_username, null ) === false ) {
			return false;
		}
	} else {
		# Not a valid token, validate as username + password.
		if( auth_attempt_script_login( $p_username, $t_password ) === false ) {
			return false;
		}
	}

	return auth_get_current_user_id();
}

/**
 * Check with a user has readonly access to the webservice for a given project
 * @param integer $p_user_id    A user identifier.
 * @param integer $p_project_id A project identifier ( Default All Projects ).
 * @return boolean indicating whether user has readonly access
 */
function mci_has_readonly_access( $p_user_id, $p_project_id = ALL_PROJECTS ) {
	$t_access_level = user_get_access_level( $p_user_id, $p_project_id );
	return( $t_access_level >= config_get( 'webservice_readonly_access_level_threshold' ) );
}

/**
 * Check with a user has readwrite access to the webservice for a given project
 * @param integer $p_user_id    User id.
 * @param integer $p_project_id Project Id ( Default All Projects ).
 * @return boolean indicating whether user has readwrite access
 */
function mci_has_readwrite_access( $p_user_id, $p_project_id = ALL_PROJECTS ) {
	$t_access_level = user_get_access_level( $p_user_id, $p_project_id );
	return( $t_access_level >= config_get( 'webservice_readwrite_access_level_threshold' ) );
}

/**
 * Check with a user has the required access level for a given project
 * @param integer $p_access_level Access level.
 * @param integer $p_user_id      User id.
 * @param integer $p_project_id   Project Id ( Default All Projects ).
 * @return boolean indicating whether user has the required access
 */
function mci_has_access( $p_access_level, $p_user_id, $p_project_id = ALL_PROJECTS ) {
	$t_access_level = user_get_access_level( $p_user_id, $p_project_id );
	return( $t_access_level >= (int)$p_access_level );
}

/**
 * Check with a user has administrative access to the webservice
 * @param integer $p_user_id    User id.
 * @param integer $p_project_id Project Id ( Default All Projects ).
 * @return boolean indicating whether user has the required access
 */
function mci_has_administrator_access( $p_user_id, $p_project_id = ALL_PROJECTS ) {
	$t_access_level = user_get_access_level( $p_user_id, $p_project_id );
	return( $t_access_level >= config_get( 'webservice_admin_access_level_threshold' ) );
}

/**
 * Given an object, return the project id
 * @param object $p_project Project Object.
 * @return integer project id
 */
function mci_get_project_id( $p_project ) {
	if( is_object( $p_project ) ) {
		$p_project = get_object_vars( $p_project );
	}

	if( isset( $p_project['id'] ) && (int)$p_project['id'] != 0 ) {
		$t_project_id = (int)$p_project['id'];
	} else if( isset( $p_project['name'] ) && !is_blank( $p_project['name'] ) ) {
		$t_project_id = project_get_id_by_name( $p_project['name'] );
	} else {
		$t_project_id = ALL_PROJECTS;
	}

	return $t_project_id;
}

/**
 * Return project Status
 * @param object $p_status Status.
 * @return integer Status
 */
function mci_get_project_status_id( $p_status ) {
	return mci_get_enum_id_from_objectref( 'project_status', $p_status );
}

/**
 * Return project view state
 * @param object $p_view_state View state.
 * @return integer View state
 */
function mci_get_project_view_state_id( $p_view_state ) {
	return mci_get_enum_id_from_objectref( 'project_view_state', $p_view_state );
}

/**
 * Return user id
 * @param stdClass $p_user User.
 * @return integer user id
 */
function mci_get_user_id( stdClass $p_user ) {
	$p_user = SoapObjectsFactory::unwrapObject( $p_user );

	$t_user_id = 0;

	if( isset( $p_user['id'] ) && (int)$p_user['id'] != 0 ) {
		$t_user_id = (int)$p_user['id'];
	} elseif( isset( $p_user['name'] ) ) {
		$t_user_id = user_get_id_by_name( $p_user['name'] );
	} elseif( isset( $p_user['email'] ) ) {
		$t_user_id = user_get_id_by_email( $p_user['email'] );
	}

	return $t_user_id;
}

/**
 * Return user's default language given a user id
 * @param integer $p_user_id User id.
 * @return string language string
 */
function mci_get_user_lang( $p_user_id ) {
	$t_lang = user_pref_get_pref( $p_user_id, 'language' );
	if( $t_lang == 'auto' ) {
		$t_lang = config_get( 'fallback_language' );
	}
	return $t_lang;
}

/**
 * Return Status
 * @param object $p_status Status.
 * @return integer status id
 */
function mci_get_status_id( $p_status ) {
	return mci_get_enum_id_from_objectref( 'status', $p_status );
}

/**
 * Return Severity
 * @param object $p_severity Severity.
 * @return integer severity id
 */
function mci_get_severity_id( $p_severity ) {
	return mci_get_enum_id_from_objectref( 'severity', $p_severity );
}

/**
 * Return Priority
 * @param object $p_priority Priority.
 * @return integer priority id
 */
function mci_get_priority_id( $p_priority ) {
	return mci_get_enum_id_from_objectref( 'priority', $p_priority );
}

/**
 * Return Reproducibility
 * @param object $p_reproducibility Reproducibility.
 * @return integer reproducibility id
 */
function mci_get_reproducibility_id( $p_reproducibility ) {
	return mci_get_enum_id_from_objectref( 'reproducibility', $p_reproducibility );
}

/**
 * Return Resolution
 * @param object $p_resolution Resolution object.
 * @return integer Resolution id
 */
function mci_get_resolution_id( $p_resolution ) {
	return mci_get_enum_id_from_objectref( 'resolution', $p_resolution );
}

/**
 * Return projection
 * @param object $p_projection Projection object.
 * @return integer projection id
 */
function mci_get_projection_id( $p_projection ) {
	return mci_get_enum_id_from_objectref( 'projection', $p_projection );
}

/**
 * Return ETA id
 * @param object $p_eta ETA object.
 * @return integer eta id
 */
function mci_get_eta_id( $p_eta ) {
	return mci_get_enum_id_from_objectref( 'eta', $p_eta );
}

/**
 * Return view state id
 * @param object $p_view_state View state object.
 * @return integer view state
 */
function mci_get_view_state_id( $p_view_state ) {
	return mci_get_enum_id_from_objectref( 'view_state', $p_view_state );
}

/**
 * Get null on empty value.
 *
 * @param string $p_value The value.
 * @return string|null The value if not empty; null otherwise.
 */
function mci_null_if_empty( $p_value ) {
	if( !is_blank( $p_value ) ) {
		return $p_value;
	}

	return null;
}

/**
 * Removes any invalid character from the string per XML 1.0 specification
 *
 * @param string $p_input XML string.
 * @return string the sanitized XML
 */
function mci_sanitize_xml_string ( $p_input ) {
	return preg_replace( '/[^\x9\xA\xD\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]+/u', '', $p_input );
}

/**
 * Gets the url for MantisBT.
 *
 * @return string MantisBT URL terminated by a /.
 */
function mci_get_mantis_path() {
	return config_get( 'path' );
}

/**
 * Given a enum string and num, return the appropriate localized string
 * @param string $p_enum_name Enumeration name.
 * @param string $p_val       Enumeration value.
 * @param string $p_lang      Language string.
 * @return string
 */
function mci_get_enum_element( $p_enum_name, $p_val, $p_lang ) {
	$t_enum_string = config_get( $p_enum_name . '_enum_string' );
	$t_localized_enum_string = lang_get( $p_enum_name . '_enum_string', $p_lang );

	return MantisEnum::getLocalizedLabel( $t_enum_string, $t_localized_enum_string, $p_val );
}

/**
 * Gets the sub-projects that are accessible to the specified user / project.
 * @param integer $p_user_id           User id.
 * @param integer $p_parent_project_id Parent Project id.
 * @param string  $p_lang              Language string.
 * @return array
 */
function mci_user_get_accessible_subprojects( $p_user_id, $p_parent_project_id, $p_lang = null ) {
	if( $p_lang === null ) {
		$t_lang = mci_get_user_lang( $p_user_id );
	} else {
		$t_lang = $p_lang;
	}

	$t_result = array();
	foreach( user_get_accessible_subprojects( $p_user_id, $p_parent_project_id ) as $t_subproject_id ) {
		$t_subproject_row = project_cache_row( $t_subproject_id );
		$t_subproject = array();
		$t_subproject['id'] = $t_subproject_id;
		$t_subproject['name'] = $t_subproject_row['name'];
		$t_subproject['status'] = mci_enum_get_array_by_id( $t_subproject_row['status'], 'project_status', $t_lang );
		$t_subproject['enabled'] = $t_subproject_row['enabled'];
		$t_subproject['view_state'] = mci_enum_get_array_by_id( $t_subproject_row['view_state'], 'project_view_state', $t_lang );
		$t_subproject['access_min'] = mci_enum_get_array_by_id( $t_subproject_row['access_min'], 'access_levels', $t_lang );
		$t_subproject['file_path'] = array_key_exists( 'file_path', $t_subproject_row ) ? $t_subproject_row['file_path'] : '';
		$t_subproject['description'] = array_key_exists( 'description', $t_subproject_row ) ? $t_subproject_row['description'] : '';
		$t_subproject['subprojects'] = mci_user_get_accessible_subprojects( $p_user_id, $t_subproject_id, $t_lang );
		$t_result[] = $t_subproject;
	}

	return $t_result;
}

/**
 * Convert a category name to a category id for a given project
 * @param string  $p_category_name Category name.
 * @param integer $p_project_id    Project id.
 * @return integer category id or 0 if not found
 */
function translate_category_name_to_id( $p_category_name, $p_project_id ) {
	if( !isset( $p_category_name ) ) {
		return 0;
	}

	$t_cat_array = category_get_all_rows( $p_project_id );
	foreach( $t_cat_array as $t_category_row ) {
		if( $t_category_row['name'] == $p_category_name ) {
			return $t_category_row['id'];
		}
	}
	return 0;
}

/**
 * Basically this is a copy of core/filter_api.php#filter_db_get_available_queries().
 * The only difference is that the result of this function is not an array of filter
 * names but an array of filter structures.
 * @param integer $p_project_id Project id.
 * @param integer $p_user_id    User id.
 * @return array
 */
function mci_filter_db_get_available_queries( $p_project_id = null, $p_user_id = null ) {
	$t_overall_query_arr = array();

	if( null === $p_project_id ) {
		$t_project_id = helper_get_current_project();
	} else {
		$t_project_id = (int)$p_project_id;
	}

	if( null === $p_user_id ) {
		$t_user_id = auth_get_current_user_id();
	} else {
		$t_user_id = (int)$p_user_id;
	}

	# If the user doesn't have access rights to stored queries, just return
	if( !access_has_project_level( config_get( 'stored_query_use_threshold' ) ) ) {
		return $t_overall_query_arr;
	}

	# Get the list of available queries. By sorting such that public queries are
	# first, we can override any query that has the same name as a private query
	# with that private one
	$t_query = 'SELECT * FROM {filters}
					WHERE (project_id=' . db_param() . '
						OR project_id=0)
					AND name!=\'\'
					AND (is_public = ' . db_param() . '
						OR user_id = ' . db_param() . ')
					ORDER BY is_public DESC, name ASC';
	$t_result = db_query( $t_query, array( $t_project_id, true, $t_user_id ) );
	$t_query_count = db_num_rows( $t_result );

	for( $i = 0;$i < $t_query_count;$i++ ) {
		$t_row = db_fetch_array( $t_result );

		$t_filter_detail = explode( '#', $t_row['filter_string'], 2 );
		if( !isset($t_filter_detail[1]) ) {
			continue;
		}
		$t_filter = json_decode( $t_filter_detail[1], true );
		$t_filter = filter_ensure_valid_filter( $t_filter );
		$t_row['url'] = filter_get_url( $t_filter );
		$t_overall_query_arr[$t_row['name']] = $t_row;
	}

	return array_values( $t_overall_query_arr );
}

/**
 * Get a category definition.
 *
 * @param integer $p_category_id The id of the category to retrieve.
 * @return array an array containing the id and the name of the category.
 */
function mci_category_as_array_by_id( $p_category_id ) {
	$t_result = array();
	$t_result['id'] = $p_category_id;
	$t_result['name'] = category_get_name( $p_category_id );
	return $t_result;
}

/**
 * Transforms a version array into an array suitable for marshalling into ProjectVersionData
 *
 * @param array $p_version Version array.
 * @return array
 */
function mci_project_version_as_array( array $p_version ) {
	return array(
			'id' => $p_version['id'],
			'name' => $p_version['version'],
			'project_id' => $p_version['project_id'],
			'date_order' => SoapObjectsFactory::newDateTimeVar( $p_version['date_order'] ),
			'description' => mci_null_if_empty( $p_version['description'] ),
			'released' => $p_version['released'],
			'obsolete' => $p_version['obsolete']
		);
}

/**
 * Returns time tracking information from a bug note.
 *
 * @param integer $p_issue_id The id of the issue.
 * @param array   $p_note     A note as passed to the soap api methods.
 *
 * @return String the string time entry to be added to the bugnote, in 'HH:mm' format
 */
function mci_get_time_tracking_from_note( $p_issue_id, array $p_note ) {
	if( !access_has_bug_level( config_get( 'time_tracking_view_threshold' ), $p_issue_id ) ) {
		return '00:00';
	}

	if( !isset( $p_note['time_tracking'] ) ) {
		return '00:00';
	}

	return db_minutes_to_hhmm( $p_note['time_tracking'] );
}

/**
 * Default error handler
 *
 * This handler will not receive E_ERROR, E_PARSE, E_CORE_*, or E_COMPILE_* errors.
 *
 * E_USER_* are triggered by us and will contain an error constant in $p_error
 * The others, being system errors, will come with a string in $p_error
 * @param integer $p_type    Contains the level of the error raised, as an integer.
 * @param string  $p_error   Contains the error message, as a string.
 * @param string  $p_file    Contains the filename that the error was raised in, as a string.
 * @param integer $p_line    Contains the line number the error was raised at, as an integer.
 * @param array   $p_context To the active symbol table at the point the error occurred (optional).
 * @return void
 */
function mc_error_handler( $p_type, $p_error, $p_file, $p_line, array $p_context ) {
	# check if errors were disabled with @ somewhere in this call chain
	# also suppress php 5 strict warnings
	if( 0 == error_reporting() || 2048 == $p_type ) {
		return;
	}

	# flush any language overrides to return to user's natural default
	if( function_exists( 'db_is_connected' ) ) {
		if( db_is_connected() ) {
			lang_push( lang_get_default() );
		}
	}

	# build an appropriate error string
	switch( $p_type ) {
		case E_WARNING:
			$t_error_type = 'SYSTEM WARNING';
			$t_error_description = $p_error;
			break;
		case E_NOTICE:
			$t_error_type = 'SYSTEM NOTICE';
			$t_error_description = $p_error;
			break;
		case E_USER_ERROR:
			$t_error_type = 'APPLICATION ERROR #' . $p_error;
			$t_error_description = error_string( $p_error );
			break;
		case E_USER_WARNING:
			$t_error_type = 'APPLICATION WARNING #' . $p_error;
			$t_error_description = error_string( $p_error );
			break;
		case E_USER_NOTICE:
			# used for debugging
			$t_error_type = 'DEBUG';
			$t_error_description = $p_error;
			break;
		default:
			#shouldn't happen, just display the error just in case
			$t_error_type = '';
			$t_error_description = $p_error;
	}

	$t_error_stack = error_get_stack_trace();

	error_log( '[mantisconnect.php] Error Type: ' . $t_error_type . ',' . "\n" . 'Error Description: ' . $t_error_description . "\n" . 'Stack Trace:' . "\n" . $t_error_stack );

	throw new SoapFault( 'Server', 'Error Type: ' . $t_error_type . ',' . "\n" . 'Error Description: ' . $t_error_description );
}

/**
 * Get a stack trace from either PHP or xdebug if present
 * @return string
 */
function error_get_stack_trace() {
	$t_trace = '';

	if( extension_loaded( 'xdebug' ) ) {

		#check for xdebug presence
		$t_stack = xdebug_get_function_stack();

		# reverse the array in a separate line of code so the
		#  array_reverse() call doesn't appear in the stack
		$t_stack = array_reverse( $t_stack );
		array_shift( $t_stack );

		#remove the call to this function from the stack trace
		foreach( $t_stack as $t_frame ) {
			$t_trace .= ( isset( $t_frame['file'] ) ? basename( $t_frame['file'] ) : 'UnknownFile' ) . ' L' . ( isset( $t_frame['line'] ) ? $t_frame['line'] : '?' ) . ' ' . ( isset( $t_frame['function'] ) ? $t_frame['function'] : 'UnknownFunction' );

			$t_args = array();
			if( isset( $t_frame['params'] ) && ( count( $t_frame['params'] ) > 0 ) ) {
				$t_trace .= ' Params: ';
				foreach( $t_frame['params'] as $t_value ) {
					$t_args[] = error_build_parameter_string( $t_value );
				}

				$t_trace .= '(' . implode( $t_args, ', ' ) . ')';
			} else {
				$t_trace .= '()';
			}

			$t_trace .= "\n";
		}
	} else {
		$t_stack = debug_backtrace();

		array_shift( $t_stack ); #remove the call to this function from the stack trace
		array_shift( $t_stack ); #remove the call to the error handler from the stack trace

		foreach( $t_stack as $t_frame ) {
			$t_trace .= ( isset( $t_frame['file'] ) ? basename( $t_frame['file'] ) : 'UnknownFile' ) . ' L' . ( isset( $t_frame['line'] ) ? $t_frame['line'] : '?' ) . ' ' . ( isset( $t_frame['function'] ) ? $t_frame['function'] : 'UnknownFunction' );

			$t_args = array();
			if( isset( $t_frame['args'] ) ) {
				foreach( $t_frame['args'] as $t_value ) {
					$t_args[] = error_build_parameter_string( $t_value );
				}

				$t_trace .= '(' . implode( $t_args, ', ' ) . ')';
			} else {
				$t_trace .= '()';
			}

			$t_trace .= "\n";
		}
	}

	return $t_trace;
}

/**
 * Returns a soap_fault signalling corresponding to a failed login
 * situation
 *
 * @return soap_fault
 */
function mci_soap_fault_login_failed() {
	return SoapObjectsFactory::newSoapFault( 'Client', 'Access denied' );
}

/**
 * Returns a soap_fault signalling that the user does not have
 * access rights for the specific action.
 *
 * @param integer $p_user_id A user id, optional.
 * @param string  $p_detail  The optional details to append to the error message.
 * @return soap_fault
 */
function mci_soap_fault_access_denied( $p_user_id = 0, $p_detail = '' ) {
	if( $p_user_id ) {
		$t_user_name = user_get_name( $p_user_id );
		$t_reason = 'Access denied for user '. $t_user_name . '.';
	} else {
		$t_reason = 'Access denied';
	}

	if( !is_blank( $p_detail ) ) {
		$t_reason .= ' Reason: ' . $p_detail . '.';
	}

	return SoapObjectsFactory::newSoapFault( 'Client', $t_reason );
}


text:
package org.nutz.lang.random;

import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.junit.Ignore;
import org.junit.Test;
import org.nutz.lang.Lang;

public class EnumRandomTest {
    public enum Color {
        RED, BLUE, YELLOW, WHITE
    };

    @Ignore("EnumRandom是可预知顺序的??")
    @Test
    public void test_enum() {
        Random<Color> r = new EnumRandom<Color>() {};
        Set<Color> re = new HashSet<Color>(Arrays.asList(Color.values()));
        Set<Color> rs = new HashSet<Color>();
        for (int j = 0; j < 4; j++) {
            for (int i = 0; i < 4; i++)
                rs.add(r.next());
            assertTrue(Lang.equals(re, rs));
        }
    }
}


text:
/* global angular:false */

(function () {
    "use strict";

    var AppController = function ($scope, $rootScope, $router, $location, $logger, $q, $timeout, $data, $jsnbt, LocationService, ScrollSpyService, AuthService, FileService,NodeService, ModalService, CONTROL_EVENTS, AUTH_EVENTS, DATA_EVENTS, ROUTE_EVENTS) {
        jsnbt.controllers.AppControllerBase.apply(this, $rootScope.getBaseArguments($scope));

    };
    AppController.prototype = Object.create(jsnbt.controllers.AppControllerBase.prototype);

    angular.module("jsnbt")
        .controller('AppController', ['$scope', '$rootScope', '$router', '$location', '$logger', '$q', '$timeout', '$data', '$jsnbt', 'LocationService', 'ScrollSpyService', 'AuthService', 'NodeService', 'ModalService', 'CONTROL_EVENTS', 'AUTH_EVENTS', 'DATA_EVENTS', 'ROUTE_EVENTS', AppController]);

    var ModalPageController = function ($scope, $rootScope, $router, $logger, $q, $timeout, $data, $jsnbt, LocationService, ScrollSpyService, AuthService, FileService,NodeService, ModalService, CONTROL_EVENTS, AUTH_EVENTS, DATA_EVENTS, ROUTE_EVENTS) {
        jsnbt.controllers.AppControllerBase.apply(this, $rootScope.getBaseArguments($scope));

        $scope.route.on('success', function () {
            var modalElement = $('.modal:last > .modal-dialog > .modal-content > div > .modal-body');
            modalElement.scrollTo(modalElement, { duration: 600 });
        });
    };
    ModalPageController.prototype = Object.create(jsnbt.controllers.AppControllerBase.prototype);

    angular.module("jsnbt")
        .controller('ModalPageController', ['$scope', '$rootScope', '$router', '$logger', '$q', '$timeout', '$data', '$jsnbt', 'LocationService', 'ScrollSpyService', 'AuthService', 'NodeService', 'ModalService', 'CONTROL_EVENTS', 'AUTH_EVENTS', 'DATA_EVENTS', 'ROUTE_EVENTS', ModalPageController]);
})();


text:
echo Testing DOUBLE PRECISION LAPACK RFP protoype linear equation routines
exec ./test_lin_rfd < $CBLAPACKDIR/test/input/dtest_rfp.in


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('ringapp', '0061_migrate_to_souffle'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='logic',
            name='concs',
        ),
        migrations.RemoveField(
            model_name='logic',
            name='hyps',
        ),
    ]


text:
import { ServerInterface } from "./server-interface.js";
import { AnnotationManager } from "./annotation-manager.js";
import { TickBar } from "./components/tick-bar.js";
import { PolygonOverlay } from "./components/polygon-overlay.js";
import { preferences } from "../utils/preference-manager.js";
import { AnnotationGUI } from "./components/annotation-gui.js";
import { InfoContainer } from "./components/info-container.js";
import { SessionManager } from "./session-manager.js";
import { MessageOverlay } from "./components/message-overlay.js";
import { Annotation } from "./annotation.js";

class VideoAnnotator {
    constructor(player, serverURL, tagsURL, apiKey){
        console.log("[VideoAnnotator] Creating VideoAnnotator...");

        this.serverURL = serverURL;
        this.tagsURL = tagsURL;
        this.apiKey = apiKey;

        this.player = player;
        this.Wrap();
        this.PopulateControls();

        this.server = new ServerInterface(this);
        this.server.SetBaseURL(this.serverURL);

        this.messageOverlay = new MessageOverlay(this);
        this.annotationManager = new AnnotationManager();
        this.sessionManager = new SessionManager(this);

        // Load annotations from server based on the player's video URL
        this.server.FetchAnnotations('location', this.player.videoElement.currentSrc)
        .done((json)=>{
            this.annotationManager.PopulateFromJSON(json);
            this.AnnotationsLoaded();
        });

        this.player.$container.on("OnTimeUpdate", (event, time) => {
            this.OnTimeUpdate(time);
        });

        this.$container.on("OnPolyClicked", (event, annotation) => {
            // Edit a poly when clicked, but only if the editor isn't already open
            if(!this.gui.open){
                this.$addAnnotationButton.button("disable");
                this.gui.BeginEditing(annotation);
            }
        });

        this.gui.$container.on("OnGUIClosed", (event) => {
            this.$addAnnotationButton.button("enable");
        });

        console.log("[VideoAnnotator] Annotator created for video.");
    }

    /**
     * Creates the divs that surround the video player.
     */
    Wrap(){
        // Wrap the video player with this container
        this.$container = $(this.player.$container).wrap("

").parent();

        // Set the container to the width of the video player
        this.$container.width(this.player.$container.width());

        // Allow the video player container to grow
        //this.player.$container.width("100%");
        //this.player.$container.height("100%");

        // Copy the video styles to the container
        console.log(this.player.originalStyles);
        this.$container.css(this.player.originalStyles);
    }

    PopulateControls(){
        // Create the tick bar
        this.tickBar = new TickBar(this);

        // Create the polygon overlay
        this.polyOverlay = new PolygonOverlay(this);

        this.$debugControls = $("

").appendTo(this.$container);
        var $showAllAnnotationsButton = this.$debugControls.append('<button>Open Annotation Manifest in New Window</button>');
        $showAllAnnotationsButton.click(() => {
            let url = this.player.videoElement.currentSrc;
            this.server.FetchAnnotations("location", url).done((json) => {
                let win = window.open();
                if(win === null) {
                    console.error("Couldn't show annotation manifest; please allow pop-ups.");
                    this.messageOverlay.ShowError("Couldn't show annotation manifest; please allow pop-ups.");
                }
                else {
                    win.document.open();
                    win.document.write(`<title>Annotation Manifest for ${url}</title>`);
                    win.document.write("
");
                    win.document.write(JSON.stringify(json, null, 2).escapeHTML());

                    win.document.write("
");
                    win.document.close();
                }
            });

        });

        // Wrap all the buttons with the list tag
        //this.$debugControls.wrapInner("

");
        // Wrap each button with the list element tag
        //this.$debugControls.find("button").wrap("

");

        // Create the info container
        this.infoContainer = new InfoContainer(this);

        // Inject the annotation edit button into the toolbar
        this.$addAnnotationButton = $("<button>Add New Annotation</button>").button({
            icon: "fa fa-plus",
            showLabel: false
        }).click(() => {
            this.$addAnnotationButton.button("disable");
            this.gui.BeginEditing();
        });
        this.player.controlBar.RegisterElement(this.$addAnnotationButton, 3, 'flex-end');

        // Inject the annotation upload button into the toolbar
        this.$uploadAnnotationButton = $("<button type='file'>Import Annotation From File</button>").button({
            icon: "fa fa-upload",
            showLabel: false
        }).click(() => {
            this.LoadFromFile();
        });
        this.player.controlBar.RegisterElement(this.$uploadAnnotationButton, 2, 'flex-end');

        this.gui = new AnnotationGUI(this);

    }

    AnnotationsLoaded(){
        //Send annotation loaded event
        this.$container.trigger("OnAnnotationsLoaded", this.annotationManager);
    }

    OnTimeUpdate(time){
        this.annotationsNow = this.annotationManager.AnnotationsAtTime(time);

        if(this.annotationsNow.equals(this.lastAnnotationSet)){
            //console.log("Skipping");
            return;
        }

        this.lastAnnotationSet = this.annotationsNow;

        this.UpdateViews();
    }

    UpdateViews(){
        this.annotationsNow = this.annotationManager.AnnotationsAtTime(this.player.videoElement.currentTime);

        // Update the info container
        this.infoContainer.Rebuild(this.annotationsNow);

        this.$container.trigger("OnNewAnnotationSet", [this.annotationsNow]);
    }

    RegisterNewAnnotation(annotation){
        //console.log(annotation);
        this.annotationManager.RegisterAnnotation(annotation);

        // Throw event for listening objects (e.g. tick-bar)
        this.$container.trigger("OnAnnotationRegistered", [annotation]);

        // Update dependent views
        this.UpdateViews();
    }

    UpdateAnnotation(annotation, oldID){
        this.annotationManager.UpdateAnnotation(annotation, oldID);

        // Throw event for listening objects (e.g. tick-bar)
        this.$container.trigger("OnAnnotationRemoved", [oldID]);
        this.$container.trigger("OnAnnotationRegistered", [annotation]);

        // Update dependent views
        this.UpdateViews();
    }

    DeregisterAnnotation(annotation){
        this.annotationManager.RemoveAnnotation(annotation.id);
        //this.annotationsNow = this.annotationManager.AnnotationsAtTime(this.player.videoElement.currentTime);

        // Throw event for listening objects (e.g. tick-bar)
        this.$container.trigger("OnAnnotationRemoved", [annotation.id]);

        // Update dependent views
        this.UpdateViews();

    }

    LoadFromFile() {
        // Create the dialog
        let $container = $("

"); // Outermost HTML
        let $headText = $("
Annotations must be W3C OA compliant in JSON format.
").appendTo($container);
        let $errorText = $("

").appendTo($container);
        $errorText.hide();
        let $form = $("<form></form>").appendTo($container);

        let $importField;

        $("Select File").appendTo($form);
        $importField = $("<input type='file' name='importFile' class='file ui-widget-content ui-corner-all'>").appendTo($form);

        $form.wrapInner("<fieldset />");

        let error = (message) => {
            console.error(message);
            $errorText.html(message);
            $errorText.show();
        }

        let self = this;
        $importField.on('change', () => {
            let files = $importField.get(0).files;
            let fr = new FileReader();

            fr.onload = ((localFile) => {
                // If the JSON is malformed, show an error and stop here.
                try {
                    JSON.parse(localFile.target.result);
                }
                catch (e) {
                    error("JSON file is malformed!");
                    return;
                }

                let localJson = JSON.parse(localFile.target.result);
                let annotation = new Annotation(localJson);
                if(this.ValidateAnnotation(annotation)){
                    // Open the GUI and populate it with this annotation's data.
                    this.gui.BeginEditing(annotation, true);
                    $dialog.dialog("close");
                }
                else {
                    error("JSON is invalid!");
                }
            });
            fr.readAsText(files[0]);
        });

        let $dialog = $container.dialog({
            autoOpen: true,
            draggable: false,
            modal: true,
            buttons: {
                Cancel: () => {
                    $dialog.dialog("close");
                }
            },
            close: () => {
                $dialog.find("form")[ 0 ].reset();
                $dialog.find("input").removeClass( "ui-state-error" );
                //this.OnModalClose();
            }
        });
    }

    ValidateAnnotation(annotation) {
        // TODO: Validate annotation here. Return false if any
        // required properties are not present.

        return true;
    }

}

export { VideoAnnotator };


text:
interface adult {
    height: number;
    age: number;
}

declare var adult: {
    minage: number;
    new(): adult;
}


text:
#define _FUDGEMSGENVELOPEIMPL_DEFINED 1
#include "fudge/envelope.h"
#include "fudge/message.h"
#include "memory_internal.h"
#include "reference.h"

struct FudgeMsgEnvelopeImpl
{
    FudgeRefCount refcount;
    fudge_byte directives;
    fudge_byte schemaversion;
    fudge_i16 taxonomy;
    FudgeMsg message;
};

FudgeStatus FudgeMsgEnvelope_create ( FudgeMsgEnvelope * envelopeptr,
                                   fudge_byte directives,
                                   fudge_byte schemaversion,
                                   fudge_i16 taxonomy,
                                   FudgeMsg message )
{
    FudgeStatus status;

    if ( ! ( *envelopeptr = FUDGEMEMORY_MALLOC( FudgeMsgEnvelope, sizeof ( struct FudgeMsgEnvelopeImpl ) ) ) )
        return FUDGE_OUT_OF_MEMORY;

    if ( ( status = FudgeRefCount_create ( &( ( *envelopeptr )->refcount ) ) ) != FUDGE_OK )
        goto release_and_fail;

    if ( ( status = FudgeMsg_retain ( message ) ) != FUDGE_OK )
        goto release_and_fail;

    ( *envelopeptr )->directives = directives;
    ( *envelopeptr )->schemaversion = schemaversion;
    ( *envelopeptr )->taxonomy = taxonomy;
    ( *envelopeptr )->message = message;

    return FUDGE_OK;

release_and_fail:
    FUDGEMEMORY_FREE( *envelopeptr );
    return status;
}

FudgeStatus FudgeMsgEnvelope_retain ( FudgeMsgEnvelope envelope )
{
    if ( ! envelope )
        return FUDGE_NULL_POINTER;

    FudgeRefCount_increment ( envelope->refcount );
    return FUDGE_OK;
}

FudgeStatus FudgeMsgEnvelope_release ( FudgeMsgEnvelope envelope )
{
    if ( ! envelope )
        return FUDGE_NULL_POINTER;

    if ( ! FudgeRefCount_decrementAndReturn ( envelope->refcount ) )
    {
        /* Last reference has been released - release the message and destroy the envelope */
        FudgeStatus status;

        if ( ( status = FudgeMsg_release ( envelope->message ) ) != FUDGE_OK )
            return status;

        if ( ( status = FudgeRefCount_destroy ( envelope->refcount ) ) != FUDGE_OK )
            return status;

        FUDGEMEMORY_FREE( envelope );
    }
    return FUDGE_OK;
}

fudge_byte FudgeMsgEnvelope_getDirectives ( const FudgeMsgEnvelope envelope )
{
    return envelope ? envelope->directives : 0;
}

fudge_byte FudgeMsgEnvelope_getSchemaVersion ( const FudgeMsgEnvelope envelope )
{
    return envelope ? envelope->schemaversion : 0;
}

fudge_i16 FudgeMsgEnvelope_getTaxonomy ( const FudgeMsgEnvelope envelope )
{
    return envelope ? envelope->taxonomy : 0;
}

FudgeMsg FudgeMsgEnvelope_getMessage ( const FudgeMsgEnvelope envelope )
{
    return envelope ? envelope->message : 0;
}


text:
@interface CommentsNode : ASDisplayNode

- (void)updateWithCommentFeedModel:(CommentFeedModel *)feed;

@end


text:
namespace surfaces {
namespace {
void CallCallback(const mojo::Closure& callback, cc::SurfaceDrawStatus status) {
  callback.Run();
}
}

DisplayImpl::DisplayImpl(SurfacesServiceApplication* application,
                         cc::SurfaceManager* manager,
                         cc::SurfaceId cc_id,
                         SurfacesScheduler* scheduler,
                         mojo::ContextProviderPtr context_provider,
                         mojo::ResourceReturnerPtr returner,
                         mojo::InterfaceRequest<mojo::Display> display_request)
    : application_(application),
      manager_(manager),
      factory_(manager, this),
      cc_id_(cc_id),
      scheduler_(scheduler),
      context_provider_(context_provider.Pass()),
      returner_(returner.Pass()),
      viewport_param_binding_(this),
      display_binding_(this, display_request.Pass()) {
  application_->DisplayCreated(this);
  mojo::ViewportParameterListenerPtr viewport_parameter_listener;
  viewport_param_binding_.Bind(GetProxy(&viewport_parameter_listener));
  context_provider_->Create(
      viewport_parameter_listener.Pass(),
      base::Bind(&DisplayImpl::OnContextCreated, base::Unretained(this)));
  factory_.Create(cc_id_);
}

void DisplayImpl::OnContextCreated(mojo::CommandBufferPtr gles2_client) {
  DCHECK(!display_);

  cc::RendererSettings settings;
  display_.reset(new cc::Display(this, manager_, nullptr, nullptr, settings));
  scheduler_->AddDisplay(display_.get());

  // TODO(brianderson): Reconcile with SurfacesScheduler crbug.com/476676
  cc::DisplayScheduler* null_display_scheduler = nullptr;
  display_->Initialize(make_scoped_ptr(new surfaces::DirectOutputSurface(
                           new surfaces::SurfacesContextProvider(
                               gles2_client.PassInterface().PassHandle()))),
                       null_display_scheduler);
  display_->Resize(last_submitted_frame_size_);

  display_->SetSurfaceId(cc_id_, 1.f);
  if (pending_frame_)
    Draw();
}

DisplayImpl::~DisplayImpl() {
  if (display_) {
    factory_.Destroy(cc_id_);
    scheduler_->RemoveDisplay(display_.get());
    // By deleting the object after display_ is reset, OutputSurfaceLost can
    // know not to do anything (which would result in double delete).
    delete display_.release();
  }
  application_->DisplayDestroyed(this);
}

void DisplayImpl::SubmitFrame(mojo::FramePtr frame,
                              const SubmitFrameCallback& callback) {
  DCHECK(pending_callback_.is_null());
  pending_frame_ = frame.Pass();
  pending_callback_ = callback;
  if (display_)
    Draw();
}

void DisplayImpl::Draw() {
  gfx::Size frame_size =
      pending_frame_->passes[0]->output_rect.To<gfx::Rect>().size();
  last_submitted_frame_size_ = frame_size;
  display_->Resize(frame_size);
  factory_.SubmitFrame(cc_id_,
                       pending_frame_.To<scoped_ptr<cc::CompositorFrame>>(),
                       base::Bind(&CallCallback, pending_callback_));
  pending_frame_.reset();
  scheduler_->SetNeedsDraw();
  pending_callback_.reset();
}

void DisplayImpl::CommitVSyncParameters(base::TimeTicks timebase,
                                        base::TimeDelta interval) {
}

void DisplayImpl::OutputSurfaceLost() {
  if (!display_)  // Shutdown case
    return;

  // If our OutputSurface is lost we can't draw until we get a new one. For now,
  // destroy the display and create a new one when our ContextProvider provides
  // a new one.
  // TODO: This is more violent than necessary - we could simply remove this
  // display from the scheduler's set and pass a new context in to the
  // OutputSurface. It should be able to reinitialize properly.
  scheduler_->RemoveDisplay(display_.get());
  display_.reset();
  viewport_param_binding_.Close();
  mojo::ViewportParameterListenerPtr viewport_parameter_listener;
  viewport_param_binding_.Bind(GetProxy(&viewport_parameter_listener));
  context_provider_->Create(
      viewport_parameter_listener.Pass(),
      base::Bind(&DisplayImpl::OnContextCreated, base::Unretained(this)));
}

void DisplayImpl::SetMemoryPolicy(const cc::ManagedMemoryPolicy& policy) {
}

void DisplayImpl::OnVSyncParametersUpdated(int64_t timebase, int64_t interval) {
  scheduler_->OnVSyncParametersUpdated(
      base::TimeTicks::FromInternalValue(timebase),
      base::TimeDelta::FromInternalValue(interval));
}

void DisplayImpl::ReturnResources(const cc::ReturnedResourceArray& resources) {
  if (resources.empty())
    return;
  DCHECK(returner_);

  mojo::Array<mojo::ReturnedResourcePtr> ret(resources.size());
  for (size_t i = 0; i < resources.size(); ++i) {
    ret[i] = mojo::ReturnedResource::From(resources[i]);
  }
  returner_->ReturnResources(ret.Pass());
}

}  // namespace surfaces


text:
#import <UIKit/UIKit.h>

@interface PieChartViewController2 : UIViewController
@end


text:
import { Component } from '@angular/core';

import { demos } from '../../routes';
import { DemoSources, DemoSourceType, MyItem } from '../../shared/interfaces';

import { Datasource } from 'ngx-ui-scroll';

@Component({
  selector: 'app-adapter-fix-updater',
  templateUrl: './adapter-fix-updater.component.html'
})
export class DemoAdapterFixUpdaterComponent {

  demoContext = {
    config: demos.experimental.map.adapterFixUpdater,
    noInfo: true
  };

  adapterPropsScope = demos.adapterProps;
  adapterMethodsScope = demos.adapterMethods;

  datasource = new Datasource<MyItem>({
    get: (index, count, success) => {
      const data: MyItem[] = [];
      for (let i = index; i < index + count; i++) {
        data.push({ id: i, text: 'item #' + i });
      }
      success(data);
    }
  });

  inputValue: string;

  constructor() {
    this.inputValue = '5';
  }

  sources: DemoSources = [{
    name: DemoSourceType.Template,
    text: `<button (click)="doUpdate()">Update</button> item #
<input [(ngModel)]="inputValue" size="2">

Items in buffer: {{this.countItems()}}

{{item.text}}

`
  }, {
    name: DemoSourceType.Component,
    text: `inputValue = '5'

datasource = new Datasource<MyItem>({
  get: (index, count, success) => {
    const data: MyItem[] = [];
    for (let i = index; i < index + count; i++) {
      data.push({ id: i, text: 'item #' + i });
    }
    success(data);
  }
});

doUpdate() {
  const index = Number(this.inputValue);
  if (!isNaN(index)) {
    this.datasource.adapter.fix({
      updater: ({ $index, data }, update) => {
        if (index === $index) {
          data.text += '*';
          // update();
        }
      }
    });
  }
}

countItems() {
  let count = 0;
  this.datasource.adapter.fix({
    updater: _ => count++
  });
  return count;
}
`
  }];

  itemAdapterDescription = `  ItemAdapter {
    $index: number;
    data: any;
    element?: HTMLElement;
  }`;

  adapterFixUpdater = 'Adapter.fix({ updater })';

  doUpdate() {
    const index = Number(this.inputValue);
    if (!isNaN(index)) {
      this.datasource.adapter.fix({
        updater: ({ $index, data }, update) => {
          if (index === $index) {
            data.text += '*';
          }
          update();
        }
      });
    }
  }

  countItems(): number {
    let count = 0;
    this.datasource.adapter.fix({
      updater: _ => count++
    });
    return count;
  }

}


text:
package fr.dgrandemange.txnmgrworkflow.model;

import java.util.List;

/**
 * @author dgrandemange
 *
 */
public class Transition {

	private Node source;

	private Node target;

	private String id;

	private String name;

	private String desc;

	private List<String> guaranteedCtxAttributes;

	private List<String> optionalCtxAttributes;

	private List<String> attributesAdded;

	public Transition() {
		super();
	}

	public Transition(String id, String name, Node source, Node target) {
		super();
		this.id = id;
		this.name = name;
		this.source = source;
		this.target = target;
		source.addAsSourceInTransition(this);
		target.addAsDestInTransition(this);
	}

	public void remove() {
		source.removeFromTransitionAsSource(this);
		target.removeFromTransitionAsDest(this);
		source = null;
		target = null;
	}

	public Node getSource() {
		return source;
	}

	public void setSource(Node source) {
		this.source = source;
	}

	public Node getTarget() {
		return target;
	}

	public void setTarget(Node target) {
		this.target = target;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	/**
	 * @return the ctxAttributes
	 */
	public List<String> getGuaranteedCtxAttributes() {
		return guaranteedCtxAttributes;
	}

	/**
	 * @param ctxAttributes
	 *            the ctxAttributes to set
	 */
	public void setGuaranteedCtxAttributes(List<String> guaranteedCtxAttributes) {
		this.guaranteedCtxAttributes = guaranteedCtxAttributes;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the optionalCtxAttributes
	 */
	public List<String> getOptionalCtxAttributes() {
		return optionalCtxAttributes;
	}

	/**
	 * @param optionalCtxAttributes the optionalCtxAttributes to set
	 */
	public void setOptionalCtxAttributes(List<String> optionalCtxAttributes) {
		this.optionalCtxAttributes = optionalCtxAttributes;
	}

	/**
	 * @return the attributesAdded
	 */
	public List<String> getAttributesAdded() {
		return attributesAdded;
	}

	/**
	 * @param attributesAdded the attributesAdded to set
	 */
	public void setAttributesAdded(List<String> attributesAdded) {
		this.attributesAdded = attributesAdded;
	}

}


text:
package com.jaquadro.minecraft.gardenstuff.core;

import com.jaquadro.minecraft.gardencore.core.ModCreativeTabs;
import com.jaquadro.minecraft.gardencore.util.UniqueMetaIdentifier;
import com.jaquadro.minecraft.gardenstuff.GardenStuff;
import com.jaquadro.minecraft.gardenstuff.item.ItemChainLink;
import com.jaquadro.minecraft.gardenstuff.item.ItemMossPaste;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;

public class ModItems
{
    public static Item chainLink;
    public static Item ironNugget;
    public static Item wroughtIronIngot;
    public static Item wroughtIronNugget;
    public static Item mossPaste;

    public void init () {
        chainLink = new ItemChainLink(makeName("chainLink"));
        ironNugget = new Item().setUnlocalizedName(makeName("ironNugget")).setCreativeTab(ModCreativeTabs.tabGardenCore).setTextureName(GardenStuff.MOD_ID + ":iron_nugget");
        wroughtIronIngot = new Item().setUnlocalizedName(makeName("wroughtIronIngot")).setCreativeTab(ModCreativeTabs.tabGardenCore).setTextureName(GardenStuff.MOD_ID + ":wrought_iron_ingot");
        wroughtIronNugget = new Item().setUnlocalizedName(makeName("wroughtIronNugget")).setCreativeTab(ModCreativeTabs.tabGardenCore).setTextureName(GardenStuff.MOD_ID + ":wrought_iron_nugget");
        mossPaste = new ItemMossPaste(makeName("mossPaste"));

        GameRegistry.registerItem(chainLink, "chain_link");
        GameRegistry.registerItem(ironNugget, "iron_nugget");
        GameRegistry.registerItem(wroughtIronIngot, "wrought_iron_ingot");
        GameRegistry.registerItem(wroughtIronNugget, "wrought_iron_nugget");
        GameRegistry.registerItem(mossPaste, "moss_paste");

        OreDictionary.registerOre("nuggetIron", ironNugget);
        OreDictionary.registerOre("ingotWroughtIron", wroughtIronIngot);
        OreDictionary.registerOre("nuggetWroughtIron", wroughtIronNugget);
    }

    public static String makeName (String name) {
        return GardenStuff.MOD_ID.toLowerCase() + "." + name;
    }

    public static UniqueMetaIdentifier getUniqueMetaID (Item item, int meta) {
        String name = GameData.getItemRegistry().getNameForObject(item);
        if (name == null)
            return null;

        return new UniqueMetaIdentifier(name, meta);
    }

    public static UniqueMetaIdentifier getUniqueMetaID (ItemStack itemStack) {
        if (itemStack.getItem() == null)
            return null;
        return getUniqueMetaID(itemStack.getItem(), itemStack.getItemDamage());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
    <msapplication>
        <tile>
            <square150x150logo src="mstile-150x150.png"/>
            <TileColor>#f4f3f1</TileColor>
        </tile>
    </msapplication>
</browserconfig>


text:
<?php

class Google_Service_Apigee_GoogleCloudApigeeV1SchemaSchemaProperty extends Google_Model
{
  public $createTime;
  public $custom;
  public $type;

  public function setCreateTime($createTime)
  {
    $this->createTime = $createTime;
  }
  public function getCreateTime()
  {
    return $this->createTime;
  }
  public function setCustom($custom)
  {
    $this->custom = $custom;
  }
  public function getCustom()
  {
    return $this->custom;
  }
  public function setType($type)
  {
    $this->type = $type;
  }
  public function getType()
  {
    return $this->type;
  }
}


text:
<?php

/**
 * Toolset_Condition_Theme_Layouts_Support_Native_Missing
 *
 * @since 2.3.0
 */
class Toolset_Condition_Theme_Layouts_Support_Native_Missing
	extends Toolset_Condition_Theme_Layouts_Support_Native_Available {

	public function is_met() {
		return ! parent::is_met();
	}

}


text:
require "coveralls"
Coveralls.wear! unless ENV["FASTLANE_SKIP_UPDATE_CHECK"]

require "webmock/rspec"
WebMock.disable_net_connect!(allow: 'coveralls.io')

require "fastlane"
UI = FastlaneCore::UI

unless ENV["DEBUG"]
  $stdout.puts "Changing stdout to /tmp/fastlane_tests, set `DEBUG` environment variable to print to stdout (e.g. when using `pry`)"
  $stdout = File.open("/tmp/fastlane_tests", "w")
end

xcode_path = FastlaneCore::Helper.xcode_path
unless xcode_path.include?("Contents/Developer")
  UI.error("Seems like you didn't set the developer tools path correctly")
  UI.error("Detected path '#{xcode_path}'") if xcode_path.to_s.length > 0
  UI.error("Please run the following on your machine")
  UI.command("sudo xcode-select -s /Applications/Xcode.app")
  UI.error("Adapt the path if you have Xcode installed/named somewhere else")
  exit(1)
end

# This module is only used to check the environment is currently a testing env
module SpecHelper
end

(Fastlane::TOOLS + [:spaceship, :fastlane_core]).each do |tool|
  path = File.join(tool.to_s, "spec", "spec_helper.rb")
  require_relative path if File.exist?(path)
  require tool.to_s
end

my_main = self
RSpec.configure do |config|
  config.before(:each) do |current_test|
    # We don't want to call the RubyGems API at any point
    # This was a request that was added with Ruby 2.4.0
    allow(Fastlane::FastlaneRequire).to receive(:install_gem_if_needed).and_return(nil)

    tool_name = current_test.id.match(%r{\.\/(\w+)\/})[1]
    method_name = "before_each_#{tool_name}".to_sym
    begin
      my_main.send(method_name)
    rescue NoMethodError
      # no method implemented
    end
  end

  config.after(:each) do |current_test|
    tool_name = current_test.id.match(%r{\.\/(\w+)\/})[1]
    method_name = "after_each_#{tool_name}".to_sym
    begin
      my_main.send(method_name)
    rescue NoMethodError
      # no method implemented
    end
  end

  config.example_status_persistence_file_path = "/tmp/rspec_failed_tests.txt"
end

module FastlaneSpec
  module Env
    # a wrapper to temporarily modify the values of ARGV to
    # avoid errors like: "warning: already initialized constant ARGV"
    # if no block is given, modifies ARGV for good
    # rubocop:disable Style/MethodName
    def self.with_ARGV(argv)
      copy = ARGV.dup
      ARGV.clear
      ARGV.concat(argv)
      if block_given?
        begin
          yield
        ensure
          ARGV.clear
          ARGV.concat(copy)
        end
      end
    end
    # rubocop:enable Style/MethodName
  end
end


text:
Create a [hard link](https://en.wikipedia.org/wiki/Hard_link) or a [symbolic link(symlink)](https://en.wikipedia.org/wiki/Symbolic_link) to an existing file.

## Usage

Create a `target dir` which links to `source dir` as followoing,

```
$ ln [<options>] <source> <target>
```

> `ln` will create a hard link in default without `-s`.

## Options

| Parameter | in short | Value | Description |
|:----------|:--------:|:-----:|:------------|
| –symbolic | -s | | Create symlink |
| -force | -f | | Force existing pathnames to be removed to allow the link |
| -interactive | -i | | Ask if overwriting an exist link |
| -no-clobber | -n | | Wont overwrite |


text:
namespace ofp {

class BucketList : public ProtocolList<BucketRange> {
  using Inherited = ProtocolList<BucketRange>;

 public:
  using Inherited::Inherited;

  void add(const BucketBuilder &bucket);
};

}  // namespace ofp

#endif  // OFP_BUCKETLIST_H_


text:
/*
Theme Name:         CarnfieldPRESS
Theme URI:          http://www.carnfieldwebdesign.co.uk
Description:        CarnfieldPRESS is a versatile responsive WordPress framework based on Gumby, using plugins such as Advanced Custom Fields.  To update to the latest Gumby framework or select specific colours then simply replacing the main Gumby files in this theme should work, copy > paste > overwrite.
Version:            1.0.1
*/

/*
Please note all code Carnfield Web Design Ltd code is property of Carnfield Web Design Ltd, and thus should not be redistributed without prior permission.

This file contains all relevent information regarding post-gumby styles, it's recommended you make no changes to the Gumby core and keep all styling changes in this document only.

This theme requires ACF - Advanced Custom Fields, this is found at:-
https://wordpress.org/plugins/advanced-custom-fields/
*/

/* Globals */
.clr {clear: both;}
.fl {float: left;}
.fr {float: right;}
.hidden {display: none;}
textarea#comment {width: auto; max-width: 100% !important;}

/* Wordpress Defaults */
.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}

/* Menu */
.navcontain {height: auto;}
.navbar {margin-bottom: 0px;}
.mobile-logo {display: none;}
#nav-3.navbar {height: auto !important; margin-bottom: none !important;}

@media (max-width: 768px) {
.mobile-logo {
	float: left;
    display: block;
    position: static;
    margin: 14px 0 0 0px;
}
}

/* Post Meta */
.meta {
	border-bottom: 1px solid #ddd;
	padding: 0 0 10px;
	margin: 0 0 10px 0;
}

/* Breadcrumbs */
.breadcrumbs {
	background: #f5f5f5;
	text-align: left !important;
	margin: 0;
	padding: 10px 0;
	border-bottom: 1px solid #ddd;
}

	.breadcrumbs p {margin: 5px !important; padding: 5px !important;}

/* Comments */
ul.commentlist {}
ul.commentlist li {padding: 0 0 50px;}
ul.commentlist li p {padding: 0 20px;}
.comment {margin: 20px 0; padding: 0px; background: #fff; border: 1px solid #ddd; position: relative;}
.thread-odd {background: #f6f6f6;}
.avatar  {position: absolute; top: 0px; right: 0px; border-left: 1px solid #ddd;}
.comment-author {padding: 20px 20px 0;}
.comment-meta {border-bottom: 1px solid #ddd; margin: 0 0 20px 0; font-size: 11px; padding: 0 20px 20px;}
.says {display: none;} /* Removes the says: part of the comments after poster name */
a.comment-reply-link {padding: 10px 20px; background: #eee; border-top: 1px solid #ddd; border-left: 1px solid #ddd; position: absolute; bottom: 0px; right: 0px;}

/* Sidebar */
#sidebar {padding: 20px 0;}
#sidebar ul {
	list-style-type: disc;
	margin: 0 0 20px 15px;
}
#sidebar ul li {}

/* Footer */
.footer-wrap {
	border-top: 1px solid #ddd;
	background: #eee;
	padding: 20px;
}
#footer {}

/* Homepage Template */
.content {margin: 0px !important;}
#homepage .headline {margin: 20px 0; text-align: center !important; padding: 10px}
	#homepage .headline h2 {}

#homepage .columns {margin: 0px; padding: 10px;}

/* Global Template Styling */
.lightgrey {background: #f5f5f5; border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}
.triblock {margin: 0px !important; padding: 40px 0;}

/* Call to Action Bar */
.calltoaction {background: #283374; color: #fff; padding: 20px 0; margin: 40px 0;}
.calltoaction p {padding: 10px; margin: 10px;}
.calltoaction a.cta-button {margin: 0 0 0 20px; padding: 10px 20px !important; background: #283374; border: 2px solid #fff; color: #fff;}


text:
function g = gaussianPriorGradient(prior, x)

% GAUSSIANPRIORGRADIENT Gradient wrt x of the log Gaussian prior.

% PRIOR

% Compute gradient of prior
g = -prior.precision*x;


text:
 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         regbase.cpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: Declares class regbase.
  */

#ifndef BOOST_REGEX_V4_REGBASE_HPP
#define BOOST_REGEX_V4_REGBASE_HPP

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4103)
#endif
#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost{
//
// class regbase
// handles error codes and flags
//
class BOOST_REGEX_DECL regbase
{
public:
   enum flag_type_
   {
      //
      // Divide the flags up into logical groups:
      // bits 0-7 indicate main synatx type.
      // bits 8-15 indicate syntax subtype.
      // bits 16-31 indicate options that are common to all
      // regex syntaxes.
      // In all cases the default is 0.
      //
      // Main synatx group:
      //
      perl_syntax_group = 0,                      // default
      basic_syntax_group = 1,                     // POSIX basic
      literal = 2,                                // all characters are literals
      main_option_type = literal | basic_syntax_group | perl_syntax_group, // everything!
      //
      // options specific to perl group:
      //
      no_bk_refs = 1 << 8,                        // \d not allowed
      no_perl_ex = 1 << 9,                        // disable perl extensions
      no_mod_m = 1 << 10,                         // disable Perl m modifier
      mod_x = 1 << 11,                            // Perl x modifier
      mod_s = 1 << 12,                            // force s modifier on (overrides match_not_dot_newline)
      no_mod_s = 1 << 13,                         // force s modifier off (overrides match_not_dot_newline)

      //
      // options specific to basic group:
      //
      no_char_classes = 1 << 8,                   // [[:CLASS:]] not allowed
      no_intervals = 1 << 9,                      // {x,y} not allowed
      bk_plus_qm = 1 << 10,                       // uses \+ and \?
      bk_vbar = 1 << 11,                          // use \| for alternatives
      emacs_ex = 1 << 12,                         // enables emacs extensions

      //
      // options common to all groups:
      //
      no_escape_in_lists = 1 << 16,                     // '\' not special inside [...]
      newline_alt = 1 << 17,                            // \n is the same as |
      no_except = 1 << 18,                              // no exception on error
      failbit = 1 << 19,                                // error flag
      icase = 1 << 20,                                  // characters are matched regardless of case
      nocollate = 0,                                    // don't use locale specific collation (deprecated)
      collate = 1 << 21,                                // use locale specific collation
      nosubs = 1 << 22,                                 // don't mark sub-expressions
      save_subexpression_location = 1 << 23,            // save subexpression locations
      no_empty_expressions = 1 << 24,                   // no empty expressions allowed
      optimize = 0,                                     // not really supported

      basic = basic_syntax_group | collate | no_escape_in_lists,
      extended = no_bk_refs | collate | no_perl_ex | no_escape_in_lists,
      normal = 0,
      emacs = basic_syntax_group | collate | emacs_ex | bk_vbar,
      awk = no_bk_refs | collate | no_perl_ex,
      grep = basic | newline_alt,
      egrep = extended | newline_alt,
      sed = basic,
      perl = normal,
      ECMAScript = normal,
      JavaScript = normal,
      JScript = normal
   };
   typedef unsigned int flag_type;

   enum restart_info
   {
      restart_any = 0,
      restart_word = 1,
      restart_line = 2,
      restart_buf = 3,
      restart_continue = 4,
      restart_lit = 5,
      restart_fixed_lit = 6,
      restart_count = 7
   };
};

//
// provide std lib proposal compatible constants:
//
namespace regex_constants{

   enum flag_type_
   {

      no_except = ::pdalboost::regbase::no_except,
      failbit = ::pdalboost::regbase::failbit,
      literal = ::pdalboost::regbase::literal,
      icase = ::pdalboost::regbase::icase,
      nocollate = ::pdalboost::regbase::nocollate,
      collate = ::pdalboost::regbase::collate,
      nosubs = ::pdalboost::regbase::nosubs,
      optimize = ::pdalboost::regbase::optimize,
      bk_plus_qm = ::pdalboost::regbase::bk_plus_qm,
      bk_vbar = ::pdalboost::regbase::bk_vbar,
      no_intervals = ::pdalboost::regbase::no_intervals,
      no_char_classes = ::pdalboost::regbase::no_char_classes,
      no_escape_in_lists = ::pdalboost::regbase::no_escape_in_lists,
      no_mod_m = ::pdalboost::regbase::no_mod_m,
      mod_x = ::pdalboost::regbase::mod_x,
      mod_s = ::pdalboost::regbase::mod_s,
      no_mod_s = ::pdalboost::regbase::no_mod_s,
      save_subexpression_location = ::pdalboost::regbase::save_subexpression_location,
      no_empty_expressions = ::pdalboost::regbase::no_empty_expressions,

      basic = ::pdalboost::regbase::basic,
      extended = ::pdalboost::regbase::extended,
      normal = ::pdalboost::regbase::normal,
      emacs = ::pdalboost::regbase::emacs,
      awk = ::pdalboost::regbase::awk,
      grep = ::pdalboost::regbase::grep,
      egrep = ::pdalboost::regbase::egrep,
      sed = basic,
      perl = normal,
      ECMAScript = normal,
      JavaScript = normal,
      JScript = normal
   };
   typedef ::pdalboost::regbase::flag_type syntax_option_type;

} // namespace regex_constants

} // namespace pdalboost

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4103)
#endif
#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

#endif


text:
#include <exec/exec.h>
#include <proto/exec.h>
#include <dos/dos.h>
#include <exec/types.h>
#include <libraries/retromode.h>
#include <proto/retromode.h>
#include <stdarg.h>

/****** retromode/main/retroDrawShortPlanar ******************************************
*
*   NAME
*      retroDrawShortPlanar -- Description
*
*   SYNOPSIS
*      void retroDrawShortPlanar(struct retroScreen * screen,
*          unsigned short data, int x, int y);
*
*   FUNCTION
*
*   INPUTS
*       screen -
*       data -
*       x -
*       y -
*
*   RESULT
*       This function does not return a result
*
*   EXAMPLE
*
*   NOTES
*
*   BUGS
*
*   SEE ALSO
*
*****************************************************************************
*
*/

void _retromode_retroPixel(struct RetroModeIFace *Self, struct retroScreen * screen, char *memory, int x, int y, unsigned char color);

void _retromode_retroDrawShortPlanar(struct RetroModeIFace *Self,
       struct retroScreen * screen,
       unsigned short data,
       int x,
       int y)
{
	int n;
	unsigned char *mem = screen -> Memory[ screen -> double_buffer_draw_frame ];

	n=0x8000;
	do
	{
		if (n&data) _retromode_retroPixel( Self, screen, mem, x, y, 1 );
		x++;
		n=n>>1;
	} while (n>0);
}