text:
<?php

namespace Ilios\CoreBundle\Controller;

use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Request\ParamFetcherInterface;
use FOS\RestBundle\Util\Codes;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use FOS\RestBundle\Controller\FOSRestController;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Ilios\CoreBundle\Exception\InvalidFormException;
use Ilios\CoreBundle\Entity\LearningMaterialUserRoleInterface;

/**
 * Class LearningMaterialUserRoleController
 * @package Ilios\CoreBundle\Controller
 * @RouteResource("LearningMaterialUserRoles")
 */
class LearningMaterialUserRoleController extends FOSRestController
{
    /**
     * Get a LearningMaterialUserRole
     *
     * @ApiDoc(
     *   section = "LearningMaterialUserRole",
     *   description = "Get a LearningMaterialUserRole.",
     *   resource = true,
     *   requirements={
     *     {
     *        "name"="id",
     *        "dataType"="integer",
     *        "requirement"="\d+",
     *        "description"="LearningMaterialUserRole identifier."
     *     }
     *   },
     *   output="Ilios\CoreBundle\Entity\LearningMaterialUserRole",
     *   statusCodes={
     *     200 = "LearningMaterialUserRole.",
     *     404 = "Not Found."
     *   }
     * )
     *
     * @Rest\View(serializerEnableMaxDepthChecks=true)
     *
     * @param $id
     *
     * @return Response
     */
    public function getAction($id)
    {
        $learningMaterialUserRole = $this->getOr404($id);

        $authChecker = $this->get('security.authorization_checker');
        if (! $authChecker->isGranted('view', $learningMaterialUserRole)) {
            throw $this->createAccessDeniedException('Unauthorized access!');
        }

        $answer['learningMaterialUserRoles'][] = $learningMaterialUserRole;

        return $answer;
    }

    /**
     * Get all LearningMaterialUserRole.
     *
     * @ApiDoc(
     *   section = "LearningMaterialUserRole",
     *   description = "Get all LearningMaterialUserRole.",
     *   resource = true,
     *   output="Ilios\CoreBundle\Entity\LearningMaterialUserRole",
     *   statusCodes = {
     *     200 = "List of all LearningMaterialUserRole",
     *     204 = "No content. Nothing to list."
     *   }
     * )
     *
     * @QueryParam(
     *   name="offset",
     *   requirements="\d+",
     *   nullable=true,
     *   description="Offset from which to start listing notes."
     * )
     * @QueryParam(
     *   name="limit",
     *   requirements="\d+",
     *   default="20",
     *   description="How many notes to return."
     * )
     * @QueryParam(
     *   name="order_by",
     *   nullable=true,
     *   array=true,
     *   description="Order by fields. Must be an array ie. &order_by[name]=ASC&order_by[description]=DESC"
     * )
     * @QueryParam(
     *   name="filters",
     *   nullable=true,
     *   array=true,
     *   description="Filter by fields. Must be an array ie. &filters[id]=3"
     * )
     *
     * @Rest\View(serializerEnableMaxDepthChecks=true)
     *
     * @param ParamFetcherInterface $paramFetcher
     *
     * @return Response
     */
    public function cgetAction(ParamFetcherInterface $paramFetcher)
    {
        $offset = $paramFetcher->get('offset');
        $limit = $paramFetcher->get('limit');
        $orderBy = $paramFetcher->get('order_by');
        $criteria = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : [];
        $criteria = array_map(function ($item) {
            $item = $item == 'null' ? null : $item;
            $item = $item == 'false' ? false : $item;
            $item = $item == 'true' ? true : $item;

            return $item;
        }, $criteria);

        $manager = $this->container->get('ilioscore.learningmaterialuserrole.manager');
        $result = $manager->findBy($criteria, $orderBy, $limit, $offset);

        $authChecker = $this->get('security.authorization_checker');
        $result = array_filter($result, function ($entity) use ($authChecker) {
            return $authChecker->isGranted('view', $entity);
        });

        //If there are no matches return an empty array
        $answer['learningMaterialUserRoles'] =
            $result ? array_values($result) : [];

        return $answer;
    }

    /**
     * Create a LearningMaterialUserRole.
     *
     * @ApiDoc(
     *   section = "LearningMaterialUserRole",
     *   description = "Create a LearningMaterialUserRole.",
     *   resource = true,
     *   input="Ilios\CoreBundle\Form\Type\LearningMaterialUserRoleType",
     *   output="Ilios\CoreBundle\Entity\LearningMaterialUserRole",
     *   statusCodes={
     *     201 = "Created LearningMaterialUserRole.",
     *     400 = "Bad Request.",
     *     404 = "Not Found."
     *   }
     * )
     *
     * @Rest\View(statusCode=201, serializerEnableMaxDepthChecks=true)
     *
     * @param Request $request
     *
     * @return Response
     */
    public function postAction(Request $request)
    {
        try {
            $handler = $this->container->get('ilioscore.learningmaterialuserrole.handler');

            $learningMaterialUserRole = $handler->post($this->getPostData($request));

            $authChecker = $this->get('security.authorization_checker');
            if (! $authChecker->isGranted('create', $learningMaterialUserRole)) {
                throw $this->createAccessDeniedException('Unauthorized access!');
            }

            $manager = $this->container->get('ilioscore.learningmaterialuserrole.manager');
            $manager->update($learningMaterialUserRole, true, false);

            $answer['learningMaterialUserRoles'] = [$learningMaterialUserRole];

            $view = $this->view($answer, Codes::HTTP_CREATED);

            return $this->handleView($view);
        } catch (InvalidFormException $exception) {
            return $exception->getForm();
        }
    }

    /**
     * Update a LearningMaterialUserRole.
     *
     * @ApiDoc(
     *   section = "LearningMaterialUserRole",
     *   description = "Update a LearningMaterialUserRole entity.",
     *   resource = true,
     *   input="Ilios\CoreBundle\Form\Type\LearningMaterialUserRoleType",
     *   output="Ilios\CoreBundle\Entity\LearningMaterialUserRole",
     *   statusCodes={
     *     200 = "Updated LearningMaterialUserRole.",
     *     201 = "Created LearningMaterialUserRole.",
     *     400 = "Bad Request.",
     *     404 = "Not Found."
     *   }
     * )
     *
     * @Rest\View(serializerEnableMaxDepthChecks=true)
     *
     * @param Request $request
     * @param $id
     *
     * @return Response
     */
    public function putAction(Request $request, $id)
    {
        try {
            $manager = $this->container->get('ilioscore.learningmaterialuserrole.manager');
            $learningMaterialUserRole = $manager->findOneBy(['id'=> $id]);
            if ($learningMaterialUserRole) {
                $code = Codes::HTTP_OK;
            } else {
                $learningMaterialUserRole = $manager->create();
                $code = Codes::HTTP_CREATED;
            }

            $handler = $this->container->get('ilioscore.learningmaterialuserrole.handler');

            $learningMaterialUserRole = $handler->put($learningMaterialUserRole, $this->getPostData($request));

            $authChecker = $this->get('security.authorization_checker');
            if (! $authChecker->isGranted('edit', $learningMaterialUserRole)) {
                throw $this->createAccessDeniedException('Unauthorized access!');
            }

            $manager->update($learningMaterialUserRole, true, true);

            $answer['learningMaterialUserRole'] = $learningMaterialUserRole;
        } catch (InvalidFormException $exception) {
            return $exception->getForm();
        }

        $view = $this->view($answer, $code);

        return $this->handleView($view);
    }

    /**
     * Delete a LearningMaterialUserRole.
     *
     * @ApiDoc(
     *   section = "LearningMaterialUserRole",
     *   description = "Delete a LearningMaterialUserRole entity.",
     *   resource = true,
     *   requirements={
     *     {
     *         "name" = "id",
     *         "dataType" = "integer",
     *         "requirement" = "\d+",
     *         "description" = "LearningMaterialUserRole identifier"
     *     }
     *   },
     *   statusCodes={
     *     204 = "No content. Successfully deleted LearningMaterialUserRole.",
     *     400 = "Bad Request.",
     *     404 = "Not found."
     *   }
     * )
     *
     * @Rest\View(statusCode=204)
     *
     * @param $id
     * @internal LearningMaterialUserRoleInterface $learningMaterialUserRole
     *
     * @return Response
     */
    public function deleteAction($id)
    {
        $learningMaterialUserRole = $this->getOr404($id);

        $authChecker = $this->get('security.authorization_checker');
        if (! $authChecker->isGranted('delete', $learningMaterialUserRole)) {
            throw $this->createAccessDeniedException('Unauthorized access!');
        }

        try {
            $manager = $this->container->get('ilioscore.learningmaterialuserrole.manager');
            $manager->delete($learningMaterialUserRole);

            return new Response('', Codes::HTTP_NO_CONTENT);
        } catch (\Exception $exception) {
            throw new \RuntimeException("Deletion not allowed: " . $exception->getMessage());
        }
    }

    /**
     * Get a entity or throw a exception
     *
     * @param $id
     * @return LearningMaterialUserRoleInterface $learningMaterialUserRole
     */
    protected function getOr404($id)
    {
        $manager = $this->container->get('ilioscore.learningmaterialuserrole.manager');
        $learningMaterialUserRole = $manager->findOneBy(['id' => $id]);
        if (!$learningMaterialUserRole) {
            throw new NotFoundHttpException(sprintf('The resource \'%s\' was not found.', $id));
        }

        return $learningMaterialUserRole;
    }

