text:
using System;
using System.Xml;
using System.Web.Caching;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

using System.Data;
using System.Web.UI;
using System.Collections;
using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Web;
using Umbraco.Web.Cache;
using umbraco.DataLayer;
using umbraco.BusinessLogic;
using Umbraco.Core.IO;
using System.Web;

namespace umbraco
{
    ///
    /// Holds methods for parsing and building umbraco templates
    ///
    [Obsolete("Do not use this class, use Umbraco.Core.Service.IFileService to work with templates")]
    public class template
    {
        #region private variables

        readonly StringBuilder _templateOutput = new StringBuilder();

        private string _templateDesign = "";
        int _masterTemplate = -1;
        private string _templateName = "";
        private string _templateAlias = "";

        #endregion

        #region public properties
        public String TemplateContent
        {
            set
            {
                _templateOutput.Append(value);
            }
            get
            {
                return _templateOutput.ToString();
            }
        }

        public int MasterTemplate
        {
            get { return _masterTemplate; }
        }

        //added fallback to the default template to avoid nasty .net errors.
        //This is referenced in /default.aspx.cs during page rendering.
        public string MasterPageFile
        {
            get
            {

                string file = TemplateAlias.Replace(" ", "") + ".master";
                string path = SystemDirectories.Masterpages + "/" + file;

                if (System.IO.File.Exists(IOHelper.MapPath(VirtualPathUtility.ToAbsolute(path))))
                    return path;
                else
                    return SystemDirectories.Umbraco + "/masterPages/default.master";
            }
        }

        //Support for template folders, if a alternative skin folder is requested
        //we will try to look for template files in another folder
        public string AlternateMasterPageFile(string templateFolder)
        {
            string file = TemplateAlias.Replace(" ", "") + ".master";
            string path = SystemDirectories.Masterpages + "/" + templateFolder + "/" + file;

            //if it doesn't exists then we return the normal file
            if (!System.IO.File.Exists(IOHelper.MapPath(VirtualPathUtility.ToAbsolute(path))))
            {

                string originalPath = IOHelper.MapPath(VirtualPathUtility.ToAbsolute(MasterPageFile));
                string copyPath = IOHelper.MapPath(VirtualPathUtility.ToAbsolute(path));

                string newFile;
                using (var fs = new FileStream(originalPath, FileMode.Open, FileAccess.ReadWrite))
                using (var f = new StreamReader(fs))
                {
                    newFile = f.ReadToEnd();
                }

                newFile = newFile.Replace("MasterPageFile=\"~/masterpages/", "MasterPageFile=\"");

                using (var fs = new FileStream(copyPath, FileMode.Create, FileAccess.Write))
                using (var replacement = new StreamWriter(fs))
                {
                    replacement.Write(newFile);
                }
            }

            return path;

        }

        public string TemplateAlias
        {
            get { return _templateAlias; }
        }
        #endregion

        #region public methods

        public override string ToString()
        {
            return this._templateName;
        }

