text:
#define _BSD_SOURCE

#define USER_RHOSTS_FILE "/.rhosts"     /* prefixed by user's home dir */

#ifdef linux
#include <endian.h>
#endif

#ifdef NEED_FSUID_H
#include <sys/fsuid.h>
#endif /* NEED_FSUID_H */

#include <sys/types.h>
#include <sys/uio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>       /* This is supposed(?) to contain the following */
int innetgr(const char *, const char *, const char *,const char *);

#include <stdio.h>
#include <errno.h>
#include <sys/time.h>
#include <arpa/inet.h>

#ifndef MAXDNAME
#define MAXDNAME  256
#endif

#include <stdarg.h>
#include <ctype.h>

#include <net/if.h>
#ifdef linux
# include <linux/sockios.h>
# ifndef __USE_MISC
#  define __USE_MISC
#  include <sys/fsuid.h>
# endif /* __USE_MISC */
#endif

#include <pwd.h>
#include <grp.h>
#include <sys/file.h>
#include <sys/signal.h>
#include <sys/stat.h>
#include <syslog.h>
#ifndef _PATH_HEQUIV
#define _PATH_HEQUIV "/etc/hosts.equiv"
#endif /* _PATH_HEQUIV */

#define PAM_SM_AUTH  /* only defines this management group */

#include <security/pam_modules.h>
#include <security/_pam_macros.h>

/* to the best of my knowledge, all modern UNIX boxes have 32 bit integers */
#define U32 unsigned int

/*
 * Options for this module
 */

struct _options {
    int  opt_no_hosts_equiv;
    int  opt_hosts_equiv_rootok;
    int  opt_no_rhosts;
    int  opt_debug;
    int  opt_nowarn;
    int  opt_disallow_null_authtok;
    int  opt_silent;
    int  opt_promiscuous;
    int  opt_suppress;
    int  opt_private_group;
    int  opt_no_uid_check;
    const char *superuser;
    const char *last_error;
};

/* logging */
static void _pam_log(int err, const char *format, ...)
{
    va_list args;

    va_start(args, format);
    openlog("pam_rhosts_auth", LOG_CONS|LOG_PID, LOG_AUTH);
    vsyslog(err, format, args);
    va_end(args);
    closelog();
}

static void set_option (struct _options *opts, const char *arg)
{
    if (strcmp(arg, "no_hosts_equiv") == 0) {
	opts->opt_no_hosts_equiv = 1;
	return;
    }

    if (strcmp(arg, "hosts_equiv_rootok") == 0) {
        opts->opt_hosts_equiv_rootok = 1;
        return;
    }

    if (strcmp(arg, "no_rhosts") == 0) {
	opts->opt_no_rhosts = 1;
	return;
    }

    if (strcmp(arg, "debug") == 0) {
	D(("debugging enabled"));
	opts->opt_debug = 1;
	return;
    }

    if (strcmp(arg, "no_warn") == 0) {
	opts->opt_nowarn = 1;
	return;
    }

    if (strcmp(arg, "promiscuous") == 0) {
	opts->opt_promiscuous = 1;   /* used to permit '+' in ...hosts file */
	return;
    }

    if (strcmp(arg, "suppress") == 0) {
	opts->opt_suppress = 1; /* used to suppress failure warning message */
	return;
    }

    if (strcmp(arg, "privategroup") == 0) {
	opts->opt_private_group = 1; /* used to permit group write on .rhosts
					file if group has same name as owner */
	return;
    }

    if (strcmp(arg, "no_uid_check") == 0) {
	opts->opt_no_uid_check = 1;  /* NIS optimization */
	return;
    }

    if (strcmp(arg, "superuser=") == 0) {
	opts->superuser = arg+sizeof("superuser=")-1;
	return;
    }
    /*
     * All other options are ignored at the present time.
     */
    _pam_log(LOG_WARNING, "unrecognized option '%s'", arg);
}

static void set_parameters (struct _options *opts, int flags,
			    int argc, const char **argv)
{
    opts->opt_silent                = flags & PAM_SILENT;
    opts->opt_disallow_null_authtok = flags & PAM_DISALLOW_NULL_AUTHTOK;

    while (argc-- > 0) {
	set_option (opts, *argv);
	++argv;
    }
}

/*
 * Obtain the name of the remote host. Currently, this is simply by
 * requesting the contents of the PAM_RHOST item.
 */

static int pam_get_rhost(pam_handle_t *pamh, const char **rhost
			 , const char *prompt)
{
    int retval;
    const char   *current;

    retval = pam_get_item (pamh, PAM_RHOST, (const void **)&current);
    if (retval != PAM_SUCCESS)
        return retval;

    if (current == NULL) {
	return PAM_AUTH_ERR;
    }
    *rhost = current;

    return retval;        /* pass on any error from conversation */
}

/*
 * Obtain the name of the remote user. Currently, this is simply by
 * requesting the contents of the PAM_RUSER item.
 */

static int pam_get_ruser(pam_handle_t *pamh, const char **ruser
			 , const char *prompt)
{
    int retval;
    const char   *current;

    retval = pam_get_item (pamh, PAM_RUSER, (const void **)&current);
    if (retval != PAM_SUCCESS)
        return retval;

    if (current == NULL) {
	return PAM_AUTH_ERR;
    }
    *ruser = current;

    return retval;        /* pass on any error from conversation */
}

/*
 * Returns 1 if positive match, 0 if no match, -1 if negative match.
 */

static int
__icheckhost (pam_handle_t *pamh, struct _options *opts, U32 raddr
	      , register char *lhost, const char *rhost)
{
    struct hostent *hp;
    U32 laddr;
    int negate=1;    /* Multiply return with this to get -1 instead of 1 */
    char **pp, *user;

    /* Check nis netgroup.  We assume that pam has done all needed
       paranoia checking before we are handed the rhost */
    if (strncmp("+@",lhost,2) == 0)
      return(innetgr(&lhost[2],rhost,NULL,NULL));

    if (strncmp("-@",lhost,2) == 0)
      return(-innetgr(&lhost[2],rhost,NULL,NULL));

    /* -host */
    if (strncmp("-",lhost,1) == 0) {
	negate=-1;
	lhost++;
    } else if (strcmp("+",lhost) == 0) {
        (void) pam_get_item(pamh, PAM_USER, (const void **)&user);
        D(("user %s has a `+' host entry", user));
	if (opts->opt_promiscuous)
	    return (1);                     /* asking for trouble, but ok.. */
	/* If not promiscuous: handle as negative */
	return (-1);
    }

    /* Try for raw ip address first. */
    if (isdigit(*lhost) && (long)(laddr = inet_addr(lhost)) != -1)
	return (negate*(! (raddr ^ laddr)));

    /* Better be a hostname. */
    hp = gethostbyname(lhost);
    if (hp == NULL)
	return (0);

    /* Spin through ip addresses. */
    for (pp = hp->h_addr_list; *pp; ++pp)
	if (!memcmp (&raddr, *pp, sizeof (U32)))
	    return (negate);

    /* No match. */
    return (0);
}

/* Returns 1 on positive match, 0 on no match, -1 on negative match */

static int __icheckuser(pam_handle_t *pamh, struct _options *opts
			, const char *luser, const char *ruser
			, const char *rhost)
{
    /*
      luser is user entry from .rhosts/hosts.equiv file
      ruser is user id on remote host
      rhost is the remote host name
      */
    char *user;

    /* [-+]@netgroup */
    if (strncmp("+@",luser,2) == 0)
	return (innetgr(&luser[2],NULL,ruser,NULL));

    if (strncmp("-@",luser,2) == 0)
	return (-innetgr(&luser[2],NULL,ruser,NULL));

    /* -user */
    if (strncmp("-",luser,1) == 0)
	return(-(strcmp(&luser[1],ruser) == 0));

    /* + */
    if (strcmp("+",luser) == 0) {
	(void) pam_get_item(pamh, PAM_USER, (const void **)&user);
	_pam_log(LOG_WARNING, "user %s has a `+' user entry", user);
	if (opts->opt_promiscuous)
	    return(1);
	/* If not promiscuous we handle it as a negative match */
	return(-1);
    }

    /* simple string match */
    return (strcmp(ruser, luser) == 0);
}

/*
 * Returns 1 for blank lines (or only comment lines) and 0 otherwise
 */

static int __isempty(char *p)
{
    while (*p && isspace(*p)) {
	++p;
    }

    return (*p == '\0' || *p == '#') ? 1:0 ;
}

/*
 * Returns 0 if positive match, 1 if _not_ ok.
 */

static int
__ivaliduser (pam_handle_t *pamh, struct _options *opts,
	      FILE *hostf, U32 raddr,
	      const char *luser, const char *ruser, const char *rhost)
{
    register const char *user;
    register char *p;
    int hcheck, ucheck;
    char buf[MAXHOSTNAMELEN + 128];                       /* host + login */

    buf[sizeof (buf)-1] = '\0';                 	/* terminate line */

    while (fgets(buf, sizeof(buf), hostf) != NULL) {   /* hostf file line */
        p = buf;                              /* from beginning of file.. */

	/* Skip empty or comment lines */
	if (__isempty(p)) {
	    continue;
	}

	/* Skip lines that are too long. */
	if (strchr(p, '\n') == NULL) {
	    int ch = getc(hostf);

	    while (ch != '\n' && ch != EOF)
		ch = getc(hostf);
	    continue;
	}

	/*
	 * If there is a hostname at the start of the line.  Set it to
	 * lower case. A leading ' ' or '\t' indicates no hostname
	 */

	for (;*p && !isspace(*p); ++p) {
	    *p = tolower(*p);
	}

	/*
	 * next we want to find the permitted name for the remote user
	 */

	if (*p == ' ' || *p == '\t') {

	    /* <nul> terminate hostname and skip spaces */
	    for (*p++='\0'; *p && isspace(*p); ++p);

	    user = p;                   /* this is the user's name */
	    while (*p && !isspace(*p))
		++p;                    /* find end of user's name */
	} else
	    user = p;

	*p = '\0';              /* <nul> terminate username (+host?) */

	/* buf -> host(?) ; user -> username(?) */

	/* First check host part */
	hcheck=__icheckhost(pamh, opts, raddr, buf, rhost);

	if (hcheck<0)
	    return(1);

	if (hcheck) {
	    /* Then check user part */
	    if (! (*user))
		user = luser;

	    ucheck=__icheckuser(pamh, opts, user, ruser, rhost);

	    /* Positive 'host user' match? */
	    if (ucheck>0)
		return(0);

	    /* Negative 'host -user' match? */
	    if (ucheck<0)
		return(1);

	    /* Neither, go on looking for match */
	}
    }

    return (1);
}

/*
 * New .rhosts strategy: We are passed an ip address. We spin through
 * hosts.equiv and .rhosts looking for a match. When the .rhosts only
 * has ip addresses, we don't have to trust a nameserver.  When it
 * contains hostnames, we spin through the list of addresses the nameserver
 * gives us and look for a match.
 *
 * Returns 0 if ok, -1 if not ok.
 */

