text:
package com.newsblur.util;

import android.content.ContentValues;
import android.database.Cursor;

import java.io.Serializable;

import com.newsblur.activity.NbActivity;
import com.newsblur.database.BlurDatabaseHelper;
import com.newsblur.database.DatabaseConstants;
import com.newsblur.domain.Classifier;
import com.newsblur.network.domain.CommentResponse;
import com.newsblur.network.domain.NewsBlurResponse;
import com.newsblur.network.domain.StoriesResponse;
import com.newsblur.network.APIManager;
import com.newsblur.service.NBSyncService;

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

@SuppressWarnings("serial")
public class ReadingAction implements Serializable {

    private static final long serialVersionUID = 0L;

    private enum ActionType {
        MARK_READ,
        MARK_UNREAD,
        SAVE,
        UNSAVE,
        SHARE,
        UNSHARE,
        REPLY,
        EDIT_REPLY,
        DELETE_REPLY,
        LIKE_COMMENT,
        UNLIKE_COMMENT,
        MUTE_FEEDS,
        UNMUTE_FEEDS,
        SET_NOTIFY,
        INSTA_FETCH,
        UPDATE_INTEL
    };

    private final long time;
    private final int tried;
    private ActionType type;
    private String storyHash;
    private FeedSet feedSet;
    private Long olderThan;
    private Long newerThan;
    private String storyId;
    private String feedId;
    private String sourceUserId;
    private String commentReplyText; // used for both comments and replies
    private String commentUserId;
    private String replyId;
    private String notifyFilter;
    private List<String> notifyTypes;
    private Classifier classifier;

    // For mute/unmute the API call is always the active feed IDs.
    // We need the feed Ids being modified for the local call.
    private Set<String> activeFeedIds;
    private Set<String> modifiedFeedIds;

    private ReadingAction() {
        // note: private - must use helpers
        this(System.currentTimeMillis(), 0);
    }

    private ReadingAction(long time, int tried) {
        // note: private - must use helpers
        this.time = time;
        this.tried = tried;
    }

    public int getTried() {
        return tried;
    }