    /**
     * Parse the request for the form data
     *
     * @param Request $request
     * @return array
     */
    protected function getPostData(Request $request)
    {
        if ($request->request->has('learningMaterialUserRole')) {
            return $request->request->get('learningMaterialUserRole');
        }

        return $request->request->all();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Javascript Muse</title>
    <meta name="description" content="This is a blog documenting my journey to master Javascript
#JavascriptisSexy" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//DuggieMitchell.github.io/JavascriptMuse/themes/Casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//DuggieMitchell.github.io/JavascriptMuse/themes/Casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://DuggieMitchell.github.io/JavascriptMuse" />
    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Javascript Muse" href="https://DuggieMitchell.github.io/JavascriptMuse/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

<header class="main-header tag-head " style="background-image: url(https://lh3.googleusercontent.com/z8GbbeSDYcpVFnqn22l1Z52WZJemKaeervQqAw-U5fWe65V87tAnEbA69i0uqadfeND0n3zcu2ZqSsmttUTsErfA5GEJMZdHKeqmBzW3GA6ciDeVzj3ClA_Rp0j2Dt8J1ju5_U_sF44gTcP0a2eq6q6XWkwLIHXw052lgRObomdV1AUN6ZQjLMQVLWKvyj0KKr6RZUjJ_u1lxHsR6Zl5h9Dknbn8Me1qL-R9d5Bw2stDcefVv-ZrYMcmX2y6fxkizmcgdZkHKh0F_WZLuxvcmEpZ7YGq90KuFEBZ_gmddrvATeAsl1-7rmJn0Eb1hD-CEcZOgFMboUmp6SDKsAmUw-sBcBuNdQfaxxZY-PUsqDJf8M4wD9K6hE39xPRnSVh10mOJdtN7Hz215_griepFGDESYM5Rc9FWbI1vPbEtFEny4FEGJCk5ThdIwIuGjmbzSpOEJdvIei3XLpYghUIHWRh5N8pvWXBL9Q07oQHOMYQt4IbnRuDB3S8eIv24-v3SkezDjMfNf-HMHVQ0lU8wbOP7ZDV7OC4whnMoAZ1B9k1xpt23o7QX-Y56MqUU2K9qBPia=w1290-h657-no)">

        Home

Shakespeare

                    A 1-post collection

        Page 1 of 1

A Rose by Any other Name

Working with Objects in Javascript What is in a name that which we call a rose by any other name would smell as sweet? Each time »

             on Javascript,  Shakespeare
            <time class="post-date" datetime="2016-01-05">05 January 2016</time>

        Page 1 of 1

Javascript Muse © 2016

Proudly published with HubPress

redpajama_set_name: RedPajamaGithub


text:
import createComponent from './create-component';
import createGroup from 'cyclejs-group';

import view from './view';
import intent from './intent';
import model from './model';

createComponent('autocompleted-select', function(interaction$, props) {
    let view$$ = createGroup({ view$: view });
    let intent$$ = createGroup(intent);
    let model$$ = createGroup(model);

    interaction$.inject(view$$.view$);
    view$$.inject(model$$);
    model$$.inject(intent$$, {
        datalistAttr$: props.datalist
    }, model$$);
    intent$$.inject({ interaction$,
        valueAttr$: props.value
    }, intent$$);

    model$$.value$.skip(1).subscribe((value) => {
        this.value = value;

        this.dispatchEvent(new Event('change'));
    });

}, [ 'value', 'datalist' ]);


text:
IMPLEMENT_CONOBJECT(ImageAsset);

ConsoleType(ImageAssetPtr, TypeImageAssetPtr, ImageAsset, ASSET_ID_FIELD_PREFIX)

//-----------------------------------------------------------------------------

ConsoleGetType(TypeImageAssetPtr)
{
   // Fetch asset Id.
   return (*((AssetPtr<ImageAsset>*)dptr)).getAssetId();
}

//-----------------------------------------------------------------------------

ConsoleSetType(TypeImageAssetPtr)
{
   // Was a single argument specified?
   if (argc == 1)
   {
      // Yes, so fetch field value.
      const char* pFieldValue = argv[0];

      // Fetch asset pointer.
      AssetPtr<ImageAsset>* pAssetPtr = dynamic_cast<AssetPtr<ImageAsset>*>((AssetPtrBase*)(dptr));

      // Is the asset pointer the correct type?
      if (pAssetPtr == NULL)
      {
         // No, so fail.
         //Con::warnf("(TypeImageAssetPtr) - Failed to set asset Id '%d'.", pFieldValue);
         return;
      }

      // Set asset.
      pAssetPtr->setAssetId(pFieldValue);

      return;
   }

   // Warn.
   Con::warnf("(TypeImageAssetPtr) - Cannot set multiple args to a single asset.");
}

//-----------------------------------------------------------------------------

ImageAsset::ImageAsset() : AssetBase(), mImage(nullptr), mUseMips(true), mIsHDRImage(false), mIsValidImage(false)
{
   mImageFileName = StringTable->EmptyString();
}

//-----------------------------------------------------------------------------

ImageAsset::~ImageAsset()
{
}

//-----------------------------------------------------------------------------

void ImageAsset::initPersistFields()
{
   // Call parent.
   Parent::initPersistFields();

   addField("imageFile", TypeString, Offset(mImageFileName, ImageAsset), "Path to the image file.");
   addField("useMips", TypeBool, Offset(mUseMips, ImageAsset), "Should the image use mips? (Currently unused).");
   addField("isHDRImage", TypeBool, Offset(mIsHDRImage, ImageAsset), "Is the image in an HDR format? (Currently unused)");
}

//------------------------------------------------------------------------------

void ImageAsset::copyTo(SimObject* object)
{
   // Call to parent.
   Parent::copyTo(object);
}

void ImageAsset::loadImage()
{
   SAFE_DELETE(mImage);

   if (mImageFileName)
   {
      if (!Platform::isFile(mImageFileName))
      {
         Con::errorf("ImageAsset::initializeAsset: Attempted to load file %s but it was not valid!", mImageFileName);
         return;
      }

      mImage.set(mImageFileName, &GFXStaticTextureSRGBProfile, avar("%s() - mImage (line %d)", __FUNCTION__, __LINE__));

      if (mImage)
      {
         mIsValidImage = true;
         return;
      }
   }

   mIsValidImage = false;
}

void ImageAsset::initializeAsset()
{
   loadImage();
}

void ImageAsset::onAssetRefresh()
{
   loadImage();
}


text:
#if !defined(XALANDOCUMENTPREFIXRESOLVER_HEADER_GUARD_1357924680)
#define XALANDOCUMENTPREFIXRESOLVER_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <xalanc/DOMSupport/DOMSupportDefinitions.hpp>

#include <xalanc/XalanDOM/XalanDOMString.hpp>

#include <xalanc/PlatformSupport/PrefixResolver.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>

#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>
#include <xalanc/Include/STLHelper.hpp>

#include <xalanc/DOMSupport/TreeWalker.hpp>

namespace XALAN_CPP_NAMESPACE {

class XalanAttr;
class XalanDocument;

typedef XalanVector<const XalanNode*>               AttributeVectorTypeDecl;
XALAN_USES_MEMORY_MANAGER(AttributeVectorTypeDecl)

class XALAN_DOMSUPPORT_EXPORT XalanDocumentPrefixResolver : public PrefixResolver
{
public:

    typedef AttributeVectorTypeDecl                     AttributeVectorType;
    typedef XalanMap<const XalanDOMString*,
                    AttributeVectorType>                NamespacesMapType;

    /**
     * Constructor.
     *
     * @param theDocument The XalanDocument instance to use for namespace bindings.
     * @param theURI The base URI for the instance.  This is rarely needed, but can be provided if the URI for the XalanDocument instance is known.
     */
    XalanDocumentPrefixResolver(
            const XalanDocument*    theDocument,
            const XalanDOMString&   theURI = XalanDOMString(XalanMemMgrs::getDummyMemMgr()),
            MemoryManager&      theManager XALAN_DEFAULT_MEMMGR);

    virtual
    ~XalanDocumentPrefixResolver();

    virtual const XalanDOMString*
    getNamespaceForPrefix(const XalanDOMString&     prefix) const;

    virtual const XalanDOMString&
    getURI() const;

    /**
     * A utility class to walk the XalanDocument instance and look for attribute nodes that declare namespaces.
     */
    class NamespaceNodesTreeWalker : public TreeWalker
    {
    public:

        NamespaceNodesTreeWalker(NamespacesMapType&     theMap);

        virtual
        ~NamespaceNodesTreeWalker();

    protected:

        virtual bool
        startNode(const XalanNode*  node);

        virtual bool
        startNode(XalanNode*    node);

        virtual bool
        endNode(const XalanNode*    node);

        virtual bool
        endNode(XalanNode*  node);

    private:

        NamespacesMapType&  m_map;
    };

protected:

    /**
     * This function is called when more than one binding exists for a given prefix.
     * The default behavior uses the first binding, but a deriving class can change
     * that behavior by overriding.
     *
     * @param theVector The vector associated with the namespace prefix.
     * @return A pointer to a const XalanDOMString containing the desired binding, or NULL.
     */
    virtual const XalanDOMString*
    duplicateBinding(const AttributeVectorType&     theVector) const;

private:

    NamespacesMapType       m_namespaces;

    const XalanDOMString    m_uri;
};

}

#endif  // XALANDOCUMENTPREFIXRESOLVER_HEADER_GUARD_1357924680


text:
namespace CSharpMath.Atom {
  /// <summary>
  /// A left atom -- Left and Right in TeX.
  /// We don't need two since we track boundaries separately.
  /// </summary>
  public readonly struct Boundary : IMathObject, System.IEquatable<Boundary> {
    public static readonly Boundary Empty = default;
    public string? Nucleus { get; }
    public string DebugString => Nucleus ?? "(null)";
    public Boundary(string nucleus) => Nucleus = nucleus;
    public bool EqualsBoundary(Boundary boundary) => Nucleus == boundary.Nucleus;
    bool System.IEquatable<Boundary>.Equals(Boundary other) => EqualsBoundary(other);
    public override bool Equals(object obj) => obj is Boundary b && EqualsBoundary(b);
    public override int GetHashCode() => Nucleus?.GetHashCode() ?? 0;
    public static bool operator ==(Boundary left, Boundary right) => left.EqualsBoundary(right);
    public static bool operator !=(Boundary left, Boundary right) => !left.EqualsBoundary(right);
    public override string ToString() => Nucleus ?? "(null)";
  }
}


text:
namespace BigEgg.Tools.ConsoleExtension.Parameters.Output
{
    using System;
    using System.Collections.Generic;

    using BigEgg.Tools.ConsoleExtension.Parameters.Errors;

    internal partial class TextBuilder
    {
        private string BuildVersionText(IEnumerable<Error> errors, int maximumDisplayWidth)
        {
            return BuildString(new List<string>()
            {
                string.Join(Environment.NewLine, new string[]
                {
                    "Program version information:",
                    $"Program Name: {ParameterConstants.INDEX_START_STRING}{programInfo.Title}",
                    $"Program Version: {ParameterConstants.INDEX_START_STRING}{programInfo.Version}",
                    $"Program Product: {ParameterConstants.INDEX_START_STRING}{programInfo.Copyright}",
                    $"Program Copyright: {ParameterConstants.INDEX_START_STRING}{programInfo.Product}",
                })
            }, maximumDisplayWidth);
        }
    }
}


text:
package hr.fer.zemris.jcms.tags.views.freemarker.tags;

import hr.fer.zemris.jcms.tags.components.MonoHierarchyIterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.components.Component;
import org.apache.struts2.views.freemarker.tags.TagModel;

import com.opensymphony.xwork2.util.ValueStack;

public class MonoHierarchyIteratorModel extends TagModel {

	public MonoHierarchyIteratorModel(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
		super(stack, req, res);
	}

	@Override
	protected Component getBean() {
		return new MonoHierarchyIterator(stack);
	}

}


text:
PersonalOptionsHandler::PersonalOptionsHandler() {
  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
  multiprofile_ = browser_command_line.HasSwitch(switches::kMultiProfiles);
#if defined(OS_CHROMEOS)
  registrar_.Add(this,
                 NotificationType::LOGIN_USER_IMAGE_CHANGED,
                 NotificationService::AllSources());
#endif
}

PersonalOptionsHandler::~PersonalOptionsHandler() {
  ProfileSyncService* sync_service =
      web_ui_->GetProfile()->GetProfileSyncService();
  if (sync_service)
    sync_service->RemoveObserver(this);
}

void PersonalOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  RegisterTitle(localized_strings, "personalPage",
                IDS_OPTIONS_CONTENT_TAB_LABEL);

  localized_strings->SetString(
      "syncOverview",
      l10n_util::GetStringFUTF16(IDS_SYNC_OVERVIEW,
                                 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
  localized_strings->SetString(
      "syncFurtherOverview",
      l10n_util::GetStringUTF16(IDS_SYNC_FURTHER_OVERVIEW));
  localized_strings->SetString("syncSection",
      multiprofile_ ?
          l10n_util::GetStringUTF16(IDS_PROFILES_OPTIONS_GROUP_NAME) :
          l10n_util::GetStringUTF16(IDS_SYNC_OPTIONS_GROUP_NAME));
  localized_strings->SetString("customizeSync",
      multiprofile_ ?
          l10n_util::GetStringUTF16(IDS_PROFILES_SYNC_CUSTOMIZE_BUTTON_LABEL) :
          l10n_util::GetStringUTF16(IDS_SYNC_CUSTOMIZE_BUTTON_LABEL));
  if (multiprofile_) {
    localized_strings->SetString("createNewProfile",
        l10n_util::GetStringUTF16(IDS_PROFILES_CREATE_INFO));
    localized_strings->SetString("createProfileButton",
        l10n_util::GetStringUTF16(IDS_PROFILES_CREATE_BUTTON_LABEL));
  }

  localized_strings->SetString("passwords",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_GROUP_NAME));
  localized_strings->SetString("passwordsAskToSave",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_ASKTOSAVE));
  localized_strings->SetString("passwordsNeverSave",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_NEVERSAVE));
  localized_strings->SetString("manage_passwords",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_MANAGE_PASSWORDS));

  localized_strings->SetString("autofill",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_SETTING_WINDOWS_GROUP_NAME));
  localized_strings->SetString("autofillEnabled",
      l10n_util::GetStringUTF16(IDS_OPTIONS_AUTOFILL_ENABLE));
  localized_strings->SetString("manageAutofillSettings",
      l10n_util::GetStringUTF16(IDS_OPTIONS_MANAGE_AUTOFILL_SETTINGS));

  localized_strings->SetString("browsingData",
      l10n_util::GetStringUTF16(IDS_OPTIONS_BROWSING_DATA_GROUP_NAME));
  localized_strings->SetString("importData",
      l10n_util::GetStringUTF16(IDS_OPTIONS_IMPORT_DATA_BUTTON));

  localized_strings->SetString("themesGallery",
      l10n_util::GetStringUTF16(IDS_THEMES_GALLERY_BUTTON));
  localized_strings->SetString("themesGalleryURL",
      l10n_util::GetStringUTF16(IDS_THEMES_GALLERY_URL));

