text:
package com.amazonaws.services.quicksight.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The display options for the layout of tiles on a sheet.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TileLayoutStyle implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The gutter settings that apply between tiles.
     *

     */
    private GutterStyle gutter;
    /**
     *

     * The margin settings that apply around the outside edge of sheets.
     *

     */
    private MarginStyle margin;

    /**
     *

     * The gutter settings that apply between tiles.
     *

     *
     * @param gutter
     *        The gutter settings that apply between tiles.
     */

    public void setGutter(GutterStyle gutter) {
        this.gutter = gutter;
    }

    /**
     *

     * The gutter settings that apply between tiles.
     *

     *
     * @return The gutter settings that apply between tiles.
     */

    public GutterStyle getGutter() {
        return this.gutter;
    }

    /**
     *

     * The gutter settings that apply between tiles.
     *

     *
     * @param gutter
     *        The gutter settings that apply between tiles.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TileLayoutStyle withGutter(GutterStyle gutter) {
        setGutter(gutter);
        return this;
    }

    /**
     *

     * The margin settings that apply around the outside edge of sheets.
     *

     *
     * @param margin
     *        The margin settings that apply around the outside edge of sheets.
     */

    public void setMargin(MarginStyle margin) {
        this.margin = margin;
    }

    /**
     *

     * The margin settings that apply around the outside edge of sheets.
     *

     *
     * @return The margin settings that apply around the outside edge of sheets.
     */

    public MarginStyle getMargin() {
        return this.margin;
    }

    /**
     *

     * The margin settings that apply around the outside edge of sheets.
     *

     *
     * @param margin
     *        The margin settings that apply around the outside edge of sheets.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TileLayoutStyle withMargin(MarginStyle margin) {
        setMargin(margin);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getGutter() != null)
            sb.append("Gutter: ").append(getGutter()).append(",");
        if (getMargin() != null)
            sb.append("Margin: ").append(getMargin());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof TileLayoutStyle == false)
            return false;
        TileLayoutStyle other = (TileLayoutStyle) obj;
        if (other.getGutter() == null ^ this.getGutter() == null)
            return false;
        if (other.getGutter() != null && other.getGutter().equals(this.getGutter()) == false)
            return false;
        if (other.getMargin() == null ^ this.getMargin() == null)
            return false;
        if (other.getMargin() != null && other.getMargin().equals(this.getMargin()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getGutter() == null) ? 0 : getGutter().hashCode());
        hashCode = prime * hashCode + ((getMargin() == null) ? 0 : getMargin().hashCode());
        return hashCode;
    }

    @Override
    public TileLayoutStyle clone() {
        try {
            return (TileLayoutStyle) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.quicksight.model.transform.TileLayoutStyleMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package org.apache.ignite.configuration;

import java.io.Serializable;
import javax.cache.configuration.Factory;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.eviction.EvictionPolicy;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.jetbrains.annotations.Nullable;

import static org.apache.ignite.configuration.CacheConfiguration.DFLT_NEAR_START_SIZE;

/**
 * Client (near) cache configuration.
 * <p>
 * Distributed cache can also be fronted by a Near cache,
 * which is a smaller local cache that stores most recently
 * or most frequently accessed data. Just like with a partitioned cache,
 * the user can control the size of the near cache and its eviction policies.
 */
public class NearCacheConfiguration<K, V> implements Serializable {
    /** */
    private static final long serialVersionUID = 0L;

    /** Near cache eviction policy. */
    @Deprecated
    private EvictionPolicy<K, V> nearEvictPlc;

    /** Near cache eviction policy factory. */
    private Factory nearEvictPlcFactory;

    /** Default near cache start size. */
    private int nearStartSize = DFLT_NEAR_START_SIZE;

    /**
     * Empty constructor.
     */
    public NearCacheConfiguration() {
        // No-op.
    }

    /**
     * Creates near cache configuration copying properties from passed in configuration.
     *
     * @param ccfg Configuration to copy.
     */
    public NearCacheConfiguration(NearCacheConfiguration<K, V> ccfg) {
        nearEvictPlcFactory = ccfg.getNearEvictionPolicyFactory();
        nearEvictPlc = ccfg.getNearEvictionPolicy();
        nearStartSize = ccfg.getNearStartSize();
    }

    /**
     * Gets near eviction policy. By default, returns {@code null}
     * which means that evictions are disabled for near cache.
     *
     * @return Near eviction policy.
     * @see CacheConfiguration#getEvictionPolicy()
     *
     * @deprecated Use {@link #getNearEvictionPolicyFactory()}  instead.
     */
    @Deprecated
    public EvictionPolicy<K, V> getNearEvictionPolicy() {
        return nearEvictPlc;
    }

    /**
     * Sets near eviction policy.
     *
     * @param nearEvictPlc Near eviction policy.
     * @return {@code this} for chaining.
     *
     * @deprecated Use {@link #setNearEvictionPolicyFactory(Factory)} instead.
     */
    @Deprecated
    public NearCacheConfiguration<K, V> setNearEvictionPolicy(EvictionPolicy<K, V> nearEvictPlc) {
        this.nearEvictPlc = nearEvictPlc;

        return this;
    }

    /**
     * Gets cache eviction policy factory. By default, returns {@code null}
     * which means that evictions are disabled for cache.
     *
     * @return Cache eviction policy or {@code null} if evictions should be disabled.
     */
    @Nullable public Factory<EvictionPolicy<? super K, ? super V>> getNearEvictionPolicyFactory() {
        return nearEvictPlcFactory;
    }

    /**
     * Sets cache eviction policy factory.
     * Note: Eviction policy factory should be {@link Serializable}.
     *
     * @param nearEvictPlcFactory Cache expiration policy.
     * @return {@code this} for chaining.
     */
    public NearCacheConfiguration<K, V> setNearEvictionPolicyFactory(
        @Nullable Factory<? extends EvictionPolicy<? super K, ? super V>> nearEvictPlcFactory) {
        this.nearEvictPlcFactory = nearEvictPlcFactory;

        return this;
    }

    /**
     * Gets initial cache size for near cache which will be used to pre-create internal
     * hash table after start. Default value is defined by {@link CacheConfiguration#DFLT_NEAR_START_SIZE}.
     *
     * @return Initial near cache size.
     */
    public int getNearStartSize() {
        return nearStartSize;
    }

