text:
package java.security;

import java.net.URL;
import java.net.SocketPermission;
import java.util.ArrayList;
import java.util.List;
import java.util.Hashtable;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.cert.*;

/**
 *
 *
This class extends the concept of a codebase to
 * encapsulate not only the location (URL) but also the certificate chains
 * that were used to verify signed code originating from that location.
 *
 * @author Li Gong
 * @author Roland Schemers
 */

public class CodeSource implements java.io.Serializable {

    private static final long serialVersionUID = 4977541819976013951L;

    /**
     * The code location.
     *
     * @serial
     */
    private URL location;

    /*
     * The code signers.
     */
    private transient CodeSigner[] signers = null;

    /*
     * The code signers. Certificate chains are concatenated.
     */
    private transient java.security.cert.Certificate certs[] = null;

    // cached SocketPermission used for matchLocation
    private transient SocketPermission sp;

    // for generating cert paths
    private transient CertificateFactory factory = null;

    /**
     * Constructs a CodeSource and associates it with the specified
     * location and set of certificates.
     *
     * @param url the location (URL).
     *
     * @param certs the certificate(s). It may be null. The contents of the
     * array are copied to protect against subsequent modification.
     */
    public CodeSource(URL url, java.security.cert.Certificate certs[]) {
        this.location = url;

        // Copy the supplied certs
        if (certs != null) {
            this.certs = certs.clone();
        }
    }

    /**
     * Constructs a CodeSource and associates it with the specified
     * location and set of code signers.
     *
     * @param url the location (URL).
     * @param signers the code signers. It may be null. The contents of the
     * array are copied to protect against subsequent modification.
     *
     * @since 1.5
     */
    public CodeSource(URL url, CodeSigner[] signers) {
        this.location = url;

        // Copy the supplied signers
        if (signers != null) {
            this.signers = signers.clone();
        }
    }

    /**
     * Returns the hash code value for this object.
     *
     * @return a hash code value for this object.
     */
    @Override
    public int hashCode() {
        if (location != null)
            return location.hashCode();
        else
            return 0;
    }

    /**
     * Tests for equality between the specified object and this
     * object. Two CodeSource objects are considered equal if their
     * locations are of identical value and if their signer certificate
     * chains are of identical value. It is not required that
     * the certificate chains be in the same order.
     *
     * @param obj the object to test for equality with this object.
     *
     * @return true if the objects are considered equal, false otherwise.
     */
    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;

        // objects types must be equal
        if (!(obj instanceof CodeSource))
            return false;

        CodeSource cs = (CodeSource) obj;

        // URLs must match
        if (location == null) {
            // if location is null, then cs.location must be null as well
            if (cs.location != null) return false;
        } else {
            // if location is not null, then it must equal cs.location
            if (!location.equals(cs.location)) return false;
        }

        // certs must match
        return matchCerts(cs, true);
    }

    /**
     * Returns the location associated with this CodeSource.
     *
     * @return the location (URL).
     */
    public final URL getLocation() {
        /* since URL is practically immutable, returning itself is not
           a security problem */
        return this.location;
    }

    /**
     * Returns the certificates associated with this CodeSource.
     *

     * If this CodeSource object was created using the
     * {@link #CodeSource(URL url, CodeSigner[] signers)}
     * constructor then its certificate chains are extracted and used to
     * create an array of Certificate objects. Each signer certificate is
     * followed by its supporting certificate chain (which may be empty).
     * Each signer certificate and its supporting certificate chain is ordered
     * bottom-to-top (i.e., with the signer certificate first and the (root)
     * certificate authority last).
     *
     * @return A copy of the certificates array, or null if there is none.
     */
    public final java.security.cert.Certificate[] getCertificates() {
        if (certs != null) {
            return certs.clone();

        } else if (signers != null) {
            // Convert the code signers to certs
            ArrayList<java.security.cert.Certificate> certChains =
                        new ArrayList<>();
            for (int i = 0; i < signers.length; i++) {
                certChains.addAll(
                    signers[i].getSignerCertPath().getCertificates());
            }
            certs = certChains.toArray(
                        new java.security.cert.Certificate[certChains.size()]);
            return certs.clone();

        } else {
            return null;
        }
    }

    /**
     * Returns the code signers associated with this CodeSource.
     *

     * If this CodeSource object was created using the
     * {@link #CodeSource(URL url, java.security.cert.Certificate[] certs)}
     * constructor then its certificate chains are extracted and used to
     * create an array of CodeSigner objects. Note that only X.509 certificates
     * are examined - all other certificate types are ignored.
     *
     * @return A copy of the code signer array, or null if there is none.
     *
     * @since 1.5
     */
    public final CodeSigner[] getCodeSigners() {
        if (signers != null) {
            return signers.clone();

        } else if (certs != null) {
            // Convert the certs to code signers
            signers = convertCertArrayToSignerArray(certs);
            return signers.clone();

        } else {
            return null;
        }
    }

    /**
     * Returns true if this CodeSource object "implies" the specified CodeSource.
     *

     * More specifically, this method makes the following checks.
     * If any fail, it returns false. If they all succeed, it returns true.
     *

     *
 codesource must not be null.
     *
 If this object's certificates are not null, then all
     * of this object's certificates must be present in codesource's
     * certificates.
     *
 If this object's location (getLocation()) is not null, then the
     * following checks are made against this object's location and
     * codesource's:
     *

     *
  codesource's location must not be null.
     *
     *
  If this object's location
     *           equals codesource's location, then return true.
     *
     *
  This object's protocol (getLocation().getProtocol()) must be
     *           equal to codesource's protocol, ignoring case.
     *
     *
  If this object's host (getLocation().getHost()) is not null,
     *           then the SocketPermission
     *           constructed with this object's host must imply the
     *           SocketPermission constructed with codesource's host.
     *
     *
  If this object's port (getLocation().getPort()) is not
     *           equal to -1 (that is, if a port is specified), it must equal
     *           codesource's port or default port
     *           (codesource.getLocation().getDefaultPort()).
     *
     *
  If this object's file (getLocation().getFile()) doesn't equal
     *           codesource's file, then the following checks are made:
     *           If this object's file ends with "/-",
     *           then codesource's file must start with this object's
     *           file (exclusive the trailing "-").
     *           If this object's file ends with a "/*",
     *           then codesource's file must start with this object's
     *           file and must not have any further "/" separators.
     *           If this object's file doesn't end with a "/",
     *           then codesource's file must match this object's
     *           file with a '/' appended.
     *
     *
  If this object's reference (getLocation().getRef()) is
     *           not null, it must equal codesource's reference.
     *
     *

     *

     *

     * For example, the codesource objects with the following locations
     * and null certificates all imply
     * the codesource with the location "http://java.sun.com/classes/foo.jar"
     * and null certificates:
     *

     *     http:
     *     http://*.sun.com/classes/*
     *     http://java.sun.com/classes/-
     *     http://java.sun.com/classes/foo.jar
     *

     *
     * Note that if this CodeSource has a null location and a null
     * certificate chain, then it implies every other CodeSource.
     *
     * @param codesource CodeSource to compare against.
     *
     * @return true if the specified codesource is implied by this codesource,
     * false if not.
     */

    public boolean implies(CodeSource codesource)
    {
        if (codesource == null)
            return false;

        return matchCerts(codesource, false) && matchLocation(codesource);
    }

    /**
     * Returns true if all the certs in this
     * CodeSource are also in that.
     *
     * @param that the CodeSource to check against.
     * @param strict If true then a strict equality match is performed.
     *               Otherwise a subset match is performed.
     */
    private boolean matchCerts(CodeSource that, boolean strict)
    {
        boolean match;

        // match any key
        if (certs == null && signers == null) {
            if (strict) {
                return (that.certs == null && that.signers == null);
            } else {
                return true;
            }
        // both have signers
        } else if (signers != null && that.signers != null) {
            if (strict && signers.length != that.signers.length) {
                return false;
            }
            for (int i = 0; i < signers.length; i++) {
                match = false;
                for (int j = 0; j < that.signers.length; j++) {
                    if (signers[i].equals(that.signers[j])) {
                        match = true;
                        break;
                    }
                }
                if (!match) return false;
            }
            return true;

        // both have certs
        } else if (certs != null && that.certs != null) {
            if (strict && certs.length != that.certs.length) {
                return false;
            }
            for (int i = 0; i < certs.length; i++) {
                match = false;
                for (int j = 0; j < that.certs.length; j++) {
                    if (certs[i].equals(that.certs[j])) {
                        match = true;
                        break;
                    }
                }
                if (!match) return false;
            }
            return true;
        }

        return false;
    }

    /**
     * Returns true if two CodeSource's have the "same" location.
     *
     * @param that CodeSource to compare against
     */
    private boolean matchLocation(CodeSource that) {
        if (location == null)
            return true;

        if ((that == null) || (that.location == null))
            return false;

        if (location.equals(that.location))
            return true;

        if (!location.getProtocol().equalsIgnoreCase(that.location.getProtocol()))
            return false;

        int thisPort = location.getPort();
        if (thisPort != -1) {
            int thatPort = that.location.getPort();
            int port = thatPort != -1 ? thatPort
                                      : that.location.getDefaultPort();
            if (thisPort != port)
                return false;
        }

        if (location.getFile().endsWith("/-")) {
            // Matches the directory and (recursively) all files
            // and subdirectories contained in that directory.
            // For example, "/a/b/-" implies anything that starts with
            // "/a/b/"
            String thisPath = location.getFile().substring(0,
                                            location.getFile().length()-1);
            if (!that.location.getFile().startsWith(thisPath))
                return false;
        } else if (location.getFile().endsWith("/*")) {
            // Matches the directory and all the files contained in that
            // directory.
            // For example, "/a/b/*" implies anything that starts with
            // "/a/b/" but has no further slashes
            int last = that.location.getFile().lastIndexOf('/');
            if (last == -1)
                return false;
            String thisPath = location.getFile().substring(0,
                                            location.getFile().length()-1);
            String thatPath = that.location.getFile().substring(0, last+1);
            if (!thatPath.equals(thisPath))
                return false;
        } else {
            // Exact matches only.
            // For example, "/a/b" and "/a/b/" both imply "/a/b/"
            if ((!that.location.getFile().equals(location.getFile()))
                && (!that.location.getFile().equals(location.getFile()+"/"))) {
                return false;
            }
        }

        if (location.getRef() != null
            && !location.getRef().equals(that.location.getRef())) {
            return false;
        }

        String thisHost = location.getHost();
        String thatHost = that.location.getHost();
        if (thisHost != null) {
            if (("".equals(thisHost) || "localhost".equals(thisHost)) &&
                ("".equals(thatHost) || "localhost".equals(thatHost))) {
                // ok
            } else if (!thisHost.equals(thatHost)) {
                if (thatHost == null) {
                    return false;
                }
                if (this.sp == null) {
                    this.sp = new SocketPermission(thisHost, "resolve");
                }
                if (that.sp == null) {
                    that.sp = new SocketPermission(thatHost, "resolve");
                }
                if (!this.sp.implies(that.sp)) {
                    return false;
                }
            }
        }
        // everything matches
        return true;
    }

    /**
     * Returns a string describing this CodeSource, telling its
     * URL and certificates.
     *
     * @return information about this CodeSource.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        sb.append(this.location);

        if (this.certs != null && this.certs.length > 0) {
            for (int i = 0; i < this.certs.length; i++) {
                sb.append( " " + this.certs[i]);
            }

        } else if (this.signers != null && this.signers.length > 0) {
            for (int i = 0; i < this.signers.length; i++) {
                sb.append( " " + this.signers[i]);
            }
        } else {
            sb.append(" <no signer certificates>");
        }
        sb.append(")");
        return sb.toString();
    }

    /**
     * Writes this object out to a stream (i.e., serializes it).
     *
     * @serialData An initial {@code URL} is followed by an
     * {@code int} indicating the number of certificates to follow
     * (a value of "zero" denotes that there are no certificates associated
     * with this object).
     * Each certificate is written out starting with a {@code String}
     * denoting the certificate type, followed by an
     * {@code int} specifying the length of the certificate encoding,
     * followed by the certificate encoding itself which is written out as an
     * array of bytes. Finally, if any code signers are present then the array
     * of code signers is serialized and written out too.
     */
    private void writeObject(java.io.ObjectOutputStream oos)
        throws IOException
    {
        oos.defaultWriteObject(); // location

        // Serialize the array of certs
        if (certs == null || certs.length == 0) {
            oos.writeInt(0);
        } else {
            // write out the total number of certs
            oos.writeInt(certs.length);
            // write out each cert, including its type
            for (int i = 0; i < certs.length; i++) {
                java.security.cert.Certificate cert = certs[i];
                try {
                    oos.writeUTF(cert.getType());
                    byte[] encoded = cert.getEncoded();
                    oos.writeInt(encoded.length);
                    oos.write(encoded);
                } catch (CertificateEncodingException cee) {
                    throw new IOException(cee.getMessage());
                }
            }
        }

        // Serialize the array of code signers (if any)
        if (signers != null && signers.length > 0) {
            oos.writeObject(signers);
        }
    }

    /**
     * Restores this object from a stream (i.e., deserializes it).
     */
    private void readObject(java.io.ObjectInputStream ois)
        throws IOException, ClassNotFoundException
    {
        CertificateFactory cf;
        Hashtable<String, CertificateFactory> cfs = null;

        ois.defaultReadObject(); // location

        // process any new-style certs in the stream (if present)
        int size = ois.readInt();
        if (size > 0) {
            // we know of 3 different cert types: X.509, PGP, SDSI, which
            // could all be present in the stream at the same time
            cfs = new Hashtable<String, CertificateFactory>(3);
            this.certs = new java.security.cert.Certificate[size];
        }

        for (int i = 0; i < size; i++) {
            // read the certificate type, and instantiate a certificate
            // factory of that type (reuse existing factory if possible)
            String certType = ois.readUTF();
            if (cfs.containsKey(certType)) {
                // reuse certificate factory
                cf = cfs.get(certType);
            } else {
                // create new certificate factory
                try {
                    cf = CertificateFactory.getInstance(certType);
                } catch (CertificateException ce) {
                    throw new ClassNotFoundException
                        ("Certificate factory for " + certType + " not found");
                }
                // store the certificate factory so we can reuse it later
                cfs.put(certType, cf);
            }
            // parse the certificate
            byte[] encoded = null;
            try {
                encoded = new byte[ois.readInt()];
            } catch (OutOfMemoryError oome) {
                throw new IOException("Certificate too big");
            }
            ois.readFully(encoded);
            ByteArrayInputStream bais = new ByteArrayInputStream(encoded);
            try {
                this.certs[i] = cf.generateCertificate(bais);
            } catch (CertificateException ce) {
                throw new IOException(ce.getMessage());
            }
            bais.close();
        }

        // Deserialize array of code signers (if any)
        try {
            this.signers = ((CodeSigner[])ois.readObject()).clone();
        } catch (IOException ioe) {
            // no signers present
        }
    }

    /*
     * Convert an array of certificates to an array of code signers.
     * The array of certificates is a concatenation of certificate chains
     * where the initial certificate in each chain is the end-entity cert.
     *
     * @return An array of code signers or null if none are generated.
     */
    private CodeSigner[] convertCertArrayToSignerArray(
        java.security.cert.Certificate[] certs) {

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

        try {
            // Initialize certificate factory
            if (factory == null) {
                factory = CertificateFactory.getInstance("X.509");
            }

            // Iterate through all the certificates
            int i = 0;
            List<CodeSigner> signers = new ArrayList<>();
            while (i < certs.length) {
                List<java.security.cert.Certificate> certChain =
                        new ArrayList<>();
                certChain.add(certs[i++]); // first cert is an end-entity cert
                int j = i;

                // Extract chain of certificates
                // (loop while certs are not end-entity certs)
                while (j < certs.length &&
                    certs[j] instanceof X509Certificate &&
                    ((X509Certificate)certs[j]).getBasicConstraints() != -1) {
                    certChain.add(certs[j]);
                    j++;
                }
                i = j;
                CertPath certPath = factory.generateCertPath(certChain);
                signers.add(new CodeSigner(certPath, null));
            }

            if (signers.isEmpty()) {
                return null;
            } else {
                return signers.toArray(new CodeSigner[signers.size()]);
            }

        } catch (CertificateException e) {
            return null; //TODO - may be better to throw an ex. here
        }
    }
}


