text:
package com.liferay.knowledgebase.service.impl;

import com.liferay.knowledgebase.admin.util.AdminUtil;
import com.liferay.knowledgebase.model.KBArticle;
import com.liferay.knowledgebase.model.KBArticleSearchDisplay;
import com.liferay.knowledgebase.model.KBFolderConstants;
import com.liferay.knowledgebase.model.impl.KBArticleSearchDisplayImpl;
import com.liferay.knowledgebase.service.base.KBArticleServiceBaseImpl;
import com.liferay.knowledgebase.service.permission.AdminPermission;
import com.liferay.knowledgebase.service.permission.DisplayPermission;
import com.liferay.knowledgebase.service.permission.KBArticlePermission;
import com.liferay.knowledgebase.util.ActionKeys;
import com.liferay.knowledgebase.util.KnowledgeBaseUtil;
import com.liferay.knowledgebase.util.PortletKeys;
import com.liferay.knowledgebase.util.comparator.KBArticleModifiedDateComparator;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.search.SearchContainer;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ArrayUtil;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.ListUtil;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.workflow.WorkflowConstants;
import com.liferay.portal.model.Group;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.RSSUtil;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.feed.synd.SyndLink;
import com.sun.syndication.feed.synd.SyndLinkImpl;
import com.sun.syndication.io.FeedException;

import java.io.InputStream;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Peter Shin
 * @author Brian Wing Shun Chan
 */
public class KBArticleServiceImpl extends KBArticleServiceBaseImpl {

	@Override
	public KBArticle addKBArticle(
			String portletId, long parentResourceClassNameId,
			long parentResourcePrimKey, String title, String urlTitle,
			String content, String description, String sourceURL,
			String[] sections, String[] selectedFileNames,
			ServiceContext serviceContext)
		throws PortalException, SystemException {

		if (portletId.equals(PortletKeys.KNOWLEDGE_BASE_ADMIN)) {
			AdminPermission.check(
				getPermissionChecker(), serviceContext.getScopeGroupId(),
				ActionKeys.ADD_KB_ARTICLE);
		}
		else if (portletId.equals(PortletKeys.KNOWLEDGE_BASE_DISPLAY)) {
			DisplayPermission.check(
				getPermissionChecker(), serviceContext.getScopeGroupId(),
				ActionKeys.ADD_KB_ARTICLE);
		}

		return kbArticleLocalService.addKBArticle(
			getUserId(), parentResourceClassNameId, parentResourcePrimKey,
			title, urlTitle, content, description, sourceURL, sections,
			selectedFileNames, serviceContext);
	}

	@Override
	public int addKBArticlesMarkdown(
			long groupId, long parentKBFolderId, String fileName,
			boolean prioritizeByNumericalPrefix, InputStream inputStream,
			ServiceContext serviceContext)
		throws PortalException, SystemException {

		AdminPermission.check(
			getPermissionChecker(), groupId, ActionKeys.ADD_KB_ARTICLE);

		return kbArticleLocalService.addKBArticlesMarkdown(
			getUserId(), groupId, parentKBFolderId, fileName,
			prioritizeByNumericalPrefix, inputStream, serviceContext);
	}

	@Override
	public void addTempAttachment(
			long groupId, long resourcePrimKey, String fileName,
			String tempFolderName, InputStream inputStream, String mimeType)
		throws PortalException, SystemException {

		checkAttachmentPermissions(
			groupId, PortletKeys.KNOWLEDGE_BASE_ADMIN, resourcePrimKey);

		kbArticleLocalService.addTempAttachment(
			groupId, getUserId(), fileName, tempFolderName, inputStream,
			mimeType);
	}

	@Override
	public KBArticle deleteKBArticle(long resourcePrimKey)
		throws PortalException, SystemException {

		KBArticlePermission.check(
			getPermissionChecker(), resourcePrimKey, ActionKeys.DELETE);

		return kbArticleLocalService.deleteKBArticle(resourcePrimKey);
	}

	@Override
	public void deleteKBArticles(long groupId, long[] resourcePrimKeys)
		throws PortalException, SystemException {

		AdminPermission.check(
			getPermissionChecker(), groupId, ActionKeys.DELETE_KB_ARTICLES);

		kbArticleLocalService.deleteKBArticles(resourcePrimKeys);
	}

	@Override
	public void deleteTempAttachment(
			long groupId, long resourcePrimKey, String fileName,
			String tempFolderName)
		throws PortalException, SystemException {

		checkAttachmentPermissions(
			groupId, PortletKeys.KNOWLEDGE_BASE_ADMIN, resourcePrimKey);

		kbArticleLocalService.deleteTempAttachment(
			groupId, getUserId(), fileName, tempFolderName);
	}

	@Override
	public KBArticle fetchLatestKBArticle(long resourcePrimKey, int status)
		throws PortalException, SystemException {

		KBArticle kbArticle = kbArticleLocalService.fetchLatestKBArticle(
			resourcePrimKey, status);

		if (kbArticle == null) {
			return null;
		}

		KBArticlePermission.check(
			getPermissionChecker(), kbArticle, ActionKeys.VIEW);

		return kbArticle;
	}

	@Override
	public List<KBArticle> getGroupKBArticles(
			long groupId, int status, int start, int end,
			OrderByComparator orderByComparator)
		throws SystemException {

		if (status == WorkflowConstants.STATUS_ANY) {
			return kbArticlePersistence.filterFindByG_L(
				groupId, true, start, end, orderByComparator);
		}
		else if (status == WorkflowConstants.STATUS_APPROVED) {
			return kbArticlePersistence.filterFindByG_M(
				groupId, true, start, end, orderByComparator);
		}

		return kbArticlePersistence.filterFindByG_S(
			groupId, status, start, end, orderByComparator);
	}

	@Override
	public int getGroupKBArticlesCount(long groupId, int status)
		throws SystemException {

		if (status == WorkflowConstants.STATUS_ANY) {
			return kbArticlePersistence.filterCountByG_L(groupId, true);
		}
		else if (status == WorkflowConstants.STATUS_APPROVED) {
			return kbArticlePersistence.filterCountByG_M(groupId, true);
		}

		return kbArticlePersistence.filterCountByG_S(groupId, status);
	}

	@Override
	public String getGroupKBArticlesRSS(
			int status, int rssDelta, String rssDisplayStyle, String rssFormat,
			ThemeDisplay themeDisplay)
		throws PortalException, SystemException {

		Group group = themeDisplay.getScopeGroup();

		String descriptiveName = HtmlUtil.escape(
			group.getDescriptiveName(themeDisplay.getLocale()));

		String name = descriptiveName;
		String description = descriptiveName;

		String feedURL = PortalUtil.getLayoutFullURL(themeDisplay);

		List<KBArticle> kbArticles = getGroupKBArticles(
			group.getGroupId(), status, 0, rssDelta,
			new KBArticleModifiedDateComparator());

		return exportToRSS(
			rssDisplayStyle, rssFormat, name, description, feedURL, kbArticles,
			themeDisplay);
	}

	@Override
	public KBArticle getKBArticle(long resourcePrimKey, int version)
		throws PortalException, SystemException {

		KBArticlePermission.check(
			getPermissionChecker(), resourcePrimKey, ActionKeys.VIEW);

		return kbArticleLocalService.getKBArticle(resourcePrimKey, version);
	}

	@Override
	public List<KBArticle> getKBArticleAndAllDescendantKBArticles(
			long groupId, long resourcePrimKey, int status,
			OrderByComparator orderByComparator)
		throws SystemException {

		List<KBArticle> kbArticles = getKBArticles(
			groupId, new long[] {resourcePrimKey}, status, null);

		kbArticles = ListUtil.copy(kbArticles);

		Long[][] params = new Long[][] {new Long[] {resourcePrimKey}};

		while ((params = KnowledgeBaseUtil.getParams(params[0])) != null) {
			List<KBArticle> curKBArticles = null;

			if (status == WorkflowConstants.STATUS_ANY) {
				curKBArticles = kbArticlePersistence.filterFindByG_P_L(
					groupId, ArrayUtil.toArray(params[1]), true);
			}
			else if (status == WorkflowConstants.STATUS_APPROVED) {
				curKBArticles = kbArticlePersistence.filterFindByG_P_M(
					groupId, ArrayUtil.toArray(params[1]), true);
			}
			else {
				curKBArticles = kbArticlePersistence.filterFindByG_P_S(
					groupId, ArrayUtil.toArray(params[1]), status);
			}

			kbArticles.addAll(curKBArticles);

			long[] resourcePrimKeys = StringUtil.split(
				ListUtil.toString(curKBArticles, "resourcePrimKey"), 0L);

			params[0] = ArrayUtil.append(
				params[0], ArrayUtil.toArray(resourcePrimKeys));
		}

		if (orderByComparator != null) {
			kbArticles = ListUtil.sort(kbArticles, orderByComparator);
		}

		return Collections.unmodifiableList(kbArticles);
	}

	/**
	 * @deprecated As of 7.0.0, replaced by
	 *             {@link #getKBArticleAndAllDescendantKBArticles(long, long,
	 *             int, com.liferay.portal.kernel.util.OrderByComparator)}
	 */
	@Override
	public List<KBArticle> getKBArticleAndAllDescendants(
			long groupId, long resourcePrimKey, int status,
			OrderByComparator orderByComparator)
		throws SystemException {

		return getKBArticleAndAllDescendantKBArticles(
			groupId, resourcePrimKey, status, orderByComparator);
	}

	@Override
	public String getKBArticleRSS(
			long resourcePrimKey, int status, int rssDelta,
			String rssDisplayStyle, String rssFormat, ThemeDisplay themeDisplay)
		throws PortalException, SystemException {

		KBArticle kbArticle = kbArticleLocalService.getLatestKBArticle(
			resourcePrimKey, status);

		String name = kbArticle.getTitle();
		String description = kbArticle.getTitle();

		String feedURL = KnowledgeBaseUtil.getKBArticleURL(
			themeDisplay.getPlid(), resourcePrimKey, status,
			themeDisplay.getPortalURL(), false);

		List<KBArticle> kbArticles = getKBArticleAndAllDescendantKBArticles(
			kbArticle.getGroupId(), resourcePrimKey, status,
			new KBArticleModifiedDateComparator());

		return exportToRSS(
			rssDisplayStyle, rssFormat, name, description, feedURL,
			ListUtil.subList(kbArticles, 0, rssDelta), themeDisplay);
	}

	@Override
	public List<KBArticle> getKBArticles(
			long groupId, long parentResourcePrimKey, int status, int start,
			int end, OrderByComparator orderByComparator)
		throws SystemException {

		if (status == WorkflowConstants.STATUS_ANY) {
			return kbArticlePersistence.filterFindByG_P_L(
				groupId, parentResourcePrimKey, true, start, end,
				orderByComparator);
		}
		else if (status == WorkflowConstants.STATUS_APPROVED) {
			return kbArticlePersistence.filterFindByG_P_M(
				groupId, parentResourcePrimKey, true, start, end,
				orderByComparator);
		}

		return kbArticlePersistence.filterFindByG_P_S(
			groupId, parentResourcePrimKey, status, start, end,
			orderByComparator);
	}