        public Control ParseWithControls(page umbPage)
        {
            System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Start parsing");

            if (System.Web.HttpContext.Current.Items["macrosAdded"] == null)
                System.Web.HttpContext.Current.Items.Add("macrosAdded", 0);

            StringBuilder tempOutput = _templateOutput;

            Control pageLayout = new Control();
            Control pageHeader = new Control();
            Control pageFooter = new Control();
            Control pageContent = new Control();
            System.Web.UI.HtmlControls.HtmlForm pageForm = new System.Web.UI.HtmlControls.HtmlForm();
            System.Web.UI.HtmlControls.HtmlHead pageAspNetHead = new System.Web.UI.HtmlControls.HtmlHead();

            // Find header and footer of page if there is an aspnet-form on page
            if (_templateOutput.ToString().ToLower().IndexOf("<?aspnet_form>") > 0 ||
                _templateOutput.ToString().ToLower().IndexOf("<?aspnet_form disablescriptmanager=\"true\">") > 0)
            {
                pageForm.Attributes.Add("method", "post");
                pageForm.Attributes.Add("action", Convert.ToString(System.Web.HttpContext.Current.Items["VirtualUrl"]));

                // Find header and footer from tempOutput
                int aspnetFormTagBegin = tempOutput.ToString().ToLower().IndexOf("<?aspnet_form>");
                int aspnetFormTagLength = 14;
                int aspnetFormTagEnd = tempOutput.ToString().ToLower().IndexOf("</?aspnet_form>") + 15;

                // check if we should disable the script manager
                if (aspnetFormTagBegin == -1)
                {
                    aspnetFormTagBegin =
                        _templateOutput.ToString().ToLower().IndexOf("<?aspnet_form disablescriptmanager=\"true\">");
                    aspnetFormTagLength = 42;
                }
                else
                {
                    ScriptManager sm = new ScriptManager();
                    sm.ID = "umbracoScriptManager";
                    pageForm.Controls.Add(sm);
                }

                StringBuilder header = new StringBuilder(tempOutput.ToString().Substring(0, aspnetFormTagBegin));

                // Check if there's an asp.net head element in the header
                if (header.ToString().ToLower().Contains("<?aspnet_head>"))
                {
                    StringBuilder beforeHeader = new StringBuilder(header.ToString().Substring(0, header.ToString().ToLower().IndexOf("<?aspnet_head>")));
                    header.Remove(0, header.ToString().ToLower().IndexOf("<?aspnet_head>") + 14);
                    StringBuilder afterHeader = new StringBuilder(header.ToString().Substring(header.ToString().ToLower().IndexOf("</?aspnet_head>") + 15, header.Length - header.ToString().ToLower().IndexOf("</?aspnet_head>") - 15));
                    header.Remove(header.ToString().ToLower().IndexOf("</?aspnet_head>"), header.Length - header.ToString().ToLower().IndexOf("</?aspnet_head>"));

                    // Find the title from head
                    MatchCollection matches = Regex.Matches(header.ToString(), @"<title>(.*?)</title>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    if (matches.Count > 0)
                    {
                        StringBuilder titleText = new StringBuilder();
                        HtmlTextWriter titleTextTw = new HtmlTextWriter(new System.IO.StringWriter(titleText));
                        parseStringBuilder(new StringBuilder(matches[0].Groups[1].Value), umbPage).RenderControl(titleTextTw);
                        pageAspNetHead.Title = titleText.ToString();
                        header = new StringBuilder(header.ToString().Replace(matches[0].Value, ""));
                    }

                    pageAspNetHead.Controls.Add(parseStringBuilder(header, umbPage));
                    pageAspNetHead.ID = "head1";

                    // build the whole header part
                    pageHeader.Controls.Add(parseStringBuilder(beforeHeader, umbPage));
                    pageHeader.Controls.Add(pageAspNetHead);
                    pageHeader.Controls.Add(parseStringBuilder(afterHeader, umbPage));

                }
                else
                    pageHeader.Controls.Add(parseStringBuilder(header, umbPage));

                pageFooter.Controls.Add(parseStringBuilder(new StringBuilder(tempOutput.ToString().Substring(aspnetFormTagEnd, tempOutput.Length - aspnetFormTagEnd)), umbPage));
                tempOutput.Remove(0, aspnetFormTagBegin + aspnetFormTagLength);
                aspnetFormTagEnd = tempOutput.ToString().ToLower().IndexOf("</?aspnet_form>");
                tempOutput.Remove(aspnetFormTagEnd, tempOutput.Length - aspnetFormTagEnd);

                //throw new ArgumentException(tempOutput.ToString());
                pageForm.Controls.Add(parseStringBuilder(tempOutput, umbPage));

                pageContent.Controls.Add(pageHeader);
                pageContent.Controls.Add(pageForm);
                pageContent.Controls.Add(pageFooter);
                return pageContent;

            }
            else
                return parseStringBuilder(tempOutput, umbPage);

        }

        public Control parseStringBuilder(StringBuilder tempOutput, page umbPage)
        {

            Control pageContent = new Control();

            bool stop = false;
            bool debugMode = umbraco.presentation.UmbracoContext.Current.Request.IsDebug;

            while (!stop)
            {
                System.Web.HttpContext.Current.Trace.Write("template", "Begining of parsing rutine...");
                int tagIndex = tempOutput.ToString().ToLower().IndexOf("<?umbraco");
                if (tagIndex > -1)
                {
                    String tempElementContent = "";
                    pageContent.Controls.Add(new LiteralControl(tempOutput.ToString().Substring(0, tagIndex)));

                    tempOutput.Remove(0, tagIndex);

                    String tag = tempOutput.ToString().Substring(0, tempOutput.ToString().IndexOf(">") + 1);
                    Hashtable attributes = helper.ReturnAttributes(tag);

                    // Check whether it's a single tag (<?.../>) or a tag with children (<?..>...</?...>)
                    if (tag.Substring(tag.Length - 2, 1) != "/" && tag.IndexOf(" ") > -1)
                    {
                        String closingTag = "</" + (tag.Substring(1, tag.IndexOf(" ") - 1)) + ">";
                        // Tag with children are only used when a macro is inserted by the umbraco-editor, in the
                        // following format: "<?UMBRACO_MACRO ...></?UMBRACO_MACRO>", so we
                        // need to delete extra information inserted which is the image-tag and the closing
                        // umbraco_macro tag
                        if (tempOutput.ToString().IndexOf(closingTag) > -1)
                        {
                            tempOutput.Remove(0, tempOutput.ToString().IndexOf(closingTag));
                        }
                    }

                    System.Web.HttpContext.Current.Trace.Write("umbTemplate", "Outputting item: " + tag);

                    // Handle umbraco macro tags
                    if (tag.ToString().ToLower().IndexOf("umbraco_macro") > -1)
                    {
                        if (debugMode)
                            pageContent.Controls.Add(new LiteralControl("
"));

                        // NH: Switching to custom controls for macros
                        if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages)
                        {
                            umbraco.presentation.templateControls.Macro macroControl = new umbraco.presentation.templateControls.Macro();
                            macroControl.Alias = helper.FindAttribute(attributes, "macroalias");
                            IDictionaryEnumerator ide = attributes.GetEnumerator();
                            while (ide.MoveNext())
                                if (macroControl.Attributes[ide.Key.ToString()] == null)
                                    macroControl.Attributes.Add(ide.Key.ToString(), ide.Value.ToString());
                            pageContent.Controls.Add(macroControl);
                        }
                        else
                        {
                            macro tempMacro;
                            String macroID = helper.FindAttribute(attributes, "macroid");
                            if (macroID != String.Empty)
                                tempMacro = getMacro(macroID);
                            else
                                tempMacro = macro.GetMacro(helper.FindAttribute(attributes, "macroalias"));

                            if (tempMacro != null)
                            {

                                try
                                {
                                    Control c = tempMacro.renderMacro(attributes, umbPage.Elements, umbPage.PageID);
                                    if (c != null)
                                        pageContent.Controls.Add(c);
                                    else
                                        System.Web.HttpContext.Current.Trace.Warn("Template", "Result of macro " + tempMacro.Name + " is null");

                                }
                                catch (Exception e)
                                {
                                    System.Web.HttpContext.Current.Trace.Warn("Template", "Error adding macro " + tempMacro.Name, e);
                                }
                            }
                        }
                        if (debugMode)
                            pageContent.Controls.Add(new LiteralControl("
"));
                    }
                    else
                    {
                        if (tag.ToLower().IndexOf("umbraco_getitem") > -1)
                        {

                            // NH: Switching to custom controls for items
                            if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages)
                            {
                                umbraco.presentation.templateControls.Item itemControl = new umbraco.presentation.templateControls.Item();
                                itemControl.Field = helper.FindAttribute(attributes, "field");
                                IDictionaryEnumerator ide = attributes.GetEnumerator();
                                while (ide.MoveNext())
                                    if (itemControl.Attributes[ide.Key.ToString()] == null)
                                        itemControl.Attributes.Add(ide.Key.ToString(), ide.Value.ToString());
                                pageContent.Controls.Add(itemControl);
                            }
                            else
                            {
                                try
                                {
                                    if (helper.FindAttribute(attributes, "nodeId") != "" && int.Parse(helper.FindAttribute(attributes, "nodeId")) != 0)
                                    {
                                        cms.businesslogic.Content c = new umbraco.cms.businesslogic.Content(int.Parse(helper.FindAttribute(attributes, "nodeId")));
                                        item umbItem = new item(c.getProperty(helper.FindAttribute(attributes, "field")).Value.ToString(), attributes);
                                        tempElementContent = umbItem.FieldContent;

                                        // Check if the content is published
                                        if (c.nodeObjectType == cms.businesslogic.web.Document._objectType)
                                        {
                                            try
                                            {
                                                cms.businesslogic.web.Document d = (cms.businesslogic.web.Document)c;
                                                if (!d.Published)
                                                    tempElementContent = "";
                                            }
                                            catch { }
                                        }

                                    }
                                    else
                                    {
                                        // NH adds Live Editing test stuff
                                        item umbItem = new item(umbPage.Elements, attributes);
                                        //								item umbItem = new item(umbPage.PageElements[helper.FindAttribute(attributes, "field")].ToString(), attributes);
                                        tempElementContent = umbItem.FieldContent;
                                    }

                                    if (debugMode)
                                        tempElementContent =
                                            "
" + tempElementContent + "
";
                                }
                                catch (Exception e)
                                {
                                    System.Web.HttpContext.Current.Trace.Warn("umbracoTemplate", "Error reading element (" + helper.FindAttribute(attributes, "field") + ")", e);
                                }
                            }
                        }
                    }
                    tempOutput.Remove(0, tempOutput.ToString().IndexOf(">") + 1);
                    tempOutput.Insert(0, tempElementContent);
                }
                else
                {
                    pageContent.Controls.Add(new LiteralControl(tempOutput.ToString()));
                    break;
                }

            }

            return pageContent;

        }

		[Obsolete("Use Umbraco.Web.Templates.TemplateUtilities.ParseInternalLinks instead")]
        public static string ParseInternalLinks(string pageContents)
		{
			return Umbraco.Web.Templates.TemplateUtilities.ParseInternalLinks(pageContents);
		}

        ///
        /// Parses the content of the templateOutput stringbuilder, and matches any tags given in the
        /// XML-file /umbraco/config/umbracoTemplateTags.xml.
        /// Replaces the found tags in the StringBuilder object, with "real content"
        ///
        /// <param name="umbPage"></param>
        public void Parse(page umbPage)
        {
            System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Start parsing");

            // First parse for known umbraco tags
            // <?UMBRACO_MACRO/> - macros
            // <?UMBRACO_GETITEM/> - print item from page, level, or recursive
            MatchCollection tags = Regex.Matches(_templateOutput.ToString(), "<\\?UMBRACO_MACRO[^>]*/>|<\\?UMBRACO_GETITEM[^>]*/>|<\\?(?<tagName>[\\S]*)[^>]*/>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            foreach (Match tag in tags)
            {
                Hashtable attributes = helper.ReturnAttributes(tag.Value.ToString());

                if (tag.ToString().ToLower().IndexOf("umbraco_macro") > -1)
                {
                    String macroID = helper.FindAttribute(attributes, "macroid");
                    if (macroID != "")
                    {
                        macro tempMacro = getMacro(macroID);
                        _templateOutput.Replace(tag.Value.ToString(), tempMacro.MacroContent.ToString());
                    }
                }
                else
                {
                    if (tag.ToString().ToLower().IndexOf("umbraco_getitem") > -1)
                    {
                        try
                        {
                            String tempElementContent = umbPage.Elements[helper.FindAttribute(attributes, "field")].ToString();
                            MatchCollection tempMacros = Regex.Matches(tempElementContent, "<\\?UMBRACO_MACRO(?<attributes>[^>]*)>]*><\\/\\?UMBRACO_MACRO>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
                            foreach (Match tempMacro in tempMacros)
                            {
                                Hashtable tempAttributes = helper.ReturnAttributes(tempMacro.Groups["attributes"].Value.ToString());
                                String macroID = helper.FindAttribute(tempAttributes, "macroid");
                                if (Convert.ToInt32(macroID) > 0)
                                {
                                    macro tempContentMacro = getMacro(macroID);
                                    _templateOutput.Replace(tag.Value.ToString(), tempContentMacro.MacroContent.ToString());
                                }

                            }

                            _templateOutput.Replace(tag.Value.ToString(), tempElementContent);
                        }
                        catch (Exception e)
                        {
                            System.Web.HttpContext.Current.Trace.Warn("umbracoTemplate", "Error reading element (" + helper.FindAttribute(attributes, "field") + ")", e);
                        }
                    }
                }
            }

            System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Done parsing");
        }

        #endregion

        #region private methods

        private macro getMacro(String macroID)
        {
            System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Starting macro (" + macroID.ToString() + ")");
            return macro.GetMacro(Convert.ToInt16(macroID));
        }

        private String FindAttribute(Hashtable attributes, String key)
        {
            if (attributes[key] != null)
                return attributes[key].ToString();
            else
                return "";
        }

        #endregion
        ///
        /// Unused, please do not use
        ///
        [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
        protected static ISqlHelper SqlHelper
        {
            get { return Application.SqlHelper; }
        }
        #region constructors

        public static string GetMasterPageName(int templateID)
        {
            return GetMasterPageName(templateID, null);
        }

        public static string GetMasterPageName(int templateID, string templateFolder)
        {
            var t = new template(templateID);

            return !string.IsNullOrEmpty(templateFolder)
                ? t.AlternateMasterPageFile(templateFolder)
                : t.MasterPageFile;
        }

        public template(int templateID)
        {
            var tId = templateID;

            var t = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<template>(
               string.Format("{0}{1}", CacheKeys.TemplateFrontEndCacheKey, tId), () =>
               {
                   using (var sqlHelper = Application.SqlHelper)
                   using (var templateData = sqlHelper.ExecuteReader(@"select nodeId, alias, node.parentID as master, text, design
from cmsTemplate
inner join umbracoNode node on (node.id = cmsTemplate.nodeId)
where nodeId = @templateID",
                           sqlHelper.CreateParameter("@templateID", templateID)))
                    {
                       if (templateData.Read())
                       {
                           // Get template master and replace content where the template
                           if (!templateData.IsNull("master"))
                               _masterTemplate = templateData.GetInt("master");
                           if (!templateData.IsNull("alias"))
                               _templateAlias = templateData.GetString("alias");
                           if (!templateData.IsNull("text"))
                               _templateName = templateData.GetString("text");
                           if (!templateData.IsNull("design"))
                               _templateDesign = templateData.GetString("design");
                       }
                    }
                   return this;
               });

            if (t == null)
                throw new InvalidOperationException("Could not find a tempalte with id " + templateID);

            this._masterTemplate = t._masterTemplate;
            this._templateAlias = t._templateAlias;
            this._templateDesign = t._templateDesign;
            this._masterTemplate = t._masterTemplate;
            this._templateName = t._templateName;

            // Only check for master on legacy templates - can show error when using master pages.
            if (!UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages)
            {
                checkForMaster(tId);
            }

        }

        private void checkForMaster(int templateID) {
            // Get template design
            if (_masterTemplate != 0 && _masterTemplate != templateID) {
                template masterTemplateDesign = new template(_masterTemplate);
                if (masterTemplateDesign.TemplateContent.IndexOf("<?UMBRACO_TEMPLATE_LOAD_CHILD/>") > -1
                    || masterTemplateDesign.TemplateContent.IndexOf("<?UMBRACO_TEMPLATE_LOAD_CHILD />") > -1) {
                    _templateOutput.Append(
                        masterTemplateDesign.TemplateContent.Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD/>",
                        _templateDesign).Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD />", _templateDesign)
                        );
                } else
                    _templateOutput.Append(_templateDesign);
            } else {
                if (_masterTemplate == templateID)
                {
                    cms.businesslogic.template.Template t = cms.businesslogic.template.Template.GetTemplate(templateID);
                    string templateName = (t != null) ? t.Text : string.Format("'Template with id: '{0}", templateID);
                    System.Web.HttpContext.Current.Trace.Warn("template",
                        String.Format("Master template is the same as the current template. It would cause an endless loop! Make sure that the current template '{0}' has another Master Template than itself. You can change this in the template editor under 'Settings'", templateName));
                    _templateOutput.Append(_templateDesign);
                }
            }
        }

        [Obsolete("Use ApplicationContext.Current.ApplicationCache.ClearCacheForTemplate instead")]
        public static void ClearCachedTemplate(int templateID)
        {
            DistributedCache.Instance.RefreshTemplateCache(templateID);
        }

        public template(String templateContent)
        {
            _templateOutput.Append(templateContent);
            _masterTemplate = 0;
        }

        #endregion
    }

}


text:
package net.addictivesoftware.deploymentagent

class InfoActor extends ComposableActor {
  private final def address:String = java.net.InetAddress.getLocalHost.toString
  private final val version = "1.0"

  receiveBuilder += {
    case RequestInfo => {
      sender ! Info("name", address, version)
    }
    case Info(name, address, version) => {
      log.info("{} at {} has version {}", name, address, version)
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace entitySys
{
    ///////////////////////////////////////
    // Entity: class global vars/functions
    /////////////////////////////////////

    // Entity unique ID counter
    unsigned int entity::uidCtr = 0;

    // Entities
    std::vector<entity*> entity::entVec;

    // Add to entVec for automatic processing of events.
    entity* const entity::sysAdd( entity* const entPtr ) {
        entVec.push_back( entPtr );
        return entPtr;
    }

    // Remove from entVec.
    void entity :: sysRemove( const entity* const entPtr ) {
        for (auto iter=entVec.begin(); iter!=entVec.end(); iter++) {
            if (*iter == entPtr) {
                entVec.erase( iter );
                return;
            }
        }
    }

    // Do game logic stuff for each entity.
    void entity::generateStepEvents()  {
        for (size_t i=0; i<entVec.size(); i++)
            entVec[i]->evStep();
    }

    // Test for collisions and respond to them.
    void entity::generateCollisionEvents() {
        // Loop through all possible unique pairings of entities.
        for (size_t iRef=0;      iRef<entVec.size(); iRef++)
        for (size_t iCom=iRef+1; iCom<entVec.size(); iCom++) {
            entity* const entRef = entVec[ iRef ];
            entity* const entCom = entVec[ iCom ];

            // Don't generate collisions for pairs where one ent has collisions disabled.
            if (entRef->collideEnable == false
            ||  entCom->collideEnable == false)
                continue;

            // Test for spherical overlap.
            const float radiusSum = entRef->radius  +  entCom->radius;
            const float dist      = distance( entRef->pos, entCom->pos );

            if (dist <= radiusSum) {
                // Synchronously generate the collision event pair.
                entRef->evCollide( entCom );
                entCom->evCollide( entRef );
            }
        }
    }

    // Draw each entity.
    void entity::generateDrawEvents()  {
        for (size_t i=0; i<entVec.size(); i++)
            entVec[i]->evDraw();
    }

    ///////////////////////////////////////
    // Entity: instance local functions
    /////////////////////////////////////

    // collide, step and draw are pure virtual functions and so don't have a body.
    // Derived entity types must implement these, entity can't be instanciated by itself.

    // Construct
    entity::entity() {
        // Initialise to defaults
        this->uid           = uidCtr++;
        this->collideEnable = true;
        this->radius        = 32.0f;
        this->pos           = 0.0f;
        this->scale         = 1.0f;

        // Add to event handling etc
        sysAdd( this );
    }

    // Destruct
    entity::~entity() {
        sysRemove( this );
    }

};


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

<title>com.wdullaer.materialdatetimepicker (library API)</title>
<meta name="date" content="2019-08-30">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

com.wdullaer.materialdatetimepicker

Interfaces

GravitySnapHelper.SnapListener

Classes

AccessibleLinearLayout

AccessibleTextView

GravitySnapHelper

HapticFeedbackController

Utils

VerticalTextView


text:
<?php

namespace Kunstmaan\UserManagementBundle;

use Kunstmaan\UserManagementBundle\DependencyInjection\Compiler\DeprecateClassParametersPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class KunstmaanUserManagementBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new DeprecateClassParametersPass());
    }
}


text:
using log4net;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using TabMon.Counters;
using TabMon.Counters.MBean;
using TabMon.Helpers;

namespace TabMon.CounterConfig
{
    /// <summary>
    /// Handles parsing & loading the MBean counters defined within a Counters.config file.
    /// </summary>
    internal sealed class MBeanCounterConfigReader : ICounterConfigReader
    {
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Parses & loads a set of MBean counters for the given host using the XML tree.
        /// </summary>
        /// <param name="root">The root MBean counters config node.</param>
        /// <param name="host">The host to load counters for.</param>
        /// <param name="lifeCycleTypeToLoad">A filter that indicates whether ephemeral or persistent counters should be loaded.</param>
        /// <returns>Collection of MBean counters specified in the root node's config.</returns>
        public ICollection<ICounter> LoadCounters(XmlNode root, Host host, CounterLifecycleType lifeCycleTypeToLoad)
        {
            var counters = new List<ICounter>();

            // We currently don't support ephemeral counters for MBeans, so just short circuit out in this case.
            if (lifeCycleTypeToLoad == CounterLifecycleType.Ephemeral)
            {
                return counters;
            }

            var sourceNodes = root.SelectNodes("./Source");
            if (sourceNodes != null)
            {
                foreach (XmlNode sourceNode in sourceNodes)
                {
                    ICollection<IMBeanClient> mbeanClientPool = null;
                    if (!host.SpecifyPorts)
                    {
                        var startPort = Convert.ToInt32(sourceNode.Attributes["startport"].Value);
                        var endPort = Convert.ToInt32(sourceNode.Attributes["endport"].Value);

                        // Retrieve a collection of all available clients within the specified port range, then new up counters using those.
                        // This way, multiple counters can share a single client & connection.
                        mbeanClientPool = MBeanClientFactory.CreateClients(host.Address, startPort, endPort);
                    }
                    else
                    {
                        var processName = sourceNode.Attributes["name"].Value;
                        if (host.Processes.ContainsKey(processName))
                        {
                            var ports = host.Processes[processName];

                            // Retrieve a collection of all available clients within the specified port range, then new up counters using those.
                            // This way, multiple counters can share a single client & connection.
                            mbeanClientPool = MBeanClientFactory.CreateClients(host.Address, ports);
                        }
                        else
                        {
                            Log.DebugFormat("Process \"{0}\" is not contained in host section. Continuing..", processName);
                        }
                    }

                    if (mbeanClientPool != null)
                    {
                        foreach (var mbeanClient in mbeanClientPool)
                        {
                            var countersForSource = BuildCountersForSourceNode(sourceNode, host, mbeanClient);
                            counters.AddRange(countersForSource);
                        }
                    }
                }
            }

            return counters;
        }

        /// <summary>
        /// Builds a collection of ICounter instances from a source XML node.
        /// </summary>
        private List<ICounter> BuildCountersForSourceNode(XmlNode sourceNode, Host host, IMBeanClient mbeanClient)
        {
            string sourceName = sourceNode.Attributes["name"].Value;
            var counterNodesForSource = sourceNode.SelectNodes(".//Counter");
            var counters = new List<ICounter>();

            if (counterNodesForSource != null)
            {
                foreach (XmlNode counterNode in counterNodesForSource)
                {
                    var counter = BuildCounterFromCounterNode(counterNode, mbeanClient, host, sourceName);
                    if (counter != null)
                    {
                        counters.Add(counter);
                    }
                }
            }

            return counters;
        }

        /// <summary>
        /// Builds an ICounter instance from a counter XML node and a set of properties.
        /// </summary>
        private static ICounter BuildCounterFromCounterNode(XmlNode counterNode, IMBeanClient mbeanClient, Host host, string sourceName)
        {
            var counterName = counterNode.Attributes["name"].Value;
            var categoryName = counterNode.ParentNode.Attributes["name"].Value;
            var path = counterNode.ParentNode.Attributes["path"].Value;

            string unitOfMeasurement = null;
            if (counterNode.Attributes.GetNamedItem("unit") != null)
            {
                unitOfMeasurement = counterNode.Attributes["unit"].Value;
            }

            var instanceName = BuildInstanceName(sourceName, mbeanClient.InstanceNumber);

            var rootCounterTypeNode = counterNode.ParentNode.ParentNode;
            var counterType = rootCounterTypeNode.Name.ToLower();

            string subDomain = null;
            if (rootCounterTypeNode.Attributes != null && rootCounterTypeNode.Attributes["subdomain"] != null)
            {
                subDomain = rootCounterTypeNode.Attributes["subdomain"].Value;
            }

            // Create the counter.
            try
            {
                var builder = new MBeanBuilder();
                return builder.CreateCounter(host)
                              .UsingClient(mbeanClient)
                              .WithSourceName(sourceName)
                              .WithSubDomain(subDomain)
                              .WithPath(path)
                              .WithCategoryName(categoryName)
                              .WithCounterName(counterName)
                              .WithInstanceName(instanceName)
                              .WithUnit(unitOfMeasurement)
                              .Build(counterType);
            }
            catch (Exception ex)
            {
                Log.DebugFormat(@"Failed to register MBean counter {0}\{1}\{2}\{3}\{4}: {5}",
                                host.Address, sourceName, categoryName, counterName, instanceName, ex.Message);
                return null;
            }
        }

        /// <summary>
        /// Builds the instance name to match what Perfmon does (i.e. a machine with two dataserver processes will have instance names "dataserver" & "dataserver#1".
        /// </summary>
        private static string BuildInstanceName(string sourceName, int instanceNumber)
        {
            if (instanceNumber == 0)
            {
                return sourceName;
            }

            return String.Format("{0}#{1}", sourceName, instanceNumber);
        }
    }
}


text:
//
//  GJCFImageBrowserScrollView.m
//  GJCommonFoundation
//
//  Created by ZYVincent on 14-10-30.
//  Copyright (c) 2014年 ZYProSoft. All rights reserved.
//

#import "GJCUImageBrowserScrollView.h"
#import "GJCUImageBrowserConstans.h"
#import "GJCUImageBrowserModel.h"
#import "GJCFUitils.h"
#import "UIView+GJCFViewFrameUitil.h"

@interface GJCUImageBrowserScrollView()<UIScrollViewDelegate>

@property (nonatomic,assign)CGSize imageSize;

@property (nonatomic,strong)UIActivityIndicatorView *indicatorView;

@end

@implementation GJCUImageBrowserScrollView
- (id)init
{
    if (self = [super init]) {

        self.showsVerticalScrollIndicator   = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.bouncesZoom                    = YES;
        self.decelerationRate               = UIScrollViewDecelerationRateFast;
        self.delegate = self;

        /* 观察下载任务 */
        [self observeDownloadTask];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        self.showsVerticalScrollIndicator   = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.bouncesZoom                    = YES;
        self.decelerationRate               = UIScrollViewDecelerationRateFast;
        self.delegate = self;

        /* 观察下载任务 */
        [self observeDownloadTask];

    }
    return self;
}

- (void)dealloc
{
    [GJCFNotificationCenter removeObserver:self];
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    // 当图片缩小的时候,让图片在中间
    CGSize boundsSize       = self.bounds.size;
    CGRect frameToCenter    = self.contentImageView.frame;

    // 水平设置中间
    if (frameToCenter.size.width < boundsSize.width)
        frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
    else
        frameToCenter.origin.x = 0;

    // 垂直设置中间
    if (frameToCenter.size.height < boundsSize.height)
        frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
    else
        frameToCenter.origin.y = 0;

    self.contentImageView.frame    = frameToCenter;
}

- (void)setIndex:(NSInteger)index
{
    _index = index;

    [self displayImageAtIndex:index];

}

- (void)displayImageAtIndex:(NSInteger)index
{
    if ([self.dataSource respondsToSelector:@selector(imageModelAtIndex:)])
    {
        // 获取Asset
        GJCUImageBrowserModel *imageModel = [self.dataSource imageModelAtIndex:index];
        NSLog(@"GJCFImageBrowserScrollView image file path:%@",imageModel.filePath);

        UIImage *image = nil;
        self.contentImageView.image = nil;

        /* 支持预览ALAsset对象 */
        if (imageModel.isPreviewAsset) {
            if (imageModel.contentAsset) {
                image = [UIImage imageWithCGImage:[[imageModel.contentAsset defaultRepresentation] fullScreenImage]];
            }
            if (imageModel.gjcfAsset) {
                image = imageModel.gjcfAsset.fullScreenImage;
            }
        }else{
            if (imageModel.filePath) {
                image = GJCFQuickImageByFilePath(imageModel.filePath);
            }
        }

        // 恢复默认的缩放
        self.zoomScale = 1.0;

        // 重新设置图片
        if (!self.contentImageView) {

            if (imageModel.thumbImage) {
                self.contentImageView = [[UIImageView alloc]initWithImage:imageModel.thumbImage];
            }else{
                self.contentImageView = [[UIImageView alloc]initWithFrame:(CGRect){0,0,self.gjcf_width,self.gjcf_height}];
            }

        }
        if (!self.indicatorView) {
            self.indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
            self.indicatorView.center = self.center;
            self.indicatorView.hidden = YES;
            [self addSubview:self.indicatorView];
        }
        if (image) {
            self.contentImageView.image = image;
            [self.indicatorView stopAnimating];
            self.indicatorView.hidden = YES;
        }else{
            self.contentImageView.image = imageModel.thumbImage;
        }
        [self autoAdjustContentImageView];

        self.contentImageView.userInteractionEnabled = YES;

        self.contentImageView.isAccessibilityElement   = YES;
        self.contentImageView.accessibilityTraits      = UIAccessibilityTraitImage;
        self.contentImageView.tag                      = 1;

        //添加点击事件
        UITapGestureRecognizer *tapR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapOnView)];
        [self.contentImageView addGestureRecognizer:tapR];

        [self addSubview:self.contentImageView];

        [self configureWithContentModel];

    }
}

#pragma mark - 观察下载任务完成情况
- (void)observeDownloadTask
{
    [GJCFNotificationCenter addObserver:self selector:@selector(observeDownloadFinished:) name:GJCUImageBrowserViewControllerDidFinishDownloadTaskNoti object:nil];
    [GJCFNotificationCenter addObserver:self selector:@selector(observeDownloadFaild:) name:GJCUImageBrowserViewControllerDidFaildDownloadTaskNoti object:nil];
    [GJCFNotificationCenter addObserver:self selector:@selector(observeBeginDownload:) name:GJCUImageBrowserViewControllerDidBeginDownloadTaskNoti object:nil];
}

- (void)observeBeginDownload:(NSNotification *)noti
{
    NSInteger index = [noti.object intValue];
    if (index == self.index) {

        GJCFAsyncMainQueue(^{

            self.indicatorView.hidden = NO;
            [self.indicatorView startAnimating];

        });

    }
}

- (void)observeDownloadFinished:(NSNotification *)noti
{
    NSLog(@"GJCFImageBrowserScrollView recieve image finish download :%@",noti.object);
    NSInteger index = [noti.object intValue];
    if (index == self.index) {

        GJCFAsyncMainQueue(^{

            [self.indicatorView stopAnimating];
            self.indicatorView.hidden = YES;

            GJCUImageBrowserModel *imageModel = [self.dataSource imageModelAtIndex:self.index];
            self.contentImageView.image = GJCFQuickImageByFilePath(imageModel.filePath);
            [self autoAdjustContentImageView];
            [self configureWithContentModel];
            [self setNeedsLayout];

        });

    }
}

- (void)observeDownloadFaild:(NSNotification *)noti
{
    NSInteger index = [noti.object intValue];
    if (index == self.index) {

        GJCFAsyncMainQueue(^{

            [self.indicatorView stopAnimating];
            self.indicatorView.hidden = YES;

        });
    }
}

- (void)autoAdjustContentImageView
{
    if (self.contentImageView.image) {

        CGFloat widthScale = 1.0;
        CGFloat heightScale = 1.0;

        CGSize contentImageSize = self.contentImageView.image.size;
        NSLog(@"contentImageSize:%@",NSStringFromCGSize(contentImageSize));

        if (contentImageSize.width > GJCFSystemScreenWidth) {
            widthScale = GJCFSystemScreenWidth/self.contentImageView.image.size.width;
        }

        if (contentImageSize.height > GJCFSystemScreenHeight) {
            heightScale = GJCFSystemScreenHeight/self.contentImageView.image.size.height;
        }

        CGFloat scaleSize = MIN(widthScale, heightScale);
        CGFloat contentImgViewWidth = contentImageSize.width * scaleSize;
        CGFloat contentImgViewHeight = contentImageSize.height * scaleSize;

        NSLog(@"contentImagWidth:%f contentImageHeight:%f",contentImgViewWidth,contentImgViewHeight);

        self.contentImageView.gjcf_width = contentImgViewWidth;
        self.contentImageView.gjcf_height = contentImgViewHeight;

        [self setNeedsLayout];

        NSLog(@"cotnenImgView frame:%@",NSStringFromCGRect(self.contentImageView.frame));
    }
}

- (void)configureWithContentModel
{
    GJCUImageBrowserModel *imageModel = [self.dataSource imageModelAtIndex:self.index];

    NSLog(@"GJCFImageBrowserScrollView imageSize:%@",NSStringFromCGSize(imageModel.imageSize));

    [self autoAdjustContentImageView];

    if (CGSizeEqualToSize(imageModel.imageSize, CGSizeZero)) {
        self.imageSize = self.gjcf_size;
    }else{
        self.imageSize = imageModel.imageSize;
    }

    self.contentSize = self.imageSize;

    [self fitZoomScaleSize];
}

- (void)fitZoomScaleSize
{
    CGSize boundsSize = self.bounds.size;
    if (self.contentImageView.image) {
        boundsSize = self.contentImageView.image.size;
    }

    CGFloat xScale = boundsSize.width  / self.imageSize.width;    // 最佳缩放宽的倍数
    CGFloat yScale = boundsSize.height / self.imageSize.height;   // 最佳缩放高的倍数

    CGFloat minScale = MIN(xScale, yScale);
    CGFloat maxScale = 2.0 * minScale;

    self.minimumZoomScale = minScale;
    self.maximumZoomScale = maxScale;

    self.zoomScale      = self.minimumZoomScale;
}

//点击发送通知,让预览视图是否隐藏navigationBar和工具条
- (void)tapOnView
{
    GJCFNotificationPost(GJCUImageBrowserItemViewControllerDidTapNoti);
}

#pragma mark - 需要放大的视图
- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.contentImageView;
}

@end


text:
<?php

declare(strict_types=1);

namespace Valkyrja\Auth\Policies;

use Valkyrja\Auth\EntityPolicy as Contract;
use Valkyrja\Auth\Repository;
use Valkyrja\ORM\Entity;

/**
 * Abstract Class EntityPolicy.
 *
 * @author Melech Mizrachi
 */
abstract class EntityPolicy extends Policy implements Contract
{
    /**
     * The entity class name.
     *
     * @var string
     */
    protected static string $entityClassName;