    /**
     * Start size for near cache. This property is only used for {@link CacheMode#PARTITIONED} caching mode.
     *
     * @param nearStartSize Start size for near cache.
     * @return {@code this} for chaining.
     */
    public NearCacheConfiguration<K, V> setNearStartSize(int nearStartSize) {
        this.nearStartSize = nearStartSize;

        return this;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(NearCacheConfiguration.class, this, super.toString());
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.stylehair.servicos;

import br.com.stylehair.dao.TelefoneDAO;
import br.com.stylehair.entity.Telefone;
import com.google.gson.Gson;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

/**
 *
 * @author vinicius
 */
@Stateless
@Path("telefone")
public class TelefoneResource {
        @PersistenceContext(unitName = "StyleHairPU")
    private EntityManager em;

    private Gson gson = new Gson();

    @Context
    private UriInfo context;

    @POST
    @Consumes("application/json")
    @Produces("application/json")
    public String salvarTelefone(String telefone) throws Exception{

            Telefone t1 = gson.fromJson(telefone, Telefone.class);
            TelefoneDAO dao = new TelefoneDAO(em);
            return gson.toJson(dao.salvar(t1));

    }

     @GET
    @Path("{telefoneId}")
    @Produces("application/json")
    public String getTelefone(@PathParam("telefoneId") String id){
        System.out.println("pegando o cliente");
        Long n = Long.parseLong(id);
        System.out.println(n);
        TelefoneDAO dao = new TelefoneDAO(em);
        Telefone c = dao.consultarPorId(Telefone.class, Long.parseLong(id));

        return gson.toJson(c);

    }
}


text:
"""Test script for ftplib module."""

# Modified by Giampaolo Rodola' to test FTP class, IPv6 and TLS
# environment

import ftplib
import asyncore
import asynchat
import socket
import io
import errno
import os
import time
try:
    import ssl
except ImportError:
    ssl = None

from unittest import TestCase, skipUnless
from test import support
from test.support import HOST, HOSTv6
threading = support.import_module('threading')

TIMEOUT = 3
# the dummy data returned by server over the data channel when
# RETR, LIST, NLST, MLSD commands are issued
RETR_DATA = 'abcde12345\r\n' * 1000
LIST_DATA = 'foo\r\nbar\r\n'
NLST_DATA = 'foo\r\nbar\r\n'
MLSD_DATA = ("type=cdir;perm=el;unique==keVO1+ZF4; test\r\n"
             "type=pdir;perm=e;unique==keVO1+d?3; ..\r\n"
             "type=OS.unix=slink:/foobar;perm=;unique==keVO1+4G4; foobar\r\n"
             "type=OS.unix=chr-13/29;perm=;unique==keVO1+5G4; device\r\n"
             "type=OS.unix=blk-11/108;perm=;unique==keVO1+6G4; block\r\n"
             "type=file;perm=awr;unique==keVO1+8G4; writable\r\n"
             "type=dir;perm=cpmel;unique==keVO1+7G4; promiscuous\r\n"
             "type=dir;perm=;unique==keVO1+1t2; no-exec\r\n"
             "type=file;perm=r;unique==keVO1+EG4; two words\r\n"
             "type=file;perm=r;unique==keVO1+IH4;  leading space\r\n"
             "type=file;perm=r;unique==keVO1+1G4; file1\r\n"
             "type=dir;perm=cpmel;unique==keVO1+7G4; incoming\r\n"
             "type=file;perm=r;unique==keVO1+1G4; file2\r\n"
             "type=file;perm=r;unique==keVO1+1G4; file3\r\n"
             "type=file;perm=r;unique==keVO1+1G4; file4\r\n")

class DummyDTPHandler(asynchat.async_chat):
    dtp_conn_closed = False

    def __init__(self, conn, baseclass):
        asynchat.async_chat.__init__(self, conn)
        self.baseclass = baseclass
        self.baseclass.last_received_data = ''

    def handle_read(self):
        self.baseclass.last_received_data += self.recv(1024).decode('ascii')

    def handle_close(self):
        # XXX: this method can be called many times in a row for a single
        # connection, including in clear-text (non-TLS) mode.
        # (behaviour witnessed with test_data_connection)
        if not self.dtp_conn_closed:
            self.baseclass.push('226 transfer complete')
            self.close()
            self.dtp_conn_closed = True

    def push(self, what):
        if self.baseclass.next_data is not None:
            what = self.baseclass.next_data
            self.baseclass.next_data = None
        if not what:
            return self.close_when_done()
        super(DummyDTPHandler, self).push(what.encode('ascii'))

    def handle_error(self):
        raise Exception

class DummyFTPHandler(asynchat.async_chat):

    dtp_handler = DummyDTPHandler

    def __init__(self, conn):
        asynchat.async_chat.__init__(self, conn)
        # tells the socket to handle urgent data inline (ABOR command)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
        self.set_terminator(b"\r\n")
        self.in_buffer = []
        self.dtp = None
        self.last_received_cmd = None
        self.last_received_data = ''
        self.next_response = ''
        self.next_data = None
        self.rest = None
        self.next_retr_data = RETR_DATA
        self.push('220 welcome')

    def collect_incoming_data(self, data):
        self.in_buffer.append(data)

    def found_terminator(self):
        line = b''.join(self.in_buffer).decode('ascii')
        self.in_buffer = []
        if self.next_response:
            self.push(self.next_response)
            self.next_response = ''
        cmd = line.split(' ')[0].lower()
        self.last_received_cmd = cmd
        space = line.find(' ')
        if space != -1:
            arg = line[space + 1:]
        else:
            arg = ""
        if hasattr(self, 'cmd_' + cmd):
            method = getattr(self, 'cmd_' + cmd)
            method(arg)
        else:
            self.push('550 command "%s" not understood.' %cmd)

    def handle_error(self):
        raise Exception

    def push(self, data):
        asynchat.async_chat.push(self, data.encode('ascii') + b'\r\n')

    def cmd_port(self, arg):
        addr = list(map(int, arg.split(',')))
        ip = '%d.%d.%d.%d' %tuple(addr[:4])
        port = (addr[4] * 256) + addr[5]
        s = socket.create_connection((ip, port), timeout=TIMEOUT)
        self.dtp = self.dtp_handler(s, baseclass=self)
        self.push('200 active data connection established')

    def cmd_pasv(self, arg):
        with socket.socket() as sock:
            sock.bind((self.socket.getsockname()[0], 0))
            sock.listen()
            sock.settimeout(TIMEOUT)
            ip, port = sock.getsockname()[:2]
            ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
            self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
            conn, addr = sock.accept()
            self.dtp = self.dtp_handler(conn, baseclass=self)

    def cmd_eprt(self, arg):
        af, ip, port = arg.split(arg[0])[1:-1]
        port = int(port)
        s = socket.create_connection((ip, port), timeout=TIMEOUT)
        self.dtp = self.dtp_handler(s, baseclass=self)
        self.push('200 active data connection established')

    def cmd_epsv(self, arg):
        with socket.socket(socket.AF_INET6) as sock:
            sock.bind((self.socket.getsockname()[0], 0))
            sock.listen()
            sock.settimeout(TIMEOUT)
            port = sock.getsockname()[1]
            self.push('229 entering extended passive mode (|||%d|)' %port)
            conn, addr = sock.accept()
            self.dtp = self.dtp_handler(conn, baseclass=self)

    def cmd_echo(self, arg):
        # sends back the received string (used by the test suite)
        self.push(arg)

    def cmd_noop(self, arg):
        self.push('200 noop ok')

    def cmd_user(self, arg):
        self.push('331 username ok')

    def cmd_pass(self, arg):
        self.push('230 password ok')

    def cmd_acct(self, arg):
        self.push('230 acct ok')

    def cmd_rnfr(self, arg):
        self.push('350 rnfr ok')

    def cmd_rnto(self, arg):
        self.push('250 rnto ok')

    def cmd_dele(self, arg):
        self.push('250 dele ok')

    def cmd_cwd(self, arg):
        self.push('250 cwd ok')

    def cmd_size(self, arg):
        self.push('250 1000')

    def cmd_mkd(self, arg):
        self.push('257 "%s"' %arg)

    def cmd_rmd(self, arg):
        self.push('250 rmd ok')

    def cmd_pwd(self, arg):
        self.push('257 "pwd ok"')

    def cmd_type(self, arg):
        self.push('200 type ok')

    def cmd_quit(self, arg):
        self.push('221 quit ok')
        self.close()

    def cmd_abor(self, arg):
        self.push('226 abor ok')

    def cmd_stor(self, arg):
        self.push('125 stor ok')

    def cmd_rest(self, arg):
        self.rest = arg
        self.push('350 rest ok')

    def cmd_retr(self, arg):
        self.push('125 retr ok')
        if self.rest is not None:
            offset = int(self.rest)
        else:
            offset = 0
        self.dtp.push(self.next_retr_data[offset:])
        self.dtp.close_when_done()
        self.rest = None

    def cmd_list(self, arg):
        self.push('125 list ok')
        self.dtp.push(LIST_DATA)
        self.dtp.close_when_done()

    def cmd_nlst(self, arg):
        self.push('125 nlst ok')
        self.dtp.push(NLST_DATA)
        self.dtp.close_when_done()

    def cmd_opts(self, arg):
        self.push('200 opts ok')

    def cmd_mlsd(self, arg):
        self.push('125 mlsd ok')
        self.dtp.push(MLSD_DATA)
        self.dtp.close_when_done()

    def cmd_setlongretr(self, arg):
        # For testing. Next RETR will return long line.
        self.next_retr_data = 'x' * int(arg)
        self.push('125 setlongretr ok')

class DummyFTPServer(asyncore.dispatcher, threading.Thread):

    handler = DummyFTPHandler

    def __init__(self, address, af=socket.AF_INET):
        threading.Thread.__init__(self)
        asyncore.dispatcher.__init__(self)
        self.create_socket(af, socket.SOCK_STREAM)
        self.bind(address)
        self.listen(5)
        self.active = False
        self.active_lock = threading.Lock()
        self.host, self.port = self.socket.getsockname()[:2]
        self.handler_instance = None

    def start(self):
        assert not self.active
        self.__flag = threading.Event()
        threading.Thread.start(self)
        self.__flag.wait()

    def run(self):
        self.active = True
        self.__flag.set()
        while self.active and asyncore.socket_map:
            self.active_lock.acquire()
            asyncore.loop(timeout=0.1, count=1)
            self.active_lock.release()
        asyncore.close_all(ignore_all=True)

    def stop(self):
        assert self.active
        self.active = False
        self.join()

    def handle_accepted(self, conn, addr):
        self.handler_instance = self.handler(conn)

    def handle_connect(self):
        self.close()
    handle_read = handle_connect

    def writable(self):
        return 0

    def handle_error(self):
        raise Exception

if ssl is not None:

    CERTFILE = os.path.join(os.path.dirname(__file__), "keycert3.pem")
    CAFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem")

    class SSLConnection(asyncore.dispatcher):
        """An asyncore.dispatcher subclass supporting TLS/SSL."""

        _ssl_accepting = False
        _ssl_closing = False

        def secure_connection(self):
            socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False,
                                     certfile=CERTFILE, server_side=True,
                                     do_handshake_on_connect=False,
                                     ssl_version=ssl.PROTOCOL_SSLv23)
            self.del_channel()
            self.set_socket(socket)
            self._ssl_accepting = True

        def _do_ssl_handshake(self):
            try:
                self.socket.do_handshake()
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
                elif err.args[0] == ssl.SSL_ERROR_EOF:
                    return self.handle_close()
                raise
            except OSError as err:
                if err.args[0] == errno.ECONNABORTED:
                    return self.handle_close()
            else:
                self._ssl_accepting = False

        def _do_ssl_shutdown(self):
            self._ssl_closing = True
            try:
                self.socket = self.socket.unwrap()
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
            except OSError as err:
                # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
                # from OpenSSL's SSL_shutdown(), corresponding to a
                # closed socket condition. See also:
                # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
                pass
            self._ssl_closing = False
            if getattr(self, '_ccc', False) is False:
                super(SSLConnection, self).close()
            else:
                pass

        def handle_read_event(self):
            if self._ssl_accepting:
                self._do_ssl_handshake()
            elif self._ssl_closing:
                self._do_ssl_shutdown()
            else:
                super(SSLConnection, self).handle_read_event()

        def handle_write_event(self):
            if self._ssl_accepting:
                self._do_ssl_handshake()
            elif self._ssl_closing:
                self._do_ssl_shutdown()
            else:
                super(SSLConnection, self).handle_write_event()

        def send(self, data):
            try:
                return super(SSLConnection, self).send(data)
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
                                   ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return 0
                raise

        def recv(self, buffer_size):
            try:
                return super(SSLConnection, self).recv(buffer_size)
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return b''
                if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
                    self.handle_close()
                    return b''
                raise

        def handle_error(self):
            raise Exception

        def close(self):
            if (isinstance(self.socket, ssl.SSLSocket) and
                self.socket._sslobj is not None):
                self._do_ssl_shutdown()
            else:
                super(SSLConnection, self).close()

