text:
package org.b3log.solo.repository;

import org.b3log.latke.Keys;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.Transaction;
import org.b3log.solo.AbstractTestCase;
import org.b3log.solo.model.Article;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Date;
import java.util.List;

/**
 * {@link ArticleRepository} test case.
 *
 * @author Liang Ding
 * @version 1.0.0.5, Feb 25, 2019
 */
@Test(suiteName = "repository")
public final class ArticleRepositoryImplTestCase extends AbstractTestCase {

    /**
     * Adds successfully.
     *
     * @throws Exception exception
     */
    @Test
    public void add() throws Exception {
        final ArticleRepository articleRepository = getArticleRepository();

        final JSONObject article = new JSONObject();

        article.put(Article.ARTICLE_TITLE, "article title1");
        article.put(Article.ARTICLE_ABSTRACT, "article abstract");
        article.put(Article.ARTICLE_ABSTRACT_TEXT, "article abstract text");
        article.put(Article.ARTICLE_TAGS_REF, "tag1, tag2");
        article.put(Article.ARTICLE_AUTHOR_ID, "1");
        article.put(Article.ARTICLE_COMMENT_COUNT, 0);
        article.put(Article.ARTICLE_VIEW_COUNT, 0);
        article.put(Article.ARTICLE_CONTENT, "article content");
        article.put(Article.ARTICLE_PERMALINK, "article permalink1");
        article.put(Article.ARTICLE_STATUS, Article.ARTICLE_STATUS_C_PUBLISHED);
        article.put(Article.ARTICLE_PUT_TOP, false);
        article.put(Article.ARTICLE_CREATED, new Date().getTime());
        article.put(Article.ARTICLE_UPDATED, new Date().getTime());
        article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random());
        article.put(Article.ARTICLE_SIGN_ID, "1");
        article.put(Article.ARTICLE_COMMENTABLE, true);
        article.put(Article.ARTICLE_VIEW_PWD, "");
        article.put(Article.ARTICLE_IMG1_URL, Article.getArticleImg1URL(article));

        final Transaction transaction = articleRepository.beginTransaction();
        articleRepository.add(article);
        transaction.commit();

        final JSONArray results = articleRepository.getByAuthorId("1", 1, Integer.MAX_VALUE).getJSONArray(Keys.RESULTS);

        Assert.assertEquals(results.length(), 1);
    }

    /**
     * Get by permalink.
     *
     * @throws Exception exception
     */
    @Test(dependsOnMethods = "add")
    public void getByPermalink() throws Exception {
        final ArticleRepository articleRepository = getArticleRepository();
        final JSONObject article = articleRepository.getByPermalink("article permalink1");

        Assert.assertNotNull(article);
        Assert.assertEquals(article.getString(Article.ARTICLE_TITLE), "article title1");

        Assert.assertNull(articleRepository.getByPermalink("not found"));
    }

    /**
     * Get by permalink.
     *
     * @throws Exception exception
     */
    @Test(dependsOnMethods = {"add"})
    public void previousAndNext() throws Exception {
        final ArticleRepository articleRepository = getArticleRepository();

        final JSONObject article = new JSONObject();

        article.put(Article.ARTICLE_TITLE, "article title2");
        article.put(Article.ARTICLE_ABSTRACT, "article abstract");
        article.put(Article.ARTICLE_ABSTRACT_TEXT, "article abstract text");
        article.put(Article.ARTICLE_TAGS_REF, "tag1, tag2");
        article.put(Article.ARTICLE_AUTHOR_ID, "1");
        article.put(Article.ARTICLE_COMMENT_COUNT, 1);
        article.put(Article.ARTICLE_VIEW_COUNT, 1);
        article.put(Article.ARTICLE_CONTENT, "article content");
        article.put(Article.ARTICLE_PERMALINK, "article permalink2");
        article.put(Article.ARTICLE_STATUS, Article.ARTICLE_STATUS_C_PUBLISHED);
        article.put(Article.ARTICLE_PUT_TOP, false);
        article.put(Article.ARTICLE_CREATED, new Date().getTime());
        article.put(Article.ARTICLE_UPDATED, new Date().getTime());
        article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random());
        article.put(Article.ARTICLE_SIGN_ID, "1");
        article.put(Article.ARTICLE_COMMENTABLE, true);
        article.put(Article.ARTICLE_VIEW_PWD, "");
        article.put(Article.ARTICLE_IMG1_URL, Article.getArticleImg1URL(article));

        final Transaction transaction = articleRepository.beginTransaction();
        articleRepository.add(article);
        transaction.commit();

        Assert.assertEquals(articleRepository.count(), 2);

        JSONObject previousArticle = articleRepository.getPreviousArticle(article.getString(Keys.OBJECT_ID));

        Assert.assertNotNull(previousArticle);
        Assert.assertEquals(previousArticle.getString(Article.ARTICLE_TITLE), "article title1");
        Assert.assertEquals(previousArticle.getString(Article.ARTICLE_PERMALINK), "article permalink1");
        Assert.assertNull(previousArticle.opt(Keys.OBJECT_ID));

        previousArticle = articleRepository.getByPermalink(previousArticle.getString(Article.ARTICLE_PERMALINK));

        final JSONObject nextArticle = articleRepository.getNextArticle(previousArticle.getString(Keys.OBJECT_ID));
        Assert.assertNotNull(previousArticle);
        Assert.assertEquals(nextArticle.getString(Article.ARTICLE_TITLE), "article title2");
    }

    /**
     * Get Most Comment Articles.
     *
     * @throws Exception exception
     */
    @Test(dependsOnMethods = {"add", "previousAndNext"})
    public void getMostCommentArticles() throws Exception {
        final ArticleRepository articleRepository = getArticleRepository();

        final JSONObject article = new JSONObject();

        article.put(Article.ARTICLE_TITLE, "article title3");
        article.put(Article.ARTICLE_ABSTRACT, "article abstract");
        article.put(Article.ARTICLE_ABSTRACT_TEXT, "article abstract text");
        article.put(Article.ARTICLE_TAGS_REF, "tag1, tag2");
        article.put(Article.ARTICLE_AUTHOR_ID, "1");
        article.put(Article.ARTICLE_COMMENT_COUNT, 2);
        article.put(Article.ARTICLE_VIEW_COUNT, 2);
        article.put(Article.ARTICLE_CONTENT, "article content");
        article.put(Article.ARTICLE_PERMALINK, "article permalink3");
        article.put(Article.ARTICLE_STATUS, Article.ARTICLE_STATUS_C_PUBLISHED);
        article.put(Article.ARTICLE_PUT_TOP, false);
        article.put(Article.ARTICLE_CREATED, new Date().getTime());
        article.put(Article.ARTICLE_UPDATED, new Date().getTime());
        article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random());
        article.put(Article.ARTICLE_SIGN_ID, "1");
        article.put(Article.ARTICLE_COMMENTABLE, true);
        article.put(Article.ARTICLE_VIEW_PWD, "");
        article.put(Article.ARTICLE_IMG1_URL, Article.getArticleImg1URL(article));

        final Transaction transaction = articleRepository.beginTransaction();
        articleRepository.add(article);
        transaction.commit();

        List<JSONObject> mostCommentArticles = articleRepository.getMostCommentArticles(2);
        Assert.assertNotNull(mostCommentArticles);
        Assert.assertEquals(mostCommentArticles.size(), 2);
        Assert.assertEquals(mostCommentArticles.get(0).getInt(Article.ARTICLE_COMMENT_COUNT), 2);
        Assert.assertEquals(mostCommentArticles.get(1).getInt(Article.ARTICLE_COMMENT_COUNT), 1);

        mostCommentArticles = articleRepository.getMostCommentArticles(1);
        Assert.assertNotNull(mostCommentArticles);
        Assert.assertEquals(mostCommentArticles.size(), 1);
        Assert.assertEquals(mostCommentArticles.get(0).getInt(Article.ARTICLE_COMMENT_COUNT), 2);
    }

    /**
     * Get Most View Count Articles
     *
     * @throws Exception exception
     */
    @Test(dependsOnMethods = {"add", "previousAndNext", "getMostCommentArticles"})
    public void getMostViewCountArticles() throws Exception {
        final ArticleRepository articleRepository = getArticleRepository();

        final JSONObject article = new JSONObject();

        article.put(Article.ARTICLE_TITLE, "article title4");
        article.put(Article.ARTICLE_ABSTRACT, "article abstract");
        article.put(Article.ARTICLE_ABSTRACT_TEXT, "article abstract text");
        article.put(Article.ARTICLE_TAGS_REF, "tag1, tag2");
        article.put(Article.ARTICLE_AUTHOR_ID, "1");
        article.put(Article.ARTICLE_COMMENT_COUNT, 3);
        article.put(Article.ARTICLE_VIEW_COUNT, 3);
        article.put(Article.ARTICLE_CONTENT, "article content");
        article.put(Article.ARTICLE_PERMALINK, "article permalink4");
        article.put(Article.ARTICLE_STATUS, Article.ARTICLE_STATUS_C_DRAFT);
        article.put(Article.ARTICLE_PUT_TOP, false);
        article.put(Article.ARTICLE_CREATED, new Date().getTime());
        article.put(Article.ARTICLE_UPDATED, new Date().getTime());
        article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random());
        article.put(Article.ARTICLE_SIGN_ID, "1");
        article.put(Article.ARTICLE_COMMENTABLE, true);
        article.put(Article.ARTICLE_VIEW_PWD, "");
        article.put(Article.ARTICLE_IMG1_URL, Article.getArticleImg1URL(article));

        final Transaction transaction = articleRepository.beginTransaction();
        articleRepository.add(article);
        transaction.commit();

        List<JSONObject> mostViewCountArticles = articleRepository.getMostViewCountArticles(2);
        Assert.assertNotNull(mostViewCountArticles);
        Assert.assertEquals(mostViewCountArticles.size(), 2);
        Assert.assertEquals(mostViewCountArticles.get(0).getInt(Article.ARTICLE_VIEW_COUNT), 2);
        Assert.assertEquals(mostViewCountArticles.get(1).getInt(Article.ARTICLE_VIEW_COUNT), 1);

        mostViewCountArticles = articleRepository.getMostViewCountArticles(1);
        Assert.assertNotNull(mostViewCountArticles);
        Assert.assertEquals(mostViewCountArticles.size(), 1);
        Assert.assertEquals(mostViewCountArticles.get(0).getInt(Article.ARTICLE_VIEW_COUNT), 2);

    }

    /**
     * Get Randomly.
     *
     * @throws Exception exception
     */
    @Test(dependsOnMethods = {"add", "previousAndNext", "getMostCommentArticles", "getMostViewCountArticles"})
    public void getRandomly() throws Exception {
        final ArticleRepository articleRepository = getArticleRepository();

        List<JSONObject> articles = articleRepository.getRandomly(3);
        Assert.assertNotNull(articles);
    }

    /**
     * Get Recent Articles.
     *
     * @throws Exception exception
     */
    @Test(dependsOnMethods = {"add", "previousAndNext", "getMostCommentArticles", "getMostViewCountArticles"})
    public void getRecentArticles() throws Exception {
        final ArticleRepository articleRepository = getArticleRepository();

        Assert.assertEquals(articleRepository.count(), 4);

        List<JSONObject> recentArticles = articleRepository.getRecentArticles(3);
        Assert.assertNotNull(recentArticles);
        Assert.assertEquals(recentArticles.size(), 3);

        Assert.assertEquals(recentArticles.get(0).getString(Article.ARTICLE_TITLE), "article title3");
        Assert.assertEquals(recentArticles.get(1).getString(Article.ARTICLE_TITLE), "article title2");
        Assert.assertEquals(recentArticles.get(2).getString(Article.ARTICLE_TITLE), "article title1");
    }

    /**
     * Is Published.
     *
     * @throws Exception exception
     */
    @Test(dependsOnMethods = {"add", "getMostViewCountArticles"})
    public void isPublished() throws Exception {
        final ArticleRepository articleRepository = getArticleRepository();

        final JSONArray all = articleRepository.get(new Query()).getJSONArray(Keys.RESULTS);
        Assert.assertNotNull(all);

        final JSONObject article = all.getJSONObject(0);
        Assert.assertTrue(articleRepository.isPublished(article.getString(Keys.OBJECT_ID)));

        final JSONObject notPublished = articleRepository.getByPermalink("article permalink4");
        Assert.assertNotNull(notPublished);
        Assert.assertEquals(Article.ARTICLE_STATUS_C_DRAFT, notPublished.optInt(Article.ARTICLE_STATUS));

        Assert.assertFalse(articleRepository.isPublished("not found"));
    }
}


