text:
import contextlib
from typing import Sequence, Any, ContextManager

from absl import app
from absl import flags
from absl import logging

import numpy as np
import pandas as pd
import tensorflow as tf

FLAGS = flags.FLAGS

flags.DEFINE_enum(
    'platform',
    'gpu',
    ['cpu', 'gpu', 'tpu'],
    'What platform to train on')
flags.DEFINE_integer('embed_dim', 64, 'Embedding Dimension')
flags.DEFINE_integer('ff_dim', 64, 'FF Dimension')
flags.DEFINE_integer('num_heads', 1, 'Num heads')
flags.DEFINE_integer('model_depth_enc', 6, 'Num Encoder Layers')
flags.DEFINE_integer('model_depth_dec', 1, 'Num Decoder Layers')
flags.DEFINE_integer('mask_pct', 70, 'Mask Pct')
flags.DEFINE_float('lr',1e-5,'Learning rate')
flags.DEFINE_integer('num_classes', 10, 'Number of Classes')
flags.DEFINE_string('model_path','', 'Path for saved model')
flags.DEFINE_string('model_path_linear','', 'Path for saved linear model')
flags.DEFINE_string('model_kw','fmnist', 'Keyword for dataset')
flags.DEFINE_integer('train_len', 60000, 'Length of train set')
flags.DEFINE_string('train_data_path','./data/fashion-mnist_train_n_s.csv', 'Path for saved linear model')
flags.DEFINE_integer('test_len', 10000, 'Length of test set')
flags.DEFINE_string('test_data_path','./data/fashion-mnist_test_n_s.csv', 'Path for saved linear model')
flags.DEFINE_string(
    'master',
    'local',
    'The BNS address of the first TPU worker.')

rng = np.random.default_rng()

def _get_distribution_strategy_scope(
    platform: str, tpu_address: str,
    ) -> ContextManager[Any]:
  """Returns the device-specific TensorFlow strategy scope used for training."""
  if platform == 'tpu':
    cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(
        tpu=tpu_address)
    tf.config.experimental_connect_to_cluster(cluster_resolver)
    tf.tpu.experimental.initialize_tpu_system(cluster_resolver)
    return tf.distribute.TPUStrategy(cluster_resolver).scope()
  elif platform == 'gpu':
    return tf.distribute.MirroredStrategy().scope()
  elif platform == 'cpu':
    # Return a dummy distribution strategy for 'cpu' case.
    return contextlib.nullcontext()
  else:
    raise ValueError(f'Invalid "platform": {platform!r}. Only "tpu",'
                     ' "gpu", and "cpu" are supported.')

def mask_and_ind(arr, mask_pct=0.15):
    """Mask a given array unformly and randomly and return non-masked part of array, non-masked indices, masked indices"""
    r, c = arr.shape
    new_c = ((100-mask_pct)*c)//100
    rem_c = c - new_c
    shuff_idx = np.array([rng.permutation(c) for _ in range(r)])
    rem_idx = shuff_idx[:, :rem_c]
    new_idx = shuff_idx[:, rem_c:]
    new_idx.sort(axis=1)
    rem_idx.sort(axis=1)
    new_arr = np.zeros((r, new_c))
    for i in range(r):
        new_arr[i] = arr[i][new_idx[i]]
    return new_arr, new_idx, rem_idx

class DataGenerator(tf.keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, inp_path, indexes, mask_pct = 15, batch_size=128 , shuffle=True):
        'Initialization'
        self.batch_size = batch_size
        self.shuffle = shuffle
        self.inp_path = inp_path
        self.orig_df = pd.read_csv(inp_path)
        self.columns = list(self.orig_df.columns)
        self.maxlen = len(self.columns)-1
        self.mask_pct= mask_pct
        self.small_maxlen = ((100-mask_pct)*self.maxlen)//100
        self.indexes = indexes
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        num_batches = int(np.floor(len(self.indexes) / self.batch_size))
        return num_batches

    def __getitem__(self, index):
        'Generate one batch of data'
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
        X, y = self.__data_generation(indexes)
        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, indexes):
        'Generates data containing batch_size samples'
        data = self.orig_df.loc[indexes].iloc[:,1:]
        arr = data.to_numpy()
        new_arr, new_idx, rem_idx = mask_and_ind(arr, self.mask_pct)
        X_train = [[],[],[],[]]
        Y_train = []

        for i in range(self.batch_size):
          X_train[0].append(new_arr[i])
          X_train[1].append(new_idx[i])
          X_train[2].append(rem_idx[i])
          X_train[3].append(np.ones(self.small_maxlen))
          Y_train.append(arr[i][list(new_idx[i])+list(rem_idx[i])])

        X_train[0]=np.array(X_train[0])
        X_train[1]=np.array(X_train[1])
        X_train[2]=np.array(X_train[2])
        X_train[3]=np.array(X_train[3])
        Y_train=np.array(Y_train)
        return X_train, Y_train

class DataGeneratorEmbed(tf.keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, inp_path, indexes, model, batch_size=128 , shuffle=True):
        'Initialization'
        self.batch_size = batch_size
        self.shuffle = shuffle
        self.inp_path = inp_path
        self.model = model
        self.orig_df = pd.read_csv(inp_path)
        self.labels = np.array(self.orig_df.iloc[:,0])
        self.one_hot = np.eye(FLAGS.num_classes)[self.labels]
        self.columns = list(self.orig_df.columns)
        self.indexes = indexes
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        num_batches = int(np.floor(len(self.indexes) / self.batch_size))
        return num_batches

    def __getitem__(self, index):
        'Generate one batch of data'
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
        X, y = self.__data_generation(indexes)
        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, indexes):
        'Generates data containing batch_size samples'
        classes_one_hot = self.one_hot[indexes]
        data = self.orig_df.loc[indexes].iloc[:,1:].to_numpy()
        pred_embed = embed_pipeline(self.model, data)
        return pred_embed, classes_one_hot

class TransformerBlock(tf.keras.layers.Layer):
  """Transformer Block Attributes:

    att:
    ffn:
    layernorm1:
    layernorm2:
    dropout1:
    dropout2:
  """

  def __init__(self, embed_dim, num_heads, ff_dim, name, rate=0.1):
    super(TransformerBlock, self).__init__()
    self._name = name
    self.att = tf.keras.layers.MultiHeadAttention(
        num_heads=num_heads, key_dim=embed_dim)
    self.ffn = tf.keras.Sequential([
        tf.keras.layers.Dense(ff_dim, activation='relu'),
        tf.keras.layers.Dense(embed_dim),
    ])
    self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
    self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
    self.dropout1 = tf.keras.layers.Dropout(rate)
    self.dropout2 = tf.keras.layers.Dropout(rate)

  def call(self, inputs, training):
    attn_output = self.att(inputs, inputs)
    attn_output = self.dropout1(attn_output, training=training)
    out1 = self.layernorm1(inputs + attn_output)
    ffn_output = self.ffn(out1)
    ffn_output = self.dropout2(ffn_output, training=training)
    return self.layernorm2(out1 + ffn_output)

class TokenAndPositionEmbedding(tf.keras.layers.Layer):
  def __init__(self, maxlen, embed_dim, name='EmbLayer'):
    super(TokenAndPositionEmbedding, self).__init__()
    self._name = name
    self.embed_dim = embed_dim
    self.pos_emb = tf.keras.layers.Embedding(
        input_dim=maxlen, output_dim=embed_dim)
    self.concat = tf.keras.layers.Concatenate(axis=2)

  def call(self, x, positions_unmask, positions_mask):
    positions_unmask = self.pos_emb(positions_unmask)
    if positions_mask.shape[1]>=2:
      positions_mask = self.pos_emb(positions_mask)
    else:
      positions_mask = []
    x = tf.expand_dims(x, -1)
    x = tf.cast(x, tf.float32)
    x = self.concat([x,positions_unmask])
    return x, positions_mask

def train_METModel(
    embed_dim=128,
    num_heads=2,
    ff_dim=128,
    model_depth_enc=6,
    model_depth_dec=1,
    mask_pct=15,
    batch_size=128,
    save_path='./saved_models/'):
    indexes_trn = [i for i in range(FLAGS.train_len)]
    indexes_tst = [i for i in range(FLAGS.test_len)]

    batch_size = min(batch_size, len(indexes_trn), len(indexes_tst))

    trn_dg = DataGenerator(
      FLAGS.train_data_path, indexes_trn, mask_pct=mask_pct, batch_size=batch_size)
    tst_dg = DataGenerator(FLAGS.test_data_path,
                         indexes_tst, mask_pct=mask_pct, batch_size=batch_size)

    maxlen = trn_dg.maxlen
    small_maxlen = ((100 - mask_pct) * maxlen) // 100
    fixed_input = tf.keras.layers.Input(
        shape=(small_maxlen,), batch_size=batch_size)

    inputs = tf.keras.layers.Input(shape=(small_maxlen,), batch_size=batch_size)
    inputs_unmask_idx = tf.keras.layers.Input(
        shape=(small_maxlen,), dtype='int32', batch_size=batch_size)
    inputs_mask_idx = tf.keras.layers.Input(
        shape=(maxlen - small_maxlen,), dtype='int32', batch_size=batch_size)

    embedding_layer = TokenAndPositionEmbedding(
        maxlen, embed_dim, name='EmbeddingLayer')
    non_mask_embed, mask_pos = embedding_layer(inputs, inputs_unmask_idx,
                                        inputs_mask_idx)

    for i in range(model_depth_enc):
        transformer_block = TransformerBlock(
            embed_dim+1, num_heads, ff_dim, name='TransformerLayerEncoder_' + str(i))
        non_mask_embed = transformer_block(non_mask_embed)

    mask_embed = tf.keras.layers.Dense(1)(
        fixed_input)  # Layer to learn mask layer -- constant tensor
    mask_embed = tf.expand_dims(mask_embed, axis=1)
    mask_embed = tf.repeat(mask_embed, repeats=maxlen - small_maxlen, axis=1)
    mask_embed = tf.keras.layers.Concatenate(axis=2)([mask_embed, mask_pos])

    all_embed = tf.keras.layers.Concatenate(axis=1)([non_mask_embed, mask_embed])

    for i in range(model_depth_dec):
        transformer_block = TransformerBlock(
            embed_dim+1, num_heads, ff_dim, name='TransformerLayerDecoder_' + str(i))
        all_embed = transformer_block(all_embed)

    pred = tf.keras.layers.Dense(1)(all_embed)
    model = tf.keras.Model(
        inputs=[inputs, inputs_unmask_idx, inputs_mask_idx, fixed_input],
        outputs=pred)
    opt = tf.keras.optimizers.Adam(learning_rate=FLAGS.lr)
    model.compile(opt, 'mse', metrics=['accuracy'])
    if FLAGS.model_path == '':
        checkpoint_filepath = save_path + FLAGS.model_kw +'_' + str(
            embed_dim) + '_' + str(num_heads) + '_' + str(ff_dim) + '_' + str(
                model_depth_enc) + '_' + str(model_depth_dec) + '_' + str(mask_pct) + '_' + str(FLAGS.lr)
    else:
        checkpoint_filepath = FLAGS.model_path
    model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
        filepath=checkpoint_filepath,
        save_weights_only=True,
        monitor='val_accuracy',
        mode='max',
        save_best_only=True)
    model.summary()
    try:
        model.load_weights(checkpoint_filepath)
        print('Pre-Trained Model loaded')
    except:
        print("No model found at given path")
        exit()
    return model, maxlen