text:
package com.waydrow.coolweather.gson;

import com.google.gson.annotations.SerializedName;

/**
 * Created by Waydrow on 2017/3/3.
 */

public class Now {

    @SerializedName("tmp")
    public String temperature;

    @SerializedName("cond")
    public More more;

    public class More {

        @SerializedName("txt")
        public String info;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<title>Patrick Skelley</title>
		<link href="../stylesheets/default_blog.css" rel="stylesheet" type="text/css">
		<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>

					Home  |
					Personal  |
					Blog  |
					Past Projects  |
					Contact  |

Blog

Hello and welcome to my blog!

In this space I would like to dive into a few concepts in tech for purposes of solidifying my learning, and enteracting with these concepts. Would love to hear your thoughts and feedback! I am always fascinated and thoroughly enjoy exploring and discussing the ever expanding tech knowledge domain.

Version Control &nbsp&nbsp&nbsp&nbsp

Classes vs. IDs&nbsp&nbsp&nbsp&nbsp

Arrays vs Hashes

The Numbers Don't Lie

The Cycle Method

Classes in Ruby &nbsp

R Classes/JS Constructor

Recursion in Ruby

&copy Patrick Skelley


text:
package com.java110.api.listener.community;

import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.community.ICommunityBMO;
import com.java110.api.listener.AbstractServiceApiPlusListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.intf.community.ICommunityInnerServiceSMO;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.utils.constant.ServiceCodeConstant;
import com.java110.utils.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;

/**
 * 保存小区侦听
 * add by wuxw 2019-06-30
 */
@Java110Listener("auditEnterCommunity")
public class AuditEnterCommunityListener extends AbstractServiceApiPlusListener {

    @Autowired
    private ICommunityBMO communityBMOImpl;
    @Autowired
    private ICommunityInnerServiceSMO communityInnerServiceSMOImpl;

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {

        Assert.hasKeyAndValue(reqJson, "communityMemberId", "小区成员ID不能为空");
        Assert.hasKeyAndValue(reqJson, "state", "必填,请填写小区审核状态");
        Assert.hasKeyAndValue(reqJson, "remark", "必填,请填写小区审核原因");

    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {

        communityBMOImpl.updateCommunityMember(reqJson, context);

    }

    @Override
    public String getServiceCode() {
        return ServiceCodeConstant.SERVICE_CODE_AUDIT_ENTER_COMMUNITY;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }

    @Override
    public int getOrder() {
        return DEFAULT_ORDER;
    }

    public ICommunityInnerServiceSMO getCommunityInnerServiceSMOImpl() {
        return communityInnerServiceSMOImpl;
    }

    public void setCommunityInnerServiceSMOImpl(ICommunityInnerServiceSMO communityInnerServiceSMOImpl) {
        this.communityInnerServiceSMOImpl = communityInnerServiceSMOImpl;
    }
}


text:
package com.pelzer.util;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import junit.framework.TestCase;

import com.pelzer.util.Logging;
import com.pelzer.util.Timecode;
import com.pelzer.util.Timecode.TimecodeException;
import com.pelzer.util.Timecode.Type;

public class TimecodeTest extends TestCase {
  public TimecodeTest(String name) {
    super(name);
  }

  public void testToFramesCD() {
    Timecode s = new Timecode(Type.TYPE_AUDIO_CD);
    s.setSeconds(1);
    s.normalize();
    assertEquals(75, s.toFrames(), 0);
  }

  /**
   * Tests that the class succussfully encodes using the java.beans.Encoder api.
   */
  public void testXMLEncoding() {
    Logging.Logger logger = Logging.getLogger(this);
    Timecode s1 = new Timecode(Type.TYPE_AUDIO_CD);
    s1.setCode(345343);
    ByteArrayOutputStream xml = new ByteArrayOutputStream();
    XMLEncoder xmlEnc = new XMLEncoder(xml);
    xmlEnc.writeObject(s1);
    xmlEnc.close();
    logger.debug("XML=" + xml.toString());
    XMLDecoder xmlDec = new XMLDecoder(new ByteArrayInputStream(xml.toByteArray()));
    Timecode s2 = (Timecode) xmlDec.readObject();
    assertEquals(s1, s2);
  }

  public void testToFramesNTSC() {
    Timecode s = new Timecode(Type.TYPE_VIDEO_NTSC);
    s.setSeconds(1);
    s.normalize();
    assertEquals(29.97F, s.toFrames(), 0);
  }

  public void testCD() throws TimecodeException {
    assertEquals(0F, new Timecode(0).toSeconds(), 0);
    assertEquals(1F, new Timecode("00:00:00:75").toSeconds(), 0);
  }

  public void testNTSCVideo() {
    assertEquals(0F, new Timecode(0, Type.TYPE_VIDEO_NTSC).toSeconds(), 0);
    assertEquals(29.97F, new Timecode(1F, Type.TYPE_VIDEO_NTSC).toFrames(), 0.001);
  }