    /**
     * The entity.
     *
     * @var Entity
     */
    protected Entity $entity;

    /**
     * Policy constructor.
     *
     * @param Repository $repository The repository
     * @param Entity     $entity     The entity
     */
    public function __construct(Repository $repository, Entity $entity)
    {
        parent::__construct($repository);

        $this->entity = $entity;
    }

    /**
     * @inheritDoc
     */
    public static function getEntityClassName(): string
    {
        return static::$entityClassName;
    }
}


text:
//
//  NSDocument+DTFoundation.h
//  DTFoundation
//
//  Created by Oliver Drobnik on 10/1/12.
//  Copyright (c) 2012 Cocoanetics. All rights reserved.
//

#import <Availability.h>
#import <TargetConditionals.h>

#if TARGET_OS_OSX

#import <AppKit/AppKit.h>

/**
 Utility Methods for working with `NSDocument` instances.
 */

@interface NSDocument (DTFoundation)

/**
 Finds the current window controller showing the main document

 At present this always returns the window controller at index 0.
 @returns mainDocumentWindowController The main document window controller
 */
- (NSWindowController *)mainDocumentWindowController;

@end

#endif


text:
<!doctype html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<title>Aplicações web modernas com JHipster</title>

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

		<link rel="stylesheet" href="lib/css/zenburn.css">