def embed_pipeline(model, inp):
    lay_stack = []
    for lay in model.layers:
        if 'EmbeddingLayer' in lay._name or 'TransformerLayerEncoder_' in lay._name:
            lay_stack.append(lay)
    r, c = inp.shape
    unmask_pos = np.array([np.arange(0, c, 1) for _ in range(r)])
    mask_pos = np.array([[] for _ in range(r)])
    embed, _ = lay_stack[0].call(inp, unmask_pos, mask_pos)
    for lay in lay_stack[1:]:
        embed = lay.call(embed, training=False)
    return embed

def get_met_embed(model, arr, idx, new_len):
    pred_embed = embed_pipeline(model, arr)
    pred_emb_train = []
    pred_emb_test = []
    for i in idx[:new_len]:
        pred_emb_train.append(pred_embed[i])
    for i in idx[new_len:]:
        pred_emb_test.append(pred_embed[i])

    pred_emb_train = np.array(pred_emb_train)
    pred_emb_test = np.array(pred_emb_test)
    return pred_emb_train, pred_emb_test

def train_and_eval_met(model, maxlen,
                       embed_dim=128, batch_size=40, save_path='./saved_models/'):
    mlp_inp = tf.keras.layers.Input(shape=(maxlen, embed_dim+1))
    mlp_layer = tf.keras.layers.Flatten()(mlp_inp)
    mlp_layer = tf.keras.layers.Dense(5040, activation='relu')(mlp_layer)
    mlp_layer = tf.keras.layers.Dense(256, activation='relu')(mlp_layer)
    mlp_pred = tf.keras.layers.Dense(10, activation='softmax')(mlp_layer)
    mlp_model = tf.keras.Model(inputs=mlp_inp, outputs=mlp_pred)
    opt = tf.keras.optimizers.Adam(learning_rate=FLAGS.lr)
    if FLAGS.model_path_linear == '':
        if 'adv' in FLAGS.model_path:
            checkpoint_filepath = save_path + FLAGS.model_kw +'_linear_adv_' + str(
                FLAGS.embed_dim) + '_' + str(FLAGS.num_heads) + '_' + str(FLAGS.ff_dim) + '_' + str(
                    FLAGS.model_depth_enc) + '_' + str(FLAGS.model_depth_dec) + '_' + str(FLAGS.mask_pct) + '_' + str(FLAGS.lr)
        else:
            checkpoint_filepath = save_path + FLAGS.model_kw +'_linear_' + str(
                FLAGS.embed_dim) + '_' + str(FLAGS.num_heads) + '_' + str(FLAGS.ff_dim) + '_' + str(
                    FLAGS.model_depth_enc) + '_' + str(FLAGS.model_depth_dec) + '_' + str(FLAGS.mask_pct) + '_' + str(FLAGS.lr)
    else:
        checkpoint_filepath = FLAGS.model_path_linear
    model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
        filepath=checkpoint_filepath,
        save_weights_only=True,
        monitor='val_accuracy',
        mode='max',
        save_best_only=True)

    mlp_model.compile(opt, 'categorical_crossentropy', metrics=['accuracy'])

    indexes_trn = [i for i in range(int(FLAGS.train_len))]
    indexes_tst = [i for i in range(int(FLAGS.test_len))]
    batch_size = min(batch_size, len(indexes_trn), len(indexes_tst))

    trn_dg = DataGeneratorEmbed(
        FLAGS.train_data_path,
        indexes_trn,
        model,
        batch_size=batch_size)
    tst_dg = DataGeneratorEmbed(
        FLAGS.test_data_path,
        indexes_tst,
        model,
        batch_size=batch_size)
    try:
        mlp_model.load_weights(checkpoint_filepath)
        print("Pre-Trained MLP model loaded from", checkpoint_filepath)
    except:
        mlp_model.fit(trn_dg, epochs=100, validation_data=tst_dg, workers=1, callbacks=[model_checkpoint_callback])
        mlp_model.load_weights(checkpoint_filepath)

    acc = mlp_model.evaluate(tst_dg)
    return acc

def main(argv: Sequence[str]) -> None:
    scope = _get_distribution_strategy_scope(FLAGS.platform, FLAGS.master)
    logging.info(
        'Train-Parms :- embed_dim %d, num_heads %d, ff_dim %d, model_depth_enc %d, model_depth_dec %d, mask_pct %d',
        FLAGS.embed_dim, FLAGS.num_heads, FLAGS.ff_dim, FLAGS.model_depth_enc,
        FLAGS.model_depth_dec, FLAGS.mask_pct)
    with scope:
        met_model, maxlen = train_METModel(
            embed_dim=FLAGS.embed_dim,
            num_heads=FLAGS.num_heads,
            ff_dim=FLAGS.ff_dim,
            model_depth_enc=FLAGS.model_depth_enc,
            model_depth_dec=FLAGS.model_depth_dec,
            mask_pct=FLAGS.mask_pct,
            batch_size=126)
        met_acc = train_and_eval_met(met_model,maxlen,FLAGS.embed_dim,batch_size=126)
        with open('./met.csv','a+') as f:
            f.write(str(FLAGS.embed_dim)+','+str(FLAGS.ff_dim)+','+str(FLAGS.num_heads)+','+str(FLAGS.model_depth_enc)+','+str(FLAGS.model_depth_dec)+','+str(FLAGS.lr)+','+str(FLAGS.mask_pct)+','+','+str(met_acc[1])+'\n')

if __name__ == '__main__':
  app.run(main)