static int
pam_iruserok(pam_handle_t *pamh,
	 struct _options *opts, U32 raddr, int superuser,
	 const char *ruser, const char *luser, const char *rhost)
{
    const char *cp;
    struct stat sbuf;
    struct passwd *pwd;
    FILE *hostf;
    uid_t uid;
    int answer;
    char pbuf[MAXPATHLEN];               /* potential buffer overrun */

    if ((!superuser||opts->opt_hosts_equiv_rootok) && !opts->opt_no_hosts_equiv ) {

	/* try to open system hosts.equiv file */
	hostf = fopen (_PATH_HEQUIV, "r");
	if (hostf) {
	    answer = __ivaliduser(pamh, opts, hostf, raddr, luser
				  , ruser, rhost);
	    (void) fclose(hostf);
	    if (answer == 0)
		return 0;      /* remote host is equivalent to localhost */
	} /* else {
	    No hosts.equiv file on system.
	} */
    }

    if ( opts->opt_no_rhosts )
	return 1;

    /*
     * Identify user's local .rhosts file
     */

    pwd = getpwnam(luser);
    if (pwd == NULL) {
	/*
	 * luser is assumed to be valid because of an earlier check for uid = 0
	 * we don't log this error twice. However, this shouldn't happen !
	 * --cristiang
	 */
	return(1);
    }

    /* check for buffer overrun */
    if (strlen(pwd->pw_dir) + sizeof(USER_RHOSTS_FILE) + 2 >= MAXPATHLEN) {
	if (opts->opt_debug)
	    _pam_log(LOG_DEBUG,"home directory for `%s' is too long", luser);
	return 1;                               /* to dangerous to try */
    }

    (void) strcpy(pbuf, pwd->pw_dir);
    (void) strcat(pbuf, USER_RHOSTS_FILE);

    /*
     * Change effective uid while _reading_ .rhosts. (not just
     * opening).  If root and reading an NFS mounted file system,
     * can't read files that are 0600 as .rhosts files should be.
     */

    /* We are root, this will not fail */
#ifdef linux
    /* If we are on linux the better way is setfsuid */
    uid = setfsuid(pwd->pw_uid);
    hostf = fopen(pbuf, "r");
#else
    uid = geteuid();
    (void) seteuid(pwd->pw_uid);
    hostf = fopen(pbuf, "r");
#endif

    if (hostf == NULL) {
        if (opts->opt_debug)
	    _pam_log(LOG_DEBUG,"Could not open %s file",pbuf);
	answer = 1;
	goto exit_function;
    }

    /*
     * If not a regular file, or is owned by someone other than
     * user or root or if writeable by anyone but the owner, quit.
     */

    cp = NULL;
    if (lstat(pbuf, &sbuf) < 0 || !S_ISREG(sbuf.st_mode))
	cp = ".rhosts not regular file";
    else if (fstat(fileno(hostf), &sbuf) < 0)
	cp = ".rhosts fstat failed";
    else if (sbuf.st_uid && sbuf.st_uid != pwd->pw_uid)
	cp = "bad .rhosts owner";
    else if (sbuf.st_mode & S_IWOTH)
	cp = ".rhosts writable by other!";
    else if (sbuf.st_mode & S_IWGRP) {

	/* private group caveat */
	if (opts->opt_private_group) {
	    struct group *grp = getgrgid(sbuf.st_gid);

	    if (NULL == grp || NULL == grp->gr_name
		|| strcmp(luser,grp->gr_name)) {
		cp = ".rhosts writable by public group";
	    } else if (grp->gr_mem) {
		int gcount;

		/* require at most one member (luser) of this group */
		for (gcount=0; grp->gr_mem[gcount]; ++gcount) {
		    if (strcmp(grp->gr_mem[gcount], luser)) {
			gcount = -1;
			break;
		    }
		}
		if (gcount < 0) {
		    cp = ".rhosts writable by other members of group";
		}
	    }
	} else {
	    cp = ".rhosts writable by group";
	}

    } /* It is _NOT_ safe to append an else here...  Do so prior to
       * S_IWGRP check */

    /* If there were any problems, quit. */
    if (cp) {
	opts->last_error = cp;
	answer = 1;
	goto exit_function;
    }

    answer = __ivaliduser (pamh, opts, hostf, raddr, luser, ruser, rhost);

exit_function:
    /*
     * Go here to exit after the fsuid/euid has been adjusted so that
     * they are reset before we exit.
     */

#ifdef linux
    setfsuid(uid);
#else
    (void)seteuid(uid);
#endif

    if (hostf != NULL)
        (void) fclose(hostf);

    return answer;
}

static int
pam_ruserok (pam_handle_t *pamh,
	     struct _options *opts, const char *rhost, int superuser,
	     const char *ruser, const char *luser)
{
    struct hostent *hp;
    int answer = 1;                             /* default to failure */
    U32 *addrs;
    int n, i;

    opts->last_error = (char *) 0;
    hp               = gethostbyname(rhost);         /* identify host */

    if (hp != NULL) {
	/* First of all check the address length */
        if (hp->h_length != 4) {
            _pam_log(LOG_ALERT, "pam_rhosts module can't work with not IPv4 "
		     "addresses");
            return 1;                                    /* not allowed */
        }

        /* loop though address list */
        for (n = 0; hp->h_addr_list[n]; n++);
        D(("rhosts: %d addresses", n));

        if (n) {
            addrs = calloc (n, hp->h_length);
            for (i = 0; i < n; i++)
                memcpy (addrs+i, hp->h_addr_list[i], hp->h_length);

            for (i = 0; i < n && answer; i++) {
                D(("rhosts: address %d is %04x", i, addrs[i]));
                answer = pam_iruserok(pamh, opts, addrs[i], superuser,
				      ruser, luser, rhost);
                         /* answer == 0 means success */
            }

            free (addrs);
        }
    }

    return answer;
}

/*
 * Internal function to do authentication
 */

static int _pam_auth_rhosts (pam_handle_t *pamh,
			     int flags,
			     int argc,
			     const char **argv)
{
    int retval;
    const char *luser;
    const char *ruser,*rhost;
    struct _options opts;
    int as_root = 0;
    /*
     * Look at the options and set the flags accordingly.
     */
    memset (&opts, 0, sizeof (opts));
    set_parameters (&opts, flags, argc, argv);
    /*
     * Obtain the parameters for the various items
     */
    for (;;) {                         /* abuse loop to avoid goto */

	/* get the remotehost */
	retval = pam_get_rhost(pamh, &rhost, NULL);
	(void) pam_set_item(pamh, PAM_RHOST, rhost);
	if (retval != PAM_SUCCESS) {
	    if (opts.opt_debug) {
		_pam_log(LOG_DEBUG, "could not get the remote host name");
	    }
	    break;
	}

	/* get the remote user */
	retval = pam_get_ruser(pamh, &ruser, NULL);
	(void) pam_set_item(pamh, PAM_RUSER, ruser);
	if (retval != PAM_SUCCESS) {
	    if (opts.opt_debug)
		_pam_log(LOG_DEBUG, "could not get the remote username");
	    break;
	}

	/* get the local user */
	retval = pam_get_user(pamh, &luser, NULL);

	if (retval != PAM_SUCCESS) {
	    if (opts.opt_debug)
		_pam_log(LOG_DEBUG, "could not determine name of local user");
	    break;
	}

	if (opts.superuser && !strcmp(opts.superuser, luser)) {
	    as_root = 1;
	}

	/* check if the luser uid == 0... --cristiang */
	if (! opts.opt_no_uid_check) {
	    struct passwd *luser_pwd;

	    luser_pwd = getpwnam(luser);
	    if (luser_pwd == NULL) {
		if (opts.opt_debug)
		    _pam_log(LOG_DEBUG, "user '%s' unknown to this system",
			     luser);
		retval = PAM_AUTH_ERR;
		break;
	    }
	    if (luser_pwd->pw_uid == 0)
		as_root = 1;
	    luser_pwd = NULL;                                   /* forget */
	}
/*
 * Validate the account information.
 */
	if (pam_ruserok (pamh, &opts, rhost, as_root, ruser, luser) != 0) {
	    if ( !opts.opt_suppress ) {
		_pam_log(LOG_WARNING, "denied to %s@%s as %s: %s",
			 ruser, rhost, luser, (opts.last_error==NULL) ?
			 "access not allowed":opts.last_error);
	    }
	    retval = PAM_AUTH_ERR;
	} else {
	    _pam_log(LOG_NOTICE, "allowed to %s@%s as %s",
                     ruser, rhost, luser);
	}
	break;
    }

    return retval;
}

/* --- authentication management functions --- */

PAM_EXTERN
int pam_sm_authenticate (pam_handle_t *pamh,
			 int flags,
			 int argc,
			 const char **argv)
{
    int retval;

    if (sizeof(U32) != 4) {
        _pam_log (LOG_ALERT, "pam_rhosts module can\'t work on this hardware "
		  "(yet)");
        return PAM_AUTH_ERR;
    }
    sethostent(1);
    retval = _pam_auth_rhosts (pamh, flags, argc, argv);
    endhostent();
    return retval;
}

PAM_EXTERN
int pam_sm_setcred(pam_handle_t *pamh,int flags,int argc,
		   const char **argv)
{
    return PAM_SUCCESS;
}

/* end of module definition */

#ifdef PAM_STATIC

/* static module data */

struct pam_module _pam_rhosts_auth_modstruct = {
    "pam_rhosts_auth",
    pam_sm_authenticate,
    pam_sm_setcred,
    NULL,
    NULL,
    NULL,
    NULL,
};

#endif


text:
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import vm

mini = None
vm_name = 'test-vm'
vm_new_name='vm-rename'

def test():
    global mini
    global vm_name
    global vm_new_name
    mini = vm.VM()
    mini.create_vm(name=vm_name)
    mini.update_info(res_type='vm', res_name=vm_name, new_name=vm_new_name, new_dsc='test dsc')
    mini.check_browser_console_log()
    test_util.test_pass('Test VM Update Info Successful')

def env_recover():
    global mini
    global vm_new_name
    mini.delete_vm(vm_new_name)
    mini.close()

#Will be called only if exception happens in test().
def error_cleanup():
    global mini
    try:
        mini.delete_vm()
        mini.close()
    except:
        pass

redpajama_set_name: RedPajamaGithub


text:
SQLAlchemy Dialect for BigQuery
===============================

|GA| |pypi| |versions|

`SQLALchemy Dialects`_

- `Dialect Documentation`_
- `Product Documentation`_

.. |GA| image:: https://img.shields.io/badge/support-GA-gold.svg
   :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#general-availability
.. |pypi| image:: https://img.shields.io/pypi/v/sqlalchemy-bigquery.svg
   :target: https://pypi.org/project/sqlalchemy-bigquery/
.. |versions| image:: https://img.shields.io/pypi/pyversions/sqlalchemy-bigquery.svg
   :target: https://pypi.org/project/sqlalchemy-bigquery/
.. _SQLAlchemy Dialects: https://docs.sqlalchemy.org/en/14/dialects/
.. _Dialect Documentation: https://googleapis.dev/python/sqlalchemy-bigquery/latest
.. _Product Documentation: https://cloud.google.com/bigquery/docs/

Quick Start
-----------

In order to use this library, you first need to go through the following steps:

1. `Select or create a Cloud Platform project.`_
2. [Optional] `Enable billing for your project.`_
3. `Enable the BigQuery Storage API.`_
4. `Setup Authentication.`_

.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project
.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project
.. _Enable the BigQuery Storage API.: https://console.cloud.google.com/apis/library/bigquery.googleapis.com
.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html

Installation
------------

Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to
create isolated Python environments. The basic problem it addresses is one of
dependencies and versions, and indirectly permissions.

With `virtualenv`_, it's possible to install this library without needing system
install permissions, and without clashing with the installed system
dependencies.

.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/

Supported Python Versions
^^^^^^^^^^^^^^^^^^^^^^^^^
Python >= 3.7

Unsupported Python Versions
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Python <= 3.6.

Mac/Linux
^^^^^^^^^