	@Override
	public List<KBArticle> getKBArticles(
			long groupId, long[] resourcePrimKeys, int status, int start,
			int end, OrderByComparator orderByComparator)
		throws SystemException {

		List<KBArticle> kbArticles = new ArrayList<KBArticle>();

		Long[][] params = new Long[][] {ArrayUtil.toArray(resourcePrimKeys)};

		while ((params = KnowledgeBaseUtil.getParams(params[0])) != null) {
			List<KBArticle> curKBArticles = null;

			if (status == WorkflowConstants.STATUS_ANY) {
				curKBArticles = kbArticlePersistence.filterFindByR_G_L(
					ArrayUtil.toArray(params[1]), groupId, true, start, end);
			}
			else if (status == WorkflowConstants.STATUS_APPROVED) {
				curKBArticles = kbArticlePersistence.filterFindByR_G_M(
					ArrayUtil.toArray(params[1]), groupId, true, start, end);
			}
			else {
				curKBArticles = kbArticlePersistence.filterFindByR_G_S(
					ArrayUtil.toArray(params[1]), groupId, status, start, end);
			}

			kbArticles.addAll(curKBArticles);
		}

		if (orderByComparator != null) {
			kbArticles = ListUtil.sort(kbArticles, orderByComparator);
		}
		else {
			kbArticles = KnowledgeBaseUtil.sort(resourcePrimKeys, kbArticles);
		}

		return Collections.unmodifiableList(kbArticles);
	}

	@Override
	public List<KBArticle> getKBArticles(
			long groupId, long[] resourcePrimKeys, int status,
			OrderByComparator orderByComparator)
		throws SystemException {

		return getKBArticles(
			groupId, resourcePrimKeys, status, QueryUtil.ALL_POS,
			QueryUtil.ALL_POS, orderByComparator);
	}

	@Override
	public int getKBArticlesCount(
			long groupId, long parentResourcePrimKey, int status)
		throws SystemException {

		if (status == WorkflowConstants.STATUS_ANY) {
			return kbArticlePersistence.filterCountByG_P_L(
				groupId, parentResourcePrimKey, true);
		}
		else if (status == WorkflowConstants.STATUS_APPROVED) {
			return kbArticlePersistence.filterCountByG_P_M(
				groupId, parentResourcePrimKey, true);
		}

		return kbArticlePersistence.filterCountByG_P_S(
			groupId, parentResourcePrimKey, status);
	}

	@Override
	public int getKBArticlesCount(
			long groupId, long[] resourcePrimKeys, int status)
		throws SystemException {

		int count = 0;

		Long[][] params = new Long[][] {ArrayUtil.toArray(resourcePrimKeys)};

		while ((params = KnowledgeBaseUtil.getParams(params[0])) != null) {
			if (status == WorkflowConstants.STATUS_ANY) {
				count += kbArticlePersistence.filterCountByR_G_L(
					ArrayUtil.toArray(params[1]), groupId, true);
			}
			else if (status == WorkflowConstants.STATUS_APPROVED) {
				count += kbArticlePersistence.filterCountByR_G_M(
					ArrayUtil.toArray(params[1]), groupId, true);
			}
			else {
				count += kbArticlePersistence.filterCountByR_G_S(
					ArrayUtil.toArray(params[1]), groupId, status);
			}
		}

		return count;
	}

	@Override
	public KBArticleSearchDisplay getKBArticleSearchDisplay(
			long groupId, String title, String content, int status,
			Date startDate, Date endDate, boolean andOperator,
			int[] curStartValues, int cur, int delta,
			OrderByComparator orderByComparator)
		throws PortalException, SystemException {

		// See LPS-9546

		int start = 0;

		if (curStartValues.length > (cur - SearchContainer.DEFAULT_CUR)) {
			start = curStartValues[cur - SearchContainer.DEFAULT_CUR];

			curStartValues = ArrayUtil.subset(
				curStartValues, 0, cur - SearchContainer.DEFAULT_CUR + 1);
		}
		else {
			cur = SearchContainer.DEFAULT_CUR;

			curStartValues = new int[] {0};
		}

		int end = start + _INTERVAL;

		List<KBArticle> kbArticles = new ArrayList<KBArticle>();

		int curStartValue = 0;

		while (curStartValue == 0) {
			List<KBArticle> curKBArticles = kbArticleLocalService.search(
				groupId, title, content, status, startDate, endDate,
				andOperator, start, end, orderByComparator);

			if (curKBArticles.isEmpty()) {
				break;
			}

			for (int i = 0; i < curKBArticles.size(); i++) {
				KBArticle curKBArticle = curKBArticles.get(i);

				if (!KBArticlePermission.contains(
						getPermissionChecker(), curKBArticle,
						ActionKeys.VIEW)) {

					continue;
				}

				if (kbArticles.size() == delta) {
					curStartValue = start + i;

					break;
				}

				kbArticles.add(curKBArticle);
			}

			start = start + _INTERVAL;
			end = start + _INTERVAL;
		}

		int total = ((cur - 1) * delta) + kbArticles.size();

		if (curStartValue > 0) {
			curStartValues = ArrayUtil.append(curStartValues, curStartValue);

			total = total + 1;
		}

		return new KBArticleSearchDisplayImpl(
			kbArticles, total, curStartValues);
	}

	@Override
	public List<KBArticle> getKBArticleVersions(
			long groupId, long resourcePrimKey, int status, int start, int end,
			OrderByComparator orderByComparator)
		throws SystemException {

		if (status == WorkflowConstants.STATUS_ANY) {
			return kbArticlePersistence.filterFindByR_G(
				resourcePrimKey, groupId, start, end, orderByComparator);
		}

		return kbArticlePersistence.filterFindByR_G_S(
			resourcePrimKey, groupId, status, start, end, orderByComparator);
	}

	@Override
	public int getKBArticleVersionsCount(
			long groupId, long resourcePrimKey, int status)
		throws SystemException {

		if (status == WorkflowConstants.STATUS_ANY) {
			return kbArticlePersistence.filterCountByR_G(
				resourcePrimKey, groupId);
		}

		return kbArticlePersistence.filterCountByR_G_S(
			resourcePrimKey, groupId, status);
	}

	@Override
	public KBArticle getLatestKBArticle(long resourcePrimKey, int status)
		throws PortalException, SystemException {

		KBArticlePermission.check(
			getPermissionChecker(), resourcePrimKey, ActionKeys.VIEW);

		return kbArticleLocalService.getLatestKBArticle(
			resourcePrimKey, status);
	}

	@Override
	public List<KBArticle> getSectionsKBArticles(
			long groupId, String[] sections, int status, int start, int end,
			OrderByComparator orderByComparator)
		throws SystemException {

		String[] array = AdminUtil.escapeSections(sections);

		for (int i = 0; i < array.length; i++) {
			array[i] = StringUtil.quote(array[i], StringPool.PERCENT);
		}

		if (status == WorkflowConstants.STATUS_ANY) {
			return kbArticlePersistence.filterFindByG_P_S_L(
				groupId, KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, array,
				true, start, end, orderByComparator);
		}
		else if (status == WorkflowConstants.STATUS_APPROVED) {
			return kbArticlePersistence.filterFindByG_P_S_M(
				groupId, KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, array,
				true, start, end, orderByComparator);
		}

		return kbArticlePersistence.filterFindByG_P_S_S(
			groupId, KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, array, status,
			start, end, orderByComparator);
	}

	@Override
	public int getSectionsKBArticlesCount(
			long groupId, String[] sections, int status)
		throws SystemException {

		String[] array = AdminUtil.escapeSections(sections);

		for (int i = 0; i < array.length; i++) {
			array[i] = StringUtil.quote(array[i], StringPool.PERCENT);
		}

		if (status == WorkflowConstants.STATUS_ANY) {
			return kbArticlePersistence.filterCountByG_P_S_L(
				groupId, KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, array,
				true);
		}
		else if (status == WorkflowConstants.STATUS_APPROVED) {
			return kbArticlePersistence.filterCountByG_P_S_M(
				groupId, KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, array,
				true);
		}

		return kbArticlePersistence.filterCountByG_P_S_S(
			groupId, KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, array, status);
	}

	/**
	 * @deprecated As of 7.0.0, replaced by {@link #getKBArticles(long, long,
	 *             int, int, int,
	 *             com.liferay.portal.kernel.util.OrderByComparator)}
	 */
	@Override
	public List<KBArticle> getSiblingKBArticles(
			long groupId, long parentResourcePrimKey, int status, int start,
			int end, OrderByComparator orderByComparator)
		throws SystemException {

		return getKBArticles(
			groupId, parentResourcePrimKey, status, start, end,
			orderByComparator);
	}

	/**
	 * @deprecated As of 7.0.0, replaced by {@link #getKBArticlesCount(long,
	 *             long, int)}
	 */
	@Override
	public int getSiblingKBArticlesCount(
			long groupId, long parentResourcePrimKey, int status)
		throws SystemException {

		return getKBArticlesCount(groupId, parentResourcePrimKey, status);
	}

	@Override
	public String[] getTempAttachmentNames(long groupId, String tempFolderName)
		throws PortalException, SystemException {

		return kbArticleLocalService.getTempAttachmentNames(
			groupId, getUserId(), tempFolderName);
	}

	@Override
	public void moveKBArticle(
			long resourcePrimKey, long parentResourceClassNameId,
			long parentResourcePrimKey, double priority)
		throws PortalException, SystemException {

		KBArticlePermission.check(
			getPermissionChecker(), resourcePrimKey,
			ActionKeys.MOVE_KB_ARTICLE);

		kbArticleLocalService.moveKBArticle(
			getUserId(), resourcePrimKey, parentResourceClassNameId,
			parentResourcePrimKey, priority);
	}

	@Override
	public void subscribeGroupKBArticles(long groupId, String portletId)
		throws PortalException, SystemException {

		if (portletId.equals(PortletKeys.KNOWLEDGE_BASE_ADMIN)) {
			AdminPermission.check(
				getPermissionChecker(), groupId, ActionKeys.SUBSCRIBE);
		}
		else if (portletId.equals(PortletKeys.KNOWLEDGE_BASE_DISPLAY)) {
			DisplayPermission.check(
				getPermissionChecker(), groupId, ActionKeys.SUBSCRIBE);
		}

		kbArticleLocalService.subscribeGroupKBArticles(getUserId(), groupId);
	}

	@Override
	public void subscribeKBArticle(long groupId, long resourcePrimKey)
		throws PortalException, SystemException {

		KBArticlePermission.check(
			getPermissionChecker(), resourcePrimKey, ActionKeys.SUBSCRIBE);

		kbArticleLocalService.subscribeKBArticle(
			getUserId(), groupId, resourcePrimKey);
	}

	@Override
	public void unsubscribeGroupKBArticles(long groupId, String portletId)
		throws PortalException, SystemException {

		if (portletId.equals(PortletKeys.KNOWLEDGE_BASE_ADMIN)) {
			AdminPermission.check(
				getPermissionChecker(), groupId, ActionKeys.SUBSCRIBE);
		}
		else if (portletId.equals(PortletKeys.KNOWLEDGE_BASE_DISPLAY)) {
			DisplayPermission.check(
				getPermissionChecker(), groupId, ActionKeys.SUBSCRIBE);
		}

		kbArticleLocalService.unsubscribeGroupKBArticles(getUserId(), groupId);
	}

	@Override
	public void unsubscribeKBArticle(long resourcePrimKey)
		throws PortalException, SystemException {

		KBArticlePermission.check(
			getPermissionChecker(), resourcePrimKey, ActionKeys.SUBSCRIBE);

		kbArticleLocalService.unsubscribeKBArticle(
			getUserId(), resourcePrimKey);
	}

	@Override
	public KBArticle updateKBArticle(
			long resourcePrimKey, String title, String content,
			String description, String sourceURL, String[] sections,
			String[] selectedFileNames, long[] removeFileEntryIds,
			ServiceContext serviceContext)
		throws PortalException, SystemException {

		KBArticlePermission.check(
			getPermissionChecker(), resourcePrimKey, ActionKeys.UPDATE);

		return kbArticleLocalService.updateKBArticle(
			getUserId(), resourcePrimKey, title, content, description,
			sourceURL, sections, selectedFileNames, removeFileEntryIds,
			serviceContext);
	}