#if defined(TOOLKIT_GTK)
  localized_strings->SetString("appearance",
      l10n_util::GetStringUTF16(IDS_APPEARANCE_GROUP_NAME));
  localized_strings->SetString("themesGTKButton",
      l10n_util::GetStringUTF16(IDS_THEMES_GTK_BUTTON));
  localized_strings->SetString("themesSetClassic",
      l10n_util::GetStringUTF16(IDS_THEMES_SET_CLASSIC));
  localized_strings->SetString("showWindowDecorations",
      l10n_util::GetStringUTF16(IDS_SHOW_WINDOW_DECORATIONS_RADIO));
  localized_strings->SetString("hideWindowDecorations",
      l10n_util::GetStringUTF16(IDS_HIDE_WINDOW_DECORATIONS_RADIO));
#else
  localized_strings->SetString("themes",
      l10n_util::GetStringUTF16(IDS_THEMES_GROUP_NAME));
  localized_strings->SetString("themesReset",
      l10n_util::GetStringUTF16(IDS_THEMES_RESET_BUTTON));
#endif

  // Sync select control.
  ListValue* sync_select_list = new ListValue;
  ListValue* datatypes = new ListValue;
  datatypes->Append(Value::CreateBooleanValue(false));
  datatypes->Append(
      Value::CreateStringValue(
          l10n_util::GetStringUTF8(IDS_SYNC_OPTIONS_SELECT_DATATYPES)));
  sync_select_list->Append(datatypes);
  ListValue* everything = new ListValue;
  everything->Append(Value::CreateBooleanValue(true));
  everything->Append(
      Value::CreateStringValue(
          l10n_util::GetStringUTF8(IDS_SYNC_OPTIONS_SELECT_EVERYTHING)));
  sync_select_list->Append(everything);
  localized_strings->Set("syncSelectList", sync_select_list);

  // Sync page.
  localized_strings->SetString("syncPage",
      l10n_util::GetStringUTF16(IDS_SYNC_NTP_SYNC_SECTION_TITLE));
  localized_strings->SetString("sync_title",
      l10n_util::GetStringUTF16(IDS_CUSTOMIZE_SYNC_DESCRIPTION));
  localized_strings->SetString("syncsettings",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_PREFERENCES));
  localized_strings->SetString("syncbookmarks",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_BOOKMARKS));
  localized_strings->SetString("synctypedurls",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_TYPED_URLS));
  localized_strings->SetString("syncpasswords",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_PASSWORDS));
  localized_strings->SetString("syncextensions",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_EXTENSIONS));
  localized_strings->SetString("syncautofill",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_AUTOFILL));
  localized_strings->SetString("syncthemes",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_THEMES));
  localized_strings->SetString("syncapps",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_APPS));
  localized_strings->SetString("syncsessions",
      l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_SESSIONS));

#if defined(OS_CHROMEOS)
  localized_strings->SetString("account",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PERSONAL_ACCOUNT_GROUP_NAME));
  localized_strings->SetString("enableScreenlock",
      l10n_util::GetStringUTF16(IDS_OPTIONS_ENABLE_SCREENLOCKER_CHECKBOX));
  localized_strings->SetString("changePicture",
      l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE));
#endif
}

void PersonalOptionsHandler::RegisterMessages() {
  DCHECK(web_ui_);
  web_ui_->RegisterMessageCallback(
      "showSyncActionDialog",
      NewCallback(this, &PersonalOptionsHandler::ShowSyncActionDialog));
  web_ui_->RegisterMessageCallback(
      "showSyncLoginDialog",
      NewCallback(this, &PersonalOptionsHandler::ShowSyncLoginDialog));
  web_ui_->RegisterMessageCallback(
      "showCustomizeSyncDialog",
      NewCallback(this, &PersonalOptionsHandler::ShowCustomizeSyncDialog));
  web_ui_->RegisterMessageCallback(
      "themesReset",
      NewCallback(this, &PersonalOptionsHandler::ThemesReset));
#if defined(TOOLKIT_GTK)
  web_ui_->RegisterMessageCallback(
      "themesSetGTK",
      NewCallback(this, &PersonalOptionsHandler::ThemesSetGTK));
#endif
  web_ui_->RegisterMessageCallback("updatePreferredDataTypes",
      NewCallback(this, &PersonalOptionsHandler::OnPreferredDataTypesUpdated));
#if defined(OS_CHROMEOS)
  web_ui_->RegisterMessageCallback(
      "loadAccountPicture",
      NewCallback(this, &PersonalOptionsHandler::LoadAccountPicture));
#endif
}

void PersonalOptionsHandler::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  if (type == NotificationType::BROWSER_THEME_CHANGED) {
    ObserveThemeChanged();
#if defined(OS_CHROMEOS)
  } else if (type == NotificationType::LOGIN_USER_IMAGE_CHANGED) {
    LoadAccountPicture(NULL);
#endif
  } else {
    OptionsPageUIHandler::Observe(type, source, details);
  }
}

void PersonalOptionsHandler::OnStateChanged() {
  string16 status_label;
  string16 link_label;
  ProfileSyncService* service = web_ui_->GetProfile()->GetProfileSyncService();
  DCHECK(service);
  bool managed = service->IsManaged();
  bool sync_setup_completed = service->HasSyncSetupCompleted();
  bool status_has_error = sync_ui_util::GetStatusLabels(service,
      &status_label, &link_label) == sync_ui_util::SYNC_ERROR;

  string16 start_stop_button_label;
  bool is_start_stop_button_visible = false;
  bool is_start_stop_button_enabled = false;
  if (sync_setup_completed) {
    start_stop_button_label = multiprofile_ ?
        l10n_util::GetStringUTF16(IDS_PROFILES_DISCONNECT_BUTTON_LABEL) :
        l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_BUTTON_LABEL);
#if defined(OS_CHROMEOS)
    is_start_stop_button_visible = false;
#else
    is_start_stop_button_visible = true;
#endif  // defined(OS_CHROMEOS)
    is_start_stop_button_enabled = !managed;
  } else if (service->SetupInProgress()) {
    start_stop_button_label =
        l10n_util::GetStringUTF16(IDS_SYNC_NTP_SETUP_IN_PROGRESS);
    is_start_stop_button_visible = true;
    is_start_stop_button_enabled = false;
  } else {
    start_stop_button_label =
        multiprofile_ ?
            l10n_util::GetStringUTF16(IDS_PROFILES_CONNECT_BUTTON_LABEL) :
            l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL);
    is_start_stop_button_visible = true;
    is_start_stop_button_enabled = !managed;
  }

  scoped_ptr<Value> completed(Value::CreateBooleanValue(sync_setup_completed));
  web_ui_->CallJavascriptFunction("PersonalOptions.setSyncSetupCompleted",
                                  *completed);

  scoped_ptr<Value> label(Value::CreateStringValue(status_label));
  web_ui_->CallJavascriptFunction("PersonalOptions.setSyncStatus", *label);

  scoped_ptr<Value> enabled(
      Value::CreateBooleanValue(is_start_stop_button_enabled));
  web_ui_->CallJavascriptFunction("PersonalOptions.setStartStopButtonEnabled",
                                  *enabled);

  scoped_ptr<Value> visible(
      Value::CreateBooleanValue(is_start_stop_button_visible));
  web_ui_->CallJavascriptFunction("PersonalOptions.setStartStopButtonVisible",
                                  *visible);

  label.reset(Value::CreateStringValue(start_stop_button_label));
  web_ui_->CallJavascriptFunction("PersonalOptions.setStartStopButtonLabel",
                                  *label);

  label.reset(Value::CreateStringValue(link_label));
  web_ui_->CallJavascriptFunction("PersonalOptions.setSyncActionLinkLabel",
                                  *label);

  enabled.reset(Value::CreateBooleanValue(!managed));
  web_ui_->CallJavascriptFunction("PersonalOptions.setSyncActionLinkEnabled",
                                  *enabled);

  visible.reset(Value::CreateBooleanValue(status_has_error));
  web_ui_->CallJavascriptFunction("PersonalOptions.setSyncStatusErrorVisible",
                                  *visible);

  // Set profile creation text and button if multi-profiles switch is on.
  if (multiprofile_) {
    visible.reset(Value::CreateBooleanValue(true));
    web_ui_->CallJavascriptFunction("PersonalOptions.setProfilesSectionVisible",
                                    *visible);

    // TODO(mirandac): enable when back end is ready.
    enabled.reset(Value::CreateBooleanValue(false));
    web_ui_->CallJavascriptFunction(
        "PersonalOptions.setNewProfileButtonEnabled", *enabled);
  } else {
    visible.reset(Value::CreateBooleanValue(false));
    web_ui_->CallJavascriptFunction("PersonalOptions.setProfilesSectionVisible",
                                    *visible);
  }
}

void PersonalOptionsHandler::OnLoginSuccess() {
  OnStateChanged();
}

void PersonalOptionsHandler::OnLoginFailure(
    const GoogleServiceAuthError& error) {
  OnStateChanged();
}

void PersonalOptionsHandler::ObserveThemeChanged() {
  Profile* profile = web_ui_->GetProfile();
#if defined(TOOLKIT_GTK)
  GtkThemeService* provider = GtkThemeService::GetFrom(profile);
  bool is_gtk_theme = provider->UseGtkTheme();
  FundamentalValue gtk_enabled(!is_gtk_theme);
  web_ui_->CallJavascriptFunction(
      "options.PersonalOptions.setGtkThemeButtonEnabled", gtk_enabled);
#else
  ThemeService* provider = ThemeServiceFactory::GetForProfile(profile);
  bool is_gtk_theme = false;
#endif

  bool is_classic_theme = !is_gtk_theme && provider->UsingDefaultTheme();
  FundamentalValue enabled(!is_classic_theme);
  web_ui_->CallJavascriptFunction(
      "options.PersonalOptions.setThemesResetButtonEnabled", enabled);
}

void PersonalOptionsHandler::Initialize() {
  banner_handler_.reset(
      new OptionsManagedBannerHandler(web_ui_,
                                      ASCIIToUTF16("PersonalOptions"),
                                      OPTIONS_PAGE_CONTENT));

  // Listen for theme installation.
  registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
                 NotificationService::AllSources());
  ObserveThemeChanged();

  ProfileSyncService* sync_service =
      web_ui_->GetProfile()->GetProfileSyncService();
  if (sync_service) {
    sync_service->AddObserver(this);
    OnStateChanged();

    DictionaryValue args;
    SyncSetupFlow::GetArgsForConfigure(sync_service, &args);

    web_ui_->CallJavascriptFunction("PersonalOptions.setRegisteredDataTypes",
                                    args);
  } else {
    web_ui_->CallJavascriptFunction("options.PersonalOptions.hideSyncSection");
  }
}

void PersonalOptionsHandler::ShowSyncActionDialog(const ListValue* args) {
  ProfileSyncService* service = web_ui_->GetProfile()->GetProfileSyncService();
  DCHECK(service);
  service->ShowErrorUI(NULL);
}

void PersonalOptionsHandler::ShowSyncLoginDialog(const ListValue* args) {
  ProfileSyncService* service = web_ui_->GetProfile()->GetProfileSyncService();
  DCHECK(service);
  service->ShowLoginDialog(NULL);
  ProfileSyncService::SyncEvent(ProfileSyncService::START_FROM_OPTIONS);
}

void PersonalOptionsHandler::ShowCustomizeSyncDialog(const ListValue* args) {
  ProfileSyncService* service = web_ui_->GetProfile()->GetProfileSyncService();
  DCHECK(service);
  service->ShowConfigure(NULL, false);
}

