text:
namespace Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners
{
    /// <summary>
    /// Header names for requests / responses.
    /// </summary>
    internal static class RequestResponseHeaders
    {
        /// <summary>
        /// Request-Context header.
        /// </summary>
        public const string RequestContextHeader = "Request-Context";

        /// <summary>
        /// Source key in the request context header that is added by an application while making http requests and retrieved by the other application when processing incoming requests.
        /// </summary>
        public const string RequestContextSourceKey = "appId";

        /// <summary>
        /// Target key in the request context header that is added to the response and retrieved by the calling application when processing incoming responses.
        /// </summary>
        public const string RequestContextTargetKey = "appId"; // Although the name of Source and Target key is the same - appId. Conceptually they are different and hence, we intentionally have two constants here. Makes for better reading of the code.

        /// <summary>
        /// Request-Id header.
        /// </summary>
        public const string RequestIdHeader = "Request-Id";

        /// <summary>
        /// Correlation-Context header.
        /// </summary>
        public const string CorrelationContextHeader = "Correlation-Context";

        /// <summary>
        /// W3C traceparent header name.
        /// </summary>
        public const string TraceParentHeader = "traceparent";

        /// <summary>
        /// W3C tracestate header name.
        /// </summary>
        public const string TraceStateHeader = "tracestate";
    }
}

redpajama_set_name: RedPajamaGithub


text: Framework for HTML and JQuery


text:
package com.sam.web.dao;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;

/**
 * Created by Sam on 2015/6/13.
 */
public class BasicDao<E, I extends Serializable> implements IBasicDao<E, I> {

    public static final Logger logger = Logger.getLogger(BasicDao.class);

    protected SessionFactory sessionFactory;

    protected Class<E> dataObjectClass;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Class<E> getDataObjectClass() {
        return dataObjectClass;
    }

    public void setDataObjectClass(Class<E> dataObjectClass) {
        this.dataObjectClass = dataObjectClass;
    }

    public Session getSession() throws Exception {
        return this.sessionFactory.getCurrentSession();
    }

    @Transactional
    public void save(E e) throws Exception {
        try{
            getSession().save(e);
        } catch (Exception e1) {
            logger.error(e1.getMessage(), e1);
            throw new Exception(e1.getMessage());
        }
    }

    @Transactional
    public void update(E e) throws Exception {
        try{
            getSession().update(e);
        } catch (Exception e1) {
            logger.error(e1.getMessage(), e1);
            throw new Exception(e1.getMessage());
        }
    }

    @Transactional
    public void delete(E e) throws Exception {
        try{
            getSession().delete(e);
        } catch (Exception e1) {
            logger.error(e1.getMessage(), e1);
            throw new Exception(e1.getMessage());
        }
    }

    @Transactional
    public E findById(I i) throws Exception {
        try {
            Criteria criteria = getSession().createCriteria(dataObjectClass);
            criteria.add(Restrictions.eq("id", i));
            List<E> dataList = criteria.list();
            if (dataList != null && dataList.size() > 0) {
                return dataList.get(0);
            } else {
                return null;
            }
        }catch (Exception e1) {
            logger.error(e1.getMessage(), e1);
            throw new Exception(e1.getMessage());
        }
    }
}


text:
typedef
Nucleus_NoError() Nucleus_NonNull(2) Nucleus_Status
Nucleus_getFileContentsExtendedCallbackFunction
    (
        Nucleus_InputOutputParameter(void *object),
        Nucleus_InputParameter(const char *bytes),
        Nucleus_InputParameter(Nucleus_Size numberOfBytes)
    );

/// @ingroup filesystem
/// @brief Get the contents of a file.
/// @param pathname a pointer to the pathname of the file
/// @param bytes a pointer to a @a (char *) variable
/// @param numberOfBytes a pointer to a @a (Nucleus_Size) variable
/// @defaultReturn
/// @success @a *numberOfBytes was assigned the size of the file which may be @a 0.
///          @a *bytes was assigned a pointer to an array of at least @a *numberOfBytes Bytes such that the first @a *numberOfBytes
///          represent the content of the file. That array must be deallocated using free if no longer required.
/// @failure Neither @a numberOfBytes nor @a bytes were dereferenced.
/// @remark The memory returned is allocated using malloc. If it is no longer referenced then it must be deallocated using free.
Nucleus_NonNull(1, 2, 3) Nucleus_Status
Nucleus_getFileContents
    (
        Nucleus_InputParameter(const char *pathname),
        Nucleus_OutputParameter(char **bytes),
        Nucleus_OutputParameter(Nucleus_Size *numberOfBytes)
    );

/// @ingroup filesystem
/// @brief Get the contents of a file.
/// @param pathname a pointer to the pathname of the file
/// @param object the object to invoke the callback pointed to by @a (callback) on
/// @param callback a pointer to a @a (Nucleus_getFileContentsCallbackFunction) function
/// @defaultReturn
Nucleus_NonNull(1, 3) Nucleus_Status
Nucleus_getFileContentsExtended
    (
        Nucleus_InputParameter(const char *pathname),
        Nucleus_InputOutputParameter(void *object),
        Nucleus_InputOutputParameter(Nucleus_getFileContentsExtendedCallbackFunction *callback)
    );


text:
package snti.example.com.materialflickr.util;

import android.content.Context;
import android.net.ConnectivityManager;

/**
 * Created by snti on 10/24/16.
 */

public class NetworkUtil {
    public static boolean isOnline(Context context)
    {
        try
        {
            ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo().isConnectedOrConnecting();
        }
        catch (Exception e)
        {
            return false;
        }
    }
}


text:
#include "platform.hpp"

//  On AIX, poll.h has to be included before zmq.h to get consistent
//  definition of pollfd structure (AIX uses 'reqevents' and 'retnevents'
//  instead of 'events' and 'revents' and defines macros to map from POSIX-y
//  names to AIX-specific names).
#if defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
    defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
    defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
    defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
    defined ZMQ_HAVE_NETBSD
#include <poll.h>
#endif

#include "../include/zmq.h"
#include "../include/zmq_utils.h"

#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <new>

#include "device.hpp"
#include "socket_base.hpp"
#include "msg_content.hpp"
#include "stdint.hpp"
#include "config.hpp"
#include "likely.hpp"
#include "clock.hpp"
#include "ctx.hpp"
#include "err.hpp"
#include "fd.hpp"

#if !defined ZMQ_HAVE_WINDOWS
#include <unistd.h>
#endif

#if defined ZMQ_HAVE_OPENPGM
#define __PGM_WININT_H__
#include <pgm/pgm.h>

//  TODO: OpenPGM redefines bool -- remove this once OpenPGM is fixed.
#if defined bool
#undef bool
#endif

#endif

void zmq_version (int *major_, int *minor_, int *patch_)
{
    *major_ = ZMQ_VERSION_MAJOR;
    *minor_ = ZMQ_VERSION_MINOR;
    *patch_ = ZMQ_VERSION_PATCH;
}

const char *zmq_strerror (int errnum_)
{
    return zmq::errno_to_string (errnum_);
}

int zmq_msg_init (zmq_msg_t *msg_)
{
    msg_->content = (zmq::msg_content_t*) ZMQ_VSM;
    msg_->flags = (unsigned char) ~ZMQ_MSG_MASK;
    msg_->vsm_size = 0;
    return 0;
}

int zmq_msg_init_size (zmq_msg_t *msg_, size_t size_)
{
    if (size_ <= ZMQ_MAX_VSM_SIZE) {
        msg_->content = (zmq::msg_content_t*) ZMQ_VSM;
        msg_->flags = (unsigned char) ~ZMQ_MSG_MASK;
        msg_->vsm_size = (uint8_t) size_;
    }
    else {
        msg_->content =
            (zmq::msg_content_t*) malloc (sizeof (zmq::msg_content_t) + size_);
        if (!msg_->content) {
            errno = ENOMEM;
            return -1;
        }
        msg_->flags = (unsigned char) ~ZMQ_MSG_MASK;

        zmq::msg_content_t *content = (zmq::msg_content_t*) msg_->content;
        content->data = (void*) (content + 1);
        content->size = size_;
        content->ffn = NULL;
        content->hint = NULL;
        new (&content->refcnt) zmq::atomic_counter_t ();
    }
    return 0;
}

int zmq_msg_init_data (zmq_msg_t *msg_, void *data_, size_t size_,
    zmq_free_fn *ffn_, void *hint_)
{
    msg_->content = (zmq::msg_content_t*) malloc (sizeof (zmq::msg_content_t));
    alloc_assert (msg_->content);
    msg_->flags = (unsigned char) ~ZMQ_MSG_MASK;
    zmq::msg_content_t *content = (zmq::msg_content_t*) msg_->content;
    content->data = data_;
    content->size = size_;
    content->ffn = ffn_;
    content->hint = hint_;
    new (&content->refcnt) zmq::atomic_counter_t ();
    return 0;
}

int zmq_msg_close (zmq_msg_t *msg_)
{
    //  Check the validity tag.
    if (unlikely (msg_->flags | ZMQ_MSG_MASK) != 0xff) {
        errno = EFAULT;
        return -1;
    }

    //  For VSMs and delimiters there are no resources to free.
    if (msg_->content != (zmq::msg_content_t*) ZMQ_DELIMITER &&
          msg_->content != (zmq::msg_content_t*) ZMQ_VSM) {

        //  If the content is not shared, or if it is shared and the reference.
        //  count has dropped to zero, deallocate it.
        zmq::msg_content_t *content = (zmq::msg_content_t*) msg_->content;
        if (!(msg_->flags & ZMQ_MSG_SHARED) || !content->refcnt.sub (1)) {

            //  We used "placement new" operator to initialize the reference.
            //  counter so we call its destructor now.
            content->refcnt.~atomic_counter_t ();

            if (content->ffn)
                content->ffn (content->data, content->hint);
            free (content);
        }
    }

    //  Remove the validity tag from the message.
    msg_->flags = 0;

    return 0;
}