.. code-block:: console

    pip install virtualenv
    virtualenv <your-env>
    source <your-env>/bin/activate
    <your-env>/bin/pip install sqlalchemy-bigquery

Windows
^^^^^^^

.. code-block:: console

    pip install virtualenv
    virtualenv <your-env>
    <your-env>\Scripts\activate
    <your-env>\Scripts\pip.exe install sqlalchemy-bigquery

Usage
-----

SQLAlchemy
^^^^^^^^^^

.. code-block:: python

    from sqlalchemy import *
    from sqlalchemy.engine import create_engine
    from sqlalchemy.schema import *
    engine = create_engine('bigquery://project')
    table = Table('dataset.table', MetaData(bind=engine), autoload=True)
    print(select([func.count('*')], from_obj=table).scalar())

Project
^^^^^^^

``project`` in ``bigquery://project`` is used to instantiate BigQuery client with the specific project ID. To infer project from the environment, use ``bigquery://`` – without ``project``

Authentication
^^^^^^^^^^^^^^

Follow the `Google Cloud library guide <https://google-cloud-python.readthedocs.io/en/latest/core/auth.html>`_ for authentication. Alternatively, you can provide the path to a service account JSON file in ``create_engine()``:

.. code-block:: python

    engine = create_engine('bigquery://', credentials_path='/path/to/keyfile.json')

Location
^^^^^^^^

To specify location of your datasets pass ``location`` to ``create_engine()``:

.. code-block:: python

    engine = create_engine('bigquery://project', location="asia-northeast1")

Table names
^^^^^^^^^^^

To query tables from non-default projects or datasets, use the following format for the SQLAlchemy schema name: ``[project.]dataset``, e.g.:

.. code-block:: python

    # If neither dataset nor project are the default
    sample_table_1 = Table('natality', schema='bigquery-public-data.samples')
    # If just dataset is not the default
    sample_table_2 = Table('natality', schema='bigquery-public-data')

Batch size
^^^^^^^^^^

By default, ``arraysize`` is set to ``5000``. ``arraysize`` is used to set the batch size for fetching results. To change it, pass ``arraysize`` to ``create_engine()``:

.. code-block:: python

    engine = create_engine('bigquery://project', arraysize=1000)

Page size for dataset.list_tables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By default, ``list_tables_page_size`` is set to ``1000``. ``list_tables_page_size`` is used to set the max_results for `dataset.list_tables`_ operation. To change it, pass ``list_tables_page_size`` to ``create_engine()``:

.. _`dataset.list_tables`: https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/list
.. code-block:: python

    engine = create_engine('bigquery://project', list_tables_page_size=100)

Adding a Default Dataset
^^^^^^^^^^^^^^^^^^^^^^^^

If you want to have the ``Client`` use a default dataset, specify it as the "database" portion of the connection string.

.. code-block:: python

    engine = create_engine('bigquery://project/dataset')

When using a default dataset, don't include the dataset name in the table name, e.g.:

.. code-block:: python

    table = Table('table_name')

Note that specifying a default dataset doesn't restrict execution of queries to that particular dataset when using raw queries, e.g.:

.. code-block:: python

    # Set default dataset to dataset_a
    engine = create_engine('bigquery://project/dataset_a')

    # This will still execute and return rows from dataset_b
    engine.execute('SELECT * FROM dataset_b.table').fetchall()

Connection String Parameters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

There are many situations where you can't call ``create_engine`` directly, such as when using tools like `Flask SQLAlchemy <http://flask-sqlalchemy.pocoo.org/2.3/>`_. For situations like these, or for situations where you want the ``Client`` to have a `default_query_job_config <https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/generated/google.cloud.bigquery.client.Client.html#google.cloud.bigquery.client.Client>`_, you can pass many arguments in the query of the connection string.

The ``credentials_path``, ``credentials_info``, ``credentials_base64``, ``location``, ``arraysize`` and ``list_tables_page_size`` parameters are used by this library, and the rest are used to create a `QueryJobConfig <https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/generated/google.cloud.bigquery.job.QueryJobConfig.html#google.cloud.bigquery.job.QueryJobConfig>`_

Note that if you want to use query strings, it will be more reliable if you use three slashes, so ``'bigquery:///?a=b'`` will work reliably, but ``'bigquery://?a=b'`` might be interpreted as having a "database" of ``?a=b``, depending on the system being used to parse the connection string.