void PersonalOptionsHandler::ThemesReset(const ListValue* args) {
  UserMetricsRecordAction(UserMetricsAction("Options_ThemesReset"));
  ThemeServiceFactory::GetForProfile(web_ui_->GetProfile())->UseDefaultTheme();
}

#if defined(TOOLKIT_GTK)
void PersonalOptionsHandler::ThemesSetGTK(const ListValue* args) {
  UserMetricsRecordAction(UserMetricsAction("Options_GtkThemeSet"));
  ThemeServiceFactory::GetForProfile(web_ui_->GetProfile())->SetNativeTheme();
}
#endif

void PersonalOptionsHandler::OnPreferredDataTypesUpdated(
    const ListValue* args) {
  NotificationService::current()->Notify(
      NotificationType::SYNC_DATA_TYPES_UPDATED,
      Source<Profile>(web_ui_->GetProfile()),
      NotificationService::NoDetails());
}

#if defined(OS_CHROMEOS)
void PersonalOptionsHandler::LoadAccountPicture(const ListValue* args) {
  const chromeos::UserManager::User& user =
      chromeos::UserManager::Get()->logged_in_user();
  std::string email = user.email();
  if (!email.empty()) {
    // int64 is either long or long long, but we need a certain format
    // specifier.
    long long timestamp = base::TimeTicks::Now().ToInternalValue();
    StringValue image_url(
        StringPrintf("%s%s?id=%lld",
                     chrome::kChromeUIUserImageURL,
                     email.c_str(),
                     timestamp));
    web_ui_->CallJavascriptFunction("PersonalOptions.setAccountPicture",
                                    image_url);
  }
}

#endif


text:
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var mongoose = require('mongoose');

var userSchema = new mongoose.Schema({
  email: { type: String, unique: true, lowercase: true },
  password: String,

  facebook: String,
  twitter: String,
  google: String,
  tokens: Array,

  profile: {
    name: { type: String, default: '' },
    gender: { type: String, default: '' },
    location: { type: String, default: '' },
    website: { type: String, default: '' },
    picture: { type: String, default: '' }
  },

  selected: String,
  locations: Array,
  favorites: Array,
  // order: {
  //   pickup: { type: String, default: '' },
  //   delivery: { type: String, default: '' },
  //   order_type: { type: String, default: '' },
  //   rice: { type: String, default: '' },
  //   beans: { type: String, default: '' },
  //   meat: { type: String, default: '' },
  //   toppings: { type: String, default: '' },
  //   additional: { type: String, default: '' }
  // },

  resetPasswordToken: String,
  resetPasswordExpires: Date
});

/**
 * Password hash middleware.
 */
userSchema.pre('save', function(next) {
  var user = this;
  if (!user.isModified('password')) return next();
  bcrypt.genSalt(10, function(err, salt) {
    if (err) return next(err);
    bcrypt.hash(user.password, salt, null, function(err, hash) {
      if (err) return next(err);
      user.password = hash;
      next();
    });
  });
});

/**
 * Helper method for validating user's password.
 */
userSchema.methods.comparePassword = function(candidatePassword, cb) {
  bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
    if (err) return cb(err);
    cb(null, isMatch);
  });
};

/**
 * Helper method for getting user's gravatar.
 */
userSchema.methods.gravatar = function(size) {
  if (!size) size = 200;
  if (!this.email) return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';
  var md5 = crypto.createHash('md5').update(this.email).digest('hex');
  return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';
};

module.exports = mongoose.model('User', userSchema);


text:
#ifndef _ICON_UTILS_H
#define _ICON_UTILS_H

#include <Mime.h>

class BBitmap;
class BNode;

// This class is a little different from many other classes.
// You don't create an instance of it; you just call its various
// static member functions for utility-like operations.
class BIconUtils {
								BIconUtils();
								~BIconUtils();
								BIconUtils(const BIconUtils&);
			BIconUtils&			operator=(const BIconUtils&);

public:

	// Utility function to import an icon from the node that
	// has either of the provided attribute names. Which icon type
	// is preferred (vector, small or large B_CMAP8 icon) depends
	// on the colorspace of the provided bitmap. If the colorspace
	// is B_CMAP8, B_CMAP8 icons are preferred. In that case, the
	// bitmap size must also match the provided icon_size "size"!
	static	status_t			GetIcon(BNode* node,
									const char* vectorIconAttrName,
									const char* smallIconAttrName,
									const char* largeIconAttrName,
									icon_size size, BBitmap* result);

	// Utility functions to import a vector icon in "flat icon"
	// format from a BNode attribute or from a flat buffer in
	// memory into the preallocated BBitmap "result".
	// The colorspace of result needs to be B_RGBA32 or at
	// least B_RGB32 (though that makes less sense). The icon
	// will be scaled from it's "native" size of 64x64 to the
	// size of the bitmap, the scale is derived from the bitmap
	// width, the bitmap should have square dimension, or the
	// icon will be cut off at the bottom (or have room left).
	static	status_t			GetVectorIcon(BNode* node,
									const char* attrName, BBitmap* result);

	static	status_t			GetVectorIcon(const uint8* buffer,
									size_t size, BBitmap* result);

	// Utility function to import an "old" BeOS icon in B_CMAP8
	// colorspace from either the small icon attribute or the
	// large icon attribute as given in "smallIconAttrName" and
	// "largeIconAttrName". Which icon is loaded depends on
	// the given "size".
	static	status_t			GetCMAP8Icon(BNode* node,
									const char* smallIconAttrName,
									const char* largeIconAttrName,
									icon_size size, BBitmap* icon);

	// Utility functions to convert from old icon colorspace
	// into colorspace of BBitmap "result" (should be B_RGBA32
	// to make any sense).
	static	status_t			ConvertFromCMAP8(BBitmap* source,
									BBitmap* result);
	static	status_t			ConvertToCMAP8(BBitmap* source,
									BBitmap* result);

	static	status_t			ConvertFromCMAP8(const uint8* data,
									uint32 width, uint32 height,
									uint32 bytesPerRow, BBitmap* result);

	static	status_t			ConvertToCMAP8(const uint8* data,
									uint32 width, uint32 height,
									uint32 bytesPerRow, BBitmap* result);
};

#endif	// _ICON_UTILS_H


text:
CREATE TABLE client (
    id integer NOT NULL auto_increment,
    name nvarchar(500) NOT NULL,
    priority int NOT NULL,
    primary key (id)
);