int zmq_msg_move (zmq_msg_t *dest_, zmq_msg_t *src_)
{
#if 0
    //  Check the validity tags.
    if (unlikely ((dest_->flags | ZMQ_MSG_MASK) != 0xff ||
          (src_->flags | ZMQ_MSG_MASK) != 0xff)) {
        errno = EFAULT;
        return -1;
    }
#endif
    zmq_msg_close (dest_);
    *dest_ = *src_;
    zmq_msg_init (src_);
    return 0;
}

int zmq_msg_copy (zmq_msg_t *dest_, zmq_msg_t *src_)
{
    //  Check the validity tags.
    if (unlikely ((dest_->flags | ZMQ_MSG_MASK) != 0xff ||
          (src_->flags | ZMQ_MSG_MASK) != 0xff)) {
        errno = EFAULT;
        return -1;
    }

    zmq_msg_close (dest_);

    //  VSMs and delimiters require no special handling.
    if (src_->content != (zmq::msg_content_t*) ZMQ_DELIMITER &&
          src_->content != (zmq::msg_content_t*) ZMQ_VSM) {

        //  One reference is added to shared messages. Non-shared messages
        //  are turned into shared messages and reference count is set to 2.
        zmq::msg_content_t *content = (zmq::msg_content_t*) src_->content;
        if (src_->flags & ZMQ_MSG_SHARED)
            content->refcnt.add (1);
        else {
            src_->flags |= ZMQ_MSG_SHARED;
            content->refcnt.set (2);
        }
    }

    *dest_ = *src_;
    return 0;
}

void *zmq_msg_data (zmq_msg_t *msg_)
{
    zmq_assert ((msg_->flags | ZMQ_MSG_MASK) == 0xff);

    if (msg_->content == (zmq::msg_content_t*) ZMQ_VSM)
        return msg_->vsm_data;
    if (msg_->content == (zmq::msg_content_t*) ZMQ_DELIMITER)
        return NULL;

    return ((zmq::msg_content_t*) msg_->content)->data;
}

size_t zmq_msg_size (zmq_msg_t *msg_)
{
    zmq_assert ((msg_->flags | ZMQ_MSG_MASK) == 0xff);

    if (msg_->content == (zmq::msg_content_t*) ZMQ_VSM)
        return msg_->vsm_size;
    if (msg_->content == (zmq::msg_content_t*) ZMQ_DELIMITER)
        return 0;

    return ((zmq::msg_content_t*) msg_->content)->size;
}

void *zmq_init (int io_threads_)
{
    if (io_threads_ < 0) {
        errno = EINVAL;
        return NULL;
    }

#if defined ZMQ_HAVE_OPENPGM

    //  Init PGM transport. Ensure threading and timer are enabled. Find PGM
    //  protocol ID. Note that if you want to use gettimeofday and sleep for
    //  openPGM timing, set environment variables PGM_TIMER to "GTOD" and
    //  PGM_SLEEP to "USLEEP".
    pgm_error_t *pgm_error = NULL;
    const bool ok = pgm_init (&pgm_error);
    if (ok != TRUE) {

        //  Invalid parameters don't set pgm_error_t
        zmq_assert (pgm_error != NULL);
        if (pgm_error->domain == PGM_ERROR_DOMAIN_TIME && (
              pgm_error->code == PGM_ERROR_FAILED)) {

            //  Failed to access RTC or HPET device.
            pgm_error_free (pgm_error);
            errno = EINVAL;
            return NULL;
        }

        //  PGM_ERROR_DOMAIN_ENGINE: WSAStartup errors or missing WSARecvMsg.
        zmq_assert (false);
    }
#endif

#ifdef ZMQ_HAVE_WINDOWS
    //  Intialise Windows sockets. Note that WSAStartup can be called multiple
    //  times given that WSACleanup will be called for each WSAStartup.
   //  We do this before the ctx constructor since its embedded mailbox_t
   //  object needs Winsock to be up and running.
    WORD version_requested = MAKEWORD (2, 2);
    WSADATA wsa_data;
    int rc = WSAStartup (version_requested, &wsa_data);
    zmq_assert (rc == 0);
    zmq_assert (LOBYTE (wsa_data.wVersion) == 2 &&
        HIBYTE (wsa_data.wVersion) == 2);
#endif

    //  Create 0MQ context.
    zmq::ctx_t *ctx = new (std::nothrow) zmq::ctx_t ((uint32_t) io_threads_);
    alloc_assert (ctx);
    return (void*) ctx;
}

int zmq_term (void *ctx_)
{
    if (!ctx_ || !((zmq::ctx_t*) ctx_)->check_tag ()) {
        errno = EFAULT;
        return -1;
    }

    int rc = ((zmq::ctx_t*) ctx_)->terminate ();
    int en = errno;

#ifdef ZMQ_HAVE_WINDOWS
    //  On Windows, uninitialise socket layer.
    rc = WSACleanup ();
    wsa_assert (rc != SOCKET_ERROR);
#endif

#if defined ZMQ_HAVE_OPENPGM
    //  Shut down the OpenPGM library.
    if (pgm_shutdown () != TRUE)
        zmq_assert (false);
#endif

    errno = en;
    return rc;
}

void *zmq_socket (void *ctx_, int type_)
{
    if (!ctx_ || !((zmq::ctx_t*) ctx_)->check_tag ()) {
        errno = EFAULT;
        return NULL;
    }
    return (void*) (((zmq::ctx_t*) ctx_)->create_socket (type_));
}

int zmq_close (void *s_)
{
    if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
        errno = ENOTSOCK;
        return -1;
    }
    ((zmq::socket_base_t*) s_)->close ();
    return 0;
}

int zmq_setsockopt (void *s_, int option_, const void *optval_,
    size_t optvallen_)
{
    if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
        errno = ENOTSOCK;
        return -1;
    }
    return (((zmq::socket_base_t*) s_)->setsockopt (option_, optval_,
        optvallen_));
}

int zmq_getsockopt (void *s_, int option_, void *optval_, size_t *optvallen_)
{
    if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
        errno = ENOTSOCK;
        return -1;
    }
    return (((zmq::socket_base_t*) s_)->getsockopt (option_, optval_,
        optvallen_));
}

int zmq_bind (void *s_, const char *addr_)
{
    if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
        errno = ENOTSOCK;
        return -1;
    }
    return (((zmq::socket_base_t*) s_)->bind (addr_));
}

int zmq_connect (void *s_, const char *addr_)
{
    if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
        errno = ENOTSOCK;
        return -1;
    }
    return (((zmq::socket_base_t*) s_)->connect (addr_));
}

int zmq_send (void *s_, zmq_msg_t *msg_, int flags_)
{
    if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
        errno = ENOTSOCK;
        return -1;
    }
    return (((zmq::socket_base_t*) s_)->send (msg_, flags_));
}

int zmq_recv (void *s_, zmq_msg_t *msg_, int flags_)
{
    if (!s_ || !((zmq::socket_base_t*) s_)->check_tag ()) {
        errno = ENOTSOCK;
        return -1;
    }
    return (((zmq::socket_base_t*) s_)->recv (msg_, flags_));
}

#if defined ZMQ_FORCE_SELECT
#define ZMQ_POLL_BASED_ON_SELECT
#elif defined ZMQ_FORCE_POLL
#define ZMQ_POLL_BASED_ON_POLL
#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
    defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
    defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
    defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
    defined ZMQ_HAVE_NETBSD
#define ZMQ_POLL_BASED_ON_POLL
#elif defined ZMQ_HAVE_WINDOWS || defined ZMQ_HAVE_OPENVMS
#define ZMQ_POLL_BASED_ON_SELECT
#endif