Here are examples of all the supported arguments. Any not present are either for legacy sql (which isn't supported by this library), or are too complex and are not implemented.

.. code-block:: python

    engine = create_engine(
        'bigquery://some-project/some-dataset' '?'
        'credentials_path=/some/path/to.json' '&'
        'location=some-location' '&'
        'arraysize=1000' '&'
        'list_tables_page_size=100' '&'
        'clustering_fields=a,b,c' '&'
        'create_disposition=CREATE_IF_NEEDED' '&'
        'destination=different-project.different-dataset.table' '&'
        'destination_encryption_configuration=some-configuration' '&'
        'dry_run=true' '&'
        'labels=a:b,c:d' '&'
        'maximum_bytes_billed=1000' '&'
        'priority=INTERACTIVE' '&'
        'schema_update_options=ALLOW_FIELD_ADDITION,ALLOW_FIELD_RELAXATION' '&'
        'use_query_cache=true' '&'
        'write_disposition=WRITE_APPEND'
    )

In cases where you wish to include the full credentials in the connection URI you can base64 the credentials JSON file and supply the encoded string to the ``credentials_base64`` parameter.

.. code-block:: python

    engine = create_engine(
        'bigquery://some-project/some-dataset' '?'
        'credentials_base64=eyJrZXkiOiJ2YWx1ZSJ9Cg==' '&'
        'location=some-location' '&'
        'arraysize=1000' '&'
        'list_tables_page_size=100' '&'
        'clustering_fields=a,b,c' '&'
        'create_disposition=CREATE_IF_NEEDED' '&'
        'destination=different-project.different-dataset.table' '&'
        'destination_encryption_configuration=some-configuration' '&'
        'dry_run=true' '&'
        'labels=a:b,c:d' '&'
        'maximum_bytes_billed=1000' '&'
        'priority=INTERACTIVE' '&'
        'schema_update_options=ALLOW_FIELD_ADDITION,ALLOW_FIELD_RELAXATION' '&'
        'use_query_cache=true' '&'
        'write_disposition=WRITE_APPEND'
    )

To create the base64 encoded string you can use the command line tool ``base64``, or ``openssl base64``, or ``python -m base64``.

Alternatively, you can use an online generator like `www.base64encode.org <https://www.base64encode.org>_` to paste your credentials JSON file to be encoded.

Supplying Your Own BigQuery Client
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The above connection string parameters allow you to influence how the BigQuery client used to execute your queries will be instantiated.
If you need additional control, you can supply a BigQuery client of your own:

.. code-block:: python

    from google.cloud import bigquery

    custom_bq_client = bigquery.Client(...)

    engine = create_engine(
        'bigquery://some-project/some-dataset?user_supplied_client=True',
	connect_args={'client': custom_bq_client},
    )

Creating tables
^^^^^^^^^^^^^^^

To add metadata to a table:

.. code-block:: python

    table = Table('mytable', ..., bigquery_description='my table description', bigquery_friendly_name='my table friendly name')

To add metadata to a column:

.. code-block:: python

    Column('mycolumn', doc='my column description')

Threading and Multiprocessing
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Because this client uses the `grpc` library, it's safe to
share instances across threads.

In multiprocessing scenarios, the best
practice is to create client instances *after* the invocation of
`os.fork` by `multiprocessing.pool.Pool` or
`multiprocessing.Process`.


text:
<?php
use wbraganca\fancytree\FancytreeWidget;

/** @var $categories array */
?>

Categories

    <?= FancytreeWidget::widget([
        'name' => 'category',
        'source' => $categories,
        'clickFolderMode' => FancytreeWidget::CLICK_ACTIVATE_EXPAND,
    ]) ?>


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package org.apache.hadoop.hbase.regionserver.metrics (HBase 0.94.9 API)
</TITLE>

<META NAME="date" CONTENT="2013-06-24">

<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 Package
org.apache.hadoop.hbase.regionserver.metrics

Packages that use org.apache.hadoop.hbase.regionserver.metrics

org.apache.hadoop.hbase.io

org.apache.hadoop.hbase.io.hfile
Provides the hbase data+index+metadata file.

org.apache.hadoop.hbase.regionserver

org.apache.hadoop.hbase.regionserver.metrics

Classes in org.apache.hadoop.hbase.regionserver.metrics used by org.apache.hadoop.hbase.io

SchemaConfigured

          A base class for objects that are associated with a particular table and
 column family.

SchemaMetrics.SchemaAware

Classes in org.apache.hadoop.hbase.regionserver.metrics used by org.apache.hadoop.hbase.io.hfile

SchemaConfigured

          A base class for objects that are associated with a particular table and
 column family.

SchemaMetrics

          A collection of metric names in a given column family or a (table, column
 family) combination.

SchemaMetrics.SchemaAware

Classes in org.apache.hadoop.hbase.regionserver.metrics used by org.apache.hadoop.hbase.regionserver

RegionServerMetrics

          This class is for maintaining the various regionserver statistics
 and publishing them through the metrics interfaces.

SchemaConfigured

          A base class for objects that are associated with a particular table and
 column family.

SchemaMetrics.SchemaAware

Classes in org.apache.hadoop.hbase.regionserver.metrics used by org.apache.hadoop.hbase.regionserver.metrics

RegionServerDynamicMetrics

          This class is for maintaining  the various RPC statistics
 and publishing them through the metrics interfaces.

SchemaConfigured

          A base class for objects that are associated with a particular table and
 column family.

SchemaMetrics

          A collection of metric names in a given column family or a (table, column
 family) combination.

SchemaMetrics.BlockMetricType

SchemaMetrics.SchemaAware

SchemaMetrics.StoreMetricType

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2013 The Apache Software Foundation. All Rights Reserved.


text:
Dot
===

`dot` is a framework for managing configuration files. A major goal for
`dot` is that it should be simple to create configurations based off of
*existing* configurations. `dot` provides the ability to create Ruby DSLs
designed to accommodate specific configuration file syntax. A `dot`
project's code consists of Ruby classes dressed up in these specialized
DSLs.

To give you a flavor of how `dot` works, look at the `set` command from the
[Polkadots][polkadots] collection's vimrc. If Alice has `set :tabstop, 4` in
her source vimrc, this will compile to `set tabstop=4`. If Bob bases his
configuration off of Alice's (via subclassing, *not* manual copy and paste),
then he could change it by adding `set :tabstop, 2`, or remove it by adding
`remove :set, :tabstop`.

Quick Start
-----------

 1. Find a dotfile suite such as [Polkadots][polkadots] or
    [Jakesdots][jakesdots] or create your own.
 2. Install the collection:

        $ gem install polkadots

    Or else, install `dot` directly:

        $ gem install dot

 3. (optional) Initialize your project's `.dot` by running this command
    in your project's root directory:

        $ dot init

 4. Configure `dot` to work with the suite:

        $ dot config --gem polkadots

    Or:

        $ dot config --bundle <suite_name> --path <path/to/suite>

 5. Install dotfiles.

        $ dot preview  # (optional) Examine the dotfiles before you install.
        $ dot delete   # (optional) Break any symlinks into your ~/.dotfiles.
        $ dot install

Configuring
-----------

Look at [Jakesdots][jakesdots] for an example of how you can configure your
dotfiles. The general steps are:

 1. Create your suite:

        class MyDots < Polkadots

    Or, if you want to individually select which dotfiles you want:

        class MyDots < DotSuite
          dot :vimrc, Polkadots
          dot :gitconfig, JakesDots

 2. Make changes to the dotfiles:

          ...  # In suite class
          dot :vimrc do
            set :backround, :dark
            colorscheme :solarized
            ...
          end

See Also
--------

View the usage (`dot --help`) and man page (`dot man`) for more info.

[polkadots]: https://github.com/jakesandlund/polkadots
[jakesdots]: https://github.com/jakesandlund/jakesdots


text:
package org.apache.spark.sql.execution.debug

import org.scalatest.FunSuite

import org.apache.spark.sql.TestData._
import org.apache.spark.sql.test.TestSQLContext._

class DebuggingSuite extends FunSuite {
  test("DataFrame.debug()") {
    testData.debug()
  }

  test("DataFrame.typeCheck()") {
    testData.typeCheck()
  }
}


text:
{% load hq_shared_tags %}
{% load i18n %}

        {% trans "Name" %}
        {% trans "Preview" %}
        {% if allow_edit %}
            {% trans "Edit" %}
        {% endif %}
        {% trans "Download" %}
        {% if not deid and saved_exports_has_media %}
            {% trans "Download Multimedia" %}
        {% endif %}

            {% trans "Add to Custom Bulk Export" %}

                {% trans "Select" %}:
                {% trans "all" %}
                {% trans "none" %}

        {% if allow_edit %}
            {% trans "Delete" %}
        {% endif %}

    {% for export in saved_exports %}

                {{ export.name|default:"[blank]" }}
                {% if not deid and export.is_safe %}{% trans "de-identified" %}{% endif %}

                    {% trans "Sheet Name" %} :
                    <input data-bind="updateCustomSheetName: selected_exports, checkForUniqueSheetName: sheet_names, event: {keydown: checkCustomSheetNameLength, keyup: updateCustomSheetNameCharacterCount}"
                           class="sheetname"
                           data-exportid="{{ export.get_id }}"
                           value="{{ export.name|default:"[blank]" }}" />
                    31
                    {% trans "duplicate" %}

{{ export.formname }}

                    {% trans "Web Preview" %}

            {% if allow_edit %}

                         {% trans "Edit" %}

            {% endif %}

                <a data-toggle="modal" href="#export-download-status"
                   data-backdrop="static"
                   data-formname="{{ export.name }}"
                   data-xmlns="{{ export.xmlns }}"
                   data-exportid="{{ export.get_id }}"
                   data-exporttype="form"
                   data-dlocation='{% url "export_custom_data" domain export.get_id %}'
                   data-format="{{ export.default_format }}"
                   data-bind="click: requestDownload"
                   class="dl-export btn btn-primary"> {% trans "Download" %}

            {% if not deid and saved_exports_has_media %}

                    {% with property_hash|dict_lookup:export.name as properties %}
                      {% if properties.size %}
                        <a  data-toggle='modal' href="#export-download-status"
                            {% if export.app.id %}
                                data-downloadurl='{% url "form_multimedia_export" domain %}?app_id={{export.app_id}}&export_id={{properties.export_id}}&{{ get_filter_params.urlencode|safe }}&name={{export.name}}'
                            {% else %}
                                data-downloadurl='{% url "form_multimedia_export" domain %}?export_id={{properties.export_id}}&{{ get_filter_params.urlencode|safe }}&name={{export.name}}'
                            {% endif %}
                            data-xmlns="{{export.xmlns}}"
                            data-modulename="{{ export.name|default:"[blank]" }}"
                            data-formname=""
                            data-bind='click: requestMultimediaDownload'
                            class="btn btn-primary dl-export" >

                                {% trans "Download " %}
 ({{properties.size}})

                      {% else %}
                          {% trans "No Multimedia" %}
                      {% endif %}
                    {% endwith %}

            {% endif %}

                {% ifequal export.default_format custom_bulk_export_format %}

                        <input type="checkbox" class="select-custom" data-bind="event: {change: updateSelectedExports}" />
                        + {% trans "Bulk Export" %}

                {% else %}
                    {{ export.default_format }} {% trans "Not Available" %}
                {% endifequal %}

            {% if allow_edit %}

                     {% trans "Delete" %}
                    {% include "export/dialogs/delete_custom_export_dialog.html" %}

            {% endif %}

    {% endfor %}


text:
/*****************************************************************************
* This example shows how to use PAPI_overflow to set up an event set to      *
* begin registering overflows.
******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include "papi.h"		/* This needs to be included every time you use PAPI */
#include <pthread.h>

#define OVER_FMT    "handler(%d ) Overflow at %p! bit=%#llx \n"
#define THRESHOLD 100000
#define ERROR_RETURN(retval) { fprintf(stderr, "Error %d %s:line %d: \n", retval,__FILE__,__LINE__);  exit(retval); }

int total = 0;	/* we use total to track the amount of overflows that occured */

/* THis is the handler called by PAPI_overflow*/
void
handler(int EventSet, void *address, long long overflow_vector, void *context)
{
   fprintf(stderr, OVER_FMT, EventSet, address, overflow_vector);
   total++;
}

int main ()
{
   int EventSet = PAPI_NULL;
   /* must be set to null before calling PAPI_create_eventset */

   char errstring[PAPI_MAX_STR_LEN];
   long long (values[2])[2];
   int retval, i;
   double tmp = 0;
   int PAPI_event;		/* a place holder for an event preset */
   char event_name[PAPI_MAX_STR_LEN];

   /****************************************************************************
   *  This part initializes the library and compares the version number of the *
   * header file, to the version of the library, if these don't match then it  *
   * is likely that PAPI won't work correctly.If there is an error, retval     *
   * keeps track of the version number.                                        *
   ****************************************************************************/

   if ((retval = PAPI_library_init (PAPI_VER_CURRENT)) != PAPI_VER_CURRENT)
   {
      printf("Library initialization error! \n");
      exit(1);
   }

   /* Here we create the eventset */
   if ((retval=PAPI_create_eventset (&EventSet)) != PAPI_OK)
      ERROR_RETURN(retval);

   PAPI_event = PAPI_TOT_INS;

   /* Here we are querying for the existence of the PAPI presets  */
   if (PAPI_query_event (PAPI_TOT_INS) != PAPI_OK)
   {
      PAPI_event = PAPI_TOT_CYC;

      if ((retval=PAPI_query_event (PAPI_TOT_INS)) != PAPI_OK)
         ERROR_RETURN(retval);

      printf ("PAPI_TOT_INS not available on this platform.");
      printf (" so subst PAPI_event with PAPI_TOT_CYC !\n\n");

   }

   /* PAPI_event_code_to_name is used to convert a PAPI preset from
     its integer value to its string name. */
   if ((retval = PAPI_event_code_to_name (PAPI_event, event_name)) != PAPI_OK)
      ERROR_RETURN(retval);

   /* add event to the event set */
   if ((retval = PAPI_add_event (EventSet, PAPI_event)) != PAPI_OK)
      ERROR_RETURN(retval);

   /* register overflow and set up threshold */
   /* The threshold "THRESHOLD" was set to 100000 */
   if ((retval = PAPI_overflow (EventSet, PAPI_event, THRESHOLD, 0,
		                       handler)) != PAPI_OK)
      ERROR_RETURN(retval);

   printf ("Here are the addresses at which overflows occured and overflow vectors \n");
  printf ("--------------------------------------------------------------\n");

  /* Start counting */

   if ( (retval=PAPI_start (EventSet)) != PAPI_OK)
      ERROR_RETURN(retval);

   for (i = 0; i < 2000000; i++)
   {
      tmp = 1.01 + tmp;
      tmp++;
   }

   /* Stops the counters and reads the counter values into the values array */
   if ( (retval=PAPI_stop (EventSet, values[0])) != PAPI_OK)
      ERROR_RETURN(retval);

   printf ("The total no of overflows was %d\n", total);

   /* clear the overflow status */
   if ((retval = PAPI_overflow (EventSet, PAPI_event, 0, 0,
		                       handler)) != PAPI_OK)
      ERROR_RETURN(retval);

   /************************************************************************
    * PAPI_cleanup_eventset can only be used after the counter has been    *
    * stopped then it remove all events in the eventset                    *
    ************************************************************************/
   if ( (retval=PAPI_cleanup_eventset (EventSet)) != PAPI_OK)
      ERROR_RETURN(retval);

   /* Free all memory and data structures, EventSet must be empty. */
   if ( (retval=PAPI_destroy_eventset(&EventSet)) != PAPI_OK)
      ERROR_RETURN(retval);

   /* free the resources used by PAPI */
   PAPI_shutdown();

   exit(0);
}


text:
'use strict';

module.exports = TemplateModelFactory;

TemplateModelFactory.$provide = 'Models.Template';
TemplateModelFactory.$inject = [
    'Model',
    'Renderable',
    '_',
    'Services.Configuration'
];

function TemplateModelFactory (Model, Renderable, _, configuration) {
    var templateModel = _.merge(
        {},
        Renderable,
        { identity: 'templates', connection: configuration.get('databaseType', 'mongo') }
    );
    return Model.extend(templateModel);
}


text:
file_path = File.expand_path("../day-08-input.txt", __FILE__)
input     = File.read(file_path).strip

height = 6
width = 25

area = height * width

layers = input.chars.map(&:to_i).each_slice(area)

layer = layers.min_by do |layer|
  layer.count { |pixel| pixel.zero? }
end

puts layer.count { |pixel| pixel == 1 } *
  layer.count { |pixel| pixel == 2 }


text:
[![Build Status](https://travis-ci.org/justsml/git-info-tiny.svg?branch=master)](https://travis-ci.org/justsml/git-info-tiny)

Install
-----------
```
	npm install git-info-tiny
```
Run tests
```
	make test
```

Usage
-----------
Returns current project info from git.

Example Response:
```javascript
{
	tinySHA: 'e004ccf',
	SHA: 'e004ccf3a9a426ab80166d51d56e0c8c9414893c',
	currentBranch: 'master',
	lastCommitTime: '"2014-12-19 14:08:12 -0700"',
	currentUser: 'Dan Levy',
	smallSHA: 'e004ccf3a9a426ab',
	lastCommitMessage: '"travis ci config added"\n',
	lastCommitNumber: '5',
	lastCommitAuthor: '"Dan Levy"',
	remoteUrl: 'git@github.com:justsml/git-info-tiny.git'
}
```


text:
from __future__ import unicode_literals
import time
import hmac
import logging
from hashlib import sha384
import tg
from tg.decorators import before_validate
from tg.configurator import ConfigurationComponent, EnvironmentLoadedConfigurationAction
from tg.support.converters import asbool, asint

def asbytes(obj):
    return obj.encode('ascii')

ENCODING = 'latin1'

def _csrf_error(reason):
    logging.warning('possible CSRF attack mitigated, details: %s', reason)
    tg.abort(403, 'The form you submitted is invalid or has expired: ' + reason)

class CSRFConfigurationComponent(ConfigurationComponent):
    """A component that will add CSRF protection to your forms"""
    id = 'csrf'

    def get_defaults(self):
        return {
            'csrf.enabled': True,
            'csrf.secret': None,
            'csrf.token_name': '_csrf_token',
            'csrf.expires': 60 * 10,
            'csrf.path': '/',  # cookie path
            'csrf.error_handler': _csrf_error,
        }
    def get_coercion(self):
        return {
            'csrf.enabled': asbool,
            'csrf.secret': asbytes,
            'csrf.expires': asint,
        }

    def on_bind(self, configurator):
        pass

def _get_conf():
    """
    Return CSRF configuration options.

    This function raises ``KeyError`` if configuration misses
    """
    conf = tg.config
    csrf_secret = conf['csrf.secret']
    csrf_token_name = conf['csrf.token_name']
    csrf_path = conf['csrf.path'].encode(ENCODING)
    cookie_expires = conf['csrf.expires']
    handler = conf['csrf.error_handler']
    return csrf_secret, csrf_token_name, csrf_path, cookie_expires, handler

def _generate_csrf_token():
    """
    Generate and set new CSRF token in cookie. The generated token is set to
    ``request.csrf_token`` attribute for easier access by other functions.
    """
    secret, token_name, path, expires, _ = _get_conf()
    session_id = tg.session['_id']
    tg.session.save()
    timestamp = str(time.time())
    digest = hmac.new(secret, (session_id + timestamp).encode('ascii'), digestmod=sha384).hexdigest()
    token = digest + ',' + timestamp
    tg.response.signed_cookie(token_name, token, secret.decode('ascii'),
                              path=path, max_age=expires)
    tg.request.csrf_token = token

def _validate_csrf(token):
    secret, token_name, path, expires, handler = _get_conf()
    session_id = tg.session['_id']
    digest, timestamp = token.split(',')
    if float(timestamp) < time.time() - expires:
        handler('expired')
    new_digest = hmac.new(secret, (session_id + timestamp).encode('ascii'), digestmod=sha384).hexdigest()
    try:
        if not hmac.compare_digest(digest, new_digest):
            handler('digest differs')
    except TypeError:
        # python < 3.3 but possible timing attack
        if digest != new_digest:
            handler('digest differs')

@before_validate
def csrf_token(remainder, params):
    """
    Create and set CSRF token in preparation for subsequent POST request. This
    decorator is used to set the token.
    It also sets the ``'Cache-Control'`` header in order to prevent caching of
    the page on which the token appears.

    The POST handler must use the :py:func:`~csrf_protect` decorator for the
    token to be used in any way.

    The token is available in the ``tg.request`` object as ``csrf_token``
    attribute::

        @csrf_token
        @expose('myapp.templates.put_token')
        def put_token_in_form():
            return dict(token=request.csrf_token)

    In a view, you can render this token as a hidden field inside the form. The
    hidden field must have the name specified in configuration ``csrf.token_name``,
    by default it is ``_csrf_token``::

        <form method="POST">
            <input type="hidden" name="_csrf_token" value="{{ token }}">
            ....
        </form>
    """
    _generate_csrf_token()
    # Pages with CSRF tokens should not be cached
    tg.request.headers[str('Cache-Control')] = ('no-cache, max-age=0, '
                                         'must-revalidate, no-store')

@before_validate
def csrf_protect(remainder, params):
    """
    Perform CSRF protection checks. Performs checks to determine if submitted
    form data matches the token in the cookie. It is assumed that the GET
    request handler successfully set the token for the request and that the
    form was instrumented with a CSRF token field. Use the
    :py:func:`~csrf_token` decorator to do this.

    Generally, the handler does not need to do anything
    CSRF-protection-specific. All it needs is the decorator::

        @csrf_protect
        @expose()
        def protected_post_handler():
            return 'OK!'
    """
    secret, token_name, path, expires, handler = _get_conf()

    cookie_token = tg.request.signed_cookie(token_name, secret=secret.decode('ascii'))
    if not cookie_token:
        handler('csrf cookie not present')

    form_token = tg.request.args_params.get(token_name)
    if not form_token:
        handler('csrf input not present')

    if form_token != cookie_token:
        tg.response.delete_cookie(token_name, path=path)
        handler('cookie and input mismatch')

    _validate_csrf(form_token)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using QTrkDotNet;

namespace NanoBLOC
{
	public partial class LUTViewer : UserControl
	{
		public LUTViewer()
		{
			InitializeComponent();
		}

		int zplanes;
		FloatImg lutImage;

		public void SetLUT(FloatImg lutimg, int zplanes)
		{
			lutImage = lutimg;
			this.zplanes = zplanes;

			if (lutimg != null)
			{
				int lutcount = lutimg.h / zplanes;
				trackBarBeadIndex.Maximum = Math.Max(0, lutcount - 1);
			}
			UpdateImage();
		}

        private void trackBarBeadIndex_Scroll(object sender, EventArgs e)
        {
			UpdateImage();
        }

		void UpdateImage()
		{
			if (lutImage!=null) {
				using (var img = lutImage.ExtractSubsection(trackBarBeadIndex.Value * zplanes, zplanes))
				{
					img.Normalize();
					pictureBoxLUT.Image = img.ToImage();
				}
			}
			else
				pictureBoxLUT.Image = null;
		}
    }
}


text:
@interface LineBreakModeViewController : BaseLabelViewController

@end


text:
package com.example.kanjuice.activities;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;

import com.example.kanjuice.R;

public class SplashActivity extends Activity {

    private BroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("AppSharedPreferences", Context.MODE_PRIVATE);
        if (sharedPreferences.getBoolean("isFirstRun", true)) {
            setContentView(R.layout.activity_splash);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(SplashActivity.this, RegionSelectionActivity.class));
                    finish();
                }
            }, 3000);
            sharedPreferences.edit().putBoolean("isFirstRun", false).commit();
        } else {
            startActivity(new Intent(SplashActivity.this, TeaMenuActivity.class));
            finish();
        }

    }

}


