text:
<!doctype html>

		<meta charset="utf-8">

		<title>automate the boring stuff</title>

		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/simpler.css" id="theme">

		<link rel="stylesheet" href="lib/css/tomorrow.css">
		<link rel="stylesheet" href="lib/css/nv.d3.min.css">

automate the boring stuff

programowanie kontra codzienność

Piotrek Dubiel

						@ok_3_2_1

Tytuł?

Pomysł?

Poznaj lunchbota

Jak?

API

application programming interface

							sposób w jaki programy komputerowe komunikują się między sobą, rozumiany jako ściśle określony zestaw reguł i ich opisów

							Wikipedia

{
  "data": [
    {
      "message": "w piątek zapraszamy na lunch rybny
		FILET MAKRELI Z GRILLA Z MUSEM JABŁKOWYM, NA PUREE DYNIOWYM ORAZ SAŁATĄ FRISEE
		do wyboru z zupą
		POMIDOROWĄ Z MAKARONEM LUB Z SOCZEWICY
		Pychota!!!",
      "story": "sofra cafe&restaurant added 2 new photos.",
      "created_time": "2015-11-20T10:34:23+0000",
      "id": "367555226656576_928579363887490"
    },
    (...)
  ]
}

					Problemy?

Jasne

						This incoming webhook had 2193 messages in the last 4 minutes.

						Due to a high volume of activity, we've stopped displaying messages from this incoming webhook integration. Once activity settles down, we'll post a summary.

						<svg></svg>

Dzięki


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Disclosure example</title>

<ui-disclosure>
    <ui-toggle>Toggle openclose</ui-toggle>
    <ui-section>Hello world</ui-section>
</ui-disclosure>

redpajama_set_name: RedPajamaGithub


text:
<?

/* Nasty way of implementing "by department" stuff with the current schema */

include_once "../../includes/easyparliament/init.php";

$dept = get_http_var('dept');
$PAGE->page_start();
$PAGE->stripe_start();
$db = new ParlDB;

if (!$dept) {
} else {
	$dept = strtolower(str_replace('_',' ',$dept));
	$q = $db->query('select epobject.epobject_id from hansard,epobject
		where hansard.epobject_id=epobject.epobject_id and major=4 and section_id=0
		and hdate>(select max(hdate) from hansard where major=4) - interval 7 day
		and lower(body) = "' . mysql_real_escape_string($dept).'"');
	$ids = array();
	for ($i=0; $i<$q->rows(); $i++) {
		$ids[] = $q->field($i, 'epobject_id');
	}

	print '
' . ucwords($dept) . '
';
	print '
Written Ministerial Statements from the past week
';
	$q = $db->query('select gid,body from hansard,epobject
		where hansard.epobject_id=epobject.epobject_id and major=4 and subsection_id=0
		and section_id in (' . join(',', $ids) . ')
		order by body');
	print '
';
	for ($i=0; $i<$q->rows(); $i++) {
		print '
field($i, 'gid')). '">' . $q->field($i, 'body'). '';
		print '
';
	}
	print '
';

}

$PAGE->stripe_end();
$PAGE->page_end();


text:
<?
	defined('C5_EXECUTE') or die("Access Denied.");
	class Concrete5_Library_Localization {

		private static $loc = null;

		public function init() {
			$loc = Localization::getInstance();
			$loc->getTranslate();
		}

		/**
		* @return Localization
		*/
		public static function getInstance() {
			if (null === self::$loc) {
				self::$loc = new self;
			}
			return self::$loc;
		}

		/** Changes the currently active locale
		* @param string $locale The locale to activate (for example: 'en_US')
		* @param bool $coreOnly = false Set to true to load only the core translation files, set to false (default) to load also packages and site locale translations
		*/
		public static function changeLocale($locale, $coreOnly = false) {
			$loc = Localization::getInstance();
			$loc->setLocale($locale, $coreOnly);
		}
		/** Returns the currently active locale
		* @return string
		* @example 'en_US'
		*/
		public static function activeLocale() {
			$loc = Localization::getInstance();
			return $loc->getLocale();
		}
		/** Returns the language for the currently active locale
		* @return string
		* @example 'en'
		*/
		public static function activeLanguage() {
			return current(explode('_', self::activeLocale()));
		}

		/** The current Zend_Translate instance (null if and only if locale is en_US)
		* @var Zend_Translate|null
		*/
		protected $translate;

		public function __construct() {
			Loader::library('3rdparty/Zend/Date');
			Loader::library('3rdparty/Zend/Translate');
			Loader::library('3rdparty/Zend/Locale');
			Loader::library('3rdparty/Zend/Locale/Data');
			$cache = Cache::getLibrary();
			if (is_object($cache)) {
				Zend_Translate::setCache($cache);
				Zend_Date::setOptions(array('cache'=>$cache));
			}
			$locale = defined('ACTIVE_LOCALE') ? ACTIVE_LOCALE : 'en_US';
			$this->setLocale($locale);
			Zend_Date::setOptions(array('format_type' => 'php'));
		}

		/** Changes the currently active locale
		* @param string $locale The locale to activate (for example: 'en_US')
		* @param bool $coreOnly = false Set to true to load only the core translation files, set to false (default) to load also packages and site locale translations
		*/
		public function setLocale($locale, $coreOnly = false) {
			$localeNeededLoading = false;
			if (($locale == 'en_US') && (!ENABLE_TRANSLATE_LOCALE_EN_US)) {
				if(isset($this->translate)) {
					unset($this->translate);
				}
				return;
			}
			if (is_dir(DIR_LANGUAGES . '/' . $locale)) {
				$languageDir = DIR_LANGUAGES . '/' . $locale;
			}
			elseif (is_dir(DIR_LANGUAGES_CORE . '/' . $locale)) {
				$languageDir = DIR_LANGUAGES_CORE . '/' . $locale;
			}
			else {
				return;
			}

			$options = array(
				'adapter' => 'gettext',
				'content' => $languageDir,
				'locale'  => $locale,
				'disableNotices'  => true,
				'ignore' => array('.', 'messages.po')
			);
			if (defined('TRANSLATE_OPTIONS')) {
				$_options = unserialize(TRANSLATE_OPTIONS);
				if (is_array($_options)) {
					$options = array_merge($options, $_options);
				}
			}

			if (!isset($this->translate)) {
				$this->translate = new Zend_Translate($options);
				$localeNeededLoading = true;
			} else {
				if (!in_array($locale, $this->translate->getList())) {
					$this->translate->addTranslation($options);
					$localeNeededLoading = true;
				}
				$this->translate->setLocale($locale);
			}
			if(!$coreOnly) {
				$this->addSiteInterfaceLanguage($locale);
				global $config_check_failed;
				if(!(isset($config_check_failed) && $config_check_failed)) {
					foreach(PackageList::get(1)->getPackages() as $p) {
						$pkg = Loader::package($p->getPackageHandle());
						if (is_object($pkg)) {
							$pkg->setupPackageLocalization($locale, null, $this->translate);
						}
					}
				}
			}
			if($localeNeededLoading) {
				Events::fire('on_locale_load', $locale);
			}
		}

		public function getLocale() {
			return isset($this->translate) ? $this->translate->getLocale() : 'en_US';
		}

		/** Returns the current Zend_Translate instance (null if and only if locale is en_US)
		* @var Zend_Translate|null
		*/
		public function getActiveTranslateObject() {
			return $this->translate;
		}

		/** Loads the site interface locale.
		* @param string $locale = null The locale to load (for instance: 'en_US'). If empty we'll use the currently active locale
		*/
		public function addSiteInterfaceLanguage($locale = null) {
			if (is_object($this->translate)) {
				if(!(is_string($locale) && strlen($locale))) {
					$locale = $this->translate->getLocale();
				}
				$path = DIR_LANGUAGES_SITE_INTERFACE . '/' . $locale . '.mo';
				if(is_file($path)) {
					$this->translate->addTranslation($path, $locale);
				}
			}
		}

		/** Returns the current Zend_Translate instance (null if and only if locale is en_US)
		* @var Zend_Translate|null
		*/
		public static function getTranslate() {
			$loc = Localization::getInstance();
			return $loc->getActiveTranslateObject();
		}

		public static function getAvailableInterfaceLanguages() {
			$languages = array();
			$fh = Loader::helper('file');

			if (file_exists(DIR_LANGUAGES)) {
				$contents = $fh->getDirectoryContents(DIR_LANGUAGES);
				foreach($contents as $con) {
					if (is_dir(DIR_LANGUAGES . '/' . $con) && file_exists(DIR_LANGUAGES . '/' . $con . '/LC_MESSAGES/messages.mo')) {
						$languages[] = $con;
					}
				}
			}
			if (file_exists(DIR_LANGUAGES_CORE)) {
				$contents = $fh->getDirectoryContents(DIR_LANGUAGES_CORE);
				foreach($contents as $con) {
					if (is_dir(DIR_LANGUAGES_CORE . '/' . $con) && file_exists(DIR_LANGUAGES_CORE . '/' . $con . '/LC_MESSAGES/messages.mo') && (!in_array($con, $languages))) {
						$languages[] = $con;
					}
				}
			}

			return $languages;
		}

		/**
		 * Generates a list of all available languages and returns an array like
		 * [ "de_DE" => "Deutsch (Deutschland)",
		 *   "en_US" => "English (United States)",
		 *   "fr_FR" => "Français (France)"]
		 * The result will be sorted by the key.
		 * If the $displayLocale is set, the language- and region-names will be returned in that language
		 * @param string $displayLocale Language of the description
		 * @return Array An associative Array with locale as the key and description as content
		 */
		public static function getAvailableInterfaceLanguageDescriptions($displayLocale = null) {
			$languages = self::getAvailableInterfaceLanguages();
			if (count($languages) > 0) {
				array_unshift($languages, 'en_US');
			}
			$locales = array();
			foreach($languages as $lang) {
				$locales[$lang] = self::getLanguageDescription($lang,$displayLocale);
			}
			natcasesort($locales);
			return $locales;
		}

		/**
		 * Get the description of a locale consisting of language and region description
		 * e.g. "French (France)"
		 * @param string $locale Locale that should be described
		 * @param string $displayLocale Language of the description
		 * @return string Description of a language
		 */
		public static function getLanguageDescription($locale, $displayLocale = null) {
			$localeList = Zend_Locale::getLocaleList();
			if (! isset($localeList[$locale])) {
				return $locale;
			}

			if ($displayLocale !== NULL && (! isset($localeList[$displayLocale]))) {
				$displayLocale = NULL;
			}

			$cacheLibrary = Cache::getLibrary();
			if (is_object($cacheLibrary)) {
				Zend_Locale_Data::setCache($cacheLibrary);
			}

			$displayLocale = $displayLocale?$displayLocale:$locale;

			$zendLocale = new Zend_Locale($locale);
			$languageName = Zend_Locale::getTranslation($zendLocale->getLanguage(), 'language', $displayLocale);
			$description = $languageName;
			$region = $zendLocale->getRegion();
			if($region !== false) {
				$regionName = Zend_Locale::getTranslation($region, 'country', $displayLocale);
				if($regionName !== false) {
					$localeData = Zend_Locale_Data::getList($displayLocale, 'layout');
					if ( $localeData['characters'] == "right-to-left") {
						$description = '(' . $languageName . ' (' . $regionName ;
					} else {
						$description = $languageName . ' (' . $regionName . ")";
					}

				}
			}
			return $description;
		}

	}


text:
from hawaiigaragesale.models import GarageSale
import time
from datetime import date
from datetime import timedelta

##########################
## To run, do:
## python manage.py  shell < scripts/create-gs-data.py
##########################

gs = GarageSale(address="940 Spencer St, Honolulu, HI ", sale_date=date.today() + timedelta(days=1) ,contact_name='Kevin English',contract_phone='808-271-5125')
gs.save()
gs = GarageSale(address="900 Fort Street Mall, Honolulu, HI ",sale_date=date.today() + timedelta(days=2),contact_name='Kevin English',contract_phone='808-271-5125')
gs.save()
gs = GarageSale(address="241 Kaiulani Ave, Honolulu, HI ", sale_date=date.today() + timedelta(days=3),contact_name='Kevin English',contract_phone='808-271-5125')
gs.save()
gs = GarageSale(address="91-1031 Kaimalie St, Ewa Beach, HI ", sale_date=date.today() + timedelta(days=4),contact_name='Kevin English',contract_phone='808-271-5125')
gs.save()

gs = GarageSale(address="1001 Bishop St, Honolulu, HI ", sale_date=date.today() + timedelta(days=5),contact_name='Kevin English',contract_phone='808-271-5125')
gs.save()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 22(2): 426 (1985)

#### Original name
Agaricus rubronanus Kerrigan

### Remarks
null


text:
"""Distributed Task Queue"""
# :copyright: (c) 2009 - 2011 by Ask Solem.
# :license:   BSD, see LICENSE for more details.

import os
import sys

VERSION = (2, 3, 0, "a1")

__version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:])
__author__ = "Ask Solem"
__contact__ = "ask@celeryproject.org"
__homepage__ = "http://celeryproject.org"
__docformat__ = "restructuredtext"