int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_)
{
#if defined ZMQ_POLL_BASED_ON_POLL
    if (unlikely (nitems_ < 0)) {
        errno = EINVAL;
        return -1;
    }
    if (unlikely (nitems_ == 0)) {
        if (timeout_ == 0)
            return 0;
#if defined ZMQ_HAVE_WINDOWS
        Sleep (timeout_ > 0 ? timeout_ / 1000 : INFINITE);
        return 0;
#else
        usleep (timeout_);
	return 0;
#endif
    }

    if (!items_) {
        errno = EFAULT;
        return -1;
    }

    zmq::clock_t clock;
    uint64_t now = 0;
    uint64_t end = 0;

    pollfd *pollfds = (pollfd*) malloc (nitems_ * sizeof (pollfd));
    alloc_assert (pollfds);

    //  Build pollset for poll () system call.
    for (int i = 0; i != nitems_; i++) {

        //  If the poll item is a 0MQ socket, we poll on the file descriptor
        //  retrieved by the ZMQ_FD socket option.
        if (items_ [i].socket) {
            size_t zmq_fd_size = sizeof (zmq::fd_t);
            if (zmq_getsockopt (items_ [i].socket, ZMQ_FD, &pollfds [i].fd,
                &zmq_fd_size) == -1) {
                free (pollfds);
                return -1;
            }
            pollfds [i].events = items_ [i].events ? POLLIN : 0;
        }
        //  Else, the poll item is a raw file descriptor. Just convert the
        //  events to normal POLLIN/POLLOUT for poll ().
        else {
            pollfds [i].fd = items_ [i].fd;
            pollfds [i].events =
                (items_ [i].events & ZMQ_POLLIN ? POLLIN : 0) |
                (items_ [i].events & ZMQ_POLLOUT ? POLLOUT : 0);
        }
    }

    bool first_pass = true;
    int nevents = 0;

    while (true) {

         //  Compute the timeout for the subsequent poll.
         int timeout;
         if (first_pass)
             timeout = 0;
         else if (timeout_ < 0)
             timeout = -1;
         else
             timeout = end - now;

        //  Wait for events.
        while (true) {
            int rc = poll (pollfds, nitems_, timeout);
            if (rc == -1 && errno == EINTR) {
                free (pollfds);
                return -1;
            }
            errno_assert (rc >= 0);
            break;
        }

        //  Check for the events.
        for (int i = 0; i != nitems_; i++) {

            items_ [i].revents = 0;

            //  The poll item is a 0MQ socket. Retrieve pending events
            //  using the ZMQ_EVENTS socket option.
            if (items_ [i].socket) {
                size_t zmq_events_size = sizeof (uint32_t);
                uint32_t zmq_events;
                if (zmq_getsockopt (items_ [i].socket, ZMQ_EVENTS, &zmq_events,
                    &zmq_events_size) == -1) {
                    free (pollfds);
                    return -1;
                }
                if ((items_ [i].events & ZMQ_POLLOUT) &&
                      (zmq_events & ZMQ_POLLOUT))
                    items_ [i].revents |= ZMQ_POLLOUT;
                if ((items_ [i].events & ZMQ_POLLIN) &&
                      (zmq_events & ZMQ_POLLIN))
                    items_ [i].revents |= ZMQ_POLLIN;
            }
            //  Else, the poll item is a raw file descriptor, simply convert
            //  the events to zmq_pollitem_t-style format.
            else {
                if (pollfds [i].revents & POLLIN)
                    items_ [i].revents |= ZMQ_POLLIN;
                if (pollfds [i].revents & POLLOUT)
                    items_ [i].revents |= ZMQ_POLLOUT;
                if (pollfds [i].revents & ~(POLLIN | POLLOUT))
                    items_ [i].revents |= ZMQ_POLLERR;
            }

            if (items_ [i].revents)
                nevents++;
        }

        //  If timout is zero, exit immediately whether there are events or not.
        if (timeout_ == 0)
            break;

        //  If there are events to return, we can exit immediately.
        if (nevents)
            break;

        //  At this point we are meant to wait for events but there are none.
        //  If timeout is infinite we can just loop until we get some events.
        if (timeout_ < 0) {
            if (first_pass)
                first_pass = false;
            continue;
        }

        //  The timeout is finite and there are no events. In the first pass
        //  we get a timestamp of when the polling have begun. (We assume that
        //  first pass have taken negligible time). We also compute the time
        //  when the polling should time out.
        if (first_pass) {
            now = clock.now_ms ();
            end = now + (timeout_ / 1000);
            if (now == end)
                break;
            first_pass = false;
            continue;
        }

        //  Find out whether timeout have expired.
        now = clock.now_ms ();
        if (now >= end)
            break;
    }

    free (pollfds);
    return nevents;

#elif defined ZMQ_POLL_BASED_ON_SELECT

    if (unlikely (nitems_ < 0)) {
        errno = EINVAL;
        return -1;
    }
    if (unlikely (nitems_ == 0)) {
        if (timeout_ == 0)
            return 0;
#if defined ZMQ_HAVE_WINDOWS
        Sleep (timeout_ > 0 ? timeout_ / 1000 : INFINITE);
        return 0;
#else
        usleep (timeout_);
        return 0;
#endif
    }

    if (!items_) {
        errno = EFAULT;
        return -1;
    }

    zmq::clock_t clock;
    uint64_t now = 0;
    uint64_t end = 0;

    //  Ensure we do not attempt to select () on more than FD_SETSIZE
    //  file descriptors.
    zmq_assert (nitems_ <= FD_SETSIZE);

    fd_set pollset_in;
    FD_ZERO (&pollset_in);
    fd_set pollset_out;
    FD_ZERO (&pollset_out);
    fd_set pollset_err;
    FD_ZERO (&pollset_err);

    zmq::fd_t maxfd = 0;

    //  Build the fd_sets for passing to select ().
    for (int i = 0; i != nitems_; i++) {

        //  If the poll item is a 0MQ socket we are interested in input on the
        //  notification file descriptor retrieved by the ZMQ_FD socket option.
        if (items_ [i].socket) {
            size_t zmq_fd_size = sizeof (zmq::fd_t);
            zmq::fd_t notify_fd;
            if (zmq_getsockopt (items_ [i].socket, ZMQ_FD, &notify_fd,
                &zmq_fd_size) == -1)
                return -1;
            if (items_ [i].events) {
                FD_SET (notify_fd, &pollset_in);
                if (maxfd < notify_fd)
                    maxfd = notify_fd;
            }
        }
        //  Else, the poll item is a raw file descriptor. Convert the poll item
        //  events to the appropriate fd_sets.
        else {
            if (items_ [i].events & ZMQ_POLLIN)
                FD_SET (items_ [i].fd, &pollset_in);
            if (items_ [i].events & ZMQ_POLLOUT)
                FD_SET (items_ [i].fd, &pollset_out);
            if (items_ [i].events & ZMQ_POLLERR)
                FD_SET (items_ [i].fd, &pollset_err);
            if (maxfd < items_ [i].fd)
                maxfd = items_ [i].fd;
        }
    }

    bool first_pass = true;
    int nevents = 0;
    fd_set inset, outset, errset;

    while (true) {

        //  Compute the timeout for the subsequent poll.
        timeval timeout;
        timeval *ptimeout;
        if (first_pass) {
            timeout.tv_sec = 0;
            timeout.tv_usec = 0;
            ptimeout = &timeout;
        }
        else if (timeout_ < 0)
            ptimeout = NULL;
        else {
            timeout.tv_sec = (long) ((end - now) / 1000);
            timeout.tv_usec = (long) ((end - now) % 1000 * 1000);
            ptimeout = &timeout;
        }

        //  Wait for events. Ignore interrupts if there's infinite timeout.
        while (true) {
            memcpy (&inset, &pollset_in, sizeof (fd_set));
            memcpy (&outset, &pollset_out, sizeof (fd_set));
            memcpy (&errset, &pollset_err, sizeof (fd_set));
#if defined ZMQ_HAVE_WINDOWS
            int rc = select (0, &inset, &outset, &errset, ptimeout);
            if (unlikely (rc == SOCKET_ERROR)) {
                zmq::wsa_error_to_errno ();
                if (errno == ENOTSOCK)
                    return -1;
                wsa_assert (false);
            }
#else
            int rc = select (maxfd + 1, &inset, &outset, &errset, ptimeout);
            if (unlikely (rc == -1)) {
                if (errno == EINTR || errno == EBADF)
                    return -1;
                errno_assert (false);
            }
#endif
            break;
        }

        //  Check for the events.
        for (int i = 0; i != nitems_; i++) {

            items_ [i].revents = 0;

            //  The poll item is a 0MQ socket. Retrieve pending events
            //  using the ZMQ_EVENTS socket option.
            if (items_ [i].socket) {
                size_t zmq_events_size = sizeof (uint32_t);
                uint32_t zmq_events;
                if (zmq_getsockopt (items_ [i].socket, ZMQ_EVENTS, &zmq_events,
                      &zmq_events_size) == -1)
                    return -1;
                if ((items_ [i].events & ZMQ_POLLOUT) &&
                      (zmq_events & ZMQ_POLLOUT))
                    items_ [i].revents |= ZMQ_POLLOUT;
                if ((items_ [i].events & ZMQ_POLLIN) &&
                      (zmq_events & ZMQ_POLLIN))
                    items_ [i].revents |= ZMQ_POLLIN;
            }
            //  Else, the poll item is a raw file descriptor, simply convert
            //  the events to zmq_pollitem_t-style format.
            else {
                if (FD_ISSET (items_ [i].fd, &inset))
                    items_ [i].revents |= ZMQ_POLLIN;
                if (FD_ISSET (items_ [i].fd, &outset))
                    items_ [i].revents |= ZMQ_POLLOUT;
                if (FD_ISSET (items_ [i].fd, &errset))
                    items_ [i].revents |= ZMQ_POLLERR;
            }

            if (items_ [i].revents)
                nevents++;
        }

        //  If timout is zero, exit immediately whether there are events or not.
        if (timeout_ == 0)
            break;

        //  If there are events to return, we can exit immediately.
        if (nevents)
            break;

        //  At this point we are meant to wait for events but there are none.
        //  If timeout is infinite we can just loop until we get some events.
        if (timeout_ < 0) {
            if (first_pass)
                first_pass = false;
            continue;
        }

        //  The timeout is finite and there are no events. In the first pass
        //  we get a timestamp of when the polling have begun. (We assume that
        //  first pass have taken negligible time). We also compute the time
        //  when the polling should time out.
        if (first_pass) {
            now = clock.now_ms ();
            end = now + (timeout_ / 1000);
            if (now == end)
                break;
            first_pass = false;
            continue;
        }

        //  Find out whether timeout have expired.
        now = clock.now_ms ();
        if (now >= end)
            break;
    }

    return nevents;

#else
    //  Exotic platforms that support neither poll() nor select().
    errno = ENOTSUP;
    return -1;
#endif
}

#if defined ZMQ_POLL_BASED_ON_SELECT
#undef ZMQ_POLL_BASED_ON_SELECT
#endif
#if defined ZMQ_POLL_BASED_ON_POLL
#undef ZMQ_POLL_BASED_ON_POLL
#endif

int zmq_errno ()
{
    return errno;
}

int zmq_device (int device_, void *insocket_, void *outsocket_)
{
    if (!insocket_ || !outsocket_) {
        errno = EFAULT;
        return -1;
    }

    if (device_ != ZMQ_FORWARDER && device_ != ZMQ_QUEUE &&
          device_ != ZMQ_STREAMER) {
       errno = EINVAL;
       return -1;
    }

    return zmq::device ((zmq::socket_base_t*) insocket_,
        (zmq::socket_base_t*) outsocket_);
}