  public void testToMMSS() {
    Timecode s = new Timecode(0);
    assertEquals("00:00", s.toMMSS());
    s.setSeconds(59);
    assertEquals("00:59", s.toMMSS());
    s.setSeconds(60);
    s.normalize();
    assertEquals("01:00", s.toMMSS());
    s.clear();
    s.setHours(1);
    s.setMinutes(3);
    s.setSeconds(5);
    s.setFrames(7);
    s.normalize();
    assertEquals("63-05", s.toMMSS("-"));
    assertEquals("6305", s.toMMSS(""));
  }

  public void testToHHMMSS() {
    Timecode s = new Timecode(0);
    assertEquals("00:00:00", s.toHHMMSS());
    s.setSeconds(59);
    assertEquals("00:00:59", s.toHHMMSS());
    s.setSeconds(60);
    s.normalize();
    assertEquals("00:01:00", s.toHHMMSS());
    s.clear();
    s.setHours(1);
    s.setMinutes(3);
    s.setSeconds(5);
    s.setFrames(7);
    s.normalize();
    assertEquals("01^_^03^_^05", s.toHHMMSS("^_^"));
    assertEquals("01-03-05", s.toHHMMSS("-"));
    assertEquals("010305", s.toHHMMSS(""));
  }

  public void testToIntSeconds() {
    Timecode s = new Timecode(0);
    assertEquals(0, s.toIntSeconds());
    s.setSeconds(59);
    assertEquals(59, s.toIntSeconds());
    s.setSeconds(60);
    s.normalize();
    assertEquals(60, s.toIntSeconds());
    s.clear();
    assertEquals(0, s.toIntSeconds());
    s.setHours(1);
    s.setMinutes(3);
    s.setSeconds(5);
    s.setFrames(7);
    s.normalize();
    assertEquals(3785, s.toIntSeconds());
  }

  public void testTypeGetInstance() {
    assertEquals(Type.getInstance(29.97f), Type.TYPE_VIDEO_NTSC);
    assertEquals(Type.getInstance(75.0f), Type.TYPE_AUDIO_CD);
    assertEquals(Type.getInstance(24.000F), Type.TYPE_VIDEO_FILM);
    assertEquals(Type.getInstance(25.000f), Type.TYPE_VIDEO_PAL);
    // Just for giggles, do the opposite.
    assertNotSame(Type.getInstance(29.97f), Type.TYPE_VIDEO_FILM);
  }

}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'gisele-analysis'

module Gisele
  module Analysis
    class Glts

      def o(name = "glts")
        tap do
          Path("#{name}.dot").write(to_dot)
          `dot -Tgif -o #{name}.gif #{name}.dot`
          Path("#{name}.dot").unlink
          puts "!!! Glts printed to #{name}.gif !!!"
        end
      end

    end
  end
end

module SpecHelpers
  include Gisele::Analysis::Mixin::BddManagement

  def meeting_scheduling_sexpr
    Gisele::Language.sexpr Path.dir/"fixtures/MeetingScheduling.gis"
  end

  def session(with_vars = false)
    @session ||= begin
      s = Gisele::Analysis::Session.new
      if with_vars
        s.fluent :moving, [:start], [:stop], false
        s.fluent :closed, [:close], [:open], true
      end
      s
    end
  end

  def s
    @session_with_vars ||= session(true)
  end

  def bddi(*args)
    session(*args).bdd_interface
  end

  def bdd(*args)
    session.bdd(*args)
  end

end

RSpec.configure do |c|
  c.include SpecHelpers

  c.after(:all){ @session.close if @session }
end


text:
@interface IBGradientView : UIView
@property (nonatomic) CGFloat gradientHeight;
@end

@implementation IBGradientView

- (id)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = NO;
    }
    return self;
}

- (void)setGradientHeight:(CGFloat)gradientHeight {
    _gradientHeight = gradientHeight;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);

    CGContextAddRect(context, self.frame);

    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGFloat components[] = {
        0.0f, 0.0f, 0.0f, 0.5f,
        0.0f, 0.0f, 0.0f, 0.0f
    };
    CGFloat locations[] = { 0.0f, 1.0f };
    size_t count = sizeof(components)/ (sizeof(CGFloat)* 4);
    CGGradientRef gradientRef =
    CGGradientCreateWithColorComponents(colorSpaceRef, components, locations, count);

    CGRect frame = self.bounds;
    CGPoint startPoint = CGPointMake(CGRectGetMidX(frame), CGRectGetMaxY(frame));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(frame), CGRectGetMaxY(frame) - _gradientHeight);
    CGContextDrawLinearGradient(context, gradientRef, startPoint, endPoint, kCGGradientDrawsAfterEndLocation);

    CGGradientRelease(gradientRef);
    CGColorSpaceRelease(colorSpaceRef);
}

@end

@interface IBImageBannerScrollView ()
@property (strong, nonatomic) IBGradientView *gradientView;
@property (strong, nonatomic) UIPageControl *pageControl;
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) NSArray *imageViews;
@property (strong, nonatomic) NSArray *actionBlocks;
@property (strong, nonatomic) NSTimer *scrollTimer;
@end

@implementation IBImageBannerScrollView

- (id)init {
    self = [super init];
    if (self) {
        self.clipsToBounds = YES;
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewDidTap:)];
        [self addGestureRecognizer:tapGestureRecognizer];

        _scrollView = [[UIScrollView alloc] init];
        _scrollView.bounces = YES;
        _scrollView.alwaysBounceHorizontal = YES;
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.scrollsToTop = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        [self addSubview:_scrollView];

        _gradientView = [[IBGradientView alloc] init];
        [self addSubview:_gradientView];

        _pageControl = [[UIPageControl alloc] init];
        _pageControl.userInteractionEnabled = NO;
        [self addSubview:_pageControl];

        _imageViews = @[];
        _actionBlocks = @[];

        [self startScrollTimer];
    }
    return self;
}

- (void)dealloc {
    NSLog(@"%s", __func__);

    _imageViews = nil;
    _actionBlocks = nil;
}

- (void)removeFromSuperview {
    [super removeFromSuperview];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGRect rect = self.bounds;

    _scrollView.frame = rect;

    _gradientView.frame = rect;
    _gradientView.gradientHeight = CGRectGetHeight(rect) / 4.0f;

    _pageControl.center = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect) - 10.0f);

    _scrollView.contentSize = CGSizeMake(CGRectGetWidth(rect) * _imageViews.count, CGRectGetHeight(rect));
    NSUInteger count = 0;
    for (UIImageView *imageView in _imageViews) {
        CGFloat positionX = count * CGRectGetWidth(rect);
        imageView.frame = CGRectMake(positionX, 0.0f, CGRectGetWidth(rect), CGRectGetHeight(rect));
        ++count;
    }
}

- (void)addBannerImage:(UIImage *)image actionBlock:(void (^)())actionBlock {
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = image;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    [_scrollView addSubview:imageView];

    _imageViews = [_imageViews arrayByAddingObject:imageView];
    if (actionBlock) {
        _actionBlocks = [_actionBlocks arrayByAddingObject:actionBlock];
    }
    else {
        _actionBlocks = [_actionBlocks arrayByAddingObject:[NSNull null]];
    }

    [self setNeedsLayout];

    ++_pageControl.numberOfPages;
    if (_pageControl.numberOfPages == 1) {
        _pageControl.hidden = YES;
    }
    else {
        _pageControl.hidden = NO;
    }
}

- (void)changeBannerImage:(UIImage *)image atIndex:(NSUInteger)index {
    if (index >= _imageViews.count) {
        return;
    }

    UIImageView *imageView = _imageViews[index];
    imageView.image = image;
}

- (void)removeBannerImageAtIndex:(NSUInteger)index {
    if (index >= _imageViews.count) {
        return;
    }

    UIImageView *imageView = _imageViews[index];
    [imageView removeFromSuperview];
    NSMutableArray *tmpImageViews = [NSMutableArray arrayWithArray:_imageViews];
    [tmpImageViews removeObject:imageView];
    _imageViews = tmpImageViews.copy;

    NSInteger numberOfPages = _pageControl.numberOfPages;
    NSInteger currentPages = _pageControl.currentPage;
    if (currentPages < numberOfPages) {
        --_pageControl.currentPage;
    }
    --_pageControl.numberOfPages;

    [self setNeedsLayout];
}

- (void)startAutoScrolling {
    [self startScrollTimer];
}

- (void)stopAutoScrolling {
    [self stopScrollTimer];
}

#pragma mark Property
- (void)setIsEnableAutoScrolling:(BOOL)isEnableAutoScrolling {
    _isEnableAutoScrolling = isEnableAutoScrolling;

    if (isEnableAutoScrolling) {
        [self startAutoScrolling];
    }
    else {
        [self stopAutoScrolling];
    }
}

#pragma mark NSTimer
- (void)timerFired:(NSTimer *)timer {
    CGPoint offset = _scrollView.contentOffset;
    CGRect rect = self.bounds;
    NSUInteger positionX = offset.x / CGRectGetWidth(rect);
    CGFloat destinationPositionX = (positionX + 1) * CGRectGetWidth(rect);
    CGRect destinationRect = CGRectMake(destinationPositionX, 0.0f, CGRectGetWidth(rect), CGRectGetHeight(rect));

    [_scrollView scrollRectToVisible:destinationRect animated:YES];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    CGRect rect = self.bounds;

    NSUInteger index = offset.x / CGRectGetWidth(rect);
    _pageControl.currentPage = index;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    CGRect rect = self.bounds;

    NSUInteger index = offset.x / CGRectGetWidth(rect);
    _pageControl.currentPage = index;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self stopScrollTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startScrollTimer];
}

#pragma mark NSTimer
- (void)startScrollTimer {
    if (!_scrollTimer) {
        _scrollTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
    }
}

- (void)stopScrollTimer {
    if (_scrollTimer) {
        [_scrollTimer invalidate];
        _scrollTimer = nil;
    }
}

#pragma mark UITapGestureRecognizer
- (void)scrollViewDidTap:(UIGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:_scrollView];
    CGRect rect = self.bounds;

    NSUInteger index = point.x / CGRectGetWidth(rect);

    void (^actionBlock)() = [_actionBlocks objectAtIndex:index];
    if (actionBlock && ![actionBlock isEqual:[NSNull null]]) {
        actionBlock();
    }
}

