text:
package hudson.cli;

import com.trilead.ssh2.crypto.PEMDecoder;
import hudson.cli.client.Messages;
import hudson.remoting.Channel;
import hudson.remoting.PingThread;
import hudson.remoting.Pipe;
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.SocketInputStream;
import hudson.remoting.SocketOutputStream;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.Console;

import static java.util.logging.Level.*;

/**
 * CLI entry point to Jenkins.
 *
 * @author Kohsuke Kawaguchi
 */
public class CLI {
    private final ExecutorService pool;
    private final Channel channel;
    private final CliEntryPoint entryPoint;
    private final boolean ownsPool;
    private final List<Closeable> closables = new ArrayList<Closeable>(); // stuff to close in the close method
    private final String httpsProxyTunnel;
    private final String authorization;

    public CLI(URL jenkins) throws IOException, InterruptedException {
        this(jenkins,null);
    }

    /**
     * @deprecated
     *      Use {@link CLIConnectionFactory} to create {@link CLI}
     */
    public CLI(URL jenkins, ExecutorService exec) throws IOException, InterruptedException {
        this(jenkins,exec,null);
    }

    /**
     * @deprecated
     *      Use {@link CLIConnectionFactory} to create {@link CLI}
     */
    public CLI(URL jenkins, ExecutorService exec, String httpsProxyTunnel) throws IOException, InterruptedException {
        this(new CLIConnectionFactory().url(jenkins).executorService(exec).httpsProxyTunnel(httpsProxyTunnel));
    }

    /*package*/ CLI(CLIConnectionFactory factory) throws IOException, InterruptedException {
        URL jenkins = factory.jenkins;
        this.httpsProxyTunnel = factory.httpsProxyTunnel;
        this.authorization = factory.authorization;
        ExecutorService exec = factory.exec;

        String url = jenkins.toExternalForm();
        if(!url.endsWith("/"))  url+='/';

        ownsPool = exec==null;
        pool = exec!=null ? exec : Executors.newCachedThreadPool();

        Channel _channel;
        try {
            _channel = connectViaCliPort(jenkins, getCliTcpPort(url));
        } catch (IOException e) {
            LOGGER.log(Level.FINE,"Failed to connect via CLI port. Falling back to HTTP",e);
            try {
                _channel = connectViaHttp(url);
            } catch (IOException e2) {
                try { // Java 7: e.addSuppressed(e2);
                    Throwable.class.getMethod("addSuppressed", Throwable.class).invoke(e, e2);
                } catch (NoSuchMethodException _ignore) {
                    // Java 6
                } catch (Exception _huh) {
                    LOGGER.log(Level.SEVERE, null, _huh);
                }
                throw e;
            }
        }
        this.channel = _channel;

        // execute the command
        entryPoint = (CliEntryPoint)_channel.waitForRemoteProperty(CliEntryPoint.class.getName());

        if(entryPoint.protocolVersion()!=CliEntryPoint.VERSION)
            throw new IOException(Messages.CLI_VersionMismatch());
    }

    private Channel connectViaHttp(String url) throws IOException {
        LOGGER.fine("Trying to connect to "+url+" via HTTP");
        url+="cli";
        URL jenkins = new URL(url);

        FullDuplexHttpStream con = new FullDuplexHttpStream(jenkins,authorization);
        Channel ch = new Channel("Chunked connection to "+jenkins,
                pool,con.getInputStream(),con.getOutputStream());
        final long interval = 15*1000;
        final long timeout = (interval * 3) / 4;
        new PingThread(ch,timeout,interval) {
            protected void onDead() {
                // noop. the point of ping is to keep the connection alive
                // as most HTTP servers have a rather short read time out
            }
        }.start();
        return ch;
    }