		<link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-theme.min.css">

        <link rel="stylesheet" href="css/presentation.css">

Aplicações Web Modernas com JHipster

						http://josenaldo.github.io/palestra-jhipster

Quem sou?

Josenaldo de Oliveira Matos Filho

Jugleader no
                        UaiJUG

Arquiteto de Software do
                        comdominiodigital.com.br

Quem somos?

Grupo de usuários Java do Triângulo Mineiro

Java pra Web na Arca de Noé

						EJB ou Spring

						Templates (JSP, JSF, XDoclet, Velocity, Tiles, Thymeleaf)

						HTML + CSS + JS + JQuery

Aplicações web modernas

						Usuários estão mais exigentes. Não querem sites lentos e estáticos. Eles querem:

Sites bonitos

Não precisar carregar páginas a cada ação

Carregar pedaços da página dinamicamente

						Precisamos usar as últimas tecnologias HTML, CSS e JS

Produtividade para desenvolvedores

						Websites devem ser desenvolvidos rapidamente

						Esperar 1 minuto para fazer um simples deploy não é mais aceitável

						Precisamos das ferramentas certas para o trabalho

Sistemas pronto para produção

						Sites que devem aguentar milhares de usuários

						Diversos clientes acessando o backend através de REST

						Precisamos de servidores parrudos, escaláveis e de alta performance

Como resolver esses problemas

Fronteend com HTML/CSS/Javascript

Backend robusto com últimas tecnologias de Java, caching e acesso a dados

Tudo configurado automaticamente, com performance em mente

Ferramentas adequadas para otimizar o desenvolvimento

Client-side technologies

YEOMAN, GULP, BOWER, ANGULARJS, BOOTSTRAP

Yeoman

Geração de esqueleto de aplicação

Centenas de geradores disponíveis

A maioria é orientado a aplicaçoes frontend javascript

Os melhor avaliados são de ótima qualidade

yo jhipster

Gulp

Automação de tarefas com JavaScript

No desenvolvimento, ele permite o "live reloading", roda tests em background...

Para produção, comprime e otimiza recursos, compila sass, atualiza referências...

gulp test

Bower

Gerenciador de dependências javascript

Permite buscar, instalar e atualizar bibliotecas javascript

Milhares de bibliotecas

bower install angular

Karma

Execução de testes unitários no javascript

Funciona com Phantom.js, um navegador sem UI

É muito rápido, e pode rodar continuamente em background

karma start src/test/javascript/karma.conf.js

AngularJS

O framework MVVM mais popular no frontend

Poderoso & fácil de aprender

Data binding, form validation, i18n... tudo out of the box

<input type="text" ng-model="yourName" placeholder="Enter a name here">
<h1>Hello {{yourName}}!</h1>

Twitter Bootstrap

Framework CSS/JavaScript para Web apps responsivas

CSS e elementos HTML para os casos mais comuns

Um montão de componentes: menus, navbars, drop-down, alertas, formulários...

Qualquer programador faz algo bonito com o Bootstrap

<div class="alert alert-success">
	<strong>Hello, world!</strong>
</div>

Server-side technologies

MAVEN, SPRING, SPRING MVC REST, SPRING DATA JPA, NETFLIX OSS

Maven | Gradle

Build e gestão de dependência

Estrutura de diretórios e tarefas padronizados

Integração com as maiores IDEs

Ecossistema de plugins rico e maduro

./mvnw spring-boot:run

./gradlew bootRun

Spring Boot

Padrão de-facto para criação de Java apps

IoC, AOP e diversas abstrações pra facilitar o desenvolvimento

Rápidi, leve e extremamente poderoso

Configuração por convenção com Spring Boot

@Service
@Transactional
public class UserService {

