text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\Employee;
use AppBundle\Form\EmployeeType;

/**
 * Employee controller.
 *
 * @Route("/admin/employee")
 */
class EmployeeController extends Controller
{

    /**
     * Lists all Employee entities.
     *
     * @Route("/", name="admin_employee")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AppBundle:Employee')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Employee entity.
     *
     * @Route("/", name="admin_employee_create")
     * @Method("POST")
     * @Template("AppBundle:Employee:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Employee();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_employee_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Employee entity.
     *
     * @param Employee $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Employee $entity)
    {
        $form = $this->createForm(new EmployeeType(), $entity, array(
            'action' => $this->generateUrl('admin_employee_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Employee entity.
     *
     * @Route("/new", name="admin_employee_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Employee();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Employee entity.
     *
     * @Route("/{id}", name="admin_employee_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Employee')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Employee entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Employee entity.
     *
     * @Route("/{id}/edit", name="admin_employee_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Employee')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Employee entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Employee entity.
    *
    * @param Employee $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Employee $entity)
    {
        $form = $this->createForm(new EmployeeType(), $entity, array(
            'action' => $this->generateUrl('admin_employee_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Employee entity.
     *
     * @Route("/{id}", name="admin_employee_update")
     * @Method("PUT")
     * @Template("AppBundle:Employee:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Employee')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Employee entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('admin_employee_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Employee entity.
     *
     * @Route("/{id}", name="admin_employee_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AppBundle:Employee')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Employee entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_employee'));
    }

    /**
     * Creates a form to delete a Employee entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_employee_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
namespace Operations.Msmq
{
    using System;
    using System.Messaging;
    using System.Security.Principal;

    public static class QueueCreation
    {

        public static void Usage()
        {
            #region msmq-create-queues-endpoint-usage

            CreateQueuesForEndpoint(
                endpointName: "myendpoint",
                account: Environment.UserName);

            #endregion

            #region msmq-create-queues-shared-usage

            CreateQueue(
                queueName: "error",
                account: Environment.UserName);

            CreateQueue(
                queueName: "audit",
                account: Environment.UserName);

            #endregion
        }

        #region msmq-create-queues

        public static void CreateQueuesForEndpoint(string endpointName, string account)
        {
            //main queue
            CreateQueue(endpointName, account);

            //retries queue
            CreateQueue(endpointName + ".retries", account);

            //timeout queue
            CreateQueue(endpointName + ".timeouts", account);

            //timeout dispatcher queue
            CreateQueue(endpointName + ".timeoutsdispatcher", account);
        }

        public static void CreateQueue(string queueName, string account)
        {
            string path = string.Format(@"{0}\private$\{1}", Environment.MachineName, queueName);
            if (MessageQueue.Exists(path))
            {
                using (MessageQueue messageQueue = new MessageQueue(path))
                {
                    SetPermissionsForQueue(messageQueue, account);
                    return;
                }
            }
            using (MessageQueue messageQueue = MessageQueue.Create(path, true))
            {
                SetPermissionsForQueue(messageQueue, account);
            }
        }

        static void SetPermissionsForQueue(MessageQueue queue, string account)
        {
            AccessControlEntryType allow = AccessControlEntryType.Allow;
            queue.SetPermissions(AdminGroup, MessageQueueAccessRights.FullControl, allow);
            queue.SetPermissions(EveryoneGroup, MessageQueueAccessRights.WriteMessage, allow);
            queue.SetPermissions(AnonymousLogon, MessageQueueAccessRights.WriteMessage, allow);

            queue.SetPermissions(account, MessageQueueAccessRights.WriteMessage, allow);
            queue.SetPermissions(account, MessageQueueAccessRights.ReceiveMessage, allow);
            queue.SetPermissions(account, MessageQueueAccessRights.PeekMessage, allow);
        }

        static string AdminGroup = GetGroupName(WellKnownSidType.BuiltinAdministratorsSid);
        static string EveryoneGroup = GetGroupName(WellKnownSidType.WorldSid);
        static string AnonymousLogon = GetGroupName(WellKnownSidType.AnonymousSid);

        static string GetGroupName(WellKnownSidType wellKnownSidType)
        {
            return new SecurityIdentifier(wellKnownSidType, null)
                .Translate(typeof(NTAccount))
                .ToString();
        }

        #endregion
    }

}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/pinpoint/Pinpoint_EXPORTS.h>
#include <aws/pinpoint/model/Action.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Pinpoint
{
namespace Model
{

  /**
   *
Specifies channel-specific content and settings for a message template that
   * can be used in push notifications that are sent through the APNs (Apple Push
   * Notification service) channel.

See Also:
   AWS
   * API Reference

   */
  class AWS_PINPOINT_API APNSPushNotificationTemplate
  {
  public:
    APNSPushNotificationTemplate();
    APNSPushNotificationTemplate(Aws::Utils::Json::JsonView jsonValue);
    APNSPushNotificationTemplate& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The action to occur if a recipient taps a push notification that's based on
     * the message template. Valid values are:

OPEN_APP - Your app opens
     * or it becomes the foreground app if it was sent to the background. This is the
     * default action.

DEEP_LINK - Your app opens and displays a
     * designated user interface in the app. This setting uses the deep-linking
     * features of the iOS platform.

URL - The default mobile browser
     * on the recipient's device opens and loads the web page at a URL that you
     * specify.

     */
    inline const Action& GetAction() const{ return m_action; }

    /**
     *
The action to occur if a recipient taps a push notification that's based on
     * the message template. Valid values are:

OPEN_APP - Your app opens
     * or it becomes the foreground app if it was sent to the background. This is the
     * default action.

DEEP_LINK - Your app opens and displays a
     * designated user interface in the app. This setting uses the deep-linking
     * features of the iOS platform.

URL - The default mobile browser
     * on the recipient's device opens and loads the web page at a URL that you
     * specify.

     */
    inline bool ActionHasBeenSet() const { return m_actionHasBeenSet; }

    /**
     *
The action to occur if a recipient taps a push notification that's based on
     * the message template. Valid values are:

OPEN_APP - Your app opens
     * or it becomes the foreground app if it was sent to the background. This is the
     * default action.

DEEP_LINK - Your app opens and displays a
     * designated user interface in the app. This setting uses the deep-linking
     * features of the iOS platform.

URL - The default mobile browser
     * on the recipient's device opens and loads the web page at a URL that you
     * specify.

     */
    inline void SetAction(const Action& value) { m_actionHasBeenSet = true; m_action = value; }

    /**
     *
The action to occur if a recipient taps a push notification that's based on
     * the message template. Valid values are:

OPEN_APP - Your app opens
     * or it becomes the foreground app if it was sent to the background. This is the
     * default action.

DEEP_LINK - Your app opens and displays a
     * designated user interface in the app. This setting uses the deep-linking
     * features of the iOS platform.

URL - The default mobile browser
     * on the recipient's device opens and loads the web page at a URL that you
     * specify.

     */
    inline void SetAction(Action&& value) { m_actionHasBeenSet = true; m_action = std::move(value); }

    /**
     *
The action to occur if a recipient taps a push notification that's based on
     * the message template. Valid values are:

OPEN_APP - Your app opens
     * or it becomes the foreground app if it was sent to the background. This is the
     * default action.

DEEP_LINK - Your app opens and displays a
     * designated user interface in the app. This setting uses the deep-linking
     * features of the iOS platform.

URL - The default mobile browser
     * on the recipient's device opens and loads the web page at a URL that you
     * specify.

     */
    inline APNSPushNotificationTemplate& WithAction(const Action& value) { SetAction(value); return *this;}

    /**
     *
The action to occur if a recipient taps a push notification that's based on
     * the message template. Valid values are:

OPEN_APP - Your app opens
     * or it becomes the foreground app if it was sent to the background. This is the
     * default action.

DEEP_LINK - Your app opens and displays a
     * designated user interface in the app. This setting uses the deep-linking
     * features of the iOS platform.

URL - The default mobile browser
     * on the recipient's device opens and loads the web page at a URL that you
     * specify.

     */
    inline APNSPushNotificationTemplate& WithAction(Action&& value) { SetAction(std::move(value)); return *this;}

    /**
     *
The message body to use in push notifications that are based on the message
     * template.

     */
    inline const Aws::String& GetBody() const{ return m_body; }

    /**
     *
The message body to use in push notifications that are based on the message
     * template.

     */
    inline bool BodyHasBeenSet() const { return m_bodyHasBeenSet; }

    /**
     *
The message body to use in push notifications that are based on the message
     * template.

     */
    inline void SetBody(const Aws::String& value) { m_bodyHasBeenSet = true; m_body = value; }

    /**
     *
The message body to use in push notifications that are based on the message
     * template.

     */
    inline void SetBody(Aws::String&& value) { m_bodyHasBeenSet = true; m_body = std::move(value); }

    /**
     *
The message body to use in push notifications that are based on the message
     * template.

     */
    inline void SetBody(const char* value) { m_bodyHasBeenSet = true; m_body.assign(value); }

    /**
     *
The message body to use in push notifications that are based on the message
     * template.

     */
    inline APNSPushNotificationTemplate& WithBody(const Aws::String& value) { SetBody(value); return *this;}

    /**
     *
The message body to use in push notifications that are based on the message
     * template.

     */
    inline APNSPushNotificationTemplate& WithBody(Aws::String&& value) { SetBody(std::move(value)); return *this;}

    /**
     *
The message body to use in push notifications that are based on the message
     * template.

     */
    inline APNSPushNotificationTemplate& WithBody(const char* value) { SetBody(value); return *this;}

    /**
     *
The URL of an image or video to display in push notifications that are based
     * on the message template.

     */
    inline const Aws::String& GetMediaUrl() const{ return m_mediaUrl; }

    /**
     *
The URL of an image or video to display in push notifications that are based
     * on the message template.

     */
    inline bool MediaUrlHasBeenSet() const { return m_mediaUrlHasBeenSet; }

    /**
     *
The URL of an image or video to display in push notifications that are based
     * on the message template.

     */
    inline void SetMediaUrl(const Aws::String& value) { m_mediaUrlHasBeenSet = true; m_mediaUrl = value; }

