text:
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Collections;
using Umbraco.Core.Composing;
using Umbraco.Core.Models.Entities;

namespace Umbraco.Core.Events
{
    /// <summary>
    /// An IEventDispatcher that queues events.
    /// </summary>
    /// <remarks>
    /// <para>Can raise, or ignore, cancelable events, depending on option.</para>
    /// <para>Implementations must override ScopeExitCompleted to define what
    /// to do with the events when the scope exits and has been completed.</para>
    /// <para>If the scope exits without being completed, events are ignored.</para>
    /// </remarks>
    public abstract class QueuingEventDispatcherBase : IEventDispatcher
    {
        //events will be enlisted in the order they are raised
        private List<IEventDefinition> _events;
        private readonly bool _raiseCancelable;

        protected QueuingEventDispatcherBase(bool raiseCancelable)
        {
            _raiseCancelable = raiseCancelable;
        }

        private List<IEventDefinition> Events => _events ?? (_events = new List<IEventDefinition>());

        public bool DispatchCancelable(EventHandler eventHandler, object sender, CancellableEventArgs args, string eventName = null)
        {
            if (eventHandler == null) return args.Cancel;
            if (_raiseCancelable == false) return args.Cancel;
            eventHandler(sender, args);
            return args.Cancel;
        }

        public bool DispatchCancelable<TArgs>(EventHandler<TArgs> eventHandler, object sender, TArgs args, string eventName = null)
            where TArgs : CancellableEventArgs
        {
            if (eventHandler == null) return args.Cancel;
            if (_raiseCancelable == false) return args.Cancel;
            eventHandler(sender, args);
            return args.Cancel;
        }

        public bool DispatchCancelable<TSender, TArgs>(TypedEventHandler<TSender, TArgs> eventHandler, TSender sender, TArgs args, string eventName = null)
            where TArgs : CancellableEventArgs
        {
            if (eventHandler == null) return args.Cancel;
            if (_raiseCancelable == false) return args.Cancel;
            eventHandler(sender, args);
            return args.Cancel;
        }

        public void Dispatch(EventHandler eventHandler, object sender, EventArgs args, string eventName = null)
        {
            if (eventHandler == null) return;
            Events.Add(new EventDefinition(eventHandler, sender, args, eventName));
        }

        public void Dispatch<TArgs>(EventHandler<TArgs> eventHandler, object sender, TArgs args, string eventName = null)
        {
            if (eventHandler == null) return;
            Events.Add(new EventDefinition<TArgs>(eventHandler, sender, args, eventName));
        }

        public void Dispatch<TSender, TArgs>(TypedEventHandler<TSender, TArgs> eventHandler, TSender sender, TArgs args, string eventName = null)
        {
            if (eventHandler == null) return;
            Events.Add(new EventDefinition<TSender, TArgs>(eventHandler, sender, args, eventName));
        }

        public IEnumerable<IEventDefinition> GetEvents(EventDefinitionFilter filter)
        {
            if (_events == null)
                return Enumerable.Empty<IEventDefinition>();

            IReadOnlyList<IEventDefinition> events;
            switch (filter)
            {
                case EventDefinitionFilter.All:
                    events = _events;
                    break;
                case EventDefinitionFilter.FirstIn:
                    var l1 = new OrderedHashSet<IEventDefinition>();
                    foreach (var e in _events)
                        l1.Add(e);
                    events = l1;
                    break;
                case EventDefinitionFilter.LastIn:
                    var l2 = new OrderedHashSet<IEventDefinition>(keepOldest: false);
                    foreach (var e in _events)
                        l2.Add(e);
                    events = l2;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("filter", filter, null);
            }

            return FilterSupersededAndUpdateToLatestEntity(events);
        }

        private class EventDefinitionInfos
        {
            public IEventDefinition EventDefinition { get; set; }
            public Type[] SupersedeTypes { get; set; }
        }

        // fixme
        // this is way too convoluted, the superceede attribute is used only on DeleteEventargs to specify
        // that it superceeds save, publish, move and copy - BUT - publish event args is also used for
        // unpublishing and should NOT be superceeded - so really it should not be managed at event args
        // level but at event level
        //
        // what we want is:
        // if an entity is deleted, then all Saved, Moved, Copied, Published events prior to this should
        // not trigger for the entity - and even though, does it make any sense? making a copy of an entity
        // should ... trigger?
        //
        // not going to refactor it all - we probably want to *always* trigger event but tell people that
        // due to scopes, they should not expected eg a saved entity to still be around - however, now,
        // going to write a ugly condition to deal with U4-10764

        // iterates over the events (latest first) and filter out any events or entities in event args that are included
        // in more recent events that Supersede previous ones. For example, If an Entity has been Saved and then Deleted, we don't want
        // to raise the Saved event (well actually we just don't want to include it in the args for that saved event)
        internal static IEnumerable<IEventDefinition> FilterSupersededAndUpdateToLatestEntity(IReadOnlyList<IEventDefinition> events)
        {
            // keeps the 'latest' entity and associated event data
            var entities = new List<Tuple<IEntity, EventDefinitionInfos>>();

            // collects the event definitions
            // collects the arguments in result, that require their entities to be updated
            var result = new List<IEventDefinition>();
            var resultArgs = new List<CancellableObjectEventArgs>();

            // eagerly fetch superceeded arg types for each arg type
            var argTypeSuperceeding = events.Select(x => x.Args.GetType())
                .Distinct()
                .ToDictionary(x => x, x => x.GetCustomAttributes<SupersedeEventAttribute>(false).Select(y => y.SupersededEventArgsType).ToArray());

            // iterate over all events and filter
            //
            // process the list in reverse, because events are added in the order they are raised and we want to keep
            // the latest (most recent) entities and filter out what is not relevant anymore (too old), eg if an entity
            // is Deleted after being Saved, we want to filter out the Saved event
            for (var index = events.Count - 1; index >= 0; index--)
            {
                var def = events[index];

                var infos = new EventDefinitionInfos
                {
                    EventDefinition = def,
                    SupersedeTypes = argTypeSuperceeding[def.Args.GetType()]
                };

                var args = def.Args as CancellableObjectEventArgs;
                if (args == null)
                {
                    // not a cancellable event arg, include event definition in result
                    result.Add(def);
                }
                else
                {
                    // event object can either be a single object or an enumerable of objects
                    // try to get as an enumerable, get null if it's not
                    var eventObjects = TypeHelper.CreateGenericEnumerableFromObject(args.EventObject);
                    if (eventObjects == null)
                    {
                        // single object, cast as an IEntity
                        // if cannot cast, cannot filter, nothing - just include event definition in result
                        var eventEntity = args.EventObject as IEntity;
                        if (eventEntity == null)
                        {
                            result.Add(def);
                            continue;
                        }

                        // look for this entity in superceding event args
                        // found = must be removed (ie not added), else track
                        if (IsSuperceeded(eventEntity, infos, entities) == false)
                        {
                            // track
                            entities.Add(Tuple.Create(eventEntity, infos));

                            // track result arguments
                            // include event definition in result
                            resultArgs.Add(args);
                            result.Add(def);
                        }
                    }
                    else
                    {
                        // enumerable of objects
                        var toRemove = new List<IEntity>();
                        foreach (var eventObject in eventObjects)
                        {
                            // extract the event object, cast as an IEntity
                            // if cannot cast, cannot filter, nothing to do - just leave it in the list & continue
                            var eventEntity = eventObject as IEntity;
                            if (eventEntity == null)
                                continue;

                            // look for this entity in superceding event args
                            // found = must be removed, else track
                            if (IsSuperceeded(eventEntity, infos, entities))
                                toRemove.Add(eventEntity);
                            else
                                entities.Add(Tuple.Create(eventEntity, infos));
                        }

                        // remove superceded entities
                        foreach (var entity in toRemove)
                            eventObjects.Remove(entity);

                        // if there are still entities in the list, keep the event definition
                        if (eventObjects.Count > 0)
                        {
                            if (toRemove.Count > 0)
                            {
                                // re-assign if changed
                                args.EventObject = eventObjects;
                            }

                            // track result arguments
                            // include event definition in result
                            resultArgs.Add(args);
                            result.Add(def);
                        }
                    }
                }
            }

            // go over all args in result, and update them with the latest instanceof each entity
            UpdateToLatestEntities(entities, resultArgs);

            // reverse, since we processed the list in reverse
            result.Reverse();

            return result;
        }

        // edits event args to use the latest instance of each entity
        private static void UpdateToLatestEntities(IEnumerable<Tuple<IEntity, EventDefinitionInfos>> entities, IEnumerable<CancellableObjectEventArgs> args)
        {
            // get the latest entities
            // ordered hash set + keepOldest will keep the latest inserted entity (in case of duplicates)
            var latestEntities = new OrderedHashSet<IEntity>(keepOldest: true);
            foreach (var entity in entities.OrderByDescending(entity => entity.Item1.UpdateDate))
                latestEntities.Add(entity.Item1);

            foreach (var arg in args)
            {
                // event object can either be a single object or an enumerable of objects
                // try to get as an enumerable, get null if it's not
                var eventObjects = TypeHelper.CreateGenericEnumerableFromObject(arg.EventObject);
                if (eventObjects == null)
                {
                    // single object
                    // look for a more recent entity for that object, and replace if any
                    // works by "equalling" entities ie the more recent one "equals" this one (though different object)
                    var foundEntity = latestEntities.FirstOrDefault(x => Equals(x, arg.EventObject));
                    if (foundEntity != null)
                        arg.EventObject = foundEntity;
                }
                else
                {
                    // enumerable of objects
                    // same as above but for each object
                    var updated = false;
                    for (var i = 0; i < eventObjects.Count; i++)
                    {
                        var foundEntity = latestEntities.FirstOrDefault(x => Equals(x, eventObjects[i]));
                        if (foundEntity == null) continue;
                        eventObjects[i] = foundEntity;
                        updated = true;
                    }

                    if (updated)
                        arg.EventObject = eventObjects;
                }
            }
        }