	@Inject
	private UserRepository userRepository;

}

Liquibase

Evolução do banco de dados

Evolução do banco scriptada e reprodutível

Funciona bem com Spring e JPA

Exige bom entendimento de banco de dados e ORM

JPA

Mapeamento Objeto Relacional padrão para Java

Hibernate é a implementação escolhida

Framework completo de acesso a dados

Complexo para noobs

@Entity
public class User implements Serializable {

	@Id
	private String login;

}

Spring Data JPA

Adds extra syntaxic sugar on top of JPA

Generates your JPA repositories automatically

Removes a lot of boilerplate code

public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {

List<PersistentAuditEvent>
    findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);

}

MongoDB

Escalabilidade com NOSQL

Alternativa aos bancos relacionais e ao JPA

Similaridade: Spring Data MongoDB parecido com Spring Data JPA

Escalável e fácil de usar

Cassandra

Escalabilidade com NOSQL

2a. Alternativa aos bancos relacionais e ao JPA

Escalabilidade Linear e alta disponibilidade

Performance extrema e baixa latência para aplicações de missão crítica

Caching

Caching é sinônimo de performance

Ehcache é a soliução mais usada

HazelCast é a alternativa para cache clusterizado

Hibernate 2nd level cache ou Spring Caching

@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User implements Serializable {

}

Spring Security

Segurança à prova de balas

Framework líder de mercado, usado em todo tipo de aplicação

Segurança aplicada a URLs e a código Java (Spring Beans)

Trabalha com arquiteturas stateful (cookies) e stateless (OAuth2/JWT)

Spring MVC REST

O melhor framework REST em Java

Solução completa de alta performance para REST

Fácil de usar com Spring, fácil de testar

@RestController
public class AccountResource {
	@RequestMapping(value = "/app/rest/account",
		method = RequestMethod.POST)
	public void saveAccount(@RequestBody UserDTO userDTO) {
	    userService.updateUserInformation(userDTO);
	}
}

Thymeleaf

Server-side templates

Used quando uma Single Web Page Application não é suficiente

Substitui JSPs e JSTLs,os quais estão datados e depreciados

Template engine poderosa e fácil de usar por  Web designers

<h1 th:text="#{title}">Hello, world</h1>

Monitoramento

Pronto pra produção com Metrics

Monitore a JVM, o servidor de aplicação, Spring beans, cache e muito mais!

Relatórios com JMX ou Graphite

@Timed
public void saveAccount(@RequestBody UserDTO userDTO) {
	userService.updateUserInformation(userDTO);
}

Implantação nas nuvens

Para o alto e além

A implantação da aplicação na nuvem é bastante facilitada

Ferramentas pra deploy na AWS, Heroku e Cloud Foundry

Porque usar JHipster

SERÁ QUE É APENAS HYPE?

Você disse hype?

Estatísticas de maio de 2016

223 contribuintes, incluindo 13 core members

4,210 GitHub stars e 928 forks

220,000 instalações

E crescendo rapidamente!

Porque?

Um monte de tecnologias legais, mas...

Gulp e Maven podem ser amigos?

AngularJS e Spring MVC REST podem ser amigos?

Netflix OSS e Spring podem ser amigos?

Colocar tudo funcionando junto, suavemente, com segurança, cache, monitoramento, não é moleza...

JHipster põe tudo pra funcionar junto

JHipster cria uma aplicação completa com todas essas tecnologias e ferramentas

As coisas simplesmente funcionam out-of-the-box

Temos o workflow do Gulp totalmente integrado nas goals do Maven

Temos o Docker configurado pra rodar tudo na boa

E ainda tem mais!

"entity": subgerador que gera uma entidade JPA completa, do banco de dados até o Angular

"import-jdl": subgerador que gera u modelo de entidades complexo usando JDL Studio

"service" subgerador que gera um Spring business service

"languages" subgerador que adiciona um novo idioma para o i18n

E ainda tem mais!

Ótimo suporte para criar microservices e gateways

JHipster Registry (Netflix Eureka + Spring cloud config server) fornecido out-of-the-box

JHipster Console com ELK (Elasticsearch + Logstash + Kibana) fornecido out-of-the-box

Suporte ao Docker

Módulos adicionais: https://jhipster.github.io/modules/marketplace/

Pronto pra rodar

GZipping e HTTP caching headers

Otimização e minificação do JavaScript e CSS com o Gulp

Executável standalone ou arquivo WAR padrão, com monitoramento habilitado

Subgeradores para deploy automático no Cloud Foundry, Heroku e AWS

"docker-compose": subgerador que gera a configuração do Docker para fazer deploy de microservices

Hello World

TUTORIAL 10 MINUTOS

Instalação

npm install -g yo
npm install -g generator-jhipster

Crie uma aplicação

E use o maven pra executar