text:
{% extends "content_template.html" %}

{% from "components/page-header.html" import page_header %}

{# Used by the content_template.html layout, prefixes the "navigation" accessible name #}
{% set navigation_label_prefix = 'Pricing information' %}

{% block per_page_title %}
  How to pay
{% endblock %}

{% block content_column_content %}

    {{ page_header('How to pay') }}

      If you use GOV.UK Notify to send text messages or letters, you may need to send us a purchase order.

      Invoices

      Notify is run by the Government Digital Service (GDS), part of the Cabinet Office.

      The Cabinet Office will send your organisation an invoice each quarter if you:

exceed the free text message allowance

send letters

      If your organisation has more than one Notify service, you'll see a breakdown of each service on your invoice.

      If the value of an invoice is less than £250 (before VAT), it will be added to the total for the next quarter to save time and effort.

      You can pay by BACS, debit card, or credit card.

      Please start your payment reference with the invoice number.

      Purchase orders

      If your organisation's total estimated spend is more than £500 per quarter (before VAT), you need to raise a purchase order (PO).

      Your organisation should raise a single PO for the estimated cost of all its services. You can update the PO any time if your usage increases.

      Your organisation may need to add the Cabinet Office as a supplier before you can raise a PO.

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
const constants = require('../../common/constants');

const User = require('../../model/user');
const Bookmark = require('../../model/bookmark');

const ValidationError = require('../../error/validation.error');
const NotFoundError = require('../../error/not-found.error');
const PublicBookmarksService = require('../public/public-bookmarks.service');

let createUserData = async function (userData, userId) {

  validateUserData(userData, userId);

  const newUserData = new User({
    userId: userId,
    profile: userData.profile,
    searches: userData.searches,
    recentSearches: userData.recentSearches,
    readLater: userData.readLater,
    likes: userData.likes,
    watchedTags: userData.watchedTags,
    ignoredTags: userData.ignoredTags,
    pinned: userData.pinned,
    favorites: userData.favorites,
    history: userData.history
  });

  const createdUserData = await newUserData.save();

  return createdUserData;
}

let updateUserData = async function (userData, userId) {
  validateUserData(userData, userId);

  delete userData._id;//once we proved it's present we delete it to avoid the following MOngoError by findOneAndUpdate
  // MongoError: After applying the update to the document {_id: ObjectId('5c513150e13cda73420a9602') , ...}, the (immutable) field '_id' was found to have been altered to _id: "5c513150e13cda73420a9602"
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userData.userId},
    userData,
    {upsert: true, new: true}, // options
  );

  return updatedUserData;
}

let updateUserDataHistory = async function (history, userId) {
  history = trimMaxAllowedStoreLength(history, constants.MAX_NUMBER_STORED_BOOKMARKS_FOR_PERSONAL_STORE);
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {
      $set: {history: history}
    }
  );

  return updatedUserData;
}

let updateUserDataFeedToggle = async function (showAllPublicInFeed, userId) {
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {
      $set: {showAllPublicInFeed: showAllPublicInFeed}
    }
  );

  return updatedUserData;
}

let updateUserDataWelcomeAck = async function ( userId) {
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {
      $set: {welcomeAck: true}
    }
  );

  return updatedUserData;
}

let updateLocalStorageOption = async function (enableLocalStorage, userId) {
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {
      $set: {enableLocalStorage: enableLocalStorage}
    }
  );

  return updatedUserData;
}

//hold max number of bookmarks in history or pinned
let trimMaxAllowedStoreLength = function (storeItems, limit) {
  if ( storeItems.length > limit ) {
    return storeItems.slice(0, limit);
  }
  return storeItems;
};

let updateUserDataPinned = async function (pinned, userId) {
  pinned = trimMaxAllowedStoreLength(pinned, constants.MAX_NUMBER_STORED_BOOKMARKS_FOR_PERSONAL_STORE);
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {
      $set: {pinned: pinned}
    }
  );

  return updatedUserData;
}

let updateUserDataReadLater = async function (readLater, userId) {
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {
      $set: {readLater: readLater}
    }
  );

  return updatedUserData;
}

let updateUserDataHistoryReadLaterPinned = async function (input, userId) {

  let {history, readLater, pinned} = input;

  history = trimMaxAllowedStoreLength(history, constants.MA);
  let updateInput = {history: history};

  if(Array.isArray(readLater) && readLater.length){
    updateInput.readLater = readLater;
  }

  if(Array.isArray(pinned) && pinned.length){
    pinned = trimMaxAllowedStoreLength(pinned, constants.MAX_NUMBER_STORED_BOOKMARKS_FOR_PERSONAL_STORE);
    updateInput.pinned = pinned;
  }

  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {
      $set: updateInput
    }
  );

  return updatedUserData;
}

function validateUserData(userData, userId) {

  let validationErrorMessages = [];

  const invalidUserIdInUserData = !userData.userId || userData.userId !== userId;
  if ( invalidUserIdInUserData ) {
    validationErrorMessages.push('Missing or invalid userId in provided user data');
  }

  if ( !userSearchesAreValid(userData) ) {
    validationErrorMessages.push('Searches are not valid - search text is required');
  }

  if ( validationErrorMessages.length > 0 ) {
    throw new ValidationError('Submitted user data is not valid', validationErrorMessages);
  }
}

function userSearchesAreValid(userData) {
  const searches = userData.searches;
  if ( searches && searches.length > 0 ) {
    for ( let i = 0; i < searches.length; i++ ) {
      if ( !searches[i].text ) {
        return false;
      }
    }
  }

  return true;
}

/**
 * Returns user data
 *  - with only latest 50 recentSearches
 *  - the followers are added to response (default deactivated)
 */
let getUserData = async function (userId) {
  const userData = await User.findOne({
    userId: userId
  }, {"recentSearches": { $slice: 50 }}).select("+followers");

  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    return userData;
  }
}

let deleteUserData = async function (userId) {
  const userData = await User.findOneAndRemove({
    userId: userId
  });

  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    return 'user deleted';
  }
}

let getReadLater = async function (userId, page, limit) {

  const userData = await User.findOne({
    userId: userId
  });
  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    const readLaterRangeIds = userData.readLater.slice((page - 1) * limit, (page - 1) * limit + limit);
    const bookmarks = await Bookmark.find({"_id": {$in: readLaterRangeIds}});

    return bookmarks;
  }
}

let getLikedBookmarks = async function (userId) {

  const userData = await User.findOne({
    userId: userId
  });
  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    const bookmarks = await Bookmark.find({"_id": {$in: userData.likes}});

    return bookmarks;
  }
}

let getUsedTagsForPublicBookmarks = async function (userId) {

  const aggregatedTags = await Bookmark.aggregate([
    //first stage - filter
    {
      $match: {
        userId: userId,
        public: true,
      },
    },

    //second stage - unwind tags
    {$unwind: "$tags"},

    //third stage - group
    {
      $group: {
        _id: {
          tag: '$tags'
        },
        count: {
          $sum: 1
        }
      }
    },

    //fourth stage - order by count desc
    {
      $sort: {count: -1}
    }

  ]);

  const usedTags = aggregatedTags.map(aggregatedTag => {
    return {
      name: aggregatedTag._id.tag,
      count: aggregatedTag.count
    }
  });

  return usedTags;
}

let getUsedTagsForPrivateBookmarks = async function (userId) {

  const aggregatedTags = await Bookmark.aggregate([
    //first stage - filter
    {
      $match: {
        userId: userId,
        public: false
      },
    },

    //second stage - unwind tags
    {$unwind: "$tags"},

    //third stage - group
    {
      $group: {
        _id: {
          tag: '$tags'
        },
        count: {
          $sum: 1
        }
      }
    },

    //fourth stage - order by count desc
    {
      $sort: {count: -1}
    }

  ]);

  const usedTags = aggregatedTags.map(aggregatedTag => {
    return {
      name: aggregatedTag._id.tag,
      count: aggregatedTag.count
    }
  });

  return usedTags;
}

let getPinnedBookmarks = async function (userId, page, limit) {

  const userData = await User.findOne({
    userId: userId
  });
  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    const pinnedRangeIds = userData.pinned.slice((page - 1) * limit, (page - 1) * limit + limit);
    const bookmarks = await Bookmark.find({"_id": {$in: pinnedRangeIds}});
    //we need to order the bookmarks to correspond the one in the userData.pinned array
    const orderedBookmarksAsInPinned = bookmarks.sort(function (a, b) {
      return pinnedRangeIds.indexOf(a._id) - pinnedRangeIds.indexOf(b._id);
    });

    return orderedBookmarksAsInPinned.filter(bookmark => bookmark !== undefined);
  }
}

/**
 * Deprecated - might get reactivated if community decides for it
 *
 */
let getFavoriteBookmarks = async function (userId, page, limit) {
  const userData = await User.findOne({
    userId: userId
  });
  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    const favoritesRangeIds = userData.favorites.slice((page - 1) * limit, (page - 1) * limit + limit);
    const bookmarks = await Bookmark.find({"_id": {$in: favoritesRangeIds}});
    //we need to order the bookmarks to correspond the one in the userData.favorites array
    const orderedBookmarksAsInFavorites = bookmarks.sort(function (a, b) {
      return favoritesRangeIds.indexOf(a._id) - favoritesRangeIds.indexOf(b._id);
    });

    return orderedBookmarksAsInFavorites;
  }
}

let getBookmarksFromHistory = async function (userId, page, limit) {

  const userData = await User.findOne({
    userId: userId
  });
  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    const historyRangeIds = userData.history.slice((page - 1) * limit, (page - 1) * limit + limit);
    const bookmarks = await Bookmark.find({"_id": {$in: historyRangeIds}});

    //we need to order the bookmarks to correspond the one in the userData.history array
    const orderedBookmarksAsInHistory = bookmarks.sort(function (a, b) {
      return historyRangeIds.indexOf(a._id) - historyRangeIds.indexOf(b._id);
    });

    //check for "potentially" deleted bookmarks via "delete all private for tag"
    //return orderedBookmarksAsInHistory.filter(bookmark => bookmark !== undefined);
    return orderedBookmarksAsInHistory;
  }
}

let getAllBookmarksFromHistory = async function (userId) {

  const userData = await User.findOne({
    userId: userId
  });
  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    const bookmarks = await Bookmark.find({"_id": {$in: userData.history}});

    //we need to order the bookmarks to correspond the one in the userData.history array
    const allBookmarksOrderedFromHistory = bookmarks.sort(function (a, b) {
      return userData.history.indexOf(a._id) - userData.history.indexOf(b._id);
    });

    //check for "potentially" deleted bookmarks via "delete all private for tag"
    //return orderedBookmarksAsInHistory.filter(bookmark => bookmark !== undefined);
    return allBookmarksOrderedFromHistory;
  }
}

let rateBookmark = async function (receivedUserData, userId, bookmarkId) {

  validateInputForBookmarkRating(receivedUserData, userId);

  const userData = await User.findOne({
    userId: userId
  });

  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    if ( receivedUserData.action === 'LIKE' ) {
      return await likeBookmark(userData, userId, bookmarkId);
    } else if ( receivedUserData.action === 'UNLIKE' ) {
      return await unlikeBookmark(userData, userId, bookmarkId);
    }
  }
}

let validateInputForBookmarkRating = function (userData, userId) {
  let validationErrorMessages = [];
  if ( userId !== userData.ratingUserId ) {
    validationErrorMessages.push('The ratingUserId in the request.body must be the same as the userId request parameter');
  }
  if ( !userData.action ) {
    validationErrorMessages.push('Missing required attributes - action');
  }
  if ( !(userData.action === 'LIKE' || userData.action === 'UNLIKE') ) {
    validationErrorMessages.push('Invalid value - rating action should be LIKE or UNLIKE');
  }
  if ( validationErrorMessages.length > 0 ) {
    throw new ValidationError('Rating bookmark input is not valid', validationErrorMessages);
  }
}

let likeBookmark = async function (userData, userId, bookmarkId) {
  if ( userData.likes.includes(bookmarkId) ) {
    throw new ValidationError('You already starred this bookmark', ['You already starred this bookmark']);
  } else {

    await User.update(
      {userId: userId},
      {$push: {likes: bookmarkId}}
    );

    const bookmark = await Bookmark.findOneAndUpdate({_id: bookmarkId}, {$inc: {likeCount: 1}});

    const bookmarkNotFound = !bookmark;
    if ( bookmarkNotFound ) {
      throw new NotFoundError('Bookmark with bookmark id ' + bookmarkId + ' not found');
    } else {
      return bookmark;
    }
  }
}

let unlikeBookmark = async function (userData, userId, bookmarkId) {
  if ( !userData.likes.includes(bookmarkId) ) {
    throw new ValidationError('You did not like this bookmark', ['You did not like this bookmark']);
  } else {

    await User.update(
      {userId: userId},
      {$pull: {likes: bookmarkId}}
    );

    const bookmark = await Bookmark.findOneAndUpdate({_id: bookmarkId}, {$inc: {likeCount: -1}});
    const bookmarkNotFound = !bookmark;
    if ( bookmarkNotFound ) {
      throw new NotFoundError('Bookmark with bookmark id ' + bookmarkId + ' not found');
    } else {
      return bookmark;
    }
  }
}

let followUser = async function (userId, followedUserId) {
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {$push: {'following.users': followedUserId}},
    {new: true}
  );

  await User.findOneAndUpdate(
    {userId: followedUserId},
    {$push: {followers: userId}}
  );

  return updatedUserData;
}

let unfollowUser = async function (userId, followedUserId) {
  const updatedUserData = await User.findOneAndUpdate(
    {userId: userId},
    {$pull: {'following.users': followedUserId}},
    {new: true}
  );

  await User.findOneAndUpdate(
    {userId: followedUserId},
    {$pull: {followers: userId}}
  );

  return updatedUserData;
}

/**
 * Return the user data for users, the user identified by @param userId
 * is following
 */
let getFollowedUsersData = async function (userId) {
  const userData = await User.findOne({
    userId: userId
  });

  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    let followedUsers = [];
    if(userData.following) {
      followedUsers = await User.find(
          {userId: {$in: userData.following.users}}
      ).select('userId profile');
    }

    return followedUsers;
  }
}
let getFollowers = async function (userId) {
  const userData = await User.findOne({
    userId: userId
  }).select("+followers");

  if ( !userData ) {
    throw new NotFoundError(`User data NOT_FOUND for userId: ${userId}`);
  } else {
    const followers = await User.find(
      {userId: {$in: userData.followers}}
    ).select('userId profile');

    return followers;
  }
}

/**
 * Return a list of bookmarks to display in the user's feed with pagination.
 * At the top are displayed recent bookmarks tagged with user's watched tags.
 *
 * If the user navigates to further pages and all bookmarks for watched tags
 * have been exhausted then return the recent public bookmarks except ones tagged with tags
 * marked as ignored by the user.
 *
 * @param userId
 * @param page
 * @param limit
 * @returns {Promise<void>}
 */
let getFeedBookmarks = async function (userId, page, limit) {
  const userData = await User.findOne({
    userId: userId
  });
  if ( !userData ) {
    // falls back to getting the public bookmarks - the case happens when the user register for the first time via Keycloak
    return PublicBookmarksService.getLatestPublicBookmarks(page, limit);
  } else {

    const filterFeedBookmarks = {
      public: true,
      $and: [
        {
          tags: {
            $elemMatch: {$in: userData.watchedTags}
          }
        },
        {
          tags: {
            $not: {$elemMatch: {$in: userData.ignoredTags}}
          }
        }
      ]
    };

    let bookmarks = await Bookmark.find(filterFeedBookmarks)
      .sort({createdAt: -1})
      .skip((page - 1) * limit)
      .limit(limit)
      .lean()
      .exec();

    if ( bookmarks.length < limit ) {
      const count = await Bookmark.countDocuments(filterFeedBookmarks);

      const intervalRight = page * limit;
      const pageOtherPublicBookmarks = count === 0 ? page -1 : Math.floor((intervalRight - count) / limit );
      const limitOtherPublicBookmarks = intervalRight - count < limit ? intervalRight - count : limit;

      const otherPublicBookmarks = await Bookmark.find({
        public: true,
        $and: [
          {
            tags: {
              $not: {$elemMatch: {$in: userData.watchedTags}}
            }
          },
          {
            tags: {
              $not: {$elemMatch: {$in: userData.ignoredTags}}
            }
          }
        ]
      })
        .sort({createdAt: -1})
        .skip(pageOtherPublicBookmarks * limit)
        .limit(limitOtherPublicBookmarks)
        .lean()
        .exec();

      bookmarks = bookmarks.concat(otherPublicBookmarks);
    }

    return bookmarks;
  }
}

module.exports = {
  updateUserData: updateUserData,
  updateUserDataHistory: updateUserDataHistory,
  updateUserDataPinned: updateUserDataPinned,
  updateUserDataReadLater: updateUserDataReadLater,
  updateUserDataHistoryReadLaterPinned: updateUserDataHistoryReadLaterPinned,
  updateUserDataFeedToggle: updateUserDataFeedToggle,
  updateLocalStorageOption: updateLocalStorageOption,
  updateUserDataWelcomeAck: updateUserDataWelcomeAck,
  createUserData: createUserData,
  getUserData: getUserData,
  deleteUserData: deleteUserData,
  getReadLater: getReadLater,
  getLikedBookmarks: getLikedBookmarks,
  getUsedTagsForPublicBookmarks: getUsedTagsForPublicBookmarks,
  getUsedTagsForPrivateBookmarks: getUsedTagsForPrivateBookmarks,
  getPinnedBookmarks: getPinnedBookmarks,
  getFavoriteBookmarks: getFavoriteBookmarks,
  getBookmarksFromHistory: getBookmarksFromHistory,
  getAllBookmarksFromHistory: getAllBookmarksFromHistory,
  rateBookmark: rateBookmark,
  followUser: followUser,
  unfollowUser: unfollowUser,
  getFollowedUsersData: getFollowedUsersData,
  getFollowers: getFollowers,
  getFeedBookmarks: getFeedBookmarks
}


text:
PYTHON=python3

help :
	@echo "The following make targets are available:"
	@echo "    help - print this message"
	@echo "    build - build python package"
	@echo "    install - install python package (local user)"
	@echo "    sinstall - install python package (system with sudo)"
	@echo "    remove - remove the package (local user)"
	@echo "    sremove - remove the package (system with sudo)"
	@echo "    clean - remove any temporary files"
	@echo "    notebook - launch ipython notebook"
build :
	$(PYTHON) setup.py build