        // determines if a given entity, appearing in a given event definition, should be filtered out,
        // considering the entities that have already been visited - an entity is filtered out if it
        // appears in another even definition, which superceedes this event definition.
        private static bool IsSuperceeded(IEntity entity, EventDefinitionInfos infos, List<Tuple<IEntity, EventDefinitionInfos>> entities)
        {
            //var argType = meta.EventArgsType;
            var argType = infos.EventDefinition.Args.GetType();

            // look for other instances of the same entity, coming from an event args that supercedes other event args,
            // ie is marked with the attribute, and is not this event args (cannot supersede itself)
            var superceeding = entities
                .Where(x => x.Item2.SupersedeTypes.Length > 0 // has the attribute
                    && x.Item2.EventDefinition.Args.GetType() != argType // is not the same
                    && Equals(x.Item1, entity)) // same entity
                .ToArray();

            // first time we see this entity = not filtered
            if (superceeding.Length == 0)
                return false;

            // fixme see notes above
            // delete event args does NOT superceedes 'unpublished' event
            if (argType.IsGenericType && argType.GetGenericTypeDefinition() == typeof(PublishEventArgs<>) && infos.EventDefinition.EventName == "Unpublished")
                return false;

            // found occurences, need to determine if this event args is superceded
            if (argType.IsGenericType)
            {
                // generic, must compare type arguments
                var supercededBy = superceeding.FirstOrDefault(x =>
                    x.Item2.SupersedeTypes.Any(y =>
                        // superceeding a generic type which has the same generic type definition
                        // fixme no matter the generic type parameters? could be different?
                        y.IsGenericTypeDefinition && y == argType.GetGenericTypeDefinition()
                        // or superceeding a non-generic type which is ... fixme how is this ever possible? argType *is* generic?
                        || y.IsGenericTypeDefinition == false && y == argType));
                return supercededBy != null;
            }
            else
            {
                // non-generic, can compare types 1:1
                var supercededBy = superceeding.FirstOrDefault(x =>
                    x.Item2.SupersedeTypes.Any(y => y == argType));
                return supercededBy != null;
            }
        }

        public void ScopeExit(bool completed)
        {
            if (_events == null) return;
            if (completed)
                ScopeExitCompleted();
            _events.Clear();
        }

        protected abstract void ScopeExitCompleted();
    }
}

redpajama_set_name: RedPajamaGithub


text:
GameWindow::GameWindow(QWidget *parent)
    : QMainWindow(parent)
{
}

GameWindow::~GameWindow()
{

}


text:
package com.xiongyingqi.email.service.impl;

import com.xiongyingqi.email.JavaMailSenderFactory;
import com.xiongyingqi.email.service.IEmailService;
import com.xiongyingqi.email.vo.AttachmentVo;
import com.xiongyingqi.email.vo.EmailAccount;
import com.xiongyingqi.email.vo.EmailVo;
import com.xiongyingqi.email.vo.InlineImageVo;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 瑛琪xiongyingqi.com on 2014/4/25 0025.
 */
@Service
public class EmailService implements IEmailService {
    private JavaMailSenderFactory javaMailSenderFactory;

    private EmailAccount emailAccount;

//    /**
//     * 系统邮件帐号
//     */
//    @Value("${email.systemEmail}")
//    private String systemEmail;
//    /**
//     * 邮件默认抄送人
//     */
//    @Value("${email.cc}")
//    private String defaultCc;
//    /**
//     * 邮件默认密送人
//     */
//    @Value("${email.bcc}")
//    private String defaultBcc;

    /**
     * 查找html内img的内容
     */
    public static final Pattern PATTERN_FIND_TAG_AND_INDEX = Pattern.compile("<\\w+\\s+\\w+\\s*=\\s*(\\'\\s*\\$\\s*\\{\\s*\\d+\\s*\\}\\s*\\'\\s*|\\\"\\s*\\$\\s*\\{\\s*\\w+\\s*\\}\\s*\\\"\\s*){1}?\\s*/{0,1}>");
    /**
     * 查找${0}的类似内容
     */
    public static final Pattern PATTERN_DOLLAR_VARIABLE_INDEX = Pattern.compile("\\s*\\$\\{\\s*\\d+\\s*\\}\\s*");

    /**
     * 查找html内img的内容
     */
    public static final Pattern PATTERN_FIND_TAG = Pattern.compile("<\\w+\\s+src\\s*=\\s*(\\'\\s*\\$\\{\\s*\\w+\\s*\\}\\s*\\'\\s*|\\\"\\s*\\$*\\{\\s*\\w+\\s*\\}\\s*\\\"\\s*){1}?\\s*/{0,1}>");
    /**
     * 查找${a}的类似内容
     */
    public static final Pattern PATTERN_DOLLAR_VARIABLE_SELF_DEFINE = Pattern.compile("\\s*\\$\\{\\s*\\w+\\s*\\}\\s*");

    public EmailService(EmailAccount emailAccount) {
        this.javaMailSenderFactory = JavaMailSenderFactory.buildNewJavaMailSender(emailAccount);
    }

    public EmailService() {
    }

    public EmailAccount getEmailAccount() {
        return emailAccount;
    }

    public void setEmailAccount(EmailAccount emailAccount) {
        this.emailAccount = emailAccount;
        this.javaMailSenderFactory = JavaMailSenderFactory.buildNewJavaMailSender(emailAccount);
    }