text:
/*
  Copyright (c) 2013 Microsoft Corporation. All rights reserved.
  Released under Apache 2.0 license as described in the file LICENSE.

  Author: Lev Nachmanson
*/
#include <string>
#include <vector>
#include "util/lp/lar_core_solver.h"
namespace lean {
template <typename T, typename X>
lar_core_solver<T, X>::lar_core_solver(std::vector<X> & x, std::vector<column_type> & column_types,
                                       std::vector<X> & low_bounds, std::vector<X> & upper_bounds,
                                       std::vector<unsigned> & basis,
                                       static_matrix<T, X> & A,
                                       lp_settings & settings,
                                       std::unordered_map<unsigned, std::string> & column_names):
    lp_core_solver_base<T, X>(A,
                              m_right_sides_dummy,
                              basis,
                              x,
                              m_costs_dummy,
                              settings,
                              column_names,
                              column_types,
                              low_bounds,
                              upper_bounds) {
}

template <typename T, typename X> void lar_core_solver<T, X>::init_costs() {
    lean_assert(this->m_x.size() >= this->m_n);
    lean_assert(this->m_column_type.size() >= this->m_n);
    X inf = m_infeasibility;
    m_infeasibility = zero_of_type<X>();
    for (unsigned j = this->m_n; j--;)
        init_cost_for_column(j);
    if (!(this->total_iterations() ==0 || inf >= m_infeasibility)) {
        std::cout << "inf was " << T_to_string(inf) << " and now " << T_to_string(m_infeasibility) << std::endl;
        lean_assert(false);
    }
    if (inf == m_infeasibility)
        this->m_iters_with_no_cost_growing++;
}

template <typename T, typename X>    void lar_core_solver<T, X>::init_cost_for_column(unsigned j) {
    // If j is a breakpoint column, then we set the cost zero.
    // When anylyzing an entering column candidate we update the cost of the breakpoints columns to get the left or the right derivative if the infeasibility function
    const X & x = this->m_x[j];
    // set zero cost for each non-basis column
    if (this->m_basis_heading[j] < 0) {
        this->m_costs[j] = numeric_traits<T>::zero();
        return;
    }
    // j is a basis column
    switch (this->m_column_type[j]) {
    case fixed:
    case boxed:
        if (x > this->m_upper_bound_values[j]) {
            this->m_costs[j] = 1;
            m_infeasibility += x - this->m_upper_bound_values[j];
        } else if (x < this->m_low_bound_values[j]) {
            m_infeasibility += this->m_low_bound_values[j] - x;
            this->m_costs[j] = -1;
        } else {
            this->m_costs[j] = numeric_traits<T>::zero();
        }
        break;
    case low_bound:
        if (x < this->m_low_bound_values[j]) {
            this->m_costs[j] = -1;
            m_infeasibility += this->m_low_bound_values[j] - x;
        } else {
            this->m_costs[j] = numeric_traits<T>::zero();
        }
        break;
    case upper_bound:
        if (x > this->m_upper_bound_values[j]) {
            this->m_costs[j] = 1;
            m_infeasibility += x - this->m_upper_bound_values[j];
        } else {
            this->m_costs[j] = numeric_traits<T>::zero();
        }
        break;
    case free_column:
        this->m_costs[j] = numeric_traits<T>::zero();
        break;
    default:
        lean_assert(false);
        break;
    }
}

template <typename T, typename X>    void lar_core_solver<T, X>::init_local() {
    this->m_m = this->m_A.row_count();
    this->m_n = this->m_A.column_count();
    this->m_pivot_row_of_B_1.resize(this->m_m);
    this->m_pivot_row.resize(this->m_n);
    this->m_b.resize(this->m_m);
    this->m_y.resize(this->m_m);
    this->m_w.resize(this->m_m);
    this->m_d.resize(this->m_n);
    this->m_ed.resize(this->m_m);
    this->m_costs.resize(this->m_n);
    this->m_breakpoint_indices_queue.resize(this->m_n);
    this->m_copy_of_xB.resize(this->m_n);
}

// returns m_sign_of_alpha_r
template <typename T, typename X>    int lar_core_solver<T, X>::column_is_out_of_bounds(unsigned j) {
    switch (this->m_column_type[j]) {
    case fixed:
    case boxed:
        if (this->x_below_low_bound(j)) {
            return -1;
        }
        if (this->x_above_upper_bound(j)) {
            return 1;
        }
        return 0;
    case low_bound:
        if (this->x_below_low_bound(j)) {
            return -1;
        }
        return 0;
    case upper_bound:
        if (this->x_above_upper_bound(j)) {
            return 1;
        }
        return 0;
    default:
        return 0;
        break;
    }
}

template <typename T, typename X>    bool lar_core_solver<T, X>::can_enter_basis_mpq(unsigned j) {
    switch (this->m_column_type[j]) {
    case low_bound:
        lean_assert(this->x_is_at_low_bound(j));
        return this->m_d[j] < numeric_traits<T>::zero();
    case upper_bound:
        lean_assert(this->x_is_at_upper_bound(j));
        return this->m_d[j] > numeric_traits<T>::zero();
    case fixed:
        return false;
    case boxed:
        {
            bool low_bound = this->x_is_at_low_bound(j);
            lean_assert(low_bound || this->x_is_at_upper_bound(j));
            return (low_bound && this->m_d[j] < numeric_traits<T>::zero()) || ((!low_bound) && this->m_d[j] > numeric_traits<T>::zero());
        }
    case free_column:
        return !numeric_traits<T>::is_zero(this->m_d[j]);
    default:
        return false;
    }
    return false;
}

template <typename T, typename X>    void lar_core_solver<T, X>::calculate_pivot_row(unsigned i) {
    this->calculate_pivot_row_of_B_1(i);
    this->calculate_pivot_row_when_pivot_row_of_B1_is_ready();
}

#ifdef LEAN_DEBUG
template <typename T, typename X>    X lar_core_solver<T, X>::get_deb_inf_column(unsigned j) {
    const X & x = this->m_x[j];
    switch (this->m_column_type[j]) {
    case low_bound:
        if (x < this->m_low_bound_values[j])
            return this->m_low_bound_values[j] - x;
        return zero_of_type<X>();
    case upper_bound:
        if (x > this->m_upper_bound_values[j])
            return x - this->m_upper_bound_values[j];
        return zero_of_type<X>();
    case fixed:
    case boxed:
        {
            if (x < this->m_low_bound_values[j])
                return this->m_low_bound_values[j] - x;
            if (x > this->m_upper_bound_values[j])
                return x - this->m_upper_bound_values[j];
            return zero_of_type<X>();
        }
    case free_column:
        {
            return zero_of_type<X>();
        }
    default:
        lean_assert(false);
        return zero_of_type<X>();
    }
}

template <typename T, typename X>    X lar_core_solver<T, X>::get_deb_inf() {
    X ret = zero_of_type<X>();
    for (unsigned j = 0; j < this->m_n; j++) {
        X d = get_deb_inf_column(j);
        ret += d;
    }
    return ret;
}

template <typename T, typename X> bool lar_core_solver<T, X>::debug_profit_delta(unsigned j, const T & delta, std::ostream & out) {
    this->update_x(j, delta);
    bool ret = m_infeasibility > get_deb_inf();
    if (ret) {
        out << "found profit for " << this->column_name(j) << " and delta = " << delta.get_double() << std::endl;
        out << "improvement = " << (m_infeasibility -  get_deb_inf()).get_double() << std::endl;
    }
    return ret;
}

template <typename T, typename X>    bool lar_core_solver<T, X>::debug_profit(unsigned j, std::ostream & out) {
    if (this->m_column_type[j] == fixed) return false;
    T delta = numeric_traits<T>::one() / 10000000;
    delta /= 10000000;
    return debug_profit_delta(j, -delta, out) || debug_profit_delta(j, delta, out);
}
#endif
template <typename T, typename X>    int lar_core_solver<T, X>::choose_column_entering_basis() {
    unsigned offset = my_random() % this->m_non_basic_columns.size();
    unsigned initial_offset_in_non_basis = offset;
    do {
        unsigned j = this->m_non_basic_columns[offset];
        if (can_enter_basis_mpq(j))
            return j;
        offset++;
        if (offset == this->m_non_basic_columns.size()) offset = 0;
    } while (offset != initial_offset_in_non_basis);
    return -1;
}

template <typename T, typename X>    void lar_core_solver<T, X>::one_iteration() {
    this->m_total_iterations++;
    lean_assert(this->m_non_basic_columns.size()  + this->m_basis.size() == this->m_basis_heading.size());
    if (is_zero(m_infeasibility)) {
        this->m_status = OPTIMAL;
        return;
    }
    int entering = choose_column_entering_basis();
    if (entering == -1) {
        decide_on_status_when_cannot_enter();
    } else {
        advance_on_entering(entering);
    }
}

template <typename T, typename X>    void lar_core_solver<T, X>::decide_on_status_when_cannot_enter() {
    if (!is_zero(m_infeasibility))
        this->m_status = INFEASIBLE;
    else
        this->m_status = FEASIBLE;
}

// j is the basic column, x is the value at x[j]
// d is the coefficient before m_entering in the row with j as the basis column
template <typename T, typename X>    void lar_core_solver<T, X>::try_add_breakpoint(unsigned j, const X & x, const T & d, breakpoint_type break_type, const X & break_value) {
    X diff = x - break_value;
    if (is_zero(diff)) {
        switch (break_type) {
        case low_break:
            if (!same_sign_with_entering_delta(d))
                return; // no breakpoint
            break;
        case upper_break:
            if (same_sign_with_entering_delta(d))
                return; // no breakpoint
            break;
        default: break;
        }
        add_breakpoint(j, zero_of_type<X>(), break_type);
        return;
    }
    auto delta_j =  diff / d;
    if (same_sign_with_entering_delta(delta_j))
        add_breakpoint(j, delta_j, break_type);
}

template <typename T, typename X>    void lar_core_solver<T, X>::add_breakpoint(unsigned j, X delta, breakpoint_type type) {
    m_breakpoints.push_back(breakpoint<X>(j, delta, type));
    m_breakpoint_indices_queue.enqueue(m_breakpoint_indices_queue.size(), abs(delta));
}

template <typename T, typename X>    void lar_core_solver<T, X>::try_add_breakpoint_in_row(unsigned i) {
    lean_assert(i < this->m_m);
    const T & d = this->m_ed[i]; // the coefficient before m_entering in the i-th row
    if (d == 0) return; // the change of x[m_entering] will not change the corresponding basis x
    unsigned j = this->m_basis[i];
    const X & x = this->m_x[j];
    switch (this->m_column_type[j]) {
    case fixed:
        try_add_breakpoint(j, x, d, fixed_break, this->m_low_bound_values[j]);
        break;
    case boxed:
        try_add_breakpoint(j, x, d, low_break, this->m_low_bound_values[j]);
        try_add_breakpoint(j, x, d, upper_break, this->m_upper_bound_values[j]);
        break;
    case low_bound:
        try_add_breakpoint(j, x, d, low_break, this->m_low_bound_values[j]);
        break;
    case upper_bound:
        try_add_breakpoint(j, x, d, upper_break, this->m_upper_bound_values[j]);
        break;
    case free_column:
        break;
    default:
        lean_assert(false);
        break;
    }
}

template <typename T, typename X> std::string lar_core_solver<T, X>::break_type_to_string(breakpoint_type type) {
    switch (type){
    case low_break: return "low_break";
    case upper_break: return "upper_break";
    case fixed_break: return "fixed_break";
    default:
        lean_assert(false);
        break;
    }
    return "type is not found";
}

template <typename T, typename X> void lar_core_solver<T, X>::print_breakpoint(const breakpoint<X> * b, std::ostream & out) {
    out << "(" << this->column_name(b->m_j) << "," << break_type_to_string(b->m_type) << "," << T_to_string(b->m_delta) << ")" << std::endl;
    print_bound_info_and_x(b->m_j);
}

template <typename T, typename X> void lar_core_solver<T, X>::print_bound_info_and_x(unsigned j, std::ostream & out) {
    out << "type of " << this->column_name(j) << " is " << column_type_to_string(this->m_column_type[j]) << std::endl;
    out << "x[" << this->column_name(j) << "] = " << this->m_x[j] << std::endl;
    switch (this->m_column_type[j]) {
    case fixed:
    case boxed:
        out << "[" << this->m_low_bound_values[j] << "," << this->m_upper_bound_values[j] << "]" << std::endl;
        break;
    case low_bound:
        out << "[" << this->m_low_bound_values[j] << ", inf" << std::endl;
        break;
    case upper_bound:
        out << "inf ," << this->m_upper_bound_values[j] << "]" << std::endl;
        break;
    case free_column:
        out << "inf, inf" << std::endl;
        break;
    default:
        lean_assert(false);
        break;
    }
}

template <typename T, typename X>    void lar_core_solver<T, X>::clear_breakpoints() {
    m_breakpoints.clear();
    m_breakpoint_indices_queue.clear();
}

template <typename T, typename X>    void lar_core_solver<T, X>::fill_breakpoints_array(unsigned entering) {
    clear_breakpoints();
    for (unsigned i = this->m_m; i--;)
        try_add_breakpoint_in_row(i);

    if (this->m_column_type[entering] == boxed) {
        if (m_sign_of_entering_delta < 0)
            add_breakpoint(entering, - this->bound_span(entering), low_break);
        else
            add_breakpoint(entering, this->bound_span(entering), upper_break);
    }
}

template <typename T, typename X>    void lar_core_solver<T, X>::advance_on_entering(unsigned entering) {
    this->solve_Bd(entering); // prepares the entering column to be like the one of the tableau
    m_sign_of_entering_delta = this->m_d[entering] < zero_of_type<T>() ? 1 : -1;

    fill_breakpoints_array(entering);
    advance_on_sorted_breakpoints(entering);
}

template <typename T, typename X> void lar_core_solver<T, X>::print_cost(std::ostream & out) {
    out << "reduced costs " << std::endl;
    for (unsigned j = 0; j < this->m_n; j++) {
        if (numeric_traits<T>::is_zero(this->m_d[j])) continue;
        out << T_to_string(this->m_d[j]) << this->column_name(j) << " ";
    }
    out << std::endl;
}

template <typename T, typename X> void lar_core_solver<T, X>::update_basis_and_x_with_comparison(unsigned entering, unsigned leaving, X delta) {
    if (entering != leaving)
        this->update_basis_and_x(entering, leaving, delta);
    else
        this->update_x(entering, delta);
}

template <typename T, typename X>    void lar_core_solver<T, X>::advance_on_sorted_breakpoints(unsigned entering) {
    T slope_at_entering = this->m_d[entering];
    breakpoint<X> * last_bp = nullptr;
    while (m_breakpoint_indices_queue.is_empty() == false) {
        unsigned bi = m_breakpoint_indices_queue.dequeue();
        breakpoint<X> *b = &m_breakpoints[bi];
        change_slope_on_breakpoint(entering, b, slope_at_entering);
        last_bp = b;
        if (slope_at_entering * m_sign_of_entering_delta > 0) { // the slope started to increase infeasibility
            break;
        } else {
            if (numeric_traits<T>::is_zero(slope_at_entering) && my_random() % 2 == 0) {
                // it is not cost benefitial to advance the delta more, so just break to increas the randomness
                break;
            }
        }
    }
    update_basis_and_x_with_comparison(entering, last_bp->m_j, last_bp->m_delta);
}

template <typename T, typename X>    void lar_core_solver<T, X>::change_slope_on_breakpoint(unsigned entering, breakpoint<X> * b, T & slope_at_entering) {
    if (b->m_j == entering) {
        lean_assert(b->m_type != fixed_break && (!is_zero(b->m_delta)));
        slope_at_entering += m_sign_of_entering_delta;
        return;
    }

    lean_assert(this->m_basis_heading[b->m_j] >= 0);
    unsigned i_row = this->m_basis_heading[b->m_j];
    const T & d = - this->m_ed[i_row];
    if (numeric_traits<T>::is_zero(d)) return;

    T delta = m_sign_of_entering_delta * abs(d);
    switch (b->m_type) {
    case fixed_break:
        if (is_zero(b->m_delta)) {
            slope_at_entering += delta;
        } else {
            slope_at_entering += 2 * delta;
        }
        break;
    case low_break:
    case upper_break:
        slope_at_entering += delta;
        break;
    default:
        lean_assert(false);
    }
}

template <typename T, typename X>    bool lar_core_solver<T, X>::row_is_infeasible(unsigned row, int & inf_sign) {
    unsigned j = this->m_basis[row];
    inf_sign = get_infeasibility_sign(j);
    return inf_sign != 0;
}

template <typename T, typename X>    bool lar_core_solver<T, X>::row_is_evidence(unsigned row, int & inf_sign) {
    if (!row_is_infeasible(row, inf_sign)) return false;
    calculate_pivot_row(row);
    int entering = choose_entering_column_for_row_inf_strategy(inf_sign);
    if (entering == -1) {
        return true;
    }
    return false;
}

template <typename T, typename X>    bool lar_core_solver<T, X>::find_evidence_row() {
    for (unsigned i = this->m_m; --i;) {
        int inf_sign;
        if (row_is_evidence(i, inf_sign)) {
            fill_evidence(i, inf_sign);
            return true;
        }
    }
    return false;
}

template <typename T, typename X> bool lar_core_solver<T, X>::done() {
    if (this->m_status == OPTIMAL) return true;
    if (this->m_status == INFEASIBLE) {
        if (this->m_settings.row_feasibility == false) {
            if (!find_evidence_row()) {
                this->m_status = FEASIBLE;
                row_feasibility_loop();
            }
        }
        return true;
    }

    if (this->m_iters_with_no_cost_growing >= this->m_settings.max_number_of_iterations_with_no_improvements) {
        this->m_status = ITERATIONS_EXHAUSTED; return true;
    }
    if (this->total_iterations() >= this->m_settings.max_total_number_of_iterations) {
        this->m_status = ITERATIONS_EXHAUSTED; return true;
    }
    return false;
}

template <typename T, typename X>    void lar_core_solver<T, X>::move_as_many_as_possible_fixed_columns_to_non_basis() {
    unsigned i = 0; // points to basis
    auto& bs = this->m_basis;
    unsigned j = 0; // points to m_column_types
    auto & ct = this->m_column_type;
    std::vector<int> heading(this->m_n, -1);
    for (int i = 0; i < bs.size(); i ++) heading[bs[j]] = i;
    lean_assert(this->m_basis.size() == this->m_m);
    while (i < this->m_m && j < ct.size()) {
        unsigned basis_j = bs[i];
        if (ct[basis_j] != fixed) {i++; continue;}
        do {
            if (heading[j] == -numeric_traits<T>::one() && ct[j] != fixed)
                break;
            j++;
        } while (j < ct.size());
        if (j == ct.size()) break;
        bs[i++] = j++;
    }
}

template <typename T, typename X> bool lar_core_solver<T, X>::non_basis_columns_are_set_correctly() {
    for (unsigned j : this->m_non_basic_columns) {
        if (!this->x_is_at_bound(j))
            return false;
    }
    return true;
}

template <typename T, typename X> void lar_core_solver<T, X>::prefix() {
    init_local();
    this->init();
    this->init_basis_heading();
}

template <typename T, typename X> void lar_core_solver<T, X>::feasibility_loop() {
    while (true) {
        init_costs();
        this->init_reduced_costs_for_one_iteration();
        if (this->print_statistics_with_cost_and_check_that_the_time_is_over(this->total_iterations(), m_infeasibility)){
            this->m_status = lp_status::TIME_EXHAUSTED;
            return; // this->m_total_iterations;
        }
        one_iteration();
        if (done()) {
            break;
        }
    }
}

template <typename T, typename X>    unsigned lar_core_solver<T, X>::get_number_of_inf_rows() const {
    unsigned r = 0;
    for (unsigned k = this->m_m; --k;) {
        unsigned j = this->m_basis[k];
        if (get_infeasibility_sign(j)) r++;
    }
    return r;
}

template <typename T, typename X>    void lar_core_solver<T, X>::row_feasibility_loop() {
    while (true) {
        if (this->print_statistics_with_iterations_and_check_that_the_time_is_over(this->m_total_iterations++)){
            this->m_status = lp_status::TIME_EXHAUSTED;
            return; // this->m_total_iterations;
        }
        int inf_sign;
        int i = find_infeasible_row(inf_sign);
        if (i == -1) {
            this->m_status = OPTIMAL;
            break;
        }
        advance_on_infeasible_row(i, inf_sign);
        if (done())
            break;
    }
}

template <typename T, typename X>    int lar_core_solver<T, X>::find_infeasible_row(int & inf_sign) {
    unsigned offset = my_random() % this->m_m;
    unsigned initial_offset_in_basis = offset;
    do {
        unsigned j = this->m_basis[offset];
        inf_sign = get_infeasibility_sign(j);
        if (inf_sign)
            return offset;
        if (++offset == this->m_m) offset = 0;
    } while (offset != initial_offset_in_basis);
    return -1;
}

template <typename T, typename X>    int lar_core_solver<T, X>::get_infeasibility_sign(unsigned j) const {
    const auto & x = this->m_x[j];
    switch (this->m_column_type[j]) {
    case fixed:
    case boxed:
        if (x < this->m_low_bound_values[j]) return 1;
        if (x > this->m_upper_bound_values[j]) return -1;
        return 0;
    case low_bound:
        return x < this->m_low_bound_values[j] ? 1 : 0;
    case upper_bound:
        return x > this->m_upper_bound_values[j]? -1 :0;
    default:
        return 0;
    }
}

template <typename T, typename X>    bool lar_core_solver<T, X>::improves_pivot_row_inf(unsigned j, int inf_sign) {
    lean_assert(this->m_basis_heading[j] < 0);
    // we have x[basis[i]] = sum (mj*x[j]), where mj = -m_pivot_row[j]

    switch (this->m_column_type[j]) {
    case fixed:
        return false;
    case boxed:
        {
            lean_assert(this->x_is_at_bound(j));
            int j_sign = - get_sign(this->m_pivot_row[j]) * inf_sign;
            if (this->x_is_at_low_bound(j))
                return j_sign > 0;
            return j_sign < 0;
        }
    case low_bound:
        {
            lean_assert(this->x_is_at_low_bound(j));
            int j_sign = - get_sign(this->m_pivot_row[j]) * inf_sign;
            return j_sign > 0;
        }
    case upper_bound:
        {
            lean_assert(this->x_is_at_upper_bound(j));
            int j_sign = - get_sign(this->m_pivot_row[j]) * inf_sign;
            return j_sign < 0;
        }
        break;
    case free_column: {
        return numeric_traits<T>::is_zero(this->m_pivot_row[j]) == false;
    }
    default:
        lean_assert(false);
    }
    return false; // it is unreachable
}

template <typename T, typename X>    int lar_core_solver<T, X>::choose_entering_column_for_row_inf_strategy(int inf_sign) {
    unsigned offset = my_random() % this->m_non_basic_columns.size();
    unsigned initial_offset_in_non_basis = offset;
    do {
        unsigned j = this->m_non_basic_columns[offset];
        if (improves_pivot_row_inf(j, inf_sign))
            return j;
        if (++offset == this->m_non_basic_columns.size()) offset = 0;
    } while (offset != initial_offset_in_non_basis);
    return -1;
}

template <typename T, typename X>    void lar_core_solver<T, X>::fill_evidence(unsigned row, int inf_sign) {
    m_infeasible_row_sign = inf_sign;
    m_infeasible_row.push_back(std::make_pair(numeric_traits<T>::one(), this->m_basis[row]));
    for (auto j : this->m_non_basic_columns) {
        T aj = this->m_pivot_row[j];
        if (!numeric_traits<T>::is_zero(aj)) {
            m_infeasible_row.push_back(std::make_pair(aj, j));
        }
    }
}

template <typename T, typename X>    void lar_core_solver<T, X>::update_delta_of_entering_and_leaving_candidates(X del, X & delta,
                                                                                std::vector<unsigned> & leaving_candidates,
                                                                                unsigned bj) {
    if (del < delta) {
        leaving_candidates.clear();
        leaving_candidates.push_back(bj);
        delta = del;
    } else if (del == delta) {
        leaving_candidates.push_back(bj);
    }
}

template <typename T, typename X>    void lar_core_solver<T, X>::update_delta_of_entering(int delta_sign, unsigned row, X & delta,
                                                                                std::vector<unsigned> & leaving_candidates) {
    unsigned bj = this->m_basis[row]; // bj - the basis column for the row
    const T & ed = this->m_ed[row]; // this is the coefficent before x[entering] in the sum representing the basis column of this row taken with minus
    if (numeric_traits<T>::is_zero(ed)) return;
    const X & x = this->m_x[bj]; // the value of the basis column
    // adjusted sign
    int adj_sign = ed < zero_of_type<T>() ? delta_sign : - delta_sign;

    switch (this->m_column_type[bj]) {
    case fixed:
    case boxed:
        if (adj_sign > 0 && x <= this->m_upper_bound_values[bj])
            update_delta_of_entering_and_leaving_candidates((this->m_upper_bound_values[bj] - x) / abs(ed), delta, leaving_candidates, bj);
        else if (adj_sign < 0 && x >= this->m_low_bound_values[bj])
            update_delta_of_entering_and_leaving_candidates((x - this->m_low_bound_values[bj]) / abs(ed), delta, leaving_candidates, bj);
        break;
    case low_bound:
        if (adj_sign < 0 && x >= this->m_low_bound_values[bj])
            update_delta_of_entering_and_leaving_candidates((x - this->m_low_bound_values[bj]) / abs(ed), delta, leaving_candidates, bj);
        break;
    case upper_bound:
        if (adj_sign > 0 && x <= this->m_upper_bound_values[bj])
            update_delta_of_entering_and_leaving_candidates((this->m_upper_bound_values[bj] - x) / abs(ed), delta, leaving_candidates, bj);
        break;
    default:
        break;
    }
}

template <typename T, typename X>    X lar_core_solver<T, X>::find_initial_delta_and_its_sign(unsigned row, unsigned entering,
                                                                                int inf_sign, int & entering_delta_sign,
                                                                                std::vector<unsigned> & leaving_candidates) {
    lean_assert(inf_sign != 0);
    unsigned bj = this->m_basis[row]; // this is the infeasible basis column
    const X & x = this->m_x[bj];
    entering_delta_sign = - get_sign(this->m_pivot_row[entering]) * inf_sign;
    lean_assert(entering_delta_sign != 0);
    X delta = (inf_sign > 0? (this->m_low_bound_values[bj] - x) : (x - this->m_upper_bound_values[bj])) / abs(this->m_pivot_row[entering]);
    if (this->m_column_type[entering] == boxed) {
        X span = this->bound_span(entering);
        if (span < delta) {
            delta = span;
            leaving_candidates.push_back(entering);
        } else {
            leaving_candidates.push_back(bj);
        }
    } else {
        leaving_candidates.push_back(bj);
    }

    return delta;
}

template <typename T, typename X>    void lar_core_solver<T, X>::advance_on_infeasible_row_and_entering(unsigned inf_row, unsigned entering, int inf_sign) {
    this->solve_Bd(entering); // puts the tableau column of entering into this->m_ed
    int entering_delta_sign;
    std::vector<unsigned> leaving_candidates;
    X delta = find_initial_delta_and_its_sign(inf_row, entering, inf_sign, entering_delta_sign, leaving_candidates);
    lean_assert(leaving_candidates.size() > 0);
    lean_assert(delta > zero_of_type<X>());
    unsigned row = my_random() % this->m_m;
    unsigned initial_row = row;
    do {
        if (row != inf_row)
            update_delta_of_entering(entering_delta_sign, row, delta, leaving_candidates);
        if (++row == this->m_m) row = 0;
    } while (row != initial_row);
    unsigned leaving = find_leaving_for_inf_row_strategy(leaving_candidates);
    update_basis_and_x_with_comparison(entering, leaving, delta * entering_delta_sign);
}

template <typename T, typename X>    void lar_core_solver<T, X>::advance_on_infeasible_row(unsigned i, int inf_sign) {
    calculate_pivot_row(i);
    int entering = choose_entering_column_for_row_inf_strategy(inf_sign);
    if (entering == -1) {
        fill_evidence(i, inf_sign);
        this->m_status = INFEASIBLE;
        return;
    }
    advance_on_infeasible_row_and_entering(i, entering, inf_sign);
}

template <typename T, typename X> void lar_core_solver<T, X>::solve() {
    prefix();
    if (is_empty()) {
        this->m_status = OPTIMAL;
        return;
    }
    this->solve_Ax_eq_b();
    lean_assert(this->A_mult_x_is_off() == false);
    lean_assert(non_basis_columns_are_set_correctly());
    if (this->m_settings.row_feasibility) {
        row_feasibility_loop();
    } else {
        feasibility_loop();
    }
}

template <typename T, typename X> void lar_core_solver<T, X>::print_column_info(unsigned j, std::ostream & out) {
    out << "type = " << column_type_to_string(this->m_column_type[j]) << std::endl;
    switch (this->m_column_type[j]) {
    case fixed:
    case boxed:
        out << "(" << this->m_low_bound_values[j] << ", " << this->m_upper_bound_values[j] << ")" << std::endl;
        break;
    case low_bound:
        out << this->m_low_bound_values[j] << std::endl;
        break;
    case upper_bound:
        out << this->m_upper_bound_values[j] << std::endl;
        break;
    default:
        lean_assert(false);
    }
}
}