    public static ReadingAction markStoryRead(String hash) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.MARK_READ;
        ra.storyHash = hash;
        return ra;
    }

    public static ReadingAction markStoryUnread(String hash) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.MARK_UNREAD;
        ra.storyHash = hash;
        return ra;
    }

    public static ReadingAction saveStory(String hash) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.SAVE;
        ra.storyHash = hash;
        return ra;
    }

    public static ReadingAction unsaveStory(String hash) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.UNSAVE;
        ra.storyHash = hash;
        return ra;
    }

    public static ReadingAction markFeedRead(FeedSet fs, Long olderThan, Long newerThan) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.MARK_READ;
        ra.feedSet = fs;
        ra.olderThan = olderThan;
        ra.newerThan = newerThan;
        return ra;
    }

    public static ReadingAction shareStory(String hash, String storyId, String feedId, String sourceUserId, String commentReplyText) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.SHARE;
        ra.storyHash = hash;
        ra.storyId = storyId;
        ra.feedId = feedId;
        ra.sourceUserId = sourceUserId;
        ra.commentReplyText = commentReplyText;
        return ra;
    }

    public static ReadingAction unshareStory(String hash, String storyId, String feedId) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.UNSHARE;
        ra.storyHash = hash;
        ra.storyId = storyId;
        ra.feedId = feedId;
        return ra;
    }

    public static ReadingAction likeComment(String storyId, String commentUserId, String feedId) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.LIKE_COMMENT;
        ra.storyId = storyId;
        ra.commentUserId = commentUserId;
        ra.feedId = feedId;
        return ra;
    }

    public static ReadingAction unlikeComment(String storyId, String commentUserId, String feedId) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.UNLIKE_COMMENT;
        ra.storyId = storyId;
        ra.commentUserId = commentUserId;
        ra.feedId = feedId;
        return ra;
    }

    public static ReadingAction replyToComment(String storyId, String feedId, String commentUserId, String commentReplyText) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.REPLY;
        ra.storyId = storyId;
        ra.commentUserId = commentUserId;
        ra.feedId = feedId;
        ra.commentReplyText = commentReplyText;
        return ra;
    }

    public static ReadingAction updateReply(String storyId, String feedId, String commentUserId, String replyId, String commentReplyText) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.EDIT_REPLY;
        ra.storyId = storyId;
        ra.commentUserId = commentUserId;
        ra.feedId = feedId;
        ra.commentReplyText = commentReplyText;
        ra.replyId = replyId;
        return ra;
    }

    public static ReadingAction deleteReply(String storyId, String feedId, String commentUserId, String replyId) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.DELETE_REPLY;
        ra.storyId = storyId;
        ra.commentUserId = commentUserId;
        ra.feedId = feedId;
        ra.replyId = replyId;
        return ra;
    }

    public static ReadingAction muteFeeds(Set<String> activeFeedIds, Set<String> modifiedFeedIds) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.MUTE_FEEDS;
        ra.activeFeedIds = activeFeedIds;
        ra.modifiedFeedIds = modifiedFeedIds;
        return ra;
    }

    public static ReadingAction unmuteFeeds(Set<String> activeFeedIds, Set<String> modifiedFeedIds) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.UNMUTE_FEEDS;
        ra.activeFeedIds = activeFeedIds;
        ra.modifiedFeedIds = modifiedFeedIds;
        return ra;
    }

    public static ReadingAction setNotify(String feedId, List<String> notifyTypes, String notifyFilter) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.SET_NOTIFY;
        ra.feedId = feedId;
        if (notifyTypes == null) {
            ra.notifyTypes = new ArrayList<String>();
        } else {
            ra.notifyTypes = notifyTypes;
        }
        ra.notifyFilter = notifyFilter;
        return ra;
    }

    public static ReadingAction instaFetch(String feedId) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.INSTA_FETCH;
        ra.feedId = feedId;
        return ra;
    }

    public static ReadingAction updateIntel(String feedId, Classifier classifier) {
        ReadingAction ra = new ReadingAction();
        ra.type = ActionType.UPDATE_INTEL;
        ra.feedId = feedId;
        ra.classifier = classifier;
        return ra;
    }

	public ContentValues toContentValues() {
		ContentValues values = new ContentValues();
        values.put(DatabaseConstants.ACTION_TIME, time);
        values.put(DatabaseConstants.ACTION_TRIED, tried);
        values.put(DatabaseConstants.ACTION_TYPE, type.toString());
        switch (type) {

            case MARK_READ:
                if (storyHash != null) {
                    values.put(DatabaseConstants.ACTION_STORY_HASH, storyHash);
                } else if (feedSet != null) {
                    values.put(DatabaseConstants.ACTION_FEED_ID, feedSet.toCompactSerial());
                    if (olderThan != null) values.put(DatabaseConstants.ACTION_INCLUDE_OLDER, olderThan);
                    if (newerThan != null) values.put(DatabaseConstants.ACTION_INCLUDE_NEWER, newerThan);
                }
                break;

            case MARK_UNREAD:
                if (storyHash != null) {
                    values.put(DatabaseConstants.ACTION_STORY_HASH, storyHash);
                }
                break;

            case SAVE:
                values.put(DatabaseConstants.ACTION_STORY_HASH, storyHash);
                break;

            case UNSAVE:
                values.put(DatabaseConstants.ACTION_STORY_HASH, storyHash);
                break;

            case SHARE:
                values.put(DatabaseConstants.ACTION_STORY_HASH, storyHash);
                values.put(DatabaseConstants.ACTION_STORY_ID, storyId);
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                values.put(DatabaseConstants.ACTION_SOURCE_USER_ID, sourceUserId);
                values.put(DatabaseConstants.ACTION_COMMENT_TEXT, commentReplyText);
                break;

            case UNSHARE:
                values.put(DatabaseConstants.ACTION_STORY_HASH, storyHash);
                values.put(DatabaseConstants.ACTION_STORY_ID, storyId);
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                break;

            case LIKE_COMMENT:
                values.put(DatabaseConstants.ACTION_STORY_ID, storyId);
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                values.put(DatabaseConstants.ACTION_COMMENT_ID, commentUserId);
                break;

            case UNLIKE_COMMENT:
                values.put(DatabaseConstants.ACTION_STORY_ID, storyId);
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                values.put(DatabaseConstants.ACTION_COMMENT_ID, commentUserId);
                break;

            case REPLY:
                values.put(DatabaseConstants.ACTION_STORY_ID, storyId);
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                values.put(DatabaseConstants.ACTION_COMMENT_ID, commentUserId);
                values.put(DatabaseConstants.ACTION_COMMENT_TEXT, commentReplyText);
                break;

            case EDIT_REPLY:
                values.put(DatabaseConstants.ACTION_STORY_ID, storyId);
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                values.put(DatabaseConstants.ACTION_COMMENT_ID, commentUserId);
                values.put(DatabaseConstants.ACTION_COMMENT_TEXT, commentReplyText);
                values.put(DatabaseConstants.ACTION_REPLY_ID, replyId);
                break;

            case DELETE_REPLY:
                values.put(DatabaseConstants.ACTION_STORY_ID, storyId);
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                values.put(DatabaseConstants.ACTION_COMMENT_ID, commentUserId);
                values.put(DatabaseConstants.ACTION_REPLY_ID, replyId);
                break;

            case MUTE_FEEDS:
                values.put(DatabaseConstants.ACTION_FEED_ID, DatabaseConstants.JsonHelper.toJson(activeFeedIds));
                values.put(DatabaseConstants.ACTION_MODIFIED_FEED_IDS, DatabaseConstants.JsonHelper.toJson(modifiedFeedIds));
                break;

            case UNMUTE_FEEDS:
                values.put(DatabaseConstants.ACTION_FEED_ID, DatabaseConstants.JsonHelper.toJson(activeFeedIds));
                values.put(DatabaseConstants.ACTION_MODIFIED_FEED_IDS, DatabaseConstants.JsonHelper.toJson(modifiedFeedIds));
                break;

            case SET_NOTIFY:
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                values.put(DatabaseConstants.ACTION_NOTIFY_FILTER, notifyFilter);
                values.put(DatabaseConstants.ACTION_NOTIFY_TYPES, DatabaseConstants.JsonHelper.toJson(notifyTypes));
                break;

            case INSTA_FETCH:
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                break;

            case UPDATE_INTEL:
                values.put(DatabaseConstants.ACTION_FEED_ID, feedId);
                values.put(DatabaseConstants.ACTION_CLASSIFIER, DatabaseConstants.JsonHelper.toJson(classifier));
                break;

            default:
                throw new IllegalStateException("cannot serialise uknown type of action.");

        }

		return values;
	}

	public static ReadingAction fromCursor(Cursor c) {
        long time = c.getLong(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_TIME));
        int tried = c.getInt(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_TRIED));
		ReadingAction ra = new ReadingAction(time, tried);
        ra.type = ActionType.valueOf(c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_TYPE)));
        if (ra.type == ActionType.MARK_READ) {
            String hash = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_HASH));
            String feedIds = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            Long includeOlder = DatabaseConstants.nullIfZero(c.getLong(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_INCLUDE_OLDER)));
            Long includeNewer = DatabaseConstants.nullIfZero(c.getLong(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_INCLUDE_NEWER)));
            if (hash != null) {
                ra.storyHash = hash;
            } else if (feedIds != null) {
                ra.feedSet = FeedSet.fromCompactSerial(feedIds);
                ra.olderThan = includeOlder;
                ra.newerThan = includeNewer;
            } else {
                throw new IllegalStateException("cannot deserialise uknown type of action.");
            }
        } else if (ra.type == ActionType.MARK_UNREAD) {
            ra.storyHash = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_HASH));
        } else if (ra.type == ActionType.SAVE) {
            ra.storyHash = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_HASH));
        } else if (ra.type == ActionType.UNSAVE) {
            ra.storyHash = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_HASH));
        } else if (ra.type == ActionType.SHARE) {
            ra.storyHash = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_HASH));
            ra.storyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_ID));
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            ra.sourceUserId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_SOURCE_USER_ID));
            ra.commentReplyText = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_COMMENT_TEXT));
        } else if (ra.type == ActionType.UNSHARE) {
            ra.storyHash = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_HASH));
            ra.storyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_ID));
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
        } else if (ra.type == ActionType.LIKE_COMMENT) {
            ra.storyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_ID));
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            ra.commentUserId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_COMMENT_ID));
        } else if (ra.type == ActionType.UNLIKE_COMMENT) {
            ra.storyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_ID));
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            ra.commentUserId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_COMMENT_ID));
        } else if (ra.type == ActionType.REPLY) {
            ra.storyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_ID));
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            ra.commentUserId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_COMMENT_ID));
            ra.commentReplyText = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_COMMENT_TEXT));
        } else if (ra.type == ActionType.EDIT_REPLY) {
            ra.storyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_ID));
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            ra.commentUserId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_COMMENT_ID));
            ra.commentReplyText = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_COMMENT_TEXT));
            ra.replyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_REPLY_ID));
        } else if (ra.type == ActionType.DELETE_REPLY) {
            ra.storyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_STORY_ID));
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            ra.commentUserId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_COMMENT_ID));
            ra.replyId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_REPLY_ID));
        } else if (ra.type == ActionType.MUTE_FEEDS) {
            ra.activeFeedIds = DatabaseConstants.JsonHelper.fromJson(c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID)), Set.class);
            ra.modifiedFeedIds = DatabaseConstants.JsonHelper.fromJson(c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_MODIFIED_FEED_IDS)), Set.class);
        } else if (ra.type == ActionType.UNMUTE_FEEDS) {
            ra.activeFeedIds = DatabaseConstants.JsonHelper.fromJson(c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID)), Set.class);
            ra.modifiedFeedIds = DatabaseConstants.JsonHelper.fromJson(c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_MODIFIED_FEED_IDS)), Set.class);
        } else if (ra.type == ActionType.SET_NOTIFY) {
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            ra.notifyFilter = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_NOTIFY_FILTER));
            ra.notifyTypes = DatabaseConstants.JsonHelper.fromJson(c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_NOTIFY_TYPES)), List.class);
        } else if (ra.type == ActionType.INSTA_FETCH) {
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
        } else if (ra.type == ActionType.UPDATE_INTEL) {
            ra.feedId = c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_FEED_ID));
            ra.classifier = DatabaseConstants.JsonHelper.fromJson(c.getString(c.getColumnIndexOrThrow(DatabaseConstants.ACTION_CLASSIFIER)), Classifier.class);
        } else {
            throw new IllegalStateException("cannot deserialise uknown type of action.");
        }
		return ra;
	}

    /**
     * Execute this action remotely via the API.
     */
    public NewsBlurResponse doRemote(APIManager apiManager, BlurDatabaseHelper dbHelper) {
        // generic response to return
        NewsBlurResponse result = null;
        // optional specific responses that are locally actionable
        StoriesResponse storiesResponse = null;
        CommentResponse commentResponse = null;
        int impact = 0;
        switch (type) {

            case MARK_READ:
                if (storyHash != null) {
                    result = apiManager.markStoryAsRead(storyHash);
                } else if (feedSet != null) {
                    result = apiManager.markFeedsAsRead(feedSet, olderThan, newerThan);
                }
                break;

            case MARK_UNREAD:
                result = apiManager.markStoryHashUnread(storyHash);
                break;

            case SAVE:
                result = apiManager.markStoryAsStarred(storyHash);
                break;

            case UNSAVE:
                result = apiManager.markStoryAsUnstarred(storyHash);
                break;

            case SHARE:
                storiesResponse = apiManager.shareStory(storyId, feedId, commentReplyText, sourceUserId);
                break;

            case UNSHARE:
                storiesResponse = apiManager.unshareStory(storyId, feedId);
                break;

            case LIKE_COMMENT:
                result = apiManager.favouriteComment(storyId, commentUserId, feedId);
                break;

            case UNLIKE_COMMENT:
                result = apiManager.unFavouriteComment(storyId, commentUserId, feedId);
                break;

            case REPLY:
                commentResponse = apiManager.replyToComment(storyId, feedId, commentUserId, commentReplyText);
                break;

            case EDIT_REPLY:
                 commentResponse = apiManager.editReply(storyId, feedId, commentUserId, replyId, commentReplyText);
                break;

            case DELETE_REPLY:
                commentResponse = apiManager.deleteReply(storyId, feedId, commentUserId, replyId);
                break;

            case MUTE_FEEDS:
            case UNMUTE_FEEDS:
                result = apiManager.saveFeedChooser(activeFeedIds);
                break;

            case SET_NOTIFY:
                result = apiManager.updateFeedNotifications(feedId, notifyTypes, notifyFilter);
                break;

            case INSTA_FETCH:
                result = apiManager.instaFetch(feedId);
                // also trigger a recount, which will unflag the feed as pending
                NBSyncService.addRecountCandidates(FeedSet.singleFeed(feedId));
                NBSyncService.flushRecounts();
                break;

            case UPDATE_INTEL:
                result = apiManager.updateFeedIntel(feedId, classifier);
                break;

            default:
                throw new IllegalStateException("cannot execute uknown type of action.");

        }

        if (storiesResponse != null) {
            result = storiesResponse;
            if (storiesResponse.story != null) {
                dbHelper.updateStory(storiesResponse, true);
            } else {
                com.newsblur.util.Log.w(this, "failed to refresh story data after action");
            }
            impact |= NbActivity.UPDATE_SOCIAL;
        }
        if (commentResponse != null) {
            result = commentResponse;
            if (commentResponse.comment != null) {
                dbHelper.updateComment(commentResponse, storyId);
            } else {
                com.newsblur.util.Log.w(this, "failed to refresh comment data after action");
            }
            impact |= NbActivity.UPDATE_SOCIAL;
        }

        NbActivity.updateAllActivities(impact);
        return result;
    }

    public int doLocal(BlurDatabaseHelper dbHelper) {
        return doLocal(dbHelper, false);
    }

    /**
     * Excecute this action on the local DB. These *must* be idempotent.
     *
     * @param isFollowup flag that this is a double-check invocation and is noncritical
     *
     * @return the union of update impact flags that resulted from this action.
     */
    public int doLocal(BlurDatabaseHelper dbHelper, boolean isFollowup) {
        int impact = 0;
        switch (type) {

            case MARK_READ:
                if (storyHash != null) {
                    dbHelper.setStoryReadState(storyHash, true);
                } else if (feedSet != null) {
                    dbHelper.markStoriesRead(feedSet, olderThan, newerThan);
                    dbHelper.updateLocalFeedCounts(feedSet);
                }
                impact |= NbActivity.UPDATE_METADATA;
                impact |= NbActivity.UPDATE_STORY;
                break;

            case MARK_UNREAD:
                dbHelper.setStoryReadState(storyHash, false);
                impact |= NbActivity.UPDATE_METADATA;
                break;

            case SAVE:
                dbHelper.setStoryStarred(storyHash, true);
                impact |= NbActivity.UPDATE_METADATA;
                break;

            case UNSAVE:
                dbHelper.setStoryStarred(storyHash, false);
                impact |= NbActivity.UPDATE_METADATA;
                break;

            case SHARE:
                if (isFollowup) break; // shares are only placeholders
                dbHelper.setStoryShared(storyHash, true);
                dbHelper.insertCommentPlaceholder(storyId, feedId, commentReplyText);
                impact |= NbActivity.UPDATE_SOCIAL;
                impact |= NbActivity.UPDATE_STORY;
                break;

            case UNSHARE:
                dbHelper.setStoryShared(storyHash, false);
                dbHelper.clearSelfComments(storyId);
                impact |= NbActivity.UPDATE_SOCIAL;
                impact |= NbActivity.UPDATE_STORY;
                break;

            case LIKE_COMMENT:
                dbHelper.setCommentLiked(storyId, commentUserId, feedId, true);
                impact |= NbActivity.UPDATE_SOCIAL;
                break;

            case UNLIKE_COMMENT:
                dbHelper.setCommentLiked(storyId, commentUserId, feedId, false);
                impact |= NbActivity.UPDATE_SOCIAL;
                break;

            case REPLY:
                if (isFollowup) break; // replies are only placeholders
                dbHelper.insertReplyPlaceholder(storyId, feedId, commentUserId, commentReplyText);
                break;

            case EDIT_REPLY:
                dbHelper.editReply(replyId, commentReplyText);
                impact |= NbActivity.UPDATE_SOCIAL;
                break;

            case DELETE_REPLY:
                dbHelper.deleteReply(replyId);
                impact |= NbActivity.UPDATE_SOCIAL;
                break;

            case MUTE_FEEDS:
            case UNMUTE_FEEDS:
                dbHelper.setFeedsActive(modifiedFeedIds, type == ActionType.UNMUTE_FEEDS);
                impact |= NbActivity.UPDATE_METADATA;
                break;

            case SET_NOTIFY:
                impact |= NbActivity.UPDATE_METADATA;
                break;

            case INSTA_FETCH:
                if (isFollowup) break; // non-idempotent and purely graphical
                dbHelper.setFeedFetchPending(feedId);
                break;

            default:
                // not all actions have these, which is fine
        }
        return impact;
    }

}