	@Override
	public void updateKBArticlesPriorities(
			long groupId, Map<Long, Double> resourcePrimKeyToPriorityMap)
		throws PortalException, SystemException {

		AdminPermission.check(
			getPermissionChecker(), groupId,
			ActionKeys.UPDATE_KB_ARTICLES_PRIORITIES);

		kbArticleLocalService.updateKBArticlesPriorities(
			resourcePrimKeyToPriorityMap);
	}

	protected String exportToRSS(
			String rssDisplayStyle, String rssFormat, String name,
			String description, String feedURL, List<KBArticle> kbArticles,
			ThemeDisplay themeDisplay)
		throws SystemException {

		SyndFeed syndFeed = new SyndFeedImpl();

		syndFeed.setDescription(description);

		List<SyndEntry> syndEntries = new ArrayList<SyndEntry>();

		syndFeed.setEntries(syndEntries);

		for (KBArticle kbArticle : kbArticles) {
			SyndEntry syndEntry = new SyndEntryImpl();

			String author = PortalUtil.getUserName(kbArticle);

			syndEntry.setAuthor(author);

			SyndContent syndContent = new SyndContentImpl();

			syndContent.setType(RSSUtil.ENTRY_TYPE_DEFAULT);

			String value = null;

			if (rssDisplayStyle.equals(RSSUtil.DISPLAY_STYLE_ABSTRACT)) {
				value = HtmlUtil.extractText(kbArticle.getDescription());

				if (Validator.isNull(value)) {
					value = StringUtil.shorten(
						HtmlUtil.extractText(kbArticle.getContent()), 200);
				}
			}
			else if (rssDisplayStyle.equals(RSSUtil.DISPLAY_STYLE_TITLE)) {
				value = StringPool.BLANK;
			}
			else {
				value = StringUtil.replace(
					kbArticle.getContent(),
					new String[] {
						"href=\"/", "src=\"/"
					},
					new String[] {
						"href=\"" + themeDisplay.getURLPortal() + "/",
						"src=\"" + themeDisplay.getURLPortal() + "/"
					});
			}

			syndContent.setValue(value);

			syndEntry.setDescription(syndContent);

			String link = KnowledgeBaseUtil.getKBArticleURL(
				themeDisplay.getPlid(), kbArticle.getResourcePrimKey(),
				kbArticle.getStatus(), themeDisplay.getPortalURL(), false);

			syndEntry.setLink(link);
			syndEntry.setPublishedDate(kbArticle.getCreateDate());
			syndEntry.setTitle(kbArticle.getTitle());
			syndEntry.setUpdatedDate(kbArticle.getModifiedDate());
			syndEntry.setUri(syndEntry.getLink());

			syndEntries.add(syndEntry);
		}

		String feedType = RSSUtil.getFeedType(
			RSSUtil.getFormatType(rssFormat),
			RSSUtil.getFormatVersion(rssFormat));

		syndFeed.setFeedType(feedType);

		List<SyndLink> syndLinks = new ArrayList<SyndLink>();

		syndFeed.setLinks(syndLinks);

		SyndLink selfSyndLink = new SyndLinkImpl();

		syndLinks.add(selfSyndLink);

		selfSyndLink.setHref(feedURL);
		selfSyndLink.setRel("self");

		syndFeed.setPublishedDate(new Date());
		syndFeed.setTitle(name);
		syndFeed.setUri(feedURL);

		try {
			return RSSUtil.export(syndFeed);
		}
		catch (FeedException fe) {
			throw new SystemException(fe);
		}
	}

	private void checkAttachmentPermissions(
			long groupId, String portletId, long resourcePrimKey)
		throws PortalException, SystemException {

		if ((resourcePrimKey <= 0) &&
			portletId.equals(PortletKeys.KNOWLEDGE_BASE_ADMIN)) {

			AdminPermission.check(
				getPermissionChecker(), groupId, ActionKeys.ADD_KB_ARTICLE);
		}
		else if ((resourcePrimKey <= 0) &&
				 portletId.equals(PortletKeys.KNOWLEDGE_BASE_DISPLAY)) {

			DisplayPermission.check(
				getPermissionChecker(), groupId, ActionKeys.ADD_KB_ARTICLE);
		}
		else {
			KBArticlePermission.check(
				getPermissionChecker(), resourcePrimKey, ActionKeys.UPDATE);
		}
	}

	private static final int _INTERVAL = 200;

}


text:
This is a fork to Swift 2, currently using Xcode 7 beta 1.

# usage

### Simple use cases: `String` extension methods

**String.grep()**

This method is modeled after Javascript's `String.match()`.  It returns a `Regex.MatchResult` object.  The object's `captures` property is an array of `String`s much as one would expect from its Javascript equivalent.

```swift
let result = "Winnie the Pooh".grep("\\s+([a-z]+)\\s+")

result.searchString == "Winnie the Pooh"
result.captures.count == 2
result.captures[0] == " the "
result.captures[1] == "the"
result.boolValue == true       // `boolValue` is `true` if there were more than 0 matches

// You can use `grep()` in conditionals because of the `boolValue` property its result exposes
let emailAddress = "bryn&typos.org"
if !emailAddress.grep("@") {
    // that's not an email address!
}
```

**String.replaceRegex()**

This method is modeled after the version of Javascript's `String.replace()` that accepts a Regex parameter.

```swift
let name = "Winnie the Pooh"
let darkName = name.replaceRegex("Winnie the ([a-zA-Z]+)", with: "Darth $1")
// darkName == "Darth Pooh"
```

### Advanced use cases: `Regex` object and operators

**operator =~**

You can use the `=~` operator to search a `String` (the left operand) for a `Regex` (the right operand).  It's the same as calling `theString.grep("the regex pattern")`, but might be more clear in some cases.  It returns the same `Regex.MatchResult` object as `String.grep()`.

```swift
"Winnie the Pooh" =~ Regex("\\s+(the)\\s+")  // returns a Regex.MatchResult
```

Quickly loop over a `Regex`'s captures:

```swift
for capture in ("Winnie the Pooh" =~ Regex("\\s+(the)\\s+")).captures {
    // capture is a String
}
```

# Overriden `map()` function for substitution

A more "functional programming" way of doing string replacement is possible via an override for `map()`.  In keeping with the overall aim to avoid reinventing a perfectly good wheel (i.e., `NSRegularExpression`), this function simply calls through to `NSRegularExpression.replaceMatchesInString()`.

```swift
func map (regexResult:Regex.MatchResult, _ replacementTemplate:String) -> String
```

You can use it like so:

```swift
let stageName = map("Winnie the Pooh" =~ Regex("([a-zA-Z]+)\\s+(the)(.*)"), "$2 $1")
// stageName == "the Winnie"
```