                        (hot reload automático)

yo jhipster
./mvnw

Client-side live reload

                        Live reload co código do frontend (HTML, CSS, JavaScript) graças ao Gulp e Browsersync.

				  		Edita > Salva > Navegador atualiza automaticamente

gulp

Adicionaruma entidade

yo jhipster:entity Foo

Rodar em modo de produção

(Rodando o banco no docker)

./mvnw -Pprod package
docker-compose -f src/main/docker/mysql.yml up -d
java -jar target/*.war --spring.profiles.active=prod

Perguntas?

Email: josenaldo@gmail.com

Twitter: @josenaldomatos

Github: https://github.com/josenaldo


text:
<?php

namespace Foo;

interface A {
    const A = 0;
    function a();
}
interface B extends A {
    const B = 0;
    function b();
}
interface C {
    const C = 0;
    function c();
}
interface D {
    const D = 1;
    function d();
}

abstract class Bar implements D {
    const BAR = 0;
    private $bar = 0;
    abstract function bar();
}
abstract class Foo extends Bar implements B, C {
    const FOO = 0;
    private $foo = 0;
    abstract function foo();
}


text:
package com.github.marathon.proxy.handler.cluster;

import com.github.marathon.proxy.message.MarathonHost;

import java.io.Closeable;
import java.util.List;

/**
 * Created by Gary on 9/30/16.
 *
 * Describes the server that will broadcast the state of the Mesos/Marathon cluster to all the agents
 */
public interface ClusterSender
{
   void send(List<MarathonHost> hosts);
}


text:
namespace {
static const char kAuthNamespace[] =
    "urn:x-cast:com.google.cast.tp.deviceauth";
// Sender and receiver IDs to use for platform messages.
static const char kPlatformSenderId[] = "sender-0";
static const char kPlatformReceiverId[] = "receiver-0";
}  // namespace

namespace extensions {
namespace api {
namespace cast_channel {

bool MessageInfoToCastMessage(const MessageInfo& message,
                              CastMessage* message_proto) {
  DCHECK(message_proto);
  if (!message.data)
    return false;

  message_proto->set_protocol_version(CastMessage_ProtocolVersion_CASTV2_1_0);
  message_proto->set_source_id(message.source_id);
  message_proto->set_destination_id(message.destination_id);
  message_proto->set_namespace_(message.namespace_);
  // Determine the type of the base::Value and set the message payload
  // appropriately.
  std::string data;
  base::BinaryValue* real_value;
  switch (message.data->GetType()) {
    // JS string
    case base::Value::TYPE_STRING:
      if (message.data->GetAsString(&data)) {
        message_proto->set_payload_type(CastMessage_PayloadType_STRING);
        message_proto->set_payload_utf8(data);
      }
      break;
    // JS ArrayBuffer
    case base::Value::TYPE_BINARY:
      real_value = static_cast<base::BinaryValue*>(message.data.get());
      if (real_value->GetBuffer()) {
        message_proto->set_payload_type(CastMessage_PayloadType_BINARY);
        message_proto->set_payload_binary(real_value->GetBuffer(),
                                          real_value->GetSize());
      }
      break;
    default:
      // Unknown value type.  message_proto will remain uninitialized because
      // payload_type is unset.
      break;
  }
  return message_proto->IsInitialized();
}

bool IsCastMessageValid(const CastMessage& message_proto) {
  if (message_proto.namespace_().empty() || message_proto.source_id().empty() ||
      message_proto.destination_id().empty()) {
    return false;
  }
  return (message_proto.payload_type() == CastMessage_PayloadType_STRING &&
          message_proto.has_payload_utf8()) ||
         (message_proto.payload_type() == CastMessage_PayloadType_BINARY &&
          message_proto.has_payload_binary());
}

bool CastMessageToMessageInfo(const CastMessage& message_proto,
                              MessageInfo* message) {
  DCHECK(message);
  message->source_id = message_proto.source_id();
  message->destination_id = message_proto.destination_id();
  message->namespace_ = message_proto.namespace_();
  // Determine the type of the payload and fill base::Value appropriately.
  std::unique_ptr<base::Value> value;
  switch (message_proto.payload_type()) {
  case CastMessage_PayloadType_STRING:
    if (message_proto.has_payload_utf8())
      value.reset(new base::StringValue(message_proto.payload_utf8()));
    break;
  case CastMessage_PayloadType_BINARY:
    if (message_proto.has_payload_binary())
      value = base::BinaryValue::CreateWithCopiedBuffer(
          message_proto.payload_binary().data(),
          message_proto.payload_binary().size());
    break;
  default:
    // Unknown payload type. value will remain unset.
    break;
  }
  if (value.get()) {
    DCHECK(!message->data.get());
    message->data.reset(value.release());
    return true;
  } else {
    return false;
  }
}

std::string CastMessageToString(const CastMessage& message_proto) {
  std::string out("{");
  out += "namespace = " + message_proto.namespace_();
  out += ", sourceId = " + message_proto.source_id();
  out += ", destId = " + message_proto.destination_id();
  out += ", type = " + base::IntToString(message_proto.payload_type());
  out += ", str = \"" + message_proto.payload_utf8() + "\"}";
  return out;
}

std::string AuthMessageToString(const DeviceAuthMessage& message) {
  std::string out("{");
  if (message.has_challenge()) {
    out += "challenge: {}, ";
  }
  if (message.has_response()) {
    out += "response: {signature: (";
    out += base::SizeTToString(message.response().signature().length());
    out += " bytes), certificate: (";
    out += base::SizeTToString(
        message.response().client_auth_certificate().length());
    out += " bytes)}";
  }
  if (message.has_error()) {
    out += ", error: {";
    out += base::IntToString(message.error().error_type());
    out += "}";
  }
  out += "}";
  return out;
}

void CreateAuthChallengeMessage(CastMessage* message_proto) {
  CHECK(message_proto);
  DeviceAuthMessage auth_message;
  auth_message.mutable_challenge();
  std::string auth_message_string;
  auth_message.SerializeToString(&auth_message_string);

  message_proto->set_protocol_version(CastMessage_ProtocolVersion_CASTV2_1_0);
  message_proto->set_source_id(kPlatformSenderId);
  message_proto->set_destination_id(kPlatformReceiverId);
  message_proto->set_namespace_(kAuthNamespace);
  message_proto->set_payload_type(CastMessage_PayloadType_BINARY);
  message_proto->set_payload_binary(auth_message_string);
}

bool IsAuthMessage(const CastMessage& message) {
  return message.namespace_() == kAuthNamespace;
}

}  // namespace cast_channel
}  // namespace api
}  // namespace extensions


text:
import * as v1 from './v1';
import * as v1beta2 from './v1beta2';

const CloudMemcacheClient = v1.CloudMemcacheClient;
type CloudMemcacheClient = v1.CloudMemcacheClient;

export {v1, v1beta2, CloudMemcacheClient};
export default {v1, v1beta2, CloudMemcacheClient};
import * as protos from '../protos/protos';
export {protos};


text:
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Nick Edmonds
//           Douglas Gregor
//           Andrew Lumsdaine
#ifndef BOOST_DISTRIBUTED_FILTERED_GRAPH_HPP
#define BOOST_DISTRIBUTED_FILTERED_GRAPH_HPP

#ifndef BOOST_GRAPH_USE_MPI
#error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included"
#endif

#include <boost/graph/parallel/process_group.hpp>
#include <boost/graph/filtered_graph.hpp>

namespace boost {
  namespace graph {
          namespace parallel {
      /// Retrieve the process group from a filtered graph
      template<typename Graph, typename EdgePredicate, typename VertexPredicate>
      struct process_group_type<filtered_graph<Graph, EdgePredicate, VertexPredicate> >
        : process_group_type<Graph> { };