////////////////////////////////////////////////////////////////////////////////
//  0MQ utils - to be used by perf tests
////////////////////////////////////////////////////////////////////////////////

void zmq_sleep (int seconds_)
{
#if defined ZMQ_HAVE_WINDOWS
    Sleep (seconds_ * 1000);
#else
    sleep (seconds_);
#endif
}

void *zmq_stopwatch_start ()
{
    uint64_t *watch = (uint64_t*) malloc (sizeof (uint64_t));
    alloc_assert (watch);
    *watch = zmq::clock_t::now_us ();
    return (void*) watch;
}

unsigned long zmq_stopwatch_stop (void *watch_)
{
    uint64_t end = zmq::clock_t::now_us ();
    uint64_t start = *(uint64_t*) watch_;
    free (watch_);
    return (unsigned long) (end - start);
}


text:
namespace MassTransit.RuntimeServices.Model
{
	using FluentNHibernate.Mapping;
	using Magnum.Infrastructure;
	using Magnum.Infrastructure.StateMachine;
	using Services.HealthMonitoring.Server;

	public class HealthSagaMap :
		ClassMap<HealthSaga>
	{
		public HealthSagaMap()
		{
			Id(x => x.CorrelationId)
				.GeneratedBy.Assigned();

			Map(x => x.CurrentState)
				.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
				.CustomType<StateMachineUserType>();

			Map(x => x.ControlUri)
				.CustomType<UriUserType>();
			Map(x => x.DataUri)
				.CustomType<UriUserType>();

			Map(x => x.LastHeartbeat);
			Map(x => x.HeartbeatIntervalInSeconds);
		}
	}
}


text:
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError

from .. import models