text:
<!-- ======================================== -->
<!--    Open ADK Object Definition File   -->
<!--     Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s)     -->
<!--     All Rights Reserved                  -->
<!-- ======================================== -->
<!--    SIF 2.5 school objects                -->
<!-- ======================================== -->
<adk package="school" version="2.5" namespace="http://www.sifinfo.org/uk/infrastructure/2.x">
  <!--ContactPersonal object-->
  <object name="ContactPersonal" topic="true">
    <desc>This object describes any person created as a contact at a school, LEA, or other institution, or associated with a Learner or other Workforce person.</desc>
    <attribute name="RefId" type="Token" flags="M">
      <desc>The ID (GUID) of a person referenced as a contact. Note that this GUID may be the same GUID assigned to a LearnerPersonal and/or WorkforcePersonal object record.</desc>
    </attribute>
    <element name="PersonalInformation" type="PersonalInformation" flags="M">
      <desc>Name, demographic, address, email, and phone information for a person acting as a contact.</desc>
    </element>
  </object>
  <!--GovernanceType enum-->
  <enum name="GovernanceType">
    <value name="COMMUNITY" value="CO" desc="Community" />
    <value name="VOLUNTARY_AIDED" value="VA" desc="Voluntary Aided" />
    <value name="VOLUNTARY_CONTROLLED" value="VC" desc="Voluntary Controlled" />
    <value name="FOUNDATION" value="FO" desc="Foundation" />
    <value name="INDEPENDENT" value="IN" desc="Independent" />
    <value name="NON_MAINTAINED" value="NM" desc="Non-maintained (England only)" />
    <value name="CITY_TECHNOLOGY_COLLEGE" value="CT" desc="City Technology College (England only)" />
    <value name="ACADEMIES" value="CA" desc="Academies (England only)" />
  </enum>
  <!--GroupRole enum-->
  <enum name="GroupRole">
    <value name="HEAD_TEACHER" value="HDT" desc="Head teacher" />
    <value name="DEPUTY_HEAD" value="DHT" desc="Deputy head" />
    <value name="ASSISTANT_HEAD" value="AHT" desc="Assistant head" />
    <value name="CLASSROOM_TEACHER" value="TCH" desc="Classroom teacher" />
    <value name="ADVANCED_SKILLS_TEACHER" value="AST" desc="Advanced Skills Teacher" />
    <value name="EXCELLENT_TEACHER" value="EXL" desc="Excellent Teacher" />
    <value name="SUPPORT_STAFF" value="SUP" desc="Support staff" />
    <value name="ADVISORY_TEACHER" value="AVT" desc="Advisory Teacher" />
    <value name="EDUCATIONAL_PSYCHOLOGIST" value="EPS" desc="Educational Psychologist" />
    <value name="ADMINISTRATOR" value="ADM" desc="Administrator" />
    <value name="GOVERNOR" value="GOV" desc="Governor" />
    <value name="ACADEMIC" value="ACD" desc="Academic" />
    <value name="OTHER" value="OTH" desc="Other" />
    <value name="VOLUNTEER" value="VOL" desc="Volunteer" />
  </enum>
  <!--GroupTypeCode enum-->
  <enum name="GroupTypeCode">
    <value name="GENERIC" value="G" desc="Generic Group" />
    <value name="REGISTRATION" value="R" desc="Registration/Class Group" />
    <value name="TEACHING" value="T" desc="Teaching (course) Group" />
  </enum>
  <!--HeadTeacherInfo object-->
  <object name="HeadTeacherInfo">
    <desc>Name and title fo the school's Head Teacher.</desc>
    <element name="ContactName" type="normalizedString" flags="M">
      <desc>The name of the head Teacher.</desc>
    </element>
    <element name="ContactTitle" type="normalizedString" flags="O">
      <desc>The official title of the Head Teacher.</desc>
    </element>
  </object>
  <!--IntakeType enum-->
  <enum name="IntakeType">
    <value name="COMPREHENSIVE" value="COMP" desc="Comprehensive" />
    <value name="SELECTIVE_GRAMMER" value="SEL1" desc="Selective (Grammer)" />
    <value name="SECONDARY_MODERN" value="SEL2" desc="Secondary Modern" />
    <value name="SELECTIVE_TECH" value="SEL3" desc="Selective (Technical)" />
    <value name="RELIGIOUS_SCHOOL" value="SEL4" desc="Religious School" />
  </enum>
  <!--LAInfo object-->
  <object name="LAInfo" topic="true">
    <desc>This object contains information about a Local Authority (LA). Compare with US/Canada object: LEAInfo</desc>
    <attribute name="RefId" type="Token" flags="M">
      <desc>The GUID of the LA whose information this is.</desc>
    </attribute>
    <element name="LAId" type="Token" flags="M">
      <desc>The 3-digit LA number assigned by DfES. CBDS: L1, S1</desc>
    </element>
    <element name="LAName" type="normalizedString" flags="M">
      <desc>The LA's short name to be used for reporting purposes. Normally, the word "Council" should not be included. CBDS: L3</desc>
    </element>
    <element name="LAFullName" type="normalizedString" flags="M">
      <desc>The LA's full name. CBDS: L2</desc>
    </element>
    <element name="LAURL" type="anyURI" flags="O">
      <desc>URL for the main LA website. CBDS: L4</desc>
    </element>
    <element name="LAAddress" type="Address" flags="O">
      <desc>The LA's main address information.</desc>
    </element>
    <element name="AddressList" type="AddressList" flags="O">
      <desc>A list of the LA's other addresses, if any.</desc>
    </element>
    <element name="LAPhoneNumber" type="PhoneNumber" flags="O">
      <desc>The LA's primary phone number.</desc>
    </element>
    <element name="PhoneNumberList" type="PhoneNumberList" flags="O">
      <desc>A list of the LA's other phone number(s).</desc>
    </element>
    <element name="LAContactList" type="ContactList" flags="O">
      <desc>A list of contacts within the LA.</desc>
    </element>
  </object>
  <!--OperationalStatus enum-->
  <enum name="OperationalStatus">
    <value name="OPEN" value="1" desc="Open" />
    <value name="CLOSED" value="2" desc="Closed" />
    <value name="PROPOSED_TO_CLOSE" value="3" desc="Open, but proposed to close" />
    <value name="PROPOSED_TO_OPEN" value="4" desc="Proposed to open" />
    <value name="DEREGISTERED_AS_EY_SETTING" value="5" desc="De-registered as EY Setting" />
  </enum>
  <!--PersonPicture object-->
  <object name="PersonPicture" topic="true">
    <desc>This object contains information about the learner's picture. Compare with US/Canada object: StudentPicture</desc>
    <attribute name="PersonRefId" type="Token" flags="M">
      <desc>It is important to note that using the same GUID a person may have a LearnerPersonal record, a WorkforcePersonal record, and a ContactPersonal record all at the same time.  This same picture is applicable regardless of the associated object type(s).</desc>
    </attribute>
    <element name="SIF_RefObjectList" type="SIF_RefObjectList" flags="M">
      <desc>A list of one or more "personal" object type codes representing objects that can be requested for this person using the specified PersonRefId.</desc>
    </element>
    <element name="SchoolYear" type="GYear" flags="M">
      <desc>School year for which this enrolment is applicable, expressed as the four-digit year in which the school year ends (e.g. 2007 for the 2006/07 school year).</desc>
    </element>
    <element name="PictureSource" type="PictureSource" flags="M">
      <desc>This element defines the picture. If the Type attribute is URL, this is the location of the picture in [JPEG] format; if Type is JPEG, this is the [JPEG] image data encoded using the Base64 Content-Transfer-Encoding defined in Section 6.8 of [RFC 2045]. CBDS: 100019</desc>
    </element>
    <element name="OKToPublish" enum="YesNo" flags="O">
      <desc>Can the picture be published?</desc>
    </element>
  </object>
  <!--PhaseType enum-->
  <enum name="PhaseType">
    <value name="EARLY_YEARS" value="EY" desc="Early Years Setting" />
    <value name="MIDDLE_DEEMED_PRIMARY" value="MP" desc="Middle (Deemed Primary)" />
    <value name="MIDDLE_DEEMED_SECONDARY" value="MS" desc="Middle (Deemed Secondary)" />
    <value name="NO_ESTABLISHMENT" value="NO" desc="No Establishment (for children not on any establishment roll)" />
    <value name="NURSERY" value="NY " desc="Nursery" />
    <value name="PRU" value="PR" desc="Pupil Referral Unit (PRU)" />
    <value name="PRIMARY" value="PY " desc="Primary" />
    <value name="SPECIAL" value="SP " desc="Special" />
    <value name="SECONDARY" value="SY " desc="Secondary" />
    <value name="MULTIPLE_PHASES" value="XX" desc="Multiple phases (not Middle, Special, or PRU)" />
  </enum>
  <!--PictureSource object-->
  <object name="PictureSource">
    <attribute name="Type" enum="PictureType" flags="R">
      <desc>The way the picture is specified.</desc>
    </attribute>
  </object>
  <!--PictureType enum-->
  <enum name="PictureType">
    <value name="URL" value="URL" desc="URL" />
    <value name="JPEG" value="JPEG" desc="JPEG" />
  </enum>
  <!--ScheduleInfo object-->
  <object name="ScheduleInfo">
    <element name="TeacherList" type="TeacherList" flags="O" />
  </object>
  <!--ScheduleInfoList object-->
  <object name="ScheduleInfoList">
    <element name="ScheduleInfo" type="ScheduleInfo" flags="OR" />
  </object>
  <!--SchoolGroup object-->
  <object name="SchoolGroup" topic="true">
    <desc>This object describes a class or teaching group, including resource and time tabling information.  All groups are based upon a SchoolCourseInfo record. However, there are courses which are not based upon any subject area and likewise may not have any teachers or other staff assigned. Compare with US/Canada object:  SectionInfo</desc>
    <attribute name="RefId" type="Token" flags="M">
      <desc>The ID (GUID) that uniquely identifies this group entity. </desc>
    </attribute>
    <attribute name="SchoolGroupTypeRefId" type="Token" flags="M">
      <desc>The ID (GUID) that identifies a course upon which this group is centered. Note that this element is mandatory when GroupType is associated with a course (teaching group). </desc>
    </attribute>
    <attribute name="SchoolYear" type="GYear" flags="M">
      <desc>School year for which the group is applicable, expressed as the four-digit year in which the school year ends (e.g. 2007 for the 2006/07 school year). Where a group membership is valid across multiple years, the current year at the time of publication will be used. </desc>
    </attribute>
    <element name="LocalId" type="Token" flags="M">
      <desc>The locally-assigned (unique) identifier for this group. </desc>
    </element>
    <element name="GroupName" type="normalizedString" flags="M">
      <desc>The name associated with this group for display purposes.</desc>
    </element>
    <element name="Description" type="normalizedString" flags="O">
      <desc>A textual description.</desc>
    </element>
    <element name="ParentSchoolGroupRefId" type="Token" flags="O">
      <desc>The parent group associated with this group, if any. </desc>
    </element>
    <element name="ScheduleInfoList" type="ScheduleInfoList" flags="O">
      <desc>A list of teachers, staff, or other non-learners associated with this group.</desc>
    </element>
  </object>
  <!--SchoolGroupType object-->
  <object name="SchoolGroupType" topic="true">
    <desc>This object describes a high-level course or class grouping organised and/or taught within a school or establishment.  Note that not all courses are based upon a subject area.  One such course is "Class Group" which is the same as a homeroom or registration group. Compare with US/Canada object: SchoolCourseInfo</desc>
    <attribute name="RefId" type="Token" flags="M">
      <desc>The GUID that uniquely identifies a school group type, such as a course. </desc>
    </attribute>
    <attribute name="SchoolInfoRefId" type="Token" flags="M">
      <desc>The ID (GUID) that references the school or establishment where the course is offered or the registration group exists. </desc>
    </attribute>
    <attribute name="SchoolYear" type="GYear" flags="M">
      <desc>School year for which the information is applicable, expressed as the four-digit year in which the school year ends (e.g. 2007 for the 2006/07 school year). Where a group membership is valid across multiple years, the current year at the time of publication will be used. </desc>
    </attribute>
    <attribute name="GroupType" enum="GroupTypeCode" flags="M">
      <desc>The group type.  Teaching groups are used to teach subjects while other groups are organised for various other reasons.</desc>
    </attribute>
    <element name="Code" type="normalizedString" flags="O">
      <desc>School defined local code for the group, such as the course code, if applicable.</desc>
    </element>
    <element name="Title" type="normalizedString" flags="O">
      <desc>Title of the group.</desc>
    </element>
    <element name="Description" type="normalizedString" flags="O">
      <desc>Textual description for the group.</desc>
    </element>
    <element name="SubjectAreaList" type="SubjectAreaList" flags="O">
      <desc>Subject matter areas taught as part of the group, if any.</desc>
    </element>
  </object>
  <!--SchoolInfo object-->
  <object name="SchoolInfo" topic="true">
    <desc>This object contains basic information about a school or other educational establishment. Compare with US/Canada object with the same name.</desc>
    <attribute name="RefId" type="Token" flags="M">
      <desc>The GUID that identifies this school.</desc>
    </attribute>
    <attribute name="LAInfoRefId" type="Token" flags="M">
      <desc>The ID (GUID) that references the school district of which this school is a member.</desc>
    </attribute>
    <element name="LocalId" type="normalizedString" flags="O">
      <desc>An ID assigned by the publishing agent for this school or establishment. This may be set to any value.</desc>
    </element>
    <element name="EstablishmentId" type="Token" flags="M">
      <desc>DfES Establishment Number for this school. CBDS: S2</desc>
    </element>
    <element name="LAId" type="Token" flags="M">
      <desc>The 3-digit LA number assigned by DfES. CBDS: S1</desc>
    </element>
    <element name="SchoolName" type="normalizedString" flags="M">
      <desc>School's name as indicated on the Annual Schools Census. CBDS: S5</desc>
    </element>
    <element name="SchoolFullName" type="normalizedString" flags="O">
      <desc>School's full name as stated in the Instrument of Government. CBDS: S4</desc>
    </element>
    <element name="URN" type="Token" flags="O">
      <desc>School Unique Reference Number.  This number is an alternate to the Establishment Number. CBDS: S3</desc>
    </element>
    <element name="SchoolURL" type="Token" flags="O">
      <desc>URL for the school.</desc>
    </element>
    <element name="SchoolAddress" type="Address" flags="O">
      <desc>The school's published address.</desc>
    </element>
    <element name="AddressList" type="AddressList" flags="O">
      <desc>Other addresses associated with the school.</desc>
    </element>
    <element name="SchoolPhoneNumber" type="PhoneNumber" flags="O">
      <desc>The main phone number for this school/establishment.</desc>
    </element>
    <element name="OtherPhoneNumberList" type="PhoneNumberList" flags="O">
      <desc>A list of the school's phone numbers.</desc>
    </element>
    <element name="SchoolEmail" type="Email" flags="O">
      <desc>School's email address for general correspondence. CBDS: S24</desc>
    </element>
    <element name="SchoolContactList" type="ContactList" flags="O">
      <desc>A list of contacts at the school.</desc>
    </element>
    <element name="HeadTeacherInfo" type="HeadTeacherInfo" flags="O">
      <desc>Name and title fo the school's Head Teacher.</desc>
    </element>
    <element name="Phase" enum="PhaseType" flags="O">
      <desc>The high level code indicating the level of the educational institution. </desc>
    </element>
    <element name="SchoolType" enum="SchoolType" flags="O">
      <desc>An indication of the level of the educational institution. CBDS: S521a</desc>
    </element>
    <element name="Governance" enum="GovernanceType" flags="O">
      <desc>Governance afforded to this school. CBDS: S12</desc>
    </element>
    <element name="Intake" enum="IntakeType" flags="O">
      <desc>Intake type. CBDS: S11</desc>
    </element>
    <element name="NCYearGroupList" type="NCYearGroupList" flags="O">
      <desc>Collection of National Curriculum Year Groups offered in this school or establishment. CBDS: S9, S10</desc>
    </element>
    <element name="GenderOfEntry" enum="GenderOfEntry" flags="O">
      <desc>Gender of learners allowed for entry to school. CBDS: S8a</desc>
    </element>
    <element name="GenderSixthForm" enum="GenderOfEntry" flags="O">
      <desc>Gender of learners allowed for entry to Sixth Form. CBDS: S522</desc>
    </element>
    <element name="Boarders" enum="YesNo" flags="O">
      <desc>Indicates whether the school supports boarders or not. CBDS: S21</desc>
    </element>
    <element name="SessionsPerDay" type="unsignedInt" flags="M">
      <desc>The number of sessions in the usual school day (usually two).</desc>
    </element>
    <element name="Nursery" enum="YesNo" flags="O">
      <desc>Indicates whether the school maintains a nursery class or not. Must be NO if Phase is set to MP, MS or SY. Must be YES if Phase is set to NY or EY. CBDS: S14</desc>
    </element>
    <element name="Special" enum="YesNo" flags="O">
      <desc>Indicates whether the school has a special class/unit or not.  Must be Yes if Phase = SP.  Any details will be stored in the associated SchoolInfoDetail object. CBDS: S15</desc>
    </element>
    <element name="OperationalStatus" enum="OperationalStatus" flags="O">
      <desc>Operational condition of a school.</desc>
    </element>
  </object>
  <!--SchoolType enum-->
  <enum name="SchoolType">
    <value name="FIRST_SCHOOL_5_8" value="01" desc="First school, 5-8" />
    <value name="FIRST_SCHOOL_5_9" value="02" desc="First school, 5-9" />
    <value name="FIRST_SCHOOL_5_10" value="03" desc="First school, 5-10" />
    <value name="FIRST_AND_MIDDLE" value="04" desc="First and Middle school, 5-12" />
    <value name="MIDDLE_SCHOOL_8_12_PRI" value="05" desc="Middle school, 8-12, deemed Primary" />
    <value name="MIDDLE_SCHOOL_9_13_PRI" value="06" desc="Middle school, 9-13, deemed Primary" />
    <value name="MIDDLE_SCHOOL_9_13_SEC" value="07" desc="Middle school, 9-13, deemed Secondary" />
    <value name="MIDDLE_SCHOOL_10_13_SEC" value="08" desc="Middle school, 10-13, deemed Secondary" />
    <value name="COMP_UPPER_12_16" value="09" desc="Comprehensive Upper school, 12-15/16" />
    <value name="COMP_UPPER_12_18" value="10" desc="Comprehensive Upper school, 12-18" />
    <value name="COMP_UPPER_13_16" value="11" desc="Comprehensive Upper school, 13-16" />
    <value name="COMP_UPPER_13_18" value="12" desc="Comprehensive Upper school, 13-18" />
    <value name="INFANT_SCHOOL_5_8" value="16" desc="Infant school, 5-7/8" />
    <value name="JUNIOR_SCHOOL_7_11" value="17" desc="Junior school, 7/8-11" />
    <value name="INFANT_AND_JUNIOR" value="18" desc="Infant and Junior school, 5-11" />
    <value name="COMP_ALL_11_16" value="21" desc="Comprehensive all-through, 11-16" />
    <value name="COMP_ALL_11_18" value="22" desc="Comprehensive all-through, 11-18" />
    <value name="JUNIOR_COMP_11_13" value="25" desc="Junior Comprehensive, 11-13, automatic transfer" />
    <value name="JUNIOR_COMP_11_14" value="26" desc="Junior Comprehensive, 11-14, automatic transfer" />
    <value name="JUNIOR_COMP_11_16" value="27" desc="Junior Comprehensive, 11-16, optional transfer at 13" />
    <value name="JUNIOR_COMP_11_16_TRANS_13" value="28" desc="Junior Comprehensive, 11-16, optional transfer at 14" />
    <value name="SENIOR_COMP_13_16_TRANS_14" value="29" desc="Senior Comprehensive, 13-16, automatic transfer" />
    <value name="SENIOR_COMP_13_18_OPT" value="30" desc="Senior Comprehensive, 13-18, optional transfer" />
    <value name="SENIOR_COMP_13_18_AUTO" value="31" desc="Senior Comprehensive, 13-18, automatic transfer" />
    <value name="SENIOR_COMP_14_18_OPT" value="32" desc="Senior Comprehensive, 14-18, optional transfer" />
    <value name="SENIOR_COMP_14_18_AUTO" value="33" desc="Senior Comprehensive, 14-18, automatic transfer" />
    <value name="NON_COMP_SECOND_MODERN" value="36" desc="Non-Comprehensive Secondary - Modern" />
    <value name="NON_COMP_SECOND_GRAMMER" value="37" desc="Non-Comprehensive Secondary - Grammar" />
    <value name="NON_COMP_SECOND_TECH" value="38" desc="Non-Comprehensive Secondary - Technical" />
    <value name="NON_COMP_SECOND_OTHER" value="39" desc="Non-Comprehensive Secondary - Other" />
    <value name="MIDDLE_SCHOOL_10_14" value="41" desc="Middle school, 10-14, deemed Secondary" />
    <value name="FIRST_SCHOOL_5_7" value="42" desc="First school, 5-7;" />
    <value name="FIRST_SCHOOL_7_10" value="43" desc="First school, 7-10;" />
    <value name="COMP_UPPER_14_18" value="44" desc="Comprehensive Upper school, 14/15-18" />
    <value name="MIDDLE_SCHOOL_9_12" value="45" desc="Middle school, 9-12, deemed Primary" />
    <value name="COMP_MIDDLE_UPPER" value="46" desc="Comprehensive, Middle and Upper, 10-16" />
    <value name="CITY_TECHNOLOGY_COLLEGE" value="47" desc="City Technology College" />
    <value name="COMP_UPPER_11_16" value="48" desc="Comprehensive Upper school, 11-16" />
    <value name="ACADEMIES" value="49" desc="Academies" />
    <value name="MAINTAINED_NURSERY" value="50" desc="Maintained Nursery" />
    <value name="DIRECT_GRANT_NURSERY" value="51" desc="Direct Grant Nursery" />
  </enum>
  <!--Teacher object-->
  <object name="Teacher">
    <attribute name="WorkforcePersonalRefId" type="Token" flags="M">
      <desc>The ID (GUID) of a teacher, staff member, or other employee participating in a non-learner capacity within this group.</desc>
    </attribute>
    <element name="Role" enum="GroupRole" flags="M">
      <desc>The role associated with this person in the context of this group.</desc>
    </element>
  </object>
  <!--TeacherList object-->
  <object name="TeacherList">
    <element name="Teacher" type="Teacher" flags="MR" />
  </object>
  <!--TermInfo object-->
  <object name="TermInfo" topic="true">
    <desc>This object provides information about a term; i.e., a reportable period of time. Compare with US/Canada object: TermInfo</desc>
    <attribute name="RefId" type="Token" flags="M">
      <desc>The ID (GUID) that uniquely identifies this TermInfo entity. </desc>
    </attribute>
    <attribute name="SchoolInfoRefId" type="Token" flags="M">
      <desc>The ID (GUID) that identifies the school where the term is used. </desc>
    </attribute>
    <element name="SchoolYear" type="GYear" flags="M">
      <desc>School year for which the information is applicable, expressed as the four-digit year in which the school year ends (e.g. 2007 for the 2006/07 school year). Where a group membership is valid across multiple years, the current year at the time of publication will be used. </desc>
    </element>
    <element name="StartDate" type="date" flags="M">
      <desc>Starting date of the term. </desc>
    </element>
    <element name="EndDate" type="date" flags="M">
      <desc>Ending date of the term (CCYYMMDD). </desc>
    </element>
    <element name="Description" type="normalizedString" flags="O">
      <desc>Text-based description of the term.</desc>
    </element>
    <element name="TermCode" type="normalizedString" flags="O">
      <desc>Locally-defined code. Use 'AUT', 'SPR', or 'SUM' for a 3 term year. Otherwise specify the term number within the year. CBDS: S115</desc>
    </element>
    <element name="TermsPerYear" type="unsignedInt" flags="O">
      <desc>The number of terms in a given year (3-6). CBDS: S43</desc>
    </element>
    <element name="MarkingTerm" enum="YesNo" flags="O">
      <desc>Does this TermInfo represent a marking period?</desc>
    </element>
    <element name="SchedulingTerm" enum="YesNo" flags="O">
      <desc>Does this TermInfo represent a scheduling term?</desc>
    </element>
    <element name="AttendanceTerm" enum="YesNo" flags="O">
      <desc>Does this TermInfo represent an attendance term?</desc>
    </element>
  </object>

  <!--Lesson-->
  <object name="Lesson" topic="true">
    <attribute name="RefId" type="String" flags="R" />
    <element name="TTDayId" type="String" flags="M" />
    <element name="PeriodIndex" type="int" flags="M">
      <desc>Index of period this lesson/meeting starts</desc>
    </element>
    <element name="Type" enum="LessonType" flags="M">
      <desc>Lesson/meeting type The value here determines whether a TeachingGroupID or an NTCode is required</desc>
    </element>
    <element name="Length" type="int" flags="O">
      <desc>Length of lesson in periods (1=single, 2=double, etc). Can omit if just a single.</desc>
    </element>
    <element name="TeachingGroupRefId" type="String" flags="O">
      <desc>The Teaching Group being taught (may not be one if Type != "T") (see TeachingGroup)</desc>
    </element>
    <element name="NTCodeRef" type="String" flags="O">
      <desc>If there is no TeachingGroupRefID (see NTCode)</desc>
    </element>
    <element name="TeacherList" type="TeacherIDList" flags="O" />
    <element name="TTRoomRefId" type="String" flags="O">
      <desc>The room (or location) where this lesson is taking place (see TTRoom)</desc>
    </element>
  </object>

  <!--TeacherIDList object-->
  <object name="TeacherIDList">
    <element name="TTTeacherRefId" type="TTTeacherRefId" flags="MR" />
  </object>

  <!--TTTeacherRefId object-->
  <object name="TTTeacherRefId" datatype="String" />

  <!--LessonType-->
  <enum name="LessonType">
    <value name="T_TEACHING" value="T" desc="teaching" />
    <value name="N_NONTEACHING" value="N" desc="non-teaching" />
  </enum>