Or if you have some functional operators lying around (for example: <https://github.com/brynbellomy/Funky>), it's a little less wordy:

```swift
("Winnie the Pooh" =~ Regex("([a-zA-Z]+)\\s+(the)(.*)")) |> map‡("$2 $1")
```

... but you have to be as crazy as me to find that more readable than `"Winnie".replaceRegex(_:withString:)`, so no pressure.

# contributors / authors

- bryn austin bellomy (<bryn.bellomy@gmail.com>)
- Ahmad Alhashemi (http://hashemi.md/)

redpajama_set_name: RedPajamaGithub


text:
#ifndef BOOST_HANA_IS_EMPTY_HPP
#define BOOST_HANA_IS_EMPTY_HPP

#include <boost/hana/fwd/is_empty.hpp>

#include <boost/hana/concept/iterable.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/core/dispatch.hpp>

BOOST_HANA_NAMESPACE_BEGIN
    //! @cond
    template <typename Xs>
    constexpr auto is_empty_t::operator()(Xs const& xs) const {
        using It = typename hana::tag_of<Xs>::type;
        using IsEmpty = BOOST_HANA_DISPATCH_IF(is_empty_impl<It>,
            hana::Iterable<It>::value
        );

    #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
        static_assert(hana::Iterable<It>::value,
        "hana::is_empty(xs) requires 'xs' to be an Iterable");
    #endif

        return IsEmpty::apply(xs);
    }
    //! @endcond

    template <typename It, bool condition>
    struct is_empty_impl<It, when<condition>> : default_ {
        template <typename ...Args>
        static constexpr auto apply(Args&& ...) = delete;
    };
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_IS_EMPTY_HPP


text:
package com.google.firebase.auth.api.internal;

import org.microg.safeparcel.AutoSafeParcelable;

public class SignInWithEmailAndPasswordAidlRequest extends AutoSafeParcelable {
    @Field(1)
    public String email;
    @Field(2)
    public String password;
    @Field(3)
    public String tenantId;
    public static final Creator<SignInWithEmailAndPasswordAidlRequest> CREATOR = new AutoCreator<>(SignInWithEmailAndPasswordAidlRequest.class);
}


text:
package org.aieonf.template.def;

import org.aieonf.concept.locator.ILocatorAieon;

public interface ITemplateAieon extends ILocatorAieon
{
}


text:
from google.cloud import websecurityscanner_v1alpha

def sample_delete_scan_config():
    # Create a client
    client = websecurityscanner_v1alpha.WebSecurityScannerClient()

    # Initialize request argument(s)
    request = websecurityscanner_v1alpha.DeleteScanConfigRequest(
        name="name_value",
    )

    # Make the request
    client.delete_scan_config(request=request)

# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_sync]


text:
<?php

namespace ChopBox;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
            'username',
            'email',
            'password',
            'status',
            'profile_state'
    ];

    public function favourites()
    {
        return $this->hasMany('ChopBox\Favourite');
    }

    public function uploads()
    {
        return $this->hasMany('ChopBox\Upload');
    }

    public function roles()
    {
        return $this->belongsToMany('ChopBox\Role');
    }

    public function chops()
    {
        return $this->hasMany('ChopBox\Chop');
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.apixandru.rummikub</groupId>
        <artifactId>rummikub</artifactId>
        <version>0.0.3-SNAPSHOT</version>
    </parent>

    <artifactId>rummikub-model</artifactId>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

    </dependencies>

</project>


text:
""" Measures for polygon meshes """

__copyright__ = "Copyright 2011, UniDesign Development Team"
__license__ = "BSD"
__authors__ = ["Stephan Gerhard <connectome@unidesign.ch>"]

import numpy as np

from ..geometry import polygonmesh

def surface_area(polygon_mesh):
    """ Computes the surface area for a polygon mesh.

    Parameters
    ----------
    polygon_mesh : ``PolygonMesh`` object

    Returns
    -------
    result : surface area

    """
    if isinstance(polygon_mesh, polygonmesh.FaceVertexMesh):
        print("A FaceVertex Mesh")
        result = 0.0
        for face in polygon_mesh.faces:
            v1, v2, v3 = face
            result += 0.5 * abs(np.linalg.norm(
                np.cross(
                    polygon_mesh.vertices[v2]-polygon_mesh.vertices[v1],
                    polygon_mesh.vertices[v3]-polygon_mesh.vertices[v1] )))
        return result

    return None


text:
#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H
#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H

#include "policy/policy_types.h"
#include "utils/lock.h"
#include "utils/timer_thread.h"
#include "utils/threads/thread.h"
#include "utils/threads/thread_delegate.h"
#include "utils/conditional_variable.h"
#include "utils/lock.h"
#include "utils/logger.h"
#include "utils/macro.h"

namespace policy {

class PolicyListener;

class UpdateStatusManager {
 public:
  /**
   * @brief Constructor
   */
  UpdateStatusManager();

  ~UpdateStatusManager();

  /**
   * @brief Sets listener pointer
   * @param listener Pointer to policy listener implementation
   */
  void set_listener(PolicyListener* listener);

  /**
   * @brief Update status hanlder for PTS sending out
   * @param update_timeout Timeout for waiting of incoming PTU
   */
  void OnUpdateSentOut(uint32_t update_timeout);

  /**
   * @brief Update status handler for PTU waiting timeout
   */
  void OnUpdateTimeoutOccurs();

  /**
   * @brief Update status handler for valid PTU receiving
   */
  void OnValidUpdateReceived();

  /**
   * @brief Update status handler for wrong PTU receiving
   */
  void OnWrongUpdateReceived();

  /**
   * @brief Update status handler for reset PT to default state
   * @param is_update_required Update necessity flag
   */
  void OnResetDefaultPT(bool is_update_required);

  /**
   * @brief Update status handler for restarting retry sequence
   */
  void OnResetRetrySequence();

  /**
   * @brief Update status handler on new application registering
   */
  void OnNewApplicationAdded();

  /**
   * @brief Update status handler for policy initialization
   * @param is_update_required Update necessity flag
   */
  void OnPolicyInit(bool is_update_required);

  /**
   * @brief IsUpdateRequired allows to distiguish if update is required
   *
   * @return  true if update required.
   */
  bool IsUpdateRequired() const;

  /**
   * @brief IsUpdatePending allows to distinguish if update is in pending mode.
   *
   * @return true if update is in pending mode.
   */
  bool IsUpdatePending() const;

  /**
   * @brief ScheduleUpdate allows to schedule next update.
   * It will change state to Update_Needed, that's is.
   */
  void ScheduleUpdate();

  /**
   * @brief ResetUpdateSchedule allows to reset all scheduled updates.
   */
  void ResetUpdateSchedule();

  /**
   * @brief StringifiedUpdateStatus allows to obtain update status as a string.
   *
   * @return stringified update status.
   */
  std::string StringifiedUpdateStatus() const;

  /**
   * @brief Status handler on applications search started
   */
  void OnAppsSearchStarted();

  /**
   * @brief Status handler on applications search completed
   */
  void OnAppsSearchCompleted();

  /**
   * @brief Returns status is application search in progress
   * @return true, if in progress, otherwise - false
   */
  bool IsAppsSearchInProgress();

private:
  /*
   * @brief Sets flag for update progress
   *
   * @param value
   */
  void set_exchange_in_progress(bool value);

  /*
   * @brief Sets flag for pending update
   *
   * @param value
   */
  void set_exchange_pending(bool value);

  /*
   * @brief Sets flag for update necessity
   *
   * @param value
   */
  void set_update_required(bool value);

  /**
   * @brief Check update status and notify HMI on changes
   */
  void CheckUpdateStatus();

private:

  /**
   * @brief Returns current policy update status
   * @return
   */
  PolicyTableStatus GetUpdateStatus() const;

  PolicyListener* listener_;
  bool exchange_in_progress_;
  bool update_required_;
  bool update_scheduled_;
  bool exchange_pending_;
  bool apps_search_in_progress_;
  sync_primitives::Lock exchange_in_progress_lock_;
  sync_primitives::Lock update_required_lock_;
  sync_primitives::Lock exchange_pending_lock_;
  sync_primitives::Lock apps_search_in_progress_lock_;
  /**
   * @brief Last status of policy table update
   */
  PolicyTableStatus last_update_status_;

  class UpdateThreadDelegate: public threads::ThreadDelegate {

  public:
    UpdateThreadDelegate(UpdateStatusManager* update_status_manager);
    ~UpdateThreadDelegate();
    virtual void threadMain();
    virtual void exitThreadMain();
    void updateTimeOut(const uint32_t timeout_ms);

    volatile uint32_t                                timeout_;
    volatile bool                                    stop_flag_;
    sync_primitives::Lock                            state_lock_;
    sync_primitives::ConditionalVariable             termination_condition_;
    UpdateStatusManager*                             update_status_manager_;
  };

  UpdateThreadDelegate*                              update_status_thread_delegate_;
  threads::Thread*                                   thread_;
};

}

#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H


text:
package gobblin.data.management.conversion.hive.extractor;

import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.thrift.TException;
import gobblin.configuration.WorkUnitState;

/**
 * Factory for {@link HiveConvertExtractor}
 */
public class HiveConvertExtractorFactory implements HiveBaseExtractorFactory {
  public HiveBaseExtractor createExtractor(WorkUnitState state, FileSystem sourceFs)
      throws IOException, TException, HiveException {
    return new HiveConvertExtractor(state, sourceFs);
  }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../openssl_sys/enum.OCSP_REQUEST.html">

Redirecting to ../../openssl_sys/enum.OCSP_REQUEST.html...


text:
bool Options::_ohhh;
bool Options::_page_table;
bool Options::_frame_table;
bool Options::_summary;

bool Options::_dbg_page_table;
bool Options::_dbg_frame_table;
bool Options::_dbg_aging;

void Options::init_options(char *options)
{
    _ohhh = false;
    _page_table = false;
    _frame_table = false;
    _summary = false;

    _dbg_aging = false;
    _dbg_page_table = false;
    _dbg_frame_table = false;

    if (options == NULL)
    {
        printf("Options::parse_options - input string is NULL");
        return;
    }

    int len = strlen(options);

    for ( int i = 0; i < len; i++ )
    {
        switch(options[i])
        {
            case 'o':
            case 'O':
                _ohhh = true;
                break;

            case 'p':
                _dbg_page_table = true;
                break;

            case 'P':
                _page_table = true;
                break;

            case 'f':
                _dbg_frame_table = true;
                break;

            case 'F':
                _frame_table = true;
                break;

            case 's':
            case 'S':
                _summary = true;
                break;

            case 'a':
            case 'A':
                _dbg_aging = true;
                break;

            default:
                printf("Options::init_options - Unknown argument %c, will ignore\n", options[i]);
                break;
        }
    }
}

bool Options::ohhh()
{
    return _ohhh;
}

bool Options::page_table()
{
    return _page_table;
}

bool Options::frame_table()
{
    return _frame_table;
}

bool Options::summary()
{
    return _summary;
}

bool Options::dbg_page_table()
{
    return _dbg_page_table;
}

bool Options::dbg_frame_table()
{
    return _dbg_frame_table;
}

bool Options::dbg_aging()
{
    return _dbg_aging;
}


text:
package ru.taximaxim.dbreplicator2;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import ru.taximaxim.dbreplicator2.abstracts.AbstractSettingTest;
import ru.taximaxim.dbreplicator2.model.HikariCPSettingsModel;
import ru.taximaxim.dbreplicator2.model.RunnerModel;
import ru.taximaxim.dbreplicator2.model.StrategyModel;

public class StrategiesTest extends AbstractSettingTest {

    protected static final Logger LOG = Logger.getLogger(StrategiesTest.class);

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        setUp(null, null, null);
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        close();
    }

    /**
     * Проверка создания модели исполняемого потока и стратегии.
     */
    @Test
    public void test() {

        session.beginTransaction();

        RunnerModel runner = createRunner(new HikariCPSettingsModel(), new HikariCPSettingsModel(), "Описание исполняемого потока");
        StrategyModel strategy = createStrategy(1, "ru.taximaxim.Class", "key", "value", true, 100);

        assertNull(runner.getId());
        LOG.debug("Идентификатор потока перед сохранением: " + runner.getId());

        addStrategy(runner, strategy);
        session.saveOrUpdate(runner);
        session.saveOrUpdate(strategy);

        LOG.debug("Идентификатор потока после его сохранения: " + runner.getId());
        assertNotNull(runner.getId());

        RunnerModel runner_compare = (RunnerModel) session.get(RunnerModel.class, runner.getId());

        LOG.debug("Идентификатор потока после его восстановления: " + runner_compare.getId());
        assertEquals(runner.getId(), runner_compare.getId());

        RunnerModel runner2 = createRunner(new HikariCPSettingsModel(), new HikariCPSettingsModel(), "Описание исполняемого потока (2)");
        StrategyModel strategy2 = createStrategy(2, "ru.taximaxim.Class", "key", "value", true, 100);
        addStrategy(runner2, strategy2);

        session.saveOrUpdate(runner2);
        session.saveOrUpdate(strategy2);

        assertNotNull(runner2.getStrategyModels().get(0).getId());
        assertEquals("Нарушение описания состаного ключа стратегии", runner2, runner2.getStrategyModels().get(0).getRunner());

        StrategyModel strategy3 = createStrategy(3, "ru.taximaxim.Class", "key", "value", true, 100);
        addStrategy(runner2, strategy3);

        session.saveOrUpdate(runner2);
        session.saveOrUpdate(strategy3);

        assertNotNull(runner2.getStrategyModels().get(1).getId());
        assertEquals("Нарушение описания состаного ключа стратегии", runner2, runner2.getStrategyModels().get(1).getRunner());
    }

    public RunnerModel createRunner(HikariCPSettingsModel source, HikariCPSettingsModel target, String description) {

        RunnerModel runner = new RunnerModel();

        runner.setSource(source);
        runner.setTarget(target);
        runner.setDescription(description);

        return runner;
    }

    public StrategyModel createStrategy(Integer id, String className, String key, String value, boolean isEnabled, int priority) {

        StrategyModel strategy = new StrategyModel();

        strategy.setId(id);
        strategy.setClassName(className);
        strategy.setParam(key, value);
        strategy.setEnabled(isEnabled);
        strategy.setPriority(priority);

        return strategy;
    }

    public void addStrategy(RunnerModel runner, StrategyModel strategy) {

        runner.getStrategyModels().add(strategy);
        strategy.setRunner(runner);

    }

    /**
     * Тестирование работы механизма хранения многострочных параметров
     */
    @Test
    public void paramTest(){
        StrategyModel strategy = new StrategyModel();

        // Добавляем 1 параметр
        strategy.setParam("1", "11");

        // Добавляем 2 параметр
        strategy.setParam("2", "22");

        // Проверяем оба параметра
        assertEquals("Ошибка в 1 параметре!", "11", strategy.getParam("1"));
        assertEquals("Ошибка в 2 параметре!", "22", strategy.getParam("2"));
    }
}


text:
package org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.fixture;

import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;
import java.util.Properties;

public final class MultiAlgorithm implements ComplexKeysShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(final Collection<String> availableTargetNames, final ComplexKeysShardingValue<String> shardingValue) {
        return null;
    }

    @Override
    public String getType() {
        return "COMPLEX_TEST";
    }

    @Override
    public Properties getProperties() {
        return new Properties();
    }

    @Override
    public void setProperties(final Properties properties) {
    }
}


text:
import tl = require("vsts-task-lib/task");
import fs = require("fs");

// moving the logging function to a separate file

export function logDebug (msg: string) {
    tl.debug(msg);
}

export function logWarning (msg: string) {
    tl.warning(msg);
 }

export function logInfo (msg: string) {
     console.log(msg);
}

export function logError (msg: string) {
    tl.error(msg);
    tl.setResult(tl.TaskResult.Failed, msg);
}

export function writeVariable (variableName: string, value: string) {
     if (variableName) {
        logInfo(`Writing output variable ${variableName}`);
        // the newlines cause a problem only first line shown
        // so remove them
        var newlineRemoved = value.replace(/\n/gi, "`n");
        tl.setVariable(variableName, newlineRemoved );
    }
}

export function getSystemAccessToken(): string {
    tl.debug("Getting credentials the agent is running as");
    var auth = tl.getEndpointAuthorization("SYSTEMVSSCONNECTION", false);
    if (auth.scheme === "OAuth") {
        tl.debug("Found an OAUTH token");
        return auth.parameters["AccessToken"];
    } else {
        tl.warning(tl.loc("BuildCredentialsWarn"));
    }
}


text:
from m5.defines import buildEnv
from m5.params import *
from m5.proxy import *
from Device import BasicPioDevice

class X86LocalApic(BasicPioDevice):
    type = 'X86LocalApic'
    cxx_class = 'X86ISA::Interrupts'
    cxx_header = 'arch/x86/interrupts.hh'
    int_master = MasterPort("Port for sending interrupt messages")
    int_slave = SlavePort("Port for receiving interrupt messages")
    int_latency = Param.Latency('1ns', \
            "Latency for an interrupt to propagate through this device.")


text:
package core.report.models;

import core.actions.custom.base.SimpleAction;
import core.report.enums.ReportType;

/**
 * Created by Arsen on 26.02.2017.
 */
public class PendingActionReport extends BaseReport {

    public PendingActionReport(SimpleAction action) {
        super(action, "");
    }

    @Override
    public ReportType getType() {
        return ReportType.PENDING_ACTION;
    }

}


text:
//
// Created by redra on 05.07.17.
//

#include <iostream>
#include <icc/Component.hpp>
#include <icc/Event.hpp>
#include <icc/Timer.hpp>
#include <icc/localbus/IService.hpp>
#include <icc/localbus/IClient.hpp>
#include "Forecast.hpp"

class WeatherStation
    : public icc::localbus::IService<Forecast>,
      public icc::ITimerListener {
 public:
  WeatherStation(std::shared_ptr<icc::IContext> _io_service)
      : icc::Component(_io_service),
        icc::localbus::IService<Forecast>("WeatherStation"),
        timer_() {
    std::cout << "WeatherStation" << std::endl;
    // Experimentation
    temperature2_ = 22;
  }

  ~WeatherStation() {
    std::cout << "~WeatherStation" << std::endl;
  }

  void processEvent(const icc::TimerEvents & _event) override {
    if (icc::TimerEvents::EXPIRED == _event) {
      std::cout << "processEvent icc::TimerEvents::EXPIRED" << std::endl;
      temperature_(28.3);
    }
  }

  void setIntervalForUpdate(int & _seconds) override {
    std::cout << "setIntervalForUpdate: seconds = " << _seconds << std::endl;
    timer_.setInterval(std::chrono::seconds(_seconds));
    timer_.setNumberOfRepetition(icc::Timer::Infinite);
    timer_.addListener(this);
    timer_.start();
  }

 protected:
  /**
   * Service with timer should override exit
   * method from parent component for stopping timer
   * and releasing io::service
   */
  void exit() override {
    icc::localbus::IService<Forecast>::exit();
    timer_.stop();
  }

 private:
  icc::Timer timer_;
};

class TestObserver
    : public icc::Component {
 public:
  using icc::Component::Component;
 public:
  void onTemperature(const double & _temperature) {
    std::cout << "TestObserver::Temperature is " << _temperature << std::endl;
  }
};

class WeatherObserver
    : public icc::localbus::IClient<Forecast> {
 public:
  WeatherObserver(std::shared_ptr<icc::IContext> _io_service)
      : icc::Component(_io_service),
        icc::localbus::IClient<Forecast>("WeatherStation") {
    std::cout << "WeatherObserver" << std::endl;
  }

  ~WeatherObserver() {
    std::cout << "~WeatherObserver" << std::endl;
  }
  void onTemperature(const double & _temperature) {
    std::cout << "WeatherObserver::Temperature is " << _temperature << std::endl;
  }

 protected:
  std::shared_ptr<TestObserver> p_test_ = std::make_shared<TestObserver>(this);

  void connected(Forecast*) override {
    std::cout << "connected is called" << std::endl;
    int i = 7;
    call(&Forecast::setIntervalForUpdate, i);
    subscribe(&Forecast::temperature_, &WeatherObserver::onTemperature);
    subscribe(&Forecast::temperature2_, &WeatherObserver::onTemperature);
    subscribe(&Forecast::temperature_, p_test_, &TestObserver::onTemperature);
    subscribe(&Forecast::temperature2_, p_test_, &TestObserver::onTemperature);
    // NOTE(redra): The following line added only for testing purposes
    //  unsubscribe(&Forecast::temperature_, &WeatherObserver::onTemperature);
    //  unsubscribe(&Forecast::temperature2_, &WeatherObserver::onTemperature);
    //  unsubscribe(&Forecast::temperature_, p_test_, &TestObserver::onTemperature);
    //  unsubscribe(&Forecast::temperature2_, p_test_, &TestObserver::onTemperature);
  }

  void disconnected(Forecast*) override {
    std::cout << "disconnected is called" << std::endl;
  }
};

int main() {
  auto defaultContext = icc::ContextBuilder::createContext<icc::ThreadSafeQueueAction>();
  std::shared_ptr<WeatherObserver> observer = std::make_shared<WeatherObserver>(defaultContext);
  std::shared_ptr<WeatherStation> station = std::make_shared<WeatherStation>(defaultContext);
  // Start event loop
  defaultContext->run();
  return 0;
}


text:
package io.vertx.mysqlclient.impl.command;

import io.vertx.core.buffer.Buffer;
import io.vertx.mysqlclient.impl.MySQLCollation;

import java.util.Map;

public class ChangeUserCommand extends AuthenticationCommandBase<Void> {
  public ChangeUserCommand(String username,
                           String password,
                           String database,
                           MySQLCollation collation,
                           Buffer serverRsaPublicKey,
                           Map<String, String> connectionAttributes) {
    super(username, password, database, collation, serverRsaPublicKey, connectionAttributes);
  }
}


text:
package pkg

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"mime/multipart"

	"github.com/wiliamsouza/apollo/db"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

// Package represents GridFS file
type Package struct {
	Filename string   `json:"filename"`
	Metadata Metadata `json:"metadata"`
}

// Metadata represents GridFS file metadata
type Metadata struct {
	Version     float32 `json:"version,omitempty"`
	Description string  `json:"description"`
	Install     string  `json:"install,omitempty"`
	Run         string  `json:"run,omitempty"`
}

// PackageList a list of packages
type PackageList []Package

// NewPackage create a new package
func NewPackage(file, meta multipart.File, filename string) (Package, error) {
	pkg := Package{}
	gfs, err := db.Session.Package().Create(filename)
	_, err = io.Copy(gfs, file)
	data, err := ioutil.ReadAll(meta)
	metadata := Metadata{}
	json.Unmarshal(data, &metadata)
	gfs.SetMeta(metadata)
	err = gfs.Close()
	_ = db.Session.Package().Files.Find(bson.M{"filename": filename}).Select(bson.M{"filename": 1, "metadata.description": 1}).One(&pkg)
	return pkg, err
}

// ListPackages list packages
func ListPackages() (PackageList, error) {
	var packages []Package
	err := db.Session.Package().Files.Find(nil).Select(bson.M{"filename": 1, "metadata.description": 1}).Sort("filename").All(&packages)
	return PackageList(packages), err
}

// DetailPackage detail package
func DetailPackage(filename string) (Package, error) {
	var pkg Package
	err := db.Session.Package().Files.Find(bson.M{"filename": filename}).One(&pkg)
	return pkg, err
}

// GetPackage get a package
func GetPackage(filename string) (*mgo.GridFile, error) {
	file, err := db.Session.Package().Open(filename)
	return file, err
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Jermy, J. Linn. Soc. , Bot. 81(1): 45 (1980)

#### Original name
Aporpium borneense Jülich

### Remarks
null


text:
"""Helpers for defining substrate specs.

Used to allow substrates to easily define the single-player specs within their
configs.
"""

from typing import Mapping, Optional

import dm_env
import immutabledict
import numpy as np

STEP_TYPE = dm_env.specs.BoundedArray(
    shape=(),
    dtype=np.int64,
    minimum=min(dm_env.StepType),
    maximum=max(dm_env.StepType),
    name='step_type',
)
DISCOUNT = dm_env.specs.BoundedArray(
    shape=(), dtype=np.float64, minimum=0, maximum=1, name='discount')
REWARD = dm_env.specs.Array(shape=(), dtype=np.float64, name='reward')
OBSERVATION = immutabledict.immutabledict({
    'READY_TO_SHOOT': dm_env.specs.Array(
        shape=(), dtype=np.float64, name='READY_TO_SHOOT'),
    'RGB': dm_env.specs.Array(shape=(88, 88, 3), dtype=np.uint8, name='RGB'),
    'POSITION': dm_env.specs.Array(shape=(2,), dtype=np.int32, name='POSITION'),
    'ORIENTATION': dm_env.specs.Array(
        shape=(), dtype=np.int32, name='ORIENTATION'),
})
_ACTION = dm_env.specs.DiscreteArray(
    num_values=1, dtype=np.int64, name='action')

def float32(*shape: int, name: Optional[str] = None) -> dm_env.specs.Array:
  """Returns the spec for an np.float32 tensor.

  Args:
    *shape: the shape of the tensor.
    name: optional name for the spec.
  """
  return dm_env.specs.Array(shape=shape, dtype=np.float32, name=name)

def float64(*shape: int, name: Optional[str] = None) -> dm_env.specs.Array:
  """Returns the spec for an np.float64 tensor.

  Args:
    *shape: the shape of the tensor.
    name: optional name for the spec.
  """
  return dm_env.specs.Array(shape=shape, dtype=np.float64, name=name)

def int32(*shape: int, name: Optional[str] = None) -> dm_env.specs.Array:
  """Returns the spec for an np.int32 tensor.

  Args:
    *shape: the shape of the tensor.
    name: optional name for the spec.
  """
  return dm_env.specs.Array(shape=shape, dtype=np.int32, name=name)

def int64(*shape: int, name: Optional[str] = None) -> dm_env.specs.Array:
  """Returns the spec for an np.int32 tensor.

  Args:
    *shape: the shape of the tensor.
    name: optional name for the spec.
  """
  return dm_env.specs.Array(shape=shape, dtype=np.int64, name=name)

def action(num_actions: int) -> dm_env.specs.DiscreteArray:
  """Returns the spec for an action.

  Args:
    num_actions: the number of actions that can be taken.
  """
  return _ACTION.replace(num_values=num_actions)

def rgb(height: int,
        width: int,
        name: Optional[str] = 'RGB') -> dm_env.specs.Array:
  """Returns the spec for an RGB observation.

  Args:
    height: the height of the observation.
    width: the width of the observation.
    name: optional name for the spec.
  """
  return OBSERVATION['RGB'].replace(shape=(height, width, 3), name=name)

def inventory(num_resources: int,
              name: Optional[str] = 'INVENTORY') -> dm_env.specs.Array:
  """Returns the spec for an INVENTORY observation.

  Args:
    num_resources: the number of resource types in the inventory.
    name: optional name for the spec.
  """
  return float64(num_resources, name=name)

def interaction_inventories(
    num_resources: int,
    name: Optional[str] = 'INTERACTION_INVENTORIES') -> dm_env.specs.Array:
  """Returns the spec for an INTERACTION_INVENTORIES observation.

  Args:
    num_resources: the number of resource types in the inventory.
    name: optional name for the spec.
  """
  return float64(2, num_resources, name=name)

def timestep(
    observation_spec: Mapping[str, dm_env.specs.Array]) -> dm_env.TimeStep:
  """Returns the spec for a timestep.

  Args:
    observation_spec: the observation spec. Spec names will be overwritten with
      their key.
  """
  observation_spec = immutabledict.immutabledict({
      name: spec.replace(name=name) for name, spec in observation_spec.items()
  })
  return dm_env.TimeStep(
      step_type=STEP_TYPE,
      discount=DISCOUNT,
      reward=REWARD,
      observation=observation_spec,
  )


text:
package com.puresoltechnologies.ductiledb.columnfamily;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.junit.Test;

import com.puresoltechnologies.ductiledb.columnfamily.CompoundKey;

public class CompoundKeyTest {

    @Test(expected = NullPointerException.class)
    public void testNullKeyParts() {
	CompoundKey.encode((byte[][]) null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEmptyKeyParts() {
	CompoundKey.encode();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testTooManyKeyParts() {
	byte[][] keyParts = new byte[256][];
	for (int i = 0; i < 256; ++i) {
	    keyParts[i] = new byte[] { (byte) i };
	}
	CompoundKey.encode(keyParts);
    }

    @Test
    public void testSingleKeyPart() {
	CompoundKey compoundKey = CompoundKey.create(new byte[] { 42 });
	assertNotNull(compoundKey);
	assertEquals(1, compoundKey.getPartNum());
	byte[] key = compoundKey.getBytes();
	assertNotNull(key);
	assertEquals(6, key.length);
	assertEquals(1, key[0]);
	assertEquals(0, key[1]);
	assertEquals(0, key[2]);
	assertEquals(0, key[3]);
	assertEquals(1, key[4]);
	assertEquals(42, key[5]);
    }

    @Test
    public void testMultiKeyParts() {
	CompoundKey compoundKey = CompoundKey.create(new byte[] { 42 }, new byte[] { 21, 22 },
		new byte[] { 13, 14, 15 });
	assertNotNull(compoundKey);
	assertEquals(3, compoundKey.getPartNum());
	byte[] key = compoundKey.getBytes();
	assertNotNull(key);
	assertEquals(19, key.length);
	assertEquals(3, key[0]);
	assertEquals(0, key[1]);
	assertEquals(0, key[2]);
	assertEquals(0, key[3]);
	assertEquals(1, key[4]);
	assertEquals(42, key[5]);
	assertEquals(0, key[6]);
	assertEquals(0, key[7]);
	assertEquals(0, key[8]);
	assertEquals(2, key[9]);
	assertEquals(21, key[10]);
	assertEquals(22, key[11]);
	assertEquals(0, key[12]);
	assertEquals(0, key[13]);
	assertEquals(0, key[14]);
	assertEquals(3, key[15]);
	assertEquals(13, key[16]);
	assertEquals(14, key[17]);
	assertEquals(15, key[18]);
    }

    @Test
    public void testPartNumEncodingToByte() {
	byte[][] keyParts = new byte[200][];
	for (int i = 0; i < 200; ++i) {
	    keyParts[i] = new byte[] { (byte) i };
	}

	CompoundKey compoundKey = CompoundKey.create(keyParts);
	assertNotNull(compoundKey);
	assertEquals(200, compoundKey.getPartNum());
	byte[] key = compoundKey.getBytes();
	assertNotNull(key);
	assertEquals(1001, key.length);
	assertEquals(200, key[0] & 0xFF);
	for (int i = 0; i < 200; ++i) {
	    assertEquals(0, key[5 * i + 1]);
	    assertEquals(0, key[5 * i + 2]);
	    assertEquals(0, key[5 * i + 3]);
	    assertEquals(1, key[5 * i + 4]);
	    assertEquals(i, key[5 * i + 5] & 0xFF);
	}
    }

    @Test
    public void testDecode() {
	byte[][] keyParts = CompoundKey
		.decode(new byte[] { 3, 0, 0, 0, 1, 42, 0, 0, 0, 2, 12, 13, 0, 0, 0, 3, 1, 2, 3 });
	assertEquals(3, keyParts.length);
	assertEquals(1, keyParts[0].length);
	assertEquals(42, keyParts[0][0]);
	assertEquals(2, keyParts[1].length);
	assertEquals(12, keyParts[1][0]);
	assertEquals(13, keyParts[1][1]);
	assertEquals(3, keyParts[2].length);
	assertEquals(1, keyParts[2][0]);
	assertEquals(2, keyParts[2][1]);
	assertEquals(3, keyParts[2][2]);
    }
}


text:
Crontab generator from JSON
========

This generator allows you store your cron-tasks config in VCS as a simple JSON-file and install it on server after deployment. You can describe task execution time as a human friendly phrase:
* Every 12 minutes
* Every 22th minute of every hour
* Every day at 10:20

Json-config concepts
--------

*Profile* - it's an enviroment, for example you can disable some tasks on test server.

Each profile has variables, which will be replaced in command line. It can be path to your framework console.php file or other cli utility.

*Jobs* - it's your cron commands, described with following properties:

* title - task name
* is_enabled - you can temporaly disable your task
* profiles - on which profiles this job will run
* schedule - human friendly string, describing when job will be executed
* command - shell code, which will be executed

Code sample
--------

```php
try {
    $generator = \Krolikoff\CronGen\Generator::init()->setJson('/path/to/config.json')
        ->generate('YOUR_PROFILE_NAME')->install();
}
catch (\Exception $e) {
    echo $e->getMessage();
}
```

This example config
--------

```json
{
    "profiles": {
        "local": {
            "variables": {
                "PREFIX": "/usr/bin/php /var/www/domain/console.php"
            }
        },
        "www": {
            "variables": {
                "PREFIX": "/usr/bin/php /var/www/vhosts/domain/public/console.php"
            }
        }
    },
    "jobs": [
        {
            "title": "Stat job",
            "is_enabled" : true,
            "profiles": ["local", "www"],
            "schedule": "every 10 minutes",
            "command": "{PREFIX} admin stats calculate"
        },
        {
            "title": "Download job",
            "is_enabled" : true,
            "profiles": ["www"],
            "schedule": "every day at 5:00",
            "command": "{PREFIX} api download stats"
        },
        {
            "title": "Upload job",
            "is_enabled" : false,
            "profiles": ["local"],
            "schedule": "every 20th minute of every hour",
            "command": "{PREFIX} admin upload photos"
        }
    ]
}
```

will produce following crontab file for the profile "www":

```php
#Stat job
*/10 * * * * /usr/bin/php /var/www/vhosts/domain/public/console.php admin stats calculate
#Download job
0 5 * * * * /usr/bin/php /var/www/vhosts/domain/public/console.php api download stats
```


text:
layout: post
title: "Exploring Apache jclouds with Groovy: A Python Developers point of view"
date: 2014-03-05 11:00
comments: true
author: John Yi
published: true
categories:
- jclouds
- sdk
- developer
- groovy
- java
- python

---

One of the most powerful features of Python is the REPL (Run, Evaluate, Print,
and Loop) This allows developers to run their code and get quick feedback.
Developers are able test out new ideas and try out different things without
the cycle of modifiying, compiling, and running the source code.

Another feature of Python's REPL is the introspection capabilities. This allows
developers to easily and dynamically explore libraries.

In the Java world there are a number of options to do this. This post explores
some of those; and how to leverage groovy and jclouds to achieve the same speed
of development.

<!-- more -->

Java developers rely on their Integrated Development Environments (IDEs) to
provide features like object introspection, code completion, on the fly code
analysis, and quick access to help documentation. However most Python
developers are not familiar with the various Java IDEs and would need time to
learn how to use their features.

They also may need to learn the Java language itself for a project. This is
where Groovy makes a lot of sense.

Groovy is a dynamic language like Python but has a Java like language syntax.
It also has seamless integration to existing Java classes and libraries making
it easy to use with existing Java code.

Apache [jclouds](http://jclouds.apache.org/) has become the defacto library of
multicloud infrastructures for Java developers. (The Python equivalent being
[libcloud](https://libcloud.readthedocs.org/en/latest/))

To make the setup easy, I'll specify a very opinionated setup running Ubuntu
12.04 with OpenJDK 7 patch 51. The code samples were created using the Ubuntu
12.04 image from Rackspace - [Ubuntu 12.04 LTS (Precise Pangolin) (PVHVM) (28b21a55-b686-4e8e-be9b-b6df2aaf60b8)]
however the precise64 virtualbox from Vagrant should work as well. Finally
your environment should have access to the internet. So let's set this up:

```
apt-get update
apt-get -y install openjdk-7-jdk zip unzip maven
```

Groovy has a environment manager called gvm that is similiar in concept to the
Ruby environment manager rvm. I've found this to be quite useful:

```
export JAVA_HOME=/etc/alternatives/java
curl -s get.gvmtool.net | bash
```

At this point gvm should be installed but you'll either have to source the gvm-init.sh or
restart the shell as specifed by the message upon gvm installation.
For most folks sourcing gvm-init.sh is easier.

```
source "$HOME/.gvm/bin/gvm-init.sh"
```

You'll now want to install the latest version of Groovy. At the time of this post the latest version is 2.2.1,
however you can run the command below to install the latest version:

```
gvm install groovy
```

Great, so now groovy is installed and we'll want to start diving into the jclouds code.
The easiest thing to start exploring is the
[jclouds-examples](https://github.com/jclouds/jclouds-examples) repo. Because
the examples already give us a lot of scaffolding code we can easily start
exploring without to much typing. So let's first clone the jclouds-example
repo from github.

```
git clone https://github.com/jclouds/jclouds-examples.git
cd jclouds-examples/rackspace
```

Next we'll need to pull down all our dependent libraries. Maven is to a Java
developer what pip is to a Python developer.

```
mvn dependency:copy-dependencies "-DoutputDirectory=./lib"
```

Also because we'll be using the jclouds-examples/rackspace we should go ahead and create class
files from the source.

```
javac -classpath "lib/*:src/main/java/:src/main/resources/" src/main/java/org/jclouds/examples/rackspace/*.java
```

So let's explore something that isn't to trival, creating a cloud server and
then adding some block storage to it.

We'll explore the example CreateVolumeAndAttach.java. So all we have to do at this point
is fire up groovy's REPL with the appropriate classpath set and import this package.

```
groovysh -cp "lib/*:src/main/java/:src/main/resources/"
Groovy Shell (2.2.1, JVM: 1.7.0_51)
Type 'help' or '\h' for help.
---------------------------------------------------------------------------------------------------------------------------
groovy:000> import org.jclouds.examples.rackspace.cloudblockstorage.CreateVolumeAndAttach
===> [import org.jclouds.examples.rackspace.cloudblockstorage.CreateVolumeAndAttach]
```

It helps to be looking
at the source here so point your browser to [CreateVolumeAndAttach.java](https://github.com/jclouds/jclouds-examples/blob/master/rackspace/src/main/java/org/jclouds/examples/rackspace/cloudblockstorage/CreateVolumeAndAttach.java)

Also, you'll need to grab your username and api_key. Instructions on how to do that are here:
[http://jclouds.apache.org/documentation/quickstart/rackspace/](http://jclouds.apache.org/documentation/quickstart/rackspace/)

```
cvs = new CreateVolumeAndAttach("groovy","beaf5678fffeeedddccc")
```

Because we've created an instance of the class CreateVolumeAndAttach, we
can should be able to access the computeService handle. We'll assign a convenient
alias to it. (A little snake_case for the Pythonista in me.)

```
compute_service = cvs.computeService
```

So let's go ahead and create our first cloud server. We'll create the Template
object first. Templates are jclouds way of abstracting the cloud instance
configurations to make it more portable to use with other clouds. Some common
elements that clouds share are things like Images, Hardware, and Location. To
make allowances for different options for booting images
jclouds also defines Options within the same Template object.

Here on the Rackspace cloud we'll use performance1-1 for our flavor and the
image that matches the regex ".*CentOS 6.4.*" So let's try this out. We'll
need to import some packages to bring them into our namespace.

```
import static org.jclouds.examples.rackspace.cloudblockstorage.Constants.*;
import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndId;
zoneAndId = ZoneAndId.fromZoneAndId(ZONE, "performance1-1");
template = compute_service.templateBuilder().locationId(ZONE).osDescriptionMatches(".*CentOS 6.4.*").hardwareId(zoneAndId.slashEncode()).build();
```

Here the constant ZONE was defined by the static import of
org.jclouds.examples.rackspace.cloudblockstorage.Constants.*
however any string defining a valid zone (i.e. "IAD", "ORD", "DFW", "SYD") would work.
Next let's create the cloud server. Because the method createNodesInGroup blocks till
the cloud server is created, let's put the method call createNodesInGroup
in its own thread so that we don't have to wait for it to finish.

```
node_create = Thread.start {
nodes = compute_service.createNodesInGroup("groovy-demo", 1, template);
nodeMetadata = nodes.iterator().next();
publicAddress = nodeMetadata.getPublicAddresses().iterator().next(); }
```

While our server is being created (1 - 2 minutes) we can work on creating our block storage.
As usual we'll need to import a few things.

```
import org.jclouds.openstack.cinder.v1.options.CreateVolumeOptions;
import com.google.common.collect.ImmutableMap;
options = CreateVolumeOptions.Builder.name("groovy-volume").metadata(ImmutableMap.<String, String> of("key1", "value1"));
volume = cvs.volumeApi.create(100, options);
```

Next let's join our thread node_create to our current context to make sure it is finished. This command
will block till node_create completes.

```
node_create.join()
```

So the method compute_service.createNodesInGroup actually returns
a list. For example if we had called it with compute_service.createNodesInGroup('groovy-demo', 5, template) we'd
be creating five servers based of the template. However because we are creating it with just one server
I'll just reference the first item in the list thus it will be nodes[0].getProviderId() in the argument
for attaching the volume. So let's attach the volume.

```
volumeAttachment = cvs.volumeAttachmentApi.attachVolumeToServerAsDevice(volume.getId(), nodes[0].getProviderId(), DEVICE);
```

At this point you should be able to see the volume attached to the server in the cloud control panel.
First we'll create a groovy password generator [from stackoverflow.com](http://stackoverflow.com/questions/8138164/groovy-generate-random-string-from-given-character-set)

Then we'll change the admin password to the secret password that we just generated.

```
generator = { String alphabet, int n ->
  new Random().with {
    (1..n).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
  }
}
set verbosity QUIET
secret_password = generator( (('a'..'z')+('A'..'Z')+('0'..'9')).join(), 12);
set verbosity INFO
cvs.nova.getApi().getServerApiForZone(ZONE).changeAdminPass(nodeMetadata.getProviderId(), secret_password);
```

Now it's time to build the script and run the
commands that will create a filesystem and mount the volume.

```
import org.jclouds.scriptbuilder.ScriptBuilder;
import static org.jclouds.scriptbuilder.domain.Statements.exec;
import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.compute.options.RunScriptOptions;
script = new ScriptBuilder()
script.addStatement(exec("mkfs -t ext4 /dev/xvdd"))
script.addStatement(exec("mount /dev/xvdd /mnt"))
script.render(OsFamily.Unix)
options = RunScriptOptions.Builder.blockOnComplete(true).overrideLoginPassword(secret_password)
response = compute_service.runScriptOnNode(nodes[0].getId(), script, options);
```

Once the command completes you should get a status that looks like this:

```
===> {output=Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
6553600 inodes, 26214400 blocks
1310720 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
800 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
	32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
	4096000, 7962624, 11239424, 20480000, 23887872

Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 29 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.
, error=mke2fs 1.41.12 (17-May-2010)
, exitStatus=0}
```

So there you go. Again the purpose of using Groovy here is to learn jclouds
in a Java context. You can of course explore jclouds with Jython and JRuby but
hopefully this will give the Python/Ruby developer yet another option when
exploring and hacking!


text:
const mongoose = require('mongoose');
const meta = require('../helper/meta');
const handleError = require('../helper/handleError');

const { isDeveloping, MONGODB_URI } = meta;

if (isDeveloping) {
	mongoose
		.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
		.then(() => console.log('Connected to MongoDB Atlas!'))
		.catch(error => {
			handleError(error);
		});
} else {
	const options = {
		useNewUrlParser: true,
		useUnifiedTopology: true,
		server: {
			socketOptions: {
				keepAlive: 300000,
				connectTimeoutMS: 30000,
			},
		},
		replset: {
			socketOptions: {
				keepAlive: 300000,
				connectTimeoutMS: 30000,
			},
		},
	};
	mongoose.connect(process.env.MONGODB_URI, options);
}
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

module.exports = db;


text:
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	QTextCodec *codec = QTextCodec::codecForName("UTF-8");
	QTextCodec::setCodecForTr(codec);
	QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
	QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());

	qRegisterMetaType<cv::Mat>("Mat");
	qRegisterMetaType<cv::Mat>("cv::Mat&");
	qRegisterMetaType<cv::Mat>("cv::Mat*");

	QString qpath(argv[1]);
	std::string file = std::string((const char *)qpath.toLocal8Bit());

	QtTrajectoryAnalysis w;
	//////ÅúÁ¿´¦Àí
	if( argc > 3){
		QStringList files;
		for( int i = 1; i < argc -1; ++i){
			files << QString::fromLocal8Bit(argv[i]);
		}
		w.setBatchInfo(files);
	}
	QString folder = QString::fromLocal8Bit(argv[argc-1]);
	w.setFolder(folder);

	if (!w.loadImage(file)){
		QMessageBox::information(0, QString::fromLocal8Bit("Ìáʾ"),
			QString::fromLocal8Bit("ÇëÕýÈ·´ò¿ª³ÌÐò£¡"));
		a.quit();
		return -1;
	}

	w.show();
	return a.exec();
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Sales Tracker</title>

  <link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Open+Sans:600'>

      <link rel="stylesheet" href="css/menubutton.css">
      <link rel="stylesheet" href="css/changeroute.css">

      <input id="tab-1" type="radio" name="tab" class="sign-in" checked>
      <input id="tab-2" type="radio" name="tab" class="sign-up">

            <input  class= "button" id="calldriver" type="submit" onclick="updatedriver()" value="Driver">
            <input  class= "button" id="changeroute" type="submit" onclick="updateroute()" value="Route">
            <input  class= "button" id="buttonStyle" type="submit" onclick="goback()" value="Back">

          Add/Update Driver

					Driver ID:
					<input id="driver" type="text" class="input">

					Driver Name:
					<input id="start" type="text" class="input">

					Address:
					<textarea id="end" type="text" class="input"></textarea>

					<input type="submit" class="button" onclick="update()" value="Add/Update Driver">

          Add/Update Route

          Driver Name:
          <select class="input" style="height:40px;">
            <option>ST_01</option>
            <option>ST_02</option>
            <option>ST_03</option>
            <option>ST_04</option>
          </select>

          Start Location:
          <select class="input" style="height:40px;">
            <option>Mekkah</option>
            <option>Medina</option>
            <option>Jeddah</option>
            <option>Taif</option>
            <option>Al Baha</option>
          </select>

          End Location:
          <select class="input" style="height:40px;">
            <option>Mekkah</option>
            <option>Medina</option>
            <option>Jeddah</option>
            <option>Taif</option>
            <option>Al Baha</option>
          </select>

          <input type="submit" class="button" onclick="update()" value="Add/Update Route">


text:
Query the list of CITY names from STATION which have vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your result cannot contain duplicates.

Input Format

The STATION table is described as follows:

Station.jpg

where LAT_N is the northern latitude and LONG_W is the western longitude.
https://www.hackerrank.com/challenges/weather-observation-station-8


text:
GridIron
========

Extensible LESS Framework for Custom Grids and Breakpoints


text: Random assortment of Javascript code snippets.


text:
package com.smithkatakkar.hauntingmod;

import com.google.common.base.Predicate;

import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.EntityAIAvoidEntity;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.util.DamageSource;

public class EntityAIScareTheLiving extends EntityAIBase {

    class AvoidPredicate implements Predicate {
        Class avoid;

        public AvoidPredicate(Class class1) {
            this.avoid = class1;
        }

        public boolean apply(Object entity)
        {
            if (entity instanceof EntityGhost && !((EntityGhost)entity).isDead) {
                return avoid.isInstance(((EntityGhost)entity).getDeceasedEntity());
            }

            return false;
        }
    }

    private EntityGhost ghost;

    EntityAIScareTheLiving(EntityGhost ghost) {
        this.ghost = ghost;
    }

    @Override
    public boolean shouldExecute() {
        EntityLiving closestEntity = (EntityLiving)this.ghost.worldObj.findNearestEntityWithinAABB(
            ghost.getDeceasedEntity().getClass(), ghost.getEntityBoundingBox().expand(
                60.0D, 60.0D, 10.0D), ghost);

        if (closestEntity != null) {
            Class avoidClass = ghost.getDeceasedEntity().getClass();
            if (avoidClass.isInstance(closestEntity)) {
                closestEntity.tasks.addTask(20, new EntityAIAvoidEntity<EntityGhost>((EntityCreature) closestEntity,
                    EntityGhost.class, new AvoidPredicate(avoidClass), 60.0F, 1.5D, 2.7D));
            }
        }

        return false;
    }

}


text:
package org.apache.curator.framework.api;

public interface Versionable<T>
{
    /**
     * Use the given version (the default is -1)
     *
     * @param version version to use
     * @return this
     */
    public T     withVersion(int version);
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Groups_Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Groups_Test")]
[assembly: AssemblyCopyright("Copyright ©  2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("23afb0cb-e593-4dd1-9d47-e2076acd72f2")]

// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
#include <aws/glue/model/CreateConnectionResult.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::Glue::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

CreateConnectionResult::CreateConnectionResult()
{
}

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

CreateConnectionResult& CreateConnectionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/backgroundBehindCards"
    android:orientation="vertical"
    android:paddingBottom="@dimen/card_padding">

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:divider="@color/transparent"
        android:dividerHeight="8dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:paddingTop="@dimen/elementMargin"
        tools:listitem="@layout/card_news_item" />

    <include
        android:id="@android:id/empty"
        layout="@layout/card_news_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/elementMargin" />

</LinearLayout>


text:
package org.bouncycastle.pkcs.test;

import java.security.Security;

import junit.extensions.TestSetup;
import junit.framework.Test;

class BCTestSetup
    extends TestSetup
{
    public BCTestSetup(Test test)
    {
        super(test);
    }

    protected void setUp()
    {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    protected void tearDown()
    {
        Security.removeProvider("BC");
    }
}


text:
namespace service {

namespace {

const ::google::protobuf::ServiceDescriptor* EchoService_descriptor_ = NULL;
const ::google::protobuf::ServiceDescriptor* EchoService2_descriptor_ = NULL;

GOOGLE_PROTOBUF_DECLARE_ONCE(protorpc_AssignDescriptors_once_);

void protorpc_AssignDesc_echo_2eproto() {
	protobuf_AddDesc_echo_2eproto();
	auto file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName("echo.proto");
	GOOGLE_CHECK(file != NULL);
	EchoService_descriptor_ = file->service(0);
	EchoService2_descriptor_ = file->service(1);
}
inline void protorpc_AssignDescriptorsOnce() {
	::google::protobuf::GoogleOnceInit(
		&protorpc_AssignDescriptors_once_,
		&protorpc_AssignDesc_echo_2eproto
	);
}

} // namespace

EchoService::~EchoService() {}

const ::google::protobuf::ServiceDescriptor* EchoService::descriptor() {
	protorpc_AssignDescriptorsOnce();
	return EchoService_descriptor_;
}

const ::google::protobuf::ServiceDescriptor* EchoService::GetDescriptor() {
	protorpc_AssignDescriptorsOnce();
	return EchoService_descriptor_;
}

const ::protorpc::Error EchoService::Echo(
	const ::service::EchoRequest* request,
	::service::EchoResponse* reponse
) {
	return ::protorpc::Error("Method EchoService::Echo() not implemented.");
}

const ::protorpc::Error EchoService::EchoTwice(
	const ::service::EchoRequest* request,
	::service::EchoResponse* reponse
) {
	return ::protorpc::Error("Method EchoService::EchoTwice() not implemented.");
}

const ::protorpc::Error EchoService::CallMethod(
	const ::google::protobuf::MethodDescriptor* method,
	const ::google::protobuf::Message* request,
	::google::protobuf::Message* response
) {
	GOOGLE_DCHECK_EQ(method->service(), EchoService_descriptor_);
	switch(method->index()) {
	case 0:
		return Echo(
			::google::protobuf::down_cast<const ::service::EchoRequest*>(request),
			::google::protobuf::down_cast< ::service::EchoResponse*>(response)
		);
	case 1:
		return EchoTwice(
			::google::protobuf::down_cast<const ::service::EchoRequest*>(request),
			::google::protobuf::down_cast< ::service::EchoResponse*>(response)
		);
	default:
		return ::protorpc::Error("Bad method index; this should never happen.");
	}
}

const ::google::protobuf::Message& EchoService::GetRequestPrototype(
	const ::google::protobuf::MethodDescriptor* method
) const {
	GOOGLE_DCHECK_EQ(method->service(), descriptor());
	switch(method->index()) {
	case 0:
		return ::service::EchoRequest::default_instance();
	case 1:
		return ::service::EchoRequest::default_instance();
	default:
		GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
		return *reinterpret_cast< ::google::protobuf::Message*>(NULL);
	}
}

const ::google::protobuf::Message& EchoService::GetResponsePrototype(
	const ::google::protobuf::MethodDescriptor* method
) const {
	GOOGLE_DCHECK_EQ(method->service(), descriptor());
	switch(method->index()) {
	case 0:
		return ::service::EchoResponse::default_instance();
	case 1:
		return ::service::EchoResponse::default_instance();
	default:
		GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
		return *reinterpret_cast< ::google::protobuf::Message*>(NULL);
	}
}

EchoService_Stub::EchoService_Stub(::protorpc::Caller* client)
	: client_(client), owns_client_(false) {}
EchoService_Stub::EchoService_Stub(::protorpc::Caller* client, bool client_ownership)
	: client_(client), owns_client_(client_ownership) {}
EchoService_Stub::~EchoService_Stub() {
	if (owns_client_) delete client_;
}

const ::protorpc::Error EchoService_Stub::Echo(
	const ::service::EchoRequest* request,
	::service::EchoResponse* response
) {
	return client_->CallMethod(descriptor()->method(0), request, response);
}

const ::protorpc::Error EchoService_Stub::EchoTwice(
	const ::service::EchoRequest* request,
	::service::EchoResponse* response
) {
	return client_->CallMethod(descriptor()->method(1), request, response);
}

EchoService2::~EchoService2() {}

const ::google::protobuf::ServiceDescriptor* EchoService2::descriptor() {
	protorpc_AssignDescriptorsOnce();
	return EchoService2_descriptor_;
}

const ::google::protobuf::ServiceDescriptor* EchoService2::GetDescriptor() {
	protorpc_AssignDescriptorsOnce();
	return EchoService2_descriptor_;
}

const ::protorpc::Error EchoService2::Echo(
	const ::service::EchoRequest* request,
	::service::EchoResponse* reponse
) {
	return ::protorpc::Error("Method EchoService2::Echo() not implemented.");
}

const ::protorpc::Error EchoService2::EchoTwice(
	const ::service::EchoRequest* request,
	::service::EchoResponse* reponse
) {
	return ::protorpc::Error("Method EchoService2::EchoTwice() not implemented.");
}

const ::protorpc::Error EchoService2::Foo(
	const ::service::Message* request,
	::service::Message* reponse
) {
	return ::protorpc::Error("Method EchoService2::Foo() not implemented.");
}

const ::protorpc::Error EchoService2::CallMethod(
	const ::google::protobuf::MethodDescriptor* method,
	const ::google::protobuf::Message* request,
	::google::protobuf::Message* response
) {
	GOOGLE_DCHECK_EQ(method->service(), EchoService2_descriptor_);
	switch(method->index()) {
	case 0:
		return Echo(
			::google::protobuf::down_cast<const ::service::EchoRequest*>(request),
			::google::protobuf::down_cast< ::service::EchoResponse*>(response)
		);
	case 1:
		return EchoTwice(
			::google::protobuf::down_cast<const ::service::EchoRequest*>(request),
			::google::protobuf::down_cast< ::service::EchoResponse*>(response)
		);
	case 2:
		return Foo(
			::google::protobuf::down_cast<const ::service::Message*>(request),
			::google::protobuf::down_cast< ::service::Message*>(response)
		);
	default:
		return ::protorpc::Error("Bad method index; this should never happen.");
	}
}

const ::google::protobuf::Message& EchoService2::GetRequestPrototype(
	const ::google::protobuf::MethodDescriptor* method
) const {
	GOOGLE_DCHECK_EQ(method->service(), descriptor());
	switch(method->index()) {
	case 0:
		return ::service::EchoRequest::default_instance();
	case 1:
		return ::service::EchoRequest::default_instance();
	case 2:
		return ::service::Message::default_instance();
	default:
		GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
		return *reinterpret_cast< ::google::protobuf::Message*>(NULL);
	}
}

const ::google::protobuf::Message& EchoService2::GetResponsePrototype(
	const ::google::protobuf::MethodDescriptor* method
) const {
	GOOGLE_DCHECK_EQ(method->service(), descriptor());
	switch(method->index()) {
	case 0:
		return ::service::EchoResponse::default_instance();
	case 1:
		return ::service::EchoResponse::default_instance();
	case 2:
		return ::service::Message::default_instance();
	default:
		GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
		return *reinterpret_cast< ::google::protobuf::Message*>(NULL);
	}
}

EchoService2_Stub::EchoService2_Stub(::protorpc::Caller* client)
	: client_(client), owns_client_(false) {}
EchoService2_Stub::EchoService2_Stub(::protorpc::Caller* client, bool client_ownership)
	: client_(client), owns_client_(client_ownership) {}
EchoService2_Stub::~EchoService2_Stub() {
	if (owns_client_) delete client_;
}

const ::protorpc::Error EchoService2_Stub::Echo(
	const ::service::EchoRequest* request,
	::service::EchoResponse* response
) {
	return client_->CallMethod(descriptor()->method(0), request, response);
}

const ::protorpc::Error EchoService2_Stub::EchoTwice(
	const ::service::EchoRequest* request,
	::service::EchoResponse* response
) {
	return client_->CallMethod(descriptor()->method(1), request, response);
}

const ::protorpc::Error EchoService2_Stub::Foo(
	const ::service::Message* request,
	::service::Message* response
) {
	return client_->CallMethod(descriptor()->method(2), request, response);
}

}  // namespace service


text:
package v1

import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Network holds cluster-wide information about Network.  The canonical name is `cluster`
// TODO this object is an example of a possible grouping and is subject to change or removal
type Network struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// spec holds user settable values for configuration.
	// +required
	Spec NetworkSpec `json:"spec"`
	// status holds observed values from the cluster. They may not be overridden.
	// +optional
	Status NetworkStatus `json:"status"`
}

// NetworkSpec is the desired network configuration.
// As a general rule, this SHOULD NOT be read directly. Instead, you should
// consume the NetworkStatus, as it indicates the currently deployed configuration.
// Currently, changing ClusterNetwork, ServiceNetwork, or NetworkType after
// installation is not supported.
type NetworkSpec struct {
	// IP address pool to use for pod IPs.
	ClusterNetwork []ClusterNetworkEntry `json:"clusterNetwork"`

	// IP address pool for services.
	// Currently, we only support a single entry here.
	ServiceNetwork []string `json:"serviceNetwork"`

	// NetworkType is the plugin that is to be deployed (e.g. OpenShiftSDN).
	// This should match a value that the cluster-network-operator understands,
	// or else no networking will be installed.
	// Currently supported values are:
	// - OpenShiftSDN
	NetworkType string `json:"networkType"`

	// externalIP defines configuration for controllers that
	// affect Service.ExternalIP
	// +optional
	ExternalIP *ExternalIPConfig `json:"externalIP,omitempty"`
}

// NetworkStatus is the current network configuration.
type NetworkStatus struct {
	// IP address pool to use for pod IPs.
	ClusterNetwork []ClusterNetworkEntry `json:"clusterNetwork,omitempty"`

	// IP address pool for services.
	// Currently, we only support a single entry here.
	ServiceNetwork []string `json:"serviceNetwork,omitempty"`

	// NetworkType is the plugin that is deployed (e.g. OpenShiftSDN).
	NetworkType string `json:"networkType,omitempty"`

	// ClusterNetworkMTU is the MTU for inter-pod networking.
	ClusterNetworkMTU int `json:"clusterNetworkMTU,omitempty"`
}

// ClusterNetworkEntry is a contiguous block of IP addresses from which pod IPs
// are allocated.
type ClusterNetworkEntry struct {
	// The complete block for pod IPs.
	CIDR string `json:"cidr"`

	// The size (prefix) of block to allocate to each node.
	HostPrefix uint32 `json:"hostPrefix"`
}

// ExternalIPConfig specifies some IP blocks relevant for the ExternalIP field
// of a Service resource.
type ExternalIPConfig struct {
	// policy is a set of restrictions applied to the ExternalIP field.
	// If nil, any value is allowed for an ExternalIP. If the empty/zero
	// policy is supplied, then ExternalIP is not allowed to be set.
	// +optional
	Policy *ExternalIPPolicy `json:"policy,omitempty"`

	// autoAssignCIDRs is a list of CIDRs from which to automatically assign
	// Service.ExternalIP. These are assigned when the service is of type
	// LoadBalancer. In general, this is only useful for bare-metal clusters.
	// In Openshift 3.x, this was misleadingly called "IngressIPs".
	// Automatically assigned External IPs are not affected by any
	// ExternalIPPolicy rules.
	// Currently, only one entry may be provided.
	// +optional
	AutoAssignCIDRs []string `json:"autoAssignCIDRs,omitempty"`
}

// ExternalIPPolicy configures exactly which IPs are allowed for the ExternalIP
// field in a Service. If the zero struct is supplied, then none are permitted.
// The policy controller always allows automatically assigned external IPs.
type ExternalIPPolicy struct {
	// allowedCIDRs is the list of allowed CIDRs.
	AllowedCIDRs []string `json:"allowedCIDRs,omitempty"`

	// rejectedCIDRs is the list of disallowed CIDRs. These take precedence
	// over allowedCIDRs.
	// +optional
	RejectedCIDRs []string `json:"rejectedCIDRs,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type NetworkList struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	metav1.ListMeta `json:"metadata"`
	Items           []Network `json:"items"`
}


text:
class AddFieldTextToDocument < ActiveRecord::Migration[4.2]
  def change
    add_column :documents, :text, :text
  end
end