    /**
     *
The URL of an image or video to display in push notifications that are based
     * on the message template.

     */
    inline void SetMediaUrl(Aws::String&& value) { m_mediaUrlHasBeenSet = true; m_mediaUrl = std::move(value); }

    /**
     *
The URL of an image or video to display in push notifications that are based
     * on the message template.

     */
    inline void SetMediaUrl(const char* value) { m_mediaUrlHasBeenSet = true; m_mediaUrl.assign(value); }

    /**
     *
The URL of an image or video to display in push notifications that are based
     * on the message template.

     */
    inline APNSPushNotificationTemplate& WithMediaUrl(const Aws::String& value) { SetMediaUrl(value); return *this;}

    /**
     *
The URL of an image or video to display in push notifications that are based
     * on the message template.

     */
    inline APNSPushNotificationTemplate& WithMediaUrl(Aws::String&& value) { SetMediaUrl(std::move(value)); return *this;}

    /**
     *
The URL of an image or video to display in push notifications that are based
     * on the message template.

     */
    inline APNSPushNotificationTemplate& WithMediaUrl(const char* value) { SetMediaUrl(value); return *this;}

    /**
     *
The raw, JSON-formatted string to use as the payload for push notifications
     * that are based on the message template. If specified, this value overrides all
     * other content for the message template.

     */
    inline const Aws::String& GetRawContent() const{ return m_rawContent; }

    /**
     *
The raw, JSON-formatted string to use as the payload for push notifications
     * that are based on the message template. If specified, this value overrides all
     * other content for the message template.

     */
    inline bool RawContentHasBeenSet() const { return m_rawContentHasBeenSet; }

    /**
     *
The raw, JSON-formatted string to use as the payload for push notifications
     * that are based on the message template. If specified, this value overrides all
     * other content for the message template.

     */
    inline void SetRawContent(const Aws::String& value) { m_rawContentHasBeenSet = true; m_rawContent = value; }

    /**
     *
The raw, JSON-formatted string to use as the payload for push notifications
     * that are based on the message template. If specified, this value overrides all
     * other content for the message template.

     */
    inline void SetRawContent(Aws::String&& value) { m_rawContentHasBeenSet = true; m_rawContent = std::move(value); }

    /**
     *
The raw, JSON-formatted string to use as the payload for push notifications
     * that are based on the message template. If specified, this value overrides all
     * other content for the message template.

     */
    inline void SetRawContent(const char* value) { m_rawContentHasBeenSet = true; m_rawContent.assign(value); }

    /**
     *
The raw, JSON-formatted string to use as the payload for push notifications
     * that are based on the message template. If specified, this value overrides all
     * other content for the message template.

     */
    inline APNSPushNotificationTemplate& WithRawContent(const Aws::String& value) { SetRawContent(value); return *this;}

    /**
     *
The raw, JSON-formatted string to use as the payload for push notifications
     * that are based on the message template. If specified, this value overrides all
     * other content for the message template.

     */
    inline APNSPushNotificationTemplate& WithRawContent(Aws::String&& value) { SetRawContent(std::move(value)); return *this;}

    /**
     *
The raw, JSON-formatted string to use as the payload for push notifications
     * that are based on the message template. If specified, this value overrides all
     * other content for the message template.

     */
    inline APNSPushNotificationTemplate& WithRawContent(const char* value) { SetRawContent(value); return *this;}

    /**
     *
The key for the sound to play when the recipient receives a push notification
     * that's based on the message template. The value for this key is the name of a
     * sound file in your app's main bundle or the Library/Sounds folder in your app's
     * data container. If the sound file can't be found or you specify default for the
     * value, the system plays the default alert sound.

     */
    inline const Aws::String& GetSound() const{ return m_sound; }

    /**
     *
The key for the sound to play when the recipient receives a push notification
     * that's based on the message template. The value for this key is the name of a
     * sound file in your app's main bundle or the Library/Sounds folder in your app's
     * data container. If the sound file can't be found or you specify default for the
     * value, the system plays the default alert sound.

     */
    inline bool SoundHasBeenSet() const { return m_soundHasBeenSet; }

    /**
     *
The key for the sound to play when the recipient receives a push notification
     * that's based on the message template. The value for this key is the name of a
     * sound file in your app's main bundle or the Library/Sounds folder in your app's
     * data container. If the sound file can't be found or you specify default for the
     * value, the system plays the default alert sound.

     */
    inline void SetSound(const Aws::String& value) { m_soundHasBeenSet = true; m_sound = value; }

    /**
     *
The key for the sound to play when the recipient receives a push notification
     * that's based on the message template. The value for this key is the name of a
     * sound file in your app's main bundle or the Library/Sounds folder in your app's
     * data container. If the sound file can't be found or you specify default for the
     * value, the system plays the default alert sound.

     */
    inline void SetSound(Aws::String&& value) { m_soundHasBeenSet = true; m_sound = std::move(value); }

    /**
     *
The key for the sound to play when the recipient receives a push notification
     * that's based on the message template. The value for this key is the name of a
     * sound file in your app's main bundle or the Library/Sounds folder in your app's
     * data container. If the sound file can't be found or you specify default for the
     * value, the system plays the default alert sound.

     */
    inline void SetSound(const char* value) { m_soundHasBeenSet = true; m_sound.assign(value); }

    /**
     *
The key for the sound to play when the recipient receives a push notification
     * that's based on the message template. The value for this key is the name of a
     * sound file in your app's main bundle or the Library/Sounds folder in your app's
     * data container. If the sound file can't be found or you specify default for the
     * value, the system plays the default alert sound.

     */
    inline APNSPushNotificationTemplate& WithSound(const Aws::String& value) { SetSound(value); return *this;}

    /**
     *
The key for the sound to play when the recipient receives a push notification
     * that's based on the message template. The value for this key is the name of a
     * sound file in your app's main bundle or the Library/Sounds folder in your app's
     * data container. If the sound file can't be found or you specify default for the
     * value, the system plays the default alert sound.

     */
    inline APNSPushNotificationTemplate& WithSound(Aws::String&& value) { SetSound(std::move(value)); return *this;}

    /**
     *
The key for the sound to play when the recipient receives a push notification
     * that's based on the message template. The value for this key is the name of a
     * sound file in your app's main bundle or the Library/Sounds folder in your app's
     * data container. If the sound file can't be found or you specify default for the
     * value, the system plays the default alert sound.

     */
    inline APNSPushNotificationTemplate& WithSound(const char* value) { SetSound(value); return *this;}

    /**
     *
The title to use in push notifications that are based on the message
     * template. This title appears above the notification message on a recipient's
     * device.

     */
    inline const Aws::String& GetTitle() const{ return m_title; }

    /**
     *
The title to use in push notifications that are based on the message
     * template. This title appears above the notification message on a recipient's
     * device.

     */
    inline bool TitleHasBeenSet() const { return m_titleHasBeenSet; }

    /**
     *
The title to use in push notifications that are based on the message
     * template. This title appears above the notification message on a recipient's
     * device.

     */
    inline void SetTitle(const Aws::String& value) { m_titleHasBeenSet = true; m_title = value; }

    /**
     *
The title to use in push notifications that are based on the message
     * template. This title appears above the notification message on a recipient's
     * device.

     */
    inline void SetTitle(Aws::String&& value) { m_titleHasBeenSet = true; m_title = std::move(value); }

    /**
     *
The title to use in push notifications that are based on the message
     * template. This title appears above the notification message on a recipient's
     * device.

     */
    inline void SetTitle(const char* value) { m_titleHasBeenSet = true; m_title.assign(value); }

    /**
     *
The title to use in push notifications that are based on the message
     * template. This title appears above the notification message on a recipient's
     * device.

     */
    inline APNSPushNotificationTemplate& WithTitle(const Aws::String& value) { SetTitle(value); return *this;}

    /**
     *
The title to use in push notifications that are based on the message
     * template. This title appears above the notification message on a recipient's
     * device.

     */
    inline APNSPushNotificationTemplate& WithTitle(Aws::String&& value) { SetTitle(std::move(value)); return *this;}

    /**
     *
The title to use in push notifications that are based on the message
     * template. This title appears above the notification message on a recipient's
     * device.

     */
    inline APNSPushNotificationTemplate& WithTitle(const char* value) { SetTitle(value); return *this;}

    /**
     *
The URL to open in the recipient's default mobile browser, if a recipient
     * taps a push notification that's based on the message template and the value of
     * the Action property is URL.

     */
    inline const Aws::String& GetUrl() const{ return m_url; }

    /**
     *
The URL to open in the recipient's default mobile browser, if a recipient
     * taps a push notification that's based on the message template and the value of
     * the Action property is URL.

     */
    inline bool UrlHasBeenSet() const { return m_urlHasBeenSet; }

    /**
     *
The URL to open in the recipient's default mobile browser, if a recipient
     * taps a push notification that's based on the message template and the value of
     * the Action property is URL.

     */
    inline void SetUrl(const Aws::String& value) { m_urlHasBeenSet = true; m_url = value; }

    /**
     *
The URL to open in the recipient's default mobile browser, if a recipient
     * taps a push notification that's based on the message template and the value of
     * the Action property is URL.

     */
    inline void SetUrl(Aws::String&& value) { m_urlHasBeenSet = true; m_url = std::move(value); }

    /**
     *
The URL to open in the recipient's default mobile browser, if a recipient
     * taps a push notification that's based on the message template and the value of
     * the Action property is URL.

     */
    inline void SetUrl(const char* value) { m_urlHasBeenSet = true; m_url.assign(value); }

    /**
     *
The URL to open in the recipient's default mobile browser, if a recipient
     * taps a push notification that's based on the message template and the value of
     * the Action property is URL.

     */
    inline APNSPushNotificationTemplate& WithUrl(const Aws::String& value) { SetUrl(value); return *this;}

    /**
     *
The URL to open in the recipient's default mobile browser, if a recipient
     * taps a push notification that's based on the message template and the value of
     * the Action property is URL.

     */
    inline APNSPushNotificationTemplate& WithUrl(Aws::String&& value) { SetUrl(std::move(value)); return *this;}