</adk>

redpajama_set_name: RedPajamaGithub


text:
import every = require( './index' );

// TESTS //

// The function returns a boolean...
{
	every( [ false, false ] ); // $ExpectType boolean
	every( [ false, true ] ); // $ExpectType boolean
	every( [ true, false ] ); // $ExpectType boolean
	every( [ true, true ] ); // $ExpectType boolean
}

// The compiler throws an error if the function is provided a value other than a collection...
{
	every( true ); // $ExpectError
	every( false ); // $ExpectError
	every( 5 ); // $ExpectError
}

// The compiler throws an error if the function is not provided one argument...
{
	every(); // $ExpectError
	every( [ true, true ], 1 ); // $ExpectError
}


text:
import { IVoteOption } from '../../services';

export interface IVoteState {
  loading: boolean;
  voteOptions: IVoteOption[];
  voting: boolean;
  error: string;
  voteOptionId: number;
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\OrderBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class RemoveExpiredCartsCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure(): void
    {
        $this
            ->setName('sylius:remove-expired-carts')
            ->setDescription('Removes carts that have been idle for a period set in `sylius_order.expiration.cart` configuration key.')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output): void
    {
        $expirationTime = $this->getContainer()->getParameter('sylius_order.cart_expiration_period');
        $output->writeln(
            sprintf('Command will remove carts that have been idle for <info>%s</info>.', $expirationTime)
        );

        $expiredCartsRemover = $this->getContainer()->get('sylius.expired_carts_remover');
        $expiredCartsRemover->remove();

        $this->getContainer()->get('sylius.manager.order')->flush();
    }
}