text:
package edu.mit.ll.nics.nicsdao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.mit.ll.dao.QueryModel;
import edu.mit.ll.jdbc.JoinRowCallbackHandler;
import edu.mit.ll.jdbc.JoinRowMapper;
import edu.mit.ll.nics.common.entity.IncidentType;
import edu.mit.ll.nics.common.entity.SystemRole;
import edu.mit.ll.nics.common.constants.SADisplayConstants;
import edu.mit.ll.nics.nicsdao.GenericDAO;
import edu.mit.ll.nics.nicsdao.QueryManager;
import edu.mit.ll.nics.nicsdao.SystemRoleDAO;
import edu.mit.ll.nics.nicsdao.mappers.IncidentTypeRowMapper;
import edu.mit.ll.nics.nicsdao.mappers.SystemRoleRowMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class SystemRoleDAOImpl extends GenericDAO implements SystemRoleDAO {

    private Logger log;

    private NamedParameterJdbcTemplate template;

    @Override
    public void initialize() {
    	log = LoggerFactory.getLogger(SystemRoleDAOImpl.class);
        this.template = new NamedParameterJdbcTemplate(datasource);
    }

    /** getSystemRoleFeatures
     * @param int systemroleid
   	 * @return String - return a list of comma delimited features for this role
   	 */
     public String getSystemRoleFeatures(int systemroleid, int workspaceid){
		String features = "";
		try{
			QueryModel queryModel = QueryManager.createQuery(SADisplayConstants.SYSTEM_ROLE_WORKSPACE_TABLE)
						.selectFromTableWhere(SADisplayConstants.FEATURES)
						.equals(SADisplayConstants.SYSTEM_ROLE_ID)
						.and().equals(SADisplayConstants.WORKSPACE_ID);

			features = template.queryForObject(queryModel.toString(),
	        				new MapSqlParameterSource(SADisplayConstants.SYSTEM_ROLE_ID, systemroleid)
							.addValue(SADisplayConstants.WORKSPACE_ID, workspaceid), String.class);

	    }catch(Exception e){
        	log.info("No role was found with systemroleid #0", systemroleid);
        }

		return features;
	}

	 /** getUserMessageTypes
	  * @param int roleid
	  * @return String - return a list of message types that this role has permission to send
	  */
	  public List<String> getSystemRoleMessageTypes(int roleid){
		QueryModel queryModel = QueryManager.createQuery(SADisplayConstants.MESSAGE_PERMISSIONS_TABLE)
					.selectFromTableWhere(SADisplayConstants.MESSAGE_TYPE).equals(SADisplayConstants.SYSTEM_ROLE_ID);

		Map<String, Object> params = new HashMap<String, Object>();
        params.put(SADisplayConstants.SYSTEM_ROLE_ID, roleid);

        return this.template.queryForList(queryModel.toString(), params, String.class);
	}

     public int getSystemRoleId(String rolename){
    	 QueryModel queryModel = QueryManager.createQuery(SADisplayConstants.SYSTEM_ROLE_TABLE)
    			 .selectFromTableWhere(SADisplayConstants.SYSTEM_ROLE_ID)
    			 .equals(SADisplayConstants.SYSTEM_ROLE_NAME);

    	 try{
	    	 return this.template.queryForInt(queryModel.toString(),
	    			 new MapSqlParameterSource(SADisplayConstants.SYSTEM_ROLE_NAME, rolename));
    	 }catch(Exception e){
    		 log.info("Could not find systemrole id for role name #0", rolename);
    	 }
    	 return -1;
     }

	  /** getHandlerWith
	   *  @param mappers - optional additional mappers
	   *  @return JoinRowCallbackHandler<SystemRole>
	   */
	   @SuppressWarnings({ "unchecked", "rawtypes" })
	private JoinRowCallbackHandler<SystemRole> getHandlerWith(JoinRowMapper... mappers) {
		   return new JoinRowCallbackHandler(new SystemRoleRowMapper(), mappers);
	   }
}

redpajama_set_name: RedPajamaGithub


text: my website for music activities


text:
<?php echo $this->session->flashdata('msg'); ?>

<?php echo $menu; ?>

Add Patient

Add Patient Form

	<?php echo form_open("operator/addpatient");?>

			Enter Name:
			<input class="form-control" type="text" name="name" value="<?php echo set_value('name'); ?>"/>
				<?php echo form_error('name'); ?>

			Enter Email:
			<input class="form-control" type="text" name="email" value="<?php echo set_value('email'); ?>"/>
				<?php echo form_error('email'); ?>

			Enter Address:
			<input class="form-control" type="text" name="address" value="<?php echo set_value('address'); ?>"/>
				<?php echo form_error('address'); ?>

			Enter Phone No.:
			<input class="form-control" type="text" name="phoneno" value="<?php echo set_value('phoneno'); ?>"/>
				<?php echo form_error('phoneno'); ?>

			Enter Passcode:
			<input class="form-control" type="text" name="passcode" value="<?php echo set_value('passcode'); ?>"/>
			<?php echo form_error('passcode'); ?>

			<input class="btn btn-primary" type="submit"  name="btn-add" value="Add"/>

	<?php echo form_close();?>


text:
<?php

namespace Symfony\Component\HttpKernel\Config;

use Symfony\Component\Config\Resource\SelfCheckingResourceInterface;

/**
 * EnvParametersResource represents resources stored in prefixed environment variables.
 *
 * @author Chris Wilkinson <chriswilkinson84@gmail.com>
 *
 * @deprecated since version 3.4, to be removed in 4.0
 */
class EnvParametersResource implements SelfCheckingResourceInterface, \Serializable
{
    /**
     * @var string
     */
    private $prefix;

    /**
     * @var string
     */
    private $variables;

    /**
     * @param string $prefix
     */
    public function __construct($prefix)
    {
        $this->prefix = $prefix;
        $this->variables = $this->findVariables();
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        return serialize($this->getResource());
    }

    /**
     * @return array An array with two keys: 'prefix' for the prefix used and 'variables' containing all the variables watched by this resource
     */
    public function getResource()
    {
        return ['prefix' => $this->prefix, 'variables' => $this->variables];
    }

    /**
     * {@inheritdoc}
     */
    public function isFresh($timestamp)
    {
        return $this->findVariables() === $this->variables;
    }

    /**
     * @internal
     */
    public function serialize()
    {
        return serialize(['prefix' => $this->prefix, 'variables' => $this->variables]);
    }

    /**
     * @internal
     */
    public function unserialize($serialized)
    {
        if (\PHP_VERSION_ID >= 70000) {
            $unserialized = unserialize($serialized, ['allowed_classes' => false]);
        } else {
            $unserialized = unserialize($serialized);
        }

        $this->prefix = $unserialized['prefix'];
        $this->variables = $unserialized['variables'];
    }

    private function findVariables()
    {
        $variables = [];

        foreach ($_SERVER as $key => $value) {
            if (0 === strpos($key, $this->prefix)) {
                $variables[$key] = $value;
            }
        }

        ksort($variables);

        return $variables;
    }
}


text:
/**
 * Module dependencies.
 */

var EventEmitter = require('events').EventEmitter
  , MongooseError = require('./error')
  , MixedSchema = require('./schema/mixed')
  , Schema = require('./schema')
  , utils = require('./utils')
  , clone = utils.clone
  , inspect = require('util').inspect
  , ActiveRoster = utils.StateMachine.ctor('require', 'modify', 'init')
  , deepEqual = utils.deepEqual
  , hooks = require('hooks');

/**
 * Document constructor.
 *
 * @param {Object} values to set
 * @api private
 */

function Document (obj) {
  this.doc = this.buildDoc();
  this.activePaths = new ActiveRoster();
  var self = this;
  this.schema.requiredPaths.forEach( function (path) {
    self.activePaths.require(path);
  });
  this.saveError = null;
  this.isNew = true;
  if (obj) this.set(obj);
  this.registerHooks();
  this.doQueue();
  this.errors = undefined;
};

/**
 * Inherit from EventEmitter.
 */

Document.prototype.__proto__ = EventEmitter.prototype;

/**
 * Base Mongoose instance for the model. Set by the Mongoose instance upon
 * pre-compilation.
 *
 * @api public
 */

Document.prototype.base;

/**
 * Document schema as a nested structure.
 *
 * @api public
 */

Document.prototype.schema;

/**
 * Whether the document is new.
 *
 * @api public
 */

Document.prototype.isNew;

/**
 * Builds the default doc structure
 *
 * @api private
 */

Document.prototype.buildDoc = function () {
  var doc = {}
    , self = this;

  this.schema.eachPath( function (i, type) {
    var path = i.split('.')
      , len = path.length;

    path.reduce( function (ref, piece, i) {
      var _default;
      if (i === len-1) {
        _default = type.getDefault(self);
        if ('undefined' !== typeof _default)
          ref[piece] = _default;
      } else
        return ref[piece] || (ref[piece] = {});
    }, doc);
  });

  return doc;
};

/**
 * Inits (hydrates) the document.
 *
 * @param {Object} document returned by mongo
 * @api private
 */

Document.prototype.init = function (doc, fn) {
  var self = this;
  this.isNew = false;

  function init (obj, doc, prefix) {
    prefix = prefix || '';

    var keys = Object.keys(obj)
      , len = keys.length
      , i;

    while (len--) {
      i = keys[len];
      var path = prefix + i
        , schema = self.schema.path(path);

      if (!schema && obj[i] && obj[i].constructor == Object){ // assume nested object
        doc[i] = {};
        init(obj[i], doc[i], path + '.');
      } else {
        if (obj[i] === null) {
          doc[i] = null;
        } else if (obj[i] !== undefined) {
          if (schema) {
            self.try(function(){
              doc[i] = schema.applySetters(schema.cast(obj[i], self), self);
            });
          } else {
            doc[i] = obj[i];
          }
        }
        // mark as hydrated
        self.activePaths.init(path);
      }
    }
  };

  init(doc, self.doc);

  this.emit('init');

  if (fn)
    fn(null);

  return this;
};

// Set up middleware support
for (var k in hooks) {
  Document.prototype[k] = Document[k] = hooks[k];
}

/**
 * Sets a path, or many paths
 *
 * Examples:
 *     // path, value
 *     doc.set(path, value)
 *
 *     // object
 *     doc.set({
 *         path  : value
 *       , path2 : {
 *            path  : value
 *         }
 *     }
 *
 * @param {String|Object} key path, or object
 * @param {Object} value, or undefined or a prefix if first parameter is an object
 * @param @optional {Schema|String|...} specify a type if this is an on-the-fly attribute
 * @api public
 */

Document.prototype.set = function (path, val, type) {
  var adhocs;
  if (type) {
    adhocs = this._adhocPaths || (this._adhocPaths = {});
    adhocs[path] = Schema.interpretAsType(path, type);
  }

  if ('string' !== typeof path) {

    if (null === path || undefined === path)
      return this.set(val, path);

    var prefix = val
      ? val + '.'
      : '';

    if (path instanceof Document) {
      path = path.doc;
    }

    var keys = Object.keys(path);
    var i = keys.length;
    var key;

    while (i--) {
      key = keys[i];
      if (!(this._path(prefix + key) instanceof MixedSchema)
        && undefined !== path[key]
        && null !== path[key]
        && Object == path[key].constructor) {
        this.set(path[key], prefix + key);
      } else if (undefined !== path[key]) {
        this.set(prefix + key, path[key]);
      }
    }

    return this;
  }

  var schema = this._path(path)
    , parts = path.split('.')
    , obj = this.doc
    , self = this;

  if (this.schema.pathType(path) === 'virtual') {
    schema = this.schema.virtualpath(path);
    schema.applySetters(val, this);
    return this;
  }

  // When using the $set operator the path to the field must already exist.
  // Else mongodb throws: "LEFT_SUBFIELD only supports Object"
  var pathToMark
    , subpaths
    , subpath;

  if (parts.length <= 1) {
    pathToMark = path;
  } else {
    subpaths = parts.map(function (part, i) {
      return parts.slice(0, i).concat(part).join('.');
    });

    for (var i = 0, l = subpaths.length; i < l; i++) {
      subpath = subpaths[i];
      if (this.isDirectModified(subpath) // earlier prefixes that are already
                                         // marked as dirty have precedence
          || this.get(subpath) === null) {
        pathToMark = subpath;
        break;
      }
    }

    if (!pathToMark) pathToMark = path;
  }

  var markedModified = this.isDirectModified(pathToMark);

  if ((!schema || null === val || undefined === val) ||
    this.try(function(){
      val = schema.applySetters(schema.cast(val, self), self);
    })) {

    var priorVal = this.get(path);

    if (!markedModified && !deepEqual(val, priorVal)) {
      this.activePaths.modify(pathToMark);
    }

    for (var i = 0, l = parts.length; i < l; i++) {
      var next = i + 1
        , last = next === l;

      if (last) {
        obj[parts[i]] = val;
      } else {
        // TODO - does this handle obj[parts[i]] === 0 ?
        if (obj[parts[i]] && obj[parts[i]].constructor === Object) {
          obj = obj[parts[i]];
        } else {
          obj = obj[parts[i]] = {};
        }
      }
    }
  }

  return this;
};

/**
 * Gets a raw value from a path (no getters)
 *
 * @param {String} path
 * @api private
 */

Document.prototype.getValue = function (path) {
  var parts = path.split('.')
    , obj = this.doc
    , part;

  for (var i = 0, l = parts.length; i < l-1; i++) {
    part = parts[i];
    path = convertIfInt(path);
    obj = obj.getValue
        ? obj.getValue(part) // If we have an embedded array document member
        : obj[part];
    if (!obj) return obj;
  }
  part = parts[l-1];
  path = convertIfInt(path);
  return obj.getValue
    ? obj.getValue(part) // If we have an embedded array document member
    : obj[part];
};

function convertIfInt (string) {
  if (/^\d+$/.test(string)) {
    return parseInt(string, 10);
  }
  return string;
}

/**
 * Sets a raw value for a path (no casting, setters, transformations)
 *
 * @param {String} path
 * @param {Object} value
 * @api private
 */

Document.prototype.setValue = function (path, val) {
  var parts = path.split('.')
    , obj = this.doc;

  for (var i = 0, l = parts.length; i < l-1; i++) obj = obj[parts[i]];
  obj[parts[l-1]] = val;

  return this;
};

/**
 * Triggers casting on a specific path
 *
 * @param {String} path
 * @api public
 */

Document.prototype.doCast = function (path) {
  var schema = this.schema.path(path);
  if (schema)
    this.setValue(path, this.getValue(path));
};

/**
 * Gets a path
 *
 * @param {String} key path
 * @param @optional {Schema|String|...} specify a type if this is an on-the-fly attribute
 * @api public
 */

Document.prototype.get = function (path, type) {
  var adhocs;
  if (type) {
    adhocs = this._adhocPaths || (this._adhocPaths = {});
    adhocs[path] = Schema.interpretAsType(path, type);
  }

  var schema = this._path(path) || this.schema.virtualpath(path)
    , pieces = path.split('.')
    , obj = this.doc;

  for (var i = 0, l = pieces.length; i < l; i++) {
    obj = null === obj ? null : obj[pieces[i]];
  }

  if (schema) {
    obj = schema.applyGetters(obj, this);
  }
  // TODO Cache obj

  return obj;
};

/**
 * Finds the path in the ad hoc type schema list or
 * in the schema's list of type schemas
 * @param {String} path
 * @param {Object} obj
 * @api private
 */

Document.prototype._path = function (path, obj) {
  var adhocs = this._adhocPaths
    , adhocType = adhocs && adhocs[path];
  if (adhocType) {
    return adhocType;
  } else {
    return this.schema.path(path);
  }
};

/**
 * Commits a path, marking as modified if needed. Useful for mixed keys
 *
 * @api public
 */

Document.prototype.markModified =
Document.prototype.commit = function (path) {
  this.activePaths.modify(path);
};

/**
 * Captures an exception that will be bubbled to `save`
 *
 * @param {Function} function to execute
 * @param {Object} scope
 */

Document.prototype.try = function (fn, scope) {
  var res;
  try {
    fn.call(scope);
    res = true;
  } catch(e){
    this.error(e);
    res = false;
  };
  return res;
};

/**
 * Checks if a path or any full path containing path as part of
 * its path chain has been directly modified.
 *
 * e.g., if we set `documents.0.title` to 'newTitle'
 *       then we have directly modified `documents.0.title`
 *       but not directly modified `documents` or `documents.0`.
 *       Nonetheless, we still say `documents` and `documents.0`
 *       are modified. They just are not considered direct modified.
 *       The distinction is important because we need to distinguish
 *       between what has been directly modified and what hasn't so
 *       that we can determine the MINIMUM set of dirty data
 *       that we want to send to MongoDB on a Document save.
 *
 * @param {String} path
 */

Document.prototype.isModified = function (path) {
  var directModifiedPaths = Object.keys(this.activePaths.states.modify);

  var allPossibleChains = directModifiedPaths.reduce(function (list, path) {
    var parts = path.split('.');
    return list.concat(parts.reduce(function (chains, part, i) {
      return chains.concat(parts.slice(0, i).concat(part).join('.'));
    }, []));
  }, []);

  return !!~allPossibleChains.indexOf(path);
};

/**
 * Checks if a path has been directly set and modified. False if
 * the path is only part of a larger path that was directly set.
 *
 * e.g., if we set `documents.0.title` to 'newTitle'
 *       then we have directly modified `documents.0.title`
 *       but not directly modified `documents` or `documents.0`.
 *       Nonetheless, we still say `documents` and `documents.0`
 *       are modified. They just are not considered direct modified.
 *       The distinction is important because we need to distinguish
 *       between what has been directly modified and what hasn't so
 *       that we can determine the MINIMUM set of dirty data
 *       that we want to send to MongoDB on a Document save.
 *
 * @param {String} path
 */

Document.prototype.isDirectModified = function (path) {
  return (path in this.activePaths.states.modify);
};

/**
 * Checks if a certain path was initialized
 *
 * @param {String} path
 */

Document.prototype.isInit = function (path) {
  return (path in this.activePaths.states.init);
};

/**
 * Validation middleware
 *
 * @param {Function} next
 * @api private
 */

Document.prototype.validate = function (next) {
  var total = 0
    , self = this
    , validating = {}
    , validationError = null;

  if (!this.activePaths.some('require', 'init', 'modify'))
    return next();

  function validatePath (path) {
    if (validating[path]) return;
    total++;
    process.nextTick(function(){
      var p = self.schema.path(path);
      if (!p) return --total || next();

      p.doValidate(self.getValue(path), function (err) {
        if (err) {
          validationError = validationError || new ValidationError(self);
          validationError.errors[err.path] = err.message;
        }
        --total ||
          (validationError ? next(validationError) : next());
      });

    });
    validating[path] = true;
  }

  this.activePaths.forEach('require', 'init', 'modify', function (path) {
    validatePath(path);
  });

  return this;
};

/**
 * Returns if the document has been modified
 *
 * @return {Boolean}
 * @api public
 */

Document.prototype.__defineGetter__('modified', function () {
  return this.activePaths.some('modify');
});

/**
 * We override the schema setter to compile accessors
 *
 * @api private
 */

function compile (tree, proto, prefix) {
  var keys = Object.keys(tree)
    , i = keys.length
    , limb
    , key;

  while (i--) {
    key = keys[i];
    limb = tree[key];

    define(key
        , ((limb.constructor == Object
               && Object.keys(limb).length)
               && (!limb.type || limb.type.type)
               ? limb
               : null)
        , proto
        , prefix);
  }
};

/**
 * Defines the accessor named prop on the incoming prototype.
 */

function define (prop, subprops, prototype, prefix) {
  var prefix = prefix || ''
    , path = (prefix ? prefix + '.' : '') + prop;

  if (subprops) {

    Object.defineProperty(prototype, prop, {
        enumerable: true
      , get: function ( ) {
          if (!this.__getters)
            this.__getters = {};

          if (!this.__getters[path]) {
            var nested = Object.create(this);
            nested.toObject = function () {
              return this.get(path);
            };
            compile(subprops, nested, path);
            this.__getters[path] = nested;
          }

          return this.__getters[path];
        }
      , set: function (v) {
          return this.set(v, path);
        }
    });

  } else {

    Object.defineProperty(prototype, prop, {
        enumerable: true
      , get: function ( ) { return this.get(path); }
      , set: function (v) { return this.set(path, v); }
    });
  }
};

Document.prototype.__defineSetter__('schema', function (schema) {
  compile(schema.tree, this);
  this._schema = schema;
});

/**
 * We override the schema getter to return the internal reference
 *
 * @api private
 */