    /**
     *
The URL to open in the recipient's default mobile browser, if a recipient
     * taps a push notification that's based on the message template and the value of
     * the Action property is URL.

     */
    inline APNSPushNotificationTemplate& WithUrl(const char* value) { SetUrl(value); return *this;}

  private:

    Action m_action;
    bool m_actionHasBeenSet = false;

    Aws::String m_body;
    bool m_bodyHasBeenSet = false;

    Aws::String m_mediaUrl;
    bool m_mediaUrlHasBeenSet = false;

    Aws::String m_rawContent;
    bool m_rawContentHasBeenSet = false;

    Aws::String m_sound;
    bool m_soundHasBeenSet = false;

    Aws::String m_title;
    bool m_titleHasBeenSet = false;

    Aws::String m_url;
    bool m_urlHasBeenSet = false;
  };

} // namespace Model
} // namespace Pinpoint
} // namespace Aws


text:
/*
 * Copyright (C) 2021-present ScyllaDB
 */

#pragma once

#include <seastar/core/coroutine.hh>

namespace seastar {

namespace internal {

struct exception_awaiter {
    std::exception_ptr eptr;

    explicit exception_awaiter(std::exception_ptr&& eptr) noexcept : eptr(std::move(eptr)) {}

    exception_awaiter(const exception_awaiter&) = delete;
    exception_awaiter(exception_awaiter&&) = delete;

    bool await_ready() const noexcept {
        return false;
    }

    template<typename U>
    void await_suspend(SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<U> hndl) noexcept {
        hndl.promise().set_exception(std::move(eptr));
        hndl.destroy();
    }

    void await_resume() noexcept {}
};

} // internal

namespace coroutine {

/// Wrapper for propagating an exception directly rather than
/// throwing it. The wrapper can be used with both co_await and co_return.
///
/// \note It is not possible to co_return the wrapper in coroutines which
/// return future<> due to language limitations (it's not possible to specify
/// both return_value and return_void in the promise_type). You can use co_await
/// instead which works in coroutines which return either future<> or future<T>.
///
/// Example usage:
///
/// ```
/// co_await coroutine::exception(std::make_exception_ptr(std::runtime_error("something failed miserably")));
/// co_return coroutine::exception(std::make_exception_ptr(std::runtime_error("something failed miserably")));
/// ```
struct exception {
    std::exception_ptr eptr;
    explicit exception(std::exception_ptr eptr) noexcept : eptr(std::move(eptr)) {}
};

/// Allows propagating an exception from a coroutine directly rather than
/// throwing it.
///
/// `make_exception()` returns an object which must be co_returned.
/// Co_returning the object will immediately resolve the current coroutine
/// to the given exception.
///
/// \note Due to language limitations, this function doesn't work in coroutines
/// which return future<>. Consider using return_exception instead.
///
/// Example usage:
///
/// ```
/// co_return coroutine::make_exception(std::runtime_error("something failed miserably"));
/// ```
[[deprecated("Use co_await coroutine::return_exception or co_return coroutine::exception instead")]]
[[nodiscard]]
inline exception make_exception(std::exception_ptr ex) noexcept {
    return exception(std::move(ex));
}

template<typename T>
[[deprecated("Use co_await coroutine::return_exception or co_return coroutine::exception instead")]]
[[nodiscard]]
exception make_exception(T&& t) noexcept {
    log_exception_trace();
    return exception(std::make_exception_ptr(std::forward<T>(t)));
}

/// Allows propagating an exception from a coroutine directly rather than
/// throwing it.
///
/// `return_exception()` returns an object which must be co_awaited.
/// Co_awaiting the object will immediately resolve the current coroutine
/// to the given exception.
///
/// Example usage:
///
/// ```
/// co_await coroutine::return_exception(std::runtime_error("something failed miserably"));
/// ```
[[nodiscard]]
inline exception return_exception_ptr(std::exception_ptr ex) noexcept {
    return exception(std::move(ex));
}

[[deprecated("Use co_await coroutine::return_exception_ptr instead")]]
[[nodiscard]]
inline exception return_exception(std::exception_ptr ex) noexcept {
    return exception(std::move(ex));
}

template<typename T>
[[nodiscard]]
exception return_exception(T&& t) noexcept {
    log_exception_trace();
    return exception(std::make_exception_ptr(std::forward<T>(t)));
}

} // coroutine

inline auto operator co_await(coroutine::exception ex) noexcept {
    return internal::exception_awaiter(std::move(ex.eptr));
}

} // seastar


text:
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- As the add_tracker_menu content view, the view below consumes the entire
      space available using match_parent in both dimensions. -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent"
            android:foreground="?android:windowContentOverlay" />

        <include layout="@layout/toolbar" />

    </FrameLayout>

</android.support.v4.widget.DrawerLayout>


text:
from build.management.commands.base_build import Command as BaseBuild
from django.conf import settings
from django.db import connection
from django.db.models import Count

from protein.models import Protein, ProteinConformation, ProteinAnomaly, ProteinState, ProteinSegment
from residue.models import Residue, ResidueGenericNumber
from structure.models import *

from collections import OrderedDict
import os
import logging
import sys
from datetime import datetime, date
import traceback
import yaml
import pprint

class Command(BaseBuild):
    help = 'Build automated chimeric GPCR homology models'

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser=parser)
        parser.add_argument('--verbose', help='Print specific outliers', default=False, action='store_true')

    def handle(self, *args, **options):
        structures = Structure.objects.all().prefetch_related('protein_conformation__protein__parent','pdb_code').annotate(dc=Count('distances'))
        structures_with_issue = []
        missing_helices = {}
        segments_query_obj = ProteinSegment.objects.filter(proteinfamily="GPCR")
        all_gns = set(ResidueGenericNumber.objects.filter(scheme__slug='gpcrdb').all().values_list('label',flat=True))
        # print(all_gns)
        missing_gns_count = OrderedDict()
        # raise
        with open(os.sep.join([settings.DATA_DIR, 'structure_data','annotation','xtal_segends.yaml']), 'r') as anno_f:
            annotations = yaml.load(anno_f, Loader=yaml.FullLoader)
        for s in structures:
            resis = Residue.objects.filter(protein_conformation=s.protein_conformation).prefetch_related('display_generic_number','protein_segment')
            wt_resis = Residue.objects.filter(protein_conformation__protein=s.protein_conformation.protein.parent)

            wt_gn = wt_resis.exclude(display_generic_number=None).count()
            s_gn = resis.exclude(display_generic_number=None).count()
            fraction = s_gn / wt_gn

            s_gns = set(resis.exclude(display_generic_number=None).all().values_list('generic_number__label',flat=True))
            missing_gns = all_gns-s_gns
            for gn in missing_gns:
                if gn not in missing_gns_count:
                    missing_gns_count[gn] = {'count':0, 'pdbs' : []}
                missing_gns_count[gn]['count'] += 1
                missing_gns_count[gn]['pdbs'].append(str(s))

            print(s,"distances",s.dc,"WT residues",wt_resis.count(),"PDB residues",resis.count(),"WT GNs",wt_gn,"PDB GNs",s_gn,"Fraction",fraction)
            # print('missing gns',missing_gns)
            c = 0
            segments = OrderedDict((i,[]) for i in segments_query_obj)
            x50s = [i.display_generic_number.label for i in resis.filter(display_generic_number__label__in=['1.50x50', '2.50x50', '3.50x50', '4.50x50', '5.50x50', '6.50x50', '7.50x50'])]
            parent_x50_resis = Residue.objects.filter(protein_conformation__protein=s.protein_conformation.protein.parent,
                                                      display_generic_number__label__in=['1.50x50', '2.50x50', '3.50x50', '4.50x50', '5.50x50', '6.50x50', '7.50x50']).prefetch_related('display_generic_number')
            missing_helices[s] = []
            missing_a_helix = False
            for x in ['1.50x50', '2.50x50', '3.50x50', '4.50x50', '5.50x50', '6.50x50', '7.50x50']:
                if x not in x50s:
                    TMb = annotations[s.protein_conformation.protein.parent.entry_name+'_'+s.pdb_code.index][x[0]+'b']
                    TMe = annotations[s.protein_conformation.protein.parent.entry_name+'_'+s.pdb_code.index][x[0]+'e']
                    if TMe=='-':
                        continue
                    if s.pdb_code.index=='4L6R' and x=='4.50x50' and TMb==274:
                        continue
                    if TMe>parent_x50_resis.get(display_generic_number__label=x).sequence_number:
                        missing_helices[s].append(x)
                        missing_a_helix = True

            if not missing_a_helix:
                del missing_helices[s]
            else:
                print(s.pdb_code.index,'missing',missing_helices[s])
            for r in resis:
                if c==0:
                    this_segment = r.protein_segment
                if this_segment==None:
                    continue
                if r.protein_segment==None:
                    if len(Fragment.objects.filter(residue=r))==0 and s not in structures_with_issue:
                        structures_with_issue.append(s)
                    continue
                if len(segments[r.protein_segment])>0:
                    if r.sequence_number-segments[r.protein_segment][-1]>400:
                        if options['verbose']:
                            print('Outlier: {} {} {} following {}'.format(s, r.protein_segment, r.sequence_number, segments[r.protein_segment][-1]))
                        if s not in structures_with_issue:
                            structures_with_issue.append(s)
                    else:
                        segments[r.protein_segment].append(r.sequence_number)
                else:
                    segments[r.protein_segment].append(r.sequence_number)
                c+=1

        cut_off = 10
        print("=== GN PDBS MISSING, PDB list === CUTOFF", cut_off)
        missing_gns_count = OrderedDict(sorted(missing_gns_count.items(), key=lambda t: t[1]['count']))
        #missing_gns_count = OrderedDict(sorted(missing_gns_count.items(), key=lambda x: x['count']))
        pdbs_with_low_occuring_missing = OrderedDict()
        for m, v in missing_gns_count.items():
            if cut_off>10: break
            print(m,v['count'],v['pdbs'])
            for pdb in v['pdbs']:
                if pdb not in pdbs_with_low_occuring_missing:
                    pdbs_with_low_occuring_missing[pdb] = {'count':0,'gns':[]}
                pdbs_with_low_occuring_missing[pdb]['count'] += 1
                pdbs_with_low_occuring_missing[pdb]['gns'].append(m)

        print("=== MAIN PDB CULPRITS ===")
        pdbs_with_low_occuring_missing = OrderedDict(sorted(pdbs_with_low_occuring_missing.items(), key=lambda t: -t[1]['count']))
        for pdb, v in pdbs_with_low_occuring_missing.items():
            print(pdb,v)
        #print(pdbs_with_low_occuring_missing)
        #print(missing_gns_count)

        if len(missing_helices)>0 or len(structures_with_issue)>0:
            print_out = 'Missing helices: '+missing_helices+'\n'+'Structures with issue: '+structures_with_issue
        else:
            print_out = 'No structure residue issues detected'
        self.logger.info('Check structure residues: '+print_out)