text:
    <button type="button" class="close" ng-click="$dismiss()">×</button>

文章编辑

            <input id="pageTitle" name="pageTitle" type="text" class="form-control page-title-input"
                   data-ng-model="page.title"
                   focus="true" placeholder="文章标题" autocomplete="off" maxlength="40"
                   required/>

                文章标题不能为空

         <textarea id="pageContent" name="pageContent" rows="3"
                   class="form-control page-content-textarea"
                   data-ng-model="page.content"
                   focus="true"
                   simplemde='{spellChecker: false}'
                   placeholder="文章内容 | 支持Markdown"
                   required></textarea>

    <button class="btn btn-primary" type="button" ng-click="savePage()"
            ng-disabled="pageForm.$invalid||isDisablePageSaveButton">{{pageSaveButtonText}}
    </button>


text:
Public Class Form1

    Dim blnContinue As Boolean = True

    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Escape Then
            blnContinue = False
        End If
    End Sub
    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        'Create graphics object
        Dim gr As Graphics = e.Graphics
        'Body
        gr.DrawArc(Pens.Black, 5, 55, 200, 200, 210, 300)
        'Mouth
        gr.DrawLine(Pens.Red, 73, 150, 18, 105)
        gr.DrawLine(Pens.Red, 73, 150, 18, 203)
        'Blue Hat
        gr.FillRectangle(Brushes.Blue, 35, 20, 165, 42)
        'Red Hat
        gr.FillRectangle(Brushes.Red, 10, 40, 212, 42)
        'Eye
        gr.DrawEllipse(Pens.Black, 90, 90, 20, 20)
        'Tongue
        Do
            Dim intMove As Integer
            For intMove = 203 To 105 Step -1
                Delay(0.01)
                gr.DrawLine(Pens.Red, 73, 150, 18, intMove)
                gr.DrawLine(Pens.White, 73, 150, 18, intMove + 1)
                'Mouth
                gr.DrawLine(Pens.Red, 73, 150, 18, 105)
                gr.DrawLine(Pens.Red, 73, 150, 18, 203)
            Next
            For intMove = 105 To 203
                Delay(0.01)
                gr.DrawLine(Pens.Red, 73, 150, 18, intMove)
                gr.DrawLine(Pens.White, 73, 150, 18, intMove - 1)
                'Mouth
                gr.DrawLine(Pens.Red, 73, 150, 18, 105)
                gr.DrawLine(Pens.Red, 73, 150, 18, 203)
            Next

        Loop Until blnContinue = False

        'Close Form
        Me.Close()

    End Sub
    Sub Delay(ByVal dblSecs As Double)
        Const OneSec As Double = 1.0# / (1440.0# * 60.0#)
        Dim dblWaitTil As Date
        Now.AddSeconds(OneSec)
        dblWaitTil = Now.AddSeconds(OneSec).AddSeconds(dblSecs)
        Do Until Now > dblWaitTil
            Application.DoEvents() ' Allow windows messages to be processed
        Loop
    End Sub