text:
package net.blufenix.gif2boot;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

public class BufferedImageManipulator {

	private Status status = Status.NOT_DONE;
	private BufferedImage image = null;

	public BufferedImageManipulator(BufferedImage image) {
		setImage(image);
	}

	public BufferedImageManipulator() {
		// do nothing
	}

	public void setImage(BufferedImage image) {
		this.image = image;
	}

	public BufferedImage getImage() {
		return image;
	}

	public void setStatus(Status status) {
		this.status = status;
	}

	public Status getStatus() {
		return status;
	}

	public void resizeToScreen(int resizeWidth, int resizeHeight) {
		// Create new (blank) image of required (scaled) size
		BufferedImage scaledImage = new BufferedImage(resizeWidth, resizeHeight, BufferedImage.TYPE_INT_ARGB);
		// Paint scaled version of image to new image
		Graphics2D graphics2D = scaledImage.createGraphics();
		graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2D.drawImage(image, 0, 0, resizeWidth, resizeHeight, null);
		graphics2D.dispose();
		image = scaledImage;
	}

	public void cropSidesToMatchAspectRatio(int resizeWidth, int resizeHeight) {
		double ratio = (double)image.getHeight() / (double)resizeHeight;
		int newWidth =  (int) Math.round(((double)resizeWidth * ratio));
		int cropTotal = image.getWidth() - newWidth;
		int cropSide = cropTotal / 2;
		// Create new (blank) image of required (cropped) size
		BufferedImage modifiedImage = new BufferedImage(newWidth, image.getHeight(), BufferedImage.TYPE_INT_ARGB);
		// Paint cropped image at negative coords to cause cropping
		Graphics2D graphics2Dtest = modifiedImage.createGraphics();
		graphics2Dtest.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2Dtest.drawImage(image, (cropSide * -1), 0, image.getWidth(), image.getHeight(), null);
		graphics2Dtest.dispose();
		image = modifiedImage;
	}

	public void CropOrLetterboxToDimensions(int frameWidth, int frameHeight) {
		int offsetHeight = (image.getHeight() - frameHeight) / 2;
		int offsetWidth = (image.getWidth() - frameWidth) / 2;
		// Create new (blank) image of required size
		BufferedImage modifiedImage = new BufferedImage(frameWidth, frameHeight, BufferedImage.TYPE_INT_ARGB);
		// Paint cropped image at negative coords to cause cropping
		Graphics2D graphics2Dtest = modifiedImage.createGraphics();
		graphics2Dtest.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2Dtest.drawImage(image, (offsetWidth * -1), (offsetHeight * -1), image.getWidth(), image.getHeight(), null);
		graphics2Dtest.dispose();
		image = modifiedImage;
	}

	public void invertColors() {
        Color c;
        for (int x = 0; x < image.getWidth(); x++) { //width
            for (int y = 0; y < image.getHeight(); y++) { //height
                int RGBA = image.getRGB(x, y); //gets RGBA data for the specific pixel
                c = new Color(RGBA, true); //get the color data of the specific pixel
                c = new Color(Math.abs(c.getRed() - 255), Math.abs(c.getGreen() - 255), Math.abs(c.getBlue() - 255)); //Swaps values
                //i.e. 255, 255, 255 (white)
                //becomes 0, 0, 0 (black)
                image.setRGB(x, y, c.getRGB()); //set the pixel to the altered colors
            }
        }
    }

	public void rotate90() {
		int width = image.getWidth();
		int height = image.getHeight();
		BufferedImage newImage = new BufferedImage(height, width, image.getType());

		for (int i = 0; i < width; i++)
			for (int j = 0; j < height; j++)
				newImage.setRGB(height - 1 - j, i, image.getRGB(i, j));

		image = newImage;
	}

	public void rotate270() {
		int width = image.getWidth();
		int height = image.getHeight();
		BufferedImage newImage = new BufferedImage(height, width, image.getType());

		for (int i = 0; i < width; i++)
			for (int j = 0; j < height; j++)
				newImage.setRGB(j, width - 1 - i, image.getRGB(i, j));

		image = newImage;
	}

}


text:
'use strict';

module.exports = {
    User       : require('./user.js'),
    UserList   : require('./userList.js'),
    VCard      : require('./vCard.js'),
    VCardParser: require('./vCardParser.js')
};