text:
#pragma once

#include <wtf/StdLibExtras.h>
#include "MacroAssemblerCodeRef.h"

namespace JSC {

class ExecState;
struct Instruction;

namespace LLInt {

// Tells you where to jump to if you want to return-to-throw, after you've already
// set up all information needed to throw the exception.
Instruction* returnToThrowForThrownException(ExecState*);

// Gives you a PC that you can tell the interpreter to go to, which when advanced
// between 1 and 9 slots will give you an "instruction" that threads to the
// interpreter's exception handler.
Instruction* returnToThrow(ExecState*);

// Use this when you're throwing to a call thunk.
void* callToThrow(ExecState*);

} } // namespace JSC::LLInt


text:
package com.bt.pi.core.application.activation;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

public enum ApplicationStatus {
    NOT_INITIALIZED("not_initialized"), ACTIVE("active"), CHECKING("checking"), PASSIVE("passive");

    private static final Map<String, ApplicationStatus> LOOKUP = new HashMap<String, ApplicationStatus>();

    static {
        for (ApplicationStatus keytype : EnumSet.allOf(ApplicationStatus.class))
            LOOKUP.put(keytype.getStatus(), keytype);
    }

    private String status;

    private ApplicationStatus(String aStatus) {
        status = aStatus;
    }

    public String getStatus() {
        return status;
    }

    public static ApplicationStatus get(String aStatus) {
        return LOOKUP.get(aStatus);
    }
}


text:
<?php
function categorySelectList($category_tree, $selected = NULL, $prefix = '') {
	foreach($category_tree as $category) {
		$option = '<option value="%s"%s>%s%s [%d]</option>';
		$select = ($category['ID'] == $selected) ? ' selected' : '';

		printf($option, $category['ID'], $select, $prefix, escapeHTML($category['NAME']), $category['ID']);

		if(isset($category['CHILDS'])) {
			# If there are children, call self and pass children array.
			(__FUNCTION__)($category['CHILDS'], $selected, $prefix.'– ');
		}
	}
}
?>
<?php if($FORM['INFO']): ?>

			<?php foreach($FORM['INFO'] as $message): ?>

<?=$message?>

			<?php endforeach ?>

<?php endif ?>

<form action="" method="POST">
	<input type="hidden" name="token" value="<?=$FORM['TOKEN']?>" />

<?php if($FORM['TYPE'] !== 'DELETE'): ?>

			<?=$Language->text('label_name')?>

			<input id="form_name" name="name" value="<?=escapeHTML($FORM['DATA']['NAME'])?>" required autofocus />

			<?=$Language->text('label_slug')?>

			<input id="form_slug" name="slug" value="<?=escapeHTML($FORM['DATA']['SLUG'])?>" />

			<?=$Language->text('label_category')?>

			<select id="form_category" name="category">
				<option value="">[ –– <?=$Language->text('label_category')?> –– ]</option>
				<?=categorySelectList($FORM['CATEGORY_TREE'], $FORM['DATA']['CATEGORY']);?>
			</select>

			<?=$Language->text('label_user')?>

			<select id="form_user" name="user">
				<?php $selected_user_id = $FORM['DATA']['USER'] ?? $_SESSION['USER_ID'] ?>
				<?php foreach($FORM['USER_LIST'] as $user): ?>
					<option value="<?=$user['ID']?>"<?=($selected_user_id == $user['ID']) ? ' selected' : '' ?>><?=escapeHTML($user['FULLNAME'])?> [<?=$user['USERNAME']?>]</option>
				<?php endforeach; ?>
			</select>

			<?=$Language->text('label_insert')?>

			<input id="form_time_insert" name="time_insert" placeholder="YYYY-MM-DD HH:II:SS" value="<?=escapeHTML($FORM['DATA']['TIME_INSERT'])?>" />

			<?=$Language->text('label_update')?>

			<input id="form_time_update" name="time_update" placeholder="<?=escapeHTML($FORM['DATA']['TIME_UPDATE'] ?: 'CURRENT_TIMESTAMP')?>" value="" />

				<li data-markdown="bold" class="fa fa-bold" title="<?=$Language->text('markdown_bold')?>">

				<li data-markdown="italic" class="fa fa-italic" title="<?=$Language->text('markdown_italic')?>">

				<li data-markdown="heading" class="fa fa-header" title="<?=$Language->text('markdown_heading')?>">

				<li data-markdown="link" class="fa fa-link" title="<?=$Language->text('markdown_link')?>">

				<li data-markdown="image" class="fa fa-picture-o" title="<?=$Language->text('markdown_image')?>">

				<li data-markdown="code" class="fa fa-code" title="<?=$Language->text('markdown_code')?>">

				<li data-markdown="quote" class="fa fa-quote-right" title="<?=$Language->text('markdown_quote')?>">

				<li data-markdown="list_ul" class="fa fa-list-ul" title="<?=$Language->text('markdown_list_ul')?>">

				<li data-markdown="list_ol" class="fa fa-list-ol" title="<?=$Language->text('markdown_list_ol')?>">

		<textarea id="content-editor" name="body" placeholder="[…]" required><?=escapeHTML($FORM['DATA']['BODY'])?></textarea>

			<?php foreach(getUnicodeEmoticons() as $emoticon => $explanation):?>
				<li data-emoticon="<?=$emoticon?>" title="<?=$explanation?>"><?=$emoticon?>

			<?php endforeach; ?>

		<input id="form_argv" name="argv" maxlength="250" placeholder="[ARGUMENT_ONE=foo|ARGUMENT_TWO=bar …]" value="<?=escapeHTML($FORM['DATA']['ARGV'])?>" />

<?php else: ?>

		<?=$HTML?>

<?php endif; ?>

		<?php if($FORM['TYPE'] === 'INSERT'): ?>
			<input id="insert-button" type="submit" name="insert" value="<?=$Language->text('insert')?>" />
		<?php elseif($FORM['TYPE'] === 'UPDATE'): ?>
			<input id="update-button" type="submit" name="update" value="<?=$Language->text('update')?>" />
		<?php elseif($FORM['TYPE'] === 'DELETE'): ?>
			<input id="delete-button" type="submit" name="delete" value="<?=$Language->text('delete')?>" data-text="<?=$Language->text('sure')?>" />
		<?php endif; ?>

</form>


text:
package br.odb.moonshot;

import br.odb.gameapp.ConsoleApplication;
import br.odb.gameapp.command.CommandParameterDefinition;
import br.odb.gameapp.command.UserMetaCommandLineAction;
import br.odb.libscene.GroupSector;
import br.odb.libscene.World;

public class NewFileCommand extends UserMetaCommandLineAction {
	@Override
	public String getDescription() {
		return "";
	}

	@Override
	public void run(ConsoleApplication app, String operand ) throws Exception {
		LevelEditor editor = (LevelEditor) app;
		editor.world = new World( new GroupSector( "root" ) );
	}

	@Override
	public String toString() {
		return "new-file";
	}

	@Override
	public CommandParameterDefinition[] requiredOperands() {
		return new CommandParameterDefinition[0];
	}
}


text:
'use strict';

/*
  React component containing the card
*/

import React from 'react';
import {Group} from 'react-art';
import Card from './Card.react';

export default class Deck extends React.Component {

  /**
   * @return {React.Element} the rendered element
   */
  render() {

    var deckLength = this.props.cards.length,
        index = 0,
        width = this.props.width,
        height = this.props.height;

    var cards = this.props.cards.map(e => {
      return <Card
                type={e.type}
                x={this.props.width * index + index ? this.props.margin : 0}
                y={0}
                width={width / (deckLength) - this.props.margin}
                height={height}
                key={index += 1}/>;
    });

    return (
      <Group x={this.props.x} y={this.props.y} width={width} height={height}>
        {cards}
      </Group>
    );
  }
}

Deck.propTypes = {
    cards: React.PropTypes.any.isRequired,
    margin: React.PropTypes.number,
    width: React.PropTypes.number,
    height: React.PropTypes.number,
    x: React.PropTypes.number,
    y: React.PropTypes.number
};

Deck.defaultProps = {
  cards: [],
  margin: 10,
  width: 200,
  height: 40,
  x: 0,
  y: 0
};

Deck.displayName = 'Deck';


text:
package com.codefactoring.android.backlogtracker.sync.fetchers;

import android.util.Log;

import com.codefactoring.android.backlogapi.BacklogApiClient;
import com.codefactoring.android.backlogapi.models.ChangeLog;
import com.codefactoring.android.backlogapi.models.Comment;
import com.codefactoring.android.backlogtracker.sync.models.CommentDto;
import com.codefactoring.android.backlogtracker.sync.utils.SyncUtils;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.functions.Func1;

public class CommentDataFetcher {

    private final String LOG_TAG = CommentDataFetcher.class.getSimpleName();

    final BacklogApiClient mBacklogApiClient;

    public CommentDataFetcher(BacklogApiClient backlogApiClient) {
        mBacklogApiClient = backlogApiClient;
    }