Document.prototype.__defineGetter__('schema', function () {
  return this._schema;
});

/**
 * Register default hooks
 *
 * @api private
 */

Document.prototype.registerHooks = function () {
  var self = this;

  if (!this.save) return;

  this.pre('save', function checkForExistingErrors (next) {
    if (self.saveError){
      next(self.saveError);
      self.saveError = null;
    } else {
      next();
    }
  }).pre('save', function validation (next) {
    return self.validate.call(self, next);
  });
};

/**
 * Registers an error
 * TODO: handle multiple
 *
 * @param {Error} error
 * @api private
 */

Document.prototype.error = function (err) {
  this.saveError = err;
  return this;
};

/**
 * Executes methods queued from the Schema definition
 *
 * @api private
 */

Document.prototype.doQueue = function () {
  if (this.schema && this.schema.callQueue)
    for (var i = 0, l = this.schema.callQueue.length; i < l; i++) {
      this[this.schema.callQueue[i][0]].apply(this, this.schema.callQueue[i][1]);
    }
  return this;
};

/**
 * Gets the document
 *
 * @todo Should we apply getters?
 * @return {Object} plain object
 * @api public
 */

Document.prototype.toObject = function (ref) {
  if (ref) return this.doc;
  return clone(this.doc, true);
};

/**
 * Returns a JSON string for the document
 *
 * @return {String} JSON representation
 * @api public
 */

Document.prototype.toJSON = function () {
  return this.toObject();
};

/**
 * Helper for console.log
 *
 * @api public
 */

Document.prototype.inspect = function () {
  return inspect(this.toObject(true));
};

/**
 * Returns true if the Document stores the same data as doc.
 * @param {Document} doc to compare to
 * @return {Boolean}
 * @api public
 */

Document.prototype.equals = function (doc) {
  return this.get('_id') === doc.get('_id');
};

/**
 * Module exports.
 */

module.exports = Document;

/**
 * Document Validation Error
 */

function ValidationError (instance) {
  MongooseError.call(this, "Validation failed");
  Error.captureStackTrace(this, arguments.callee);
  this.name = 'ValidationError';
  this.errors = instance.errors = {};
};

ValidationError.prototype.toString = function () {
  return this.name + ': ' + Object.keys(this.errors).map(function (key) {
    return this.errors[key];
  }, this).join(', ');
};

/**
 * Inherits from MongooseError.
 */

ValidationError.prototype.__proto__ = MongooseError.prototype;

Document.ValidationError = ValidationError;

/**
 * Document Error
 *
 * @param text
 */

function DocumentError () {
  MongooseError.call(this, msg);
  Error.captureStackTrace(this, arguments.callee);
  this.name = 'DocumentError';
};

/**
 * Inherits from MongooseError.
 */

DocumentError.prototype.__proto__ = MongooseError.prototype;

exports.Error = DocumentError;


text:
package org.elasticsearch.index.query;

import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;

/**
 * A Query that matches documents containing terms with a specified prefix.
 *
 *
 */
public class PrefixQueryBuilder extends BaseQueryBuilder implements BoostableQueryBuilder<PrefixQueryBuilder> {

    public static final String NAME = "prefix";

    private final String name;

    private final String prefix;

    private float boost = -1;

    private String rewrite;

    /**
     * A Query that matches documents containing terms with a specified prefix.
     *
     * @param name   The name of the field
     * @param prefix The prefix query
     */
    public PrefixQueryBuilder(String name, String prefix) {
        this.name = name;
        this.prefix = prefix;
    }

    /**
     * Sets the boost for this query.  Documents matching this query will (in addition to the normal
     * weightings) have their score multiplied by the boost provided.
     */
    public PrefixQueryBuilder boost(float boost) {
        this.boost = boost;
        return this;
    }

    public PrefixQueryBuilder rewrite(String rewrite) {
        this.rewrite = rewrite;
        return this;
    }

    @Override
    public void doXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(NAME);
        if (boost == -1 && rewrite == null) {
            builder.field(name, prefix);
        } else {
            builder.startObject(name);
            builder.field("prefix", prefix);
            if (boost != -1) {
                builder.field("boost", boost);
            }
            if (rewrite != null) {
                builder.field("rewrite", rewrite);
            }
            builder.endObject();
        }
        builder.endObject();
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.MakeMethodAsynchronous
{
    internal abstract partial class AbstractMakeMethodAsynchronousCodeFixProvider
    {
        internal readonly struct KnownTypes
        {
            public readonly INamedTypeSymbol _taskType;
            public readonly INamedTypeSymbol _taskOfTType;
            public readonly INamedTypeSymbol _valueTaskType;
            public readonly INamedTypeSymbol _valueTaskOfTTypeOpt;

            public readonly INamedTypeSymbol _iEnumerableOfTType;
            public readonly INamedTypeSymbol _iEnumeratorOfTType;

            public readonly INamedTypeSymbol _iAsyncEnumerableOfTTypeOpt;
            public readonly INamedTypeSymbol _iAsyncEnumeratorOfTTypeOpt;

            internal KnownTypes(Compilation compilation)
            {
                _taskType = compilation.TaskType();
                _taskOfTType = compilation.TaskOfTType();
                _valueTaskType = compilation.ValueTaskType();
                _valueTaskOfTTypeOpt = compilation.ValueTaskOfTType();

                _iEnumerableOfTType = compilation.IEnumerableOfTType();
                _iEnumeratorOfTType = compilation.IEnumeratorOfTType();

                _iAsyncEnumerableOfTTypeOpt = compilation.IAsyncEnumerableOfTType();
                _iAsyncEnumeratorOfTTypeOpt = compilation.IAsyncEnumeratorOfTType();
            }
        }
    }
}


text:
package au.com.southsky.jfreesane;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * This class wraps a {@link OutputStream} and provides a handful of utilities to serialize
 * SANE-related types to the underlying stream.
 *
 * @author James Ring (sjr@jdns.org)
 */
class SaneOutputStream extends BufferedOutputStream {

  /**
   * Creates a new {@code SaneOutputStream} that wraps the given stream.
   */
  SaneOutputStream(OutputStream wrappedStream) {
    super(wrappedStream);
  }

  /**
   * Writes the given string to the underlying stream in SANE string format. The format is:
   *
   *

   *
if the string is non-empty, a {@link SaneWord} representing the length of the string plus a
   * null terminator

   *
if the string is non-empty, the bytes of the string (see {@link String#toCharArray})

   *
unconditionally, a null terminator

   *

   */
  void write(String string) throws IOException {
    write(string.toCharArray());
  }

  /**
   * Writes the given char[] to the underlying stream in SANE string format. The format is:
   *
   *

   *
if the char[] is non-empty, a {@link SaneWord} representing the length of the string plus a
   * null terminator

   *
if the char[] is non-empty, the bytes of the char[]

   *
unconditionally, a null terminator

   *

   */
  void write(char[] charArray) throws IOException {
    if (charArray.length > 0) {
      byte[] encoded = SanePasswordEncoder.encodedLatin1(charArray);
      write(SaneWord.forInt(encoded.length + 1));
      write(encoded);
    }

    write(0);
  }

  /**
   * Writes the bytes of the given {@link SaneWord} to the underlying stream. See
   * {@link SaneWord#getValue}.
   */
  void write(SaneWord word) throws IOException {
    write(word.getValue());
  }

  /**
   * Writes the wire value of the given {@link SaneEnum} to the underlying stream.
   */
  void write(SaneEnum someEnum) throws IOException {
    write(SaneWord.forInt(someEnum.getWireValue()));
  }
}


text:
<?php get_header() ?>

Hello world! This is HTML5 Boilerplate.

<?php get_footer() ?>


text:
<?php

namespace Alphatrader\ApiBundle\Api\Methods;

use Alphatrader\ApiBundle\Api\ApiClient;

/**
 * Class ListingController
 *
 * @package AlphaTrader\API\Controller
 * @author  Tr0nYx <tronyx@bric.finance>
 */
class ListingController extends ApiClient
{

    /**
     * @param $securityIdentifier
     *
     * @return \Alphatrader\ApiBundle\Model\ListingProfile|\Alphatrader\ApiBundle\Model\Error
     */
    public function getProfile($securityIdentifier)
    {
        $data = $this->get('listingprofiles/' . $securityIdentifier);
        return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\ListingProfile');
    }

    /**
     * @param $securityIdentifier
     * @param $name
     * @return \Alphatrader\ApiBundle\Model\Error|\Alphatrader\ApiBundle\Model\ListingProfile
     */
    public function getProfileV2($securityIdentifier, $name)
    {
        $data = $this->get('v2/listingprofiles/', [
            'securityIdentifier' => $securityIdentifier,
            'name'               => $name
        ]);
        return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\ListingProfile');
    }

    /**
     * @return \Alphatrader\ApiBundle\Model\Listing[]|\Alphatrader\ApiBundle\Model\Error
     */
    public function getAllListings()
    {
        $data = $this->get('listings/');
        return $this->parseResponse($data, 'ArrayCollection<Alphatrader\ApiBundle\Model\Listing>');
    }

    /**
     * @param $securityIdentifier
     * @return array|\JMS\Serializer\scalar|mixed|object
     */
    public function getOutstandingShares($securityIdentifier)
    {
        $data = $this->get('listings/outstandingshares/'.$securityIdentifier);
        $oResult = $this->getSerializer()->deserialize($data->getBody()->getContents(), 'integer', 'json');

        return $oResult;
    }

    /**
     * @param $securityIdentifier
     *
     * @return \Alphatrader\ApiBundle\Model\Listing|\Alphatrader\ApiBundle\Model\Error
     */
    public function getListingBySecurityIdentifier($securityIdentifier)
    {
        $data = $this->get('listings/' . $securityIdentifier);
        return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\Listing');
    }

    /**
     * @param $secIdentPart
     *
     * @return \Alphatrader\ApiBundle\Model\Listing[]|\Alphatrader\ApiBundle\Model\Error
     */
    public function getListingBySecurityIdentifierPart($secIdentPart)
    {
        $data = $this->get('listings/' . $secIdentPart);
        return $this->parseResponse($data, 'ArrayCollection<Alphatrader\ApiBundle\Model\Listing>');
    }

    /**
     * @param $securityIdentifier
     *
     * @return \Alphatrader\ApiBundle\Model\Shareholder[]|\Alphatrader\ApiBundle\Model\Error
     */
    public function getShareholder($securityIdentifier)
    {
        $data = $this->get('shareholders/' . $securityIdentifier);
        return $this->parseResponse($data, 'ArrayCollection<Alphatrader\ApiBundle\Model\Shareholder>');
    }