    class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
        """A DummyDTPHandler subclass supporting TLS/SSL."""

        def __init__(self, conn, baseclass):
            DummyDTPHandler.__init__(self, conn, baseclass)
            if self.baseclass.secure_data_channel:
                self.secure_connection()

    class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler):
        """A DummyFTPHandler subclass supporting TLS/SSL."""

        dtp_handler = DummyTLS_DTPHandler

        def __init__(self, conn):
            DummyFTPHandler.__init__(self, conn)
            self.secure_data_channel = False
            self._ccc = False

        def cmd_auth(self, line):
            """Set up secure control channel."""
            self.push('234 AUTH TLS successful')
            self.secure_connection()

        def cmd_ccc(self, line):
            self.push('220 Reverting back to clear-text')
            self._ccc = True
            self._do_ssl_shutdown()

        def cmd_pbsz(self, line):
            """Negotiate size of buffer for secure data transfer.
            For TLS/SSL the only valid value for the parameter is '0'.
            Any other value is accepted but ignored.
            """
            self.push('200 PBSZ=0 successful.')

        def cmd_prot(self, line):
            """Setup un/secure data channel."""
            arg = line.upper()
            if arg == 'C':
                self.push('200 Protection set to Clear')
                self.secure_data_channel = False
            elif arg == 'P':
                self.push('200 Protection set to Private')
                self.secure_data_channel = True
            else:
                self.push("502 Unrecognized PROT type (use C or P).")

    class DummyTLS_FTPServer(DummyFTPServer):
        handler = DummyTLS_FTPHandler

class TestFTPClass(TestCase):

    def setUp(self):
        self.server = DummyFTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)

    def tearDown(self):
        self.client.close()
        self.server.stop()

    def check_data(self, received, expected):
        self.assertEqual(len(received), len(expected))
        self.assertEqual(received, expected)

    def test_getwelcome(self):
        self.assertEqual(self.client.getwelcome(), '220 welcome')

    def test_sanitize(self):
        self.assertEqual(self.client.sanitize('foo'), repr('foo'))
        self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
        self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))

    def test_exceptions(self):
        self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
        self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
        self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
        self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
        self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')

    def test_all_errors(self):
        exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
                      ftplib.error_proto, ftplib.Error, OSError, EOFError)
        for x in exceptions:
            try:
                raise x('exception not included in all_errors set')
            except ftplib.all_errors:
                pass

    def test_set_pasv(self):
        # passive mode is supposed to be enabled by default
        self.assertTrue(self.client.passiveserver)
        self.client.set_pasv(True)
        self.assertTrue(self.client.passiveserver)
        self.client.set_pasv(False)
        self.assertFalse(self.client.passiveserver)

    def test_voidcmd(self):
        self.client.voidcmd('echo 200')
        self.client.voidcmd('echo 299')
        self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
        self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')

    def test_login(self):
        self.client.login()

    def test_acct(self):
        self.client.acct('passwd')

    def test_rename(self):
        self.client.rename('a', 'b')
        self.server.handler_instance.next_response = '200'
        self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')

    def test_delete(self):
        self.client.delete('foo')
        self.server.handler_instance.next_response = '199'
        self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')

    def test_size(self):
        self.client.size('foo')

    def test_mkd(self):
        dir = self.client.mkd('/foo')
        self.assertEqual(dir, '/foo')

    def test_rmd(self):
        self.client.rmd('foo')

    def test_cwd(self):
        dir = self.client.cwd('/foo')
        self.assertEqual(dir, '250 cwd ok')

    def test_pwd(self):
        dir = self.client.pwd()
        self.assertEqual(dir, 'pwd ok')

    def test_quit(self):
        self.assertEqual(self.client.quit(), '221 quit ok')
        # Ensure the connection gets closed; sock attribute should be None
        self.assertEqual(self.client.sock, None)

    def test_abort(self):
        self.client.abort()

    def test_retrbinary(self):
        def callback(data):
            received.append(data.decode('ascii'))
        received = []
        self.client.retrbinary('retr', callback)
        self.check_data(''.join(received), RETR_DATA)

    def test_retrbinary_rest(self):
        def callback(data):
            received.append(data.decode('ascii'))
        for rest in (0, 10, 20):
            received = []
            self.client.retrbinary('retr', callback, rest=rest)
            self.check_data(''.join(received), RETR_DATA[rest:])

    def test_retrlines(self):
        received = []
        self.client.retrlines('retr', received.append)
        self.check_data(''.join(received), RETR_DATA.replace('\r\n', ''))

    def test_storbinary(self):
        f = io.BytesIO(RETR_DATA.encode('ascii'))
        self.client.storbinary('stor', f)
        self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
        # test new callback arg
        flag = []
        f.seek(0)
        self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
        self.assertTrue(flag)

    def test_storbinary_rest(self):
        f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
        for r in (30, '30'):
            f.seek(0)
            self.client.storbinary('stor', f, rest=r)
            self.assertEqual(self.server.handler_instance.rest, str(r))

    def test_storlines(self):
        f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
        self.client.storlines('stor', f)
        self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
        # test new callback arg
        flag = []
        f.seek(0)
        self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
        self.assertTrue(flag)

        f = io.StringIO(RETR_DATA.replace('\r\n', '\n'))
        # storlines() expects a binary file, not a text file
        with support.check_warnings(('', BytesWarning), quiet=True):
            self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)

    def test_nlst(self):
        self.client.nlst()
        self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])

    def test_dir(self):
        l = []
        self.client.dir(lambda x: l.append(x))
        self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))

    def test_mlsd(self):
        list(self.client.mlsd())
        list(self.client.mlsd(path='/'))
        list(self.client.mlsd(path='/', facts=['size', 'type']))

        ls = list(self.client.mlsd())
        for name, facts in ls:
            self.assertIsInstance(name, str)
            self.assertIsInstance(facts, dict)
            self.assertTrue(name)
            self.assertIn('type', facts)
            self.assertIn('perm', facts)
            self.assertIn('unique', facts)

        def set_data(data):
            self.server.handler_instance.next_data = data

        def test_entry(line, type=None, perm=None, unique=None, name=None):
            type = 'type' if type is None else type
            perm = 'perm' if perm is None else perm
            unique = 'unique' if unique is None else unique
            name = 'name' if name is None else name
            set_data(line)
            _name, facts = next(self.client.mlsd())
            self.assertEqual(_name, name)
            self.assertEqual(facts['type'], type)
            self.assertEqual(facts['perm'], perm)
            self.assertEqual(facts['unique'], unique)

        # plain
        test_entry('type=type;perm=perm;unique=unique; name\r\n')
        # "=" in fact value
        test_entry('type=ty=pe;perm=perm;unique=unique; name\r\n', type="ty=pe")
        test_entry('type==type;perm=perm;unique=unique; name\r\n', type="=type")
        test_entry('type=t=y=pe;perm=perm;unique=unique; name\r\n', type="t=y=pe")
        test_entry('type=====;perm=perm;unique=unique; name\r\n', type="====")
        # spaces in name
        test_entry('type=type;perm=perm;unique=unique; na me\r\n', name="na me")
        test_entry('type=type;perm=perm;unique=unique; name \r\n', name="name ")
        test_entry('type=type;perm=perm;unique=unique;  name\r\n', name=" name")
        test_entry('type=type;perm=perm;unique=unique; n am  e\r\n', name="n am  e")
        # ";" in name
        test_entry('type=type;perm=perm;unique=unique; na;me\r\n', name="na;me")
        test_entry('type=type;perm=perm;unique=unique; ;name\r\n', name=";name")
        test_entry('type=type;perm=perm;unique=unique; ;name;\r\n', name=";name;")
        test_entry('type=type;perm=perm;unique=unique; ;;;;\r\n', name=";;;;")
        # case sensitiveness
        set_data('Type=type;TyPe=perm;UNIQUE=unique; name\r\n')
        _name, facts = next(self.client.mlsd())
        for x in facts:
            self.assertTrue(x.islower())
        # no data (directory empty)
        set_data('')
        self.assertRaises(StopIteration, next, self.client.mlsd())
        set_data('')
        for x in self.client.mlsd():
            self.fail("unexpected data %s" % x)

    def test_makeport(self):
        with self.client.makeport():
            # IPv4 is in use, just make sure send_eprt has not been used
            self.assertEqual(self.server.handler_instance.last_received_cmd,
                                'port')

    def test_makepasv(self):
        host, port = self.client.makepasv()
        conn = socket.create_connection((host, port), timeout=TIMEOUT)
        conn.close()
        # IPv4 is in use, just make sure send_epsv has not been used
        self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')

    def test_with_statement(self):
        self.client.quit()

        def is_client_connected():
            if self.client.sock is None:
                return False
            try:
                self.client.sendcmd('noop')
            except (OSError, EOFError):
                return False
            return True

        # base test
        with ftplib.FTP(timeout=TIMEOUT) as self.client:
            self.client.connect(self.server.host, self.server.port)
            self.client.sendcmd('noop')
            self.assertTrue(is_client_connected())
        self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
        self.assertFalse(is_client_connected())

        # QUIT sent inside the with block
        with ftplib.FTP(timeout=TIMEOUT) as self.client:
            self.client.connect(self.server.host, self.server.port)
            self.client.sendcmd('noop')
            self.client.quit()
        self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
        self.assertFalse(is_client_connected())

        # force a wrong response code to be sent on QUIT: error_perm
        # is expected and the connection is supposed to be closed
        try:
            with ftplib.FTP(timeout=TIMEOUT) as self.client:
                self.client.connect(self.server.host, self.server.port)
                self.client.sendcmd('noop')
                self.server.handler_instance.next_response = '550 error on quit'
        except ftplib.error_perm as err:
            self.assertEqual(str(err), '550 error on quit')
        else:
            self.fail('Exception not raised')
        # needed to give the threaded server some time to set the attribute
        # which otherwise would still be == 'noop'
        time.sleep(0.1)
        self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
        self.assertFalse(is_client_connected())

    def test_source_address(self):
        self.client.quit()
        port = support.find_unused_port()
        try:
            self.client.connect(self.server.host, self.server.port,
                                source_address=(HOST, port))
            self.assertEqual(self.client.sock.getsockname()[1], port)
            self.client.quit()
        except OSError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise

    def test_source_address_passive_connection(self):
        port = support.find_unused_port()
        self.client.source_address = (HOST, port)
        try:
            with self.client.transfercmd('list') as sock:
                self.assertEqual(sock.getsockname()[1], port)
        except OSError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise

    def test_parse257(self):
        self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
        self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
        self.assertEqual(ftplib.parse257('257 ""'), '')
        self.assertEqual(ftplib.parse257('257 "" created'), '')
        self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
        # The 257 response is supposed to include the directory
        # name and in case it contains embedded double-quotes
        # they must be doubled (see RFC-959, chapter 7, appendix 2).
        self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
        self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')

    def test_line_too_long(self):
        self.assertRaises(ftplib.Error, self.client.sendcmd,
                          'x' * self.client.maxline * 2)

    def test_retrlines_too_long(self):
        self.client.sendcmd('SETLONGRETR %d' % (self.client.maxline * 2))
        received = []
        self.assertRaises(ftplib.Error,
                          self.client.retrlines, 'retr', received.append)

    def test_storlines_too_long(self):
        f = io.BytesIO(b'x' * self.client.maxline * 2)
        self.assertRaises(ftplib.Error, self.client.storlines, 'stor', f)