    public List<CommentDto> getCommentList(final long issueId) {
        return mBacklogApiClient.getIssueOperations().getCommentList(issueId)
                .onErrorReturn(new Func1<Throwable, List<Comment>>() {
                    @Override
                    public List<Comment> call(Throwable throwable) {
                        Log.e(LOG_TAG, "Error on getCommentList", throwable);
                        return new ArrayList<>();
                    }
                })
                .flatMapIterable(new Func1<List<Comment>, Iterable<Comment>>() {
                    @Override
                    public Iterable<Comment> call(List<Comment> comments) {
                        return comments;
                    }
                })
                .flatMap(new Func1<Comment, Observable<CommentDto>>() {
                    @Override
                    public Observable<CommentDto> call(Comment comment) {
                        final CommentDto commentDto = new CommentDto();
                        commentDto.setId(comment.getId());
                        commentDto.setIssueId(issueId);
                        commentDto.setCreatedUserId(comment.getCreatedUser().getId());
                        commentDto.setContent(
                                comment.getContent() == null || comment.getContent().isEmpty()
                                        ? transformToString(comment.getChangeLog())
                                        : comment.getContent());
                        commentDto.setCreated(SyncUtils.formatDate(comment.getCreated()));
                        commentDto.setUpdated(SyncUtils.formatDate(comment.getUpdated()));
                        return Observable.just(commentDto);
                    }
                })
                .toList()
                .toBlocking()
                .first();
    }

    private String transformToString(ChangeLog[] changeLogs) {
        final StringBuilder sb = new StringBuilder();

        for (ChangeLog changeLog : changeLogs) {
            sb.append(changeLog.getField())
                    .append(": ")
                    .append(changeLog.getOldValue())
                    .append(" -> ")
                    .append(changeLog.getNewValue())
                    .append("\n");
        }

        return sb.toString();
    }
}


text:
#include "mali_kernel_common.h"
#include "mali_osk.h"
#include "mali_uk_types.h"
#include "mali_mmu_page_directory.h"
#include "mali_memory.h"
#include "mali_l2_cache.h"

static _mali_osk_errcode_t fill_page(mali_io_address mapping, u32 data);

u32 mali_allocate_empty_page(mali_io_address *virt_addr)
{
	_mali_osk_errcode_t err;
	mali_io_address mapping;
	u32 address;

	if(_MALI_OSK_ERR_OK != mali_mmu_get_table_page(&address, &mapping)) {
		/* Allocation failed */
		MALI_DEBUG_PRINT(2, ("Mali MMU: Failed to get table page for empty pgdir\n"));
		return 0;
	}

	MALI_DEBUG_ASSERT_POINTER( mapping );

	err = fill_page(mapping, 0);
	if (_MALI_OSK_ERR_OK != err) {
		mali_mmu_release_table_page(address, mapping);
		MALI_DEBUG_PRINT(2, ("Mali MMU: Failed to zero page\n"));
		return 0;
	}

	*virt_addr = mapping;
	return address;
}

void mali_free_empty_page(u32 address, mali_io_address virt_addr)
{
	if (MALI_INVALID_PAGE != address) {
		mali_mmu_release_table_page(address, virt_addr);
	}
}

_mali_osk_errcode_t mali_create_fault_flush_pages(u32 *page_directory, mali_io_address *page_directory_mapping,
        u32 *page_table, mali_io_address *page_table_mapping,
        u32 *data_page, mali_io_address *data_page_mapping)
{
	_mali_osk_errcode_t err;

	err = mali_mmu_get_table_page(data_page, data_page_mapping);
	if (_MALI_OSK_ERR_OK == err) {
		err = mali_mmu_get_table_page(page_table, page_table_mapping);
		if (_MALI_OSK_ERR_OK == err) {
			err = mali_mmu_get_table_page(page_directory, page_directory_mapping);
			if (_MALI_OSK_ERR_OK == err) {
				fill_page(*data_page_mapping, 0);
				fill_page(*page_table_mapping, *data_page | MALI_MMU_FLAGS_DEFAULT);
				fill_page(*page_directory_mapping, *page_table | MALI_MMU_FLAGS_PRESENT);
				MALI_SUCCESS;
			}
			mali_mmu_release_table_page(*page_table, *page_table_mapping);
			*page_table = MALI_INVALID_PAGE;
		}
		mali_mmu_release_table_page(*data_page, *data_page_mapping);
		*data_page = MALI_INVALID_PAGE;
	}
	return err;
}

void mali_destroy_fault_flush_pages(u32 *page_directory, mali_io_address *page_directory_mapping,
                                    u32 *page_table, mali_io_address *page_table_mapping,
                                    u32 *data_page, mali_io_address *data_page_mapping)
{
	if (MALI_INVALID_PAGE != *page_directory) {
		mali_mmu_release_table_page(*page_directory, *page_directory_mapping);
		*page_directory = MALI_INVALID_PAGE;
		*page_directory_mapping = NULL;
	}

	if (MALI_INVALID_PAGE != *page_table) {
		mali_mmu_release_table_page(*page_table, *page_table_mapping);
		*page_table = MALI_INVALID_PAGE;
		*page_table_mapping = NULL;
	}

	if (MALI_INVALID_PAGE != *data_page) {
		mali_mmu_release_table_page(*data_page, *data_page_mapping);
		*data_page = MALI_INVALID_PAGE;
		*data_page_mapping = NULL;
	}
}

static _mali_osk_errcode_t fill_page(mali_io_address mapping, u32 data)
{
	int i;
	MALI_DEBUG_ASSERT_POINTER( mapping );

	for(i = 0; i < MALI_MMU_PAGE_SIZE/4; i++) {
		_mali_osk_mem_iowrite32_relaxed( mapping, i * sizeof(u32), data);
	}
	_mali_osk_mem_barrier();
	MALI_SUCCESS;
}

_mali_osk_errcode_t mali_mmu_pagedir_map(struct mali_page_directory *pagedir, u32 mali_address, u32 size)
{
	const int first_pde = MALI_MMU_PDE_ENTRY(mali_address);
	const int last_pde = MALI_MMU_PDE_ENTRY(mali_address + size - 1);
	_mali_osk_errcode_t err;
	mali_io_address pde_mapping;
	u32 pde_phys;
	int i;

	if (last_pde < first_pde) {
		MALI_ERROR(_MALI_OSK_ERR_INVALID_ARGS);
	}

	for(i = first_pde; i <= last_pde; i++) {
		if(0 == (_mali_osk_mem_ioread32(pagedir->page_directory_mapped, i*sizeof(u32)) & MALI_MMU_FLAGS_PRESENT)) {
			/* Page table not present */
			MALI_DEBUG_ASSERT(0 == pagedir->page_entries_usage_count[i]);
			MALI_DEBUG_ASSERT(NULL == pagedir->page_entries_mapped[i]);

			err = mali_mmu_get_table_page(&pde_phys, &pde_mapping);
			if(_MALI_OSK_ERR_OK != err) {
				MALI_PRINT_ERROR(("Failed to allocate page table page.\n"));
				return err;
			}
			pagedir->page_entries_mapped[i] = pde_mapping;

			/* Update PDE, mark as present */
			_mali_osk_mem_iowrite32_relaxed(pagedir->page_directory_mapped, i*sizeof(u32),
			                                pde_phys | MALI_MMU_FLAGS_PRESENT);

			MALI_DEBUG_ASSERT(0 == pagedir->page_entries_usage_count[i]);
			pagedir->page_entries_usage_count[i] = 1;
		} else {
			pagedir->page_entries_usage_count[i]++;
		}
	}
	_mali_osk_write_mem_barrier();

	MALI_SUCCESS;
}

MALI_STATIC_INLINE void mali_mmu_zero_pte(mali_io_address page_table, u32 mali_address, u32 size)
{
	int i;
	const int first_pte = MALI_MMU_PTE_ENTRY(mali_address);
	const int last_pte = MALI_MMU_PTE_ENTRY(mali_address + size - 1);

	for (i = first_pte; i <= last_pte; i++) {
		_mali_osk_mem_iowrite32_relaxed(page_table, i * sizeof(u32), 0);
	}
}

_mali_osk_errcode_t mali_mmu_pagedir_unmap(struct mali_page_directory *pagedir, u32 mali_address, u32 size)
{
	const int first_pde = MALI_MMU_PDE_ENTRY(mali_address);
	const int last_pde = MALI_MMU_PDE_ENTRY(mali_address + size - 1);
	u32 left = size;
	int i;
	mali_bool pd_changed = MALI_FALSE;
	u32 pages_to_invalidate[3]; /* hard-coded to 3: max two pages from the PT level plus max one page from PD level */
	u32 num_pages_inv = 0;
	mali_bool invalidate_all = MALI_FALSE; /* safety mechanism in case page_entries_usage_count is unreliable */

	/* For all page directory entries in range. */
	for (i = first_pde; i <= last_pde; i++) {
		u32 size_in_pde, offset;

		MALI_DEBUG_ASSERT_POINTER(pagedir->page_entries_mapped[i]);
		MALI_DEBUG_ASSERT(0 != pagedir->page_entries_usage_count[i]);

		/* Offset into page table, 0 if mali_address is 4MiB aligned */
		offset = (mali_address & (MALI_MMU_VIRTUAL_PAGE_SIZE - 1));
		if (left < MALI_MMU_VIRTUAL_PAGE_SIZE - offset) {
			size_in_pde = left;
		} else {
			size_in_pde = MALI_MMU_VIRTUAL_PAGE_SIZE - offset;
		}

		pagedir->page_entries_usage_count[i]--;

		/* If entire page table is unused, free it */
		if (0 == pagedir->page_entries_usage_count[i]) {
			u32 page_phys;
			void *page_virt;
			MALI_DEBUG_PRINT(4, ("Releasing page table as this is the last reference\n"));
			/* last reference removed, no need to zero out each PTE  */

			page_phys = MALI_MMU_ENTRY_ADDRESS(_mali_osk_mem_ioread32(pagedir->page_directory_mapped, i*sizeof(u32)));
			page_virt = pagedir->page_entries_mapped[i];
			pagedir->page_entries_mapped[i] = NULL;
			_mali_osk_mem_iowrite32_relaxed(pagedir->page_directory_mapped, i*sizeof(u32), 0);

			mali_mmu_release_table_page(page_phys, page_virt);
			pd_changed = MALI_TRUE;
		} else {
			MALI_DEBUG_ASSERT(num_pages_inv < 2);
			if (num_pages_inv < 2) {
				pages_to_invalidate[num_pages_inv] = mali_page_directory_get_phys_address(pagedir, i);
				num_pages_inv++;
			} else {
				invalidate_all = MALI_TRUE;
			}

			/* If part of the page table is still in use, zero the relevant PTEs */
			mali_mmu_zero_pte(pagedir->page_entries_mapped[i], mali_address, size_in_pde);
		}

		left -= size_in_pde;
		mali_address += size_in_pde;
	}
	_mali_osk_write_mem_barrier();

	/* L2 pages invalidation */
	if (MALI_TRUE == pd_changed) {
		MALI_DEBUG_ASSERT(num_pages_inv < 3);
		if (num_pages_inv < 3) {
			pages_to_invalidate[num_pages_inv] = pagedir->page_directory;
			num_pages_inv++;
		} else {
			invalidate_all = MALI_TRUE;
		}
	}

	if (invalidate_all) {
		mali_l2_cache_invalidate_all();
	} else {
		mali_l2_cache_invalidate_all_pages(pages_to_invalidate, num_pages_inv);
	}

	MALI_SUCCESS;
}