if sys.version_info < (2, 5):
    import warnings
    warnings.warn(DeprecationWarning("""

Python 2.4 support is deprecated and only versions 2.5, 2.6, 2.7+
will be supported starting from Celery version 2.3.

"""))

def Celery(*args, **kwargs):
    from celery.app import App
    return App(*args, **kwargs)

if not os.environ.get("CELERY_NO_EVAL", False):
    from celery.local import LocalProxy

    def _get_current_app():
        from celery.app import current_app
        return current_app()

    current_app = LocalProxy(_get_current_app)


text:
namespace
{
    // Filter the events received by windows (only allow those matching a specific window)
    Bool checkEvent(::Display*, XEvent* event, XPointer userData)
    {
        // Just check if the event matches the window
        return event->xany.window == reinterpret_cast< ::Window >(userData);
    }
}

namespace sf
{
namespace priv
{

////////////////////////////////////////////////////////////
String ClipboardImpl::getString()
{
    return getInstance().getStringImpl();
}

////////////////////////////////////////////////////////////
void ClipboardImpl::setString(const String& text)
{
    getInstance().setStringImpl(text);
}

////////////////////////////////////////////////////////////
void ClipboardImpl::processEvents()
{
    getInstance().processEventsImpl();
}

////////////////////////////////////////////////////////////
ClipboardImpl::ClipboardImpl() :
m_window (0),
m_requestResponded(false)
{
    // Open a connection with the X server
    m_display = OpenDisplay();

    // Get the atoms we need to make use of the clipboard
    m_clipboard      = getAtom("CLIPBOARD",                      false);
    m_targets        = getAtom("TARGETS",                        false);
    m_text           = getAtom("TEXT",                           false);
    m_utf8String     = getAtom("UTF8_STRING",                    true );
    m_targetProperty = getAtom("SFML_CLIPBOARD_TARGET_PROPERTY", false);

    // Create a hidden window that will broker our clipboard interactions with X
    m_window = XCreateSimpleWindow(m_display, DefaultRootWindow(m_display), 0, 0, 1, 1, 0, 0, 0);

    // Register the events we are interested in
    XSelectInput(m_display, m_window, SelectionNotify | SelectionClear | SelectionRequest);
}

////////////////////////////////////////////////////////////
ClipboardImpl::~ClipboardImpl()
{
    // Destroy the window
    if (m_window)
    {
        XDestroyWindow(m_display, m_window);
        XFlush(m_display);
    }

    // Close the connection with the X server
    CloseDisplay(m_display);
}

////////////////////////////////////////////////////////////
ClipboardImpl& ClipboardImpl::getInstance()
{
    static ClipboardImpl instance;

    return instance;
}

////////////////////////////////////////////////////////////
String ClipboardImpl::getStringImpl()
{
    // Check if anybody owns the current selection
    if (XGetSelectionOwner(m_display, m_clipboard) == None)
    {
        m_clipboardContents.clear();

        return m_clipboardContents;
    }

    // Process any already pending events
    processEvents();

    m_requestResponded = false;

    // Request the current selection to be converted to UTF-8 (or STRING
    // if UTF-8 is not available) and written to our window property
    XConvertSelection(
        m_display,
        m_clipboard,
        (m_utf8String != None) ? m_utf8String : XA_STRING,
        m_targetProperty,
        m_window,
        CurrentTime
    );

    Clock clock;

    // Wait for a response for up to 1000ms
    while (!m_requestResponded && (clock.getElapsedTime().asMilliseconds() < 1000))
        processEvents();

    // If no response was received within the time period, clear our clipboard contents
    if (!m_requestResponded)
        m_clipboardContents.clear();

    return m_clipboardContents;
}

////////////////////////////////////////////////////////////
void ClipboardImpl::setStringImpl(const String& text)
{
    m_clipboardContents = text;

    // Set our window as the current owner of the selection
    XSetSelectionOwner(m_display, m_clipboard, m_window, CurrentTime);

    // Check if setting the selection owner was successful
    if (XGetSelectionOwner(m_display, m_clipboard) != m_window)
        err() << "Cannot set clipboard string: Unable to get ownership of X selection" << std::endl;
}

////////////////////////////////////////////////////////////
void ClipboardImpl::processEventsImpl()
{
    XEvent event;

    // Pick out the events that are interesting for this window
    while (XCheckIfEvent(m_display, &event, &checkEvent, reinterpret_cast<XPointer>(m_window)))
        m_events.push_back(event);

    // Handle the events for this window that we just picked out
    while (!m_events.empty())
    {
        event = m_events.front();
        m_events.pop_front();
        processEvent(event);
    }
}

////////////////////////////////////////////////////////////
void ClipboardImpl::processEvent(XEvent& windowEvent)
{
    switch (windowEvent.type)
    {
        case SelectionClear:
        {
            // We don't have any resources we need to clean up
            // when losing selection ownership so we don't do
            // anything when we receive SelectionClear
            // We will still respond to any future SelectionRequest
            // events since doing so doesn't really do any harm
            break;
        }
        case SelectionNotify:
        {
            // Notification that the current selection owner
            // has responded to our request

            XSelectionEvent& selectionEvent = *reinterpret_cast<XSelectionEvent*>(&windowEvent.xselection);

            m_clipboardContents.clear();

            // If retrieving the selection fails or conversion is unsuccessful
            // we leave the contents of the clipboard empty since we don't
            // own it and we don't know what it could currently be
            if ((selectionEvent.property == None) || (selectionEvent.selection != m_clipboard))
                break;

            Atom type;
            int format;
            unsigned long items;
            unsigned long remainingBytes;
            unsigned char* data = 0;

            // The selection owner should have wrote the selection
            // data to the specified window property
            int result = XGetWindowProperty(
                m_display,
                m_window,
                m_targetProperty,
                0,
                0x7fffffff,
                False,
                AnyPropertyType,
                &type,
                &format,
                &items,
                &remainingBytes,
                &data
            );

            if (result == Success)
            {
                // We don't support INCR for now
                // It is very unlikely that this will be returned
                // for purely text data transfer anyway
                if (type != getAtom("INCR", false))
                {
                    // Only copy the data if the format is what we expect
                    if ((type == m_utf8String) && (format == 8))
                    {
                        m_clipboardContents = String::fromUtf8(data, data + items);
                    }
                    else if ((type == XA_STRING) && (format == 8))
                    {
                        // Convert from ANSI std::string to sf::String
                        m_clipboardContents = std::string(data, data + items);
                    }
                }

                XFree(data);

                // The selection requestor must always delete the property themselves
                XDeleteProperty(m_display, m_window, m_targetProperty);
            }

            m_requestResponded = true;

            break;
        }
        case SelectionRequest:
        {
            // Respond to a request for our clipboard contents
            XSelectionRequestEvent& selectionRequestEvent = *reinterpret_cast<XSelectionRequestEvent*>(&windowEvent.xselectionrequest);

            // Our reply
            XSelectionEvent selectionEvent;

            selectionEvent.type      = SelectionNotify;
            selectionEvent.requestor = selectionRequestEvent.requestor;
            selectionEvent.selection = selectionRequestEvent.selection;
            selectionEvent.property  = selectionRequestEvent.property;
            selectionEvent.time      = selectionRequestEvent.time;

            if (selectionRequestEvent.selection == m_clipboard)
            {
                if (selectionRequestEvent.target == m_targets)
                {
                    // Respond to a request for our valid conversion targets
                    std::vector<Atom> targets;

                    targets.push_back(m_targets);
                    targets.push_back(m_text);
                    targets.push_back(XA_STRING);

                    if (m_utf8String != None)
                        targets.push_back(m_utf8String);

                    XChangeProperty(
                        m_display,
                        selectionRequestEvent.requestor,
                        selectionRequestEvent.property,
                        XA_ATOM,
                        32,
                        PropModeReplace,
                        reinterpret_cast<unsigned char*>(&targets[0]),
                        targets.size()
                    );

                    // Notify the requestor that they can read the targets from their window property
                    selectionEvent.target = m_targets;

                    XSendEvent(m_display, selectionRequestEvent.requestor, True, NoEventMask, reinterpret_cast<XEvent*>(&selectionEvent));

                    break;
                }
                else if ((selectionRequestEvent.target == XA_STRING) || ((m_utf8String == None) && (selectionRequestEvent.target == m_text)))
                {
                    // Respond to a request for conversion to a Latin-1 string
                    std::string data = m_clipboardContents.toAnsiString();

                    XChangeProperty(
                        m_display,
                        selectionRequestEvent.requestor,
                        selectionRequestEvent.property,
                        XA_STRING,
                        8,
                        PropModeReplace,
                        reinterpret_cast<const unsigned char*>(data.c_str()),
                        data.size()
                    );

                    // Notify the requestor that they can read the data from their window property
                    selectionEvent.target = XA_STRING;

                    XSendEvent(m_display, selectionRequestEvent.requestor, True, NoEventMask, reinterpret_cast<XEvent*>(&selectionEvent));

                    break;
                }
                else if ((m_utf8String != None) && ((selectionRequestEvent.target == m_utf8String) || (selectionRequestEvent.target == m_text)))
                {
                    // Respond to a request for conversion to a UTF-8 string
                    // or an encoding of our choosing (we always choose UTF-8)
                    std::basic_string<Uint8> data = m_clipboardContents.toUtf8();

                    XChangeProperty(
                        m_display,
                        selectionRequestEvent.requestor,
                        selectionRequestEvent.property,
                        m_utf8String,
                        8,
                        PropModeReplace,
                        reinterpret_cast<const unsigned char*>(data.c_str()),
                        data.size()
                    );

                    // Notify the requestor that they can read the data from their window property
                    selectionEvent.target = m_utf8String;

                    XSendEvent(m_display, selectionRequestEvent.requestor, True, NoEventMask, reinterpret_cast<XEvent*>(&selectionEvent));

                    break;
                }
            }

            // Notify the requestor that we could not respond to their request
            selectionEvent.target = selectionRequestEvent.target;
            selectionEvent.property = None;

            XSendEvent(m_display, selectionRequestEvent.requestor, True, NoEventMask, reinterpret_cast<XEvent*>(&selectionEvent));

            break;
        }
        default:
            break;
    }
}

} // namespace priv

} // namespace sf


text:
@interface PodsDummy_LCProgressHUD : NSObject
@end
@implementation PodsDummy_LCProgressHUD
@end


text:
<?php

namespace Cmf\Form\Element;

use Cmf\Form\Constants;
use Cmf\Form\Form;

/**
 * @author Vital Leshchyk <vitalleshchyk@gmail.com>
 */
class MultiSelect extends Form
{
    /** @var \Cmf\Data\Source\AbstractSource */
    protected $dataSource;

    /** @var bool */
    protected $elementsIsInitialized = false;

    /**
     * @param array $params
     */
    public function __construct($params = [])
    {
        $defaultParams = [
            'type' => Constants::TYPE_SUB_FORM,
            'dataSource' => null,
        ];

        $params = array_merge($this->defaultParams, $defaultParams, $params);

        parent::__construct($params);

        if ($params['dataSource']) {
            $this->dataSource = $params['dataSource'];
        }
    }

    /**
     * @return $this
     */
    protected function initializeElements()
    {
        if ($this->elementsIsInitialized) {
            return $this;
        }

        $this->elementsIsInitialized = true;

        foreach ($this->dataSource->getData() as $item) {
            $element = new Checkbox();
            $element->setTitle($item['title'])->setName($item['value']);
            $this->setElement($element);
        }

        return $this;
    }

    /**
     * @param array $values
     * @return $this
     */
    public function setValue($values = [])
    {
        foreach ($this->getElements() as $element) {
            $element->setValue(false);
        }

        foreach ($values as $key => $value) {
            $this->getElement($key)->setValue(true);
        }

        return $this;
    }
}