class LocationBasedPerformanceTierOperations(object):
    """LocationBasedPerformanceTierOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An objec model deserializer.
    :ivar api_version: The API version to use for the request. Constant value: "2017-04-30-preview".
    """

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "2017-04-30-preview"

        self.config = config

    def list(
            self, location_name, custom_headers=None, raw=False, **operation_config):
        """List all the performance tiers at specified location in a given
        subscription.

        :param location_name: The name of the location.
        :type location_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of PerformanceTierProperties
        :rtype:
         ~azure.mgmt.rdbms.mysql.models.PerformanceTierPropertiesPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierProperties]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers'
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
                    'locationName': self._serialize.url("location_name", location_name, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.PerformanceTierPropertiesPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.PerformanceTierPropertiesPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized


text:
namespace org {
  namespace apache {
    namespace lucene {
      namespace index {
        class AtomicReaderContext;
      }
      namespace search {
        class FieldCache$LongParser;
      }
      namespace queries {
        namespace function {
          class FunctionValues;
        }
      }
    }
  }
}
namespace java {
  namespace lang {
    class Object;
    class Class;
    class String;
  }
  namespace util {
    class Map;
  }
  namespace io {
    class IOException;
  }
}
template<class T> class JArray;

namespace org {
  namespace apache {
    namespace lucene {
      namespace queries {
        namespace function {
          namespace valuesource {

            class LongFieldSource : public ::org::apache::lucene::queries::function::valuesource::FieldCacheSource {
            public:
              enum {
                mid_init$_5fdc3f48,
                mid_init$_d7533242,
                mid_description_14c7b5c5,
                mid_equals_290588e2,
                mid_externalToLong_5fdc3f54,
                mid_getValues_4c566485,
                mid_hashCode_54c6a179,
                mid_longToObject_fe727f5c,
                mid_longToString_3e02f30e,
                mid_newMutableValueLong_31ee279b,
                max_mid
              };

              static ::java::lang::Class *class$;
              static jmethodID *mids$;
              static bool live$;
              static jclass initializeClass(bool);

              explicit LongFieldSource(jobject obj) : ::org::apache::lucene::queries::function::valuesource::FieldCacheSource(obj) {
                if (obj != NULL)
                  env->getClass(initializeClass);
              }
              LongFieldSource(const LongFieldSource& obj) : ::org::apache::lucene::queries::function::valuesource::FieldCacheSource(obj) {}

              LongFieldSource(const ::java::lang::String &);
              LongFieldSource(const ::java::lang::String &, const ::org::apache::lucene::search::FieldCache$LongParser &);

              ::java::lang::String description() const;
              jboolean equals(const ::java::lang::Object &) const;
              jlong externalToLong(const ::java::lang::String &) const;
              ::org::apache::lucene::queries::function::FunctionValues getValues(const ::java::util::Map &, const ::org::apache::lucene::index::AtomicReaderContext &) const;
              jint hashCode() const;
              ::java::lang::Object longToObject(jlong) const;
              ::java::lang::String longToString(jlong) const;
            };
          }
        }
      }
    }
  }
}

#include <Python.h>

namespace org {
  namespace apache {
    namespace lucene {
      namespace queries {
        namespace function {
          namespace valuesource {
            extern PyTypeObject PY_TYPE(LongFieldSource);

            class t_LongFieldSource {
            public:
              PyObject_HEAD
              LongFieldSource object;
              static PyObject *wrap_Object(const LongFieldSource&);
              static PyObject *wrap_jobject(const jobject&);
              static void install(PyObject *module);
              static void initialize(PyObject *module);
            };
          }
        }
      }
    }
  }
}

#endif


text:
require 'spec_helper'

module Msg
  describe MessagesController do

    # just basic CRUD here so the tests will be very dull

  end
end


text:
<?php

/**
 * Google Content Target country Source
 *
 * @category	BlueVisionTec
 * @package    BlueVisionTec_GoogleShoppingApi
 * @author     Magento Core Team <core@magentocommerce.com>
 * @author      BlueVisionTec UG (haftungsbeschränkt) <magedev@bluevisiontec.eu>
 */
class BlueVisionTec_GoogleShoppingApi_Model_Source_Country
{
    /**
     * Retrieve option array with allowed countries
     *
     * @return array
     */
    public function toOptionArray()
    {
        $_allowed = Mage::getSingleton('googleshoppingapi/config')->getAllowedCountries();
        $result = array();
        foreach ($_allowed as $iso => $info) {
            $result[] = array('value' => $iso, 'label' => $info['name']);
        }
        return $result;
    }
}


text:
'use strict';

var path = require('path'),
    auth = require('../config/auth');

module.exports = function(app) {
  // User Routes
  var users = require('../controllers/users');
  app.post('/auth/users', users.create);
  app.get('/auth/users/:userId', users.show);

  // Check if username is available
  // todo: probably should be a query on users
  app.get('/auth/check_username/:username', users.exists);

  // Session Routes
  var session = require('../controllers/session');
  app.get('/auth/session', auth.ensureAuthenticated, session.session);
  app.post('/auth/session', session.login);
  app.del('/auth/session', session.logout);

  // Brand Routes
  var brands = require('../controllers/brands');
  app.get('/api/brands', brands.all);
  app.post('/api/brands', auth.ensureAuthenticated, brands.create);
  app.get('/api/brands/:brandId', brands.show);
  app.put('/api/brands/:brandId', auth.ensureAuthenticated, auth.brand.hasAuthorization, brands.update);
  app.del('/api/brands/:brandId', auth.ensureAuthenticated, auth.brand.hasAuthorization, brands.destroy);

  //Setting up the brandId param
  app.param('brandId', brands.brand);

  // Angular Routes
  app.get('/partials/*', function(req, res) {
    var requestedView = path.join('./', req.url);
    res.render(requestedView);
  });

  app.get('/*', function(req, res) {
    if(req.user) {
      res.cookie('user', JSON.stringify(req.user.user_info));
    }

    res.render('index.html');
  });

}


text:
package com.fisnail.updateapp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.fisnail.updateapp.AutoUpdate;
import com.fisnail.updateapp.UpdateAppPlugin;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import org.json.JSONObject;

/**
 *  自动更新
 * @author Fisnail(fisnail@163.com)
 * 2014-11-26
 *
 */
public class UpdateAppPlugin extends CordovaPlugin {
	private static final String TAG ="UpdateApp";
	private static Gson gson = new GsonBuilder().create();

	/**
	 * NEW_APK名称
	 */
	private String newAPKName;
	/**
	 * NEW_APK 版本名称
	 */
	private String newVersionName;
	/**
	 * NEW_APK 版本号
	 */
	private Integer newVersionCode;
	/**
	 * NEW_APK 下载路径(js)
	 */
	private String newAPKDownLoadPath;
	/**
	 * 本次更新优化内容简介
	 */
	private String newAPKUpdateLogInfo;
	/**
	 * 本地当前APK版本名称
	 */
	private String nativeVersionName;
	/**
	 * 本地当前APK版本号
	 */
	private Integer nativeVersionCode;
	/**
	 * 本地应用包名
	 */
	private String nativePackageName;
	/**
	 * 本地应用名称
	 */
	private String nativeAppName;

	/**
	 * 记录进度条数量
	 */
    private int progress;
	/**
	 * 下载中
	 */
    private static final int DOWNLOAD = 1;
    /**
     * 下载结束
     */
    private static final int DOWNLOAD_FINISH = 2;
    /**
     * 下载NEW_APK保存路径
     */
    private String newAPKSavePath;
    /**
     * 提示下载对话框
     */
    private Dialog dialog;
	/**
	 * 线程停止状态位
	 */
	private boolean stop;
    /**
     * 下载进度对话框
     */
	private Handler handler = new Handler();
	private Context context;
	private ProgressDialog pBar;
	private CallbackContext callbackContextInClass;
	 /**
	     * 取消更新
	     */
	    private boolean cancelUpdate = false;

	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException{
		callbackContextInClass = callbackContext;
		try {
			if ("update".equals(action)) {
				JSONObject versionJsonPath = args.getJSONObject(0);
				Log.v(TAG, "check js set version.json file path...");
//				String versionJsonFilePath = null;
//				try {
//					versionJsonFilePath = String.valueOf(versionJsonPath.get("versionJsonFilePath"));
//					if (null == versionJsonFilePath || "".equals(versionJsonFilePath.trim())) {
//						throw new JSONException("version file path not set!");
//					}
//				} catch (JSONException e) {
//					Log.e(TAG, e.getMessage());
//					throw new JSONException(e.getMessage());
//				}
				Log.v(TAG,"Ready to check for update...");
				update(versionJsonPath+"");
				return true;
			}
		} catch (JSONException e) {
			stop = true;
			callbackContextInClass.error(e.getMessage());
			callbackContextInClass.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
		}   catch (Exception e){
			stop = true;
			callbackContextInClass.error(e.getMessage());
			callbackContextInClass.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
		}
		return super.execute(action, args, callbackContext);
	}

	private boolean update(final String versionJsonFilePath){
		 new AsyncTask<Void, Integer, String>() {
			@Override
			protected String doInBackground(Void... params) {
//				Log.v(TAG, "Ready to read the contents of the remote file(version.json)...");
//				Log.v(TAG, "Remote file address:"+versionJsonFilePath);
//				try {
//					return getRemoteServerVersion(versionJsonFilePath);
//				} catch (IOException e) {
//					Log.e(TAG,e.getMessage());
//					stop  = true;
//					callbackContextInClass.error(e.getMessage());
//					callbackContextInClass.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
//				}
				return "";
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if (stop){
					return;
				}
			try {
//				if ("".equals(result)) {
//					Log.e(TAG, "version.json file is null");
//					throw new Exception("version.json file is null");
//				}
				result = versionJsonFilePath;
				if (result != "") {
					AutoUpdate autoUpdate = gson.fromJson(result, AutoUpdate.class);
					newAPKName = autoUpdate.getApkName();
					Log.v(TAG, "server newAPKName:" + newAPKName);
					newVersionName = autoUpdate.getVerName();
					Log.v(TAG, "server newVersionName:" + newVersionName);
					newVersionCode = autoUpdate.getVerCode();
					Log.v(TAG, "server newVersionCode:" + newVersionCode);
					newAPKDownLoadPath = autoUpdate.getDownLoadPath();
					Log.v(TAG, "server newAPKDownLoadPath:" + newAPKDownLoadPath);
					newAPKUpdateLogInfo = autoUpdate.getLogs();
					Log.v(TAG, "server newAPKUpdateLogInfo:" + newAPKUpdateLogInfo);
				}
				Log.v(TAG, "wait for get native version");
				getNativeVersion();
				Log.v(TAG, "begin checkUpdate...");
				checkUpdate();
			}catch (Exception e){
				Log.e(TAG,e.getMessage());
				stop = true;
				callbackContextInClass.error(e.getMessage());
				callbackContextInClass.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
			}
			}

			@Override
			protected void onProgressUpdate(Integer... values) {
				super.onProgressUpdate(values);
			}
		}.execute();
		return true;
	}
	/**
	 * 检测自动更新
	 */
	public void checkUpdate() throws Exception{

		Log.v(TAG, "newVersionCode:"+newVersionCode);
		Log.v(TAG, "nativeVersionCode" + nativeVersionCode);

		if((newVersionCode>nativeVersionCode)){
			showUpdateAPKDialog();
		}
	}

	/**
	 * 获取本地APK版本信息
	 */
	public void getNativeVersion() throws NameNotFoundException {
		context = cordova.getActivity();
        PackageInfo packageInfo;
        PackageManager pm = this.context.getPackageManager() ;
		packageInfo = this.context.getPackageManager().getPackageInfo(this.context.getPackageName(), 0);
		nativeVersionName = packageInfo.versionName;
		Log.v(TAG,"nativeVersionName:"+nativeVersionName);
		nativeVersionCode = packageInfo.versionCode;
		Log.v(TAG,"nativeVersionCode:"+nativeVersionCode);
		nativePackageName = packageInfo.packageName;
		Log.v(TAG,"nativePackageName:"+nativePackageName);
		ApplicationInfo applicationInfo = pm.getApplicationInfo(nativePackageName, 0);
		nativeAppName =  applicationInfo.loadLabel(pm).toString();
		Log.v(TAG,"nativeAppName:"+nativeAppName);
	}

	/**
	 * 获取远程APK版本信息
	 */
	public String getRemoteServerVersion(String versionJsonPath) throws IOException {
		/**
		 * version.json文件内容
		 */
		StringBuilder versionJsonStr = new StringBuilder();
		URL url = null;
		Log.v(TAG,"Ready for request version.json...");
		url = new URL(versionJsonPath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setReadTimeout(5000);
		conn.connect();
		Log.v(TAG,"Ready for read file version.json...");
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"),8192);
		String line = null;
		while((line = reader.readLine()) != null){
			versionJsonStr.append(line);
		}
		reader.close();
		Log.v(TAG,"read file end,version.json info:"+versionJsonStr.toString());
		if (versionJsonStr.length()==0){

			Log.e(TAG,"version.json file length is zero");
			throw new IOException("version.json file length is zero");
		}
		if(versionJsonStr.length()>0){
			return versionJsonStr.toString();
		}
		return "";
	}

	/**
	 * 下载NEW_APK
	 */
	public void downLoadNewAPK() throws Exception{

		Log.v(TAG, "show download progressDialog...");
		pBar.setCanceledOnTouchOutside(false);
		pBar.show();
		if (stop){
			return;
		}

		Thread thread =	new Thread() {
				public void run() {

					// 判断SD卡是否存在,并且是否具有读写权限
					try {
						if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
							// 获得存储卡的路径
							newAPKSavePath = Environment.getExternalStorageDirectory() + "/";

							URL url = new URL(newAPKDownLoadPath);
							// 创建连接
							HttpURLConnection conn = (HttpURLConnection) url.openConnection();
							conn.connect();
							// 获取文件大小
							int length = conn.getContentLength();
							// 创建输入流
							InputStream is = conn.getInputStream();

							File file = new File(newAPKSavePath);
							// 判断文件目录是否存在
							if (!file.exists()) {
								Log.v(TAG,"create file dir");
								file.mkdir();
							}
							File apkFile = new File(newAPKSavePath, newAPKName);
							FileOutputStream fos = new FileOutputStream(apkFile);
							int count = 0;
							// 缓存
							byte buf[] = new byte[1024];
							// 写入到文件中
							do {
								int numread = is.read(buf);
								count += numread;
								// 计算进度条位置
								progress = (int) (((float) count / length) * 100);
								// 更新进度
								Log.v(TAG,"downLoading...");
								mHandler.sendEmptyMessage(DOWNLOAD);
								if (numread <= 0) {
									// 下载完成
									Log.v(TAG,"down load finish");
									mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
									break;
								}
								// 写入文件
								fos.write(buf, 0, numread);
							} while (!cancelUpdate);// 点击取消就停止下载.
							fos.close();
							is.close();
						}
					}  catch (Exception e) {
						Log.e(TAG,e.getMessage());
						stop =true;
						pBar.dismiss();
						callbackContextInClass.error(e.getMessage());
						callbackContextInClass.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
					}
				}
			};
		if (!stop){
			thread.start();
		}

	}

	 private Handler mHandler = new Handler()
	    {
	        public void handleMessage(Message msg)
	        {
	            switch (msg.what)
	            {
	            // 正在下载
	            case DOWNLOAD:
	                // 设置进度条位置
	                pBar.setProgress(progress);
	                break;
	            case DOWNLOAD_FINISH:
	            	pBar.dismiss();
	                // 安装文件
					try {
						installNewAPK();
					}catch (Exception e){
						Log.e(TAG,e.getMessage());
						stop = true;
						callbackContextInClass.error(e.getMessage());
						callbackContextInClass.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
					}
	                break;
	            default:
	                break;
	            }
	        };
	    };

	/**
	 * 显示是否下载APK对话框
	 */
	public void showUpdateAPKDialog() throws Exception{

			Log.v(TAG, "show update apk dialog...");
			context = cordova.getActivity();
			StringBuffer sb = new StringBuffer();
			sb.append("当前版本:" + nativeVersionName + "\n");
			sb.append("发现新版本:" + newVersionName + "\n");
			sb.append(newAPKUpdateLogInfo + "\n");// 更新日志
			sb.append("是否更新?");
			dialog = new AlertDialog.Builder(context)
					.setTitle("温馨提示")
					.setMessage(sb.toString())
					.setPositiveButton("立即更新",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
													int which) {
									try {
										showUpdatingAPKProcessBar();// 更新当前版本
									} catch (Exception e) {
										Log.e(TAG,e.getMessage());
										stop = true;
										callbackContextInClass.error(e.getMessage());
										callbackContextInClass.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
									}
								}
							})
					.setNegativeButton("暂不更新",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
													int which) {
									cancelUpdate = true;
									//finish();
								}
							}).create();
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();

	}

	/**
	 * 显示正在下载APK进度条
	 */
	public void showUpdatingAPKProcessBar() throws Exception{
Log.v(TAG,"show update APK processBar...");
		context = cordova.getActivity();
		pBar = new ProgressDialog(context);
		pBar.setTitle("");
		pBar.setMessage("正在下载,请稍后...");
		pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

		downLoadNewAPK();

	}

	/**
	 * NEW_APK安装
	 */
	public void installNewAPK() throws  Exception{
		Log.v(TAG, "install apk...");
		context = cordova.getActivity();
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), newAPKName)),
				"application/vnd.android.package-archive");
		this.context.startActivity(intent);
	}

}


text:
<?php echo substr($sub_title, 0 , -2); ?>

        Home

 /

Contact Us

      <form id='contactmain'>

          <input type="email" class="form-control textfield" placeholder="Enter you Email address here" required>

          <input type="text" class="form-control textfield" placeholder="Enter you Email address here" required>

          <input type="text" class="form-control textfield" placeholder="Enter you contact number here" required>

          <input type="text" class="form-control textfield" placeholder="Enter the subject of the message" required>

          <textarea class="form-control textfield" rows='5' placeholder='Enter the message here' required></textarea>

        <button type="submit" class="button button-blue">Submit</button>
      </form>

 MEA Engineering College

 IEEE SBC, STB : 08091

 Kerala Sub-Section

 Region 10, India

 +91 8129609230

             meaieeestudentbranch@gmail.com

godaddy vs bluehost


text:
\section{Upplösning av teknologsektionen}

\subsection{Beslut om upplösning}

För att teknologsektion skall upplösas krävs beslut av två på varandra följande sektionsmöten, med minst 15 läsdagars mellanrum, med minst 3/4 majoritet.

\subsection{Tillgångar och nystart}

Om sektionsmötet beslutar att upplösa teknologsektionen skall samtliga dess tillgångar och skulder, som framgår av upprättad balansräkning, vid upplösningen tillfalla Chalmers studentkår. Kåren får sedan förvalta till dess att en ny förening eller teknologsektion bildas som representerar studerande vid utbildningsprogrammet för Informationsteknik vid Chalmers tekniska högskola.


text:
package org.jboss.wise.smooks.decoders;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import org.milyn.javabean.DataDecodeException;
import org.milyn.javabean.DataDecoder;
import org.milyn.javabean.DecodeType;
import org.milyn.javabean.decoders.DateDecoder;

/**
 * {@link javax.xml.datatype.Duration} data decoder.
 * <p/>
 * Decodes the supplied string into a {@link javax.xml.datatype.Duration} String value is supposed to be milliseconds representing
 * this Duration
 */
@DecodeType( Duration.class )
public class DurationDecoder extends DateDecoder implements DataDecoder {

    @Override
    public Object decode( String data ) throws DataDecodeException {
        Object result = null;
        try {
            result = DatatypeFactory.newInstance().newDuration(Long.parseLong(data));
        } catch (DatatypeConfigurationException e) {
            throw new DataDecodeException("Error decoding Duration data value '" + data, e);
        } catch (NumberFormatException e) {
            throw new DataDecodeException("Error decoding Duration data value '" + data, e);
        }

        return result;
    }

}


text:
package org.sourcepit.mavenizor.maven.converter;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.sourcepit.common.utils.file.FileUtils.deleteFileOrDirectory;
import static org.sourcepit.mavenizor.MavenizorTestHarness.addEmbeddedLibrary;
import static org.sourcepit.mavenizor.MavenizorTestHarness.addMavenMetaData;
import static org.sourcepit.mavenizor.MavenizorTestHarness.getBundle;
import static org.sourcepit.mavenizor.MavenizorTestHarness.jar;
import static org.sourcepit.mavenizor.MavenizorTestHarness.newBundle;
import static org.sourcepit.mavenizor.MavenizorTestHarness.newManifest;
import static org.sourcepit.mavenizor.MavenizorTestHarness.newState;

import java.io.File;
import java.io.IOException;

import javax.inject.Inject;

import org.eclipse.osgi.service.resolver.BundleDescription;
import org.eclipse.osgi.service.resolver.State;
import org.hamcrest.core.Is;
import org.hamcrest.core.IsEqual;
import org.junit.Before;
import org.junit.Test;
import org.sourcepit.common.manifest.osgi.BundleManifest;
import org.sourcepit.common.maven.model.ArtifactKeyBuilder;
import org.sourcepit.common.maven.model.MavenArtifact;
import org.sourcepit.common.maven.model.ProjectKey;
import org.sourcepit.common.utils.props.LinkedPropertiesMap;
import org.sourcepit.common.utils.props.PropertiesMap;
import org.sourcepit.mavenizor.AbstractMavenizorTest;
import org.sourcepit.mavenizor.Mavenizor.TargetType;
import org.sourcepit.mavenizor.maven.converter.BundleConverter.Request;
import org.sourcepit.mavenizor.maven.converter.BundleConverter.Result;
import org.sourcepit.mavenizor.state.BundleAdapterFactory;

public class DefaultBundleConverterTest extends AbstractMavenizorTest {
   @Inject
   private DefaultBundleConverter converter;

   @Inject
   private GAVStrategyFactory gavStrategyFactory;

   private GAVStrategy gavStrategy;

   private File bundlesDir;

   private File workingDir;

   @Before
   @Override
   public void setUp() throws Exception {
      super.setUp();
      bundlesDir = new File(getWs().getRoot(), "bundles");
      workingDir = new File(getWs().getRoot(), "work");
      gavStrategy = gavStrategyFactory.newGAVStrategy(new GAVStrategyFactory.Request());
   }

   @Test
   public void testIgnoreBundle() {
      BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
      File bundleDir = newBundle(bundlesDir, mf);
      addEmbeddedLibrary(bundleDir, mf, ".");
      addEmbeddedLibrary(bundleDir, mf, "embedded.jar");

      State state = newState(bundlesDir, mf);

      BundleDescription bundle = getBundle(state, "foo");

      PropertiesMap options = new LinkedPropertiesMap();
      options.put(bundle.toString() + "/embedded.jar", "mavenize");

      Request request = newRequest(bundle, options);

      Result result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(2));
      assertFalse(result.getConvertedArtifacts().get(0).isEmbeddedLibrary());
      assertTrue(result.getConvertedArtifacts().get(1).isEmbeddedLibrary());

      options.put(bundle.toString(), "ignore");

      result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(0));
   }

   private Request newRequest(BundleDescription bundle, PropertiesMap options) {
      Request request = new Request();
      request.setBundle(bundle);
      request.setTargetType(TargetType.JAVA);
      request.setGAVStrategy(gavStrategy);
      request.setOptions(options);
      request.setWorkingDirectory(workingDir);
      return request;
   }

   @Test
   public void testIgnoreLibrary() {
      BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
      File bundleDir = newBundle(bundlesDir, mf);
      addEmbeddedLibrary(bundleDir, mf, ".");
      addEmbeddedLibrary(bundleDir, mf, "embedded.jar");

      State state = newState(bundlesDir, mf);

      BundleDescription bundle = getBundle(state, "foo");

      PropertiesMap options = new LinkedPropertiesMap();
      options.put(bundle.toString() + "/embedded.jar", "mavenize");

      Request request = newRequest(bundle, options);

      Result result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(2));
      assertFalse(result.getConvertedArtifacts().get(0).isEmbeddedLibrary());
      assertTrue(result.getConvertedArtifacts().get(1).isEmbeddedLibrary());

      options.put(bundle.toString() + "/embedded.jar", "ignore");

      result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(1));
      assertFalse(result.getConvertedArtifacts().get(0).isEmbeddedLibrary());
   }

   @Test
   public void testOmitMainBundle() {
      BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
      File bundleDir = newBundle(bundlesDir, mf);
      addEmbeddedLibrary(bundleDir, mf, ".");
      addEmbeddedLibrary(bundleDir, mf, "embedded.jar");

      State state = newState(bundlesDir, mf);

      BundleDescription bundle = getBundle(state, "foo");

      PropertiesMap options = new LinkedPropertiesMap();
      options.put(bundle.toString() + "/embedded.jar", "mavenize");

      Request request = newRequest(bundle, options);

      Result result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(2));
      ConvertedArtifact convertedArtifact = result.getConvertedArtifacts().get(0);
      assertFalse(convertedArtifact.isEmbeddedLibrary());
      assertTrue(result.getConvertedArtifacts().get(1).isEmbeddedLibrary());

      options.put(bundle.toString(), "omit");

      result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(1));
      convertedArtifact = result.getConvertedArtifacts().get(0);
      assertThat(convertedArtifact.getMavenArtifact().getArtifactId(), IsEqual.equalTo("embedded"));
      assertTrue(convertedArtifact.isEmbeddedLibrary());
   }

   @Test
   public void testOmitMainBundleWithoutEmbeddedLibrary() {
      BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
      newBundle(bundlesDir, mf);

      State state = newState(bundlesDir, mf);

      BundleDescription bundle = getBundle(state, "foo");

      PropertiesMap options = new LinkedPropertiesMap();

      Request request = newRequest(bundle, options);

      Result result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(1));
      assertFalse(result.getConvertedArtifacts().get(0).isEmbeddedLibrary());

      options.put(bundle.toString(), "omit");

      result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(0));
   }

   @Test
   public void testReplaceBundle() {
      BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
      File bundleDir = newBundle(bundlesDir, mf);
      addEmbeddedLibrary(bundleDir, mf, ".");
      addEmbeddedLibrary(bundleDir, mf, "embedded.jar");
      newBundle(bundlesDir, mf);

      State state = newState(bundlesDir, mf);

      BundleDescription bundle = getBundle(state, "foo");

      PropertiesMap options = new LinkedPropertiesMap();
      options.put(bundle.toString() + "/embedded.jar", "mavenize");

      Request request = newRequest(bundle, options);

      Result result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(2));
      assertThat(result.getConvertedArtifacts().size(), Is.is(2));
      assertFalse(result.getConvertedArtifacts().get(0).isEmbeddedLibrary());
      assertThat(result.getConvertedArtifacts().get(0).getDirective(), Is.is(ConvertionDirective.MAVENIZE));
      assertTrue(result.getConvertedArtifacts().get(1).isEmbeddedLibrary());
      assertThat(result.getConvertedArtifacts().get(1).getDirective(), Is.is(ConvertionDirective.MAVENIZE));

      options.put(bundle.toString(), "foo:bar:jar:2");

      result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(1));
      ConvertedArtifact artifact = result.getConvertedArtifacts().get(0);
      assertThat(artifact.getDirective(), Is.is(ConvertionDirective.REPLACE));
      MavenArtifact mavenArtifact = artifact.getMavenArtifact();
      assertThat(mavenArtifact.getGroupId(), IsEqual.equalTo("foo"));
      assertThat(mavenArtifact.getArtifactId(), IsEqual.equalTo("bar"));
      assertThat(mavenArtifact.getVersion(), IsEqual.equalTo("2"));
   }

   @Test
   public void testReplaceLibrary() {
      BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
      File bundleDir = newBundle(bundlesDir, mf);
      addEmbeddedLibrary(bundleDir, mf, ".");
      addEmbeddedLibrary(bundleDir, mf, "embedded.jar");
      newBundle(bundlesDir, mf);

      State state = newState(bundlesDir, mf);

      BundleDescription bundle = getBundle(state, "foo");

      PropertiesMap options = new LinkedPropertiesMap();
      options.put(bundle.toString() + "/embedded.jar", "mavenize");

      Request request = newRequest(bundle, options);

      Result result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(2));
      assertFalse(result.getConvertedArtifacts().get(0).isEmbeddedLibrary());
      assertThat(result.getConvertedArtifacts().get(0).getDirective(), Is.is(ConvertionDirective.MAVENIZE));
      assertTrue(result.getConvertedArtifacts().get(1).isEmbeddedLibrary());
      assertThat(result.getConvertedArtifacts().get(1).getDirective(), Is.is(ConvertionDirective.MAVENIZE));

      options.put(bundle.toString() + "/embedded.jar", "foo:bar:jar:2");

      result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(2));
      ConvertedArtifact artifact = result.getConvertedArtifacts().get(1);
      assertThat(artifact.getDirective(), Is.is(ConvertionDirective.REPLACE));
      MavenArtifact mavenArtifact = artifact.getMavenArtifact();
      assertThat(mavenArtifact.getGroupId(), IsEqual.equalTo("foo"));
      assertThat(mavenArtifact.getArtifactId(), IsEqual.equalTo("bar"));
      assertThat(mavenArtifact.getVersion(), IsEqual.equalTo("2"));
   }

   @Test
   public void testAutoDetectLibrary() {
      final ProjectKey expectedLib = new ArtifactKeyBuilder().setGroupId("hans")
         .setArtifactId("wurst")
         .setType("jar")
         .setVersion("3")
         .toArtifactKey()
         .getProjectKey();

      BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
      File bundleDir = newBundle(bundlesDir, mf);
      addEmbeddedLibrary(bundleDir, mf, ".");
      addEmbeddedLibrary(bundleDir, mf, "embedded.jar", expectedLib);

      State state = newState(bundlesDir, mf);

      BundleDescription bundle = getBundle(state, "foo");

      PropertiesMap options = new LinkedPropertiesMap();

      Request request = newRequest(bundle, options);

      Result result = converter.toMavenArtifacts(request);
      assertThat(result.getConvertedArtifacts().size(), Is.is(2));
      assertFalse(result.getConvertedArtifacts().get(0).isEmbeddedLibrary());

      ConvertedArtifact artifact = result.getConvertedArtifacts().get(1);
      assertTrue(artifact.isEmbeddedLibrary());
      assertThat(artifact.getDirective(), Is.is(ConvertionDirective.AUTO_DETECT));
      MavenArtifact mavenArtifact = artifact.getMavenArtifact();
      assertThat(mavenArtifact.getGroupId(), IsEqual.equalTo(expectedLib.getGroupId()));
      assertThat(mavenArtifact.getArtifactId(), IsEqual.equalTo(expectedLib.getArtifactId()));
      assertThat(mavenArtifact.getVersion(), IsEqual.equalTo(expectedLib.getVersion()));
   }

   @Test
   public void testAutoDetectLibraryAmbiguous() {
      final ProjectKey expectedLib = new ArtifactKeyBuilder().setGroupId("hans")
         .setArtifactId("wurst")
         .setType("jar")
         .setVersion("3")
         .toArtifactKey()
         .getProjectKey();

      final ProjectKey expectedLib2 = new ArtifactKeyBuilder().setGroupId("foo")
         .setArtifactId("bar")
         .setType("jar")
         .setVersion("3")
         .toArtifactKey()
         .getProjectKey();

      BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
      File bundleDir = newBundle(bundlesDir, mf);
      addEmbeddedLibrary(bundleDir, mf, ".");
      addEmbeddedLibrary(bundleDir, mf, "embedded.jar", expectedLib, expectedLib2);

      State state = newState(bundlesDir, mf);

      BundleDescription bundle = getBundle(state, "foo");

      PropertiesMap options = new LinkedPropertiesMap();

      Request request = newRequest(bundle, options);

      Result result = converter.toMavenArtifacts(request);
      assertFalse(result.getConvertedArtifacts().get(0).isEmbeddedLibrary());
      assertThat(result.getConvertedArtifacts().size(), Is.is(1));
      assertThat(result.getUnhandledEmbeddedLibraries().size(), Is.is(1));
   }

   @Test
   public void testAutoDetectBundle() throws IOException {
      for (int i = 0; i < 2; i++) {
         final boolean jar = i == 1;

         BundleManifest mf = newManifest("foo", "1.0.0.qualifier");
         File bundleDir = newBundle(bundlesDir, mf);
         addEmbeddedLibrary(bundleDir, mf, "embedded.jar");

         final ProjectKey expectedGAV = new ArtifactKeyBuilder().setGroupId("hans")
            .setArtifactId("wurst")
            .setType("jar")
            .setType("jar")
            .setVersion("3")
            .toArtifactKey()
            .getProjectKey();

         addMavenMetaData(bundleDir, expectedGAV);

         if (jar) {
            jar(bundleDir);
            deleteFileOrDirectory(bundleDir);
         }

         State state = newState(bundlesDir, mf);

         BundleDescription bundle = getBundle(state, "foo");

         if (jar) {
            assertTrue(BundleAdapterFactory.DEFAULT.adapt(bundle, File.class).isFile());
         }
         else {
            assertTrue(BundleAdapterFactory.DEFAULT.adapt(bundle, File.class).isDirectory());
         }

         PropertiesMap options = new LinkedPropertiesMap();

         Request request = newRequest(bundle, options);

         Result result = converter.toMavenArtifacts(request);
         assertThat(result.getConvertedArtifacts().size(), Is.is(1));

         ConvertedArtifact artifact = result.getConvertedArtifacts().get(0);
         assertFalse(artifact.isEmbeddedLibrary());
         assertThat(artifact.getDirective(), Is.is(ConvertionDirective.AUTO_DETECT));

         MavenArtifact mavenArtifact = artifact.getMavenArtifact();
         assertThat(mavenArtifact.getGroupId(), IsEqual.equalTo(expectedGAV.getGroupId()));
         assertThat(mavenArtifact.getArtifactId(), IsEqual.equalTo(expectedGAV.getArtifactId()));
         assertThat(mavenArtifact.getVersion(), IsEqual.equalTo(expectedGAV.getVersion()));

         getWs().delete();
      }
   }
}


text:
<html>
<head>
  <meta charset="UTF-8">
  <title>Borgnix-Toolkit</title>
  <link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/style.css">
</head>
<body>

  <script>
    var gui = require('nw.gui')
      , win = gui.Window.get()
    window.requireNode = window.require
    global.gui = gui
    global.document= window.document
    global.navigator= window.navigator
    // window.require = undefined
    require('./convert/main')
  </script>

</body>
</html>


text:
import { fork, take, delay, put, takeEvery } from 'redux-saga/effects';
import { watchGetBmData, watchExportData, watchGetBmDataSuccess} from './watchers';

export default function* startForman() {
yield [
    watchGetBmData(),
    watchExportData(),
    watchGetBmDataSuccess()
  ]
}


text:
<?php
/**
 * jobber job board platform
 *
 * @author     Chronos <http://chronoscripts.com> <chronos@chronoscripts.com>
 * @license    You are free to edit and use this work, but it would be nice if you always referenced the original author ;)
 *             (see license.txt).
 */

	$city_array = get_cities_cloud();
	$smarty->assign('cities_overview', $city_array);

	$numberOfJobsInOtherCities = $job->GetNumberOfJobsInOtherCities();
	$smarty->assign('jobs_count_in_other_cities', $numberOfJobsInOtherCities);
	$smarty->assign('jobs_count_in_other_cities_tag_height', get_cloud_tag_height($numberOfJobsInOtherCities));

	$totalNumberOfJobs = 0;

	foreach ($city_array as $city_job_data)
	{
		$totalNumberOfJobs += $city_job_data['count'];
	}

	$totalNumberOfJobs += $numberOfJobsInOtherCities;

	$smarty->assign('total_number_of_jobs', $totalNumberOfJobs);

	$html_title = $translations['jobscity']['page_title'];
	$template = 'cities.tpl';
?>


text:
"""Factories for the aps_process app."""
import factory

from .. import models

# ======
# Mixins
# ======

class HierarchyFactoryMixin(factory.DjangoModelFactory):
    """Mixin for the ``Hierarchy`` base model."""
    ABSTRACT_FACTORY = True

    name = factory.Sequence(lambda n: 'name_{0}'.format(n))

# =========
# Factories
# =========

class BufferFactory(HierarchyFactoryMixin, factory.DjangoModelFactory):
    """Factory for the ``Buffer`` model."""
    FACTORY_FOR = models.Buffer

    item = factory.SubFactory('aps_process.tests.factories.ItemFactory')

class CalendarFactory(factory.DjangoModelFactory):
    """Factory for the ``Calendar`` model."""
    FACTORY_FOR = models.Calendar

    name = factory.Sequence(lambda n: 'name_{0}'.format(n))

class CalendarBucketFactory(factory.DjangoModelFactory):
    """Factory for the ``CalendarBucket`` model."""
    FACTORY_FOR = models.CalendarBucket

    id = factory.Sequence(lambda n: n)
    calendar = factory.SubFactory(CalendarFactory)

class FlowFactory(factory.DjangoModelFactory):
    """Factory for the ``Flow`` model."""
    FACTORY_FOR = models.Flow

    id = factory.Sequence(lambda n: n)
    operation = factory.SubFactory(
        'aps_process.tests.factories.OperationFactory')
    thebuffer = factory.SubFactory(BufferFactory)

class ItemFactory(HierarchyFactoryMixin, factory.DjangoModelFactory):
    """Factory for the ``Item`` model."""
    FACTORY_FOR = models.Item

class LocationFactory(HierarchyFactoryMixin, factory.DjangoModelFactory):
    """Factory for the ``Location`` model."""
    FACTORY_FOR = models.Location

class OperationFactory(factory.DjangoModelFactory):
    """Factory for the ``Operation`` model."""
    FACTORY_FOR = models.Operation

    name = factory.Sequence(lambda n: 'name_{0}'.format(n))

class ResourceFactory(HierarchyFactoryMixin, factory.DjangoModelFactory):
    """Factory for the ``Resource`` model."""
    FACTORY_FOR = models.Resource

class ResourceLoadFactory(factory.DjangoModelFactory):
    """Factory for the ``ResourceLoad`` model."""
    FACTORY_FOR = models.ResourceLoad

    id = factory.Sequence(lambda n: n)
    operation = factory.SubFactory(OperationFactory)
    resource = factory.SubFactory(ResourceFactory)

class SetupMatrixFactory(factory.DjangoModelFactory):
    """Factory for the ``SetupMatrix`` model."""
    FACTORY_FOR = models.SetupMatrix

    name = factory.Sequence(lambda n: 'name_{0}'.format(n))

class SetupRuleFactory(factory.DjangoModelFactory):
    """Factory for the ``SetupRule`` model."""
    FACTORY_FOR = models.SetupRule

    id = factory.Sequence(lambda n: n)
    setupmatrix = factory.SubFactory(SetupMatrixFactory)

class SubOperationFactory(factory.DjangoModelFactory):
    """Factory for the ``SubOperation`` model."""
    FACTORY_FOR = models.SubOperation

    id = factory.Sequence(lambda n: n)
    operation = factory.SubFactory(OperationFactory)
    suboperation = factory.SubFactory(OperationFactory)


text:
(function() {
    'use strict';

    require.config({
        paths: {
            jquery: 'Libs/jquery',
            underscore: 'Libs/underscore',
            handlebars: 'Libs/handlebars',
            tasks: 'game-logic',
            alphanum: 'Libs/jquery.alphanum',
            storage : 'storage'
        },
        'shim' : {
            'handlebars': {
                exports: 'Handlebars'
            }
        }
    });

    require(['jquery', 'game-logic', 'storage','underscore', 'alphanum'], function ($, GameLogic,storage,_, alphanum) {
        var currentNumber,
            guessedNumber,
            currentGuessResult,
            turn =0;
        $('#number-input').numeric({
            allowMinus: false,
            allowThouSep: false,
            allowDecSep: false,
            maxDigits: 4,
            min: 1000,
            max : 9999
        });

        currentNumber = GameLogic.generateNumber();

        //For easier testing purposes and verification of the game logic
        console.log(currentNumber);

        $('body').on('keypress', function(e){
            var turnResult,
                displayMessage = $('#display-message'),
                turnHistory = $('#turn-history ul'),
                name,
                highscore;
            if(e.keyCode === 13){
                guessedNumber =$('#number-input').val();
                if(!guessedNumber || GameLogic.isInvalidNumber(guessedNumber)){
                    $('#display-message').html('The input number is invalid. It must be four digits in the range 1000 - 9999 with four different digits');
                } else {
                    turn++;
                    currentGuessResult = GameLogic.getRamsAndSheep(currentNumber,guessedNumber);
                    turnResult = 'Rams: '+currentGuessResult.rams + ' Sheep: '+currentGuessResult.sheep;
                    displayMessage.html(turnResult);
                    $('<li/>').append('Turn '+turn+' : '+ turnResult).appendTo(turnHistory)

                    if(currentGuessResult.rams===4){
                        var name = prompt('Congratulations you\'ve beaten the game in '+turn+' turns. Please enter your name.')
                        if(name || name === 0){
                            highscore = localStorage.getItem('highscore');

                            if(!highscore){
                                highscore = [];
                            } else {
                                highscore = JSON.parse(highscore);
                            }

                            highscore.push({
                                name: name,
                                turns: turn
                            });

                            localStorage.setItem('highscore',JSON.stringify(highscore));

                            alert(JSON.stringify(_.sortBy(highscore,function(score){
                                return score.turns;
                            })))
                        }

                    }
                }

            }

        })

    })
}())


text:
namespace Microsoft.Azure.CognitiveServices.Search.WebSearch.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Defines a suggested query string that likely represents the user's
    /// intent. The search results include this response if Bing determines
    /// that the user may have intended to search for something different. For
    /// example, if the user searches for alon brown, Bing may determine that
    /// the user likely intended to search for Alton Brown instead (based on
    /// past searches by others of Alon Brown).
    /// </summary>
    public partial class SpellSuggestions : SearchResultsAnswer
    {
        /// <summary>
        /// Initializes a new instance of the SpellSuggestions class.
        /// </summary>
        public SpellSuggestions()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the SpellSuggestions class.
        /// </summary>
        /// <param name="value">A list of suggested query strings that may
        /// represent the user's intention. The list contains only one Query
        /// object.</param>
        /// <param name="id">A String identifier.</param>
        /// <param name="webSearchUrl">The URL To Bing's search result for this
        /// item.</param>
        /// <param name="totalEstimatedMatches">The estimated number of
        /// webpages that are relevant to the query. Use this number along with
        /// the count and offset query parameters to page the results.</param>
        public SpellSuggestions(IList<Query> value, string id = default(string), string webSearchUrl = default(string), IList<Query> followUpQueries = default(IList<Query>), QueryContext queryContext = default(QueryContext), long? totalEstimatedMatches = default(long?), bool? isFamilyFriendly = default(bool?))
            : base(id, webSearchUrl, followUpQueries, queryContext, totalEstimatedMatches, isFamilyFriendly)
        {
            Value = value;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets a list of suggested query strings that may represent
        /// the user's intention. The list contains only one Query object.
        /// </summary>
        [JsonProperty(PropertyName = "value")]
        public IList<Query> Value { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public override void Validate()
        {
            base.Validate();
            if (Value == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Value");
            }
            if (Value != null)
            {
                foreach (var element in Value)
                {
                    if (element != null)
                    {
                        element.Validate();
                    }
                }
            }
        }
    }
}


text:
package org.hisp.dhis.result;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hisp.dhis.common.Grid;
import org.hisp.dhis.system.grid.GridUtils;
import org.hisp.dhis.system.util.CodecUtils;
import org.hisp.dhis.util.ContextUtils;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;

/**
 * @author Lars Helge Overland
 */
public class GridJasperResult
    implements Result
{
    /**
     * Determines if a de-serialized file is compatible with this class.
     */
    private static final long serialVersionUID = 7071299079048199227L;

    private static final String DEFAULT_FILENAME = "Grid";

    // -------------------------------------------------------------------------
    // Input
    // -------------------------------------------------------------------------

    private Grid grid;

    public void setGrid( Grid grid )
    {
        this.grid = grid;
    }

    private Map<String, Object> params;

    public void setParams( Map<String, Object> params )
    {
        this.params = params;
    }

    // -------------------------------------------------------------------------
    // Result implementation
    // -------------------------------------------------------------------------

    @Override
    @SuppressWarnings( "unchecked" )
    public void execute( ActionInvocation invocation )
        throws Exception
    {
        // ---------------------------------------------------------------------
        // Get grid
        // ---------------------------------------------------------------------

        Grid _grid = (Grid) invocation.getStack().findValue( "grid" );

        grid = _grid != null ? _grid : grid;

        Map<String, Object> _params = (Map<String, Object>) invocation.getStack().findValue( "params" );

        params = _params != null ? _params : params;

        // ---------------------------------------------------------------------
        // Configure response
        // ---------------------------------------------------------------------

        HttpServletResponse response = ServletActionContext.getResponse();

        String filename = CodecUtils.filenameEncode( StringUtils.defaultIfEmpty( grid.getTitle(), DEFAULT_FILENAME ) )
            + ".pdf";

        ContextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PDF, true, filename, false );

        // ---------------------------------------------------------------------
        // Write jrxml based on Velocity template
        // ---------------------------------------------------------------------

        GridUtils.toJasperReport( grid, params, response.getOutputStream() );
    }
}


text:
import { browser, by, element } from 'protractor';

export class CopayRecoveryPage {
  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('app-root h1')).getText();
  }
}


text:
<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Acme\DemoBundle\Form\ContactType;
use Symfony\Component\HttpFoundation\Response;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DemoController extends Controller
{
    /**
     * @Route("/", name="_demo")
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/hello/{name}", name="_demo_hello")
     * @Template()
     */
    public function helloAction($name)
    {
        return array('name' => $name);
    }

    /**
     * @Route("/contact", name="_demo_contact")
     * @Template()
     */
    public function contactAction(Request $request)
    {
        $form = $this->createForm(new ContactType());
        $form->handleRequest($request);

        if ($form->isValid()) {
            $mailer = $this->get('mailer');

            // .. setup a message and send it
            // http://symfony.com/doc/current/cookbook/email.html

            $request->getSession()->getFlashBag()->set('notice', 'Message sent!');

            return new RedirectResponse($this->generateUrl('_demo'));
        }

        return array('form' => $form->createView());
    }

    /**
     * @Template()
     */
    public function contactezAction()
    {
        return new Response('
Contactez nous!

Bande de rotis de porc!');
    }
}


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>XPathNSResolver non-string return value</title>
<link rel="help" href="https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator">