text:
namespace kaldi {

bool ContextDependency::Compute(const std::vector<int32> &phoneseq,
                                int32 pdf_class, int32 *pdf_id) const {
  KALDI_ASSERT(static_cast<int32>(phoneseq.size()) == N_);
  EventType event_vec;
  event_vec.reserve(N_ + 1);
  event_vec.push_back(
      std::make_pair(static_cast<EventKeyType>(kPdfClass),  // -1
                     static_cast<EventValueType>(pdf_class)));
  KALDI_COMPILE_TIME_ASSERT(kPdfClass < 0);  // or it would not be sorted.
  for (int32 i = 0; i < N_; i++) {
    event_vec.push_back(
        std::make_pair(static_cast<EventKeyType>(i),
                       static_cast<EventValueType>(phoneseq[i])));
    KALDI_ASSERT(static_cast<EventAnswerType>(phoneseq[i]) != -1);  // >=0 ?
  }
  KALDI_ASSERT(pdf_id != NULL);
  return to_pdf_->Map(event_vec, pdf_id);
}

ContextDependency *GenRandContextDependency(const std::vector<int32> &phone_ids,
                                            bool ensure_all_covered,
                                            std::vector<int32> *hmm_lengths) {
  KALDI_ASSERT(IsSortedAndUniq(phone_ids));
  int32 num_phones = phone_ids.size();
  int32 num_stats =
      1 + (Rand() % 15) * (Rand() % 15);  // up to 14^2 + 1 separate stats.
  int32 N = 2 + Rand() % 3;               // 2, 3 or 4.
  int32 P = Rand() % N;
  float ctx_dep_prob = 0.7 + 0.3 * RandUniform();
  int32 max_phone = *std::max_element(phone_ids.begin(), phone_ids.end());
  hmm_lengths->clear();
  hmm_lengths->resize(max_phone + 1, -1);
  std::vector<bool> is_ctx_dep(max_phone + 1);

  for (int32 i = 0; i <= max_phone; i++) {
    (*hmm_lengths)[i] = 1 + Rand() % 3;
    is_ctx_dep[i] = (RandUniform() < ctx_dep_prob);  // true w.p. ctx_dep_prob.
  }
  for (size_t i = 0; i < (size_t)num_phones; i++) {
    KALDI_VLOG(2) << "For idx = " << i
                  << ", (phone_id, hmm_length, is_ctx_dep) == "
                  << (phone_ids[i]) << " " << ((*hmm_lengths)[phone_ids[i]])
                  << " " << (is_ctx_dep[phone_ids[i]]);
  }
  // Generate rand stats.
  BuildTreeStatsType stats;
  size_t dim = 3 + Rand() % 20;
  GenRandStats(dim, num_stats, N, P, phone_ids, *hmm_lengths, is_ctx_dep,
               ensure_all_covered, &stats);

  // Now build the tree.

  Questions qopts;
  int32 num_quest = Rand() % 10, num_iters = rand() % 5;
  qopts.InitRand(stats, num_quest, num_iters,
                 kAllKeysUnion);  // This was tested in build-tree-utils-test.cc

  float thresh = 100.0 * RandUniform();

  EventMap *tree = NULL;
  std::vector<std::vector<int32> > phone_sets(phone_ids.size());
  for (size_t i = 0; i < phone_ids.size(); i++)
    phone_sets[i].push_back(phone_ids[i]);
  std::vector<bool> share_roots(phone_sets.size(), true),
      do_split(phone_sets.size(), true);

  tree = BuildTree(qopts, phone_sets, *hmm_lengths, share_roots, do_split,
                   stats, thresh, 1000, 0.0, P);
  DeleteBuildTreeStats(&stats);
  return new ContextDependency(N, P, tree);
}

ContextDependency *GenRandContextDependencyLarge(
    const std::vector<int32> &phone_ids, int N, int P, bool ensure_all_covered,
    std::vector<int32> *hmm_lengths) {
  KALDI_ASSERT(IsSortedAndUniq(phone_ids));
  int32 num_phones = phone_ids.size();
  int32 num_stats = 3000;  // each is a separate context.
  float ctx_dep_prob = 0.9;
  KALDI_ASSERT(num_phones > 0);
  hmm_lengths->clear();
  int32 max_phone = *std::max_element(phone_ids.begin(), phone_ids.end());
  hmm_lengths->resize(max_phone + 1, -1);
  std::vector<bool> is_ctx_dep(max_phone + 1);

  for (int32 i = 0; i <= max_phone; i++) {
    (*hmm_lengths)[i] = 1 + Rand() % 3;
    is_ctx_dep[i] = (RandUniform() < ctx_dep_prob);  // true w.p. ctx_dep_prob.
  }
  for (size_t i = 0; i < (size_t)num_phones; i++) {
    KALDI_VLOG(2) << "For idx = " << i
                  << ", (phone_id, hmm_length, is_ctx_dep) == "
                  << (phone_ids[i]) << " " << ((*hmm_lengths)[phone_ids[i]])
                  << " " << (is_ctx_dep[phone_ids[i]]);
  }
  // Generate rand stats.
  BuildTreeStatsType stats;
  size_t dim = 3 + Rand() % 20;
  GenRandStats(dim, num_stats, N, P, phone_ids, *hmm_lengths, is_ctx_dep,
               ensure_all_covered, &stats);

  // Now build the tree.

  Questions qopts;
  int32 num_quest = 40, num_iters = 0;
  qopts.InitRand(stats, num_quest, num_iters,
                 kAllKeysUnion);  // This was tested in build-tree-utils-test.cc

  float thresh = 100.0 * RandUniform();

  EventMap *tree = NULL;
  std::vector<std::vector<int32> > phone_sets(phone_ids.size());
  for (size_t i = 0; i < phone_ids.size(); i++)
    phone_sets[i].push_back(phone_ids[i]);
  std::vector<bool> share_roots(phone_sets.size(), true),
      do_split(phone_sets.size(), true);

  tree = BuildTree(qopts, phone_sets, *hmm_lengths, share_roots, do_split,
                   stats, thresh, 1000, 0.0, P);
  DeleteBuildTreeStats(&stats);
  return new ContextDependency(N, P, tree);
}

void ContextDependency::Write(std::ostream &os, bool binary) const {
  WriteToken(os, binary, "ContextDependency");
  WriteBasicType(os, binary, N_);
  WriteBasicType(os, binary, P_);
  WriteToken(os, binary, "ToPdf");
  to_pdf_->Write(os, binary);
  WriteToken(os, binary, "EndContextDependency");
}

void ContextDependency::Read(std::istream &is, bool binary) {
  if (to_pdf_) {
    delete to_pdf_;
    to_pdf_ = NULL;
  }
  ExpectToken(is, binary, "ContextDependency");
  ReadBasicType(is, binary, &N_);
  ReadBasicType(is, binary, &P_);
  EventMap *to_pdf = NULL;
  std::string token;
  ReadToken(is, binary, &token);
  if (token == "ToLength") {  // back-compat.
    EventMap *to_num_pdf_classes = EventMap::Read(is, binary);
    if (to_num_pdf_classes) delete to_num_pdf_classes;
    ReadToken(is, binary, &token);
  }
  if (token == "ToPdf") {
    to_pdf = EventMap::Read(is, binary);
  } else {
    KALDI_ERR << "Got unexpected token " << token
              << " reading context-dependency object.";
  }
  ExpectToken(is, binary, "EndContextDependency");
  to_pdf_ = to_pdf;
}

void ContextDependency::GetPdfInfo(
    const std::vector<int32> &phones,
    const std::vector<int32> &num_pdf_classes,  // indexed by phone,
    std::vector<std::vector<std::pair<int32, int32> > > *pdf_info) const {
  EventType vec;
  KALDI_ASSERT(pdf_info != NULL);
  pdf_info->resize(NumPdfs());
  for (size_t i = 0; i < phones.size(); i++) {
    int32 phone = phones[i];
    vec.clear();
    vec.push_back(std::make_pair(static_cast<EventKeyType>(P_),
                                 static_cast<EventValueType>(phone)));
    // Now get length.
    KALDI_ASSERT(static_cast<size_t>(phone) < num_pdf_classes.size());
    EventAnswerType len = num_pdf_classes[phone];

    for (int32 pos = 0; pos < len; pos++) {
      vec.resize(2);
      vec[0] = std::make_pair(static_cast<EventKeyType>(P_),
                              static_cast<EventValueType>(phone));
      vec[1] = std::make_pair(kPdfClass, static_cast<EventValueType>(pos));
      std::sort(vec.begin(), vec.end());
      std::vector<EventAnswerType>
          pdfs;  // pdfs that can be at this pos as this phone.
      to_pdf_->MultiMap(vec, &pdfs);
      SortAndUniq(&pdfs);
      if (pdfs.empty()) {
        KALDI_WARN
            << "ContextDependency::GetPdfInfo, no pdfs returned for position "
            << pos << " of phone " << phone
            << ".   Continuing but this is a serious error.";
      }
      for (size_t j = 0; j < pdfs.size(); j++) {
        KALDI_ASSERT(static_cast<size_t>(pdfs[j]) < pdf_info->size());
        (*pdf_info)[pdfs[j]].push_back(std::make_pair(phone, pos));
      }
    }
  }
  for (size_t i = 0; i < pdf_info->size(); i++) {
    std::sort(((*pdf_info)[i]).begin(), ((*pdf_info)[i]).end());
    KALDI_ASSERT(IsSortedAndUniq(((*pdf_info)[i])));  // should have no dups.
  }
}

ContextDependency *MonophoneContextDependency(
    const std::vector<int32> phones,
    const std::vector<int32> phone2num_pdf_classes) {
  std::vector<std::vector<int32> > phone_sets(phones.size());
  for (size_t i = 0; i < phones.size(); i++) phone_sets[i].push_back(phones[i]);
  std::vector<bool> share_roots(phones.size(), false);  // don't share roots.
  // N is context size, P = position of central phone (must be 0).
  int32 num_leaves = 0, P = 0, N = 1;
  EventMap *pdf_map = GetStubMap(P, phone_sets, phone2num_pdf_classes,
                                 share_roots, &num_leaves);
  return new ContextDependency(N, P, pdf_map);
}

ContextDependency *MonophoneContextDependencyShared(
    const std::vector<std::vector<int32> > phone_sets,
    const std::vector<int32> phone2num_pdf_classes) {
  std::vector<bool> share_roots(phone_sets.size(),
                                false);  // don't share roots.
  // N is context size, P = position of central phone (must be 0).
  int32 num_leaves = 0, P = 0, N = 1;
  EventMap *pdf_map = GetStubMap(P, phone_sets, phone2num_pdf_classes,
                                 share_roots, &num_leaves);
  return new ContextDependency(N, P, pdf_map);
}

}  // end namespace kaldi.


text:
package org.apache.accumulo.test.compaction;

import org.apache.accumulo.core.clientImpl.thrift.ThriftSecurityException;
import org.apache.accumulo.core.dataImpl.thrift.TKeyExtent;
import org.apache.accumulo.core.securityImpl.thrift.TCredentials;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.trace.thrift.TInfo;
import org.apache.accumulo.server.zookeeper.TransactionWatcher;
import org.apache.accumulo.tserver.TabletClientHandler;
import org.apache.accumulo.tserver.TabletServer;
import org.apache.accumulo.tserver.WriteTracker;
import org.apache.thrift.TException;