@skipUnless(support.IPV6_ENABLED, "IPv6 not enabled")
class TestIPv6Environment(TestCase):

    def setUp(self):
        self.server = DummyFTPServer((HOSTv6, 0), af=socket.AF_INET6)
        self.server.start()
        self.client = ftplib.FTP(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)

    def tearDown(self):
        self.client.close()
        self.server.stop()

    def test_af(self):
        self.assertEqual(self.client.af, socket.AF_INET6)

    def test_makeport(self):
        with self.client.makeport():
            self.assertEqual(self.server.handler_instance.last_received_cmd,
                                'eprt')

    def test_makepasv(self):
        host, port = self.client.makepasv()
        conn = socket.create_connection((host, port), timeout=TIMEOUT)
        conn.close()
        self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')

    def test_transfer(self):
        def retr():
            def callback(data):
                received.append(data.decode('ascii'))
            received = []
            self.client.retrbinary('retr', callback)
            self.assertEqual(len(''.join(received)), len(RETR_DATA))
            self.assertEqual(''.join(received), RETR_DATA)
        self.client.set_pasv(True)
        retr()
        self.client.set_pasv(False)
        retr()

@skipUnless(ssl, "SSL not available")
class TestTLS_FTPClassMixin(TestFTPClass):
    """Repeat TestFTPClass tests starting the TLS layer for both control
    and data connections first.
    """

    def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        # enable TLS
        self.client.auth()
        self.client.prot_p()

@skipUnless(ssl, "SSL not available")
class TestTLS_FTPClass(TestCase):
    """Specific TLS_FTP class tests."""

    def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)

    def tearDown(self):
        self.client.close()
        self.server.stop()

    def test_control_connection(self):
        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.auth()
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)

    def test_data_connection(self):
        # clear text
        with self.client.transfercmd('list') as sock:
            self.assertNotIsInstance(sock, ssl.SSLSocket)
        self.assertEqual(self.client.voidresp(), "226 transfer complete")

        # secured, after PROT P
        self.client.prot_p()
        with self.client.transfercmd('list') as sock:
            self.assertIsInstance(sock, ssl.SSLSocket)
        self.assertEqual(self.client.voidresp(), "226 transfer complete")

        # PROT C is issued, the connection must be in cleartext again
        self.client.prot_c()
        with self.client.transfercmd('list') as sock:
            self.assertNotIsInstance(sock, ssl.SSLSocket)
        self.assertEqual(self.client.voidresp(), "226 transfer complete")

    def test_login(self):
        # login() is supposed to implicitly secure the control connection
        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.login()
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)
        # make sure that AUTH TLS doesn't get issued again
        self.client.login()

    def test_auth_issued_twice(self):
        self.client.auth()
        self.assertRaises(ValueError, self.client.auth)

    def test_auth_ssl(self):
        try:
            self.client.ssl_version = ssl.PROTOCOL_SSLv23
            self.client.auth()
            self.assertRaises(ValueError, self.client.auth)
        finally:
            self.client.ssl_version = ssl.PROTOCOL_TLSv1

    def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          keyfile=CERTFILE, context=ctx)

        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.auth()
        self.assertIs(self.client.sock.context, ctx)
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)

        self.client.prot_p()
        with self.client.transfercmd('list') as sock:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket)

    def test_ccc(self):
        self.assertRaises(ValueError, self.client.ccc)
        self.client.login(secure=True)
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.ccc()
        self.assertRaises(ValueError, self.client.sock.unwrap)

    def test_check_hostname(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        ctx.verify_mode = ssl.CERT_REQUIRED
        ctx.check_hostname = True
        ctx.load_verify_locations(CAFILE)
        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)

        # 127.0.0.1 doesn't match SAN
        self.client.connect(self.server.host, self.server.port)
        with self.assertRaises(ssl.CertificateError):
            self.client.auth()
        # exception quits connection

        self.client.connect(self.server.host, self.server.port)
        self.client.prot_p()
        with self.assertRaises(ssl.CertificateError):
            with self.client.transfercmd("list") as sock:
                pass
        self.client.quit()

        self.client.connect("localhost", self.server.port)
        self.client.auth()
        self.client.quit()

        self.client.connect("localhost", self.server.port)
        self.client.prot_p()
        with self.client.transfercmd("list") as sock:
            pass

class TestTimeouts(TestCase):

    def setUp(self):
        self.evt = threading.Event()
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(20)
        self.port = support.bind_port(self.sock)
        self.server_thread = threading.Thread(target=self.server)
        self.server_thread.start()
        # Wait for the server to be ready.
        self.evt.wait()
        self.evt.clear()
        self.old_port = ftplib.FTP.port
        ftplib.FTP.port = self.port

    def tearDown(self):
        ftplib.FTP.port = self.old_port
        self.server_thread.join()

    def server(self):
        # This method sets the evt 3 times:
        #  1) when the connection is ready to be accepted.
        #  2) when it is safe for the caller to close the connection
        #  3) when we have closed the socket
        self.sock.listen()
        # (1) Signal the caller that we are ready to accept the connection.
        self.evt.set()
        try:
            conn, addr = self.sock.accept()
        except socket.timeout:
            pass
        else:
            conn.sendall(b"1 Hola mundo\n")
            conn.shutdown(socket.SHUT_WR)
            # (2) Signal the caller that it is safe to close the socket.
            self.evt.set()
            conn.close()
        finally:
            self.sock.close()

    def testTimeoutDefault(self):
        # default -- use global socket timeout
        self.assertIsNone(socket.getdefaulttimeout())
        socket.setdefaulttimeout(30)
        try:
            ftp = ftplib.FTP(HOST)
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(ftp.sock.gettimeout(), 30)
        self.evt.wait()
        ftp.close()

    def testTimeoutNone(self):
        # no timeout -- do not use global socket timeout
        self.assertIsNone(socket.getdefaulttimeout())
        socket.setdefaulttimeout(30)
        try:
            ftp = ftplib.FTP(HOST, timeout=None)
        finally:
            socket.setdefaulttimeout(None)
        self.assertIsNone(ftp.sock.gettimeout())
        self.evt.wait()
        ftp.close()

    def testTimeoutValue(self):
        # a value
        ftp = ftplib.FTP(HOST, timeout=30)
        self.assertEqual(ftp.sock.gettimeout(), 30)
        self.evt.wait()
        ftp.close()

    def testTimeoutConnect(self):
        ftp = ftplib.FTP()
        ftp.connect(HOST, timeout=30)
        self.assertEqual(ftp.sock.gettimeout(), 30)
        self.evt.wait()
        ftp.close()

    def testTimeoutDifferentOrder(self):
        ftp = ftplib.FTP(timeout=30)
        ftp.connect(HOST)
        self.assertEqual(ftp.sock.gettimeout(), 30)
        self.evt.wait()
        ftp.close()

    def testTimeoutDirectAccess(self):
        ftp = ftplib.FTP()
        ftp.timeout = 30
        ftp.connect(HOST)
        self.assertEqual(ftp.sock.gettimeout(), 30)
        self.evt.wait()
        ftp.close()

def test_main():
    tests = [TestFTPClass, TestTimeouts,
             TestIPv6Environment,
             TestTLS_FTPClassMixin, TestTLS_FTPClass]

    thread_info = support.threading_setup()
    try:
        support.run_unittest(*tests)
    finally:
        support.threading_cleanup(*thread_info)

if __name__ == '__main__':
    test_main()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

  <title>RForm.KeepAbove</title>
  <link href="css/style.css" rel="stylesheet" type="text/css">
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

    Concept Framework 2.2 documentation
  	Contents | Index

RForm.KeepAbove

     Name
     Type
     Access
     Version
     Deprecated

     KeepAbove
     property
     public
     version 1.0
     no

Prototype:

[Read/Write] property KeepAbove[=true|false]

Description:

Asks to keep RForm above (if set to true), so that it stays on top.