text:
describe('The app factory', function() {

  var uut;

  beforeEach(function(done) {
    uut = appFactory;
    done();
  });

  it('should create a brand new application', function(done) {
    uut().should.be.an('object');
    done();
  });

  describe('generated application', function() {

    var aut;
    var router = function() {};
    var global = {};

    beforeEach(function(done) {
      aut = uut(global, router);
      done();
    });

    it('should register the main method', function(done) {
      aut.main(done);
      aut.run();
    });

    it('should throw exception if main is not set on run', function(done) {
      aut.run.should.throw(ReferenceError, /Main is not set/);
      done();
    });

    it('should throw exception if main is not a function', function(done) {
      (function() {
        aut.main('not a function');
      }).should.throw(Error, /Invalid function/);
      done();
    });

    it('should register a controller', function(done) {
      aut.controller('testcontroller', done);
      aut.main(function() {
        aut.controller('testcontroller')();
      });
      aut.run();
    });

    it('should register a controller object', function(done) {
      aut.controller('testcontroller', {
        done: done
      });
      aut.main(function() {
        aut.controller('testcontroller').done();
      });
      aut.run();
    });

    it('should except if the controller is neither a function nor an object', function(done) {
      (function() {
        aut.controller('not a controller', 'not a function');
      }).should.throw(Error, /This component is neither a function nor an object/);
      done();
    });

    it('should can return all controllers', function(done) {
      var spyFunction = function() {};
      aut.controller('testcontroller', spyFunction);
      var result = aut.controllers();
      result.testcontroller.should.be.equal(spyFunction);
      done();
    });

    it('should register a model', function(done) {
      aut.model('testmodel', done);
      aut.main(function() {
        aut.model('testmodel')();
      });
      aut.run();
    });

    it('should register a model object', function(done) {
      aut.model('testmodel', {
        done: done
      });
      aut.main(function() {
        aut.model('testmodel').done();
      });
      aut.run();
    });

    it('should except if the model is neither a function nor an object', function(done) {
      (function() {
        aut.model('not a model', 'not a function');
      }).should.throw(Error, /This component is neither a function nor an object/);
      done();
    });

    it('should can return all models', function(done) {
      var spyFunction = function() {};
      aut.model('testmodel', spyFunction);
      var result = aut.models();
      result.testmodel.should.be.equal(spyFunction);
      done();
    });

    it('should initialize the router on run if a template wrapper is defined', function(done) {
      router = function(g, id) {
        g.should.be.equal(global);
        id.should.be.equal(testId);
        done();
      };
      aut = uut(global, router);

      aut.main(function() {});
      var testId = 'test-id';

      aut.run(testId);
    });

  });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  Wildfly Camel Patch
  %%
  Copyright (C) 2013 - 2014 RedHat
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<!--
  This file holds all the module definitions that are defined elsewhere or skipped.
-->
<modules xmlns="http://smartics.de/ns/jboss-modules-descriptor/2">

	<!-- =========================================================== -->
	<!--          modules defined in wildfly-alternatives            -->
	<!-- =========================================================== -->

    <module name="com.google.code.gson" slot="fuse" skip="true">
        <include artifact="com.google.code.gson:gson" />
    </module>

    <module name="com.jcraft.jsch" slot="fuse" skip="true">
        <include artifact="com.jcraft:jsch" />
    </module>

    <module name="io.netty" slot="fuse" skip="true">
        <include artifact="io.netty:netty-all" />
    </module>

    <module name="org.apache.avro" slot="fuse" skip="true">
        <include artifact="org.apache.avro:avro"/>
    </module>

    <module name="org.apache.commons.beanutils" slot="fuse" skip="true">
        <include artifact=":commons-beanutils" />
    </module>

    <module name="org.apache.commons.cli" slot="fuse" skip="true">
        <include artifact=":commons-cli" />
    </module>

    <module name="org.apache.commons.codec" slot="fuse" skip="true">
        <include artifact=":commons-codec" />
    </module>

    <module name="org.apache.commons.collections" slot="fuse" skip="true">
        <include artifact=":commons-collections" />
    </module>

    <module name="org.apache.commons.io" slot="fuse" skip="true">
        <include artifact=":commons-io" />
    </module>

    <module name="org.apache.commons.lang" slot="fuse" skip="true">
        <include artifact=":commons-lang" />
    </module>

    <module name="org.apache.commons.lang3" slot="fuse" skip="true">
        <include artifact=":commons-lang3" />
    </module>

    <module name="org.apache.commons.logging" slot="fuse" skip="true">
        <include artifact=":commons-logging" />
    </module>

    <module name="org.apache.httpcomponents" slot="fuse" skip="true">
        <include artifact="org.apache.httpcomponents:httpasyncclient" />
        <include artifact="org.apache.httpcomponents:httpclient" />
        <include artifact="org.apache.httpcomponents:httpcore" />
        <include artifact="org.apache.httpcomponents:httpcore-nio" />
        <include artifact="org.apache.httpcomponents:httpmime" />
    </module>

    <module name="org.codehaus.jettison" slot="fuse" skip="true">
        <include artifact=":jettison" />
    </module>

    <module name="org.codehaus.woodstox" slot="fuse" skip="true">
        <include artifact="org.codehaus.woodstox:woodstox-core-asl" />
        <include artifact="org.codehaus.woodstox:woodstox-core" />
        <include artifact="org.codehaus.woodstox:stax2-api" />
    </module>

	<!-- =========================================================== -->
	<!--          modules defined in features/modules                -->
	<!-- =========================================================== -->

	<module name="com.fasterxml.woodstox" skip="true">
        <include artifact="com.fasterxml.woodstox:woodstox-core"/>
	</module>

    <module name="com.google.guava" slot="fuse" skip="true">
        <include artifact="com.google.guava:guava" />
    </module>

    <module name="com.rometools.rome" slot="1.0" skip="true">
        <include artifact="rome:rome" />
    </module>

    <module name="io.netty" slot="3.10" skip="true">
        <include artifact="io.netty:netty" />
    </module>

    <module name="net.minidev.smart" skip="true">
        <include artifact="net.minidev:accessors-smart" />
        <include artifact="net.minidev:json-smart-action" />
        <include artifact="net.minidev:json-smart" />
    </module>

    <module name="org.apache.camel.core" skip="true">
        <include artifact="org.apache.camel:camel-api" />
        <include artifact="org.apache.camel:camel-core" />
        <include artifact="org.apache.camel:camel-management-api" />
        <include artifact="org.apache.camel:camel-support" />
        <include artifact="org.apache.camel:camel-util" />
    </module>

    <module name="org.apache.commons.compress" skip="true">
        <include artifact=":commons-compress" />
    </module>

    <module name="org.apache.commons.configuration" skip="true">
        <include artifact=":commons-configuration" />
    </module>

    <module name="org.apache.commons.httpclient" skip="true">
        <include artifact="commons-httpclient:commons-httpclient" />
    </module>

    <module name="org.apache.commons.math3" skip="true">
        <include artifact="org.apache.commons:commons-math3" />
    </module>

    <module name="org.apache.commons.net" skip="true">
        <include artifact="commons.net:commons.net" />
    </module>

    <module name="org.apache.commons.pool" skip="true">
        <include artifact="commons-pool:commons-pool" />
    </module>

    <module name="org.apache.curator" skip="true">
        <include artifact="org.apache.curator:curator-client" />
        <include artifact="org.apache.curator:curator-framework" />
        <include artifact="org.apache.curator:curator-recipes" />
        <include artifact="org.apache.curator:curator-x-discovery" />
    </module>

    <module name="org.apache.directory" skip="true">
        <include artifact="org.apache.directory.api:api-asn1-api" />
        <include artifact="org.apache.directory.api:api-asn1-ber" />
        <include artifact="org.apache.directory.api:api-i18n" />
        <include artifact="org.apache.directory.api:api-ldap-client-api" />
        <include artifact="org.apache.directory.api:api-ldap-codec-core" />
        <include artifact="org.apache.directory.api:api-ldap-codec-standalone" />
        <include artifact="org.apache.directory.api:api-ldap-extras-aci" />
        <include artifact="org.apache.directory.api:api-ldap-extras-codec" />
        <include artifact="org.apache.directory.api:api-ldap-extras-codec-api" />
        <include artifact="org.apache.directory.api:api-ldap-extras-util" />
        <include artifact="org.apache.directory.api:api-ldap-model" />
        <include artifact="org.apache.directory.api:api-ldap-net-mina" />
        <include artifact="org.apache.directory.api:api-ldap-schema-data" />
        <include artifact="org.apache.directory.api:api-util" />
    </module>

    <module name="org.apache.directory.server" skip="true">
        <include artifact="org.apache.directory.server:apacheds-core-api" />
        <include artifact="org.apache.directory.server:apacheds-core-constants" />
        <include artifact="org.apache.directory.server:apacheds-i18n" />
        <include artifact="org.apache.directory.server:apacheds-kerberos-codec" />
    </module>

    <module name="org.apache.tika" skip="true">
        <include artifact="org.apache.tika:tika-core" />
    </module>

    <module name="org.apache.zookeeper" skip="true">
        <include artifact="org.apache.zookeeper:zookeeper" />
    </module>

    <module name="org.eclipse.jetty" skip="true">
        <include artifact="org.eclipse.jetty:jetty-client" />
        <include artifact="org.eclipse.jetty:jetty-http" />
        <include artifact="org.eclipse.jetty:jetty-io" />
        <include artifact="org.eclipse.jetty:jetty-util" />
        <include artifact="org.eclipse.jetty:jetty-util-ajax" />
    </module>

    <module name="org.fusesource.leveldbjni.all" skip="true">
        <include artifact="org.fusesource.leveldbjni:leveldbjni-all" />
    </module>

    <module name="org.osgi.core" skip="true">
        <include artifact=":org.osgi.core" />
        <include artifact="org.osgi:core" />
    </module>

	<!-- =========================================================== -->
	<!--          modules skipped here                               -->
	<!-- =========================================================== -->

    <module name="dnsjava" skip="true">
        <include artifact="dnsjava:dnsjava" />
    </module>

    <module name="org.apache.hadoop.skipped" skip="true">
        <include artifact="org.apache.hadoop:hadoop-mapreduce-client-core"/>
        <include artifact="org.apache.hadoop:hadoop-yarn-api"/>
        <include artifact="org.apache.hadoop:hadoop-yarn-client"/>
        <include artifact="org.apache.hadoop:hadoop-yarn-common"/>
    </module>

</modules>


text:
<?php
namespace StandardExceptions\IOExceptions;
use StandardExceptions\Traits\ThrowIf;

/**
* Use this exception when an IO operation tries to write some content to
* a file but cannot do so due to filesystem permissions.
*
* @package  Standard-Exceptions
* @author   Mathieu Dumoulin aka CrazyCodr <crazyone@crazycoders.net>
* @license  MIT
*/
class FileNotWritableException extends \RuntimeException
{
    use ThrowIf;

    public function __construct($message = 'Cannot write to specified file resource', $code = 0, $previous = NULL)
    {
    	parent::__construct($message, $code, $previous);
    }

}


text:
package com.go2plus.common.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.go2plus.common.X;

public class ZipUtil {
  private final static Logger log = LoggerFactory.getLogger(ZipUtil.class);

  /**
   * 将指定的zip文件 压缩到指定的目录,忽略所有zip内部的子目录, 将所有文件 按照 目录1_目录2_文件.txt 的对应方式平铺在destinationFilePath 所指定的目录下,(其下再无其他子目录). 该类用于将用户上传的不标准的压缩包 按照统一标准来解压.
   * 便于后续处理.
   *
   * @param sourceFilePath
   *          (/Users/gaofeng/Desktop/1.zip)
   * @param destinationFilePath
   *          (/Users/gaofeng/Desktop/)
   * @param charset
   *          "UTF-8" "GBK"
   * @throws Exception
   */
  public static void unzipToSingleFolder(String sourceFilePath, String destinationFilePath, String charset) throws Exception {
    long startTime = System.currentTimeMillis();
    FileOutputStream fos = null;
    InputStream is = null;
    ZipFile zipFile = null;
    File outDirFile = null;
    // 创建输出文件夹对象
    if (destinationFilePath == null) {
      //未指定输出路径,默认用源zip文件名作为输出目录
      outDirFile= new File(sourceFilePath.substring(0, sourceFilePath.length()-4));
    } else {
      outDirFile = new File(destinationFilePath);
    }

    if (!outDirFile.isDirectory())
      outDirFile.mkdirs();
    File sourceFile = new File(sourceFilePath);
    if (!sourceFilePath.endsWith(".zip")) {
      throw new Exception("sourceFile is not a zip");
    }
    if (!sourceFile.exists()) {
      throw new Exception("sourceFile not found!");
    }
    try {
      zipFile = new ZipFile(sourceFilePath, Charset.forName(charset));
      for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
        ZipEntry ze = (ZipEntry) entries.nextElement();
        String fileName = ze.getName().replaceAll("\\\\", "_").replaceAll("/", "_");
        File file = new File(outDirFile, fileName);
        if (ze.isDirectory()) {
          // 是目录,则忽略之
        } else {
          file.createNewFile();
          fos = new FileOutputStream(file);
          is = zipFile.getInputStream(ze);
          X.copyStreamAndClose(is, fos);
        }
      }
    } catch (Exception e) {
      throw e;
    } finally {
      if(null!=zipFile){
        zipFile.close();
      }
    }
    long endTime = System.currentTimeMillis();
    log.debug("@@Zip decompression : {}  -----------------  duration : {} ms", sourceFilePath, endTime - startTime);
  }

  /**
   * 将指定的zip文件 压缩到指定的目录,按照zip中的目录结构原样输出
   *
   * @param sourceFilePath
   *          (/Users/gaofeng/Desktop/1.zip)
   * @param destinationFilePath
   *          (/Users/gaofeng/Desktop/)
   * @param charset
   *          "UTF-8" "GBK"
   * @throws Exception
   */
  public static void unzip(String sourceFilePath, String destinationFilePath, String charset) throws Exception {
    long startTime = System.currentTimeMillis();
    FileOutputStream fos = null;
    InputStream is = null;
    ZipFile zipFile = null;
    // 创建输出文件夹对象
    File outDirFile = new File(destinationFilePath);
    outDirFile.mkdirs();
    File sourceFile = new File(sourceFilePath);
    if (!sourceFilePath.endsWith(".zip")) {
      throw new Exception("sourceFile is not a zip");
    }
    if (!sourceFile.exists()) {
      throw new Exception("sourceFile not found!");
    }
    try {
      zipFile = new ZipFile(sourceFilePath, Charset.forName(charset));
      for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
        ZipEntry ze = (ZipEntry) entries.nextElement();
        File file = new File(outDirFile, ze.getName());
        if (ze.isDirectory()) {// 是目录,则创建之
          file.mkdirs();
        } else {
          File parent = file.getParentFile();
          if (parent != null && !parent.exists()) {
            parent.mkdirs();
          }
          file.createNewFile();
          fos = new FileOutputStream(file);
          is = zipFile.getInputStream(ze);
          X.copyStreamAndClose(is, fos);
        }
      }
    } catch (Exception e) {
      throw e;
    } finally {
      zipFile.close();
    }
    long endTime = System.currentTimeMillis();
    log.debug("@@Zip decompression : {}  -----------------  duration : {} ms", sourceFilePath, endTime - startTime);
  }

  /**
   * 将指定的文件或目录 压缩成指定的zip文件
   *
   * @param sourceFilePath
   *          (/Users/gaofeng/Desktop/X98) 文件或目录都可以
   * @param destinationFilePath
   *          (/Users/gaofeng/Desktop/1/1.zip)
   * @param charset
   *          "UTF-8" "GBK" !!!由于大多数用户用的windows电脑 zip在windows 下会使用GBK编码 因此这里最好设置成 GBK编码 否则 windows用户用系统自带的zip工具解压将丢失数据.
   *          但是设成GBK对mac用户不友好,mac自带的解压遵从UTF-8 linux也是 , 但是可以借助第三方压缩工具来解压. 考虑windows:mac 比例非常高 所以推荐用GBK. 另外,如果待压缩的文件的文件名只有 ASCII字符
   *          那就无论如何都不会有问题了.. 因此建议对待压缩的文件进行重命名!!
   * @throws Exception
   */
  public static void zip(String sourceFilePath, String destinationFilePath, String charset) {
    long startTime = System.currentTimeMillis();
    File sourceFile = new File(sourceFilePath);
    ZipOutputStream out = null;
    try {
      out = new ZipOutputStream(new FileOutputStream(destinationFilePath), Charset.forName(charset));// 默认编码方式是UTF-8
      compress(sourceFile, sourceFile.getName(), out);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      long endTime = System.currentTimeMillis();
      log.debug("@@Zip compression : {}  -----------------  duration : {} ms", destinationFilePath, endTime - startTime);
    }
  }

  /**
   * 将指定的文件或目录 压缩成指定的zip文件,根据指定的map进行对文件进行重命名.
   *
   * @param sourceFilePath
   *          (/Users/gaofeng/Desktop/X98) 文件或目录都可以
   * @param destinationFilePath
   *          (/Users/gaofeng/Desktop/1/1.zip)
   * @param charset
   *          "UTF-8" "GBK" !!!由于大多数用户用的windows电脑 zip在windows 下会使用GBK编码 因此这里最好设置成 GBK编码 否则 windows用户用系统自带的zip工具解压将丢失数据.
   *          但是设成GBK对mac用户不友好,mac自带的解压遵从UTF-8 linux也是 , 但是可以借助第三方压缩工具来解压. 考虑windows:mac 比例非常高 所以推荐用GBK. 另外,如果待压缩的文件的文件名只有 ASCII字符
   *          那就无论如何都不会有问题了.. 因此建议对待压缩的文件进行重命名!!
   *
   * @param renameMap
   *          <String,String>
   * @throws Exception
   */
  public static void zipAndRename(String sourceFilePath, String destinationFilePath, String charset) {
    long startTime = System.currentTimeMillis();
    File sourceFile = new File(sourceFilePath);
    ZipOutputStream out = null;
    try {
      out = new ZipOutputStream(new FileOutputStream(destinationFilePath), Charset.forName(charset));// 默认编码方式是UTF-8
      compress(sourceFile, sourceFile.getName(), out);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      long endTime = System.currentTimeMillis();
      log.debug("@@Zip compression : {}  -----------------  duration : {} ms", destinationFilePath, endTime - startTime);
    }
  }

  /**
   * 递归将源目录下的文件全部写入 zip文件中.
   *
   * @param sourceFile
   *          源文件File
   * @param sourceFileName
   *          源文件 文件名
   * @param out
   * @throws Exception
   */
  private static void compress(File sourceFile, String sourceFileName, ZipOutputStream out) throws Exception { // 方法重载
    if (sourceFile.isDirectory()) {
      // 源文件是一个目录
      // 获取该目录下所有文件
      File[] fl = sourceFile.listFiles();
      if (fl.length == 0) {
        // 目录是空目录, 只创建zip中空目录
        out.putNextEntry(new ZipEntry(sourceFileName + "/")); // 创建zip压缩进入点base
      }
      for (int i = 0; i < fl.length; i++) {
        // 遍历目录下所有文件/目录 进行递归操作
        compress(fl[i], sourceFileName + "/" + fl[i].getName(), out); // 递归遍历子文件夹
      }
    } else {
      // 源文件是一个文件
      out.putNextEntry(new ZipEntry(sourceFileName)); // 创建zip压缩进入点base
      FileInputStream fis = new FileInputStream(sourceFile);
      // 将源文件内容写入zip文件
      X.copyStream(fis, out);
      // 关闭源文件流
      X.close(fis);
    }
  }
}