End Class

'Kaleb Haslam
'Pacman


text:
from dataclasses import dataclass
from typing import Dict, List, Union, Tuple, Optional, Set

from siebenapp.domain import (
    Graph,
    Command,
    EdgeType,
    ToggleClose,
    Add,
    ToggleLink,
    Insert,
    Rename,
    Delete,
    GoalId,
    RenderResult,
    RenderRow,
)
from siebenapp.goaltree import Goals

@dataclass(frozen=True)
class ToggleAutoLink(Command):
    keyword: str

AutoLinkData = List[Tuple[int, str]]

class AutoLink(Graph):
    def __init__(self, goals: Graph, data: Optional[AutoLinkData] = None):
        super(AutoLink, self).__init__(goals)
        self.keywords: Dict[str, int] = {}
        self.back_kw: Dict[int, str] = {}
        if data:
            for goal_id, keyword in data:
                self.keywords[keyword] = goal_id
                self.back_kw[goal_id] = keyword

    def accept_ToggleAutoLink(self, command: ToggleAutoLink) -> None:
        selected_id: int = self.settings("selection")
        if selected_id in self.goaltree.closed:
            self.error("Autolink cannot be set for closed goals")
            return
        if selected_id == Goals.ROOT_ID:
            self.error("Autolink cannot be set for the root goal")
            return
        keyword: str = command.keyword.lower().strip()
        if selected_id in self.back_kw:
            self.keywords.pop(self.back_kw[selected_id])
            self.back_kw.pop(selected_id)
            self.events().append(("remove_autolink", selected_id))
        if keyword in self.keywords:
            old_id: int = self.keywords.pop(keyword)
            self.back_kw.pop(old_id)
            self.events().append(("remove_autolink", old_id))
        if not keyword:
            # empty keyword? exit right now
            return
        self.keywords[keyword] = selected_id
        self.back_kw[selected_id] = keyword
        self.events().append(("add_autolink", selected_id, keyword))

    def accept_ToggleClose(self, command: ToggleClose) -> None:
        selected_id: int = self.settings("selection")
        if selected_id in self.back_kw:
            self.keywords.pop(self.back_kw[selected_id])
            self.back_kw.pop(selected_id)
            self.events().append(("remove_autolink", selected_id))
        self.goaltree.accept(command)

    def accept_Add(self, command: Add) -> None:
        self._autolink_new_goal(command)

    def accept_Insert(self, command: Insert) -> None:
        self._autolink_new_goal(command)

    def _autolink_new_goal(self, command: Union[Add, Insert]) -> None:
        matching: List[int] = self._find_matching_goals(command.name)
        ids_before: Set[int] = set(self.goaltree.goals.keys())
        self.goaltree.accept(command)
        ids_after: Set[int] = set(self.goaltree.goals.keys())
        ids_diff: Set[int] = ids_after.difference(ids_before)
        if ids_diff:
            added_id: int = ids_diff.pop()
            self._make_links(matching, added_id)

    def accept_Rename(self, command: Rename) -> None:
        matching: List[int] = self._find_matching_goals(command.new_name)
        self.goaltree.accept(command)
        selected_id: int = command.goal_id or self.settings("selection")
        self._make_links(matching, selected_id)

    def accept_Delete(self, command: Delete) -> None:
        selected_id: int = command.goal_id or self.settings("selection")
        edges: Dict[int, List[Tuple[GoalId, EdgeType]]] = {
            row.raw_id: row.edges for row in self.goaltree.q().rows
        }
        goals_to_check: List[int] = [selected_id]
        while goals_to_check:
            goal_id: int = goals_to_check.pop()
            goals_to_check.extend(
                e[0]
                for e in edges[goal_id]
                if e[1] == EdgeType.PARENT and isinstance(e[0], int)
            )
            if goal_id in self.back_kw:
                added_kw: str = self.back_kw.pop(goal_id)
                self.keywords.pop(added_kw)
                self.events().append(("remove_autolink", goal_id))
        self.goaltree.accept(command)

    def _find_matching_goals(self, text: str) -> List[int]:
        return [goal_id for kw, goal_id in self.keywords.items() if kw in text.lower()]

    def _make_links(self, matching_goals: List[int], target_goal: int) -> None:
        if not matching_goals:
            return
        self_children: Dict[int, List[GoalId]] = {
            row.raw_id: [e[0] for e in row.edges] for row in self.goaltree.q().rows
        }
        for add_to in matching_goals:
            if target_goal not in self_children[add_to]:
                self.goaltree.accept(ToggleLink(add_to, target_goal, EdgeType.PARENT))

    def q(self) -> RenderResult:
        render_result = self.goaltree.q()
        rows: List[RenderRow] = [
            RenderRow(
                row.goal_id,
                row.raw_id,
                row.name,
                row.is_open,
                row.is_switchable,
                row.edges,
                {
                    # We could use `r.attrs | (...)` in Python 3.9+
                    **row.attrs,
                    **(
                        {"Autolink": self.back_kw[int(row.goal_id)]}
                        if row.goal_id in self.back_kw
                        else {}
                    ),
                },
            )
            for row in render_result.rows
        ]
        return RenderResult(
            rows, select=render_result.select, roots=render_result.roots
        )

    @staticmethod
    def fake_id(goal_id: GoalId) -> GoalId:
        return -(goal_id + 10) if isinstance(goal_id, int) else goal_id

    @staticmethod
    def export(goals: "AutoLink") -> AutoLinkData:
        return [(goal_id, kw) for goal_id, kw in goals.back_kw.items()]


text:
package com.voxelwind.server.network;

import com.voxelwind.server.network.mcpe.annotations.BatchDisallowed;
import com.voxelwind.server.network.mcpe.packets.*;
import com.voxelwind.server.network.raknet.packets.*;
import gnu.trove.TCollections;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;

@SuppressWarnings("unchecked")
public class PacketRegistry {
    private static final Class<? extends NetworkPackage>[] RAKNET_PACKETS = new Class[256];
    private static final Class<? extends NetworkPackage>[] MCPE_PACKETS = new Class[256];
    private static final TObjectIntMap<Class<? extends NetworkPackage>> PACKAGE_MAPPING;