Note that you shouldn't assume the RForm is definitely above afterward, because other entities (e.g. the user or window manager) could not keep it above, and not all window managers support keeping windows above. But normally the window will end kept above. Just don't write code that crashes if not.

It's permitted to call this function before showing a window, in which case the window will be kept above when it appears onscreen initially.

Returns:

Returns true if the RForm is kept above other windows, false otherwise.

Documented by Eduard Suica, generation time: Sun Jan 27 18:15:05 2013
 GMT	(c)2013 Devronium Applications


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.12.16 at 05:58:11 PM CET
//

package eu.fbk.das.adaptation.ensemble;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlType;

/**
 * While a condition is true, continue to execute a list
 * 				of activities
 *
 *
 *
Java class for whileType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="whileType">
 *   <complexContent>
 *     <extension base="{http://das.fbk.eu/Process}activityType">
 *       <sequence>
 *         <element name="contextCondition" type="{http://das.fbk.eu/Annotation}PreconditionType"/>
 *         <element name="varCondition">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                   <element name="value" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *         <sequence>
 *           <group ref="{http://das.fbk.eu/Process}activity" maxOccurs="unbounded"/>
 *         </sequence>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "whileType", propOrder = {
    "contextCondition",
    "varCondition",
    "activity"
})
public class WhileType
    extends ActivityType
{

    @XmlElement(required = true)
    protected PreconditionType contextCondition;
    @XmlElement(required = true)
    protected WhileType.VarCondition varCondition;
    @XmlElements({
        @XmlElement(name = "abstract", type = AbstractType.class),
        @XmlElement(name = "concrete", type = ConcreteType.class),
        @XmlElement(name = "switch", type = SwitchType.class),
        @XmlElement(name = "pick", type = PickType.class),
        @XmlElement(name = "receive", type = ReceiveType.class),
        @XmlElement(name = "invoke", type = InvokeType.class),
        @XmlElement(name = "while", type = WhileType.class)
    })
    protected List<ActivityType> activity;

    /**
     * Gets the value of the contextCondition property.
     *
     * @return
     *     possible object is
     *     {@link PreconditionType }
     *
     */
    public PreconditionType getContextCondition() {
        return contextCondition;
    }

    /**
     * Sets the value of the contextCondition property.
     *
     * @param value
     *     allowed object is
     *     {@link PreconditionType }
     *
     */
    public void setContextCondition(PreconditionType value) {
        this.contextCondition = value;
    }

    /**
     * Gets the value of the varCondition property.
     *
     * @return
     *     possible object is
     *     {@link WhileType.VarCondition }
     *
     */
    public WhileType.VarCondition getVarCondition() {
        return varCondition;
    }

    /**
     * Sets the value of the varCondition property.
     *
     * @param value
     *     allowed object is
     *     {@link WhileType.VarCondition }
     *
     */
    public void setVarCondition(WhileType.VarCondition value) {
        this.varCondition = value;
    }

    /**
     * Gets the value of the activity property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the activity property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getActivity().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link AbstractType }
     * {@link ConcreteType }
     * {@link SwitchType }
     * {@link PickType }
     * {@link ReceiveType }
     * {@link InvokeType }
     * {@link WhileType }
     *
     *
     */
    public List<ActivityType> getActivity() {
        if (activity == null) {
            activity = new ArrayList<ActivityType>();
        }
        return this.activity;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *         <element name="value" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "name",
        "value"
    })
    public static class VarCondition {

        @XmlElement(required = true)
        protected String name;
        @XmlElement(required = true)
        protected String value;

        /**
         * Gets the value of the name property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getName() {
            return name;
        }

        /**
         * Sets the value of the name property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setName(String value) {
            this.name = value;
        }

        /**
         * Gets the value of the value property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getValue() {
            return value;
        }

        /**
         * Sets the value of the value property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setValue(String value) {
            this.value = value;
        }

    }

}


text:
package com.ab.yuri.aifuwu;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.yuri.aifuwu.gson.Exercise;
import com.ab.yuri.aifuwu.util.HttpUtil;
import com.ab.yuri.aifuwu.util.Utility;
import com.ab.yuri.aifuwu.widget.NoScrollListView;
import com.bumptech.glide.Glide;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RunActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    private ImageView runTitleView;
    private LinearLayout runLayout;
    private ArrayAdapter<String> adapter;
    private NestedScrollView scrollView;
    private ImageView bgRun;
    private SwipeRefreshLayout refreshLayout;
    private AppBarLayout mAppBarLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_run);

        mToolbar= (Toolbar) findViewById(R.id.run_toolbar);
        mCollapsingToolbarLayout= (CollapsingToolbarLayout) findViewById(R.id.run_collapsing_toolbar);
        runTitleView= (ImageView) findViewById(R.id.run_image_view);
        runLayout= (LinearLayout) findViewById(R.id.run_content);
        scrollView= (NestedScrollView) findViewById(R.id.run_scroll);
        bgRun= (ImageView) findViewById(R.id.bg_run);
        refreshLayout= (SwipeRefreshLayout) findViewById(R.id.refresh_run);
        mAppBarLayout= (AppBarLayout) findViewById(R.id.run_appBar);

        if (Build.VERSION.SDK_INT>=21){
            View decorView=getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(this);
        final String account=prefs.getString("account","");
        final String stuName=prefs.getString("student_name","");

        //设置Title
        setSupportActionBar(mToolbar);
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        mCollapsingToolbarLayout.setTitle("跑操查询");

        Glide.with(this).load(R.drawable.run_title).into(runTitleView);
        Glide.with(this).load(R.drawable.bg_run).into(bgRun);

        requestRun(account,stuName);

        runLayout.setVisibility(View.INVISIBLE);

        /*
        刷新并使得刷新位置在最上方。
         */
        refreshLayout.setColorSchemeResources(R.color.colorPrimary);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestRun(account,stuName);

            }
        });
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset>=0){
                    refreshLayout.setEnabled(true);
                }else {
                    refreshLayout.setEnabled(false);
                }
            }
        });
    }

    /*
    通过网络请求跑操数据
     */
    private void requestRun(final String id,final String name){
        String runUrl=""+id+"&student_name="+name;
        HttpUtil.sendOkHttpRequest(runUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(RunActivity.this,"网络错误,请重试",Toast.LENGTH_SHORT).show();
                        refreshLayout.setRefreshing(false);
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText=response.body().string();
                final Exercise exercise= Utility.handleExerciseResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (exercise!=null&&"success".equals(exercise.query)){
                            showRun(exercise);
                        }else {
                            showZero();
                            Toast.makeText(RunActivity.this,"您本学期并未跑步",Toast.LENGTH_SHORT).show();
                        }
                        refreshLayout.setRefreshing(false);
                    }
                });

            }
        });

    }

     /*
    展示数据
     */
    private void showRun(Exercise exercise){
        String times=exercise.times;
        runLayout.removeAllViews();

        View timesView= LayoutInflater.from(this).inflate(R.layout.run_times,runLayout,false);
        TextView runTimes= (TextView)timesView.findViewById(R.id.run_times);
        runTimes.setText(times);
        runLayout.addView(timesView);

        View detailView=LayoutInflater.from(this).inflate(R.layout.run_detail,runLayout,false);
        NoScrollListView listView= (NoScrollListView) detailView.findViewById(R.id.run_detail);
        adapter=new ArrayAdapter<String>(this,R.layout.run_list_item_1,exercise.list);
        listView.setAdapter(adapter);
        scrollView.smoothScrollTo(0,0);
        runLayout.addView(detailView);
        runLayout.setVisibility(View.VISIBLE);

    }

    private void showZero(){
        runLayout.removeAllViews();
        View timesView= LayoutInflater.from(this).inflate(R.layout.run_times,runLayout,false);
        TextView runTimes= (TextView)timesView.findViewById(R.id.run_times);
        runTimes.setText("0");
        runLayout.addView(timesView);
        runLayout.setVisibility(View.VISIBLE);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}


text:
package panelController;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TCPconnection implements Runnable{

	private String message = "";
	private String serverIP;
	private int serverPort;
	private static Socket connection;
	private static ObjectOutputStream output;
	private static ObjectInputStream input;

	public TCPconnection(String ip, int port) {
		serverIP = ip;
		serverPort = port;
	}

	public void run() {
		try {
			connectToServer();
			setupStreams();
			whileChatting();
		}catch(EOFException eofException){
			MotorControls.sBar.setText("");
			TCPmessage(" [~] Client ended connection", 4, true);
		}catch(IOException ioException){
		}catch(NullPointerException nullPointerException){
		}finally{
			cleanUp();
		}
	}

	private void connectToServer() {
		try {
			MotorControls.sBar.setText("");
			TCPmessage(" [~] Attempting to connect...", 4, true);
			connection = new Socket(InetAddress.getByName(serverIP), serverPort);
			TCPmessage("Connected to: " + connection.getInetAddress().getHostName(), 2, true);
			LoginTCP.connectedGUIstate(true);
			MotorControls.controlsEnabled(true);
		}catch(IOException ioException){
			TCPmessage("Server not found!", 0, true);
		}
	}

	private void setupStreams() {
		try {
			output = new ObjectOutputStream(connection.getOutputStream());
			output.flush();
			input = new ObjectInputStream(connection.getInputStream());
		}catch(IOException ioException){
		}
	}

	private void whileChatting() throws IOException {
		do {
			try {
				message = (String) input.readObject();
				TCPmessage(message, 2, true);
			}catch(ClassNotFoundException classNotFoundException){
				TCPmessage("Unable to read message", 3, false);
			}
		}while(!message.equals("SERVER: END"));
	}

	public final void cleanUp() {
		try {
			TCPmessage("Closing sockets...", 1, true);
			output.close();
			input.close();
			connection.close();
			MotorControls.controlsEnabled(false);
			TCPmessage("Successfully closed sockets.", 0, false);
			TCPmessage("Connection closed", 0, true);
		}catch(IOException ioException){
		}catch(NullPointerException nullPointerException){
			LoginTCP.connectBtn.setSelected(false);
		}
	}

	public static void sendMessage(String message) {
		try {
			if((message.equals("END"))) {
				output.writeObject("CLIENT: " + "END");
				output.flush();
			}else{
				output.writeObject("CLIENT: " + message);
				output.flush();
				TCPmessage("CLIENT: " + message, 2, false);
			}
		}catch(IOException ioException){
		}
	}

	public static void TCPmessage(String message, int connectionState, boolean toStatusBar) {
		if(toStatusBar == true){
			MotorControls.statusBarUpdate(message, connectionState);
			System.out.println(" --StatusBAR-- (" + connectionState + ") " + message);
		}else{
			System.out.println(message);
		}
	}
}