text:
package service

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io/ioutil"
	"math/rand"
	"strconv"
	"strings"
	"time"

	"go-common/app/service/main/push/dao"
	"go-common/app/service/main/push/dao/apns2"
	"go-common/app/service/main/push/dao/fcm"
	"go-common/app/service/main/push/dao/huawei"
	"go-common/app/service/main/push/dao/jpush"
	"go-common/app/service/main/push/dao/oppo"
	"go-common/app/service/main/push/model"
	"go-common/library/log"
	"go-common/library/sync/errgroup"
	"go-common/library/xstr"
)

const (
	_pushLimitAndroid = 1000
)

func (s *Service) pushAPNSproc() {
	for {
		v, ok := <-s.apnsCh
		if !ok {
			log.Info("apnsCh has been closed.")
			return
		}
		s.pushIOS(v.Info, v.Item)
		s.setChCounter(v.Info.TaskID, -1)
		time.Sleep(time.Millisecond)
	}
}

func (s *Service) pushMiproc() {
	for {
		v, ok := <-s.miCh
		if !ok {
			log.Info("miCh has been closed.")
			return
		}
		for scheme, items := range dispatchByScheme(v.Info.LinkType, v.Info.LinkValue, v.Items) {
			s.pushMi(v.Info, scheme, items)
		}
		s.setChCounter(v.Info.TaskID, -1)
		time.Sleep(time.Millisecond)
	}
}

func (s *Service) pushHuaweiproc() {
	for {
		v, ok := <-s.huaweiCh
		if !ok {
			log.Info("huaweiCh has been closed.")
			return
		}
		for scheme, items := range dispatchByScheme(v.Info.LinkType, v.Info.LinkValue, v.Items) {
			s.pushHuawei(v.Info, scheme, items)
		}
		s.setChCounter(v.Info.TaskID, -1)
		time.Sleep(time.Millisecond)
	}
}

func (s *Service) pushOppoproc() {
	for {
		v, ok := <-s.oppoCh
		if !ok {
			log.Info("oppoCh has been closed.")
			return
		}
		s.pushOppoOne(v.Info, v.Item)
		s.setChCounter(v.Info.TaskID, -1)
		time.Sleep(time.Millisecond)
	}
}

func (s *Service) pushJpushproc() {
	for {
		v, ok := <-s.jpushCh
		if !ok {
			log.Info("jpushCh has been closed.")
			return
		}
		for scheme, items := range dispatchByScheme(v.Info.LinkType, v.Info.LinkValue, v.Items) {
			s.pushJpush(v.Info, scheme, items)
		}
		s.setChCounter(v.Info.TaskID, -1)
		time.Sleep(time.Millisecond)
	}
}

func (s *Service) pushFCMproc() {
	for {
		v, ok := <-s.fcmCh
		if !ok {
			log.Info("fcmCh has been closed")
			return
		}
		for scheme, items := range dispatchByScheme(v.Info.LinkType, v.Info.LinkValue, v.Items) {
			s.pushFCM(v.Info, scheme, items)
		}
		s.setChCounter(v.Info.TaskID, -1)
		time.Sleep(time.Millisecond)
	}
}

func dispatchByScheme(linkType int8, linkValue string, items []*model.PushItem) (res map[string][]*model.PushItem) {
	var scheme string
	res = make(map[string][]*model.PushItem)
	for _, item := range items {
		scheme = model.Scheme(linkType, linkValue, model.PlatformAndroid, item.Build)
		res[scheme] = append(res[scheme], item)
	}
	return
}

func (s *Service) pushInfo(task *model.Task) *model.PushInfo {
	info := &model.PushInfo{
		Job:         task.Job,
		APPID:       task.APPID,
		TaskID:      task.ID,
		Title:       task.Title,
		Summary:     task.Summary,
		LinkType:    task.LinkType,
		LinkValue:   task.LinkValue,
		PushTime:    task.PushTime,
		ExpireTime:  task.ExpireTime,
		Sound:       task.Sound,
		Vibration:   task.Vibration,
		PassThrough: s.c.Push.PassThrough,
		// PassThrough: task.PassThrough,
		ImageURL: task.ImageURL,
	}
	if info.Title == "" {
		info.Title = model.DefaultMessageTitle
	}
	return info
}

// Pushs push some mids.
func (s *Service) Pushs(c context.Context, task *model.Task, mids []int64) (err error) {
	if len(mids) == 0 {
		log.Warn("s.Pushs(%d) no mids", task.ID)
		dao.PromInfo("push:没有mid")
		return
	}
	s.pushByPart(c, task, mids)
	return
}

// SinglePush push one mid.
func (s *Service) SinglePush(c context.Context, token string, task *model.Task, mid int64) (err error) {
	if err = s.checkBusiness(task.BusinessID, token); err != nil {
		return
	}
	var rs map[int][]*model.PushItem
	if rs, err = s.tokensByMid(task, mid); err != nil {
		return
	}
	if len(rs) == 0 {
		log.Warn("no tokens. mid(%d) task(%+v)", mid, task)
		return
	}
	info := s.pushInfo(task)
	for p, v := range rs {
		s.pushByPlatform(info, p, v)
	}
	for {
		if s.chCounterVal(task.ID) == 0 {
			log.Info("Pushs done. task(%+v) result(%+v)", task, s.fetchProgress(task.ID))
			return
		}
		time.Sleep(10 * time.Millisecond)
	}
}

// TestToken for test via push token.
func (s *Service) TestToken(c context.Context, info *model.PushInfo, token string) (err error) {
	r, err := s.dao.Report(context.Background(), token)
	if err != nil {
		return
	}
	if r == nil {
		log.Warn("test token(%s) not exist in db", token)
		return
	}
	var (
		res  *model.HTTPResponse
		item = &model.PushItem{
			Platform:  r.PlatformID,
			Mid:       r.Mid,
			Token:     token,
			Sound:     info.Sound,
			Vibration: info.Vibration,
			Build:     r.Build,
		}
		androidScheme = model.Scheme(info.LinkType, info.LinkValue, model.PlatformAndroid, item.Build)
	)
	switch item.Platform {
	case model.PlatformIPhone, model.PlatformIPad:
		if item.Platform == model.PlatformIPhone {
			res, err = s.dao.PushIPhone(c, info, item)
		} else {
			res, err = s.dao.PushIPad(c, info, item)
		}
		if err == nil && res.Code != apns2.StatusCodeSuccess {
			err = errors.New(res.Msg)
		}
	case model.PlatformXiaomi:
		res, err = s.dao.PushMi(c, info, androidScheme, token)
		if err == nil && res.Code != model.HTTPCodeOk {
			err = errors.New(res.Msg)
		}
	case model.PlatformHuawei:
		var resp *huawei.Response
		resp, err = s.dao.PushHuawei(c, info, androidScheme, []string{token})
		if err == nil && resp.Code != huawei.ResponseCodeSuccess {
			err = errors.New(resp.Msg)
		}
		log.Info("huawei s.TestToken(%+v,%s) result(%+v)", info, token, resp)
	case model.PlatformOppo:
		err = s.pushOppoOne(info, item)
		log.Info("oppo pushOne s.TestToken(%+v,%s)", info, token)
	case model.PlatformJpush:
		_, err = s.dao.PushJpush(c, info, androidScheme, []string{token})
	case model.PlatformFCM:
		_, err = s.dao.PushFCM(c, info, androidScheme, []string{token})
		log.Info("fcm s.dao.PushFCM(%+v,%s)", info, token)
	default:
		err = errors.New("平台类型错误")
	}
	if err != nil {
		log.Error("s.TestToken(%+v,%s) error(%v)", info, token, err)
		return
	}
	log.Info("s.TestToken(%+v,%s) result(%+v)", info, token, res)
	return
}

func (s *Service) pushByPart(c context.Context, task *model.Task, mids []int64) (err error) {
	var (
		counter int
		group   = errgroup.Group{}
		info    = s.pushInfo(task)
	)
	for {
		l := len(mids)
		if l == 0 {
			break
		}
		n := s.c.Push.PushPartSize
		if l < n {
			n = l
		}
		part := mids[:n]
		mids = mids[n:]
		group.Go(func() error {
			var rs map[int][]*model.PushItem
			var missed []int64
			if rs, missed, err = s.tokensByMids(c, task, part); err != nil {
				return nil
			}
			log.Info("missed mid task(%s) %s", task.ID, xstr.JoinInts(missed))
			for p, v := range rs {
				s.pushByPlatform(info, p, v)
			}
			_ = missed
			return nil
		})
		time.Sleep(time.Duration(s.c.Push.PushPartInterval))
		counter++
		if counter > s.c.Push.PushPartChanSize {
			group.Wait()
			counter = 0
		}
	}
	if counter > 0 {
		group.Wait()
	}
	for {
		if s.chCounterVal(task.ID) == 0 {
			log.Info("Pushs done. task(%+v) result(%+v)", task, s.fetchProgress(task.ID))
			return nil
		}
		time.Sleep(10 * time.Millisecond)
	}
}

func (s *Service) pushByPlatform(info *model.PushInfo, platform int, rs []*model.PushItem) {
	switch platform {
	case model.PlatformIPhone, model.PlatformIPad:
		for _, v := range rs {
			s.apnsCh <- &model.PushChanItem{Info: info, Item: v}
			dao.PromChanLen("apns_chan_len", int64(len(s.apnsCh)))
			s.setChCounter(info.TaskID, 1)
		}
		return
	case model.PlatformOppo:
		for _, v := range rs {
			s.oppoCh <- &model.PushChanItem{Info: info, Item: v}
			dao.PromChanLen("oppo_chan_len", int64(len(s.oppoCh)))
			s.setChCounter(info.TaskID, 1)
		}
		return
	}
	n := _pushLimitAndroid
	if platform == model.PlatformHuawei {
		n = s.c.Android.PushHuaweiPart
	}
	for len(rs) > 0 {
		if n > len(rs) {
			n = len(rs)
		}
		part := rs[:n]
		rs = rs[n:]
		switch platform {
		case model.PlatformHuawei:
			s.huaweiCh <- &model.PushChanItems{Info: info, Items: part}
			dao.PromChanLen("huawei_chan_len", int64(len(s.huaweiCh)))
		case model.PlatformJpush:
			s.jpushCh <- &model.PushChanItems{Info: info, Items: part}
			dao.PromChanLen("jpush_chan_len", int64(len(s.jpushCh)))
		case model.PlatformFCM:
			s.fcmCh <- &model.PushChanItems{Info: info, Items: part}
			dao.PromChanLen("fcm_chan_len", int64(len(s.fcmCh)))
		default:
			s.miCh <- &model.PushChanItems{Info: info, Items: part}
			dao.PromChanLen("mi_chan_len", int64(len(s.miCh)))
		}
		s.setChCounter(info.TaskID, 1)
	}
}

func (s *Service) pushMi(info *model.PushInfo, scheme string, items []*model.PushItem) (err error) {
	all := len(items)
	// ts := make([]string, all)
	tokenBuf := bytes.Buffer{}
	for _, item := range items {
		tokenBuf.WriteString(item.Token)
		tokenBuf.WriteString(",")
		// ts = append(ts, item.Token)
	}
	if tokenBuf.Len() == 0 {
		return nil
	}
	tokenBuf.Truncate(tokenBuf.Len() - 1)
	tokens := tokenBuf.String()
	ctx := context.Background()
	var res *model.HTTPResponse
	for c := 0; c <= s.c.Push.RetryTimes; c++ {
		res, err = s.dao.PushMi(ctx, info, scheme, tokens)
		if err == nil {
			break
		}
		dao.PromInfo("retry push mi")
		s.setProgress(info.TaskID, _pgRetryTimes, 1)
	}
	if err != nil || res.Code != model.HTTPCodeOk {
		s.setProgress(info.TaskID, _pgTokenFailed, int64(all))
		return
	}
	s.setProgress(info.TaskID, _pgTokenSuccess, int64(all))
	s.cache.Save(func() { logPushed(info.TaskID, model.PlatformXiaomi, items) })
	var success int
	msg := strings.Split(res.Msg, " ")
	if len(msg) == 6 {
		success, _ = strconv.Atoi(msg[4])
	} else {
		log.Warn("push mi result msg(%s)", res.Msg)
	}
	s.setProgress(info.TaskID, _pgTokenValid, int64(success))
	return
}

func (s *Service) pushIOS(info *model.PushInfo, item *model.PushItem) (err error) {
	var (
		res *model.HTTPResponse
		ctx = context.Background()
	)
	for c := 0; c <= s.c.Push.RetryTimes; c++ {
		if item.Platform == model.PlatformIPhone {
			res, err = s.dao.PushIPhone(ctx, info, item)
		} else {
			res, err = s.dao.PushIPad(ctx, info, item)
		}
		if err == nil {
			break
		}
		dao.PromInfo("retry push iOS")
		s.setProgress(info.TaskID, _pgRetryTimes, 1)
	}
	if err != nil || res == nil {
		s.setProgress(info.TaskID, _pgTokenFailed, 1)
		return
	}
	s.setProgress(info.TaskID, _pgTokenSuccess, 1)
	if res.Code == apns2.StatusCodeSuccess {
		s.setProgress(info.TaskID, _pgTokenValid, 1)
	} else if res.Code == apns2.StatusCodeNoActive || res.Code == apns2.StatusCodeNotForTopic {
		log.Warn("invalid token. mid(%d) token(%s) response(%+v)", item.Mid, item.Token, res)
		s.reportCache.Save(func() { s.DelReport(context.TODO(), info.APPID, item.Mid, item.Token) })
	} else {
		log.Error("apns response(%+v)", res)
	}
	return
}

func (s *Service) pushHuawei(info *model.PushInfo, scheme string, items []*model.PushItem) (err error) {
	var (
		tokens []string
		res    *huawei.Response
		all    = int64(len(items))
	)
	for _, item := range items {
		tokens = append(tokens, item.Token)
	}
	for c := 0; c <= s.c.Push.RetryTimes; c++ {
		if res, err = s.dao.PushHuawei(context.TODO(), info, scheme, tokens); err == nil {
			break
		}
		dao.PromInfo("retry push huawei")
		s.setProgress(info.TaskID, _pgRetryTimes, 1)
		if err == huawei.ErrLimit {
			time.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)
		}
	}
	if err != nil {
		dao.PromError("push:推送华为")
		s.setProgress(info.TaskID, _pgTokenFailed, all)
		if err == huawei.ErrLimit {
			for _, t := range tokens {
				log.Error("push huawei task(%s) token(%s) error(%v)", info.TaskID, t, err)
			}
		}
		return
	}
	s.setProgress(info.TaskID, _pgTokenSuccess, all)
	s.cache.Save(func() { logPushed(info.TaskID, model.PlatformHuawei, items) })
	switch res.Code {
	case huawei.ResponseCodeSuccess:
		s.setProgress(info.TaskID, _pgTokenValid, all)
		log.Info("push huawei success task(%s) success(%d)", info.TaskID, all)
	case huawei.ResponseCodeSomeTokenInvalid:
		itr := &huawei.InvalidTokenResponse{}
		if err = json.Unmarshal([]byte(res.Msg), itr); err != nil {
			log.Error("json.Unmarshal() error(%v)", err)
			return
		}
		s.setProgress(info.TaskID, _pgTokenValid, int64(itr.Success))
		log.Warn("push huawei success task(%s) failed(%d) illegal(%v)", info.TaskID, itr.Failure, itr.IllegalTokens)
		if len(itr.IllegalTokens) == 0 {
			return
		}
		s.reportCache.Save(func() {
			m := make(map[string]int64, all)
			for _, i := range items {
				m[i.Token] = i.Mid
			}
			for _, t := range itr.IllegalTokens {
				s.DelReport(context.TODO(), info.APPID, m[t], t)
			}
		})
	case huawei.ResponseCodeAllTokenInvalid, huawei.ResponseCodeAllTokenInvalidNew:
		s.cache.Save(func() {
			for _, i := range items {
				s.DelReport(context.TODO(), info.APPID, i.Mid, i.Token)
			}
		})
		log.Error("push huawei failed task(%s) failed(%d) illegal(%v)", info.TaskID, all, tokens)
	default:
		log.Error("huawei push response task(%s) error(%v)", info.TaskID, res)
	}
	return
}

func (s *Service) pushOppoOne(info *model.PushInfo, item *model.PushItem) (err error) {
	params, _ := json.Marshal(map[string]string{
		"task_id": info.TaskID,
		"scheme":  model.Scheme(info.LinkType, info.LinkValue, model.PlatformAndroid, item.Build),
	})
	m := &oppo.Message{
		Title:        info.Title,
		Content:      info.Summary,
		ActionType:   oppo.ActionTypeInner,
		ActionParams: string(params),
		OfflineTTL:   int(int64(info.ExpireTime) - time.Now().Unix()),
		CallbackURL:  oppo.CallbackURL(info.APPID, info.TaskID),
	}
	var res *oppo.Response
	for c := 0; c <= s.c.Push.RetryTimes; c++ {
		if res, err = s.dao.PushOppoOne(context.TODO(), info, m, item.Token); err == nil {
			break
		}
		dao.PromInfo("retry push oppo")
		s.setProgress(info.TaskID, _pgRetryTimes, 1)
	}
	if err != nil || res == nil {
		s.setProgress(info.TaskID, _pgTokenFailed, 1)
		dao.PromError("push:推送oppo")
		log.Error("oppo push response task(%s) error(%v)", info.TaskID, res)
		return
	}
	s.setProgress(info.TaskID, _pgTokenSuccess, 1)
	if res.Code == oppo.ResponseCodeInvalidToken || res.Code == oppo.ResponseCodeUnsubscribeToken || res.Code == oppo.ResponseCodeRepeatToken {
		if item.Mid > 0 {
			s.reportCache.Save(func() { s.DelReport(context.TODO(), info.APPID, item.Mid, item.Token) })
		}
		return
	}
	s.setProgress(info.TaskID, _pgTokenValid, 1)
	return
}

// func (s *Service) pushOppo(info *model.PushInfo, items []*model.PushItem) (err error) {
// 	params, _ := json.Marshal(map[string]string{
// 		"task_id": info.TaskID,
// 		"scheme":  model.Scheme(info.LinkType, info.LinkValue, model.PlatformAndroid),
// 	})
// 	m := &oppo.Message{
// 		Title:        info.Title,
// 		Content:      info.Summary,
// 		ActionType:   oppo.ActionTypeInner,
// 		ActionParams: string(params),
// 		OfflineTTL:   int(int64(info.ExpireTime) - time.Now().Unix()),
// 		CallbackURL:  oppo.CallbackURL(info.APPID, info.TaskID),
// 	}
// 	res, err := s.dao.OppoMessage(context.TODO(), info, m)
// 	if err != nil || res == nil || res.Data.MsgID == "" {
// 		return
// 	}
// 	var (
// 		ts  []string
// 		all = int64(len(items))
// 		tm  = make(map[string]int64, all)
// 	)
// 	for _, i := range items {
// 		ts = append(ts, i.Token)
// 		tm[i.Token] = i.Mid
// 	}
// 	for c := 0; c <= s.c.Push.RetryTimes; c++ {
// 		if res, err = s.dao.PushOppo(context.TODO(), info, res.Data.MsgID, ts); err == nil {
// 			break
// 		}
// 		dao.PromInfo("retry push oppo")
// 		s.setProgress(info.TaskID, _pgRetryTimes, 1, model.PlatformOppo)
// 	}
// 	if err != nil || res == nil || res.Code != oppo.ResponseCodeSuccess {
// 		s.setProgress(info.TaskID, _pgTokenFailed, all, model.PlatformOppo)
// 		dao.PromError("push:推送oppo")
// 		log.Error("oppo push response task(%s) error(%v)", info.TaskID, res)
// 		if res.Code == oppo.ResponseCodeInvalidToken {
// 			s.delOppoReports(tm, info.APPID, ts)
// 		}
// 		return
// 	}
// 	s.setProgress(info.TaskID, _pgTokenSuccess, all, model.PlatformOppo)
// 	s.cache.Save(func() { logPushed(model.PlatformOppo, items) })
// 	var (
// 		invalid     = len(res.Data.TokenInvalid)
// 		unsubscribe = len(res.Data.TokenUnsubscribe)
// 		repeat      = len(res.Data.TokenRepeat)
// 		valid       = int(all) - invalid - unsubscribe - repeat
// 	)
// 	if invalid+unsubscribe+repeat > 0 {
// 		if invalid > 0 {
// 			s.delOppoReports(tm, info.APPID, res.Data.TokenInvalid)
// 		}
// 		if unsubscribe > 0 {
// 			s.delOppoReports(tm, info.APPID, res.Data.TokenUnsubscribe)
// 		}
// 		if repeat > 0 {
// 			s.delOppoReports(tm, info.APPID, res.Data.TokenRepeat)
// 		}
// 	}
// 	s.setProgress(info.TaskID, _pgTokenValid, int64(valid), model.PlatformOppo)
// 	s.cache.Save(func() { s.dao.AddTokensCache(context.TODO(), info.TaskID, ts) })
// 	log.Info("push oppo success task(%s) success(%d)", info.TaskID, all)
// 	return
// }

// func (s *Service) delOppoReports(m map[string]int64, appid int64, tokens []string) {
// 	if len(tokens) == 0 {
// 		return
// 	}
// 	s.reportCache.Save(func() {
// 		for _, t := range tokens {
// 			s.DelReport(context.TODO(), appid, m[t], t)
// 		}
// 	})
// }

func (s *Service) pushJpush(info *model.PushInfo, scheme string, items []*model.PushItem) (err error) {
	var (
		tokens []string
		all    = int64(len(items))
		valid  = all
		resp   *jpush.PushResponse
	)
	for _, item := range items {
		tokens = append(tokens, item.Token)
	}
	for c := 0; c <= s.c.Push.RetryTimes; c++ {
		if resp, err = s.dao.PushJpush(context.TODO(), info, scheme, tokens); err == nil && !resp.Retry {
			break
		}
		dao.PromInfo("retry push jpush")
		s.setProgress(info.TaskID, _pgRetryTimes, 1)
	}
	if err != nil {
		dao.PromError("push:推送极光")
		s.setProgress(info.TaskID, _pgTokenFailed, all)
		return
	}
	if resp.Error.Code != 0 {
		s.setProgress(info.TaskID, _pgTokenFailed, all)
		log.Error("jpush task(%s) tokens(%d) invalid code(%+v)", info.TaskID, len(tokens), resp)
		return
	}
	valid -= int64(len(resp.IllegalTokens))
	s.setProgress(info.TaskID, _pgTokenSuccess, all)
	s.cache.Save(func() { logPushed(info.TaskID, model.PlatformJpush, items) })
	s.setProgress(info.TaskID, _pgTokenValid, valid)
	log.Info("push jpush success task(%s) success(%d)", info.TaskID, all)
	return
}

func (s *Service) pushFCM(info *model.PushInfo, scheme string, items []*model.PushItem) (err error) {
	var (
		tokens []string
		all    = int64(len(items))
		valid  = all
		resp   *fcm.Response
	)
	for _, item := range items {
		tokens = append(tokens, item.Token)
	}
	for c := 0; c <= s.c.Push.RetryTimes; c++ {
		if resp, err = s.dao.PushFCM(context.Background(), info, scheme, tokens); err == nil {
			break
		}
		// 报错的情况下,如果 RetryAfter 有值才需要重试
		if resp != nil && resp.RetryAfter == "" {
			break
		}
		if d, e := resp.GetRetryAfterTime(); e == nil {
			time.Sleep(d)
		}
		dao.PromInfo("retry push fcm")
		s.setProgress(info.TaskID, _pgRetryTimes, 1)
	}
	if err != nil {
		dao.PromError("push:push fcm")
		s.setProgress(info.TaskID, _pgTokenFailed, all)
		return
	}
	s.setProgress(info.TaskID, _pgTokenSuccess, all)
	s.cache.Save(func() { logPushed(info.TaskID, model.PlatformFCM, items) })
	valid -= int64(resp.Fail)
	s.setProgress(info.TaskID, _pgTokenValid, valid)
	log.Info("push fcm success task(%s) success(%d)", info.TaskID, all)
	return
}

func (s *Service) tokensByMid(task *model.Task, mid int64) (res map[int][]*model.PushItem, err error) {
	var rs []*model.Report
	if rs, err = s.dao.ReportsCacheByMid(context.TODO(), mid); err != nil {
		if rs, err = s.dao.ReportsByMid(context.TODO(), mid); err != nil {
			return
		}
	}
	if len(rs) == 0 {
		return
	}
	p := map[int64][]*model.Report{mid: rs}
	res = s.distribute(task, p)
	return
}

func (s *Service) tokensByMids(c context.Context, task *model.Task, mids []int64) (res map[int][]*model.PushItem, missed []int64, err error) {
	rs, missed, err := s.dao.ReportsCacheByMids(c, mids)
	if err != nil {
		dao.PromInfo("report:查缓存失败回源")
		if rs, err = s.dao.ReportsByMids(c, mids); err != nil {
			return
		}
	}
	res = s.distribute(task, rs)
	return
}