struct mali_page_directory *mali_mmu_pagedir_alloc(void)
{
	struct mali_page_directory *pagedir;

	pagedir = _mali_osk_calloc(1, sizeof(struct mali_page_directory));
	if(NULL == pagedir) {
		return NULL;
	}

	if(_MALI_OSK_ERR_OK != mali_mmu_get_table_page(&pagedir->page_directory, &pagedir->page_directory_mapped)) {
		_mali_osk_free(pagedir);
		return NULL;
	}

	/* Zero page directory */
	fill_page(pagedir->page_directory_mapped, 0);

	return pagedir;
}

void mali_mmu_pagedir_free(struct mali_page_directory *pagedir)
{
	const int num_page_table_entries = sizeof(pagedir->page_entries_mapped) / sizeof(pagedir->page_entries_mapped[0]);
	int i;

	/* Free referenced page tables and zero PDEs. */
	for (i = 0; i < num_page_table_entries; i++) {
		if (pagedir->page_directory_mapped && (_mali_osk_mem_ioread32(pagedir->page_directory_mapped, sizeof(u32)*i) & MALI_MMU_FLAGS_PRESENT)) {
			u32 phys = _mali_osk_mem_ioread32(pagedir->page_directory_mapped, i*sizeof(u32)) & ~MALI_MMU_FLAGS_MASK;
			_mali_osk_mem_iowrite32_relaxed(pagedir->page_directory_mapped, i * sizeof(u32), 0);
			mali_mmu_release_table_page(phys, pagedir->page_entries_mapped[i]);
		}
	}
	_mali_osk_write_mem_barrier();

	/* Free the page directory page. */
	mali_mmu_release_table_page(pagedir->page_directory, pagedir->page_directory_mapped);

	_mali_osk_free(pagedir);
}

void mali_mmu_pagedir_update(struct mali_page_directory *pagedir, u32 mali_address, u32 phys_address, u32 size, u32 permission_bits)
{
	u32 end_address = mali_address + size;

	/* Map physical pages into MMU page tables */
	for ( ; mali_address < end_address; mali_address += MALI_MMU_PAGE_SIZE, phys_address += MALI_MMU_PAGE_SIZE) {
		MALI_DEBUG_ASSERT_POINTER(pagedir->page_entries_mapped[MALI_MMU_PDE_ENTRY(mali_address)]);
		_mali_osk_mem_iowrite32_relaxed(pagedir->page_entries_mapped[MALI_MMU_PDE_ENTRY(mali_address)],
		                                MALI_MMU_PTE_ENTRY(mali_address) * sizeof(u32),
		                                phys_address | permission_bits);
	}
}

u32 mali_page_directory_get_phys_address(struct mali_page_directory *pagedir, u32 index)
{
	return (_mali_osk_mem_ioread32(pagedir->page_directory_mapped, index*sizeof(u32)) & ~MALI_MMU_FLAGS_MASK);
}

/* For instrumented */
struct dump_info {
	u32 buffer_left;
	u32 register_writes_size;
	u32 page_table_dump_size;
	u32 *buffer;
};

static _mali_osk_errcode_t writereg(u32 where, u32 what, const char *comment, struct dump_info *info)
{
	if (NULL != info) {
		info->register_writes_size += sizeof(u32)*2; /* two 32-bit words */

		if (NULL != info->buffer) {
			/* check that we have enough space */
			if (info->buffer_left < sizeof(u32)*2) MALI_ERROR(_MALI_OSK_ERR_NOMEM);

			*info->buffer = where;
			info->buffer++;

			*info->buffer = what;
			info->buffer++;

			info->buffer_left -= sizeof(u32)*2;
		}
	}

	MALI_SUCCESS;
}

static _mali_osk_errcode_t mali_mmu_dump_page(mali_io_address page, u32 phys_addr, struct dump_info * info)
{
	if (NULL != info) {
		/* 4096 for the page and 4 bytes for the address */
		const u32 page_size_in_elements = MALI_MMU_PAGE_SIZE / 4;
		const u32 page_size_in_bytes = MALI_MMU_PAGE_SIZE;
		const u32 dump_size_in_bytes = MALI_MMU_PAGE_SIZE + 4;

		info->page_table_dump_size += dump_size_in_bytes;

		if (NULL != info->buffer) {
			if (info->buffer_left < dump_size_in_bytes) MALI_ERROR(_MALI_OSK_ERR_NOMEM);

			*info->buffer = phys_addr;
			info->buffer++;

			_mali_osk_memcpy(info->buffer, page, page_size_in_bytes);
			info->buffer += page_size_in_elements;

			info->buffer_left -= dump_size_in_bytes;
		}
	}

	MALI_SUCCESS;
}

static _mali_osk_errcode_t dump_mmu_page_table(struct mali_page_directory *pagedir, struct dump_info * info)
{
	MALI_DEBUG_ASSERT_POINTER(pagedir);
	MALI_DEBUG_ASSERT_POINTER(info);

	if (NULL != pagedir->page_directory_mapped) {
		int i;
		const int num_page_table_entries = sizeof(pagedir->page_entries_mapped) / sizeof(pagedir->page_entries_mapped[0]);
		MALI_CHECK_NO_ERROR(
		    mali_mmu_dump_page(pagedir->page_directory_mapped, pagedir->page_directory, info)
		);

		for (i = 0; i < num_page_table_entries; i++)
		{
			if (NULL != pagedir->page_entries_mapped[i])
			{
				MALI_CHECK_NO_ERROR(
				    mali_mmu_dump_page(pagedir->page_entries_mapped[i],
				                       _mali_osk_mem_ioread32(pagedir->page_directory_mapped,
				                               i * sizeof(u32)) & ~MALI_MMU_FLAGS_MASK, info)
				);
			}
		}
	}

	MALI_SUCCESS;
}

static _mali_osk_errcode_t dump_mmu_registers(struct mali_page_directory *pagedir, struct dump_info * info)
{
	MALI_CHECK_NO_ERROR(writereg(0x00000000, pagedir->page_directory,
	                             "set the page directory address", info));
	MALI_CHECK_NO_ERROR(writereg(0x00000008, 4, "zap???", info));
	MALI_CHECK_NO_ERROR(writereg(0x00000008, 0, "enable paging", info));
	MALI_SUCCESS;
}

_mali_osk_errcode_t _mali_ukk_query_mmu_page_table_dump_size( _mali_uk_query_mmu_page_table_dump_size_s *args )
{
	struct dump_info info = { 0, 0, 0, NULL };
	struct mali_session_data * session_data;

	MALI_DEBUG_ASSERT_POINTER(args);
	MALI_CHECK_NON_NULL(args->ctx, _MALI_OSK_ERR_INVALID_ARGS);

	session_data = (struct mali_session_data *)(args->ctx);

	MALI_CHECK_NO_ERROR(dump_mmu_registers(session_data->page_directory, &info));
	MALI_CHECK_NO_ERROR(dump_mmu_page_table(session_data->page_directory, &info));
	args->size = info.register_writes_size + info.page_table_dump_size;
	MALI_SUCCESS;
}

_mali_osk_errcode_t _mali_ukk_dump_mmu_page_table( _mali_uk_dump_mmu_page_table_s * args )
{
	struct dump_info info = { 0, 0, 0, NULL };
	struct mali_session_data * session_data;

	MALI_DEBUG_ASSERT_POINTER(args);
	MALI_CHECK_NON_NULL(args->ctx, _MALI_OSK_ERR_INVALID_ARGS);
	MALI_CHECK_NON_NULL(args->buffer, _MALI_OSK_ERR_INVALID_ARGS);

	session_data = (struct mali_session_data *)(args->ctx);

	info.buffer_left = args->size;
	info.buffer = args->buffer;

	args->register_writes = info.buffer;
	MALI_CHECK_NO_ERROR(dump_mmu_registers(session_data->page_directory, &info));

	args->page_table_dump = info.buffer;
	MALI_CHECK_NO_ERROR(dump_mmu_page_table(session_data->page_directory, &info));

	args->register_writes_size = info.register_writes_size;
	args->page_table_dump_size = info.page_table_dump_size;

	MALI_SUCCESS;
}


text:
var os = require('os');
var path = require('path');
var Q = require('q');
var fs = require('fs');
var _ = require('lodash');
var should = require('should');

var fsUtil = require('../lib/utils/fs');
var Book = require('../').Book;
var LOG_LEVELS = require('../').LOG_LEVELS;

require("./assertions");

var BOOKS = {};
var TMPDIR = os.tmpdir();

// Generate and return a book
function generateBook(bookId, test, opts) {
    opts = _.defaults(opts || {}, {
        prepare: function() {}
    });

    return parseBook(bookId, test)
    .then(function(book) {

        return Q(opts.prepare(book))
        .then(function() {
            return book.generate(test);
        })
        .thenResolve(book);
    });
}

// Generate and return a book
function parseBook(bookId, test) {
    test = test || "website";
    BOOKS[bookId] = BOOKS[bookId] || {};
    if (BOOKS[bookId][test]) return Q(BOOKS[bookId][test]);

    BOOKS[bookId][test] = new Book(path.resolve(__dirname, "books", bookId), {
        logLevel: LOG_LEVELS.DISABLED,
        config: {
            output: path.resolve(TMPDIR, bookId+"-"+test)
        }
    });

    return BOOKS[bookId][test].parse()
    .then(function() {
        return BOOKS[bookId][test];
    });
}

global.books = {
    parse: parseBook,
    generate: generateBook
};

// Cleanup all tests
after(function() {
    return _.chain(BOOKS)
        .map(function(types, bookId) {
            return _.values(types);
        })
        .flatten()
        .reduce(function(prev, book) {
            return prev.then(function() {
                return fsUtil.remove(book.options.output);
            })
        }, Q())
        .value();
});


text:
@auth.requires_login()
def index():
    return locals()

@auth.requires_login()
def orders():
    return locals()

@auth.requires_login()
def address():
    pass

@auth.requires_login()
def select_address():
    addresses = db(db.address.user_id == auth.user.id).select()

    adrs = []
    for address in addresses:
        adrs.append(address.address+', '+str(address.adr_number))

    form = SQLFORM.factory(
        Field('address', requires=IS_IN_SET(adrs))
        )
    if form.accepts(request.vars):
        session.address = form.vars.address
        redirect(URL('default', 'buy'))

    button = A(T('New address'), _href=URL('create_address'))
    return dict(addresses=addresses, button=button, form=form)

@auth.requires_login()
def create_address():
    db.address.user_id.default = auth.user.id
    db.address.user_id.readable = db.address.user_id.writable = False

    form = SQLFORM(db.address)
    if form.process().accepted:
        if session.cart and session.balance != 0:
            redirect(URL('default', 'select_address'))
        else:
            redirect(URL('default', 'index'))
    return dict(form=form)

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    http://..../[app]/default/user/manage_users (requires membership in
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())