text:
import zmq
from time import time
from datetime import datetime
from functools import wraps
from contextlib import contextmanager

class Zibrato(object):

    """
    Zibrato class sets up the connection to ZeroMQ and provides the timer and
    counter methods used to make measurements.
    """

    def __init__(self, **kwargs):
        self.host = kwargs.get('host') or '127.0.0.1'
        self.port = kwargs.get('port') or 5550
        self.context = kwargs.get('context') or zmq.Context()
        self.socket = self.context.socket(zmq.PUB)
        self.socket.connect('tcp://%s:%d' % (self.host, int(self.port)))
        self.socket.setsockopt(zmq.LINGER, 0)

    def close(self):
        self.socket.close()

    def connected(self):
        return not self.socket.closed

    def pack(self, **kwargs):
        level = kwargs.get('level') or 'info'
        mtype = kwargs.get('mtype') or 'Gauge'
        name = kwargs.get('name') or 'default'
        value = str(kwargs.get('value') or 1)
        source = kwargs.get('source') or "not_specified"
        timestamp = str(int(float(time())))
        message = '%s|%s|%s|%s|%s|%s' % (level, mtype, name, value,
                                         timestamp, source)
        return message

    def send(self, **kwargs):
        self.socket.send(self.pack(**kwargs))

    def gauge(self, **kwargs):
        self.send(**kwargs)

    def time_me(self, **decargs):
        def inner(f):
            def wrapper(*args, **kwargs):
                start = datetime.now()
                ret = f(*args, **kwargs)
                total = datetime.now() - start
                decargs['mtype'] = decargs.get('mtype') or 'Timer'
                decargs['name'] = decargs.get('name') or 'default_timer'
                decargs['value'] = str(
                    total.seconds + total.microseconds / 1000000.00)
                self.send(**decargs)
                return ret
            return wraps(f)(wrapper)
        return inner

    @contextmanager
    def Time_me(self, **kwargs):
        start = datetime.now()
        yield
        total = datetime.now() - start
        kwargs['mtype'] = kwargs.get('mtype') or 'Timer'
        kwargs['name'] = kwargs.get('name') or 'default_timer'
        kwargs['value'] = str(total.seconds + total.microseconds / 1000000.00)
        self.send(**kwargs)

    def count_me(self, **decargs):
        def inner(f):
            def wrapper(*args, **kwargs):
                ret = f(*args, **kwargs)
                decargs['mtype'] = decargs.get('mtype') or 'Counter'
                decargs['name'] = decargs.get('name') or 'default_counter'
                decargs['value'] = str(decargs.get('value') or 1)
                self.send(**decargs)
                return ret
            return wraps(f)(wrapper)
        return inner

    @contextmanager
    def Count_me(self, **kwargs):
        yield
        kwargs['mtype'] = kwargs.get('mtype') or 'Counter'
        kwargs['name'] = kwargs.get('name') or 'default_counter'
        kwargs['value'] = str(kwargs.get('value') or 1)
        self.send(**kwargs)


text:
<?php

declare(strict_types=1);

namespace Reinfi\DependencyInjection\Annotation;

use Reinfi\DependencyInjection\Injection\InjectionInterface;

/**
 * @package Reinfi\DependencyInjection\Annotation
 */
interface AnnotationInterface extends InjectionInterface
{
}


text:
from ZODB import (DB, FileStorage)
import transaction
import argparse

class ToDo:
    def __init__(self):
        self.store = FileStorage.FileStorage("ToDo.fs")
        self.database = DB(self.store)
        self.connection = self.database.open()
        self.root = self.connection.root()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        transaction.get()
        transaction.abort()
        self.connection.close()
        self.database.close()
        self.store.close()

    def add(self, key, value):
        if key != "":
            self.root[key] = value
            transaction.commit()
            print("New task added..")
        else:
            print("A task must have a name")

    def list(self):
        print("Tasks To Do..")
        for k in self.root.keys():
            print("%s\t%s" % (k, self.root[k]))

    def delete(self, key):
        if key in self.root.keys():
            del(self.root[key])
            transaction.commit()
            print("Task deleted..")
        else:
            print("There is no task '%s'.." % key)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--add', nargs=2, help="add a tast to the ToDo list")
    parser.add_argument('-d', '--delete', nargs=1, help="delete a task from the ToDo list")
    args = parser.parse_args()
    tasks = ToDo()
    if args.add:
        tasks.add(args.add[0],args.add[1])
    elif args.delete:
        tasks.delete(args.delete[0])
    else:
        tasks.list()


text:
package zutil.io;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

/**
 * Created by Ziver on 2016-07-12.
 */
public class IOUtilTest {

    @Test
    public void readLine() throws IOException {
        StringInputStream in = new StringInputStream("test\ntest2\ntest3");

        assertEquals("test", IOUtil.readLine(in));
        assertEquals("test2", IOUtil.readLine(in));
        assertEquals("test3", IOUtil.readLine(in));
        assertNull(IOUtil.readLine(in));
    }
    @Test
    public void readLineCarriageReturn() throws IOException {
        StringInputStream in = new StringInputStream("test\r\ntest2\r\n");

        assertEquals("test", IOUtil.readLine(in));
        assertEquals("test2", IOUtil.readLine(in));
        assertNull(IOUtil.readLine(in));
    }
}


text:
using System.Collections.Generic;

namespace MyCalculator
{
    public class Calculator : ICalculator
    {
        private readonly Stack<int> operands = new Stack<int>();

        public int Result => operands.Peek();

        public void Enter(int operand)
        {
            operands.Push(operand);
        }

        public void Add()
        {
            operands.Push(operands.Pop() + operands.Pop());
        }

        public void Multiply()
        {
            operands.Push(operands.Pop() * operands.Pop());
        }
    }
}


text:
import { ModuleWithProviders, NgModule } from '@angular/core';
import { IDBService
	   , IDBServiceConfig
	   , IDB_DI_CONFIG                 } from './idb.service';

@NgModule({})
export class IDBModule {

	/*
	 * It helps us to pre-configure the IDBService
	 */
	static forRoot(config: IDBServiceConfig): ModuleWithProviders {
		return {
			ngModule: IDBModule,
			providers: [
				{provide: IDB_DI_CONFIG, useValue: config}
			]
		};
	}
}


text:
//  Sample refactored by David Rousset - Microsoft France - http://blogs.msdn.com/davrous
//  Using Hand.js to support all platforms

//  Based on https://github.com/sebleedelisle/JSTouchController/blob/master/Touches.html

//  Copyright (c)2010-2011, Seb Lee-Delisle, sebleedelisle.com. All rights reserved.

//  Redistribution and use in source and binary forms, with or without modification, are permitted provided
//  that the following conditions are met:

//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//    * 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.

// shim layer with setTimeout fallback
window.requestAnimFrame = (function () {
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };
})();

var control_canvas,
c,	// c is the fg_canvas' context 2D
halfWidth,
halfHeight,
leftPointerID = -1,
leftPointerPos = new Vector2(0, 0),
leftPointerStartPos = new Vector2(0, 0),
leftVector = new Vector2(0, 0);
arrow = new VectorLED(0, 0, 0, 0);

var touches; // collections of pointers

/////////////////////////////// ARDUINO SETUP
var IOBoard = BO.IOBoard;
var IOBoardEvent = BO.IOBoardEvent;
var Pin = BO.Pin;

//// Variables
// LED related
var led1; //-90
var led2; //0
var led3; //90
var led4; //180=-180
var LEDloopON = false;
var LEDcont = 1;
var max_val;

var frame = 0;
var lastUpdateTime = 0;
var acDelta = 0;
var msPerFrame = 10;

// Set to true to print debug messages to console
BO.enableDebugging = true;

var host = window.location.hostname;
// if the file is opened locally, set the host to "localhost"
if (window.location.protocol.indexOf("file:") === 0) {
        host = "171.65.102.132";
    }
var arduino = new IOBoard(host, 8887);
///////////////////////////// ARDUINO SETUP END

var username = "noname";
var socket;

document.addEventListener("DOMContentLoaded", init);

window.onorientationchange = resetCanvas;
window.onresize = resetCanvas;

function init() {
    setupCanvas();
    setupVidCanvas();
    //setupMotionDetection();

    touches = new Collection();

    arduino.addEventListener(IOBoardEvent.READY, onReady);
}