    /**
     * 发送邮件
     *
     * @param emailVo
     */
    @Override
    public void sendEmail(EmailVo emailVo) throws MessagingException {
        Assert.notNull(emailVo.getTo(), "接收人不能为空");

        MimeMessage msg = javaMailSenderFactory.createMimeMessage();

        MimeMessageHelper msgHelper = null;
        if ((emailVo.getInlineImageVos() != null && emailVo.getInlineImageVos().size() > 0) || (emailVo.getAttachmentVos() != null && emailVo.getAttachmentVos().size() > 0)) {
            msgHelper = new MimeMessageHelper(msg, true, "utf-8");
        } else {
            msgHelper = new MimeMessageHelper(msg, "utf-8");
        }

        if (emailVo.getFrom() == null || "".equals(emailVo.getFrom().trim())) {
            emailVo.setFrom(javaMailSenderFactory.getSystemEmail());
        }
        if ((emailVo.getCc() == null || "".equals(emailVo.getCc().length == 0)) && javaMailSenderFactory.getDefaultCc() != null && !javaMailSenderFactory.getDefaultCc().equals("")) {
            emailVo.setCc(javaMailSenderFactory.getDefaultCc().split(","));
        }
        if ((emailVo.getBcc() == null || "".equals(emailVo.getBcc().length == 0)) && javaMailSenderFactory.getDefaultBcc() != null && !javaMailSenderFactory.getDefaultBcc().equals("")) {
            emailVo.setBcc(javaMailSenderFactory.getDefaultBcc().split(","));
        }

        if (emailVo.getMessageDate() == null) {
            emailVo.setMessageDate(new Date());
        }
        if (emailVo.getCc() != null) {
            msgHelper.setCc(emailVo.getCc());// 抄送
        }
        if (emailVo.getBcc() != null) {
            msgHelper.setBcc(emailVo.getBcc());// 密送
        }
        if (emailVo.getSubject() != null) {
            msgHelper.setSubject(emailVo.getSubject());
        }

        handlerAttachments(emailVo, msgHelper);

        String from = null;
        if (emailVo.getFrom() != null && !"".equals(emailVo.getFrom())) {
            from = emailVo.getFrom();
        } else {
            if (javaMailSenderFactory.getEmailAccount().getFrom() != null && !"".equals(javaMailSenderFactory.getEmailAccount().getFrom())) {
                from = javaMailSenderFactory.getEmailAccount().getFrom();
            } else {
                from = javaMailSenderFactory.getEmailAccount().getUsername();
            }
        }

        try {
            if (javaMailSenderFactory.getEmailAccount().getNickName() != null) {
                msgHelper.setFrom(from, javaMailSenderFactory.getEmailAccount().getNickName());
            } else {
                msgHelper.setFrom(from);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            msgHelper.setFrom(from);
        }

        msgHelper.setTo(emailVo.getTo());// 接收人
        Collection<Inline> inlines = handlerInlineImages(emailVo, msgHelper);

        if (emailVo.getHtml() != null) {
            msgHelper.setText(emailVo.getHtml(), emailVo.isHtml());

            if (inlines != null) {// 添加inline
                for (Inline inline : inlines) {
                    msgHelper.addInline(inline.getContentId(), inline.getFile());
                }
            }
        }
        javaMailSenderFactory.send(msg);
    }

    /**
     * 处理内嵌对象
     *
     * @param emailVo
     * @param msgHelper
     * @throws javax.mail.MessagingException
     */
    private Collection<Inline> handlerInlineImages(EmailVo emailVo, MimeMessageHelper msgHelper) throws MessagingException {
        Collection<Inline> inlines = null;
        if (emailVo.getInlineImageVos() != null && emailVo.getInlineImageVos().size() > 0) {
            inlines = new HashSet<Inline>();
            String html = emailVo.getHtml();
            if (html == null || html.trim().equals("")) {// 如果内容空或者不是 html则直接跳过
                return inlines;
            }

            //  ------------------------------------------- 查找带数字的标记 ${数字} -------------------------------------------
            Matcher matcherIndexTag = PATTERN_FIND_TAG_AND_INDEX.matcher(html);

            int contentIdIndex = 0;
            while (matcherIndexTag.find()) {

                String htmlTag = matcherIndexTag.group(); // 查找到 的内容
                Matcher matcherDollar = PATTERN_DOLLAR_VARIABLE_INDEX.matcher(htmlTag);
                if (matcherDollar.find()) {

                    String dollarFind = matcherDollar.group();// 查找到${1}内容
                    String indexStr = dollarFind.replace("$", "").replace("{", "").replace("}", "").trim();// 移除外面的$符号和大括号
                    int index = Integer.parseInt(indexStr);
                    try {
                        InlineImageVo inlineImageVo = emailVo.getInlineImageVos().get(index);
                        File file = inlineImageVo.getFile();

                        String contentId = "file" + contentIdIndex++; // 生成contentId
//                        msgHelper.addInline(contentId, file);// 将附件内容传送给MimeMessageHelper

                        Inline inline = new Inline();
                        inline.setFile(file);
                        inline.setContentId(contentId);

                        inlines.add(inline);

                        htmlTag = matcherDollar.replaceAll("cid:" + contentId);
//                        System.out.println("indexStr ====== " + indexStr);
//                        System.out.println("htmlTag ====== " + htmlTag);

                        html = matcherIndexTag.replaceFirst(htmlTag);
                        matcherIndexTag = PATTERN_FIND_TAG_AND_INDEX.matcher(html);

//                        System.out.println("html ====== " + html);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            //  ------------------------------------------- 查找带字母变量的标记 ${variable} -------------------------------------------
            Matcher matcherTag = PATTERN_FIND_TAG.matcher(html);
            while (matcherTag.find()) {
                String htmlTag = matcherTag.group(); // 查找到 的内容
                Matcher matcherDollar = PATTERN_DOLLAR_VARIABLE_SELF_DEFINE.matcher(htmlTag);
                if (matcherDollar.find()) {
                    String dollarFind = matcherDollar.group();// 查找到${1}内容
                    String dollarVariable = dollarFind.replace("$", "").replace("{", "").replace("}", "").trim();// 移除外面的$符号和大括号
                    try {
                        InlineImageVo inlineImageVo = null;
                        for (InlineImageVo imageVo : emailVo.getInlineImageVos()) {
                            if (imageVo.getContentId() != null && imageVo.getContentId().equals(dollarVariable)) {
                                inlineImageVo = imageVo;
                            }
                        }

                        if (inlineImageVo == null) {
                            continue;
                        }
                        File file = inlineImageVo.getFile();

//                        String contentId = "file" + contentIdIndex++; // 生成contentId
//                        msgHelper.addInline(contentId, file);// 将附件内容传送给MimeMessageHelper

                        Inline inline = new Inline();
                        inline.setFile(file);
                        inline.setContentId(inlineImageVo.getContentId());

                        inlines.add(inline);

                        htmlTag = matcherDollar.replaceAll("cid:" + inlineImageVo.getContentId());
//                        System.out.println("htmlTag ====== " + htmlTag);

                        html = matcherTag.replaceFirst(htmlTag);
                        matcherTag = PATTERN_FIND_TAG.matcher(html);

//                        System.out.println("html ====== " + html);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            emailVo.setHtml(html);

            if (inlines != null && inlines.size() > 0) {
                emailVo.setHtml(true);
            }
        }
        return inlines;
    }

    /**
     * 处理附件
     *
     * @param emailVo
     * @param msgHelper
     * @throws javax.mail.MessagingException
     */
    private void handlerAttachments(EmailVo emailVo, MimeMessageHelper msgHelper) throws MessagingException {
        if (emailVo.getAttachmentVos() != null) {// 检查附件
            for (AttachmentVo attachmentVo : emailVo.getAttachmentVos()) {
                File attachment = attachmentVo.getAttachment();

                if (attachment == null) {
                    InputStream inputStream = attachmentVo.getAttachmentInputStream();

                    if (attachmentVo.getAttachmentName() == null) {
                        attachmentVo.setAttachmentName(new Date().toString());
                    }
                    InputStreamSource inputStreamSource = new InputStreamResource(inputStream);
                    msgHelper.addAttachment(attachmentVo.getAttachmentName(), inputStreamSource);
                } else {
                    if (attachmentVo.getAttachmentName() == null) {
                        attachmentVo.setAttachmentName(attachment.getName());
                    }

                    try {
                        msgHelper.addAttachment(MimeUtility.encodeWord(attachmentVo.getAttachmentName()), attachment);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    class Inline {
        private String contentId;
        private File file;

        public String getContentId() {
            return contentId;
        }

        public void setContentId(String contentId) {
            this.contentId = contentId;
        }

        public File getFile() {
            return file;
        }

        public void setFile(File file) {
            this.file = file;
        }
    }

}


text:
title: Metodo Spagyrico
---

*********************************************************************
Metodo Spagyrico: Come estrarre in casa rimedi naturali dalle piante
*********************************************************************

.. image:: https://images.gr-assets.com/books/1544020708l/43152301.jpg

Molto di più che un metodo. Le parole di questo libro, scritte dall'Amico e
compagno di Viaggio `Stefano Valbonesi <https://www.facebook.com/stefano.valbonesi.1>`_, riecheggiano all' *interno*, pagina dopo
pagina. Un vero e proprio viaggio scritto col cuore, da un' Anima che ha fatto
diretta esperienza di ciò di cui egregiamente e direi poeticamente tratta.

Penso di aver letto pochi testi cosi puri. Nella semplicità di linguaggio e
nelle poche pagine, racchiudono una sostanza meravigliosa e viva. Pur
ritenendomi di parte nel giudicare questa Via di trasmutazione dell' Essere (
*amata Alchimia...*), ritengo che ogni "viandante" dal più giovane al più anziano
possa deliziare la sua esperienza con la lettura di questa testimonianza.

A chi fosse interessato al percorso Spagyrico, senza alcun dubbio ed esitazione
direi che ha trovato un testo cardine. Completo di filosofia, di pratica e di un
erbario mette a disposizione le basi per praticare quest' Arte interiormente ed
esteriormente.

Non voglio dilungarmi troppo per mantenermi coerente col libro e per poter
assaporare ancora meglio quelle ricche sensazioni che mi ha lasciato questa
lettura.

Grazie Stefano.

♡🜕


text:
/*
 * Misc database library functions
 */

/*
 * Execute an SQL statement. This can be both DML (queries) or DDL (create/alter)
 * @param {String} statement : The statement to run
 * @param {Boolean} throwException : If true, throw exception on error. Default:false
 * @returns {array} rows:The rows, if any returned by the query
 */
Devwik.SQL.execStatement = function(statement, transaction) {
	var future = new Future();
	if(transaction) {
		console.log('tranaction');
		if(transaction.cancelled) {
			console.log('tranaction cancelled');
			//not doing anything in this transaction
			return([]);
		}
	}
	query = Devwik.SQL.connection.query(statement, function(err, result) {
		if (err) {
			if(transaction) {
				transaction.cancelled = true;
			}
			console.log(err);
			console.log(err.stack);
		}
		future.ret(result);
	});
	return(future.wait());
};

/*
 * Escape an SQL statement to try and catch SQL injections
 */
Devwik.SQL.escape = function(statement) {
	statement = statement.toString();//For consistency let's convert to string
	statement = Devwik.SQL.connection.escape(statement).toString();
	statement = statement.substring(1, statement.length-1);
	return(statement);
};

/*
 * Wrap a function in an SQL Transaction
 * @param {Function} func: the function that performs the SQL operations
 * @param {Function} errFunc: optional function to call on error
 *
 */

Devwik.SQL.Transaction = function(){
	var connection = Devwik.SQL.connection;
	if(!connection) {
		console.log ("No database connection");
		return null;
	}
	connection.query('START TRANSACTION');
	return(this);
};

Devwik.SQL.Transaction.prototype.end = function() {
	var self = this;
	var connection = Devwik.SQL.connection;
	if(self.cancelled) {
	console.log('rollback');
	connection.query('ROLLBACK');
	} else {
	console.log('commit');
	connection.query('COMMIT');
	}
};

Devwik.SQL.Transaction.prototype.commit = function() {
	Devwik.SQL.connection.query('COMMIT');
};

Devwik.SQL.Transaction.prototype.rollback = function() {
	Devwik.SQL.connection.query('ROLLBACK');
};


text:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;

namespace System {
  // Summary:
  //     Represents the method that handles the System.AppDomain.AssemblyLoad event
  //     of an System.AppDomain.
  //
  // Parameters:
  //   sender:
  //     The source of the event.
  //
  //   args:
  //     An System.AssemblyLoadEventArgs that contains the event data.
  [Serializable]
  [ComVisible(true)]
  public delegate void AssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Palaeontographica, Abt. B 133(1-3): 37 + pl. 13, fig. 1; pl. 15, fig. 1 (1971)

#### Original name
Inapertisporites vulgaris Sheffy & Dilcher

### Remarks
null


text:
// Class libraries
#include "Encoder.h"

/**
 * @brief	Encoder constructor.
 */
Encoder::Encoder(QWidget *parent) :
    QDialog(parent), ui(new Ui::Encoder) {
    ui->setupUi(this);
    this->fs = 44100;
    this->input = NULL;
    this->output = NULL;
    this->bitstream = NULL;
    this->setInput("");
    this->reset();
    // Signals
    QObject::connect(ui->bitstream_filename, SIGNAL(textEdited(QString)), this,
                     SLOT(setBitstream()));
    QObject::connect(ui->bitstream_buried,SIGNAL(toggled(bool)),this,SLOT(setBuried(bool)));
    QObject::connect(ui->tree_5151, SIGNAL(released()), this,
                     SLOT(toggleTree()));
    QObject::connect(ui->tree_5152, SIGNAL(released()), this,
                     SLOT(toggleTree()));
    QObject::connect(ui->tree_525, SIGNAL(released()), this,
                     SLOT(toggleTree()));
    QObject::connect(ui->input_controls->button(QDialogButtonBox::Open),
                     SIGNAL(released()), this, SLOT(load()));
    QObject::connect(ui->encoding_controls->button(QDialogButtonBox::Reset),
                     SIGNAL(released()), this, SLOT(reset()));
    QObject::connect(ui->encoding_controls->button(QDialogButtonBox::Apply),
                     SIGNAL(released()), this, SLOT(apply()));
    QObject::connect(ui->output_controls->button(QDialogButtonBox::Cancel),
                     SIGNAL(released()), this, SLOT(cancel()));
    QObject::connect(ui->output_controls->button(QDialogButtonBox::Ok),
                     SIGNAL(released()), this, SLOT(submit()));
    consolelog("Encoder", LogType::progress, "Encoder object is created");
}

/**
 * @brief	Encoder destructor.
 *
 */
Encoder::~Encoder() {
    delete ui;
    consolelog("Encoder", LogType::progress, "Encoder object is deleted");
}

/**
 * @brief   It sets the input audio file.
 * @param   filename            file path
 */
void Encoder::setInput(std::string filename) {
    if (filename != "") {
        this->input = new WAVFile(filename, false);
    }
    bool loaded = this->input->exists();
    if (loaded && filename != "") {
        ui->input_filename->setText(QString::fromStdString(filename));
        consolelog("Encoder", LogType::progress,
                   "selected \"" + filename + "\" as input audio file");
    } else if (loaded && filename == "") {
        ui->input_filename->setText(
                    QString::fromStdString(this->input->getFilename()));
        consolelog("Encoder", LogType::interaction,
                   "input file selection was cancelled");
    } else {
        ui->input_filename->setText(
                    QString::fromStdString("please load a file"));
        consolelog("Encoder", LogType::warning, "input audio file is empty");
    }
    // File name font
    QFont font;
    font.setItalic(!loaded);
    ui->input_filename->setFont(font);
    // Buttons enabling
    ui->encoding_controls->button(QDialogButtonBox::Apply)->setEnabled(loaded);
    ui->output_controls->button(QDialogButtonBox::Ok)->setEnabled(
                loaded && this->output->exists());
}

/**
 * @brief   It sets the output audio file.
 * @param   filename            file path
 */
void Encoder::setOutput(std::string filename) {
    if (filename != "") {
        this->output = new WAVFile(filename, false);
    }
    bool loaded = this->output->exists();
    if (loaded && filename != "") {
        ui->output_filename->setText(QString::fromStdString(filename));
        consolelog("Encoder", LogType::progress,
                   "selected \"" + filename + "\" as output audio file");
    } else if (loaded && filename == "") {
        ui->output_filename->setText(
                    QString::fromStdString(this->output->getFilename()));
        consolelog("Encoder", LogType::interaction,
                   "output file selection was cancelled");
    } else {
        ui->output_filename->setText(
                    QString::fromStdString("please load a file"));
        consolelog("Encoder", LogType::warning, "output audio file is empty");
    }
    // File name font
    QFont font;
    font.setItalic(!loaded);
    ui->output_filename->setFont(font);
    // Buttons enabling
    ui->output_controls->button(QDialogButtonBox::Ok)->setEnabled(loaded);
}

/**
 * @brief   It sets a tree configuration.
 * @param   tree                configuration index
 */
void Encoder::setTree(int tree) {
    this->tree = tree;
    ui->tree_5151->setChecked(false);
    ui->tree_5152->setChecked(false);
    ui->tree_525->setChecked(false);
    ui->tree_group->findChild<QRadioButton *>(
                QString("tree_") + QString::number(tree))->setChecked(true);
}

/**
 * @name    Coder interface slots
 * @brief   User interface control functions of coder.
 * @{
 */

/**
 * @brief   It sets the bitstream file name.
 */
void Encoder::setBitstream() {
    QObject::sender()->blockSignals(true);
    std::string filename = ui->bitstream_filename->text().toStdString();
    // Deleting reserved characters
    char reservedchar[6] = { '/', '>', '<', '|', ':', '&' };
    for (int index = 0; index < (int) sizeof(reservedchar); index++) {
        while (filename.find(reservedchar[index]) < filename.length()) {
            filename = filename.substr(0, filename.find(reservedchar[index]))
                    + filename.substr(filename.find(reservedchar[index]) + 1);
        }
    }
    ui->bitstream_filename->setText(QString::fromStdString(filename));
    consolelog("Encoder", LogType::interaction,
               "bitstream file name changed to " + filename);
    QObject::sender()->blockSignals(false);
}

/**
 * @brief   It sets the buried parameter.
 * @param   state              true if it is buried
 */
void Encoder::setBuried(bool state) {
    ui->bitstream_buried->setChecked(state);
    ui->bitstream_filename->setEnabled(!state);
    if (state) {
        consolelog("Encoder", LogType::interaction,
                   "bitstream is changed to be buried");
    } else {
        consolelog("Encoder", LogType::interaction,
                   "bitstream is changed to be a file");
    }
}

/**
 * @brief   It performs change action when tree configuration is changed.
 */
void Encoder::toggleTree() {
    QObject::sender()->blockSignals(true);
    std::string prefix = "tree_";
    int tree = std::stoi(
                QObject::sender()->objectName().toStdString().substr(
                    QObject::sender()->objectName().toStdString().find(prefix)
                    + prefix.length()));
    this->setTree(tree);
    consolelog("Encoder", LogType::interaction,
               "tree configuration changed to " + std::to_string(tree));
    QObject::sender()->blockSignals(false);
}

/**
 * @brief   It loads an input audio file.
 */
void Encoder::load() {
    QObject::sender()->blockSignals(true);
    consolelog("Encoder", LogType::interaction, "selecting input audio file");
    std::string filename = QFileDialog::getOpenFileName(NULL,
                                                        "Load input audio file for encoder", "", "*.wav").toStdString();
    this->setInput(filename);
    if (filename != "") {
        this->reset();
    }
    QObject::sender()->blockSignals(false);
}

/**
 * @brief   It resets all encoding parameters, including output file.
 */
void Encoder::reset() {
    // Encoding
    ui->bitstream_filename->setText("bitstream.bs");
    this->setBuried(false);
    this->setTree(5151);
    // Output
    this->output = NULL;
    this->setOutput("");
    consolelog("Encoder", LogType::interaction,
               "all encoding parameters has been reset as default");
}

/**
 * @brief   It applies the codification.
 */
void Encoder::apply() {
    QObject::sender()->blockSignals(true);
    consolelog("Encoder", LogType::interaction, "encoding");
    std::string input_str = this->input->getFilename();
    std::string output_str = QFileDialog::getSaveFileName(NULL,
                                                          "Save output file for encoder", "", "*.wav").toStdString();
    std::string bitstream_str = output_str.substr(0,
                                                  output_str.rfind("/") + 1);
    if (output_str != "") {
        // SAC encoding
        consolelog("Encoder", LogType::progress, "proceeding to SAC encoder");
        if (ui->bitstream_buried->isChecked()) {
            bitstream_str = "buried";
        } else {
            bitstream_str += ui->bitstream_filename->text().toStdString();
        }
        const char *input_char = input_str.c_str();
        const char *bitstream_char = bitstream_str.c_str();
        const char *output_char = output_str.c_str();
        int timeslots = this->input->header.bitspersample;
        consolelog("Encoder", LogType::info, "input file:\t " + input_str);
        consolelog("Encoder", LogType::info,
                   "bitstream file:\t " + bitstream_str);
        consolelog("Encoder", LogType::info, "output file:\t " + output_str);
        consolelog("Encoder", LogType::info,
                   "sampling frequency:\t " + std::to_string(this->fs) + "Hz");
        consolelog("Encoder", LogType::info,
                   "tree configuration:\t " + std::to_string(this->tree));
        consolelog("Encoder", LogType::info,
                   "time slots:\t " + std::to_string(timeslots) + "bits");
        char *error = sac_encode(input_char, output_char, bitstream_char,
                                 (double) this->fs, this->tree, timeslots); // SAC function
        if (error == NULL) {
            this->setOutput(output_str);
            if (bitstream_str == "buried") {
                this->bitstream = NULL;
            } else {
                this->bitstream = new File(bitstream_str, false);
            }
            consolelog("sac_encoder", LogType::progress,
                       "encoding was completed successfully");
        } else {
            consolelog("sac_encoder", LogType::error, std::string(error));
        }
    }
    QObject::sender()->blockSignals(false);
}

/**
 * @brief   It closes the coder dialog without no consequences.
 */
void Encoder::cancel() {
    QObject::sender()->blockSignals(true);
    this->output = NULL;
    this->bitstream = NULL;
    consolelog("Encoder", LogType::interaction,
               "the coding has been cancelled");
    QObject::sender()->blockSignals(false);
    this->close();
}

/**
 * @brief   It loads the output to decoder and closes coder dialog.
 */
void Encoder::submit() {
    QObject::sender()->blockSignals(true);
    consolelog("Encoder", LogType::interaction, "loading output from coder");
    QObject::sender()->blockSignals(false);
    this->close();
}

/** @} */


text:
local files = {
    [1] = {
        "client",
        "https://raw.githubusercontent.com/CoolMan119/HousePost/master/client.lua"
    },
    [2] = {
        "server",
        "https://raw.githubusercontent.com/CoolMan119/HousePost/master/server.lua"
    }
}
if term.isColor() == false then
   print("Sorry, But you need an Advanced PC to run this!")
else
term.setBackgroundColor(colors.red)
term.clear()
term.setCursorPos(18,8)
print("HousePost")
term.setCursorPos(11,10)
print("A Fast, Simple, and Secure OS")
term.setCursorPos(21,16)
term.setBackgroundColor(colors.lightGray)
print("Install")
while true do
local event, side, x, y = os.pullEvent("mouse_click")
if x >= 21 and x < 28 and y == 16 then
   term.clear()
   shell.run("mkdir", "System")
   term.setCursorPos(1,1)
   textutils.slowPrint("Installing HousePost...")
   local req
   local code
   local file
   for k,v in pairs(files) do
       print(v[1])
       req = http.get(v[2])
       if req ~= nil then
       code = req.readAll()
       req.close()
       else
       print("Failed!")
   end

   file = fs.open(v[1], "w")
   file.write(code)
   file.close()
end
print("Sucessfully installed HousePost!")
print("Rebooting...")
os.sleep(1)
os.reboot()


text:
require 'abstract_unit'

class OutputArnTest < Minitest::Test
  def test_normal
    template = <<-EOS
_output_arn "test"
    EOS
    act_template = run_client_as_json(template)
    exp_template = <<-EOS
{
  "TestName": {
    "Description": "description of TestName",
    "Value": {
      "Ref": "Test"
    }
  },
  "TestArn": {
    "Description": "description of TestArn",
    "Value": {
      "Fn::GetAtt": [
        "Test",
        "Arn"
      ]
    }
  }
}
    EOS
    assert_equal exp_template.chomp, act_template
  end
end


text:
@interface MeeWaterflowController1 : UIViewController

@end


text:
Title: Process Attachment List component
Added: v2.0.0
Status: Active
Last reviewed: 2019-01-14
---

# [Process Attachment List component](../../../lib/process-services/src/lib/attachment/process-attachment-list.component.ts "Defined in process-attachment-list.component.ts")

Displays documents attached to a specified process instance.

![process-attachment-list-sample](../../docassets/images/process-attachment-list.png)

## Basic Usage

```html
<adf-process-attachment-list
    [processInstanceId]="YOUR_PROCESS_INSTANCE_ID"
    (attachmentClick)="YOUR_ATTACHMENT_CLICK_EMITTER_HANDLER">
</adf-process-attachment-list>
```

Make sure to override the [`UploadService`](../../core/services/upload.service.md) with the [`ProcessUploadService`](../../../lib/process-services/src/lib/task-list/services/process-upload.service.ts)

```ts
import { UploadService } from '@alfresco/adf-core';
import { ProcessUploadService } from '@alfresco/adf-process-services';

@Component({
    selector: 'my-custom-process-attachment',
    providers: [
        { provide: UploadService, useClass: ProcessUploadService }
    ]
})
export class MyCustomProcessAttachmentComponent {
    constructor() {}
}
```

### [Transclusions](../../user-guide/transclusion.md)

Any content inside the `<adf-process-attachment-list>` element will be shown when
the list is empty:

```html
<adf-process-attachment-list ...>
    <div><!-- Custom empty list message goes here --></div>
</adf-process-attachment-list>
```

![custom-no-content-drag-drop-template-sample](../../docassets/images/custom-no-content-drag-drop-template.png)

A default template will be used if you don't supply a custom one to override it:

![default-no-content-template-sample](../../docassets/images/default-no-content-template.png)

## Class members

### Properties

| Name | Type | Default value | Description |
| ---- | ---- | ------------- | ----------- |
| disabled | `boolean` | false | Disable/Enable read-only mode for attachment list. |
| processInstanceId | `string` |  | (**required**) The ID of the process instance to display. |

### Events

| Name | Type | Description |
| ---- | ---- | ----------- |
| attachmentClick | [`EventEmitter`](https://angular.io/api/core/EventEmitter)`<any>` | Emitted when the attachment is double-clicked or the view option is selected from the context menu by the user from within the component. Returns a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) representing the object that was clicked. |
| error | [`EventEmitter`](https://angular.io/api/core/EventEmitter)`<any>` | Emitted when the attachment list is not able to fetch the attachments (eg, following a network error). |
| success | [`EventEmitter`](https://angular.io/api/core/EventEmitter)`<any>` | Emitted when the attachment list has fetched all the attachments. Returns a list of attachments. |

## Details

### How to Add Drag and Drop Functionality

You can wrap the attachment list with an
[Upload Drag Area component](../../content-services/components/upload-drag-area.component.md)
to let the user upload attachments to empty lists. When you do this, you can also supply
a custom _no content template_ (using <adf-empty-list>) to invite the user to add their attachments:

<!-- {% raw %} -->

```html
<adf-upload-drag-area
    [rootFolderId]="YOUR_PROCESS_ID"
    [showNotificationBar]="BOOLEAN">
    <adf-process-attachment-list
        [processId]="YOUR_PROCESS_ID"
        (attachmentClick)="YOUR_HANDLER">
            <div adf-empty-list> //no content template
                <adf-empty-list>
                    <div adf-empty-list-header>{{This List is empty}}</div>
                    <div adf-empty-list-body>{{Drag and drop to upload}}</div>
                    <div adf-empty-list-footer>
                        <img [src]="Your custom image URL"></div>
                </adf-empty-list>
            </div>
    </adf-process-attachment-list>
</adf-upload-drag-area>
```

<!-- {% endraw %} -->


text:
package com.develhack.lombok;

import java.util.List;

import lombok.ConfigurationKeys;
import lombok.core.AST;
import lombok.core.LombokNode;
import lombok.core.TypeLibrary;
import lombok.core.TypeResolver;
import lombok.core.handlers.HandlerUtil;

import com.develhack.Conditions;

public class NameResolver {

	public static final TypeLibrary BIG_INTEGER;
	public static final TypeLibrary BIG_DECIMAL;
	public static final TypeLibrary DATE;
	public static final TypeLibrary JDK_LOCAL_DATE;
	public static final TypeLibrary JDK_LOCAL_TIME;
	public static final TypeLibrary JDK_LOCAL_DATE_TIME;
	public static final TypeLibrary JDK_OFFSET_TIME;
	public static final TypeLibrary JDK_OFFSET_DATE_TIME;
	public static final TypeLibrary JDK_ZONED_DATE_TIME;
	public static final TypeLibrary BP_LOCAL_DATE;
	public static final TypeLibrary BP_LOCAL_TIME;
	public static final TypeLibrary BP_LOCAL_DATE_TIME;
	public static final TypeLibrary BP_OFFSET_TIME;
	public static final TypeLibrary BP_OFFSET_DATE_TIME;
	public static final TypeLibrary BP_ZONED_DATE_TIME;

	static {
		BIG_INTEGER = createTypeLibrary("java.math.BigInteger");
		BIG_DECIMAL = createTypeLibrary("java.math.BigDecimal");
		DATE = createTypeLibrary("java.util.Date");
		JDK_LOCAL_DATE = createTypeLibrary("java.time.LocalDate");
		JDK_LOCAL_TIME = createTypeLibrary("java.time.LocalTime");
		JDK_LOCAL_DATE_TIME = createTypeLibrary("java.time.LocalDateTime");
		JDK_OFFSET_TIME = createTypeLibrary("java.time.OffsetTime");
		JDK_OFFSET_DATE_TIME = createTypeLibrary("java.time.OffsetDateTime");
		JDK_ZONED_DATE_TIME = createTypeLibrary("java.time.ZonedDateTime");
		BP_LOCAL_DATE = createTypeLibrary("org.threeten.bp.LocalDate");
		BP_LOCAL_TIME = createTypeLibrary("org.threeten.bp.LocalTime");
		BP_LOCAL_DATE_TIME = createTypeLibrary("org.threeten.bp.LocalDateTime");
		BP_OFFSET_TIME = createTypeLibrary("org.threeten.bp.OffsetTime");
		BP_OFFSET_DATE_TIME = createTypeLibrary("org.threeten.bp.OffsetDateTime");
		BP_ZONED_DATE_TIME = createTypeLibrary("org.threeten.bp.ZonedDateTime");
	}

	private static TypeLibrary createTypeLibrary(String fqn) {
		TypeLibrary typeLibrary = new TypeLibrary();
		typeLibrary.addType(fqn);
		typeLibrary.lock();
		return typeLibrary;
	}

	public static String resolveFQN(LombokNode<?, ?, ?> context, String name, TypeLibrary... libraries) {

		TypeResolver resolver = new TypeResolver(context.getImportList());

		for (TypeLibrary library : libraries) {
			String fqn = resolver.typeRefToFullyQualifiedName(context, library, name);
			if (fqn != null) return fqn;
		}

		return null;
	}

	public static String resolvePropertyName(AST<?, ?, ?> ast, String fieldName) {
		if (fieldName.length() == 0) return null;
		List<String> prefix = ast.readConfiguration(ConfigurationKeys.ACCESSORS_PREFIX);
		CharSequence unprefixedFieldName = HandlerUtil.removePrefix(fieldName, prefix);
		if (unprefixedFieldName == null) return fieldName;
		return unprefixedFieldName.toString();
	}

	public static String resolveAccessorName(AST<?, ?, ?> ast, String fieldName, boolean isBoolean, String booleanPrefix,
			String normalPrefix, boolean adhereToFluent) {

		if (Boolean.TRUE.equals(ast.readConfiguration(ConfigurationKeys.GETTER_CONSEQUENT_BOOLEAN))) isBoolean = false;
		boolean fluent = Boolean.TRUE.equals(ast.readConfiguration(ConfigurationKeys.ACCESSORS_FLUENT));

		String fName = resolvePropertyName(ast, fieldName);
		if(fName == null) return null;
		if (adhereToFluent && fluent) return fName;

		if (isBoolean && fName.startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) {
			// The field is for example named 'isRunning'.
			return booleanPrefix + fName.substring(2);
		}

		return HandlerUtil.buildAccessorName(isBoolean ? booleanPrefix : normalPrefix, fName);
	}

	public static String resolveGetterName(AST<?, ?, ?> ast, String fieldName, boolean isBoolean) {
		return resolveAccessorName(ast, fieldName, isBoolean, "is", "get", true);
	}

	public static String resolveSetterName(AST<?, ?, ?> ast, String fieldName, boolean isBoolean) {
		return resolveAccessorName(ast, fieldName, isBoolean, "set", "set", true);
	}

	public static String resolveConstantFieldName(String typeFqn, String value, boolean isBoxedType) {

		StringBuilder buff = new StringBuilder().append('$');
		String[] tokens = typeFqn.split("\\.");
		if(tokens.length == 1 && isBoxedType) {
			buff.append("JAVA_LANG_");
		}
		for (String token : tokens) {
			buff.append(toSnakeCase(token, true));
			buff.append('_');
		}

		for (int i = 0, length = value.length(); i < length; i++) {
			char c = value.charAt(i);
			buff.append(Conditions.isInRange(c, '0', '9') ? c : '_');
		}

		return buff.toString();
	}

	public static String toSnakeCase(CharSequence camelCase, boolean upperCase) {

		if (camelCase == null) return null;
		if (camelCase.length() == 0) return "";

		int length = camelCase.length();
		StringBuilder builder = new StringBuilder(length * 2);

		boolean adjacent;
		char c = camelCase.charAt(0);
		if (Character.isUpperCase(c)) {
			builder.append(upperCase ? c : Character.toLowerCase(c));
			adjacent = true;
		} else {
			builder.append(upperCase ? Character.toUpperCase(c) : c);
			adjacent = false;
		}
		for (int i = 1; i < length; i++) {
			c = camelCase.charAt(i);
			if (Character.isUpperCase(c)) {
				if (!adjacent) builder.append('_');
				builder.append(upperCase ? c : Character.toLowerCase(c));
				adjacent = true;
			} else {
				builder.append(upperCase ? Character.toUpperCase(c) : c);
				adjacent = false;
			}
		}

		return builder.toString();
	}
}


text:
package lombok.delombok;

public final class Comment {

	public enum StartConnection {
		START_OF_LINE,
		ON_NEXT_LINE,
		DIRECT_AFTER_PREVIOUS,
		AFTER_PREVIOUS
	}

	public enum EndConnection {
		DIRECT_AFTER_COMMENT,
		AFTER_COMMENT,
		ON_NEXT_LINE
	}

	final int pos;
	final int prevEndPos;
	final String content;
	final int endPos;
	final StartConnection start;
	final EndConnection end;

	public Comment(int prevEndPos, int pos, int endPos, String content, StartConnection start, EndConnection end) {
		this.pos = pos;
		this.prevEndPos = prevEndPos;
		this.endPos = endPos;
		this.content = content;
		this.start = start;
		this.end = end;
	}

	@Override
	public String toString() {
		return String.format("%d: %s (%s,%s)", pos, content, start, end);
	}
}


text:
<?php
/**
 * File Italian lexicon topic
 *
 * @language it
 * @package modx
 * @subpackage lexicon
 */
$_lang['directory'] = 'Directory';
$_lang['file_confirm_remove'] = 'Sei sicuro di voler rimuovere questo file? Il sito potrebbe danneggiarsi.';
$_lang['file_create'] = 'Creare File';
$_lang['file_deleted'] = 'Successo!';
$_lang['file_delete_file'] = 'Elimina file';
$_lang['file_delete_folder'] = 'Elimina cartella';
$_lang['file_download'] = 'Scarica File';
$_lang['file_download_file'] = 'Scarica file';
$_lang['file_download_unzip'] = 'Decomprimi file';
$_lang['file_edit'] = 'Modifica file';
$_lang['file_err_ae'] = 'Il file %s esiste di già';
$_lang['file_err_chmod'] = 'Si è verificato un errore sconosciuto tentando di cambiare autorizzazioni (chmod) .';
$_lang['file_err_chmod_ns'] = 'Specificare una modalità di autorizzazioni (chmod).';
$_lang['file_err_create'] = 'Si è verificato un errore durante la creazione del file.';
$_lang['file_err_ext_not_allowed'] = 'L\'estensione `[[+ext]]` non è permessa.';
$_lang['file_err_filter'] = 'Nessun file soddisfa questo filtro di ricerca.';
$_lang['file_err_invalid'] = 'Questo non è un file convenzionale e non può essere rimosso.';
$_lang['file_err_nf'] = 'Il file non esiste!';
$_lang['file_err_ns'] = 'Specifica un file valido.';
$_lang['file_err_open'] = 'Non è possibile aprire il file: ';
$_lang['file_err_perms_rename'] = 'Il webserver non ha sufficienti privilegi per rinominare il file.';
$_lang['file_err_perms_remove'] = 'Il webserver non ha sufficienti privilegi per rimuovere il file.';
$_lang['file_err_rename'] = 'MODX non è riuscito a rinominare il file. Assicurati che i permessi siano settati correttamente.';
$_lang['file_err_remove'] = 'MODX non è riuscito a cancellare il file. Assicurati che i permessi siano settati correttamente.';
$_lang['file_err_save'] = 'Non posso salvare il file, assicurati che la directory di destinazione sia scrivibile!';
$_lang['file_err_too_large'] = 'Il file caricato è troppo grande: [[+size]] bytes. Assicurati che risultino meno di [[+allowed]] bytes.';
$_lang['file_err_unzip'] = 'Decompressione fallita!';
$_lang['file_err_unzip_invalid_path'] = 'Percorso non valido per il file decompresso.';
$_lang['file_err_unzip_missing_lib'] = ' Manca la libreria zip (php_zip.dll / zip.so)';
$_lang['file_err_upload'] = 'Si è verificato un errore cercando di caricare i file.';
$_lang['file_exists_hk'] = 'Il file {0} esiste già';
$_lang['file_extensions'] = 'Estensioni  file';
$_lang['file_folder_enter_new'] = 'Inserisci un nuovo nome per la cartella';
$_lang['file_folder_chmod'] = 'Chmod directory';
$_lang['file_folder_create'] = 'Crea directory';
$_lang['file_folder_create_here'] = 'Crea directory qui';
$_lang['file_folder_created'] = 'Cartella creata con successo!';
$_lang['file_folder_deleted'] = 'Cartella eliminata con successo!';
$_lang['file_folder_err_ae'] = 'Un questa sede esiste già una directory con questo nome.';
$_lang['file_folder_err_chmod'] = 'Impossibile modificare permessi, devono essere modificati fuori da MODX.';
$_lang['file_folder_err_create'] = 'Si è verificato un errore sconosciuto cercando di creare la directory.';
$_lang['file_folder_err_invalid'] = 'La directory specificata non è una directory.';
$_lang['file_folder_err_invalid_path'] = 'Percorso non valido per creare una cartella.';
$_lang['file_folder_err_nf'] = 'La cartella non esiste!';
$_lang['file_folder_err_ns'] = 'Specifica una directory valida.';
$_lang['file_folder_err_ns_name'] = 'Specifica un nome valido per la cartella.';
$_lang['file_folder_err_parent_invalid'] = 'La directory genitore specificata non è una directory.';
$_lang['file_folder_err_perms'] = 'Il webserver non ha i privilegi necessari per aggiornare la directory.';
$_lang['file_folder_err_perms_parent'] = 'Il webserver non ha i privilegi necessari per aggiungere la directory.';
$_lang['file_folder_err_perms_remove'] = 'Il webserver non ha i privilegi necessari per rimuovere la directory.';
$_lang['file_folder_err_perms_upload'] = 'Il webserver non ha i privilegi necessari per caricare la directory.';
$_lang['file_folder_err_rename'] = 'Si è verificato un errore sconosciuto tentando di rinominare la directory.';
$_lang['file_folder_err_remove'] = 'Si è verificato un errore tentando di rimuovere la directory.';
$_lang['file_folder_parent'] = 'Directory genitore';
$_lang['file_folder_remove'] = 'Rimuovi directory';
$_lang['file_folder_remove_confirm'] = 'Sei sicuro di voler rimuovere questa directory? Il sito potrebbe danneggiarsi.';
$_lang['file_last_accessed'] = 'Ultimo accesso';
$_lang['file_last_modified'] = 'Ultima modifica';
$_lang['file_name'] = 'Nome del file';
$_lang['file_quick_create'] = 'Creazione rapida file';
$_lang['file_quick_update'] = 'Modifica rapida file';
$_lang['file_remove'] = 'Rimuovi file';
$_lang['file_remove_confirm'] = 'Sei sicuro di voler rimuovere completamente questo file?';
$_lang['file_saved'] = 'File aggiornato con successo!';
$_lang['file_size'] = 'Dimensione del file';
$_lang['file_unzip'] = 'Decompressione effettuata con successo!';
$_lang['file_upload'] = 'Carica files';
$_lang['file_upload_here'] = 'Carica files qui';
$_lang['file_view'] = 'Mostra file';
$_lang['files_access_denied'] = 'Accesso negato!';
$_lang['files_data'] = 'Dati';
$_lang['files_directories'] = 'Directories';
$_lang['files_dirwritable'] = 'Directory scrivibile?';
$_lang['files_dir_listing'] = 'Elenco directory per:';
$_lang['files_editfile'] = 'Modifica file';
$_lang['files_filename'] = 'NomeFile (Filename)';
$_lang['files_fileoptions'] = 'Opzioni';
$_lang['files_files'] = 'Files';
$_lang['files_filesize'] = 'Dimensione file';
$_lang['files_file_type'] = 'Tipo di file: ';
$_lang['files_modified'] = 'Modificato!';
$_lang['files_viewfile'] = 'Mostra file';
$_lang['upf_abort'] = 'Interrompi!';
$_lang['upf_abort_desc'] = 'Interrompi caricamento.';
$_lang['upf_aborted'] = 'Interrotto dall\'utente.';
$_lang['upf_add'] = 'Aggiungi';
$_lang['upf_add_desc'] = 'Aggiungi file alla coda di caricamento.';
$_lang['upf_close'] = 'Chiudi';
$_lang['upf_close_desc'] = 'Chiudi la finestra.';
$_lang['upf_err_failed'] = 'Si è verificato un errore interno al server o il server non è disponibile.';
$_lang['upf_err_filetype'] = 'L\'estensione selezionata non è permessa.
Selezionare file con le seguenti estensioni: {1}';
$_lang['upf_error'] = 'Errore!';
$_lang['upf_filename'] = 'NomeFile (Filename)';
$_lang['upf_note'] = 'Nota';
$_lang['upf_progress_wait'] = 'In attesa...';
$_lang['upf_queued'] = 'Coda di caricamento.';
$_lang['upf_remove'] = 'Rimuovi';
$_lang['upf_remove_desc'] = 'Rimuovi file dalla coda di caricamento.';
$_lang['upf_reset'] = 'Resetta';
$_lang['upf_reset_desc'] = 'Resetta coda.';
$_lang['upf_state'] = 'Stato';
$_lang['upf_success'] = 'OK.';
$_lang['upf_upload'] = 'Carica';
$_lang['upf_upload_desc'] = 'Carica nel server i file in coda.';
$_lang['upf_upload_err'] = 'Errore di caricamento.';
$_lang['upf_uploading'] = 'Sto caricando...';
$_lang['upf_uploading_desc'] = 'Caricati completamente {0} di {1} files.';
$_lang['upload_files'] = 'Carica files';


text:
  Saint-Laurent-des-Bois est
       un village
       géographiquement positionné dans le département de l'Eure en Haute-Normandie. Elle totalisait 195 habitants en 2008.

Le nombre d'habitations, à Saint-Laurent-des-Bois, était réparti en 2011 en zero appartements et 99 maisons soit
 un marché plutôt équilibré.

Si vous pensez demenager à Saint-Laurent-des-Bois, vous pourrez facilement trouver une maison à acheter.

À coté de Saint-Laurent-des-Bois sont positionnées géographiquement les villes de
Lignerolles à 3 km, 279 habitants,
Marcilly-sur-Eure à 2 km, 1 427 habitants,
Illiers-l'Évêque à 4 km, 970 habitants,
Champigny-la-Futelaye à 2 km, 223 habitants,
Croth située à 4 km, 1 309 habitants,
Sorel-Moussel située à 5 km, 1 810 habitants,
 entre autres. De plus, Saint-Laurent-des-Bois est située à seulement 23 km de Évreux.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace App.Models.Enums
{
    public enum AttackType
    {
        Melee,
        Range,
        Cast
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <include
        android:id="@+id/ll_step"
        layout="@layout/include_act_publish_step" />

    <FrameLayout
        android:id="@+id/frame_act_publish_1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <FrameLayout
        android:id="@+id/frame_act_publish_2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:visibility="gone" />

</LinearLayout>


text:
<?php

namespace GithubService\Hydrator;

use GithubService\Hydrator;
use GithubService\HydratorRegistry;
use GithubService\Model\Tags;

class TagsHydrator implements Hydrator
{
    public function hydrate(array $data, HydratorRegistry $hydratorRegistry)
    {
        $tags = new Tags();
        foreach ($data as $entry) {
            $tags->repoTags[] = $hydratorRegistry->instantiateClass('GithubService\\Model\\Tag', $entry);
        }

        return $tags;
    }
}


text:
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext

from resources.models import PdResource

def view(request, id):
	pdresource = get_object_or_404(PdResource, pk=id)
	pdresources = PdResource.objects.filter(sub_page=False)
	return render_to_response("resources/pd/view.haml",
							  {'pdresource': pdresource, 'pdresources': pdresources},
							  context_instance=RequestContext(request))

def list(request):
	pdresources = PdResource.objects.filter(sub_page=False)
	return render_to_response("resources/pd/list.haml",
							  {'pdresources': pdresources},
							  context_instance=RequestContext(request))


text:
/* ------- MENU ------- */
$(document).ready(function(){
ddsmoothmenu.init({
	mainmenuid: "smoothmenu1", //menu DIV id
	orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
	classname: 'ddsmoothmenu', //class added to menu's outer DIV
	//customtheme: ["#1c5a80", "#18374a"],
	contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})
});
/* ------- TWITTER ------- */

getTwitters('twitter', {
        id: 'elemisdesign',
        count: 1,
        enableLinks: true,
        ignoreReplies: false,
        template: '%text% - %time%
@ %user_screen_name%',
        newwindow: true
    });


text:
using System;

namespace Cake.Storm.Fluent.Steps
{
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class CleanStepAttribute : Attribute
	{
	}
}


text:
package pony.cache;

public class CacheConfig {

}


text:
import path = require('path');
import tl = require('vsts-task-lib/task');

async function run() {
    try {
        tl.setResourcePath(path.join( __dirname, 'task.json'));

        var bash = tl.createToolRunner(tl.which('bash', true));

        var scriptPath: string = tl.getPathInput('scriptPath', true, true);
        var cwd: string = tl.getPathInput('cwd', true, false);

        // if user didn't supply a cwd (advanced), then set cwd to folder script is in.
        // All "script" tasks should do this
        if (!tl.filePathSupplied('cwd') && !tl.getBoolInput('disableAutoCwd', false)) {
            cwd = path.dirname(scriptPath);
        }
        tl.mkdirP(cwd);
        tl.cd(cwd);

        bash.pathArg(scriptPath);

        // additional args should always call argString.  argString() parses quoted arg strings
        bash.argString(tl.getInput('args', false));

        // determines whether output to stderr will fail a task.
        // some tools write progress and other warnings to stderr.  scripts can also redirect.
        var failOnStdErr: boolean = tl.getBoolInput('failOnStandardError', false);

        var code: number = await bash.exec(<any>{failOnStdErr: failOnStdErr});
        tl.setResult(tl.TaskResult.Succeeded, tl.loc('BashReturnCode', code));
    }
    catch(err) {
        tl.setResult(tl.TaskResult.Failed, tl.loc('BashFailed', err.message));
    }
}

run();


text:
<?php
function image_double_plugin() {
    if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) ) {
        return;
    }
    if ( 'true' == get_user_option( 'rich_editing' ) ) {
        add_filter( 'mce_external_plugins', 'naba_add_tinymce_plugin_double' );
        add_filter( 'mce_buttons', 'naba_register_mce_button_double' );
    }
}
add_action('admin_head', 'image_double_plugin');

// Declare script for new button
function naba_add_tinymce_plugin_double( $plugin_array ) {
    $plugin_array['image_double_plugin'] = get_template_directory_uri() .'/inc/tinymce/js/image-double.js';
    return $plugin_array;
}

// Register new button in the editor
function naba_register_mce_button_double( $buttons ) {
    array_push( $buttons, 'image_double_plugin' );
    return $buttons;
}


text:
using Microsoft.Practices.Unity;

namespace EzApp.Web.Core.Config.Ioc
{
    public interface IEzEntityStackRegistration
    {
        void RegisterEntityStack(IUnityContainer container);
    }
}


text:
/**
 * mapbox-angular adapted for webzine
 */

var module = webzine.getModule('webzine.directives', [ 'mapbox' ]);

module.directive('mapPosts', ['$timeout', function($timeout) {

    var getGeojsonFromPost = function(post) {
        return {
            type: 'Feature',
            geometry: {
                type: "Point",
                //coordinates: [2.3508, 48.8567]
                coordinates: [post.position.lng, post.position.lat]
            },
            properties: {
                "id": post._id,
                "opacity": post.opacity,
                "order": post.viewId
            }
        };

    };

    var getPostFromFeature = function(feature, posts) {
        var post = _.find(posts, function(post) {
            if (feature !== null &&
                typeof feature !== 'undefined' &&
                typeof feature.feature !== 'undefined' &&
                typeof feature.feature.properties !== 'undefined' &&
                typeof feature.feature.properties.id !== 'undefined'
            ) {
                return post._id == feature.feature.properties.id;
            } else {
                return false;
            }
        });
        return post;
    };

    return {
        restrict: 'E',
        // replace: 'E',
        scope: {
            posts: '=',
            bounds: '=',
            postSelected: '=',
            onPostClicked: '&'
        },
        template: "<mapbox geojson='geojson' posts='posts' bounds='bounds' selected='selected' on-feature-clicked='onFeatureClicked(feature)'></mapbox>",
        link: function($scope, elem, params) {

            $scope.onFeatureClicked = function(feature) {
                var post = getPostFromFeature(feature, $scope.posts);
                $scope.onPostClicked({post: post});
            };

            $scope.$watch('posts', function(newValue, oldValue) {
                $scope.geojson = _($scope.posts).map(getGeojsonFromPost);
            });

            $scope.$watch('selected', function() {
                $scope.postSelected = getPostFromFeature($scope.selected, $scope.posts);
            });
        }
    };
}]);


text:
mock_scheduler::mock_scheduler()
:
  unix_time_(0),
  tasks_(mock_scheduler_queue_cmp())
{
}

remove_task_future_t mock_scheduler::add_periodic_task(task_fn_t task,
                                                       float interval)
{
  auto p = static_cast<time_t>(interval);
  tasks_.push(std::make_tuple(unix_time_ + p, p, task));

  return {};
}

remove_task_future_t mock_scheduler::add_once_task(task_fn_t task, float dt) {
  auto p = static_cast<time_t>(dt);
  tasks_.push(std::make_tuple(unix_time_ + p, 0, task));

  return {};
}

remove_ns_tasks_future_t mock_scheduler::remove_ns_tasks(const std::string) {
  return {};
}

time_t mock_scheduler::unix_time() {
  return unix_time_;
}

void mock_scheduler::set_time(const time_t event_time) {
  while (!tasks_.empty()) {
    auto lowest = std::get<0>(tasks_.top());
    if (lowest > event_time) {
      break;
    }
    set_forward_time(lowest);
    auto interval = std::get<1>(tasks_.top());
    auto fn = std::get<2>(tasks_.top());
    tasks_.pop();
    fn();
    if (interval) {
      tasks_.push(std::make_tuple(unix_time_ + interval, interval, fn));
    }
  }
  set_forward_time(event_time);
}

void mock_scheduler::set_forward_time(time_t time) {
  if (time > unix_time_) {
    unix_time_ = time;
  }
}

void mock_scheduler::clear() {
  while (!tasks_.empty()) {
    tasks_.pop();
  }
  unix_time_ = 0;
}


text:
{# Template for home view #}

{% extends "site/base.html" %}

{% block body_classes %}style="background-image: url('{{'enkiblog:static/background.jpeg'|static_url }}');"{% endblock %}

{% block content %}

        {% block article %}
        {% endblock article %}

        {% block sidebar %}
        {% endblock sidebar %}

{% endblock %}


text:
.PHONY:all
all: client server

client:lib
	make -C client

server:lib
	make -C server

.PHONY:lib
lib:
	make -C lib

.PHONY:clean
clean:
	make -C lib clean
	make -C client clean
	make -C server clean

smooth:smooth.c
	cc -o $@ $< `pkg-config --cflags --libs gtk+-3.0`

.PHONY:run

run:smooth
	./smooth


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title><?php echo $title;?> - With Us</title>

    <meta name="viewport" content="initial-scale=1, maximum-scale=1">

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

    <link href="/static/lib/ratchet/css/ratchet.min.css" rel="stylesheet">
    <link href="/static/css/style.css" rel="stylesheet">

		  <button class="btn btn-link btn-nav pull-right">

		  </button>
      <?php if(!isset($_SESSION['user'])) { ?>
		  LOGIN
		  <?php }else{ ?>
      LOGOUT
      <?php } ?>

回到首页

注册和登录

空间介绍

会议室预约租用

活动空间预约租用


text:
layout: post
title: "CSS 颜色 单位"
subtitle: "Different ways to define colors"
section: css
---

**颜色** 在CSS中运用广泛,比如文字颜色、背景颜色、渐变、阴影、边框... 这里有几种定义颜色的方式,他们各有利弊。

`color` 属性定义**文字**颜色。这很简单。本文的重点是多种可使用的**颜色单位**。

### 颜色名字

CSS 提供了 [145个颜色名](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value), from the most basic (black, white, orange, yellow, blue...) 非常具体。

{% highlight css %}
body{ color: black;}
a{ color: orange;}
{% endhighlight %}

因为颜色名并不容易记住,我们需要更加具体的颜色,所以颜色名不经常用。

### rgb

计算机显示器、电视、手机、都是用RGB颜色模式来展示颜色。本质来讲,每一个颜色都是通过红、绿、蓝混合而成,三种颜色分别有256个值。因为计算机计数从0开始255结束。

考虑到一个颜色是红、绿、蓝的混合结果,而每个颜色只有256个值,所以有`256 * 256 * 256 = 16,777,216`个颜色可以使用。

RGB模式成为CSS的颜色单位的主要原因是因为它与颜色的物理渲染直接相关。

举个例子,红色的数值是红色219,绿色78,蓝色是68:

{% highlight css %}
a{ color: rgb(219, 78, 68);}
{% endhighlight %}

黑色没有数值:

{% highlight css %}
body{ color: rgb(0, 0, 0);}
{% endhighlight %}

在色谱的另一边,白色是满值的:

{% highlight css %}
body{ color: rgb(255, 255, 255);}
{% endhighlight %}

### rgba

`rgba`颜色代为是`rgb`颜色单位多了 **alpha** 值(取值范围是0-1之前,是一个小数值),他定义了这个颜色的透明度。

{% highlight css %}
body{ color: rgba(0, 0, 0, 0.8);}
{% endhighlight %}

有一点透明的黑色
{: .info}

颜色透明的目的是与背景融合,因此根据上下文看起来稍有不同。对于**背景颜色**非常有用。

### hsl and hsla

**HSL** is another way to define a color. Think of it as a **color wheel**.

Source: Wikipedia

Instead of a color being a combination of Red, Green and Blue, you define:

* the **Hue** a value ranging from 0 to 360, defines _which color_ you want.
* the **Saturation** percentage, ranging from 0% to 100%, defines _how much_ of that color you want.
* the **Lightness** percentage, ranging from 0% to 100%, defines _how bright_ you want that color to be.

Again, the red color of this website is defined this way in HSL:

{% highlight css %}
a{ color: hsl(4, 68%, 56%);}
{% endhighlight %}

`4` indicates it's red
`68%` indicates the red is quite prominent
`56%` indicates it's halfway between black and white

The `hsl` color unit is easier to understand than `rgb` because the expected result is clearer. You basically define a color in 3 separate steps, and can play around with each value to come up with the color you want. If you want a yellow shade, you can start with a value like `hsl(50, 68%, 56%)`, and alter the Saturation and Lightness value to find the specific shade you're looking for.

I consider `hsl` to be **human-readable**, whereas `rgb` is more **computer-readable**.

`hsla` is the same as `hsl`, with the added value of being able to define an **alpha** value:

{% highlight css %}
body{ color: hsla(4, 68%, 56%, 0.5);}
{% endhighlight %}

A transparent red color.
{: .info}

### Hexadecimal

Colors in CSS can also be defined with **hexadecimal values**, like `#db4e44`.

To understand what hexadecimal values are, let's look at how binary and decimal work:

        binary
        2 possible values

      0
      1

        decimal
        10 possible values

      0
      1
      2
      3
      4
      5
      6
      7
      8
      9

        hexadecimal
        16 possible values

      0
      1
      2
      3
      4
      5
      6
      7
      8
      9
      A
      B
      C
      D
      E
      F

Consider the 0-9 numbers and the A-F letters as **symbols**.

Humans use the **decimal** system. We have 10 symbols to form numbers.

In **hexadecimal**, we have 16 symbols to form numbers. Because 0-9 are not enough symbols, we also use A-F. And it starts at zero. So:

* the number `4` in hexadecimal is `4`
* the number `12` in hexadecimal is `C`
* the number `16` in hexadecimal is `10` because after you've run out of symbols (the last one being `F`), you add a second symbol to the left and increment (`0` becomes `1`) and the right one starts over (from `F` to `0`)

#### Do I have to remember this?

Not at all! It is here to provide an explanation of how hexadecimal values work. The most important thing to remember is that there are 16 hexadecimal symbols.

Just like RGB, a hexadecimal color value is a combination of Red, Green, and Blue, each of them being represent as a hexadecimal value, like `DB` for Red, `4E` for Green, and `44` for Blue.

Because Red, Green or Blue can only have 2 symbols, their possible values are `16 * 16 = 256`, which mirrors the RGB color unit!

#### Why not use RGB then?

Usually, when choosing colors, you **don't write** them directly. You either use a color picker, or copy/paste it from Photoshop, or choose a [colour palette](http://www.colourlovers.com/palettes) somewhere.

Hexadecimal values are easier to **copy and paste**, as they only comprise 6 characters.

![Photoshop one field for hex](/images/photoshop-color-picker.png)

#### It is easier to copy paste a single field than 3 separate ones.

In CSS, you only need to prepend a hexadecimal color value with a hash `#`.

### Which one to pick?

If you don't intend to use any transparent color, stick to **hexadecimal** values, as they are easier to copy/paste and don't take much space in your code.

If you want some transparency, convert your color from hex to rgba, and use the `rgba` color unit.

If you want to play around with your color directly in the browser, try `hsl`.


text:
package com.zabbix.sisyphus.proxy.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.zabbix.sisyphus.proxy.entity.ProxyIP;

public abstract interface ProxyIPDao extends JpaRepository<ProxyIP, Long> {
	List<ProxyIP> findByStatus(String status);

	List<ProxyIP> findByIp(String ip);
}


text:
import entries from '../../common/entries';
import keys from '../../common/keys';
import addCommas from '../../system/addCommas';
import { cdn } from '../../system/system';

function imgHtml(imageId) {
  return `<img class="tip-static" src="${cdn
  }creatures/${imageId}.png" data-tipped="" width=40 height=40>`;
}

function hazEnhancements(enhancements) {
  return enhancements && keys(enhancements).length > 0;
}

function statMinMax(stat) {
  return `${stat.min.toString()} - ${stat.max.toString()}`;
}

function buildEnhancements(pair) {
  return `${pair[0]}: ${
    statMinMax(pair[1])}`;
}

function formatEnhancements(enhancements) {
  if (hazEnhancements(enhancements)) {
    let tmp = '';
    tmp += entries(enhancements).map(buildEnhancements).join('
');
    return `${tmp}</span>`;
  }
  return '**Missing**';
}

export default function buildHtml(data, key) {
  return {
    ...data[key],
    name: key,
    image: imgHtml(data[key].image_id),
    level: addCommas(data[key].level),
    attack: statMinMax(data[key].attack),
    defense: statMinMax(data[key].defense),
    armor: statMinMax(data[key].armor),
    damage: statMinMax(data[key].damage),
    hp: statMinMax(data[key].hp),
    enhancements: formatEnhancements(data[key].enhancements),
  };
}


text:
#ifndef CAFFE2_UTILS_PROTO_UTILS_H_
#define CAFFE2_UTILS_PROTO_UTILS_H_

#include "google/protobuf/message_lite.h"
#ifndef CAFFE2_USE_LITE_PROTO
#include "google/protobuf/message.h"
#endif  // !CAFFE2_USE_LITE_PROTO

#include "caffe2/core/logging.h"
#include "caffe2/proto/caffe2.pb.h"
#include "caffe2/proto/predictor_consts.pb.h"

namespace caffe2 {

using std::string;
using ::google::protobuf::MessageLite;

// A wrapper function to return device name string for use in blob serialization
// / deserialization. This should have one to one correspondence with
// caffe2/proto/caffe2.proto: enum DeviceType.
//
// Note that we can't use DeviceType_Name, because that is only available in
// protobuf-full, and some platforms (like mobile) may want to use
// protobuf-lite instead.
std::string DeviceTypeName(const int32_t& d);

// Common interfaces that reads file contents into a string.
bool ReadStringFromFile(const char* filename, string* str);
bool WriteStringToFile(const string& str, const char* filename);

// Common interfaces that are supported by both lite and full protobuf.
bool ReadProtoFromBinaryFile(const char* filename, MessageLite* proto);
inline bool ReadProtoFromBinaryFile(const string filename, MessageLite* proto) {
  return ReadProtoFromBinaryFile(filename.c_str(), proto);
}

void WriteProtoToBinaryFile(const MessageLite& proto, const char* filename);
inline void WriteProtoToBinaryFile(const MessageLite& proto,
                                   const string& filename) {
  return WriteProtoToBinaryFile(proto, filename.c_str());
}

#ifdef CAFFE2_USE_LITE_PROTO

inline string ProtoDebugString(const MessageLite& proto) {
  return proto.SerializeAsString();
}

// Text format MessageLite wrappers: these functions do nothing but just
// allowing things to compile. It will produce a runtime error if you are using
// MessageLite but still want text support.
inline bool ReadProtoFromTextFile(const char* filename, MessageLite* proto) {
  LOG(FATAL) << "If you are running lite version, you should not be "
                  << "calling any text-format protobuffers.";
  return false;  // Just to suppress compiler warning.
}
inline bool ReadProtoFromTextFile(const string filename, MessageLite* proto) {
  return ReadProtoFromTextFile(filename.c_str(), proto);
}

inline void WriteProtoToTextFile(const MessageLite& proto,
                                 const char* filename) {
  LOG(FATAL) << "If you are running lite version, you should not be "
                  << "calling any text-format protobuffers.";
}
inline void WriteProtoToTextFile(const MessageLite& proto,
                                 const string& filename) {
  return WriteProtoToTextFile(proto, filename.c_str());
}

inline bool ReadProtoFromFile(const char* filename, MessageLite* proto) {
  return (ReadProtoFromBinaryFile(filename, proto) ||
          ReadProtoFromTextFile(filename, proto));
}

inline bool ReadProtoFromFile(const string& filename, MessageLite* proto) {
  return ReadProtoFromFile(filename.c_str(), proto);
}

#else  // CAFFE2_USE_LITE_PROTO

using ::google::protobuf::Message;

inline string ProtoDebugString(const Message& proto) {
  return proto.ShortDebugString();
}

bool ReadProtoFromTextFile(const char* filename, Message* proto);
inline bool ReadProtoFromTextFile(const string filename, Message* proto) {
  return ReadProtoFromTextFile(filename.c_str(), proto);
}

void WriteProtoToTextFile(const Message& proto, const char* filename);
inline void WriteProtoToTextFile(const Message& proto, const string& filename) {
  return WriteProtoToTextFile(proto, filename.c_str());
}

// Read Proto from a file, letting the code figure out if it is text or binary.
inline bool ReadProtoFromFile(const char* filename, Message* proto) {
  return (ReadProtoFromBinaryFile(filename, proto) ||
          ReadProtoFromTextFile(filename, proto));
}

inline bool ReadProtoFromFile(const string& filename, Message* proto) {
  return ReadProtoFromFile(filename.c_str(), proto);
}

#endif  // CAFFE2_USE_LITE_PROTO

template <class IterableInputs, class IterableOutputs, class IterableArgs>
OperatorDef CreateOperatorDef(
    const string& type, const string& name, const IterableInputs& inputs,
    const IterableOutputs& outputs, const IterableArgs& args,
    const DeviceOption& device_option, const string& engine) {
  OperatorDef def;
  def.set_type(type);
  def.set_name(name);
  for (const string& in : inputs) {
    def.add_input(in);
  }
  for (const string& out : outputs) {
    def.add_output(out);
  }
  for (const Argument& arg : args) {
    def.add_arg()->CopyFrom(arg);
  }
  if (device_option.has_device_type()) {
    def.mutable_device_option()->CopyFrom(device_option);
  }
  if (engine.size()) {
    def.set_engine(engine);
  }
  return def;
}

// A simplified version compared to the full CreateOperator, if you do not need
// to specify device option or engine.
template <class IterableInputs, class IterableOutputs, class IterableArgs>
inline OperatorDef CreateOperatorDef(
    const string& type, const string& name, const IterableInputs& inputs,
    const IterableOutputs& outputs, const IterableArgs& args) {
  return CreateOperatorDef(
      type, name, inputs, outputs, args, DeviceOption(), "");
}

// A simplified version compared to the full CreateOperator, if you do not need
// to specify device option or engine or args.
template <class IterableInputs, class IterableOutputs>
inline OperatorDef CreateOperatorDef(
    const string& type, const string& name, const IterableInputs& inputs,
    const IterableOutputs& outputs) {
  return CreateOperatorDef(type, name, inputs, outputs,
                           std::vector<Argument>(), DeviceOption(), "");
}

inline bool HasArgument(const OperatorDef& def, const string& name) {
  for (const Argument& arg : def.arg()) {
    if (arg.name() == name) {
      return true;
    }
  }
  return false;
}

/**
 * @brief A helper class to index into arguments.
 *
 * This helper helps us to more easily index into a set of arguments
 * that are present in the operator. To save memory, the argument helper
 * does not copy the operator def, so one would need to make sure that the
 * lifetime of the OperatorDef object outlives that of the ArgumentHelper.
 */
class ArgumentHelper {
 public:
  explicit ArgumentHelper(const OperatorDef& def);
  explicit ArgumentHelper(const NetDef& netdef);
  bool HasArgument(const string& name) const;

  template <typename T>
  T GetSingleArgument(const string& name, const T& default_value) const;
  template <typename T>
  bool HasSingleArgumentOfType(const string& name) const;
  template <typename T>
  vector<T> GetRepeatedArgument(
      const string& name,
      const std::vector<T>& default_value = std::vector<T>()) const;

  template <typename MessageType>
  MessageType GetMessageArgument(const string& name) const {
    CAFFE_ENFORCE(arg_map_.count(name), "Cannot find parameter named ", name);
    MessageType message;
    if (arg_map_.at(name)->has_s()) {
      CAFFE_ENFORCE(
          message.ParseFromString(arg_map_.at(name)->s()),
          "Faild to parse content from the string");
    } else {
      VLOG(1) << "Return empty message for parameter " << name;
    }
    return message;
  }

  template <typename MessageType>
  vector<MessageType> GetRepeatedMessageArgument(const string& name) const {
    CAFFE_ENFORCE(arg_map_.count(name), "Cannot find parameter named ", name);
    vector<MessageType> messages(arg_map_.at(name)->strings_size());
    for (int i = 0; i < messages.size(); ++i) {
      CAFFE_ENFORCE(
          messages[i].ParseFromString(arg_map_.at(name)->strings(i)),
          "Faild to parse content from the string");
    }
    return messages;
  }

 private:
  CaffeMap<string, const Argument*> arg_map_;
};

const Argument& GetArgument(const OperatorDef& def, const string& name);
bool GetFlagArgument(
    const OperatorDef& def,
    const string& name,
    bool def_value = false);

Argument* GetMutableArgument(
    const string& name,
    const bool create_if_missing,
    OperatorDef* def);

template <typename T>
Argument MakeArgument(const string& name, const T& value);

template <typename T>
inline void AddArgument(const string& name, const T& value, OperatorDef* def) {
  GetMutableArgument(name, true, def)->CopyFrom(MakeArgument(name, value));
}

}  // namespace caffe2

#endif  // CAFFE2_UTILS_PROTO_UTILS_H_


text:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class GUI extends JFrame {

	/**
	 *
	 */
	private static final long serialVersionUID = 6300871629154863889L;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new GUI(true);
	}

	JScrollPane scrollPane;
	JTextArea text;
	JTextField input_text;
	String input = "";
	JButton input_button;
	JPanel panel;
	boolean isFirst = true;

	public GUI(boolean run_gui) {
		this.setLocation(100, 100);
	    this.setResizable(false);
	    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    this.setLayout(null);

	    input_button = new JButton("Enter");
	    input_button.addActionListener(new Enter());
	    input_button.setSize(200, 40);
	    input_button.setLocation(220, 15);
	    this.add(input_button);

	    input_text = new JTextField("");
	    input_text.setSize(200, 20);
	    input_text.setLocation(10, 25);
	    this.add(input_text);

	    text = new JTextArea();
		scrollPane = new JScrollPane(text);
		scrollPane.setSize(480, 500);
		scrollPane.setLocation(10, 70);
		text.setEditable(true);
		this.add(scrollPane);

	    this.setSize(500, 600);
		if(run_gui)
			this.setVisible(true);
	}

	private class Enter implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if(!input_text.getText().equals("")) {
				input = input_text.getText();
				input_text.setText("");
			}
			else
				System.out.println(input_text.getText() + ", " + input);
		}

	}

	public void print(String str) {
		String temp = text.getText();
		if(isFirst) {
			text.setText(temp + str);
			isFirst = false;
		} else
			text.setText(str + "\n" + temp);
	}

	public String get_input() {
		return input;
	}

}


text:
package com.ajjpj.adiagram_.ui.fw

/**
 * @author arno
 */
trait Unbindable {
  def unbind ()    (implicit digest: Digest): Unit
}