func (s *Service) distribute(task *model.Task, rs map[int64][]*model.Report) (res map[int][]*model.PushItem) {
	var (
		validMid     int64
		validMidPlat = make(map[int]map[int64]bool)
		buildCount   = len(task.Build)
		// platformCount = len(task.Platform)
		brands = make(map[string]int64)
	)
	res = make(map[int][]*model.PushItem)
	for mid, rr := range rs {
		var valid bool
		for _, r := range rr {
			if r.APPID != task.APPID {
				// log.Info("task(%s) token(%s) mid(%d) app not match", task.ID, r.DeviceToken, mid)
				continue
			}
			if r.NotifySwitch == model.SwitchOff {
				// log.Info("task(%s) token(%s) mid(%d) switchoff", task.ID, r.DeviceToken, mid)
				continue
			}
			realTime := model.RealTime(r.TimeZone)
			if realTime.Unix() > int64(task.ExpireTime) {
				// log.Info("task(%s) token(%s) mid(%d) expire_time(%s) expired", task.ID, r.DeviceToken, mid, task.ExpireTime)
				continue
			}
			// if platformCount > 0 && !validatePlatform(r.PlatformID, task.Platform) {
			// 	// log.Info("task(%s) token(%s) mid(%d) platform forbid", task.ID, r.DeviceToken, mid)
			// 	continue
			// }
			if buildCount > 0 && !validateBuild(r.PlatformID, r.Build, task.Build) {
				// log.Info("task(%s) token(%s) mid(%d) build forbid", task.ID, r.DeviceToken, mid)
				continue
			}
			p := &model.PushItem{Platform: r.PlatformID, Token: r.DeviceToken, Mid: mid, Sound: task.Sound, Vibration: task.Vibration}
			res[r.PlatformID] = append(res[r.PlatformID], p)
			valid = true
			brands[r.DeviceBrand]++
			if _, ok := validMidPlat[r.PlatformID]; !ok {
				validMidPlat[r.PlatformID] = make(map[int64]bool)
			}
			validMidPlat[r.PlatformID][r.Mid] = true
		}
		if valid {
			validMid++
		}
	}
	s.setProgress(task.ID, _pgMidValid, validMid)
	for br, v := range brands {
		s.setBrandProgress(task.ID, model.DeviceBrand(br), v)
	}
	return
}

// func validatePlatform(platform int, set []int) bool {
// 	for _, v := range set {
// 		if v == platform {
// 			return true
// 		}
// 	}
// 	if platform == model.PlatformIPhone || platform == model.PlatformIPad {
// 		return false
// 	}
// 	if platform == model.PlatformAndroid {
// 		return true
// 	}
// 	return false
// }

func logPushed(task string, platform int, items []*model.PushItem) {
	for _, v := range items {
		log.Info("push done, task(%s) platform(%d) mid(%d) token(%s)", task, platform, v.Mid, v.Token)
	}
}

func validateBuild(platform, build int, builds map[int]*model.Build) bool {
	if len(builds) == 0 {
		return true
	}
	if builds[platform] == nil {
		return true
	}
	c := builds[platform].Condition
	b := builds[platform].Build
	switch c {
	case "gt":
		return build > b
	case "gte":
		return build >= b
	case "lt":
		return build < b
	case "lte":
		return build <= b
	case "eq":
		return build == b
	case "ne":
		return build != b
	}
	return false
}

func (s *Service) pushTokens(task *model.Task) (err error) {
	bs, err := ioutil.ReadFile(task.MidFile)
	if err != nil {
		log.Error("ioutil.ReadFile(%s) error(v)", task.MidFile, err)
		return
	}
	var (
		counter int
		group   = errgroup.Group{}
		info    = s.pushInfo(task)
		tokens  = strings.Split(string(bs), "\n")
	)
	for {
		l := len(tokens)
		if l == 0 {
			break
		}
		n := s.c.Push.PushPartSize
		if l < n {
			n = l
		}
		part := tokens[:n]
		tokens = tokens[n:]
		group.Go(func() error {
			res, missed, e := s.dao.TokensCache(context.Background(), part)
			if e != nil {
				log.Error("s.dao.TokensCache error(%v)", err)
			}
			if len(missed) > 0 {
				log.Info("task(%s) tokens cache missed(%d)", task.ID, len(missed))
			}
			var rs []*model.PushItem
			brands := make(map[int]int64)
			for _, t := range part {
				build := model.UnknownBuild
				if v, ok := res[t]; ok {
					build = v.Build
					brands[model.DeviceBrand(v.DeviceBrand)]++
				}
				rs = append(rs, &model.PushItem{Platform: task.PlatformID, Token: t, Sound: task.Sound, Vibration: task.Vibration, Build: build})
			}
			log.Info("push tokens task(%+v) tokens(%d)", task, len(rs))
			s.setProgress(task.ID, _pgTokenTotal, int64(len(rs)))
			for k, v := range brands {
				s.setBrandProgress(task.ID, k, v)
			}
			s.pushByPlatform(info, task.PlatformID, rs)
			return nil
		})
		time.Sleep(time.Duration(s.c.Push.PushPartInterval))
		counter++
		if counter > s.c.Push.PushPartChanSize {
			group.Wait()
			counter = 0
		}
	}
	if counter > 0 {
		group.Wait()
	}
	for {
		if s.chCounterVal(task.ID) == 0 {
			log.Info("Pushs done. task(%+v) result(%+v)", task, s.fetchProgress(task.ID))
			return nil
		}
		time.Sleep(10 * time.Millisecond)
	}
}


text:
from django.db import migrations

import touchtechnology.common.db.models

class Migration(migrations.Migration):

    dependencies = [
        ("news", "0005_auto_20191122_1340"),
    ]

    operations = [
        migrations.AddField(
            model_name="article",
            name="copy",
            field=touchtechnology.common.db.models.HTMLField(
                blank=True, verbose_name="Copy"
            ),
        ),
    ]


text:
import { compose, defaultLogger } from '../../utils.js';
import { createTheme } from '../theme.js';
import { leftPad, withMargin } from '../utils.js';
import getDiagnosticMessage from './diagnostic.js';
import getSummaryMessage from './summary.js';

export const createWriter = ({
  log = defaultLogger,
  theme = createTheme(),
} = {}) => {
  const print = compose([log, leftPad(2)]);

  const diagnostics = getDiagnosticMessage({ theme });
  const summary = getSummaryMessage({ theme });

  const printDiagnostic = (diag) => {
    const { description, operator } = diag;
    print('');
    const operatorString = theme.operator(`[${operator}]`);
    print(description);
    print(`${operatorString} ${diagnostics(diag)}`);
  };

  const printSummary = (counter) => {
    print('');
    print(summary.total(counter));
    print(summary.pass(counter));
    print(summary.fail(counter));
    print(summary.skip(counter));
    print('');
  };

  const printLocation = (at) => print(`${theme.light('at')}: ${at}`);

  const printFailingTestPath = (stack) => {
    print('');
    const testPath = [...stack];
    const current = testPath.pop();
    print(
      `${theme.errorBadge('FAIL')} ${theme.header(
        [...testPath, theme.emphasis(current)].join(
          theme.adorner(withMargin('>'))
        )
      )}`
    );
  };

  return {
    printDiagnostic,
    print,
    printSummary,
    printFailingTestPath,
    printLocation,
  };
};


text:
package fr.insalyon.citi.golo.doc;