function onReady(event) {
	// Remove the event listener because it is no longer needed
	arduino.removeEventListener(IOBoardEvent.READY, onReady);

	// Set Pin 5,6,9,10 to PWM
	arduino.setDigitalPinMode(5, Pin.PWM);
	arduino.setDigitalPinMode(6, Pin.PWM);
	arduino.setDigitalPinMode(9, Pin.PWM);
	arduino.setDigitalPinMode(10, Pin.PWM);

	// Create an LED object to interface with the LED wired
	// to the I/O board
	led1 = arduino.getDigitalPin(5);
	led2 = arduino.getDigitalPin(6);
	led3 = arduino.getDigitalPin(9);
	led4 = arduino.getDigitalPin(10);

	// jQuery part for the button
    $("#slider").slider({
        step: 0.05,
        min : 0.0,
        max : 1.0
    });

    $('#value').text("Value: 0");

    $( "#slider" ).bind( "slide", function(event, ui) {
        var value = ui.value;
        $('#value').text("Value: " + value.toFixed(2));
        brown_const = value;
        console.log(brown_const);
    });

	$('input[name=setUsername]').click(function(){
			if($('input[name=usernameTxt]').val() != ""){
				username = $('input[name=usernameTxt]').val();
				var msg = {type:'setUsername', user:username};
				socket.json.send(msg);
			}
			$('#username').slideUp("slow",function(){
				$('#sendChat').slideDown("slow");
				resetGame();
			});
	});

	socket = new io.connect('http://171.65.102.132:8088');
	var chat = $('#chat');
	var board = $('#board');

	socket.on('connect', function() {
		console.log("Connected");
		socket.emit('message', {channel:'chatting'});
	});

	socket.on('reconnecting', function(){
		console.log("Reconnecting...");
	}

	socket.on('message', function(message){
		chat.append(message + '
');
	});

	socket.on('postscore', function(score){
		board.empty();
		for (var i=0;i<score.length;i++){
			if(i==0){
				board.append(''+ score[i][0]+'  :  '+score[i][1]+'
');
			}else{
				board.append(score[i][0]+'  :  '+score[i][1]+ '
');
			}
		}
		board.fadeOut('fast');
		board.fadeIn('fast');
		board.fadeOut('fast');
		board.fadeIn('fast');
	});

	socket.on('gamearray', function(arrGame){
		drawBox(arrGame[0],arrGame[1],ObjL);
	}

	socket.on('disconnect', function() {
		console.log('disconnected');
		chat.html("Disconnect!");
	});

	$("input[name=sendBtn]").click(function(){
		var msg = {type:'chat',message:username + " : " + $("input[name=chatTxt]").val()}
		socket.json.send(msg);
		$("input[name=chatTxt]").val("");
	});

	control_canvas.addEventListener('pointerdown', onPointerDown, false);
    control_canvas.addEventListener('pointermove', onPointerMove, false);
    control_canvas.addEventListener('pointerup', onPointerUp, false);
    control_canvas.addEventListener('pointerout', onPointerUp, false);

    requestAnimFrame(draw);
}

function draw() {
	c.clearRect(0, 0, control_canvas.width, control_canvas.height);

    c.beginPath();
    c.moveTo(halfWidth, halfHeight-4);
    c.strokeStyle = "rgba(250, 102, 0, 1)";
    c.lineWidth = 2;
    c.lineTo(halfWidth, halfHeight+4);
    c.stroke();

    c.beginPath();
    c.moveTo(halfWidth+4, halfHeight);
    c.strokeStyle = "rgba(250, 102, 0, 1)";
    c.lineWidth = 2;
    c.lineTo(halfWidth-4, halfHeight);
    c.stroke();

    drawCircles(halfWidth, halfHeight);

	//// mouse event loop
    touches.forEach(function (touch) {
        if (touch.identifier == leftPointerID) {
            var alpha = arrow.trimArrow(leftVector, max_val);

            c.beginPath();
            c.fillStyle = "rgba(250, 102, 0, 1)";
            c.arc(leftPointerPos.x, leftPointerPos.y, 16, 0, Math.PI * 2, true);
            c.fill();

            c.beginPath();
            c.moveTo(leftPointerStartPos.x,leftPointerStartPos.y);
            c.strokeStyle = "rgba(250, 102, 0, 1)";
			c.lineTo(leftPointerStartPos.x+max_val*(arrow.int2-arrow.int4),leftPointerStartPos.y+max_val*(arrow.int1-arrow.int3));
			c.lineWidth = 3;
			c.stroke();

			c.beginPath();
			c.fillStyle = "rgba(255, 255, 255, "+alpha*(LEDcont)+")";
    		c.arc(halfWidth, halfHeight, 16, 0, Math.PI * 2, true);
    		c.fill();

			c.beginPath();
        	c.fillStyle = "#fff";
        	c.fillText(alpha,halfWidth-10, halfHeight-25);

        	c.beginPath();
        	c.fillStyle = "#dd6600";
        	var theta = leftVector.angle();
        	c.fillText(theta.toFixed(0),leftPointerPos.x+10, leftPointerPos.y-20);
        }
    });

    requestAnimFrame(draw);

    //// LED control loop
    var delta = Date.now() - lastUpdateTime;
    if (acDelta > msPerFrame)
    {
        acDelta = 0;
        if(LEDloopON)
        {
        	//LEDon = frame%2;
        	LEDcont = 1;
        	changeLED(LEDcont);
        }
        frame++;
        if (frame >= 2) {frame = 0;}
    } else
    {
        acDelta += delta;
    }
    lastUpdateTime = Date.now();
}

function drawCircles(xCenter,yCenter)
{
	var needle = new Vector2(max_val, 0);
	for(var i=0;i<24*3;i++)
	{
		c.beginPath();
		c.fillStyle = "rgba(255, 255, 255, 0.5)";
		c.lineWidth = 3;
		c.arc(xCenter + needle.x, yCenter + needle.y, 1, 0, Math.PI * 2, true);
		c.fill();
		needle.rotate(5,0);
	}
}

function givePointerType(event) {
    switch (event.pointerType) {
        case event.POINTER_TYPE_MOUSE:
            return "MOUSE";
            break;
        case event.POINTER_TYPE_PEN:
            return "PEN";
            break;
        case event.POINTER_TYPE_TOUCH:
            return "TOUCH";
            break;
    }
}

function onPointerDown(e) {
    var newPointer = { identifier: e.pointerId, x: e.clientX, y: e.clientY, type: givePointerType(e) };
    leftPointerID = e.pointerId;
    //leftPointerStartPos.reset(e.clientX, e.clientY);
    leftPointerStartPos.reset(halfWidth, halfHeight);
    leftPointerPos.copyFrom(leftPointerStartPos);
    leftVector.reset(0, 0);
    arrow.reset(0, 0, 0, 0);
    touches.add(e.pointerId, newPointer);
}

function onPointerMove(e) {
    if (leftPointerID == e.pointerId) {
        //leftPointerPos.reset(e.clientX, e.clientY);
        leftPointerPos.reset(e.offsetX, e.offsetY);
        leftVector.copyFrom(leftPointerPos);
        //leftVector.minusEq(leftPointerStartPos);
        leftVector.minusEq(leftPointerStartPos);
        arrow.setArrow(leftVector, max_val);
        LEDloopON = true;
    }
    else {
        if (touches.item(e.pointerId)) {
            touches.item(e.pointerId).x = e.clientX;
            touches.item(e.pointerId).y = e.clientY;
        }
    }
}

function onPointerUp(e) {
    if (leftPointerID == e.pointerId) {
        leftPointerID = -1;
        leftVector.reset(0, 0);
    }
    leftVector.reset(0, 0);
    arrow.reset(0, 0, 0, 0);
    touches.remove(e.pointerId);
    LEDloopON = false;
    changeLED(0);
}

function setupCanvas() {
    control_canvas = document.getElementById('controlCanvas');
    c = control_canvas.getContext('2d');
    resetCanvas();
    c.strokeStyle = "#ffffff";
    c.lineWidth = 2;
}

// Arduino control functions
function changeLED(LEDon) {
	if(LEDon)
	{
		led1.value = arrow.int1;
    	led2.value = arrow.int2;
    	led3.value = arrow.int3;
    	led4.value = arrow.int4;
    }
    else
    {
    	led1.value = 0;
    	led2.value = 0;
    	led3.value = 0;
    	led4.value = 0;
	}
}

function resetCanvas(e) {
    max_val = (document.getElementById("controlArea").offsetWidth-100)/2;

    // resize the canvas - but remember - this clears the canvas too.

    control_canvas.width = document.getElementById("controlArea").offsetWidth-20;
    control_canvas.height = control_canvas.width-20;

    halfWidth = (control_canvas.width)/2;
    halfHeight = (control_canvas.height)/2;

    // make sure we scroll to the top left.
    window.scrollTo(0, 0);
}


text:
package com.google.maps.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import com.google.maps.MediumTests;
import java.util.AbstractMap;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Category(MediumTests.class)
public class RateLimitExecutorServiceTest {

  private static final Logger LOG =
      LoggerFactory.getLogger(RateLimitExecutorServiceTest.class.getName());

  @Test
  public void testRateLimitDoesNotExceedSuppliedQps() throws Exception {
    int qps = 10;
    RateLimitExecutorService service = new RateLimitExecutorService();
    service.setQueriesPerSecond(qps);
    final ConcurrentHashMap<Integer, Integer> executedTimestamps = new ConcurrentHashMap<>();

    for (int i = 0; i < 100; i++) {
      Runnable emptyTask =
          new Runnable() {
            @Override
            public void run() {
              int nearestSecond = (int) (new Date().getTime() / 1000);
              if (executedTimestamps.containsKey(nearestSecond)) {
                executedTimestamps.put(nearestSecond, executedTimestamps.get(nearestSecond) + 1);
              } else {
                executedTimestamps.put(nearestSecond, 1);
              }
            }
          };
      service.execute(emptyTask);
    }

    // Sleep until finished, or 20s expires (to prevent waiting forever)
    long sleepTime = 0;
    while (sleepTime < 20000 && countTotalRequests(executedTimestamps) < 100) {
      long sleepFor = TimeUnit.SECONDS.toMillis(1);
      sleepTime += sleepFor;
      Thread.sleep(sleepFor);
    }

    // Check that we executed at the correct rate
    for (Integer timestamp : executedTimestamps.keySet()) {
      Integer actualQps = executedTimestamps.get(timestamp);
      // Logging QPS here to detect if a previous iteration had qps-1 and this is qps+1.
      LOG.info(
          String.format(
              "Timestamp(%d) logged %d queries (target of %d qps)", timestamp, actualQps, qps));
      assertTrue(
          String.format("Expected <= %d queries in a second, got %d.", qps, actualQps),
          actualQps <= qps);
    }
    // Check that we executed every request
    assertEquals(100, countTotalRequests(executedTimestamps));

    service.shutdown();
  }

  private static int countTotalRequests(AbstractMap<?, Integer> hashMap) {
    int counter = 0;
    for (Integer value : hashMap.values()) {
      counter += value;
    }
    return counter;
  }

  @Test
  public void testDelayThreadIsStoppedAfterShutdownIsCalled() throws InterruptedException {
    RateLimitExecutorService service = new RateLimitExecutorService();
    final Thread delayThread = service.delayThread;
    assertNotNull(
        "Delay thread should be created in constructor of RateLimitExecutorService", delayThread);
    assertTrue(
        "Delay thread should start in constructor of RateLimitExecutorService",
        delayThread.isAlive());
    // this is needed to make sure that delay thread has reached queue.take()
    delayThread.join(10);
    service.shutdown();
    delayThread.join(10);
    assertFalse(delayThread.isAlive());
  }
}


text:
using System.Collections.Generic;
using System.Linq;
using GlowingBrain.Json.Infrastructure;

namespace GlowingBrain.Json
{
    /// <summary>
    /// Manages a collection of property formatting rules
    /// </summary>
    public class PropertyFormattingRulesCollection : List<PropertyFormattingRules>
    {
        private readonly FormattingRules _defaultFormattingRules;

        /// <summary>
        /// Initializes an instance of the <see cref="PropertyFormattingRulesCollection"/> Type
        /// </summary>
        public PropertyFormattingRulesCollection() : this (FormattingRules.Default)
        {
        }

        /// <summary>
        /// Initializes an instance of the <see cref="PropertyFormattingRulesCollection"/> Type
        /// </summary>
        /// <param name="defaultFormattingRules">Specifies the default formatting rules</param>
        public PropertyFormattingRulesCollection(FormattingRules defaultFormattingRules)
        {
            _defaultFormattingRules = defaultFormattingRules;
        }

        /// <summary>
        /// Adds a set of formatting rules for the given property pattern
        /// </summary>
        /// <param name="propertyPattern">The property pattern</param>
        /// <param name="formattingRules">The formatting rules</param>
        public void AddPatternRule(string propertyPattern, FormattingRules formattingRules)
        {
            this.Add(new PropertyFormattingRules(propertyPattern, formattingRules));
        }

        /// <summary>
        /// Gets the formatting rules that should be applied to the property path
        /// </summary>
        /// <param name="propertyPath">The property path</param>
        /// <returns>The formatting rules to be applied to the property path</returns>
        /// <remarks>
        /// A property path is specified as parentProperty.childProperty.grandchildProperty
        /// format (with arbitary levels of nesting). An empty path denotes the root
        /// object of a data structure.
        /// </remarks>
        public FormattingRules GetEffectiveFormattingRules(string propertyPath)
        {
            // get all formatting rules that apply to the given property name
            // ordering them by priority such that we overlay rules at higher
            // priority
            var matches = this
                .Where(r => r.PropertyPatternRegex.IsMatch(propertyPath))
                .OrderBy(r => r.Priority)
                .ToList();

            // starting with default rules overlay matching rule property values
            var result = _defaultFormattingRules.DeepClone();
            matches.Each(match => match.FormattingRules.ApplySpecifiedRulesTo(result));

            return result;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Quizzly</title>
    <link rel="stylesheet" href="css/style.css">

    <button id="retry-button">Try Again</button>
    <button id="submit-button">Submit Answers</button>
    <button id="clear-button">Clear Answer</button>
    <button id="next-question-button">Next Question</button>
    <button id="prev-question-button">Previous Question</button>


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

<TITLE>
Uses of Class datastore.Table
</TITLE>

<META NAME="date" CONTENT="2013-07-13">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
datastore.Table

Packages that use Table

datastore

net.floodlightcontroller.devicemanager.internal

net.floodlightcontroller.learningswitch

net.floodlightcontroller.loadbalancer

net.floodlightcontroller.topology

Uses of Table in datastore

Subclasses of Table in datastore

 class
TableLearningSwitch<K extends Serializable,V extends Serializable>

Methods in datastore that return Table

<K extends java.io.Serializable,A extends java.io.Serializable>

Table<K,A>

Datastore.getTable(java.lang.String tableName,
         org.python.google.common.base.Function<byte[],K> deserialize,
         org.python.google.common.base.Function<K,byte[]> serialize)

<K extends java.io.Serializable,A extends java.io.Serializable>

Table<K,A>

Datastore.getTableL(java.lang.String tableName,
          org.python.google.common.base.Function<byte[],K> deserialize,
          org.python.google.common.base.Function<K,byte[]> serialize)

Uses of Table in net.floodlightcontroller.devicemanager.internal

Fields in net.floodlightcontroller.devicemanager.internal declared as Table

protected  Table<java.util.EnumSet<IDeviceService.DeviceField>,DeviceIndex>
DeviceManagerImpl.secondaryIndexMap

          This stores secondary indices over the fields in the devices

Uses of Table in net.floodlightcontroller.learningswitch

Fields in net.floodlightcontroller.learningswitch with type parameters of type Table

protected  java.util.Map<java.lang.String,Table>
LearningSwitchO.tables

Uses of Table in net.floodlightcontroller.loadbalancer

Fields in net.floodlightcontroller.loadbalancer declared as Table

protected  Table<net.floodlightcontroller.loadbalancer.IPClient,LBMember>
LoadBalancer.clientToMember

protected  Table<java.lang.Integer,java.lang.String>
LoadBalancer.memberIpToId

protected  Table<java.lang.String,LBMember>
LoadBalancer.members

protected  Table<java.lang.String,LBPool>
LoadBalancer.pools

protected  Table<java.lang.Integer,LBVip>
LoadBalancer.vipIpToId

protected  Table<java.lang.String,LBVip>
LoadBalancer.vips

Uses of Table in net.floodlightcontroller.topology

Fields in net.floodlightcontroller.topology declared as Table

protected  Table<NodePortTuple,java.util.HashSet<Link>>
TopologyManager.directLinks

          Set of direct links

protected  Table<NodePortTuple,java.util.HashSet<Link>>
TopologyManager.portBroadcastDomainLinks

          set of links that are broadcast domain links.

protected  Table<NodePortTuple,java.util.HashSet<Link>>
TopologyManager.switchPortLinks

          Set of links organized by node port tuple

protected  Table<java.lang.Long,java.util.HashSet<java.lang.Short>>
TopologyManager.switchPorts

          Set of ports for each switch

protected  Table<NodePortTuple,NodePortTuple>
TopologyManager.tunnelPorts

          set of tunnel links

Constructors in net.floodlightcontroller.topology with parameters of type Table

TopologyInstanceWrapper(Table<java.lang.String,java.lang.String> controllersTable)

TopologyManager.UpdateTopologyWorker(Table<java.lang.String,java.lang.String> controllersTable)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Person;

/**
 * PersonSearch represents the model behind the search form about `app\models\Person`.
 */
class PersonSearch extends Person
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'cpf', 'rg', 'phone_1', 'phone_2', 'number'], 'integer'],
            [['name', 'email', 'address', 'neighborhood', 'city', 'state', 'password'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Person::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'cpf' => $this->cpf,
            'rg' => $this->rg,
            'phone_1' => $this->phone_1,
            'phone_2' => $this->phone_2,
            'number' => $this->number,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'address', $this->address])
            ->andFilterWhere(['like', 'neighborhood', $this->neighborhood])
            ->andFilterWhere(['like', 'city', $this->city])
            ->andFilterWhere(['like', 'state', $this->state])
            ->andFilterWhere(['like', 'password', $this->password]);

        return $dataProvider;
    }
}


text:
class Shape
{
public:
	virtual ~Shape();

	virtual float area() const = 0;
	virtual float volume() const = 0;
	virtual std::ostream& print(std::ostream& os) const;
	std::string name() const;
	Material material() const;

protected:
	Shape();
	Shape(std::string const& name, Material const& material);

private:
	std::string name_;
	Material material_;
};

std::ostream& operator<<(std::ostream& os, Shape const& s);
#endif


text:
{% extends "main.html" %}
{% block pagetitle %}Page not found!{% endblock %}

{% block content %}
{{ super() }}

oops, we couldn't find that!

404 - Not found

We are sorry but we couldn't find the page you requested.

Check the address for typing errors such as ww.example.com instead of www.example.com

  ×

{% endblock %}

{% block bottomextra %}
  {{ super() }}
  {% compress js %}

  {% endcompress %}
{% endblock %}


text:
'use strict';

exports.register = function (server, options, next) {

    server.ext('onRequest', function (request, reply) {

        if (request.headers['x-forwarded-for']) {

            request.info.remoteAddress = request.headers['x-forwarded-for'].split(',')[0].trim();
        }

        if (request.headers['x-forwarded-port']) {

            request.info.remotePort = request.headers['x-forwarded-port'];
        }

        return reply.continue();
    });

    return next();
};

exports.register.attributes = {
    pkg: require('../package.json')
};