text:
package Mod.Gui;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;

import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;

import Mod.GuiObjects.GuiColorButton;

import cpw.mods.fml.common.FMLCommonHandler;

public class GuiPlayerFinder extends GuiScreen{

	private final ResourceLocation Texture = new ResourceLocation("miscitems" , "textures/gui/GuiPlayerFinder.png");

    protected static int xSize = 248;
    protected static int ySize = 169;

    public static final int xSizeOfTexture = xSize;
    public static final int ySizeOfTexture = ySize;

    GuiTextField textField;
    GuiButton teleport;

    EntityPlayer player;
    String Mode;

    int Page = 1;
    int Pages = 1;

    protected int guiLeft;
    protected int guiTop;

    public ArrayList<EntityPlayer> players = new ArrayList<EntityPlayer>();

    @Override
    public void updateScreen()
    {

    	players.clear();

    	 for(int i = 0; i < mc.theWorld.playerEntities.size(); i++)
         {
                 EntityPlayer player = (EntityPlayer)mc.theWorld.playerEntities.get(i);
                 if(player.isEntityAlive() && !players.contains(player.username))
                 {
                         players.add(player);
                 }
         }

         buttonList.clear();
    	 Pages = players.size() / 5;

    	 if(Pages <= 0)
    		 Pages = 1;

    	 if(players.size() > Pages * 5){
    		 Pages++;
    	 }

    	 buttonList.add(new GuiButton(players.size() + 1, guiLeft + 160, guiTop + 114, 80, 20, "Prev Page"));
    	 buttonList.add(new GuiButton(players.size() + 2, guiLeft + 160, guiTop + 144, 80, 20, "Next Page"));

         for(int i = 0; i < players.size(); i++)
         {

        	 if(i < Page * 5 && i >= (Page - 1) * 5){

                 buttonList.add(new GuiButton(i, guiLeft + 160, (guiTop - ((Page - 1) * 110)) + 4  + 22 * (int)Math.floor((double)i / 1D), 80, 20, players.get(i).getCommandSenderName()));

        	 }
         }

	        teleport = new GuiButton(players.size() + 5, guiLeft + 60, guiTop + 5, 50, 20, StatCollector.translateToLocal("gui.string.teleport"));

	        buttonList.add(new GuiButton(players.size() + 4, guiLeft + 6, guiTop + 5, 50, 20, StatCollector.translateToLocal("gui.string.clear")));
	        buttonList.add(teleport);

	        if(player == null || !Minecraft.getMinecraft().thePlayer.capabilities.isCreativeMode)
	        teleport.enabled = false;
    }

	 @Override
	    public void drawScreen(int x, int y, float f) {
	        drawDefaultBackground();

	        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
	        Minecraft.getMinecraft().renderEngine.bindTexture(Texture);

	        int posX = (this.width - xSizeOfTexture) / 2;
	        int posY = (this.height - ySizeOfTexture) / 2;

	        drawTexturedModalRect(posX, posY, 0, 0, xSizeOfTexture, ySizeOfTexture);

	    	 this.drawCenteredString(fontRenderer, Page + "/" + Pages, guiLeft + 200, guiTop + 135, 0x444444);

	        this.drawRect(posX + 5, posY + 97, posX + 130, posY + 30, new Color(100,100,100).getRGB());

	        if(player != null && Mode == "Valid"){
		    fontRenderer.drawString(player.username + "`s Coords: ", posX + 7, posY + 32, 10);
	        fontRenderer.drawString("X Coord: " + (int)player.posX, posX + 7, posY + 40, 10);
	        fontRenderer.drawString("Y Coord: " + (int)player.posY, posX + 7, posY + 48, 10);
	        fontRenderer.drawString("Z Coord: " + (int)player.posZ, posX + 7, posY + 56, 10);

	        if(Minecraft.getMinecraft().thePlayer.capabilities.isCreativeMode){
	        	teleport.enabled = true;
	        }else{
	        	teleport.enabled = false;
	        }

	        }

	        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
	        GL11.glDisable(GL11.GL_LIGHTING);

	        super.drawScreen(x, y, f);
	    }

	    @Override
	    public boolean doesGuiPauseGame() {
	        return false;
	    }

	    @Override
	    public void initGui() {
			super.initGui();
			buttonList.clear();

	        this.guiLeft = (this.width - this.xSize) / 2;
	        this.guiTop = (this.height - this.ySize) / 2;
	    }

	    @Override
	    protected void actionPerformed(GuiButton button) {

	    	if(button.id == players.size() + 1){

	    		if(Page - 1 > 0)
	    			Page--;

	    	}else if (button.id == players.size() + 2){

	    		if(Page + 1 <= Pages)
	    		Page++;

	    	}else if (button.id == players.size() + 4){
	        	teleport.enabled = false;
	        	Mode = "Empty";
	        	player = null;
	    	}else if (button.id == players.size() + 5){

	        	if(this.player != null && Mode == "Valid"){

	        		Minecraft.getMinecraft().thePlayer.setLocationAndAngles((int)this.player.posX, (int)this.player.posY, (int)this.player.posZ, Minecraft.getMinecraft().thePlayer.rotationYaw, Minecraft.getMinecraft().thePlayer.rotationPitch);
	        		Minecraft.getMinecraft().thePlayer.closeScreen();
	        	}

	    	}else{

	    		if(this.players.get(button.id) != null){

	    		       if(players.get(button.id) != null){

	    		    	   Mode = "Valid";
	    		    	   player = players.get(button.id);
	    		       }
	    		}
	    	}

	        }
}