@end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace chchch.Invoke
{
    public static class Ch3CoroutineManager
    {
        private class _coroutineBehaviour : MonoBehaviour { };

        private static _coroutineBehaviour _monoBehaviour;

        private static _coroutineBehaviour coroutineBehaviour
        {
            get
            {
                if (_monoBehaviour == null)
                {
                    GameObject gameObject = new GameObject(typeof(Ch3CoroutineManager).Name);
                    gameObject.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector | HideFlags.DontSave;
                    Object.DontDestroyOnLoad(gameObject);
                    _monoBehaviour = gameObject.AddComponent<_coroutineBehaviour>();
                }

                return _monoBehaviour;
            }
        }

        public static Coroutine Start(IEnumerator p_enumerator)
        {
            return coroutineBehaviour.StartCoroutine(p_enumerator);
        }

        public static void Kill(Coroutine p_coroutine)
        {
            coroutineBehaviour.StopCoroutine(p_coroutine);
        }

        public static void KillAll()
        {
            coroutineBehaviour.StopAllCoroutines();
        }
    }
}


text:
package com.tq.requisition.infrastructure.Specifications.project;

import com.tq.requisition.domain.Specification.Specification;
import com.tq.requisition.domain.Specification.expression.IHqlExpression;
import com.tq.requisition.domain.Specification.expression.OperationType;
import com.tq.requisition.domain.model.project.ProjectItem;
import com.tq.requisition.infrastructure.Specifications.Expression.HqlExpression;
import com.tq.requisition.presentation.dto.project.ProExportCondition;

/**
 * 按照月份查询项目月度信息
 * @author jjh
 * @time 2016-01-15 22:02
 *
 */
public class ProByMonthSpecification extends Specification<ProjectItem>{
	private ProExportCondition condition;

	public ProByMonthSpecification(Class<ProjectItem> _t,ProExportCondition condition) {
		super(_t);
		this.condition = condition;
	}

	@Override
	public IHqlExpression getHqlExpression() {
		IHqlExpression expression = new HqlExpression();
		String hql = "from ProjectItem where ";
		if(condition.getIsInstantAchieve() != null && condition.getIsInstantAchieve()){
			hql += "curMonthComplete is not null and curMonthComplete <> '' and curMonthComplete <> '否' and ";
		} else if (condition.getIsInstantAchieve() != null && !condition.getIsInstantAchieve()) {
			hql += "(curMonthComplete is null or curMonthComplete = '' or curMonthComplete = '否') and ";
		}
		hql += "date between ? and ?";
		expression.setHql(hql);
		expression.setParameters(condition.getStartDate(),condition.getEndDate());
		expression.setType(OperationType.HQL);
		return expression;
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Boletín de la Soc. Ciencias de Córdoba 23: 374 (1919)

#### Original name
Collybia muscigera var. lateritia Speg.

### Remarks
null


text:
package marketplaces

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"strings"
)

var (
	// categories of marketplaces queue process
	RAWIMAGE     = "marketplaces.rawimages"
	MARKETPLACES = "localsite.marketplaces"
)

type ReqOpts struct {
	AccountId string `json:"account_id" cql:"account_id"`
	CatId     string `json:"cat_id" cql:"cat_id"`
	Action    string `json:"action" cql:"action"`
	Category  string `json:"category" cql:"category"`
}

func NewRequestOpt(acc, cat_id, category, action string) *ReqOpts {
	return &ReqOpts{
		AccountId: acc,
		CatId:     cat_id,
		Action:    action,
		Category:  category,
	}
}
func (r *ReqOpts) String() string {
	if d, err := yaml.Marshal(r); err != nil {
		return err.Error()
	} else {
		return string(d)
	}
}

func (r *ReqOpts) ParseRequest() (MarketplaceInterface, error) {
	switch r.Category {
	case RAWIMAGE:
		return r.getRawImage()
	case MARKETPLACES:
		return r.getMarketplace()
	default:
		return nil, newParseError([]string{"Category: ", r.Category}, []string{RAWIMAGE, MARKETPLACES})
	}
}

func (r *ReqOpts) getRawImage() (*RawImages, error) {
	raw := new(RawImages)
	raw.AccountId = r.AccountId
	raw.Id = r.CatId
	return raw.Get()
}

func (r *ReqOpts) getMarketplace() (*Marketplaces, error) {
	return GetMarketplace(r.AccountId, r.CatId)
}

// ParseError represents an error that occurred during parsing.
type ParseError struct {
	Found    string
	Expected []string
}

// newParseError returns a new instance of ParseError.
func newParseError(found []string, expected []string) *ParseError {
	return &ParseError{Found: strings.Join(found, ","), Expected: expected}
}

// Error returns the string representation of the error.
func (e *ParseError) Error() string {
	return fmt.Sprintf("found %s, expected [ %s ]", e.Found, strings.Join(e.Expected, ", "))
}


text:
package mealplaner.proposal;

import static java.util.Optional.empty;
import static java.util.stream.Collectors.toList;
import static mealplaner.model.proposal.Proposal.from;
import static mealplaner.model.proposal.ProposedMenu.proposed;
import static mealplaner.plugins.builtins.courses.CourseSettings.ONLY_MAIN;
import static mealplaner.plugins.builtins.courses.CourseType.DESERT;
import static mealplaner.plugins.builtins.courses.CourseType.ENTRY;
import static mealplaner.plugins.builtins.courses.CourseType.MAIN;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

import mealplaner.api.ProposalBuilderInterface;
import mealplaner.commons.Pair;
import mealplaner.commons.errorhandling.MealException;
import mealplaner.model.meal.Meal;
import mealplaner.model.proposal.Proposal;
import mealplaner.model.proposal.ProposedMenu;
import mealplaner.model.settings.Settings;
import mealplaner.plugins.api.ProposalBuilderStep;
import mealplaner.plugins.builtins.courses.CourseTypeFact;
import mealplaner.plugins.builtins.courses.CourseTypeSetting;

public class ProposalBuilder implements ProposalBuilderInterface {
  private boolean firstDayIsToday = false;
  private boolean random = false;

  private final Random randomIntGenerator = new Random();
  private final Map<UUID, Meal> mealDataMain = new HashMap<>();
  private final Map<UUID, Meal> mealDataEntry = new HashMap<>();
  private final Map<UUID, Meal> mealDataDesert = new HashMap<>();

  private final List<ProposedMenu> proposalList;
  private final Collection<ProposalBuilderStep> proposalBuilderSteps;

  public ProposalBuilder(
      List<Meal> meals,
      Collection<ProposalBuilderStep> proposalBuilderSteps) {
    this.proposalBuilderSteps = new ArrayList<>();
    this.proposalBuilderSteps.addAll(proposalBuilderSteps);
    meals.stream()
        .filter(meal -> meal.getTypedMealFact(CourseTypeFact.class).getCourseType().equals(ENTRY))
        .forEach(meal -> mealDataEntry.put(meal.getId(), meal));
    meals.stream()
        .filter(meal -> meal.getTypedMealFact(CourseTypeFact.class).getCourseType().equals(MAIN))
        .forEach(meal -> mealDataMain.put(meal.getId(), meal));
    meals.stream()
        .filter(meal -> meal.getTypedMealFact(CourseTypeFact.class).getCourseType().equals(DESERT))
        .forEach(meal -> mealDataDesert.put(meal.getId(), meal));
    proposalList = new ArrayList<>();
  }

  @Override
  public ProposalBuilder randomise(boolean randomise) {
    random = randomise;
    return this;
  }

  @Override
  public ProposalBuilder firstProposal(boolean today) {
    firstDayIsToday = today;
    return this;
  }

  @Override
  public Proposal propose(Settings... settings) { // NOPMD
    for (var step : proposalBuilderSteps) {
      step.setupProposalStep(mealDataMain);
    }
    if (!mealDataMain.isEmpty()) {
      for (int today = 0; today < settings.length; today++) {
        makeNextProposal(settings, today);
      }
    }
    return from(firstDayIsToday, proposalList);
  }

  private void makeNextProposal(Settings[] settings, int today) {
    Optional<UUID> entry = empty();
    UUID main = mealDataMain.entrySet()
        .stream()
        .findFirst()
        .map(Map.Entry::getKey)
        .orElseThrow();
    Optional<UUID> desert = empty();
    switch (settings[today]
        .getTypedSubSettingOrDefault(CourseTypeSetting.class, new CourseTypeSetting(ONLY_MAIN))
        .getCourseSetting()) {
      case ONLY_MAIN:
        main = proposeNextMain(proposalList, settings[today]).orElse(main);
        break;
      case ENTRY_MAIN:
        main = proposeNextMain(proposalList, settings[today]).orElse(main);
        entry = proposeNextEntry(settings[today], mealDataMain.get(main), proposalList, mealDataEntry);
        break;
      case MAIN_DESERT:
        main = proposeNextMain(proposalList, settings[today]).orElse(main);
        desert = proposeNextDesert(settings[today], mealDataMain.get(main), proposalList, mealDataDesert);
        break;
      case THREE_COURSE:
        main = proposeNextMain(proposalList, settings[today]).orElse(main);
        entry = proposeNextEntry(settings[today], mealDataMain.get(main), proposalList, mealDataEntry);
        desert = proposeNextDesert(settings[today], mealDataMain.get(main), proposalList, mealDataDesert);
        break;
      default:
        throw new MealException("Internal Error: This should not happen");
    }
    proposalList.add(proposed(entry, main, desert, settings[today].getNumberOfPeople()));
    for (var step : proposalBuilderSteps) {
      step.incrementProposalStepBetweenMeals(mealDataMain.get(main));
    }
  }

  private Optional<UUID> proposeNextMain(
      final List<ProposedMenu> proposalList, final Settings settings) {
    var proposalStream = mealDataMain.values().stream()
        .map(meal -> Pair.of(meal, meal.getDaysPassedAsInteger()))
        .map(pair -> takeProposalIntoAccount(
            pair, proposalList, menu -> true, menu -> menu.main, mealDataMain));
    for (var proposalStep : proposalBuilderSteps) {
      proposalStream = proposalStep.applyPluginSuggestions(proposalStream, settings);
    }
    return pickMeal(proposalStream);
  }

  private Optional<UUID> proposeNextDesert(
      Settings settings, Meal main, List<ProposedMenu> proposalList, Map<UUID, Meal> mealData) {
    var meals = mealData.values().stream()
        .map(desert -> Pair.of(desert, desert.getDaysPassedAsInteger()))
        .map(desert -> takeProposalIntoAccount(
            desert, proposalList, menu -> menu.desert.isPresent(), menu -> menu.desert.get(), mealDataDesert));
    for (var step : proposalBuilderSteps) {
      meals = step.applyPluginSuggestionsToDeserts(meals, settings, main);
    }
    return pickMeal(meals);
  }

  private Optional<UUID> proposeNextEntry(
      Settings settings, Meal main, List<ProposedMenu> proposalList, Map<UUID, Meal> mealData) {
    var meals = mealData.values().stream()
        .map(entry -> Pair.of(entry, entry.getDaysPassedAsInteger()))
        .map(entry -> takeProposalIntoAccount(
            entry, proposalList, menu -> menu.entry.isPresent(), menu -> menu.entry.get(), mealDataEntry));
    for (var step : proposalBuilderSteps) {
      meals = step.applyPluginSuggestionsToEntries(meals, settings, main);
    }
    return pickMeal(meals);
  }

  private Optional<UUID> pickMeal(Stream<Pair<Meal, Integer>> meals) {
    return meals
        .map(this::randomize)
        .sorted((pair1, pair2) -> pair2.right.compareTo(pair1.right))
        .map(pair -> pair.left.getId())
        .findFirst();
  }

  private Pair<Meal, Integer> randomize(Pair<Meal, Integer> pair) {
    return random ? Pair.of(pair.left, pair.right + randomIntGenerator.nextInt(100)) : pair;
  }

  private Pair<Meal, Integer> takeProposalIntoAccount(
      Pair<Meal, Integer> pair,
      List<ProposedMenu> proposalList,
      Predicate<ProposedMenu> presentCheck,
      Function<ProposedMenu, UUID> menuGetter,
      Map<UUID, Meal> mealData) {
    List<Meal> proposedMeals = proposalList.stream()
        .filter(presentCheck)
        .filter(menu -> mealData.containsKey(menuGetter.apply(menu)))
        .map(menu -> mealData.get(menuGetter.apply(menu)))
        .collect(toList());
    return proposedMeals.contains(pair.left)
        ? Pair.of(pair.left, proposalList.size() - proposedMeals.indexOf(pair.left) - 1)
        : Pair.of(pair.left, pair.right + proposalList.size());
  }
}


text:
$(function(){
  $('[rel="tooltip"]').tooltip();

  if ( window.location.pathname == '/' ) {
    $('[rel="tooltip"]').hover(
      function () {
        $('.tooltip.top').addClass("home");
      }
    );
  }

  $(".tweet").tweet({
    username: $('.tweet').data('twitter-user'),
    join_text: "auto",
    avatar_size: 32,
    count: 3,
    loading_text: "loading tweets...",
    auto_join_text_default: "",
    auto_join_text_ed: "",
    auto_join_text_ing: "",
    auto_join_text_reply: "",
    auto_join_text_url: ""
  });

  var instagramElement = $('.instagram');
  var instagram = {
    userId: instagramElement.data('instagram-user'),
    clientId: instagramElement.data('instagram-client'),
    accessToken: instagramElement.data('instagram-access-token')
  };

  $(".instagram").instagram({
    userId: instagram.userId,
    clientId: instagram.clientId,
    accessToken: instagram.accessToken,
    show: 4,
    onComplete: function(photos, data) {
      if (data.pagination) {
        insta_next_url = data.pagination.next_url;
      }
    }
  });

  $('#instabutton').on('click', function(){
    var button = $(this);
    var text = button.text();
    var insta_container = $(".instagram");
    button.addClass('disabled');

    if (button.text() != 'Loading…') {
      button.text('Loading…');
      insta_container.instagram({
          userId: instagram.userId,
          clientId: instagram.clientId,
          accessToken: instagram.accessToken,
          next_url : insta_next_url,
          show : 4,
          onComplete : function(photos, data) {
            insta_next_url = data.pagination.next_url;
            button.text(text);
            button.removeClass('disabled');
          }
      });
    }
  });

  var githubInfo = $("#gh_repos");
  if(githubInfo.data('github-user')) {

    github.showRepos({
      user: githubInfo.data('github-user'),
      count: githubInfo.data('github-repo-count'),
      skip_forks: githubInfo.data('github-skip-forks'),
      skip_github_io: githubInfo.data('github-skip-github-io'),
      target: githubInfo
    });
  }

  var $container = $('#post-container');
  $container.imagesLoaded(function(){
    $container.masonry({
      itemSelector : '.span4',
      columnWidth: function( containerWidth ) {
        return containerWidth / 3;
      }
    });
  });

});


text:
@interface MCLayerViewController ()
@property (strong, nonatomic) NSMutableArray *cellArray;
@property (strong, nonatomic) MCFeatureTable *featureTable;
@property (strong, nonatomic) MCTileTable *tileTable;
@property (strong, nonatomic) UITableView *tableView;
@property (nonatomic) BOOL haveScrolled;
@property (nonatomic) CGFloat contentOffset;
@end

@implementation MCLayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect bounds = self.view.bounds;
    CGRect insetBounds = CGRectMake(bounds.origin.x, bounds.origin.y + 32, bounds.size.width, bounds.size.height - 20);
    self.tableView = [[UITableView alloc] initWithFrame: insetBounds style:UITableViewStylePlain];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.allowsMultipleSelectionDuringEditing = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 141.0;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.backgroundColor = [UIColor clearColor];

    [self registerCellTypes];
    [self initCellArray];

    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

    UIEdgeInsets tabBarInsets = UIEdgeInsetsMake(0, 0, self.tabBarController.tabBar.frame.size.height, 0);
    self.tableView.contentInset = tabBarInsets;
    self.tableView.scrollIndicatorInsets = tabBarInsets;
    [self addAndConstrainSubview:self.tableView];
    [self addDragHandle];
    [self addCloseButton];
    self.contentOffset = 0;
    self.haveScrolled = NO;
}

- (void) registerCellTypes {
    [self.tableView registerNib:[UINib nibWithNibName:@"MCHeaderCellDisplay" bundle:nil] forCellReuseIdentifier:@"header"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MCFeatureLayerOperationsCell" bundle:nil] forCellReuseIdentifier:@"featureButtons"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MCTileLayerOperationsCell" bundle:nil] forCellReuseIdentifier:@"tileButtons"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MCTitleCell" bundle:nil] forCellReuseIdentifier:@"title"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MCDescriptionCell" bundle:nil] forCellReuseIdentifier:@"description"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MCLayerCell" bundle: nil] forCellReuseIdentifier:@"layerCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MCButtonCell" bundle: nil] forCellReuseIdentifier:@"button"];
}

- (void) initCellArray {
    _cellArray = [[NSMutableArray alloc] init];

    if ([self.table isKindOfClass:MCTileTable.class]) {
        self.tileTable = (MCTileTable *) self.table;
    } else if ([self.table isKindOfClass:MCFeatureTable.class]) {
        self.featureTable = (MCFeatureTable *) self.table;
    }

    MCHeaderCell *headerCell = [self.tableView dequeueReusableCellWithIdentifier:@"header"];
    headerCell.nameLabel.text = self.table.name;

    if (_featureTable != nil) {
        [headerCell setDetailLabelOneText:[NSString stringWithFormat:@"feature layer in %@", _featureTable.database]];
        [headerCell setDetailLabelTwoText:[NSString stringWithFormat:@"%d features", _featureTable.count]];
        [headerCell setDetailLabelThreeText:@""];
        [_cellArray addObject:headerCell];

        MCFeatureLayerOperationsCell *featureButtonsCell = [self.tableView dequeueReusableCellWithIdentifier:@"featureButtons"];
        featureButtonsCell.delegate = self;
        [_cellArray addObject:featureButtonsCell];

        MCDescriptionCell *featureAddDescription = [self.tableView dequeueReusableCellWithIdentifier:@"description"];
        [featureAddDescription setDescription:@"Long press the map to add points to this layer."];
        [featureAddDescription textAlignCenter];
        [_cellArray addObject:featureAddDescription];

        MCTitleCell *fieldsTitle = [self.tableView dequeueReusableCellWithIdentifier:@"title"];
        [fieldsTitle setLabelText:@"Fields"];
        [_cellArray addObject:fieldsTitle];

        MCButtonCell *addFieldsButton = [self.tableView dequeueReusableCellWithIdentifier:@"button"];
        [addFieldsButton setButtonLabel:@"Add a field"];
        addFieldsButton.action = @"add-fields";
        addFieldsButton.delegate = self;
        [_cellArray addObject:addFieldsButton];

        if (self.columns.count == 2) {
            // TODO add empty state
        }

        for (GPKGUserColumn *column in self.columns) {
            if (![column.name isEqualToString:@"id"] && ![column.name isEqualToString:@"geom"]) {
                MCLayerCell *fieldCell = [self.tableView dequeueReusableCellWithIdentifier:@"layerCell"];
                [fieldCell setName:column.name];
                [fieldCell activeIndicatorOff];

                if (column.dataType == GPKG_DT_TEXT) {
                    [fieldCell.layerTypeImage setImage:[UIImage imageNamed:@"text"]];
                    [fieldCell setDetails:@"Text"];
                } else if (column.dataType == GPKG_DT_INTEGER || column.dataType == GPKG_DT_REAL || column.dataType == GPKG_DT_DOUBLE || column.dataType == GPKG_DT_INT || column.dataType == GPKG_DT_FLOAT || column.dataType == GPKG_DT_SMALLINT || column.dataType == GPKG_DT_TINYINT || column.dataType == GPKG_DT_MEDIUMINT) {
                    [fieldCell.layerTypeImage setImage:[UIImage imageNamed:@"number"]];
                    [fieldCell setDetails:@"Number"];
                } else if (column.dataType == GPKG_DT_BOOLEAN) {
                    [fieldCell.layerTypeImage setImage:[UIImage imageNamed:@"boolean"]];
                    [fieldCell setDetails:@"Checkbox"];
                }

                [_cellArray addObject:fieldCell];
            }
        }

    } else if (_tileTable != nil) {
        MCTileLayerOperationsCell *tileButtonsCell = [self.tableView dequeueReusableCellWithIdentifier:@"tileButtons"];
        [headerCell setDetailLabelOneText: [NSString stringWithFormat:@"tile layer in %@", _tileTable.database]];
        [headerCell setDetailLabelTwoText: [NSString stringWithFormat:@"Zoom levels %d - %d",  _tileTable.minZoom, _tileTable.maxZoom]];
        [headerCell setDetailLabelThreeText:[NSString stringWithFormat:@"%d tiles", _tileTable.count]];
        tileButtonsCell.delegate = self;
        _cellArray = [[NSMutableArray alloc] initWithObjects:headerCell, tileButtonsCell, nil];

        MCTitleCell *zoomLevelsTitle = [self.tableView dequeueReusableCellWithIdentifier:@"title"];
        [zoomLevelsTitle setLabelText:@"Zoom levels"];
        [_cellArray addObject:zoomLevelsTitle];

        for (MCTileMatrix *tileMatrix in _tileTable.tileMatrices) {
            if (tileMatrix.tileCount.intValue > 0) {
                MCLayerCell *tileMatricCell = [self.tableView dequeueReusableCellWithIdentifier:@"layerCell"];
                [tileMatricCell setName:[NSString stringWithFormat: @"%@ ", tileMatrix.zoomLevel]];
                NSString *tileText = tileMatrix.tileCount.intValue > 1 ? @"tiles" : @"tile";
                [tileMatricCell setDetails:[NSString stringWithFormat:@"%@ %@", tileMatrix.tileCount, tileText]];
                [tileMatricCell.layerTypeImage setImage:[UIImage imageNamed:@"ZoomLevel"]];
                [tileMatricCell activeIndicatorOff];
                [_cellArray addObject:tileMatricCell];
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void) update {
    [self initCellArray];
    [self.tableView reloadData];
}

#pragma mark - Table view data source and delegate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_cellArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [_cellArray objectAtIndex:indexPath.row];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void) renameLayer {
    NSLog(@"Renaming Layer");

    UIAlertController *renameAlert = [UIAlertController alertControllerWithTitle:@"Rename Layer" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [renameAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        [textField setText:self.table.name];
    }];

    UIAlertAction *confirmRename = [UIAlertAction actionWithTitle:@"Rename" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"New name is: %@", renameAlert.textFields[0].text);

        NSString * newName = renameAlert.textFields[0].text;

        bool validName = newName != nil && [newName length] > 0 && ![newName isEqualToString:self.table.name];
        if(validName){
            @try {
                NSString *originalName = self.table.name;

                if([self.delegate renameLayer:newName]){
                    [self.table setName:newName];
                    [self initCellArray];
                    [self.tableView reloadData];
                }else{
                    [MCUtils showMessageWithDelegate:self
                                               andTitle:[MCProperties getValueOfProperty:GPKGS_PROP_GEOPACKAGE_RENAME_LABEL]
                                             andMessage:[NSString stringWithFormat:@"Rename from %@ to %@ was not successful", originalName, newName]];
                }
            }
            @catch (NSException *exception) {
                [MCUtils showMessageWithDelegate:self
                                           andTitle:[NSString stringWithFormat:@"Rename %@ to %@", @"OLDNAME", newName]
                                         andMessage:[NSString stringWithFormat:@"%@", [exception description]]];
            }
        }
    }];

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [renameAlert dismissViewControllerAnimated:YES completion:nil];
    }];

    [renameAlert addAction:confirmRename];
    [renameAlert addAction:cancel];

    [self presentViewController:renameAlert animated:YES completion:nil];
}