public class NonCommittingExternalCompactionTabletClientHandler extends TabletClientHandler
    implements TabletClientService.Iface {

  public NonCommittingExternalCompactionTabletClientHandler(TabletServer server,
      TransactionWatcher watcher, WriteTracker writeTracker) {
    super(server, watcher, writeTracker);
  }

  @Override
  public void compactionJobFinished(TInfo tinfo, TCredentials credentials,
      String externalCompactionId, TKeyExtent extent, long fileSize, long entries)
      throws ThriftSecurityException, TException {
    // do nothing
  }

  @Override
  public void compactionJobFailed(TInfo tinfo, TCredentials credentials,
      String externalCompactionId, TKeyExtent extent) throws TException {
    // do nothing
  }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:key="supported_netapps_list"
        android:title="@string/supported_netapps_category_title" />
    <Preference
        android:key="@string/settings_prefix_last_fm"
        android:icon="@drawable/ic_last_fm"
        android:visibility="gone"
        />
    <Preference
        android:key="@string/settings_prefix_libre_fm"
        android:icon="@drawable/ic_libre_fm"
        android:visibility="gone"
        />
    <Preference
        android:key="@string/settings_prefix_listenbrainz"
        android:icon="@drawable/ic_listenbrainz"
        android:visibility="gone"
        />
    <Preference
        android:key="@string/settings_prefix_libre_fm_custom"
        android:icon="@drawable/ic_libre_fm"
        android:visibility="gone"
        />
    <Preference
        android:key="@string/settings_prefix_listenbrainz_custom"
        android:icon="@drawable/ic_listenbrainz"
        android:visibility="gone"
        />
    <PreferenceCategory
        android:key="clear_all_creds_category"
        android:title="@string/other_category_title" />
    <Preference
        android:key="clear_all_user_credentials"
        android:summary="@string/user_credentials_clear_summary"
        android:title="@string/user_credentials_clear_title" />
</PreferenceScreen>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.secretwpn.redflag">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ItemSummaryActivity"
            android:label="@string/app_name"
            android:parentActivityName=".MainActivity" />
        <activity
            android:name=".ItemCreateActivity"
            android:label="@string/app_name"
            android:parentActivityName=".MainActivity" />

        <activity
            android:name=".ItemEditActivity"
            android:label="@string/app_name"
            android:parentActivityName=".ItemSummaryActivity" />
    </application>

</manifest>


text:
package es.tid.cosmos.api.auth.multiauth

import es.tid.cosmos.common.ConfigComponent

trait ConfigBasedMultiAuthProviderComponent extends MultiAuthProviderComponent {
  this: ConfigComponent =>

  override val multiAuthProvider: MultiAuthProvider = new ConfigBasedMultiAuthProvider(config)
}


text:
(function($P) {
	'use strict';

	$P.Bubble.Pathway = $P.defineClass(
		$P.Bubble,
		function PathwayBubble(config) {
			config = $.extend(config, {
				closeMenu: true,
				groupMenu: true});
			$P.Bubble.call(this, config);
			if (undefined !== config.text) {this.text = config.text;}},
		{
			onAdded: function(parent) {
				if ($P.BubbleBase.prototype.onAdded.call(this, parent) || this.content) {return;}
				var config = {};
				config = $.extend(config, this.getInteriorDimensions());
				config.x += 8;
				config.y += 8;
				config.w -= 16;
				config.h -= 16;
				config.parent = this;
				this.content = new $P.Bubble.PathwayContent(config);}

		});

})(PATHBUBBLES);


text:
package com.planet57.gshell.commands.plugin.internal;

import com.google.inject.Injector;
import org.eclipse.aether.artifact.Artifact;

import java.net.URLClassLoader;

import static com.google.common.base.Preconditions.checkNotNull;

// FIXME: find a better name

/**
 * ???
 *
 * @since 3.0
 */
public class PluginRegistration
{
  private final Artifact artifact;

  private final String id;

  private final URLClassLoader classLoader;

  private final Injector injector;

  public PluginRegistration(final Artifact artifact, final URLClassLoader classLoader, final Injector injector) {
    this.artifact = checkNotNull(artifact);
    // TODO: id may be better off w/o version
    this.id = String.format("%s:%s:%s", artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
    this.classLoader = checkNotNull(classLoader);
    this.injector = checkNotNull(injector);
  }

  public String getId() {
    return id;
  }

  public Artifact getArtifact() {
    return artifact;
  }

  public URLClassLoader getClassLoader() {
    return classLoader;
  }

  public Injector getInjector() {
    return injector;
  }

  public String toString() {
    return id;
  }
}


text:
See [Understanding LSTM Networks](https://colah.github.io/posts/2015-08-Understanding-LSTMs/){:.external}
for an introduction to recurrent neural networks and LSTMs.

## Language Modeling

In this tutorial we will show how to train a recurrent neural network on
a challenging task of language modeling. The goal of the problem is to fit a
probabilistic model which assigns probabilities to sentences. It does so by
predicting next words in a text given a history of previous words. For this
purpose we will use the [Penn Tree Bank](https://catalog.ldc.upenn.edu/ldc99t42)
(PTB) dataset, which is a popular benchmark for measuring the quality of these
models, whilst being small and relatively fast to train.

Language modeling is key to many interesting problems such as speech
recognition, machine translation, or image captioning. It is also fun --
take a look [here](https://karpathy.github.io/2015/05/21/rnn-effectiveness/).

For the purpose of this tutorial, we will reproduce the results from
[Zaremba et al., 2014](https://arxiv.org/abs/1409.2329)
([pdf](https://arxiv.org/pdf/1409.2329.pdf)), which achieves very good quality
on the PTB dataset.

## Tutorial Files

This tutorial references the following files from `models/tutorials/rnn/ptb` in the [TensorFlow models repo](https://github.com/tensorflow/models):

File | Purpose
--- | ---
`ptb_word_lm.py` | The code to train a language model on the PTB dataset.
`reader.py` | The code to read the dataset.

## Download and Prepare the Data

The data required for this tutorial is in the `data/` directory of the
[PTB dataset from Tomas Mikolov's webpage](http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz).

The dataset is already preprocessed and contains overall 10000 different words,
including the end-of-sentence marker and a special symbol (\<unk\>) for rare
words. In `reader.py`, we convert each word to a unique integer identifier,
in order to make it easy for the neural network to process the data.

## The Model

### LSTM

The core of the model consists of an LSTM cell that processes one word at a
time and computes probabilities of the possible values for the next word in the
sentence. The memory state of the network is initialized with a vector of zeros
and gets updated after reading each word. For computational reasons, we will
process data in mini-batches of size `batch_size`.  In this example, it is
important to note that `current_batch_of_words` does not correspond to a
"sentence" of words.  Every word in a batch should correspond to a time t.
TensorFlow will automatically sum the gradients of each batch for you.

For example:

```
 t=0  t=1    t=2  t=3     t=4
[The, brown, fox, is,     quick]
[The, red,   fox, jumped, high]

words_in_dataset[0] = [The, The]
words_in_dataset[1] = [brown, red]
words_in_dataset[2] = [fox, fox]
words_in_dataset[3] = [is, jumped]
words_in_dataset[4] = [quick, high]
batch_size = 2, time_steps = 5
```

The basic pseudocode is as follows:

```python
words_in_dataset = tf.placeholder(tf.float32, [time_steps, batch_size, num_features])
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
# Initial state of the LSTM memory.
hidden_state = tf.zeros([batch_size, lstm.state_size])
current_state = tf.zeros([batch_size, lstm.state_size])
state = hidden_state, current_state
probabilities = []
loss = 0.0
for current_batch_of_words in words_in_dataset:
    # The value of state is updated after processing each batch of words.
    output, state = lstm(current_batch_of_words, state)

    # The LSTM output can be used to make next word predictions
    logits = tf.matmul(output, softmax_w) + softmax_b
    probabilities.append(tf.nn.softmax(logits))
    loss += loss_function(probabilities, target_words)
```

### Truncated Backpropagation

By design, the output of a recurrent neural network (RNN) depends on arbitrarily
distant inputs. Unfortunately, this makes backpropagation computation difficult.
In order to make the learning process tractable, it is common practice to create
an "unrolled" version of the network, which contains a fixed number
(`num_steps`) of LSTM inputs and outputs. The model is then trained on this
finite approximation of the RNN. This can be implemented by feeding inputs of
length `num_steps` at a time and performing a backward pass after each
such input block.

Here is a simplified block of code for creating a graph which performs
truncated backpropagation:

```python
# Placeholder for the inputs in a given iteration.
words = tf.placeholder(tf.int32, [batch_size, num_steps])

lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
# Initial state of the LSTM memory.
initial_state = state = tf.zeros([batch_size, lstm.state_size])

for i in range(num_steps):
    # The value of state is updated after processing each batch of words.
    output, state = lstm(words[:, i], state)

    # The rest of the code.
    # ...

final_state = state
```

And this is how to implement an iteration over the whole dataset:

```python
# A numpy array holding the state of LSTM after each batch of words.
numpy_state = initial_state.eval()
total_loss = 0.0
for current_batch_of_words in words_in_dataset:
    numpy_state, current_loss = session.run([final_state, loss],
        # Initialize the LSTM state from the previous iteration.
        feed_dict={initial_state: numpy_state, words: current_batch_of_words})
    total_loss += current_loss
```

### Inputs

The word IDs will be embedded into a dense representation (see the
@{$word2vec$Vector Representations Tutorial}) before feeding to
the LSTM. This allows the model to efficiently represent the knowledge about
particular words. It is also easy to write:

```python
# embedding_matrix is a tensor of shape [vocabulary_size, embedding size]
word_embeddings = tf.nn.embedding_lookup(embedding_matrix, word_ids)
```

The embedding matrix will be initialized randomly and the model will learn to
differentiate the meaning of words just by looking at the data.

### Loss Function

We want to minimize the average negative log probability of the target words:

$$ \text{loss} = -\frac{1}{N}\sum_{i=1}^{N} \ln p_{\text{target}_i} $$

It is not very difficult to implement but the function
`sequence_loss_by_example` is already available, so we can just use it here.

The typical measure reported in the papers is average per-word perplexity (often
just called perplexity), which is equal to

$$e^{-\frac{1}{N}\sum_{i=1}^{N} \ln p_{\text{target}_i}} = e^{\text{loss}} $$

and we will monitor its value throughout the training process.

### Stacking multiple LSTMs

To give the model more expressive power, we can add multiple layers of LSTMs
to process the data. The output of the first layer will become the input of
the second and so on.

We have a class called `MultiRNNCell` that makes the implementation seamless:

```python
def lstm_cell():
  return tf.contrib.rnn.BasicLSTMCell(lstm_size)
stacked_lstm = tf.contrib.rnn.MultiRNNCell(
    [lstm_cell() for _ in range(number_of_layers)])

initial_state = state = stacked_lstm.zero_state(batch_size, tf.float32)
for i in range(num_steps):
    # The value of state is updated after processing each batch of words.
    output, state = stacked_lstm(words[:, i], state)

    # The rest of the code.
    # ...

final_state = state
```

## Run the Code

Before running the code, download the PTB dataset, as discussed at the beginning
of this tutorial.  Then, extract the PTB dataset underneath your home directory
as follows:

```bsh
tar xvfz simple-examples.tgz -C $HOME
```
_(Note: On Windows, you may need to use
[other tools](https://wiki.haskell.org/How_to_unpack_a_tar_file_in_Windows).)_

Now, clone the [TensorFlow models repo](https://github.com/tensorflow/models)
from GitHub. Run the following commands:

```bsh
cd models/tutorials/rnn/ptb
python ptb_word_lm.py --data_path=$HOME/simple-examples/data/ --model=small
```

There are 3 supported model configurations in the tutorial code: "small",
"medium" and "large". The difference between them is in size of the LSTMs and
the set of hyperparameters used for training.

The larger the model, the better results it should get. The `small` model should
be able to reach perplexity below 120 on the test set and the `large` one below
80, though it might take several hours to train.

## What Next?

There are several tricks that we haven't mentioned that make the model better,
including:

* decreasing learning rate schedule,
* dropout between the LSTM layers.

Study the code and modify it to improve the model even further.


text:
{% extends 'base.html' %}

{% block title %}

{{ review.mineralwater.name }}

{% endblock %}

{% block content %}

Rated {{ review.rating }} of 5 by {{ review.user_name }}

{{ review.pub_date }}

{{ review.comment }}

{% endblock %}


text:
package de.uni_koeln.spinfo.upcase.mongodb.data.document.future.tree;

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

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "trees")
public class Tree {

	public static final String TREE_COLLECTION = "trees";

	@Id private String id; // TREE_ID

	private String name; // TREE_NAME

	private String collectionId; // COLLECTION_REF

	private List<String> nodes = new ArrayList<>(); // NODES_REF

	private String root; // ROOT_REF

	public Tree() {
	}

	public Tree(String name, String collectionId) {
		this.name = name;
		this.collectionId = collectionId;
	}

	public String getRoot() {
		return root;
	}

	public void setRoot(String root) {
		this.root = root;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getId() {
		return id;
	}

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

	public boolean addNode(String nodeId) {
		return nodes.add(nodeId);
	}

	public List<String> getNodes() {
		return nodes;
	}

	public void setNodes(List<String> nodes) {
		this.nodes = nodes;
	}

	public boolean addAll(List<String> nodes) {
		return this.nodes.addAll(nodes);
	}

	public String getCollectionId() {
		return collectionId;
	}

	public void setCollectionId(String collectionId) {
		this.collectionId = collectionId;
	}

	@Override
	public String toString() {
		return "Tree [id=" + id + ", name=" + name + ", collectionId=" + collectionId + ", root=" + root + "]";
	}

}


text:
layout: post
title:  "Myeclipse10 server视图报错:Could not create the view: An unexpected exception was thrown.解决"
date:   2016-10-12 19:37:50 +0800
categories: 编程
tag: myeclipse
---

* content
{:toc}

Myeclipse10 server视图报错
----------

{% highlight bash %}
Could not create the view: An unexpected exception was thrown
java.lang.NullPointerException`
	at com.genuitec.eclipse.ast.deploy.core.Deployment.<init>(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.ModuleDeployment.<init>(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.WebDeployment.<init>(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.Deployment.create(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.DeploymentManager.loadFromPreferences(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.DeploymentManager.init(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.DeploymentManager.<init>(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.DeploymentManager.getDefault(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.ui.ServerTreeViewer$ServerTreeContentProvider.inputChanged(Unknown Source)
	at org.eclipse.jface.viewers.ContentViewer.setInput(ContentViewer.java:276)
	at org.eclipse.jface.viewers.StructuredViewer.setInput(StructuredViewer.java:1690)
	at com.genuitec.eclipse.ast.deploy.core.ui.ServerTreeViewer.<init>(Unknown Source)
	at com.genuitec.eclipse.ast.deploy.core.ui.ServerView.createPartControl(Unknown Source)
	at org.eclipse.ui.internal.ViewReference.createPartHelper(ViewReference.java:375)
	at org.eclipse.ui.internal.ViewReference.createPart(ViewReference.java:229)
	at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:595)
	at org.eclipse.ui.internal.WorkbenchPage$ActivationList.setActive(WorkbenchPage.java:4317)
	at org.eclipse.ui.internal.WorkbenchPage$18.runWithException(WorkbenchPage.java:3359)
	at org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
	at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
	at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
	at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)
	at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
	at org.eclipse.ui.application.WorkbenchAdvisor.openWindows(WorkbenchAdvisor.java:803)
	at org.eclipse.ui.internal.Workbench$33.runWithException(Workbench.java:1600)
	at org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
	at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
	at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
	at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)
	at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
	at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2609)
	at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
	at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
	at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
	at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
	at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
	at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:123)
	at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
	at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
	at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
{% endhighlight %}

按照搜到的方法

> 打开所在的wordspace文件夹,在下面子文件夹
> .metadata\.plugins\org.eclipse.core.runtime\.settings
> 删除
> com.genuitec.eclipse.ast.deploy.core.prefs
> 即可

试验一无效。
----------

我索性将整个workspace文件夹删除,重启问题依旧。

实验二无效。
----------

最终:
----------

- 删除D盘原有workspace(1.44G)
- 默认在c盘新建workspace
- 删除c盘新建的workspace(1.5G)
- 再打开,正常了

怀疑D盘产生问题,删除后使用默认的c盘workspace,但这个"新建的"C盘workspace其实并不是新建的,很可能是最初就有,我以前改到过D盘,导致该文件夹这么大。

结论
----------

网上分析很有道理,摁着工作空间使劲就行。见一个删一个,失败一个删一个,删删就好了。


text:
require 'open-uri'
require 'rexml/document'
require 'fileutils'

module Program
  class << self
    def fetch_feed(url)
      content = nil
      open(url) do |f|
        content = f.read
      end
      content
    end

    def fetch_digg_feed
      url = 'http://services.digg.com/2.0/story.getTopNews?type=rss'
      content = fetch_feed(url)
      content.force_encoding('iso-8859-1');
      content.encode('utf-8')
    end

    def fetch_hackernews_feed
      url = 'http://news.ycombinator.com/rss'
      fetch_feed(url)
    end

    def fetch_delicious_feed
      url = 'http://feeds.delicious.com/v2/rss/?count=30'
      fetch_feed(url)
    end

    def parse_rss(feed)
      xml = REXML::Document.new(feed)
      xml.elements.each("//item") do |item|
        link = item.get_elements('link')[0].text.strip
        title = item.get_elements('title')[0].text.strip
        yield link, title
      end
    end

    def run
      dir = File.expand_path('../pages', __FILE__)
      FileUtils.mkdir(dir) unless File.exists? dir

      [fetch_digg_feed, fetch_hackernews_feed, fetch_delicious_feed].each do |feed|
        parse_rss(feed) do |url, title|
          filename = title.gsub(/\W/, '_') + '.html'
          filepath = File.join(dir, filename)
          puts "fetching #{url} as #{filepath}"
          puts `curl --connect-timeout=5 #{url} > #{filepath} &`
          sleep 1
        end
      end
    end

  end
end

if __FILE__ == $0
  Program.run
end


text:
// Copyright(C) 1999-2017 National Technology & Engineering Solutions
// of Sandia, LLC (NTESS).  Under the terms of Contract DE-NA0003525 with
// NTESS, the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
//     * Neither the name of NTESS nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <Ioss_GroupingEntity.h>
#include <Ioss_Property.h>
#include <Ioss_Utils.h>
#include <cstddef>
#include <ostream>
#include <string>

namespace {
  std::string type_string(Ioss::Property::BasicType type)
  {
    switch (type) {
    case Ioss::Property::INVALID: return std::string("invalid");
    case Ioss::Property::REAL: return std::string("real");
    case Ioss::Property::INTEGER: return std::string("integer");
    case Ioss::Property::POINTER: return std::string("pointer");
    case Ioss::Property::STRING: return std::string("string");
    default: return std::string("internal error");
    }
  }

  void error_message(const Ioss::Property &property, const std::string &requested_type)
  {
    std::ostringstream errmsg;
    errmsg << "ERROR: For property named '" << property.get_name()
           << "', code requested value of type '" << requested_type << "', but property type is '"
           << type_string(property.get_type()) << "'. Types must match\n";
    IOSS_ERROR(errmsg);
  }
} // namespace

/** \brief Create an explicit, empty property having no name, INVALID type
 */
Ioss::Property::Property()
    : name_(""), type_(INVALID), isImplicit_(false)
{
  data_.pval = nullptr;
}

/** \brief Create a property with a specified type.
 *
 *  \param[in] name The property name.
 *  \param[in] type The property type.
 *  \param[in] data The property value.
 *  \param[in] is_it_implicit True if the property is calculated, rather than stored directly
 */
Ioss::Property::Property(std::string name, const BasicType type,
                         void *data, bool is_it_implicit)
    : name_(std::move(name)), type_(type), isImplicit_(is_it_implicit)
{
  data_.pval = data;
}

/** \brief Create an INTEGER type property.
 *
 *  \param[in] name The property name.
 *  \param[in] value The property value.
 *  \param[in] is_it_implicit True if the property is calculated, rather than stored directly
 */
Ioss::Property::Property(std::string name, int value, bool is_it_implicit)
    : name_(std::move(name)), type_(INTEGER), isImplicit_(is_it_implicit)
{
  data_.ival = value;
}

/** \brief Create an INTEGER type property using an int64_t variable.
 *
 *  \param[in] name The property name.
 *  \param[in] value The property value.
 *  \param[in] is_it_implicit True if the property is calculated, rather than stored directly
 */
Ioss::Property::Property(std::string name, int64_t value, bool is_it_implicit)
    : name_(std::move(name)), type_(INTEGER), isImplicit_(is_it_implicit)
{
  data_.ival = value;
}

/** \brief Create a REAL type property.
 *
 *  \param[in] name The property name.
 *  \param[in] value The property value.
 *  \param[in] is_it_implicit True if the property is calculated, rather than stored directly
 */
Ioss::Property::Property(std::string name, double value, bool is_it_implicit)
    : name_(std::move(name)), type_(REAL), isImplicit_(is_it_implicit)
{
  data_.rval = value;
}

/** \brief Create a STRING type property.
 *
 *  \param[in] name The property name.
 *  \param[in] value The property value.
 *  \param[in] is_it_implicit True if the property is calculated, rather than stored directly
 */
Ioss::Property::Property(std::string name, const std::string &value, bool is_it_implicit)
    : name_(std::move(name)), type_(STRING), isImplicit_(is_it_implicit)
{
  data_.sval = new std::string(value);
}

/** \brief Create a POINTER type property.
 *
 *  \param[in] name The property name.
 *  \param[in] value The property value.
 *  \param[in] is_it_implicit True if the property is calculated, rather than stored directly
 */
Ioss::Property::Property(std::string name, void *value, bool is_it_implicit)
    : name_(std::move(name)), type_(POINTER), isImplicit_(is_it_implicit)
{
  data_.pval = value;
}

/** \brief Set implicit property with a specified type.
 *
 *  \param[in] ge The property value.
 *  \param[in] name The property name.
 *  \param[in] type The property type.
 */
Ioss::Property::Property(const Ioss::GroupingEntity *ge, std::string name, const BasicType type)
    : name_(std::move(name)), type_(type), isImplicit_(true)
{
  data_.ge = ge;
}

/** \brief Copy constructor.
 *
 *  \param[in] from The Ioss::Property to copy
 */
Ioss::Property::Property(const Ioss::Property &from)
{
  name_       = from.name_;
  type_       = from.type_;
  isImplicit_ = from.isImplicit_;
  if (!isImplicit_ && type_ == STRING) {
    data_.sval = new std::string(*(from.data_.sval));
  }
  else {
    data_ = from.data_;
  }
}

Ioss::Property::~Property()
{
  if (!isImplicit_ && type_ == STRING) {
    delete data_.sval;
  }
}

Ioss::Property &Ioss::Property::operator=(Ioss::Property rhs)
{
  std::swap(*this, rhs);
  return *this;
}

/** \brief Get the property value if it is of type STRING.
 *
 *  \returns The STRING-type property value
 */
std::string Ioss::Property::get_string() const
{
  std::string value;
  bool        valid = get_value(&value);
  if (!valid) {
    error_message(*this, "string");
  }
  return value;
}

/** \brief Get the property value if it is of type INTEGER.
 *
 *  \returns The INTEGER-type property value
 */
int64_t Ioss::Property::get_int() const
{
  int64_t value;
  bool    valid = get_value(&value);
  if (!valid) {
    error_message(*this, "int");
  }
  return value;
}

/** \brief Get the property value if it is of type REAL.
 *
 *  \returns The REAL-type property value.
 */
double Ioss::Property::get_real() const
{
  double value;
  bool   valid = get_value(&value);
  if (!valid) {
    error_message(*this, "real");
  }
  return value;
}

/** \brief Get the property value if it is of type POINTER.
 *
 *  \returns The POINTER-type property value.
 */
void *Ioss::Property::get_pointer() const
{
  void *value = nullptr;
  bool  valid = get_value(value);
  if (!valid) {
    error_message(*this, "pointer");
  }
  return value;
}

bool Ioss::Property::get_value(int64_t *value) const
{
  bool valid_request = false;
  if (type_ == INTEGER) {
    valid_request = true;
  }
  if (is_explicit()) {
    *value = data_.ival;
  }
  else {
    const Ioss::GroupingEntity *ge       = data_.ge;
    const Ioss::Property        implicit = ge->get_implicit_property(name_);
    valid_request                        = implicit.get_value(value);
  }
  return valid_request;
}

bool Ioss::Property::get_value(double *value) const
{
  bool valid_request = false;
  if (type_ == REAL) {
    valid_request = true;
  }
  if (is_explicit()) {
    *value = data_.rval;
  }
  else {
    const Ioss::GroupingEntity *ge       = data_.ge;
    const Ioss::Property        implicit = ge->get_implicit_property(name_);
    valid_request                        = implicit.get_value(value);
  }
  return valid_request;
}

bool Ioss::Property::get_value(std::string *value) const
{
  bool valid_request = false;
  if (type_ == STRING) {
    valid_request = true;
  }
  if (is_explicit()) {
    *value = *(data_.sval);
  }
  else {
    const Ioss::GroupingEntity *ge       = data_.ge;
    const Ioss::Property        implicit = ge->get_implicit_property(name_);
    valid_request                        = implicit.get_value(value);
  }
  return valid_request;
}

bool Ioss::Property::get_value(void *&value) const
{
  bool valid_request = false;
  if (type_ == POINTER) {
    valid_request = true;
  }
  if (is_explicit()) {
    value = data_.pval;
  }
  else {
    const Ioss::GroupingEntity *ge       = data_.ge;
    const Ioss::Property        implicit = ge->get_implicit_property(name_);
    valid_request                        = implicit.get_value(value);
  }
  return valid_request;
}


text:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/main.css">
  <link rel="stylesheet" href="bower_components/angular-material/angular-material.css">
  <link rel="stylesheet" href="app.css"/>
  <script src="bower_components/html5-boilerplate/js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body ng-cloak layout="column" ng-controller="AppCtrl">
  <header-toolbar></header-toolbar>
  <div layout="row" flex>
    <navigation-bar></navigation-bar>
    <md-content class="view-container" ng-view layout-fill></md-content>
  </div>

  <!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.x/angular.min.js"></script>
<script src="//cdn.firebase.com/js/client/2.2.x/firebase.js"></script>
<script src="//cdn.firebase.com/libs/angularfire/1.0.x/angularfire.min.js"></script>
-->
  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/angular-route/angular-route.js"></script>
  <script src="bower_components/firebase/firebase.js"></script>
  <script src="bower_components/angularfire/dist/angularfire.js"></script>
  <script src="bower_components/angular-aria/angular-aria.js"></script>
  <script src="bower_components/angular-animate/angular-animate.js"></script>
  <script src="bower_components/angular-material/angular-material.js"></script>

  <script src="app.js"></script>
  <script src="config.js"></script>

  <script src="components/appversion/appversion-directive.js"></script>
  <script src="components/auth/auth.js"></script>
  <script src="components/firebase.utils/firebase.utils.js"></script>
  <script src="components/ngcloak/ngcloak-decorator.js"></script>
  <script src="components/reverse/reverse-filter.js"></script>
  <script src="components/security/security.js"></script>

  <script src="navigation/navigation.js"></script>
  <script src="header/header.js"></script>
  <script src="home/home.js"></script>
  <script src="account/account.js"></script>
  <script src="chat/chat.js"></script>
  <script src="login/login.js"></script>
</body>
</html>


text:
<?php

// Warning! This code was generated by WSDL2PHP tool.
// author: Filippov Andrey <afi.work@gmail.com>
// see https://solo-framework-lib.googlecode.com

namespace Moneta\Types;

/**
 * Тип для запроса подтверждения операции в пакетном режиме.
	 * Request parameters for confirming transactions in batch mode.
	 *
 */
class ConfirmTransactionBatchRequestType extends EntityBatchRequestType
{

	/**
	 * Набор операций, которые необходимо выполнить в одном пакете. Операции выполняются в том порядке, в котором они переданы в запросе.
	 * The set of transactions that must be processed in a single batch. MONETA.RU processes transactions in the order that they are defined in the request.
	 *
	 *
	 * @var ConfirmTransactionRequestType
	 */
	 public $transaction = null;

	/**
	 * Набор операций, которые необходимо выполнить в одном пакете. Операции выполняются в том порядке, в котором они переданы в запросе.
	 * The set of transactions that must be processed in a single batch. MONETA.RU processes transactions in the order that they are defined in the request.
	 *
	 *
	 * @param ConfirmTransactionRequestType
	 *
	 * @return void
	 */
	public function addTransaction(ConfirmTransactionRequestType $item)
	{
		$this->transaction[] = $item;
	}

}


text:
namespace jingle_xmpp {
class TaskParent;
}  // namespace

namespace notifier {

// jingle_xmpp::XmppClient's destructor isn't marked virtual, but it inherits
// from rtc::Task, whose destructor *is* marked virtual, so we
// can safely inherit from it.
class WeakXmppClient : public jingle_xmpp::XmppClient {
 public:
  explicit WeakXmppClient(jingle_xmpp::TaskParent* parent);

  WeakXmppClient(const WeakXmppClient&) = delete;
  WeakXmppClient& operator=(const WeakXmppClient&) = delete;

  ~WeakXmppClient() override;

  // Returns a weak pointer that is invalidated when the XmppClient
  // becomes invalid to use.
  base::WeakPtr<WeakXmppClient> AsWeakPtr();

  // Invalidates all weak pointers to this object.  (This method is
  // necessary as calling Abort() does not always lead to Stop() being
  // called, so it's not a reliable way to cause an invalidation.)
  void Invalidate();

 protected:
  void Stop() override;

 private:
  SEQUENCE_CHECKER(sequence_checker_);

  // We use our own WeakPtrFactory instead of inheriting from
  // SupportsWeakPtr since we want to invalidate in other places
  // besides the destructor.
  base::WeakPtrFactory<WeakXmppClient> weak_ptr_factory_{this};
};

}  // namespace notifier

#endif  // JINGLE_NOTIFIER_BASE_WEAK_XMPP_CLIENT_H_


text:
@class DVTNotificationToken, IDEPlaygroundDocument, IDEToybox;

@interface IDEToyboxDocument : IDEEditorDocument
{
    DVTNotificationToken *_playgroundDocumentWillCloseObservingToken;
    IDEPlaygroundDocument *_playgroundDocument;
}

+ (id)keyPathsForValuesAffectingToybox;
+ (id)keyPathsForValuesAffectingReadOnlyStatus;
@property(retain, nonatomic) IDEPlaygroundDocument *playgroundDocument; // @synthesize playgroundDocument=_playgroundDocument;
- (void).cxx_destruct;
- (void)editorDocumentWillClose;
@property(readonly) IDEToybox *toybox;
- (void)setFileURL:(id)arg1;
- (id)dataOfType:(id)arg1 error:(id *)arg2;
- (BOOL)readFromURL:(id)arg1 ofType:(id)arg2 error:(id *)arg3;
- (int)readOnlyStatus;

@end


text:
/*
	JanusForumInfo.h
	The implementation of properties and methods for the JanusForumInfo object.
	Generated by SudzC.com
*/
#import "JanusForumInfo.h"

@implementation JanusForumInfo
	@synthesize forumId = _forumId;
	@synthesize forumGroupId = _forumGroupId;
	@synthesize shortForumName = _shortForumName;
	@synthesize forumName = _forumName;
	@synthesize rated = _rated;
	@synthesize inTop = _inTop;
	@synthesize rateLimit = _rateLimit;

	- (id) init
	{
		if(self = [super init])
		{
			self.shortForumName = nil;
			self.forumName = nil;

		}
		return self;
	}

	+ (JanusForumInfo*) newWithNode: (CXMLNode*) node
	{
		if(node == nil) { return nil; }
		return (JanusForumInfo*)[[JanusForumInfo alloc] initWithNode: node];
	}

	- (id) initWithNode: (CXMLNode*) node {
		if(self = [super initWithNode: node])
		{
			self.forumId = [[Soap getNodeValue: node withName: @"forumId"] intValue];
			self.forumGroupId = [[Soap getNodeValue: node withName: @"forumGroupId"] intValue];
			self.shortForumName = [Soap getNodeValue: node withName: @"shortForumName"];
			self.forumName = [Soap getNodeValue: node withName: @"forumName"];
			self.rated = [[Soap getNodeValue: node withName: @"rated"] intValue];
			self.inTop = [[Soap getNodeValue: node withName: @"inTop"] intValue];
			self.rateLimit = [[Soap getNodeValue: node withName: @"rateLimit"] intValue];
		}
		return self;
	}

	- (NSMutableString*) serialize
	{
		return [self serialize: @"JanusForumInfo"];
	}

	- (NSMutableString*) serialize: (NSString*) nodeName
	{
		NSMutableString* s = [NSMutableString string];
		[s appendFormat: @"<%@", nodeName];
		[s appendString: [self serializeAttributes]];
		[s appendString: @">"];
		[s appendString: [self serializeElements]];
		[s appendFormat: @"</%@>", nodeName];
		return s;
	}

	- (NSMutableString*) serializeElements
	{
		NSMutableString* s = [super serializeElements];
		[s appendFormat: @"<forumId>%@</forumId>", [NSString stringWithFormat: @"%i", self.forumId]];
		[s appendFormat: @"<forumGroupId>%@</forumGroupId>", [NSString stringWithFormat: @"%i", self.forumGroupId]];
		if (self.shortForumName != nil) [s appendFormat: @"<shortForumName>%@</shortForumName>", [[self.shortForumName stringByReplacingOccurrencesOfString:@"\"" withString:@"""] stringByReplacingOccurrencesOfString:@"&" withString:@"&"]];
		if (self.forumName != nil) [s appendFormat: @"<forumName>%@</forumName>", [[self.forumName stringByReplacingOccurrencesOfString:@"\"" withString:@"""] stringByReplacingOccurrencesOfString:@"&" withString:@"&"]];
		[s appendFormat: @"<rated>%@</rated>", [NSString stringWithFormat: @"%i", self.rated]];
		[s appendFormat: @"<inTop>%@</inTop>", [NSString stringWithFormat: @"%i", self.inTop]];
		[s appendFormat: @"<rateLimit>%@</rateLimit>", [NSString stringWithFormat: @"%i", self.rateLimit]];

		return s;
	}

	- (NSMutableString*) serializeAttributes
	{
		NSMutableString* s = [super serializeAttributes];

		return s;
	}

	-(BOOL)isEqual:(id)object{
		if(object != nil && [object isKindOfClass:[JanusForumInfo class]]) {
			return [[self serialize] isEqualToString:[object serialize]];
		}
		return NO;
	}

	-(NSUInteger)hash{
		return [Soap generateHash:self];

	}

@end


text:
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title>MySystem Authoring</title>

  <link rel="stylesheet" href="css/custom.css">
  <link rel="stylesheet" href="css/jquery.gritter.css">

MySystem Authoring Preview

        <button id="save_authoring">Save authored activity</button>

          <input type="checkbox" id="save_external" disabled>Enable diagram saving

            <input type="checkbox" id="autosave_external" disabled>Autosave every
            <input type="text" size="2" value="20" id="autosave_time" disabled> seconds


text:
#include "grid/scanGrid.h"
#include "grid/scanToGrid.h"
#include "slam6d/scan.h"
#include "grid/scanmanager.h"
#include "grid/parcelmanager.h"
#include "grid/gridWriter.h"
#include "grid/viewpointinfo.h"
#include "grid/gridlines.h"
#include "slam6d/globals.icc"

#include "grid/Debug.h"

#include <math.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <dirent.h>

using std::cerr;
using std::flush;

#ifdef _MSC_VER
  #define  _USE_MATH_DEFINES
  #include <windows.h>
  #include "GL/glut.h"    /* Header File For The glu toolkit */
  #include "XGetopt.h"
#else
  #include <getopt.h>
  #include <strings.h>
#endif

/**
 * 2DGridder
 *
 * Main class to convert a 3D scan to a 2D grid
 *
 * @author Andre Schemschadt, Uwe Hebbelmann, Sebastian Stock
 * @date 20.02.2008
 */

/**
 * Explains the usage of this program's command line parameters
 *
 * @param prog name of the program
 */
void usage(char* prog)
{
#ifndef _MSC_VER
  const string bold("\033[1m");
  const string normal("\033[m");
#else
  const string bold("");
  const string normal("");
#endif

    cout << endl
	 << "Usage: " << prog << endl
	 << "       [-s NR] [-e NR] [-m NR] [-M NR] [-f F] [-o DIR] [-t] " << endl
	 << "       [-h NR] [-H NR] [-r NR] [-w] [-p NR] [-P Nr] [-y] [-n] " <<endl
	 << "       [-g] [-d] [-l] [-a NR] inputdirectory" << endl << endl;

    cout << "  -s NR   start at scan NR (i.e., neglects the first NR scans)" << endl
	 << "          [ATTENTION: counting starts with 0]" << endl
	 << "  -e NR   end after scan NR" << "" << endl
	 << "  -m NR   set the maximal range distance to NR 'units' (unit of scan data, e.g. cm)" << endl
	 << "          (default 2500, unit of scan data, e.g. cm)" << endl
	 << "  -M NR   set the minimal range distance to NR 'units' (unit of scan data, e.g. cm)" << endl
	 << "  -f F    format = F" << endl
	 << "          using shared library F for input" << endl
	 << "          (chose F from {uos, uos_map, uos_frames, uos_map_frames, old, rts, rts_map, ifp, riegl_bin, riegl_txt, zahn, ply})" << endl
	 << "  -o DIR  the output directory (if none is set use the input directory" << endl
	 << "  -t      read a file containing a initial transformation matrix" << endl
	 << "  -H NR   set the maximal relevant height to NR 'units' (unit of scan data, e.g. cm)" << endl
	 << "  -h NR   set the minimal relevant height to NR 'units' (unit of scan data, e.g. cm)" << endl
	 << "  -r NR   the width of the gridunit (unit of scan data, e.g. cm per unit)" << endl
	 << "  -w      default true, if set false " << endl
	 << "          (if true free points between viewpoint and points will be created)" << endl
	 << "  -p NR   set the parcel width (unit of scan data, e.g. cm)" << endl
	 << "  -P NR   set the parcel height (unit of scan data, e.g. cm)" << endl
	 << "  -y      default false, if set true " <<endl
	 << "          (if true the transformationmatrix of the scans will be corrected (the value for Y)" << endl
	 << "  -n      default true, if set false" << endl
	 << "          (if true, neighbours will be weighted) " << endl
	 << "  -a NR   the spot diameter of the laser per 3000 units of scan data, e.g. cm " << endl
	 << "          (default 15 cm / 3000 cm) " << endl
	 << "  -g      default false, if set true " << endl
	 << "          (if true, the grids will be written) " << endl
	 << "  -d      default true, if set false " << endl
	 << "          (if true, the world will be written) " << endl
	 << "  -l      default false, if set true " << endl
	 << "          (if true, lines will be created and written) " << endl
	 << "  -i      default false, if set true " << endl
	 << "          (if true, a world ppm will be created) " << endl
	 << "  -c      default 50. This is the numbers of scans which " << endl
	 << "          will be process at a time" << endl
	 << "  -R      default false, if set the programm will resume " << endl
	 << endl << endl;

    exit(1);
}

/**
 * Checks if the directory exists
 * @param path the directory to check
 * @return true if exists, else false
 */
bool directoryExists(const string path )
{
    DIR *pDir;
    bool bExists = false;

    pDir = opendir(path.c_str());

    if (pDir != NULL){
	bExists = true;
	closedir (pDir);
    }

    return bExists;
}

/**
 * A function that parses the command-line arguments and sets the respective flags.
 *
 * @param argc the number of arguments
 * @param argv the arguments
 * @param inputdir parsing result - the input directory
 * @param outputdir parsing result - the output directory
 * @param start parsing result - starting at scan number 'start'
 * @param end parsing result - stopping at scan number 'end'
 * @param maxDist parsing result - maximal distance
 * @param minDist parsing result - minimal distance
 * @param readInitial parsing result -  read a file containing a initial transformation matrix
 * @param type parsing result - file format to be read
 * @param minHeight the minimal relevant height
 * @param maxHeight the maximal relevant height
 * @param resolution the width of the gridunit (centimeters per unit)
 * @param waypoints default true, if set false (if true free points between viewpoint and points will be created)
 * @param parcel_width the width of the parcel
 * @param parcel_height the height of the parcel
 * @param correctY default true, if set false (if true the transformationmatrix of the scans will be corrected (the value for Y)
 * @return 0, if the parsing was successful, 1 otherwise
 */
int parseArgs(int argc, char **argv,
	      string &inputdir, string &outputdir,
	      int& start, int& end, int& maxDist, int& minDist,
	      bool &readInitial, IOType &type, bool& correctY,
	      double &minHeight, double &maxHeight, long &resolution,
	      bool &waypoints, bool &neighbours,
	      int &parcelWidth, int &parcelHeight,
	      bool &writeWorld, bool &writeLines, bool &writeGrids,
	      int &spotradius, bool &writeWorldppm, int& count,
	      bool &resume)
{
    int  c;

    // from unistd.h
    extern char *optarg;
    extern int optind;

    cout << endl;
    while ((c = getopt (argc, argv, "o:s:a:e:m:ncwgidlRM:h:H:f:r:p:P:yt")) != -1)
    {
      switch (c)
      {
        case 'o':
          outputdir = optarg;
          if (!directoryExists(outputdir)) {
            cerr << "Error: Directory doesn't exist.\n";
            exit(1);
          }
          break;
        case 's':
          start = atoi(optarg);
          if (start < 0) {
            cerr << "Error: Cannot start at a negative scan number.\n";
            exit(1);
          }
          break;
        case 'e':
          end = atoi(optarg);
          if (end < 0) {
            cerr << "Error: Cannot end at a negative scan number.\n";
            exit(1);
          }
          if (end < start) {
            cerr << "Error: <end> cannot be smaller than <start>.\n";
            exit(1);
          }
          break;
        case 'c':
          count = atoi(optarg);
          if( count < 1){
            cerr << "Error: <count> must be greater than 1.\n";
            exit(1);
          }
          break;
        case 'R':
          resume = true;
          break;
        case 'm':
          maxDist = atoi(optarg);
          break;
        case 'M':
          minDist = atoi(optarg);
          break;
        case 't':
          readInitial = true;
          break;
        case 'f':
          try {
            type = formatname_to_io_type(optarg);
          } catch (...) { // runtime_error
            cerr << "Format " << optarg << " unknown." << endl;
            abort();
          }
          break;
        case 'H':
          maxHeight = atoi(optarg);
          break;
        case 'h':
          minHeight = atoi(optarg);
          break;
        case 'g':
          writeGrids = true;
          break;
        case 'r':
          resolution = atol(optarg);
          if (resolution < 1) {
            cerr << "Error: <resolution> cannot be smaller than 1.\n";
            exit(1);
          }
          break;
        case 'w':
          waypoints = false;
          break;
        case 'n':
          neighbours = false;
          break;
        case 'p':
          parcelWidth = atol(optarg);
          if (parcelWidth < 1) {
            cerr << "Error: <parcel_width> cannot be smaller than 1.\n";
            exit(1);
          }
          break;
        case 'P':
          parcelHeight = atol(optarg);
          if (parcelHeight < 1) {
            cerr << "Error: <parcel_height> cannot be smaller than 1.\n";
            exit(1);
          }
          break;
        case 'y':
          correctY = true;
          break;
        case 'a':
          spotradius = atoi(optarg);
          if (spotradius < 0) {
            cerr << "Error: <spotradius> cannot be smaller than 0.\n";
            exit(1);
          }
          break;
        case 'd':
          writeWorld = false;
          break;
        case 'l':
          writeLines = true;
          break;
        case 'i':
          writeWorldppm = true;
          break;
        case '?':
          usage(argv[0]);
          return 1;
        default:
          abort();
      }}

    if (optind != argc-1) {
	cerr << "\n*** Input directory missing ***" << endl;
	usage(argv[0]);
    }
    inputdir = argv[optind];

    //If no output directory is set, set it to the input directory
    if (outputdir == "") outputdir = inputdir;

#ifndef _MSC_VER
  if (inputdir[inputdir.length()-1] != '/') inputdir = inputdir + "/";
  if (outputdir[outputdir.length()-1] != '/') outputdir = outputdir + "/";
#else
  if (inputdir[inputdir.length()-1] != '\\') inputdir = inputdir + "\\";
  if (outputdir[outputdir.length()-1] != '\\') outputdir = outputdir + "\\";
#endif

    return 0;
}

/**
 * Main function.
 * Reads the scan (scan000.3d, ...) and frames files (scan000.frames, ...) from the data directory.
 * The frames are used for animation of the matching process. Converts the 3D scan data to a 2D grid map
 * and stores it
 *
 * @param argc count of the command-line arguments
 * @param argv command-line arguments
 */
int main(int argc, char **argv){
    // Start message
    cout << "(c) University of Osnabrueck, 2006 - 2008" << endl << endl
	 << "Restricted Usage" << endl
	 << "Don't use without permission" << endl;

    // Usage
    if(argc <= 1){
	usage(argv[0]);
    }

    ///////////////////////////////////////
    // Defaultvalues
    string scandir = "";
    string outputdir = "./parcels/";

    int start = 0;
    int end = -1;
    int maxDistance = 2500;
    int minDistance = -1;
    bool readInitial = false;
    IOType scantype  = UOS;
    bool correctY = false;

    double maxRelevantHeight = 50;
    double minRelevantHeight = 2;
    long resolution = 10;
    bool createWaypoints = true;
    bool createNeighbours = true;

    int parcelWidth = 1000;
    int parcelHeight = 1000;

    int spotradius = 15;

    bool writeWorld = true;
    bool writeLines = false;
    bool writeGrids = false;
    bool writeWorldppm = false;

    double isSolidPoint = 0.2;
    int count = 50;
    bool resume = false;
    ///////////////////////////////////////

    // parses the command-line arguments and sets the respective flags
    parseArgs(argc, argv,
	      scandir, outputdir, start, end, maxDistance, minDistance,
	      readInitial, scantype, correctY,
	      minRelevantHeight, maxRelevantHeight, resolution,
	      createWaypoints, createNeighbours,
	      parcelWidth, parcelHeight,
	      writeWorld, writeLines, writeGrids, spotradius, writeWorldppm,
	      count, resume);

    // calculate parcel width and height
    parcelWidth /= resolution;
    parcelHeight /= resolution;

    // create parcelmanager
    cout << "Create parcelmanager ..." << endl;
    parcelmanager parcelman(parcelWidth, parcelHeight,
			    outputdir, resolution, resume);

    cout << "Create viewpointlist ... " << endl;
    viewpointinfo viewpoint(outputdir);

    for (int i = start; i <= end; i+=count)
    {
	int endloop = i + count - 1 < end ? i + count - 1 : end;

	// get Scans
	cout << "Reading scans " << i << " to " << endloop << " ... ";
	scanmanager scanman;
	scanman.startscan(scandir, outputdir, scantype, i, endloop,
				   readInitial, maxDistance, minDistance,
				   correctY);

	cout << "Done."<< endl;

	// create grid from scans
	cout << "Creating grids " << i << " to " << endloop << " ... ";
	scanToGrid stg(resolution,
		       minRelevantHeight,
		       maxRelevantHeight,
		       maxDistance,
		       spotradius,
		       createWaypoints,
		       createNeighbours);

	cout << "Done."<< endl;

	// convert scans
	cout << "Converting " << scanman.getScanCount() <<" scans ... ";

	vector<scanGrid*> grids;
	for(size_t j = 0; j < scanman.getScanCount(); j++)
	{
	    cout << "." << flush;
	    double* p = scanman.getMatrix(j).back();
	    scanman.getScan(j).transformAll(p);
	    grids.push_back(stg.convert(scanman.getScan(j), p));
	}
	cout << "Done." << endl;

	// start writing
	cout << "Processing from " << i << " to " << endloop << endl;
	for(size_t j = 0; j < grids.size(); ++j)
	{
	    cout << "Adding scan " << i << " ... " << flush;
	    parcelman.addGrid(grids[j],
			      grids[j]->getViewpointX(),
			      grids[j]->getViewpointZ());

	    viewpoint.addGrid(grids[j]);
	    cout << "Done."<< endl;
	}

	// print grids for each scan if wished
	if(writeGrids)
	{
	    cout << "Writing grids " << i
		 << " to " << endloop << " ... " << endl;

	    string str;
	    stringstream stream;
	    for(size_t j = 0; j < grids.size(); ++j)
	    {
	      cout << "Writing grid " << i << " ... " << flush;
		stream.clear();
		stream << outputdir << "grid" << j+i << ".ppm ";
		stream >> str;

		ppmWriter writer(str);
		writer.write(*grids[j]);
		cout << "Done."<<endl;
	    }
	}

	cout << "Freeing subdate ... "<< flush;
	for(size_t j = 0; j < grids.size(); ++j)
	    delete grids[j];
	grids.clear();
	cout << "Done."<< endl;
    }

    // write the world and the viewpoints
    if(writeWorld)
    {
	// write world map
	cout << "Writing world map ... " << flush;
	parcelman.writeWorld("world.2dm");
	cout << "done." << endl;

	// write viewpoints
	cout << "Writing viewpoints ... " << flush;
	viewpoint.write("viewpoints.pts");
	cout << "Done." << endl;
    }

    // write gridlines
    if(writeLines || writeWorldppm)
    {
	cout << "Creating world grid ... ";
	grid *g = parcelman.createWorldGrid();
	cout << "Done." << endl;

	if(writeLines) {
	    cout << "Writing Lines ... ";
	    gridlines glines(g, maxDistance, isSolidPoint);
	    glines.writeLin(outputdir + "/lines.plot");
	    cout << "Done." << endl;
	}

	if(writeWorldppm) {
	    cout << "Writing world ppm ... ";
	    ppmWriter writer(outputdir + "world.ppm");
	    writer.write(*g);
	    cout << "Done." << endl;
	}

	delete g;
    }

    cout << "Freeing data ... " << endl;
}


text:
class AsmPrinter:
    """ Subclass this class to create render assembly code correctly """

    def print_instruction(self, instruction):
        return str(instruction)


text:
local jsonStringify = require('json').stringify
local send
local names = {}

local function handleSocket(req, read, write)
  if not send then
    send = require('redis-client')()
  end
  p(req)
  for message in read do
    if message.opcode == 1 then
      p(message.payload)
      local list = {}
      for part in message.payload:gmatch("%w+") do
        list[#list + 1] = part
      end
      local res = send(unpack(list))
      p(list, res)
      for i = 1, #res, 2 do
        local key = res[i]
        local name = names[key]
        if not name then
          name = send("GET", key)
          names[key] = name
        end
        res[i] = name
        res[i + 1] = tonumber(res[i + 1])
      end
      write {
        opcode = 1,
        payload = jsonStringify(res)
      }
    end
  end
  send()
end

require('weblit-websocket')
require('weblit-app')

.bind({
  host = "0.0.0.0",
  port = 3000
})

.use(require('weblit-logger'))
.use(require('weblit-auto-headers'))
.use(require('weblit-etag-cache'))

.websocket({
  path = "/",
  protocol = "resp",
}, handleSocket)

.use(require('weblit-static')(module.dir .. "/www"))

.start()


text:
<?php
include_once("conexion.php");

/*
// Rellenar la tabla para el reporte
$quer0 = "DELETE FROM repbonoafiliacion WHERE 1";
$resul0 = mysql_query($quer0,$link);

$query = "SELECT * FROM patrocinio order by patroc_codigo,tit_codigo";
$result = mysql_query($query,$link);
$txt = "";
while($row = mysql_fetch_array($result)) {
   	$patroc_codigo = $row["patroc_codigo"];
    $tit_codigo = $row["tit_codigo"];
    $fecha_afiliacion = $row["fecha_afiliacion"]; // del afiliado no del patrocinador
    $fecha_fin_bono =  $row["fecha_fin_bono"];

	$quer2 = "SELECT * from organizacion where organizacion.organizacion='".$tit_codigo."' and nivel>='0' AND nivel<'3' order by nivel,afiliado";
	$resul2 = mysql_query($quer2,$link);
	$m = 0;
	$d2 = false;
	$ha1 = true;
	$st = 0.00;
	while($ro2 = mysql_fetch_array($resul2)) {
		$nivel = $ro2["nivel"]+1;
		$afiliado = $ro2["afiliado"];

		$quer3 = "SELECT * from afiliados where tit_codigo='".$afiliado."'";
		$resul3 = mysql_query($quer3,$link);
		if($ro3 = mysql_fetch_array($resul3)) {
			$tipo_afiliado = $ro3["tipo_afiliado"];

			$quer4 = " SELECT * from transacciones where afiliado='".$afiliado."' and tipo='01' and fecha>='".$fecha_afiliacion."' and fecha<='".$fecha_fin_bono."' and status_comision='Pendiente'";
			$resul4 = mysql_query($quer4,$link);
			if($ro4 = mysql_fetch_array($resul4)) {
				$monto = $ro4["monto"];
				$fectr = $ro4["fecha"];

				$quer5 = "SELECT * from bono_afiliacion where bono_afiliacion.nivel='".trim($nivel)."'";
				$resul5 = mysql_query($quer5,$link);
				$ro5 = mysql_fetch_array($resul5);
				$porcentaje = 0.00;
				switch ($tipo_afiliado) {
					case 'Premium':
						$porcentaje = $ro5["premium"];
						break;
					case 'VIP':
						$porcentaje = $ro5["vip"];
						break;
					case 'Oro':
						$porcentaje = $ro5["oro"];
						break;
				}
				$comision = $monto*($porcentaje/100);
				if ($monto<>0.00) {
					$quer6 = "INSERT INTO repbonoafiliacion VALUES ('".$patroc_codigo."','".$tit_codigo."','".$fecha_afiliacion."','".$fecha_fin_bono."',".$nivel.",'".$afiliado."','".$tipo_afiliado."','".$fectr."',".$monto.",".$porcentaje.",".$comision.");";
					$resul6 = mysql_query($quer6,$link);
				}
			}
		}
	}
}
// Hasta aqui rellena la tabla para el reporte
*/

// +-----------------------------------------------------------------------+
// | Copyright (c) 2002-2005, Richard Heyes, Harald Radi                   |
// | All rights reserved.                                                  |
// |                                                                       |
// | Redistribution and use in source and binary forms, with or without    |
// | modification, are permitted provided that the following conditions    |
// | are met:                                                              |
// |                                                                       |
// | o Redistributions of source code must retain the above copyright      |
// |   notice, this list of conditions and the following disclaimer.       |
// | o Redistributions in binary form must reproduce the above copyright   |
// |   notice, this list of conditions and the following disclaimer in the |
// |   documentation and/or other materials provided with the distribution.|
// | o The names of the authors may not be used to endorse or promote      |
// |   products derived from this software without specific prior written  |
// |   permission.                                                         |
// |                                                                       |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
// |                                                                       |
// +-----------------------------------------------------------------------+
// | Author: Richard Heyes <http://www.phpguru.org/>                       |
// |         Harald Radi <harald.radi@nme.at>                              |
// +-----------------------------------------------------------------------+
//
// $Id: example.php 181173 2005-03-02 02:16:51Z richard $
//error_reporting(E_ALL | E_STRICT);
    require_once('html_tree_menu/TreeMenu.php');

    $icon         = 'folder.gif';
    $expandedIcon = 'folder-expanded.gif';

    $menu  = new HTML_TreeMenu();

	$query = "SELECT * FROM genealogia order by padre,hijo";
	if ($result = mysql_query($query,$link)) {
		$padre = '';
		$hijo = '';
		$first = true;
		$second = true;
		$nodos = array();
		while($row = mysql_fetch_array($result)) {
			if ($first) {
				$padre = $row["padre"];
				$hijo = $row["hijo"];
				$quer2 = "SELECT tit_nombres,tit_apellidos FROM afiliados where tit_codigo=".trim($padre);
				$resul2 = mysql_query($quer2,$link);
				$ro2 = mysql_fetch_array($resul2);
				$nombre = trim($ro2["tit_nombres"])." ".trim($ro2["tit_apellidos"]);
//				$nodos[$padre] = &$menu->addItem(new HTML_TreeNode(array('text' => $nombre.' - PM: '.strval(trim(number_format(rand(0,1000),0,',','.'))).' - PMO: '.strval(trim(number_format(rand(0,1000),0,',','.'))), 'link' => "test.php", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
				$nodos[$padre] = &$menu->addItem(new HTML_TreeNode(array('text' => $nombre, 'link' => "", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
				$first = false;
			}
			if ($padre<>$row["padre"]) {
				$padre = $row["padre"];
				$hijo = $row["hijo"];
				$quer2 = "SELECT tit_nombres,tit_apellidos FROM afiliados where tit_codigo='".trim($padre)."'";
				$resul2 = mysql_query($quer2,$link);
				$ro2 = mysql_fetch_array($resul2);
				$nombre = trim($ro2["tit_nombres"])." ".trim($ro2["tit_apellidos"]);
			}
			$hijo = $row["hijo"];
			$quer3 = "SELECT tit_nombres,tit_apellidos FROM afiliados where tit_codigo='".trim($hijo)."'";
			$resul3 = mysql_query($quer3,$link);
			$ro3 = mysql_fetch_array($resul3);
			$nombr2 = trim($ro3["tit_nombres"])." ".trim($ro3["tit_apellidos"]);
//			$nodos[$hijo] = &$nodos[$padre]->addItem(new HTML_TreeNode(array('text' => $nombr2.' - PM: '.strval(trim(number_format(rand(0,1000),0,',','.'))).' - PMO: '.strval(trim(number_format(rand(500,1500),0,',','.'))), 'link' => "test.php", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
			$nodos[$hijo] = &$nodos[$padre]->addItem(new HTML_TreeNode(array('text' => $nombr2, 'link' => "", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
		}
	}

    // Create the presentation class
    $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'html_tree_menu/images', 'defaultClass' => 'treeMenuDefault'));
    $listBox  = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
    //$treeMenuStatic = &new HTML_TreeMenu_staticHTML($menu, array('images' => '../images', 'defaultClass' => 'treeMenuDefault', 'noTopLevelImages' => true));

?>

GENEALOGÍA PARA 00000

<?$treeMenu->printMenu()?>


text:
<?php

declare(strict_types=1);

namespace Psi\Component\ObjectAgent\Query\Converter;

use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Composite;
use Psi\Component\ObjectAgent\Query\Join;
use Psi\Component\ObjectAgent\Query\Query;

class ArrayConverter
{
    private static $comparisons = [
        Comparison::EQUALS,
        Comparison::NOT_EQUALS,
        Comparison::GREATER_THAN,
        Comparison::GREATER_THAN_EQUAL,
        Comparison::LESS_THAN,
        Comparison::LESS_THAN_EQUAL,
        Comparison::NULL,
        Comparison::NOT_NULL,
        Comparison::IN,
        Comparison::NOT_IN,
        Comparison::CONTAINS,
        Comparison::NOT_CONTAINS,
    ];

    private static $composites = [
        Composite::AND,
        Composite::OR,
    ];

    public function __invoke(array $query)
    {
        $query = $this->merge([
            'selects' => [],
            'from' => null,
            'criteria' => null,
            'orderings' => [],
            'joins' => [],
            'firstResult' => null,
            'maxResults' => null,
        ], $query);

        if (null === $query['from']) {
            throw new \InvalidArgumentException(sprintf(
                'You must specify the "from" part of the query.'
            ));
        }

        if ($query['criteria']) {
            $query['criteria'] = new Composite(Composite::AND, $this->walkCriteria($query['criteria']));
        }

        $query['joins'] = $this->walkJoins($query['joins']);
        $from = $query['from'];
        unset($query['from']);

        return Query::create($from, $query);
    }

    private function walkJoins(array $joins)
    {
        $joinObjects = [];

        foreach ($joins as $join) {
            $join = $this->merge([
                'type' => Join::INNER_JOIN,
                'join'=> null,
                'alias' => null,
            ], $join, ['join', 'alias']);

            $joinObjects[] = new Join($join['join'], $join['alias'], $join['type']);
        }

        return $joinObjects;
    }

    private function walkCriteria(array $exprs, array $original = null)
    {
        $original = $original ?: $exprs;

        $criterias = [];
        foreach ($exprs as $operator => $right) {
            if (in_array($operator, self::$comparisons)) {
                if (!is_array($right)) {
                    throw new \InvalidArgumentException(sprintf(
                        'Comparison must have an array as the right-sided value, got "%s"',
                        gettype($right)
                    ));
                }

                foreach ($right as $field => $value) {
                    $criterias[] = new Comparison($operator, $field, $value);
                }

                continue;
            }

            if (in_array($operator, self::$composites)) {
                $criterias[] = new Composite($operator, $this->walkCriteria($right, $original));
                continue;
            }

            throw new \InvalidArgumentException(sprintf(
                'Unknown expression operator "%s" in "%s"', $operator, $this->toString($original)
            ));
        }

        return $criterias;
    }

    private function toString(array $expr)
    {
        return json_encode($expr);
    }

    private function merge(array $defaults, array $values, array $required = [])
    {
        if ($diff = array_diff($required, array_keys($values))) {
            throw new \InvalidArgumentException(sprintf(
                'Keys "%s" are required for "%s"',
                implode('", "', $diff), json_encode($values)
            ));
        }

        if ($diff = array_diff(array_keys($values), array_keys($defaults))) {
            throw new \InvalidArgumentException(sprintf(
                'Invalid query keys "%s", valid keys: "%s"',
                implode('", "', $diff), implode('", "', array_keys($defaults))
            ));
        }

        return array_merge($defaults, $values);
    }
}


text:
<?php

namespace Magento\Framework\Setup\Test\Unit\Option;

use Magento\Framework\Setup\Option\SelectConfigOption;
use Magento\Framework\Setup\Option\TextConfigOption;

class TextConfigOptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Frontend input type has to be 'text', 'textarea' or 'password'.
     */
    public function testConstructInvalidFrontendType()
    {
        new TextConfigOption('test', SelectConfigOption::FRONTEND_WIZARD_SELECT, 'path/to/value');
    }

    public function testGetFrontendType()
    {
        $option = new TextConfigOption('test', TextConfigOption::FRONTEND_WIZARD_TEXT, 'path/to/value');
        $this->assertEquals(TextConfigOption::FRONTEND_WIZARD_TEXT, $option->getFrontendType());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage must be a string
     */
    public function testValidateException()
    {
        $option = new TextConfigOption('test', TextConfigOption::FRONTEND_WIZARD_TEXT, 'path/to/value');
        $option->validate(1);
    }
}


text:
using System.Collections.Generic;

namespace Falkor.Application
{
  public interface IHandlerModule
  {
    IEnumerable<IHandle<object>> TryResolve(object message);
  }
}


text:
#include <aws/ec2/model/FleetStateCode.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace EC2
  {
    namespace Model
    {
      namespace FleetStateCodeMapper
      {

        static const int submitted_HASH = HashingUtils::HashString("submitted");
        static const int active_HASH = HashingUtils::HashString("active");
        static const int deleted_HASH = HashingUtils::HashString("deleted");
        static const int failed_HASH = HashingUtils::HashString("failed");
        static const int deleted_running_HASH = HashingUtils::HashString("deleted-running");
        static const int deleted_terminating_HASH = HashingUtils::HashString("deleted-terminating");
        static const int modifying_HASH = HashingUtils::HashString("modifying");

        FleetStateCode GetFleetStateCodeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == submitted_HASH)
          {
            return FleetStateCode::submitted;
          }
          else if (hashCode == active_HASH)
          {
            return FleetStateCode::active;
          }
          else if (hashCode == deleted_HASH)
          {
            return FleetStateCode::deleted;
          }
          else if (hashCode == failed_HASH)
          {
            return FleetStateCode::failed;
          }
          else if (hashCode == deleted_running_HASH)
          {
            return FleetStateCode::deleted_running;
          }
          else if (hashCode == deleted_terminating_HASH)
          {
            return FleetStateCode::deleted_terminating;
          }
          else if (hashCode == modifying_HASH)
          {
            return FleetStateCode::modifying;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<FleetStateCode>(hashCode);
          }

          return FleetStateCode::NOT_SET;
        }

        Aws::String GetNameForFleetStateCode(FleetStateCode enumValue)
        {
          switch(enumValue)
          {
          case FleetStateCode::submitted:
            return "submitted";
          case FleetStateCode::active:
            return "active";
          case FleetStateCode::deleted:
            return "deleted";
          case FleetStateCode::failed:
            return "failed";
          case FleetStateCode::deleted_running:
            return "deleted-running";
          case FleetStateCode::deleted_terminating:
            return "deleted-terminating";
          case FleetStateCode::modifying:
            return "modifying";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace FleetStateCodeMapper
    } // namespace Model
  } // namespace EC2
} // namespace Aws


text:
ERROR=""

# Initialize profile.cov
echo "mode: count" > coverage/profile.cov

die() {
    echo $*
    exit 1
}

# Standard go tooling behavior is to ignore dirs with leading underscors
for dir in $(find . -maxdepth 10 -not -path './.git*' -not -path '*/_*' -not -path '*/vendor/*' -type d);
do
    if ls $dir/*.go &> /dev/null; then
        godep go test -short -covermode=count -coverprofile=$dir/profile.tmp $dir
        if [ -f $dir/profile.tmp ]
        then
            cat $dir/profile.tmp | tail -n +2 >> coverage/profile.cov || die "Unable to append coverage for $pkg"
            rm $dir/profile.tmp
        fi
    fi
done

if [ ! -z "$ERROR" ]
then
    die "Encountered error, last error was: $ERROR"
fi


text:
<?php
namespace SinglePay\PaymentService\Element\Express\Enum;

class TransactionSetupMethod
{
    const __default = 'Null';
    const Null = 'Null';
    const CreditCardSale = 'CreditCardSale';
    const CreditCardAuthorization = 'CreditCardAuthorization';
    const CreditCardAVSOnly = 'CreditCardAVSOnly';
    const CreditCardForce = 'CreditCardForce';
    const DebitCardSale = 'DebitCardSale';
    const CheckSale = 'CheckSale';
    const PaymentAccountCreate = 'PaymentAccountCreate';
    const PaymentAccountUpdate = 'PaymentAccountUpdate';
    const Sale = 'Sale';
}


text:
var os = require('os');
var _ = require('lodash');

function getExternalInterfaces() {
    var ifaces = os.networkInterfaces();
    return _.pick(ifaces, function (iface) {
        return _.some(iface, function (ifaceDetail) {
            return (ifaceDetail.internal === false)
        });
    });
}

function getAddress(interfaces, interface, family) {
    if (!family) family = 'IPv4';
    if (!(interface in interfaces)) return null;

    var result = _.find(interfaces[interface], function(iface) {
        return iface.family === family;
    });

    if (!result) return null;

    return result.address;
}

module.exports.getExternalInterfaces = getExternalInterfaces;
module.exports.getAddress = getAddress;


text:
package org.apereo.cas.support.saml.services.idp.metadata.cache;

import org.apereo.cas.support.saml.services.SamlRegisteredService;

import org.opensaml.saml.metadata.resolver.MetadataResolver;

/**
 * This is {@link SamlRegisteredServiceCachingMetadataResolver}
 * that defines how metadata is to be resolved and cached for a given saml
 * registered service.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public interface SamlRegisteredServiceCachingMetadataResolver {

    /**
     * Resolve chaining metadata resolver.
     *
     * @param service the service
     * @return the chaining metadata resolver
     */
    MetadataResolver resolve(SamlRegisteredService service);

    /**
     * Invalid and clean the result of all previous operations.
     * Invocation of this method is expected to force a clean
     * resolution of the metadata for all follow-up requests, disregarding
     * any and all cached results.
     */
    void invalidate();

    /**
     * Invalid and clean the result of previous operations for the given service.
     * Invocation of this method is expected to force a clean
     * resolution of the metadata for all follow-up requests that apply to the given service (relying party),
     * disregarding any and all cached results.
     *
     * @param service the service
     */
    void invalidate(SamlRegisteredService service);
}


text:
package com.didi.virtualapk.internal;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextThemeWrapper;

import com.didi.virtualapk.PluginManager;
import com.didi.virtualapk.utils.PluginUtil;
import com.didi.virtualapk.utils.ReflectUtil;

/**
 * Created by renyugang on 16/8/10.
 */
public class VAInstrumentation extends Instrumentation implements Handler.Callback {
    public static final String TAG = "VAInstrumentation";
    public static final int LAUNCH_ACTIVITY         = 100;

    private Instrumentation mBase;

    PluginManager mPluginManager;

    public VAInstrumentation(PluginManager pluginManager, Instrumentation base) {
        this.mPluginManager = pluginManager;
        this.mBase = base;
    }

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        mPluginManager.getComponentsHandler().transformIntentToExplicitAsNeeded(intent);
        // null component is an implicitly intent
        if (intent.getComponent() != null) {
            Log.i(TAG, String.format("execStartActivity[%s : %s]", intent.getComponent().getPackageName(),
                    intent.getComponent().getClassName()));
            // resolve intent with Stub Activity if needed
            this.mPluginManager.getComponentsHandler().markIntentIfNeeded(intent);
        }

        ActivityResult result = realExecStartActivity(who, contextThread, token, target,
                    intent, requestCode, options);

        return result;

    }

    private ActivityResult realExecStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        ActivityResult result = null;
        try {
            Class[] parameterTypes = {Context.class, IBinder.class, IBinder.class, Activity.class, Intent.class,
            int.class, Bundle.class};
            result = (ActivityResult)ReflectUtil.invoke(Instrumentation.class, mBase,
                    "execStartActivity", parameterTypes,
                    who, contextThread, token, target, intent, requestCode, options);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        try {
            cl.loadClass(className);
        } catch (ClassNotFoundException e) {
            LoadedPlugin plugin = this.mPluginManager.getLoadedPlugin(intent);
            String targetClassName = PluginUtil.getTargetActivity(intent);

            Log.i(TAG, String.format("newActivity[%s : %s]", className, targetClassName));

            if (targetClassName != null) {
                Activity activity = mBase.newActivity(plugin.getClassLoader(), targetClassName, intent);
                activity.setIntent(intent);

                try {
                    // for 4.1+
                    ReflectUtil.setField(ContextThemeWrapper.class, activity, "mResources", plugin.getResources());
                } catch (Exception ignored) {
                    // ignored.
                }

                return activity;
            }
        }

        return mBase.newActivity(cl, className, intent);
    }

    @Override
    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        final Intent intent = activity.getIntent();
        if (PluginUtil.isIntentFromPlugin(intent)) {
            Context base = activity.getBaseContext();
            try {
                LoadedPlugin plugin = this.mPluginManager.getLoadedPlugin(intent);
                ReflectUtil.setField(base.getClass(), base, "mResources", plugin.getResources());
                ReflectUtil.setField(ContextWrapper.class, activity, "mBase", plugin.getPluginContext());
                ReflectUtil.setField(Activity.class, activity, "mApplication", plugin.getApplication());
                ReflectUtil.setFieldNoException(ContextThemeWrapper.class, activity, "mBase", plugin.getPluginContext());

                // set screenOrientation
                ActivityInfo activityInfo = plugin.getActivityInfo(PluginUtil.getComponent(intent));
                if (activityInfo.screenOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
                    activity.setRequestedOrientation(activityInfo.screenOrientation);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        mBase.callActivityOnCreate(activity, icicle);
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == LAUNCH_ACTIVITY) {
            // ActivityClientRecord r
            Object r = msg.obj;
            try {
                Intent intent = (Intent) ReflectUtil.getField(r.getClass(), r, "intent");
                intent.setExtrasClassLoader(VAInstrumentation.class.getClassLoader());
                ActivityInfo activityInfo = (ActivityInfo) ReflectUtil.getField(r.getClass(), r, "activityInfo");

                if (PluginUtil.isIntentFromPlugin(intent)) {
                    int theme = PluginUtil.getTheme(mPluginManager.getHostContext(), intent);
                    if (theme != 0) {
                        Log.i(TAG, "resolve theme, current theme:" + activityInfo.theme + "  after :0x" + Integer.toHexString(theme));
                        activityInfo.theme = theme;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    @Override
    public Context getContext() {
        return mBase.getContext();
    }

    @Override
    public Context getTargetContext() {
        return mBase.getTargetContext();
    }

    @Override
    public ComponentName getComponentName() {
        return mBase.getComponentName();
    }

}


text:
package com.google.cloud.runtimes.tomcat.test.integration;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/"})
public class HelloServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setContentType("text.plain");
    resp.getWriter().print("Hello World!");
  }

}


text:
layout:  post
title:  Spring Data and Spring Data JPA - Quick Tutorial for Beginners
date:   2022-04-10 12:31:19
summary: In this article, we take a look at Spring Data and Spring Data JPA.
categories:  SpringBoot
permalink:  /introduction-to-spring-data-and-spring-data-jpa
image: /images/spring-data-category.png
---

In this article, we take a look at Spring Data and Spring Data JPA.

![image info](images/Capture-081-02.png)

### You will Learn

- What are the challenges with existing data store integration solutions?
- What is Spring Data?
- What are the aims of Spring Data?
- How does Spring Data abstract talking to different data stores?
- What is Spring Data JPA?
- How does Spring Data JPA help in making JPA easier?

### Challenges with Existing Data Store solutions

Let's start with looking at problems with some of the existing solutions for storing data to data stores.

#### Duplication of Code

Let's start with looking at one of the important challenges with JPA - Duplicate code.

Let's look at a couple of data layer classes to manage Passport and Student entities.

#### Passport

```java

	@PersistenceContext
	private EntityManager entityManager;

	public Passport getPassport(final long id) {
		return entityManager.find(Passport.class, id);
	}

	public Passport createPassport(Passport passport) {
		return entityManager.merge(passport);
	}

```

#### Student

```java

	@PersistenceContext
	private EntityManager entityManager;

	public Student retrieveStudent(final long id) {
		return entityManager.find(Student.class, id);
	}

	public Student createStudent(Studetn student) {
		return entityManager.merge(student);
	}

```

When we look at the above two snippets of code, we can see that there is a lot of similarity in the code structurally. Any additional methods written for the two entities would be very similar.

A straightforward approach to deal with such duplication would be to create a common interface to extract the functionality, and implement that interface in an application.

#### Explosion Of Data Stores

Nowadays, we are not confined to talking to just relational databases. We have a variety of data stores including NoSQL data stores such as MongoDB, Hadoop and Cassandra.

### Spring Data

Spring Data provides common abstractions to store and retrieve data from a data store. This eliminates the need to connect and interact differently, with different types of data stores.

Such abstractions allow you to connect in the same way to relational databases and NO-SQL databases. It enables you to switch effortlessly between data stores.

### Spring Data JPA

Spring Data JPA is an extension of Spring Data, to connect to JPA - concerned with talking with relational databases.

#### Using Spring Data JPA

This is how you go about using this framework:

```java

	public interface StudentRepository extends CrudRepository<Student, Long> {
		//...
	}

	public interface PassportRepository extends CrudRepository<Passport, Long> {
		//...
	}

```

Each of the repositories extends the base ```CrudRepository```, which is a repository that supports the CRUD operations - Create, read, Update and Delete.

#### CrudRepository Interface

Let's look at some of the methods in ```CrudRepository``` ```interface```:

```java

	public interface Crudrepository<T, ID> extends Repository<T, ID> {
		<S extends T> S save(Entity s);
		Optional<T> findById(ID id);
		boolean existsById(ID id);
		Iterable<T> findAll();
		void deleteById(ID id);
		long count();
		//Other methods
	}

```

### Exploring Other Repositories

The ```CrudRepository``` is a very useful interface, and there are other repositories built on top of this. Let's look at a few of them.

#### The PaginationAndSortingRepository

```java

	public interface PaginationAndSortingRepository<T, ID> extends CrudRepository<T,ID> {
		Iterable<T> findAll(Sort sort);
		Page<T> findAll(Pageable pageable);
	}

```

If you wanted to access a particular page in a set of search results, or want them sorted in a specific order, then this repository is of good use.

Do check out our video on the same topic:

[![image info](images/Capture-083-01.png)](https://www.youtube.com/watch?v=bg0_9FsOI64)

### Summary

In this article, we talked about Spring Data, and Spring Data JPA.

Spring Data offers common abstractions, which allows us to talk to different data stores, both relational and otherwise. It is independent of any kind of data store. Spring Data JPA is an Spring Data Extension to work with JPA relational data stores.