text:
package com.google.cloud.recommender.v1beta1;

import com.google.api.core.BetaApi;
import com.google.cloud.recommender.v1beta1.RecommenderGrpc.RecommenderImplBase;
import com.google.protobuf.AbstractMessage;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.annotation.Generated;

@BetaApi
@Generated("by gapic-generator-java")
public class MockRecommenderImpl extends RecommenderImplBase {
  private List<AbstractMessage> requests;
  private Queue<Object> responses;

  public MockRecommenderImpl() {
    requests = new ArrayList<>();
    responses = new LinkedList<>();
  }

  public List<AbstractMessage> getRequests() {
    return requests;
  }

  public void addResponse(AbstractMessage response) {
    responses.add(response);
  }

  public void setResponses(List<AbstractMessage> responses) {
    this.responses = new LinkedList<Object>(responses);
  }

  public void addException(Exception exception) {
    responses.add(exception);
  }

  public void reset() {
    requests = new ArrayList<>();
    responses = new LinkedList<>();
  }

  @Override
  public void listInsights(
      ListInsightsRequest request, StreamObserver<ListInsightsResponse> responseObserver) {
    Object response = responses.poll();
    if (response instanceof ListInsightsResponse) {
      requests.add(request);
      responseObserver.onNext(((ListInsightsResponse) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method ListInsights, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  ListInsightsResponse.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void getInsight(GetInsightRequest request, StreamObserver<Insight> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Insight) {
      requests.add(request);
      responseObserver.onNext(((Insight) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method GetInsight, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Insight.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void markInsightAccepted(
      MarkInsightAcceptedRequest request, StreamObserver<Insight> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Insight) {
      requests.add(request);
      responseObserver.onNext(((Insight) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method MarkInsightAccepted, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Insight.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void listRecommendations(
      ListRecommendationsRequest request,
      StreamObserver<ListRecommendationsResponse> responseObserver) {
    Object response = responses.poll();
    if (response instanceof ListRecommendationsResponse) {
      requests.add(request);
      responseObserver.onNext(((ListRecommendationsResponse) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method ListRecommendations, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  ListRecommendationsResponse.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void getRecommendation(
      GetRecommendationRequest request, StreamObserver<Recommendation> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Recommendation) {
      requests.add(request);
      responseObserver.onNext(((Recommendation) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method GetRecommendation, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Recommendation.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void markRecommendationClaimed(
      MarkRecommendationClaimedRequest request, StreamObserver<Recommendation> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Recommendation) {
      requests.add(request);
      responseObserver.onNext(((Recommendation) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method MarkRecommendationClaimed, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Recommendation.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void markRecommendationSucceeded(
      MarkRecommendationSucceededRequest request, StreamObserver<Recommendation> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Recommendation) {
      requests.add(request);
      responseObserver.onNext(((Recommendation) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method MarkRecommendationSucceeded, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Recommendation.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void markRecommendationFailed(
      MarkRecommendationFailedRequest request, StreamObserver<Recommendation> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Recommendation) {
      requests.add(request);
      responseObserver.onNext(((Recommendation) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method MarkRecommendationFailed, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Recommendation.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void getRecommenderConfig(
      GetRecommenderConfigRequest request, StreamObserver<RecommenderConfig> responseObserver) {
    Object response = responses.poll();
    if (response instanceof RecommenderConfig) {
      requests.add(request);
      responseObserver.onNext(((RecommenderConfig) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method GetRecommenderConfig, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  RecommenderConfig.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void updateRecommenderConfig(
      UpdateRecommenderConfigRequest request, StreamObserver<RecommenderConfig> responseObserver) {
    Object response = responses.poll();
    if (response instanceof RecommenderConfig) {
      requests.add(request);
      responseObserver.onNext(((RecommenderConfig) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method UpdateRecommenderConfig, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  RecommenderConfig.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void getInsightTypeConfig(
      GetInsightTypeConfigRequest request, StreamObserver<InsightTypeConfig> responseObserver) {
    Object response = responses.poll();
    if (response instanceof InsightTypeConfig) {
      requests.add(request);
      responseObserver.onNext(((InsightTypeConfig) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method GetInsightTypeConfig, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  InsightTypeConfig.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void updateInsightTypeConfig(
      UpdateInsightTypeConfigRequest request, StreamObserver<InsightTypeConfig> responseObserver) {
    Object response = responses.poll();
    if (response instanceof InsightTypeConfig) {
      requests.add(request);
      responseObserver.onNext(((InsightTypeConfig) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method UpdateInsightTypeConfig, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  InsightTypeConfig.class.getName(),
                  Exception.class.getName())));
    }
  }
}


text:
<?php

namespace Proxies\__CG__\MyApp\EspritBundle\Entity;

/**
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
 */
class Utilisateur extends \MyApp\EspritBundle\Entity\Utilisateur implements \Doctrine\ORM\Proxy\Proxy
{
    private $_entityPersister;
    private $_identifier;
    public $__isInitialized__ = false;
    public function __construct($entityPersister, $identifier)
    {
        $this->_entityPersister = $entityPersister;
        $this->_identifier = $identifier;
    }
    /** @private */
    public function __load()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;

            if (method_exists($this, "__wakeup")) {
                // call this after __isInitialized__to avoid infinite recursion
                // but before loading to emulate what ClassMetadata::newInstance()
                // provides.
                $this->__wakeup();
            }

            if ($this->_entityPersister->load($this->_identifier, $this) === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            unset($this->_entityPersister, $this->_identifier);
        }
    }

    /** @private */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

<<<<<<< HEAD
    public function getRole()
    {
        $this->__load();
        return parent::getRole();
    }

    public function setRole($role)
    {
        $this->__load();
        return parent::setRole($role);
=======
    public function getRoles()
    {
        $this->__load();
        return parent::getRoles();
    }

    public function setRoles($roles)
    {
        $this->__load();
        return parent::setRoles($roles);
>>>>>>> bbf8d3aba2126247b3a80474a93cc08d37f30fc3
    }

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }

    public function setNom($nom)
    {
        $this->__load();
        return parent::setNom($nom);
    }

    public function getNom()
    {
        $this->__load();
        return parent::getNom();
    }

    public function setLogin($login)
    {
        $this->__load();
        return parent::setLogin($login);
    }

    public function getLogin()
    {
        $this->__load();
        return parent::getLogin();
    }

    public function setPassword($password)
    {
        $this->__load();
        return parent::setPassword($password);
    }

    public function getPassword()
    {
        $this->__load();
        return parent::getPassword();
    }

    public function setMail($mail)
    {
        $this->__load();
        return parent::setMail($mail);
    }

    public function getMail()
    {
        $this->__load();
        return parent::getMail();
    }

    public function getMenus()
    {
        $this->__load();
        return parent::getMenus();
    }

    public function getActualites()
    {
        $this->__load();
        return parent::getActualites();
    }

    public function setMenus($menus)
    {
        $this->__load();
        return parent::setMenus($menus);
    }

    public function setActualites($actualites)
    {
        $this->__load();
        return parent::setActualites($actualites);
    }

    public function __toString()
    {
        $this->__load();
        return parent::__toString();
    }

    public function __sleep()
    {
<<<<<<< HEAD
        return array('__isInitialized__', 'id', 'nom', 'login', 'password', 'mail', 'role', 'menus', 'actualites');
=======
        return array('__isInitialized__', 'id', 'nom', 'login', 'password', 'mail', 'roles', 'menus', 'actualites');
>>>>>>> bbf8d3aba2126247b3a80474a93cc08d37f30fc3
    }

    public function __clone()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;
            $class = $this->_entityPersister->getClassMetadata();
            $original = $this->_entityPersister->load($this->_identifier);
            if ($original === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            foreach ($class->reflFields as $field => $reflProperty) {
                $reflProperty->setValue($this, $reflProperty->getValue($original));
            }
            unset($this->_entityPersister, $this->_identifier);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.eljavatar.swingutils.core.renderercomponents;

import java.awt.Component;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

/**
 *
 * @author Andres Mauricio (http://www.eljavatar.com)
 */
public class ComboBoxRendererDefault extends BasicComboBoxRenderer implements JComboBox.KeySelectionManager {

    private final String textNoSeleccionable;
    private final ListCellRenderer rendererDefault;
    private Method methodLabel;
    private Method methodTooltip;

    private Function<Object, String> functionLabel;
    private Function<Object, String> functionTooltip;

    private long timeFactor;
    private long lastTime;
    private long currentTime;
    private String prefix = "";

    private ComboBoxRendererDefault(JComboBox jComboBox, ListCellRenderer rendererDefault, String textNoSeleccionable) {
        super();
        this.rendererDefault = rendererDefault;
        this.textNoSeleccionable = textNoSeleccionable;

        jComboBox.setRenderer(this);
        jComboBox.setKeySelectionManager(this);

        Long value = (Long) UIManager.get("ComboBox.timeFactor");
        timeFactor = value == null ? 250L : value;
    }

    public ComboBoxRendererDefault(JComboBox jComboBox, ListCellRenderer rendererDefault, String textNoSeleccionable, Class clazz, String nameMethodLabel, String nameMethodTooltip) {
        this(jComboBox, rendererDefault, textNoSeleccionable);

        if (clazz != null) {
            try {
                this.methodLabel = nameMethodLabel != null ? clazz.getMethod(nameMethodLabel) : null;
                this.methodTooltip = nameMethodTooltip != null ? clazz.getMethod(nameMethodTooltip) : null;
            } catch (NoSuchMethodException | SecurityException ex) {
                Logger.getLogger(ComboBoxRendererDefault.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            this.methodLabel = null;
            this.methodTooltip = null;
        }

    }

    public ComboBoxRendererDefault(JComboBox jComboBox, ListCellRenderer rendererDefault, String textNoSeleccionable, Function functionLabel, Function functionTooltip) {
        this(jComboBox, rendererDefault, textNoSeleccionable);

        this.functionLabel = functionLabel != null ? functionLabel : null;
        this.functionTooltip = functionTooltip != null ? functionTooltip : null;
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        javax.swing.JComponent component = (javax.swing.JComponent) rendererDefault.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        javax.swing.JLabel label = (javax.swing.JLabel) component;

        label.setText(getDisplayValue(value));
        label.setToolTipText(getTooltipValue(value));

        return label;
    }

    @Override
    public int selectionForKey(char aKey, ComboBoxModel model) {
        this.currentTime = System.currentTimeMillis();

        //  Get the index of the currently selected item
        int size = model.getSize();
        int startIndex = -1;
        Object selectedItem = model.getSelectedItem();

        if (selectedItem != null) {
            for (int i = 0; i < size; i++) {
                if (selectedItem == model.getElementAt(i)) {
                    startIndex = i;
                    break;
                }
            }
        }

        //  Determine the "prefix" to be used when searching the model. The
        //  prefix can be a single letter or multiple letters depending on how
        //  fast the user has been typing and on which letter has been typed.
        if (currentTime - lastTime < timeFactor) {
            if ((prefix.length() == 1) && (aKey == prefix.charAt(0))) {
                // Subsequent same key presses move the keyboard focus to the next
                // object that starts with the same letter.
                startIndex++;
            } else {
                prefix += aKey;
            }
        } else {
            startIndex++;
            prefix = "" + aKey;
        }

        lastTime = currentTime;

        //  Search from the current selection and wrap when no match is found
        if (startIndex < 0 || startIndex >= size) {
            startIndex = 0;
        }

        int index = getNextMatch(prefix, startIndex, size, model);

        if (index < 0) {
            // wrap
            index = getNextMatch(prefix, 0, startIndex, model);
        }

        return index;
    }

    private int getNextMatch(String prefix, int start, int end, ComboBoxModel model) {
        for (int i = start; i < end; i++) {
            Object item = model.getElementAt(i);
            if (item != null) {
                String displayValue = getDisplayValue(item).toLowerCase();
                if (displayValue.startsWith(prefix)) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * This method must be implemented in the extended class.
     *
     * @param valueItem an item from the ComboBoxModel
     * @return a String containing the text to be rendered for this item.
     */
    public String getDisplayValue(Object valueItem) {
        String text;
        if (methodLabel != null && valueItem != null) {
            try {
                text = (String) methodLabel.invoke(valueItem);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                text = valueItem.toString();
                Logger.getLogger(ComboBoxRendererDefault.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (functionLabel != null && valueItem != null) {
            text = functionLabel.apply(valueItem);
        } else {
            text = (valueItem == null) ? textNoSeleccionable : valueItem.toString();
        }
        return text;
    };

    /**
     *
     * @param valueItem an item from the ComboBoxModel
     * @return a String containing the text to be rendered for the tooltip
     */
    public String getTooltipValue(Object valueItem) {
        String text;
        if (methodTooltip != null && valueItem != null) {
            try {
                text = (String) methodTooltip.invoke(valueItem);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                text = valueItem.toString();
                Logger.getLogger(ComboBoxRendererDefault.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (functionTooltip != null && valueItem != null) {
            text = functionTooltip.apply(valueItem);
        } else {
            text = null;
        }
        return text;
    };

}


text:
using System;
using System.Linq;
using System.Web.Mvc;
using CRP.Controllers.Filter;
using CRP.Controllers.Helpers;
using CRP.Controllers.ViewModels;
using CRP.Core.Domain;
using CRP.Core.Resources;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Web.Validator;
using UCDArch.Web.Attributes;
using MvcContrib;
using Check = UCDArch.Core.Utils.Check;

namespace CRP.Controllers
{
    [Authorize]
    [AnyoneWithRole]
    public class QuestionSetController : ApplicationController
    {
        private readonly IRepositoryWithTypedId<School, string> _schoolRepository;

        public QuestionSetController(IRepositoryWithTypedId<School, string> schoolRepository)
        {
            _schoolRepository = schoolRepository;
        }

        //
        // GET: /QuestionSet/
        // Tested 20200416
        public ActionResult Index()
        {
            return this.RedirectToAction(a => a.List());
        }

        /// <summary>
        /// GET: /QuestionSet/List
        /// Tested 20200416
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            var user = Repository.OfType<User>().Queryable.FirstOrDefault(a => a.LoginID == CurrentUser.Identity.Name);
            Check.Require(user != null, "User is required.");

            var schools = user.Units.Select(a => a.School).ToList();

            IQueryable<QuestionSet> query;
            if (CurrentUser.IsInRole(RoleNames.Admin))
            {
                query = Repository.OfType<QuestionSet>().Queryable
                            .Where(a => a.SystemReusable
                                || (a.UserReusable && a.User.Id == user.Id)
                                || (a.CollegeReusable && schools.Contains(a.School)));
            }
            else if (CurrentUser.IsInRole(RoleNames.SchoolAdmin))
            {
                query = Repository.OfType<QuestionSet>().Queryable
                            .Where(a => a.UserReusable && a.User.Id == user.Id
                                || (a.CollegeReusable && schools.Contains(a.School)));
            }
            else
            {
                query = Repository.OfType<QuestionSet>().Queryable
                    .Where(a => a.UserReusable && a.User.Id == user.Id);
            }

            return View(query.ToList());
        }
        /// <summary>
        /// Tested 20200416
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Details(int id)
        {
            var questionSet = Repository.OfType<QuestionSet>().GetNullableById(id);

            if (questionSet == null)
            {
                return this.RedirectToAction(a => a.List());
            }

            return View(questionSet);
        }

        /// <summary>
        /// GET: /QuestionSet/Edit/{id}
        /// </summary>
        /// <param name="id"></param>
        /// Tested 202020416
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            var questionSet = Repository.OfType<QuestionSet>().GetNullableById(id);
            if (questionSet == null || !Access.HasQuestionSetAccess(Repository, CurrentUser, questionSet))
            {
                Message = "You do not have access to the requested Question Set.";
                return this.RedirectToAction(a => a.List());
            }

            var viewModel = QuestionSetViewModel.Create(Repository, CurrentUser, _schoolRepository);
            viewModel.QuestionSet = questionSet;

            if (!questionSet.SystemReusable && !questionSet.CollegeReusable && !questionSet.UserReusable)
            {
                // there should only be one item type or item associated with this question set since it's not reusable
                var itemType = questionSet.ItemTypes.FirstOrDefault();
                var item = questionSet.Items.FirstOrDefault();

                if (itemType != null)
                {
                    viewModel.ItemType = itemType.ItemType;
                }

                if (item != null)
                {
                    viewModel.Item = item.Item;
                }
            }

            return View(viewModel);
        }

        /// <summary>
        /// POST: /QuestionSet/Edit/
        /// </summary>
        /// <remarks>
        /// Description:
        ///     Edits a question set.
        /// PreCondition:
        ///     Question set exists
        ///     Question set is not the system default "Contact Information"
        /// PostCondition:
        ///     Question set is updated
        /// </remarks>
        /// <param name="questionSet"></param>
        /// Tested 20200416
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(int id, QuestionSet questionSet)
        {
            ModelState.Clear();
            var existingQs = Repository.OfType<QuestionSet>().GetNullableById(id);

            // check for valid question set and access
            if (existingQs == null || !Access.HasQuestionSetAccess(Repository, CurrentUser, existingQs))
            {
                Message = "You do not have access to the requested Question Set.";
                return this.RedirectToAction(a => a.List());
            }

            // check to make sure it isn't the system's default contact information set
            //This check MUST happen before we change the name
            if (existingQs.Name == StaticValues.QuestionSet_ContactInformation && existingQs.SystemReusable)
            {
                Message = "This is a system default question set and cannot be modified";
                ModelState.AddModelError("Question Set", "This is a system default question set and cannot be modified");
            }

            // copy the fields
            existingQs.Name = questionSet.Name;
            //existingQs.IsActive = questionSet.IsActive;
            existingQs.IsActive = true; //I don't this is being used anywhere

            MvcValidationAdapter.TransferValidationMessagesTo(ModelState, existingQs.ValidationResults());

            if (questionSet.Name != null && questionSet.Name.ToLower() == StaticValues.QuestionSet_ContactInformation.ToLower())
            {
                ModelState.AddModelError("QuestionSet.Name", StaticValues.QuestionSet_ContactInformation + " is reserved for internal system use only.");
                Message = StaticValues.QuestionSet_ContactInformation + " is reserved for internal system use only.";
            }

            if (ModelState.IsValid)
            {
                Repository.OfType<QuestionSet>().EnsurePersistent(existingQs);
                Message = NotificationMessages.STR_ObjectSaved.Replace(NotificationMessages.ObjectType, "Question Set");
            }

            var viewModel = QuestionSetViewModel.Create(Repository, CurrentUser, _schoolRepository);
            viewModel.QuestionSet = existingQs;

            if (!existingQs.SystemReusable && !existingQs.CollegeReusable && !existingQs.UserReusable)
            {
                // there should only be one item type or item associated with this question set since it's not reusable
                var itemType = existingQs.ItemTypes.FirstOrDefault();
                var item = existingQs.Items.FirstOrDefault();

                if (itemType != null)
                {
                    viewModel.ItemType = itemType.ItemType;
                }

                if (item != null)
                {
                    viewModel.Item = item.Item;
                }
            }

            return View(viewModel);
        }

        /// <summary>
        /// GET: /QuestionSet/Create
        /// </summary>
        /// <param name="itemId">The id for an item, if it is to be automatically associated with an item</param>
        /// <param name="itemTypeId">The id for an itemType, if it is to be automatically associated with an itemType</param>
        /// <param name="transaction">If adding to an item or item type, the questionSet type to add it to</param>
        /// <param name="quantity">If adding to an item or item type, the questionSet type to add it to</param>
        /// Tested 20200416
        /// <returns></returns>
        public ActionResult Create(int? itemId, int? itemTypeId, bool? transaction, bool? quantity)
        {
            var viewModel = QuestionSetViewModel.Create(Repository, CurrentUser, _schoolRepository);

            // set the item or item type as needed
            if (itemId.HasValue)
            {
                viewModel.Item = Repository.OfType<Item>().GetNullableById(itemId.Value);
                if (viewModel.Item == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "Item");
                    return this.RedirectToAction(a => a.List());
                }
            }
            if (itemTypeId.HasValue)
            {
                viewModel.ItemType = Repository.OfType<ItemType>().GetNullableById(itemTypeId.Value);
                if(viewModel.ItemType == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "ItemType");
                    return this.RedirectToAction(a => a.List());
                }
            }

            viewModel.Transaction = transaction.HasValue ? transaction.Value : false;
            viewModel.Quantity = quantity.HasValue ? quantity.Value : false;

            // display reusable options
            if (CurrentUser.IsInRole(RoleNames.Admin))
            {
                viewModel.IsAdmin = true;
            }
            else if (CurrentUser.IsInRole(RoleNames.SchoolAdmin))
            {
                viewModel.IsSchoolAdmin = true;
            }
            else
            {
                viewModel.IsUser = true;
            }

            return View(viewModel);
        }

        /// <summary>
        /// POST: /QuestionSet/Create
        /// </summary>
        /// <remarks>
        /// Description:
        ///     Creates a question set and automatically associates it to an item if an item itemId is provided.
        /// PreCondition:
        ///     Questionset does not exist with the same name if it is reusable at each level of reusability
        /// PostCondition:
        ///     Questionset is created with no question
        ///     if item itemId is given, question set is assigend to item
        /// </remarks>
        /// <param name="itemId">the id for an item to be assigned to</param>
        /// <param name="itemTypeId">the item type id to be associated with</param>
        /// <param name="questionSet"></param>
        /// <param name="school"></param>
        /// <param name="transaction"></param>
        /// <param name="quantity"></param>
        /// Tested 20200416
        /// <returns></returns>
        [HttpPost]
        [HandleTransactionsManually]
        public ActionResult Create(int? itemId, int? itemTypeId, [Bind(Exclude="Id")]QuestionSet questionSet, string school, bool? transaction, bool? quantity)
        {
            ModelState.Clear();
            var user = Repository.OfType<User>().Queryable.Where(a => a.LoginID == CurrentUser.Identity.Name).FirstOrDefault();
            questionSet.User = user;

            if (questionSet.CollegeReusable) questionSet.School = _schoolRepository.GetNullableById(school);

            MvcValidationAdapter.TransferValidationMessagesTo(ModelState, questionSet.ValidationResults());

            if (itemId.HasValue || itemTypeId.HasValue)
            {
                if (!transaction.HasValue || !quantity.HasValue)
                {
                    ModelState.AddModelError("Transaction/Quantity", "Transaction or Quantity must be specified.");
                }
                else if (transaction.Value == quantity.Value)
                {
                    ModelState.AddModelError("Transaction/Quantity", "Transaction and Quantity cannot be the same.");
                }
            }
            if (questionSet.Name != null && questionSet.Name.ToLower() == "Contact Information".ToLower())
            {
                ModelState.AddModelError("QuestionSet.Name", "Contact Information is reserved for internal system use only.");
            }

            //Validation check before we persist, shouldn't really be needed
            if (itemId.HasValue)
            {
                var item = Repository.OfType<Item>().GetNullableById(itemId.Value);
                if (item == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "Item");
                    return this.RedirectToAction(a => a.List());
                }
                MvcValidationAdapter.TransferValidationMessagesTo(ModelState, item.ValidationResults());
            }
            else if (itemTypeId.HasValue)
            {
                var itemType = Repository.OfType<ItemType>().GetNullableById(itemTypeId.Value);
                if (itemType == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "ItemType");
                    return this.RedirectToAction(a => a.List());
                }
                MvcValidationAdapter.TransferValidationMessagesTo(ModelState, itemType.ValidationResults());
            }
            if (ModelState.IsValid)
            {
                if (itemId.HasValue)
                {
                    // has an item to automatically associate to
                    var item = Repository.OfType<Item>().GetById(itemId.Value);

                    if (transaction.Value)
                    {
                        item.AddTransactionQuestionSet(questionSet);
                    }
                    else
                    {
                        item.AddQuantityQuestionSet(questionSet);
                    }

                    using (var ts = new TransactionScope())
                    {
                        Repository.OfType<Item>().EnsurePersistent(item);
                        ts.CommitTransaction();
                    }

                    Message = NotificationMessages.STR_ObjectCreated.Replace(NotificationMessages.ObjectType, "Question Set");
                    return this.RedirectToAction(a => a.Edit(questionSet.Id));
                }
                else if (itemTypeId.HasValue)
                {
                    var itemType = Repository.OfType<ItemType>().GetById(itemTypeId.Value);

                    if (transaction.Value)
                    {
                        itemType.AddTransactionQuestionSet(questionSet);
                    }
                    else
                    {
                        itemType.AddQuantityQuestionSet(questionSet);
                    }

                    using (var ts = new TransactionScope())
                    {
                        Repository.OfType<ItemType>().EnsurePersistent(itemType);
                        ts.CommitTransaction();
                    }

                    Message = NotificationMessages.STR_ObjectCreated.Replace(NotificationMessages.ObjectType, "Question Set");
                    return this.RedirectToAction(a => a.Edit(questionSet.Id));
                }
                else
                {
                    if (!CurrentUser.IsInRole(RoleNames.Admin) && !CurrentUser.IsInRole(RoleNames.SchoolAdmin) && CurrentUser.IsInRole(RoleNames.User))
                    {
                        questionSet.UserReusable = true;
                    }

                    //Do an extra check here. Note, no one should have a SchoolAdmin value.
                    if (!CurrentUser.IsInRole(RoleNames.Admin))
                    {
                        questionSet.CollegeReusable = false;
                        questionSet.SystemReusable = false;
                    }

                    //make sure it's some type of reusable
                    if (questionSet.SystemReusable || questionSet.CollegeReusable || questionSet.UserReusable)
                    {
                        using (var ts = new TransactionScope())
                        {
                            Repository.OfType<QuestionSet>().EnsurePersistent(questionSet);
                            ts.CommitTransaction();
                        }

                        Message = NotificationMessages.STR_ObjectCreated.Replace(NotificationMessages.ObjectType, "Question Set");
                        return this.RedirectToAction(a => a.Edit(questionSet.Id));
                    }
                    else
                    {
                        ModelState.AddModelError("Reusable", "Question set must be reusable of some sort.");
                    }
                }
            }

            // return to the view
            var viewModel = QuestionSetViewModel.Create(Repository, CurrentUser, _schoolRepository);
            viewModel.QuestionSet = questionSet;

            if (itemId.HasValue) viewModel.Item = Repository.OfType<Item>().GetNullableById(itemId.Value);
            if (itemTypeId.HasValue) viewModel.ItemType = Repository.OfType<ItemType>().GetNullableById(itemTypeId.Value);

            viewModel.Transaction = transaction.HasValue ? transaction.Value : false;
            viewModel.Quantity = quantity.HasValue ? quantity.Value : false;

            if (CurrentUser.IsInRole(RoleNames.Admin))
            {
                viewModel.IsAdmin = true;
            }
            else if (CurrentUser.IsInRole(RoleNames.SchoolAdmin))
            {
                viewModel.IsSchoolAdmin = true;
            }
            else
            {
                viewModel.IsUser = true;
            }

            return View(viewModel);
        }

        /// <summary>
        /// GET: /QuestionSet/LinkToItemType/{itemTypeId}
        /// </summary>
        /// <param name="itemTypeId">The id of the item type to link to</param>
        /// <param name="transaction"></param>
        /// <param name="quantity"></param>
        /// Tested 202020416
        /// <returns></returns>
        [Authorize(Roles = "Admin")]
        public ActionResult LinkToItemType(int itemTypeId, bool transaction, bool quantity)
        {
            var item = Repository.OfType<ItemType>().GetNullableById(itemTypeId);

            if (item == null || transaction == quantity)
            {
                // redirect no item to link to
                if(item == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "ItemType");
                }
                else
                {
                    Message = NotificationMessages.STR_TransactionQuantitySame;
                }
                return this.RedirectToAction<ApplicationManagementController>(a => a.ListItemTypes());
            }

            var viewModel = QuestionSetLinkViewModel.Create(Repository, CurrentUser.Identity.Name);
            viewModel.ItemTypeId = itemTypeId;
            viewModel.Transaction = transaction;
            viewModel.Quantity = quantity;

            return View(viewModel);
        }

        /// <summary>
        /// POST: /QuestionSet/LinkToItemType/
        /// </summary>
        /// <remarks>
        /// Description:
        ///     Adds a question set to the selected item type
        /// Assumption:
        ///     User has access to modify item type
        /// PreCondition:
        ///     Item Type has been created
        /// PostCondition:
        ///     Item type has question set associated with it
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="itemTypeId">The item type id.</param>
        /// <param name="transaction">if set to <c>true</c> [transaction].</param>
        /// <param name="quantity">if set to <c>true</c> [quantity].</param>
        /// Tested 20200416
        /// <returns></returns>
        [HttpPost]
        [AdminOnly]
        public ActionResult LinkToItemType(int id, int itemTypeId, bool transaction, bool quantity)
        {
            // get the question set
            var questionSet = Repository.OfType<QuestionSet>().GetNullableById(id);
            var itemType = Repository.OfType<ItemType>().GetNullableById(itemTypeId);

            if (questionSet == null || itemType == null || transaction == quantity)
            {
                if(questionSet == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "QuestionSet");
                }
                else if (itemType == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "ItemType");
                }
                else
                {
                    Message = NotificationMessages.STR_TransactionQuantitySame;
                }
                return this.RedirectToAction<ApplicationManagementController>(a => a.ListItemTypes());
            }

            foreach (var itemTypeQuestionSet in itemType.QuestionSets)
            {
                if(itemTypeQuestionSet.QuestionSet == questionSet)
                {
                    ModelState.AddModelError("Question Set", "QuestionSet \"" + questionSet.Name.Trim() + "\" is already added to the ItemType.");
                    Message = "QuestionSet was already added";
                    break;
                }
            }

            // add the questionset
            if (transaction)
            {
                itemType.AddTransactionQuestionSet(questionSet);
            }
            else if (quantity)
            {
                itemType.AddQuantityQuestionSet(questionSet);
            }

            MvcValidationAdapter.TransferValidationMessagesTo(ModelState, itemType.ValidationResults());

            // check if it's a contact information question set
            if (questionSet.Name == StaticValues.QuestionSet_ContactInformation) ModelState.AddModelError("Question Set Name", "A duplicate Contact Information question set cannot be added.");

            if (ModelState.IsValid)
            {
                Repository.OfType<ItemType>().EnsurePersistent(itemType);
                Message = NotificationMessages.STR_ObjectCreated.Replace(NotificationMessages.ObjectType, "Question Set");
            }
            else
            {
                return LinkToItemType(itemTypeId, transaction, quantity);
            }

            return this.RedirectToAction<ApplicationManagementController>(a => a.EditItemType(itemTypeId));
        }

        /// <summary>
        /// Get: /QuestionSet/LinkToItem
        /// Tested 20200420
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <param name="transaction">if set to <c>true</c> [transaction].</param>
        /// <param name="quantity">if set to <c>true</c> [quantity].</param>
        /// <returns></returns>
        [UserOnly]
        public ActionResult LinkToItem(int itemId, bool transaction, bool quantity)
        {
            var item = Repository.OfType<Item>().GetNullableById(itemId);

            if (item == null || transaction == quantity)
            {
                // redirect no item to link to
                if (item == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "Item");
                }
                else
                {
                    Message = NotificationMessages.STR_TransactionQuantitySame;
                }
                return this.RedirectToAction<ItemManagementController>(a => a.List(null));
            }

            var viewModel = QuestionSetLinkViewModel.Create(Repository, CurrentUser.Identity.Name);
            viewModel.ItemId = itemId;
            viewModel.Transaction = transaction;
            viewModel.Quantity = quantity;

            return View(viewModel);
        }

        /// <summary>
        /// POST: /QuestionSet/LinkToItem/
        /// Tested 20200420
        /// </summary>
        /// <remarks>
        /// Description:
        ///     Adds a question set to an item
        /// Assumption:
        ///     Item exists
        ///     User is an editor for that item
        ///     User has the "User" role
        /// PreCondition:
        ///     Item exists with no transactions against it
        /// PostCondition:
        ///     Question set is assigned to the item
        /// </remarks>
        /// <param name="id"></param>
        /// <param name="itemId"></param>
        /// <param name="transaction"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        [HttpPost]
        [UserOnly]
        public ActionResult LinkToItem(int id, int itemId, bool transaction, bool quantity)
        {
            // get the question set
            var questionSet = Repository.OfType<QuestionSet>().GetNullableById(id);
            var item = Repository.OfType<Item>().GetNullableById(itemId);

            if (questionSet == null || item == null || transaction == quantity)
            {
                if (questionSet == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "QuestionSet");
                }
                else if (item == null)
                {
                    Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "Item");
                }
                else
                {
                    Message = NotificationMessages.STR_TransactionQuantitySame;
                }
                return this.RedirectToAction<ItemManagementController>(a => a.List(null));
            }
            if (!Access.HasItemAccess(CurrentUser, item))
            {
                //Don't Have editor rights
                Message = NotificationMessages.STR_NoEditorRights;
                return this.RedirectToAction<ItemManagementController>(a => a.List(null));
            }

            // add the questionset
            if (transaction)
            {
                item.AddTransactionQuestionSet(questionSet);
            }
            else if (quantity)
            {
                item.AddQuantityQuestionSet(questionSet);
            }

            MvcValidationAdapter.TransferValidationMessagesTo(ModelState, item.ValidationResults());

            // check if it's a contact information question set
            if (questionSet.Name == StaticValues.QuestionSet_ContactInformation) ModelState.AddModelError("Question Set Name", "A duplicate Contact Information question set cannot be added.");

            if (ModelState.IsValid)
            {
                Repository.OfType<Item>().EnsurePersistent(item);
                Message = NotificationMessages.STR_ObjectCreated.Replace(NotificationMessages.ObjectType, "Question Set");
            }
            else
            {
                if(item.QuestionSets.Where(a => a.QuestionSet == questionSet).Where(b => b.TransactionLevel).Count() > 1)
                {
                    Message = "That question set is already linked to the transaction question sets";
                }
                else if (item.QuestionSets.Where(a => a.QuestionSet == questionSet).Where(b => b.QuantityLevel).Count() > 1)
                {
                    Message = "That question set is already linked to the quantity question sets";
                }
                else
                {
                    Message = "An error with the item prevents this from saving.";
                }
                return LinkToItem(itemId, transaction, quantity);
            }

            var redirectUrl = Url.Action("Edit", "ItemManagement", new { id = itemId });
            return Redirect(redirectUrl + "#Questions");

        }

        /// <summary>
        /// POST: /QuestionSet/UnlinkFromItem
        /// Tested 20200420
        /// </summary>
        /// <remarks>
        /// Description:
        ///     Removes a question set to an item
        /// Assumption:
        ///     Item exists
        ///     Question set exists
        ///     ItemQuestionSet object exists
        ///     User is an editor for that item
        ///     User has the "User" role
        /// PreCondition:
        ///     Item exists with no transactions against it
        /// PostCondition:
        ///     Question set is removed from the item
        /// </remarks>
        /// <param name="id">Item Question Set Id</param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        [HttpPost]
        [UserOnly]
        public ActionResult UnlinkFromItem(int id)
        {
            var itemQuestionSet = Repository.OfType<ItemQuestionSet>().GetNullableById(id);
            if (itemQuestionSet == null)
            {
                Message = NotificationMessages.STR_ObjectNotFound.Replace(NotificationMessages.ObjectType, "ItemQuestionSet");
                return this.RedirectToAction<ItemManagementController>(a => a.List(null));
            }
            if (!Access.HasItemAccess(CurrentUser, itemQuestionSet.Item))
            {
                //Don't Have editor rights
                Message = NotificationMessages.STR_NoEditorRights;
                return this.RedirectToAction<ItemManagementController>(a => a.List(null));
            }

            var itemId = itemQuestionSet.Item.Id;

            //We are removing it, we don't care about any invalid data
            //MvcValidationAdapter.TransferValidationMessagesTo(ModelState, itemQuestionSet.ValidationResults());

            // check to make sure it isn't the system's default contact information set
            var ciQuestionSet = Repository.OfType<QuestionSet>().GetNullableById(itemQuestionSet.QuestionSet.Id);
            if (ciQuestionSet != null)
            {
                if (ciQuestionSet.Name == StaticValues.QuestionSet_ContactInformation && ciQuestionSet.SystemReusable)
                {
                    ModelState.AddModelError("Question Set",
                                             "This is a system default question set and cannot be modified.");
                }
            }

            // check to make sure there aren't any answers already
            if (Repository.OfType<TransactionAnswer>().Queryable.Where(a => a.QuestionSet == itemQuestionSet.QuestionSet).Any())
            {
                if (Repository.OfType<TransactionAnswer>().Queryable
                    .Any(a => a.QuestionSet == itemQuestionSet.QuestionSet && a.Transaction.Item.Id == itemId))
                {
                    ModelState.AddModelError("Question Set",
                        "Someone has already entered a response to this question set and it cannot be deleted.");
                }
            }

            if(ModelState.IsValid)
            {
                Repository.OfType<ItemQuestionSet>().Remove(itemQuestionSet);
                Message = NotificationMessages.STR_ObjectRemoved.Replace(NotificationMessages.ObjectType, "Question Set");
            }
            else
            {
                Message = "Unable to remove question set.";
            }

            var redirectUrl = Url.Action("Edit", "ItemManagement", new { id = itemId });
            return Redirect(redirectUrl + "#Questions");
        }
    }
}


text:
package com.viggibear.cepnet.app;

import android.app.Application;
import com.parse.Parse;

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Parse.initialize(this, "JIlJ16fgPMUW06SfEUFW3R16LZ863gWH72yYway8", "n97cOErhfOPnxUsN5ltijfVqPQ8ZEXdg65nvIZho");
    }
}


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.addons.mod_chat')

/**
 * Chat service.
 *
 * @module mm.addons.mod_chat
 * @ngdoc service
 * @name $mmaModChat
 */
.factory('$mmaModChat', function($q, $mmSite, $mmUser) {
    var self = {};

    /**
     * Return whether or not the plugin is enabled. Plugin is enabled if the chat WS are available.
     *
     * @module mm.addons.mod_chat
     * @ngdoc method
     * @name $mmaModChat#isPluginEnabled
     * @return {Boolean} True if plugin is enabled, false otherwise.
     */
    self.isPluginEnabled = function() {
        return  $mmSite.wsAvailable('mod_chat_get_chats_by_courses') &&
                $mmSite.wsAvailable('mod_chat_login_user') &&
                $mmSite.wsAvailable('mod_chat_get_chat_users') &&
                $mmSite.wsAvailable('mod_chat_send_chat_message') &&
                $mmSite.wsAvailable('mod_chat_get_chat_latest_messages');
    };

    /**
     * Get a chat.
     *
     * @module mm.addons.mod_chat
     * @ngdoc method
     * @name $mmaModChat#getChat
     * @param {Number} courseid Course ID.
     * @param {Number} cmid     Course module ID.
     * @param {Boolean} [refresh] True when we should not get the value from the cache.
     * @return {Promise}        Promise resolved when the chat is retrieved.
     */
    self.getChat = function(courseid, cmid, refresh) {
        var params = {
            courseids: [courseid]
            },
            preSets = {};

        if (refresh) {
            preSets.getFromCache = false;
        }

        return $mmSite.read('mod_chat_get_chats_by_courses', params, preSets).then(function(response) {
            if (response.chats) {
                var currentChat;
                angular.forEach(response.chats, function(chat) {
                    if (chat.coursemodule == cmid) {
                        currentChat = chat;
                    }
                });
                if (currentChat) {
                    return currentChat;
                }
            }
            return $q.reject();
        });
    };

    /**
     * Get a chat.
     *
     * @module mm.addons.mod_chat
     * @ngdoc method
     * @name $mmaModChat#loginUser
     * @param {Number} chatId   Chat instance ID.
     * @return {Promise}        Promise resolved when the WS is executed.
     */
    self.loginUser = function(chatId) {
        var params = {
            chatid: chatId
        };

        return $mmSite.write('mod_chat_login_user', params).then(function(response) {
            if (response.chatsid) {
                return response.chatsid;
            }
            return $q.reject();
        });
    };

    /**
     * Report a chat as being viewed.
     *
     * @module mm.addons.mod_chat
     * @ngdoc method
     * @name $mmaModChat#logView
     * @param {String} id Module ID.
     * @return {Promise}  Promise resolved when the WS call is successful.
     */
    self.logView = function(id) {
        if (id) {
            var params = {
                chatid: id
            };
            return $mmSite.write('mod_chat_view_chat', params);
        }
        return $q.reject();
    };

    /**
     * Send a message to a chat.
     *
     * @module mm.addons.mod_chat
     * @ngdoc method
     * @name $mmaModChat#sendMessage
     * @param {Number} chatsid  Chat sessiond ID.
     * @param {String} message  Message text.
     * @param {Number} beep     Beep user ID.
     * @return {Promise}        Promise resolved when the WS is executed.
     */
    self.sendMessage = function(chatsid, message, beep) {
        var params = {
            chatsid: chatsid,
            messagetext: message,
            beepid: beep
        };

        return $mmSite.write('mod_chat_send_chat_message', params).then(function(response) {
            if (response.messageid) {
                return response.messageid;
            }
            return $q.reject();
        });
    };

    /**
     * Get the latest messages from a chat.
     *
     * @module mm.addons.mod_chat
     * @ngdoc method
     * @name $mmaModChat#getLatestMessages
     * @param {Number} chatsid  Chat sessiond ID.
     * @param {Number} lasttime Last time when messages were retrieved.
     * @return {Promise}        Promise resolved when the WS is executed.
     */
    self.getLatestMessages = function(chatsid, lasttime) {
        var params = {
            chatsid: chatsid,
            chatlasttime: lasttime
        };
        var preSets = {
            getFromCache: false
        };

        return $mmSite.read('mod_chat_get_chat_latest_messages', params, preSets);
    };

    /**
     * Get user data for messages since they only have userid.
     *
     * @module mm.addons.messages
     * @ngdoc method
     * @name $mmaModChat#getMessagesUserData
     * @param {Object[]} messages    Messages to get the data for.
     * @param {Number}   courseid    ID of the course the messages belong to.
     * @return {Promise}             Promise always resolved. Resolve param is the formatted messages.
     */
    self.getMessagesUserData = function(messages, courseid) {
        var promises = [];

        angular.forEach(messages, function(message) {
            var promise = $mmUser.getProfile(message.userid, courseid, true).then(function(user) {
                message.userfullname = user.fullname;
                message.userprofileimageurl = user.profileimageurl;
            }, function() {
                // Error getting profile. Set default data.
                message.userfullname = message.userid;
            });
            promises.push(promise);
        });
        return $q.all(promises).then(function() {
            return messages;
        });
    };

    /**
     * Get the actives users of a current chat.
     *
     * @module mm.addons.mod_chat
     * @ngdoc method
     * @name $mmaModChat#getChatUsers
     * @param {Number} chatsid  Chat sessiond ID.
     * @return {Promise}        Promise resolved when the WS is executed.
     */
    self.getChatUsers = function(chatsid) {
        var params = {
            chatsid: chatsid
        };
        var preSets = {
            getFromCache: false
        };

        return $mmSite.read('mod_chat_get_chat_users', params, preSets);
    };

    return self;
});


text:
..
   Copyright 2012-2014, Continuuity, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

:orphan:

.. plugin-resources-reference:

.. index::
   single: Plugin Resources

================
Plugin Resources
================

.. include:: /guide/admin/admin-links.rst

There is out of the box support for creating Hadoop clusters. Internally, the installation, configuration, and management of Hadoop
services is handled on the provisioner by the Chef Automator plugin. The Chef Automator plugin uses out of the box cookbooks to
execute all tasks it needs to perform. However, administrators may wish to manage other sorts of clusters using other sorts of
services. For example, you may want to create an Elastic Search template to create an indexing and search cluster.
In order to allow simple and easy expansion of service and template capabilities, plugins are able to define different
types of resources they can use to perform tasks. For example, the Chef Automator plugin defines 3 types of resources:
cookbooks, data bags, and roles. We include several cookbooks out of the box, but the plugin resource system allows administrators to
add and manage any number of cookbooks, enabling support of any service desired. Similarly, plugin resources can be used on the
provider plugin side to upload and manage tenant specific data, such as user keys or credentials.

Overview
========

Plugin resources can only be managed by the administrator of a tenant.  As with all other entities, plugin resources are isolated to within
a tenant. Users from one tenant cannot see plugin resources in another tenant. The basic flow is that an administrator uploads resources
as needed. Each time a resource is uploaded, a new version of it is created. These resources are not available for use until the administrator
stages a specific version of the resource, and then performs a sync to push all staged versions from the server to provisioners. If a resource
needs to be removed, it can be recalled, which means it will be unavailable for use after the next sync.  Thus there are four
possible states in the lifecycle of a resource: inactive, staged, active, and recalled.

An inactive resource is not available to provisioners and is not scheduled to be available any time in the future. A staged resource is not
available to provisioners, but is scheduled to be available after the next resource sync. An active resource is available to provisioners
and will continue to be available after the next sync. A recalled resource is available to provisioners, but scheduled to be removed from
provisioners after the next sync.

Generally, an administrator will upload some resources, stage the versions that should be active, then sync all resources. As resources
evolve and update, new versions are uploaded and synced. If a resource ever needs to be removed completely, it is recalled, synced,
and finally deleted. All resource operations can be performed through the UI or directly through the REST APIs documented :doc:`here </rest/plugins>`

Uploading Resources
===================

Plugin resources can only be uploaded by a tenant administrator. It can be done through the UI, or through the REST API
documented :doc:`here </rest/plugins>`. Each time a resource is uploaded, a new version of the resource is created. Subsequent
interactions require the version of a resource as well as the name. Archive resources are assumed to be constructed such that
the name of the resource is a top level folder in the expanded archive. A newly uploaded resource begins in the 'inactive' state.
An inactive resource is not visible to provisioners, meaning it cannot be used. It is also not scheduled to be used at any point
in the future.

Staging Resources
=================

Before a resource can be made available for use by provisioners, a specific version of the resource must be staged.
In the 'staged' state, a resource is still not available to provisioners, but is scheduled to be pushed out after the next sync.

Staging an inactive resource will move it to the staged state. Additionally, if there is an active version of the resource, it
will be moved to the recalled state. Similarly, if there is already a staged version, it will be moved to the inactive state.
For example, suppose version 2 of the mysql cookbook is active. Staging version 3 of the mysql cookbook will move version 2 from
the active state to the recalled state. If version 4 of the mysql cookbook is now staged, version 2 will move back to the inactive
state.

Staging a recalled resource will move it back to the active state.
Staging a staged resource has no effect. Staging an active resource also has no effect.

Recalling Resources
===================

The admin can remove a resource from use by recalling it. Recalling the active version of a resource moves it to the recalled state.
A resource in the recalled state is still available for use by provisioners, but will be removed after the next sync. Recalling
a staged resource will move it back to the inactive state. Recalling a recalled resource has no effect. Recalling an inactive resource
also has no effect.

Syncing Resources
=================

Syncing resources will make all staged resources active and all recalled resources inactive. Any active resources will stay active,
and any inactive resources will stay inactive. Any tasks that were already running when the sync began will continue to run with
the old resources. However, all new tasks are guaranteed to use the new active set of resources.


text:
package brooklyn.entity.messaging.kafka;

import brooklyn.entity.basic.AbstractEntity;
import brooklyn.entity.messaging.Topic;

public class KafkaTopic extends AbstractEntity implements Topic {

    public KafkaTopic() {
    }

    // kafka:type=kafka.logs.${topicName}

    @Override
    public String getTopicName() {
        return null; // TODO
    }

    @Override
    public void create() {
        // TODO
    }

    @Override
    public void delete() {
        // TODO
    }

}


text:
@implementation FLFacebookMessage
@synthesize message = _message;
@synthesize to = _to;
@synthesize created_time = _created_time;
@synthesize from = _from;
+(FLFacebookMessage*) facebookMessage {
    return FLAutorelease([[[self class] alloc] init]);
}
#if FL_MRC
-(void) dealloc {
    [_message release];
    [_to release];
    [_created_time release];
    [_from release];
    [super dealloc];
}
#endif
@end


text:
using System;
using System.Collections.Generic;
using System.Globalization;

namespace Grpc.Core.Logging
{
    /// Logger that logs to System.Console.
    public class ConsoleLogger : TextWriterLogger
    {
        /// Creates a console logger not associated to any specific type.
        public ConsoleLogger() : this(null)
        {
        }

        /// Creates a console logger that logs messsage specific for given type.
        private ConsoleLogger(Type forType) : base(() => Console.Error, forType)
        {
        }

        ///
        /// Returns a logger associated with the specified type.
        ///
        public override ILogger ForType<T>()
        {
            if (typeof(T) == AssociatedType)
            {
                return this;
            }
            return new ConsoleLogger(typeof(T));
        }
    }
}


text:
package org.jenkins.plugins.appaloosa;

import hudson.model.Action;
import hudson.model.ProminentProjectAction;

public class AppaloosaBuildAction implements ProminentProjectAction {
    public String iconFileName;
    public String displayName;
    public String urlName;

    public AppaloosaBuildAction() {
    }

    public AppaloosaBuildAction(Action action) {
        iconFileName = action.getIconFileName();
        displayName = action.getDisplayName();
        urlName = action.getUrlName();
    }

    public String getIconFileName() {
        return iconFileName;
    }

    public String getDisplayName() {
        return displayName;
    }

    public String getUrlName() {
        return urlName;
    }
}


text:
#ifndef FS_H_
#define FS_H_

/**文件系统的文件名和路径+文件名的最大长度定义*/
#define FILENAME_MAX 256			// 最长文件名

typedef struct file_info
{
	char name[FILENAME_MAX];
	unsigned long size;
	unsigned int cluster;
	char detail;
}file_info;

/**初始化文件系统*/
void init_FS(void);

/**获得下一个簇号*/
unsigned int get_next_clu(unsigned int clu);

/**将簇号转换为LBA扇区寻址*/
unsigned int clu_to_sector(unsigned int clu_num);

/**加载数据*/
void load_data(void *buf, unsigned long clu);

/**获取元数据*/
unsigned int get_metadata(char *name);

/**FAT32读取文件函数*/
struct file_info fat32_read_file(unsigned long storage_number, unsigned long partition, const char *name, void *addr, char detail);

/**获取文件信息函数*/
file_info fat32_read_file_info(const char *name);

/**读取文件信息函数*/
struct file_info read_file_info(unsigned long storage_number, unsigned long partition, char *name);

/**读取文件函数*/
struct file_info read_file(unsigned long storage_number, unsigned long partition, char *name, void *addr, char detail);

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2022 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:interpolator/decelerate_quad">
	<translate android:fromYDelta="0" android:toYDelta="100%"
            android:duration="@android:integer/config_mediumAnimTime"/>
	<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
            android:duration="@android:integer/config_mediumAnimTime" />
</set>


text:
import time
from heapq import *

import debug
import historybuffer
import logsupport
import pygame
from logsupport import ConsoleError

Tasks = None

class EventItem(object):
	# basic event has name,dt, abstime,target (screen, proc, something - needed for hash)
	def __init__(self, gpid, name):
		self.gpid = gpid
		# self.delay = -1  # delay in seconds filled in when added to list
		self.abstime = 0  # set when added
		self.name = name
		self.deleted = False
		self.onlist = False

	def __hash__(self):
		return id(self)  # hash((self.delay, self.gpid, self.name))

	def __eq__(self, other):
		if other is None:
			return False
		return (self.abstime, self.gpid, self.name) == (
			other.abstime, other.gpid, other.name)

	def __ne__(self, other):
		return not (self == other)

	def __repr__(self):
		return 'ID:' + str(id(self)) + ' gpid: ' + str(self.gpid) + ' name: ' + self.name + ' del: ' + str(
			self.deleted) + ' onlist: ' + str(self.onlist) + ' abstm: ' + str(self.abstime)

	def OnList(self):
		return self.onlist

class ProcEventItem(EventItem):
	def __init__(self, gpid, name, proc):
		EventItem.__init__(self, gpid, name)
		self.proc = proc
		debug.debugPrint('EventList', ' Proc Item Created: ', self)

	def __repr__(self):
		return EventItem.__repr__(self) + ' Proc: ' + repr(self.proc)

class EventList(object):
	def __init__(self):
		self.BaseTime = 0
		self.List = []
		self.finder = {}
		self.TASKREADY = pygame.event.Event(pygame.USEREVENT, {})
		self.HB = historybuffer.HistoryBuffer(100, 'EventList')

	def StartLongOp(self):
		self.HB.Entry('StartLongOp')
		pygame.time.set_timer(self.TASKREADY.type, 0)

	def EndLongOp(self):
		nextdelay = self.TimeToNext()
		self.HB.Entry('EndLongOp Next: {}'.format(nextdelay))
		pygame.time.set_timer(self.TASKREADY.type, nextdelay)

	def PrettyTime(self, t):
		return t - self.BaseTime

	def PrettyList(self, inlist):
		plist = ''
		for t, item in enumerate(inlist):
			plist = plist + '\n--------------------' + str(t) + ' : ' + str(self.PrettyTime(item[0])) + str(item)
		return plist

	def RelNow(self):
		return time.time() - self.BaseTime

	def AddTask(self, evnt, dt):
		self.HB.Entry('AddTask: ' + repr(evnt) + ' DeltaT: ' + str(dt))
		if self.BaseTime == 0: self.BaseTime = time.time()

		self.finder[id(evnt)] = evnt
		skipadd = False
		for i in self.List:
			if i[1] == evnt:
				logsupport.Logs.Log("Event add task error: ", repr(evnt), severity=ConsoleError, hb=True)
				skipadd = True
		if not skipadd:
			evnt.abstime = time.time() + dt
			evnt.deleted = False
			evnt.onlist = True
			heappush(self.List, (evnt.abstime, evnt))
		T = self.TimeToNext()
		self.HB.Entry('Set next: {} delta {}'.format(time.time() + T, T))
		debug.debugPrint('EventList', self.RelNow(), ' Add: ', dt, evnt, T)
		# debug.debugPrint('EventList', self.RelNow(), ' Add: ', dt, item,T,self.PrettyList(self.List))
		pygame.time.set_timer(self.TASKREADY.type, T)

	def RemoveTask(self, evnt):
		self.HB.Entry('RemoveTask: ' + repr(evnt))
		debug.debugPrint('EventList', self.RelNow(), ' Remove: ', evnt)
		# noinspection PyBroadException
		try:
			self.finder[id(evnt)].deleted = True
		except Exception:
			self.HB.Entry('Not on List')
			debug.debugPrint('EventList', self.RelNow(), ' Remove item not on list: : ', evnt)

	def _TopItem(self):
		try:
			acttime, evnt = self.List[0]
			while evnt.deleted is True:
				debug.debugPrint('EventList', "PRE", self.List)
				debug.debugPrint('EventList', self.RelNow(), ' Flush deleted: ', evnt)
				heappop(self.List)
				evnt.onlist = False
				debug.debugPrint('EventList', "POST", self.List)
				try:
					del self.finder[id(evnt)]
				except KeyError:
					debug.debugPrint('EventList', self.RelNow(), 'Extra delete?', evnt)
				acttime, evnt = self.List[0]
			return acttime, evnt
		except IndexError:
			return None

	def TimeToNext(self):
		# time in milliseconds to next task
		T = self._TopItem()
		if T is not None:
			interval = max(int(round((T[0] - time.time()) * 1000)), 1)  # always at least 1 millisec if list non-empty
			self.HB.Entry('TimeToNext: Abs: {} Now: {} Delta: {}'.format(T[0], time.time(), interval))
			return interval
		else:
			self.HB.Entry('No TimeToNext')
			return 0

	def PopTask(self):
		epsilon = 0.01
		T = self._TopItem()
		if T is not None:
			DiffToSched = T[0] - time.time()
			if DiffToSched <= epsilon:  # task is due
				I = heappop(self.List)[1]
				I.onlist = False
				del self.finder[id(I)]
				nextdelay = self.TimeToNext()
				self.HB.Entry('PopTask: ' + str(time.time()) + ' Item: {} Next: {}'.format(repr(T), nextdelay))
				pygame.time.set_timer(self.TASKREADY.type, nextdelay)
				debug.debugPrint('EventList', self.RelNow(), ' Pop: ', I, ' Nextdelay: ', nextdelay)
				return I
			else:  # we are early for some reason so just repost a wakeup
				'''
				Note - early wakeups are likely when events happen close together in time.  set_timer actually sets
				a repeating timer so if 2 events are scheduled for essentially the same time, the time to next after the
				first of them will be very short and it is likely to tick a second time before the correct time to next
				is set by the second of the 2 close events.
				'''
				self.HB.Entry('PopTaskEarly: ' + repr(T) + ' Early: ' + str(DiffToSched))
				pygame.time.set_timer(self.TASKREADY.type, int(round(DiffToSched * 1000 + .5)))
				debug.debugPrint('EventList', self.RelNow(), ' Early wake: ', DiffToSched, self.PrettyList(self.List))
				return None
		else:
			self.HB.Entry('PopTask Empty')
			pygame.time.set_timer(self.TASKREADY.type, 0)  # there is no next item
			debug.debugPrint('EventList', self.RelNow(), ' Clear timer on list empty')
			return None

	def RemoveAllGrp(self, gpid):
		# remove all events where screen is this screen
		self.HB.Entry('RemoveGp: ' + repr(gpid))
		for e in self.finder.values():
			if e.gpid == gpid:
				self.RemoveTask(e)
		# print('Removed'+repr(e))


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>A-Index</title>
<meta name="date" content="2013-12-09">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N O P R S T U V W

A

About - Class in org.raspberrypi.cecil.view

About CECIL page.

About() - Constructor for class org.raspberrypi.cecil.view.About

assignment() - Method in class org.raspberrypi.cecil.model.grammar.CecilParser

AssignmentException - Exception in org.raspberrypi.cecil.model.grammar

CECIL Exception class that defines the incorrect assignment syntax exception

AssignmentException(String, int) - Constructor for exception org.raspberrypi.cecil.model.grammar.AssignmentException

Default parametric Constructor

A B C D E F G H I L M N O P R S T U V W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
/*
interact with packer. this parses packer's output. packer may be operated over
ssh in the future.
*/
package packer

import (
	"encoding/csv"
	"fmt"
	"io"
	"os/exec"
	"strconv"
	"strings"
	"time"
)

type ErrorOutput []Output

func (err ErrorOutput) Error() string { return fmt.Sprint([]Output(err)) }

func Command(name string, args ...string) *exec.Cmd {
	_args := []string{"-machine-readable", name}
	_args = append(_args, args...)
	return exec.Command("packer", args...)
}

func Run(cmd *exec.Cmd) ([]Output, error) {
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	d := NoUI(NewDecoder(stdout))

	err = cmd.Start()
	if err != nil {
		return nil, err
	}

	var outs []Output
	for {
		o, err := d.Decode()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
		outs = append(outs, o)
	}

	err = cmd.Wait()
	if err != nil {
		return outs, err
	}

	return outs, nil
}

func Validate(path string) error {
	outs, err := Run(Command("validate", path))
	if err != nil {
		return ErrorOutput(outs)
	}
	return nil
}

func Fix(path string) ([]Output, error) {
	outs, err := Run(Command("fix", path))
	if err != nil {
		return nil, ErrorOutput(outs)
	}
	return outs, nil
}

func Inspect(path string) ([]Output, error) {
	outs, err := Run(Command("inspect", path))
	if err != nil {
		return nil, ErrorOutput(outs)
	}
	return outs, nil
}

type Opts struct {
	Vars     []string
	Varfiles []string
	Only     []string
	Except   []string
}

func Build(packerfile string, opts Opts) ([]Output, error) {
	var args []string
	for i := range opts.Vars {
		args = append(args, "-var="+opts.Vars[i])
	}
	for i := range opts.Varfiles {
		args = append(args, "-var-file="+opts.Varfiles[i])
	}
	if len(opts.Only) > 0 {
		args = append(args, "-only="+strings.Join(opts.Only, ","))
	}
	if len(opts.Except) > 0 {
		args = append(args, "-except="+strings.Join(opts.Except, ","))
	}
	args = append(args, packerfile)

	outs, err := Run(Command("build", args...))
	if err != nil {
		return nil, ErrorOutput(outs)
	}

	return outs, nil
}

func NoUI(d Decoder) Decoder {
	return decoderFunc(func() (Output, error) {
		for {
			o, err := d.Decode()
			if err != nil {
				return o, err
			}
			if o.Type == "ui" {
				continue
			}
			return o, nil
		}
	})
}

type decoderFunc func() (Output, error)

func (fn decoderFunc) Decode() (Output, error) { return fn() }

type Decoder interface {
	Decode() (Output, error)
}

func NewDecoder(r io.Reader) Decoder {
	return &decoder{csv.NewReader(r)}
}

type decoder struct {
	r *csv.Reader
}

func (d *decoder) Decode() (Output, error) {
	var o Output
	row, err := d.r.Read()
	if err != nil {
		return o, err
	}
	switch len(row) {
	default:
		fallthrough
	case 4:
		o.Data = row[3]
		o.Data = strings.Replace(o.Data, `\r`, "\r", -1)
		o.Data = strings.Replace(o.Data, `\n`, "\n", -1)
		o.Data = strings.Replace(o.Data, `%!(PACKER_COMMA)`, ",", -1)
		fallthrough
	case 3:
		o.Type = row[2]
		fallthrough
	case 2:
		o.Target = row[1]
		fallthrough
	case 1:
		unix, err := strconv.ParseInt(row[0], 10, 64)
		if err != nil {
			return o, err
		}
		o.Time = time.Unix(unix, 0)
	case 0:
		panic("no columns")
	}
	return o, nil
}

type Output struct {
	Time   time.Time
	Target string
	Type   string
	Data   string
}