- (void) deleteLayer {
    NSLog(@"Deleting layer");

    UIAlertController *deleteAlert = [UIAlertController alertControllerWithTitle:@"Delete" message:@"Do you wanbt to delete this layer? This action can not be undone." preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmDelete = [UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self.delegate deleteLayer];
        [self dismissViewControllerAnimated:YES completion:nil];
    }];

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [deleteAlert dismissViewControllerAnimated:YES completion:nil];
    }];

    [deleteAlert addAction:confirmDelete];
    [deleteAlert addAction:cancel];

    [self presentViewController:deleteAlert animated:YES completion:nil];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([[_cellArray objectAtIndex:indexPath.row] isKindOfClass:[MCLayerCell class]]) {
        return YES;
    } else {
        return NO;
    }
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (_tileTable != nil) {
        return nil;
    }

    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"Delete" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        MCLayerCell *cell = [self.cellArray objectAtIndex:indexPath.row];
        GPKGUserColumn *columnToDelete = nil;

        for (GPKGUserColumn *column in self.columns) {
            if ([cell.layerNameLabel.text isEqualToString:column.name]) {
                columnToDelete = column;
            }
        }

        UIAlertController *deleteAlert = [UIAlertController alertControllerWithTitle:@"Delete" message:@"Do you want to delete this field? Data saved in this field will be lost for all points in this layer. This action can not be undone." preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *confirmDelete = [UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            @try {
                [self.delegate deleteColumn:columnToDelete];
            }
            @catch (NSException *exception) {
                [MCUtils showMessageWithDelegate:self
                                           andTitle:[NSString stringWithFormat:@"Delete failed"]
                                         andMessage:[NSString stringWithFormat:@"%@", [exception description]]];
            }
        }];

        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [deleteAlert dismissViewControllerAnimated:YES completion:nil];
        }];

        [deleteAlert addAction:confirmDelete];
        [deleteAlert addAction:cancel];
        [self presentViewController:deleteAlert animated:YES completion:nil];

        completionHandler(YES);
    }];

    UIContextualAction *renameAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"Rename" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {

        MCLayerCell *cell = [self.cellArray objectAtIndex:indexPath.row];
        GPKGUserColumn *columnToRename = nil;

        for (GPKGUserColumn *column in self.columns) {
            if ([cell.layerNameLabel.text isEqualToString:column.name]) {
                columnToRename = column;
            }
        }

        UIAlertController *renameAlert = [UIAlertController alertControllerWithTitle:@"Rename" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [renameAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            [textField setText:cell.layerNameLabel.text];
        }];

        UIAlertAction *confirmRename = [UIAlertAction actionWithTitle:@"Rename" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"New name is: %@", renameAlert.textFields[0].text);
            NSString * newName = renameAlert.textFields[0].text;

            if(newName != nil && [newName length] > 0){
                @try {
                    [self.delegate renameColumn:columnToRename name:newName];
                }
                @catch (NSException *exception) {
                    [MCUtils showMessageWithDelegate:self
                                               andTitle:[NSString stringWithFormat:@"Rename failed"]
                                             andMessage:[NSString stringWithFormat:@"%@", [exception description]]];
                }
            }
        }];

        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [renameAlert dismissViewControllerAnimated:YES completion:nil];
        }];

        [renameAlert addAction:confirmRename];
        [renameAlert addAction:cancel];
        [self presentViewController:renameAlert animated:YES completion:nil];

        completionHandler(YES);
    }];

    deleteAction.backgroundColor = [UIColor redColor];
    renameAction.backgroundColor = [UIColor orangeColor];
    UISwipeActionsConfiguration *configuration = [UISwipeActionsConfiguration configurationWithActions:@[]];
    configuration.performsFirstActionWithFullSwipe = YES;
    return configuration;
}

#pragma mark - MCFeatureLayerOperationsCellDelegate methods
// TODO pass these up to be done in the repository
- (void) renameFeatureLayer {
    NSLog(@"MCLayerOperationsDelegate editLayer");
    [self renameLayer];
}

- (void) indexFeatures {
    NSLog(@"MCLayerOperationsDelegate indexLayer");
    //[_delegate indexLayer];
}

- (void) createTiles {
    NSLog(@"MCLayerOperationsDelegate createTiles");
    //[_delegate createTiles];
}

- (void) createOverlay {
    NSLog(@"MCLayerOperationsDelegate createOverlay");
    //[_delegate createOverlay];
}

- (void) deleteFeatureLayer {
    NSLog(@"MCFeatureButtonsCellDelegate deleteLayer %@", _table.name);
    [self deleteLayer];

}

#pragma mark - MCButtonCellDelegate methods
- (void)performButtonAction:(NSString *)action {
    if ([action isEqualToString:@"add-fields"]) {

        NSLog(@"show create fields view");
        [_delegate showFieldCreationView];
    }
}

#pragma mark - MCTileButtonsDelegate methods
- (void) renameTileLayer {
    NSLog(@"MCTileButtonsDelegate renameLayer");
    [self renameLayer];
}

- (void) showScalingOptions {
    NSLog(@"MCTileButtonsDelegate showScalingOptions");
    //[_delegate showTileScalingOptions];
}

- (void) deleteTileLayer {
    NSLog(@"MCTileButtonsDelegate deleteTileLayer");
    [self deleteLayer];
}

- (void)closeDrawer {
    [self.drawerViewDelegate popDrawer];
    [self.delegate layerViewCompletionHandler];
}

- (void) drawerWasCollapsed {
    [super drawerWasCollapsed];
    [self.tableView setScrollEnabled:NO];
}

- (void) drawerWasMadeFull {
    [super drawerWasMadeFull];
    [self.tableView setScrollEnabled:YES];
}

- (void) becameTopDrawer {
    [self.delegate setSelectedLayerName];
}

- (BOOL)gestureIsInConflict:(UIPanGestureRecognizer *) recognizer {
    CGPoint point = [recognizer locationInView:self.view];

    if (CGRectContainsPoint(self.tableView.frame, point)) {
        return true;
    }

    return false;
}

// Override this method to make the drawer and the scrollview play nice
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.haveScrolled) {
        [self rollUpPanGesture:scrollView.panGestureRecognizer withScrollView:scrollView];
    }
}

// If the table view is scrolling rollup the gesture to the drawer and handle accordingly.
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.haveScrolled = YES;

    if (!self.isFullView) {
        scrollView.scrollEnabled = NO;
        scrollView.scrollEnabled = YES;
    } else {
        scrollView.scrollEnabled = YES;
    }
}

@end


text:
<?php

namespace Pointless\Extend;

abstract class Extension
{
    /**
     * @var string
     */
    protected $path = null;

    /**
     * Run Extension
     *
     * @return string
     */
    final public function getPath()
    {
        return $this->path;
    }

    /**
     * Run Extension
     *
     * @param array $data
     *
     * @return string
     */
    abstract public function render($data);
}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.ServiceModel.Description
{
  static public partial class MetadataResolver
  {
    #region Methods and constructors
    public static IAsyncResult BeginResolve(Type contract, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }

    public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, System.ServiceModel.EndpointAddress address, MetadataExchangeClient client, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }

    public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, System.ServiceModel.EndpointAddress address, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }

    public static IAsyncResult BeginResolve(Type contract, System.ServiceModel.EndpointAddress address, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }

    public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Requires(address.IsAbsoluteUri);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }

    public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Requires(address.IsAbsoluteUri);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }

    public static ServiceEndpointCollection EndResolve(IAsyncResult result)
    {
      return default(ServiceEndpointCollection);
    }

    public static ServiceEndpointCollection Resolve(IEnumerable<ContractDescription> contracts, System.ServiceModel.EndpointAddress address, MetadataExchangeClient client)
    {
      Contract.Requires(contracts != null);
      Contract.Requires(address != null);
      Contract.Requires(client != null);
      Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpointCollection>() != null);

      return default(ServiceEndpointCollection);
    }

    public static ServiceEndpointCollection Resolve(IEnumerable<ContractDescription> contracts, System.ServiceModel.EndpointAddress address)
    {
      Contract.Requires(contracts != null);
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpointCollection>() != null);

      return default(ServiceEndpointCollection);
    }

    public static ServiceEndpointCollection Resolve(Type contract, System.ServiceModel.EndpointAddress address)
    {
      Contract.Requires(contract != null);
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpointCollection>() != null);

      return default(ServiceEndpointCollection);
    }

    public static ServiceEndpointCollection Resolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client)
    {
      Contract.Requires(contracts != null);
      Contract.Requires(address != null);
      Contract.Requires(client != null);
      Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpointCollection>() != null);

      return default(ServiceEndpointCollection);
    }

    public static ServiceEndpointCollection Resolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode)
    {
      Contract.Requires(contracts != null);
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpointCollection>() != null);

      return default(ServiceEndpointCollection);
    }

    public static ServiceEndpointCollection Resolve(Type contract, Uri address, MetadataExchangeClientMode mode)
    {
      Contract.Requires(contract != null);
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpointCollection>() != null);

      return default(ServiceEndpointCollection);
    }
    #endregion
  }
}