text:
import { Observable } from 'rxjs/Observable';
import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  HostListener,
  Input,
  OnInit,
  OnDestroy,
  Output,
  ViewChild,
  ViewChildren,
  QueryList
} from '@angular/core';
import {
  animate,
  state,
  style,
  transition,
  trigger
} from '@angular/animations';
import { ActivatedRoute, Params, NavigationExtras } from '@angular/router';
import { Location }               from '@angular/common';
import { Router }                 from '@angular/router';
import { FormGroup } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';

import { cloneDeep, trimEnd, merge, remove } from 'lodash';
import { Space, Spaces } from 'ngx-fabric8-wit';
import { Broadcaster, Logger } from 'ngx-base';
import {
  AuthenticationService,
  User,
  UserService
} from 'ngx-login-client';

import { AreaUI } from '../../models/area.model';
import { IterationModel, IterationUI } from './../../models/iteration.model';
import { LabelSelectorComponent } from './../../components/label-selector/label-selector.component';
import { MarkdownControlComponent } from './../../components/markdown-control/markdown-control.component';
import { TypeaheadDropdown, TypeaheadDropdownValue } from './../../components/typeahead-dropdown/typeahead-dropdown.component';

import { CommentUI } from './../../models/comment';
import { WorkItem, WorkItemUI, WorkItemRelations } from '../../models/work-item';
import { UserUI } from '../../models/user';
import { LabelUI } from '../../models/label.model';
import { AssigneeSelectorComponent } from './../../components/assignee-selector/assignee-selector.component';
import { WorkItemService } from './../../services/work-item.service';

import {
  SelectDropdownComponent
} from './../../widgets/select-dropdown/select-dropdown.component';

//ngrx stuff
import { Store } from '@ngrx/store';
import { AppState } from './../../states/app.state';
import * as CommentActions from './../../actions/comment.actions';
import * as LinkTypeActions from './../../actions/link-type.actions';

@Component({
  selector: 'work-item-preview',
  templateUrl: './work-item-quick-preview.component.html',
  styleUrls: ['./work-item-quick-preview.component.less'],
  animations: [
    trigger('slideInOut', [
      state('in', style({
        transform: 'translateX(5px)',
        left: 'auto'
      })),
      state('out', style({
        transform: 'translateX(100%)',
        left: '100%'
      })),
      transition('in => out', animate('200ms ease-in-out')),
      transition('out => in', animate('200ms ease-in-out'))
    ]),
  ]
})

export class WorkItemQuickPreviewComponent implements OnInit, OnDestroy {

  @ViewChild('title') title: any;
  @ViewChild('userList') userList: any;
  @ViewChild('dropdownButton') dropdownButton: any;
  @ViewChild('areaSelectbox') areaSelectbox: TypeaheadDropdown;
  @ViewChild('iterationSelectbox') iterationSelectbox: TypeaheadDropdown;
  @ViewChild('labelSelector') labelSelector: LabelSelectorComponent;
  @ViewChild('assignee') assignee : any;
  @ViewChild('labelname') labelnameInput: ElementRef;
  @ViewChild('dropdown') dropdownRef: SelectDropdownComponent;
  @ViewChild('AssigneeSelector') AssigneeSelector: AssigneeSelectorComponent;
  @Input() selectedLabels: LabelUI[] = [];
  @Input() selectedAssignees: User[] = [];

  @Output() onOpenSelector: EventEmitter<any> = new EventEmitter();
  @Output() onCloseSelector: EventEmitter<LabelUI[]> = new EventEmitter();

  private spaceSource = this.store
    .select('listPage')
    .select('space')
    .filter(s => !!s);
  private areaSource = this.store
    .select('listPage')
    .select('areas')
    .filter(a => !!a);
  private iterationSource = this.store
    .select('listPage')
    .select('iterations')
    .filter(i => !!i.length);
  private labelSource = this.store
    .select('listPage')
    .select('labels')
    .filter(l => !!l.length);
  private collaboratorSource = this.store
    .select('listPage')
    .select('collaborators')
    .filter(c => !!c.length);
  private workItemStateSource = this.store
    .select('listPage')
    .select('workItemStates')
    .filter(wis => !!wis.length);
  private workItemCommentSource = this.store
    .select('detailPage')
    .select('comments');

  private collaborators: UserUI[] = [];
  private areasUI: AreaUI[] = [];
  private iterationUI: IterationUI[] = [];
  private workItem: WorkItemUI;
  private loggedIn: Boolean = false;
  private headerEditable: Boolean = false;
  private searchAssignee: Boolean = false;
  private loggedInUser: User;
  private panelState: string = 'out';
  private areas: TypeaheadDropdownValue[] = [];
  private iterations: TypeaheadDropdownValue[] = [];
  private eventListeners: any[] = [];
  private queryParams: Object = {};
  private labels: LabelUI[] = [];
  private workItemStates: string[] = [];
  private comments: CommentUI[] = [];

  private activeAddAssignee: boolean = false;
  private searchValue: string = '';

  constructor(
    private auth: AuthenticationService,
    private broadcaster: Broadcaster,
    private route: ActivatedRoute,
    private location: Location,
    private logger: Logger,
    private router: Router,
    private spaces: Spaces,
    private store: Store<AppState>,
    private userService: UserService,
    private workItemService: WorkItemService
  ) {}

  @HostListener('document:click', ['$event.target','$event.target.classList.contains('+'"assigned_user"'+')'])
  public onClick(targetElement,assigned_user) {
    if (this.assignee) {
      const clickedInsidePopup = this.assignee.nativeElement.contains(targetElement);
      if (!clickedInsidePopup&&!assigned_user) {
          this.cancelAssignment();
      }
    }
  }

  ngOnInit(): void {
    this.loggedIn = this.auth.isLoggedIn();
    this.listenToEvents();

    Observable.combineLatest(
      this.spaceSource,
      this.areaSource,
      this.iterationSource,
      this.labelSource,
      this.collaboratorSource,
      this.workItemStateSource
    ).take(1).subscribe(([
      spaceSource,
      areaSource,
      iterationSource,
      labelSource,
      collaboratorSource,
      workItemStateSource
    ]) => {
      this.collaborators = [...collaboratorSource];
      this.areasUI = [...areaSource];
      this.iterationUI = [...iterationSource];
      this.labels = [...labelSource];
      this.workItemStates = [...workItemStateSource];
      this.workItemCommentSource.subscribe(comments => {
        this.comments = [...comments];
      })
    })
  }

  ngOnDestroy() {
    console.log('Destroying all the listeners in detail component');
    this.eventListeners.forEach(subscriber => subscriber.unsubscribe());
  }

  openPreview(workitem) {
    if (!workitem) return;
    this.workItem = workitem;
    this.areas = this.extractAreaKeyValue(this.areasUI);
    this.iterations = this.extractIterationKeyValue(this.iterationUI);
    this.store.dispatch(new CommentActions.Get(this.workItem.commentLink));
    this.store.dispatch(new LinkTypeActions.Get());
    this.panelState = 'in';
  }

  closePreview() {
    this.panelState = 'out';
    this.eventListeners.forEach(subscriber => subscriber.unsubscribe());
    setTimeout(() => {
      this.workItem = null;
    }, 400);
  }

  showPreview(event: any): void {
    const rawText = event.rawText;
    const callBack = event.callBack;
    this.workItemService.renderMarkDown(rawText)
      .subscribe(renderedHtml => {
        callBack(
          rawText,
          renderedHtml
        );
      })
  }

  closeHeader(): void {
    this.headerEditable = false;
  }

  closeDetails(): void {

  }

  listenToEvents() {
    this.eventListeners.push(
      this.broadcaster.on<string>('logout')
        .subscribe(message => {
          this.loggedIn = false;
          this.loggedInUser = null;
      })
    );
    if (this.loggedIn) {
      this.eventListeners.push(
        this.userService.loggedInUser.subscribe(user => {
          this.loggedInUser = user;
        })
      );
    }
    let id = null;
    this.eventListeners.push(
      this.spaces.current.subscribe(space => {
        this.closePreview();
      })
    );
  }

  preventDef(event: any) {
    event.preventDefault();
  }

  activeSearchAssignee() {
  }

  cancelAssignment(): void {
    this.searchAssignee = false;
  }

  closeUserRestFields(): void {
    this.searchAssignee = false;
    if (this.workItem && this.workItem.id != null) {
      this.headerEditable = false;
    }
    if (this.areaSelectbox && this.areaSelectbox.isOpen()) {
      this.areaSelectbox.close();
    }
    if (this.iterationSelectbox && this.iterationSelectbox.isOpen()) {
      this.iterationSelectbox.close();
    }
  }

  extractAreaKeyValue(areas: AreaUI[]): TypeaheadDropdownValue[] {
    let result: TypeaheadDropdownValue[] = [];
    let selectedFound: boolean = false;
    let selectedAreaId: string;
    if (this.workItem.area && this.workItem.area.id) {
      selectedAreaId = this.workItem.area.id;
    }
    for (let i=0; i<areas.length; i++) {
      result.push({
        key: areas[i].id,
        value: (areas[i].parentPathResolved !== '/' ? areas[i].parentPathResolved:'') + '/' + areas[i].name,
        selected: selectedAreaId === areas[i].id ? true : false,
        cssLabelClass: undefined
      });
      if (selectedAreaId === areas[i].id) {
        selectedFound = true;
      }
    };
    return result;
  }