text:
using System.Windows;

namespace Nuance.Radiology.DNSProfileChecker.Views
{
	/// <summary>
	/// Interaction logic for ShellView.xaml
	/// </summary>
	public partial class ShellView : Window
	{
		public ShellView()
		{
			InitializeComponent();
		}
	}
}


text:
package com.krishagni.catissueplus.core.biospecimen.print;

import com.krishagni.catissueplus.core.biospecimen.domain.Visit;
import com.krishagni.catissueplus.core.common.domain.AbstractLabelTmplToken;
import com.krishagni.catissueplus.core.common.domain.LabelTmplToken;

public class VisitCpShortTitlePrintToken extends AbstractLabelTmplToken implements LabelTmplToken {
	@Override
	public String getName() {
		return "visit_cp_title";
	}

	@Override
	public String getReplacement(Object object) {
		return ((Visit)object).getCollectionProtocol().getShortTitle();
	}
}


text:
package com.nashlincoln.blink.content;

import android.os.Handler;
import android.util.Log;

import com.nashlincoln.blink.app.BlinkApp;
import com.nashlincoln.blink.event.Event;
import com.nashlincoln.blink.model.Attribute;
import com.nashlincoln.blink.model.AttributeType;
import com.nashlincoln.blink.model.AttributeTypeDao;
import com.nashlincoln.blink.model.DaoSession;
import com.nashlincoln.blink.model.Device;
import com.nashlincoln.blink.model.DeviceDao;
import com.nashlincoln.blink.model.DeviceType;
import com.nashlincoln.blink.model.DeviceTypeDao;
import com.nashlincoln.blink.model.Group;
import com.nashlincoln.blink.model.GroupDao;
import com.nashlincoln.blink.model.GroupDevice;
import com.nashlincoln.blink.network.BlinkApi;
import com.nashlincoln.blink.nfc.NfcCommand;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by nash on 10/18/14.
 */
public class Syncro {
    private static final String TAG = "Syncro";
    public static final String CONNECTION = "Connection";
    private static Syncro sInstance;
    private final DaoSession mDaoSession;
    private boolean mIsConnected = false;
    private Handler mHandler;

    public static Syncro getInstance() {
        if (sInstance == null) {
            sInstance = new Syncro();
        }
        return sInstance;
    }

    private Syncro() {
        mDaoSession = BlinkApp.getDaoSession();
        mHandler = new Handler(BlinkApp.getApp().getMainLooper());
    }

    public void syncDevices() {
        if (!mIsConnected) {
            return;
        }

        final List<Command> commands = new ArrayList<>();

        addDeviceCommands(commands);
        addGroupCommands(commands);
        addGroupDeviceCommands(commands);

        if (commands.size() > 0) {
            BlinkApi.getClient().sendCommands(commands, new Callback<Response>() {
                @Override
                public void success(Response response, Response response2) {
                    final boolean[] needsRefresh = {false};
                    BlinkApp.getDaoSession().runInTx(new Runnable() {
                        @Override
                        public void run() {
                            for (Command command : commands) {
                                needsRefresh[0] |= command.action.equals(Command.ADD);
                                needsRefresh[0] |= command.action.equals(Command.UPDATE_GROUP);

                                if (command.device != null) {
                                    command.device.setNominal();
                                }

                                if (command.group != null) {
                                    command.group.setNominal();
                                }

                                if (command.groupDevice != null) {
                                    command.groupDevice.setNominal();
                                }
                            }
                        }
                    });

                    Event.broadcast(Device.KEY);
                    Event.broadcast(Group.KEY);

//                    if (needsRefresh[0]) {
//                        // delay this so that commands have a chance to complete
//                        mHandler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                fetchDevices();
//                            }
//                        }, 500);
//                    }
                }

                @Override
                public void failure(RetrofitError error) {

                }
            });
        }
    }

    private void addGroupDeviceCommands(List<Command> commands) {
        for (GroupDevice groupDevice : mDaoSession.getGroupDeviceDao().loadAll()) {
            Command command = null;
            if (groupDevice.getState() == null) {
                groupDevice.setState(BlinkApp.STATE_NOMINAL);
            }
            switch (groupDevice.getState()) {
                case BlinkApp.STATE_ADDED:
                    command = Command.add(groupDevice);
                    break;

                case BlinkApp.STATE_REMOVED:
                    command = Command.remove(groupDevice);
                    break;
            }
            if (command != null) {
                commands.add(command);
            }
        }
    }

    private void addGroupCommands(List<Command> commands) {
        for (Group group : mDaoSession.getGroupDao().loadAll()) {
            Command command = null;
            if (group.getState() == null) {
                group.setState(BlinkApp.STATE_NOMINAL);
            }
            switch (group.getState()) {
                case BlinkApp.STATE_ADDED:
                    command = Command.add(group);
                    break;

                case BlinkApp.STATE_REMOVED:
                    command = Command.remove(group);
                    break;

                case BlinkApp.STATE_NAME_SET:
                    command = Command.setName(group);
                    break;

                case BlinkApp.STATE_UPDATED:
                    command = Command.update(group);
                    break;

                case BlinkApp.STATE_NOMINAL:
                    break;
            }
            if (command != null) {
                commands.add(command);
            }
        }
    }

    private void addDeviceCommands(List<Command> commands) {
        for (Device device : mDaoSession.getDeviceDao().loadAll()) {
            Command command = null;
            if (device.getState() == null) {
                device.setState(BlinkApp.STATE_NOMINAL);
            }
            switch (device.getState()) {
                case BlinkApp.STATE_ADDED:
                    command = Command.add(device);
                    break;

                case BlinkApp.STATE_REMOVED:
                    command = Command.remove(device);
                    break;

                case BlinkApp.STATE_UPDATED:
                    command = Command.update(device);
                    break;

                case BlinkApp.STATE_NAME_SET:
                    command = Command.setName(device);
                    break;

                case BlinkApp.STATE_NOMINAL:
                    break;
            }
            if (command != null) {
                commands.add(command);
            }
        }
    }

    public void fetchDeviceTypes() {
        if (!mIsConnected) {
            return;
        }
        BlinkApi.getClient().getDeviceTypes(new Callback<List<DeviceType>>() {
            @Override
            public void success(List<DeviceType> deviceTypes, Response response) {
                DeviceTypeDao deviceTypeDao = mDaoSession.getDeviceTypeDao();
                deviceTypeDao.insertOrReplaceInTx(deviceTypes);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    public void fetchAttributeTypes() {
        if (!mIsConnected) {
            return;
        }
        BlinkApi.getClient().getAttributeTypes(new Callback<List<AttributeType>>() {
            @Override
            public void success(List<AttributeType> attributeTypes, Response response) {
                AttributeTypeDao attributeTypeDao = mDaoSession.getAttributeTypeDao();
                attributeTypeDao.insertOrReplaceInTx(attributeTypes);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    public void fetchDevicesAndGroups() {
        fetchDevices();
        final String key = Device.KEY + "/fetch";
        Event.observe(key, new Observer() {
            @Override
            public void update(Observable observable, Object data) {
                Event.ignore(key, this);
                fetchGroups();
            }
        });
    }

    public void fetchDevices() {
        if (!mIsConnected) {
            return;
        }
        BlinkApi.getClient().getDevices(new Callback<List<Device>>() {
            @Override
            public void success(final List<Device> devices, Response response) {
                final DeviceDao deviceDao = mDaoSession.getDeviceDao();
                mDaoSession.runInTx(new Runnable() {
                    @Override
                    public void run() {
                        List<Device> currentDevices = deviceDao.loadAll();
                        Set<Long> newIds = new HashSet<>();
                        for (Device device : devices) {
                            newIds.add(device.getId());
                            device.setAttributableType(Device.ATTRIBUTABLE_TYPE);
                            device.flushAttributes();
                            device.resetAttributes();
                            deviceDao.insertOrReplace(device);
                        }

                        for (Device device : currentDevices) {
                            if (!newIds.contains(device.getId())) {
                                device.deleteWithReferences();
                            }
                        }

                    }
                });
                mDaoSession.clear();
                Event.broadcast(Device.KEY);
                Event.broadcast(Device.KEY + "/fetch");
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    public void fetchGroups() {
        if (!mIsConnected) {
            return;
        }
        BlinkApi.getClient().getGroups(new Callback<List<Group>>() {
            @Override
            public void success(final List<Group> groups, Response response) {
                final GroupDao groupDao = mDaoSession.getGroupDao();
                mDaoSession.runInTx(new Runnable() {
                    @Override
                    public void run() {
                        List<Group> currentGroups = groupDao.loadAll();
                        Set<Long> newIds = new HashSet<>();
                        for (Group group : groups) {
                            newIds.add(group.getId());
                            group.setAttributableType(Group.ATTRIBUTABLE_TYPE);
                            group.flushAttributes();
                            group.resetAttributes();
                            group.flushGroupDevices();
                            group.resetGroupDeviceList();
                            groupDao.insertOrReplace(group);
                        }

                        for (Group group : currentGroups) {
                            if (!newIds.contains(group.getId())) {
                                group.deleteWithReferences();
                            }
                        }

                    }
                });
                mDaoSession.clear();
                Event.broadcast(Group.KEY);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    public synchronized void onConnected(boolean isConnected) {
        Log.d(TAG, "onConnected: " + isConnected);
        boolean previous = mIsConnected;
        mIsConnected = isConnected;

        if (mIsConnected && !previous) {
            Event.observe(Device.KEY, new Observer() {
                @Override
                public void update(Observable observable, Object data) {
                    Event.ignore(Device.KEY, this);
                    syncDevices();
                }
            });
            fetchDevicesAndGroups();
        }

        Event.broadcast(CONNECTION, mIsConnected);
    }

    public void applyNfcCommands(final List<NfcCommand> commands) {
        final DeviceDao deviceDao = mDaoSession.getDeviceDao();
        final GroupDao groupDao = mDaoSession.getGroupDao();
        mDaoSession.runInTx(new Runnable() {
            @Override
            public void run() {
                for (NfcCommand command : commands) {
                    if (command.d != null) {
                        Device device = deviceDao.load(command.d);
                        if (device != null) {
                            for (NfcCommand.Update update : command.u) {
                                if (update.i == 1) {
                                    device.setOn(update.v.equals(Attribute.ON));
                                } else if (update.i == 2) {
                                    device.setLevel(Integer.parseInt(update.v));
                                }
                            }
                        }
                    }

                    if (command.g != null) {
                        Group group = groupDao.load(command.g);
                        if (group != null) {
                            for (NfcCommand.Update update : command.u) {
                                if (update.i == 1) {
                                    group.setOn(update.v.equals(Attribute.ON));
                                } else if (update.i == 2) {
                                    group.setLevel(Integer.parseInt(update.v));
                                }
                            }
                        }
                    }
                }
            }
        });
        syncDevices();
    }
}


text:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <com.brightcove.player.view.BrightcoveVideoView
        android:id="@+id/brightcove_video_view"
        android:layout_width="match_parent"
        android:layout_height="280dp"
        android:layout_gravity="center_horizontal|top"/>

    <FrameLayout
        android:id="@+id/ad_frame"
        android:background="#0DBD5F"
        android:layout_width="300px"
        android:layout_height="250px"
        android:layout_gravity="center_horizontal|bottom" />

</merge>