@cache.action()
def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request, db)


text:
================
Data Structures
================

Module: ``polygraphy.comparator``

.. automodule:: polygraphy.comparator.struct


text:
package xyz.upperlevel.uppercore.board;

import lombok.Getter;
import org.bukkit.entity.Player;
import xyz.upperlevel.uppercore.config.ConfigConstructor;
import xyz.upperlevel.uppercore.config.ConfigProperty;
import xyz.upperlevel.uppercore.placeholder.PlaceholderRegistry;
import xyz.upperlevel.uppercore.placeholder.PlaceholderValue;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * This class represents an implementation of the BoardModel that supports config loading
 * and uses placeholders for both title and lines.
 */
public class SimpleBoardModel implements BoardModel {
    @Getter
    private PlaceholderValue<String> title;

    @Getter
    private List<PlaceholderValue<String>> lines;

    @Getter
    private int updateInterval;

    @ConfigConstructor
    public SimpleBoardModel(
            @ConfigProperty("title") PlaceholderValue<String> title,
            @ConfigProperty("lines") List<PlaceholderValue<String>> lines,
            @ConfigProperty("update-interval") Optional<Integer> updateInterval
    ) {
        this.title = title;
        this.lines = lines;
        updateInterval.ifPresent(value -> this.updateInterval = value);
    }

    @Override
    public void apply(Board board, Player player, PlaceholderRegistry<?> placeholders) {
        board.setTitle(title.resolve(player, placeholders));
        board.setLines(
                lines.stream()
                        .map(line -> line.resolve(player, placeholders))
                        .collect(Collectors.toList())
        );
    }
}


text:
> Returns true if a filepath is a windows UNC file path.

## Install

Install with [npm](https://www.npmjs.com/):

```sh
$ npm install --save is-unc-path
```

## Usage

```js
var isUncPath = require('is-unc-path');
```

**true**

Returns true for windows UNC paths:

```js
isUncPath('\\/foo/bar');
isUncPath('\\\\foo/bar');
isUncPath('\\\\foo\\admin$');
isUncPath('\\\\foo\\admin$\\system32');
isUncPath('\\\\foo\\temp');
isUncPath('\\\\/foo/bar');
isUncPath('\\\\\\/foo/bar');
```

**false**

Returns false for non-UNC paths:

```js
isUncPath('/foo/bar');
isUncPath('/');
isUncPath('/foo');
isUncPath('/foo/');
isUncPath('c:');
isUncPath('c:.');
isUncPath('c:./');
isUncPath('c:./file');
isUncPath('c:/');
isUncPath('c:/file');
```

**Customization**

Use `.source` to use the regex as a component of another regex:

```js
var myRegex = new RegExp(isUncPath.source + 'foo');
```

**[Rules for UNC paths](http://resources.esri.com/help/9.3/ArcGISDesktop/com/Gp_ToolRef/sharing_tools_and_toolboxes/pathnames_explained_colon_absolute_relative_unc_and_url.htm)**

* The computer name is always preceded by a double backward-slash (`\\`).
* UNC paths cannot contain a drive letter (such as `D:`)

## Release history

### v1.0.0 - 2017-07-12

**Changes**

* now throws a `TypeError` if value is not a string

## About

### Related projects

* [is-absolute](https://www.npmjs.com/package/is-absolute): Polyfill for node.js `path.isAbolute`. Returns true if a file path is absolute. | [homepage](https://github.com/jonschlinkert/is-absolute "Polyfill for node.js `path.isAbolute`. Returns true if a file path is absolute.")
* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet")
* [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.")

### Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).

### Building docs

_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_

To generate the readme, run the following command:

```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```

### Running tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

```sh
$ npm install && npm test
```

### Author

**Jon Schlinkert**

* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)

### License

Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).

***

_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 13, 2017._


text:
package hyweb.jo.db;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import hyweb.jo.type.JOTypes;
import hyweb.jo.IJOResource;
import hyweb.jo.org.json.JSONObject;

/**
 * @author william
 * @param <M> 使用的model
 */
public interface IDB<M> extends IJOResource {

    public Object action(M mq) throws Exception;

    public Connection connection() throws SQLException;

    public M row(String sql, Object... params) throws Exception;

    public List<M> rows(String sql, Object... params) throws Exception;

    public Object fun(String sql, Object... params) throws Exception;

    public long execute(String sql, Object... params) throws Exception;

    public int[] batch(String sql, List<Object[]> data) throws Exception;

    public String catalog();

    public String schema();

    public String database();

    public JOTypes types();

    public String to_alias(String text);

    public String to_short(String text);

    public String base();

    public void shutdown() throws Exception;

    public String status();

    public JSONObject cfg();

}


text:
package render

import "net/http"

type Data struct {
	ContentType string
	Data        []byte
}

func (r Data) Render(w http.ResponseWriter) error {
	if len(r.ContentType) > 0 {
		w.Header()["Content-Type"] = []string{r.ContentType}
	}
	w.Write(r.Data)
	return nil
}


text:
layout: post
title: Factoring Binomials Raised to a Power of n
tags: [Math, Algebra]
redirect_from:
  - /blog/2008/01/factoring-binomials-raised-to-power-of.html
---

Factoring binomials raised to a particular power can be done easily when you follow a few patterns. We'll use the following binomial to demonstrate these patterns: (2a - b)3. I'm going to do this the long way to illustrate the mechanics.

The first pattern has to do with the power the binomial is raised to. The factored form will first have the original terms multiplied by each other to form a new term. This new term will be added to itself the same number of times as the power of the unfactored binomial plus one; in this example it will be 4 (3 + 1). Since the operation in the unfactored binomial is subtraction the second term, b, will be negative.

(2a)(-b) + (2a)(-b) + (2a)(-b) + (2a)(-b)

The next pattern involves the coefficients. The coefficients for each term in the factored binomial match a row in Pascal's Triangle. The row number we want in Pascal's Triangle is the power the unfactored binomial was raised too (With the first row in the triangle being zero). So in this example the binomial is raised to the 3rd power and the coefficients will match the values in row 3 of Pascal's Triangle: 1, 3, 3 and 1 in that order.

1(2a)(-b) + 3(2a)(-b) + 3(2a)(-b) + 1(2a)(-b)

The next pattern involves the powers of the terms. The first term in the original unfactored binomial, 2a, starts with the power of the original unfactored binomial and decreases by one, in the factored form. The second term in the original unfactored binomial, b, starts with a power of zero and increases by one, in the factored form.

1(2a)3(-b)0 + 3(2a)2(-b)1 + 3(2a)1(-b)2 + 1(2a)0(-b)3

Now the factored form can be reduced. First, if the terms in the unfactored binomial are subtracted, every other operation in the factored binomial will be subtraction. This occurs because the power determines the sign of the term. Negative terms raised to an even number will be positive (IE: -22 == -2 * -2 == 4) and negative terms raised to an odd power will remain negative (IE: -23 == -2 * -2 * -2 == -8). The pattern ends up being the first first operation is subtraction, the second is addition and so on.

1(2a)3(b)0 - 3(2a)2(b)1 + 3(2a)1(b)2 - 1(2a)0(b)3

Now reduce the terms:

8a3 - 12a2b + 6ab2 - b3

So a binomial raised to the third power, (a + b)3, will follow this pattern:

a3 + 3a2b + 3ab2 + b3

The following script will factor out binomials (at least to a certain degree):

( <INPUT class=TermInput id=TermA> <SELECT class=TermInput id=Operator> <OPTION value=+ selected>+</OPTION> <OPTION value=->-</OPTION></SELECT> <INPUT class=TermInput id=TermB> )
<SELECT class=Power id=Power> <OPTION value=0 selected>0</OPTION> <OPTION value=1>1</OPTION> <OPTION value=2>2</OPTION> <OPTION value=3>3</OPTION> <OPTION value=4>4</OPTION> <OPTION value=5>5</OPTION> <OPTION value=6>6</OPTION> <OPTION value=7>7</OPTION> <OPTION value=8>8</OPTION> <OPTION value=9>9</OPTION></SELECT>
  <INPUT onclick="FactorCubedBinomial();return false;" type=submit value="Factor Me">

Unfactored

Factored

Reduced


text:
Run the following commands *in an administrator console*:

```
choco install ccleaner
```


text:
#include <QThread>

class FFTThread : public QThread
{
    Q_OBJECT
public:
    explicit FFTThread(QObject *parent = 0);
    void run();

signals:

public slots:

};

#endif // FFTTHREAD_H


text:
package io.apiman.gateway.engine;

import io.apiman.gateway.engine.async.IAsyncResultHandler;
import io.apiman.gateway.engine.beans.ApiRequest;
import io.apiman.gateway.engine.beans.exceptions.ConnectorException;

/**
 * Interface implemented by connectors to back end systems.  The engine uses
 * a connector to invoke a back end system on behalf of a managed API.
 * All connectors are expected to do their work asynchronously.
 *
 * @author eric.wittmann@redhat.com
 */
public interface IApiConnector {

    /**
     * Invokes the back-end system.
     *
     * @param request The inbound API request
     * @param handler An async handler to receive the API connection response (or a connection error if one occurs)
     * @return A connection used by caller to pass data to the back-end
     * @throws ConnectorException If a connection error occurs
     */
    IApiConnection connect(ApiRequest request, IAsyncResultHandler<IApiConnectionResponse> handler) throws ConnectorException;
}


text:
title: Plugins
taxonomy:
    category: docs
process:
    twig: true
---

![Grav Admin Plugins](plugins.png)

The **Plugins** area of the admin is where you can go to manage your plugins, add new ones, remove existing ones, and quickly access links to documentation and other information.

In this page, we will explore this area of the admin in detail, including how to active and deactivate installed plugins, and add new ones with ease.

### Controls

![Grav Admin Plugins](plugins_1.png)

The **Controls** area at the top of the page give you access to the ability to add new plugins, as well as check for updates for existing ones.

![Grav Admin Plugins](plugins_2.png)

The  Add button takes you to a page listing all of the currently-available Grav plugins, enabling you to view their information and install them by selecting the  Install button to the right of the plugin.

>>>>> The  icon indicates that the plugin is created and supported by the Grav team. Plugins without this icon were created by third-party developers.

### Installed Plugins

![Grav Admin Plugins](plugins_4.png)

This area of the Plugins administrator gives you the ability to see, at a glance, which plugins are presently installed on your Grav site. Additionally, you can enable and disable these plugins by selecting the  toggle icon to the right of each plugin.

![Grav Admin Plugins](plugins_3.png)

Upon selecting the  chevron icon will give you more information about the plugin, including its author, project home page and bug tracker, as well as its license and a brief description. You can also quickly access the plugin's readme file for additional information and usage guide.