text:
layout: page
title: Rain Productions Award Ceremony
date: 2016-05-24
author: Victoria French
tags: weekly links, java
status: published
summary: Aenean at lacus dapibus, euismod.
banner: images/banner/office-01.jpg
booking:
  startDate: 11/05/2016
  endDate: 11/09/2016
  ctyhocn: MSPLLHX
  groupCode: RPAC
published: true
---
Nam eu magna elementum, semper enim ut, ultrices ligula. Suspendisse potenti. Suspendisse potenti. Donec molestie volutpat convallis. Nullam quam felis, volutpat at mollis non, vulputate eget diam. Vivamus euismod dapibus pulvinar. Cras consectetur consequat mauris, sed rhoncus est. Aliquam euismod pulvinar ex at sagittis. Phasellus fermentum tincidunt tortor, in rhoncus erat dictum quis.
Quisque neque sapien, dignissim et aliquam vel, pharetra non risus. Aenean dictum sagittis turpis, in ultrices mauris consectetur vitae. Nulla auctor massa at magna ullamcorper, at volutpat erat ultricies. Nam a ante arcu. Nulla ut vestibulum purus. Morbi lobortis commodo consectetur. Duis consectetur enim diam, at auctor ante luctus ut. In sed nulla varius, efficitur lorem nec, pharetra nisl. Pellentesque est orci, tincidunt at magna vitae, maximus dapibus sapien.

* Aliquam congue nibh a mattis aliquam
* Maecenas feugiat ante at placerat blandit
* Pellentesque vulputate purus nec pellentesque condimentum
* Vestibulum sed purus rutrum, scelerisque eros id, posuere neque.

Nulla vel varius quam, sit amet sagittis dolor. Etiam vitae lacus ut arcu tempor volutpat faucibus sit amet sapien. Sed sed turpis luctus, imperdiet arcu vel, hendrerit nibh. Mauris tristique tincidunt massa. Donec consectetur massa id lacus vulputate consectetur. Aenean rhoncus tincidunt eleifend. In vitae dolor pharetra, feugiat elit vel, venenatis ante. Praesent eleifend pharetra turpis, eu porta urna dapibus a. Fusce suscipit dolor vel arcu lacinia ornare. Donec vel massa massa. Cras sed ultrices orci. Mauris vel dolor ac felis imperdiet venenatis varius eget turpis.


text:
title: View and Ajax
---

#Sharing objects with view

To register objects to be accessed by view, we use the `include` method:

~~~
#!java
@Controller
class ClientsController {

	@Inject
	private Result result;

	public void search(int id) {
		result.include("message", "Some message");
		result.include("client", new Client(id));
	}
}
~~~

Now the variables `message` and `client` are available to use in your template engine.
It's possible to register the object by invoking the `include` method with only one argument:

~~~
#!java
@Controller
class ClientsController {

	@Inject
	private Result result;

	public void search(int id) {
		result.include("Some message").include(new Client(id));
	}
}
~~~

In this case, the first invocation registers the `string` key and the second registers the `client` key. You can change this behavior writing your own `TypeNameExtractor`.

##Custom PathResolver

By default, to render your views, VRaptor uses the convention:

~~~
#!java
public class ClientsController {
	public void list() {
		//...
	}
}
~~~

The method above will render the view `/WEB-INF/jsp/clients/list.jsp`. However, if you want to change this behavior for some reason, or if you want to use another template engine like Freemarker or Velocity, you just need to extend the `DefaultPathResolver` class.

~~~
#!java
@Specializes
public class FreemarkerPathResolver extends DefaultPathResolver {
	protected String getPrefix() {
		return "/WEB-INF/freemarker/";
	}

	protected String getExtension() {
		return "ftl";
	}
}
~~~

Thus the logic will render the view `/WEB-INF/freemarker/clients/list.ftl`. If you want more customization, you can implement the `PathResolver` interface. Remember that you need to annotate your implementation with `@Specializes` annotation.

##View

If you want to change the view of some logic, you can use the `Result` object:

~~~
#!java
@Controller
public class ClientsController {

	@Inject
	private Result result;

	public void list() {}

	public void save(Client client) {
		//...
		result.use(Results.logic()).redirectTo(ClientsController.class).list();
	}
}
~~~

There are these kinds of implemented views:

| Results.logic() | will redirect to another logic method.
| Results.page() | will redirect directly to one page, may be a JSP, HTML, or any URI on web application dir, or application context.
| Results.http() | send informations of HTTP protocol with status code and headers.
| Results.status() | send status code with more informations.
| Results.referer() | use the header Referer to do redirects or forwards.
| Results.nothing() | just returns the success code (HTTP 200 OK).
| Results.xml() | serializes objects to XML.
| Results.json() | serializes objects to JSON.
| Results.representation() | serializes objects on a format determined by request (_format parameter or header Accept).
{: .content-table}

##Shortcuts on Result

Some redirects are often used, so were created shortcuts for them. The available shortcuts are:

| result.forwardTo("/some/uri") | result.use(page()).forward("/some/uri");
| result.redirectTo("/some/uri") | result.use(page()).redirect("/some/uri)
| result.permanentlyRedirectTo("/some/uri") | result.use(status()).movedPermanentlyTo("/some/uri");
| result.forwardTo(ClientsController.class).list() | result.use(logic()).forwardTo(ClientsController.class).list();
| result.redirectTo(ClientsController.class).list() | result.use(logic()).redirectTo(ClientsController.class).list();
| result.of(ClientsController.class).list() | result.use(page()).of(ClientsController.class).list();
| result.permanentlyRedirectTo(Controller.class) | use(status()).movedPermanentlyTo(Controller.class);
| result.notFound() | use(status()).notFound()
| result.nothing() | use(nothing());
{: .content-table}

Furthermore if the redirect is to another method in the same Controller, we can use:

| result.forwardTo(this).list() | result.use(logic()).forwardTo(this.getClass()).list();
| result.redirectTo(this).list() | result.use(logic()).redirectTo(this.getClass()).list();
| result.of(this).list() | result.use(page()).of(this.getClass()).list();
| result.permanentlyRedirectTo(this) | use(status()).movedPermanentlyTo(this.getClass());
{: .content-table}

##Redirect and forward

With VRaptor we can use both redirect or a forward to another logic or a JSP. Although they are Servlet API concepts, worth remembering the difference: the redirect happens on client side through HTTP codes that will make the browser access a new URL; forward happens on server side, totally transparent for the client/browser.

A good redirect usage example is with 'redirect-after-post' pattern. As example: when you add a client and after the submitted form, the client is returned to the client's listing page. Doing it with redirect, we prevent the user refresh the page (F5) and resubmit all the request, resulting in duplicate data.

In the case of forward, an example of using is when you have a validation and it failed, often you want the user continues on the same screen of form with fulfilled data request, but internally you will make the forward to another business logic (that prepares the necessery data for the form).

##Automatic Flash Scope

If you will add object in the `Result` and do a redirect, these objects will be available in the next request.

~~~
#!java
public void add(Client client) {
	dao.add(client);
	result.include("message", "Client successfully added");
	result.redirectTo(ClientsController.class).list();
}
~~~

list.jsp:

~~~
#!xml

${message}

~~~

##Accepts and the _format parameter

Many times, we need render different formats to the same logic. For example, we want return JSON instead of HTML. To do this, we can define the Header Accepts of request to accept the desired type, or put a `_format` parameter in the request.

If it's a JSON format, the view rendered by default will be: `/WEB-INF/jsp/{controller}/{logic}.json.jsp`, in other words, in general will be render the view: `/WEB-INF/jsp/{controller}/{logic}.{format}.jsp`. If the format is HTML you don't need put it in the filename. The `_format` parameter has priority over the header Accepts.

##Ajax: building in view

To return a JSON in your view, you just need to provide the object to the view, and inside the view you form the JSON as desired.
As example, your `/WEB-INF/jsp/clients/load.json.jsp`:

~~~
#!javascript
{ name: '${client.name}', id: '${client.id}' }
~~~

And the logic:

~~~
#!java
@Controller
public class ClientsController {

	@Inject
	private Result result;

	@Inject
	private ClientDao dao;

	public void load(Client client) {
		result.include("client", dao.load(client));
	}
}
~~~

##Ajax: programmatic version

If you want the VRaptor automatically serialize your objects to XML or JSON, you can write in your logic:

~~~
#!java
import static br.com.caelum.vraptor.view.Results.*;
@Controller
public class ClientsController {

	@Inject
	private Result result;

	@Inject
	private ClientDao dao;

	public void loadJson(Client client) {
		result.use(json()).from(client).serialize();
	}
	public void loadXml(Client client) {
		result.use(xml()).from(client).serialize();
	}
}
~~~

The results will be simillar to:

~~~
#!javascript
{"client": {
    "name": "John"
}}
~~~

and xml:

~~~
#!xml
<client>
    <name>John</name>
</client>
~~~

By default, just primitive types will be serialized (String, numbers, enums, dates), if you want include a field of non-primitive type you need include it explicitly:

~~~
#!java
result.use(json()).from(client).include("address").serialize();
~~~

Will result something like:

~~~
#!javascript
{"client": {
    "name": "John",
    "address" {
        "street": "Vergueiro"
    }
}}
~~~

You can also exclude some fields:

~~~
#!java
result.use(json()).from(user).exclude("password").serialize();
~~~

Will result something like:

~~~
#!javascript
{"user": {
    "name": "John",
    "login": "john"
}}
~~~

You can also exclude or include many fields.

~~~
#!java
result.use(json()).from(user).recursive().serialize(); // includes all fields recursively
result.use(xml()).from(user).exclude("email").serialize(); // exclude the email field
result.use(xml()).from(user).excludeAll().serialize(); // excludes all fields
~~~

The default behavior of JSON serialization is exclude atributes with `null` values, but it's possible to change this behavior by calling `serializeNulls` method:
~~~
#!java
result.use(json()).serializeNulls().from(new Person("John", null)).serialize();
~~~

The resulting JSON will be the following:
~~~
#!javascript
{"person":{
	"name": "John",
	"age": null
}}
~~~

You can add versioning capability to JSON based results.
Through this resource it is possible to add API versioning.
As a useful example, suppose that an API which returns a list of our system's customers was created.
The first version returns a list of customers defined by the structure that follows:

~~~
#!java
public class Customer {
	private String name;
	private String group;

	// getters and setters omitted
}
~~~

Now suppose you've created a controller's method as follows:

~~~
#!java
@Get{"/customers"}
public void customers() {
	List<Customer> customers = customersRepository.getAll();
	result.use(json()).from(customers).serialize();
}
~~~

So far, so good. But what if we need to add a new attribute as a result. A new attribute that only makes sense to the new API version.
How could we solve it? We could write a new class named as CustomerV2 with new attribute and rewrite the cotroller's method so it could look like the following code:

~~~
#!java
@Get{"/{versionParameter}/customers"}
public void customers(String versionParameter) {
    double version = Double.parseDouble(versionParameter);
    if (version == 2.0) {
		result.use(json()).from(customersRepository.getAll()).serialize();
	} else {
		result.use(json()).from(customersRepository.getAllFromV2()).serialize();
	}
}
~~~

Certainly, that was not a well suited approach. Regarding that VRaptor comes with GSON lib from Google as a dependency, we can use the same Customer class just by inserting @Since annotation through our new versioned attributes. This annotation, tells that an attribute will be available since an specified version as follows at our new Customer class:

~~~
#!java
public class Customer {
	private String name;
	private String group;

	@Since(2.0)
	private Calendar registerDate;

	// getters and setters omitted
}
~~~

Now, the our method could be rewritten as follows:

~~~
#!java
@Get{"/{versionParameter}/customers"}
public void customers(String versionParameter) {
    double version = Double.parseDouble(versionParameter);
    List<Customer> customers = customersRepository.getAll();
	result.use(json()).version(version).from(customers).serialize();
}
~~~

That's all. Now our API clients could request for a specified versioned result.

The default XML Serialization implementation is based on XStream, then you can configure serialization by annotations or direct settings to XStream, just create the class:

~~~
#!java
@Specializes
public class CustomXStreamBuilder extends XStreamBuilderImpl {

	@Override
	protected XStream xmlInstance() {
		XStream xStream = super.xmlInstance();
		//your settings to XStream here
		return xStream;
	}
}
~~~

To configure the JSON serialization you can create a class that extends `GsonJSONSerialization` and overwrite the method `getSerializer()`.

When serialiazing to JSON you can use the annotation `SkipSerialization` to omit the serialization of a field or class.

The following class was annotated with `SkipSerialization`, thus it's fields will never be serialized to JSON:

~~~
#!java
@SkipSerialization
public class UserPrivateInfo {

	private String document;
	private String phone;
	private String address;

	// getters and setters
}
~~~

In this another class, the field password will not be serialized. The info field will not be serialized either due to the `UserPrivateInfo` class was annotated with `SkipSerialization`
:

~~~
#!java
public class User {

	private String name;
	private String login;

	@SkipSerialization
	private String password;

	private UserPrivateInfo info;

	// getters and setters
}
~~~

Making the following call:

~~~
#!java
User user = ...;
result.use(json()).withoutRoot().from(user).recursive().serialize();
~~~

The obtained result is similar to:

~~~
#!javascript
{
	"name": "John Smith",
	"login": "john"
}
~~~

Note that the password field and the entire `UserPrivateInfo` wasn't serialized.

##Serializing Collections##

When serializing collections, by default is put the tag `list` around elements:

~~~
#!java
List<Client> clients = ...;
result.use(json()).from(clients).serialize();
//or
result.use(xml()).from(clients).serialize();
~~~

Will result something like:

~~~
#!javascript
{"list": [
    { "name": "John" },
    { "name": "Mary" }
]}
~~~

or

~~~
#!xml
<list>
	<client>
		<name>John</name>
	</client>
	<client>
		<name>Mary</name>
	</client>
</list>
~~~

You can customize the outside element, using the method:

~~~
#!java
List<Client> clients = ...;
result.use(json()).from(clients, "clients").serialize();
//ou
result.use(xml()).from(clients, "clients").serialize();
~~~

Will result something like:

~~~
#!javascript
{"clients": [
    {"name": "John"},
    {"name": "Mary"}
]}
~~~

or

~~~
#!xml
<clients>
	<client>
		<name>John</name>
	</client>
	<client>
		<name>Mary</name>
	</client>
</clients>
~~~

The includes and excludes work as if you were applied in the element within the list. For example if you want include the address on the client:

~~~
#!java
List<Client> clients = ...;
result.use(json()).from(clients).include("address").serialize();
~~~

With result:

~~~
#!javascript
{"list": [
    {
        "name": "John",
        "address": { "street": "Vergueiro, 3185" }
    },
    {
        "name": "Mary",
        "address": { "street": "Vergueiro, 3185" }
    }
]}
~~~

##JSON serialization without root element

If you want serialize an object in JSON format without naming it, you can do this with the method `withoutRoot`:

~~~
#!java
result.use(json()).from(car).serialize();
~~~

Will result something like:

~~~
#!javascript
{
  'car':
  {
    'color': 'blue'
  }
}
~~~

and

~~~
#!java
result.use(json()).withoutRoot().from(car).serialize();
~~~

Will result something like:

~~~
#!javascript
{
  'color': 'blue'
}
~~~

##JSON and XML result indentation

By default, the serialization result is without indentation, that is useful to improve browser downloading time.

~~~
#!java
result.use(json()).indented().from(car).serialize();
~~~

Will result something like:

~~~
#!javascript
{
  'car':
  {
    'color': 'blue'
  }
}
~~~

Or you can also use the Environment to define the default indentation according with enviroment. In this case you can define that in `DEVELOPMENT` enviroment the indentation will be enabled, and in `PRODUCTION` enviroment will be disabled.

`development.properties`:

~~~
#!properties
br.com.caelum.vraptor.serialization.xml.indented=true
br.com.caelum.vraptor.serialization.json.indented=true
~~~

`production.properties`:

~~~
#!properties
br.com.caelum.vraptor.serialization.xml.indented=false
br.com.caelum.vraptor.serialization.json.indented=false
~~~

**Note:** The `Enviroment` settings has lower priority than code. In other words, if you define `br.com.caelum.vraptor.serialization.xml.indented=false` on `Enviroment` and call the `indented` method in your code, the result will be an indented JSON or XML.

## Creating links on view with linkTo

LinkTo is a functionality that allows you create links on JSP pages without writing link, but just indicating the class of controller, and the method.

To the following controller:

~~~
#!java
public class ClientController {
	@Path("/client/list")
	public void list() {
		// some logic here
	}

	@Path("/client/{id}")
	public void show(Long id) {
		// some logic here
	}
}
~~~

To call the `list` and `show` methods respectively, we would have to write the JSP:

~~~
#!jsp
list clients
show client 1
~~~

Using the linkTo functionality, we can simplify the call to the `list` method:

~~~
#!jsp
list clients
~~~

Because the method have no parameters, you also can omit the parentheses.

~~~
#!jsp
list clients
~~~

To call the `show` method, we can do a call like this:

~~~
#!jsp
show client 1
~~~

Instead of the fixed parameter, you can pass JSTL variables, for example:

~~~
#!jsp
show client ${client.name}
~~~

##Automatic parameters inclusion

If you annotate your method with `@IncludeParameters`, all method parameters will be automatically included in the view.

So, instead of doing something like:

~~~
#!java
public void filters(Interval interval, Representative representative,
	    Unit unit, BigDecimal maxValue, BigDecimal minValue) {

	// filter logic

	result.include("interval", interval);
	result.include("representative", representative);
	result.include("maxValue", maxValue);
	result.include("minValue", minValue);
}
~~~

Now you can do:

~~~
#!java
@IncludeParameters
public void filters(Interval interval, Representative representative,
	    Unit unit, BigDecimal maxValue, BigDecimal minValue) {

	// filter logic
}
~~~

All the parameters will be available by JSP with EL: `${interval.begin}`


text:
<?php

return [

    /*
    +----------------------------------------------------------------+
    |\ PhalconSlayer Registered Commands                            /|
    +----------------------------------------------------------------+
    |
    | Register your slayer commands to lists up upon running
    | `php brood` to your terminal
    |
    */

    Components\Console\QueueWorker::class,
    Clarity\Console\App\ControllerCommand::class,
    Clarity\Console\App\ModuleCommand::class,
    Clarity\Console\App\RouteCommand::class,
    Clarity\Console\Clear\AllCommand::class,
    Clarity\Console\Clear\CacheCommand::class,
    Clarity\Console\Clear\CompiledCommand::class,
    Clarity\Console\Clear\LogsCommand::class,
    Clarity\Console\Clear\SessionCommand::class,
    Clarity\Console\Clear\ViewsCommand::class,
    Clarity\Console\DB\SeedFactory::class,
    Clarity\Console\Mail\InlinerCommand::class,
    Clarity\Console\Make\CollectionCommand::class,
    Clarity\Console\Make\ConsoleCommand::class,
    Clarity\Console\Make\ModelCommand::class,
    Clarity\Console\Script\RunCommand::class,
    Clarity\Console\Server\OptimizeCommand::class,
    Clarity\Console\Server\ServeCommand::class,
    Clarity\Console\Server\EnvCommand::class,
    Clarity\Console\Vendor\PublishCommand::class,
    Clarity\Support\Phinx\Console\Command\Create::class,
    Clarity\Support\Phinx\Console\Command\Migrate::class,
    Clarity\Support\Phinx\Console\Command\Rollback::class,
    Clarity\Support\Phinx\Console\Command\SeedCreate::class,
    Clarity\Support\Phinx\Console\Command\SeedRun::class,
    Clarity\Support\Phinx\Console\Command\Status::class,

    # - add your console commands below ...

]; # - end of return


text:
    <button (click)="onBackClick()" mat-icon-button matTooltip="Go back...">
        <mat-icon>keyboard_backspace</mat-icon>
    </button>

 Media object: {{mediaobject.objectid}}

            <video #videoplayer *ngIf="mediaobject.mediatype === 'VIDEO'"
                   [style.width]="'400px'" controls
                   src="{{mediaobject|ObjectPathPipe}}"></video>
            <audio #audioplayer *ngIf="mediaobject.mediatype === 'AUDIO'"
                   [style.width]="'400px'" controls
                   src="{{mediaobject|ObjectPathPipe}}"
                   width="400"></audio>

            <app-m3d-loader #modelviewer *ngIf="mediaobject.mediatype === 'MODEL3D'"
                            [height]="200" [interaction]="true" [width]="200"
                            src="{{mediaobject|ObjectPathPipe}}"></app-m3d-loader>

ID

{{mediaobject.objectId}}

Filename

{{mediaobject.name}}

Path

{{(mediaobject).path}}

Mediatype

{{mediaobject.mediatype}}