    private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException {
        LOGGER.fine("Trying to connect directly via TCP/IP to "+clip.endpoint);
        final Socket s;
        OutputStream out;

        if (httpsProxyTunnel!=null) {
            String[] tokens = httpsProxyTunnel.split(":");
            s = new Socket(tokens[0], Integer.parseInt(tokens[1]));
            PrintStream o = new PrintStream(s.getOutputStream());
            o.print("CONNECT " + clip.endpoint.getHostName() + ":" + clip.endpoint.getPort() + " HTTP/1.0\r\n\r\n");

            // read the response from the proxy
            ByteArrayOutputStream rsp = new ByteArrayOutputStream();
            while (!rsp.toString().endsWith("\r\n\r\n")) {
                int ch = s.getInputStream().read();
                if (ch<0)   throw new IOException("Failed to read the HTTP proxy response: "+rsp);
                rsp.write(ch);
            }
            String head = new BufferedReader(new StringReader(rsp.toString())).readLine();
            if (!head.startsWith("HTTP/1.0 200 "))
                throw new IOException("Failed to establish a connection through HTTP proxy: "+rsp);

            // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well.
            // So instead of relying on it, we'll just send the close command and then let the server
            // cut their side, then close the socket after the join.
            out = new SocketOutputStream(s) {
                @Override
                public void close() throws IOException {
                    // ignore
                }
            };
        } else {
            s = new Socket();
            s.connect(clip.endpoint,3000);
            out = new SocketOutputStream(s);
        }

        closables.add(new Closeable() {
            public void close() throws IOException {
                s.close();
            }
        });

        Connection c = new Connection(new SocketInputStream(s),out);

        switch (clip.version) {
        case 1:
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            dos.writeUTF("Protocol:CLI-connect");
            // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor.
            break;
        case 2:
            DataInputStream dis = new DataInputStream(s.getInputStream());
            dos = new DataOutputStream(s.getOutputStream());
            dos.writeUTF("Protocol:CLI2-connect");
            String greeting = dis.readUTF();
            if (!greeting.equals("Welcome"))
                throw new IOException("Handshaking failed: "+greeting);
            try {
                byte[] secret = c.diffieHellman(false).generateSecret();
                SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret,128/8),"AES");
                c = c.encryptConnection(sessionKey,"AES/CFB8/NoPadding");

                // validate the instance identity, so that we can be sure that we are talking to the same server
                // and there's no one in the middle.
                byte[] signature = c.readByteArray();

                if (clip.identity!=null) {
                    Signature verifier = Signature.getInstance("SHA1withRSA");
                    verifier.initVerify(clip.getIdentity());
                    verifier.update(secret);
                    if (!verifier.verify(signature))
                        throw new IOException("Server identity signature validation failed.");
                }

            } catch (GeneralSecurityException e) {
                throw (IOException)new IOException("Failed to negotiate transport security").initCause(e);
            }
        }

        return new Channel("CLI connection to "+jenkins, pool,
                new BufferedInputStream(c.in), new BufferedOutputStream(c.out));
    }

    /**
     * If the server advertises CLI endpoint, returns its location.
     */
    private CliPort getCliTcpPort(String url) throws IOException {
        URL _url = new URL(url);
        if (_url.getHost()==null || _url.getHost().length()==0) {
            throw new IOException("Invalid URL: "+url);
        }
        URLConnection head = _url.openConnection();
        try {
            head.connect();
        } catch (IOException e) {
            throw (IOException)new IOException("Failed to connect to "+url).initCause(e);
        }

        String h = head.getHeaderField("X-Jenkins-CLI-Host");
        if (h==null)    h = head.getURL().getHost();
        String p1 = head.getHeaderField("X-Jenkins-CLI-Port");
        if (p1==null)    p1 = head.getHeaderField("X-Hudson-CLI-Port");   // backward compatibility
        String p2 = head.getHeaderField("X-Jenkins-CLI2-Port");

        String identity = head.getHeaderField("X-Instance-Identity");

        flushURLConnection(head);
        if (p1==null && p2==null) {
            throw new IOException("No X-Jenkins-CLI2-Port among " + head.getHeaderFields().keySet());
        }

        if (p2!=null)   return new CliPort(new InetSocketAddress(h,Integer.parseInt(p2)),identity,2);
        else            return new CliPort(new InetSocketAddress(h,Integer.parseInt(p1)),identity,1);
    }

    /**
     * Flush the supplied {@link URLConnection} input and close the
     * connection nicely.
     * @param conn the connection to flush/close
     */
    private void flushURLConnection(URLConnection conn) {
        byte[] buf = new byte[1024];
        try {
            InputStream is = conn.getInputStream();
            while (is.read(buf) >= 0) {
                // Ignore
            }
            is.close();
        } catch (IOException e) {
            try {
                InputStream es = ((HttpURLConnection)conn).getErrorStream();
                while (es.read(buf) >= 0) {
                    // Ignore
                }
                es.close();
            } catch (IOException ex) {
                // Ignore
            }
        }
    }

    /**
     * Shuts down the channel and closes the underlying connection.
     */
    public void close() throws IOException, InterruptedException {
        channel.close();
        channel.join();
        if(ownsPool)
            pool.shutdown();
        for (Closeable c : closables)
            c.close();
    }

    public int execute(List<String> args, InputStream stdin, OutputStream stdout, OutputStream stderr) {
        return entryPoint.main(args, Locale.getDefault(),
                new RemoteInputStream(stdin),
                new RemoteOutputStream(stdout),
                new RemoteOutputStream(stderr));
    }

    public int execute(List<String> args) {
        return execute(args, System.in, System.out, System.err);
    }

    public int execute(String... args) {
        return execute(Arrays.asList(args));
    }

    /**
     * Returns true if the named command exists.
     */
    public boolean hasCommand(String name) {
        return entryPoint.hasCommand(name);
    }

    /**
     * Accesses the underlying communication channel.
     * @since 1.419
     */
    public Channel getChannel() {
        return channel;
    }

    /**
     * Attempts to lift the security restriction on the underlying channel.
     * This requires the administer privilege on the server.
     *
     * @throws SecurityException
     *      If we fail to upgrade the connection.
     */
    public void upgrade() {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (execute(Arrays.asList("groovy", "="),
                new ByteArrayInputStream("hudson.remoting.Channel.current().setRestricted(false)".getBytes()),
                out,out)!=0)
            throw new SecurityException(out.toString()); // failed to upgrade
    }

    public static void main(final String[] _args) throws Exception {
//        Logger l = Logger.getLogger(Channel.class.getName());
//        l.setLevel(ALL);
//        ConsoleHandler h = new ConsoleHandler();
//        h.setLevel(ALL);
//        l.addHandler(h);
//
        System.exit(_main(_args));
    }

    public static int _main(String[] _args) throws Exception {
        List<String> args = Arrays.asList(_args);
        List<KeyPair> candidateKeys = new ArrayList<KeyPair>();
        boolean sshAuthRequestedExplicitly = false;
        String httpProxy=null;

        String url = System.getenv("JENKINS_URL");

        if (url==null)
            url = System.getenv("HUDSON_URL");

        while(!args.isEmpty()) {
            String head = args.get(0);
            if (head.equals("-version")) {
                System.out.println("Version: "+computeVersion());
                return 0;
            }
            if(head.equals("-s") && args.size()>=2) {
                url = args.get(1);
                args = args.subList(2,args.size());
                continue;
            }
            if (head.equals("-noCertificateCheck")) {
                System.out.println("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(null, new TrustManager[]{new NoCheckTrustManager()}, new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
                // bypass host name check, too.
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
                args = args.subList(1,args.size());
                continue;
            }
            if(head.equals("-i") && args.size()>=2) {
                File f = new File(args.get(1));
                if (!f.exists()) {
                    printUsage(Messages.CLI_NoSuchFileExists(f));
                    return -1;
                }
                KeyPair kp;
                try {
                    kp = loadKey(f);
                } catch (IOException e) {
                    //if the PEM file is encrypted, IOException is thrown
                    kp = tryEncryptedFile(f);
                } catch (GeneralSecurityException e) {
                    throw new Exception("Failed to load key: "+f,e);
                }
                if(kp != null)
                    candidateKeys.add(kp);
                args = args.subList(2,args.size());
                sshAuthRequestedExplicitly = true;
                continue;
            }
            if(head.equals("-p") && args.size()>=2) {
                httpProxy = args.get(1);
                args = args.subList(2,args.size());
                continue;
            }
            break;
        }

        if(url==null) {
            printUsage(Messages.CLI_NoURL());
            return -1;
        }

        if(args.isEmpty())
            args = Arrays.asList("help"); // default to help

        if (candidateKeys.isEmpty())
            addDefaultPrivateKeyLocations(candidateKeys);

        CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy);
        String userInfo = new URL(url).getUserInfo();
        if (userInfo != null) {
            factory = factory.basicAuth(userInfo);
        }

        CLI cli = factory.connect();
        try {
            if (!candidateKeys.isEmpty()) {
                try {
                    // TODO: server verification
                    cli.authenticate(candidateKeys);
                } catch (IllegalStateException e) {
                    if (sshAuthRequestedExplicitly) {
                        System.err.println("The server doesn't support public key authentication");
                        return -1;
                    }
                } catch (UnsupportedOperationException e) {
                    if (sshAuthRequestedExplicitly) {
                        System.err.println("The server doesn't support public key authentication");
                        return -1;
                    }
                } catch (GeneralSecurityException e) {
                    if (sshAuthRequestedExplicitly) {
                        System.err.println(e.getMessage());
                        LOGGER.log(FINE,e.getMessage(),e);
                        return -1;
                    }
                    System.err.println("[WARN] Failed to authenticate with your SSH keys. Proceeding as anonymous");
                    LOGGER.log(FINE,"Failed to authenticate with your SSH keys.",e);
                }
            }

            // execute the command
            // Arrays.asList is not serializable --- see 6835580
            args = new ArrayList<String>(args);
            return cli.execute(args, System.in, System.out, System.err);
        } finally {
            cli.close();
        }
    }

    private static String computeVersion() {
        Properties props = new Properties();
        try {
            InputStream is = CLI.class.getResourceAsStream("/jenkins/cli/jenkins-cli-version.properties");
            if(is!=null)
                props.load(is);
        } catch (IOException e) {
            e.printStackTrace(); // if the version properties is missing, that's OK.
        }
        return props.getProperty("version","?");
    }

    /**
     * Loads RSA/DSA private key in a PEM format into {@link KeyPair}.
     */
    public static KeyPair loadKey(File f, String passwd) throws IOException, GeneralSecurityException {
        return loadKey(readPemFile(f), passwd);
    }

    public static KeyPair loadKey(File f) throws IOException, GeneralSecurityException {
    	return loadKey(f, null);
    }

    private static String readPemFile(File f) throws IOException{
        DataInputStream dis = new DataInputStream(new FileInputStream(f));
        byte[] bytes = new byte[(int) f.length()];
        dis.readFully(bytes);
        dis.close();
        return new String(bytes);
    }

    /**
     * Loads RSA/DSA private key in a PEM format into {@link KeyPair}.
     */
    public static KeyPair loadKey(String pemString, String passwd) throws IOException, GeneralSecurityException {
        Object key = PEMDecoder.decode(pemString.toCharArray(), passwd);
        if (key instanceof com.trilead.ssh2.signature.RSAPrivateKey) {
            com.trilead.ssh2.signature.RSAPrivateKey x = (com.trilead.ssh2.signature.RSAPrivateKey)key;
//            System.out.println("ssh-rsa " + new String(Base64.encode(RSASHA1Verify.encodeSSHRSAPublicKey(x.getPublicKey()))));

            return x.toJCEKeyPair();
        }
        if (key instanceof com.trilead.ssh2.signature.DSAPrivateKey) {
            com.trilead.ssh2.signature.DSAPrivateKey x = (com.trilead.ssh2.signature.DSAPrivateKey)key;
            KeyFactory kf = KeyFactory.getInstance("DSA");
//            System.out.println("ssh-dsa " + new String(Base64.encode(DSASHA1Verify.encodeSSHDSAPublicKey(x.getPublicKey()))));

            return new KeyPair(
                    kf.generatePublic(new DSAPublicKeySpec(x.getY(), x.getP(), x.getQ(), x.getG())),
                    kf.generatePrivate(new DSAPrivateKeySpec(x.getX(), x.getP(), x.getQ(), x.getG())));
        }

        throw new UnsupportedOperationException("Unrecognizable key format: "+key);
    }

    public static KeyPair loadKey(String pemString) throws IOException, GeneralSecurityException {
    	return loadKey(pemString, null);
    }

    private static KeyPair tryEncryptedFile(File f) throws IOException, GeneralSecurityException{
        KeyPair kp = null;
        if(isPemEncrypted(f)){
            String passwd = askForPasswd(f.getCanonicalPath());
            kp = loadKey(f,passwd);
        }
        return kp;
    }

    private static boolean isPemEncrypted(File f) throws IOException{
        String pemString = readPemFile(f);
        //simple check if the file is encrypted
        return pemString.contains("4,ENCRYPTED");
    }

    @SuppressWarnings("Since15")
    @IgnoreJRERequirement
    private static String askForPasswd(String filePath){
        try {
            Console cons = System.console();
            String passwd = null;
            if (cons != null){
                char[] p = cons.readPassword("%s", "Enter passphrase for "+filePath+":");
                passwd = String.valueOf(p);
            }
            return passwd;
        } catch (LinkageError e) {
            throw new Error("Your private key is encrypted, but we need Java6 to ask you password safely",e);
        }
    }

    /**
     * try all the default key locations
     */
    private static void addDefaultPrivateKeyLocations(List<KeyPair> keyFileCandidates) {
        File home = new File(System.getProperty("user.home"));
        for (String path : new String[]{".ssh/id_rsa",".ssh/id_dsa",".ssh/identity"}) {
            File key = new File(home,path);
            if (key.exists()) {
                try {
                    keyFileCandidates.add(loadKey(key));
                } catch (IOException e) {
                    // don't report an error. the user can still see it by using the -i option
                    LOGGER.log(FINE, "Failed to load "+key,e);
                } catch (GeneralSecurityException e) {
                    LOGGER.log(FINE, "Failed to load " + key, e);
                }
            }
        }
    }

    /**
     * Authenticate ourselves against the server.
     *
     * @return
     *      identity of the server represented as a public key.
     */
    public PublicKey authenticate(Iterable<KeyPair> privateKeys) throws IOException, GeneralSecurityException {
        Pipe c2s = Pipe.createLocalToRemote();
        Pipe s2c = Pipe.createRemoteToLocal();
        entryPoint.authenticate("ssh",c2s, s2c);
        Connection c = new Connection(s2c.getIn(), c2s.getOut());

        try {
            byte[] sharedSecret = c.diffieHellman(false).generateSecret();
            PublicKey serverIdentity = c.verifyIdentity(sharedSecret);

            // try all the public keys
            for (KeyPair key : privateKeys) {
                c.proveIdentity(sharedSecret,key);
                if (c.readBoolean())
                    return serverIdentity;  // succeeded
            }
            if (privateKeys.iterator().hasNext())
                throw new GeneralSecurityException("Authentication failed. No private key accepted.");
            else
                throw new GeneralSecurityException("No private key is available for use in authentication");
        } finally {
            c.close();
        }
    }

    public PublicKey authenticate(KeyPair key) throws IOException, GeneralSecurityException {
        return authenticate(Collections.singleton(key));
    }

    private static void printUsage(String msg) {
        if(msg!=null)   System.out.println(msg);
        System.err.println(Messages.CLI_Usage());
    }

    private static final Logger LOGGER = Logger.getLogger(CLI.class.getName());
}


text:
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package h2o.jodd.typeconverter.impl;

import h2o.common.lang.LTime;
import h2o.common.lang.SDate;
import h2o.common.lang.SDateTime;
import h2o.common.lang.SNumber;
import h2o.jodd.time.JulianDate;
import h2o.jodd.time.TimeUtil;
import h2o.jodd.typeconverter.TypeConversionException;
import h2o.jodd.typeconverter.TypeConverter;
import h2o.jodd.util.StringUtil;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * Converts given object to Byte.
 * Conversion rules:
 *

 *
null value is returned as null

 *
object of destination type is simply casted

 *
Date object is converted

 *
JulianDate object is converted

 *
LocalDateTime object is converted

 *
LocalDate object is converted

 *
Number is used as number of milliseconds

 *
finally, if string value contains only numbers it is parsed as milliseconds

 *

 */
public class CalendarConverter implements TypeConverter<Calendar> {

	@Override
	public Calendar convert(final Object value) {
		if (value == null) {
			return null;
		}
		if (value instanceof Calendar) {
			return (Calendar) value;
		}
		if (value instanceof Date) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime((Date) value);
			return calendar;
		}
		if (value instanceof JulianDate) {
			return TimeUtil.toCalendar(((JulianDate)value).toLocalDateTime());
		}
		if (value instanceof LocalDateTime) {
			return TimeUtil.toCalendar((LocalDateTime)value);
		}
		if (value instanceof LocalDate) {
			return TimeUtil.toCalendar((LocalDate)value);
		}

		if ( value instanceof SDate ) {
			if ( ((SDate) value).isPresent() ) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(((SDate) value).toDate());
				return calendar;
			} else {
				return null;
			}
		}

		if ( value instanceof SDateTime) {
			if ( ((SDateTime) value).isPresent() ) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(((SDateTime) value).toDate());
				return calendar;
			} else {
				return null;
			}
		}

		if ( value instanceof LTime) {
			if ( ((LTime) value).isPresent() ) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(((LTime) value).getValue());
				return calendar;
			} else {
				return null;
			}
		}

		if ( value instanceof SNumber) {
			if ( ((SNumber) value).isPresent() ) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(((Number) value).longValue());
				return calendar;
			} else {
				return null;
			}
		}

		if (value instanceof Number) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(((Number) value).longValue());
			return calendar;
		}

		String stringValue = value.toString().trim();

		if (!StringUtil.containsOnlyDigits(stringValue)) {
			// try to parse default string format
			return TimeUtil.toCalendar(LocalDateTime.parse(stringValue));
		}

		try {
			long milliseconds = Long.parseLong(stringValue);
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(milliseconds);
			return calendar;
		} catch (NumberFormatException nfex) {
			throw new TypeConversionException(value, nfex);
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
namespace blink {

SerializedContentHintType SerializeContentHint(
    WebMediaStreamTrack::ContentHintType type) {
  switch (type) {
    case WebMediaStreamTrack::ContentHintType::kNone:
      return SerializedContentHintType::kNone;
    case WebMediaStreamTrack::ContentHintType::kAudioSpeech:
      return SerializedContentHintType::kAudioSpeech;
    case WebMediaStreamTrack::ContentHintType::kAudioMusic:
      return SerializedContentHintType::kAudioMusic;
    case WebMediaStreamTrack::ContentHintType::kVideoMotion:
      return SerializedContentHintType::kVideoMotion;
    case WebMediaStreamTrack::ContentHintType::kVideoDetail:
      return SerializedContentHintType::kVideoDetail;
    case WebMediaStreamTrack::ContentHintType::kVideoText:
      return SerializedContentHintType::kVideoText;
  }
  // Exhaustive list of enum values of WebMediaStreamTrack::ContentHintType. If
  // new values are added in enum WebMediaStreamTrack::ContentHintType, then add
  // them here as well. Do not use default.
  NOTREACHED();
  return SerializedContentHintType::kNone;
}

SerializedReadyState SerializeReadyState(MediaStreamSource::ReadyState state) {
  switch (state) {
    case MediaStreamSource::kReadyStateLive:
      return SerializedReadyState::kReadyStateLive;
    case MediaStreamSource::kReadyStateMuted:
      return SerializedReadyState::kReadyStateMuted;
    case MediaStreamSource::kReadyStateEnded:
      return SerializedReadyState::kReadyStateEnded;
  }
  // Exhaustive list of enum values of MediaStreamSource::ReadyState. If new
  // values are added in enum MediaStreamSource::ReadyState, then add them here
  // as well. Do not use default.
  NOTREACHED();
  return SerializedReadyState::kReadyStateEnded;
}

WebMediaStreamTrack::ContentHintType DeserializeContentHint(
    SerializedContentHintType type) {
  switch (type) {
    case SerializedContentHintType::kNone:
      return WebMediaStreamTrack::ContentHintType::kNone;
    case SerializedContentHintType::kAudioSpeech:
      return WebMediaStreamTrack::ContentHintType::kAudioSpeech;
    case SerializedContentHintType::kAudioMusic:
      return WebMediaStreamTrack::ContentHintType::kAudioMusic;
    case SerializedContentHintType::kVideoMotion:
      return WebMediaStreamTrack::ContentHintType::kVideoMotion;
    case SerializedContentHintType::kVideoDetail:
      return WebMediaStreamTrack::ContentHintType::kVideoDetail;
    case SerializedContentHintType::kVideoText:
      return WebMediaStreamTrack::ContentHintType::kVideoText;
  }
}

MediaStreamSource::ReadyState DeserializeReadyState(
    SerializedReadyState state) {
  switch (state) {
    case SerializedReadyState::kReadyStateLive:
      return MediaStreamSource::kReadyStateLive;
    case SerializedReadyState::kReadyStateMuted:
      return MediaStreamSource::kReadyStateMuted;
    case SerializedReadyState::kReadyStateEnded:
      return MediaStreamSource::kReadyStateEnded;
  }
}

}  // namespace blink


text:
"""Unittests for the utilities.py module"""
import unittest
from ini_handler.utilities import validate_key_type

class TestUtilities(unittest.TestCase):

    def test_validate_key_type(self):
        validate_key_type('test')

    def test_validate_key_type_with_error(self):
        with self.assertRaises(TypeError):
            validate_key_type(3)

if __name__ == '__main__':
    unittest.main()


text:
import { CommandPacket } from "../command-packet"
import { ErrorPacket } from "../error-packet"
import { IPacket } from "../packet"
import { MiscellaneousPacket } from "../miscellaneous-packet"
import { PacketType } from "../packet-type"
import { SerialDataPacket } from "../serial-data-packet"
import { SerialListPacket } from "../serial-list-packet"
import { SerialStatusPacket } from "../serial-status-packet"

import {
    IDiscordWebhookLogger, DiscordWebhookLogger,
    ISlackAttachment,
    ISlackField,
} from "../../discord/discord-webhook-logger"

const debug = require('debug')('Packet Logger')

export interface IPacketLogger {
    isConfigured: boolean
    configure(name: string, webhookId: string, webhookToken: string): boolean
    log(packet: IPacket): void
}

export class PacketLogger implements IPacketLogger {
    public name: string

    private _isConfigured: boolean = false
    private webhook: IDiscordWebhookLogger | null = null

    constructor() {
    }

    public get isConfigured(): boolean {
        return this._isConfigured
    }

    public configure = (name: string, webhookId: string, webhookToken: string): boolean => {
        // Shut down old.
        this._isConfigured = false
        this.webhook = null

        if (!name || !webhookId || !webhookToken) {
            debug(`Can't configure Discord.`)
            return false
        }

        this.name = name
        this.webhook = new DiscordWebhookLogger(webhookId, webhookToken)
        this._isConfigured = true

        debug('Configured Discord for ', name)
        return true
    }

    public log = (packet: IPacket): void => {
        if (!this.isConfigured) {
            debug('Tried to log packet but not configured. ', packet)
            return
        }

        if (!packet) {
            if (this.webhook)
                this.webhook.plainText('Tried to transmit an empty packet.')
            return
        }

        let type = PacketType[packet.packetType]
        if (packet.packetType == PacketType.Miscellaneous)
            this.logMiscellaneousPacket(packet)
        else if (packet.packetType == PacketType.Data)
            this.logDataPacket(packet)
        else if (packet.packetType == PacketType.Error)
            this.logErrorPacket(packet)
        else if (packet.packetType == PacketType.List)
            this.logListPacket(packet)
        else if (packet.packetType == PacketType.Status)
            this.logStatusPacket(packet)
        else if (packet.packetType == PacketType.Command)
            this.logCommandPacket(packet)
        else {
            debug('Sending raw text to the webhook: ', packet)
            if (this.webhook)
                this.webhook.plainText(`${this.name}: ${type}`)
        }
    }

    private getFooter = (packet: IPacket): string => {
        if (!packet.connectionId)
            return ''
        else
            return `${packet.connectionId} #${packet.sequence}`
    }

    private logCommandPacket = (packet: IPacket): void => {
        let command: string = (<CommandPacket>packet).command
        let device: string | undefined = (<CommandPacket>packet).device
        let data: string | undefined = (<CommandPacket>packet).data

        let value: string = `${command} ${device || ''}${data || ''}`

        let date = new Date()
        let attachments: ISlackAttachment[] = [{
            color: '#f80',
            title: 'Command',
            text: `\`${value}\``,
            footer: this.getFooter(packet),
            fields: [
                {value: date.toLocaleDateString(), short: true},
                {value: date.toLocaleTimeString(), short: true},
            ],
        }]

        debug('Sending command packet to the webhook: ', value, attachments, this.name)
        if (this.webhook)
            this.webhook.rawSlack(attachments, this.name)
    }

    private logDataPacket = (packet: IPacket): void => {
        let value: string = (<SerialDataPacket>packet).data

        let date = new Date()
        let attachments: ISlackAttachment[] = [{
            color: '#0f0',
            title: 'Data',
            text: `\`${value}\``,
            footer: this.getFooter(packet),
            fields: [
                {value: date.toLocaleDateString(), short: true},
                {value: date.toLocaleTimeString(), short: true},
            ],
        }]

        debug('Sending data packet to the webhook: ', value, attachments, this.name)
        if (this.webhook)
            this.webhook.rawSlack(attachments, this.name)
    }

    private logErrorPacket = (packet: IPacket): void => {
        let message: string = (<ErrorPacket>packet).message
        let error: string = (<ErrorPacket>packet).error

        let date = new Date()
        let attachments: ISlackAttachment[] = [{
            color: '#f00',
            title: 'Error',
            text: `${message}\n\`${error}\``,
            footer: this.getFooter(packet),
            fields: [
                {value: date.toLocaleDateString(), short: true},
                {value: date.toLocaleTimeString(), short: true},
            ],
        }]

        debug('Sending data packet to the webhook: ', attachments, this.name)
        if (this.webhook)
            this.webhook.rawSlack(attachments, this.name)
    }

    private logListPacket = (packet: IPacket): void => {
        let list = (<SerialListPacket>packet).list

        let fields: ISlackField[] = []
        for (let l of list) {

            let field: ISlackField = {
                title: l.device,
                value: '',
                short: false,
            }

            // There are several conditional values to add to "value".
            if (l.prefer)
                field.value += '[Prefer]'

            if (l.connected)
                field.value += ' **Connected**'

            if (l.vendor)
                field.value += ` ${l.vendor}`

            if (l.vendorId)
                field.value += ` \`${l.vendorId}\``

            if (l.productId)
                field.value += ` \`${l.productId}\``

            field.value = field.value.trim()

            fields.push(field)
        }

        let date = new Date()
        fields.push({value: date.toLocaleDateString(), short: true})
        fields.push({value: date.toLocaleTimeString(), short: true})

        let attachments: ISlackAttachment[] = [{
            color: '#f0f',
            title: 'List',
            footer: this.getFooter(packet),
            fields: fields,
        }]

        debug('Sending data packet to the webhook: ', attachments, this.name)
        if (this.webhook)
            this.webhook.rawSlack(attachments, this.name)
    }

    private logMiscellaneousPacket = (packet: IPacket): void => {
        let value: string = (<MiscellaneousPacket>packet).message

        let date = new Date()
        let attachments: ISlackAttachment[] = [{
            color: '#ff0',
            title: 'Miscellaneous',
            text: value,
            footer: this.getFooter(packet),
            fields: [
                {value: date.toLocaleDateString(), short: true},
                {value: date.toLocaleTimeString(), short: true},
            ],
        }]

        debug('Sending data packet to the webhook: ', value, attachments, this.name)
        if (this.webhook)
            this.webhook.rawSlack(attachments, this.name)
    }

    private logStatusPacket = (packet: IPacket): void => {
        let connected: boolean = (<SerialStatusPacket>packet).connected
        let device: string = (<SerialStatusPacket>packet).device

        let color = connected ? '#0ff' : '#044'
        let state = connected ? `Connected to \`${device}\`` : 'Disconnected'

        let date = new Date()
        let attachments: ISlackAttachment[] = [{
            color: color,
            title: 'Status',
            text: state,
            footer: this.getFooter(packet),
            fields: [
                {value: date.toLocaleDateString(), short: true},
                {value: date.toLocaleTimeString(), short: true},
            ],
        }]

        debug('Sending data packet to the webhook: ', attachments, this.name)
        if (this.webhook)
            this.webhook.rawSlack(attachments, this.name)
    }
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Object = Google.Apis.Storage.v1.Data.Object;

namespace Google.Cloud.Storage.V1
{
    public abstract partial class StorageClient
    {
        /// <summary>
        /// Patches the metadata for an object in storage synchronously.
        /// </summary>
        /// <param name="obj">Object to update. Must not be null, and must have populated <c>Name</c> and
        /// <c>Bucket</c> properties.</param>
        /// <param name="options">Additional options for the update. May be null, in which case appropriate
        /// defaults will be used.</param>
        /// <returns>The <see cref="Object"/> representation of the updated storage object.</returns>
        public virtual Object PatchObject(
            Object obj,
            PatchObjectOptions options = null)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Patches the metadata for an object in storage asynchronously.
        /// </summary>
        /// <param name="obj">Object to update. Must not be null, and must have populated <c>Name</c> and
        /// <c>Bucket</c> properties.</param>
        /// <param name="options">Additional options for the update. May be null, in which case appropriate
        /// defaults will be used.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A task representing the asynchronous operation, with a result returning the
        /// <see cref="Object"/> representation of the updated storage object.</returns>
        public virtual Task<Object> PatchObjectAsync(
            Object obj,
            PatchObjectOptions options = null,
            CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }
    }
}


text:
/**
 * @author Jon Carey
 * @author Dan Nuffer
 */

#include "OW_config.h"
#include "OW_Runnable.hpp"
#include "OW_Thread.hpp"

namespace OW_NAMESPACE
{

/////////////////////////////////////////////////////////////////////////////
Runnable::~Runnable()
{
}

/////////////////////////////////////////////////////////////////////////////
void
Runnable::doCooperativeCancel()
{
}

/////////////////////////////////////////////////////////////////////////////
void
Runnable::doDefinitiveCancel()
{
}

} // end namespace OW_NAMESPACE


text:
package service.dao.models;

import java.util.Objects;

public class Address {

    private int id;
    private String country;
    private String city;
    private String street;
    private int home;
    private int apart;
    private User user;

    public Address() {
    }

    public Address(String country, String city, String street, int home, int apart, User user) {
        this.country = country;
        this.city = city;
        this.street = street;
        this.home = home;
        this.apart = apart;
        this.user = user;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public int getHome() {
        return home;
    }

    public void setHome(int home) {
        this.home = home;
    }

    public int getApart() {
        return apart;
    }

    public void setApart(int apart) {
        this.apart = apart;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Address address = (Address) o;
        return getId() == address.getId() &&
                getHome() == address.getHome() &&
                getApart() == address.getApart() &&
                Objects.equals(getCountry(), address.getCountry()) &&
                Objects.equals(getCity(), address.getCity()) &&
                Objects.equals(getStreet(), address.getStreet()) &&
                Objects.equals(getUser(), address.getUser());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getId(), getCountry(), getCity(), getStreet(), getHome(), getApart(), getUser());
    }

    @Override
    public String toString() {
        return String.format("Address id = %d; %nCountry = %s;%n Town = %s;%nAddress = %s; home %d; apart %d", id, country, city, street, home, apart);
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.datapipelines.v1.model;

/**
 * Definition of the job information maintained by the pipeline. Fields in this entity are retrieved
 * from the executor API (e.g. Dataflow API).
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Data pipelines API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDatapipelinesV1Job extends com.google.api.client.json.GenericJson {

  /**
   * Output only. The time of job creation.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String createTime;

  /**
   * All the details that are specific to a Dataflow job.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudDatapipelinesV1DataflowJobDetails dataflowJobDetails;

  /**
   * Output only. The time of job termination. This is absent if the job is still running.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String endTime;

  /**
   * Output only. The internal ID for the job.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String id;

  /**
   * Required. The fully qualified resource name for the job.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * The current state of the job.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String state;

  /**
   * Status capturing any error code or message related to job creation or execution.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleRpcStatus status;

  /**
   * Output only. The time of job creation.
   * @return value or {@code null} for none
   */
  public String getCreateTime() {
    return createTime;
  }

  /**
   * Output only. The time of job creation.
   * @param createTime createTime or {@code null} for none
   */
  public GoogleCloudDatapipelinesV1Job setCreateTime(String createTime) {
    this.createTime = createTime;
    return this;
  }

  /**
   * All the details that are specific to a Dataflow job.
   * @return value or {@code null} for none
   */
  public GoogleCloudDatapipelinesV1DataflowJobDetails getDataflowJobDetails() {
    return dataflowJobDetails;
  }

  /**
   * All the details that are specific to a Dataflow job.
   * @param dataflowJobDetails dataflowJobDetails or {@code null} for none
   */
  public GoogleCloudDatapipelinesV1Job setDataflowJobDetails(GoogleCloudDatapipelinesV1DataflowJobDetails dataflowJobDetails) {
    this.dataflowJobDetails = dataflowJobDetails;
    return this;
  }

  /**
   * Output only. The time of job termination. This is absent if the job is still running.
   * @return value or {@code null} for none
   */
  public String getEndTime() {
    return endTime;
  }

  /**
   * Output only. The time of job termination. This is absent if the job is still running.
   * @param endTime endTime or {@code null} for none
   */
  public GoogleCloudDatapipelinesV1Job setEndTime(String endTime) {
    this.endTime = endTime;
    return this;
  }

  /**
   * Output only. The internal ID for the job.
   * @return value or {@code null} for none
   */
  public java.lang.String getId() {
    return id;
  }

  /**
   * Output only. The internal ID for the job.
   * @param id id or {@code null} for none
   */
  public GoogleCloudDatapipelinesV1Job setId(java.lang.String id) {
    this.id = id;
    return this;
  }

  /**
   * Required. The fully qualified resource name for the job.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Required. The fully qualified resource name for the job.
   * @param name name or {@code null} for none
   */
  public GoogleCloudDatapipelinesV1Job setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * The current state of the job.
   * @return value or {@code null} for none
   */
  public java.lang.String getState() {
    return state;
  }

  /**
   * The current state of the job.
   * @param state state or {@code null} for none
   */
  public GoogleCloudDatapipelinesV1Job setState(java.lang.String state) {
    this.state = state;
    return this;
  }

  /**
   * Status capturing any error code or message related to job creation or execution.
   * @return value or {@code null} for none
   */
  public GoogleRpcStatus getStatus() {
    return status;
  }

  /**
   * Status capturing any error code or message related to job creation or execution.
   * @param status status or {@code null} for none
   */
  public GoogleCloudDatapipelinesV1Job setStatus(GoogleRpcStatus status) {
    this.status = status;
    return this;
  }

  @Override
  public GoogleCloudDatapipelinesV1Job set(String fieldName, Object value) {
    return (GoogleCloudDatapipelinesV1Job) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudDatapipelinesV1Job clone() {
    return (GoogleCloudDatapipelinesV1Job) super.clone();
  }

}


text:
Used to highlight a certain number or group of numbers, such as showing a numerical value, such as a dollar amount, ranking, etc.

Countdown mode

### Basic usage
The component provides a thousandth place display, but you can use rate to set the 10,000th place, and so on
:::demo
```html
<template>
  <div >
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <el-statistic group-separator="," :precision="2" :value="value2" :title="title"></el-statistic>
          </div>
        </el-col>
            <el-col :span="6">
          <div>
            <el-statistic  title="Gender Distribution">
              <template slot="formatter">
                  456/2
              </template>

            </el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <el-statistic group-separator="," :precision="2" decimal-separator="." :value="value1" :title="title">
              <template slot="prefix">
                <i class="el-icon-s-flag" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-s-flag" style="color: blue"></i>
              </template>
            </el-statistic>
          </div>

    </el-col>
    <el-col :span="6">
      <div>
        <el-statistic :value="like ? 521 : 520" title="Feedback">
          <template slot="suffix">
            <span @click="like = !like" class="like">
              <i class="el-icon-star-on" style="color:red" v-show="!!like"></i>
              <i class="el-icon-star-off"  v-show="!like"></i>
            </span> </template>
        </el-statistic>
      </div>
    </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      like: true,
      value1: 4154.564,
      value2: 2222,
      title: "Growth this year",
      input: "Hello Element UI!",
    };
  },
};
</script>
<style lang="scss" >
.like {
  cursor: pointer;
  font-size: 25px;
  display: inline-block;
}
</style>
```
:::

### 倒计时
:::warning
Suspend is tentative, it ** just pauses the countdown, not the time, because value points to a future time node **

If you need to add time to the original, please note that the overall time (the amount of time added and the original time) must be a ** future ** time node, otherwise it is still the end of the countdown
:::
:::demo Providing a future time via 'value' will enable the countdown function
```html
<template>
  <div >
    <el-row :gutter="20">
  <el-col :span="14">
     <div style="width: 100%; display: inline-block; ">
      <el-statistic :value="deadline2"  time-indices title="商品降价">
        <template slot="suffix">
          The rush is about to begin
        </template>
      </el-statistic>
    </div>
    <div style="width: 100%; display: inline-block; margin-top: 50px; ">
      <el-statistic @finish="hilarity" :value="deadline3"   time-indices title="The Value of Time">
        <template slot="suffix">
          <el-button type="primary " size="small" @click="add">add 10 second</el-button>
        </template>
      </el-statistic>
    </div>

  </el-col>
  <el-col :span="10">
        <el-card  shadow="hover"  style="width: 100%;">
  <div slot="header" class="clearfix">
    <span>文嘉《明日歌》</span>
    <el-button style="float: right; padding: 3px 0" type="text" @click="clickFn">暂停</el-button>
  </div>
  <div style="font-size: 18px;text-align: center; " >明日复明日</div>
  <div style="font-size: 18px;text-align: center;" >明日何其多</div>

  <div style="font-size: 18px;text-align: center;" >我生待明日</div>

  <div style="font-size: 18px;text-align: center;" >万事成蹉跎</div>
<div style="margin-top: 40px;"></div>
  <el-statistic ref="statistic" @finish="hilarity" format="HH:mm:ss" :value="deadline4" title="Distance to Tomorrow:" time-indices > </el-statistic>
</el-card>
  </el-col>
</el-row>

  </div>
</template>

<script>
export default {
  data() {
    return {
      format:'HH小时:mm:ss:SSS',
      deadline: Date.now() + 1000 * 60 * 60 * 24 * 2,
      deadline2: Date.now() + 1000 * 60 * 60 * 8,
      deadline3: Date.now() + 1000 *  60 *30,
        deadline4: Date.now() + (new Date().setHours(23,59,59)-Date.now()) ,
    };
  },
  methods: {
    hilarity() {
      this.$notify({
          title: 'Prompt',
          message: "Time is up, do you know that an inch of gold can't buy an inch of time?",
          duration: 0
        });
    },
        clickFn(){
       this.$refs.statistic.suspend( this.stop)
         this.stop=!this.stop
    },
    add(){
      this.deadline3= this.deadline3+ 1000 * 10
    }
  }
};
</script>
<style lang="scss" >
.like {
  cursor: pointer;
  font-size: 25px;
  display: inline-block;
}
</style>
```
:::

### Statistic Attributes

| Attribute          | Description            | Type            | Accepted Values                 | Default   |
|-------------  |---------------- |---------------- |---------------------- |-------- |
| value            | Numerical content                 | string \| number    | -          | -       |
| decimal-separator | Setting the decimal point            | string                  | -      | .       |
| formatter        | Custom numerical presentation| v-slot \|({value}) => VNode | -   | -      |
| group-separator   | Sets the thousandth identifier              | string           | -             | ,       |
| precision        | numerical precision      | number                | -        | 0      |
| prefix           | Sets the prefix of a number          | string \| v-slot | -             | -       |
| suffix           |Sets the suffix of a number          | string \| v-slot     | -         | -       |
| title            | 	Numeric titles               | string \| v-slot   | -           | -       |
| value-style        | Styles numeric values          | style             | -            | -       |
| rate       | Set the ratio          | number             | -            | 1000       |

### Statistic Slots
| Name | Description |
|------|--------|
| prefix | Numeric prefix |
| suffix | Suffixes for numeric values |
| formatter | Numerical content |
| title | Numeric titles |

### Statistic.Countdown  Attributes

| Attribute          | Description            | Type            | Options                 | Default   |
|-------------  |---------------- |---------------- |---------------------- |-------- |
| time-indices       | Whether to enable the countdown function     | boolean     | true\|false                        | false      |
| value         | Required value, enter the bound value   | string  | — | — |
| format         | Formatting the countdown display   | string  | — | 'HH:mm:ss' |
### Statistic.Countdown Events
| Method | Description | Parameters |
|---------|--------|---------|
| change | Enable in the 'countdown' function | (value:  Date) |
| finish | Launched after the 'countdown' is complete | (value: boolean) |

### Statistic Methods
| Method | Description | Parameters |CallBack|
| ---- | ---- | ---- |---- |
| suspend | Pause the countdown|(value:boolean) |(value:  Date) |


text:
using System;
using System.Collections.Generic;
using _01.Generic_Box;

namespace _02.GenericBoxString
{
    public class Startup
    {
        public static void Main()
        {
            var n = int.Parse(Console.ReadLine());
            var boxes = new List<Box<string>>();

            for (int i = 0; i < n; i++)
            {
                var input = Console.ReadLine();
                boxes.Add(new Box<string>(input));
            }

            boxes.ForEach(b => Console.WriteLine(b.ToString()));
        }
    }
}


text:
BoronCalc
=========

MtG Calculator Chrome app for Android and Chrome

This is the source code for BoronCalc, a Magic the Gathering utility for Chrome and Android.
Currently super simple and plain, but much is in store.


text:
using System.Collections.Generic;
using System.Net.Mail;
using Umbraco.Core.Models;

namespace FormEditor.Fields
{
	public class EmailField : FieldWithPlaceholder
	{
		public override string PrettyName => "Email address";

		public override string Type => "core.email";

		public bool Multiple { get; set; }

		protected internal override bool ValidateSubmittedValue(IEnumerable<Field> allCollectedValues, IPublishedContent content)
		{
			if (base.ValidateSubmittedValue(allCollectedValues, content) == false)
			{
				return false;
			}
			if (string.IsNullOrEmpty(SubmittedValue))
			{
				return true;
			}
			var emails = Multiple ? SubmittedValue.Split(',') : new[] { SubmittedValue };
			foreach (var email in emails)
			{
				try
				{
					var address = new MailAddress(email);
				}
				catch
				{
					return false;
				}
			}
			return true;
		}

		public IEnumerable<MailAddress> GetSubmittedMailAddresses()
		{
			var mailAddresses = new List<MailAddress>();
			foreach(var email in SubmittedValue.Split(','))
			{
				try
				{
					mailAddresses.Add(new MailAddress(email));
				}
				catch
				{
					// silently fail for invalid email addresses
				}
			}
			return mailAddresses;
		}
	}
}