      template<typename Graph, typename EdgePredicate, typename VertexPredicate>
      struct process_group_type<const filtered_graph<Graph, EdgePredicate, VertexPredicate> >
        : process_group_type<Graph> { };
    }

  }

  /// Retrieve the process group from a filtered graph
  template<typename Graph, typename EdgePredicate, typename VertexPredicate>
  inline typename graph::parallel::process_group_type<Graph>::type
  process_group(filtered_graph<Graph, EdgePredicate, VertexPredicate> const& g) {
    return process_group(g.m_g);
  }

  /// Forward vertex() to vertex() of the base graph
  template <typename Graph, typename EdgePredicate, typename VertexPredicate>
  typename graph_traits<Graph>::vertex_descriptor
  vertex(typename graph_traits<Graph>::vertices_size_type i,
         filtered_graph<Graph, EdgePredicate, VertexPredicate> const& g)
  { return vertex(i, g.m_g); }

}

#endif // BOOST_DISTRIBUTED_FILTERED_GRAPH_HPP


text:
/**
 * BaseTest.java
 */
package com.skycloud.jkb.base;

import java.util.Locale;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 测试基类.
 *
 * @creation 2013年12月24日 下午12:58:53
 * @modification 2013年12月24日 下午12:58:53
 * @company Skycloud
 * @author xiweicheng
 * @version 1.0
 *
 */
@ContextConfiguration(locations = { "classpath*:servlet-context.xml", "classpath*:root-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseTest {

	protected Locale locale = Locale.CHINA;
}


text:
""" Test server.Server.__main__ entry point

"""

import pytest
from unittest.mock import patch

from foglamp.services import core

@pytest.allure.feature("unit")
@pytest.allure.story("services", "core")
async def test_main():
    with patch('foglamp.services.core', return_value=None) as mockedMain:
        srvr = mockedMain.Server
        srvr.start.return_value = None

        srvr.start()

        srvr.start.assert_called_once_with()  # assert_called_once() is python3.6 onwards :]

        # Okay, let's verify once more! :P
        assert 1 == srvr.start.call_count


text:
class HTU21D {
public:
	static bool reset();
	static bool read_temp(uint16_t& temp);
	static bool read_hum(uint16_t& hum);
	static void seti2c(I2CI* i2c);

private:
	static I2CI* i2c;
	static bool _reset();
	static bool _read(uint8_t cmd, uint16_t& m);
};


text:
/*
 * Author: tdanford
 * Date: Aug 25, 2008
 */
package edu.psu.compbio.seqcode.gse.datasets;

public class SimpleDBID implements DBID {
	private int dbid;

	public SimpleDBID(int id) { dbid = id; }

	public String toString() { return String.format("DBID:%d", dbid); }

	public int getID() { return dbid; }

	public boolean equals(Object o) {
		if(!(o instanceof SimpleDBID)) { return false; }
		return dbid == ((SimpleDBID)o).dbid;
	}

	public int hashCode() {
		int code = 17; code += dbid; code *= 37;
		return code;
	}
}


text:
package com.example.animation.db;

import org.litepal.crud.DataSupport;

/**
 * Created by 刘通 on 2017/4/9.
 */

public class ComicMessageItem extends DataSupport {

    private String comicUrl;

    private boolean myFavourity;

    private String readNow;

    private String comicImageUrl;

    private String comicName;

    public ComicMessageItem(){

    }

    public ComicMessageItem(String comicUrl,Boolean myFavourity,String readNow,String comicImageUrl,String comicName){
        this.comicUrl = comicUrl;
        this.myFavourity = myFavourity;
        this.readNow = readNow;
        this.comicImageUrl = comicImageUrl;
        this.comicName = comicName;
    }

    public String getComicName() {
        return comicName;
    }

    public void setComicName(String comicName) {
        this.comicName = comicName;
    }

    public String getComicImageUrl() {
        return comicImageUrl;
    }

    public void setComicImageUrl(String comicImageUrl) {
        this.comicImageUrl = comicImageUrl;
    }

    public String getReadNow() {
        return readNow;
    }

    public void setReadNow(String readNow) {
        this.readNow = readNow;
    }

    public String getComicUrl() {
        return comicUrl;
    }

    public void setComicUrl(String comicUrl) {
        this.comicUrl = comicUrl;
    }

    public boolean isMyFavourity() {
        return myFavourity;
    }

    public void setMyFavourity(boolean myFavourity) {
        this.myFavourity = myFavourity;
    }

}