import fr.insalyon.citi.golo.compiler.parser.ASTCompilationUnit;
import fr.insalyon.citi.golo.compiler.parser.GoloParser;
import gololang.Predefined;
import org.testng.SkipException;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class DocumentationRenderingTest {

  public static final String SRC = "src/test/resources/for-parsing-and-compilation/";

  @BeforeMethod
  public void check_bootstrapped() throws Throwable {
    if (System.getenv("golo.bootstrapped") == null) {
      throw new SkipException("Golo is in a bootstrap build execution");
    }
  }

  @Test
  public void markdown_processor() throws Throwable {
    GoloParser parser = new GoloParser(new FileInputStream(SRC + "doc.golo"));
    ASTCompilationUnit compilationUnit = parser.CompilationUnit();

    MarkdownProcessor processor = new MarkdownProcessor();
    String result = processor.render(compilationUnit);
    assertThat(result, containsString("# Documentation for `Documented`"));
    assertThat(result, containsString("### `with_doc(a, b)`"));
    assertThat(result, containsString("println(\"foo\": yop())"));

    Path tempDir = Files.createTempDirectory("foo");
    processor.process(Arrays.asList(compilationUnit), tempDir);
    Path expectedDocFile = tempDir.resolve("Documented.markdown");
    assertThat(Files.exists(expectedDocFile), is(true));
    assertThat(Files.isRegularFile(expectedDocFile), is(true));
    assertThat(Files.size(expectedDocFile) > 0, is(true));

    String contents = (String) Predefined.fileToText(expectedDocFile, "UTF-8");
    assertThat(contents, is(result));

    Path expectedIndexFile = tempDir.resolve("index.markdown");
    assertThat(Files.exists(expectedIndexFile), is(true));
    assertThat(Files.isRegularFile(expectedIndexFile), is(true));
    assertThat(Files.size(expectedIndexFile) > 0, is(true));

    contents = (String) Predefined.fileToText(expectedIndexFile, "UTF-8");
    assertThat(contents, containsString("# Modules index"));
    assertThat(contents, containsString("* [Documented](Documented.markdown"));
  }

  @Test
  public void html_processor() throws Throwable {
    GoloParser parser = new GoloParser(new FileInputStream(SRC + "doc.golo"));
    ASTCompilationUnit compilationUnit = parser.CompilationUnit();

    HtmlProcessor processor = new HtmlProcessor();
    String result = processor.render(compilationUnit);
    assertThat(result, containsString("
Documentation for Documented
"));
    assertThat(result, containsString("
with_doc(a, b)"));
    assertThat(result, containsString("
println(\"foo\": yop())"));
    assertThat(result, containsString("
Point
"));
    assertThat(result, containsString("x and y"));

    Path tempDir = Files.createTempDirectory("foo");
    processor.process(Arrays.asList(compilationUnit), tempDir);
    Path expectedDocFile = tempDir.resolve("Documented.html");
    assertThat(Files.exists(expectedDocFile), is(true));
    assertThat(Files.isRegularFile(expectedDocFile), is(true));
    assertThat(Files.size(expectedDocFile) > 0, is(true));

    Path expectedIndexFile = tempDir.resolve("index.html");
    assertThat(Files.exists(expectedIndexFile), is(true));
    assertThat(Files.isRegularFile(expectedIndexFile), is(true));
    assertThat(Files.size(expectedIndexFile) > 0, is(true));

    String contents = (String) Predefined.fileToText(expectedIndexFile, "UTF-8");
    assertThat(contents, containsString("
Modules index
"));
    assertThat(contents, containsString("Documented"));
  }
}


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

namespace Sitecore.Ecommerce.Data.Convertors
{
  using System.Data;
  using Sitecore.Diagnostics;
  using Sitecore.Ecommerce.DomainModel.Carts;
  using Sitecore.Ecommerce.DomainModel.Data;

  /// <summary>
  /// Converts the ShoppingCart to DataRow and vice-versa
  /// </summary>
  public class ShoppingCartConvertor : Convertor<ShoppingCart>
  {
    /// <summary>
    /// The shopping cart line convertor
    /// </summary>
    private static readonly ShoppingCartLineConvertor ShoppingCartLineConvertor = new ShoppingCartLineConvertor();

    /// <summary>
    /// The totals convertor
    /// </summary>
    private static readonly KeyValuePairConvertor<string, decimal> TotalsConvertor = new KeyValuePairConvertor<string, decimal>();

    /// <summary>
    /// Puts the content of the ShoppingCart to the DataRow
    /// </summary>
    /// <param name="model">
    /// The Shopping cart to store.
    /// </param>
    /// <param name="row">
    /// The row which contains the information.
    /// </param>
    public override void DomainModelToDTO(ShoppingCart model, ref DataRow row)
    {
      Assert.IsNotNull(model, "model must not be null");
      Assert.IsNotNull(row, "row must not be null");

      if (model.Currency is IEntity)
      {
        row["Currency.Alias"] = ((IEntity)model.Currency).Alias;
      }

      row["Currency.Code"] = model.Currency.Code;
      row["Currency.Name"] = model.Currency.Name;
      row["Currency.Title"] = model.Currency.Title;

      if (model.CustomerInfo is IEntity)
      {
        row["CustomerInfo.Alias"] = ((IEntity)model.CustomerInfo).Alias;
      }

      row["CustomerInfo.AccountId"] = model.CustomerInfo.AccountId;
      row["CustomerInfo.AccountType"] = model.CustomerInfo.AccountType;

      if (model.CustomerInfo.BillingAddress is IEntity)
      {
        row["CustomerInfo.BillingAddress.Alias"] = ((IEntity)model.CustomerInfo.BillingAddress).Alias;
      }

      row["CustomerInfo.BillingAddress.Address"] = model.CustomerInfo.BillingAddress.Address;
      row["CustomerInfo.BillingAddress.Address2"] = model.CustomerInfo.BillingAddress.Address2;
      row["CustomerInfo.BillingAddress.City"] = model.CustomerInfo.BillingAddress.City;

      if (model.CustomerInfo.BillingAddress.Country is IEntity)
      {
        row["CustomerInfo.BillingAddress.Country.Alias"] = ((IEntity)model.CustomerInfo.BillingAddress.Country).Alias;
      }

      row["CustomerInfo.BillingAddress.Country.Code"] = model.CustomerInfo.BillingAddress.Country.Code;
      row["CustomerInfo.BillingAddress.Country.Name"] = model.CustomerInfo.BillingAddress.Country.Name;
      row["CustomerInfo.BillingAddress.Country.Title"] = model.CustomerInfo.BillingAddress.Country.Title;

      if (model.CustomerInfo.BillingAddress.Country.VatRegion is IEntity)
      {
        row["CustomerInfo.BillingAddress.Country.VatRegion.Alias"] = ((IEntity)model.CustomerInfo.BillingAddress.Country.VatRegion).Alias;
      }

      row["CustomerInfo.BillingAddress.Country.VatRegion.Code"] = model.CustomerInfo.BillingAddress.Country.VatRegion.Code;
      row["CustomerInfo.BillingAddress.Country.VatRegion.Name"] = model.CustomerInfo.BillingAddress.Country.VatRegion.Name;
      row["CustomerInfo.BillingAddress.Country.VatRegion.Title"] = model.CustomerInfo.BillingAddress.Country.VatRegion.Title;
      row["CustomerInfo.BillingAddress.Name"] = model.CustomerInfo.BillingAddress.Name;
      row["CustomerInfo.BillingAddress.Name2"] = model.CustomerInfo.BillingAddress.Name2;
      row["CustomerInfo.BillingAddress.State"] = model.CustomerInfo.BillingAddress.State;
      row["CustomerInfo.BillingAddress.Zip"] = model.CustomerInfo.BillingAddress.Zip;
      row["CustomerInfo.CustomerId"] = model.CustomerInfo.CustomerId;
      row["CustomerInfo.Email"] = model.CustomerInfo.Email;
      row["CustomerInfo.Email2"] = model.CustomerInfo.Email2;
      row["CustomerInfo.Fax"] = model.CustomerInfo.Fax;
      row["CustomerInfo.Mobile"] = model.CustomerInfo.Mobile;
      row["CustomerInfo.NickName"] = model.CustomerInfo.NickName;
      row["CustomerInfo.Phone"] = model.CustomerInfo.Phone;

      if (model.CustomerInfo.ShippingAddress is IEntity)
      {
        row["CustomerInfo.ShippingAddress.Alias"] = ((IEntity)model.CustomerInfo.ShippingAddress).Alias;
      }

      row["CustomerInfo.ShippingAddress.Address"] = model.CustomerInfo.ShippingAddress.Address;
      row["CustomerInfo.ShippingAddress.Address2"] = model.CustomerInfo.ShippingAddress.Address2;
      row["CustomerInfo.ShippingAddress.City"] = model.CustomerInfo.ShippingAddress.City;

      if (model.CustomerInfo.ShippingAddress.Country is IEntity)
      {
        row["CustomerInfo.ShippingAddress.Country.Alias"] = ((IEntity)model.CustomerInfo.ShippingAddress.Country).Alias;
      }

      row["CustomerInfo.ShippingAddress.Country.Code"] = model.CustomerInfo.ShippingAddress.Country.Code;
      row["CustomerInfo.ShippingAddress.Country.Name"] = model.CustomerInfo.ShippingAddress.Country.Name;
      row["CustomerInfo.ShippingAddress.Country.Title"] = model.CustomerInfo.ShippingAddress.Country.Title;

      if (model.CustomerInfo.ShippingAddress.Country.VatRegion is IEntity)
      {
        row["CustomerInfo.ShippingAddress.Country.VatRegion.Alias"] = ((IEntity)model.CustomerInfo.ShippingAddress.Country.VatRegion).Alias;
      }

      row["CustomerInfo.ShippingAddress.Country.VatRegion.Code"] = model.CustomerInfo.ShippingAddress.Country.VatRegion.Code;
      row["CustomerInfo.ShippingAddress.Country.VatRegion.Name"] = model.CustomerInfo.ShippingAddress.Country.VatRegion.Name;
      row["CustomerInfo.ShippingAddress.Country.VatRegion.Title"] = model.CustomerInfo.ShippingAddress.Country.VatRegion.Title;
      row["CustomerInfo.ShippingAddress.Name"] = model.CustomerInfo.ShippingAddress.Name;
      row["CustomerInfo.ShippingAddress.Name2"] = model.CustomerInfo.ShippingAddress.Name2;
      row["CustomerInfo.ShippingAddress.State"] = model.CustomerInfo.ShippingAddress.State;
      row["CustomerInfo.ShippingAddress.Zip"] = model.CustomerInfo.ShippingAddress.Zip;

      if (model.NotificationOption is IEntity)
      {
        row["NotificationOption.Alias"] = ((IEntity)model.NotificationOption).Alias;
      }

      row["NotificationOption.Code"] = model.NotificationOption.Code;
      row["NotificationOption.Name"] = model.NotificationOption.Name;
      row["NotificationOption.Title"] = model.NotificationOption.Title;
      row["NotificationOptionValue"] = model.NotificationOptionValue;
      row["OrderNumber"] = model.OrderNumber;

      if (model.PaymentSystem is IEntity)
      {
        row["PaymentSystem.Alias"] = ((IEntity)model.PaymentSystem).Alias;
      }

      row["PaymentSystem.Code"] = model.PaymentSystem.Code;
      row["PaymentSystem.Description"] = model.PaymentSystem.Description;
      row["PaymentSystem.LogoUrl"] = model.PaymentSystem.LogoUrl;
      row["PaymentSystem.Password"] = model.PaymentSystem.Password;
      row["PaymentSystem.PaymentSecondaryUrl"] = model.PaymentSystem.PaymentSecondaryUrl;
      row["PaymentSystem.PaymentSettings"] = model.PaymentSystem.PaymentSettings;
      row["PaymentSystem.PaymentUrl"] = model.PaymentSystem.PaymentUrl;
      row["PaymentSystem.Title"] = model.PaymentSystem.Title;
      row["PaymentSystem.Username"] = model.PaymentSystem.Username;
      row["ShippingPrice"] = model.ShippingPrice;

      if (model.ShippingProvider is IEntity)
      {
        row["ShippingProvider.Alias"] = ((IEntity)model.ShippingProvider).Alias;
      }

      row["ShippingProvider.AvailableNotificationOptions"] = model.ShippingProvider.AvailableNotificationOptions;
      row["ShippingProvider.Code"] = model.ShippingProvider.Code;
      row["ShippingProvider.Description"] = model.ShippingProvider.Description;
      row["ShippingProvider.IconUrl"] = model.ShippingProvider.IconUrl;
      row["ShippingProvider.Name"] = model.ShippingProvider.Name;
      row["ShippingProvider.Price"] = model.ShippingProvider.Price;
      row["ShippingProvider.Title"] = model.ShippingProvider.Title;
      row["ShoppingCartLines"] = ShoppingCartLineConvertor.DomainModelToDTO(model.ShoppingCartLines);
      row["Totals"] = TotalsConvertor.DomainModelToDTO(model.Totals);
    }

    /// <summary>
    /// Restores the ShoppingCart from the DataRow
    /// </summary>
    /// <param name="row">
    /// The row to retrieve information from.
    /// </param>
    /// <param name="model">
    /// The model to restore.
    /// </param>
    public override void DTOToDomainModel(DataRow row, ref ShoppingCart model)
    {
      Assert.IsNotNull(model, "model must not be null");
      Assert.IsNotNull(row, "row must not be null");

      if (model.Currency is IEntity)
      {
        ((IEntity)model.Currency).Alias = this.ConvertDataRowValue<string>(row["Currency.Alias"]);
      }

      model.Currency.Code = this.ConvertDataRowValue<string>(row["Currency.Code"]);
      model.Currency.Name = this.ConvertDataRowValue<string>(row["Currency.Name"]);
      model.Currency.Title = this.ConvertDataRowValue<string>(row["Currency.Title"]);

      if (model.CustomerInfo is IEntity)
      {
        ((IEntity)model.CustomerInfo).Alias = this.ConvertDataRowValue<string>(row["CustomerInfo.Alias"]);
      }

      model.CustomerInfo.AccountId = this.ConvertDataRowValue<string>(row["CustomerInfo.AccountId"]);
      model.CustomerInfo.AccountType = this.ConvertDataRowValue<string>(row["CustomerInfo.AccountType"]);

      if (model.CustomerInfo.BillingAddress is IEntity)
      {
        ((IEntity)model.CustomerInfo.BillingAddress).Alias = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Alias"]);
      }

      model.CustomerInfo.BillingAddress.Address = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Address"]);
      model.CustomerInfo.BillingAddress.Address2 = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Address2"]);
      model.CustomerInfo.BillingAddress.City = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.City"]);

      if (model.CustomerInfo.BillingAddress.Country is IEntity)
      {
        ((IEntity)model.CustomerInfo.BillingAddress.Country).Alias = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Country.Alias"]);
      }

      model.CustomerInfo.BillingAddress.Country.Code = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Country.Code"]);
      model.CustomerInfo.BillingAddress.Country.Name = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Country.Name"]);
      model.CustomerInfo.BillingAddress.Country.Title = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Country.Title"]);

      if (model.CustomerInfo.BillingAddress.Country.VatRegion is IEntity)
      {
        ((IEntity)model.CustomerInfo.BillingAddress.Country.VatRegion).Alias = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Country.VatRegion.Alias"]);
      }

      model.CustomerInfo.BillingAddress.Country.VatRegion.Code = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Country.VatRegion.Code"]);
      model.CustomerInfo.BillingAddress.Country.VatRegion.Name = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Country.VatRegion.Name"]);
      model.CustomerInfo.BillingAddress.Country.VatRegion.Title = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Country.VatRegion.Title"]);
      model.CustomerInfo.BillingAddress.Name = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Name"]);
      model.CustomerInfo.BillingAddress.Name2 = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Name2"]);
      model.CustomerInfo.BillingAddress.State = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.State"]);
      model.CustomerInfo.BillingAddress.Zip = this.ConvertDataRowValue<string>(row["CustomerInfo.BillingAddress.Zip"]);
      model.CustomerInfo.CustomerId = this.ConvertDataRowValue<string>(row["CustomerInfo.CustomerId"]);
      model.CustomerInfo.Email = this.ConvertDataRowValue<string>(row["CustomerInfo.Email"]);
      model.CustomerInfo.Email2 = this.ConvertDataRowValue<string>(row["CustomerInfo.Email2"]);
      model.CustomerInfo.Fax = this.ConvertDataRowValue<string>(row["CustomerInfo.Fax"]);
      model.CustomerInfo.Mobile = this.ConvertDataRowValue<string>(row["CustomerInfo.Mobile"]);
      model.CustomerInfo.NickName = this.ConvertDataRowValue<string>(row["CustomerInfo.NickName"]);
      model.CustomerInfo.Phone = this.ConvertDataRowValue<string>(row["CustomerInfo.Phone"]);

      if (model.CustomerInfo.ShippingAddress is IEntity)
      {
        ((IEntity)model.CustomerInfo.ShippingAddress).Alias = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Alias"]);
      }

      model.CustomerInfo.ShippingAddress.Address = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Address"]);
      model.CustomerInfo.ShippingAddress.Address2 = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Address2"]);
      model.CustomerInfo.ShippingAddress.City = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.City"]);

      if (model.CustomerInfo.ShippingAddress.Country is IEntity)
      {
        ((IEntity)model.CustomerInfo.ShippingAddress.Country).Alias = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Country.Alias"]);
      }

      model.CustomerInfo.ShippingAddress.Country.Code = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Country.Code"]);
      model.CustomerInfo.ShippingAddress.Country.Name = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Country.Name"]);
      model.CustomerInfo.ShippingAddress.Country.Title = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Country.Title"]);

      if (model.CustomerInfo.ShippingAddress.Country.VatRegion is IEntity)
      {
        ((IEntity)model.CustomerInfo.ShippingAddress.Country.VatRegion).Alias = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Country.VatRegion.Alias"]);
      }

      model.CustomerInfo.ShippingAddress.Country.VatRegion.Code = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Country.VatRegion.Code"]);
      model.CustomerInfo.ShippingAddress.Country.VatRegion.Name = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Country.VatRegion.Name"]);
      model.CustomerInfo.ShippingAddress.Country.VatRegion.Title = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Country.VatRegion.Title"]);
      model.CustomerInfo.ShippingAddress.Name = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Name"]);
      model.CustomerInfo.ShippingAddress.Name2 = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Name2"]);
      model.CustomerInfo.ShippingAddress.State = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.State"]);
      model.CustomerInfo.ShippingAddress.Zip = this.ConvertDataRowValue<string>(row["CustomerInfo.ShippingAddress.Zip"]);

      if (model.NotificationOption is IEntity)
      {
        ((IEntity)model.NotificationOption).Alias = this.ConvertDataRowValue<string>(row["NotificationOption.Alias"]);
      }

      model.NotificationOption.Code = this.ConvertDataRowValue<string>(row["NotificationOption.Code"]);
      model.NotificationOption.Name = this.ConvertDataRowValue<string>(row["NotificationOption.Name"]);
      model.NotificationOption.Title = this.ConvertDataRowValue<string>(row["NotificationOption.Title"]);
      model.NotificationOptionValue = this.ConvertDataRowValue<string>(row["NotificationOptionValue"]);
      model.OrderNumber = this.ConvertDataRowValue<string>(row["OrderNumber"]);

      if (model.PaymentSystem is IEntity)
      {
        ((IEntity)model.PaymentSystem).Alias = this.ConvertDataRowValue<string>(row["PaymentSystem.Alias"]);
      }

      model.PaymentSystem.Code = this.ConvertDataRowValue<string>(row["PaymentSystem.Code"]);
      model.PaymentSystem.Description = this.ConvertDataRowValue<string>(row["PaymentSystem.Description"]);
      model.PaymentSystem.LogoUrl = this.ConvertDataRowValue<string>(row["PaymentSystem.LogoUrl"]);
      model.PaymentSystem.Password = this.ConvertDataRowValue<string>(row["PaymentSystem.Password"]);
      model.PaymentSystem.PaymentSecondaryUrl = this.ConvertDataRowValue<string>(row["PaymentSystem.PaymentSecondaryUrl"]);
      model.PaymentSystem.PaymentSettings = this.ConvertDataRowValue<string>(row["PaymentSystem.PaymentSettings"]);
      model.PaymentSystem.PaymentUrl = this.ConvertDataRowValue<string>(row["PaymentSystem.PaymentUrl"]);
      model.PaymentSystem.Title = this.ConvertDataRowValue<string>(row["PaymentSystem.Title"]);
      model.PaymentSystem.Username = this.ConvertDataRowValue<string>(row["PaymentSystem.Username"]);
      model.ShippingPrice = this.ConvertDataRowValue<decimal>(row["ShippingPrice"]);

      if (model.ShippingProvider is IEntity)
      {
        ((IEntity)model.ShippingProvider).Alias = this.ConvertDataRowValue<string>(row["ShippingProvider.Alias"]);
      }

      model.ShippingProvider.AvailableNotificationOptions = this.ConvertDataRowValue<string>(row["ShippingProvider.AvailableNotificationOptions"]);
      model.ShippingProvider.Code = this.ConvertDataRowValue<string>(row["ShippingProvider.Code"]);
      model.ShippingProvider.Description = this.ConvertDataRowValue<string>(row["ShippingProvider.Description"]);
      model.ShippingProvider.IconUrl = this.ConvertDataRowValue<string>(row["ShippingProvider.IconUrl"]);
      model.ShippingProvider.Name = this.ConvertDataRowValue<string>(row["ShippingProvider.Name"]);
      model.ShippingProvider.Price = this.ConvertDataRowValue<decimal>(row["ShippingProvider.Price"]);
      model.ShippingProvider.Title = this.ConvertDataRowValue<string>(row["ShippingProvider.Title"]);

      foreach (ShoppingCartLine shoppingCartLine in ShoppingCartLineConvertor.DTOToDomainModel((DataTable)row["ShoppingCartLines"]))
      {
        model.ShoppingCartLines.Add(shoppingCartLine);
      }
    }

    /// <summary>
    /// Creates an instance of ShoppingCart
    /// </summary>
    /// <returns>
    /// New ShoppingCar instance
    /// </returns>
    public override ShoppingCart GetInstance()
    {
      return Context.Entity.Resolve<ShoppingCart>();
    }
  }
}


text:
package com.rokpetek.breadcrumbtoolbar;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.graphics.drawable.DrawerArrowDrawable;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;

import java.util.ArrayList;
import java.util.Stack;

public class BreadcrumbToolbar extends android.support.v7.widget.Toolbar implements BreadcrumbScrollView.BreadcrumbItemCallback {

    private static final String TAG = BreadcrumbToolbar.class.getSimpleName();

    // Gui
    private BreadcrumbScrollView breadcrumbScrollView;

    // Listeners
    private BreadcrumbToolbarListener breadcrumbToolbarListener;

    // Data
    private Stack<BreadcrumbToolbarItem> toolbarItemStack = new Stack<>();
    private String toolbarTitle;

    // Meta
    public static final String SAVE_INSTANCE_STATE_TAG = "save_instance_state_tag";
    public static final String SAVE_TOOLBAR_STACK_TAG = "save_toolbar_stack_tag";
    public static final String PROGRESS_ANIM_TAG = "progress";
    public static final int ICON_ANIM_DURATION = 300;

    public interface BreadcrumbToolbarListener {
        void onBreadcrumbToolbarItemPop(int stackSize);

        void onBreadcrumbToolbarEmpty();

        String getFragmentName();
    }

    public BreadcrumbToolbar(Context context) {
        super(context);
        init();
    }

    public BreadcrumbToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BreadcrumbToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setSaveEnabled(true);
    }

    public void initToolbar(BreadcrumbToolbarItem object) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        breadcrumbScrollView = (BreadcrumbScrollView) inflater.inflate(R.layout.breadcrumb_scroll_view, null);
        breadcrumbScrollView.setBreadcrumbItemCallback(this);
        addView(breadcrumbScrollView);

        // Breadcrumb scroll view is now initialized and needs its first root element
        addItem(object);

        // Animate toolbar toggle icon if exists, set navigation back icon otherwise.
        if (getNavigationIcon() instanceof DrawerArrowDrawable) {
            animateNavigationIcon(((DrawerArrowDrawable) getNavigationIcon()), true);
        } else {
            initNavigationListener(true);
        }

        // Primary title needs to be saved
        if (getTitle() != null) {
            toolbarTitle = getTitle().toString();
        }

        // Clear toolbar title on breadcrumb before adding breadcrumbs
        setTitle("");

    }

    private void initNavigationListener(boolean withIcon) {
        if (withIcon) {
            setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        }
        setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (breadcrumbToolbarListener != null) {
                    breadcrumbToolbarListener.onBreadcrumbToolbarItemPop(toolbarItemStack.size());
                }
            }
        });
    }

    private void animateNavigationIcon(DrawerArrowDrawable arrowDrawable, final boolean showArrow) {
        if (showArrow) {
            // Set a back click listener on toolbar icon when showing an arrow
            initNavigationListener(false);
        }
        ObjectAnimator animator = ObjectAnimator.ofFloat(arrowDrawable, PROGRESS_ANIM_TAG, showArrow ? 1 : 0).setDuration(ICON_ANIM_DURATION);
        animator.start();
        animator.addListener(new AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                // Animating end from navigation icon to hamburger icon
                if (breadcrumbToolbarListener != null && !showArrow) {
                    breadcrumbToolbarListener.onBreadcrumbToolbarEmpty();
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {
            }

            @Override
            public void onAnimationRepeat(Animator animator) {
            }
        });
    }

    public void addItem(@NonNull BreadcrumbToolbarItem object) {
        if (breadcrumbScrollView != null) {
            toolbarItemStack.add(object);
            breadcrumbScrollView.addItem(object.getName(), toolbarItemStack.size());
        } else {
            initToolbar(object);
        }
    }

    public void removeItem() {
        toolbarItemStack.pop();
        if (breadcrumbScrollView != null && breadcrumbToolbarListener != null) {
            if (toolbarItemStack.size() > 0) {
                breadcrumbScrollView.popBreadcrumbItem(toolbarItemStack.size());
            } else {
                cleanToolbar();
            }
        }
    }

    public void cleanToolbar() {
        if (breadcrumbScrollView != null) {
            toolbarItemStack.removeAllElements();

            if (getNavigationIcon() instanceof DrawerArrowDrawable) {
                // Animate navigation icon
                animateNavigationIcon(((DrawerArrowDrawable) getNavigationIcon()), false);
            } else {
                // Navigation icon must be removed if none existed
                setNavigationIcon(null);
            }

            // Remove scroll view
            removeView(breadcrumbScrollView);
            breadcrumbScrollView = null;

            // Reset the toolbar title
            setTitle(toolbarTitle);
        }
    }

    @Override
    public void onItemClick(int position) {
        if (breadcrumbScrollView != null && breadcrumbToolbarListener != null) {
            for (int i = toolbarItemStack.size(); i > position; i--) {
                // We must call pop on views after removing the top item from stack
                breadcrumbToolbarListener.onBreadcrumbToolbarItemPop(i - 1);
            }
        }
    }

    public void onBreadcrumbAction(int toolbarStackSize) {
        if (breadcrumbToolbarListener != null) {
            if (toolbarStackSize > toolbarItemStack.size()) {
                String itemName = breadcrumbToolbarListener.getFragmentName();
                addItem(new BreadcrumbToolbarItem(itemName));
            } else {
                removeItem();
            }
        }
    }

    public void setBreadcrumbToolbarListener(BreadcrumbToolbarListener listener) {
        this.breadcrumbToolbarListener = listener;
    }

    private void setRestoredStack(Stack<BreadcrumbToolbarItem> stack) {
        for (BreadcrumbToolbarItem item : stack) {
            addItem(item);
        }
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(SAVE_INSTANCE_STATE_TAG, super.onSaveInstanceState());
        bundle.putSerializable(SAVE_TOOLBAR_STACK_TAG, toolbarItemStack);
        return bundle;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            Object o = bundle.getSerializable(SAVE_TOOLBAR_STACK_TAG);

            // Stack gets de-serialized as an ArrayList - known bug !!!
            // Stack does not implement Serializable but rather just extends the Serializable Vector
            // which is equivalent to ArrayList
            Stack itemStack = new Stack();
            if (o instanceof Stack) {
                itemStack = (Stack) o;
            } else if (o instanceof ArrayList) {
                itemStack.addAll((ArrayList) o);
            }
            // Restore toolbar items
            setRestoredStack(itemStack);
            state = bundle.getParcelable(SAVE_INSTANCE_STATE_TAG);
        }
        super.onRestoreInstanceState(state);
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
        super.dispatchFreezeSelfOnly(container);
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
        super.dispatchThawSelfOnly(container);
    }
}


text:
package com.evolveum.midpoint.web.component.data;

import org.apache.wicket.extensions.markup.html.repeater.data.sort.ISortStateLocator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.HeadersToolbar;
import org.apache.wicket.markup.html.WebMarkupContainer;

/**
 * @author lazyman
 */
public class TableHeadersToolbar<T> extends HeadersToolbar {

    public TableHeadersToolbar(DataTable<T, String> table, ISortStateLocator stateLocator) {
        super(table, stateLocator);
    }

    @Override
    protected WebMarkupContainer newSortableHeader(String headerId, Object property, ISortStateLocator locator) {
        return new BasicOrderByBorder(headerId, property, locator) {

            @Override
            protected void onSortChanged() {
                getTable().setCurrentPage(0);
            }
        };
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>ComboBoxItemIcon</title>

ComboBoxItemIcon

	open
	/run/com.vaadin.tests.components.combobox.ComboBoxItemIcon?restartApplication

	waitForVaadin

	click
	vaadin=runcomvaadintestscomponentscomboboxComboBoxItemIcon::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[0]/VFilterSelect[0]/domChild[1]

	waitForVaadin

	screenCapture

	first-combobox-open

	click
	//div[@id='VAADIN_COMBOBOX_OPTIONLIST']/div/div[2]/table/tbody/tr[2]/td

	waitForVaadin

	screenCapture

	fi-hu-selected

	mouseClick
	vaadin=runcomvaadintestscomponentscomboboxComboBoxItemIcon::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[1]/VFilterSelect[0]/domChild[2]
	12,17

	screenCapture

	second-combobox-open

	mouseClick
	vaadin=runcomvaadintestscomponentscomboboxComboBoxItemIcon::Root/VFilterSelect$SuggestionPopup[0]/VFilterSelect$SuggestionMenu[0]#item2
	32,10

	screenCapture

	fi-au-selected


text:
import io

import xlsxwriter
from django.conf import settings
from django.http import HttpResponse

from democracy.models import SectionComment

from .section_comment import SectionCommentSerializer

class HearingReport(object):

    def __init__(self, json):
        self.json = json
        self.buffer = io.BytesIO()
        self.xlsdoc = xlsxwriter.Workbook(self.buffer, {'in_memory': True})
        self.hearing_worksheet = self.xlsdoc.add_worksheet('Hearing')
        self.hearing_worksheet.set_landscape()
        self.hearing_worksheet_active_row = 0
        self.comments_worksheet = self.xlsdoc.add_worksheet('Comments')
        self.comments_worksheet.set_landscape()
        self.comments_worksheet_active_row = 0
        self.format_bold = self.xlsdoc.add_format({'bold': True})

    def add_hearing_row(self, label, content):
        row = self.hearing_worksheet_active_row
        self.hearing_worksheet.write(row, 0, label, self.format_bold)
        self.hearing_worksheet.write(row, 1, content)
        self.hearing_worksheet_active_row += 1

    def _get_default_translation(self, field):
        lang = settings.LANGUAGE_CODE
        if field.get(lang):
            return field.get(lang)
        for lang, value in field.items():
            if value:
                return value

    def generate_hearing_worksheet(self):
        self.hearing_worksheet.set_column('A:A', 20)
        self.hearing_worksheet.set_column('B:B', 200)

        # add header to hearing worksheet
        self.hearing_worksheet.set_header(self._get_default_translation(self.json['title']))

        for lang, title in self.json['title'].items():
            self.add_hearing_row('Title (%s)' % lang, title)
        self.add_hearing_row('Created', self.json['created_at'])
        self.add_hearing_row('Close', self.json['close_at'])
        # self.add_hearing_row('Author', self.json['created_by'])
        for lang, abstract in self.json['abstract'].items():
            self.add_hearing_row('Abstract (%s)' % lang, abstract)
        for lang, borough in self.json['borough'].items():
            self.add_hearing_row('Borough (%s)' % lang, borough)
        self.add_hearing_row('Labels', str('%s' % ', '.join(self._get_default_translation(label) for label in
                                                            self.json['labels'])))
        self.add_hearing_row('Comments', str(self.json['n_comments']))
        self.add_hearing_row('Sections', str(len(self.json['sections'])))

    def add_comment_row(self, commented_type, title, comment):
        row = self.comments_worksheet_active_row
        # add title
        self.comments_worksheet.write(row, 0, title)
        # add type
        self.comments_worksheet.write(row, 1, commented_type)
        # add author
        self.comments_worksheet.write(row, 2, comment['author_name'])
        # add creation date
        self.comments_worksheet.write(row, 3, comment['created_at'])
        # add votes
        self.comments_worksheet.write(row, 4, comment['n_votes'])
        # add content
        self.comments_worksheet.write(row, 5, comment['content'])
        self.comments_worksheet_active_row += 1

    def generate_comments_worksheet(self):
        self.comments_worksheet.set_column('A:A', 30)
        self.comments_worksheet.set_column('C:C', 20)
        self.comments_worksheet.set_column('D:D', 25)
        self.comments_worksheet.set_column('E:E', 5)
        self.comments_worksheet.set_column('F:F', 200)

        self.comments_worksheet.set_header('Comments of %s' % self.json['title'])

        self.comments_worksheet.write(0, 0, 'Title', self.format_bold)
        self.comments_worksheet.write(0, 1, 'Type', self.format_bold)
        self.comments_worksheet.write(0, 2, 'Author', self.format_bold)
        self.comments_worksheet.write(0, 3, 'Created', self.format_bold)
        self.comments_worksheet.write(0, 4, 'Votes', self.format_bold)
        self.comments_worksheet.write(0, 5, 'Content', self.format_bold)

        self.comments_worksheet_active_row = 1

        comments_count = 0

        sections = [s for s in self.json['sections']]
        for s in sections:
            comments = [SectionCommentSerializer(c).data for c in SectionComment.objects.filter(section=s['id'])]
            for comment in comments:
                self.add_comment_row('Section', self._get_default_translation(s['title']), comment)
                comments_count += 1

        self.add_hearing_row('All comments', str(comments_count))

    def get_xlsx(self):
        self.generate_hearing_worksheet()
        self.generate_comments_worksheet()
        self.xlsdoc.close()

        return self.buffer.getvalue()

    def get_response(self):
        response = HttpResponse(
            self.get_xlsx(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = 'attachment; filename={filename}.xlsx'.format(filename=self.json['title'])
        return response


text:
package converters;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import repositories.RatingRepository;
import domain.Rating;

@Component
@Transactional
public class StringToRatingConverter implements Converter<String, Rating> {

	@Autowired
	RatingRepository ratingRepository;

	@Override
	public Rating convert(String text) {
		Rating result;
		int id;

		try {
			if (StringUtils.isEmpty(text))
				result = null;
			else {
				id = Integer.valueOf(text);
				result = ratingRepository.findOne(id);
			}
		} catch (Throwable oops) {
			throw new IllegalArgumentException(oops);
		}

		return result;
	}

}


text:
<?php

use Illuminate\Database\Seeder;

class CustomEarringBeadOptionsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $beads = [
	    	'some',
			'none',
		];

    	foreach ($beads as $bead) {
    		DB::insert('insert into custom_earring_bead_options (beads) values (?)', [$bead]);
    	}

    }
}


text:
import {isEqual} from 'lodash'
import locationStore from 'part:@sanity/base/location'
import {Observable, of} from 'rxjs'
import {
  map,
  filter,
  scan,
  publishReplay,
  refCount,
  tap,
  catchError,
  distinctUntilChanged,
} from 'rxjs/operators'
import rootRouter from '../router'
import getOrderedTools from '../util/getOrderedTools'
import reconfigureClient from '../util/reconfigureClient'
import {HAS_SPACES, CONFIGURED_SPACES} from '../util/spaces'

interface SnapshotStateEvent {
  type: 'snapshot'
  intent: {
    name: string
    params: {[key: string]: string}
  }
  isNotFound: boolean
  state: Record<string, unknown>
}

interface StateChangeEvent {
  type: 'change'
  state: Record<string, unknown>
  isNotFound: boolean
}

interface ErrorStateEvent {
  type: 'error'
  error: Error
}

type StateEvent = SnapshotStateEvent | ErrorStateEvent | StateChangeEvent

function resolveUrlStateWithDefaultSpace(state) {
  if (!HAS_SPACES || !state || state.space) {
    return state
  }
  const defaultSpace = CONFIGURED_SPACES.find((ds) => ds.default) || CONFIGURED_SPACES[0]
  return Object.assign({}, state, {space: defaultSpace.name})
}

function resolveUrlStateWithDefaultTool(state) {
  const defaultTool = getOrderedTools()[0]
  if (!state || state.tool || !defaultTool) {
    return state
  }

  return Object.assign({}, state, {
    tool: defaultTool.name,
  })
}

function makeBackwardsCompatible(state) {
  if (!state) {
    return state
  }
  if (getOrderedTools().find((tool) => tool.name === state.space)) {
    return Object.assign({}, state, {tool: state.space, space: undefined})
  }
  return state
}

function resolveDefaultState(state) {
  const urlStateWithDefaultTool = resolveUrlStateWithDefaultTool(makeBackwardsCompatible(state))
  return HAS_SPACES
    ? resolveUrlStateWithDefaultSpace(urlStateWithDefaultTool)
    : urlStateWithDefaultTool
}

function resolveIntentState(currentState, intentState) {
  const {intent, params, payload} = intentState

  const tools = getOrderedTools()

  const currentTool = currentState.tool
    ? tools.find((tool) => tool.name === currentState.tool)
    : null

  // If current tool can handle intent and if so, give it precedence
  const matchingTool = (currentTool ? [currentTool, ...tools] : tools).find(
    (tool) =>
      tool &&
      typeof tool.canHandleIntent === 'function' &&
      tool.canHandleIntent(intent, params, currentState[tool.name])
  )

  if (matchingTool?.getIntentState) {
    const toolState = matchingTool.getIntentState(
      intent,
      params,
      currentState[matchingTool.name],
      payload
    )
    const currentWithState = resolveUrlStateWithDefaultSpace(currentState) || currentState
    return Object.assign({}, currentWithState, {
      tool: matchingTool.name,
      [matchingTool.name]: toolState,
    })
  }
  return {
    isNotFound: true,
    intent: {name: intent, params},
  }
}

function maybeHandleIntent(
  prevEvent: {type: string; state: Record<string, unknown>; isNotFound: boolean},
  currentEvent: {type: string; state: Record<string, unknown>; isNotFound: boolean}
) {
  if (currentEvent && currentEvent.state && currentEvent.state.intent) {
    const redirectState = resolveIntentState(prevEvent ? prevEvent.state : {}, currentEvent.state)

    if (redirectState) {
      const newUrl = rootRouter.encode(redirectState)
      setTimeout(() => navigate(newUrl, {replace: true}), 0)
      return null
    }
  }

  return currentEvent
}

function decodeUrlState(locationEvent: {type: string}) {
  return {
    type: locationEvent.type,
    state: rootRouter.decode(location.pathname),
    isNotFound: rootRouter.isNotFound(location.pathname),
  }
}

function maybeRedirectDefaultState(event: SnapshotStateEvent): StateEvent | null {
  const redirectState = resolveDefaultState(event.state)
  if (redirectState !== event.state) {
    navigate(rootRouter.encode(redirectState), {replace: true})
    return null
  }
  return event
}

export function navigate(newUrl: string, options: {replace: boolean}): void {
  locationStore.actions.navigate(newUrl, options)
}

export const state: Observable<StateEvent> = locationStore.state.pipe(
  map(decodeUrlState),
  scan(maybeHandleIntent, null),
  filter(Boolean),
  map(maybeRedirectDefaultState),
  filter(Boolean),
  distinctUntilChanged(isEqual),
  catchError((err) => of({type: 'error', error: err})),
  publishReplay(1),
  refCount()
)

export function isStateUpdateEvent(
  event: StateEvent
): event is SnapshotStateEvent | StateChangeEvent {
  return event.type === 'snapshot' || event.type === 'change'
}

if (HAS_SPACES) {
  // Uglybugly mutation ahead.
  state
    .pipe(
      filter(isStateUpdateEvent),
      map((event) => event.state),
      filter(Boolean),
      tap(reconfigureClient)
    )
    .subscribe()
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Res. 101(12): 1524 (1997)

#### Original name
Buxetroldia K.R.L. Petersen & Jørg. Koch

### Remarks
null


text:
@import XCTest;
@import UIKit;

#import "NSString_HTML.h"

@interface TestNSString_HTML : XCTestCase

@end

@implementation TestNSString_HTML

- (void)testStringByCleaningHTML {
	NSDictionary *htmlAndCleanedStrings = @{
											@"hi": @"hi",
											@"good > bad": @"good > bad",
											@""quote"": @"\"quote\"",
											@"clichés": @"clichés",
											@"House of Pancakes": @"House of Pancakes",
											@"bad > worse": @"bad > worse",
											@"I Accidentally <noun>": @"I Accidentally <noun>",
											@"<3": @"<3",
											@"<>": @"<>",
											@"RSS&M": @"RSS&M",
											@"(or \\;;\"\\''{\\<<[' this mouseover text": @"(or \\;;\"\\''{\\<<[' this mouseover text"
											};

	for (NSString *snippet in htmlAndCleanedStrings) {
		NSString *cleaned = htmlAndCleanedStrings[snippet];
		XCTAssertEqualObjects([NSString stringByCleaningHTML:snippet], cleaned, @"Snippet '%@' should result in clean string '%@'.", snippet, cleaned);
	}
}

@end