  extractIterationKeyValue(iterations: IterationUI[]): TypeaheadDropdownValue[] {
    let result: TypeaheadDropdownValue[] = [];
    let selectedFound: boolean = false;
    let selectedIterationId;
    if (this.workItem.iteration && this.workItem.iteration.id) {
      selectedIterationId = this.workItem.iteration.id;
    }
    for (let i=0; i<iterations.length; i++) {
      result.push({
        key: iterations[i].id,
        value: (iterations[i].resolvedParentPath !== '/' ? iterations[i].resolvedParentPath:'') + '/' + iterations[i].name,
        selected: selectedIterationId === iterations[i].id ? true : false,
        cssLabelClass: undefined
      });
      if (selectedIterationId === iterations[i].id) {
        selectedFound = true;
      }
    };
    return result;
  }

  focusArea() {
    this.iterationSelectbox.close();
    this.cancelAssignment();
    this.areas = [
      ...this.areas,
      {
        key: '0',
        value: '',
        selected: false,
        cssLabelClass: 'spinner spinner-sm spinner-inline'
      }
    ];
    this.areas = this.extractAreaKeyValue(this.areasUI);
  }

  focusIteration() {
    this.areaSelectbox.close();
    this.cancelAssignment();
    this.iterations = [
      ...this.iterations,
      {
        key: '0',
        value: '',
        selected: false,
        cssLabelClass: 'spinner spinner-sm spinner-inline'
      }
    ];
    this.iterations = this.extractIterationKeyValue(this.iterationUI);
  }

  constructUrl(workItem: WorkItem) {
    return this.router.url.split('plan')[0] + 'plan/detail/' + workItem.number;
  }

  onLabelClick(event) {
    let params = {
      label: event.attributes.name
    }
    // Prepare navigation extra with query params
    let navigationExtras: NavigationExtras = {
      queryParams: params
    };

    // Navigated to filtered view
    this.router.navigate([], navigationExtras);
  }

  createComment(event: any) {
    const payload = {
      url: this.workItem.commentLink,
      comment: event
    };
    this.store.dispatch(new CommentActions.Add(payload));
  }

  updateComment(comment) {
    this.store.dispatch(new CommentActions.Update(comment));
  }

  deleteComment(event: any) {
    this.store.dispatch(new CommentActions.Delete(event));
  }

  @HostListener('window:keydown', ['$event'])
  onKeyEvent(event: any) {
    event = (event || window.event);
    // for ESC key handling
    if (event.keyCode == 27) {
      try {
        event.preventDefault(); //Non-IE
      } catch (x){
        event.returnValue = false; //IE
      }
      if (this.headerEditable) {
        this.closeHeader();
      } else if (this.searchAssignee) {
        this.searchAssignee = false;
      } else if (this.areaSelectbox && this.areaSelectbox.isOpen()) {
        this.areaSelectbox.close();
      } else if (this.iterationSelectbox && this.iterationSelectbox.isOpen()) {
        this.iterationSelectbox.close();
    } else {
        this.closePreview();
      }
    }
  }
  onOpen(event) {
    this.onOpenSelector.emit('open');
  }

  onClose(event) {
    this.onCloseSelector.emit(cloneDeep(this.selectedLabels));
  }

  openDropdown() {
    this.dropdownRef.openDropdown();
  }

  closeDropdown() {
    this.dropdownRef.closeDropdown();
  }
  closeAddAssignee() {
    this.activeAddAssignee = false;
  }
}


text:
<?php