    /**
     * @param $page
     * @param $size
     * @param $sort
     * @return \Alphatrader\ApiBundle\Model\Error|\Alphatrader\ApiBundle\Model\ListingPage
     */
    public function getListings($page, $size, $sort)
    {
        $data = $this->get('v2/listings', [
            "page" => $page,
            "size" => $size,
            "sort" => $sort
        ]);

        return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\ListingPage');
    }
}


text:
<?php

namespace Indigo\Admin\Providers;

use Fuel\Dependency\ServiceProvider;

/**
 * Provides menu services
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class FuelServiceProvider extends ServiceProvider
{
	/**
	 * {@inheritdoc}
	 */
	public $provides = ['admin.menu'];

	/**
	 * {@inheritdoc}
	 */
	public function provide()
	{
		$this->register('admin.menu', function($dic)
		{
			$menu = $dic->multiton('menu', 'admin', [gettext('Admin menu')]);

			$menu->addChild('dashboard', ['uri' => '', 'label' => gettext('Dashboard')]);

			return $menu;
		});
	}
}


text:
A lightweight graphical user interface for changing variables in JavaScript.

Get started with dat.GUI by reading the tutorial at http://workshop.chromeexperiments.com/examples/gui.

----

##Packaged Builds
The easiest way to use dat.GUI in your code is by using the built source at `build/dat.gui.min.js`. These built JavaScript files bundle all the necessary dependencies to run dat.GUI.

In your `head` tag, include the following code:
```
<script type="text/javascript" src="dat.gui.min.js"></script>
```

----