buildext :
	$(PYTHON) setup.py build_ext --inplace

install :
	$(PYTHON) setup.py install --user

sinstall :
	sudo $(PYTHON) setup.py install

remove :
	$(PYTHON) setup.py install --user --record files.txt
	tr '\n' '\0' < files.txt | xargs -0 rm -f --
	rm files.txt

sremove :
	$(PYTHON) setup.py install  --record files.txt
	tr '\n' '\0' < files.txt | sudo xargs -0 rm -f --
	rm files.txt

clean : FORCE
	$(PYTHON) setup.py clean

pep8 :
	flake8 examples/ ot/ test/

test : FORCE pep8
	$(PYTHON) -m pytest -v test/ --cov=ot --cov-report html:cov_html

pytest : FORCE
	python -m py.test -v test/ --cov=ot

uploadpypi :
	#python setup.py register
	python setup.py sdist upload -r pypi

rdoc :
	pandoc --from=markdown --to=rst --output=docs/source/readme.rst README.md

notebook :
	ipython notebook --matplotlib=inline  --notebook-dir=notebooks/

autopep8 :
	autopep8 -ir test ot examples

aautopep8 :
	autopep8 -air test ot examples

FORCE :


text:
MilliSim was initially designed as a simulator for [THE iDOLM@STER Million Live! Theater Days](https://millionlive.idolmaster.jp/theaterdays/).
It has become a general, plugin-based simulator framework.

**This repository now only contains the framework itself. For the Theater Days simulator, an example for using this framework, check out
[TheaterDaysSim](https://github.com/hozuki/TheaterDaysSim).** Older binaries and assets in this repository are still kept for archiving.

It can be extended to support other games, such as [Arcaea](https://arcaea.lowiro.com) ([ArcaeaSim](https://github.com/hozuki/ArcaeaSim2)).

Demo videos (Theater Days):

| Title | Beatmap Author | Branch |
|---|---|---|
| [Death by Glamour](https://www.bilibili.com/video/av15612246/) | [hozuki](https://github.com/hozuki) | v0.2 |
| [dear...](https://www.bilibili.com/video/av16069466/) | MinamiKaze | v0.2 |
| [茜ちゃんメーカー](http://www.nicovideo.jp/watch/sm32977985) | [Sacno](https://twitter.com/Sacno3) | v0.3 |

| Downloads | Status |
|--|--|
| [GitHub Releases](https://github.com/hozuki/MilliSim/releases) | ![GitHub (pre-)release](https://img.shields.io/github/release/hozuki/MilliSim/all.svg) ![Github All Releases](https://img.shields.io/github/downloads/hozuki/MilliSim/total.svg) |
| [AppVeyor](https://ci.appveyor.com/api/projects/hozuki/MilliSim/artifacts/millisim-appveyor-latest.zip) | (latest development build) |

| Build Status | |
|--|--|
| Travis (not maintained) | [![Travis](https://img.shields.io/travis/hozuki/MilliSim.svg)](https://travis-ci.org/hozuki/MilliSim) |
| AppVeyor | [![AppVeyor](https://img.shields.io/appveyor/ci/hozuki/MilliSim.svg)](https://ci.appveyor.com/project/hozuki/MilliSim) |

**Stage:** alpha

**Miscellaneous:**

[![GitHub contributors](https://img.shields.io/github/contributors/hozuki/MilliSim.svg)](https://github.com/hozuki/MilliSim/graphs/contributors)
[![Libraries.io for GitHub](https://img.shields.io/librariesio/github/hozuki/MilliSim.svg)](https://github.com/hozuki/MilliSim)
[![license](https://img.shields.io/github/license/hozuki/MilliSim.svg)](LICENSE.txt)

## Usage

**Requirements:**

- Operating System:
  - Windows: Windows 7 SP1 or later
    - [.NET Framework 4.5](https://www.microsoft.com/en-us/download/details.aspx?id=42642)
  - macOS and Linux: macOS 10.8 / Ubuntu 16.04 or later
    - and latest [Wine](https://wiki.winehq.org/Download) (will download `wine-mono` on launch)
- [Visual C++ 2015 Runtime](https://www.microsoft.com/en-us/download/details.aspx?id=53587)
- OpenAL (bundled OpenAL-Soft Win32 build in newer releases)

OpenGL builds (`TheaterDays.OpenGL.exe`) can run on all platforms, but it is problematic.
DirectX builds (`TheaterDays.Direct3D11.exe`) can only run on Windows.

### Note: Video Playback Support

If you want to play videos as the background, you must download FFmpeg binaries (version 3.4.1)
from [here](https://ffmpeg.zeranoe.com/builds/), and place the binaries into `x64` and `x86` directories
correspondingly. Due to license restrictions, MilliSim builds cannot include FFmpeg binaries, so you have
to download them yourself.

[File structure](https://github.com/hozuki/MonoGame.Extended2/tree/master/Sources/MonoGame.Extended.VideoPlayback#usage):

```plain
TheaterDays.*.exe
x64/
  avcodec-57.dll
  avdevice-57.dll
  ...
x86/
  avcodec-57.dll
  avdevice-57.dll
  ...
```

Without FFmpeg, you must either:

1. disable background video (comment out `plugin.component_factory.background_video` in `Contents/plugins.yml`), or
2. leave video file path as empty (`data`-`video` section in `Contents/config/background_video.yml`).

### Note: If MilliSim Applications Cannot Launch

To enable debug mode, use [Command Prompt](https://en.wikipedia.org/wiki/Cmd.exe) to run MilliSim like:

```cmd
MilliSimApp.exe --debug
```

When MilliSim encounters problems (e.g. app crash), it will write a debug log in `log-file.txt`. Please open the log and
submit it by [opening an issue](https://github.com/hozuki/MilliSim/issues).

            A common problem of MilliSim not starting may relate to error 0x80131515.
            Since MilliSim uses a plugin architecture, it will scan and load plugin DLLs under its directory.
            That error code means it is not authorized to access those DLLs.
            Please make sure:

if you run MilliSim in C drive, it must be place somewhere inside your user directory (i.e. C:\Users\YOUR_USER_NAME\SOME_DIR\);

you must unblock the downloaded ZIP file before you extract the EXEs and DLLs (shown as the picture on the right). (thanks @Sacno3)

## Building

Please read [Building.md](docs/Building.md).

## Developing Plugins

MilliSim is designed to support plugins. Please read the [wiki page](https://github.com/hozuki/MilliSim/wiki/Creating-Plugins) for more information.
(Note: this is mainly about version 0.2 so it may be deprecated. Proceed with caution. Help is appreciated!)

You can find precompiled NuGet packages for plugin development [here](https://www.nuget.org/packages?q=MilliSim). (Suspended; help needed.)

## Other

### Wiki

MilliSim has a [wiki](https://github.com/hozuki/MilliSim/wiki) on GitHub. It is still under construction but you may find some useful information there.

### Naming

The name is an abbreviation of **Milli**on Live **Sim**ulator.

According to English traditions, it should be written and read as *MilliSim*.
Corresponding Japanese version should be *ミリシミュ* (MilliSimu/*mirisimyu*).
Both versions are acceptable.

## License

MIT


text:
// ===========================================================================================================
//      _                                 _              _       _
//     | |                               | |            | |     | |
//   __| |   __ _  __  __  _ __     ___  | |_   ______  | |__   | |   ___     __ _
//  / _` |  / _` | \ \/ / | '_ \   / _ \ | __| |______| | '_ \  | |  / _ \   / _` |
// | (_| | | (_| |  >  <  | | | | |  __/ | |_           | |_) | | | | (_) | | (_| |
//  \__,_|  \__,_| /_/\_\ |_| |_|  \___|  \__|          |_.__/  |_|  \___/   \__, |
//                                                                            __/ |
//                                                                           |___/
//
//
// Daxnet Personal Blog
// Copyright © 2016 by daxnet (Sunny Chen)
//
// https://github.com/daxnet/daxnet-blog
//
// MIT License
//
// Copyright(c) 2016 Sunny Chen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// ===========================================================================================================

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

namespace DaxnetBlog.Common.Storage
{
    public interface IEntityStore<TEntity, TKey>
        where TKey : IEquatable<TKey>
        where TEntity : class, IEntity<TKey>, new()
    {
        IEnumerable<TEntity> Select(IDbConnection connection,
            Expression<Func<TEntity, bool>> expression = null,
            Sort<TEntity, TKey> sorting = null,
            IDbTransaction transaction = null);

        IEnumerable<TEntity> Select<TJoined>(IDbConnection connection,
            Expression<Func<TEntity, TJoined>> includePath,
            Expression<Func<TEntity, TKey>> keySelector,
            Expression<Func<TJoined, TKey>> joinedKeySelector,
            Expression<Func<TEntity, bool>> expression = null,
            Sort<TEntity, TKey> sorting = null,
            IDbTransaction transaction = null)
            where TJoined : class, IEntity<TKey>, new();

        PagedResult<TEntity, TKey> Select(int pageNumber, int pageSize,
            IDbConnection connection,
            Sort<TEntity, TKey> sorting,
            Expression<Func<TEntity, bool>> expression = null,
            IDbTransaction transaction = null);

        Task<IEnumerable<TEntity>> SelectAsync(IDbConnection connection,
            Expression<Func<TEntity, bool>> expression = null,
            Sort<TEntity, TKey> sorting = null,
            IDbTransaction transaction = null,
            CancellationToken cancellationToken = default(CancellationToken));

        Task<IEnumerable<TEntity>> SelectAsync<TJoined>(IDbConnection connection,
            Expression<Func<TEntity, TJoined>> includePath,
            Expression<Func<TEntity, TKey>> keySelector,
            Expression<Func<TJoined, TKey>> joinedKeySelector,
            Expression<Func<TEntity, bool>> expression = null,
            Sort<TEntity, TKey> sorting = null,
            IDbTransaction transaction = null,
            CancellationToken cancellationToken = default(CancellationToken))
            where TJoined : class, IEntity<TKey>, new();

        Task<PagedResult<TEntity, TKey>> SelectAsync(int pageNumber, int pageSize,
            IDbConnection connection,
            Sort<TEntity, TKey> sorting,
            Expression<Func<TEntity, bool>> expression = null,
            IDbTransaction transaction = null,
            CancellationToken cancellationToken = default(CancellationToken));

        int Insert(TEntity entity,
            IDbConnection connection,
            IEnumerable<Expression<Func<TEntity, object>>> autoIncrementFields = null,
            IDbTransaction transaction = null);

        Task<int> InsertAsync(TEntity entity,
            IDbConnection connection,
            IEnumerable<Expression<Func<TEntity, object>>> autoIncrementFields = null,
            IDbTransaction transaction = null,
            CancellationToken cancellationToken = default(CancellationToken));

        int Update(TEntity entity,
            IDbConnection connection,
            Expression<Func<TEntity, bool>> expression = null,
            IEnumerable<Expression<Func<TEntity, object>>> updateFields = null,
            IDbTransaction transaction = null);

        Task<int> UpdateAsync(TEntity entity,
            IDbConnection connection,
            Expression<Func<TEntity, bool>> expression = null,
            IEnumerable<Expression<Func<TEntity, object>>> updateFields = null,
            IDbTransaction transaction = null,
            CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
#include <aws/chime-sdk-media-pipelines/model/CreateMediaLiveConnectorPipelineResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

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

CreateMediaLiveConnectorPipelineResult::CreateMediaLiveConnectorPipelineResult()
{
}

CreateMediaLiveConnectorPipelineResult::CreateMediaLiveConnectorPipelineResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

CreateMediaLiveConnectorPipelineResult& CreateMediaLiveConnectorPipelineResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("MediaLiveConnectorPipeline"))
  {
    m_mediaLiveConnectorPipeline = jsonValue.GetObject("MediaLiveConnectorPipeline");

  }

  return *this;
}


text: Fork the repo and submit a Pull Request if you have improvements or bug fixes.


text:
@interface LivingViewController : BaseViewController

@end


text:
package org.kitesdk.data.hbase;

import org.apache.hadoop.mapreduce.InputFormat;
import org.kitesdk.data.Dataset;
import org.kitesdk.data.DatasetDescriptor;
import org.kitesdk.data.Key;
import org.kitesdk.data.PartitionKey;
import org.kitesdk.data.PartitionStrategy;
import org.kitesdk.data.RandomAccessDataset;
import org.kitesdk.data.RefinableView;
import org.kitesdk.data.hbase.impl.Dao;
import org.kitesdk.data.spi.AbstractDataset;
import org.kitesdk.data.spi.Constraints;
import org.kitesdk.data.spi.InputFormatAccessor;

class DaoDataset<E> extends AbstractDataset<E> implements RandomAccessDataset<E>,
    InputFormatAccessor<E> {

  private String name;
  private Dao<E> dao;
  private DatasetDescriptor descriptor;
  private final DaoView<E> unbounded;

  public DaoDataset(String name, Dao<E> dao, DatasetDescriptor descriptor) {
    this.name = name;
    this.dao = dao;
    this.descriptor = descriptor;
    this.unbounded = new DaoView<E>(this);
  }

  Dao<E> getDao() {
    return dao;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public DatasetDescriptor getDescriptor() {
    return descriptor;
  }

  @Override
  public Dataset<E> getPartition(PartitionKey key, boolean autoCreate) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void dropPartition(PartitionKey key) {
    throw new UnsupportedOperationException();
  }

  @Override
  public Iterable<Dataset<E>> getPartitions() {
    throw new UnsupportedOperationException();
  }

  @Override
  protected RefinableView<E> asRefinableView() {
    return unbounded;
  }

  @Override
  public DaoView<E> filter(Constraints c) {
    return unbounded.filter(c);
  }

  @Override
  @SuppressWarnings("deprecation")
  public E get(Key key) {
    return dao.get(keyFor(getDescriptor().getPartitionStrategy(), key));
  }

  @Override
  public boolean put(E entity) {
    return dao.put(entity);
  }

  @Override
  @SuppressWarnings("deprecation")
  public long increment(Key key, String fieldName, long amount) {
    return dao.increment(keyFor(getDescriptor().getPartitionStrategy(), key), fieldName, amount);
  }

  @Override
  @SuppressWarnings("deprecation")
  public void delete(Key key) {
    dao.delete(keyFor(getDescriptor().getPartitionStrategy(), key));
  }

  @Override
  public boolean delete(E entity) {
    return dao.delete(entity);
  }

  @Deprecated
  static PartitionKey keyFor(PartitionStrategy strategy, Key key) {
    final int size = strategy.getFieldPartitioners().size();
    final Object[] values = new Object[size];

    for (int i = 0; i < size; i += 1) {
      values[i] = key.get(i);
    }

    return strategy.partitionKey(values);
  }

  @Override
  public InputFormat<E, Void> getInputFormat() {
    return new HBaseViewKeyInputFormat<E>(this);
  }
}


text:
from __future__ import print_function
import numpy as np
import tables
from time import time

N = 1000 * 1000
NCOLL = 200  # 200 collections maximum

# In order to have reproducible results
np.random.seed(19)

class Energies(tables.IsDescription):
    collection = tables.UInt8Col()
    energy = tables.Float64Col()

def fill_bucket(lbucket):
    #c = np.random.normal(NCOLL/2, NCOLL/10, lbucket)
    c = np.random.normal(NCOLL / 2, NCOLL / 100, lbucket)
    e = np.arange(lbucket, dtype='f8')
    return c, e

# Fill the table
t1 = time()
f = tables.open_file("data.nobackup/collations.h5", "w")
table = f.create_table("/", "Energies", Energies, expectedrows=N)
# Fill the table with values
lbucket = 1000   # Fill in buckets of 1000 rows, for speed
for i in range(0, N, lbucket):
    bucket = fill_bucket(lbucket)
    table.append(bucket)
# Fill the remaining rows
bucket = fill_bucket(N % lbucket)
table.append(bucket)
f.close()
print("Time to create the table with %d entries: %.3f" % (N, time() - t1))

# Now, read the table and group it by collection
f = tables.open_file("data.nobackup/collations.h5", "a")
table = f.root.Energies

#########################################################
# First solution: load the table completely in memory
#########################################################
t1 = time()
t = table[:]  # convert to structured array
coll1 = []
collections = np.unique(t['collection'])
for c in collections:
    cond = t['collection'] == c
    energy_this_collection = t['energy'][cond]
    sener = energy_this_collection.sum()
    coll1.append(sener)
    print(c, ' : ', sener)
del collections, energy_this_collection
print("Time for first solution: %.3f" % (time() - t1))

#########################################################
# Second solution: load all the collections in memory
#########################################################
t1 = time()
collections = {}
for row in table:
    c = row['collection']
    e = row['energy']
    if c in collections:
        collections[c].append(e)
    else:
        collections[c] = [e]
# Convert the lists in numpy arrays
coll2 = []
for c in sorted(collections):
    energy_this_collection = np.array(collections[c])
    sener = energy_this_collection.sum()
    coll2.append(sener)
    print(c, ' : ', sener)
del collections, energy_this_collection
print("Time for second solution: %.3f" % (time() - t1))

t1 = time()
table.cols.collection.create_csindex()
# table.cols.collection.reindex()
print("Time for indexing: %.3f" % (time() - t1))

#########################################################
# Third solution: load each collection separately
#########################################################
t1 = time()
coll3 = []
for c in np.unique(table.col('collection')):
    energy_this_collection = table.read_where(
        'collection == c', field='energy')
    sener = energy_this_collection.sum()
    coll3.append(sener)
    print(c, ' : ', sener)
del energy_this_collection
print("Time for third solution: %.3f" % (time() - t1))

t1 = time()
table2 = table.copy('/', 'EnergySortedByCollation', overwrite=True,
                    sortby="collection", propindexes=True)
print("Time for sorting: %.3f" % (time() - t1))

#####################################################################
# Fourth solution: load each collection separately.  Sorted table.
#####################################################################
t1 = time()
coll4 = []
for c in np.unique(table2.col('collection')):
    energy_this_collection = table2.read_where(
        'collection == c', field='energy')
    sener = energy_this_collection.sum()
    coll4.append(sener)
    print(c, ' : ', sener)
    del energy_this_collection
print("Time for fourth solution: %.3f" % (time() - t1))

# Finally, check that all solutions do match
assert coll1 == coll2 == coll3 == coll4

f.close()


text:
angular.module('dbmsgram')
    .controller('DetailCtrl', function($scope, API) {

    });
});


text:
package software.amazon.awssdk.authcrt.signer.internal;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream;
import software.amazon.awssdk.auth.signer.internal.util.SignerMethodResolver;
import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner;
import software.amazon.awssdk.authcrt.signer.SignerTestUtils;
import software.amazon.awssdk.authcrt.signer.SigningTestCase;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.ChecksumSpecs;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.interceptor.trait.HttpChecksum;
import software.amazon.awssdk.core.internal.signer.SigningMethod;
import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig;
import software.amazon.awssdk.http.SdkHttpFullRequest;

/**
 * Unit tests for the {@link DefaultAwsCrtS3V4aSigner}.
 */
@RunWith(MockitoJUnitRunner.class)
public class DefaultAwsCrtS3V4aSignerTest {

    private static HttpChecksum HTTP_CRC32_CHECKSUM =
        HttpChecksum.builder().requestAlgorithm("crc32").isRequestStreaming(true).build();

    @Mock
    AwsCrt4aSigningAdapter signerAdapter;

    ArgumentCaptor<AwsSigningConfig> configCaptor = ArgumentCaptor.forClass(AwsSigningConfig.class);

    private SigningConfigProvider configProvider;
    private DefaultAwsCrtS3V4aSigner s3V4aSigner;

    @Before
    public void setup() {
        configProvider = new SigningConfigProvider();
        s3V4aSigner = new DefaultAwsCrtS3V4aSigner(signerAdapter, configProvider);

        SdkHttpFullRequest unsignedPayloadSignedRequest = SignerTestUtils.createSignedHttpRequest("data");

        SdkHttpFullRequest signedPayloadSignedRequest = SignerTestUtils.createSignedPayloadHttpRequest("data");
        String signedPayloadSignature = SignerTestUtils.extractSignatureFromAuthHeader(signedPayloadSignedRequest);

//        when(configProvider.createS3CrtSigningConfig(any())).thenReturn(new AwsSigningConfig());
        when(signerAdapter.sign(any(), any())).thenReturn(new SdkSigningResult(signedPayloadSignature.getBytes(StandardCharsets.UTF_8),
                                                                               signedPayloadSignedRequest));
        when(signerAdapter.signRequest(any(), any())).thenReturn(unsignedPayloadSignedRequest);
    }

    @Test
    public void when_credentials_are_anonymous_return_request() {
        SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
        executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS,
                                         AnonymousCredentialsProvider.create().resolveCredentials());

        SdkHttpFullRequest request = testCase.requestBuilder.build();
        SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);

        assertThat(signedRequest).isEqualTo(request);
    }

    @Test
    public void no_special_configuration_does_not_sign_payload() {
        SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);

        SdkHttpFullRequest request = testCase.requestBuilder.build();
        SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);

        verifyUnsignedPayload(signedRequest);
    }

    @Test
    public void protocol_http_triggers_payload_signing() {
        SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);

        SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder;
        requestBuilder.uri(URI.create("http://demo.us-east-1.amazonaws.com"));

        SdkHttpFullRequest signedRequest = s3V4aSigner.sign(requestBuilder.build(), executionAttributes);

        verifySignedPayload(signedRequest);
    }

    @Test
    public void protocol_http_triggers_payload_signing_with_trailer_checksums() {
        SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
        executionAttributes.putAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, HTTP_CRC32_CHECKSUM);
        SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder;
        requestBuilder.uri(URI.create("http://demo.us-east-1.amazonaws.com"));

        SdkHttpFullRequest signedRequest = s3V4aSigner.sign(requestBuilder.build(), executionAttributes);
        verifySignedChecksumPayload(signedRequest);
    }

    @Test
    public void unsigned_payload_signing_with_trailer_checksums() {
        SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
        executionAttributes.putAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, HTTP_CRC32_CHECKSUM);
        SdkHttpFullRequest request = testCase.requestBuilder.build();
        SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);

        verifyUnsignedPayloadWithTrailerChecksum(signedRequest);
    }

    @Test
    public void payloadSigning_AND_chunkedEnabled_triggers_payload_signing() {
        SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);

        executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true);
        executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, true);

        SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);

        verifySignedPayload(signedRequest);
    }

    @Test
    public void payloadSigning_and_chunked_disabled_does_not_sign_payload() {
        SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);

        executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true);
        executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, false);

        SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);

        verifyUnsignedPayload(signedRequest);
    }

    @Test
    public void no_payloadSigning_and_chunkedEnabled_does_not_sign_payload() {
        SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);

        executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, false);
        executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, true);

        SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);

        verifyUnsignedPayload(signedRequest);
    }

    @Test
    public void presigning_returns_signed_params() {
        SdkHttpFullRequest signedPresignedRequest = SignerTestUtils.createPresignedPayloadHttpRequest("data");
        when(signerAdapter.signRequest(any(), any())).thenReturn(signedPresignedRequest);

        SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
        ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);

        SdkHttpFullRequest request = testCase.requestBuilder.build();
        SdkHttpFullRequest signed = s3V4aSigner.presign(request, executionAttributes);

        assertThat(signed.rawQueryParameters().get("X-Amz-Signature").get(0)).isEqualTo("signature");
    }

    @Test
    public void defaultAwsCrtS3V4aSigner_resolves_to_correct_signing_method(){
        ExecutionAttributes executionAttributes = Mockito.mock(ExecutionAttributes.class);
        AwsCredentials awsCredentials = Mockito.mock(AwsCredentials.class);
        when(executionAttributes.getOptionalAttribute(ENABLE_PAYLOAD_SIGNING)).thenReturn(Optional.of(false));
        when(executionAttributes.getOptionalAttribute(ENABLE_CHUNKED_ENCODING)).thenReturn(Optional.of(true));
        SigningMethod signingMethod = SignerMethodResolver.resolveSigningMethodUsed(DefaultAwsCrtS3V4aSigner.create(),
                                                                                executionAttributes,
                                                                                awsCredentials);
        assertThat(signingMethod).isEqualTo(SigningMethod.PROTOCOL_STREAMING_SIGNING_AUTH);
    }

    private void verifyUnsignedPayload(SdkHttpFullRequest signedRequest) {
        verifyUnsignedHeaderRequest(signedRequest);
        Mockito.verify(signerAdapter).signRequest(any(), configCaptor.capture());
        AwsSigningConfig usedConfig = configCaptor.getValue();
        assertThat(usedConfig.getSignedBodyValue()).isEqualTo(AwsSigningConfig.AwsSignedBodyValue.UNSIGNED_PAYLOAD);
    }

    private void verifyUnsignedPayloadWithTrailerChecksum(SdkHttpFullRequest signedRequest) {
        verifyUnsignedHeaderRequest(signedRequest);
        Mockito.verify(signerAdapter).signRequest(any(), configCaptor.capture());
        AwsSigningConfig usedConfig = configCaptor.getValue();
        assertThat(usedConfig.getSignedBodyValue()).isEqualTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER");
    }

    private void verifyUnsignedHeaderRequest(SdkHttpFullRequest signedRequest) {
        assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
        assertThat(signedRequest.firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent();
        assertThat(signedRequest.contentStreamProvider()).isPresent();
        assertThat(signedRequest.contentStreamProvider().get().newStream()).isNotInstanceOf(AwsSignedChunkedEncodingInputStream.class);
    }

    private void verifySignedPayload(SdkHttpFullRequest signedRequest) {
        verifySignedRequestHeaders(signedRequest);
        verifySignedBody(AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD);
    }

    private void verifySignedChecksumPayload(SdkHttpFullRequest signedRequest) {
        verifySignedRequestHeaders(signedRequest);
        verifySignedBody(AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER);
    }

    private void verifySignedBody(String awsSignedBodyValue) {
        Mockito.verify(signerAdapter).sign(any(), configCaptor.capture());
        AwsSigningConfig usedConfig = configCaptor.getValue();
        assertThat(usedConfig.getSignedBodyValue()).isEqualTo(awsSignedBodyValue);
    }

    private void verifySignedRequestHeaders(SdkHttpFullRequest signedRequest) {
        assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
        assertThat(signedRequest.firstMatchingHeader("Content-Length")).isPresent();
        assertThat(signedRequest.firstMatchingHeader("x-amz-decoded-content-length")).isPresent();
        assertThat(signedRequest.contentStreamProvider()).isPresent();
        assertThat(signedRequest.contentStreamProvider().get().newStream()).isInstanceOf(AwsSignedChunkedEncodingInputStream.class);
    }

}


text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta content="telephone=no" name="format-detection">
<meta content="email=no" name="format-detection">
<link rel="stylesheet" type="text/css" href="assets/wordssign/css/group_style.css">
<link rel="stylesheet" type="text/css" href="assets/wordssign/css/gongdu.css">
<title>词汇无忧</title>

<img src="<?php echo $user['headimgurl']; ?>">

您好,<?php echo urldecode($user['nickname']); ?>

订阅成功!


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=trait.SampleRange.html">

Redirecting to trait.SampleRange.html...


text:
This project only supports out of source builds. The include paths in the header file
look for prefix 'fool'.

Dependencies:
origin library from: https://github.com/hiraditya/origin

g++ > 4.9

For out of source builds:

1. Download the sources in $DIR/fool, such that $DIR/fool/fool is the git repository.

2. mkdir -p $DIR/build.

3. cd $DIR/build

4. cmake ../fool

5. make

You might want to modify the top level CMakeLists.txt, for appropriate include paths.


text: - provider (Object)


text:
DisapprovalReasonValuesオブジェクトは、 EditorialReason一覧を格納するコンテナです。

### Service

+ [DictionaryService](../../services/DictionaryService.md)

### Namespace

[DictionaryService#Namespace](../../services/DictionaryService.md#namespace)

### Inheritance

+ [ReturnValue](../Common/ReturnValue.md)

| Field | Type | Description | response |
| ----- | ---- | ----------- | -------- |
| disapprovalReason | [DisapprovalReason](./DisapprovalReason.md) | 審査否認理由とその対処方法を格納したコンテナです。 | yes | |

この 作品 は クリエイティブ・コモンズ 表示 - 改変禁止 2.1 日本 ライセンスの下に提供されています。


text:
package couchdb

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"reflect"
	"strconv"
	"strings"
	"sync"
)

// Options represents CouchDB query string parameters.
type Options map[string]interface{}

// clone creates a shallow copy of an Options map
func (opts Options) clone() (result Options) {
	result = make(Options)
	for k, v := range opts {
		result[k] = v
	}
	return
}

type transport struct {
	prefix string // URL prefix
	http   *http.Client
	mu     sync.RWMutex
	auth   Auth
}

func newTransport(prefix string, rt http.RoundTripper, auth Auth) *transport {
	return &transport{
		prefix: strings.TrimRight(prefix, "/"),
		http:   &http.Client{Transport: rt},
		auth:   auth,
	}
}

func (t *transport) setAuth(a Auth) {
	t.mu.Lock()
	t.auth = a
	t.mu.Unlock()
}

func (t *transport) newRequest(method, path string, body io.Reader) (*http.Request, error) {
	req, err := http.NewRequest(method, t.prefix+path, body)
	if err != nil {
		return nil, err
	}
	t.mu.RLock()
	defer t.mu.RUnlock()
	if t.auth != nil {
		t.auth.AddAuth(req)
	}
	return req, nil
}

// request sends an HTTP request to a CouchDB server.
// The request URL is constructed from the server's
// prefix and the given path, which may contain an
// encoded query string.
//
// Status codes >= 400 are treated as errors.
func (t *transport) request(method, path string, body io.Reader) (*http.Response, error) {
	req, err := t.newRequest(method, path, body)
	req.Header.Add("Content-Type", "application/json") // Required for POST
	if err != nil {
		return nil, err
	}
	resp, err := t.http.Do(req)
	if err != nil {
		return nil, err
	} else if resp.StatusCode >= 400 {
		return nil, parseError(resp) // the Body is closed by parseError
	} else {
		return resp, nil
	}
}

// closedRequest sends an HTTP request and discards the response body.
func (t *transport) closedRequest(method, path string, body io.Reader) (*http.Response, error) {
	resp, err := t.request(method, path, body)
	if err == nil {
		resp.Body.Close()
	}
	return resp, err
}

func path(segs ...string) string {
	r := ""
	for i, seg := range segs {
		r += "/"
		if i == 1 && strings.HasPrefix(seg,"_design/") {
			r += seg
		} else {
			r += url.QueryEscape(seg)
		}
	}
	return r
}

func revpath(rev string, segs ...string) string {
	r := path(segs...)
	if rev != "" {
		r += "?rev=" + url.QueryEscape(rev)
	}
	return r
}

func optpath(opts Options, jskeys []string, segs ...string) (string, error) {
	r := path(segs...)
	if len(opts) > 0 {
		os, err := encopts(opts, jskeys)
		if err != nil {
			return "", err
		}
		r += os
	}
	return r, nil
}

func encopts(opts Options, jskeys []string) (string, error) {
	buf := new(bytes.Buffer)
	buf.WriteRune('?')
	amp := false
	for k, v := range opts {
		if amp {
			buf.WriteByte('&')
		}
		buf.WriteString(url.QueryEscape(k))
		buf.WriteByte('=')
		isjson := false
		for _, jskey := range jskeys {
			if k == jskey {
				isjson = true
				break
			}
		}
		if isjson {
			jsonv, err := json.Marshal(v)
			if err != nil {
				return "", fmt.Errorf("invalid option %q: %v", k, err)
			}
			buf.WriteString(url.QueryEscape(string(jsonv)))
		} else {
			if err := encval(buf, k, v); err != nil {
				return "", fmt.Errorf("invalid option %q: %v", k, err)
			}
		}
		amp = true
	}
	return buf.String(), nil
}

func encval(w io.Writer, k string, v interface{}) error {
	if v == nil {
		return errors.New("value is nil")
	}
	rv := reflect.ValueOf(v)
	var str string
	switch rv.Kind() {
	case reflect.String:
		str = url.QueryEscape(rv.String())
	case reflect.Bool:
		str = strconv.FormatBool(rv.Bool())
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		str = strconv.FormatInt(rv.Int(), 10)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		str = strconv.FormatUint(rv.Uint(), 10)
	case reflect.Float32:
		str = strconv.FormatFloat(rv.Float(), 'f', -1, 32)
	case reflect.Float64:
		str = strconv.FormatFloat(rv.Float(), 'f', -1, 64)
	default:
		return fmt.Errorf("unsupported type: %s", rv.Type())
	}
	_, err := io.WriteString(w, str)
	return err
}

// responseRev returns the unquoted Etag of a response.
func responseRev(resp *http.Response, err error) (string, error) {
	if err != nil {
		return "", err
	} else if etag := resp.Header.Get("Etag"); etag == "" {
		return "", fmt.Errorf("couchdb: missing Etag header in response")
	} else {
		return etag[1 : len(etag)-1], nil
	}
}

func readBody(resp *http.Response, v interface{}) error {
	if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
		resp.Body.Close()
		return err
	}
	return resp.Body.Close()
}

// Error represents API-level errors, reported by CouchDB as
//    {"error": <ErrorCode>, "reason": <Reason>}
type Error struct {
	Method     string // HTTP method of the request
	URL        string // HTTP URL of the request
	StatusCode int    // HTTP status code of the response

	// These two fields will be empty for HEAD requests.
	ErrorCode string // Error reason provided by CouchDB
	Reason    string // Error message provided by CouchDB
}

func (e *Error) Error() string {
	if e.ErrorCode == "" {
		return fmt.Sprintf("%v %v: %v", e.Method, e.URL, e.StatusCode)
	}
	return fmt.Sprintf("%v %v: (%v) %v: %v",
		e.Method, e.URL, e.StatusCode, e.ErrorCode, e.Reason)
}

// NotFound checks whether the given errors is a DatabaseError
// with StatusCode == 404. This is useful for conditional creation
// of databases and documents.
func NotFound(err error) bool {
	return ErrorStatus(err, http.StatusNotFound)
}

// Unauthorized checks whether the given error is a DatabaseError
// with StatusCode == 401.
func Unauthorized(err error) bool {
	return ErrorStatus(err, http.StatusUnauthorized)
}

// Conflict checks whether the given error is a DatabaseError
// with StatusCode == 409.
func Conflict(err error) bool {
	return ErrorStatus(err, http.StatusConflict)
}

// ErrorStatus checks whether the given error is a DatabaseError
// with a matching statusCode.
func ErrorStatus(err error, statusCode int) bool {
	dberr, ok := err.(*Error)
	return ok && dberr.StatusCode == statusCode
}

func parseError(resp *http.Response) error {
	var reply struct{ Error, Reason string }
	if resp.Request.Method != "HEAD" {
		if err := readBody(resp, &reply); err != nil {
			return fmt.Errorf("couldn't decode CouchDB error: %v", err)
		}
	}
	return &Error{
		Method:     resp.Request.Method,
		URL:        resp.Request.URL.String(),
		StatusCode: resp.StatusCode,
		ErrorCode:  reply.Error,
		Reason:     reply.Reason,
	}
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>

    <predicate lemma="healing">

        <roleset framnet="" id="healing.01" name="Curing or repairing" vncls="">
            <roles>
                <role descr="Entity causing cure" f="" n="0"/>

                <role descr="Entity healed" f="" n="1"/>
                <note/>
            </roles>

            <note>heal.01</note>
            <example name="Arg1 (no causer)" src="" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>We support her in her healing and recovery.</text>
                <note/>
                <arg f="" n="1">her</arg>
                <rel f="">healing</rel>
            </example>
        </roleset>
        <note/>
    </predicate>
    <note/>
</frameset>


text:
package org.apache.reef.io.storage;

import org.apache.reef.exception.evaluator.ServiceException;
import org.apache.reef.exception.evaluator.StorageException;
import org.apache.reef.io.Accumulable;
import org.apache.reef.io.Accumulator;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FramingOutputStream extends OutputStream implements Accumulable<byte[]> {

  private final ByteArrayOutputStream baos;
  private final DataOutputStream o;
  private long offset;
  private boolean closed;

  public FramingOutputStream(OutputStream o) {
    if (!(o instanceof DataOutputStream)) {
      this.o = new DataOutputStream(o);
    } else {
      this.o = (DataOutputStream) o;
    }
    this.baos = new ByteArrayOutputStream();
  }

  public void nextFrame() throws StorageException {
    try {
      o.writeInt(baos.size());
      offset += 4;
      baos.writeTo(o);
      baos.reset();
    } catch (IOException e) {
      throw new StorageException(e);
    }
  }

  public long getCurrentOffset() {
    return offset;
  }

  @Override
  public void write(int b) throws IOException {
    baos.write(b);
    offset++;
    ;
  }

  @Override
  public void write(byte[] b) throws IOException {
    baos.write(b);
    offset += b.length;
  }

  @Override
  public void write(byte[] b, int offset, int length) throws IOException {
    baos.write(b, offset, length);
    offset += length;
  }

  @Override
  public void flush() {
    // no-op.
  }

  @Override
  public void close() throws IOException {
    if (!closed) {
      try {
        if (this.offset > 0) nextFrame();
      } catch (StorageException e) {
        throw (IOException) e.getCause();
      }
      o.writeInt(-1);
      o.close();
      closed = true;
    }
  }

  @Override
  public Accumulator<byte[]> accumulator() throws StorageException {
    @SuppressWarnings("resource")
    final FramingOutputStream fos = this;
    return new Accumulator<byte[]>() {

      @Override
      public void add(byte[] datum) throws ServiceException {
        try {
          o.writeInt(datum.length);
          offset += 4;
          o.write(datum);
          offset += datum.length;
        } catch (IOException e) {
          throw new ServiceException(e);
        }

      }

      @Override
      public void close() throws ServiceException {
        try {
          o.writeInt(-1);
          offset += 4;
          o.close();
          fos.closed = true;
        } catch (IOException e) {
          throw new ServiceException(e);
        }
      }

    };
  }

}


text:
package isolated

import (
	"regexp"

	. "code.cloudfoundry.org/cli/cf/util/testhelpers/matchers"

	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("share-private-domain command", func() {
	Context("Help", func() {
		When("--help flag is set", func() {
			It("appears in cf help -a", func() {
				session := helpers.CF("help", "-a")
				Eventually(session).Should(Exit(0))
				Expect(session).To(HaveCommandInCategoryWithDescription("share-private-domain", "ORG ADMIN", "Share a private domain with a specific org"))
			})

			It("displays the help information", func() {
				session := helpers.CF("share-private-domain", "--help")
				Eventually(session).Should(Say("NAME:\n"))
				Eventually(session).Should(Say(regexp.QuoteMeta("share-private-domain - Share a private domain with a specific org")))
				Eventually(session).Should(Say("USAGE:\n"))
				Eventually(session).Should(Say(regexp.QuoteMeta("cf share-private-domain ORG DOMAIN")))
				Eventually(session).Should(Say("SEE ALSO:\n"))
				Eventually(session).Should(Say("create-private-domain, domains, unshare-private-domain"))
				Eventually(session).Should(Exit(0))
			})
		})
	})

	var (
		sharedWithOrgName string
		orgName           string
		spaceName         string
		domainName        string
		userName          string
	)

	BeforeEach(func() {
		sharedWithOrgName = helpers.NewOrgName()
		orgName = helpers.NewOrgName()
		spaceName = helpers.NewSpaceName()
		domainName = helpers.NewDomainName()
	})

	When("user is logged in", func() {
		BeforeEach(func() {
			userName, _ = helpers.GetCredentials()
			helpers.SetupCF(orgName, spaceName)
			helpers.CreateOrg(sharedWithOrgName)
			domain := helpers.NewDomain(orgName, domainName)
			domain.CreatePrivate()
		})

		It("should create the shared domain", func() {
			session := helpers.CF("share-private-domain", sharedWithOrgName, domainName)

			Eventually(session).Should(Say("Sharing domain %s with org %s as %s...", domainName, sharedWithOrgName, userName))
			Eventually(session).Should(Say("OK"))
			Eventually(session).Should(Exit(0))

			session = helpers.CF("domains")
			Eventually(session).Should(Say(`%s\s+private`, domainName))
			Eventually(session).Should(Exit(0))
		})
	})

	When("there is an error", func() {
		It("should report failure and exit with non-zero exit code", func() {
			session := helpers.CF("share-private-domain", orgName, domainName)

			Eventually(session.Err).Should(Say("Not logged in. Use 'cf login' or 'cf login --sso' to log in."))
			Eventually(session).Should(Say("FAILED"))
			Eventually(session).Should(Exit(1))
		})
	})
})


text:
<!DOCTYPE html>

    <title>IO Doctor - The Doctor is in</title>

    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">

    <link href="css/default.css" rel="stylesheet">
    <link href="css/ribbon.css" rel="stylesheet">
    <link href="css/prettify.css" rel="stylesheet">

          I/O Doctor

              Load

              Edit

              Output

                <textarea id="service-definition" class="span12 service-input"></textarea>

                    Load Service Definition

                    Copy Output

                    <form class="form-horizontal" id="config">

                    </form>


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "departamento".
 *
 * @property integer $id
 * @property string $nombre
 * @property string $descripcion
 */
class Departamento extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'departamento';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nombre'], 'required'],
            [['nombre'], 'string', 'max' => 40],
            [['descripcion'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'nombre' => 'Nombre',
            'descripcion' => 'Descripcion',
        ];
    }
}


text:
define(
({
	"clearFilterDialogTitle": "Очистить фильтр",
	"filterDefDialogTitle": "Фильтр",
	"ruleTitleTemplate": "Правило ${0}",
	"conditionEqual": "равно",
	"conditionNotEqual": "не равно",
	"conditionLess": "меньше чем",
	"conditionLessEqual": "не меньше чем",
	"conditionLarger": "больше чем",
	"conditionLargerEqual": "не больше чем",
	"conditionContains": "содержит",
	"conditionIs": "-",
	"conditionStartsWith": "начинается с",
	"conditionEndWith": "заканчивается",
	"conditionNotContain": "не содержит",
	"conditionIsNot": "не соответствует",
	"conditionNotStartWith": "не начинается с",
	"conditionNotEndWith": "не заканчивается",
	"conditionBefore": "до",
	"conditionAfter": "после",
	"conditionRange": "диапазон",
	"conditionIsEmpty": "пуст",
	"all": "все",
	"any": "любое",
	"relationAll": "все правила",
	"waiRelAll": "Соответствует всем следующим правилам:",
	"relationAny": "любые правила",
	"waiRelAny": "Соответствует любому из следующих правил:",
	"relationMsgFront": "Соответствие:",
	"relationMsgTail": "",
	"and": "и",
	"or": "или",
	"addRuleButton": "Добавить правило",
	"waiAddRuleButton": "Добавить новое правило",
	"removeRuleButton": "Удалить правило",
	"waiRemoveRuleButtonTemplate": "Удалить правило ${0}",
	"cancelButton": "Отмена",
	"waiCancelButton": "Отменить этот диалог",
	"clearButton": "Очистить",
	"waiClearButton": "Очистить фильтр",
	"filterButton": "Фильтр",
	"waiFilterButton": "Применить фильтр",
	"columnSelectLabel": "Столбец",
	"waiColumnSelectTemplate": "Столбец правила ${0}",
	"conditionSelectLabel": "Условие",
	"waiConditionSelectTemplate": "Условие правила ${0}",
	"valueBoxLabel": "Значение",
	"waiValueBoxTemplate": "Введите значение в фильтр правила ${0}",
	"rangeTo": "к",
	"rangeTemplate": "от ${0} до ${1}",
	"statusTipHeaderColumn": "Столбец",
	"statusTipHeaderCondition": "Правила",
	"statusTipTitle": "Панель фильтров",
	"statusTipMsg": "Нажмите на панель фильтров для фильтрации по значениям в ${0}.",
	"anycolumn": "любой столбец",
	"statusTipTitleNoFilter": "Панель фильтров",
	"statusTipTitleHasFilter": "Фильтр",
	"statusTipRelAny": "Соответствие любому из правил.",
	"statusTipRelAll": "Соответствие всем правилам.",
	"defaultItemsName": "элементов",
	"filterBarMsgHasFilterTemplate": "Показано ${0} из ${1} ${2}.",
	"filterBarMsgNoFilterTemplate": "Фильтры не используются",
	"filterBarDefButton": "Определить фильтр",
	"waiFilterBarDefButton": "Фильтровать таблицу",
	"a11yFilterBarDefButton": "Фильтровать...",
	"filterBarClearButton": "Очистить фильтр",
	"waiFilterBarClearButton": "Очистить фильтр",
	"closeFilterBarBtn": "Закрыть панель фильтров",
	"clearFilterMsg": "Эта опция удалит фильтр и будут показаны все доступные записи.",
	"anyColumnOption": "Любой столбец",
	"trueLabel": "Истина",
	"falseLabel": "Ложь"
})
);


text:
module InParallel
  VERSION = Version = '0.1.12'
end


text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace EasyWeChat\Kernel\Messages;

/**
 * Class Raw.
 */
class Raw extends Message
{
    /**
     * @var string
     */
    protected $type = 'raw';

    /**
     * Properties.
     *
     * @var array
     */
    protected $properties = ['content'];

    /**
     * Constructor.
     *
     * @param string $content
     */
    public function __construct(string $content)
    {
        parent::__construct(['content' => strval($content)]);
    }

    /**
     * @param array $appends
     * @param bool  $withType
     *
     * @return array
     */
    public function transformForJsonRequest(array $appends = [], $withType = true): array
    {
        return json_decode($this->content, true) ?? [];
    }

    public function __toString()
    {
        return $this->get('content') ?? '';
    }
}


text:
Splendid has a extensive API for plugin developers to easily access the many aspects of the editor this accomplished by using
AngularJS Services.

**More To Come!**


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>A wild tea tasting session</title>
    <meta name="description" content="Hiding in plain sight along every hedge row in England is an underutilised wealth of flavour.  Each year from late July to September a separate crop of "weed...">

    <meta name="keywords" content="features" />

    <meta name="HandheldFriendly" content="True">
    <meta name="robots" content="index,follow">
    <meta name="googlebot" content="index,follow">

	<meta property="og:title" content="A wild tea tasting session" />
	<meta property="og:type" content="article" />

<meta property="og:image" content="/media/img/wildteas/tea.jpg" />

<meta property="og:site_name" content="BOLDLY GOES" />
<meta property="og:description" content="Hiding in plain sight along every hedge row in England is an underutilised wealth of flavour.  Each year from late July to September a separate crop of "weed..." />

<meta property="og:url" content="/features/wild-teas" />

	<meta property="article:author" content="" />
	<link rel="author" href="" />

<meta property="article:published_time" content="2017-07-07T00:00:00+01:00" />

<meta property="article:tag" content="features" />

    <link href='https://fonts.googleapis.com/css?family=Mrs+Saint+Delafield|Merriweather:300italic,700,300,700italic|Open+Sans:400,700' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" type="text/css" href="https://boldlygoes.co.uk/css/prism.css">
    <link rel="stylesheet" type="text/css" href="https://boldlygoes.co.uk/css/screen.css">

    <link rel="alternate" type="application/rss+xml" title="BOLDLY GOES" href="/feed.xml">

    <link rel="icon" href="/assets/favicon.ico" sizes="16x16" type="image/png">
    <link rel="icon" href="/assets/favicon-32.png" sizes="32x32" type="image/png">
    <link rel="icon" href="/assets/favicon-48.png" sizes="48x48" type="image/png">
    <link rel="icon" href="/assets/favicon-62.png" sizes="62x62" type="image/png">

BOLDLY GOES

Outdoor Articles and Reviews

Home

About

Features

Reviews

A wild tea tasting session

                <time datetime="2017-07-07T00:00:00+01:00" itemprop="datePublished">Jul 7, 2017</time>
                in

                features

Hiding in plain sight along every hedge row in England is an underutilised wealth of flavour.  Each year from late July to September a separate crop of "weeds" ripens in the gaps between fields of corn and peas and rots on the vine, almost entirely ignored both by farmers and the general population.  Most people are not even aware that the fruit exists and some who are are put off by the thought that foraging near fields might be seen as stealing, but actually as long as you are picking for personal consumption you are protected by the law in England and Wales.

"A person who picks mushrooms growing wild on any land, or who picks flowers, fruit or foliage from a plant growing wild on any land, does not (although not in possession of the land) steal what he picks, unless he does it for reward or for sale or other commercial purpose."
 - The England and Wales Theft Act 1968

Last summer, James and I decided to spend some time searching for and tasting some hedgerow delicacies, we were pleasantly surprised by what we found in a very short space of time.  We started with the more common forageable plants and chose tea as the medium by which to explore the flavours as it is easily prepared with the most basic camping equipment, requires no extra ingredients and no messy preparation or clean up.

We prepared each tea in the same way; by simply adding the foraged item to hot water, sometimes lightly crushing or tearing it first so that brewed faster.

We began with Blackberries, these sweet fruits are easily spotted on brambles all over the country and are tasty straight off of the plant.  Brewing a handful in to two cups of hot water provides a sweet and light flavour with an aftertaste dominated by tannins which stays with you for some time and really wakes you up.  Brewed with more berries, the sugars override the astringent aftertaste and make something we really recommend, especially when you are cold and need a pick-me-up in the woods.

Sweet and slightly tangy, it would be most welcome on a cold morning or once left to cool, enjoyed as a cordial on a summer's day.

Next we picked some leaves from a Hawthorn bush, tore them up and added them with a few seeded berries to boiling water.  This tea did not smell particularly appetising and tasted about the same, quite earthy, bitter but with some of the apple-y notes that the leaves provide when chewed raw.   I took some of the berries home and dried them above my boiler; the dried berries made for a much sweeter tea, but it wasn't really worth the work.

Our final and surprisingly palatable tea came from the abundant wild spearmint supply in the meadow the other side of the hedgerow.  We expected to taste mint straight away, but there is actually a sweet and aromatic tangy flavour more like celery first, followed by an airy spearmint aftertaste.  We would definitely recommend this tea, mostly because it is so easy to prepare and tastes incredible, but also because it always seems to grow in the best sunny spots in meadows covered in butterflies and bumblebees.  After all, the best foraging brings you to a new beautiful place physically as well as culinarily.

The spearmint tea left us with a refreshed feeling and a hankering for a Polo.

Once you start looking for tasty treats in the undergrowth a foraging Baader-Meinhof effect kicks in quite quickly, soon you'll be spotting food in places you have driven past every day for years and begin wondering why no-one else has noticed this before.  We picked everything we needed to make these teas and more from a single hedgerow on one side of a field in Hertfordshire.

This year I am fully prepared and have been on the lookout for flowers and other tell tale signs of a soon-to-be ripening feast in some hedges and trees while running.  I have marked several spots I think are developing well on my OS map and plan to bring you some more tasting sessions and recipe ideas later in the season.

Remember not to over do it with any foraged fruit and plants, not only because you should leave some for the local wildlife and re-seeding for next year, but also because some foraged fruits contain chemicals that can be both beneficial and detrimental to your health.  If you have any ongoing medical conditions check with a doctor before you try some of these teas!

            Sam Scott-Hake's Picture

Sam Scott-Hake

            Herts, UK
            11 posts

    			View Comments...

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>

    <button class="go-to-top"></button>

BOLDLY GOES © 2017 | RSS Feed

</script>