class Comments extends CI_Controller{
    public function index(){
        $this->load->view('administration/partials/header');
        $this->load->view('administration/comments/index');
        $this->load->view('administration/partials/footer');
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Package com.hazelcast.collection.list (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<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

Next

Frames

No Frames

All Classes

Uses of Package
com.hazelcast.collection.list

Packages that use com.hazelcast.collection.list

Package
Description

com.hazelcast.collection

This package contains classes related to Collections (IList,ISet etc..)

com.hazelcast.collection.list

This package contains IList functionality for Hazelcast.

com.hazelcast.collection.txn

This package contains the Transaction behavior for the Collections.

Classes in com.hazelcast.collection.list used by com.hazelcast.collection

Class and Description

ListContainer

Classes in com.hazelcast.collection.list used by com.hazelcast.collection.list

Class and Description

ListContainer

ListService

Classes in com.hazelcast.collection.list used by com.hazelcast.collection.txn

Class and Description

ListService

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Hazelcast, Inc.. All Rights Reserved.


text:
<resources>
    <string name="app_name">C3_self_04_ToggleView</string>
</resources>


text:
package handler

import (
	"fmt"
	"log"
	"net/http"
	"net/url"

	"github.com/drone/drone/pkg/database"
	. "github.com/drone/drone/pkg/model"
)

// ErrorHandler wraps the default http.HandleFunc to handle an
// error as the return value.
type ErrorHandler func(w http.ResponseWriter, r *http.Request) error

func (h ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if err := h(w, r); err != nil {
		log.Print(err)
	}
}

// UserHandler wraps the default http.HandlerFunc to include
// the currently authenticated User in the method signature,
// in addition to handling an error as the return value.
type UserHandler func(w http.ResponseWriter, r *http.Request, user *User) error

func (h UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	user, err := readUser(r)
	if err != nil {
		redirectLogin(w, r)
		return
	}

	if err = h(w, r, user); err != nil {
		log.Print(err)
		RenderError(w, err, http.StatusBadRequest)
	}
}

// AdminHandler wraps the default http.HandlerFunc to include
// the currently authenticated User in the method signature,
// in addition to handling an error as the return value. It also
// verifies the user has Administrative priveleges.
type AdminHandler func(w http.ResponseWriter, r *http.Request, user *User) error

func (h AdminHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	user, err := readUser(r)
	if err != nil {
		redirectLogin(w, r)
		return
	}

	// User MUST have administrative priveleges in order
	// to execute the handler.
	if user.Admin == false {
		RenderNotFound(w)
		return
	}

	if err = h(w, r, user); err != nil {
		log.Print(err)
		RenderError(w, err, http.StatusBadRequest)
	}
}

// RepoHandler wraps the default http.HandlerFunc to include
// the currently authenticated User and requested Repository
// in the method signature, in addition to handling an error
// as the return value.
type RepoHandler func(w http.ResponseWriter, r *http.Request, user *User, repo *Repo) error

func (h RepoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	user, err := readUser(r)
	if err != nil {
		redirectLogin(w, r)
		return
	}

	// repository name from the URL parameters
	hostParam := r.FormValue(":host")
	userParam := r.FormValue(":owner")
	nameParam := r.FormValue(":name")
	repoName := fmt.Sprintf("%s/%s/%s", hostParam, userParam, nameParam)

	repo, err := database.GetRepoSlug(repoName)
	if err != nil {
		RenderNotFound(w)
		return
	}

	// The User must own the repository OR be a member
	// of the Team that owns the repository.
	if user.ID != repo.UserID {
		if member, _ := database.IsMember(user.ID, repo.TeamID); !member {
			RenderNotFound(w)
			return
		}
	}

	if err = h(w, r, user, repo); err != nil {
		log.Print(err)
		RenderError(w, err, http.StatusBadRequest)
	}
}

// RepoHandler wraps the default http.HandlerFunc to include
// the currently authenticated User and requested Repository
// in the method signature, in addition to handling an error
// as the return value.
type RepoAdminHandler func(w http.ResponseWriter, r *http.Request, user *User, repo *Repo) error

func (h RepoAdminHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	user, err := readUser(r)
	if err != nil {
		redirectLogin(w, r)
		return
	}

	// repository name from the URL parameters
	hostParam := r.FormValue(":host")
	userParam := r.FormValue(":owner")
	nameParam := r.FormValue(":name")
	repoName := fmt.Sprintf("%s/%s/%s", hostParam, userParam, nameParam)

	repo, err := database.GetRepoSlug(repoName)
	if err != nil {
		RenderNotFound(w)
		return
	}

	// The User must own the repository OR be a member
	// of the Team that owns the repository.
	if user.ID != repo.UserID {
		if admin, _ := database.IsMemberAdmin(user.ID, repo.TeamID); admin == false {
			RenderNotFound(w)
			return
		}
	}

	if err = h(w, r, user, repo); err != nil {
		log.Print(err)
		RenderError(w, err, http.StatusBadRequest)
	}
}

// helper function that reads the currently authenticated
// user from the given http.Request.
func readUser(r *http.Request) (*User, error) {
	username := GetCookie(r, "_sess")
	if len(username) == 0 {
		return nil, fmt.Errorf("No user session")
	}

	// get the user from the database
	user, err := database.GetUserEmail(username)
	if err != nil || user == nil || user.ID == 0 {
		return nil, err
	}

	return user, nil
}

// helper function that retrieves the repository based
// on the URL parameters
func readRepo(r *http.Request) (*Repo, error) {
	// get the repo data from the URL parameters
	hostParam := r.FormValue(":host")
	userParam := r.FormValue(":owner")
	nameParam := r.FormValue(":slug")
	repoSlug := fmt.Sprintf("%s/%s/%s", hostParam, userParam, nameParam)

	// get the repo from the database
	return database.GetRepoSlug(repoSlug)
}

// helper function that sends the user to the login page.
func redirectLogin(w http.ResponseWriter, r *http.Request) {
	v := url.Values{}
	v.Add("return_to", r.URL.String())
	http.Redirect(w, r, "/login?"+v.Encode(), http.StatusSeeOther)
}

func renderNotFound(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	RenderTemplate(w, "404.amber", nil)
}

func renderBadRequest(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusBadRequest)
	RenderTemplate(w, "500.amber", nil)
}


text:
User Information Dashboard

    <form>
        Name
        <input type="text" name="name" ng-model="newcontact.name"/>
        Email
        <input type="text" name="email" ng-model="newcontact.email"/>
        Phone
        <input type="text" name="phone" ng-model="newcontact.phone"/>

        <input type="hidden" ng-model="newcontact.id" />
        <input type="button" value="Save" ng-click="saveContact()" />
    </form>

            Name
            Email
            Phone
            Action

            {{ contact.name }}
            {{ contact.email }}
            {{ contact.phone }}

                <button ng-click="edit(contact.id)">edit</button>
                <button ng-click="delete(contact.id)">delete</button>

Polymer Example

    <paper-button label="flat button"></paper-button>
    <paper-button label="raised button" raisedButton></paper-button>

        <button ng-click="find()">update</button>
        <button ng-click="galleries = null;">clear</button>

{{gal}}

display name:   {{gal.user.displayName}}

user id     :   {{gal.user._id}}

document id :   {{gal._id}}

version     :   {{gal.__v}}

name        :   {{gal.name}}

		<product-description></product-description>


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

/**
 * A message to display by the ngeo notification service.
 */
export type Message = {
  /**
   * The delay in milliseconds the message is shown
   */
  delay?: number;
  /**
   * Whether the message should be displayed inside a popup window or not.
   */
  popup?: boolean;
  /**
   * The message text to display.
   */
  msg: string;
  /**
   * The target element (or selector to get the element) in which
   * to display the message. If not defined, then the default target of the notification service is used.
   */
  target?: Element;
  /**
   * The type of message.
   */
  type?: string;
};

export enum MessageType {
  ERROR = 'error',
  INFORMATION = 'information',
  SUCCESS = 'success',
  WARNING = 'warning',
}

/**
 * Abstract class for services that display messages.
 *
 * @class
 * @abstract
 */
export default class {
  /**
   * Show the message.
   *
   * @abstract
   * @param message Message.
   * @protected
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  showMessage(message: Message): void {}

  /**
   * Show disclaimer message string or object or list of disclame message
   * strings or objects.
   *
   * @param object A message or list of messages as text or configuration objects.
   */
  show(object: string | Message | (string | Message)[]): void {
    const msgObjects = this.getMessageObjects(object);
    msgObjects.forEach((msg) => this.showMessage(msg));
  }

  /**
   * Display the given error message or list of error messages.
   *
   * @param message Message or list of messages.
   */
  error(message: string | string[]): void {
    this.show(this.getMessageObjects(message, MessageType.ERROR));
  }

  /**
   * Display the given info message or list of info messages.
   *
   * @param message Message or list of messages.
   */
  info(message: string | string[]): void {
    this.show(this.getMessageObjects(message, MessageType.INFORMATION));
  }

  /**
   * Display the given success message or list of success messages.
   *
   * @param message Message or list of messages.
   */
  success(message: string | string[]): void {
    this.show(this.getMessageObjects(message, MessageType.SUCCESS));
  }

  /**
   * Display the given warning message or list of warning messages.
   *
   * @param message Message or list of messages.
   */
  warn(message: string | string[]): void {
    this.show(this.getMessageObjects(message, MessageType.WARNING));
  }

  /**
   * Returns an array of message object from any given message string, list of
   * message strings, message object or list message objects. The type can be
   * overridden here as well OR defined (if the message(s) is/are string(s),
   * defaults to 'information').
   *
   * @param object
   *     A message or list of messages as text or configuration objects.
   * @param opt_type The type of message to override the messages with.
   * @returns List of message objects.
   * @protected
   */
  getMessageObjects(object: string | Message | (string | Message)[], opt_type?: string): Message[] {
    const msgObjects: Message[] = [];
    const defaultType = MessageType.INFORMATION;

    if (typeof object === 'string') {
      msgObjects.push({
        msg: /** @type {string} */ object,
        type: opt_type !== undefined ? opt_type : defaultType,
      });
    } else if (Array.isArray(object)) {
      object.forEach((msg) => {
        if (typeof object === 'string') {
          msgObjects.push({
            msg: msg as string,
            type: opt_type !== undefined ? opt_type : defaultType,
          });
        } else {
          if (typeof msg == 'string') {
            throw new Error('Wrong msg type');
          }
          if (opt_type !== undefined) {
            msg.type = opt_type;
          }
          msgObjects.push(msg);
        }
      });
    } else {
      const msgObject: Message = object;
      if (opt_type !== undefined) {
        msgObject.type = opt_type;
      }
      if (msgObject.type === undefined) {
        msgObject.type = defaultType;
      }
      msgObjects.push(msgObject);
    }

    return msgObjects;
  }
}


text:
package com.sectong.authorization.annotation;

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

/**
 * 在Controller的方法上使用此注解,该方法在映射时会检查用户是否登录,未登录返回401错误
 * @see com.sectong.authorization.interceptor.AuthorizationInterceptor
 * @author ScienJus
 * @date 2015/7/31.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorization {
}


text:
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';

// libs
import {Store, ActionReducer, Action} from '@ngrx/store';

// app
import {Analytics, AnalyticsService} from '../../analytics.framework/index';
import {HttpService} from '../../core.framework/index';

// analytics
const CATEGORY: string = 'NameList';

/**
 * ngrx setup start --
 */
export const NAME_LIST_ACTIONS: any = {
  INIT: `[${CATEGORY}] INIT`,
  NAME_ADDED: `[${CATEGORY}] NAME_ADDED`
};

export const nameListReducer: ActionReducer<any> = (state: any = [], action: Action) => {
  switch (action.type) {
    case NAME_LIST_ACTIONS.INIT:
      return [...action.payload];
    case NAME_LIST_ACTIONS.NAME_ADDED:
      return [...state, action.payload];
    default:
      return state;
  }
};
/**
 * ngrx end --
 */

@Injectable()
export class NameListService extends Analytics {
  public names: Observable<any>;

  constructor(public analytics: AnalyticsService, private store: Store<any>, private http: HttpService) {
    super(analytics);
    this.category = CATEGORY;

    this.names = store.select('names');

    this.init();
  }

  init() {
    this.http.get(`assets/data.json`)
      .subscribe((results: string[]) => {
        this.store.dispatch({ type: NAME_LIST_ACTIONS.INIT, payload: results });
      });
  }

  add(name: string): void {
    this.track(NAME_LIST_ACTIONS.NAME_ADDED, { label: name });
    this.store.dispatch({ type: NAME_LIST_ACTIONS.NAME_ADDED, payload: name });
  }
}


text:
using System;
using System.Net;
using System.Threading.Tasks;
using Toggl.Shared;

namespace Toggl.Networking.Network
{
    internal sealed class AdaptingRateLimitingAwareApiClient : IApiClient
    {
        private const uint normalBucketSize = 80u;
        private const uint assumedBurstSize = 10u;
        private const uint noBursts = 0u;

        private readonly LeakyBucket leakyBucket;
        private readonly IApiClient internalClient;

        private bool burstsEnabled;

        public AdaptingRateLimitingAwareApiClient(IApiClient internalClient, Func<DateTimeOffset> currentTime)
        {
            Ensure.Argument.IsNotNull(internalClient, nameof(internalClient));
            Ensure.Argument.IsNotNull(currentTime, nameof(currentTime));

            leakyBucket = new LeakyBucket(currentTime, normalBucketSize, assumedBurstSize);
            this.internalClient = new RateLimitingAwareApiClient(internalClient, leakyBucket);

            burstsEnabled = true;
        }

        public void Dispose()
        {
            internalClient.Dispose();
        }

        public async Task<IResponse> Send(IRequest request)
        {
            var response = await internalClient.Send(request);

            if (response.StatusCode == HttpStatusCode.TooManyRequests)
            {
                burstsEnabled = false;
            }

            if (response.TryGetBucketSizeFromHeaders(out var size))
            {
                // We assume that under normal circumstances (there is no unexpected heavy load on the server) the burst
                // size is at the normal size (10). When the bucket size is decreased dynamically and is below a threshold (80),
                // we will assume that the burst size has dropped to zero as well. This isn't guaranteed by the ops team
                // though and it might be possible that the burst size is lower even when the bucket size drops.
                //
                // If we get a "Too Many Requests" error, we will stop sending requests in bursts until the app restarts
                // or until the size of the bucket increases.

                lock (leakyBucket)
                {
                    if (size > leakyBucket.Size && response.StatusCode != HttpStatusCode.TooManyRequests)
                    {
                        burstsEnabled = true;
                    }

                    var burstSize = size >= normalBucketSize && burstsEnabled ? assumedBurstSize : noBursts;
                    leakyBucket.ChangeSize(size, burstSize);
                }
            }

            return response;
        }
    }
}


text:
#pragma once

struct ZcCell;
struct ZcCellRange;
class ZcDbTable;
class ZcDbLinkedTableData;

class ZcDbTableIterator
{
public:
    ZcDbTableIterator(const ZcDbTable* pTable);
    ZcDbTableIterator(const ZcDbTable* pTable, const ZcCellRange* pRange,
        ZcDb::TableIteratorOption nOption);
    ZcDbTableIterator(const ZcDbLinkedTableData* pTable);
    ZcDbTableIterator(const ZcDbLinkedTableData* pTable, const ZcCellRange* pRange,
        ZcDb::TableIteratorOption nOption);
    ZcDbTableIterator(const ZcCellRange& range);
    ZcDbTableIterator(const ZcCellRange& range, ZcDb::TableIteratorOption nOption);
    ~ZcDbTableIterator();

    void            start                   (void);
    void            step                    (void);
    bool            done                    (void);
    bool            seek                    (const ZcCell& cell);
    const ZcCell&   getCell                 (void) const;
    int             getRow                  (void) const;
    int             getColumn               (void) const;

protected:
    ZcDbTableIterator(void);

protected:
    void        *   mpImpObj;
};


text:
/**
 * @class Logger
 *
 * @author: darryl.west@raincitysoftware.com
 * @created: 7/5/14 6:28 PM
 */

const Logger = function(options) {
    'use strict';

    const logger = this;
    const pid = options.pid || process.pid;
    const errorEventName = options.errorEventName;
    const stats = new Map();

    let domain = options.domain;
    let category = options.category;
    let level = options.level || Logger.DEFAULT_LEVEL;
    let levels = options.levels || Logger.STANDARD_LEVELS;
    let currentLevel = levels.indexOf(level);
    let appenders = options.appenders || [];

    // helper method
    const isLevelAt = function(lvl) {
        const idx = levels.indexOf(lvl);

        return idx >= currentLevel;
    };

    /**
     * log the statement message
     *
     * @param level the level of this message (label, i.e, info, warn, etc)
     * @param msg
     */
    this.log = function(level, msg) {
        const entry = logger.createEntry(level, msg);

        process.nextTick(function() {
            // write the message to the appenders...
            appenders.forEach(function(appender) {
                appender.write(entry);
            });

            if (level === 'error' && typeof (errorEventName) === 'string' || typeof (errorEventName) === String) {
                process.emit(errorEventName, entry);
            }
        });

        return entry;
    };

    /**
     * create the entry object used to log messages
     *
     * @param level - info, debug, etc.
     * @param messageList - a list of message objects
     * @returns then entry object
     */
    this.createEntry = function(level, messageList) {
        const entry = {};

        entry.ts = Date.now();

        entry.pid = pid;
        if (domain) {
            entry.domain = domain;
        }
        if (category) {
            entry.category = category;
        }

        entry.level = level;
        entry.msg = messageList;

        return entry;
    };

    /**
     * set the level
     *
     * @param lvl one of the recognized logger levels
     */
    this.setLevel = function(lvl) {
        currentLevel = levels.indexOf(lvl);
        level = lvl;
        appenders.forEach(app => {
            app.setLevel(lvl);
        });
    };

    /**
     * return the current level string
     */
    this.getLevel = function() {
        return level;
    };

    /**
     * set the list of appenders
     * @param appenderList
     */
    this.setAppenders = function(appenderList) {
        appenders = appenderList;
    };

    /**
     * add an appender to the list
     *
     * @param appender - implements write method
     */
    this.addAppender = function(appender) {
        appenders.push(appender);
    };

    /**
     * remove the appender using the type name
     */
    this.removeAppender = function(typeName) {
        throw new Error(`remove appender ${typeName} is not implemented yet...`);
    };

    this.getAppenders = function() {
        return appenders;
    };

    this.isDebug = function() {
        return isLevelAt('debug');
    };

    this.isInfo = function() {
        return isLevelAt('info');
    };

    /**
     * return the status map with log counts for each level
     */
    this.getStats = function() {
        return stats;
    };

    /**
     * return the category name
     */
    this.getCategory = function() {
        return category;
    };

    /**
     * return the domain name
     */
    this.getDomain = function() {
        return domain;
    };

    // now initialize the methods for the standard levels
    const init = function() {
        levels.forEach(function(lvl) {
            stats.set(lvl, 0);
            logger[lvl] = function() {
                stats.set(lvl, stats.get(lvl) + 1);
                if (levels.indexOf(lvl) >= currentLevel) {
                    const args = Array.prototype.slice.call(arguments);
                    logger.log(lvl, args);
                }
            };
        });
    };

    this.__protected = function() {
        return {
            pid: pid,
            domain: domain,
            category: category
        };
    };

    init();
};

Logger.STANDARD_LEVELS = ['all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal'];
Logger.DEFAULT_LEVEL = 'info';

module.exports = Logger;


text:
cd test
rm -rf fixtures/two-commit-new-branch
git init
git commit --allow-empty -m "first commit"
sleep 1s
git checkout -b feat-x
git checkout master
git commit --allow-empty -m "second commit"
sleep 1s
git tag "expected"
git checkout feat-x
git commit --allow-empty -m "x1"
sleep 1s
git commit --allow-empty -m "x2"
sleep 1s
git commit --allow-empty -m "x3"
sleep 1s
git merge master --no-ff -m "merge master to feat-x"
git checkout master
git checkout -b feat-y
git commit --allow-empty -m "y1"
sleep 1s
git commit --allow-empty -m "y2"

echo "==================== two-commit-new-branch ===================="
git show-branch -a --sha1-name

mv .git fixtures/two-commit-new-branch
rm -rf .git


text:
var ribbon = (function() {

  var defaults = {
    headers: {},
    method: 'GET',
    keycloak: false,
    keycloakUpdateInterval: 30,
    context: '/ribbon'
  }, topology = {};

  function factory( options ) {
    options = merge(defaults, options);

    function ajax( serviceName, path, settings ) {
      var allServers = topology[serviceName],
          deferredResult = deferred(),
          keycloak = options.keycloak;

      if (!allServers || allServers.length < 1 ) {
        return deferredResult.reject('No servers available').promise;
      }

      // ensure some default settings exist
      settings = merge({
        method: options.method,
        headers: options.headers,
        data: undefined
      }, settings);

      path = path || '/';

      // TODO: Try other URLs if there is more than one server
      settings.url = '//' + allServers[0] + path;

      // Set relevant headers
      if (settings.method === 'POST') {
        settings.headers['Content-Type'] = 'application/json';
      }

      if (!keycloak) {
        // If we're not authenticating, go ahead and make the request
        return doRequest( settings ).promise;
      } else if (!keycloak.authenticated) {
        // But if we are authenticating...
        return deferredResult.reject("Not authenticated").promise;
      } else {
        // Using keycloak, update token, and make the request
        settings.headers.Authorization = 'Bearer ' + keycloak.token;

        // TODO: Make token update interval configurable
        keycloak.updateToken(30).success( function() {
          console.log( "ribbon.js: keycloak token refreshed" );

          // make the request
          doRequest( settings ).then( function(result) {
            deferredResult.resolve(result);
          });
        }).error( function(e) {
          console.log( "ribbon.js: Failed to update keycloak token. " + e );
          deferredResult.reject('Failed to update keycloak token. ' + e);
        });
      }

      return deferredResult.promise;
    }

    function doRequest(settings) {
      var request = new XMLHttpRequest(),
          deferredResponse = deferred();

      // set the state change handler and open the http request
      request.onreadystatechange = changeState(request, deferredResponse);
      request.open(settings.method, settings.url);

      getHeaders(settings.headers).forEach(function(header) {
        request.setRequestHeader(header.field, header.value);
      });

      if (settings.data) request.send(settings.data);
      else request.send();

      // return a deferred promise
      return deferredResponse;

      function changeState(request, deferredResponse) {
        return function() {
          switch(request.readyState) {
          case 0:
          case 1:
          case 2:
          case 3:
            break;
          case 4:
            processResponse(request, deferredResponse);
            break;
          default:
            console.log('ribbon.js: Unexpected XMLHttpRequest state');
            deferred.reject('Unexpected XMLHttpRequst state');
          }
        };
      }

      function processResponse(request, response) {
        if (request.status === 200) {
          response.resolve(JSON.parse(request.responseText));
        } else {
          response.reject('ribbon.js: Bad request: ' + request.statusText);
        }
      }

      function getHeaders(headers) {
        var headerList = [];
        for (var key in headers) {
          if (headers.hasOwnProperty(key)) {
            headerList.push({
              field: key,
              value: headers[key]
            });
          }
        }
        return headerList;
      }
    }

    function getJSON(serviceName, path) {
      return ajax( serviceName, path );
    }

    function postJSON(serviceName, path, data) {
      if (typeof path === 'object') {
        data = path;
        path = '/';
      }
      return ajax( serviceName, path, {
        method: 'POST',
        data: JSON.stringify(data)
      });
    }

    var sse = new EventSource( options.context + "/system/stream" );
    sse.addEventListener('topologyChange', function(message) {
      console.log('ribbon.js: topology changed: ', message.data);
      topology = JSON.parse(message.data);
    });

    sse.onerror = function(e) {
      console.log( "ribbon.js: topology SSE error", e );
    };

    function onTopologyChange(f) {
      sse.addEventListener('topologyChange', function(message) {
        f(message.data);
      });
    }

    var _ribbon = {
      ajax: ajax,
      postJSON: postJSON,
      getJSON: getJSON,
      onTopologyChange: onTopologyChange
    };

    Object.defineProperty(_ribbon, 'topology', {
      get: function() { return topology; },
      enumerable: true
    });
    Object.freeze(_ribbon);
    return _ribbon;
  }

  function merge(defaults, provided) {
    var obj = {};
    if (!provided) provided = {};
    for (var key in defaults) {
      if (defaults.hasOwnProperty(key))
        obj[key] = provided[key] || defaults[key];
    }
    return obj;
  }

  function promises() {
    var PENDING = 0,
        FULFILLED = 1,
        REJECTED = 2;

    function promise(fn) {

      var p = {
        state: PENDING,
        identify: 'fidelity',
        value: null,
        queue: [],
        handlers: {
          fulfill: null,
          reject: null
        }
      };
      p.then = then(p);

      if (isA('function', fn)) {
        fn(
          function(v) { resolve(p, v); },
          function(r) { reject(p, r); }
        );
      }

      return p;
    }

    function then(p) {
      return function(onFulfilled, onRejected) {
        var q = promise();
        if (isA('function', onFulfilled)) {
          q.handlers.fulfill = onFulfilled;
        }
        if (isA('function', onRejected)) {
          q.handlers.reject = onRejected;
        }
        p.queue.push(q);
        process(p);
        return q;
      };
    }

    function resolve(p, x) {
      if (x === p)
        reject(p, new TypeError('The promise and its value are the same.'));

      if (isPromise(x)) {
        if (x.state === PENDING) {
          x.then(function(value) {
            resolve(p, value);
          }, function(cause) {
            reject(p, cause);
          });
        } else {
          transition(p, x.state, x.value);
        }
      } else if (isA('function', x) || isA('object', x)) {
        var called = false, thenFunction;
        try {
          thenFunction = x.then;
          if (isA('function', thenFunction)) {
            thenFunction.call(x, function(y) {
              if (!called) {
                resolve(p, y);
                called = true;
              }
            }, function (r) {
              if (!called) {
                reject(p, r);
                called = true;
              }
            });
          } else {
            fulfill(p, x);
            called = true;
          }
        } catch (e) {
          if (!called) {
            reject(p, e);
            called = true;
          }
        }
      }
      else fulfill(p, x);
    }

    function fulfill(p, result) {
      transition(p, FULFILLED, result);
    }

    function reject(p, cause) {
      transition(p, REJECTED, cause);
    }

    function defaultFulfill(v) { return v; }

    function defaultReject(r) { throw r; }

    function process(p) {
      if (p.state === PENDING) return;
      setTimeout(function() {
        while(p.queue.length) {
          var qp = p.queue.shift(),
              handler, value;
          if (p.state === FULFILLED) {
            handler = qp.handlers.fulfill || defaultFulfill;
          } else if (p.state === REJECTED) {
            handler = qp.handlers.reject || defaultReject;
          }
          try {
            value = handler(p.value);
          } catch(e) {
            transition(qp, REJECTED, e);
            continue;
          }
          resolve(qp, value);
        }
      }, 0);
    }

    function transition(p, state, value) {
      if (p.state === state ||
          p.state !== PENDING ||
          arguments.length !== 3) return;
      p.state = state;
      p.value = value;
      process(p);
    }

    function isA(type, x) {
      return x && typeof x === type;
    }

    function isPromise(x) {
      return x && x.identify === 'fidelity';
    }

    promise.PENDING = PENDING;
    promise.FULFILLED = FULFILLED;
    promise.REJECTED = REJECTED;
    return promise;
  }

  var promise = promises(),
      deferred = function() {
        var resolver, rejecter,
            p = promise(function(resolve, reject) {
              resolver = resolve;
              rejecter = reject;
            });
        function resolve(value) {
          resolver(value);
        }
        function reject(cause) {
          rejecter(cause);
        }
        return {
          promise: p,
          resolve: resolve,
          reject: reject
        };
      };
  return factory;

})();


text:
<?php

namespace Imgur\tests\Api;

use Imgur\Client;
use PHPUnit\Framework\TestCase;

abstract class ApiTestCase extends TestCase
{
    abstract protected function getApiClass();

    protected function getApiMock()
    {
        $httpClient = $this->getMockBuilder('Imgur\HttpClient\HttpClient')
            ->disableOriginalConstructor()
            ->getMock();
        $httpClient
            ->expects($this->any())
            ->method('get');
        $httpClient
            ->expects($this->any())
            ->method('delete');
        $httpClient
            ->expects($this->any())
            ->method('post');
        $httpClient
            ->expects($this->any())
            ->method('put');

        $client = new Client(null, $httpClient);

        return $this->getMockBuilder($this->getApiClass())
            ->setMethods(['get', 'post', 'put', 'delete'])
            ->setConstructorArgs([$client])
            ->getMock();
    }
}


text:
import { Table } from "./helpers";
export declare function generateNormalizrDefine(table: Table): string;


text:
package net.sf.mmm.ui.toolkit.base;

import java.util.concurrent.Callable;

import net.sf.mmm.ui.toolkit.api.UiDevice;
import net.sf.mmm.ui.toolkit.api.UiDisplay;

/**
 * This is the abstract base implementation of the {@link UiDisplay} interface.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.0.0
 */
public abstract class AbstractUiDisplay extends AbstractUiObject implements UiDisplay {

  /** the UI device this display belongs to */
  private UiDevice device;

  /**
   * The constructor.
   *
   * @param uiFactory is the {@link #getFactory() factory} instance.
   * @param uiDevice is the device the display belongs to.
   */
  public AbstractUiDisplay(AbstractUiFactory uiFactory, UiDevice uiDevice) {

    super(uiFactory);
    this.device = uiDevice;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String getType() {

    return TYPE;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString() {

    return getDevice().toString() + "[" + getWidthInPixel() + "*" + getHeightInPixel() + "]";
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public UiDevice getDevice() {

    return this.device;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public <T> T invokeSynchron(Callable<T> task) throws Exception {

    if (isDispatchThread()) {
      return task.call();
    } else {
      CallableRunner<T> runner = new CallableRunner<T>(task);
      doInvokeSynchron(runner);
      return runner.getResult();
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void invokeSynchron(Runnable task) {

    if (isDispatchThread()) {
      task.run();
    } else {
      doInvokeSynchron(task);
    }
  }

  /**
   * This method handles the {@link #invokeSynchron(Runnable)} if called from another thread.
   *
   * @param task is the task to invoke.
   */
  protected abstract void doInvokeSynchron(Runnable task);

}


text:
/*
 * FRC 4931 (http://www.evilletech.com)
 *
 * Open source software. Licensed under the FIRST BSD license file in the
 * root directory of this project's Git repository.
 */
package org.frc4931.robot.hardware;

import org.frc4931.robot.component.AngleSensor;
import org.frc4931.robot.component.CurrentSensor;
import org.frc4931.robot.component.Motor;
import org.frc4931.robot.component.Switch;

import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.CANTalon.ControlMode;

/**
 * Talon speed controller with position sensor
 * @author Nathan Brown
 */
public class HardwareTalonSRX {
    private final CANTalon talon;
    private final Motor motor;
    private final AngleSensor encoder;
    private final Switch homeSwitch;
    private final CurrentSensor current;

    private final double ppd;

    HardwareTalonSRX(int id, double pulsesPerDegree){
        this.talon = new CANTalon(id);
        this.ppd = pulsesPerDegree;

        // Set up hard limits
        talon.enableLimitSwitch(false, true);
        talon.ConfigRevLimitSwitchNormallyOpen(true);

        // Disable soft limits, we are handling them in PIDMotorWithAngle
        talon.enableForwardSoftLimit(false);
        talon.enableReverseSoftLimit(false);

        motor = new TalonMotor();
        encoder = new TalonEncoder();

        homeSwitch = talon::isRevLimitSwitchClosed;
        current = talon::getOutputCurrent;
    }

    public Motor getMotor() {
        return motor;
    }

    public AngleSensor getAngleSensor() {
        return encoder;
    }

    public Switch getHomeSwitch() {
        return homeSwitch;
    }

    public CurrentSensor getCurrentSensor() {
        return current;
    }

    private class TalonMotor implements Motor {
        public TalonMotor() {}

        @Override
        public void setSpeed(double speed) {
            talon.changeControlMode(ControlMode.PercentVbus);
            talon.set(speed);
        }

        @Override
        public short getSpeedAsShort() {
            return (short)(getSpeed() * 1000);
        }

        @Override
        public double getSpeed() {
            talon.changeControlMode(ControlMode.PercentVbus);
            return talon.get();
        }

        @Override
        public void stop() {
            talon.enableBrakeMode(true);
            talon.set(0);
        }
    }

    private class TalonEncoder implements AngleSensor {
        int zero;

        public TalonEncoder() {}

        @Override
        public double getAngle() {
            return (talon.getEncPosition() - zero) / ppd;
        }

        @Override
        public void reset() {
            zero = talon.getEncPosition();
        }
    }
}


text:
using System;

namespace Geocoding.Core
{
	public class GeocodingException : Exception
	{
		public GeocodingException(string message, Exception innerException = null)
			: base(message, innerException)
		{
		}
	}
}


text:
using namespace llvm;

TEST(RemarksStrTab, ParsingEmpty) {
  StringRef Empty("", 0);
  remarks::ParsedStringTable StrTab(Empty);
  Expected<StringRef> Nothing = StrTab[0];
  EXPECT_FALSE(static_cast<bool>(Nothing));
  EXPECT_EQ(toString(Nothing.takeError()),
            "String with index 0 is out of bounds (size = 0).");
}

TEST(RemarksStrTab, ParsingGood) {
  StringRef Strings("str1\0str2\0str3\0str4", 20);
  remarks::ParsedStringTable StrTab(Strings);
  Expected<StringRef> Result = StrTab[0];
  EXPECT_TRUE(static_cast<bool>(Result));
  EXPECT_EQ(*Result, "str1");
  Result = StrTab[1];
  EXPECT_TRUE(static_cast<bool>(Result));
  EXPECT_EQ(*Result, "str2");
  Result = StrTab[2];
  EXPECT_TRUE(static_cast<bool>(Result));
  EXPECT_EQ(*Result, "str3");
  Result = StrTab[3];
  EXPECT_TRUE(static_cast<bool>(Result));
  EXPECT_EQ(*Result, "str4");
}


text:
import Component from './component';

const Bar = {

  x: 0,
  y: 0,
  width: 0,
  height: 0,

  init() {
    var cursorX;
    var cursorY;
    window.addEventListener('keydown', checkKeyPressed.bind(this), false);
    this.widthC = this.canvas.width;
    this.heightC = this.canvas.height;
    this.height = (this.heightC/100) * 20;
    this.width = (this.widthC/100) * 2;
    this.x = this.width;
    this.movimentUnit = (this.widthC/100) * 10;

    canvas.addEventListener('mousemove', mousemovePad.bind(this), false);

    function checkKeyPressed(e) {
      if (e.keyCode == '38') {
        if( (this.y - this.movimentUnit) >= 0){
          this.y = this.y - this.movimentUnit;
        }
      }
      if (e.keyCode == '40') {
        if( (this.y + this.movimentUnit) <= (this.heightC-this.height/2)){
          this.y = this.y + this.movimentUnit;
        }
      }
    }

    function mousemovePad(evt) {
        var mousePos = getMousePos(canvas, evt);

        if(mousePos.y > this.y){
            if( (this.y + this.movimentUnit) <= (this.heightC-this.height/2)){
              this.y = this.y + this.movimentUnit;
            }
        }

        if(mousePos.y < this.y){
            if( (this.y - this.movimentUnit) >= 0){
              this.y = this.y - this.movimentUnit;
            }
        }
    }

    function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }

  },

  draw() {
    this.ctx.beginPath();
    this.ctx.fillStyle = 'white';
    this.ctx.fillRect(this.x, this.y, this.width, this.height);
    this.ctx.restore();
  }
};

export default function createBar() {
  return Object.assign({}, Component, Bar);
}


text:
class RemoveSocialSharingPreferences < ActiveRecord::Migration
  def up
    execute "DELETE FROM preferences WHERE name IN ('share_observations_on_twitter', 'share_observations_on_facebook')"
  end

  def down
    say "There's no coming back from this"
  end
end