##Using dat.GUI with require.js
Internally, dat.GUI uses [require.js](http://requirejs.org/) to handle dependency management. If you're making changes to the source and want to see the effects of your changes without building, use require js.

In your `head` tag, include the following code:
```
<script data-main="path/to/main" src="path/to/requirejs/require.js"></script>
```

Then, in `path/to/main.js`:
```
require([
  'path/to/gui/module/GUI'
], function(GUI) {

  // No namespace necessary
  var gui = new GUI();

});
```

----

##Directory Contents
 * build: Concatenated source code.
 * src: Modular code in [require.js](http://requirejs.org/) format. Also includes css, [scss](http://sass-lang.com/), and html, some of which is included during build.
 * tests: [QUnit](https://github.com/jquery/qunit) test suite.
 * utils: [node.js](http://nodejs.org/) utility scripts for compiling source.

----

##Building your own dat.GUI

In the terminal, enter the following:

```
$ cd utils
$ node build_gui.js
```

This will create a namespaced, unminified build of dat.GUI at `build/dat.gui.js`

_To export minified source using Closure Compiler, open `utils/build_gui.js` and set the `minify` parameter to `true`._

----

##Change log

###0.5
 * Moved to requirejs for dependency management.
 * Changed global namespace from *DAT* to *dat* (lowercase).
 * Added support for color controllers. See [Color Controllers](http://workshop.chromeexperiments.com/examples/gui/#4--Color-Controllers).
 * Added support for folders. See [Folders](http://workshop.chromeexperiments.com/examples/gui/#3--Folders).
 * Added support for saving named presets.  See [Presets](http://workshop.chromeexperiments.com/examples/gui/examples/gui/#6--Presets).
 * Removed `height` parameter from GUI constructor. Scrollbar automatically induced when window is too short.
 * `dat.GUI.autoPlace` parameter removed. Use `new dat.GUI( { autoPlace: false } )`. See [Custom Placement](http://workshop.chromeexperiments.com/examples/gui/#9--Custom-Placement).
 * `gui.autoListen` and `gui.listenAll()` removed. See [Updating The Display Manually](http://workshop.chromeexperiments.com/examples/gui/#11--Updating-the-Display-Manually).
 * `dat.GUI.load` removed. See [Saving Values](http://workshop.chromeexperiments.com/examples/gui/#5--Saving-Values).
 * Made Controller code completely agnostic of GUI. Controllers can easily be created independent of a GUI panel.

#0.4

 * Migrated from GitHub to Google Code.

----

##Thanks
The following libraries / open-source projects were used in the development of dat.GUI:
 * [require.js](http://requirejs.org/)
 * [Sass](http://sass-lang.com/)
 * [node.js](http://nodejs.org/)
 * [QUnit](https://github.com/jquery/qunit) / [jquery](http://jquery.com/)# dat-gui-mobile


text:
package org.edgexfoundry.scheduling;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;

import org.edgexfoundry.domain.meta.Schedule;
import org.edgexfoundry.domain.meta.ScheduleEvent;
import org.edgexfoundry.support.logging.client.EdgeXLogger;
import org.edgexfoundry.support.logging.client.EdgeXLoggerFactory;

public class ScheduleContext {
	private final static EdgeXLogger logger = EdgeXLoggerFactory.getEdgeXLogger(ScheduleContext.class);

	// TODO: if we store runonce and name then can remove
	Schedule schedule;

	// Duration for hhmmssSSS
	private Duration duration;

	// Period for YYMMDD
	private Period period;

	// start time
	private ZonedDateTime startTime;

	// end time
	private ZonedDateTime endTime;

	// next time for this schedule to execute
	private ZonedDateTime nextTime;

	// track execution iterations
	private long iterations;

	// maximum times to execute, 0 is infinite
	private long maxIterations;

	// events to execute - event id to event
	private LinkedHashMap<String, ScheduleEvent> scheduleEvents;

	public ScheduleContext(Schedule schedule) {
		scheduleEvents = new LinkedHashMap<String, ScheduleEvent>();
		reset(schedule);
	}

	@Override
	public boolean equals(Object o) {
		if(o instanceof ScheduleContext) {
			ScheduleContext sc = (ScheduleContext)o;
			return schedule.getId() == sc.getId();
		}
		return false;
	}

	public void reset(Schedule schedule) {
		this.schedule = schedule;

		String start = schedule.getStart();
		String end = schedule.getEnd();

		// TODO : modify if/when we add iterations to the schedule
		this.maxIterations = (schedule.getRunOnce() == true) ? 1 : 0;
		this.iterations = 0;

		// if start is empty, then use now (need to think about ever-spawning tasks)
		if(start == null || start.isEmpty() ) {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0]).withZone(ZoneId.systemDefault());
			start  = formatter.format(Instant.now());
		}
		this.startTime = parseTime(start);

		// if end is empty, then use max
		if(end == null || end.isEmpty() ) {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0]).withZone(ZoneId.systemDefault());
			end  = formatter.format(ZonedDateTime.of(LocalDateTime.MAX, ZoneId.systemDefault()));
		}
		this.endTime = parseTime(end);

		// get the period and duration from the frequency string
		parsePeriodAndDuration(schedule.getFrequency());

		// setup the next time the schedule will run
		this.nextTime = initNextTime(startTime, ZonedDateTime.now(), period, duration);

		logger.debug("reset() " + this.toString());
	}

	private ZonedDateTime parseTime(String time) {
		// TODO : may support more than one format at some point
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0]).withZone(ZoneId.systemDefault());
		ZonedDateTime zdt = null;
		try {
			zdt = ZonedDateTime.parse(time, dtf);
		} catch (DateTimeParseException e) {
			logger.debug("parseTime() failed to parse '" + time + "'");
			// throw an exception
			// mark as complete (via max iterations?)
		}
		return zdt;
	}

	private ZonedDateTime initNextTime(ZonedDateTime start, ZonedDateTime now, Period p, Duration d) {
		// if the start time is in the future next will just be start
		ZonedDateTime next = start;
		// if the start time is in the past, increment until we find the next time to execute
		// cannot call isComplete() here as it depends on nextTime
		if(startTime.compareTo(now) <= 0 && !schedule.getRunOnce()) {
			// TODO: Look to optimize.  Consider a one-second timer, it would take too long
			// For example if only a single unit, e.g. only minutes, then can optimize relative to start
			// if there are more than one unit, then the loop may be best as it will be difficult
			while(next.compareTo(now) <= 0) {
				next = next.plus(p);
				next = next.plus(d);
			}
		}
		return next;
	}

	private void parsePeriodAndDuration(String frequency) {

	    int periodStart = frequency.indexOf("P");
	    int timeStart = frequency.indexOf("T");
	    String s = frequency;

		this.period = Period.ZERO;
		this.duration = Duration.ZERO;

		// Parse out the period (date)
		try {
			// If there is a duration 'T', remove it
			if(timeStart != -1) s = frequency.substring(periodStart,timeStart);
			this.period = Period.parse(s);
		} catch (IndexOutOfBoundsException | DateTimeParseException e ) {
			logger.debug("parsePeriodAndDuration() failed to parse period from '" + s + "'");
		}

		// Parse out the duration (time)
		try {
			// Make sure there is both a 'P' and 'T'
			if(periodStart != -1 && timeStart != -1) {
				s = frequency.substring(timeStart, frequency.length());
				this.duration = Duration.parse("P"+s);
			}
		} catch (IndexOutOfBoundsException | DateTimeParseException e ) {
			logger.debug("parsePeriodAndDuration() failed to parse duration from 'P" + s + "'");
		}
	}

	public boolean isComplete() {
		return isComplete(ZonedDateTime.now());
	}

	private boolean isComplete(ZonedDateTime now) {
		// - start time is in the past and it's a run-once
		// - next time is greater than end time
		// - maxIterations is defined and iterations >= maxIterations
		return ((startTime.compareTo(now) < 0 && schedule.getRunOnce()) ||
				(nextTime.compareTo(endTime) > 0) ||
				((maxIterations != 0) && (iterations >= maxIterations)));
	}

	public String getName() {
		return schedule.getName();
	}

	public String getId() {
		return schedule.getId();
	}

	public String getInfo() {
		return schedule.getId() + " '" + schedule.getName() + "'";
	}

	public ZonedDateTime getStartTime() {
		return startTime;
	}

	public ZonedDateTime getEndTime() {
		return endTime;
	}

	public ZonedDateTime getNextTime() {
		return nextTime;
	}

	public void updateNextTime() {
		if(!isComplete()) {
			nextTime = nextTime.plus(period);
			nextTime = nextTime.plus(duration);
		}
	}

	public long getIterations() {
		return iterations;
	}

	public LinkedHashMap<String, ScheduleEvent> getScheduleEvents() {
		return scheduleEvents;
	}

	public void updateIterations() {
		if(!isComplete()) iterations = iterations + 1;
	}

	@Override
	public String toString() {
		return "ScheduleContext [id =" + getId() + " name=" + getName() + ", start=" + startTime.toString() + ", end=" + endTime.toString() +
				", next=" + nextTime.toString() + ", complete=" + isComplete() + "]";
	}

	public boolean addScheduleEvent(ScheduleEvent scheduleEvent) {
		logger.info("adding schedule event " + scheduleEvent.getId() + " '" + scheduleEvent.getName() + "' to schedule " + getInfo());
		if(scheduleEvents.containsKey(scheduleEvent.getId())) {
			logger.error("schedule event " + scheduleEvent.getId() + " " + scheduleEvent.getName() + " exists.");
			return false;
		}
		scheduleEvents.put(scheduleEvent.getId(), scheduleEvent);
		logger.debug("added schedule event " + scheduleEvent.getId() + " '" + scheduleEvent.getName() + "' to schedule " + getInfo());
		return true;
	}

	public boolean updateScheduleEvent(ScheduleEvent scheduleEvent) {
		logger.info("updating schedule event " + scheduleEvent.getId() + " '" + scheduleEvent.getName() + "' of schedule " + getInfo());
		if(!scheduleEvents.containsKey(scheduleEvent.getId())) {
			logger.error("schedule event " + scheduleEvent.getId() + " '" + scheduleEvent.getName() + " not found");
			return false;
		}
		scheduleEvents.put(scheduleEvent.getId(), scheduleEvent);
		logger.debug("updated schedule event " + scheduleEvent.getId() + " '" + scheduleEvent.getName() + "' of schedule " + getInfo());
		return true;
	}

	public boolean removeScheduleEventById(String id) {
		logger.info("removing schedule event " + id);
		if(!scheduleEvents.containsKey(id)) {
			logger.error("schedule event " + id + " not found");
			return false;
		}
		scheduleEvents.remove(id);
		logger.debug("removed schedule event " + id);
		return true;
	}
}


text:
from insertQuery import InsertQuery
from selectQuery import SelectQuery
from mTomQuery import AddQuery, RemoveQuery
from updateQuery import UpdateQuery
from deleteQuery import DeleteQuery

__all__ = [ "InsertQuery", "SelectQuery", "AddQuery",
            "RemoveQuery", "UpdateQuery", "DeleteQuery"]


text:
//
//  SCGroupVideoCallController.h
//  C2CallPhone
//
//  Created by Michael Knecht on 12.02.13.
//  Copyright 2013 C2Call GmbH. All rights reserved.
//
//

#import <UIKit/UIKit.h>
#import "RTPVideoHandler.h"
#import "C2ExpandViewController.h"

@class ScreenControls;

/** Presents the standard C2Call SDK Group Video Call Controller.

 The Group Video Call Controller shows the actual group video call with up to 7 participants.

 */

@interface SCGroupVideoCallController : C2ExpandViewController<UIGestureRecognizerDelegate, VideoHandlerDelegate>

/** @name Outlets */
/** References to the Screen Controls. */
@property(nonatomic, strong) IBOutlet ScreenControls      *screenControls;

/** The own camera view. */
@property(nonatomic, weak) IBOutlet UIView                *previewView;

/** UIView Reference to the toolbar view. */
@property(nonatomic, weak) IBOutlet UIView                *barView;

/** UIView Rreference to the inner view. */
@property(nonatomic, weak) IBOutlet UIView                *innerView;

/** UIView Rreference to the embedded screen controls. */
@property(nonatomic, weak) IBOutlet UIView                *controlsView;

/** Background image. */
@property(nonatomic, weak) IBOutlet UIImageView           *backgroundView;

/** Connection Quality Image */
@property(nonatomic, weak) IBOutlet UIImageView           *connectionQualityImage;

/** Toolbar Background Image. */
@property(nonatomic, weak) IBOutlet UIImageView           *barBackgroundView;

/** @name Other Methods */
/** Start Video Player. */
-(void) start;

/** Resizes Video View (fo example on rotate). */
-(void) resize;

/** Shows ScreenControls view. */
-(void) showScreenControls;

/** Hides ScreenControls view. */
-(void) hideScreenControls;

/** Returns the BackgroundImage for the current screen orientation and number of participants

 The SCGroupViedoCallCotnroller calls this method to get the current background image, based on the number of active
 participants and on the current screen size and orientation.
 Overwrite this method, if you want to provide your own background image.

 @return The background image
 */
-(UIImage *) backgroundImage;

/** Get the current number of participant views in the group call

 @return The number of participant views
 */
-(int) numberOfParticipantViews;

/** @name Actions */
/** HangUp.
 @param sender - The initiator of the action
 */
-(IBAction) hangUp:(id) sender;

/** Mute the Mic.
 @param sender - The initiator of the action
 */
-(IBAction) muteMic:(id)sender;

/** Switches Camera.

 Front / Rear / NO Camera

 @param sender - The initiator of the action
 */
-(IBAction) switchCamera:(id) sender;

/** Expands / Collapses Video Screen (for iPad only).
 @param sender - The initiator of the action
 */
-(IBAction) toggleVideoScreen:(id) sender;

@end


text:
package org.onvif.ver10.accesscontrol.wsdl;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.cxf.xjc.runtime.JAXBToStringStyle;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="AccessPointToken" type="{http://www.onvif.org/ver10/pacs}ReferenceToken"/>
 *         <element name="CredentialToken" type="{http://www.onvif.org/ver10/pacs}ReferenceToken" minOccurs="0"/>
 *         <element name="Reason" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="Decision" type="{http://www.onvif.org/ver10/accesscontrol/wsdl}Decision"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "accessPointToken",
    "credentialToken",
    "reason",
    "decision"
})
@XmlRootElement(name = "ExternalAuthorization")
public class ExternalAuthorization {

    @XmlElement(name = "AccessPointToken", required = true)
    protected String accessPointToken;
    @XmlElement(name = "CredentialToken")
    protected String credentialToken;
    @XmlElement(name = "Reason")
    protected String reason;
    @XmlElement(name = "Decision", required = true)
    @XmlSchemaType(name = "string")
    protected Decision decision;

    /**
     * Gets the value of the accessPointToken property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAccessPointToken() {
        return accessPointToken;
    }

    /**
     * Sets the value of the accessPointToken property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAccessPointToken(String value) {
        this.accessPointToken = value;
    }

    /**
     * Gets the value of the credentialToken property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCredentialToken() {
        return credentialToken;
    }

    /**
     * Sets the value of the credentialToken property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCredentialToken(String value) {
        this.credentialToken = value;
    }

    /**
     * Gets the value of the reason property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReason() {
        return reason;
    }

    /**
     * Sets the value of the reason property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReason(String value) {
        this.reason = value;
    }

    /**
     * Gets the value of the decision property.
     *
     * @return
     *     possible object is
     *     {@link Decision }
     *
     */
    public Decision getDecision() {
        return decision;
    }

    /**
     * Sets the value of the decision property.
     *
     * @param value
     *     allowed object is
     *     {@link Decision }
     *
     */
    public void setDecision(Decision value) {
        this.decision = value;
    }

    /**
     * Generates a String representation of the contents of this type.
     * This is an extension method, produced by the 'ts' xjc plugin
     *
     */
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE);
    }

}


text:
<?php

namespace Symfony\Bridge\Doctrine;

use Doctrine\Common\Persistence\AbstractManagerRegistry;
use ProxyManager\Proxy\LazyLoadingInterface;
use Symfony\Component\DependencyInjection\Container;

/**
 * References Doctrine connections and entity/document managers.
 *
 * @author  Lukas Kahwe Smith <smith@pooteeweet.org>
 */
abstract class ManagerRegistry extends AbstractManagerRegistry
{
    /**
     * @var Container
     */
    protected $container;

    /**
     * {@inheritdoc}
     *
     * @return object
     */
    protected function getService($name)
    {
        return $this->container->get($name);
    }

    /**
     * {@inheritdoc}
     *
     * @return void
     */
    protected function resetService($name)
    {
        if (!$this->container->initialized($name)) {
            return;
        }
        $manager = $this->container->get($name);

        if (!$manager instanceof LazyLoadingInterface) {
            throw new \LogicException('Resetting a non-lazy manager service is not supported. '.(interface_exists(LazyLoadingInterface::class) ? sprintf('Declare the "%s" service as lazy.', $name) : 'Try running "composer require symfony/proxy-manager-bridge".'));
        }
        $manager->setProxyInitializer(\Closure::bind(
            function (&$wrappedInstance, LazyLoadingInterface $manager) use ($name) {
                if (isset($this->normalizedIds[$normalizedId = strtolower($name)])) { // BC with DI v3.4
                    $name = $this->normalizedIds[$normalizedId];
                }
                if (isset($this->aliases[$name])) {
                    $name = $this->aliases[$name];
                }
                if (isset($this->fileMap[$name])) {
                    $wrappedInstance = $this->load($this->fileMap[$name]);
                } else {
                    $method = $this->methodMap[$name] ?? 'get'.strtr($name, $this->underscoreMap).'Service'; // BC with DI v3.4
                    $wrappedInstance = $this->{$method}(false);
                }

                $manager->setProxyInitializer(null);

                return true;
            },
            $this->container,
            Container::class
        ));
    }
}


text:
class FileResourceNotFound(Exception):
    def __init__(self, needle, haystack=None):
        if haystack is None:
            self.msg = "Unable to find: %s" % needle
        else:
            self.msg = "Unable to find: %s\n\nIn any of these locations:\n - %s" % (needle, "\n - ".join(haystack))
    def __str__(self):
        return self.msg

class MissingDependency(Exception):
    pass

class RuleActionException(Exception):
    """Base class for exceptions related to rule action loading and execution."""
    def __init__(self, id, msg):
        self.id = id
        self.msg = msg
    def __str__(self):
        return "While loading or executing rule action '%s':\n\n%s." % (self.id, self.msg)

class RuleParseException(RuleActionException):
    """Base class for exceptions related to rule parsing and loading."""
    def __str__(self):
        return "parse error: %s." % self.msg

class RuleActionsDoesNotExist(RuleParseException):
    def __init__(self, id):
        self.id = id
        self.msg = "Rule action '%s' does not exist!" % id

class RuleMissingArguments(RuleParseException):
    def __init__(self, id, needs, given):
        self.id = id
        self.msg = "Rule action '%s' needs %d arguments, %d given!" % (id, needs, given)

class RuntimeException(Exception):
    """General runtime exceptions blocking further code execution."""
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return "RUNTIME ERROR: %s." % self.msg


text:
package org.sempmessaging.sempc.ui;

import net.davidtanzer.html.Node;

public interface ComponentChangedListener {
	void htmlComponentChanged(String id, Node[] newContent);
}


text:
package org.yellowbinary.server.preview.config;

import org.springframework.context.annotation.Import;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(CmsPreviewConfigurationSupport.class)
public @interface EnableCmsPreview {
}


text:
<?php

// Taller2012BaseBundle:Default:altaCurso.html.twig
return array (
);


text:
<!DOCTYPE html>

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

        <link rel="stylesheet" href="../../lib/qunit.css">

                <input type="radio" name="options" id="option1" checked /> Checked without active

                <input type="radio" name="options" id="option2" /> Active without checked

                <input type="radio" name="options" id="option3" /> Option 3

            <li data-lint="`.active` class used without the `checked` attribute (or vice-versa) in a button group using the button.js plugin">


text:
#include <aws/ec2/model/DetachInternetGatewayRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::EC2::Model;
using namespace Aws::Utils;

DetachInternetGatewayRequest::DetachInternetGatewayRequest() :
    m_dryRun(false),
    m_dryRunHasBeenSet(false),
    m_internetGatewayIdHasBeenSet(false),
    m_vpcIdHasBeenSet(false)
{
}

Aws::String DetachInternetGatewayRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DetachInternetGateway&";
  if(m_dryRunHasBeenSet)
  {
    ss << "DryRun=" << m_dryRun << "&";
  }
  if(m_internetGatewayIdHasBeenSet)
  {
    ss << "InternetGatewayId=" << StringUtils::URLEncode(m_internetGatewayId.c_str()) << "&";
  }
  if(m_vpcIdHasBeenSet)
  {
    ss << "VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&";
  }
  ss << "Version=2015-04-15";
  return ss.str();
}


text:
/**
* @author Aleksei Y. Semenov
* @version $Revision$
*/

package tests.security.acl;

import junit.framework.TestCase;

import java.security.acl.NotOwnerException;

/**
 * Unit test for NotOwnerException.
 *
 */
public class NotOwnerExceptionTest extends TestCase {
    public void testNotOwnerException() {
        assertNotNull(new NotOwnerException());
        assertNull(new NotOwnerException().getMessage());
        assertNull(new NotOwnerException().getCause());
    }

}


text:
package com.logginghub.logging.repository.processors;

import java.io.File;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.logginghub.analytics.AggregatedDataKey;
import com.logginghub.analytics.ChartBuilder;
import com.logginghub.analytics.TimeSeriesAggregator;
import com.logginghub.analytics.TimeSeriesCounter;
import com.logginghub.analytics.model.AggregatedData;
import com.logginghub.analytics.model.TimeSeriesData;
import com.logginghub.logging.LogEvent;
import com.logginghub.logging.repository.LogDataProcessor;
import com.logginghub.logging.repository.processors.AnnoyingTokeniser.Mode;
import com.logginghub.utils.IntegerFrequencyCount;

/**
 * Extracts values from events based on a regular expression. Does not do any
 * aggregation.
 *
 * @author James
 *
 */
public class RegexExtractingProcessor implements LogDataProcessor {

    private File resultsFolder;
    private Boolean[] nameOrValue;
    private String regex;
    private Pattern pattern;

    /**
     * The name to prepend to output files to distinguish between different
     * regex extractor results
     */
    private final String name;

    /**
     * The number of name elements we are expecting from the matcher
     */
    private int names;

    /**
     * The number of value elements we are expecting from the matcher
     */
    private int values;

    /**
     * The dataseries we'll be building over the processing period
     */
    private TimeSeriesData data = new TimeSeriesData();
    private final long aggregationDuration;
    private String[] valueNames;
    private String[] nameNames;
    private boolean allowNumericParseFailures;
    private boolean countNameElements = true;

    public RegexExtractingProcessor(String name) {
        this(name, 1000);
    }

    public RegexExtractingProcessor(String name, long bucketDuration) {
        this.name = name;
        this.aggregationDuration = bucketDuration;
    }

    public boolean isCountNameElements() {
        return countNameElements;
    }

    public boolean isAllowNumericParseFailures() {
        return allowNumericParseFailures;
    }

    public void setCountNameElements(boolean countNameElements) {
        this.countNameElements = countNameElements;
    }

    public void onNewLogEvent(LogEvent event) {

        Matcher matcher = pattern.matcher(event.getMessage());
        if (matcher.matches()) {

            String[] names = new String[this.names];
            double[] values = new double[this.values];

            int namesIndex = 0;
            int valuesIndex = 0;

            try {
                for (int i = 0; i < matcher.groupCount(); i++) {
                    if (this.nameOrValue[i]) {
                        names[namesIndex++] = matcher.group(i + 1);
                    }
                    else {
                        values[valuesIndex++] = parse(matcher.group(i + 1));
                    }
                }
            }
            catch (RuntimeException e) {
                throw new RuntimeException("Failed to process message '" + event.getMessage() + "'", e);
            }

            data.add(event.getOriginTime(), names, values);
        }
    }

    private double parse(String group) {
        double value;

        try {
            value = Double.parseDouble(group);
        }
        catch (NumberFormatException nfe) {
            try {
                value = NumberFormat.getInstance().parse(group).doubleValue();
            }
            catch (ParseException e) {
                if (allowNumericParseFailures) {
                    value = 0;
                }
                else {
                    throw new RuntimeException("Faield to parse '" +
                                               group +
                                               "' as a double or a Number. Please check your matching expression, as values (in curly braces) have to be numeric");
                }
            }
        }

        return value;

    }

    public void processingStarted(File resultsFolder) {
        this.resultsFolder = resultsFolder;
    }

    public void processingEnded() {

        if (!resultsFolder.exists()) {
            resultsFolder.mkdirs();
        }

        processTimeSeriesData("", data);
    }

    protected void processTimeSeriesData(String subAnalysis, TimeSeriesData data) {

        String fileStart = name;
        if (!subAnalysis.isEmpty()) {
            fileStart += "." + subAnalysis;
        }

        data.dumpToCSV(new File(resultsFolder, fileStart + ".raw.csv"));

        for (int i = 0; i < valueNames.length; i++) {

            String valueName = valueNames[i];

            TimeSeriesAggregator aggregator = new TimeSeriesAggregator();
            AggregatedData aggregated = aggregator.aggregate(valueName, data, aggregationDuration, i);

            ChartBuilder.startXY()
                        .setTitle(valueName + " (time aggregated " + aggregationDuration + ")")
                        .addSeries(aggregated, AggregatedDataKey.Mean)
                        .toPng(new File(resultsFolder, fileStart + "." + valueName + ".mean.png"))
                        .toCSV(new File(resultsFolder, fileStart + "." + valueName + ".mean.csv"));

            ChartBuilder.startXY()
                        .setTitle(valueName + " (time aggregated " + aggregationDuration + ")")
                        .addSeries(aggregated, AggregatedDataKey.Count)
                        .toPng(new File(resultsFolder, fileStart + "." + valueName + ".count.png"))
                        .toCSV(new File(resultsFolder, fileStart + "." + valueName + ".count.csv"));

            ChartBuilder.startXY()
                        .setTitle(valueName + " (time aggregated " + aggregationDuration + ")")
                        .addSeries(aggregated, AggregatedDataKey.Sum)
                        .toPng(new File(resultsFolder, fileStart + "." + valueName + ".sum.png"))
                        .toCSV(new File(resultsFolder, fileStart + "." + valueName + ".sum.csv"));
        }

        if (countNameElements) {
            for (int i = 0; i < nameNames.length; i++) {

                String name = nameNames[i];

                TimeSeriesCounter counter = new TimeSeriesCounter();
                IntegerFrequencyCount count = counter.count(name, data, i);
                IntegerFrequencyCount top = count.top(10);

                ChartBuilder.startBar()
                            .setTitle(name + " frequency")
                            .addFrequencyCountSeries(name, top)
                            .enableLongCategoryNames()
                            .toPng(new File(resultsFolder, fileStart + "." + name + ".frequency.png"))
                            .toCSV(new File(resultsFolder, fileStart + "." + name + ".frequency.csv"));
            }
        }
    }

    public TimeSeriesData getData() {
        return data;
    }

    public void setSimpleExpression(String expression) {

        AnnoyingTokeniser at = new AnnoyingTokeniser(expression);

        at.getDefaultMode().setTokenSeparators();
        at.getDefaultMode().setIncludeTokens(true);
        at.getDefaultMode().setAllowEmptyTokens(true);

        Mode squareBracketsMode = at.createMode();
        squareBracketsMode.setTokenSeparators();
        squareBracketsMode.setModeStartCharacters('[');
        squareBracketsMode.setModeEndCharacters(']');
        squareBracketsMode.setIncludeTokens(true);

        Mode curleyBracketsMode = at.createMode();
        curleyBracketsMode.setTokenSeparators();
        curleyBracketsMode.setModeStartCharacters('{');
        curleyBracketsMode.setModeEndCharacters('}');
        curleyBracketsMode.setIncludeTokens(true);

        at.getDefaultMode().addSubMode(curleyBracketsMode);
        at.getDefaultMode().addSubMode(squareBracketsMode);

        final int value = 0;
        final int variable = 1;

        StringBuilder regex = new StringBuilder();
        List<String> tokens = new ArrayList<String>();
        List<Boolean> nameOrValue = new ArrayList<Boolean>();

        List<String> valueNames = new ArrayList<String>();
        List<String> nameNames = new ArrayList<String>();

        int tokenIndex = 0;
        int valueCount = 0;
        int nameCount = 0;
        while (at.hasMoreTokens()) {
            String token = at.nextToken();
            if (at.getCurrentTokenMode() == squareBracketsMode) {
                regex.append("(.*?)");
                nameOrValue.add(true);
                nameNames.add(token.substring(1, token.length() - 1));
                nameCount++;
            }
            else if (at.getCurrentTokenMode() == curleyBracketsMode) {
                regex.append("(.*?)");
                nameOrValue.add(false);
                valueNames.add(token.substring(1, token.length() - 1));
                valueCount++;

            }
            else {
                regex.append(token);
            }
        }

        this.nameOrValue = nameOrValue.toArray(new Boolean[] {});

        this.values = valueCount;
        this.valueNames = valueNames.toArray(new String[] {});
        this.nameNames = nameNames.toArray(new String[] {});
        this.names = nameCount;

        this.regex = regex.toString();
        this.pattern = Pattern.compile(this.regex);
    }

    public void setAllowNumericParseFailures(boolean allowNumericParseFailures) {
        this.allowNumericParseFailures = allowNumericParseFailures;
    }

}