    static {
        RAKNET_PACKETS[0x00] = ConnectedPingPacket.class;
        RAKNET_PACKETS[0x01] = UnconnectedPingPacket.class;
        RAKNET_PACKETS[0x03] = ConnectedPongPacket.class;
        RAKNET_PACKETS[0x05] = OpenConnectionRequest1Packet.class;
        RAKNET_PACKETS[0x06] = OpenConnectionResponse1Packet.class;
        RAKNET_PACKETS[0x07] = OpenConnectionRequest2Packet.class;
        RAKNET_PACKETS[0x08] = OpenConnectionResponse2Packet.class;
        RAKNET_PACKETS[0x09] = ConnectionRequestPacket.class;
        RAKNET_PACKETS[0x10] = ConnectionResponsePacket.class;
        RAKNET_PACKETS[0x13] = NewIncomingConnectionPacket.class;
        RAKNET_PACKETS[0x14] = NoFreeIncomingConnectionsPacket.class;
        RAKNET_PACKETS[0x15] = DisconnectNotificationPacket.class;
        RAKNET_PACKETS[0x1c] = UnconnectedPongPacket.class;
        RAKNET_PACKETS[0xa0] = NakPacket.class;
        RAKNET_PACKETS[0xc0] = AckPacket.class;
        RAKNET_PACKETS[0xfe] = McpeWrapper.class; // Technically not an MCPE packet, but here for convenience

        MCPE_PACKETS[0x01] = McpeLogin.class;
        MCPE_PACKETS[0x02] = McpePlayStatus.class;
        MCPE_PACKETS[0x03] = McpeServerHandshake.class;  // McpeServerExchange.class
        MCPE_PACKETS[0x04] = McpeClientMagic.class;
        MCPE_PACKETS[0x05] = McpeDisconnect.class;
        MCPE_PACKETS[0x06] = McpeBatch.class;
        MCPE_PACKETS[0x07] = McpeResourcePackInfo.class;
	    // RESOURCE_PACK_STACK_PACKET = 0x08; //McpeResourcePackStack.class
	    MCPE_PACKETS[0x09] = McpeResourcePackClientResponse.class;
        MCPE_PACKETS[0x0a] = McpeText.class;
        MCPE_PACKETS[0x0b] = McpeSetTime.class;
        MCPE_PACKETS[0x0c] = McpeStartGame.class;
        MCPE_PACKETS[0x0d] = McpeAddPlayer.class;
        MCPE_PACKETS[0x0e] = McpeAddEntity.class;
        MCPE_PACKETS[0x0f] = McpeRemoveEntity.class;
        MCPE_PACKETS[0x10] = McpeAddItemEntity.class;
        // ADD_HANGING_ENTITY_PACKET = 0x11; McpeAddHangingEntity.class
        MCPE_PACKETS[0x12] = McpeTakeItem.class;  //McpeTakeItemEntity.class
        MCPE_PACKETS[0x13] = McpeMoveEntity.class;
        MCPE_PACKETS[0x14] = McpeMovePlayer.class;
        // RIDER_JUMP_PACKET = 0x15;  //McpeRiderJump.class
        MCPE_PACKETS[0x16] = McpeRemoveBlock.class;
        MCPE_PACKETS[0x17] = McpeUpdateBlock.class;
        // ADD_PAINTING_PACKET = 0x18;  // McpeAddPainting.class
        // EXPLODE_PACKET = 0x19;  // McpeExplode.class
        // LEVEL_SOUND_EVENT_PACKET = 0x1a; // McpeLevelSoundEvent.class
        // LEVEL_EVENT_PACKET = 0x1b;  // McpeLevelEvent.class
        // BLOCK_EVENT_PACKET = 0x1c;  // McpeBlockEvent.class
        MCPE_PACKETS[0x1d] = McpeEntityEvent.class;
        // MOB_EFFECT_PACKET = 0x1e; // McpeMobEffect.class
        MCPE_PACKETS[0x1f] = McpeUpdateAttributes.class;
        MCPE_PACKETS[0x20] = McpeMobEquipment.class;
        // MOB_ARMOR_EQUIPMENT_PACKET = 0x21; // McpeMobArmorEquipment.class
        MCPE_PACKETS[0x22] = McpeInteract.class;
        // BLOCK_PICK_REQUEST_PACKET = 0x23; // McpeBlockPickRequest.class
        MCPE_PACKETS[0x24] = McpeUseItem.class;
        MCPE_PACKETS[0x25] = McpePlayerAction.class;
        // PLAYER_FALL_PACKET = 0x26; // McpePlayerFall.class
        // HURT_ARMOR_PACKET = 0x27; // McpeHurtArmor.class
        MCPE_PACKETS[0x28] = McpeSetEntityData.class;
        MCPE_PACKETS[0x29] = McpeSetEntityMotion.class;
        // SET_ENTITY_LINK_PACKET = 0x2a;   // McpeSetEntityLink.class
        MCPE_PACKETS[0x2b] = McpeSetHealth.class;
        MCPE_PACKETS[0x2c] = McpeSetSpawnPosition.class;
        MCPE_PACKETS[0x2d] = McpeAnimate.class;
        MCPE_PACKETS[0x2e] = McpeRespawn.class;
        MCPE_PACKETS[0x2f] = McpeDropItem.class;
        // INVENTORY_ACTION_PACKET = 0x30;  // McpeInventoryAction.class
        MCPE_PACKETS[0x31] = McpeContainerOpen.class;
        MCPE_PACKETS[0x32] = McpeContainerClose.class;
        MCPE_PACKETS[0x33] = McpeContainerSetSlot.class;
        MCPE_PACKETS[0x34] = McpeContainerSetData.class;
        MCPE_PACKETS[0x35] = McpeContainerSetContents.class;
        // CRAFTING_DATA_PACKET = 0x36;  // McpeCraftingData.class
	    // CRAFTING_EVENT_PACKET = 0x37; // McpeCraftingEvent.class
        MCPE_PACKETS[0x38] = McpeAdventureSettings.class;
        MCPE_PACKETS[0x39] = McpeBlockEntityData.class;
        // PLAYER_INPUT_PACKET = 0x3a; // McpePlayerInput.class
        MCPE_PACKETS[0x3b] = McpeFullChunkData.class;
        MCPE_PACKETS[0x3c] = McpeSetCommandsEnabled.class;
        // SET_DIFFICULTY_PACKET = 0x3d; // McpeSetDifficulty.class
        MCPE_PACKETS[0x3e] = McpeChangeDimension.class;
        MCPE_PACKETS[0x3f] = McpeSetPlayerGameMode.class;
        MCPE_PACKETS[0x40] = McpePlayerList.class;
        // EVENT_PACKET = 0x41; //McpeEvent.class
        // SPAWN_EXPERIENCE_ORB_PACKET = 0x42;   // McpeSpawnExperienceOrb.class
        // CLIENTBOUND_MAP_ITEM_DATA_PACKET = 0x43;  // McpeClientboundMapItemData.class
        // MAP_INFO_REQUEST_PACKET = 0x44;  // McpeMapInfoRequest.class

        MCPE_PACKETS[0x45] = McpeRequestChunkRadius.class;
        MCPE_PACKETS[0x46] = McpeChunkRadiusUpdated.class;

        // ITEM_FRAME_DROP_ITEM_PACKET = 0x47;  // McpeItemFramDropItem.class
        // REPLACE_SELECTED_ITEM_PACKET = 0x48; // McpeReplaceSelectedItem.class
        // GAME_RULES_CHANGED_PACKET = 0x49;    // McpeGameRulesChanged.class
        // CAMERA_PACKET = 0x4a;                // McpeCamera.class
        // ADD_ITEM_PACKET = 0x4b;              // McpeAddItem.class
        // BOSS_EVENT_PACKET = 0x4c;            // McpeBossEvent.class
        // SHOW_CREDITS_PACKET = 0x4d;          // McpeShowCredits.class
        MCPE_PACKETS[0x4e] = McpeAvailableCommands.class;
        MCPE_PACKETS[0x4f] = McpeCommandStep.class;
        // COMMAND_BLOCK_UPDATE_PACKET = 0x50; // McpeCommandBlockUpdate.class
        // UPDATE_TRADE_PACKET = 0x51; // McpeUpdateTrade.class
        // RESOURCE_PACK_DATA_INFO_PACKET = 0x52; // McpeResourcePackDataInfo.class
        // RESOURCE_PACK_CHUNK_DATA_PACKET = 0x53;// McpeResourcePackChunkData.class
        // RESOURCE_PACK_CHUNK_REQUEST_PACKET = 0x54; //McpeResourcePackChunkRequest.class

        // TRANSFER_PACKET = 0x52 // McpeTransfer.class
        // PLAY_SOUND_PACKET = 0x56; // McpePlaySound.class
        // STOP_SOUND_PACKET = 0x57; // MspeStopSound.class
        // SET_TITLE_PACKET = 0x58; // McpeSetTitle.class

        TObjectIntMap<Class<? extends NetworkPackage>> classToIdMap = new TObjectIntHashMap<>(64, 0.75f, -1);
        for (int i = 0; i < RAKNET_PACKETS.length; i++) {
            Class clazz = RAKNET_PACKETS[i];
            if (clazz != null) {
                classToIdMap.put(clazz, i);
            }
        }

        for (int i = 0; i < MCPE_PACKETS.length; i++) {
            Class clazz = MCPE_PACKETS[i];
            if (clazz != null) {
                classToIdMap.put(clazz, i);
            }
        }

        PACKAGE_MAPPING = TCollections.unmodifiableMap(classToIdMap);
    }

    private PacketRegistry() {

    }

    public static NetworkPackage tryDecode(ByteBuf buf, PacketType type) {
        return tryDecode(buf, type, false);
    }

    public static NetworkPackage tryDecode(ByteBuf buf, PacketType type, boolean fromBatch) {
        int id = buf.readUnsignedByte();
        Class<? extends NetworkPackage> pkgClass;
        switch (type) {
            case RAKNET:
                pkgClass = RAKNET_PACKETS[id];
                break;
            case MCPE:
                pkgClass = MCPE_PACKETS[id];
                break;
            default:
                throw new IllegalArgumentException("Invalid PacketType");
        }

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

        if (fromBatch) {
            if (pkgClass.isAnnotationPresent(BatchDisallowed.class)) {
                return null;
            }
        }

        NetworkPackage netPackage;
        try {
            netPackage = pkgClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("Unable to create packet instance", e);
        }

        netPackage.decode(buf);
        return netPackage;
    }

    public static int getId(NetworkPackage pkg) {
        Class<? extends NetworkPackage> pkgClass = pkg.getClass();
        int res = PACKAGE_MAPPING.get(pkgClass);
        if (res == -1) {
            throw new IllegalArgumentException("Packet ID for " + pkgClass.getName() + " does not exist.");
        }
        return res;
    }

    public static ByteBuf tryEncode(NetworkPackage pkg) {
        int id = getId(pkg);

        ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer();
        buf.writeByte((id & 0xFF));
        pkg.encode(buf);

        return buf;
    }
}


text:
package org.jivesoftware.spark.util;

import java.awt.Color;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.jivesoftware.resource.Res;

/**
 * A simple Colorpicker with sliders
 * @author wolf.posdorfer
 *
 */
public class ColorPick extends JPanel implements ChangeListener {

    private static final long serialVersionUID = 2709297435120012839L;
    private JSlider[] _sliderarray;
    private JLabel _preview;

    /**
     * Creates a Colorpicker with initial values 0,0,0,0
     *
     * @param opacity
     *            , true if Opacity Slider should be visible
     */
    public ColorPick(boolean opacity)
    {
	this.setLayout(new GridBagLayout());

	JLabel red = new JLabel(Res.getString("lookandfeel.color.red"));
	JLabel green = new JLabel(Res.getString("lookandfeel.color.green"));
	JLabel blue = new JLabel(Res.getString("lookandfeel.color.blue"));
	JLabel opaq = new JLabel(Res.getString("lookandfeel.color.opacity"));

	JSlider redslider = new JSlider(0,255);
	JSlider greenslider = new JSlider(0,255);
	JSlider blueslider = new JSlider(0,255);
	JSlider opaqslider = new JSlider(0,255);

	_sliderarray = new JSlider[4];
	_sliderarray[0] = redslider;
	_sliderarray[1] = greenslider;
	_sliderarray[2] = blueslider;
	_sliderarray[3] = opaqslider;

	for(JSlider s : _sliderarray)
	{
	    s.addChangeListener(this);
	    s.setMajorTickSpacing(256/3);
	    s.setMinorTickSpacing(0);
	    s.setPaintTicks(true);
	    s.setPaintLabels(true);
	}

	_preview = new JLabel("   ");
	_preview.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
	_preview.setOpaque(true);

	this.add(red,new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));
	this.add(redslider,new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));

	this.add(green,new GridBagConstraints(0, 1, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));
	this.add(greenslider,new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));

	this.add(blue,new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));
	this.add(blueslider,new GridBagConstraints(1, 2, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));

	if(opacity)
	{
        	this.add(opaq,new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));
        	this.add(opaqslider,new GridBagConstraints(1, 3, 1, 1, 1.0, 1.0,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));
	}

	this.add(_preview,new GridBagConstraints(2, 0, 1, 4, 0.1, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5,5,5,5),0,0));

    }
    /**
     * Creates a Colorpicker with initialvalues provided by c
     * @param opacity, true if Opacity Slider should be visible
     * @param c, the initial Color
     */
    public ColorPick(boolean opacity, Color c)
    {
	this(opacity);
	for(int i=0; i < 3; i++)
	{
	   float w = c.getColorComponents(new float[3])[i];
	   int x = Math.round(w*255f/1f);
	   _sliderarray[i].setValue(x);
	}

	_sliderarray[3].setValue(c.getAlpha());

	this.revalidate();

    }

    /**
     * Returns the Color of the Current View
     * @return
     */
    public Color getColor() {

	return new Color(_sliderarray[0].getValue(), _sliderarray[1].getValue(), _sliderarray[2].getValue(),
		_sliderarray[3].getValue());
    }

    /**
     * Sets the Color of this Colorpicker
     * @param c
     */
    public void setColor(Color c) {
	for (int i = 0; i < 3; i++) {
	    float w = c.getColorComponents(new float[3])[i];
	    int x = Math.round(w * 255f / 1f);
	    _sliderarray[i].setValue(x);
	}

	_sliderarray[3].setValue(c.getAlpha());

	this.revalidate();
    }

    public void addChangeListener(ChangeListener cl)
    {
	for(JSlider sl : _sliderarray)
	{
	    sl.addChangeListener(cl);
	}
    }

    @Override
    public void stateChanged(ChangeEvent e) {

	_preview.setBackground(new Color(_sliderarray[0].getValue(), _sliderarray[1].getValue(), _sliderarray[2]
		.getValue(), _sliderarray[3].getValue()));

	_preview.setForeground(new Color(_sliderarray[0].getValue(), _sliderarray[1].getValue(), _sliderarray[2]
		.getValue(), _sliderarray[3].getValue()));

	_preview.invalidate();
	_preview.repaint();
	_preview.revalidate();

	Container c = _preview.getParent();
	if (c instanceof JPanel) {
	    ((JPanel) c).repaint();
	    ((JPanel) c).revalidate();
	}
    }

}